@crewx/sdk 0.9.0-rc.221 → 0.9.0-rc.222

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 nu=require('fs'),Re=require('path'),Na=require('os'),crypto=require('crypto'),sqliteCore=require('drizzle-orm/sqlite-core'),drizzleOrm=require('drizzle-orm'),child_process=require('child_process');require('string_decoder');var promises=require('fs/promises');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 nu__namespace=/*#__PURE__*/_interopNamespace(nu);var Re__namespace=/*#__PURE__*/_interopNamespace(Re);var Na__namespace=/*#__PURE__*/_interopNamespace(Na);var Ul=Object.defineProperty;var fn=(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 C=(t,e)=>()=>(t&&(e=t(t=0)),e);var ql=(t,e)=>{for(var n in e)Ul(t,n,{get:e[n],enumerable:true});};var g=C(()=>{});var f,vt=C(()=>{g();f=class extends Error{code;cause;constructor(e,n,r){super(n),this.name="RepositoryError",this.code=e,this.cause=r,Object.setPrototypeOf(this,new.target.prototype);}};});function Ia(t){if(t===":memory:")return t;let e=Re.resolve(t),n=e,r=[];for(;!nu.existsSync(n);){let s=Re.dirname(n);if(s===n)return e;r.unshift(n.slice(s.length+1)),n=s;}let o=nu.realpathSync(n);for(let s of r)o=Re.join(o,s);return Re.resolve(o)}function Yl(t,e){let n=Ia(t),r=Ia(e);return process.platform==="win32"?n.toLowerCase()===r.toLowerCase():n===r}function jt(t){if((process.env.NODE_ENV==="test"||process.env.VITEST!==void 0)&&Ql.some(e=>Yl(t,Re.join(Na__namespace.default.homedir(),".crewx",e))))throw new Error(`${Xl}: ${t}. Set CREWX_DB to an isolated temporary path or :memory:.`);return t}var Xl,Ql,ve,Ct=C(()=>{g();Xl="[crewx] Refusing to open the real CrewX database from a test process";Ql=["crewx.db","logs.db"];ve=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||Re.join(Na__namespace.default.homedir(),".crewx","crewx.db");return jt(e)}resolveDbPaths(){return [this.resolveDbPath()]}isMissingTableError(e){return e instanceof Error&&/no such table:/i.test(e.message)}dbExists(e){return nu.existsSync(e??this.resolveDbPath())}};});function U(t,e={}){let n=jt(t),r=fn("better-sqlite3"),{drizzle:o}=fn("drizzle-orm/better-sqlite3"),s=e.readOnly?new r(n,{readonly:true,fileMustExist:true}):new r(n);return e.readOnly||(s.exec("PRAGMA journal_mode = WAL"),s.exec(`PRAGMA journal_size_limit = ${ep}`),s.exec("PRAGMA busy_timeout = 5000"),s.exec("PRAGMA foreign_keys = ON"),s.exec("PRAGMA analysis_limit = 400")),{db:o(s),sqlite:s,runRaw:(i,c=[])=>s.prepare(i).run(...c),close:()=>s.close()}}var ep,Kt=C(()=>{g();Ct();ep=32*1024*1024;});function hn(t,e){return (t.get(`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='${e}'`)?.cnt??0)>0}function np(t,e){if(e>0||!hn(t,"tasks"))return;let n=t.all("PRAGMA table_info(tasks)"),r=new Set(n.map(o=>o.name));for(let[o,s]of Object.entries(tp))r.has(o)||t.run(`ALTER TABLE tasks ADD COLUMN ${o} ${s}`);}function op(t,e,n){if(!hn(t,"__drizzle_migrations")||!hn(t,"tasks"))return;let r=t.all(n`SELECT hash FROM __drizzle_migrations`),o=new Set(r.map(i=>i.hash)),s=JSON.parse(nu.readFileSync(Re__namespace.default.join(e,"meta/_journal.json"),"utf-8"));for(let i of s.entries){let c=rp[i.tag];if(!c)continue;let d=Re__namespace.default.join(e,`${i.tag}.sql`);if(!nu.existsSync(d))continue;let u=nu.readFileSync(d,"utf-8"),l=crypto.createHash("sha256").update(u).digest("hex");if(o.has(l))continue;let p=t.all("PRAGMA table_info(tasks)"),_=new Set(p.map(h=>h.name));for(let[h,m]of Object.entries(c))_.has(h)||(t.run(`ALTER TABLE tasks ADD COLUMN ${h} ${m}`),_.add(h));}}function Ca(t){let e=t.trim().replace(/;+\s*$/,"").trim(),n=e.match(/^ALTER\s+TABLE\s+[`"]?([A-Za-z_][\w$]*)[`"]?\s+ADD\s+(?:COLUMN\s+)?[`"]?([A-Za-z_][\w$]*)[`"]?/i);if(n)return {kind:"add-column",table:n[1],column:n[2]};let r=e.match(/^CREATE\s+(?:UNIQUE\s+)?INDEX(?:\s+IF\s+NOT\s+EXISTS)?\s+[`"]?([A-Za-z_][\w$]*)[`"]?\s+ON\s+/i);if(r)return {kind:"create-index",name:r[1]};let o=e.match(/^DROP\s+INDEX\s+IF\s+EXISTS\s+[`"]?([A-Za-z_][\w$]*)[`"]?/i);if(o)return {kind:"drop-index",name:o[1]}}function xa(t){return t.split(/-->\s*statement-breakpoint/).map(e=>e.trim()).filter(Boolean)}function sp(t,e,n){return t.all(`PRAGMA table_info("${e}")`).some(s=>s.name===n)}function ip(t,e){return t.all(`SELECT name FROM sqlite_master WHERE type = 'index' AND name = '${e}'`).length>0}function Wr(t,e){return e.kind==="add-column"?sp(t,e.table,e.column):ip(t,e.name)}function ba(t,e,n){let r=t;for(let o of xa(e)){let s=Ca(o);s?.kind==="add-column"&&Wr(r,s)||s?.kind==="create-index"&&Wr(r,s)||s?.kind==="drop-index"&&!Wr(r,s)||r.run(n.raw(o));}}function ap(t,e,n){let r=t.all(n`SELECT hash FROM __drizzle_migrations`),o=new Set(r.map(i=>i.hash)),s=JSON.parse(nu.readFileSync(Re__namespace.default.join(e,"meta/_journal.json"),"utf-8"));for(let i of s.entries){let c=Re__namespace.default.join(e,`${i.tag}.sql`);if(!nu.existsSync(c))continue;let d=nu.readFileSync(c,"utf-8"),u=crypto.createHash("sha256").update(d).digest("hex");if(o.has(u))continue;let p=xa(d).map(Ca);if(p.some(h=>!h))continue;let _=p;_.some(h=>h.kind==="add-column")&&_.some(h=>Wr(t,h))&&(t.transaction(h=>{ba(h,d,n),h.run(n`INSERT INTO __drizzle_migrations (hash, created_at) VALUES (${u}, ${i.when})`);},{behavior:"immediate"}),o.add(u),console.error(`[crewx] Reconciled additive migration ${i.tag} from existing schema objects.`));}}function dp(t,e){let{sql:n}=fn("drizzle-orm"),r=JSON.parse(nu.readFileSync(Re__namespace.default.join(e,"meta/_journal.json"),"utf-8")),s=["0025_task_heartbeat","0025_thread_app_instance_ledger","0026_mcp_action_source","0027_ui_instance_active_unique"].map(i=>{let c=r.entries.find(u=>u.tag===i);if(!c)throw new Error(`Missing release/App compatibility migration: ${i}`);let d=nu.readFileSync(Re__namespace.default.join(e,`${i}.sql`),"utf-8");return {entry:c,content:d,hash:crypto.createHash("sha256").update(d).digest("hex")}});t.transaction(i=>{let c=new Set(i.all(n`SELECT hash FROM __drizzle_migrations`).map(d=>d.hash));if(c.has(s[0].hash))for(let d of s.slice(1))c.has(d.hash)||(ba(i,d.content,n),i.run(n`INSERT INTO __drizzle_migrations (hash, created_at) VALUES (${d.hash}, ${d.entry.when})`),c.add(d.hash),console.error(`[crewx] Replayed release/App migration ${d.entry.tag} safely.`));},{behavior:"immediate"});}function pp(t,e,n,r){let s=JSON.parse(nu.readFileSync(Re__namespace.default.join(e,"meta/_journal.json"),"utf-8")).entries.find(({tag:p})=>p===cp);if(!s)return;let i=Re__namespace.default.join(e,`${s.tag}.sql`);if(!nu.existsSync(i))return;let c=crypto.createHash("sha256").update(nu.readFileSync(i,"utf-8")).digest("hex");if(r&&t.all(n`SELECT hash FROM __drizzle_migrations`).some(_=>_.hash===c))return;if(!hn(t,"tasks"))return {hash:c,affectedRows:0};let d=t.all("PRAGMA table_info(tasks)"),u=new Set(d.map(p=>p.name));if(!u.has("stop_requested_at")||!u.has("stop_requested_epoch"))return {hash:c,affectedRows:0};let l=t.get(n`
1
+ 'use strict';var Iu=require('fs'),Ne=require('path'),Ja=require('os'),crypto=require('crypto'),sqliteCore=require('drizzle-orm/sqlite-core'),drizzleOrm=require('drizzle-orm'),child_process=require('child_process');require('string_decoder');var promises=require('fs/promises');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 Iu__namespace=/*#__PURE__*/_interopNamespace(Iu);var Ne__namespace=/*#__PURE__*/_interopNamespace(Ne);var Ja__namespace=/*#__PURE__*/_interopNamespace(Ja);var mp=Object.defineProperty;var In=(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 kp=(t,e)=>{for(var n in e)mp(t,n,{get:e[n],enumerable:true});};var g=b(()=>{});var f,Nt=b(()=>{g();f=class extends Error{code;cause;constructor(e,n,r){super(n),this.name="RepositoryError",this.code=e,this.cause=r,Object.setPrototypeOf(this,new.target.prototype);}};});function za(t){if(t===":memory:")return t;let e=Ne.resolve(t),n=e,r=[];for(;!Iu.existsSync(n);){let s=Ne.dirname(n);if(s===n)return e;r.unshift(n.slice(s.length+1)),n=s;}let o=Iu.realpathSync(n);for(let s of r)o=Ne.join(o,s);return Ne.resolve(o)}function vp(t,e){let n=za(t),r=za(e);return process.platform==="win32"?n.toLowerCase()===r.toLowerCase():n===r}function on(t){if((process.env.NODE_ENV==="test"||process.env.VITEST!==void 0)&&bp.some(e=>vp(t,Ne.join(Ja__namespace.default.homedir(),".crewx",e))))throw new Error(`${Op}: ${t}. Set CREWX_DB to an isolated temporary path or :memory:.`);return t}var Op,bp,me,Ot=b(()=>{g();Op="[crewx] Refusing to open the real CrewX database from a test process";bp=["crewx.db","logs.db"];me=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||Ne.join(Ja__namespace.default.homedir(),".crewx","crewx.db");return on(e)}resolveDbPaths(){return [this.resolveDbPath()]}isMissingTableError(e){return e instanceof Error&&/no such table:/i.test(e.message)}dbExists(e){return Iu.existsSync(e??this.resolveDbPath())}};});function H(t,e={}){let n=on(t),r=In("better-sqlite3"),{drizzle:o}=In("drizzle-orm/better-sqlite3"),s=e.readOnly?new r(n,{readonly:true,fileMustExist:true}):new r(n);return e.readOnly||(s.exec("PRAGMA journal_mode = WAL"),s.exec(`PRAGMA journal_size_limit = ${xp}`),s.exec("PRAGMA busy_timeout = 5000"),s.exec("PRAGMA foreign_keys = ON"),s.exec("PRAGMA analysis_limit = 400")),{db:o(s),sqlite:s,runRaw:(i,c=[])=>s.prepare(i).run(...c),close:()=>s.close()}}var xp,qt=b(()=>{g();Ot();xp=32*1024*1024;});function Nn(t,e){return (t.get(`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='${e}'`)?.cnt??0)>0}function Pp(t,e){if(e>0||!Nn(t,"tasks"))return;let n=t.all("PRAGMA table_info(tasks)"),r=new Set(n.map(o=>o.name));for(let[o,s]of Object.entries(Dp))r.has(o)||t.run(`ALTER TABLE tasks ADD COLUMN ${o} ${s}`);}function Mp(t,e,n){if(!Nn(t,"__drizzle_migrations")||!Nn(t,"tasks"))return;let r=t.all(n`SELECT hash FROM __drizzle_migrations`),o=new Set(r.map(i=>i.hash)),s=JSON.parse(Iu.readFileSync(Ne__namespace.default.join(e,"meta/_journal.json"),"utf-8"));for(let i of s.entries){let c=Lp[i.tag];if(!c)continue;let d=Ne__namespace.default.join(e,`${i.tag}.sql`);if(!Iu.existsSync(d))continue;let u=Iu.readFileSync(d,"utf-8"),l=crypto.createHash("sha256").update(u).digest("hex");if(o.has(l))continue;let p=t.all("PRAGMA table_info(tasks)"),_=new Set(p.map(h=>h.name));for(let[h,m]of Object.entries(c))_.has(h)||(t.run(`ALTER TABLE tasks ADD COLUMN ${h} ${m}`),_.add(h));}}function Ya(t){let e=t.trim().replace(/;+\s*$/,"").trim(),n=e.match(/^ALTER\s+TABLE\s+[`"]?([A-Za-z_][\w$]*)[`"]?\s+ADD\s+(?:COLUMN\s+)?[`"]?([A-Za-z_][\w$]*)[`"]?/i);if(n)return {kind:"add-column",table:n[1],column:n[2]};let r=e.match(/^CREATE\s+(?:UNIQUE\s+)?INDEX(?:\s+IF\s+NOT\s+EXISTS)?\s+[`"]?([A-Za-z_][\w$]*)[`"]?\s+ON\s+/i);if(r)return {kind:"create-index",name:r[1]};let o=e.match(/^DROP\s+INDEX\s+IF\s+EXISTS\s+[`"]?([A-Za-z_][\w$]*)[`"]?/i);if(o)return {kind:"drop-index",name:o[1]}}function Qa(t){return t.split(/-->\s*statement-breakpoint/).map(e=>e.trim()).filter(Boolean)}function $p(t,e,n){return t.all(`PRAGMA table_info("${e}")`).some(s=>s.name===n)}function Hp(t,e){return t.all(`SELECT name FROM sqlite_master WHERE type = 'index' AND name = '${e}'`).length>0}function to(t,e){return e.kind==="add-column"?$p(t,e.table,e.column):Hp(t,e.name)}function Za(t,e,n){let r=t;for(let o of Qa(e)){let s=Ya(o);s?.kind==="add-column"&&to(r,s)||s?.kind==="create-index"&&to(r,s)||s?.kind==="drop-index"&&!to(r,s)||r.run(n.raw(o));}}function Up(t,e,n){let r=t.all(n`SELECT hash FROM __drizzle_migrations`),o=new Set(r.map(i=>i.hash)),s=JSON.parse(Iu.readFileSync(Ne__namespace.default.join(e,"meta/_journal.json"),"utf-8"));for(let i of s.entries){let c=Ne__namespace.default.join(e,`${i.tag}.sql`);if(!Iu.existsSync(c))continue;let d=Iu.readFileSync(c,"utf-8"),u=crypto.createHash("sha256").update(d).digest("hex");if(o.has(u))continue;let p=Qa(d).map(Ya);if(p.some(h=>!h))continue;let _=p;_.some(h=>h.kind==="add-column")&&_.some(h=>to(t,h))&&(t.transaction(h=>{Za(h,d,n),h.run(n`INSERT INTO __drizzle_migrations (hash, created_at) VALUES (${u}, ${i.when})`);},{behavior:"immediate"}),o.add(u),console.error(`[crewx] Reconciled additive migration ${i.tag} from existing schema objects.`));}}function qp(t,e){let{sql:n}=In("drizzle-orm"),r=JSON.parse(Iu.readFileSync(Ne__namespace.default.join(e,"meta/_journal.json"),"utf-8")),s=["0025_task_heartbeat","0025_thread_app_instance_ledger","0026_mcp_action_source","0027_ui_instance_active_unique"].map(i=>{let c=r.entries.find(u=>u.tag===i);if(!c)throw new Error(`Missing release/App compatibility migration: ${i}`);let d=Iu.readFileSync(Ne__namespace.default.join(e,`${i}.sql`),"utf-8");return {entry:c,content:d,hash:crypto.createHash("sha256").update(d).digest("hex")}});t.transaction(i=>{let c=new Set(i.all(n`SELECT hash FROM __drizzle_migrations`).map(d=>d.hash));if(c.has(s[0].hash))for(let d of s.slice(1))c.has(d.hash)||(Za(i,d.content,n),i.run(n`INSERT INTO __drizzle_migrations (hash, created_at) VALUES (${d.hash}, ${d.entry.when})`),c.add(d.hash),console.error(`[crewx] Replayed release/App migration ${d.entry.tag} safely.`));},{behavior:"immediate"});}function Gp(t,e,n,r){let s=JSON.parse(Iu.readFileSync(Ne__namespace.default.join(e,"meta/_journal.json"),"utf-8")).entries.find(({tag:p})=>p===Bp);if(!s)return;let i=Ne__namespace.default.join(e,`${s.tag}.sql`);if(!Iu.existsSync(i))return;let c=crypto.createHash("sha256").update(Iu.readFileSync(i,"utf-8")).digest("hex");if(r&&t.all(n`SELECT hash FROM __drizzle_migrations`).some(_=>_.hash===c))return;if(!Nn(t,"tasks"))return {hash:c,affectedRows:0};let d=t.all("PRAGMA table_info(tasks)"),u=new Set(d.map(p=>p.name));if(!u.has("stop_requested_at")||!u.has("stop_requested_epoch"))return {hash:c,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:c,affectedRows:l?.count??0}}function _p(t,e,n,r){let s=JSON.parse(nu.readFileSync(Re__namespace.default.join(e,"meta/_journal.json"),"utf-8")).entries.find(({tag:p})=>p===up);if(!s)return;let i=Re__namespace.default.join(e,`${s.tag}.sql`);if(!nu.existsSync(i))return;let c=crypto.createHash("sha256").update(nu.readFileSync(i,"utf-8")).digest("hex");if(r&&t.all(n`SELECT hash FROM __drizzle_migrations`).some(_=>_.hash===c))return;if(!hn(t,"threads"))return {hash:c,markedPointers:0};if(!t.all("PRAGMA table_info(threads)").some(p=>p.name==="created_by_task_id"))return {hash:c,markedPointers:0};let u=hn(t,va)?`AND NOT EXISTS (
6
+ `);return {hash:c,affectedRows:l?.count??0}}function jp(t,e,n,r){let s=JSON.parse(Iu.readFileSync(Ne__namespace.default.join(e,"meta/_journal.json"),"utf-8")).entries.find(({tag:p})=>p===Fp);if(!s)return;let i=Ne__namespace.default.join(e,`${s.tag}.sql`);if(!Iu.existsSync(i))return;let c=crypto.createHash("sha256").update(Iu.readFileSync(i,"utf-8")).digest("hex");if(r&&t.all(n`SELECT hash FROM __drizzle_migrations`).some(_=>_.hash===c))return;if(!Nn(t,"threads"))return {hash:c,markedPointers:0};if(!t.all("PRAGMA table_info(threads)").some(p=>p.name==="created_by_task_id"))return {hash:c,markedPointers:0};let u=Nn(t,Xa)?`AND NOT EXISTS (
7
7
  SELECT 1
8
- FROM ${va} AS marked
8
+ FROM ${Xa} 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,21 +15,21 @@
15
15
  SELECT 1
16
16
  FROM sqlite_master
17
17
  WHERE type = 'trigger'
18
- AND name = '${lp}'
18
+ AND name = '${Wp}'
19
19
  )
20
- ${u}`);return {hash:c,markedPointers:l?.count??0}}function fp(t){let{migrate:e}=fn("drizzle-orm/better-sqlite3/migrator"),{sql:n}=fn("drizzle-orm"),r=[Re__namespace.default.join(__dirname,"../migrations"),Re__namespace.default.join(__dirname,"migrations"),Re__namespace.default.join(__dirname,"../../../../drizzle/migrations"),Re__namespace.default.join(process.cwd(),"drizzle/migrations")],o=r.find(p=>nu.existsSync(Re__namespace.default.join(p,"meta/_journal.json")));if(!o)throw new Error(`migrations folder not found. Searched:
20
+ ${u}`);return {hash:c,markedPointers:l?.count??0}}function zp(t){let{migrate:e}=In("drizzle-orm/better-sqlite3/migrator"),{sql:n}=In("drizzle-orm"),r=[Ne__namespace.default.join(__dirname,"../migrations"),Ne__namespace.default.join(__dirname,"migrations"),Ne__namespace.default.join(__dirname,"../../../../drizzle/migrations"),Ne__namespace.default.join(process.cwd(),"drizzle/migrations")],o=r.find(p=>Iu.existsSync(Ne__namespace.default.join(p,"meta/_journal.json")));if(!o)throw new Error(`migrations folder not found. Searched:
21
21
  ${r.join(`
22
- `)}`);let s=t.get(n`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`),i=0;s?.cnt&&(i=t.get(n`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),np(t,i),s?.cnt&&(dp(t,o),ap(t,o,n),op(t,o,n));let c=pp(t,o,n,!!s?.cnt),d=_p(t,o,n,!!s?.cnt);e(t,{migrationsFolder:o});let l=(t.get(n`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-i;if(l>0){let p=s?.cnt?"Database migrated":"Database initialized";console.error(`[crewx] ${p} (${l} migration${l>1?"s":""} applied).`);}c&&t.all(n`SELECT hash FROM __drizzle_migrations`).some(_=>_.hash===c.hash)&&console.error(`[crewx] Task stop-marker cleanup (${c.affectedRows} success/failed row(s) affected).`),d&&t.all(n`SELECT hash FROM __drizzle_migrations`).some(_=>_.hash===d.hash)&&console.error(`[crewx] Thread creator pointer migration (${d.markedPointers} pointer(s) marked unverified).`);}function Be(t,e){Oa.has(e)||(fp(t),Oa.add(e));}var Oa,tp,rp,cp,up,lp,va,zt=C(()=>{g();Oa=new Set,tp={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"};rp={"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"}};cp="0027_task_stop_scope_cleanup",up="0033_thread_creator_boundary_guard",lp="trg_threads_creator_late_fill_guard",va="thread_creator_unverified";});var de,Gr=C(()=>{g();de=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,hy,yp,ce,mn=C(()=>{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:hy,...yp}=drizzleOrm.getTableColumns(a),ce=yp;});var wt,Ma=C(()=>{g();mn();wt=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 pt,Ha=C(()=>{g();mn();pt=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 Ap,Np,y,Xn=C(()=>{g();Gr();Ap="json_extract(metadata, '$.threadTitle.state')",Np="json_extract(metadata, '$.threadTitle.priority')",y=sqliteCore.sqliteTable("threads",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").references(()=>de.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(Ap)),idx_threads_workspace_thread_priority:sqliteCore.index("idx_threads_workspace_thread_priority").on(t.workspace_id,drizzleOrm.sql.raw(Np))}));});var Fa=C(()=>{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 bp,Wa=C(()=>{g();mn();bp=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(()=>bp.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 Ga=C(()=>{g();mn();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 Ka=C(()=>{g();Xn();sqliteCore.sqliteTable("thread_boxes",{id:sqliteCore.text("id").primaryKey(),thread_id:sqliteCore.text("thread_id").notNull().references(()=>y.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 Ja=C(()=>{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 Va=C(()=>{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 Qa=C(()=>{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 Za=C(()=>{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 td=C(()=>{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 rd=C(()=>{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 od=C(()=>{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 id=C(()=>{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 s=t.get(n`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`),i=0;s?.cnt&&(i=t.get(n`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),Pp(t,i),s?.cnt&&(qp(t,o),Up(t,o,n),Mp(t,o,n));let c=Gp(t,o,n,!!s?.cnt),d=jp(t,o,n,!!s?.cnt);e(t,{migrationsFolder:o});let l=(t.get(n`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-i;if(l>0){let p=s?.cnt?"Database migrated":"Database initialized";console.error(`[crewx] ${p} (${l} migration${l>1?"s":""} applied).`);}c&&t.all(n`SELECT hash FROM __drizzle_migrations`).some(_=>_.hash===c.hash)&&console.error(`[crewx] Task stop-marker cleanup (${c.affectedRows} success/failed row(s) affected).`),d&&t.all(n`SELECT hash FROM __drizzle_migrations`).some(_=>_.hash===d.hash)&&console.error(`[crewx] Thread creator pointer migration (${d.markedPointers} pointer(s) marked unverified).`);}function Pe(t,e){Va.has(e)||(zp(t),Va.add(e));}var Va,Dp,Lp,Bp,Fp,Wp,Xa,Bt=b(()=>{g();Va=new Set,Dp={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"};Lp={"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"}};Bp="0027_task_stop_scope_cleanup",Fp="0033_thread_creator_boundary_guard",Wp="trg_threads_creator_late_fill_guard",Xa="thread_creator_unverified";});var ue,no=b(()=>{g();ue=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,dT,Yp,le,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:dT,...Yp}=drizzleOrm.getTableColumns(a),le=Yp;});var vt,rd=b(()=>{g();On();vt=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 ht,sd=b(()=>{g();On();ht=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 o_,s_,y,vn=b(()=>{g();no();o_="json_extract(metadata, '$.threadTitle.state')",s_="json_extract(metadata, '$.threadTitle.priority')",y=sqliteCore.sqliteTable("threads",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").references(()=>ue.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(o_)),idx_threads_workspace_thread_priority:sqliteCore.index("idx_threads_workspace_thread_priority").on(t.workspace_id,drizzleOrm.sql.raw(s_))}));});var dd=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 u_,ud=b(()=>{g();On();u_=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(()=>u_.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 ld=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 _d=b(()=>{g();vn();sqliteCore.sqliteTable("thread_boxes",{id:sqliteCore.text("id").primaryKey(),thread_id:sqliteCore.text("thread_id").notNull().references(()=>y.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 j,mt,gd=b(()=>{g();vn();j=sqliteCore.sqliteTable("thread_branches",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").notNull(),parent_thread_id:sqliteCore.text("parent_thread_id").notNull().references(()=>y.id),child_thread_id:sqliteCore.text("child_thread_id").notNull().unique().references(()=>y.id,{onDelete:"cascade"}),branch_point_task_id:sqliteCore.text("branch_point_task_id").notNull(),branch_answer_no:sqliteCore.integer("branch_answer_no").notNull(),first_task_id:sqliteCore.text("first_task_id").notNull(),parent_title:sqliteCore.text("parent_title").notNull(),actor_id:sqliteCore.text("actor_id").notNull(),request_id:sqliteCore.text("request_id").notNull(),payload_hash:sqliteCore.text("payload_hash").notNull(),snapshot_version:sqliteCore.integer("snapshot_version").notNull(),carry_json:sqliteCore.text("carry_json").notNull(),carried_turns:sqliteCore.integer("carried_turns").notNull(),carried_chars:sqliteCore.integer("carried_chars").notNull(),carried_truncated:sqliteCore.integer("carried_truncated").notNull().default(0),status:sqliteCore.text("status",{enum:["active","undone"]}).notNull().default("active"),created_at:sqliteCore.text("created_at").notNull(),undone_at:sqliteCore.text("undone_at")},t=>({idx_thread_branches_parent_point:sqliteCore.index("idx_thread_branches_parent_point").on(t.parent_thread_id,t.branch_point_task_id),uniq_thread_branches_request:sqliteCore.unique("uniq_thread_branches_workspace_actor_request").on(t.workspace_id,t.actor_id,t.request_id),thread_branches_status_ck:sqliteCore.check("thread_branches_status_ck",drizzleOrm.sql`${t.status} IN ('active', 'undone')`),thread_branches_carried_truncated_ck:sqliteCore.check("thread_branches_carried_truncated_ck",drizzleOrm.sql`${t.carried_truncated} IN (0, 1)`)})),mt=sqliteCore.sqliteTable("thread_branch_sources",{branch_id:sqliteCore.text("branch_id").primaryKey().references(()=>j.id,{onDelete:"cascade"}),source_json:sqliteCore.text("source_json").notNull(),bytes:sqliteCore.integer("bytes").notNull()},t=>({thread_branch_sources_bytes_ck:sqliteCore.check("thread_branch_sources_bytes_ck",drizzleOrm.sql`${t.bytes} >= 0 AND ${t.bytes} <= 524288`)}));});var md=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 kd=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 wd=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 Ed=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 Sd=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 Ad=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 Nd=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 vd=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`(
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 ad=C(()=>{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 bd=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`(
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 cd=C(()=>{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 ld,pd=C(()=>{g();ld=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(()=>ld.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(()=>ld.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 fs,gs,L,hs=C(()=>{g();fs=["THREAD_STATE","THREAD_PRIORITY"],gs=["gray","blue","violet","green","amber","orange","red","pink"],L=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 _d,fd,gd,hd,md,V,j,F,kd=C(()=>{g();Xn();_d=["thread.snapshot.imported","thread.title.changed","thread.priority.changed","thread.state.changed","thread.highlight.created","thread.highlight.updated","thread.highlight.deleted","thread.highlights.regenerated"],fd=["user","agent","system"],gd=["auto","manual"],hd=["decision","judgment","issue","result","pivot"],md=["queued","running","completed","failed"],V=sqliteCore.sqliteTable("thread_events",{id:sqliteCore.text("id").primaryKey().notNull(),thread_id:sqliteCore.text("thread_id").notNull().references(()=>y.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)})),j=sqliteCore.sqliteTable("thread_highlight_runs",{id:sqliteCore.text("id").primaryKey().notNull(),thread_id:sqliteCore.text("thread_id").notNull().references(()=>y.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)})),F=sqliteCore.sqliteTable("thread_highlights",{id:sqliteCore.text("id").primaryKey().notNull(),thread_id:sqliteCore.text("thread_id").notNull().references(()=>y.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 Td=C(()=>{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 $e,wd=C(()=>{g();$e=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 Sd,Id=C(()=>{g();Xn();Gr();sqliteCore.sqliteTable("sidebar_states",{workspace_id:sqliteCore.text("workspace_id").primaryKey().references(()=>de.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)`)})),Sd=sqliteCore.sqliteTable("sidebar_groups",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").notNull().references(()=>de.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', 'green', 'lime', 'yellow', 'coral', 'pink', 'indigo', 'sand', 'gray')`),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(()=>de.id,{onDelete:"cascade"}),thread_id:sqliteCore.text("thread_id").notNull().references(()=>y.id,{onDelete:"cascade"}),group_id:sqliteCore.text("group_id").references(()=>Sd.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(()=>de.id,{onDelete:"cascade"}),thread_id:sqliteCore.text("thread_id").notNull().references(()=>y.id,{onDelete:"cascade"}),group_id:sqliteCore.text("group_id").references(()=>Sd.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(()=>de.id,{onDelete:"cascade"}),thread_id:sqliteCore.text("thread_id").notNull().references(()=>y.id,{onDelete:"cascade"}),read_through_at:sqliteCore.text("read_through_at").notNull()},t=>({pk:sqliteCore.primaryKey({columns:[t.workspace_id,t.thread_id]})}));});var Ad=C(()=>{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 Nd=C(()=>{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 Od=C(()=>{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 vd=C(()=>{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(),connection_kind:sqliteCore.text("connection_kind").$type().notNull().default("document"),app_grant_id:sqliteCore.text("app_grant_id"),app_grant_generation:sqliteCore.integer("app_grant_generation"),app_scope_version:sqliteCore.text("app_scope_version"),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),connectionKindAccountIdx:sqliteCore.index("doc_sync_links_connection_account_idx").on(t.account_key,t.connection_kind,t.app_id)}));});var Cd=C(()=>{g();sqliteCore.sqliteTable("doc_create_dispatches",{dispatch_id:sqliteCore.text("dispatch_id").primaryKey().notNull(),request_id:sqliteCore.text("request_id").notNull(),account_key:sqliteCore.text("account_key").notNull(),source:sqliteCore.text("source").$type().notNull(),dispatched_at:sqliteCore.integer("dispatched_at").notNull()},t=>({dispatchIdCheck:sqliteCore.check("doc_create_dispatches_id_ck",drizzleOrm.sql`length(${t.dispatch_id}) BETWEEN 1 AND 128`),requestIdCheck:sqliteCore.check("doc_create_dispatches_request_id_ck",drizzleOrm.sql`length(${t.request_id}) BETWEEN 1 AND 128`),accountKeyCheck:sqliteCore.check("doc_create_dispatches_account_key_ck",drizzleOrm.sql`length(${t.account_key}) = 64 AND ${t.account_key} NOT GLOB '*[^0-9a-f]*'`),sourceCheck:sqliteCore.check("doc_create_dispatches_source_ck",drizzleOrm.sql`${t.source} IN ('human', 'app_create', 'app_reattach')`),timestampCheck:sqliteCore.check("doc_create_dispatches_time_ck",drizzleOrm.sql`${t.dispatched_at} >= 0`),accountDispatchedIndex:sqliteCore.index("doc_create_dispatches_account_time_idx").on(t.account_key,t.dispatched_at)}));});var Tn,I_,xd=C(()=>{g();Tn=sqliteCore.sqliteTable("app_sync_bindings",{binding_id:sqliteCore.text("binding_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(),grant_id:sqliteCore.text("grant_id"),grant_generation:sqliteCore.integer("grant_generation"),scope_version:sqliteCore.text("scope_version"),status:sqliteCore.text("status").notNull().default("local_only"),created_at:sqliteCore.integer("created_at").notNull(),updated_at:sqliteCore.integer("updated_at").notNull()},t=>({bindingIdCheck:sqliteCore.check("app_sync_bindings_binding_id_ck",drizzleOrm.sql`length(${t.binding_id}) BETWEEN 1 AND 128`),accountKeyCheck:sqliteCore.check("app_sync_bindings_account_key_ck",drizzleOrm.sql`length(${t.account_key}) = 64 AND ${t.account_key} NOT GLOB '*[^0-9a-f]*'`),workspaceIdCheck:sqliteCore.check("app_sync_bindings_workspace_id_ck",drizzleOrm.sql`length(${t.workspace_id}) BETWEEN 1 AND 256`),appIdCheck:sqliteCore.check("app_sync_bindings_app_id_ck",drizzleOrm.sql`${t.app_id} = 'workout-log'`),rootSegmentsCheck:sqliteCore.check("app_sync_bindings_root_segments_ck",drizzleOrm.sql`json_valid(${t.root_segments}) AND json_type(${t.root_segments}) = 'array'`),grantGenerationCheck:sqliteCore.check("app_sync_bindings_generation_ck",drizzleOrm.sql`${t.grant_generation} IS NULL OR ${t.grant_generation} >= 1`),statusCheck:sqliteCore.check("app_sync_bindings_status_ck",drizzleOrm.sql`${t.status} IN ('local_only', 'consent_required', 'checking', 'syncing', 'synced', 'partial', 'offline', 'revoked', 'unavailable', 'stopping')`),timestampsCheck:sqliteCore.check("app_sync_bindings_timestamps_ck",drizzleOrm.sql`${t.updated_at} >= ${t.created_at}`),ownerAppUnique:sqliteCore.uniqueIndex("app_sync_bindings_owner_app_uq").on(t.account_key,t.app_id)})),sqliteCore.sqliteTable("app_sync_creation_jobs",{job_id:sqliteCore.text("job_id").primaryKey().notNull(),binding_id:sqliteCore.text("binding_id").notNull(),account_key:sqliteCore.text("account_key").notNull(),grant_id:sqliteCore.text("grant_id").notNull(),grant_generation:sqliteCore.integer("grant_generation").notNull(),ref:sqliteCore.text("ref").notNull(),request_id:sqliteCore.text("request_id").notNull(),fingerprint:sqliteCore.text("fingerprint").notNull(),operation_kind:sqliteCore.text("operation_kind").$type().notNull().default("create"),document_id:sqliteCore.text("document_id"),status:sqliteCore.text("status").notNull().default("waiting"),attempts:sqliteCore.integer("attempts").notNull().default(0),next_attempt_at:sqliteCore.integer("next_attempt_at").notNull().default(0),created_at:sqliteCore.integer("created_at").notNull(),updated_at:sqliteCore.integer("updated_at").notNull()},t=>({jobIdCheck:sqliteCore.check("app_sync_creation_jobs_job_id_ck",drizzleOrm.sql`length(${t.job_id}) BETWEEN 1 AND 128`),accountKeyCheck:sqliteCore.check("app_sync_creation_jobs_account_key_ck",drizzleOrm.sql`length(${t.account_key}) = 64 AND ${t.account_key} NOT GLOB '*[^0-9a-f]*'`),generationCheck:sqliteCore.check("app_sync_creation_jobs_generation_ck",drizzleOrm.sql`${t.grant_generation} >= 1`),refCheck:sqliteCore.check("app_sync_creation_jobs_ref_ck",drizzleOrm.sql`length(${t.ref}) BETWEEN 1 AND 256`),documentIdCheck:sqliteCore.check("app_sync_creation_jobs_document_id_ck",drizzleOrm.sql`${t.document_id} IS NULL OR length(${t.document_id}) BETWEEN 1 AND 128`),operationKindCheck:sqliteCore.check("app_sync_creation_jobs_operation_kind_ck",drizzleOrm.sql`${t.operation_kind} IN ('create', 'reattach')`),reattachDocumentCheck:sqliteCore.check("app_sync_creation_jobs_reattach_document_ck",drizzleOrm.sql`${t.operation_kind} != 'reattach' OR ${t.document_id} IS NOT NULL`),fingerprintCheck:sqliteCore.check("app_sync_creation_jobs_fingerprint_ck",drizzleOrm.sql`length(${t.fingerprint}) = 71 AND substr(${t.fingerprint}, 1, 7) = 'sha256:' AND substr(${t.fingerprint}, 8) NOT GLOB '*[^0-9a-f]*'`),statusCheck:sqliteCore.check("app_sync_creation_jobs_status_ck",drizzleOrm.sql`${t.status} IN ('waiting', 'processing', 'completed', 'failed', 'conflict', 'blocked', 'invalidated', 'deleted')`),attemptsCheck:sqliteCore.check("app_sync_creation_jobs_attempts_ck",drizzleOrm.sql`${t.attempts} >= 0`),timestampsCheck:sqliteCore.check("app_sync_creation_jobs_timestamps_ck",drizzleOrm.sql`${t.updated_at} >= ${t.created_at}`),bindingFk:sqliteCore.foreignKey({columns:[t.binding_id],foreignColumns:[Tn.binding_id]}).onDelete("cascade"),requestIdUnique:sqliteCore.uniqueIndex("app_sync_creation_jobs_request_id_uq").on(t.request_id),activeFingerprintUnique:sqliteCore.uniqueIndex("app_sync_creation_jobs_active_identity_uq").on(t.binding_id,t.grant_id,t.grant_generation,t.ref,t.fingerprint,t.operation_kind).where(drizzleOrm.sql`${t.status} IN ('waiting', 'processing')`),runnableIndex:sqliteCore.index("app_sync_creation_jobs_runnable_idx").on(t.binding_id,t.status,t.next_attempt_at),accountIndex:sqliteCore.index("app_sync_creation_jobs_account_idx").on(t.account_key,t.status)})),sqliteCore.sqliteTable("app_sync_results",{binding_id:sqliteCore.text("binding_id").notNull(),account_key:sqliteCore.text("account_key").notNull(),ref:sqliteCore.text("ref").notNull(),grant_id:sqliteCore.text("grant_id").notNull(),grant_generation:sqliteCore.integer("grant_generation").notNull(),source_fingerprint:sqliteCore.text("source_fingerprint"),synced_fingerprint:sqliteCore.text("synced_fingerprint"),document_id:sqliteCore.text("document_id"),status:sqliteCore.text("status").notNull(),error_code:sqliteCore.text("error_code"),next_attempt_at:sqliteCore.integer("next_attempt_at").notNull().default(0),attempts:sqliteCore.integer("attempts").notNull().default(0),updated_at:sqliteCore.integer("updated_at").notNull()},t=>({resultAccountCheck:sqliteCore.check("app_sync_results_account_key_ck",drizzleOrm.sql`length(${t.account_key}) = 64 AND ${t.account_key} NOT GLOB '*[^0-9a-f]*'`),resultRefCheck:sqliteCore.check("app_sync_results_ref_ck",drizzleOrm.sql`length(${t.ref}) BETWEEN 1 AND 256`),resultGenerationCheck:sqliteCore.check("app_sync_results_generation_ck",drizzleOrm.sql`${t.grant_generation} >= 1`),resultStatusCheck:sqliteCore.check("app_sync_results_status_ck",drizzleOrm.sql`${t.status} IN ('waiting', 'processing', 'synced', 'failed', 'conflict', 'blocked', 'excluded', 'deleted')`),resultAttemptsCheck:sqliteCore.check("app_sync_results_attempts_ck",drizzleOrm.sql`${t.attempts} >= 0`),resultBindingFk:sqliteCore.foreignKey({columns:[t.binding_id],foreignColumns:[Tn.binding_id]}).onDelete("cascade"),resultIdentityUnique:sqliteCore.uniqueIndex("app_sync_results_binding_ref_uq").on(t.binding_id,t.ref),resultAccountIndex:sqliteCore.index("app_sync_results_account_status_idx").on(t.account_key,t.status)})),sqliteCore.sqliteTable("app_sync_control_requests",{request_id:sqliteCore.text("request_id").primaryKey().notNull(),binding_id:sqliteCore.text("binding_id").notNull(),account_key:sqliteCore.text("account_key").notNull(),app_id:sqliteCore.text("app_id").notNull(),workspace_id:sqliteCore.text("workspace_id").notNull(),root_fingerprint:sqliteCore.text("root_fingerprint").notNull(),kind:sqliteCore.text("kind").notNull(),state:sqliteCore.text("state").notNull().default("pending"),grant_id:sqliteCore.text("grant_id"),generation:sqliteCore.integer("generation"),created_at:sqliteCore.integer("created_at").notNull(),updated_at:sqliteCore.integer("updated_at").notNull(),resolved_at:sqliteCore.integer("resolved_at"),resolution:sqliteCore.text("resolution"),resolution_id:sqliteCore.text("resolution_id")},t=>({requestIdCheck:sqliteCore.check("app_sync_control_requests_request_id_ck",drizzleOrm.sql`length(${t.request_id}) BETWEEN 1 AND 128`),requestAccountCheck:sqliteCore.check("app_sync_control_requests_account_key_ck",drizzleOrm.sql`length(${t.account_key}) = 64 AND ${t.account_key} NOT GLOB '*[^0-9a-f]*'`),requestAppCheck:sqliteCore.check("app_sync_control_requests_app_id_ck",drizzleOrm.sql`${t.app_id} = 'workout-log'`),requestWorkspaceCheck:sqliteCore.check("app_sync_control_requests_workspace_id_ck",drizzleOrm.sql`length(${t.workspace_id}) BETWEEN 1 AND 256`),rootFingerprintCheck:sqliteCore.check("app_sync_control_requests_root_fingerprint_ck",drizzleOrm.sql`length(${t.root_fingerprint}) = 64 AND ${t.root_fingerprint} NOT GLOB '*[^0-9a-f]*'`),requestKindCheck:sqliteCore.check("app_sync_control_requests_kind_ck",drizzleOrm.sql`${t.kind} IN ('connect', 'revoke')`),requestStateCheck:sqliteCore.check("app_sync_control_requests_state_ck",drizzleOrm.sql`${t.state} IN ('pending', 'unknown', 'confirmed', 'failed')`),revokeGrantCheck:sqliteCore.check("app_sync_control_requests_revoke_grant_ck",drizzleOrm.sql`${t.kind} != 'revoke' OR (${t.grant_id} IS NOT NULL AND ${t.generation} >= 1)`),requestResolutionCheck:sqliteCore.check("app_sync_control_requests_resolution_ck",drizzleOrm.sql`(${t.state} IN ('pending', 'unknown') AND ${t.resolved_at} IS NULL AND ${t.resolution} IS NULL AND ${t.resolution_id} IS NULL) OR (${t.state} IN ('confirmed', 'failed') AND ${t.resolved_at} IS NOT NULL AND ${t.resolution} IN ('remote', 'human') AND length(${t.resolution_id}) BETWEEN 1 AND 128)`),generationCheck:sqliteCore.check("app_sync_control_requests_generation_ck",drizzleOrm.sql`${t.generation} IS NULL OR ${t.generation} >= 1`),timestampsCheck:sqliteCore.check("app_sync_control_requests_timestamps_ck",drizzleOrm.sql`${t.updated_at} >= ${t.created_at}`),bindingFk:sqliteCore.foreignKey({columns:[t.binding_id],foreignColumns:[Tn.binding_id]}).onDelete("cascade"),unresolvedPerBinding:sqliteCore.uniqueIndex("app_sync_control_requests_one_pending_uq").on(t.binding_id).where(drizzleOrm.sql`${t.state} IN ('pending', 'unknown')`),accountLookup:sqliteCore.index("app_sync_control_requests_account_idx").on(t.account_key,t.app_id,t.state)})),sqliteCore.sqliteTable("app_sync_deleted_refs",{account_key:sqliteCore.text("account_key").notNull(),app_id:sqliteCore.text("app_id").notNull(),ref_sha256:sqliteCore.text("ref_sha256").notNull(),created_at:sqliteCore.integer("created_at").notNull()},t=>({deletedAccountCheck:sqliteCore.check("app_sync_deleted_refs_account_key_ck",drizzleOrm.sql`length(${t.account_key}) = 64 AND ${t.account_key} NOT GLOB '*[^0-9a-f]*'`),deletedAppCheck:sqliteCore.check("app_sync_deleted_refs_app_id_ck",drizzleOrm.sql`${t.app_id} = 'workout-log'`),deletedHashCheck:sqliteCore.check("app_sync_deleted_refs_hash_ck",drizzleOrm.sql`length(${t.ref_sha256}) = 64 AND ${t.ref_sha256} NOT GLOB '*[^0-9a-f]*'`),deletedIdentityUnique:sqliteCore.uniqueIndex("app_sync_deleted_refs_identity_uq").on(t.account_key,t.app_id,t.ref_sha256)})),sqliteCore.sqliteTable("app_sync_discovery_checkpoints",{binding_id:sqliteCore.text("binding_id").primaryKey().notNull(),account_key:sqliteCore.text("account_key").notNull(),workspace_id:sqliteCore.text("workspace_id").notNull(),root_fingerprint:sqliteCore.text("root_fingerprint").notNull(),grant_id:sqliteCore.text("grant_id").notNull(),grant_generation:sqliteCore.integer("grant_generation").notNull(),scope_version:sqliteCore.text("scope_version").notNull(),last_cycle_started_at:sqliteCore.integer("last_cycle_started_at"),cycle_started_at:sqliteCore.integer("cycle_started_at"),docs_cursor:sqliteCore.text("docs_cursor"),docs_complete:sqliteCore.integer("docs_complete").notNull().default(0),deleted_cursor:sqliteCore.text("deleted_cursor"),deleted_complete:sqliteCore.integer("deleted_complete").notNull().default(0),updated_at:sqliteCore.integer("updated_at").notNull()},t=>({checkpointAccountCheck:sqliteCore.check("app_sync_discovery_checkpoints_account_key_ck",drizzleOrm.sql`length(${t.account_key}) = 64 AND ${t.account_key} NOT GLOB '*[^0-9a-f]*'`),checkpointRootCheck:sqliteCore.check("app_sync_discovery_checkpoints_root_fingerprint_ck",drizzleOrm.sql`length(${t.root_fingerprint}) = 64 AND ${t.root_fingerprint} NOT GLOB '*[^0-9a-f]*'`),checkpointGenerationCheck:sqliteCore.check("app_sync_discovery_checkpoints_generation_ck",drizzleOrm.sql`${t.grant_generation} >= 1`),checkpointScopeCheck:sqliteCore.check("app_sync_discovery_checkpoints_scope_ck",drizzleOrm.sql`${t.scope_version} = 'workout-log.records.v1'`),checkpointDocsCompleteCheck:sqliteCore.check("app_sync_discovery_checkpoints_docs_complete_ck",drizzleOrm.sql`${t.docs_complete} IN (0, 1)`),checkpointDeletedCompleteCheck:sqliteCore.check("app_sync_discovery_checkpoints_deleted_complete_ck",drizzleOrm.sql`${t.deleted_complete} IN (0, 1)`),checkpointTimeCheck:sqliteCore.check("app_sync_discovery_checkpoints_time_ck",drizzleOrm.sql`${t.updated_at} >= 0 AND (${t.last_cycle_started_at} IS NULL OR ${t.last_cycle_started_at} >= 0) AND (${t.cycle_started_at} IS NULL OR ${t.cycle_started_at} >= 0)`),checkpointBindingFk:sqliteCore.foreignKey({columns:[t.binding_id],foreignColumns:[Tn.binding_id]}).onDelete("cascade"),checkpointAccountIndex:sqliteCore.index("app_sync_discovery_checkpoints_account_idx").on(t.account_key,t.grant_id,t.grant_generation)})),sqliteCore.sqliteTable("app_sync_pending_discoveries",{binding_id:sqliteCore.text("binding_id").notNull(),account_key:sqliteCore.text("account_key").notNull(),grant_id:sqliteCore.text("grant_id").notNull(),grant_generation:sqliteCore.integer("grant_generation").notNull(),ref:sqliteCore.text("ref").notNull(),doc_id:sqliteCore.text("doc_id").notNull(),listed_revision:sqliteCore.integer("listed_revision").notNull(),listed_fingerprint:sqliteCore.text("listed_fingerprint").notNull(),app_grant_generation:sqliteCore.integer("app_grant_generation").notNull(),needs_reattach:sqliteCore.integer("needs_reattach").notNull().default(0),needs_reconcile:sqliteCore.integer("needs_reconcile").notNull().default(0),status:sqliteCore.text("status").notNull().default("waiting"),error_code:sqliteCore.text("error_code"),attempts:sqliteCore.integer("attempts").notNull().default(0),updated_at:sqliteCore.integer("updated_at").notNull()},t=>({pendingAccountCheck:sqliteCore.check("app_sync_pending_discoveries_account_key_ck",drizzleOrm.sql`length(${t.account_key}) = 64 AND ${t.account_key} NOT GLOB '*[^0-9a-f]*'`),pendingRefCheck:sqliteCore.check("app_sync_pending_discoveries_ref_ck",drizzleOrm.sql`length(${t.ref}) BETWEEN 1 AND 256`),pendingDocCheck:sqliteCore.check("app_sync_pending_discoveries_doc_id_ck",drizzleOrm.sql`length(${t.doc_id}) BETWEEN 1 AND 128`),pendingRevisionCheck:sqliteCore.check("app_sync_pending_discoveries_revision_ck",drizzleOrm.sql`${t.listed_revision} >= 0`),pendingFingerprintCheck:sqliteCore.check("app_sync_pending_discoveries_fingerprint_ck",drizzleOrm.sql`length(${t.listed_fingerprint}) = 71 AND substr(${t.listed_fingerprint}, 1, 7) = 'sha256:' AND substr(${t.listed_fingerprint}, 8) NOT GLOB '*[^0-9a-f]*'`),pendingGenerationCheck:sqliteCore.check("app_sync_pending_discoveries_generation_ck",drizzleOrm.sql`${t.grant_generation} >= 1 AND ${t.app_grant_generation} >= 1`),pendingFlagsCheck:sqliteCore.check("app_sync_pending_discoveries_flags_ck",drizzleOrm.sql`${t.needs_reattach} IN (0, 1) AND ${t.needs_reconcile} IN (0, 1)`),pendingStatusCheck:sqliteCore.check("app_sync_pending_discoveries_status_ck",drizzleOrm.sql`${t.status} IN ('waiting', 'processing', 'failed', 'invalidated')`),pendingAttemptsCheck:sqliteCore.check("app_sync_pending_discoveries_attempts_ck",drizzleOrm.sql`${t.attempts} >= 0 AND ${t.updated_at} >= 0`),pendingBindingFk:sqliteCore.foreignKey({columns:[t.binding_id],foreignColumns:[Tn.binding_id]}).onDelete("cascade"),pendingIdentityUnique:sqliteCore.uniqueIndex("app_sync_pending_discoveries_identity_uq").on(t.binding_id,t.grant_id,t.grant_generation,t.ref),pendingRunnableIdx:sqliteCore.index("app_sync_pending_discoveries_runnable_idx").on(t.binding_id,t.grant_id,t.grant_generation,t.status,t.ref)})),I_=sqliteCore.sqliteTable("app_sync_conflicts",{conflict_id:sqliteCore.text("conflict_id").primaryKey().notNull(),binding_id:sqliteCore.text("binding_id").notNull(),account_key:sqliteCore.text("account_key").notNull(),workspace_id:sqliteCore.text("workspace_id").notNull(),root_fingerprint:sqliteCore.text("root_fingerprint").notNull(),grant_id:sqliteCore.text("grant_id").notNull(),grant_generation:sqliteCore.integer("grant_generation").notNull(),scope_version:sqliteCore.text("scope_version").notNull(),ref:sqliteCore.text("ref").notNull(),doc_id:sqliteCore.text("doc_id").notNull(),local_version:sqliteCore.text("local_version").notNull(),local_fingerprint:sqliteCore.text("local_fingerprint").notNull(),baseline_revision:sqliteCore.integer("baseline_revision"),baseline_fingerprint:sqliteCore.text("baseline_fingerprint"),remote_revision:sqliteCore.integer("remote_revision").notNull(),remote_fingerprint:sqliteCore.text("remote_fingerprint").notNull(),needs_reattach:sqliteCore.integer("needs_reattach").notNull().default(0),vault_handle:sqliteCore.text("vault_handle"),preservation_status:sqliteCore.text("preservation_status").notNull().default("pending"),state:sqliteCore.text("state").notNull().default("open"),superseded_by:sqliteCore.text("superseded_by"),resolution_request_id:sqliteCore.text("resolution_request_id"),resolution_choice:sqliteCore.text("resolution_choice"),cleanup_pending:sqliteCore.integer("cleanup_pending").notNull().default(0),created_at:sqliteCore.integer("created_at").notNull(),updated_at:sqliteCore.integer("updated_at").notNull()},t=>({conflictIdCheck:sqliteCore.check("app_sync_conflicts_id_ck",drizzleOrm.sql`length(${t.conflict_id}) BETWEEN 1 AND 128`),conflictAccountCheck:sqliteCore.check("app_sync_conflicts_account_key_ck",drizzleOrm.sql`length(${t.account_key}) = 64 AND ${t.account_key} NOT GLOB '*[^0-9a-f]*'`),conflictRootCheck:sqliteCore.check("app_sync_conflicts_root_fingerprint_ck",drizzleOrm.sql`length(${t.root_fingerprint}) = 64 AND ${t.root_fingerprint} NOT GLOB '*[^0-9a-f]*'`),conflictGenerationCheck:sqliteCore.check("app_sync_conflicts_generation_ck",drizzleOrm.sql`${t.grant_generation} >= 1`),conflictScopeCheck:sqliteCore.check("app_sync_conflicts_scope_ck",drizzleOrm.sql`${t.scope_version} = 'workout-log.records.v1'`),conflictRefCheck:sqliteCore.check("app_sync_conflicts_ref_ck",drizzleOrm.sql`length(${t.ref}) BETWEEN 1 AND 256`),conflictDocCheck:sqliteCore.check("app_sync_conflicts_doc_id_ck",drizzleOrm.sql`length(${t.doc_id}) BETWEEN 1 AND 128`),conflictLocalVersionCheck:sqliteCore.check("app_sync_conflicts_local_version_ck",drizzleOrm.sql`length(${t.local_version}) BETWEEN 1 AND 256 AND instr(${t.local_version}, '/') = 0 AND instr(${t.local_version}, char(92)) = 0`),conflictLocalFingerprintCheck:sqliteCore.check("app_sync_conflicts_local_fingerprint_ck",drizzleOrm.sql`length(${t.local_fingerprint}) = 71 AND substr(${t.local_fingerprint}, 1, 7) = 'sha256:' AND substr(${t.local_fingerprint}, 8) NOT GLOB '*[^0-9a-f]*'`),conflictBaselineCheck:sqliteCore.check("app_sync_conflicts_baseline_ck",drizzleOrm.sql`(${t.baseline_revision} IS NULL) = (${t.baseline_fingerprint} IS NULL) AND (${t.baseline_revision} IS NULL OR (${t.baseline_revision} >= 0 AND length(${t.baseline_fingerprint}) = 71 AND substr(${t.baseline_fingerprint}, 1, 7) = 'sha256:' AND substr(${t.baseline_fingerprint}, 8) NOT GLOB '*[^0-9a-f]*'))`),conflictRemoteCheck:sqliteCore.check("app_sync_conflicts_remote_ck",drizzleOrm.sql`${t.remote_revision} >= 0 AND length(${t.remote_fingerprint}) = 71 AND substr(${t.remote_fingerprint}, 1, 7) = 'sha256:' AND substr(${t.remote_fingerprint}, 8) NOT GLOB '*[^0-9a-f]*'`),conflictFlagsCheck:sqliteCore.check("app_sync_conflicts_flags_ck",drizzleOrm.sql`${t.needs_reattach} IN (0, 1) AND ${t.cleanup_pending} IN (0, 1)`),conflictHandleCheck:sqliteCore.check("app_sync_conflicts_handle_ck",drizzleOrm.sql`${t.vault_handle} IS NULL OR (length(${t.vault_handle}) BETWEEN 1 AND 256 AND instr(${t.vault_handle}, '/') = 0 AND instr(${t.vault_handle}, char(92)) = 0)`),conflictPreservationCheck:sqliteCore.check("app_sync_conflicts_preservation_ck",drizzleOrm.sql`${t.preservation_status} IN ('pending', 'ready', 'failed')`),conflictStateCheck:sqliteCore.check("app_sync_conflicts_state_ck",drizzleOrm.sql`${t.state} IN ('open', 'resolving', 'superseded', 'resolved', 'kept_both', 'purging')`),conflictArchiveLifecycleCheck:sqliteCore.check("app_sync_conflicts_archive_lifecycle_ck",drizzleOrm.sql`(
32
+ )`)}));});var xd=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 Pd,Ld=b(()=>{g();Pd=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(()=>Pd.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(()=>Pd.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 bs,Cs,L,xs=b(()=>{g();bs=["THREAD_STATE","THREAD_PRIORITY"],Cs=["gray","blue","violet","green","amber","orange","red","pink"],L=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 Md,$d,Hd,Ud,qd,X,z,B,Bd=b(()=>{g();vn();Md=["thread.snapshot.imported","thread.title.changed","thread.priority.changed","thread.state.changed","thread.highlight.created","thread.highlight.updated","thread.highlight.deleted","thread.highlights.regenerated"],$d=["user","agent","system"],Hd=["auto","manual"],Ud=["decision","judgment","issue","result","pivot"],qd=["queued","running","completed","failed"],X=sqliteCore.sqliteTable("thread_events",{id:sqliteCore.text("id").primaryKey().notNull(),thread_id:sqliteCore.text("thread_id").notNull().references(()=>y.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)})),z=sqliteCore.sqliteTable("thread_highlight_runs",{id:sqliteCore.text("id").primaryKey().notNull(),thread_id:sqliteCore.text("thread_id").notNull().references(()=>y.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)})),B=sqliteCore.sqliteTable("thread_highlights",{id:sqliteCore.text("id").primaryKey().notNull(),thread_id:sqliteCore.text("thread_id").notNull().references(()=>y.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 Wd=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 We,Gd=b(()=>{g();We=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 Kd,Jd=b(()=>{g();vn();no();sqliteCore.sqliteTable("sidebar_states",{workspace_id:sqliteCore.text("workspace_id").primaryKey().references(()=>ue.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)`)})),Kd=sqliteCore.sqliteTable("sidebar_groups",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").notNull().references(()=>ue.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', 'green', 'lime', 'yellow', 'coral', 'pink', 'indigo', 'sand', 'gray')`),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(()=>ue.id,{onDelete:"cascade"}),thread_id:sqliteCore.text("thread_id").notNull().references(()=>y.id,{onDelete:"cascade"}),group_id:sqliteCore.text("group_id").references(()=>Kd.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(()=>ue.id,{onDelete:"cascade"}),thread_id:sqliteCore.text("thread_id").notNull().references(()=>y.id,{onDelete:"cascade"}),group_id:sqliteCore.text("group_id").references(()=>Kd.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(()=>ue.id,{onDelete:"cascade"}),thread_id:sqliteCore.text("thread_id").notNull().references(()=>y.id,{onDelete:"cascade"}),read_through_at:sqliteCore.text("read_through_at").notNull()},t=>({pk:sqliteCore.primaryKey({columns:[t.workspace_id,t.thread_id]})}));});var Vd=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 Xd=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 Yd=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 Qd=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(),connection_kind:sqliteCore.text("connection_kind").$type().notNull().default("document"),app_grant_id:sqliteCore.text("app_grant_id"),app_grant_generation:sqliteCore.integer("app_grant_generation"),app_scope_version:sqliteCore.text("app_scope_version"),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),connectionKindAccountIdx:sqliteCore.index("doc_sync_links_connection_account_idx").on(t.account_key,t.connection_kind,t.app_id)}));});var Zd=b(()=>{g();sqliteCore.sqliteTable("doc_create_dispatches",{dispatch_id:sqliteCore.text("dispatch_id").primaryKey().notNull(),request_id:sqliteCore.text("request_id").notNull(),account_key:sqliteCore.text("account_key").notNull(),source:sqliteCore.text("source").$type().notNull(),dispatched_at:sqliteCore.integer("dispatched_at").notNull()},t=>({dispatchIdCheck:sqliteCore.check("doc_create_dispatches_id_ck",drizzleOrm.sql`length(${t.dispatch_id}) BETWEEN 1 AND 128`),requestIdCheck:sqliteCore.check("doc_create_dispatches_request_id_ck",drizzleOrm.sql`length(${t.request_id}) BETWEEN 1 AND 128`),accountKeyCheck:sqliteCore.check("doc_create_dispatches_account_key_ck",drizzleOrm.sql`length(${t.account_key}) = 64 AND ${t.account_key} NOT GLOB '*[^0-9a-f]*'`),sourceCheck:sqliteCore.check("doc_create_dispatches_source_ck",drizzleOrm.sql`${t.source} IN ('human', 'app_create', 'app_reattach')`),timestampCheck:sqliteCore.check("doc_create_dispatches_time_ck",drizzleOrm.sql`${t.dispatched_at} >= 0`),accountDispatchedIndex:sqliteCore.index("doc_create_dispatches_account_time_idx").on(t.account_key,t.dispatched_at)}));});var Dn,sf,ec=b(()=>{g();Dn=sqliteCore.sqliteTable("app_sync_bindings",{binding_id:sqliteCore.text("binding_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(),grant_id:sqliteCore.text("grant_id"),grant_generation:sqliteCore.integer("grant_generation"),scope_version:sqliteCore.text("scope_version"),status:sqliteCore.text("status").notNull().default("local_only"),created_at:sqliteCore.integer("created_at").notNull(),updated_at:sqliteCore.integer("updated_at").notNull()},t=>({bindingIdCheck:sqliteCore.check("app_sync_bindings_binding_id_ck",drizzleOrm.sql`length(${t.binding_id}) BETWEEN 1 AND 128`),accountKeyCheck:sqliteCore.check("app_sync_bindings_account_key_ck",drizzleOrm.sql`length(${t.account_key}) = 64 AND ${t.account_key} NOT GLOB '*[^0-9a-f]*'`),workspaceIdCheck:sqliteCore.check("app_sync_bindings_workspace_id_ck",drizzleOrm.sql`length(${t.workspace_id}) BETWEEN 1 AND 256`),appIdCheck:sqliteCore.check("app_sync_bindings_app_id_ck",drizzleOrm.sql`${t.app_id} = 'workout-log'`),rootSegmentsCheck:sqliteCore.check("app_sync_bindings_root_segments_ck",drizzleOrm.sql`json_valid(${t.root_segments}) AND json_type(${t.root_segments}) = 'array'`),grantGenerationCheck:sqliteCore.check("app_sync_bindings_generation_ck",drizzleOrm.sql`${t.grant_generation} IS NULL OR ${t.grant_generation} >= 1`),statusCheck:sqliteCore.check("app_sync_bindings_status_ck",drizzleOrm.sql`${t.status} IN ('local_only', 'consent_required', 'checking', 'syncing', 'synced', 'partial', 'offline', 'revoked', 'unavailable', 'stopping')`),timestampsCheck:sqliteCore.check("app_sync_bindings_timestamps_ck",drizzleOrm.sql`${t.updated_at} >= ${t.created_at}`),ownerAppUnique:sqliteCore.uniqueIndex("app_sync_bindings_owner_app_uq").on(t.account_key,t.app_id)})),sqliteCore.sqliteTable("app_sync_creation_jobs",{job_id:sqliteCore.text("job_id").primaryKey().notNull(),binding_id:sqliteCore.text("binding_id").notNull(),account_key:sqliteCore.text("account_key").notNull(),grant_id:sqliteCore.text("grant_id").notNull(),grant_generation:sqliteCore.integer("grant_generation").notNull(),ref:sqliteCore.text("ref").notNull(),request_id:sqliteCore.text("request_id").notNull(),fingerprint:sqliteCore.text("fingerprint").notNull(),operation_kind:sqliteCore.text("operation_kind").$type().notNull().default("create"),document_id:sqliteCore.text("document_id"),status:sqliteCore.text("status").notNull().default("waiting"),attempts:sqliteCore.integer("attempts").notNull().default(0),next_attempt_at:sqliteCore.integer("next_attempt_at").notNull().default(0),created_at:sqliteCore.integer("created_at").notNull(),updated_at:sqliteCore.integer("updated_at").notNull()},t=>({jobIdCheck:sqliteCore.check("app_sync_creation_jobs_job_id_ck",drizzleOrm.sql`length(${t.job_id}) BETWEEN 1 AND 128`),accountKeyCheck:sqliteCore.check("app_sync_creation_jobs_account_key_ck",drizzleOrm.sql`length(${t.account_key}) = 64 AND ${t.account_key} NOT GLOB '*[^0-9a-f]*'`),generationCheck:sqliteCore.check("app_sync_creation_jobs_generation_ck",drizzleOrm.sql`${t.grant_generation} >= 1`),refCheck:sqliteCore.check("app_sync_creation_jobs_ref_ck",drizzleOrm.sql`length(${t.ref}) BETWEEN 1 AND 256`),documentIdCheck:sqliteCore.check("app_sync_creation_jobs_document_id_ck",drizzleOrm.sql`${t.document_id} IS NULL OR length(${t.document_id}) BETWEEN 1 AND 128`),operationKindCheck:sqliteCore.check("app_sync_creation_jobs_operation_kind_ck",drizzleOrm.sql`${t.operation_kind} IN ('create', 'reattach')`),reattachDocumentCheck:sqliteCore.check("app_sync_creation_jobs_reattach_document_ck",drizzleOrm.sql`${t.operation_kind} != 'reattach' OR ${t.document_id} IS NOT NULL`),fingerprintCheck:sqliteCore.check("app_sync_creation_jobs_fingerprint_ck",drizzleOrm.sql`length(${t.fingerprint}) = 71 AND substr(${t.fingerprint}, 1, 7) = 'sha256:' AND substr(${t.fingerprint}, 8) NOT GLOB '*[^0-9a-f]*'`),statusCheck:sqliteCore.check("app_sync_creation_jobs_status_ck",drizzleOrm.sql`${t.status} IN ('waiting', 'processing', 'completed', 'failed', 'conflict', 'blocked', 'invalidated', 'deleted')`),attemptsCheck:sqliteCore.check("app_sync_creation_jobs_attempts_ck",drizzleOrm.sql`${t.attempts} >= 0`),timestampsCheck:sqliteCore.check("app_sync_creation_jobs_timestamps_ck",drizzleOrm.sql`${t.updated_at} >= ${t.created_at}`),bindingFk:sqliteCore.foreignKey({columns:[t.binding_id],foreignColumns:[Dn.binding_id]}).onDelete("cascade"),requestIdUnique:sqliteCore.uniqueIndex("app_sync_creation_jobs_request_id_uq").on(t.request_id),activeFingerprintUnique:sqliteCore.uniqueIndex("app_sync_creation_jobs_active_identity_uq").on(t.binding_id,t.grant_id,t.grant_generation,t.ref,t.fingerprint,t.operation_kind).where(drizzleOrm.sql`${t.status} IN ('waiting', 'processing')`),runnableIndex:sqliteCore.index("app_sync_creation_jobs_runnable_idx").on(t.binding_id,t.status,t.next_attempt_at),accountIndex:sqliteCore.index("app_sync_creation_jobs_account_idx").on(t.account_key,t.status)})),sqliteCore.sqliteTable("app_sync_results",{binding_id:sqliteCore.text("binding_id").notNull(),account_key:sqliteCore.text("account_key").notNull(),ref:sqliteCore.text("ref").notNull(),grant_id:sqliteCore.text("grant_id").notNull(),grant_generation:sqliteCore.integer("grant_generation").notNull(),source_fingerprint:sqliteCore.text("source_fingerprint"),synced_fingerprint:sqliteCore.text("synced_fingerprint"),document_id:sqliteCore.text("document_id"),status:sqliteCore.text("status").notNull(),error_code:sqliteCore.text("error_code"),next_attempt_at:sqliteCore.integer("next_attempt_at").notNull().default(0),attempts:sqliteCore.integer("attempts").notNull().default(0),updated_at:sqliteCore.integer("updated_at").notNull()},t=>({resultAccountCheck:sqliteCore.check("app_sync_results_account_key_ck",drizzleOrm.sql`length(${t.account_key}) = 64 AND ${t.account_key} NOT GLOB '*[^0-9a-f]*'`),resultRefCheck:sqliteCore.check("app_sync_results_ref_ck",drizzleOrm.sql`length(${t.ref}) BETWEEN 1 AND 256`),resultGenerationCheck:sqliteCore.check("app_sync_results_generation_ck",drizzleOrm.sql`${t.grant_generation} >= 1`),resultStatusCheck:sqliteCore.check("app_sync_results_status_ck",drizzleOrm.sql`${t.status} IN ('waiting', 'processing', 'synced', 'failed', 'conflict', 'blocked', 'excluded', 'deleted')`),resultAttemptsCheck:sqliteCore.check("app_sync_results_attempts_ck",drizzleOrm.sql`${t.attempts} >= 0`),resultBindingFk:sqliteCore.foreignKey({columns:[t.binding_id],foreignColumns:[Dn.binding_id]}).onDelete("cascade"),resultIdentityUnique:sqliteCore.uniqueIndex("app_sync_results_binding_ref_uq").on(t.binding_id,t.ref),resultAccountIndex:sqliteCore.index("app_sync_results_account_status_idx").on(t.account_key,t.status)})),sqliteCore.sqliteTable("app_sync_control_requests",{request_id:sqliteCore.text("request_id").primaryKey().notNull(),binding_id:sqliteCore.text("binding_id").notNull(),account_key:sqliteCore.text("account_key").notNull(),app_id:sqliteCore.text("app_id").notNull(),workspace_id:sqliteCore.text("workspace_id").notNull(),root_fingerprint:sqliteCore.text("root_fingerprint").notNull(),kind:sqliteCore.text("kind").notNull(),state:sqliteCore.text("state").notNull().default("pending"),grant_id:sqliteCore.text("grant_id"),generation:sqliteCore.integer("generation"),created_at:sqliteCore.integer("created_at").notNull(),updated_at:sqliteCore.integer("updated_at").notNull(),resolved_at:sqliteCore.integer("resolved_at"),resolution:sqliteCore.text("resolution"),resolution_id:sqliteCore.text("resolution_id")},t=>({requestIdCheck:sqliteCore.check("app_sync_control_requests_request_id_ck",drizzleOrm.sql`length(${t.request_id}) BETWEEN 1 AND 128`),requestAccountCheck:sqliteCore.check("app_sync_control_requests_account_key_ck",drizzleOrm.sql`length(${t.account_key}) = 64 AND ${t.account_key} NOT GLOB '*[^0-9a-f]*'`),requestAppCheck:sqliteCore.check("app_sync_control_requests_app_id_ck",drizzleOrm.sql`${t.app_id} = 'workout-log'`),requestWorkspaceCheck:sqliteCore.check("app_sync_control_requests_workspace_id_ck",drizzleOrm.sql`length(${t.workspace_id}) BETWEEN 1 AND 256`),rootFingerprintCheck:sqliteCore.check("app_sync_control_requests_root_fingerprint_ck",drizzleOrm.sql`length(${t.root_fingerprint}) = 64 AND ${t.root_fingerprint} NOT GLOB '*[^0-9a-f]*'`),requestKindCheck:sqliteCore.check("app_sync_control_requests_kind_ck",drizzleOrm.sql`${t.kind} IN ('connect', 'revoke')`),requestStateCheck:sqliteCore.check("app_sync_control_requests_state_ck",drizzleOrm.sql`${t.state} IN ('pending', 'unknown', 'confirmed', 'failed')`),revokeGrantCheck:sqliteCore.check("app_sync_control_requests_revoke_grant_ck",drizzleOrm.sql`${t.kind} != 'revoke' OR (${t.grant_id} IS NOT NULL AND ${t.generation} >= 1)`),requestResolutionCheck:sqliteCore.check("app_sync_control_requests_resolution_ck",drizzleOrm.sql`(${t.state} IN ('pending', 'unknown') AND ${t.resolved_at} IS NULL AND ${t.resolution} IS NULL AND ${t.resolution_id} IS NULL) OR (${t.state} IN ('confirmed', 'failed') AND ${t.resolved_at} IS NOT NULL AND ${t.resolution} IN ('remote', 'human') AND length(${t.resolution_id}) BETWEEN 1 AND 128)`),generationCheck:sqliteCore.check("app_sync_control_requests_generation_ck",drizzleOrm.sql`${t.generation} IS NULL OR ${t.generation} >= 1`),timestampsCheck:sqliteCore.check("app_sync_control_requests_timestamps_ck",drizzleOrm.sql`${t.updated_at} >= ${t.created_at}`),bindingFk:sqliteCore.foreignKey({columns:[t.binding_id],foreignColumns:[Dn.binding_id]}).onDelete("cascade"),unresolvedPerBinding:sqliteCore.uniqueIndex("app_sync_control_requests_one_pending_uq").on(t.binding_id).where(drizzleOrm.sql`${t.state} IN ('pending', 'unknown')`),accountLookup:sqliteCore.index("app_sync_control_requests_account_idx").on(t.account_key,t.app_id,t.state)})),sqliteCore.sqliteTable("app_sync_deleted_refs",{account_key:sqliteCore.text("account_key").notNull(),app_id:sqliteCore.text("app_id").notNull(),ref_sha256:sqliteCore.text("ref_sha256").notNull(),created_at:sqliteCore.integer("created_at").notNull()},t=>({deletedAccountCheck:sqliteCore.check("app_sync_deleted_refs_account_key_ck",drizzleOrm.sql`length(${t.account_key}) = 64 AND ${t.account_key} NOT GLOB '*[^0-9a-f]*'`),deletedAppCheck:sqliteCore.check("app_sync_deleted_refs_app_id_ck",drizzleOrm.sql`${t.app_id} = 'workout-log'`),deletedHashCheck:sqliteCore.check("app_sync_deleted_refs_hash_ck",drizzleOrm.sql`length(${t.ref_sha256}) = 64 AND ${t.ref_sha256} NOT GLOB '*[^0-9a-f]*'`),deletedIdentityUnique:sqliteCore.uniqueIndex("app_sync_deleted_refs_identity_uq").on(t.account_key,t.app_id,t.ref_sha256)})),sqliteCore.sqliteTable("app_sync_discovery_checkpoints",{binding_id:sqliteCore.text("binding_id").primaryKey().notNull(),account_key:sqliteCore.text("account_key").notNull(),workspace_id:sqliteCore.text("workspace_id").notNull(),root_fingerprint:sqliteCore.text("root_fingerprint").notNull(),grant_id:sqliteCore.text("grant_id").notNull(),grant_generation:sqliteCore.integer("grant_generation").notNull(),scope_version:sqliteCore.text("scope_version").notNull(),last_cycle_started_at:sqliteCore.integer("last_cycle_started_at"),cycle_started_at:sqliteCore.integer("cycle_started_at"),docs_cursor:sqliteCore.text("docs_cursor"),docs_complete:sqliteCore.integer("docs_complete").notNull().default(0),deleted_cursor:sqliteCore.text("deleted_cursor"),deleted_complete:sqliteCore.integer("deleted_complete").notNull().default(0),updated_at:sqliteCore.integer("updated_at").notNull()},t=>({checkpointAccountCheck:sqliteCore.check("app_sync_discovery_checkpoints_account_key_ck",drizzleOrm.sql`length(${t.account_key}) = 64 AND ${t.account_key} NOT GLOB '*[^0-9a-f]*'`),checkpointRootCheck:sqliteCore.check("app_sync_discovery_checkpoints_root_fingerprint_ck",drizzleOrm.sql`length(${t.root_fingerprint}) = 64 AND ${t.root_fingerprint} NOT GLOB '*[^0-9a-f]*'`),checkpointGenerationCheck:sqliteCore.check("app_sync_discovery_checkpoints_generation_ck",drizzleOrm.sql`${t.grant_generation} >= 1`),checkpointScopeCheck:sqliteCore.check("app_sync_discovery_checkpoints_scope_ck",drizzleOrm.sql`${t.scope_version} = 'workout-log.records.v1'`),checkpointDocsCompleteCheck:sqliteCore.check("app_sync_discovery_checkpoints_docs_complete_ck",drizzleOrm.sql`${t.docs_complete} IN (0, 1)`),checkpointDeletedCompleteCheck:sqliteCore.check("app_sync_discovery_checkpoints_deleted_complete_ck",drizzleOrm.sql`${t.deleted_complete} IN (0, 1)`),checkpointTimeCheck:sqliteCore.check("app_sync_discovery_checkpoints_time_ck",drizzleOrm.sql`${t.updated_at} >= 0 AND (${t.last_cycle_started_at} IS NULL OR ${t.last_cycle_started_at} >= 0) AND (${t.cycle_started_at} IS NULL OR ${t.cycle_started_at} >= 0)`),checkpointBindingFk:sqliteCore.foreignKey({columns:[t.binding_id],foreignColumns:[Dn.binding_id]}).onDelete("cascade"),checkpointAccountIndex:sqliteCore.index("app_sync_discovery_checkpoints_account_idx").on(t.account_key,t.grant_id,t.grant_generation)})),sqliteCore.sqliteTable("app_sync_pending_discoveries",{binding_id:sqliteCore.text("binding_id").notNull(),account_key:sqliteCore.text("account_key").notNull(),grant_id:sqliteCore.text("grant_id").notNull(),grant_generation:sqliteCore.integer("grant_generation").notNull(),ref:sqliteCore.text("ref").notNull(),doc_id:sqliteCore.text("doc_id").notNull(),listed_revision:sqliteCore.integer("listed_revision").notNull(),listed_fingerprint:sqliteCore.text("listed_fingerprint").notNull(),app_grant_generation:sqliteCore.integer("app_grant_generation").notNull(),needs_reattach:sqliteCore.integer("needs_reattach").notNull().default(0),needs_reconcile:sqliteCore.integer("needs_reconcile").notNull().default(0),status:sqliteCore.text("status").notNull().default("waiting"),error_code:sqliteCore.text("error_code"),attempts:sqliteCore.integer("attempts").notNull().default(0),updated_at:sqliteCore.integer("updated_at").notNull()},t=>({pendingAccountCheck:sqliteCore.check("app_sync_pending_discoveries_account_key_ck",drizzleOrm.sql`length(${t.account_key}) = 64 AND ${t.account_key} NOT GLOB '*[^0-9a-f]*'`),pendingRefCheck:sqliteCore.check("app_sync_pending_discoveries_ref_ck",drizzleOrm.sql`length(${t.ref}) BETWEEN 1 AND 256`),pendingDocCheck:sqliteCore.check("app_sync_pending_discoveries_doc_id_ck",drizzleOrm.sql`length(${t.doc_id}) BETWEEN 1 AND 128`),pendingRevisionCheck:sqliteCore.check("app_sync_pending_discoveries_revision_ck",drizzleOrm.sql`${t.listed_revision} >= 0`),pendingFingerprintCheck:sqliteCore.check("app_sync_pending_discoveries_fingerprint_ck",drizzleOrm.sql`length(${t.listed_fingerprint}) = 71 AND substr(${t.listed_fingerprint}, 1, 7) = 'sha256:' AND substr(${t.listed_fingerprint}, 8) NOT GLOB '*[^0-9a-f]*'`),pendingGenerationCheck:sqliteCore.check("app_sync_pending_discoveries_generation_ck",drizzleOrm.sql`${t.grant_generation} >= 1 AND ${t.app_grant_generation} >= 1`),pendingFlagsCheck:sqliteCore.check("app_sync_pending_discoveries_flags_ck",drizzleOrm.sql`${t.needs_reattach} IN (0, 1) AND ${t.needs_reconcile} IN (0, 1)`),pendingStatusCheck:sqliteCore.check("app_sync_pending_discoveries_status_ck",drizzleOrm.sql`${t.status} IN ('waiting', 'processing', 'failed', 'invalidated')`),pendingAttemptsCheck:sqliteCore.check("app_sync_pending_discoveries_attempts_ck",drizzleOrm.sql`${t.attempts} >= 0 AND ${t.updated_at} >= 0`),pendingBindingFk:sqliteCore.foreignKey({columns:[t.binding_id],foreignColumns:[Dn.binding_id]}).onDelete("cascade"),pendingIdentityUnique:sqliteCore.uniqueIndex("app_sync_pending_discoveries_identity_uq").on(t.binding_id,t.grant_id,t.grant_generation,t.ref),pendingRunnableIdx:sqliteCore.index("app_sync_pending_discoveries_runnable_idx").on(t.binding_id,t.grant_id,t.grant_generation,t.status,t.ref)})),sf=sqliteCore.sqliteTable("app_sync_conflicts",{conflict_id:sqliteCore.text("conflict_id").primaryKey().notNull(),binding_id:sqliteCore.text("binding_id").notNull(),account_key:sqliteCore.text("account_key").notNull(),workspace_id:sqliteCore.text("workspace_id").notNull(),root_fingerprint:sqliteCore.text("root_fingerprint").notNull(),grant_id:sqliteCore.text("grant_id").notNull(),grant_generation:sqliteCore.integer("grant_generation").notNull(),scope_version:sqliteCore.text("scope_version").notNull(),ref:sqliteCore.text("ref").notNull(),doc_id:sqliteCore.text("doc_id").notNull(),local_version:sqliteCore.text("local_version").notNull(),local_fingerprint:sqliteCore.text("local_fingerprint").notNull(),baseline_revision:sqliteCore.integer("baseline_revision"),baseline_fingerprint:sqliteCore.text("baseline_fingerprint"),remote_revision:sqliteCore.integer("remote_revision").notNull(),remote_fingerprint:sqliteCore.text("remote_fingerprint").notNull(),needs_reattach:sqliteCore.integer("needs_reattach").notNull().default(0),vault_handle:sqliteCore.text("vault_handle"),preservation_status:sqliteCore.text("preservation_status").notNull().default("pending"),state:sqliteCore.text("state").notNull().default("open"),superseded_by:sqliteCore.text("superseded_by"),resolution_request_id:sqliteCore.text("resolution_request_id"),resolution_choice:sqliteCore.text("resolution_choice"),cleanup_pending:sqliteCore.integer("cleanup_pending").notNull().default(0),created_at:sqliteCore.integer("created_at").notNull(),updated_at:sqliteCore.integer("updated_at").notNull()},t=>({conflictIdCheck:sqliteCore.check("app_sync_conflicts_id_ck",drizzleOrm.sql`length(${t.conflict_id}) BETWEEN 1 AND 128`),conflictAccountCheck:sqliteCore.check("app_sync_conflicts_account_key_ck",drizzleOrm.sql`length(${t.account_key}) = 64 AND ${t.account_key} NOT GLOB '*[^0-9a-f]*'`),conflictRootCheck:sqliteCore.check("app_sync_conflicts_root_fingerprint_ck",drizzleOrm.sql`length(${t.root_fingerprint}) = 64 AND ${t.root_fingerprint} NOT GLOB '*[^0-9a-f]*'`),conflictGenerationCheck:sqliteCore.check("app_sync_conflicts_generation_ck",drizzleOrm.sql`${t.grant_generation} >= 1`),conflictScopeCheck:sqliteCore.check("app_sync_conflicts_scope_ck",drizzleOrm.sql`${t.scope_version} = 'workout-log.records.v1'`),conflictRefCheck:sqliteCore.check("app_sync_conflicts_ref_ck",drizzleOrm.sql`length(${t.ref}) BETWEEN 1 AND 256`),conflictDocCheck:sqliteCore.check("app_sync_conflicts_doc_id_ck",drizzleOrm.sql`length(${t.doc_id}) BETWEEN 1 AND 128`),conflictLocalVersionCheck:sqliteCore.check("app_sync_conflicts_local_version_ck",drizzleOrm.sql`length(${t.local_version}) BETWEEN 1 AND 256 AND instr(${t.local_version}, '/') = 0 AND instr(${t.local_version}, char(92)) = 0`),conflictLocalFingerprintCheck:sqliteCore.check("app_sync_conflicts_local_fingerprint_ck",drizzleOrm.sql`length(${t.local_fingerprint}) = 71 AND substr(${t.local_fingerprint}, 1, 7) = 'sha256:' AND substr(${t.local_fingerprint}, 8) NOT GLOB '*[^0-9a-f]*'`),conflictBaselineCheck:sqliteCore.check("app_sync_conflicts_baseline_ck",drizzleOrm.sql`(${t.baseline_revision} IS NULL) = (${t.baseline_fingerprint} IS NULL) AND (${t.baseline_revision} IS NULL OR (${t.baseline_revision} >= 0 AND length(${t.baseline_fingerprint}) = 71 AND substr(${t.baseline_fingerprint}, 1, 7) = 'sha256:' AND substr(${t.baseline_fingerprint}, 8) NOT GLOB '*[^0-9a-f]*'))`),conflictRemoteCheck:sqliteCore.check("app_sync_conflicts_remote_ck",drizzleOrm.sql`${t.remote_revision} >= 0 AND length(${t.remote_fingerprint}) = 71 AND substr(${t.remote_fingerprint}, 1, 7) = 'sha256:' AND substr(${t.remote_fingerprint}, 8) NOT GLOB '*[^0-9a-f]*'`),conflictFlagsCheck:sqliteCore.check("app_sync_conflicts_flags_ck",drizzleOrm.sql`${t.needs_reattach} IN (0, 1) AND ${t.cleanup_pending} IN (0, 1)`),conflictHandleCheck:sqliteCore.check("app_sync_conflicts_handle_ck",drizzleOrm.sql`${t.vault_handle} IS NULL OR (length(${t.vault_handle}) BETWEEN 1 AND 256 AND instr(${t.vault_handle}, '/') = 0 AND instr(${t.vault_handle}, char(92)) = 0)`),conflictPreservationCheck:sqliteCore.check("app_sync_conflicts_preservation_ck",drizzleOrm.sql`${t.preservation_status} IN ('pending', 'ready', 'failed')`),conflictStateCheck:sqliteCore.check("app_sync_conflicts_state_ck",drizzleOrm.sql`${t.state} IN ('open', 'resolving', 'superseded', 'resolved', 'kept_both', 'purging')`),conflictArchiveLifecycleCheck:sqliteCore.check("app_sync_conflicts_archive_lifecycle_ck",drizzleOrm.sql`(
33
33
  (${t.preservation_status} IN ('pending', 'failed') AND ${t.vault_handle} IS NULL
34
34
  AND ${t.state} IN ('open', 'purging') AND ${t.cleanup_pending} = 0
35
35
  AND (${t.state} = 'purging' OR ${t.superseded_by} IS NULL))
@@ -42,30 +42,30 @@ ${r.join(`
42
42
  AND ((${t.cleanup_pending} = 1 AND ${t.vault_handle} IS NOT NULL)
43
43
  OR (${t.cleanup_pending} = 0 AND ${t.vault_handle} IS NULL)))
44
44
  ))
45
- )`),conflictSupersededCheck:sqliteCore.check("app_sync_conflicts_superseded_ck",drizzleOrm.sql`${t.state} != 'superseded' OR ${t.superseded_by} IS NOT NULL`),conflictResolutionCheck:sqliteCore.check("app_sync_conflicts_resolution_ck",drizzleOrm.sql`(${t.resolution_request_id} IS NULL AND ${t.resolution_choice} IS NULL) OR (length(${t.resolution_request_id}) BETWEEN 1 AND 128 AND ${t.resolution_choice} IN ('keep_local', 'use_cloud', 'keep_both'))`),conflictTimeCheck:sqliteCore.check("app_sync_conflicts_time_ck",drizzleOrm.sql`${t.updated_at} >= ${t.created_at}`),conflictBindingFk:sqliteCore.foreignKey({columns:[t.binding_id],foreignColumns:[Tn.binding_id]}).onDelete("cascade"),conflictIdentityUnique:sqliteCore.uniqueIndex("app_sync_conflicts_identity_uq").on(t.binding_id,t.grant_id,t.grant_generation,t.ref,t.local_version,t.remote_revision,t.remote_fingerprint),conflictLookup:sqliteCore.index("app_sync_conflicts_lookup_idx").on(t.account_key,t.binding_id,t.state,t.updated_at)})),sqliteCore.sqliteTable("app_sync_conflict_resolutions",{request_id:sqliteCore.text("request_id").primaryKey().notNull(),conflict_id:sqliteCore.text("conflict_id").notNull(),account_key:sqliteCore.text("account_key").notNull(),human_identity:sqliteCore.text("human_identity").notNull(),choice:sqliteCore.text("choice").notNull(),expected_local_version:sqliteCore.text("expected_local_version").notNull(),expected_remote_revision:sqliteCore.integer("expected_remote_revision").notNull(),expected_remote_fingerprint:sqliteCore.text("expected_remote_fingerprint").notNull(),state:sqliteCore.text("state").notNull().default("pending"),error_code:sqliteCore.text("error_code"),created_at:sqliteCore.integer("created_at").notNull(),updated_at:sqliteCore.integer("updated_at").notNull()},t=>({resolutionRequestIdCheck:sqliteCore.check("app_sync_conflict_resolutions_request_id_ck",drizzleOrm.sql`length(${t.request_id}) BETWEEN 1 AND 128`),resolutionAccountCheck:sqliteCore.check("app_sync_conflict_resolutions_account_key_ck",drizzleOrm.sql`length(${t.account_key}) = 64 AND ${t.account_key} NOT GLOB '*[^0-9a-f]*'`),resolutionIdentityCheck:sqliteCore.check("app_sync_conflict_resolutions_human_identity_ck",drizzleOrm.sql`length(${t.human_identity}) = 64 AND ${t.human_identity} NOT GLOB '*[^0-9a-f]*'`),resolutionChoiceCheck:sqliteCore.check("app_sync_conflict_resolutions_choice_ck",drizzleOrm.sql`${t.choice} IN ('keep_local', 'use_cloud', 'keep_both')`),resolutionLocalVersionCheck:sqliteCore.check("app_sync_conflict_resolutions_local_version_ck",drizzleOrm.sql`length(${t.expected_local_version}) BETWEEN 1 AND 256 AND instr(${t.expected_local_version}, '/') = 0 AND instr(${t.expected_local_version}, char(92)) = 0`),resolutionRemoteCheck:sqliteCore.check("app_sync_conflict_resolutions_remote_ck",drizzleOrm.sql`${t.expected_remote_revision} >= 0 AND length(${t.expected_remote_fingerprint}) = 71 AND substr(${t.expected_remote_fingerprint}, 1, 7) = 'sha256:' AND substr(${t.expected_remote_fingerprint}, 8) NOT GLOB '*[^0-9a-f]*'`),resolutionStateCheck:sqliteCore.check("app_sync_conflict_resolutions_state_ck",drizzleOrm.sql`${t.state} IN ('pending', 'unknown', 'resolved', 'stale', 'failed')`),resolutionTimeCheck:sqliteCore.check("app_sync_conflict_resolutions_time_ck",drizzleOrm.sql`${t.updated_at} >= ${t.created_at}`),resolutionConflictFk:sqliteCore.foreignKey({columns:[t.conflict_id],foreignColumns:[I_.conflict_id]}).onDelete("cascade"),resolutionConflictIdx:sqliteCore.index("app_sync_conflict_resolutions_conflict_idx").on(t.conflict_id,t.created_at),resolutionActiveUnique:sqliteCore.uniqueIndex("app_sync_conflict_resolutions_one_active_uq").on(t.conflict_id).where(drizzleOrm.sql`${t.state} IN ('pending', 'unknown')`)})),sqliteCore.sqliteTable("app_sync_account_data_purges",{request_id:sqliteCore.text("request_id").primaryKey().notNull(),binding_id:sqliteCore.text("binding_id").notNull(),account_key:sqliteCore.text("account_key").notNull(),workspace_id:sqliteCore.text("workspace_id").notNull(),root_fingerprint:sqliteCore.text("root_fingerprint").notNull(),human_identity:sqliteCore.text("human_identity").notNull(),state:sqliteCore.text("state").notNull().default("pending"),created_at:sqliteCore.integer("created_at").notNull(),updated_at:sqliteCore.integer("updated_at").notNull()},t=>({purgeRequestIdCheck:sqliteCore.check("app_sync_account_data_purges_request_id_ck",drizzleOrm.sql`length(${t.request_id}) BETWEEN 1 AND 128`),purgeAccountCheck:sqliteCore.check("app_sync_account_data_purges_account_key_ck",drizzleOrm.sql`length(${t.account_key}) = 64 AND ${t.account_key} NOT GLOB '*[^0-9a-f]*'`),purgeWorkspaceCheck:sqliteCore.check("app_sync_account_data_purges_workspace_id_ck",drizzleOrm.sql`length(${t.workspace_id}) BETWEEN 1 AND 256`),purgeRootCheck:sqliteCore.check("app_sync_account_data_purges_root_fingerprint_ck",drizzleOrm.sql`length(${t.root_fingerprint}) = 64 AND ${t.root_fingerprint} NOT GLOB '*[^0-9a-f]*'`),purgeHumanIdentityCheck:sqliteCore.check("app_sync_account_data_purges_human_identity_ck",drizzleOrm.sql`length(${t.human_identity}) = 64 AND ${t.human_identity} NOT GLOB '*[^0-9a-f]*'`),purgeStateCheck:sqliteCore.check("app_sync_account_data_purges_state_ck",drizzleOrm.sql`${t.state} IN ('pending', 'complete')`),purgeTimeCheck:sqliteCore.check("app_sync_account_data_purges_time_ck",drizzleOrm.sql`${t.updated_at} >= ${t.created_at}`),purgeAccountIndex:sqliteCore.index("app_sync_account_data_purges_account_idx").on(t.account_key,t.state,t.updated_at)}));});var bd=C(()=>{g();sqliteCore.sqliteTable("route_states",{workspace_key:sqliteCore.text("workspace_key").notNull().default("legacy"),route_id:sqliteCore.text("route_id").notNull(),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()},t=>({pk_route_state_workspace:sqliteCore.primaryKey({columns:[t.workspace_key,t.route_id]})})),sqliteCore.sqliteTable("route_sticky_bindings",{workspace_key:sqliteCore.text("workspace_key").notNull().default("legacy"),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.workspace_key,t.route_id,t.thread_id),idx_route_sticky_candidate:sqliteCore.index("idx_route_sticky_candidate").on(t.workspace_key,t.route_id,t.candidate_id)})),sqliteCore.sqliteTable("route_decisions",{id:sqliteCore.text("id").primaryKey(),workspace_key:sqliteCore.text("workspace_key").notNull().default("legacy"),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.workspace_key,t.route_id,t.task_id),idx_route_decisions_workspace_created:sqliteCore.index("idx_route_decisions_workspace_created").on(t.workspace_key,t.route_id,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 rn=C(()=>{g();Gr();mn();Ma();Ha();Xn();Fa();Wa();Ga();Ka();Ja();Va();Qa();Za();td();rd();od();id();ad();cd();pd();hs();kd();Td();wd();Id();Ad();Nd();Od();vd();Cd();xd();bd();});function or(t){return typeof t=="string"&&Dt.includes(t)}function Dd(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 o=n.workflow;if(typeof o=="object"&&o!==null&&!Array.isArray(o)){let s=o.exec_id;if(typeof s=="string"&&s!=="")return s}return null}var Dt,ro=C(()=>{g();Dt=["workflow_card","workflow_ui_instance","workflow_run"];});var wn,Is,Pd,As=C(()=>{g();wn={"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.8-flash":{input:1.5,cachedInput:.15,output:7.5},"gemini-4-argon":{input:4,cachedInput:.2,output:20},"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}},Is=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"]),Pd=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 Ns(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 v_(t){if(!t)return console.warn("[pricing] missing model id; cost is being recorded as 0"),sr;let e=Ns(t),n=O_[e];if(n)return oo[n]??wn[n]??sr;if(oo[e])return oo[e];if(wn[e])return wn[e];if(Is.has(e))return console.warn(`[pricing] unpublished model pricing: ${t}, cost_usd=0`),sr;if(Pd.has(e))return console.warn(`[pricing] missing catalog pricing: ${t}, cost_usd=0`),sr;let r={...wn,...oo};for(let o of Object.keys(r))if(e.includes(o))return r[o];return console.warn(`[pricing] Unknown model: ${t}, cost_usd=0`),sr}function C_(t,e,n,r=0,o){let s=v_(n),i=Math.min(r,t),d=(t-i)*s.input/1e6,u=i*s.cachedInput/1e6,l=e*s.output/1e6;return d+u+l}function Ld(t,e,n,r,o,s){return t&&t>0?t:!e&&!n?0:C_(e??0,n??0,o,r??0)}var O_,sr,oo,so=C(()=>{g();As();As();O_={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"},sr={input:0,cachedInput:0,output:0},oo={};});function Ud(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"||!x_.includes(r))return null;let o=n.schedule_id;return typeof o=="string"&&o!==""?o:null}var x_,qd=C(()=>{g();x_=["cron","cron_manual"];});function vs(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 io(t){return Number.isSafeInteger(t)&&t>0}function $_(t){let e=t.trim();if(!e)return "";let n=/^(?:"([^"]+)"|'([^']+)')/.exec(e);return n?.[1]??n?.[2]??e.split(/\s+/,1)[0]??""}function H_(t,e,n){let r=n==="win32"?t.toLowerCase():t,o=n==="win32"?e.toLowerCase():e;if(!o.trim())return false;if(o==="agy"){let s=$_(t).split(/[\\/]/).pop()??"",i=n==="win32"?s.toLowerCase():s;return i==="agy"||n==="win32"&&(i==="agy.exe"||i==="agy.cmd")}return r.includes(o)}function U_(t,e,n){return e.some(r=>H_(t,r,n))}function q_(t,e){try{let n=child_process.spawnSync(t,e,{encoding:"utf8",timeout:Os,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:vs(n)}}}function F_(t,e){return new Promise(n=>{let r;try{r=child_process.spawn(t,e,{windowsHide:!0});}catch(u){n({status:null,stdout:"",stderr:"",error:vs(u)});return}let o="",s="",i=false,c,d=setTimeout(()=>{try{r.kill();}catch{}c({status:null,stdout:o,stderr:s,error:new Error(`Command timed out after ${Os}ms`)});},Os);c=u=>{i||(i=true,clearTimeout(d),n(u));},r.stdout?.setEncoding("utf8"),r.stderr?.setEncoding("utf8"),r.stdout?.on("data",u=>{o+=String(u);}),r.stderr?.on("data",u=>{s+=String(u);}),r.once("error",u=>{c({status:null,stdout:o,stderr:s,error:u});}),r.once("close",u=>{c({status:u,stdout:o,stderr:s});});})}async function Cs(t,e,n){return n.runCommandAsync?n.runCommandAsync(t,e):n.runCommand?n.runCommand(t,e):F_(t,e)}function B_(t){return new Promise(e=>{setTimeout(e,Math.max(0,t));})}function W_(){return new Promise(t=>{setImmediate(t);})}function Pt(t,e=process.kill){try{return e(t,0),"alive"}catch(n){return Fd(n)==="ESRCH"?"not_found":Fd(n)==="EPERM"?"alive":"unknown"}}function G_(t,e){let n=Pt(-t,e),r=Pt(t,e);return n==="alive"||r==="alive"?"alive":n==="unknown"||r==="unknown"?"unknown":"not_found"}async function Wd(t,e,n,r){let o=Math.max(0,n),s=Math.max(1,r.pollIntervalMs??L_),i=Date.now()+o,c,d=o===0,u=r.sleep?Promise.resolve().then(()=>r.sleep(o)).then(()=>{},()=>{}):new Promise(l=>{c=setTimeout(l,o);});u.then(()=>{d=true;});try{for(await W_();;){let l=G_(t,e);if(l==="not_found")return l;let p=i-Date.now();if(d||p<=0)return l;await Promise.race([u,B_(Math.min(s,p))]);}}finally{c!==void 0&&clearTimeout(c);}}async function Bd(t,e,n,r,o){let s=await Wd(t,e,o.hardConfirmMs??M_,{...o,sleep:void 0});return s==="not_found"?n?{status:"not_found",pid:t,method:r}:{status:"terminated",pid:t,method:r}:s==="alive"?{status:"failed",pid:t,method:r,error:"Process is still running after termination attempt"}:{status:"failed",pid:t,method:r,error:"Unable to verify process termination"}}async function Gd(t,e,n={}){if(!io(t))return "unknown";let r=n.platform??process.platform,o=r==="win32"?"powershell.exe":"ps",s=r==="win32"?["-NoLogo","-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-Command",`$p = Get-CimInstance -ClassName Win32_Process -Filter 'ProcessId = ${t}' -ErrorAction Stop; if ($null -ne $p) { [Console]::Write([string]$p.CommandLine) }`]:["-p",String(t),"-o","command="],i;try{i=await Cs(o,s,n);}catch{return "unknown"}if(i.error||i.status!==0)return "unknown";let c=i.stdout.trim();return c?U_(c,e,r)?"owned":"not_owned":"not_found"}function J_(t){let e=j_.exec(t.trim());if(!e)return;let[,n="0",r="0",o="0",s="0"]=e;return ((Number(n)*24+Number(r))*60+Number(o))*60+Number(s)}function V_(t){let e=t.trim(),n=z_.exec(e);if(n){let[,o,s,i,c,d,u,l,p]=n;return Date.UTC(Number(o),Number(s)-1,Number(i),Number(c),Number(d),Number(u),Math.trunc(Number(l)/1e3))-Number(p)*6e4}let r=Date.parse(e);return Number.isFinite(r)?r:void 0}function jd(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=V_(r);return i===void 0?{status:"unknown"}:{status:"found",startedAtMs:i,groupId:null}}let o=K_.exec(r),s=o?J_(o[2]):void 0;return !o||s===void 0?{status:"unknown"}:o[3].startsWith("Z")?{status:"unknown"}:{status:"found",startedAtMs:n-s*1e3,groupId:Number(o[1])}}function zd(t,e={}){if(!io(t))return {status:"unknown"};let n=e.platform??process.platform,{command:r,args:o}=jd(t,n),s=e.runCommand??q_,i;try{i=s(r,o);}catch{return {status:"unknown"}}return Kd(i,n,Date.now())}async function Jd(t,e={}){if(!io(t))return {status:"unknown"};let n=e.platform??process.platform,{command:r,args:o}=jd(t,n),s;try{s=await Cs(r,o,e);}catch{return {status:"unknown"}}return Kd(s,n,Date.now())}async function Mt(t,e={}){let n=e.platform??process.platform,r=n==="win32"?"taskkill":"process-group",o=_=>({status:"failed",pid:t,method:r,error:_});if(!io(t))return o("Invalid process ID");let s=e.kill??process.kill,i=Pt(t,s);if(i==="not_found")return {status:"not_found",pid:t,method:r};if(i!=="alive")return o("Unable to determine whether the process is alive");if(n==="win32"){let _;try{_=await Cs("taskkill",["/PID",String(t),"/T","/F"],e);}catch(m){_={status:null,stdout:"",stderr:"",error:vs(m)};}let h=Pt(t,s);return h==="not_found"?_.status===0&&!_.error?{status:"terminated",pid:t,method:r}:{status:"not_found",pid:t,method:r}:o(h==="alive"?"Process is still running after termination attempt":"Unable to verify process termination")}let c,d=e.signal??"SIGKILL";try{s(-t,d);}catch(_){c=_;}if(d==="SIGKILL")return Bd(t,s,c,r,e);if(await Wd(t,s,e.graceMs??P_,e)==="not_found")return c?{status:"not_found",pid:t,method:r}:{status:"terminated",pid:t,method:r};let l;try{s(-t,"SIGKILL");}catch(_){l=_;}let p=await Bd(t,s,l,r,e);return p.status==="terminated"?p:p.status==="not_found"?c?p:{status:"terminated",pid:t,method:r}:o(p.error??"Process termination failed")}var Os,Lt,P_,L_,M_,ao,j_,K_,z_,co=C(()=>{g();Os=3e3,Lt="SIGINT",P_=2e3,L_=25,M_=100;ao=3e3,j_=/^(?:(\d+)-)?(?:(\d+):)?(\d{1,2}):(\d{2})$/,K_=/^\s*(\d+)\s+(\S+)\s+(\S+)\s*$/,z_=/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})\.(\d{6})([+-]\d{3})$/;});function Zd(t,e){let n=e===void 0?"":` at index ${e}`;if(!t||typeof t!="object")throw new f("VALIDATION",`Task log entry${n} must be an object`);if(typeof t.timestamp!="string"||typeof t.level!="string"||typeof t.message!="string")throw new f("VALIDATION",`Task log entry${n} must contain string timestamp, level, and message fields`);return {timestamp:t.timestamp,level:t.level,message:t.message}}function Yd(t,e){if(e===null||e.trim()==="")return [];let n;try{n=JSON.parse(e);}catch(r){throw new f("DB_ERROR",`Malformed legacy task logs: ${t}`,r)}if(!Array.isArray(n))throw new f("DB_ERROR",`Malformed legacy task logs: ${t} (expected an array)`);try{return n.map((r,o)=>Zd(r,o))}catch(r){throw r instanceof f?new f("DB_ERROR",`Malformed legacy task logs: ${t}`,r):r}}function ec(t){if(t.log_storage!=="blob"&&t.log_storage!=="events")throw new f("DB_ERROR",`Invalid task log storage for task: ${t.id}`);if(!Number.isInteger(t.last_log_seq)||t.last_log_seq<0)throw new f("DB_ERROR",`Invalid task log sequence for task: ${t.id}`);if(!Number.isInteger(t.log_revision)||t.log_revision<0)throw new f("DB_ERROR",`Invalid task log revision for task: ${t.id}`);return t.log_storage}function Qd(t){return {taskId:t.id,source:ec(t),revision:t.log_revision,lastSeq:t.last_log_seq}}function tf(t){if(!Number.isInteger(t)||t<0)throw new f("VALIDATION","Task log tail limit must be a non-negative integer")}var uo,tc=C(()=>{g();Ct();Kt();zt();vt();rn();uo=class extends ve{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=Re.join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?jt(this.dbPath):super.resolveDbPath()}openHandle(e){let n=this.resolveDbPath();if(e){let o=Re.dirname(n);nu.existsSync(o)||nu.mkdirSync(o,{recursive:true});}else if(!nu.existsSync(n))throw new f("NOT_FOUND","Database not found");let r=U(n);if(e)try{Be(r.db,n);}catch(o){throw r.close(),o}return r}findStateRow(e,n){return e.db.select({id:a.id,log_storage:a.log_storage,last_log_seq:a.last_log_seq,log_revision:a.log_revision,logs:a.logs}).from(a).where(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 f("NOT_FOUND",`Task not found: ${n}`);return r}appendLog(e,n){return this.appendLogs(e,[n])}appendLogs(e,n){let r=n.map((s,i)=>Zd(s,i));if(r.length===0){let s=this.getLogState(e);if(!s)throw new f("NOT_FOUND",`Task not found: ${e}`);return s}let o=this.openHandle(true);try{return o.db.transaction(i=>{let c=this.requireStateRowInTransaction(i,e),d=ec(c);if(d==="blob"){let _=Yd(e,c.logs);if(i.update(a).set({logs:JSON.stringify([..._,...r]),log_revision:drizzleOrm.sql`${a.log_revision} + 1`}).where(drizzleOrm.eq(a.id,e)).run().changes!==1)throw new f("NOT_FOUND",`Task not found: ${e}`);return {taskId:e,source:d,revision:c.log_revision+1,lastSeq:c.last_log_seq}}let u=c.last_log_seq+1,l=c.last_log_seq+r.length;if(i.insert(pt).values(r.map((_,h)=>({task_id:e,seq:u+h,timestamp:_.timestamp,level:_.level,message:_.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 f("NOT_FOUND",`Task not found: ${e}`);return {taskId:e,source:d,revision:c.log_revision+1,lastSeq:l}},{behavior:"immediate"})}catch(s){throw s instanceof f?s:new f("DB_ERROR","Failed to append task log",s)}finally{o.close();}}getLogState(e){if(!this.dbExists())return;let n=this.openHandle(false);try{let r=this.findStateRow(n,e);return r?Qd(r):void 0}catch(r){throw r instanceof f?r:new f("DB_ERROR","Failed to read task log state",r)}finally{n.close();}}readLogs(e){return this.readLogsInternal(e)}readLogsTail(e,n){return tf(n),this.readLogsInternal(e,n)}readTail(e,n){return this.readLogsTail(e,n)}readLogsInternal(e,n){if(!this.dbExists())return;let r=this.openHandle(false);try{return r.db.transaction(o=>{let s=this.findStateRowInTransaction(o,e);if(!s)return;let i=Qd(s);if(i.source==="blob"){let l=Yd(e,s.logs).map((p,_)=>({...p,seq:_+1}));return {...i,entries:n===void 0?l:l.slice(Math.max(0,l.length-n))}}let c=o.select({seq:pt.seq,timestamp:pt.timestamp,level:pt.level,message:pt.message}).from(pt).where(drizzleOrm.eq(pt.task_id,e)).orderBy(n===void 0?drizzleOrm.asc(pt.seq):drizzleOrm.desc(pt.seq)),u=(n===void 0?c.all():c.limit(n).all()).map(({seq:l,timestamp:p,level:_,message:h})=>({seq:l,timestamp:p,level:_,message:h}));return n!==void 0&&u.reverse(),{...i,entries:u}},{behavior:"deferred"})}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to read task logs",o)}finally{r.close();}}};});var af,lo,rc=C(()=>{g();Ct();Kt();zt();vt();rn();af=50,lo=class extends ve{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=U(e);try{return Be(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($e).values({workspace_id:e.workspaceId,actor_id:e.actorId,agent_id:e.agentId,last_accepted_at:r}).onConflictDoUpdate({target:[$e.workspace_id,$e.actor_id,$e.agent_id],set:{last_accepted_at:drizzleOrm.sql`MAX(${$e.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:$e.agent_id,lastAcceptedAt:$e.last_accepted_at}).from($e).where(drizzleOrm.and(drizzleOrm.eq($e.workspace_id,e),drizzleOrm.eq($e.actor_id,n))).orderBy(drizzleOrm.desc($e.last_accepted_at),drizzleOrm.asc($e.agent_id)).limit(af).all()}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to find recent agent sends",o)}finally{r?.close();}}};});var oc=C(()=>{g();});var df,W,$t=C(()=>{g();df=new Set(["ACCOUNT_SETTING_REQUIRED","MODEL_RETIRED","SUBSCRIPTION_REQUIRED"]),W=class extends Error{constructor(n,r,o){super(n);this.providerStr=r;this.name="ProviderError",this.code=o?.code??"UNKNOWN",this.kind=df.has(this.code)?"config":o?.kind??(this.code==="UNKNOWN"?"transient":void 0),this.retryAfterMs=o?.retryAfterMs,this.settingReason=o?.settingReason,this.replacementModel=o?.replacementModel,this.providerReason=o?.providerReason;}providerStr;code;kind;retryAfterMs;settingReason;replacementModel;providerReason;stdout};});var on,xs=C(()=>{g();$t();on=class extends W{name="RateLimitError";constructor(e,n="cli/claude"){super(e,n,{code:"QUOTA_EXHAUSTED",kind:"transient"});}};});function po(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 ${Ne}]`),e=uf(e),e=e.replace(/\b(?:Bearer|Basic)\s+[A-Za-z0-9._~+\-/]+=*/gi,`${Ne}`),e=e.replace(/\bsk-[A-Za-z0-9][A-Za-z0-9_-]*/g,Ne),e=e.replace(/\bghp_[A-Za-z0-9][A-Za-z0-9_-]*/g,Ne),e=e.replace(/\bxoxb-[A-Za-z0-9-]+/g,Ne),e=e.replace(/\bxoxp-[A-Za-z0-9-]+/g,Ne),e=e.replace(/\bAKIA[0-9A-Z]{12,}\b/g,Ne),e=e.replace(/\bgithub_pat_[A-Za-z0-9_]+/g,Ne),e=e.replace(/\bgho_[A-Za-z0-9_]+/g,Ne),e=e.replace(/\bAIza[A-Za-z0-9_-]{20,}\b/g,Ne),e=e.replace(/\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/g,Ne),e=e.replace(/\b(?:authorization|api[_ -]?key|access[_ -]?token|auth[_ -]?token|refresh[_ -]?token|token|secret|password)\s*([:=])\s*["']?[^\s,;&"']+/gi,(n,r)=>`${Ne}${r}${Ne}`),e=e.replace(/([?&](?:api[_-]?key|access[_-]?token|token)=)[^&\s]+/gi,`$1${Ne}`),e=e.replace(/(?:\/(?:Users|home|private|var\/folders|tmp|workspace|workspaces|Volumes|opt|etc|srv|Applications)\/[^\s"'`),;]+)/g,sc),e=e.replace(/\b[A-Z]:\\(?:Users|home|Windows|Program Files|workspace|workspaces)\\[^\s"'`),;]*/gi,sc),e=e.replace(/[\r\n]{3,}/g,`
45
+ )`),conflictSupersededCheck:sqliteCore.check("app_sync_conflicts_superseded_ck",drizzleOrm.sql`${t.state} != 'superseded' OR ${t.superseded_by} IS NOT NULL`),conflictResolutionCheck:sqliteCore.check("app_sync_conflicts_resolution_ck",drizzleOrm.sql`(${t.resolution_request_id} IS NULL AND ${t.resolution_choice} IS NULL) OR (length(${t.resolution_request_id}) BETWEEN 1 AND 128 AND ${t.resolution_choice} IN ('keep_local', 'use_cloud', 'keep_both'))`),conflictTimeCheck:sqliteCore.check("app_sync_conflicts_time_ck",drizzleOrm.sql`${t.updated_at} >= ${t.created_at}`),conflictBindingFk:sqliteCore.foreignKey({columns:[t.binding_id],foreignColumns:[Dn.binding_id]}).onDelete("cascade"),conflictIdentityUnique:sqliteCore.uniqueIndex("app_sync_conflicts_identity_uq").on(t.binding_id,t.grant_id,t.grant_generation,t.ref,t.local_version,t.remote_revision,t.remote_fingerprint),conflictLookup:sqliteCore.index("app_sync_conflicts_lookup_idx").on(t.account_key,t.binding_id,t.state,t.updated_at)})),sqliteCore.sqliteTable("app_sync_conflict_resolutions",{request_id:sqliteCore.text("request_id").primaryKey().notNull(),conflict_id:sqliteCore.text("conflict_id").notNull(),account_key:sqliteCore.text("account_key").notNull(),human_identity:sqliteCore.text("human_identity").notNull(),choice:sqliteCore.text("choice").notNull(),expected_local_version:sqliteCore.text("expected_local_version").notNull(),expected_remote_revision:sqliteCore.integer("expected_remote_revision").notNull(),expected_remote_fingerprint:sqliteCore.text("expected_remote_fingerprint").notNull(),state:sqliteCore.text("state").notNull().default("pending"),error_code:sqliteCore.text("error_code"),created_at:sqliteCore.integer("created_at").notNull(),updated_at:sqliteCore.integer("updated_at").notNull()},t=>({resolutionRequestIdCheck:sqliteCore.check("app_sync_conflict_resolutions_request_id_ck",drizzleOrm.sql`length(${t.request_id}) BETWEEN 1 AND 128`),resolutionAccountCheck:sqliteCore.check("app_sync_conflict_resolutions_account_key_ck",drizzleOrm.sql`length(${t.account_key}) = 64 AND ${t.account_key} NOT GLOB '*[^0-9a-f]*'`),resolutionIdentityCheck:sqliteCore.check("app_sync_conflict_resolutions_human_identity_ck",drizzleOrm.sql`length(${t.human_identity}) = 64 AND ${t.human_identity} NOT GLOB '*[^0-9a-f]*'`),resolutionChoiceCheck:sqliteCore.check("app_sync_conflict_resolutions_choice_ck",drizzleOrm.sql`${t.choice} IN ('keep_local', 'use_cloud', 'keep_both')`),resolutionLocalVersionCheck:sqliteCore.check("app_sync_conflict_resolutions_local_version_ck",drizzleOrm.sql`length(${t.expected_local_version}) BETWEEN 1 AND 256 AND instr(${t.expected_local_version}, '/') = 0 AND instr(${t.expected_local_version}, char(92)) = 0`),resolutionRemoteCheck:sqliteCore.check("app_sync_conflict_resolutions_remote_ck",drizzleOrm.sql`${t.expected_remote_revision} >= 0 AND length(${t.expected_remote_fingerprint}) = 71 AND substr(${t.expected_remote_fingerprint}, 1, 7) = 'sha256:' AND substr(${t.expected_remote_fingerprint}, 8) NOT GLOB '*[^0-9a-f]*'`),resolutionStateCheck:sqliteCore.check("app_sync_conflict_resolutions_state_ck",drizzleOrm.sql`${t.state} IN ('pending', 'unknown', 'resolved', 'stale', 'failed')`),resolutionTimeCheck:sqliteCore.check("app_sync_conflict_resolutions_time_ck",drizzleOrm.sql`${t.updated_at} >= ${t.created_at}`),resolutionConflictFk:sqliteCore.foreignKey({columns:[t.conflict_id],foreignColumns:[sf.conflict_id]}).onDelete("cascade"),resolutionConflictIdx:sqliteCore.index("app_sync_conflict_resolutions_conflict_idx").on(t.conflict_id,t.created_at),resolutionActiveUnique:sqliteCore.uniqueIndex("app_sync_conflict_resolutions_one_active_uq").on(t.conflict_id).where(drizzleOrm.sql`${t.state} IN ('pending', 'unknown')`)})),sqliteCore.sqliteTable("app_sync_account_data_purges",{request_id:sqliteCore.text("request_id").primaryKey().notNull(),binding_id:sqliteCore.text("binding_id").notNull(),account_key:sqliteCore.text("account_key").notNull(),workspace_id:sqliteCore.text("workspace_id").notNull(),root_fingerprint:sqliteCore.text("root_fingerprint").notNull(),human_identity:sqliteCore.text("human_identity").notNull(),state:sqliteCore.text("state").notNull().default("pending"),created_at:sqliteCore.integer("created_at").notNull(),updated_at:sqliteCore.integer("updated_at").notNull()},t=>({purgeRequestIdCheck:sqliteCore.check("app_sync_account_data_purges_request_id_ck",drizzleOrm.sql`length(${t.request_id}) BETWEEN 1 AND 128`),purgeAccountCheck:sqliteCore.check("app_sync_account_data_purges_account_key_ck",drizzleOrm.sql`length(${t.account_key}) = 64 AND ${t.account_key} NOT GLOB '*[^0-9a-f]*'`),purgeWorkspaceCheck:sqliteCore.check("app_sync_account_data_purges_workspace_id_ck",drizzleOrm.sql`length(${t.workspace_id}) BETWEEN 1 AND 256`),purgeRootCheck:sqliteCore.check("app_sync_account_data_purges_root_fingerprint_ck",drizzleOrm.sql`length(${t.root_fingerprint}) = 64 AND ${t.root_fingerprint} NOT GLOB '*[^0-9a-f]*'`),purgeHumanIdentityCheck:sqliteCore.check("app_sync_account_data_purges_human_identity_ck",drizzleOrm.sql`length(${t.human_identity}) = 64 AND ${t.human_identity} NOT GLOB '*[^0-9a-f]*'`),purgeStateCheck:sqliteCore.check("app_sync_account_data_purges_state_ck",drizzleOrm.sql`${t.state} IN ('pending', 'complete')`),purgeTimeCheck:sqliteCore.check("app_sync_account_data_purges_time_ck",drizzleOrm.sql`${t.updated_at} >= ${t.created_at}`),purgeAccountIndex:sqliteCore.index("app_sync_account_data_purges_account_idx").on(t.account_key,t.state,t.updated_at)}));});var tc=b(()=>{g();sqliteCore.sqliteTable("route_states",{workspace_key:sqliteCore.text("workspace_key").notNull().default("legacy"),route_id:sqliteCore.text("route_id").notNull(),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()},t=>({pk_route_state_workspace:sqliteCore.primaryKey({columns:[t.workspace_key,t.route_id]})})),sqliteCore.sqliteTable("route_sticky_bindings",{workspace_key:sqliteCore.text("workspace_key").notNull().default("legacy"),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.workspace_key,t.route_id,t.thread_id),idx_route_sticky_candidate:sqliteCore.index("idx_route_sticky_candidate").on(t.workspace_key,t.route_id,t.candidate_id)})),sqliteCore.sqliteTable("route_decisions",{id:sqliteCore.text("id").primaryKey(),workspace_key:sqliteCore.text("workspace_key").notNull().default("legacy"),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.workspace_key,t.route_id,t.task_id),idx_route_decisions_workspace_created:sqliteCore.index("idx_route_decisions_workspace_created").on(t.workspace_key,t.route_id,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 Gt=b(()=>{g();no();On();rd();sd();vn();dd();ud();ld();_d();gd();md();kd();wd();Ed();Sd();Ad();Nd();vd();bd();xd();Ld();xs();Bd();Wd();Gd();Jd();Vd();Xd();Yd();Qd();Zd();ec();tc();});function kr(t){return typeof t=="string"&&jt.includes(t)}function nc(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 o=n.workflow;if(typeof o=="object"&&o!==null&&!Array.isArray(o)){let s=o.exec_id;if(typeof s=="string"&&s!=="")return s}return null}var jt,ho=b(()=>{g();jt=["workflow_card","workflow_ui_instance","workflow_run"];});var Pn,Bs,rc,Fs=b(()=>{g();Pn={"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.8-flash":{input:1.5,cachedInput:.15,output:7.5},"gemini-4-argon":{input:4,cachedInput:.2,output:20},"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}},Bs=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"]),rc=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 Ws(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 uf(t){if(!t)return console.warn("[pricing] missing model id; cost is being recorded as 0"),yr;let e=Ws(t),n=cf[e];if(n)return mo[n]??Pn[n]??yr;if(mo[e])return mo[e];if(Pn[e])return Pn[e];if(Bs.has(e))return console.warn(`[pricing] unpublished model pricing: ${t}, cost_usd=0`),yr;if(rc.has(e))return console.warn(`[pricing] missing catalog pricing: ${t}, cost_usd=0`),yr;let r={...Pn,...mo};for(let o of Object.keys(r))if(e.includes(o))return r[o];return console.warn(`[pricing] Unknown model: ${t}, cost_usd=0`),yr}function lf(t,e,n,r=0,o){let s=uf(n),i=Math.min(r,t),d=(t-i)*s.input/1e6,u=i*s.cachedInput/1e6,l=e*s.output/1e6;return d+u+l}function oc(t,e,n,r,o,s){return t&&t>0?t:!e&&!n?0:lf(e??0,n??0,o,r??0)}var cf,yr,mo,ko=b(()=>{g();Fs();Fs();cf={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"},yr={input:0,cachedInput:0,output:0},mo={};});function dc(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"||!pf.includes(r))return null;let o=n.schedule_id;return typeof o=="string"&&o!==""?o:null}var pf,cc=b(()=>{g();pf=["cron","cron_manual"];});function js(t){return t instanceof Error?t:t===void 0?void 0:new Error(String(t))}function uc(t){return typeof t=="object"&&t!==null&&"code"in t?String(t.code):void 0}function yo(t){return Number.isSafeInteger(t)&&t>0}function kf(t){let e=t.trim();if(!e)return "";let n=/^(?:"([^"]+)"|'([^']+)')/.exec(e);return n?.[1]??n?.[2]??e.split(/\s+/,1)[0]??""}function yf(t,e,n){let r=n==="win32"?t.toLowerCase():t,o=n==="win32"?e.toLowerCase():e;if(!o.trim())return false;if(o==="agy"){let s=kf(t).split(/[\\/]/).pop()??"",i=n==="win32"?s.toLowerCase():s;return i==="agy"||n==="win32"&&(i==="agy.exe"||i==="agy.cmd")}return r.includes(o)}function Tf(t,e,n){return e.some(r=>yf(t,r,n))}function wf(t,e){try{let n=child_process.spawnSync(t,e,{encoding:"utf8",timeout:Gs,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:js(n)}}}function Ef(t,e){return new Promise(n=>{let r;try{r=child_process.spawn(t,e,{windowsHide:!0});}catch(u){n({status:null,stdout:"",stderr:"",error:js(u)});return}let o="",s="",i=false,c,d=setTimeout(()=>{try{r.kill();}catch{}c({status:null,stdout:o,stderr:s,error:new Error(`Command timed out after ${Gs}ms`)});},Gs);c=u=>{i||(i=true,clearTimeout(d),n(u));},r.stdout?.setEncoding("utf8"),r.stderr?.setEncoding("utf8"),r.stdout?.on("data",u=>{o+=String(u);}),r.stderr?.on("data",u=>{s+=String(u);}),r.once("error",u=>{c({status:null,stdout:o,stderr:s,error:u});}),r.once("close",u=>{c({status:u,stdout:o,stderr:s});});})}async function zs(t,e,n){return n.runCommandAsync?n.runCommandAsync(t,e):n.runCommand?n.runCommand(t,e):Ef(t,e)}function Rf(t){return new Promise(e=>{setTimeout(e,Math.max(0,t));})}function Sf(){return new Promise(t=>{setImmediate(t);})}function zt(t,e=process.kill){try{return e(t,0),"alive"}catch(n){return uc(n)==="ESRCH"?"not_found":uc(n)==="EPERM"?"alive":"unknown"}}function If(t,e){let n=zt(-t,e),r=zt(t,e);return n==="alive"||r==="alive"?"alive":n==="unknown"||r==="unknown"?"unknown":"not_found"}async function pc(t,e,n,r){let o=Math.max(0,n),s=Math.max(1,r.pollIntervalMs??hf),i=Date.now()+o,c,d=o===0,u=r.sleep?Promise.resolve().then(()=>r.sleep(o)).then(()=>{},()=>{}):new Promise(l=>{c=setTimeout(l,o);});u.then(()=>{d=true;});try{for(await Sf();;){let l=If(t,e);if(l==="not_found")return l;let p=i-Date.now();if(d||p<=0)return l;await Promise.race([u,Rf(Math.min(s,p))]);}}finally{c!==void 0&&clearTimeout(c);}}async function lc(t,e,n,r,o){let s=await pc(t,e,o.hardConfirmMs??mf,{...o,sleep:void 0});return s==="not_found"?n?{status:"not_found",pid:t,method:r}:{status:"terminated",pid:t,method:r}:s==="alive"?{status:"failed",pid:t,method:r,error:"Process is still running after termination attempt"}:{status:"failed",pid:t,method:r,error:"Unable to verify process termination"}}async function _c(t,e,n={}){if(!yo(t))return "unknown";let r=n.platform??process.platform,o=r==="win32"?"powershell.exe":"ps",s=r==="win32"?["-NoLogo","-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-Command",`$p = Get-CimInstance -ClassName Win32_Process -Filter 'ProcessId = ${t}' -ErrorAction Stop; if ($null -ne $p) { [Console]::Write([string]$p.CommandLine) }`]:["-p",String(t),"-o","command="],i;try{i=await zs(o,s,n);}catch{return "unknown"}if(i.error||i.status!==0)return "unknown";let c=i.stdout.trim();return c?Tf(c,e,r)?"owned":"not_owned":"not_found"}function vf(t){let e=Af.exec(t.trim());if(!e)return;let[,n="0",r="0",o="0",s="0"]=e;return ((Number(n)*24+Number(r))*60+Number(o))*60+Number(s)}function bf(t){let e=t.trim(),n=Of.exec(e);if(n){let[,o,s,i,c,d,u,l,p]=n;return Date.UTC(Number(o),Number(s)-1,Number(i),Number(c),Number(d),Number(u),Math.trunc(Number(l)/1e3))-Number(p)*6e4}let r=Date.parse(e);return Number.isFinite(r)?r:void 0}function fc(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 gc(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=bf(r);return i===void 0?{status:"unknown"}:{status:"found",startedAtMs:i,groupId:null}}let o=Nf.exec(r),s=o?vf(o[2]):void 0;return !o||s===void 0?{status:"unknown"}:o[3].startsWith("Z")?{status:"unknown"}:{status:"found",startedAtMs:n-s*1e3,groupId:Number(o[1])}}function hc(t,e={}){if(!yo(t))return {status:"unknown"};let n=e.platform??process.platform,{command:r,args:o}=fc(t,n),s=e.runCommand??wf,i;try{i=s(r,o);}catch{return {status:"unknown"}}return gc(i,n,Date.now())}async function mc(t,e={}){if(!yo(t))return {status:"unknown"};let n=e.platform??process.platform,{command:r,args:o}=fc(t,n),s;try{s=await zs(r,o,e);}catch{return {status:"unknown"}}return gc(s,n,Date.now())}async function Jt(t,e={}){let n=e.platform??process.platform,r=n==="win32"?"taskkill":"process-group",o=_=>({status:"failed",pid:t,method:r,error:_});if(!yo(t))return o("Invalid process ID");let s=e.kill??process.kill,i=zt(t,s);if(i==="not_found")return {status:"not_found",pid:t,method:r};if(i!=="alive")return o("Unable to determine whether the process is alive");if(n==="win32"){let _;try{_=await zs("taskkill",["/PID",String(t),"/T","/F"],e);}catch(m){_={status:null,stdout:"",stderr:"",error:js(m)};}let h=zt(t,s);return h==="not_found"?_.status===0&&!_.error?{status:"terminated",pid:t,method:r}:{status:"not_found",pid:t,method:r}:o(h==="alive"?"Process is still running after termination attempt":"Unable to verify process termination")}let c,d=e.signal??"SIGKILL";try{s(-t,d);}catch(_){c=_;}if(d==="SIGKILL")return lc(t,s,c,r,e);if(await pc(t,s,e.graceMs??gf,e)==="not_found")return c?{status:"not_found",pid:t,method:r}:{status:"terminated",pid:t,method:r};let l;try{s(-t,"SIGKILL");}catch(_){l=_;}let p=await lc(t,s,l,r,e);return p.status==="terminated"?p:p.status==="not_found"?c?p:{status:"terminated",pid:t,method:r}:o(p.error??"Process termination failed")}var Gs,Kt,gf,hf,mf,To,Af,Nf,Of,wo=b(()=>{g();Gs=3e3,Kt="SIGINT",gf=2e3,hf=25,mf=100;To=3e3,Af=/^(?:(\d+)-)?(?:(\d+):)?(\d{1,2}):(\d{2})$/,Nf=/^\s*(\d+)\s+(\S+)\s+(\S+)\s*$/,Of=/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})\.(\d{6})([+-]\d{3})$/;});function Ec(t,e){let n=e===void 0?"":` at index ${e}`;if(!t||typeof t!="object")throw new f("VALIDATION",`Task log entry${n} must be an object`);if(typeof t.timestamp!="string"||typeof t.level!="string"||typeof t.message!="string")throw new f("VALIDATION",`Task log entry${n} must contain string timestamp, level, and message fields`);return {timestamp:t.timestamp,level:t.level,message:t.message}}function Tc(t,e){if(e===null||e.trim()==="")return [];let n;try{n=JSON.parse(e);}catch(r){throw new f("DB_ERROR",`Malformed legacy task logs: ${t}`,r)}if(!Array.isArray(n))throw new f("DB_ERROR",`Malformed legacy task logs: ${t} (expected an array)`);try{return n.map((r,o)=>Ec(r,o))}catch(r){throw r instanceof f?new f("DB_ERROR",`Malformed legacy task logs: ${t}`,r):r}}function Rc(t){if(t.log_storage!=="blob"&&t.log_storage!=="events")throw new f("DB_ERROR",`Invalid task log storage for task: ${t.id}`);if(!Number.isInteger(t.last_log_seq)||t.last_log_seq<0)throw new f("DB_ERROR",`Invalid task log sequence for task: ${t.id}`);if(!Number.isInteger(t.log_revision)||t.log_revision<0)throw new f("DB_ERROR",`Invalid task log revision for task: ${t.id}`);return t.log_storage}function wc(t){return {taskId:t.id,source:Rc(t),revision:t.log_revision,lastSeq:t.last_log_seq}}function Mf(t){if(!Number.isInteger(t)||t<0)throw new f("VALIDATION","Task log tail limit must be a non-negative integer")}var Eo,Sc=b(()=>{g();Ot();qt();Bt();Nt();Gt();Eo=class extends me{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=Ne.join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?on(this.dbPath):super.resolveDbPath()}openHandle(e){let n=this.resolveDbPath();if(e){let o=Ne.dirname(n);Iu.existsSync(o)||Iu.mkdirSync(o,{recursive:true});}else if(!Iu.existsSync(n))throw new f("NOT_FOUND","Database not found");let r=H(n);if(e)try{Pe(r.db,n);}catch(o){throw r.close(),o}return r}findStateRow(e,n){return e.db.select({id:a.id,log_storage:a.log_storage,last_log_seq:a.last_log_seq,log_revision:a.log_revision,logs:a.logs}).from(a).where(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 f("NOT_FOUND",`Task not found: ${n}`);return r}appendLog(e,n){return this.appendLogs(e,[n])}appendLogs(e,n){let r=n.map((s,i)=>Ec(s,i));if(r.length===0){let s=this.getLogState(e);if(!s)throw new f("NOT_FOUND",`Task not found: ${e}`);return s}let o=this.openHandle(true);try{return o.db.transaction(i=>{let c=this.requireStateRowInTransaction(i,e),d=Rc(c);if(d==="blob"){let _=Tc(e,c.logs);if(i.update(a).set({logs:JSON.stringify([..._,...r]),log_revision:drizzleOrm.sql`${a.log_revision} + 1`}).where(drizzleOrm.eq(a.id,e)).run().changes!==1)throw new f("NOT_FOUND",`Task not found: ${e}`);return {taskId:e,source:d,revision:c.log_revision+1,lastSeq:c.last_log_seq}}let u=c.last_log_seq+1,l=c.last_log_seq+r.length;if(i.insert(ht).values(r.map((_,h)=>({task_id:e,seq:u+h,timestamp:_.timestamp,level:_.level,message:_.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 f("NOT_FOUND",`Task not found: ${e}`);return {taskId:e,source:d,revision:c.log_revision+1,lastSeq:l}},{behavior:"immediate"})}catch(s){throw s instanceof f?s:new f("DB_ERROR","Failed to append task log",s)}finally{o.close();}}getLogState(e){if(!this.dbExists())return;let n=this.openHandle(false);try{let r=this.findStateRow(n,e);return r?wc(r):void 0}catch(r){throw r instanceof f?r:new f("DB_ERROR","Failed to read task log state",r)}finally{n.close();}}readLogs(e){return this.readLogsInternal(e)}readLogsTail(e,n){return 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(o=>{let s=this.findStateRowInTransaction(o,e);if(!s)return;let i=wc(s);if(i.source==="blob"){let l=Tc(e,s.logs).map((p,_)=>({...p,seq:_+1}));return {...i,entries:n===void 0?l:l.slice(Math.max(0,l.length-n))}}let c=o.select({seq:ht.seq,timestamp:ht.timestamp,level:ht.level,message:ht.message}).from(ht).where(drizzleOrm.eq(ht.task_id,e)).orderBy(n===void 0?drizzleOrm.asc(ht.seq):drizzleOrm.desc(ht.seq)),u=(n===void 0?c.all():c.limit(n).all()).map(({seq:l,timestamp:p,level:_,message:h})=>({seq:l,timestamp:p,level:_,message:h}));return n!==void 0&&u.reverse(),{...i,entries:u}},{behavior:"deferred"})}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to read task logs",o)}finally{r.close();}}};});var Bf,Ro,Ac=b(()=>{g();Ot();qt();Bt();Nt();Gt();Bf=50,Ro=class extends me{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=H(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(We).values({workspace_id:e.workspaceId,actor_id:e.actorId,agent_id:e.agentId,last_accepted_at:r}).onConflictDoUpdate({target:[We.workspace_id,We.actor_id,We.agent_id],set:{last_accepted_at:drizzleOrm.sql`MAX(${We.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:We.agent_id,lastAcceptedAt:We.last_accepted_at}).from(We).where(drizzleOrm.and(drizzleOrm.eq(We.workspace_id,e),drizzleOrm.eq(We.actor_id,n))).orderBy(drizzleOrm.desc(We.last_accepted_at),drizzleOrm.asc(We.agent_id)).limit(Bf).all()}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to find recent agent sends",o)}finally{r?.close();}}};});var Nc=b(()=>{g();});var Ff,W,Vt=b(()=>{g();Ff=new Set(["ACCOUNT_SETTING_REQUIRED","MODEL_RETIRED","SUBSCRIPTION_REQUIRED"]),W=class extends Error{constructor(n,r,o){super(n);this.providerStr=r;this.name="ProviderError",this.code=o?.code??"UNKNOWN",this.kind=Ff.has(this.code)?"config":o?.kind??(this.code==="UNKNOWN"?"transient":void 0),this.retryAfterMs=o?.retryAfterMs,this.settingReason=o?.settingReason,this.replacementModel=o?.replacementModel,this.providerReason=o?.providerReason;}providerStr;code;kind;retryAfterMs;settingReason;replacementModel;providerReason;stdout};});var gn,Ks=b(()=>{g();Vt();gn=class extends W{name="RateLimitError";constructor(e,n="cli/claude"){super(e,n,{code:"QUOTA_EXHAUSTED",kind:"transient"});}};});function So(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 ${Ce}]`),e=Gf(e),e=e.replace(/\b(?:Bearer|Basic)\s+[A-Za-z0-9._~+\-/]+=*/gi,`${Ce}`),e=e.replace(/\bsk-[A-Za-z0-9][A-Za-z0-9_-]*/g,Ce),e=e.replace(/\bghp_[A-Za-z0-9][A-Za-z0-9_-]*/g,Ce),e=e.replace(/\bxoxb-[A-Za-z0-9-]+/g,Ce),e=e.replace(/\bxoxp-[A-Za-z0-9-]+/g,Ce),e=e.replace(/\bAKIA[0-9A-Z]{12,}\b/g,Ce),e=e.replace(/\bgithub_pat_[A-Za-z0-9_]+/g,Ce),e=e.replace(/\bgho_[A-Za-z0-9_]+/g,Ce),e=e.replace(/\bAIza[A-Za-z0-9_-]{20,}\b/g,Ce),e=e.replace(/\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/g,Ce),e=e.replace(/\b(?:authorization|api[_ -]?key|access[_ -]?token|auth[_ -]?token|refresh[_ -]?token|token|secret|password)\s*([:=])\s*["']?[^\s,;&"']+/gi,(n,r)=>`${Ce}${r}${Ce}`),e=e.replace(/([?&](?:api[_-]?key|access[_-]?token|token)=)[^&\s]+/gi,`$1${Ce}`),e=e.replace(/(?:\/(?:Users|home|private|var\/folders|tmp|workspace|workspaces|Volumes|opt|etc|srv|Applications)\/[^\s"'`),;]+)/g,Oc),e=e.replace(/\b[A-Z]:\\(?:Users|home|Windows|Program Files|workspace|workspaces)\\[^\s"'`),;]*/gi,Oc),e=e.replace(/[\r\n]{3,}/g,`
46
46
 
47
- `).trim(),cf(e,1024)||void 0}function cf(t,e){let n=new TextEncoder;if(n.encode(t).byteLength<=e)return t;let r="",o=0;for(let s of t){let i=n.encode(s).byteLength;if(o+i>e)break;r+=s,o+=i;}return r}function uf(t){let e=/\b(?:request|response|http)?\s*body\s*[:=]\s*/gim,n="",r=0,o;for(;(o=e.exec(t))!==null;){if(o.index<r)continue;let s=o.index+o[0].length,i=lf(t,s),c=i>=0?i:t.indexOf(`
47
+ `).trim(),Wf(e,1024)||void 0}function Wf(t,e){let n=new TextEncoder;if(n.encode(t).byteLength<=e)return t;let r="",o=0;for(let s of t){let i=n.encode(s).byteLength;if(o+i>e)break;r+=s,o+=i;}return r}function Gf(t){let e=/\b(?:request|response|http)?\s*body\s*[:=]\s*/gim,n="",r=0,o;for(;(o=e.exec(t))!==null;){if(o.index<r)continue;let s=o.index+o[0].length,i=jf(t,s),c=i>=0?i:t.indexOf(`
48
48
  `,s)>=0?t.indexOf(`
49
- `,s):t.length;n+=t.slice(r,o.index),n+=`[HTTP BODY ${Ne}]`,r=c;}return n+t.slice(r)}function lf(t,e){let n=t[e];if(n==='"'||n==="'")return pf(t,e,n);if(n!=="{"&&n!=="[")return -1;let r=[],o,s=false;for(let i=e;i<t.length;i+=1){let c=t[i];if(o){s?s=false:c==="\\"?s=true:c===o&&(o=void 0);continue}if(c==='"'||c==="'"){o=c;continue}if(c==="{"||c==="["){r.push(c);continue}if(c!=="}"&&c!=="]")continue;let d=r.pop();if(c==="}"&&d!=="{"||c==="]"&&d!=="[")return -1;if(r.length===0)return i+1}return -1}function pf(t,e,n){let r=false;for(let o=e+1;o<t.length;o+=1){let s=t[o];if(r)r=false;else if(s==="\\")r=true;else if(s===n)return o+1}return -1}var Ne,sc,bs=C(()=>{g();Ne="[REDACTED]",sc="[PATH]";});function Ps(t){if(!_o(t)||t.type!=="item.started"||!ac(t)||!ic(t))return false;let e=t.item;return !_o(e)||!ac(e)||!ic(e)||!Ds(e.id)?false:e.type==="web_search"?e.query===""&&_o(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=>_o(n)&&Ds(n.path)&&Ds(n.kind)):false}function _o(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function dc(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function Ds(t){return typeof t=="string"&&t.trim().length>0}function ic(t){return !dc(t,"status")||t.status==="in_progress"}function ac(t){for(let e of ["error","errors","isError","is_error"])if(dc(t,e))return false;return true}var Ls=C(()=>{g();});function En(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Rn(t){return typeof t=="string"&&t.trim().length>0}function Ms(t){return typeof t=="string"?t.trim().length>0:En(t)?Rn(t.code)||Rn(t.message)||Rn(t.error)||Rn(t.reason):false}function ar(t){let e;try{e=JSON.parse(t);}catch{return}if(En(e))switch(e.event){case "init":return En(e.init)?{kind:"init",envelope:e,init:e.init}:void 0;case "step_update":{if(!En(e.step_update))return;let n=e.step_update;return !Rn(n.conversation_id)||!Number.isSafeInteger(n.step_index)||n.state!=="ACTIVE"&&n.state!=="DONE"&&!(n.state==="ERROR"&&n.step_type==="tool")||!Rn(n.step_type)?void 0:{kind:"step_update",envelope:e,step:n}}case "result":return En(e.result)?{kind:"result",envelope:e,result:e.result}:void 0;case "AGY_ERROR":{let n=Ms(e)?e:e.error;return Ms(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"||Ms(e.error)||En(e.usage))?{kind:"legacy_result",envelope:e,result:e}:void 0}}function cc(t){return ar(t)!==void 0}function dr(t){let e=[];for(let n of t.split(/\r?\n/)){if(!n.trim())continue;let r=ar(n);r&&e.push(r);}return e}var $s=C(()=>{g();});function _f(t,e){let n=t.trimStart();if(!n.startsWith("{"))return false;let r;try{r=JSON.parse(n);}catch{return false}let o=typeof r.type=="string"?r.type:"",s=e?wf[e]:void 0;return s?s(r,o):o?Object.values(lc).some(i=>i(r,o)):false}function mt(t,e){let n=t.split(`
50
- `).filter(r=>r.trim());return n.length===0?false:n.every(r=>_f(r,e))}function xe(t){return typeof t=="object"&&t!==null}function uc(t,e){if(e==="assistant"||e==="user"){let n=t.message;return xe(n)&&Array.isArray(n.content)}return e==="system"?typeof t.subtype=="string"||typeof t.session_id=="string":e==="result"?typeof t.result=="string"||xe(t.usage)||typeof t.total_cost_usd=="number"||typeof t.is_error=="boolean":e==="rate_limit_event"?xe(t.rate_limit_info):e==="tool_progress"?t.heartbeat===true&&typeof t.tool_use_id=="string":false}function ff(t,e){return typeof t.session_id=="string"||typeof t.uuid=="string"?true:uc(t,e)}function gf(t,e){if(e==="error")return typeof t.message=="string"||typeof t.errorMessage=="string"||typeof t.error=="string"||xe(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 xe(n)&&typeof n.type=="string"}return false}function hf(t,e){if(e==="step_start"||e==="step_finish")return typeof t.stepID=="string"||typeof t.sessionID=="string"||xe(t.part);if(e==="text"||e==="tool_use")return xe(t.part);if(e==="error"){let n=t.error;return xe(n)&&typeof n.type=="string"&&typeof n.message=="string"}return e==="result"?typeof t.result=="string":false}function mf(t,e){return !!(typeof t.stepID=="string"||typeof t.sessionID=="string"||xe(t.part)||e==="result"&&typeof t.result=="string")}function kf(t,e){return e.startsWith("assistant.")||e.startsWith("tool.execution")||e==="user.message"?xe(t.data):e==="result"?typeof t.result=="string":false}function yf(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 Tf(t,e){return e==="available_commands"?xe(t.tools)||xe(t.commands):e==="usage"?xe(t.usage):e==="end"?typeof t.sessionId=="string"||typeof t.stopReason=="string"||xe(t.usage):e==="tool_call_update"?typeof t.toolCallId=="string"||typeof t.status=="string":false}var lc,wf,Sn=C(()=>{g();Ls();$s();lc={claude:uc,codex:gf,opencode:hf,copilot:kf,gemini:yf},wf={...lc,claude:ff,opencode:mf,grok:Tf,antigravity:t=>cc(JSON.stringify(t))};});function kt(t){return /crewx\s+(q|query|x|execute)\s/.test(t)}function yt(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 In=C(()=>{g();});function Sf(t){let e=If(t),n=e.map((s,i)=>({line:s,index:i})).filter(({line:s})=>Nf(s.value)),r=Af(e);return {result:n.length===1&&n[0].index===r?Of(n[0].line.value):null,resultPreview:xf(e,n),hasReservedLine:n.length>0}}function et(t,e){let n=Sf(t);return {resultPreview:n.resultPreview,isError:e||n.result?.isError===true,...n.hasReservedLine?{delegationResult:n.result}:{}}}function If(t){let e=[],n=0;for(let r=0;r<t.length;r++){let o=t[r];if(o!==`
49
+ `,s):t.length;n+=t.slice(r,o.index),n+=`[HTTP BODY ${Ce}]`,r=c;}return n+t.slice(r)}function jf(t,e){let n=t[e];if(n==='"'||n==="'")return zf(t,e,n);if(n!=="{"&&n!=="[")return -1;let r=[],o,s=false;for(let i=e;i<t.length;i+=1){let c=t[i];if(o){s?s=false:c==="\\"?s=true:c===o&&(o=void 0);continue}if(c==='"'||c==="'"){o=c;continue}if(c==="{"||c==="["){r.push(c);continue}if(c!=="}"&&c!=="]")continue;let d=r.pop();if(c==="}"&&d!=="{"||c==="]"&&d!=="[")return -1;if(r.length===0)return i+1}return -1}function zf(t,e,n){let r=false;for(let o=e+1;o<t.length;o+=1){let s=t[o];if(r)r=false;else if(s==="\\")r=true;else if(s===n)return o+1}return -1}var Ce,Oc,Js=b(()=>{g();Ce="[REDACTED]",Oc="[PATH]";});function Xs(t){if(!Io(t)||t.type!=="item.started"||!bc(t)||!vc(t))return false;let e=t.item;return !Io(e)||!bc(e)||!vc(e)||!Vs(e.id)?false:e.type==="web_search"?e.query===""&&Io(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=>Io(n)&&Vs(n.path)&&Vs(n.kind)):false}function Io(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Cc(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function Vs(t){return typeof t=="string"&&t.trim().length>0}function vc(t){return !Cc(t,"status")||t.status==="in_progress"}function bc(t){for(let e of ["error","errors","isError","is_error"])if(Cc(t,e))return false;return true}var Ys=b(()=>{g();});function Ln(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Mn(t){return typeof t=="string"&&t.trim().length>0}function Qs(t){return typeof t=="string"?t.trim().length>0:Ln(t)?Mn(t.code)||Mn(t.message)||Mn(t.error)||Mn(t.reason):false}function wr(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 !Mn(n.conversation_id)||!Number.isSafeInteger(n.step_index)||n.state!=="ACTIVE"&&n.state!=="DONE"&&!(n.state==="ERROR"&&n.step_type==="tool")||!Mn(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=Qs(e)?e:e.error;return Qs(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"||Qs(e.error)||Ln(e.usage))?{kind:"legacy_result",envelope:e,result:e}:void 0}}function xc(t){return wr(t)!==void 0}function Er(t){let e=[];for(let n of t.split(/\r?\n/)){if(!n.trim())continue;let r=wr(n);r&&e.push(r);}return e}var Zs=b(()=>{g();});function Kf(t,e){let n=t.trimStart();if(!n.startsWith("{"))return false;let r;try{r=JSON.parse(n);}catch{return false}let o=typeof r.type=="string"?r.type:"",s=e?tg[e]:void 0;return s?s(r,o):o?Object.values(Pc).some(i=>i(r,o)):false}function Et(t,e){let n=t.split(`
50
+ `).filter(r=>r.trim());return n.length===0?false:n.every(r=>Kf(r,e))}function Me(t){return typeof t=="object"&&t!==null}function Dc(t,e){if(e==="assistant"||e==="user"){let n=t.message;return Me(n)&&Array.isArray(n.content)}return e==="system"?typeof t.subtype=="string"||typeof t.session_id=="string":e==="result"?typeof t.result=="string"||Me(t.usage)||typeof t.total_cost_usd=="number"||typeof t.is_error=="boolean":e==="rate_limit_event"?Me(t.rate_limit_info):e==="tool_progress"?t.heartbeat===true&&typeof t.tool_use_id=="string":false}function Jf(t,e){return typeof t.session_id=="string"||typeof t.uuid=="string"?true:Dc(t,e)}function Vf(t,e){if(e==="error")return typeof t.message=="string"||typeof t.errorMessage=="string"||typeof t.error=="string"||Me(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 Me(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"||Me(t.part);if(e==="text"||e==="tool_use")return Me(t.part);if(e==="error"){let n=t.error;return Me(n)&&typeof n.type=="string"&&typeof n.message=="string"}return e==="result"?typeof t.result=="string":false}function Yf(t,e){return !!(typeof t.stepID=="string"||typeof t.sessionID=="string"||Me(t.part)||e==="result"&&typeof t.result=="string")}function Qf(t,e){return e.startsWith("assistant.")||e.startsWith("tool.execution")||e==="user.message"?Me(t.data):e==="result"?typeof t.result=="string":false}function Zf(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 eg(t,e){return e==="available_commands"?Me(t.tools)||Me(t.commands):e==="usage"?Me(t.usage):e==="end"?typeof t.sessionId=="string"||typeof t.stopReason=="string"||Me(t.usage):e==="tool_call_update"?typeof t.toolCallId=="string"||typeof t.status=="string":false}var Pc,tg,$n=b(()=>{g();Ys();Zs();Pc={claude:Dc,codex:Vf,opencode:Xf,copilot:Qf,gemini:Zf},tg={...Pc,claude:Jf,opencode:Yf,grok:eg,antigravity:t=>xc(JSON.stringify(t))};});function Rt(t){return /crewx\s+(q|query|x|execute)\s/.test(t)}function St(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 Hn=b(()=>{g();});function og(t){let e=sg(t),n=e.map((s,i)=>({line:s,index:i})).filter(({line:s})=>ag(s.value)),r=ig(e);return {result:n.length===1&&n[0].index===r?dg(n[0].line.value):null,resultPreview:lg(e,n),hasReservedLine:n.length>0}}function ot(t,e){let n=og(t);return {resultPreview:n.resultPreview,isError:e||n.result?.isError===true,...n.hasReservedLine?{delegationResult:n.result}:{}}}function sg(t){let e=[],n=0;for(let r=0;r<t.length;r++){let o=t[r];if(o!==`
51
51
  `&&o!=="\r")continue;let s=o==="\r"&&t[r+1]===`
52
52
  `?`\r
53
- `:o;e.push({value:t.slice(n,r),separator:s}),r+=s.length-1,n=r+1;}return e.push({value:t.slice(n),separator:""}),e}function Af(t){for(let e=t.length-1;e>=0;e--)if(t[e].value.trim())return e;return -1}function Nf(t){return t.trimStart().startsWith(Ef)}function Of(t){let e=t.trim();if(!e.startsWith(pc)||!e.endsWith("]]"))return null;let n=e.slice(pc.length,-2);if(!n)return null;try{return vf(JSON.parse(n))}catch{return null}}function vf(t){return Cf(t)?Object.prototype.hasOwnProperty.call(t,"taskId")?{schema:1,taskId:t.taskId,agentId:t.agentId,isError:t.isError}:{schema:1,isError:true}:null}function Cf(t){if(!bf(t)||Object.keys(t).some(r=>!Rf.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?_c(t.taskId)&&_c(t.agentId):t.isError===true}function xf(t,e){if(e.length===0)return t.map(r=>r.value+r.separator).join("");let n=new Set(e.map(({index:r})=>r));return t.map((r,o)=>n.has(o)?"":r.value+r.separator).join("")}function _c(t){return typeof t=="string"&&t.trim().length>0}function bf(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var pc,Ef,Rf,An=C(()=>{g();pc="[[crewx:delegation-result ",Ef="[[crewx:delegation-result",Rf=new Set(["schema","taskId","agentId","isError"]);});function tt(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 Nn=C(()=>{g();});var fc,fo,Hs,go=C(()=>{g();fc=["none","minimal","low","medium","high","xhigh","max","ultra"],fo={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"]},Hs={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(Hs).map(([t,e])=>[t,e.models]));});function Us(t){return Pf[t]??t}function Mf(t){return Lf.get(t)??t}function qs(t){if(!t)return {};let e=Hf.get(t);return e?{...e}:{model:t}}function Fs(t,e){return t==="antigravity"||t==="cli/antigravity"?qs(e):e===void 0?{}:{model:Mf(e)}}var Df,Pf,Lf,$f,Hf,cr=C(()=>{g();Df=[{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]"}],Pf={"accept-edits":"acceptEdits",yolo:"bypassPermissions","agent-full-access":"bypassPermissions"};Lf=new Map(Df.map(({baseModelId:t,catalogModelId:e})=>[t,e]));$f=[{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"}],Hf=new Map($f.map(({legacyId:t,model:e,effort:n})=>[t,n===void 0?{model:e}:{model:e,effort:n}]));});function qf(){return {models:[],modes:[],effort:[],modelOverrides:{},providerOptions:[]}}function It(t){return ur(t).models}function ur(t){let e=Uf[t],n=Hs[t];return e?e.suggestedModels!==void 0||n?.suggestedModels===void 0?e:{...e,suggestedModels:n.suggestedModels}:n??qf()}function On(t,e){let n=ur(t);if(e){if(Object.prototype.hasOwnProperty.call(n.modelOverrides,e))return n.modelOverrides[e]?.effort??n.effort;let r=Fs(t,e);return r.model===void 0?n.effort:n.modelOverrides[r.model]?.effort??n.effort}return n.effort}function Bs(t){return ur(t).modelOverrides}function gc(){return It("claude")}function hc(){return It("codex")}function mc(){return It("copilot")}function kc(){return It("antigravity")}var Uf,Ht=C(()=>{g();go();so();cr();Uf={};});function yc(t){return Bf[t]??t}var Bf,Tc=C(()=>{g();Ht();cr();Bf={auto:"default"};});function ho(t,e){return (fo[t]??[]).includes(e)}function Ut(t){if(!t)return {};let e=t.match(/^(.+?)\[([^\]]+)\]$/);if(e){let n=e[2].toLowerCase();return Wf.has(n)?{model:e[1],effort:n}:{model:t}}return {model:t}}function wc(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 Ec(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 Rc(t){return !t||!ho("codex",t)?[]:["-c",`model_reasoning_effort=${t}`]}function Sc(t){if(!t)return [];let e=new Set(["acceptEdits","bypassPermissions","default","delegate","dontAsk","plan"]),n=yc(t);return e.has(n)?["--permission-mode",n]:[]}function Ic(t){return t?ho("claude",t)?["--effort",t]:[]:[]}function Ac(t){return t==="default"?[]:t&&Gf.has(t)?["--permission-mode",t]:[]}function Nc(t){return t===true?["--always-approve"]:[]}function Oc(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 vc(t){return t?ho("grok",t)?["--effort",t]:[]:[]}function Cc(t){if(!t)return [];switch(Us(t)){case "default":return [];case "plan":return ["--mode","plan"];case "acceptEdits":return ["--mode","accept-edits"];case "bypassPermissions":return ["--dangerously-skip-permissions"];default:return []}}function xc(t){return t?ho("antigravity",t)?["--effort",t]:[]:[]}var Wf,Gf,lr=C(()=>{g();Tc();cr();go();Wf=new Set(fc);Gf=new Set(["default","acceptEdits","auto","dontAsk","bypassPermissions","plan"]);});function jf(t){if(t.type!=="usage"||!("input_tokens"in t))return null;let e=Number(t.input_tokens??0),n=Number(t.output_tokens??0),o="cache_read_input_tokens"in t?Number(t.cache_read_input_tokens):void 0,s="cached_input_tokens"in t?Number(t.cached_input_tokens):void 0,i=o!==void 0?o:s??0;return {inputTokens:o!==void 0?e+o:e,outputTokens:n,cachedInputTokens:i}}function Kf(t){let e=t.usage;if(!e||typeof e!="object"||Array.isArray(e))return null;let n=e;if(!("input_tokens"in n))return null;let r=Number(n.input_tokens??0),o=Number(n.output_tokens??0),i="cache_read_input_tokens"in n?Number(n.cache_read_input_tokens):void 0,c="cached_input_tokens"in n?Number(n.cached_input_tokens):void 0,d=i!==void 0?i:c??0;return {inputTokens:i!==void 0?r+i:r,outputTokens:o,cachedInputTokens:d}}function zf(t){if(t.type!=="step_finish")return null;let n=t.part?.tokens;if(!n)return null;let r=Number(n.input??0),o=Number(n.output??0)+Number(n.reasoning??0),s=n.cache,i=s?Number(s.read??0):0;return {inputTokens:r+i,outputTokens:o,cachedInputTokens:i}}function bc(t){let e=new Map,n;for(let s of t.split(`
54
- `))if(s.trim())try{let i=JSON.parse(s);if(i.type!=="assistant")continue;let c=i.message,d=c?.id,u=c?.usage;if(typeof d!="string"||!u)continue;let l=Number(u.input_tokens??0),p=Number(u.cache_read_input_tokens??0);e.set(d,{inputTokens:l+p,cachedInputTokens:p});let _=c?.model;typeof _=="string"&&_&&(n=_);}catch{}if(e.size===0)return;let r=0,o=0;for(let s of e.values())r+=s.inputTokens,o+=s.cachedInputTokens;return {inputTokens:r,cachedInputTokens:o,model:n}}function vn(t){if(!t||!t.trim())return;let e=null,n=null;for(let r of t.split(`
55
- `))if(r.trim())try{let o=JSON.parse(r),s=zf(o);if(s){n||(n={inputTokens:0,outputTokens:0,cachedInputTokens:0}),n.inputTokens+=s.inputTokens,n.outputTokens+=s.outputTokens,n.cachedInputTokens+=s.cachedInputTokens;continue}let i=jf(o)??Kf(o);i&&(e=i);}catch{}return n||(e??void 0)}var pr=C(()=>{g();});function nt(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 sn=C(()=>{g();});var mo,Dc=C(()=>{g();mo=Object.freeze({CLAUDE_CODE_DISABLE_AUTO_MEMORY:"1"});});function Lc(t){return t==="all"?[...Pc,...Jf]:Pc}function Mc(t){return Lc(t).map(e=>`Bash(${e} *)`)}function $c(t){return Lc(t).map(e=>`command(${e})`)}var Pc,Jf,Ws=C(()=>{g();Pc=["crewx memory","crewx search","crewx doc","crewx notify"],Jf=["crewx q","crewx query","crewx x","crewx execute","crewx cron","crewx wbs","crewx wi","crewx workflow","crewx app","crewx skill"];});function Hc(t){let e=t.split(`
56
- `).filter(o=>o.trim()),n=[],r=null;for(let o of e)try{let s=JSON.parse(o);if(s.type==="assistant"&&Array.isArray(s.message?.content))for(let i of s.message.content)i.type==="text"&&typeof i.text=="string"&&i.text.trim()&&n.push(i.text.trim());s.type==="result"&&typeof s.result=="string"&&(r=s.result);}catch{}if(n.length>0)return n[n.length-1];if(r)return r}function Uc(t){let e=t.split(`
57
- `).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 Cn(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0}function Gc(t){let e=Cn(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=eg(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(tg(n))return `Claude rate limit: ${n}`}}function Yf(t){for(let e of t.split(`
58
- `)){let n=e.trim();if(n){if(n.startsWith("Not logged in"))return n;try{let r=Cn(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 Qf(t){let e=Cn(t);if(e?.type!=="rate_limit_event")return;let n=Cn(Cn(e.rate_limit_info)?.unifiedWindows);if(!n)return;let r=qc(n.five_hour),o=qc(n.seven_day);if(!(!r&&!o))return {...r?{five_hour:r}:{},...o?{seven_day:o}:{}}}function qc(t){let e=Cn(t);if(!(typeof e?.utilization!="number"||typeof e.resetsAt!="number"))return {utilization:e.utilization,resetsAt:e.resetsAt}}function Fc(t){if(t?.is_error===true)return po(t.result)}function Zf(t){let e=Gc(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",o=typeof t.terminal_reason=="string"?t.terminal_reason:"unknown";return `Claude ended without an answer (subtype=${r}, terminal_reason=${o})`}function eg(t){let n=t.message?.content;return Array.isArray(n)?n.map(r=>typeof r.text=="string"?r.text.trim():"").filter(Boolean).join(`
53
+ `:o;e.push({value:t.slice(n,r),separator:s}),r+=s.length-1,n=r+1;}return e.push({value:t.slice(n),separator:""}),e}function ig(t){for(let e=t.length-1;e>=0;e--)if(t[e].value.trim())return e;return -1}function ag(t){return t.trimStart().startsWith(ng)}function dg(t){let e=t.trim();if(!e.startsWith(Lc)||!e.endsWith("]]"))return null;let n=e.slice(Lc.length,-2);if(!n)return null;try{return cg(JSON.parse(n))}catch{return null}}function cg(t){return ug(t)?Object.prototype.hasOwnProperty.call(t,"taskId")?{schema:1,taskId:t.taskId,agentId:t.agentId,isError:t.isError}:{schema:1,isError:true}:null}function ug(t){if(!pg(t)||Object.keys(t).some(r=>!rg.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?Mc(t.taskId)&&Mc(t.agentId):t.isError===true}function lg(t,e){if(e.length===0)return t.map(r=>r.value+r.separator).join("");let n=new Set(e.map(({index:r})=>r));return t.map((r,o)=>n.has(o)?"":r.value+r.separator).join("")}function Mc(t){return typeof t=="string"&&t.trim().length>0}function pg(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var Lc,ng,rg,Un=b(()=>{g();Lc="[[crewx:delegation-result ",ng="[[crewx:delegation-result",rg=new Set(["schema","taskId","agentId","isError"]);});function st(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 qn=b(()=>{g();});var $c,Ao,ei,No=b(()=>{g();$c=["none","minimal","low","medium","high","xhigh","max","ultra"],Ao={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"]},ei={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(ei).map(([t,e])=>[t,e.models]));});function ti(t){return fg[t]??t}function hg(t){return gg.get(t)??t}function ni(t){if(!t)return {};let e=kg.get(t);return e?{...e}:{model:t}}function ri(t,e){return t==="antigravity"||t==="cli/antigravity"?ni(e):e===void 0?{}:{model:hg(e)}}var _g,fg,gg,mg,kg,Rr=b(()=>{g();_g=[{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]"}],fg={"accept-edits":"acceptEdits",yolo:"bypassPermissions","agent-full-access":"bypassPermissions"};gg=new Map(_g.map(({baseModelId:t,catalogModelId:e})=>[t,e]));mg=[{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"}],kg=new Map(mg.map(({legacyId:t,model:e,effort:n})=>[t,n===void 0?{model:e}:{model:e,effort:n}]));});function Tg(){return {models:[],modes:[],effort:[],modelOverrides:{},providerOptions:[]}}function Dt(t){return Sr(t).models}function Sr(t){let e=yg[t],n=ei[t];return e?e.suggestedModels!==void 0||n?.suggestedModels===void 0?e:{...e,suggestedModels:n.suggestedModels}:n??Tg()}function Bn(t,e){let n=Sr(t);if(e){if(Object.prototype.hasOwnProperty.call(n.modelOverrides,e))return n.modelOverrides[e]?.effort??n.effort;let r=ri(t,e);return r.model===void 0?n.effort:n.modelOverrides[r.model]?.effort??n.effort}return n.effort}function oi(t){return Sr(t).modelOverrides}function Hc(){return Dt("claude")}function Uc(){return Dt("codex")}function qc(){return Dt("copilot")}function Bc(){return Dt("antigravity")}var yg,Xt=b(()=>{g();No();ko();Rr();yg={};});function Fc(t){return Eg[t]??t}var Eg,Wc=b(()=>{g();Xt();Rr();Eg={auto:"default"};});function Oo(t,e){return (Ao[t]??[]).includes(e)}function Yt(t){if(!t)return {};let e=t.match(/^(.+?)\[([^\]]+)\]$/);if(e){let n=e[2].toLowerCase();return Rg.has(n)?{model:e[1],effort:n}:{model:t}}return {model:t}}function Gc(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 jc(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 zc(t){return !t||!Oo("codex",t)?[]:["-c",`model_reasoning_effort=${t}`]}function Kc(t){if(!t)return [];let e=new Set(["acceptEdits","bypassPermissions","default","delegate","dontAsk","plan"]),n=Fc(t);return e.has(n)?["--permission-mode",n]:[]}function Jc(t){return t?Oo("claude",t)?["--effort",t]:[]:[]}function Vc(t){return t==="default"?[]:t&&Sg.has(t)?["--permission-mode",t]:[]}function Xc(t){return t===true?["--always-approve"]:[]}function Yc(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 Qc(t){return t?Oo("grok",t)?["--effort",t]:[]:[]}function Zc(t){if(!t)return [];switch(ti(t)){case "default":return [];case "plan":return ["--mode","plan"];case "acceptEdits":return ["--mode","accept-edits"];case "bypassPermissions":return ["--dangerously-skip-permissions"];default:return []}}function eu(t){return t?Oo("antigravity",t)?["--effort",t]:[]:[]}var Rg,Sg,Ir=b(()=>{g();Wc();Rr();No();Rg=new Set($c);Sg=new Set(["default","acceptEdits","auto","dontAsk","bypassPermissions","plan"]);});function Ig(t){if(t.type!=="usage"||!("input_tokens"in t))return null;let e=Number(t.input_tokens??0),n=Number(t.output_tokens??0),o="cache_read_input_tokens"in t?Number(t.cache_read_input_tokens):void 0,s="cached_input_tokens"in t?Number(t.cached_input_tokens):void 0,i=o!==void 0?o:s??0;return {inputTokens:o!==void 0?e+o:e,outputTokens:n,cachedInputTokens:i}}function Ag(t){let e=t.usage;if(!e||typeof e!="object"||Array.isArray(e))return null;let n=e;if(!("input_tokens"in n))return null;let r=Number(n.input_tokens??0),o=Number(n.output_tokens??0),i="cache_read_input_tokens"in n?Number(n.cache_read_input_tokens):void 0,c="cached_input_tokens"in n?Number(n.cached_input_tokens):void 0,d=i!==void 0?i:c??0;return {inputTokens:i!==void 0?r+i:r,outputTokens:o,cachedInputTokens:d}}function Ng(t){if(t.type!=="step_finish")return null;let n=t.part?.tokens;if(!n)return null;let r=Number(n.input??0),o=Number(n.output??0)+Number(n.reasoning??0),s=n.cache,i=s?Number(s.read??0):0;return {inputTokens:r+i,outputTokens:o,cachedInputTokens:i}}function tu(t){let e=new Map,n;for(let s of t.split(`
54
+ `))if(s.trim())try{let i=JSON.parse(s);if(i.type!=="assistant")continue;let c=i.message,d=c?.id,u=c?.usage;if(typeof d!="string"||!u)continue;let l=Number(u.input_tokens??0),p=Number(u.cache_read_input_tokens??0);e.set(d,{inputTokens:l+p,cachedInputTokens:p});let _=c?.model;typeof _=="string"&&_&&(n=_);}catch{}if(e.size===0)return;let r=0,o=0;for(let s of e.values())r+=s.inputTokens,o+=s.cachedInputTokens;return {inputTokens:r,cachedInputTokens:o,model:n}}function Fn(t){if(!t||!t.trim())return;let e=null,n=null;for(let r of t.split(`
55
+ `))if(r.trim())try{let o=JSON.parse(r),s=Ng(o);if(s){n||(n={inputTokens:0,outputTokens:0,cachedInputTokens:0}),n.inputTokens+=s.inputTokens,n.outputTokens+=s.outputTokens,n.cachedInputTokens+=s.cachedInputTokens;continue}let i=Ig(o)??Ag(o);i&&(e=i);}catch{}return n||(e??void 0)}var Ar=b(()=>{g();});function it(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 hn=b(()=>{g();});var vo,nu=b(()=>{g();vo=Object.freeze({CLAUDE_CODE_DISABLE_AUTO_MEMORY:"1"});});function ou(t){return t==="all"?[...ru,...Og]:ru}function su(t){return ou(t).map(e=>`Bash(${e} *)`)}function iu(t){return ou(t).map(e=>`command(${e})`)}var ru,Og,si=b(()=>{g();ru=["crewx memory","crewx search","crewx doc","crewx notify"],Og=["crewx q","crewx query","crewx x","crewx execute","crewx cron","crewx wbs","crewx wi","crewx workflow","crewx app","crewx skill"];});function au(t){let e=t.split(`
56
+ `).filter(o=>o.trim()),n=[],r=null;for(let o of e)try{let s=JSON.parse(o);if(s.type==="assistant"&&Array.isArray(s.message?.content))for(let i of s.message.content)i.type==="text"&&typeof i.text=="string"&&i.text.trim()&&n.push(i.text.trim());s.type==="result"&&typeof s.result=="string"&&(r=s.result);}catch{}if(n.length>0)return n[n.length-1];if(r)return r}function du(t){let e=t.split(`
57
+ `).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 Wn(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0}function _u(t){let e=Wn(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=Pg(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(Lg(n))return `Claude rate limit: ${n}`}}function Cg(t){for(let e of t.split(`
58
+ `)){let n=e.trim();if(n){if(n.startsWith("Not logged in"))return n;try{let r=Wn(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 xg(t){let e=Wn(t);if(e?.type!=="rate_limit_event")return;let n=Wn(Wn(e.rate_limit_info)?.unifiedWindows);if(!n)return;let r=cu(n.five_hour),o=cu(n.seven_day);if(!(!r&&!o))return {...r?{five_hour:r}:{},...o?{seven_day:o}:{}}}function cu(t){let e=Wn(t);if(!(typeof e?.utilization!="number"||typeof e.resetsAt!="number"))return {utilization:e.utilization,resetsAt:e.resetsAt}}function uu(t){if(t?.is_error===true)return So(t.result)}function Dg(t){let e=_u(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",o=typeof t.terminal_reason=="string"?t.terminal_reason:"unknown";return `Claude ended without an answer (subtype=${r}, terminal_reason=${o})`}function Pg(t){let n=t.message?.content;return Array.isArray(n)?n.map(r=>typeof r.text=="string"?r.text.trim():"").filter(Boolean).join(`
59
59
 
60
- `):""}function tg(t){let e=t.toLowerCase();return e.includes("out of extra usage")||e.includes("rate limit")||e.includes("quota")}function Wc(t){return t.replace(/\s+/g," ").trim()}function ng(t,e){let n=t?.description;if(typeof n!="string")return;let r=Wc(n);if(!r||r===Wc(e))return;if(r.length<=Bc)return r;let o=r.slice(0,Bc-1);return /[\uD800-\uDBFF]$/.test(o)&&(o=o.slice(0,-1)),`${o}\u2026`}function rg(t,e){let n=e.type;if(n==="text"){let r=String(e.text||"");return r?{timestamp:t,type:"text",content:r}:null}if(n==="thinking"){let r=typeof e.thinking=="string"?e.thinking.trim():"";return r?{timestamp:t,type:"thinking",content:r}:null}if(n==="tool_use"){let r=String(e.name||""),o=e.id,s=e.input,i=tt(s);if(r==="Bash"&&kt(i))return yt(t,i,o);let c=ng(s,i);return {timestamp:t,type:"tool_use",toolUseId:o,toolName:r,toolInput:i,...c?{toolTitle:c}:{}}}if(n==="tool_result"){let r=!!e.is_error,o=e.tool_use_id,s=e.output??e.content??"",i;return typeof s=="string"?i=s:Array.isArray(s)?i=s.filter(c=>c.type==="text"&&typeof c.text=="string").map(c=>c.text).join(`
61
- `):i=JSON.stringify(s),{timestamp:t,type:"tool_result",toolUseId:o,...et(i,r)}}return null}var Vf,Xf,ko,Bc,Gs=C(()=>{g();xs();$t();bs();Sn();In();An();Nn();lr();Ht();pr();sn();Dc();Ws();Vf=new Set(["tool_progress"]),Xf="cli/claude";ko={command:"claude",meta:{displayName:"Claude",models:gc(),capabilities:{resume:true}},buildArgs(t,e,n){let{model:r,effort:o}=Ut(e.model),s=e.effort??o,i=Sc(e.mode),c=Ic(s),d=r?["--model",r]:[],u=e.mode==="bypassPermissions"?[]:["--allowedTools",...Mc(e.builtinAllow)],l=e.resumeSessionId?["--resume",e.resumeSessionId]:[];if(e.additionalArgs!==void 0){let _=[...e.additionalArgs];return _.indexOf("-p")!==-1?{args:["--output-format","stream-json","--verbose",...l,...i,...c,...d,...u,..._],stdinMessage:t,env:mo}:{args:["--output-format","stream-json","--verbose",...l,...i,...c,...d,...u,..._],stdinMessage:t,env:mo}}return {args:["-p","--output-format","stream-json","--verbose",...l,...i,...c,...d,...u],stdinMessage:t,env:mo}},extractText(t){let e=Uc(t);if(e?.is_error===true){let o=ko.extractFailure(JSON.stringify(e));if(o)throw o;let s=typeof e.subtype=="string"?e.subtype:"unknown",i=typeof e.terminal_reason=="string"?e.terminal_reason:"unknown";throw new W(Fc(e)??`Claude ended without an answer (subtype=${s}, terminal_reason=${i})`,Xf,{code:"EMPTY_OUTPUT",kind:"permanent"})}let n=Hc(t);if(n)return n;let r=t.trim();return mt(r,"claude")?"":r},extractPartialText(t){return Hc(t)},extractFailure(t){try{let e=JSON.parse(t),n=Gc(e);if(n)return new on(n)}catch{}return null},interpretExit(t,e,n){let r=Yf(n??"");if(r)return new W(`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 o=Fc(Uc(n??""));return o?new W(o,"cli/claude"):null},observeRateLimit(t){try{let e=JSON.parse(t);return Qf(e)}catch{return}},parseResultMeta(t){let e=t.split(`
62
- `);for(let r of e)if(r.trim())try{let o=JSON.parse(r);if(o.type==="result"){let s=o.usage,i=s?{inputTokens:Number(s.input_tokens??0)+Number(s.cache_read_input_tokens??0),outputTokens:Number(s.output_tokens??0),cachedInputTokens:Number(s.cache_read_input_tokens??0),costUsd:Number(o.total_cost_usd??0)}:null,c=o.modelUsage,d=c?Object.keys(c)[0]??null:null;return {usage:i,model:d}}}catch{}let n=bc(t);return n?{usage:{inputTokens:n.inputTokens,outputTokens:0,cachedInputTokens:n.cachedInputTokens,costUsd:0},model:n.model??null}:{usage:null,model:null}},parseEvent(t,e){let n;try{n=JSON.parse(t);}catch{return []}let r=n.type;if(!r)return [];let o=nt(n,e??new Date().toISOString()),s=Zf(n);if(s)return [{timestamp:o,type:"error",content:s,errorMessage:s}];let i=n.output_file,c=n.summary;if(r==="system"&&n.subtype==="task_notification"&&n.status==="completed"&&typeof i=="string"&&i.trim().length>0&&typeof c=="string"&&c.trim().length>0)return [{timestamp:o,type:"text",content:c}];if(r!=="assistant"&&r!=="user")return [];let u=n.message?.content;if(!Array.isArray(u))return [];let l=[];for(let p of u){let _=rg(o,p);_&&l.push(_);}return l},suppressOutputLine(t){let e=t.trim();if(!e.startsWith("{")||!e.endsWith("}"))return false;try{let r=JSON.parse(e).type;return r?Vf.has(r):!1}catch{return false}}};Bc=200;});function jc(t){let e=t.split(`
63
- `).filter(o=>o.trim()),n=[],r=null;for(let o of e)try{let s=JSON.parse(o);if(s.type==="assistant.message"&&typeof s.data?.content=="string"){let i=s.data.content;i.trim()&&n.push(i.trim());}s.type==="result"&&typeof s.result=="string"&&(r=s.result);}catch{}if(n.length>0)return n[n.length-1];if(r)return r}var og,js,Ks=C(()=>{g();Sn();pr();In();Nn();An();Ht();go();sn();og=new Set(["interactive","plan","autopilot"]);js={command:"copilot",meta:{displayName:"Copilot",models:mc()},buildArgs(t,e,n){let r=e.additionalArgs?[...e.additionalArgs]:[];return e.model&&r.push("--model",e.model),e.mode&&og.has(e.mode)&&r.push("--mode",e.mode),e.effort&&(fo.copilot??[]).includes(e.effort)&&r.push("--effort",e.effort),{args:r,stdinMessage:t}},extractText(t){let e=jc(t);if(e)return e;let n=t.trim();return mt(n,"copilot")?"":n},extractPartialText(t){return jc(t)},parseResultMeta(t){let e=vn(t);return e?{usage:{inputTokens:e.inputTokens,outputTokens:e.outputTokens,cachedInputTokens:e.cachedInputTokens,costUsd:0},model:null}:{usage:null,model:null}},parseEvent(t,e){let n;try{n=JSON.parse(t);}catch{return []}let r=n.type;if(!r)return [];if(!r.startsWith("tool.execution")&&!r.startsWith("assistant.")&&r!=="user.message")return [];let o=n.data;if(!o)return [];let s=nt(n,e??new Date().toISOString()),i=o.toolCallId;if(r==="tool.execution_start"){let c=String(o.toolName||""),d=o.arguments,u=tt(d);return (c==="bash"||c==="Bash")&&kt(u)?[yt(s,u,i)]:[{timestamp:s,type:"tool_use",toolName:c,toolInput:u,...i&&{toolUseId:i}}]}if(r==="tool.execution_complete"){let c=o.error;if(c)return [{timestamp:s,type:"tool_result",...i&&{toolUseId:i},...et(String(c.message||""),true)}];let d=o.result,u=String(d?.content||"");return [{timestamp:s,type:"tool_result",...i&&{toolUseId:i},...et(u,false)}]}if(r==="assistant.message"){let c=String(o.content||"");return c?[{timestamp:s,type:"text",content:c}]:[]}return []}};});function ag(t){let e=[],n=0,r=false,o=false,s=0;for(let c=0;c<t.length;c++){let d=t[c];if(o){o=false;continue}if(d==="\\"&&r){o=true;continue}if(d==='"'){r=!r;continue}if(!r){if(d==="{")n++;else if(d==="}"&&(n--,n===0)){let u=t.slice(s,c+1).trim();u&&e.push(u),s=c+1;}}}let i=t.slice(s).trim();return i&&e.push(i),e}function dg(t){return t[0]==="exec"?t.slice(1):t}function Kc(t){let e=t.split(`
64
- `).map(o=>o.trim()).filter(Boolean),n=[],r=null;for(let o of e)try{let s=JSON.parse(o);if(s.type==="item.completed"&&(s.item?.type==="message"||s.item?.type==="agent_message")&&typeof s.item?.text=="string"){let i=s.item.text;i.trim()&&n.push(i.trim());}s.type==="result"&&typeof s.result=="string"&&(r=s.result);}catch{}if(n.length>0)return n[n.length-1];if(r)return r}function qt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Jc(t){return t.type==="turn.failed"?true:t.type!=="error"?false:typeof t.message=="string"||typeof t.errorMessage=="string"||typeof t.error=="string"||qt(t.error)}function Vc(t){let e=qt(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 cg(t){for(let e of t.split(/\r?\n/)){if(!e.trim())continue;let n;try{n=JSON.parse(e);}catch{continue}if(qt(n)&&Jc(n))return Vc(n)}}function zc(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 o=n.state.get("codex.pending");o||(o=new Map,n.state.set("codex.pending",o));let s=JSON.stringify([t.type,t.id]);if(e==="item.started"){let d=`codex:${JSON.stringify(t.id)}#${n.rowIndex}:${r}`,u=o.get(s)??[];return u.push(d),o.set(s,u),d}let i=o.get(s),c=i?.pop();return i?.length||o.delete(s),c}function ug(t,e,n){let r=e.type;if(r==="command_execution"){let o=String(e.command||"");return kt(o)?[yt(t,o,n)]:[{timestamp:t,type:"tool_use",toolName:"Bash",toolInput:o,...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:tt(e.arguments),...n?{toolUseId:n}:{}}]:[]}function lg(t,e,n){let r=e.type;if(r==="message"||r==="text"){let o=e.content;if(Array.isArray(o))for(let s of o){let i=pg(t,s);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 o=typeof e.text=="string"?e.text.trim():"";return o?{timestamp:t,type:"thinking",content:o}:null}if(r==="command_execution"){let o=String(e.aggregated_output||e.output||""),s=!!e.is_error;return {timestamp:t,type:"tool_result",...et(o,s),...n?{toolUseId:n}:{}}}if(r==="mcp_tool_call"){let o=qt(e.result)?e.result:void 0,i=(Array.isArray(o?.content)?o.content:[]).filter(d=>qt(d)&&d.type==="text"&&typeof d.text=="string").map(d=>d.text).join(`
65
- `),c=typeof e.error=="string"?e.error:qt(e.error)&&typeof e.error.message=="string"?e.error.message:"";return {timestamp:t,type:"tool_result",resultPreview:i||c,isError:e.status==="failed"||e.status==="error"||e.is_error===true||e.error!=null,...n?{toolUseId:n}:{}}}if(r==="tool_use"){let o=String(e.name||e.tool_name||""),s=e.input,i=tt(s);return o==="Bash"&&kt(i)?yt(t,i):{timestamp:t,type:"tool_use",toolName:o,toolInput:i}}if(r==="tool_result"){let o=!!e.is_error,s=String(e.output||e.content||"");return {timestamp:t,type:"tool_result",...et(s,o)}}if(r==="web_search"){let o=e.action,s;if(o?.type==="search"){let i=o.queries;s=String(o.query||"")||(i?.length?i.join(", "):"")||String(e.query||"");}else s=e.query?"open: "+String(e.query):"";return !s&&!(qt(o)&&o.type==="other"&&e.query==="")?null:{timestamp:t,type:"tool_use",toolName:"WebSearch",toolInput:s}}if(r==="file_change"){let o=e.changes;if(!Array.isArray(o)||o.length===0)return null;let s=o.map(c=>String(c.path||"")).filter(Boolean);if(s.length===0)return null;let i=s.length===1?s[0]:`${s.slice(0,2).join(", ")}${s.length>2?` (+${s.length-2})`:""}`;return {timestamp:t,type:"tool_use",toolName:"Edit",toolInput:i}}return null}function pg(t,e){let n=e.type;if(n==="text")return {timestamp:t,type:"text",content:String(e.text||"")};if(n==="tool_use"){let r=String(e.name||""),o=e.input,s=tt(o);return r==="Bash"&&kt(s)?yt(t,s):{timestamp:t,type:"tool_use",toolName:r,toolInput:s}}return null}var sg,ig,zs,Js=C(()=>{g();$t();Sn();pr();In();Nn();Ls();An();lr();Ht();sn();sg=new Set(["turn.started","turn.completed","item.updated"]),ig="cli/codex";zs={command:"codex",meta:{displayName:"Codex",models:hc(),capabilities:{resume:true}},buildArgs(t,e,n){let{model:r,effort:o}=Ut(e.model),s=e.effort??o,i=e.resumeSessionId?Ec(e.mode):wc(e.mode),c=Rc(s),d=r?["-m",r]:[],u=dg(e.additionalArgs??[]),p=u.includes("--json")||u.includes("--experimental-json")?[]:["--json"];return e.resumeSessionId?{args:["exec","resume",...p,...i,...c,...d,...u,e.resumeSessionId,"-"],stdinMessage:t}:{args:["exec",...p,...i,...c,...d,...u],stdinMessage:t}},extractText(t){let e=cg(t);if(e)throw new W(e,ig);let n=Kc(t);if(n)return n;let r=t.trim();return mt(r,"codex")?"":r},extractPartialText(t){return Kc(t)},parseResultMeta(t){let e=vn(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(),o=[],s;try{JSON.parse(t),s=[t];}catch{s=ag(t),s.length>1&&console.warn("[codex] parseEvent: falling back to concatenated-JSON split for a malformed line");}for(let[i,c]of s.entries()){let d;try{d=JSON.parse(c);}catch{continue}if(!qt(d))continue;let u=d.type;if(!u)continue;let l=nt(d,r);if(Jc(d)){let _=Vc(d);o.push({timestamp:l,type:"error",content:_,errorMessage:_});continue}if(!u.startsWith("item.")&&!u.startsWith("turn.")&&!u.startsWith("thread.")||Ps(d))continue;u==="thread.started"&&n&&n.state.delete("codex.pending");let p=d.item;if(p){if(u==="item.started"){o.push(...ug(l,p,zc(p,u,n,i)));continue}if(u==="item.completed"){let _=lg(l,p,zc(p,u,n,i));_&&o.push(_);continue}}}return o},suppressOutputLine(t){let e=t.trim();if(!e.startsWith("{")||!e.endsWith("}"))return false;try{let r=JSON.parse(e).type;return r?sg.has(r):!1}catch{return false}}};});function Ke(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 _r(t){let e=Ke(t);if(e)return Ke(e.replace(/^Upstream request failed:\s*/i,""),200)}var Xc=C(()=>{g();});var Yc=C(()=>{g();});function fg(t){let e=t.match(/(?:^|[^0-9])([0-9]{1,5})(?![0-9])/);if(!e)return null;let n=Number(e[1]);return Number.isInteger(n)&&n>0&&n<=65535?n:null}function gg(){return new Promise(t=>{let e=false,n,r=o=>{e||(e=true,n&&clearTimeout(n),t(o));};n=setTimeout(()=>r(null),Qc),n.unref();try{child_process.execFile("chcp.com",[],{encoding:"ascii",timeout:Qc,windowsHide:!0},(s,i)=>{if(s){r(null);return}r(fg(String(i)));}).once("error",()=>r(null));}catch{r(null);}})}function hg(){return process.platform!=="win32"?Promise.resolve(null):(yo||(yo=gg(),yo.then(t=>{},()=>{})),yo)}function mg(){process.platform==="win32"&&hg();}var Qc,yo,eu=C(()=>{g();Qc=1e3;mg();});function yg(t,e){let n={};for(let[r,o]of Object.entries(t))o!==void 0&&(e.includes(r)||(n[r]=o));return n}function Vs(t){return yg(t,kg)}var kg,Xs=C(()=>{g();kg=["CREWX_ASSIGNED_TASK_ID","CREWX_DETACHED_RUNNER"];});function To(){if(process.env.CREWX_HOME){let t=Re__namespace.resolve(process.env.CREWX_HOME);try{return nu__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?Re__namespace.join(process.env.XDG_CONFIG_HOME,"crewx"):Re__namespace.join(Na__namespace.homedir(),".crewx")}var ru=C(()=>{g();});function gr(t=To()){let e=Re.join(t,"opencode-xdg");return {XDG_DATA_HOME:Re.join(e,"data"),XDG_STATE_HOME:Re.join(e,"state")}}function hr(t=To()){return Re.join(gr(t).XDG_DATA_HOME,"opencode")}async function Rg(){return (await import('better-sqlite3')).default}function Sg(t){return Re.join(t,"opencode.db")}function Ig(t){let e=t??process.env.XDG_DATA_HOME??Re.join(Na.homedir(),".local","share");return Re.join(Re.resolve(e),"opencode","opencode.db")}function su(t,e){return !!t.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?").get(e)}function Ag(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 Ng(t,e){if(!nu.existsSync(e))return [];let n;try{return n=new t(e,{readonly:!0,fileMustExist:!0}),su(n,"credential")?n.prepare(`
60
+ `):""}function Lg(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 Mg(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 o=r.slice(0,lu-1);return /[\uD800-\uDBFF]$/.test(o)&&(o=o.slice(0,-1)),`${o}\u2026`}function $g(t,e){let n=e.type;if(n==="text"){let r=String(e.text||"");return r?{timestamp:t,type:"text",content:r}:null}if(n==="thinking"){let r=typeof e.thinking=="string"?e.thinking.trim():"";return r?{timestamp:t,type:"thinking",content:r}:null}if(n==="tool_use"){let r=String(e.name||""),o=e.id,s=e.input,i=st(s);if(r==="Bash"&&Rt(i))return St(t,i,o);let c=Mg(s,i);return {timestamp:t,type:"tool_use",toolUseId:o,toolName:r,toolInput:i,...c?{toolTitle:c}:{}}}if(n==="tool_result"){let r=!!e.is_error,o=e.tool_use_id,s=e.output??e.content??"",i;return typeof s=="string"?i=s:Array.isArray(s)?i=s.filter(c=>c.type==="text"&&typeof c.text=="string").map(c=>c.text).join(`
61
+ `):i=JSON.stringify(s),{timestamp:t,type:"tool_result",toolUseId:o,...ot(i,r)}}return null}var vg,bg,bo,lu,ii=b(()=>{g();Ks();Vt();Js();$n();Hn();Un();qn();Ir();Xt();Ar();hn();nu();si();vg=new Set(["tool_progress"]),bg="cli/claude";bo={command:"claude",meta:{displayName:"Claude",models:Hc(),capabilities:{resume:true}},buildArgs(t,e,n){let{model:r,effort:o}=Yt(e.model),s=e.effort??o,i=Kc(e.mode),c=Jc(s),d=r?["--model",r]:[],u=e.mode==="bypassPermissions"?[]:["--allowedTools",...su(e.builtinAllow)],l=e.resumeSessionId?["--resume",e.resumeSessionId]:[];if(e.additionalArgs!==void 0){let _=[...e.additionalArgs];return _.indexOf("-p")!==-1?{args:["--output-format","stream-json","--verbose",...l,...i,...c,...d,...u,..._],stdinMessage:t,env:vo}:{args:["--output-format","stream-json","--verbose",...l,...i,...c,...d,...u,..._],stdinMessage:t,env:vo}}return {args:["-p","--output-format","stream-json","--verbose",...l,...i,...c,...d,...u],stdinMessage:t,env:vo}},extractText(t){let e=du(t);if(e?.is_error===true){let o=bo.extractFailure(JSON.stringify(e));if(o)throw o;let s=typeof e.subtype=="string"?e.subtype:"unknown",i=typeof e.terminal_reason=="string"?e.terminal_reason:"unknown";throw new W(uu(e)??`Claude ended without an answer (subtype=${s}, terminal_reason=${i})`,bg,{code:"EMPTY_OUTPUT",kind:"permanent"})}let n=au(t);if(n)return n;let r=t.trim();return Et(r,"claude")?"":r},extractPartialText(t){return au(t)},extractFailure(t){try{let e=JSON.parse(t),n=_u(e);if(n)return new gn(n)}catch{}return null},interpretExit(t,e,n){let r=Cg(n??"");if(r)return new W(`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 o=uu(du(n??""));return o?new W(o,"cli/claude"):null},observeRateLimit(t){try{let e=JSON.parse(t);return xg(e)}catch{return}},parseResultMeta(t){let e=t.split(`
62
+ `);for(let r of e)if(r.trim())try{let o=JSON.parse(r);if(o.type==="result"){let s=o.usage,i=s?{inputTokens:Number(s.input_tokens??0)+Number(s.cache_read_input_tokens??0),outputTokens:Number(s.output_tokens??0),cachedInputTokens:Number(s.cache_read_input_tokens??0),costUsd:Number(o.total_cost_usd??0)}:null,c=o.modelUsage,d=c?Object.keys(c)[0]??null:null;return {usage:i,model:d}}}catch{}let n=tu(t);return n?{usage:{inputTokens:n.inputTokens,outputTokens:0,cachedInputTokens:n.cachedInputTokens,costUsd:0},model:n.model??null}:{usage:null,model:null}},parseEvent(t,e){let n;try{n=JSON.parse(t);}catch{return []}let r=n.type;if(!r)return [];let o=it(n,e??new Date().toISOString()),s=Dg(n);if(s)return [{timestamp:o,type:"error",content:s,errorMessage:s}];let i=n.output_file,c=n.summary;if(r==="system"&&n.subtype==="task_notification"&&n.status==="completed"&&typeof i=="string"&&i.trim().length>0&&typeof c=="string"&&c.trim().length>0)return [{timestamp:o,type:"text",content:c}];if(r!=="assistant"&&r!=="user")return [];let u=n.message?.content;if(!Array.isArray(u))return [];let l=[];for(let p of u){let _=$g(o,p);_&&l.push(_);}return l},suppressOutputLine(t){let e=t.trim();if(!e.startsWith("{")||!e.endsWith("}"))return false;try{let r=JSON.parse(e).type;return r?vg.has(r):!1}catch{return false}}};lu=200;});function fu(t){let e=t.split(`
63
+ `).filter(o=>o.trim()),n=[],r=null;for(let o of e)try{let s=JSON.parse(o);if(s.type==="assistant.message"&&typeof s.data?.content=="string"){let i=s.data.content;i.trim()&&n.push(i.trim());}s.type==="result"&&typeof s.result=="string"&&(r=s.result);}catch{}if(n.length>0)return n[n.length-1];if(r)return r}var Hg,ai,di=b(()=>{g();$n();Ar();Hn();qn();Un();Xt();No();hn();Hg=new Set(["interactive","plan","autopilot"]);ai={command:"copilot",meta:{displayName:"Copilot",models:qc()},buildArgs(t,e,n){let r=e.additionalArgs?[...e.additionalArgs]:[];return e.model&&r.push("--model",e.model),e.mode&&Hg.has(e.mode)&&r.push("--mode",e.mode),e.effort&&(Ao.copilot??[]).includes(e.effort)&&r.push("--effort",e.effort),{args:r,stdinMessage:t}},extractText(t){let e=fu(t);if(e)return e;let n=t.trim();return Et(n,"copilot")?"":n},extractPartialText(t){return fu(t)},parseResultMeta(t){let e=Fn(t);return e?{usage:{inputTokens:e.inputTokens,outputTokens:e.outputTokens,cachedInputTokens:e.cachedInputTokens,costUsd:0},model:null}:{usage:null,model:null}},parseEvent(t,e){let n;try{n=JSON.parse(t);}catch{return []}let r=n.type;if(!r)return [];if(!r.startsWith("tool.execution")&&!r.startsWith("assistant.")&&r!=="user.message")return [];let o=n.data;if(!o)return [];let s=it(n,e??new Date().toISOString()),i=o.toolCallId;if(r==="tool.execution_start"){let c=String(o.toolName||""),d=o.arguments,u=st(d);return (c==="bash"||c==="Bash")&&Rt(u)?[St(s,u,i)]:[{timestamp:s,type:"tool_use",toolName:c,toolInput:u,...i&&{toolUseId:i}}]}if(r==="tool.execution_complete"){let c=o.error;if(c)return [{timestamp:s,type:"tool_result",...i&&{toolUseId:i},...ot(String(c.message||""),true)}];let d=o.result,u=String(d?.content||"");return [{timestamp:s,type:"tool_result",...i&&{toolUseId:i},...ot(u,false)}]}if(r==="assistant.message"){let c=String(o.content||"");return c?[{timestamp:s,type:"text",content:c}]:[]}return []}};});function Bg(t){let e=[],n=0,r=false,o=false,s=0;for(let c=0;c<t.length;c++){let d=t[c];if(o){o=false;continue}if(d==="\\"&&r){o=true;continue}if(d==='"'){r=!r;continue}if(!r){if(d==="{")n++;else if(d==="}"&&(n--,n===0)){let u=t.slice(s,c+1).trim();u&&e.push(u),s=c+1;}}}let i=t.slice(s).trim();return i&&e.push(i),e}function Fg(t){return t[0]==="exec"?t.slice(1):t}function gu(t){let e=t.split(`
64
+ `).map(o=>o.trim()).filter(Boolean),n=[],r=null;for(let o of e)try{let s=JSON.parse(o);if(s.type==="item.completed"&&(s.item?.type==="message"||s.item?.type==="agent_message")&&typeof s.item?.text=="string"){let i=s.item.text;i.trim()&&n.push(i.trim());}s.type==="result"&&typeof s.result=="string"&&(r=s.result);}catch{}if(n.length>0)return n[n.length-1];if(r)return r}function Qt(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"||Qt(t.error)}function ku(t){let e=Qt(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 Wg(t){for(let e of t.split(/\r?\n/)){if(!e.trim())continue;let n;try{n=JSON.parse(e);}catch{continue}if(Qt(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 o=n.state.get("codex.pending");o||(o=new Map,n.state.set("codex.pending",o));let s=JSON.stringify([t.type,t.id]);if(e==="item.started"){let d=`codex:${JSON.stringify(t.id)}#${n.rowIndex}:${r}`,u=o.get(s)??[];return u.push(d),o.set(s,u),d}let i=o.get(s),c=i?.pop();return i?.length||o.delete(s),c}function Gg(t,e,n){let r=e.type;if(r==="command_execution"){let o=String(e.command||"");return Rt(o)?[St(t,o,n)]:[{timestamp:t,type:"tool_use",toolName:"Bash",toolInput:o,...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:st(e.arguments),...n?{toolUseId:n}:{}}]:[]}function jg(t,e,n){let r=e.type;if(r==="message"||r==="text"){let o=e.content;if(Array.isArray(o))for(let s of o){let i=zg(t,s);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 o=typeof e.text=="string"?e.text.trim():"";return o?{timestamp:t,type:"thinking",content:o}:null}if(r==="command_execution"){let o=String(e.aggregated_output||e.output||""),s=!!e.is_error;return {timestamp:t,type:"tool_result",...ot(o,s),...n?{toolUseId:n}:{}}}if(r==="mcp_tool_call"){let o=Qt(e.result)?e.result:void 0,i=(Array.isArray(o?.content)?o.content:[]).filter(d=>Qt(d)&&d.type==="text"&&typeof d.text=="string").map(d=>d.text).join(`
65
+ `),c=typeof e.error=="string"?e.error:Qt(e.error)&&typeof e.error.message=="string"?e.error.message:"";return {timestamp:t,type:"tool_result",resultPreview:i||c,isError:e.status==="failed"||e.status==="error"||e.is_error===true||e.error!=null,...n?{toolUseId:n}:{}}}if(r==="tool_use"){let o=String(e.name||e.tool_name||""),s=e.input,i=st(s);return o==="Bash"&&Rt(i)?St(t,i):{timestamp:t,type:"tool_use",toolName:o,toolInput:i}}if(r==="tool_result"){let o=!!e.is_error,s=String(e.output||e.content||"");return {timestamp:t,type:"tool_result",...ot(s,o)}}if(r==="web_search"){let o=e.action,s;if(o?.type==="search"){let i=o.queries;s=String(o.query||"")||(i?.length?i.join(", "):"")||String(e.query||"");}else s=e.query?"open: "+String(e.query):"";return !s&&!(Qt(o)&&o.type==="other"&&e.query==="")?null:{timestamp:t,type:"tool_use",toolName:"WebSearch",toolInput:s}}if(r==="file_change"){let o=e.changes;if(!Array.isArray(o)||o.length===0)return null;let s=o.map(c=>String(c.path||"")).filter(Boolean);if(s.length===0)return null;let i=s.length===1?s[0]:`${s.slice(0,2).join(", ")}${s.length>2?` (+${s.length-2})`:""}`;return {timestamp:t,type:"tool_use",toolName:"Edit",toolInput:i}}return null}function zg(t,e){let n=e.type;if(n==="text")return {timestamp:t,type:"text",content:String(e.text||"")};if(n==="tool_use"){let r=String(e.name||""),o=e.input,s=st(o);return r==="Bash"&&Rt(s)?St(t,s):{timestamp:t,type:"tool_use",toolName:r,toolInput:s}}return null}var Ug,qg,ci,ui=b(()=>{g();Vt();$n();Ar();Hn();qn();Ys();Un();Ir();Xt();hn();Ug=new Set(["turn.started","turn.completed","item.updated"]),qg="cli/codex";ci={command:"codex",meta:{displayName:"Codex",models:Uc(),capabilities:{resume:true}},buildArgs(t,e,n){let{model:r,effort:o}=Yt(e.model),s=e.effort??o,i=e.resumeSessionId?jc(e.mode):Gc(e.mode),c=zc(s),d=r?["-m",r]:[],u=Fg(e.additionalArgs??[]),p=u.includes("--json")||u.includes("--experimental-json")?[]:["--json"];return e.resumeSessionId?{args:["exec","resume",...p,...i,...c,...d,...u,e.resumeSessionId,"-"],stdinMessage:t}:{args:["exec",...p,...i,...c,...d,...u],stdinMessage:t}},extractText(t){let e=Wg(t);if(e)throw new W(e,qg);let n=gu(t);if(n)return n;let r=t.trim();return Et(r,"codex")?"":r},extractPartialText(t){return gu(t)},parseResultMeta(t){let e=Fn(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(),o=[],s;try{JSON.parse(t),s=[t];}catch{s=Bg(t),s.length>1&&console.warn("[codex] parseEvent: falling back to concatenated-JSON split for a malformed line");}for(let[i,c]of s.entries()){let d;try{d=JSON.parse(c);}catch{continue}if(!Qt(d))continue;let u=d.type;if(!u)continue;let l=it(d,r);if(mu(d)){let _=ku(d);o.push({timestamp:l,type:"error",content:_,errorMessage:_});continue}if(!u.startsWith("item.")&&!u.startsWith("turn.")&&!u.startsWith("thread.")||Xs(d))continue;u==="thread.started"&&n&&n.state.delete("codex.pending");let p=d.item;if(p){if(u==="item.started"){o.push(...Gg(l,p,hu(p,u,n,i)));continue}if(u==="item.completed"){let _=jg(l,p,hu(p,u,n,i));_&&o.push(_);continue}}}return o},suppressOutputLine(t){let e=t.trim();if(!e.startsWith("{")||!e.endsWith("}"))return false;try{let r=JSON.parse(e).type;return r?Ug.has(r):!1}catch{return false}}};});function Xe(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 Nr(t){let e=Xe(t);if(e)return Xe(e.replace(/^Upstream request failed:\s*/i,""),200)}var yu=b(()=>{g();});var Tu=b(()=>{g();});function Jg(t){let e=t.match(/(?:^|[^0-9])([0-9]{1,5})(?![0-9])/);if(!e)return null;let n=Number(e[1]);return Number.isInteger(n)&&n>0&&n<=65535?n:null}function Vg(){return new Promise(t=>{let e=false,n,r=o=>{e||(e=true,n&&clearTimeout(n),t(o));};n=setTimeout(()=>r(null),wu),n.unref();try{child_process.execFile("chcp.com",[],{encoding:"ascii",timeout:wu,windowsHide:!0},(s,i)=>{if(s){r(null);return}r(Jg(String(i)));}).once("error",()=>r(null));}catch{r(null);}})}function Xg(){return process.platform!=="win32"?Promise.resolve(null):(Co||(Co=Vg(),Co.then(t=>{},()=>{})),Co)}function Yg(){process.platform==="win32"&&Xg();}var wu,Co,Ru=b(()=>{g();wu=1e3;Yg();});function Zg(t,e){let n={};for(let[r,o]of Object.entries(t))o!==void 0&&(e.includes(r)||(n[r]=o));return n}function li(t){return Zg(t,Qg)}var Qg,pi=b(()=>{g();Qg=["CREWX_ASSIGNED_TASK_ID","CREWX_DETACHED_RUNNER"];});function xo(){if(process.env.CREWX_HOME){let t=Ne__namespace.resolve(process.env.CREWX_HOME);try{return Iu__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?Ne__namespace.join(process.env.XDG_CONFIG_HOME,"crewx"):Ne__namespace.join(Ja__namespace.homedir(),".crewx")}var Au=b(()=>{g();});function vr(t=xo()){let e=Ne.join(t,"opencode-xdg");return {XDG_DATA_HOME:Ne.join(e,"data"),XDG_STATE_HOME:Ne.join(e,"state")}}function br(t=xo()){return Ne.join(vr(t).XDG_DATA_HOME,"opencode")}async function rh(){return (await import('better-sqlite3')).default}function oh(t){return Ne.join(t,"opencode.db")}function sh(t){let e=t??process.env.XDG_DATA_HOME??Ne.join(Ja.homedir(),".local","share");return Ne.join(Ne.resolve(e),"opencode","opencode.db")}function Ou(t,e){return !!t.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?").get(e)}function ih(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 ah(t,e){if(!Iu.existsSync(e))return [];let n;try{return n=new t(e,{readonly:!0,fileMustExist:!0}),Ou(n,"credential")?n.prepare(`
66
66
  SELECT id, integration_id, label, value, connector_id, method_id, active, time_created, time_updated
67
67
  FROM credential
68
- `).all().filter(o=>o.integration_id!==null&&Ag(o.value)):[]}catch{return []}finally{n?.close();}}function ou(t,e){if(!nu.existsSync(e))return false;let n;try{return n=new t(e,{readonly:!0,fileMustExist:!0}),su(n,"credential")}catch{return false}finally{n?.close();}}function Og(t){return new Promise((e,n)=>{child_process.execFile("opencode",["auth","list","--standalone"],{timeout:15e3,maxBuffer:1024*1024,encoding:"utf8",env:{...Vs(process.env),...t}},r=>{r?n(r):e();});})}function vg(t,e,n){let r=new t(e,{fileMustExist:true});try{let o=r.prepare(`
68
+ `).all().filter(o=>o.integration_id!==null&&ih(o.value)):[]}catch{return []}finally{n?.close();}}function Nu(t,e){if(!Iu.existsSync(e))return false;let n;try{return n=new t(e,{readonly:!0,fileMustExist:!0}),Ou(n,"credential")}catch{return false}finally{n?.close();}}function dh(t){return new Promise((e,n)=>{child_process.execFile("opencode",["auth","list","--standalone"],{timeout:15e3,maxBuffer:1024*1024,encoding:"utf8",env:{...li(process.env),...t}},r=>{r?n(r):e();});})}function ch(t,e,n){let r=new t(e,{fileMustExist:true});try{let o=r.prepare(`
69
69
  INSERT INTO credential (
70
70
  id, integration_id, label, value, connector_id, method_id, active, time_created, time_updated
71
71
  ) VALUES (
@@ -80,17 +80,17 @@ ${r.join(`
80
80
  active = excluded.active,
81
81
  time_created = excluded.time_created,
82
82
  time_updated = excluded.time_updated
83
- `);r.transaction(i=>{for(let c of i)o.run(c);})(n);}finally{r.close();}}function Cg(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 o=t[n+1],s=o!==void 0&&!o.startsWith("-");e.push({sessionId:s?o:void 0}),s&&(n+=1);continue}(r.startsWith("--session=")||r.startsWith("-s="))&&e.push({sessionId:r.slice(r.indexOf("=")+1)||void 0});}return e}function xg(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 wo(t){let e=xg(t.additionalArgs);return {...t,...e===void 0?{}:{additionalArgs:e},resumeSessionId:void 0}}function bg(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 Dg(t,e,n){let r=new t(e,{readonly:true,fileMustExist:true});try{return bg(r,n)}finally{r.close();}}async function Qs(t,e={}){let n;try{n=await(e.loadSqlite??Rg)();}catch{throw new W("OpenCode isolation requires the optional better-sqlite3 dependency. Install it and retry.","cli/opencode",{code:"INVALID_PROVIDER_FORMAT",kind:"config"})}let r=e.crewxHome??To(),o=gr(r),s=hr(r),i=Sg(s),c=Ig(e.userDataHome),d=Ng(n,c);if(d.length>0){if(!ou(n,i))try{await(e.initializeDatabase??Og)(o);}catch{throw new W("Could not initialize the isolated OpenCode credential database.","cli/opencode",{code:"INVALID_PROVIDER_FORMAT",kind:"config"})}if(!ou(n,i))throw new W("The isolated OpenCode credential database is unavailable.","cli/opencode",{code:"INVALID_PROVIDER_FORMAT",kind:"config"});try{vg(n,i,d);}catch{throw new W("Could not copy API-key credentials into the isolated OpenCode database.","cli/opencode",{code:"INVALID_PROVIDER_FORMAT",kind:"config"})}}let u=Cg(t.additionalArgs),l=u.map(_=>_.sessionId),p=u.length>0?l[l.length-1]:t.resumeSessionId;if(!p)return u.length>0?wo(t):t;if(l.some(_=>_!==p)||!nu.existsSync(i))return wo(t);try{return Dg(n,i,p)?{...t,resumeSessionId:p}:wo(t)}catch{throw new W("Could not read the isolated OpenCode session database safely.","cli/opencode",{code:"INVALID_PROVIDER_FORMAT",kind:"config"})}}var Zs=C(()=>{g();$t();Xs();ru();});function dn(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}async function ei(){let t;try{let n=(await import('better-sqlite3')).default,r=Re.join(hr(),"opencode.db");t=new n(r,{readonly:!0,fileMustExist:!0});let o=t.prepare("SELECT value FROM kv WHERE key = ?").get("models-dev:v2:catalog");if(!o||typeof o.value!="string")throw new Error("OpenCode model catalog row is unavailable");let s=JSON.parse(o.value);if(!dn(s))throw new Error("OpenCode model catalog shape is unavailable");let i=typeof s.body=="string"?JSON.parse(s.body):s.body;if(!dn(i))throw new Error("OpenCode model catalog body shape is unavailable");let c=new Map;for(let[d,u]of Object.entries(i)){if(!d||!dn(u)||!dn(u.models))throw new Error("OpenCode model provider shape is unavailable");for(let[l,p]of Object.entries(u.models)){if(!l||!dn(p))throw new Error("OpenCode model shape is unavailable");let _=p.capabilities;if(_===void 0)continue;if(!dn(_))throw new Error("OpenCode model capability shape is unavailable");let h=_.reasoning;if(h===void 0)continue;if(!dn(h))throw new Error("OpenCode reasoning capability shape is unavailable");let m=h.effort;(m===void 0||Array.isArray(m)&&m.every(k=>typeof k=="string"))&&c.set(`${d}/${l}`,Array.isArray(m)?m:[]);}}return c}catch{return console.debug("[opencode] could not read private model effort catalog; omitting effort choices"),new Map}finally{try{t?.close();}catch{}}}var iu=C(()=>{g();ni();Yc();eu();Xs();Zs();Ht();});function qg(t){return t?Ug[t]??{agent:"build",autoApprove:false}:{agent:void 0,autoApprove:false}}function ze(t,e){return t.some(n=>n===e||n.startsWith(`${e}=`))}function Fg(){let t;try{t=hr();}catch{return ei().catch(()=>new Map)}let e=Date.now();if(au===t&&Eo&&Eo.expiresAt>e)return Eo.result;au=t;let n=ei().catch(()=>new Map);return Eo={expiresAt:e+Hg,result:n},n}async function Bg(t){let e=await Qs(t),n=t.additionalArgs??[],r=ze(n,"--model")||ze(n,"-m");if(!t.model||!t.effort||r)return e;let o=(await Fg()).get(t.model);return !o||o.includes(t.effort)?e:(console.debug("[opencode] requested effort is not listed for this model; using OpenCode default"),{...e,effort:void 0})}function pu(t){let e=[],n=0,r=false,o=false,s=0;for(let c=0;c<t.length;c++){let d=t[c];if(o){o=false;continue}if(d==="\\"&&r){o=true;continue}if(d==='"'){r=!r;continue}if(!r){if(d==="{")n++;else if(d==="}"&&(n--,n===0)){let u=t.slice(s,c+1).trim();u&&e.push(u),s=c+1;}}}let i=t.slice(s).trim();return i&&e.push(i),e}function ie(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function _u(t){let e=ie(t.part)?t.part:void 0;return t.type==="reasoning"||e?.type==="reasoning"}function Wg(t){let e=ie(t.part)?t.part:void 0;return (typeof e?.text=="string"?e.text:typeof t.text=="string"?t.text:void 0)?.trim()||void 0}function Gg(t){let e=[],n=false;for(let r of t.split(/\r?\n/)){let o=r.trim();if(!o)continue;try{let i=JSON.parse(o);ie(i)?e.push(i):n=!0;continue}catch{}let s=pu(o);s.length>1&&console.warn("[opencode] extractText: falling back to concatenated-JSON split for a malformed line");for(let i of s)try{let c=JSON.parse(i);ie(c)?e.push(c):n=!0;}catch{n=true;}}return {events:e,malformed:n}}function si(t){let e=ie(t.error)?t.error:void 0,n=e&&ie(e.data)?e.data:void 0,r=fu(e),o=Ke(e?.name),s=Ke(n?.message)??Ke(e?.message)??ri(r)??Ke(t.message)??Ke(t.errorMessage)??Ke(t.error),i=Ke(t.ref),c=o&&s&&o!==s?`${o}: ${s}`:o??s??lu;return (i?`${c} (ref: ${i})`:c).slice(0,Mg)}function du(t){let e=ie(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),o=si(t),s=fu(e),i=s&&ie(s.error)?s.error:void 0,c=typeof i?.type=="string"?i.type:void 0,d=[o,ri(s)].filter(Boolean).join(`
84
- `);if(r===402||jg(d))return new W(`OpenCode subscription is required: ${o}`,He,{code:"SUBSCRIPTION_REQUIRED",kind:"config",providerReason:_r(o)});if(r===403&&(c==="RegionError"||c==="FreeTierError"))return new W(`OpenCode account settings are required: ${o}`,He,{code:"ACCOUNT_SETTING_REQUIRED",kind:"config",settingReason:"access",providerReason:_r(o)});if(n==="provider.auth"||r===401||r===403)return new W(`OpenCode authentication is required: ${o}`,He,{code:"AUTH_REQUIRED",kind:"config"});if(r===410||c==="ModelDeprecated")return new W(`OpenCode model has been retired: ${o}`,He,{code:"MODEL_RETIRED",kind:"config",replacementModel:Kg(s,e,t),providerReason:_r(o)});if(n==="provider.free-limit"||r===429){let u=zg(e);return new W(`OpenCode rate limit reached: ${o}`,He,{code:"RATE_LIMITED",kind:"transient",...u===void 0?{}:{retryAfterMs:u}})}if(n==="provider.no-route")return new W(`OpenCode model or variant unavailable: ${o}`,He,{code:"MODEL_UNAVAILABLE",kind:"config"});if(n==="provider.invalid-request"&&r===400){let u=[o,ri(s)].filter(h=>h!==void 0),l=u.find(h=>/requires global regions/i.test(h)),p=u.find(h=>/trains on request data/i.test(h)),_=l?"region":p?"training_consent":void 0;if(_)return new W(`OpenCode account settings are required: ${o}`,He,{code:"ACCOUNT_SETTING_REQUIRED",kind:"config",settingReason:_,providerReason:_r(l??p)})}return new W(`OpenCode error: ${o}`,He,{code:"PROVIDER_CRASHED",kind:"transient"})}function fu(t){let n=(t&&ie(t.response)?t.response:void 0)?.body;if(ie(n))return n;if(typeof n=="string")try{let r=JSON.parse(n);return ie(r)?r:void 0}catch{return}}function ri(t){let e=t&&ie(t.error)?t.error:void 0;return Ke(e?.message)??Ke(t?.message)}function jg(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 Kg(t,e,n){let r=t&&ie(t.metadata)?t.metadata:void 0,o=typeof r?.replacement=="string"?r.replacement.trim():void 0;if(!o)return;let s=[r?.model,e?.model,n.model,n.modelID].find(d=>typeof d=="string"&&d.trim().length>0)?.trim(),i=s&&s.includes("/")?s.slice(0,s.indexOf("/")):"opencode-go",c=o.includes("/")?o:`${i}/${o}`;return /^[A-Za-z0-9._/-]{1,128}$/.test(c)?c:void 0}function zg(t){let e=t?.retryAfterMs;if(typeof e=="number"&&Number.isFinite(e)&&e>=0)return e;let r=(t&&ie(t.response)?t.response:void 0)?.body,o=typeof r=="string"?Jg(r):ie(r)?r:void 0;if(o){let s=oi(o);if(s)return cu(s.value,s.key==="retryafterms")}if(typeof r=="string"){let s=r.match(/retry[-_]after(?:\s*[:=]\s*|\s+)["']?([^"'\s,;}]+)/i);if(s?.[1])return cu(s[1],false)}}function Jg(t){try{let e=JSON.parse(t);return ie(e)?e:void 0}catch{return}}function oi(t){if(Array.isArray(t)){for(let e of t){let n=oi(e);if(n)return n}return}if(ie(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=oi(e);if(n)return n}}}function cu(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 uu(t){let e=Gg(t),n=[],r=null,o=0,s=[],i=[],c,d=false;for(let u of e.events){if(_u(u))continue;let l=typeof u.type=="string"?u.type:void 0;if(l){if(l==="text"){let p=ie(u.part)?u.part:void 0,_=typeof p?.text=="string"?p.text:void 0;_?.trim()&&n.push(_.trim());continue}if(l==="result"){typeof u.result=="string"&&(r=u.result);continue}if(l==="tool_use"){o++;continue}if(l==="error"){s.push(u),i.push(si(u));continue}if(l==="step_finish"){d=true;let p=ie(u.part)?u.part:void 0;c=typeof p?.reason=="string"?p.reason:void 0;}}}return {...e,texts:n,resultText:r,toolUseCount:o,errorEvents:s,errorMessages:i,terminalReason:c,hasTerminal:d}}function gu(t){return (t??"unknown").trim().toLowerCase().replace(/_/g,"-")}function Vg(){return new W("OpenCode returned no assistant output.",He,{code:"EMPTY_OUTPUT",kind:"transient"})}function Xg(){return new W("OpenCode emitted malformed JSON output.",He,{code:"PROVIDER_CRASHED",kind:"transient"})}function Yg(t,e){switch(gu(t)){case "length":return new W("OpenCode stopped because the context window was exceeded.",He,{code:"UNKNOWN",kind:"permanent"});case "content-filter":return new W("OpenCode stopped because the content filter blocked the response.",He,{code:"UNKNOWN",kind:"permanent"});case "error":return new W(`${lu} while generating a response.`,He,{code:"PROVIDER_CRASHED",kind:"transient"});default:return null}}var Lg,He,lu,Mg,$g,Hg,au,Eo,Ug,ii,ai=C(()=>{g();$t();Xc();pr();Nn();sn();iu();Zs();Lg=new Set(["step_start","step_finish"]),He="cli/opencode",lu="OpenCode provider error",Mg=240,$g="Follow the instructions provided on standard input.",Hg=3e5,Ug={build:{agent:"build",autoApprove:false},"build-auto":{agent:"build",autoApprove:true},plan:{agent:"plan",autoApprove:false},"plan-auto":{agent:"plan",autoApprove:true}};ii={command:"opencode",prepare:Bg,meta:{displayName:"OpenCode",capabilities:{resume:true}},buildArgs(t,e,n){let r=e.additionalArgs,o=r!==void 0?[...r]:["run"];ze(o,"--format")||o.push("--format","json"),ze(o,"--thinking")||o.push("--thinking"),!ze(o,"--standalone")&&!ze(o,"--server")&&o.push("--standalone"),e.resumeSessionId&&!ze(o,"-s")&&!ze(o,"--session")&&o.push("-s",e.resumeSessionId);let{agent:s,autoApprove:i}=qg(e.mode);ze(o,"--agent")||s!==void 0&&o.push("--agent",s),i&&!ze(o,"--auto")&&o.push("--auto");let c=ze(o,"--model")||ze(o,"-m");if(e.model&&!c){let d=e.effort?`${e.model}#${e.effort}`:e.model;o.push("--model",d);}else e.effort&&!e.model&&!c&&console.debug("[opencode] ignoring effort because no model is configured");return o.push($g),{args:o,stdinMessage:t,env:gr()}},extractText(t){let e=uu(t),n=e.errorEvents[0];if(n)throw du(n);let r=Yg(e.terminalReason??"");if(r)throw r;let o=e.texts.length>0?e.texts[e.texts.length-1]:void 0;if(o!==void 0)return o;if(e.resultText?.trim())return e.resultText;if(e.malformed)throw Xg();let s=gu(e.terminalReason);if(e.hasTerminal&&s==="tool-calls"&&e.toolUseCount>0)return "";throw Vg()},interpretExit(t,e,n=""){if(t===0)return null;let o=uu(n).errorEvents[0];return o?du(o):null},parseResultMeta(t){let e=vn(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(),o=[],s=new Map,i;try{JSON.parse(t),i=[t];}catch{i=pu(t),i.length>1&&console.warn("[opencode] parseEvent: falling back to concatenated-JSON split for a malformed line");}for(let c of i){let d;try{d=JSON.parse(c);}catch{continue}let u=nt(d,r),l=d.type;if(_u(d)){let p=Wg(d);if(!p)continue;let _=ie(d.part)?d.part:void 0,h=typeof _?.id=="string"?_.id:typeof d.id=="string"?d.id:void 0,m=p;if(h){let k=`opencode.reasoning:${h}`,E=n?.state.get(k),b=typeof E=="string"?E:s.get(h);if(typeof b=="string"&&(b===p||b.startsWith(p))||typeof b=="string"&&p.startsWith(b)&&(m=p.slice(b.length).trim(),!m))continue;s.set(h,p),n?.state.set(k,p);}o.push({timestamp:u,type:"thinking",content:m});continue}if(l){if(l==="text"){let _=d.part?.text;_&&o.push({timestamp:u,type:"text",content:_});continue}if(l==="tool_use"){let p=d.part;if(!p)continue;let _=String(p.tool||""),h=String(p.callID||p.id||""),m=p.state,k=String(m?.status||""),E=m?.input,b=tt(E);if(o.push({timestamp:u,type:"tool_use",toolName:_,toolUseId:h,toolInput:b}),k==="completed"&&m?.output!==void 0){let T=m.output,P=typeof T=="string"?T:JSON.stringify(T);o.push({timestamp:u,type:"tool_result",toolUseId:h,resultPreview:P,isError:false});}else k==="error"&&o.push({timestamp:u,type:"tool_result",toolUseId:h,resultPreview:String(m?.error||"tool error"),isError:true});continue}if(l==="error"){let p=si(d);o.push({timestamp:u,type:"error",content:p,errorMessage:p});continue}}}return o},suppressOutputLine(t){let e=t.trim();if(!e.startsWith("{")||!e.endsWith("}"))return false;try{let r=JSON.parse(e).type;return r?Lg.has(r):!1}catch{return false}}};});var hu=C(()=>{g();});function xn(t,e){return t.some(n=>n===e||n.startsWith(`${e}=`))}function nh(t,e){return t&&mu.has(t)||xn(e,"--dangerously-skip-permissions")?true:e.some((n,r)=>{let o=n==="--mode"?e[r+1]:n.startsWith("--mode=")?n.slice(7):void 0;return typeof o=="string"&&mu.has(o)})}function rh(t,e){let n=[];for(let r=0;r<t.length;r+=1){let o=t[r],s=[...e].find(i=>o===i||o.startsWith(`${i}=`));s?o===s&&r+1<t.length&&(r+=1):n.push(o);}return n}function oh(t){let e=[];for(let n=0;n<t.length;n+=1){let r=t[n],o=r.indexOf("="),s=o>0?r.slice(0,o):r;if(!eh.has(s)){e.push(r);continue}r===s&&n+1<t.length&&!t[n+1].startsWith("-")&&(n+=1);}return e}function Je(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function sh(t,e){if(!(t?Zg.has(t)||It(di).some(s=>s.id===t):false)||!t)return e;let r=On(di,t),o=Bs(di)[t]?.defaultEffort;if(r.length!==0)return e?r.includes(e)?e:o&&r.includes(o)?o:void 0:o}function At(t){return typeof t=="number"&&Number.isSafeInteger(t)&&t>=0?t:void 0}function li(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 pi(t){return t.step.step_index}function se(t){if(typeof t!="string")return;let e=t.split(/\r?\n/,1)[0]?.trim();return e&&po(e)?.slice(0,500).trim()||void 0}function ih(t,e){let n=(t??"").trim().toUpperCase().replace(/[^A-Z0-9]+/g,"_");if(n!=="UNKNOWN"&&th.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(s=>s.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 ah(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=Je(t)?t:void 0,n=e&&Je(e.error)?e.error:void 0,r=e?se(e.code)??se(e.error_code)??se(n?.code)??se(n?.error_code):void 0,o=typeof t=="string"?se(t):e?se(e.message)??se(e.error)??se(e.reason)??se(n?.message)??se(n?.error)??se(n?.reason):void 0,s=ih(r,o),i=e?At(e.retry_after_ms)??At(e.retryAfterMs)??At(n?.retry_after_ms)??At(n?.retryAfterMs):void 0;return {code:s,kind:ah(s),message:o??"Antigravity reported a terminal error.",...i===void 0?{}:{retryAfterMs:i}}}function So(t){let e=Tu(t);return new W(e.message,"cli/antigravity",{code:e.code,kind:e.kind,...e.retryAfterMs===void 0?{}:{retryAfterMs:e.retryAfterMs}})}function _i(t){return new W(t,"cli/antigravity",{code:"INVALID_PROVIDER_FORMAT",kind:"config"})}function dh(t){let e=new TextEncoder().encode(t).byteLength;if(!(e<=ui))throw new W(`Input is too large: final provider initial input is ${e} UTF-8 bytes; budget is ${ui} bytes.`,"cli/antigravity",{code:"UNKNOWN",kind:"config"})}function ci(){return new W("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 Io(t){if(t.kind==="result"||t.kind==="legacy_result")return t.result}function Ao(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 ch(t){let e=Ao(t);if(!e||e.event.kind==="agy_error"||e.index!==t.length-1||Io(e.event)?.status!=="SUCCESS"||Ro(t))return false;let r=new Map;for(let o of t){if(o.kind!=="step_update"||o.step.step_type!=="agent_response")continue;let s=li(o),i=pi(o);!s||!Number.isSafeInteger(i)||r.set(JSON.stringify([s,i]),o.step);}if(r.size===0)return false;for(let o of r.values())if(o.state!=="DONE"||!Je(o.usage)||At(o.usage.input_tokens)===void 0||At(o.usage.output_tokens)===void 0)return false;return true}function uh(t,e){for(let n=e-1;n>=0;n-=1){let r=t[n];if(r?.kind==="agy_error")return r.error}}function lh(t,e){return Je(t)&&Je(e)?{...e,...t}:Je(t)&&typeof e=="string"?{...t,message:e}:typeof t=="string"&&Je(e)?{...e,message:t}:t??e}function ph(t){let e=Array.isArray(t.denied_actions)?t.denied_actions:[],n=[];for(let i of e){let c=Je(i)?i:void 0,d=typeof i=="string"?se(i):se(c?.display_name)??se(c?.action);d&&!n.includes(d)&&n.length<5&&n.push(d.slice(0,80));}let r=Math.max(0,e.length-n.length),o=n.length>0?` (${n.join(", ")}${r>0?`, +${r} more`:""})`:"",s=`Permission denied: Antigravity blocked ${e.length} requested action${e.length===1?"":"s"}${o}.`;return new W("\uAD8C\uD55C \uB54C\uBB38\uC5D0 \uC2E4\uD589\uD558\uC9C0 \uBABB\uD588\uC5B4\uC694","cli/antigravity",{code:"UNKNOWN",kind:"permanent",providerReason:s})}function Ro(t){let e=Ao(t);if(!e)return;if(e.event.kind==="agy_error")return So(e.event.error);let n=Io(e.event);if(!n)return;if(Array.isArray(n.denied_actions)&&n.denied_actions.length>0)return ph(n);if(n.status==="SUCCESS")return;if(n.status!=="ERROR")return _i("Antigravity returned a result with an unsupported status.");let r=n.error,o=lh(r==null||r===""?n:r,uh(t,e.index));return So(o)}function wu(t){if(typeof t=="string")return t;if(t!=null)try{return JSON.stringify(t)}catch{return}}function _h(t){return `agy:${String(t.conversation_id)}:${String(t.step_index)}`}function fh(t,e){let n=typeof e?.name=="string"?e.name:t.tool_name;return typeof n=="string"&&n.trim()?n:void 0}function Eu(t){let e=wu(t);if(e)return e.length<=2e3?e:`${e.slice(0,1999)}\u2026`}function gh(t){let e=Je(t)?t:void 0,n=e&&Je(e.error)?e.error:void 0,r=typeof t=="string"?t.trim().match(/^([A-Z][A-Z0-9_]*)(?:[:\s]|$)/)?.[1]:void 0,o=(se(e?.type)??se(e?.code)??se(e?.error_type)??se(n?.type)??se(n?.code)??se(n?.error_type)??se(r)??"TOOL_ERROR").slice(0,60),s=Tu(t).message.slice(0,250);return Eu({type:o,message:s})??"Antigravity reported a tool error."}function ku(t,e){return t?t.state.has(e)?true:(t.state.set(e,true),false):false}function yu(t,e){return {timestamp:t,type:"error",content:e.message,errorMessage:e.message,isError:true}}var di,Zg,eh,mu,ui,th,fi,gi=C(()=>{g();$t();hu();bs();cr();Ht();lr();$s();Ws();di="antigravity",Zg=new Set(["claude-sonnet-4-6","claude-opus-4-6-thinking","gpt-oss-120b"]),eh=new Set(["--conversation","--resume","--continue"]),mu=new Set(["bypassPermissions","agent-full-access","yolo"]),ui=18e4,th=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"]);fi={command:"agy",maxInitialInputBytes:ui,meta:{displayName:"Antigravity",models:kc(),defaultIdleMs:6e5,capabilities:{resume:true,usageCompleteness:true}},extractSessionId(t){let e=ar(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){dh(t);let{model:r,effort:o}=Ut(e.model),s=qs(r),i=s.model,c=e.effort??o??s.effort,d=sh(i,c),u=e.additionalArgs??[],l=oh(rh(u,new Set(["--input-format","--output-format"]))),p=i&&!xn(u,"--model")?["--model",i]:[],_=xn(u,"--effort")?[]:xc(d),h=xn(u,"--mode")||xn(u,"--dangerously-skip-permissions")?[]:Cc(e.mode),m=nh(e.mode,u)||xn(u,"--settings")?[]:["--settings",JSON.stringify({permissions:{allow:$c(e.builtinAllow)}})],k=typeof e.resumeSessionId=="string"&&e.resumeSessionId.trim().length>0?["--conversation",e.resumeSessionId]:[];return {args:["--input-format","stream-json","--output-format","stream-json",...p,..._,...h,...k,...m,...l],stdinMessage:`${JSON.stringify({event:"user",message:{content:t}})}
85
- `,env:{AGY_CLI_DISABLE_AUTO_UPDATE:"true"}}},extractText(t){let e=dr(t),n=Ao(e)?.event,r=Ro(e);if(r)throw r;let o=n?Io(n):void 0;if(o){if(o.status!=="SUCCESS")throw _i("Antigravity returned a result with an unsupported status.");if(typeof o.response!="string")throw _i("Antigravity returned a successful result without a response string.");if(!o.response.trim())throw ci();return o.response}if(e.length>0)throw ci();let s=t.trim();if(!s)throw ci();return s},extractPartialText(t){let e=dr(t),n=Ao(e)?.event;if(!n||n.kind==="agy_error")return;let r=Io(n);return r&&typeof r.response=="string"&&r.response.trim()?r.response:void 0},interpretExit(t,e,n){let r=dr(n??""),o=Ro(r);return o||(t!==0&&e.trim()?So(e):null)},parseResultMeta(t){let e=dr(t),n=0,r=0,o=0,s=0,i=new Set;for(let d of e){if(d.kind!=="step_update"||d.step.state!=="DONE"||!Je(d.step.usage))continue;let u=li(d),l=pi(d);if(!u||!Number.isSafeInteger(l))continue;let p=JSON.stringify([u,l]);if(i.has(p))continue;let _=d.step.usage,h=At(_.input_tokens),m=At(_.output_tokens);if(h===void 0||m===void 0)continue;i.add(p);let k=At(_.cache_read_tokens)??0;n+=h+k,r+=m,o+=k,s+=1;}return {usage:s===0?null:{inputTokens:n,outputTokens:r,cachedInputTokens:o,costUsd:0,complete:ch(e)},model:null}},parseEvent(t,e,n){let r=ar(t);if(!r)return [];let o=e??new Date().toISOString();if(r.kind==="agy_error")return [yu(o,So(r.error))];if(r.kind==="legacy_result"||r.kind==="result"){let h=Ro([r]);return h?[yu(o,h)]:[]}if(r.kind!=="step_update")return [];let{step:s}=r,i=li(r)??"unknown",c=pi(r),d=`${i}:${c}`;if((s.state==="DONE"||s.state==="ERROR")&&ku(n,`antigravity:terminal:${d}`))return [];if(s.step_type==="agent_response")return typeof s.text_delta=="string"&&s.text_delta.length>0?[{timestamp:o,type:"text",content:s.text_delta}]:[];if(s.step_type!=="tool")return [];let u=Je(s.tool_info)?s.tool_info:void 0,l=fh(s,u);if(!l)return [];let p=_h(s);if(s.state==="ACTIVE"){if(ku(n,`antigravity:active:${d}`))return [];let h=wu(u?.parameters);return [{timestamp:o,type:"tool_use",toolName:l,toolUseId:p,...h===void 0?{}:{toolInput:h}}]}let _=s.state==="ERROR"?gh(u?.error):Eu(u?.output);return [{timestamp:o,type:"tool_result",toolName:l,toolUseId:p,..._===void 0?{}:{resultPreview:_},...s.state==="ERROR"?{isError:true}:{}}]}};});var Ru=C(()=>{g();In();Nn();An();sn();});function bn(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Dn(t){return bn(t)?t:void 0}function be(t){return typeof t=="string"?t:void 0}function un(t){let e=typeof t=="number"?t:Number(t??0);return Number.isFinite(e)?e:0}function Sh(t){let e=[],n=-1,r=0,o=false,s=false;for(let i=0;i<t.length;i+=1){let c=t[i];if(n===-1){(c==="{"||c==="[")&&(n=i,r=1);continue}if(s){s=false;continue}if(c==="\\"&&o){s=true;continue}if(c==='"'){o=!o;continue}o||(c==="{"||c==="["?r+=1:(c==="}"||c==="]")&&(r-=1,r===0&&(e.push(t.slice(n,i+1)),n=-1)));}return n!==-1&&e.push(t.slice(n)),e}function mr(t){let e=t.trim();if(!e)return [];try{let n=JSON.parse(e);return bn(n)?[n]:[]}catch{return Sh(e).flatMap(n=>{try{let r=JSON.parse(n);return bn(r)?[r]:[]}catch{return []}})}}function Cu(t){let e=JSON.stringify(t);return e===void 0?String(t):e}function cn(t){if(typeof t=="string")return t;if(Array.isArray(t)){let e=t.map(cn).filter(n=>n!==void 0);return e.length>0?e.join(`
86
- `):void 0}if(bn(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=cn(t[e]);if(n!==void 0)return n}}}function Ih(t){let e=i=>Array.isArray(i)&&i.every(c=>Number.isInteger(c)&&c>=0&&c<=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)),o=i=>{let c=JSON.stringify(i,(d,u)=>e(u)?`<bytes:${u.length}>`:u);return c===void 0?String(i):c},s=t.rawOutput;if(s!=null){let i=Dn(s);if(!i)return n(cn(s))??o(s);let c;if(e(i.output)&&i.output.length>0&&(c=n(r(i.output))),!c&&e(i.stdout)&&i.stdout.length>0&&(c=n(r(i.stdout))),!c){let l=Dn(i.Result);c=n(i.output)??n(l?.output)??n(cn(s));}let d=e(i.stderr)&&i.stderr.length>0?r(i.stderr):void 0;if(d!==void 0)if(c){let l=c.endsWith(`
83
+ `);r.transaction(i=>{for(let c of i)o.run(c);})(n);}finally{r.close();}}function uh(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 o=t[n+1],s=o!==void 0&&!o.startsWith("-");e.push({sessionId:s?o:void 0}),s&&(n+=1);continue}(r.startsWith("--session=")||r.startsWith("-s="))&&e.push({sessionId:r.slice(r.indexOf("=")+1)||void 0});}return e}function lh(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 Do(t){let e=lh(t.additionalArgs);return {...t,...e===void 0?{}:{additionalArgs:e},resumeSessionId:void 0}}function ph(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 _h(t,e,n){let r=new t(e,{readonly:true,fileMustExist:true});try{return ph(r,n)}finally{r.close();}}async function fi(t,e={}){let n;try{n=await(e.loadSqlite??rh)();}catch{throw new W("OpenCode isolation requires the optional better-sqlite3 dependency. Install it and retry.","cli/opencode",{code:"INVALID_PROVIDER_FORMAT",kind:"config"})}let r=e.crewxHome??xo(),o=vr(r),s=br(r),i=oh(s),c=sh(e.userDataHome),d=ah(n,c);if(d.length>0){if(!Nu(n,i))try{await(e.initializeDatabase??dh)(o);}catch{throw new W("Could not initialize the isolated OpenCode credential database.","cli/opencode",{code:"INVALID_PROVIDER_FORMAT",kind:"config"})}if(!Nu(n,i))throw new W("The isolated OpenCode credential database is unavailable.","cli/opencode",{code:"INVALID_PROVIDER_FORMAT",kind:"config"});try{ch(n,i,d);}catch{throw new W("Could not copy API-key credentials into the isolated OpenCode database.","cli/opencode",{code:"INVALID_PROVIDER_FORMAT",kind:"config"})}}let u=uh(t.additionalArgs),l=u.map(_=>_.sessionId),p=u.length>0?l[l.length-1]:t.resumeSessionId;if(!p)return u.length>0?Do(t):t;if(l.some(_=>_!==p)||!Iu.existsSync(i))return Do(t);try{return _h(n,i,p)?{...t,resumeSessionId:p}:Do(t)}catch{throw new W("Could not read the isolated OpenCode session database safely.","cli/opencode",{code:"INVALID_PROVIDER_FORMAT",kind:"config"})}}var gi=b(()=>{g();Vt();pi();Au();});function kn(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}async function hi(){let t;try{let n=(await import('better-sqlite3')).default,r=Ne.join(br(),"opencode.db");t=new n(r,{readonly:!0,fileMustExist:!0});let o=t.prepare("SELECT value FROM kv WHERE key = ?").get("models-dev:v2:catalog");if(!o||typeof o.value!="string")throw new Error("OpenCode model catalog row is unavailable");let s=JSON.parse(o.value);if(!kn(s))throw new Error("OpenCode model catalog shape is unavailable");let i=typeof s.body=="string"?JSON.parse(s.body):s.body;if(!kn(i))throw new Error("OpenCode model catalog body shape is unavailable");let c=new Map;for(let[d,u]of Object.entries(i)){if(!d||!kn(u)||!kn(u.models))throw new Error("OpenCode model provider shape is unavailable");for(let[l,p]of Object.entries(u.models)){if(!l||!kn(p))throw new Error("OpenCode model shape is unavailable");let _=p.capabilities;if(_===void 0)continue;if(!kn(_))throw new Error("OpenCode model capability shape is unavailable");let h=_.reasoning;if(h===void 0)continue;if(!kn(h))throw new Error("OpenCode reasoning capability shape is unavailable");let m=h.effort;(m===void 0||Array.isArray(m)&&m.every(k=>typeof k=="string"))&&c.set(`${d}/${l}`,Array.isArray(m)?m:[]);}}return c}catch{return console.debug("[opencode] could not read private model effort catalog; omitting effort choices"),new Map}finally{try{t?.close();}catch{}}}var vu=b(()=>{g();ki();Tu();Ru();pi();gi();Xt();});function Th(t){return t?yh[t]??{agent:"build",autoApprove:false}:{agent:void 0,autoApprove:false}}function Ye(t,e){return t.some(n=>n===e||n.startsWith(`${e}=`))}function wh(){let t;try{t=br();}catch{return hi().catch(()=>new Map)}let e=Date.now();if(bu===t&&Po&&Po.expiresAt>e)return Po.result;bu=t;let n=hi().catch(()=>new Map);return Po={expiresAt:e+kh,result:n},n}async function Eh(t){let e=await fi(t),n=t.additionalArgs??[],r=Ye(n,"--model")||Ye(n,"-m");if(!t.model||!t.effort||r)return e;let o=(await wh()).get(t.model);return !o||o.includes(t.effort)?e:(console.debug("[opencode] requested effort is not listed for this model; using OpenCode default"),{...e,effort:void 0})}function Lu(t){let e=[],n=0,r=false,o=false,s=0;for(let c=0;c<t.length;c++){let d=t[c];if(o){o=false;continue}if(d==="\\"&&r){o=true;continue}if(d==='"'){r=!r;continue}if(!r){if(d==="{")n++;else if(d==="}"&&(n--,n===0)){let u=t.slice(s,c+1).trim();u&&e.push(u),s=c+1;}}}let i=t.slice(s).trim();return i&&e.push(i),e}function de(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Mu(t){let e=de(t.part)?t.part:void 0;return t.type==="reasoning"||e?.type==="reasoning"}function Rh(t){let e=de(t.part)?t.part:void 0;return (typeof e?.text=="string"?e.text:typeof t.text=="string"?t.text:void 0)?.trim()||void 0}function Sh(t){let e=[],n=false;for(let r of t.split(/\r?\n/)){let o=r.trim();if(!o)continue;try{let i=JSON.parse(o);de(i)?e.push(i):n=!0;continue}catch{}let s=Lu(o);s.length>1&&console.warn("[opencode] extractText: falling back to concatenated-JSON split for a malformed line");for(let i of s)try{let c=JSON.parse(i);de(c)?e.push(c):n=!0;}catch{n=true;}}return {events:e,malformed:n}}function wi(t){let e=de(t.error)?t.error:void 0,n=e&&de(e.data)?e.data:void 0,r=$u(e),o=Xe(e?.name),s=Xe(n?.message)??Xe(e?.message)??yi(r)??Xe(t.message)??Xe(t.errorMessage)??Xe(t.error),i=Xe(t.ref),c=o&&s&&o!==s?`${o}: ${s}`:o??s??Pu;return (i?`${c} (ref: ${i})`:c).slice(0,hh)}function Cu(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),o=wi(t),s=$u(e),i=s&&de(s.error)?s.error:void 0,c=typeof i?.type=="string"?i.type:void 0,d=[o,yi(s)].filter(Boolean).join(`
84
+ `);if(r===402||Ih(d))return new W(`OpenCode subscription is required: ${o}`,Ge,{code:"SUBSCRIPTION_REQUIRED",kind:"config",providerReason:Nr(o)});if(r===403&&(c==="RegionError"||c==="FreeTierError"))return new W(`OpenCode account settings are required: ${o}`,Ge,{code:"ACCOUNT_SETTING_REQUIRED",kind:"config",settingReason:"access",providerReason:Nr(o)});if(n==="provider.auth"||r===401||r===403)return new W(`OpenCode authentication is required: ${o}`,Ge,{code:"AUTH_REQUIRED",kind:"config"});if(r===410||c==="ModelDeprecated")return new W(`OpenCode model has been retired: ${o}`,Ge,{code:"MODEL_RETIRED",kind:"config",replacementModel:Ah(s,e,t),providerReason:Nr(o)});if(n==="provider.free-limit"||r===429){let u=Nh(e);return new W(`OpenCode rate limit reached: ${o}`,Ge,{code:"RATE_LIMITED",kind:"transient",...u===void 0?{}:{retryAfterMs:u}})}if(n==="provider.no-route")return new W(`OpenCode model or variant unavailable: ${o}`,Ge,{code:"MODEL_UNAVAILABLE",kind:"config"});if(n==="provider.invalid-request"&&r===400){let u=[o,yi(s)].filter(h=>h!==void 0),l=u.find(h=>/requires global regions/i.test(h)),p=u.find(h=>/trains on request data/i.test(h)),_=l?"region":p?"training_consent":void 0;if(_)return new W(`OpenCode account settings are required: ${o}`,Ge,{code:"ACCOUNT_SETTING_REQUIRED",kind:"config",settingReason:_,providerReason:Nr(l??p)})}return new W(`OpenCode error: ${o}`,Ge,{code:"PROVIDER_CRASHED",kind:"transient"})}function $u(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 yi(t){let e=t&&de(t.error)?t.error:void 0;return Xe(e?.message)??Xe(t?.message)}function Ih(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 Ah(t,e,n){let r=t&&de(t.metadata)?t.metadata:void 0,o=typeof r?.replacement=="string"?r.replacement.trim():void 0;if(!o)return;let s=[r?.model,e?.model,n.model,n.modelID].find(d=>typeof d=="string"&&d.trim().length>0)?.trim(),i=s&&s.includes("/")?s.slice(0,s.indexOf("/")):"opencode-go",c=o.includes("/")?o:`${i}/${o}`;return /^[A-Za-z0-9._/-]{1,128}$/.test(c)?c:void 0}function Nh(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,o=typeof r=="string"?Oh(r):de(r)?r:void 0;if(o){let s=Ti(o);if(s)return xu(s.value,s.key==="retryafterms")}if(typeof r=="string"){let s=r.match(/retry[-_]after(?:\s*[:=]\s*|\s+)["']?([^"'\s,;}]+)/i);if(s?.[1])return xu(s[1],false)}}function Oh(t){try{let e=JSON.parse(t);return de(e)?e:void 0}catch{return}}function Ti(t){if(Array.isArray(t)){for(let e of t){let n=Ti(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=Ti(e);if(n)return n}}}function xu(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 Du(t){let e=Sh(t),n=[],r=null,o=0,s=[],i=[],c,d=false;for(let u of e.events){if(Mu(u))continue;let l=typeof u.type=="string"?u.type:void 0;if(l){if(l==="text"){let p=de(u.part)?u.part:void 0,_=typeof p?.text=="string"?p.text:void 0;_?.trim()&&n.push(_.trim());continue}if(l==="result"){typeof u.result=="string"&&(r=u.result);continue}if(l==="tool_use"){o++;continue}if(l==="error"){s.push(u),i.push(wi(u));continue}if(l==="step_finish"){d=true;let p=de(u.part)?u.part:void 0;c=typeof p?.reason=="string"?p.reason:void 0;}}}return {...e,texts:n,resultText:r,toolUseCount:o,errorEvents:s,errorMessages:i,terminalReason:c,hasTerminal:d}}function Hu(t){return (t??"unknown").trim().toLowerCase().replace(/_/g,"-")}function vh(){return new W("OpenCode returned no assistant output.",Ge,{code:"EMPTY_OUTPUT",kind:"transient"})}function bh(){return new W("OpenCode emitted malformed JSON output.",Ge,{code:"PROVIDER_CRASHED",kind:"transient"})}function Ch(t,e){switch(Hu(t)){case "length":return new W("OpenCode stopped because the context window was exceeded.",Ge,{code:"UNKNOWN",kind:"permanent"});case "content-filter":return new W("OpenCode stopped because the content filter blocked the response.",Ge,{code:"UNKNOWN",kind:"permanent"});case "error":return new W(`${Pu} while generating a response.`,Ge,{code:"PROVIDER_CRASHED",kind:"transient"});default:return null}}var gh,Ge,Pu,hh,mh,kh,bu,Po,yh,Ei,Ri=b(()=>{g();Vt();yu();Ar();qn();hn();vu();gi();gh=new Set(["step_start","step_finish"]),Ge="cli/opencode",Pu="OpenCode provider error",hh=240,mh="Follow the instructions provided on standard input.",kh=3e5,yh={build:{agent:"build",autoApprove:false},"build-auto":{agent:"build",autoApprove:true},plan:{agent:"plan",autoApprove:false},"plan-auto":{agent:"plan",autoApprove:true}};Ei={command:"opencode",prepare:Eh,meta:{displayName:"OpenCode",capabilities:{resume:true}},buildArgs(t,e,n){let r=e.additionalArgs,o=r!==void 0?[...r]:["run"];Ye(o,"--format")||o.push("--format","json"),Ye(o,"--thinking")||o.push("--thinking"),!Ye(o,"--standalone")&&!Ye(o,"--server")&&o.push("--standalone"),e.resumeSessionId&&!Ye(o,"-s")&&!Ye(o,"--session")&&o.push("-s",e.resumeSessionId);let{agent:s,autoApprove:i}=Th(e.mode);Ye(o,"--agent")||s!==void 0&&o.push("--agent",s),i&&!Ye(o,"--auto")&&o.push("--auto");let c=Ye(o,"--model")||Ye(o,"-m");if(e.model&&!c){let d=e.effort?`${e.model}#${e.effort}`:e.model;o.push("--model",d);}else e.effort&&!e.model&&!c&&console.debug("[opencode] ignoring effort because no model is configured");return o.push(mh),{args:o,stdinMessage:t,env:vr()}},extractText(t){let e=Du(t),n=e.errorEvents[0];if(n)throw Cu(n);let r=Ch(e.terminalReason??"");if(r)throw r;let o=e.texts.length>0?e.texts[e.texts.length-1]:void 0;if(o!==void 0)return o;if(e.resultText?.trim())return e.resultText;if(e.malformed)throw bh();let s=Hu(e.terminalReason);if(e.hasTerminal&&s==="tool-calls"&&e.toolUseCount>0)return "";throw vh()},interpretExit(t,e,n=""){if(t===0)return null;let o=Du(n).errorEvents[0];return o?Cu(o):null},parseResultMeta(t){let e=Fn(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(),o=[],s=new Map,i;try{JSON.parse(t),i=[t];}catch{i=Lu(t),i.length>1&&console.warn("[opencode] parseEvent: falling back to concatenated-JSON split for a malformed line");}for(let c of i){let d;try{d=JSON.parse(c);}catch{continue}let u=it(d,r),l=d.type;if(Mu(d)){let p=Rh(d);if(!p)continue;let _=de(d.part)?d.part:void 0,h=typeof _?.id=="string"?_.id:typeof d.id=="string"?d.id:void 0,m=p;if(h){let k=`opencode.reasoning:${h}`,w=n?.state.get(k),C=typeof w=="string"?w:s.get(h);if(typeof C=="string"&&(C===p||C.startsWith(p))||typeof C=="string"&&p.startsWith(C)&&(m=p.slice(C.length).trim(),!m))continue;s.set(h,p),n?.state.set(k,p);}o.push({timestamp:u,type:"thinking",content:m});continue}if(l){if(l==="text"){let _=d.part?.text;_&&o.push({timestamp:u,type:"text",content:_});continue}if(l==="tool_use"){let p=d.part;if(!p)continue;let _=String(p.tool||""),h=String(p.callID||p.id||""),m=p.state,k=String(m?.status||""),w=m?.input,C=st(w);if(o.push({timestamp:u,type:"tool_use",toolName:_,toolUseId:h,toolInput:C}),k==="completed"&&m?.output!==void 0){let T=m.output,P=typeof T=="string"?T:JSON.stringify(T);o.push({timestamp:u,type:"tool_result",toolUseId:h,resultPreview:P,isError:false});}else k==="error"&&o.push({timestamp:u,type:"tool_result",toolUseId:h,resultPreview:String(m?.error||"tool error"),isError:true});continue}if(l==="error"){let p=wi(d);o.push({timestamp:u,type:"error",content:p,errorMessage:p});continue}}}return o},suppressOutputLine(t){let e=t.trim();if(!e.startsWith("{")||!e.endsWith("}"))return false;try{let r=JSON.parse(e).type;return r?gh.has(r):!1}catch{return false}}};});var Uu=b(()=>{g();});function Gn(t,e){return t.some(n=>n===e||n.startsWith(`${e}=`))}function Mh(t,e){return t&&qu.has(t)||Gn(e,"--dangerously-skip-permissions")?true:e.some((n,r)=>{let o=n==="--mode"?e[r+1]:n.startsWith("--mode=")?n.slice(7):void 0;return typeof o=="string"&&qu.has(o)})}function $h(t,e){let n=[];for(let r=0;r<t.length;r+=1){let o=t[r],s=[...e].find(i=>o===i||o.startsWith(`${i}=`));s?o===s&&r+1<t.length&&(r+=1):n.push(o);}return n}function Hh(t){let e=[];for(let n=0;n<t.length;n+=1){let r=t[n],o=r.indexOf("="),s=o>0?r.slice(0,o):r;if(!Ph.has(s)){e.push(r);continue}r===s&&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 Uh(t,e){if(!(t?Dh.has(t)||Dt(Si).some(s=>s.id===t):false)||!t)return e;let r=Bn(Si,t),o=oi(Si)[t]?.defaultEffort;if(r.length!==0)return e?r.includes(e)?e:o&&r.includes(o)?o:void 0:o}function Pt(t){return typeof t=="number"&&Number.isSafeInteger(t)&&t>=0?t:void 0}function Ni(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 Oi(t){return t.step.step_index}function ae(t){if(typeof t!="string")return;let e=t.split(/\r?\n/,1)[0]?.trim();return e&&So(e)?.slice(0,500).trim()||void 0}function qh(t,e){let n=(t??"").trim().toUpperCase().replace(/[^A-Z0-9]+/g,"_");if(n!=="UNKNOWN"&&Lh.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(s=>s.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 Bh(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 Wu(t){let e=Qe(t)?t:void 0,n=e&&Qe(e.error)?e.error:void 0,r=e?ae(e.code)??ae(e.error_code)??ae(n?.code)??ae(n?.error_code):void 0,o=typeof t=="string"?ae(t):e?ae(e.message)??ae(e.error)??ae(e.reason)??ae(n?.message)??ae(n?.error)??ae(n?.reason):void 0,s=qh(r,o),i=e?Pt(e.retry_after_ms)??Pt(e.retryAfterMs)??Pt(n?.retry_after_ms)??Pt(n?.retryAfterMs):void 0;return {code:s,kind:Bh(s),message:o??"Antigravity reported a terminal error.",...i===void 0?{}:{retryAfterMs:i}}}function Mo(t){let e=Wu(t);return new W(e.message,"cli/antigravity",{code:e.code,kind:e.kind,...e.retryAfterMs===void 0?{}:{retryAfterMs:e.retryAfterMs}})}function vi(t){return new W(t,"cli/antigravity",{code:"INVALID_PROVIDER_FORMAT",kind:"config"})}function Fh(t){let e=new TextEncoder().encode(t).byteLength;if(!(e<=Ai))throw new W(`Input is too large: final provider initial input is ${e} UTF-8 bytes; budget is ${Ai} bytes.`,"cli/antigravity",{code:"UNKNOWN",kind:"config"})}function Ii(){return new W("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 $o(t){if(t.kind==="result"||t.kind==="legacy_result")return t.result}function Ho(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 Wh(t){let e=Ho(t);if(!e||e.event.kind==="agy_error"||e.index!==t.length-1||$o(e.event)?.status!=="SUCCESS"||Lo(t))return false;let r=new Map;for(let o of t){if(o.kind!=="step_update"||o.step.step_type!=="agent_response")continue;let s=Ni(o),i=Oi(o);!s||!Number.isSafeInteger(i)||r.set(JSON.stringify([s,i]),o.step);}if(r.size===0)return false;for(let o of r.values())if(o.state!=="DONE"||!Qe(o.usage)||Pt(o.usage.input_tokens)===void 0||Pt(o.usage.output_tokens)===void 0)return false;return true}function Gh(t,e){for(let n=e-1;n>=0;n-=1){let r=t[n];if(r?.kind==="agy_error")return r.error}}function jh(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 zh(t){let e=Array.isArray(t.denied_actions)?t.denied_actions:[],n=[];for(let i of e){let c=Qe(i)?i:void 0,d=typeof i=="string"?ae(i):ae(c?.display_name)??ae(c?.action);d&&!n.includes(d)&&n.length<5&&n.push(d.slice(0,80));}let r=Math.max(0,e.length-n.length),o=n.length>0?` (${n.join(", ")}${r>0?`, +${r} more`:""})`:"",s=`Permission denied: Antigravity blocked ${e.length} requested action${e.length===1?"":"s"}${o}.`;return new W("\uAD8C\uD55C \uB54C\uBB38\uC5D0 \uC2E4\uD589\uD558\uC9C0 \uBABB\uD588\uC5B4\uC694","cli/antigravity",{code:"UNKNOWN",kind:"permanent",providerReason:s})}function Lo(t){let e=Ho(t);if(!e)return;if(e.event.kind==="agy_error")return Mo(e.event.error);let n=$o(e.event);if(!n)return;if(Array.isArray(n.denied_actions)&&n.denied_actions.length>0)return zh(n);if(n.status==="SUCCESS")return;if(n.status!=="ERROR")return vi("Antigravity returned a result with an unsupported status.");let r=n.error,o=jh(r==null||r===""?n:r,Gh(t,e.index));return Mo(o)}function Gu(t){if(typeof t=="string")return t;if(t!=null)try{return JSON.stringify(t)}catch{return}}function Kh(t){return `agy:${String(t.conversation_id)}:${String(t.step_index)}`}function Jh(t,e){let n=typeof e?.name=="string"?e.name:t.tool_name;return typeof n=="string"&&n.trim()?n:void 0}function ju(t){let e=Gu(t);if(e)return e.length<=2e3?e:`${e.slice(0,1999)}\u2026`}function Vh(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,o=(ae(e?.type)??ae(e?.code)??ae(e?.error_type)??ae(n?.type)??ae(n?.code)??ae(n?.error_type)??ae(r)??"TOOL_ERROR").slice(0,60),s=Wu(t).message.slice(0,250);return ju({type:o,message:s})??"Antigravity reported a tool error."}function Bu(t,e){return t?t.state.has(e)?true:(t.state.set(e,true),false):false}function Fu(t,e){return {timestamp:t,type:"error",content:e.message,errorMessage:e.message,isError:true}}var Si,Dh,Ph,qu,Ai,Lh,bi,Ci=b(()=>{g();Vt();Uu();Js();Rr();Xt();Ir();Zs();si();Si="antigravity",Dh=new Set(["claude-sonnet-4-6","claude-opus-4-6-thinking","gpt-oss-120b"]),Ph=new Set(["--conversation","--resume","--continue"]),qu=new Set(["bypassPermissions","agent-full-access","yolo"]),Ai=18e4,Lh=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"]);bi={command:"agy",maxInitialInputBytes:Ai,meta:{displayName:"Antigravity",models:Bc(),defaultIdleMs:6e5,capabilities:{resume:true,usageCompleteness:true}},extractSessionId(t){let e=wr(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){Fh(t);let{model:r,effort:o}=Yt(e.model),s=ni(r),i=s.model,c=e.effort??o??s.effort,d=Uh(i,c),u=e.additionalArgs??[],l=Hh($h(u,new Set(["--input-format","--output-format"]))),p=i&&!Gn(u,"--model")?["--model",i]:[],_=Gn(u,"--effort")?[]:eu(d),h=Gn(u,"--mode")||Gn(u,"--dangerously-skip-permissions")?[]:Zc(e.mode),m=Mh(e.mode,u)||Gn(u,"--settings")?[]:["--settings",JSON.stringify({permissions:{allow:iu(e.builtinAllow)}})],k=typeof e.resumeSessionId=="string"&&e.resumeSessionId.trim().length>0?["--conversation",e.resumeSessionId]:[];return {args:["--input-format","stream-json","--output-format","stream-json",...p,..._,...h,...k,...m,...l],stdinMessage:`${JSON.stringify({event:"user",message:{content:t}})}
85
+ `,env:{AGY_CLI_DISABLE_AUTO_UPDATE:"true"}}},extractText(t){let e=Er(t),n=Ho(e)?.event,r=Lo(e);if(r)throw r;let o=n?$o(n):void 0;if(o){if(o.status!=="SUCCESS")throw vi("Antigravity returned a result with an unsupported status.");if(typeof o.response!="string")throw vi("Antigravity returned a successful result without a response string.");if(!o.response.trim())throw Ii();return o.response}if(e.length>0)throw Ii();let s=t.trim();if(!s)throw Ii();return s},extractPartialText(t){let e=Er(t),n=Ho(e)?.event;if(!n||n.kind==="agy_error")return;let r=$o(n);return r&&typeof r.response=="string"&&r.response.trim()?r.response:void 0},interpretExit(t,e,n){let r=Er(n??""),o=Lo(r);return o||(t!==0&&e.trim()?Mo(e):null)},parseResultMeta(t){let e=Er(t),n=0,r=0,o=0,s=0,i=new Set;for(let d of e){if(d.kind!=="step_update"||d.step.state!=="DONE"||!Qe(d.step.usage))continue;let u=Ni(d),l=Oi(d);if(!u||!Number.isSafeInteger(l))continue;let p=JSON.stringify([u,l]);if(i.has(p))continue;let _=d.step.usage,h=Pt(_.input_tokens),m=Pt(_.output_tokens);if(h===void 0||m===void 0)continue;i.add(p);let k=Pt(_.cache_read_tokens)??0;n+=h+k,r+=m,o+=k,s+=1;}return {usage:s===0?null:{inputTokens:n,outputTokens:r,cachedInputTokens:o,costUsd:0,complete:Wh(e)},model:null}},parseEvent(t,e,n){let r=wr(t);if(!r)return [];let o=e??new Date().toISOString();if(r.kind==="agy_error")return [Fu(o,Mo(r.error))];if(r.kind==="legacy_result"||r.kind==="result"){let h=Lo([r]);return h?[Fu(o,h)]:[]}if(r.kind!=="step_update")return [];let{step:s}=r,i=Ni(r)??"unknown",c=Oi(r),d=`${i}:${c}`;if((s.state==="DONE"||s.state==="ERROR")&&Bu(n,`antigravity:terminal:${d}`))return [];if(s.step_type==="agent_response")return typeof s.text_delta=="string"&&s.text_delta.length>0?[{timestamp:o,type:"text",content:s.text_delta}]:[];if(s.step_type!=="tool")return [];let u=Qe(s.tool_info)?s.tool_info:void 0,l=Jh(s,u);if(!l)return [];let p=Kh(s);if(s.state==="ACTIVE"){if(Bu(n,`antigravity:active:${d}`))return [];let h=Gu(u?.parameters);return [{timestamp:o,type:"tool_use",toolName:l,toolUseId:p,...h===void 0?{}:{toolInput:h}}]}let _=s.state==="ERROR"?Vh(u?.error):ju(u?.output);return [{timestamp:o,type:"tool_result",toolName:l,toolUseId:p,..._===void 0?{}:{resultPreview:_},...s.state==="ERROR"?{isError:true}:{}}]}};});var zu=b(()=>{g();Hn();qn();Un();hn();});function jn(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function zn(t){return jn(t)?t:void 0}function $e(t){return typeof t=="string"?t:void 0}function Tn(t){let e=typeof t=="number"?t:Number(t??0);return Number.isFinite(e)?e:0}function om(t){let e=[],n=-1,r=0,o=false,s=false;for(let i=0;i<t.length;i+=1){let c=t[i];if(n===-1){(c==="{"||c==="[")&&(n=i,r=1);continue}if(s){s=false;continue}if(c==="\\"&&o){s=true;continue}if(c==='"'){o=!o;continue}o||(c==="{"||c==="["?r+=1:(c==="}"||c==="]")&&(r-=1,r===0&&(e.push(t.slice(n,i+1)),n=-1)));}return n!==-1&&e.push(t.slice(n)),e}function Cr(t){let e=t.trim();if(!e)return [];try{let n=JSON.parse(e);return jn(n)?[n]:[]}catch{return om(e).flatMap(n=>{try{let r=JSON.parse(n);return jn(r)?[r]:[]}catch{return []}})}}function Zu(t){let e=JSON.stringify(t);return e===void 0?String(t):e}function yn(t){if(typeof t=="string")return t;if(Array.isArray(t)){let e=t.map(yn).filter(n=>n!==void 0);return e.length>0?e.join(`
86
+ `):void 0}if(jn(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=yn(t[e]);if(n!==void 0)return n}}}function sm(t){let e=i=>Array.isArray(i)&&i.every(c=>Number.isInteger(c)&&c>=0&&c<=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)),o=i=>{let c=JSON.stringify(i,(d,u)=>e(u)?`<bytes:${u.length}>`:u);return c===void 0?String(i):c},s=t.rawOutput;if(s!=null){let i=zn(s);if(!i)return n(yn(s))??o(s);let c;if(e(i.output)&&i.output.length>0&&(c=n(r(i.output))),!c&&e(i.stdout)&&i.stdout.length>0&&(c=n(r(i.stdout))),!c){let l=zn(i.Result);c=n(i.output)??n(l?.output)??n(yn(s));}let d=e(i.stderr)&&i.stderr.length>0?r(i.stderr):void 0;if(d!==void 0)if(c){let l=c.endsWith(`
87
87
  `)||c.endsWith("\r")?"":`
88
- `;c=`${c}${l}${d}`;}else c=n(d);if(c)return c;let u=n(i.summary)??n(cn(t.content))??n(i.output_for_prompt);return u!==void 0?u:o(s)}if(t.content!==null&&t.content!==void 0)return cn(t.content)??o(t.content);if(t.result!==null&&t.result!==void 0)return cn(t.result)??o(t.result)}function xu(t){let e=Dn(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(Rh,"").split(/\r?\n/).map(n=>n.trim()).filter(Boolean)[0]??t.trim()).slice(0,500)}function Ou(t){return Eh.test(t)}function Ah(t){let e=Dn(t.modelUsage);return e?Object.keys(e)[0]??null:null}function Nh(t){let e=Dn(t.usage);if(!e)return null;let n=un(e.cache_read_input_tokens);return {inputTokens:un(e.input_tokens)+n,cachedInputTokens:n,outputTokens:un(e.output_tokens),costUsd:un(t.total_cost_usd)}}function Oh(t){let e=0,n=0,r=0,o=false,s=new Set;for(let i of t.split(`
89
- `).flatMap(mr)){if(i.type!=="usage")continue;let c=Dn(i.usage);if(!c)continue;let d=be(i.signature);if(d&&d.length>0){let l=`signature:${d}`;if(s.has(l))continue;s.add(l);}let u=un(c.cache_read_input_tokens);e+=un(c.input_tokens)+u,n+=u,r+=un(c.output_tokens),o=true;}return o?{inputTokens:e,cachedInputTokens:n,outputTokens:r,costUsd:0}:null}function vh(t,e){if(!Array.isArray(e.entries)||e.entries.length===0)return [];let n=[];for(let s of e.entries.slice(0,Iu)){if(!bn(s))continue;let i=be(s.content)?.trim();if(!i)continue;let c=be(s.status)?.trim(),d=be(s.priority)?.trim(),u=[c?`status=${c}`:void 0,d?`priority=${d}`:void 0].filter(p=>!!p),l=u.length>0?` (${u.join(", ")})`:"";n.push(`- ${i}${l}`);}if(n.length===0)return [];e.entries.length>Iu&&n.push(Nu);let r=n.join(`
90
- `),o=r.length>Au?`${r.slice(0,Au-1)}${Nu}`:r;return [{timestamp:t,type:"info",content:o}]}function Ch(t,e){let n=be(e.type);if(n==="thought"){let r=be(e.data);return r===void 0?[]:[{timestamp:t,type:"thinking",content:r}]}if(n==="text"){let r=be(e.data);return r===void 0?[]:[{timestamp:t,type:"text",content:r}]}if(n==="plan")return vh(t,e);if(n==="tool_call"){let r=be(e.toolCallId),o=be(e.toolName)??be(e.title),s=e.rawInput===void 0?void 0:Cu(e.rawInput);return [{timestamp:t,type:"tool_use",toolUseId:r,toolName:o,toolInput:s}]}if(n==="tool_call_update"){let r=be(e.status);if(r!=="completed"&&r!=="failed"&&r!=="error")return [];let o=Ih(e),s=r!=="completed"||e.isError===true;return [{timestamp:t,type:"tool_result",toolUseId:be(e.toolCallId),toolName:be(e.toolName)??be(e.title),...o!==void 0?et(o,s):{isError:s}}]}if(n==="error"){let r=xu(e);return [{timestamp:t,type:"error",content:r,errorMessage:r}]}return []}function xh(t){return process.platform==="win32"?{flags:["--prompt-file",vu]}:{flags:["--prompt-file","/dev/stdin"],stdinMessage:t}}var No,wh,Eh,Rh,Iu,Au,Nu,vu,hi,mi=C(()=>{g();$t();xs();Ht();An();lr();sn();No="cli/grok",wh=new Set(["available_commands","usage","end"]),Eh=/(?:rate[\s_-]*limit|quota|usage[\s_-]*limit|too many requests|limit(?:ed|ing)?\s+(?:exceeded|reached))/i,Rh=/\u001b\[[0-?]*[ -/]*[@-~]/g,Iu=20,Au=4e3,Nu="\u2026",vu="__CREWX_GROK_PROMPT_FILE__";hi={command:"grok",createSessionId:()=>crypto.randomUUID(),meta:{displayName:"Grok",capabilities:{resume:true}},buildArgs(t,e){let{model:n,effort:r}=Ut(e.model),o=e.effort??r,s=e.resumeSessionId?["--resume",e.resumeSessionId]:e.providerSessionId?["--session-id",e.providerSessionId]:[],i=n?["--model",n]:[],c=n?It("grok").some(K=>K.id===n):false,d=n&&c?On("grok",n):[],u=!o||d.length===0||d.includes(o)?o:void 0,l=vc(u),p=e.additionalArgs??[],_=K=>p.some(te=>te===K||te.startsWith(`${K}=`)),h=e.providerOptions,m=h?.alwaysApprove,k=h?.sandbox,E=_("--permission-mode")?[]:Ac(e.mode),b=_("--always-approve")?[]:Nc(m),T=_("--sandbox")?[]:Oc(k),P=_("--verbatim")?[]:["--verbatim"],A=xh(t),x=["--no-auto-update",...s,...A.flags,...P,"--output-format","streaming-json","--no-alt-screen",...i,...l,...E,...b,...T,...p],S={args:x,stdinMessage:A.stdinMessage};if(process.platform==="win32"){let K=x.indexOf(vu);if(K<0)throw new Error("Grok Windows prompt file placeholder is missing from argv");let te,De,we;S.prepare=()=>we?Promise.reject(new Error("Grok prompt invocation was already disposed")):(De||(De=(async()=>{te=await promises.mkdtemp(Re.join(Na.tmpdir(),"crewx-grok-"));let Gt=Re.join(te,"prompt.txt"),Fr=await promises.open(Gt,"wx",384);try{await Fr.writeFile(t,{encoding:"utf8"});}finally{await Fr.close();}x[K]=Gt;})()),De),S.dispose=()=>(we||(we=(async()=>{await De?.catch(()=>{}),te&&(await promises.rm(te,{recursive:true,force:true}),te=void 0);})()),we);}return S},extractText(t){let e=[],n=false;for(let r of t.split(`
91
- `).flatMap(mr))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 mr(t))if(e.type==="error"){let n=xu(e);return Ou(Cu(e))?new on(n,No):new W(n,No)}return null},interpretExit(t,e){if(t===0)return null;let n=bu(e)||`Grok CLI exited with code ${t}.`;return Ou(e)?new on(n,No):new W(n,No)},parseResultMeta(t){let n=t.split(`
92
- `).flatMap(mr).find(r=>r.type==="end");return n?{usage:Nh(n),model:Ah(n)}:{usage:Oh(t),model:null}},parseEvent(t,e){let n=e??new Date().toISOString();return mr(t).flatMap(r=>Ch(nt(r,n),r))},suppressOutputLine(t){let e=t.trim();if(!e.startsWith("{")||!e.endsWith("}"))return false;try{let n=JSON.parse(e);return bn(n)&&typeof n.type=="string"?wh.has(n.type):!1}catch{return false}}};});var ti,ni=C(()=>{g();Gs();Ks();Js();ai();gi();Ru();mi();Gs();Ks();Js();ai();gi();mi();In();ti={codex:zs,claude:ko,opencode:ii,antigravity:fi,copilot:js,grok:hi};});function Du(t){if(t.startsWith("cli/"))return ti[t.slice(4)]}var Pu=C(()=>{g();oc();ni();});function Oo(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function bh(t,e){return typeof t=="string"&&t.length>0?t:typeof e=="string"&&e.length>0?e:null}function vo(t){if(typeof t.provider!="string"||t.provider.length===0)return;let n=t.taskLogRepository.readLogs(t.taskId)?.entries.filter(_=>_.level==="stdout").map(_=>_.message).join(`
93
- `)??"";if(!n.trim())return;let r=Du(t.provider);if(!r)return;let o;try{o=r.parseResultMeta?.(n);}catch{return {stdout:n,adapter:r}}let s=bh(o?.model,t.model),i=o?.usage;if(!i)return {stdout:n,adapter:r};let c=Oo(i.inputTokens),d=Oo(i.outputTokens),u=Oo(i.cachedInputTokens),l=Ld(Oo(i.costUsd),c,d,u,s);return c!==0||d!==0||u!==0||l!==0?{stdout:n,adapter:r,usage:{inputTokens:c,outputTokens:d,cachedInputTokens:u,costUsd:l,model:s,...i.complete===void 0?{}:{complete:i.complete}}}:{stdout:n,adapter:r}}var ki=C(()=>{g();Pu();so();});function Ti(t){let e=new Set;for(let n of t)for(let r of Dh.get(n)??[n])e.add(r);return [...e]}function wi(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"&&Ph.has(n)?n:void 0}catch{return}}function rt(t){let e=wi(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(yi.stopped.test(t.error))return "user_stop";if(yi.runnerLost.test(t.error))return "runner_lost"}}function Ue(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=wi(t.metadata);return e==="user_stop"?"stopped":e?"failed":typeof t.error=="string"&&yi.stopped.test(t.error)?"stopped":"failed"}default:return t.status}}function Lh(t){if(!t)return {};try{let e=JSON.parse(t);return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:{}}catch{return {}}}function kr(t){let e=Ue(t);return t.status==="runner_lost"&&wi(t.metadata)===void 0?{...t,status:e,metadata:JSON.stringify({...Lh(t.metadata),terminalReason:"runner_lost"})}:{...t,status:e}}var ln,Dh,yi,Ph,yr=C(()=>{g();ln=["success","completed","done","failed","error","stopped","runner_lost"],Dh=new Map([["success",["success","completed","done"]],["failed",["failed","error","runner_lost"]]]);yi={stopped:/^(Killed by user|Stopped by user|Cancelled by user|사용자에 의해 중지됨)/,runnerLost:/^Reaped: (process not found|pid never recorded|stale workflow run)/},Ph=new Set(["user_stop","runner_lost","launch_failed"]);});function Ei(t,e,n=1){let r=process.env[t];if(r===void 0||r==="")return e;let o=Number(r);return !Number.isFinite(o)||o<=0?e:Math.max(n,Math.trunc(o))}function wr(){return Ei("CREWX_TASK_HEARTBEAT_MS",1e4,200)}function Ln(){return Ei("CREWX_TASK_HEARTBEAT_STALE_MS",3e4)}function xo(){return Ei("CREWX_TASK_HEARTBEAT_HARD_STALE_MS",18e5)}function Pn(t){return typeof t=="number"&&Number.isFinite(t)?Math.trunc(t):0}function Co(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 Mh(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 Lu(t,e){return !!t.stop_requested_at&&Pn(t.stop_requested_epoch)===Pn(e)}function Mu(t,e){let n=Pn(e.runEpoch);if(!(e.writeHeartbeat===false?true:t.heartbeatTask({id:e.taskId,runEpoch:n})))return {accepted:false,row:null};let o=Mh(t.getTask(e.taskId));return !o||o.status!=="running"||Pn(o.run_epoch)!==n?{accepted:false,row:o}:{accepted:true,row:o}}function qu(t,e){let n=Tr.get(t);return !n||e&&n!==e?false:(clearInterval(n.timer),Tr.delete(t),true)}function Er(t,e){let n=Tr.get(t);return !n||e!==void 0&&n.runEpoch!==Pn(e)?false:qu(t,n)}function Fu(t,e){let n=Pn(e.runEpoch);Er(e.taskId);let r=true,o=null;try{let u=Mu(t,{...e,runEpoch:n});r=u.accepted,o=u.row;}catch(u){Co(u);}if(!r)return false;let s=wr(),i=Math.min(s,1e3),c=setInterval(()=>{let u=Tr.get(e.taskId);if(!(!u||u.timer!==c))try{u.heartbeatElapsedMs+=i;let l=u.heartbeatElapsedMs>=s,p=Mu(t,{taskId:e.taskId,runEpoch:n,writeHeartbeat:l});if(!p.accepted){qu(e.taskId,u);return}l&&(u.heartbeatElapsedMs%=s,u.lastHeartbeatAt=Date.now()),p.row&&Lu(p.row,n)&&!u.stopRequested&&(u.stopRequested=!0,e.onStopRequested&&Promise.resolve(e.onStopRequested(p.row)).catch(Co));}catch(l){Co(l);}},i),d={timer:c,runEpoch:n,stopRequested:false,lastHeartbeatAt:Date.now(),heartbeatElapsedMs:0};return Tr.set(e.taskId,d),typeof c=="object"&&c!==null&&"unref"in c&&c.unref(),o&&Lu(o,n)&&e.onStopRequested&&(d.stopRequested=true,Promise.resolve(e.onStopRequested(o)).catch(Co)),true}var $u,Hu,Uu,Tr,Rr=C(()=>{g();$u=1e4,Hu=3e4,Uu=18e5;Tr=new Map;});function Do(t,e=Date.now(),n=Oi){let r=t?Date.parse(t):Number.NaN,o=typeof e=="number"?e:Date.parse(e),s=xi(n,Oi,0);return Number.isFinite(r)&&Number.isFinite(o)&&o-r>s?"forced":"cooperative"}function Pi(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=ju(t.metadata),o=r.ownership==="runner"&&typeof r.providerPid=="number"&&Number.isSafeInteger(r.providerPid)&&r.providerPid>0?r.providerPid:void 0;if(o!==void 0&&o!==n){let s=r.providerPidStartedAt;e.push({pid:o,startedAt:typeof s=="string"?s:null});}return e}async function Li(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),o=e.legacyStartBoundaryMs;if(!r&&o===void 0)return {verdict:"unproven",ownership:"unknown",reason:"no start time recorded"};let s=e.processControlOptions??{},i=e.processControl?.checkProcessOwnershipAsync??Gd,c=e.processControl?.readProcessIdentityAsync??Jd,d;try{d=await i(t.pid,e.ownershipMarkers??Hh,s);}catch{d="unknown";}let u;try{u=await c(t.pid,s);}catch{u={status:"unknown"};}if(u.status==="not_found")return {verdict:"unproven",ownership:"not_found",reason:"process is no longer running"};if(u.status!=="found")return {verdict:"unproven",ownership:"unknown",reason:"start time could not be read"};let l=new Date(u.startedAtMs).toISOString();if(r){if(Math.abs(u.startedAtMs-n)>ao)return {verdict:"reused",reason:`started ${l}, not the recorded ${t.startedAt}`}}else return o!==void 0&&u.startedAtMs>o?{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"}:u.groupId!==null&&u.groupId!==t.pid?{verdict:"unproven",ownership:"not_owned",reason:"pid does not lead its process group"}:{verdict:"owned"}}async function Mi(t,e={}){let n=await Li(t,e);return n.verdict==="owned"?"owned":n.verdict==="reused"?"not_owned":n.ownership}function xi(t,e,n){return t===void 0||!Number.isFinite(t)?e:Math.max(n,Math.trunc(t))}function ju(t){if(!t)return {};try{let e=JSON.parse(t);if(typeof e=="object"&&e!==null&&!Array.isArray(e))return e}catch{}return {}}function Gh(t){if(!t)return;let e=ju(t.metadata).stopMethod;return e==="cooperative"||e==="forced"?e:void 0}function qe(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=Gh(t);return {status:"stopped",finalStatus:t.status,...r?{method:r}:{},...n?{pid:n}:{}}}return {status:"not_running",finalStatus:t.status,...n?{pid:n}:{}}}function bo(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 oe(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 Ni(t,e){return oe(t,qh,e)}function jh(t,e){if(!t.heartbeat_at)return false;let n=Date.parse(t.heartbeat_at);return Number.isFinite(n)?e-n<=Ln():false}function Kh(t){return {...t.processControlOptions,...t.platform?{platform:t.platform}:{}}}function zh(t,e,n){let r=t.getTask(e);if(!r||r.status!=="running")return qe(r,n)}async function Jh(t,e,n,r){let o=Date.now()+n;for(;;){let s=zh(t,e);if(s)return s;let i=o-Date.now();if(i<=0)return;await new Promise(c=>{setTimeout(c,Math.min(r,i));});}}async function Gu(t,e,n){let r=new Date().toISOString(),o={origin:n.origin??"internal",...n.callerPid!==void 0?{callerPid:n.callerPid}:{},...n.callerTaskId!==void 0?{callerTaskId:n.callerTaskId}:{}},s=t.requestTaskStop({id:e,requestedAt:r,...o}),i=t.getTask(e);if(!s.accepted){if(s.status==="pending"){let P=t.stopPendingTask(e,void 0,void 0,{...o,at:r}),A=t.getTask(e);if(P||!A||A.status!=="running")return qe(A);if(s=t.requestTaskStop({id:e,requestedAt:r,...o}),!s.accepted&&s.status!=="running"||!s.accepted&&!s.alreadyRequestedAt)return qe(t.getTask(e))}else if(!(s.status==="running"&&s.alreadyRequestedAt))return qe(i)}let c=s.runEpoch,d=xi(n.graceMs,Oi,0),u=xi(n.pollMs,$h,1),l=await Jh(t,e,d,u);if(l)return l;let p=t.getTask(e);if(!p||p.status!=="running")return qe(p);let _=Pi(p),h=_.map(P=>P.pid),m=h[0];if(!m){let P=t.finalizeTaskStop({id:e,runEpoch:c,method:"forced"}),A=t.getTask(e);return P||A?.status!=="running"?qe(A):oe(A,"Failed to finalize task stop")}let k=Kh(n);if(!jh(p,Date.now())){for(let P of _)if(await Mi(P,{ownershipMarkers:n.ownershipMarkers,processControl:n.processControl,processControlOptions:k})!=="owned")return bo(p)}let E=n.processControl?.terminateProcessTree??Mt;for(let P of h){let A;try{A=await E(P,{...k,signal:Lt});}catch(x){A={status:"failed",pid:P,method:k.platform==="win32"?"taskkill":"process-group",error:x instanceof Error?x.message:String(x)};}if(A.status==="failed")return oe(t.getTask(e),A.error??"Failed to terminate process tree")}let b=t.finalizeTaskStop({id:e,runEpoch:c,method:"forced"}),T=t.getTask(e);return b||T?.status!=="running"?qe(T,m):oe(T,"Task changed before stop was finalized")}function bi(t){return typeof t=="number"&&Number.isSafeInteger(t)&&t>0}function Di(t){return Number.isSafeInteger(t)&&t>=0}function Sr(t){return typeof t=="number"&&Number.isFinite(t)?Math.trunc(t):0}function Vh(t){return {...t.processControlOptions,...t.platform?{platform:t.platform}:{}}}function Xh(t){return {...t.processControlOptions,...t.platform?{platform:t.platform}:{}}}function Yh(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 Qh(t){switch(t){case "epoch_mismatch":return vi;case "workspace_mismatch":return Ci;default:return}}async function Ku(t,e){let n=t.getTask(e.taskId);if(!n||n.status!=="running")return Ni(n,bi(e.targetPid)?e.targetPid:void 0);if(!Di(e.sourceRunEpoch)||!Di(e.settleRunEpoch)||Sr(n.run_epoch)!==e.settleRunEpoch)return oe(n,Ri,e.targetPid);if(e.workspaceId!==void 0&&n.workspace_id!==e.workspaceId)return oe(n,Si,e.targetPid);let r=new Date().toISOString(),o;try{o=t.requestTaskStop({id:e.taskId,requestedAt:r,sourceRunEpoch:e.sourceRunEpoch,settleRunEpoch:e.settleRunEpoch,...e.workspaceId!==void 0?{workspaceId:e.workspaceId}:{}});}catch{return oe(n,Ai,e.targetPid)}let s=b=>o.stopRequestReceipt?{...b,stopRequestReceipt:o.stopRequestReceipt}:b,i=n,c=()=>{let b=t.getTask(e.taskId);return i=b,b},d=(b,T=false)=>{if(T)try{c();}catch{}return s(oe(i,b,e.targetPid))},u;try{u=c();}catch{return d(Ai)}if(!u||u.status!=="running")return s(Ni(u,e.targetPid));if(o.runEpoch!==e.settleRunEpoch||Sr(u.run_epoch)!==e.settleRunEpoch)return s(oe(u,Ri,e.targetPid));if(e.workspaceId!==void 0&&u.workspace_id!==e.workspaceId)return s(oe(u,Si,e.targetPid));if(!bi(e.targetPid))return s(oe(u,Uh));let l=Vh(e),p;try{p=await Mi({pid:e.targetPid,startedAt:u.pid_started_at},{ownershipMarkers:e.ownershipMarkers,processControl:e.processControl,processControlOptions:l});}catch{return s(bo(u,e.targetPid))}if(p!=="owned")return s(bo(u,e.targetPid));let _;try{_=c();}catch{return d(Ai)}if(!_||_.status!=="running")return s(Ni(_,e.targetPid));if(Sr(_.run_epoch)!==e.settleRunEpoch)return s(oe(_,Ri,e.targetPid));if(e.workspaceId!==void 0&&_.workspace_id!==e.workspaceId)return s(oe(_,Si,e.targetPid));let h=e.processControl?.terminateProcessTree??Mt,m;try{m=await h(e.targetPid,{...l,signal:Lt});}catch{return d(Bu,true)}if(m.status==="failed")return d(Bu,true);let k;try{k=t.finalizeTaskStop({id:e.taskId,runEpoch:e.settleRunEpoch,method:"forced"});}catch{return d(Ii,true)}if(!k)return d(Ii,true);let E;try{E=c();}catch{return d(Ii)}return s(qe(E,e.targetPid))}async function zu(t,e){let n=t.getTask(e.taskId);if(!n||n.status!=="running")return qe(n);if(!Di(e.expectedRunEpoch)||Sr(n.run_epoch)!==e.expectedRunEpoch)return oe(n,vi);if(e.workspaceId!==void 0&&n.workspace_id!==e.workspaceId)return oe(n,Ci);let r=n.pid;if(!bi(r))return oe(n,Fh);let o=Xh(e);if(await Mi({pid:r,startedAt:n.pid_started_at},{ownershipMarkers:e.ownershipMarkers,processControl:e.processControl,processControlOptions:o})!=="owned")return bo(n,r,Bh);let i=e.processControl?.terminateProcessTree??Mt,c;try{c=await i(r,{...o,signal:Lt});}catch{return oe(t.getTask(e.taskId),Wu,r)}if(c.status==="failed")return oe(t.getTask(e.taskId),Wu,r);let d=t.getTask(e.taskId);if(!d||d.status!=="running")return qe(d,r);if(Sr(d.run_epoch)!==e.expectedRunEpoch)return oe(d,vi,r);if(e.workspaceId!==void 0&&d.workspace_id!==e.workspaceId)return oe(d,Ci,r);let u;try{u=t.finalizeTaskForHostShutdown({id:e.taskId,expectedRunEpoch:e.expectedRunEpoch,...e.workspaceId!==void 0?{workspaceId:e.workspaceId}:{}});}catch{return oe(t.getTask(e.taskId),Wh,r)}let l=Qh(u);return l?oe(t.getTask(e.taskId),l,r):u!=="settled"?qe(t.getTask(e.taskId),r):Yh(t.getTask(e.taskId),r)}function Ju(t,e,n={}){if(typeof t=="string"){let r=t,o=e??{};return Promise.resolve().then(()=>(Hi(),Vu)).then(({TaskRepository:s})=>Gu(new s,r,o))}return Gu(t,e,n)}var Oi,$h,Hh,Uh,Ri,Si,qh,Bu,Ii,Ai,vi,Ci,Fh,Bh,Wu,Wh,$i=C(()=>{g();co();Rr();Oi=5e3,$h=250;Hh=["agy","crewx","claude","codex","opencode","grok","node"];Uh="INSTRUCTION_STOP_TARGET_PID_MISSING",Ri="INSTRUCTION_STOP_EPOCH_MISMATCH",Si="INSTRUCTION_STOP_WORKSPACE_MISMATCH",qh="INSTRUCTION_STOP_GENERATION_ALREADY_SETTLED",Bu="INSTRUCTION_STOP_PROCESS_TERMINATION_FAILED",Ii="INSTRUCTION_STOP_SETTLE_CAS_FAILED",Ai="INSTRUCTION_STOP_REQUEST_FAILED",vi="HOST_SHUTDOWN_EPOCH_MISMATCH",Ci="HOST_SHUTDOWN_WORKSPACE_MISMATCH",Fh="HOST_SHUTDOWN_TARGET_PID_MISSING",Bh="HOST_SHUTDOWN_OWNERSHIP_UNVERIFIED",Wu="HOST_SHUTDOWN_PROCESS_TERMINATION_FAILED",Wh="HOST_SHUTDOWN_SETTLE_CAS_FAILED";});var Vu={};ql(Vu,{CANONICAL_USER_STOP_ERROR:()=>Ji,DEFAULT_TASK_REAPER_TICK_INTERVAL_MS:()=>ol,HOST_SHUTDOWN_TERMINAL_ERROR:()=>el,PENDING_ADOPT_GRACE_MS:()=>rl,PID_NULL_REAP_GRACE_MS:()=>Qi,RATED_TASK_EXCERPT_MAX_CHARS:()=>Zi,RATED_TASK_LIST_MAX_LIMIT:()=>il,TASK_HEARTBEAT_HARD_STALE_MS:()=>Uu,TASK_HEARTBEAT_INTERVAL_MS:()=>$u,TASK_HEARTBEAT_STALE_MS:()=>Hu,TASK_RATINGS:()=>sl,TaskRatingError:()=>Cr,TaskRepository:()=>vr,WORKFLOW_ANCHOR_TASK_KINDS:()=>Dt,buildRatedTasksCountQuery:()=>dl,buildRatedTasksQuery:()=>al,countRatedTasks:()=>mm,hasRecordedUsage:()=>Xi,isWorkflowAnchorTaskKind:()=>or,listRatedTasks:()=>hm,mergeTerminalReason:()=>Vi,resolveTaskHeartbeatHardStaleMs:()=>xo,resolveTaskHeartbeatIntervalMs:()=>wr,resolveTaskHeartbeatStaleMs:()=>Ln,setTaskRating:()=>gm});function st(t){return kr(t)}function qi(t){return kr(t)}function Fi(){return drizzleOrm.or(...Dt.map(t=>drizzleOrm.like(a.metadata,`%"kind":"${t}"%`)))}function Xu(){return drizzleOrm.and(...Dt.map(t=>drizzleOrm.notLike(a.metadata,`%"kind":"${t}"%`)))}function Wi(t=a.model,e=a.metadata){let n=drizzleOrm.sql`
88
+ `;c=`${c}${l}${d}`;}else c=n(d);if(c)return c;let u=n(i.summary)??n(yn(t.content))??n(i.output_for_prompt);return u!==void 0?u:o(s)}if(t.content!==null&&t.content!==void 0)return yn(t.content)??o(t.content);if(t.result!==null&&t.result!==void 0)return yn(t.result)??o(t.result)}function el(t){let e=zn(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?tl(n):"Grok CLI reported an error."}function tl(t){return (t.replace(rm,"").split(/\r?\n/).map(n=>n.trim()).filter(Boolean)[0]??t.trim()).slice(0,500)}function Yu(t){return nm.test(t)}function im(t){let e=zn(t.modelUsage);return e?Object.keys(e)[0]??null:null}function am(t){let e=zn(t.usage);if(!e)return null;let n=Tn(e.cache_read_input_tokens);return {inputTokens:Tn(e.input_tokens)+n,cachedInputTokens:n,outputTokens:Tn(e.output_tokens),costUsd:Tn(t.total_cost_usd)}}function dm(t){let e=0,n=0,r=0,o=false,s=new Set;for(let i of t.split(`
89
+ `).flatMap(Cr)){if(i.type!=="usage")continue;let c=zn(i.usage);if(!c)continue;let d=$e(i.signature);if(d&&d.length>0){let l=`signature:${d}`;if(s.has(l))continue;s.add(l);}let u=Tn(c.cache_read_input_tokens);e+=Tn(c.input_tokens)+u,n+=u,r+=Tn(c.output_tokens),o=true;}return o?{inputTokens:e,cachedInputTokens:n,outputTokens:r,costUsd:0}:null}function cm(t,e){if(!Array.isArray(e.entries)||e.entries.length===0)return [];let n=[];for(let s of e.entries.slice(0,Ju)){if(!jn(s))continue;let i=$e(s.content)?.trim();if(!i)continue;let c=$e(s.status)?.trim(),d=$e(s.priority)?.trim(),u=[c?`status=${c}`:void 0,d?`priority=${d}`:void 0].filter(p=>!!p),l=u.length>0?` (${u.join(", ")})`:"";n.push(`- ${i}${l}`);}if(n.length===0)return [];e.entries.length>Ju&&n.push(Xu);let r=n.join(`
90
+ `),o=r.length>Vu?`${r.slice(0,Vu-1)}${Xu}`:r;return [{timestamp:t,type:"info",content:o}]}function um(t,e){let n=$e(e.type);if(n==="thought"){let r=$e(e.data);return r===void 0?[]:[{timestamp:t,type:"thinking",content:r}]}if(n==="text"){let r=$e(e.data);return r===void 0?[]:[{timestamp:t,type:"text",content:r}]}if(n==="plan")return cm(t,e);if(n==="tool_call"){let r=$e(e.toolCallId),o=$e(e.toolName)??$e(e.title),s=e.rawInput===void 0?void 0:Zu(e.rawInput);return [{timestamp:t,type:"tool_use",toolUseId:r,toolName:o,toolInput:s}]}if(n==="tool_call_update"){let r=$e(e.status);if(r!=="completed"&&r!=="failed"&&r!=="error")return [];let o=sm(e),s=r!=="completed"||e.isError===true;return [{timestamp:t,type:"tool_result",toolUseId:$e(e.toolCallId),toolName:$e(e.toolName)??$e(e.title),...o!==void 0?ot(o,s):{isError:s}}]}if(n==="error"){let r=el(e);return [{timestamp:t,type:"error",content:r,errorMessage:r}]}return []}function lm(t){return process.platform==="win32"?{flags:["--prompt-file",Qu]}:{flags:["--prompt-file","/dev/stdin"],stdinMessage:t}}var Uo,tm,nm,rm,Ju,Vu,Xu,Qu,xi,Di=b(()=>{g();Vt();Ks();Xt();Un();Ir();hn();Uo="cli/grok",tm=new Set(["available_commands","usage","end"]),nm=/(?:rate[\s_-]*limit|quota|usage[\s_-]*limit|too many requests|limit(?:ed|ing)?\s+(?:exceeded|reached))/i,rm=/\u001b\[[0-?]*[ -/]*[@-~]/g,Ju=20,Vu=4e3,Xu="\u2026",Qu="__CREWX_GROK_PROMPT_FILE__";xi={command:"grok",createSessionId:()=>crypto.randomUUID(),meta:{displayName:"Grok",capabilities:{resume:true}},buildArgs(t,e){let{model:n,effort:r}=Yt(e.model),o=e.effort??r,s=e.resumeSessionId?["--resume",e.resumeSessionId]:e.providerSessionId?["--session-id",e.providerSessionId]:[],i=n?["--model",n]:[],c=n?Dt("grok").some(K=>K.id===n):false,d=n&&c?Bn("grok",n):[],u=!o||d.length===0||d.includes(o)?o:void 0,l=Qc(u),p=e.additionalArgs??[],_=K=>p.some(re=>re===K||re.startsWith(`${K}=`)),h=e.providerOptions,m=h?.alwaysApprove,k=h?.sandbox,w=_("--permission-mode")?[]:Vc(e.mode),C=_("--always-approve")?[]:Xc(m),T=_("--sandbox")?[]:Yc(k),P=_("--verbatim")?[]:["--verbatim"],A=lm(t),x=["--no-auto-update",...s,...A.flags,...P,"--output-format","streaming-json","--no-alt-screen",...i,...l,...w,...C,...T,...p],I={args:x,stdinMessage:A.stdinMessage};if(process.platform==="win32"){let K=x.indexOf(Qu);if(K<0)throw new Error("Grok Windows prompt file placeholder is missing from argv");let re,Ue,Ie;I.prepare=()=>Ie?Promise.reject(new Error("Grok prompt invocation was already disposed")):(Ue||(Ue=(async()=>{re=await promises.mkdtemp(Ne.join(Ja.tmpdir(),"crewx-grok-"));let rn=Ne.join(re,"prompt.txt"),Zr=await promises.open(rn,"wx",384);try{await Zr.writeFile(t,{encoding:"utf8"});}finally{await Zr.close();}x[K]=rn;})()),Ue),I.dispose=()=>(Ie||(Ie=(async()=>{await Ue?.catch(()=>{}),re&&(await promises.rm(re,{recursive:true,force:true}),re=void 0);})()),Ie);}return I},extractText(t){let e=[],n=false;for(let r of t.split(`
91
+ `).flatMap(Cr))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 Cr(t))if(e.type==="error"){let n=el(e);return Yu(Zu(e))?new gn(n,Uo):new W(n,Uo)}return null},interpretExit(t,e){if(t===0)return null;let n=tl(e)||`Grok CLI exited with code ${t}.`;return Yu(e)?new gn(n,Uo):new W(n,Uo)},parseResultMeta(t){let n=t.split(`
92
+ `).flatMap(Cr).find(r=>r.type==="end");return n?{usage:am(n),model:im(n)}:{usage:dm(t),model:null}},parseEvent(t,e){let n=e??new Date().toISOString();return Cr(t).flatMap(r=>um(it(r,n),r))},suppressOutputLine(t){let e=t.trim();if(!e.startsWith("{")||!e.endsWith("}"))return false;try{let n=JSON.parse(e);return jn(n)&&typeof n.type=="string"?tm.has(n.type):!1}catch{return false}}};});var mi,ki=b(()=>{g();ii();di();ui();Ri();Ci();zu();Di();ii();di();ui();Ri();Ci();Di();Hn();mi={codex:ci,claude:bo,opencode:Ei,antigravity:bi,copilot:ai,grok:xi};});function nl(t){if(t.startsWith("cli/"))return mi[t.slice(4)]}var rl=b(()=>{g();Nc();ki();});function qo(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function pm(t,e){return typeof t=="string"&&t.length>0?t:typeof e=="string"&&e.length>0?e:null}function Bo(t){if(typeof t.provider!="string"||t.provider.length===0)return;let n=t.taskLogRepository.readLogs(t.taskId)?.entries.filter(_=>_.level==="stdout").map(_=>_.message).join(`
93
+ `)??"";if(!n.trim())return;let r=nl(t.provider);if(!r)return;let o;try{o=r.parseResultMeta?.(n);}catch{return {stdout:n,adapter:r}}let s=pm(o?.model,t.model),i=o?.usage;if(!i)return {stdout:n,adapter:r};let c=qo(i.inputTokens),d=qo(i.outputTokens),u=qo(i.cachedInputTokens),l=oc(qo(i.costUsd),c,d,u,s);return c!==0||d!==0||u!==0||l!==0?{stdout:n,adapter:r,usage:{inputTokens:c,outputTokens:d,cachedInputTokens:u,costUsd:l,model:s,...i.complete===void 0?{}:{complete:i.complete}}}:{stdout:n,adapter:r}}var Pi=b(()=>{g();rl();ko();});function Mi(t){let e=new Set;for(let n of t)for(let r of _m.get(n)??[n])e.add(r);return [...e]}function $i(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"&&fm.has(n)?n:void 0}catch{return}}function at(t){let e=$i(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(Li.stopped.test(t.error))return "user_stop";if(Li.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=$i(t.metadata);return e==="user_stop"?"stopped":e?"failed":typeof t.error=="string"&&Li.stopped.test(t.error)?"stopped":"failed"}default:return t.status}}function gm(t){if(!t)return {};try{let e=JSON.parse(t);return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:{}}catch{return {}}}function xr(t){let e=xe(t);return t.status==="runner_lost"&&$i(t.metadata)===void 0?{...t,status:e,metadata:JSON.stringify({...gm(t.metadata),terminalReason:"runner_lost"})}:{...t,status:e}}var wn,_m,Li,fm,Kn=b(()=>{g();wn=["success","completed","done","failed","error","stopped","runner_lost"],_m=new Map([["success",["success","completed","done"]],["failed",["failed","error","runner_lost"]]]);Li={stopped:/^(Killed by user|Stopped by user|Cancelled by user|사용자에 의해 중지됨)/,runnerLost:/^Reaped: (process not found|pid never recorded|stale workflow run)/},fm=new Set(["user_stop","runner_lost","launch_failed"]);});function Hi(t,e,n=1){let r=process.env[t];if(r===void 0||r==="")return e;let o=Number(r);return !Number.isFinite(o)||o<=0?e:Math.max(n,Math.trunc(o))}function Pr(){return Hi("CREWX_TASK_HEARTBEAT_MS",1e4,200)}function Vn(){return Hi("CREWX_TASK_HEARTBEAT_STALE_MS",3e4)}function Wo(){return Hi("CREWX_TASK_HEARTBEAT_HARD_STALE_MS",18e5)}function Jn(t){return typeof t=="number"&&Number.isFinite(t)?Math.trunc(t):0}function Fo(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 hm(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 ol(t,e){return !!t.stop_requested_at&&Jn(t.stop_requested_epoch)===Jn(e)}function sl(t,e){let n=Jn(e.runEpoch);if(!(e.writeHeartbeat===false?true:t.heartbeatTask({id:e.taskId,runEpoch:n})))return {accepted:false,row:null};let o=hm(t.getTask(e.taskId));return !o||o.status!=="running"||Jn(o.run_epoch)!==n?{accepted:false,row:o}:{accepted:true,row:o}}function cl(t,e){let n=Dr.get(t);return !n||e&&n!==e?false:(clearInterval(n.timer),Dr.delete(t),true)}function Lr(t,e){let n=Dr.get(t);return !n||e!==void 0&&n.runEpoch!==Jn(e)?false:cl(t,n)}function ul(t,e){let n=Jn(e.runEpoch);Lr(e.taskId);let r=true,o=null;try{let u=sl(t,{...e,runEpoch:n});r=u.accepted,o=u.row;}catch(u){Fo(u);}if(!r)return false;let s=Pr(),i=Math.min(s,1e3),c=setInterval(()=>{let u=Dr.get(e.taskId);if(!(!u||u.timer!==c))try{u.heartbeatElapsedMs+=i;let l=u.heartbeatElapsedMs>=s,p=sl(t,{taskId:e.taskId,runEpoch:n,writeHeartbeat:l});if(!p.accepted){cl(e.taskId,u);return}l&&(u.heartbeatElapsedMs%=s,u.lastHeartbeatAt=Date.now()),p.row&&ol(p.row,n)&&!u.stopRequested&&(u.stopRequested=!0,e.onStopRequested&&Promise.resolve(e.onStopRequested(p.row)).catch(Fo));}catch(l){Fo(l);}},i),d={timer:c,runEpoch:n,stopRequested:false,lastHeartbeatAt:Date.now(),heartbeatElapsedMs:0};return Dr.set(e.taskId,d),typeof c=="object"&&c!==null&&"unref"in c&&c.unref(),o&&ol(o,n)&&e.onStopRequested&&(d.stopRequested=true,Promise.resolve(e.onStopRequested(o)).catch(Fo)),true}var il,al,dl,Dr,Mr=b(()=>{g();il=1e4,al=3e4,dl=18e5;Dr=new Map;});function jo(t,e=Date.now(),n=Gi){let r=t?Date.parse(t):Number.NaN,o=typeof e=="number"?e:Date.parse(e),s=Ki(n,Gi,0);return Number.isFinite(r)&&Number.isFinite(o)&&o-r>s?"forced":"cooperative"}function Xi(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=fl(t.metadata),o=r.ownership==="runner"&&typeof r.providerPid=="number"&&Number.isSafeInteger(r.providerPid)&&r.providerPid>0?r.providerPid:void 0;if(o!==void 0&&o!==n){let s=r.providerPidStartedAt;e.push({pid:o,startedAt:typeof s=="string"?s:null});}return e}async function Yi(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),o=e.legacyStartBoundaryMs;if(!r&&o===void 0)return {verdict:"unproven",ownership:"unknown",reason:"no start time recorded"};let s=e.processControlOptions??{},i=e.processControl?.checkProcessOwnershipAsync??_c,c=e.processControl?.readProcessIdentityAsync??mc,d;try{d=await i(t.pid,e.ownershipMarkers??km,s);}catch{d="unknown";}let u;try{u=await c(t.pid,s);}catch{u={status:"unknown"};}if(u.status==="not_found")return {verdict:"unproven",ownership:"not_found",reason:"process is no longer running"};if(u.status!=="found")return {verdict:"unproven",ownership:"unknown",reason:"start time could not be read"};let l=new Date(u.startedAtMs).toISOString();if(r){if(Math.abs(u.startedAtMs-n)>To)return {verdict:"reused",reason:`started ${l}, not the recorded ${t.startedAt}`}}else return o!==void 0&&u.startedAtMs>o?{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"}:u.groupId!==null&&u.groupId!==t.pid?{verdict:"unproven",ownership:"not_owned",reason:"pid does not lead its process group"}:{verdict:"owned"}}async function Qi(t,e={}){let n=await Yi(t,e);return n.verdict==="owned"?"owned":n.verdict==="reused"?"not_owned":n.ownership}function Ki(t,e,n){return t===void 0||!Number.isFinite(t)?e:Math.max(n,Math.trunc(t))}function fl(t){if(!t)return {};try{let e=JSON.parse(t);if(typeof e=="object"&&e!==null&&!Array.isArray(e))return e}catch{}return {}}function Sm(t){if(!t)return;let e=fl(t.metadata).stopMethod;return e==="cooperative"||e==="forced"?e:void 0}function je(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=Sm(t);return {status:"stopped",finalStatus:t.status,...r?{method:r}:{},...n?{pid:n}:{}}}return {status:"not_running",finalStatus:t.status,...n?{pid:n}:{}}}function Go(t,e,n="Process owner could not be verified"){let r=e??(t.pid&&t.pid>0?t.pid:void 0);return {status:"ownership_unverified",finalStatus:t.status,...r?{pid:r}:{},error:n}}function ie(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 Wi(t,e){return ie(t,Tm,e)}function Im(t,e){if(!t.heartbeat_at)return false;let n=Date.parse(t.heartbeat_at);return Number.isFinite(n)?e-n<=Vn():false}function Am(t){return {...t.processControlOptions,...t.platform?{platform:t.platform}:{}}}function Nm(t,e,n){let r=t.getTask(e);if(!r||r.status!=="running")return je(r,n)}async function Om(t,e,n,r){let o=Date.now()+n;for(;;){let s=Nm(t,e);if(s)return s;let i=o-Date.now();if(i<=0)return;await new Promise(c=>{setTimeout(c,Math.min(r,i));});}}async function _l(t,e,n){let r=new Date().toISOString(),o={origin:n.origin??"internal",...n.callerPid!==void 0?{callerPid:n.callerPid}:{},...n.callerTaskId!==void 0?{callerTaskId:n.callerTaskId}:{}},s=t.requestTaskStop({id:e,requestedAt:r,...o}),i=t.getTask(e);if(!s.accepted){if(s.status==="pending"){let P=t.stopPendingTask(e,void 0,void 0,{...o,at:r}),A=t.getTask(e);if(P||!A||A.status!=="running")return je(A);if(s=t.requestTaskStop({id:e,requestedAt:r,...o}),!s.accepted&&s.status!=="running"||!s.accepted&&!s.alreadyRequestedAt)return je(t.getTask(e))}else if(!(s.status==="running"&&s.alreadyRequestedAt))return je(i)}let c=s.runEpoch,d=Ki(n.graceMs,Gi,0),u=Ki(n.pollMs,mm,1),l=await Om(t,e,d,u);if(l)return l;let p=t.getTask(e);if(!p||p.status!=="running")return je(p);let _=Xi(p),h=_.map(P=>P.pid),m=h[0];if(!m){let P=t.finalizeTaskStop({id:e,runEpoch:c,method:"forced"}),A=t.getTask(e);return P||A?.status!=="running"?je(A):ie(A,"Failed to finalize task stop")}let k=Am(n);if(!Im(p,Date.now())){for(let P of _)if(await Qi(P,{ownershipMarkers:n.ownershipMarkers,processControl:n.processControl,processControlOptions:k})!=="owned")return Go(p)}let w=n.processControl?.terminateProcessTree??Jt;for(let P of h){let A;try{A=await w(P,{...k,signal:Kt});}catch(x){A={status:"failed",pid:P,method:k.platform==="win32"?"taskkill":"process-group",error:x instanceof Error?x.message:String(x)};}if(A.status==="failed")return ie(t.getTask(e),A.error??"Failed to terminate process tree")}let C=t.finalizeTaskStop({id:e,runEpoch:c,method:"forced"}),T=t.getTask(e);return C||T?.status!=="running"?je(T,m):ie(T,"Task changed before stop was finalized")}function Ji(t){return typeof t=="number"&&Number.isSafeInteger(t)&&t>0}function Vi(t){return Number.isSafeInteger(t)&&t>=0}function $r(t){return typeof t=="number"&&Number.isFinite(t)?Math.trunc(t):0}function vm(t){return {...t.processControlOptions,...t.platform?{platform:t.platform}:{}}}function bm(t){return {...t.processControlOptions,...t.platform?{platform:t.platform}:{}}}function Cm(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 xm(t){switch(t){case "epoch_mismatch":return ji;case "workspace_mismatch":return zi;default:return}}async function gl(t,e){let n=t.getTask(e.taskId);if(!n||n.status!=="running")return Wi(n,Ji(e.targetPid)?e.targetPid:void 0);if(!Vi(e.sourceRunEpoch)||!Vi(e.settleRunEpoch)||$r(n.run_epoch)!==e.settleRunEpoch)return ie(n,Ui,e.targetPid);if(e.workspaceId!==void 0&&n.workspace_id!==e.workspaceId)return ie(n,qi,e.targetPid);let r=new Date().toISOString(),o;try{o=t.requestTaskStop({id:e.taskId,requestedAt:r,sourceRunEpoch:e.sourceRunEpoch,settleRunEpoch:e.settleRunEpoch,...e.workspaceId!==void 0?{workspaceId:e.workspaceId}:{}});}catch{return ie(n,Fi,e.targetPid)}let s=C=>o.stopRequestReceipt?{...C,stopRequestReceipt:o.stopRequestReceipt}:C,i=n,c=()=>{let C=t.getTask(e.taskId);return i=C,C},d=(C,T=false)=>{if(T)try{c();}catch{}return s(ie(i,C,e.targetPid))},u;try{u=c();}catch{return d(Fi)}if(!u||u.status!=="running")return s(Wi(u,e.targetPid));if(o.runEpoch!==e.settleRunEpoch||$r(u.run_epoch)!==e.settleRunEpoch)return s(ie(u,Ui,e.targetPid));if(e.workspaceId!==void 0&&u.workspace_id!==e.workspaceId)return s(ie(u,qi,e.targetPid));if(!Ji(e.targetPid))return s(ie(u,ym));let l=vm(e),p;try{p=await Qi({pid:e.targetPid,startedAt:u.pid_started_at},{ownershipMarkers:e.ownershipMarkers,processControl:e.processControl,processControlOptions:l});}catch{return s(Go(u,e.targetPid))}if(p!=="owned")return s(Go(u,e.targetPid));let _;try{_=c();}catch{return d(Fi)}if(!_||_.status!=="running")return s(Wi(_,e.targetPid));if($r(_.run_epoch)!==e.settleRunEpoch)return s(ie(_,Ui,e.targetPid));if(e.workspaceId!==void 0&&_.workspace_id!==e.workspaceId)return s(ie(_,qi,e.targetPid));let h=e.processControl?.terminateProcessTree??Jt,m;try{m=await h(e.targetPid,{...l,signal:Kt});}catch{return d(ll,true)}if(m.status==="failed")return d(ll,true);let k;try{k=t.finalizeTaskStop({id:e.taskId,runEpoch:e.settleRunEpoch,method:"forced"});}catch{return d(Bi,true)}if(!k)return d(Bi,true);let w;try{w=c();}catch{return d(Bi)}return s(je(w,e.targetPid))}async function hl(t,e){let n=t.getTask(e.taskId);if(!n||n.status!=="running")return je(n);if(!Vi(e.expectedRunEpoch)||$r(n.run_epoch)!==e.expectedRunEpoch)return ie(n,ji);if(e.workspaceId!==void 0&&n.workspace_id!==e.workspaceId)return ie(n,zi);let r=n.pid;if(!Ji(r))return ie(n,wm);let o=bm(e);if(await Qi({pid:r,startedAt:n.pid_started_at},{ownershipMarkers:e.ownershipMarkers,processControl:e.processControl,processControlOptions:o})!=="owned")return Go(n,r,Em);let i=e.processControl?.terminateProcessTree??Jt,c;try{c=await i(r,{...o,signal:Kt});}catch{return ie(t.getTask(e.taskId),pl,r)}if(c.status==="failed")return ie(t.getTask(e.taskId),pl,r);let d=t.getTask(e.taskId);if(!d||d.status!=="running")return je(d,r);if($r(d.run_epoch)!==e.expectedRunEpoch)return ie(d,ji,r);if(e.workspaceId!==void 0&&d.workspace_id!==e.workspaceId)return ie(d,zi,r);let u;try{u=t.finalizeTaskForHostShutdown({id:e.taskId,expectedRunEpoch:e.expectedRunEpoch,...e.workspaceId!==void 0?{workspaceId:e.workspaceId}:{}});}catch{return ie(t.getTask(e.taskId),Rm,r)}let l=xm(u);return l?ie(t.getTask(e.taskId),l,r):u!=="settled"?je(t.getTask(e.taskId),r):Cm(t.getTask(e.taskId),r)}function ml(t,e,n={}){if(typeof t=="string"){let r=t,o=e??{};return Promise.resolve().then(()=>(ea(),kl)).then(({TaskRepository:s})=>_l(new s,r,o))}return _l(t,e,n)}var Gi,mm,km,ym,Ui,qi,Tm,ll,Bi,Fi,ji,zi,wm,Em,pl,Rm,Zi=b(()=>{g();wo();Mr();Gi=5e3,mm=250;km=["agy","crewx","claude","codex","opencode","grok","node"];ym="INSTRUCTION_STOP_TARGET_PID_MISSING",Ui="INSTRUCTION_STOP_EPOCH_MISMATCH",qi="INSTRUCTION_STOP_WORKSPACE_MISMATCH",Tm="INSTRUCTION_STOP_GENERATION_ALREADY_SETTLED",ll="INSTRUCTION_STOP_PROCESS_TERMINATION_FAILED",Bi="INSTRUCTION_STOP_SETTLE_CAS_FAILED",Fi="INSTRUCTION_STOP_REQUEST_FAILED",ji="HOST_SHUTDOWN_EPOCH_MISMATCH",zi="HOST_SHUTDOWN_WORKSPACE_MISMATCH",wm="HOST_SHUTDOWN_TARGET_PID_MISSING",Em="HOST_SHUTDOWN_OWNERSHIP_UNVERIFIED",pl="HOST_SHUTDOWN_PROCESS_TERMINATION_FAILED",Rm="HOST_SHUTDOWN_SETTLE_CAS_FAILED";});var kl={};kp(kl,{CANONICAL_USER_STOP_ERROR:()=>ua,DEFAULT_TASK_REAPER_TICK_INTERVAL_MS:()=>Nl,HOST_SHUTDOWN_TERMINAL_ERROR:()=>Rl,PENDING_ADOPT_GRACE_MS:()=>Al,PID_NULL_REAP_GRACE_MS:()=>fa,RATED_TASK_EXCERPT_MAX_CHARS:()=>ga,RATED_TASK_LIST_MAX_LIMIT:()=>vl,TASK_HEARTBEAT_HARD_STALE_MS:()=>dl,TASK_HEARTBEAT_INTERVAL_MS:()=>il,TASK_HEARTBEAT_STALE_MS:()=>al,TASK_RATINGS:()=>Ol,TaskRatingError:()=>Wr,TaskRepository:()=>Fr,WORKFLOW_ANCHOR_TASK_KINDS:()=>jt,buildRatedTasksCountQuery:()=>Cl,buildRatedTasksQuery:()=>bl,countRatedTasks:()=>Ym,hasRecordedUsage:()=>pa,isWorkflowAnchorTaskKind:()=>kr,listRatedTasks:()=>Xm,mergeTerminalReason:()=>la,resolveTaskHeartbeatHardStaleMs:()=>Wo,resolveTaskHeartbeatIntervalMs:()=>Pr,resolveTaskHeartbeatStaleMs:()=>Vn,setTaskRating:()=>Vm});function ct(t){return xr(t)}function na(t){return xr(t)}function ra(){return drizzleOrm.or(...jt.map(t=>drizzleOrm.like(a.metadata,`%"kind":"${t}"%`)))}function yl(){return drizzleOrm.and(...jt.map(t=>drizzleOrm.notLike(a.metadata,`%"kind":"${t}"%`)))}function sa(t=a.model,e=a.metadata){let n=drizzleOrm.sql`
94
94
  CASE
95
95
  WHEN ${t} LIKE 'claude-%' OR ${t} IN ('opus', 'sonnet', 'haiku', 'opus[1m]', 'sonnet[1m]') THEN 'claude'
96
96
  WHEN ${t} LIKE 'gpt-%' OR ${t} LIKE 'codex-%' THEN 'codex'
@@ -119,7 +119,7 @@ ${r.join(`
119
119
  WHEN trim(${i}) = '' THEN 'unknown'
120
120
  ELSE ${i}
121
121
  END
122
- `}function im(t){let e={status:t.status,metadata:t.metadata},n=Ue(e);return n==="stopped"||n==="failed"&&rt(e)==="runner_lost"}function Nr(t){return drizzleOrm.sql`${t} NOT IN (${drizzleOrm.sql.join(am.map(e=>drizzleOrm.sql`${e}`),drizzleOrm.sql`, `)})`}function Po(t){let e=drizzleOrm.sql`
122
+ `}function qm(t){let e={status:t.status,metadata:t.metadata},n=xe(e);return n==="stopped"||n==="failed"&&at(e)==="runner_lost"}function qr(t){return drizzleOrm.sql`${t} NOT IN (${drizzleOrm.sql.join(Bm.map(e=>drizzleOrm.sql`${e}`),drizzleOrm.sql`, `)})`}function zo(t){let e=drizzleOrm.sql`
123
123
  CASE
124
124
  WHEN json_valid(${t}) = 1
125
125
  THEN json_extract(${t}, '$.usageAccounting')
@@ -129,7 +129,7 @@ ${r.join(`
129
129
  COALESCE(SUM(
130
130
  CASE WHEN ${e} = 'unavailable' THEN 1 ELSE 0 END
131
131
  ), 0)
132
- `}function pn(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function pe(t){if(!t)return {};try{let e=JSON.parse(t);return pn(e)?{...e}:{}}catch{return {}}}function Uo(t){return t==null||t===""}function Lo(t,e){return Uo(t)&&!Uo(e)?e:t}function dm(t,e){let n=pe(t);if(!e)return n;for(let[r,o]of Object.entries(e))Uo(n[r])&&!Uo(o)&&(n[r]=o);return n}function Mo(t,e){let n=t.origin&&tl.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 cm(t){let e=pe(t).stopRequest;if(pn(e)&&!(typeof e.origin!="string"||!tl.has(e.origin)||typeof e.at!="string"||typeof e.callerPid!="number"))return {...e}}function Yu(){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 Vi(t,e){let n=pe(t??null);return n.terminalReason=e,JSON.stringify(n)}function ji(t,e){let n={...t,terminalReason:"user_stop"},r=e?.trim();return r&&r!==Ji&&(n[sm]=e),{error:Ji,metadata:n}}function ye(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function Xi(t){return ye(t.input_tokens)!==0||ye(t.output_tokens)!==0||ye(t.cached_input_tokens)!==0||ye(t.cost_usd)!==0}function z(t){return typeof t=="number"&&Number.isFinite(t)?Math.trunc(t):0}function Qu(t){return {inputTokens:ye(t.inputTokens??0),outputTokens:ye(t.outputTokens??0),cachedInputTokens:ye(t.cachedInputTokens??0),costUsd:ye(t.costUsd??0)}}function nl(t){if(pn(t))return {inputTokens:ye(t.inputTokens),outputTokens:ye(t.outputTokens),cachedInputTokens:ye(t.cachedInputTokens),costUsd:ye(t.costUsd)}}function Or(t){if(!pn(t))return;let e=t.accounting;return e==="recorded"||e==="partial"||e==="unavailable"?e:void 0}function Yi(t){return t.inputTokens!==0||t.outputTokens!==0||t.cachedInputTokens!==0||t.costUsd!==0}function um(t){let e=Or(t);if(e==="recorded"||e==="partial")return true;if(e==="unavailable")return false;let n=nl(t);return n!==void 0&&Yi(n)}function lm(t){return Object.values(t).some(e=>{let n=Or(e);return n==="partial"||n==="unavailable"})}function pm(t){let e={inputTokens:0,outputTokens:0,cachedInputTokens:0,costUsd:0};for(let n of Object.values(t)){if(Or(n)==="unavailable")continue;let r=nl(n);r&&(e.inputTokens+=r.inputTokens,e.outputTokens+=r.outputTokens,e.cachedInputTokens+=r.cachedInputTokens,e.costUsd+=r.costUsd);}return e}function $o(t,e,n){let r=Date.parse(t),o=Date.parse(e);return Number.isFinite(r)&&Number.isFinite(o)?o-r:n??null}function Ki(t,e){if(typeof t!="number"||!Number.isSafeInteger(t)||t<=0)return null;let n=zd(t,e);return n.status==="found"?new Date(n.startedAtMs).toISOString():null}function Un(t,e){if(typeof t!="string"||t.length===0)throw new f("VALIDATION",`${e} is required`);return t}function ea(t,e){let n=Date.parse(t);if(!Number.isFinite(n))throw new f("VALIDATION",`${e} is not a valid ISO time: ${t}`);return new Date(n).toISOString()}function gm(t,e){let n=Un(e.workspaceId,"workspaceId"),r=Un(e.taskId,"taskId"),o=e.rating;if(o!==null&&!sl.includes(o))throw new f("VALIDATION","rating must be 'up', 'down' or null");let s=e.now===void 0?new Date().toISOString():ea(e.now,"now");try{return t.transaction(i=>{let c=drizzleOrm.and(drizzleOrm.eq(a.id,r),drizzleOrm.eq(a.workspace_id,n),drizzleOrm.inArray(a.status,[...ln])),d=i.update(a).set({rating:o,rated_at:o===null?null:s}).where(drizzleOrm.and(c,drizzleOrm.sql`${a.rating} IS NOT ${o}`)).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 u=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(!u)throw new Cr("TASK_NOT_FOUND",r);if(!fm.has(u.status))throw new Cr("TASK_RATING_NOT_TERMINAL",r);return {taskId:r,rating:u.rating,ratedAt:u.rated_at,changed:!1}},{behavior:"immediate"})}catch(i){throw i instanceof f?i:new f("DB_ERROR","Failed to set task rating",i)}}function al(t){let e=drizzleOrm.sql`
132
+ `}function En(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function fe(t){if(!t)return {};try{let e=JSON.parse(t);return En(e)?{...e}:{}}catch{return {}}}function Yo(t){return t==null||t===""}function Ko(t,e){return Yo(t)&&!Yo(e)?e:t}function Fm(t,e){let n=fe(t);if(!e)return n;for(let[r,o]of Object.entries(e))Yo(n[r])&&!Yo(o)&&(n[r]=o);return n}function Jo(t,e){let n=t.origin&&Sl.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 Wm(t){let e=fe(t).stopRequest;if(En(e)&&!(typeof e.origin!="string"||!Sl.has(e.origin)||typeof e.at!="string"||typeof e.callerPid!="number"))return {...e}}function Tl(){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 la(t,e){let n=fe(t??null);return n.terminalReason=e,JSON.stringify(n)}function aa(t,e){let n={...t,terminalReason:"user_stop"},r=e?.trim();return r&&r!==ua&&(n[Um]=e),{error:ua,metadata:n}}function Re(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function pa(t){return Re(t.input_tokens)!==0||Re(t.output_tokens)!==0||Re(t.cached_input_tokens)!==0||Re(t.cost_usd)!==0}function J(t){return typeof t=="number"&&Number.isFinite(t)?Math.trunc(t):0}function wl(t){return {inputTokens:Re(t.inputTokens??0),outputTokens:Re(t.outputTokens??0),cachedInputTokens:Re(t.cachedInputTokens??0),costUsd:Re(t.costUsd??0)}}function Il(t){if(En(t))return {inputTokens:Re(t.inputTokens),outputTokens:Re(t.outputTokens),cachedInputTokens:Re(t.cachedInputTokens),costUsd:Re(t.costUsd)}}function Br(t){if(!En(t))return;let e=t.accounting;return e==="recorded"||e==="partial"||e==="unavailable"?e:void 0}function _a(t){return t.inputTokens!==0||t.outputTokens!==0||t.cachedInputTokens!==0||t.costUsd!==0}function Gm(t){let e=Br(t);if(e==="recorded"||e==="partial")return true;if(e==="unavailable")return false;let n=Il(t);return n!==void 0&&_a(n)}function jm(t){return Object.values(t).some(e=>{let n=Br(e);return n==="partial"||n==="unavailable"})}function zm(t){let e={inputTokens:0,outputTokens:0,cachedInputTokens:0,costUsd:0};for(let n of Object.values(t)){if(Br(n)==="unavailable")continue;let r=Il(n);r&&(e.inputTokens+=r.inputTokens,e.outputTokens+=r.outputTokens,e.cachedInputTokens+=r.cachedInputTokens,e.costUsd+=r.costUsd);}return e}function Vo(t,e,n){let r=Date.parse(t),o=Date.parse(e);return Number.isFinite(r)&&Number.isFinite(o)?o-r:n??null}function da(t,e){if(typeof t!="number"||!Number.isSafeInteger(t)||t<=0)return null;let n=hc(t,e);return n.status==="found"?new Date(n.startedAtMs).toISOString():null}function Zn(t,e){if(typeof t!="string"||t.length===0)throw new f("VALIDATION",`${e} is required`);return t}function ha(t,e){let n=Date.parse(t);if(!Number.isFinite(n))throw new f("VALIDATION",`${e} is not a valid ISO time: ${t}`);return new Date(n).toISOString()}function Vm(t,e){let n=Zn(e.workspaceId,"workspaceId"),r=Zn(e.taskId,"taskId"),o=e.rating;if(o!==null&&!Ol.includes(o))throw new f("VALIDATION","rating must be 'up', 'down' or null");let s=e.now===void 0?new Date().toISOString():ha(e.now,"now");try{return t.transaction(i=>{let c=drizzleOrm.and(drizzleOrm.eq(a.id,r),drizzleOrm.eq(a.workspace_id,n),drizzleOrm.inArray(a.status,[...wn])),d=i.update(a).set({rating:o,rated_at:o===null?null:s}).where(drizzleOrm.and(c,drizzleOrm.sql`${a.rating} IS NOT ${o}`)).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 u=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(!u)throw new Wr("TASK_NOT_FOUND",r);if(!Jm.has(u.status))throw new Wr("TASK_RATING_NOT_TERMINAL",r);return {taskId:r,rating:u.rating,ratedAt:u.rated_at,changed:!1}},{behavior:"immediate"})}catch(i){throw i instanceof f?i:new f("DB_ERROR","Failed to set task rating",i)}}function bl(t){let e=drizzleOrm.sql`
133
133
  SELECT id, rated_at FROM tasks
134
134
  WHERE workspace_id = ${t.workspaceId}
135
135
  AND rating IS NOT NULL
@@ -139,41 +139,41 @@ ${r.join(`
139
139
  LIMIT ${t.limit}
140
140
  `;return drizzleOrm.sql`
141
141
  SELECT t.id AS taskId, t.agent_id AS agentId, t.thread_id AS threadId, t.status AS status,
142
- substr(t.error, 1, ${_m}) AS errorHead,
142
+ substr(t.error, 1, ${Km}) AS errorHead,
143
143
  CASE WHEN json_valid(t.metadata) THEN json_extract(t.metadata, '$.terminalReason') END AS terminalReason,
144
144
  t.rating AS rating, t.rated_at AS ratedAt,
145
- NULLIF(substr(t.prompt, 1, ${Zi}), '') AS promptExcerpt,
146
- NULLIF(substr(t.result, 1, ${Zi}), '') AS resultExcerpt
145
+ NULLIF(substr(t.prompt, 1, ${ga}), '') AS promptExcerpt,
146
+ NULLIF(substr(t.result, 1, ${ga}), '') AS resultExcerpt
147
147
  FROM (${e}) AS page
148
148
  JOIN tasks t ON t.id = page.id
149
149
  ORDER BY page.rated_at DESC, page.id DESC
150
- `}function hm(t,e){let n=Un(e.workspaceId,"workspaceId");if(e.agentId!==void 0&&Un(e.agentId,"agentId"),!Number.isFinite(e.limit)||Math.trunc(e.limit)<1)throw new f("VALIDATION","limit must be a positive integer");let r=Math.min(Math.trunc(e.limit),il),o=e.sinceIso===void 0?void 0:ea(e.sinceIso,"sinceIso");try{return t.all(al({workspaceId:n,agentId:e.agentId,sinceIso:o,limit:r})).map(i=>({taskId:i.taskId,agentId:i.agentId,threadId:i.threadId,status:Ue({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(s){throw s instanceof f?s:new f("DB_ERROR","Failed to list rated tasks",s)}}function dl(t){return drizzleOrm.sql`
150
+ `}function Xm(t,e){let n=Zn(e.workspaceId,"workspaceId");if(e.agentId!==void 0&&Zn(e.agentId,"agentId"),!Number.isFinite(e.limit)||Math.trunc(e.limit)<1)throw new f("VALIDATION","limit must be a positive integer");let r=Math.min(Math.trunc(e.limit),vl),o=e.sinceIso===void 0?void 0:ha(e.sinceIso,"sinceIso");try{return t.all(bl({workspaceId:n,agentId:e.agentId,sinceIso:o,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(s){throw s instanceof f?s:new f("DB_ERROR","Failed to list rated tasks",s)}}function Cl(t){return drizzleOrm.sql`
151
151
  SELECT COUNT(*) AS total FROM tasks
152
152
  WHERE workspace_id = ${t.workspaceId}
153
153
  AND rating IS NOT NULL
154
154
  ${t.agentId!==void 0?drizzleOrm.sql`AND agent_id = ${t.agentId}`:drizzleOrm.sql``}
155
155
  ${t.sinceIso!==void 0?drizzleOrm.sql`AND rated_at >= ${t.sinceIso}`:drizzleOrm.sql``}
156
- `}function mm(t,e){let n=Un(e.workspaceId,"workspaceId");e.agentId!==void 0&&Un(e.agentId,"agentId");let r=e.sinceIso===void 0?void 0:ea(e.sinceIso,"sinceIso");try{return t.all(dl({workspaceId:n,agentId:e.agentId,sinceIso:r}))[0]?.total??0}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to count rated tasks",o)}}var Bi,Mn,rm,$n,Hn,om,Gi,Ar,Ve,Ji,el,sm,am,tl,Qi,rl,ol,vr,sl,Zi,il,_m,Cr,fm,Hi=C(()=>{g();Ct();Kt();zt();vt();rn();ro();so();qd();co();tc();rc();ki();yr();Rr();$i();Rr();ro();Bi=40,Mn="2026-05-09",rm="0.8.9-rc.13",$n=10,Hn=parseInt(rm.split("rc.")[1]);om=new Set(["workflow","mcp"]),Gi="usageByEpoch",Ar="lateUsage",Ve="usageAccounting",Ji="Stopped by user",el="Stopped by app shutdown",sm="terminalErrorOriginal";am=["pending","running"];tl=new Set(["http","cli","instruction","workflow","internal"]);Qi=600*1e3,rl=600*1e3,ol=300*1e3;vr=class extends ve{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=Re.join(e.dbRoot,".crewx","crewx.db")),this.taskLogRepository=new uo({dbPath:this.dbPath});}resolveDbPath(){return this.dbPath?jt(this.dbPath):super.resolveDbPath()}openHandle(e){let n=this.resolveDbPath();if(e){let o=Re.dirname(n);nu.existsSync(o)||nu.mkdirSync(o,{recursive:true});}else if(!nu.existsSync(n))throw new f("NOT_FOUND","Database not found");let r=U(n);if(e)try{Be(r.db,n);}catch(o){throw r.close(),o}return r}heartbeatTask(e){let n=this.openHandle(true);try{let r=z(e.runEpoch),o=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),o,drizzleOrm.eq(a.status,"running"))).run().changes>0}catch(r){throw r instanceof f?r:new f("DB_ERROR","Failed to heartbeat task",r)}finally{n.close();}}requestTaskStop(e){if(!this.dbExists())return {accepted:false,status:"not_running",runEpoch:0};let n=this.openHandle(true);try{let r={accepted:!1,status:"not_running",runEpoch:0};return n.db.transaction(o=>{let s=o.select({id:a.id,status:a.status,run_epoch:a.run_epoch,stop_requested_at:a.stop_requested_at,stop_requested_epoch:a.stop_requested_epoch,metadata:a.metadata}).from(a).where(drizzleOrm.eq(a.id,e.id)).limit(1).get();if(!s)return;let i=z(s.run_epoch);if(s.status!=="running"){r={accepted:!1,status:s.status,runEpoch:i};return}let c=s.stop_requested_at!==null&&z(s.stop_requested_epoch)===i,d=c?s.stop_requested_at:e.requestedAt,u=pe(s.metadata),l=c?cm(s.metadata)??Mo({origin:e.origin,at:d,callerPid:e.callerPid,callerTaskId:e.callerTaskId},d):Mo({origin:e.origin,at:d,callerPid:e.callerPid,callerTaskId:e.callerTaskId},d);if(o.update(a).set({stop_requested_at:e.requestedAt,stop_requested_epoch:drizzleOrm.sql`${a.run_epoch}`,metadata:JSON.stringify({...u,stopRequest:l})}).where(drizzleOrm.and(drizzleOrm.eq(a.id,e.id),drizzleOrm.eq(a.status,"running"),Yu())).run().changes===0){let m=o.select({status:a.status,run_epoch:a.run_epoch,stop_requested_at:a.stop_requested_at,stop_requested_epoch:a.stop_requested_epoch}).from(a).where(drizzleOrm.eq(a.id,e.id)).limit(1).get();if(!m||m.status!=="running"){r={accepted:!1,status:m?.status??"not_running",runEpoch:z(m?.run_epoch)};return}r={accepted:!1,status:m.status,runEpoch:z(m.run_epoch),...m.stop_requested_at&&z(m.stop_requested_epoch)===z(m.run_epoch)?{alreadyRequestedAt:m.stop_requested_at}:{}};}else r={accepted:!0,status:s.status,runEpoch:i};let _=new Set([e.id]),h=(m,k)=>{if(k>=8)return;let E=o.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 b of E)_.has(b.id)||(_.add(b.id),o.update(a).set({stop_requested_at:d,stop_requested_epoch:drizzleOrm.sql`${a.run_epoch}`,metadata:JSON.stringify({...pe(b.metadata),stopRequest:l})}).where(drizzleOrm.and(drizzleOrm.eq(a.id,b.id),drizzleOrm.eq(a.status,"running"),Yu())).run(),h(b.id,k+1));};h(e.id,0);},{behavior:"immediate"}),r}catch(r){throw r instanceof f?r:new f("DB_ERROR","Failed to request task stop",r)}finally{n.close();}}requestTaskStopForInstruction(e){if(!this.dbExists())return {accepted:false,status:"not_running",runEpoch:0};let n=this.openHandle(true);try{let r={accepted:!1,status:"not_running",runEpoch:0};return n.db.transaction(o=>{let s=o.select({id:a.id,status:a.status,run_epoch:a.run_epoch,workspace_id:a.workspace_id,stop_requested_at:a.stop_requested_at,stop_requested_epoch:a.stop_requested_epoch,metadata:a.metadata}).from(a).where(drizzleOrm.eq(a.id,e.id)).limit(1).get();if(!s)return;let i=z(s.run_epoch),c=z(e.sourceRunEpoch),d=z(e.settleRunEpoch);if(s.status!=="running"||i!==d||e.workspaceId!==void 0&&s.workspace_id!==e.workspaceId){r={accepted:!1,status:s.status,runEpoch:i};return}let u=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,c)),p=Mo({origin:"instruction",at:e.requestedAt,callerPid:e.callerPid,callerTaskId:e.callerTaskId},e.requestedAt),_=JSON.stringify({...pe(s.metadata),stopRequest:p}),h=T=>o.update(a).set({stop_requested_at:e.requestedAt,stop_requested_epoch:c,metadata:_}).where(drizzleOrm.and(drizzleOrm.eq(a.id,e.id),drizzleOrm.eq(a.status,"running"),u,T,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:z(k.run_epoch),stopRequestReceipt:{taskId:k.id,workspaceId:k.workspace_id,sourceRunEpoch:c,settleRunEpoch:z(k.run_epoch),stopRequestedAt:k.stop_requested_at,stopRequestedEpoch:z(k.stop_requested_epoch),metadataBefore:s.metadata,metadataAfter:k.metadata}};return}let E=o.select({status:a.status,run_epoch:a.run_epoch,stop_requested_at:a.stop_requested_at,stop_requested_epoch:a.stop_requested_epoch}).from(a).where(drizzleOrm.eq(a.id,e.id)).limit(1).get();if(!E||E.status!=="running"){r={accepted:!1,status:E?.status??"not_running",runEpoch:z(E?.run_epoch)};return}let b=z(E.run_epoch);r={accepted:!1,status:E.status,runEpoch:b,...E.stop_requested_at&&z(E.stop_requested_epoch)===c?{alreadyRequestedAt:E.stop_requested_at}:{}};},{behavior:"immediate"}),r}catch(r){throw r instanceof f?r:new f("DB_ERROR","Failed to request instruction task stop",r)}finally{n.close();}}finalizeTaskStop(e){if(!this.dbExists())return false;let n=this.openHandle(true);try{let r=e.completedAt??new Date(this.clock()).toISOString(),o=!1;return n.db.transaction(s=>{let i=s.select({status:a.status,run_epoch:a.run_epoch,stop_requested_at:a.stop_requested_at,stop_requested_epoch:a.stop_requested_epoch,started_at:a.started_at,duration_ms:a.duration_ms,metadata:a.metadata}).from(a).where(drizzleOrm.eq(a.id,e.id)).limit(1).get();if(!i||i.status!=="running"||z(i.run_epoch)!==z(e.runEpoch))return;let c=i.stop_requested_at!==null&&z(i.stop_requested_epoch)===z(e.runEpoch),d=pe(i.metadata),u=c?ji(d,e.error):{error:e.error??null,metadata:e.terminalReason===void 0?{...d}:{...d,terminalReason:e.terminalReason}},l={...u.metadata,stopMethod:e.method},p=i.duration_ms??e.durationMs??$o(i.started_at,r,void 0),_=i.run_epoch===null?drizzleOrm.isNull(a.run_epoch):drizzleOrm.eq(a.run_epoch,i.run_epoch);o=s.update(a).set({status:"stopped",error:u.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"),_)).run().changes>0;},{behavior:"immediate"}),o}catch(r){throw r instanceof f?r:new f("DB_ERROR","Failed to finalize task stop",r)}finally{n.close();}}finalizeTaskForHostShutdown(e){if(!this.dbExists())return "not_running";let n=this.openHandle(true);try{let r=e.completedAt??new Date(this.clock()).toISOString(),o=z(e.expectedRunEpoch),s="not_running";return n.db.transaction(i=>{let c=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(!c||c.status!=="running"){s="not_running";return}if(z(c.run_epoch)!==o){s="epoch_mismatch";return}if(e.workspaceId!==void 0&&c.workspace_id!==e.workspaceId){s="workspace_mismatch";return}let u=c.run_epoch===null?drizzleOrm.isNull(a.run_epoch):drizzleOrm.eq(a.run_epoch,c.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={...pe(c.metadata),terminalReason:"runner_lost"},_=c.duration_ms??$o(c.started_at,r,void 0);s=i.update(a).set({status:"failed",error:el,completed_at:r,duration_ms:_,metadata:JSON.stringify(p)}).where(drizzleOrm.and(drizzleOrm.eq(a.id,e.id),drizzleOrm.eq(a.status,"running"),u,l)).run().changes>0?"settled":"not_running";},{behavior:"immediate"}),s}catch(r){throw r instanceof f?r:new f("DB_ERROR","Failed to finalize task for host shutdown",r)}finally{n.close();}}async stopTask(e,n={}){return Ju(this,e,n)}async stopTaskGenerationForInstruction(e){return Ku({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,o=r?n.db.select({id:a.id}).from(a).where(drizzleOrm.eq(a.id,e.id)).get()!==void 0:!0,s={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:Ki(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:Dd(e.metadata),schedule_id:Ud(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=c=>{n.db.insert(a).values(c).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(s);}catch(c){let d=c instanceof Error?c.message:typeof c=="object"&&c!==null&&"message"in c?String(c.message):String(c);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 c;let u=new Set(n.db.all("PRAGMA table_info(tasks)").map(Gt=>Gt.name)),l=u.has("cwd"),p=u.has("user_id"),_=u.has("actor_kind"),h=u.has("actor_id"),m=u.has("log_storage"),k=l?", cwd":"",E=l?", ?":"",b=l?", cwd = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN COALESCE(tasks.cwd, excluded.cwd) ELSE tasks.cwd END":"",T=m?", log_storage":"",P=m?", ?":"",A=p?", user_id":"",x=p?", ?":"",S=_?", actor_kind":"",K=_?", ?":"",te=h?", actor_id":"",De=h?", ?":"",we=m?`,
156
+ `}function Ym(t,e){let n=Zn(e.workspaceId,"workspaceId");e.agentId!==void 0&&Zn(e.agentId,"agentId");let r=e.sinceIso===void 0?void 0:ha(e.sinceIso,"sinceIso");try{return t.all(Cl({workspaceId:n,agentId:e.agentId,sinceIso:r}))[0]?.total??0}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to count rated tasks",o)}}var oa,Xn,$m,Yn,Qn,Hm,ia,Ur,Ze,ua,Rl,Um,Bm,Sl,fa,Al,Nl,Fr,Ol,ga,vl,Km,Wr,Jm,ea=b(()=>{g();Ot();qt();Bt();Nt();Gt();ho();ko();cc();wo();Sc();Ac();Pi();Kn();Mr();Zi();Mr();ho();oa=40,Xn="2026-05-09",$m="0.8.9-rc.13",Yn=10,Qn=parseInt($m.split("rc.")[1]);Hm=new Set(["workflow","mcp"]),ia="usageByEpoch",Ur="lateUsage",Ze="usageAccounting",ua="Stopped by user",Rl="Stopped by app shutdown",Um="terminalErrorOriginal";Bm=["pending","running"];Sl=new Set(["http","cli","instruction","workflow","internal"]);fa=600*1e3,Al=600*1e3,Nl=300*1e3;Fr=class extends me{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=Ne.join(e.dbRoot,".crewx","crewx.db")),this.taskLogRepository=new Eo({dbPath:this.dbPath});}resolveDbPath(){return this.dbPath?on(this.dbPath):super.resolveDbPath()}openHandle(e){let n=this.resolveDbPath();if(e){let o=Ne.dirname(n);Iu.existsSync(o)||Iu.mkdirSync(o,{recursive:true});}else if(!Iu.existsSync(n))throw new f("NOT_FOUND","Database not found");let r=H(n);if(e)try{Pe(r.db,n);}catch(o){throw r.close(),o}return r}heartbeatTask(e){let n=this.openHandle(true);try{let r=J(e.runEpoch),o=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),o,drizzleOrm.eq(a.status,"running"))).run().changes>0}catch(r){throw r instanceof f?r:new f("DB_ERROR","Failed to heartbeat task",r)}finally{n.close();}}requestTaskStop(e){if(!this.dbExists())return {accepted:false,status:"not_running",runEpoch:0};let n=this.openHandle(true);try{let r={accepted:!1,status:"not_running",runEpoch:0};return n.db.transaction(o=>{let s=o.select({id:a.id,status:a.status,run_epoch:a.run_epoch,stop_requested_at:a.stop_requested_at,stop_requested_epoch:a.stop_requested_epoch,metadata:a.metadata}).from(a).where(drizzleOrm.eq(a.id,e.id)).limit(1).get();if(!s)return;let i=J(s.run_epoch);if(s.status!=="running"){r={accepted:!1,status:s.status,runEpoch:i};return}let c=s.stop_requested_at!==null&&J(s.stop_requested_epoch)===i,d=c?s.stop_requested_at:e.requestedAt,u=fe(s.metadata),l=c?Wm(s.metadata)??Jo({origin:e.origin,at:d,callerPid:e.callerPid,callerTaskId:e.callerTaskId},d):Jo({origin:e.origin,at:d,callerPid:e.callerPid,callerTaskId:e.callerTaskId},d);if(o.update(a).set({stop_requested_at:e.requestedAt,stop_requested_epoch:drizzleOrm.sql`${a.run_epoch}`,metadata:JSON.stringify({...u,stopRequest:l})}).where(drizzleOrm.and(drizzleOrm.eq(a.id,e.id),drizzleOrm.eq(a.status,"running"),Tl())).run().changes===0){let m=o.select({status:a.status,run_epoch:a.run_epoch,stop_requested_at:a.stop_requested_at,stop_requested_epoch:a.stop_requested_epoch}).from(a).where(drizzleOrm.eq(a.id,e.id)).limit(1).get();if(!m||m.status!=="running"){r={accepted:!1,status:m?.status??"not_running",runEpoch:J(m?.run_epoch)};return}r={accepted:!1,status:m.status,runEpoch:J(m.run_epoch),...m.stop_requested_at&&J(m.stop_requested_epoch)===J(m.run_epoch)?{alreadyRequestedAt:m.stop_requested_at}:{}};}else r={accepted:!0,status:s.status,runEpoch:i};let _=new Set([e.id]),h=(m,k)=>{if(k>=8)return;let w=o.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 C of w)_.has(C.id)||(_.add(C.id),o.update(a).set({stop_requested_at:d,stop_requested_epoch:drizzleOrm.sql`${a.run_epoch}`,metadata:JSON.stringify({...fe(C.metadata),stopRequest:l})}).where(drizzleOrm.and(drizzleOrm.eq(a.id,C.id),drizzleOrm.eq(a.status,"running"),Tl())).run(),h(C.id,k+1));};h(e.id,0);},{behavior:"immediate"}),r}catch(r){throw r instanceof f?r:new f("DB_ERROR","Failed to request task stop",r)}finally{n.close();}}requestTaskStopForInstruction(e){if(!this.dbExists())return {accepted:false,status:"not_running",runEpoch:0};let n=this.openHandle(true);try{let r={accepted:!1,status:"not_running",runEpoch:0};return n.db.transaction(o=>{let s=o.select({id:a.id,status:a.status,run_epoch:a.run_epoch,workspace_id:a.workspace_id,stop_requested_at:a.stop_requested_at,stop_requested_epoch:a.stop_requested_epoch,metadata:a.metadata}).from(a).where(drizzleOrm.eq(a.id,e.id)).limit(1).get();if(!s)return;let i=J(s.run_epoch),c=J(e.sourceRunEpoch),d=J(e.settleRunEpoch);if(s.status!=="running"||i!==d||e.workspaceId!==void 0&&s.workspace_id!==e.workspaceId){r={accepted:!1,status:s.status,runEpoch:i};return}let u=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,c)),p=Jo({origin:"instruction",at:e.requestedAt,callerPid:e.callerPid,callerTaskId:e.callerTaskId},e.requestedAt),_=JSON.stringify({...fe(s.metadata),stopRequest:p}),h=T=>o.update(a).set({stop_requested_at:e.requestedAt,stop_requested_epoch:c,metadata:_}).where(drizzleOrm.and(drizzleOrm.eq(a.id,e.id),drizzleOrm.eq(a.status,"running"),u,T,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:J(k.run_epoch),stopRequestReceipt:{taskId:k.id,workspaceId:k.workspace_id,sourceRunEpoch:c,settleRunEpoch:J(k.run_epoch),stopRequestedAt:k.stop_requested_at,stopRequestedEpoch:J(k.stop_requested_epoch),metadataBefore:s.metadata,metadataAfter:k.metadata}};return}let w=o.select({status:a.status,run_epoch:a.run_epoch,stop_requested_at:a.stop_requested_at,stop_requested_epoch:a.stop_requested_epoch}).from(a).where(drizzleOrm.eq(a.id,e.id)).limit(1).get();if(!w||w.status!=="running"){r={accepted:!1,status:w?.status??"not_running",runEpoch:J(w?.run_epoch)};return}let C=J(w.run_epoch);r={accepted:!1,status:w.status,runEpoch:C,...w.stop_requested_at&&J(w.stop_requested_epoch)===c?{alreadyRequestedAt:w.stop_requested_at}:{}};},{behavior:"immediate"}),r}catch(r){throw r instanceof f?r:new f("DB_ERROR","Failed to request instruction task stop",r)}finally{n.close();}}finalizeTaskStop(e){if(!this.dbExists())return false;let n=this.openHandle(true);try{let r=e.completedAt??new Date(this.clock()).toISOString(),o=!1;return n.db.transaction(s=>{let i=s.select({status:a.status,run_epoch:a.run_epoch,stop_requested_at:a.stop_requested_at,stop_requested_epoch:a.stop_requested_epoch,started_at:a.started_at,duration_ms:a.duration_ms,metadata:a.metadata}).from(a).where(drizzleOrm.eq(a.id,e.id)).limit(1).get();if(!i||i.status!=="running"||J(i.run_epoch)!==J(e.runEpoch))return;let c=i.stop_requested_at!==null&&J(i.stop_requested_epoch)===J(e.runEpoch),d=fe(i.metadata),u=c?aa(d,e.error):{error:e.error??null,metadata:e.terminalReason===void 0?{...d}:{...d,terminalReason:e.terminalReason}},l={...u.metadata,stopMethod:e.method},p=i.duration_ms??e.durationMs??Vo(i.started_at,r,void 0),_=i.run_epoch===null?drizzleOrm.isNull(a.run_epoch):drizzleOrm.eq(a.run_epoch,i.run_epoch);o=s.update(a).set({status:"stopped",error:u.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"),_)).run().changes>0;},{behavior:"immediate"}),o}catch(r){throw r instanceof f?r:new f("DB_ERROR","Failed to finalize task stop",r)}finally{n.close();}}finalizeTaskForHostShutdown(e){if(!this.dbExists())return "not_running";let n=this.openHandle(true);try{let r=e.completedAt??new Date(this.clock()).toISOString(),o=J(e.expectedRunEpoch),s="not_running";return n.db.transaction(i=>{let c=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(!c||c.status!=="running"){s="not_running";return}if(J(c.run_epoch)!==o){s="epoch_mismatch";return}if(e.workspaceId!==void 0&&c.workspace_id!==e.workspaceId){s="workspace_mismatch";return}let u=c.run_epoch===null?drizzleOrm.isNull(a.run_epoch):drizzleOrm.eq(a.run_epoch,c.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={...fe(c.metadata),terminalReason:"runner_lost"},_=c.duration_ms??Vo(c.started_at,r,void 0);s=i.update(a).set({status:"failed",error:Rl,completed_at:r,duration_ms:_,metadata:JSON.stringify(p)}).where(drizzleOrm.and(drizzleOrm.eq(a.id,e.id),drizzleOrm.eq(a.status,"running"),u,l)).run().changes>0?"settled":"not_running";},{behavior:"immediate"}),s}catch(r){throw r instanceof f?r:new f("DB_ERROR","Failed to finalize task for host shutdown",r)}finally{n.close();}}async stopTask(e,n={}){return ml(this,e,n)}async stopTaskGenerationForInstruction(e){return gl({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,o=r?n.db.select({id:a.id}).from(a).where(drizzleOrm.eq(a.id,e.id)).get()!==void 0:!0,s={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:da(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:nc(e.metadata),schedule_id:dc(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=c=>{n.db.insert(a).values(c).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(s);}catch(c){let d=c instanceof Error?c.message:typeof c=="object"&&c!==null&&"message"in c?String(c.message):String(c);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 c;let u=new Set(n.db.all("PRAGMA table_info(tasks)").map(rn=>rn.name)),l=u.has("cwd"),p=u.has("user_id"),_=u.has("actor_kind"),h=u.has("actor_id"),m=u.has("log_storage"),k=l?", cwd":"",w=l?", ?":"",C=l?", cwd = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN COALESCE(tasks.cwd, excluded.cwd) ELSE tasks.cwd END":"",T=m?", log_storage":"",P=m?", ?":"",A=p?", user_id":"",x=p?", ?":"",I=_?", actor_kind":"",K=_?", ?":"",re=h?", actor_id":"",Ue=h?", ?":"",Ie=m?`,
157
157
  log_storage = CASE WHEN tasks.status = 'pending' THEN excluded.log_storage ELSE tasks.log_storage END`:"";n.runRaw(`INSERT INTO tasks (
158
158
  id, agent_id, prompt, mode, status, started_at, pid,
159
159
  parent_task_id, caller_agent_id, trace_id, command, metadata,
160
160
  workspace_id${k}, project_id, platform, crewx_version, thread_id,
161
- model, rendered_prompt, coding_agent_command${A}${S}${te}${T}
162
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?${E}${x}${K}${De}${P})
161
+ model, rendered_prompt, coding_agent_command${A}${I}${re}${T}
162
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?${w}${x}${K}${Ue}${P})
163
163
  ON CONFLICT(id) DO UPDATE SET
164
164
  status = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN 'running' ELSE tasks.status END,
165
165
  pid = COALESCE(excluded.pid, tasks.pid),
166
166
  command = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN excluded.command ELSE tasks.command END,
167
167
  metadata = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN excluded.metadata ELSE tasks.metadata END,
168
- workspace_id = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN COALESCE(tasks.workspace_id, excluded.workspace_id) ELSE tasks.workspace_id END${b},
168
+ workspace_id = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN COALESCE(tasks.workspace_id, excluded.workspace_id) ELSE tasks.workspace_id END${C},
169
169
  project_id = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN COALESCE(tasks.project_id, excluded.project_id) ELSE tasks.project_id END,
170
170
  crewx_version = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN excluded.crewx_version ELSE tasks.crewx_version END,
171
171
  model = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN excluded.model ELSE tasks.model END,
172
172
  rendered_prompt = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN excluded.rendered_prompt ELSE tasks.rendered_prompt END,
173
- coding_agent_command = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN excluded.coding_agent_command ELSE tasks.coding_agent_command END${we}
174
- WHERE tasks.status = 'running' OR (tasks.status = 'pending' AND tasks.pid IS NULL)`,[s.id,s.agent_id,s.prompt,s.mode,s.status,s.started_at,s.pid,s.parent_task_id,s.caller_agent_id,s.trace_id,s.command,s.metadata,s.workspace_id,...l?[s.cwd]:[],s.project_id,s.platform,s.crewx_version,s.thread_id,s.model,s.rendered_prompt,s.coding_agent_command,...p?[s.user_id]:[],..._?[s.actor_kind]:[],...h?[s.actor_id]:[],...m?[s.log_storage]:[]]);}r&&!o&&new lo({dbPath:this.resolveDbPath()}).recordAccepted({workspaceId:e.workspaceId,actorId:e.actorId,actorKind:e.actorKind,agentId:e.agentId});}catch(r){throw r instanceof f?r:new f("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"||z(r.run_epoch)!==z(e.runEpoch))return !1;let o=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:Ki(e.pid,this.processControl)}).where(drizzleOrm.and(drizzleOrm.eq(a.id,e.id),drizzleOrm.eq(a.status,"running"),o)).run().changes>0}catch(r){throw r instanceof f?r:new f("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"||z(r.run_epoch)!==z(e.runEpoch))return !1;let o=dm(r.metadata,e.runtime?.metadata);if(o.ownership=e.ownership,e.ownership==="runner"&&e.providerPid!==void 0){o.providerPid=e.providerPid;let c=Ki(e.providerPid,this.processControl);c!==null?o.providerPidStartedAt=c:delete o.providerPidStartedAt;}let s=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(o),model:Lo(r.model,e.runtime?.model),rendered_prompt:Lo(r.rendered_prompt,e.runtime?.renderedPrompt),security_key:Lo(r.security_key,e.runtime?.securityKey),coding_agent_command:Lo(r.coding_agent_command,e.runtime?.codingAgentCommand)}).where(drizzleOrm.and(drizzleOrm.eq(a.id,e.id),drizzleOrm.eq(a.status,"running"),s)).run();return i.changes>0&&z(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"),s,drizzleOrm.sql`${a.stop_requested_at} IS NOT NULL
175
- AND COALESCE(${a.stop_requested_epoch}, 0) <> COALESCE(${a.run_epoch}, 0)`)).run(),i.changes>0}catch(r){throw r instanceof f?r:new f("DB_ERROR","Failed to update task ownership",r)}finally{n.close();}}adoptPendingTask(e){let n=this.openHandle(true);try{return n.db.update(a).set({status:"running"}).where(drizzleOrm.and(drizzleOrm.eq(a.id,e),drizzleOrm.eq(a.status,"pending"),drizzleOrm.isNull(a.pid))).run().changes===1}catch(r){throw r instanceof f?r:new f("DB_ERROR","Failed to adopt pending task",r)}finally{n.close();}}failPendingTask(e,n,r=new Date().toISOString()){let o=this.openHandle(true);try{return o.db.update(a).set({status:"failed",error:n,completed_at:r}).where(drizzleOrm.and(drizzleOrm.eq(a.id,e),drizzleOrm.eq(a.status,"pending"))).run().changes>0}catch(s){throw s instanceof f?s:new f("DB_ERROR","Failed to fail pending task",s)}finally{o.close();}}stopPendingTask(e,n,r=new Date().toISOString(),o={}){let s=this.openHandle(true);try{let i=!1;return s.db.transaction(c=>{let d=c.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 u=ji(pe(d.metadata),n),l={...u.metadata,stopMethod:"cooperative",stopRequest:Mo(o,r)};i=c.update(a).set({status:"stopped",error:u.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 f?i:new f("DB_ERROR","Failed to stop pending task",i)}finally{s.close();}}listTasksByProjectId(e){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.select(ce).from(a).where(drizzleOrm.eq(a.project_id,e)).orderBy(drizzleOrm.desc(a.started_at)).all().map(st)}catch(r){throw r instanceof f?r:new f("DB_ERROR","Failed to list tasks by project",r)}finally{n.close();}}finishTask(e){let n=this.openHandle(true),r,o;try{n.db.transaction(s=>{let i=s.select({status:a.status,run_epoch:a.run_epoch,stop_requested_at:a.stop_requested_at,stop_requested_epoch:a.stop_requested_epoch,started_at:a.started_at,duration_ms:a.duration_ms,result:a.result,exit_code:a.exit_code,error:a.error,metadata:a.metadata,model:a.model,input_tokens:a.input_tokens,output_tokens:a.output_tokens,cached_input_tokens:a.cached_input_tokens,cost_usd:a.cost_usd}).from(a).where(drizzleOrm.eq(a.id,e.id)).limit(1).get();if(!i)return;let c=z(i.run_epoch),d=z(e.runEpoch),u=i.status==="running"&&c===d,l=i.stop_requested_at!==null&&z(i.stop_requested_epoch)===c,p=u&&l,_=i.status==="stopped"&&c===d&&l,h=pe(i.metadata),m=pn(h[Ar])?h[Ar]:{},k=String(d),E=im(i),b=E&&c===d&&!Xi(i)&&!Object.prototype.hasOwnProperty.call(m,k),T=E&&c===d&&!Object.prototype.hasOwnProperty.call(m,k),P=c>0||d>0||e.runEpoch!==void 0&&e.runEpoch!==null||e.usageComplete!==void 0||c!==d,A={},x;if(i.status!=="running"&&(r=i.status,o=e.result?.trim()||e.error?.trim()||`task:end status=${e.status}`),P&&(i.status==="running"||T)){x=pe(i.metadata);let S=pn(x[Gi])?{...x[Gi]}:{},K=String(d),te=Qu(e),De=Or(S[K]);e.usageComplete!==void 0?S[K]={...te,accounting:e.usagePresent===!0?e.usageComplete?"recorded":"partial":"unavailable"}:De!==void 0?S[K]={...te,accounting:De}:S[K]=te,x[Gi]=S;let we=pm(S),Gt=Yi(we),Fr=Object.values(S).some(um),$l=Object.values(S).some(Hl=>Or(Hl)!==void 0);e.usageComplete!==void 0||$l?(x[Ve]=Fr?"recorded":"unavailable",lm(S)?x.usageIncomplete=!0:delete x.usageIncomplete):Gt&&h[Ve]==="unavailable"?x[Ve]="recorded":i.status!=="running"&&!Gt&&h[Ve]===void 0&&(x[Ve]="unavailable"),A.metadata=JSON.stringify(x),A.input_tokens=we.inputTokens,A.output_tokens=we.outputTokens,A.cached_input_tokens=we.cachedInputTokens,A.cost_usd=we.costUsd;}else if(u||b)if(u)A.input_tokens=ye(e.inputTokens??0),A.output_tokens=ye(e.outputTokens??0),A.cached_input_tokens=ye(e.cachedInputTokens??0),A.cost_usd=ye(e.costUsd??0);else {let S=Qu(e),K=e.usageComplete!==void 0?e.usagePresent===!0:Yi(S);K&&(A.input_tokens=S.inputTokens,A.output_tokens=S.outputTokens,A.cached_input_tokens=S.cachedInputTokens,A.cost_usd=S.costUsd),x={...h};let te=pn(h[Ar])?{...h[Ar]}:{};te[k]={at:e.completedAt},x[Ar]=te,x[Ve]===void 0?x[Ve]=K?"recorded":"unavailable":K&&x[Ve]==="unavailable"&&(x[Ve]="recorded"),A.metadata=JSON.stringify(x);}if((u||b)&&e.model!==void 0&&e.model!==null&&(!b||i.model===null)&&(A.model=e.model),p){x??=pe(i.metadata);let S=ji(x,e.error);x={...S.metadata,...e.partialResultRecovered===!0?{partialResultRecovered:!0}:{},stopMethod:Do(i.stop_requested_at,e.completedAt)},A.status="stopped",A.result=e.result??i.result,A.error=S.error,A.completed_at=e.completedAt,A.duration_ms=i.duration_ms??e.durationMs??$o(i.started_at,e.completedAt,void 0),A.exit_code=e.exitCode??i.exit_code,A.metadata=JSON.stringify(x);}else if(u)e.partialResultRecovered===!0&&(x??=pe(i.metadata),x.partialResultRecovered=!0,A.metadata=JSON.stringify(x)),A.status=e.status,A.result=e.result??null,A.error=e.error??null,A.completed_at=e.completedAt,A.duration_ms=c>0?$o(i.started_at,e.completedAt,e.durationMs):e.durationMs??null,A.exit_code=e.exitCode??null;else if(_){let S=!1;i.result===null&&e.result!==void 0&&e.result!==null&&(A.result=e.result,S=!0),i.exit_code===null&&e.exitCode!==void 0&&e.exitCode!==null&&(A.exit_code=e.exitCode),e.partialResultRecovered===!0&&(x??=pe(i.metadata),x.partialResultRecovered=!0,A.metadata=JSON.stringify(x)),S&&(r=void 0,o=void 0);}Object.keys(A).length>0&&s.update(a).set(A).where(drizzleOrm.eq(a.id,e.id)).run();},{behavior:"immediate"});}catch(s){throw s instanceof f?s:new f("DB_ERROR","Failed to finish task",s)}finally{n.close();}if(r!==void 0){try{this.taskLogRepository.appendLog(e.id,{timestamp:e.completedAt,level:"late-result",message:o??`task:end status=${e.status}`});}catch(s){console.error(`[crewx] failed to preserve late task result for ${e.id}: ${s instanceof Error?s.message:String(s)}`);}process.stderr.write(`Task ${e.id} was already finalized (${r}); late result kept in task log
176
- `);}}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)),o={status:e.status,error:e.error,completed_at:e.completedAt,duration_ms:e.durationMs};if(e.terminalReason){let s=n.db.select({metadata:a.metadata}).from(a).where(r).limit(1).get(),i=pe(s?.metadata??null);i.terminalReason=e.terminalReason,o.metadata=JSON.stringify(i);}n.db.update(a).set(o).where(r).run();}catch(r){throw r instanceof f?r:new f("DB_ERROR","Failed to update task lifecycle",r)}finally{n.close();}}appendLog(e,n){this.taskLogRepository.appendLog(e,n);}appendLogs(e,n){this.taskLogRepository.appendLogs(e,n);}readLogs(e){return this.taskLogRepository.readLogs(e)}readLogsTail(e,n){return this.taskLogRepository.readLogsTail(e,n)}getLogState(e){return this.taskLogRepository.getLogState(e)}getRunningTasks(){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select(ce).from(a).where(drizzleOrm.eq(a.status,"running")).orderBy(drizzleOrm.desc(a.started_at)).all().map(st)}catch(n){throw new f("DB_ERROR","Failed to get running tasks",n)}finally{e.close();}}getActiveTasks(){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select(ce).from(a).where(drizzleOrm.inArray(a.status,["pending","running"])).orderBy(drizzleOrm.desc(a.started_at)).all().map(st)}catch(n){throw new f("DB_ERROR","Failed to get active tasks",n)}finally{e.close();}}getAllTasks(){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select(ce).from(a).orderBy(drizzleOrm.desc(a.started_at)).limit(100).all().map(st)}catch(n){throw new f("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 f("DB_ERROR","Failed to read task security key",r)}finally{n.close();}}recordProviderInput(e){if(!this.dbExists())return false;let n=z(e.runEpoch);if(n===0&&e.interceptedRequest!==true)return false;let r=e.recordedAt??new Date(this.clock()).toISOString(),o=this.openHandle(true);try{let s=!1;return o.db.transaction(i=>{let c=i.select({run_epoch:a.run_epoch}).from(a).where(drizzleOrm.eq(a.id,e.id)).limit(1).get();if(!c||z(c.run_epoch)!==n)return;s=i.insert(wt).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;}),s}catch(s){throw s instanceof f?s:new f("DB_ERROR","Failed to record provider input",s)}finally{o.close();}}listProviderInputEpochs(e,n={}){if(!this.dbExists())return [];let r=this.openHandle(false);try{let o=r.db.select({run_epoch:a.run_epoch}).from(a).where(drizzleOrm.eq(a.id,e)).limit(1).get();if(!o)return [];let s=z(o.run_epoch),i=r.db.select({run_epoch:wt.run_epoch,key_wrap_skipped:wt.key_wrap_skipped}).from(wt).where(drizzleOrm.eq(wt.task_id,e)).all(),c=new Map(i.map(u=>[u.run_epoch,u])),d=[];for(let u=1;u<=s;u++){let l=c.get(u);l?d.push({runEpoch:u,available:!0,...l.key_wrap_skipped===1?{keyWrapSkipped:!0}:{}}):d.push({runEpoch:u,available:!1,reason:n.archivedRunEpochs?.has(u)?"pruned":"absent"});}return d}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to list provider inputs",o)}finally{r.close();}}readProviderInput(e,n){if(!this.dbExists())return;let r=this.openHandle(false);try{let o=r.db.select().from(wt).where(drizzleOrm.and(drizzleOrm.eq(wt.task_id,e),drizzleOrm.eq(wt.run_epoch,z(n)))).limit(1).get();return o?{runEpoch:o.run_epoch,input:o.input,keyWrapSkipped:o.key_wrap_skipped===1,recordedAt:o.recorded_at}:void 0}catch(o){throw new f("DB_ERROR","Failed to read provider input",o)}finally{r.close();}}getTask(e){if(!this.dbExists())return;let n=this.openHandle(false);try{let r=n.db.select(ce).from(a).where(drizzleOrm.eq(a.id,e)).limit(1).get();return r?st(r):void 0}catch(r){throw new f("DB_ERROR","Failed to get task",r)}finally{n.close();}}async killTask(e){let n=await this.stopTask(e);return n.status==="stopped"?{status:"terminated",killed:n.method==="forced"||n.method==="cooperative",...n.pid?{pid:n.pid}:{}}:n.status==="not_running"?{status:"not_running",killed:false,...n.pid?{pid:n.pid}:{},...n.error?{error:n.error}:{}}:{status:"failed",killed:false,...n.pid?{pid:n.pid}:{},...n.error?{error:n.error}:{}}}reapOrphanedTasks(e={}){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(),o=this.clock(),s=Math.max(1,Math.trunc(e.tickIntervalMs??ol)),i=this.lastReaperTickAt,c=i===void 0?Number.POSITIVE_INFINITY:o-i,d=i!==void 0&&c>=0&&c<=s*2;this.lastReaperTickAt=o;let u=Ln(),l=xo(),p=new Date(o-rl).toISOString(),_=new Date(o).toISOString(),h=new Set,m=[],k=0,E=(T,P)=>{let A=pe(Vi(T.metadata,"runner_lost")),x=typeof A.provider=="string"?A.provider:void 0,S;try{S=vo({taskLogRepository:this.taskLogRepository,taskId:T.id,provider:x,model:T.model})?.usage;}catch{}let K={status:"failed",error:P,completed_at:_};S?(K.input_tokens=S.inputTokens,K.output_tokens=S.outputTokens,K.cached_input_tokens=S.cachedInputTokens,K.cost_usd=S.costUsd,T.model===null&&S.model!==null&&(K.model=S.model),A[Ve]="recorded"):!Xi(T)&&A[Ve]!=="recorded"&&(A[Ve]="unavailable"),K.metadata=JSON.stringify(A);let te=T.run_epoch===null?drizzleOrm.isNull(a.run_epoch):drizzleOrm.eq(a.run_epoch,T.run_epoch),De=T.heartbeat_at===null?drizzleOrm.isNull(a.heartbeat_at):drizzleOrm.eq(a.heartbeat_at,T.heartbeat_at),we=n.db.update(a).set(K).where(drizzleOrm.and(drizzleOrm.eq(a.id,T.id),drizzleOrm.eq(a.status,"running"),te,De)).run();return we.changes>0&&k++,we.changes>0};for(let T of r){if(T.status==="pending"){if(T.pid!==null||T.started_at>=p)continue;let S=Vi(T.metadata,"launch_failed");n.db.update(a).set({status:"failed",error:"Reaped: runner never adopted task (pending timeout)",completed_at:_,metadata:S}).where(drizzleOrm.and(drizzleOrm.eq(a.id,T.id),drizzleOrm.eq(a.status,"pending"),drizzleOrm.isNull(a.pid),drizzleOrm.lt(a.started_at,p))).run().changes>0&&k++;continue}if(om.has(T.platform??"cli"))continue;if(T.pid===null){let S=`${T.id}:${T.run_epoch??0}`;h.add(S);let K=this.pidNullObservedSince.get(S);if(K===void 0){this.pidNullObservedSince.set(S,o);continue}o-K>=Qi&&E(T,"Reaped: pid never recorded after resume (stale running_instruction)")&&this.pidNullObservedSince.delete(S);continue}if(T.heartbeat_at===null){Pt(T.pid,this.processControl.kill)==="not_found"&&E(T,"Reaped: process not found (orphaned task)");continue}let P=Date.parse(T.heartbeat_at),A=Number.isFinite(P)?o-P:Number.POSITIVE_INFINITY;if(A<=u)continue;let x=Pi(T).filter(S=>Pt(S.pid,this.processControl.kill)!=="not_found");x.length===0?E(T,"Reaped: process not found (orphaned task)"):A>l&&d&&m.push({row:T,targets:x});}let b=new Map;for(let T of m){let{row:P,targets:A}=T,x=n.db.select({status:a.status,run_epoch:a.run_epoch,heartbeat_at:a.heartbeat_at}).from(a).where(drizzleOrm.eq(a.id,P.id)).get();if(!x||x.status!=="running"||z(x.run_epoch)!==z(P.run_epoch)||x.heartbeat_at!==P.heartbeat_at)continue;let S=await this.judgeRecordedTargets(P,A);if(S.unproven!==void 0){console.warn("[crewx] reaper left running task",{taskId:P.id,reason:S.unproven});continue}if(S.owned.length>0){let K=await this.terminateRecordedProcesses(S.owned,b);if(K!==void 0){console.warn("[crewx] reaper left running task",{taskId:P.id,reason:K});continue}}E(P,"Reaped: heartbeat stale beyond hard limit (orphaned task)")&&S.reused.length>0&&console.warn("[crewx] reaper reaped task whose recorded pid was reused",{taskId:P.id,reason:S.reused.join("; ")});}for(let T of Array.from(this.pidNullObservedSince.keys()))h.has(T)||this.pidNullObservedSince.delete(T);return k}finally{n.close();}}async judgeRecordedTargets(e,n){let r=e.heartbeat_at===null?Number.NaN:Date.parse(e.heartbeat_at),o=Number.isFinite(r)?r+wr()+ao:void 0,s=[],i=[];for(let c of n){let d=await Li(c,{processControlOptions:this.processControl,legacyStartBoundaryMs:o});if(d.verdict==="owned")s.push(c);else if(d.verdict==="reused")i.push(`pid ${c.pid} reused (${d.reason})`);else return {owned:s,reused:i,unproven:`pid ${c.pid} not proven owned (${d.ownership}): ${d.reason}`}}return {owned:s,reused:i}}async terminateRecordedProcesses(e,n){for(let r of e){if(!n.has(r.pid)){let o;try{o=(await Mt(r.pid,{...this.processControl,signal:Lt})).status==="failed"?"failed":"terminated";}catch{o="failed";}n.set(r.pid,o);}if(n.get(r.pid)==="failed")return `pid ${r.pid} termination not confirmed`;if(Pt(r.pid,this.processControl.kill)!=="not_found")return `pid ${r.pid} still alive after termination`}}reapRunningWorkflowTasks(e=Qi){if(!this.dbExists())return 0;let n=this.openHandle(true);try{let r=new Date(Date.now()-e).toISOString(),o=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),Xu())),s=n.db.select({id:a.id,metadata:a.metadata}).from(a).where(o).all(),i=new Date().toISOString(),c=0;for(let d of s){let u=pe(d.metadata);u.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(u)}).where(drizzleOrm.and(drizzleOrm.eq(a.id,d.id),drizzleOrm.eq(a.status,"running"))).run();c+=l.changes??0;}return c}finally{n.close();}}findTaskStatus(e,n){let r=this.resolveDbPaths();for(let o of r){if(!nu.existsSync(o))continue;let s=U(o);try{let i=n?drizzleOrm.eq(a.workspace_id,n):void 0,c=i?drizzleOrm.and(drizzleOrm.eq(a.id,e),i):drizzleOrm.eq(a.id,e),d=s.db.select(ce).from(a).where(c).limit(1).get()??void 0;if(!d){let u=i?drizzleOrm.and(drizzleOrm.eq(a.thread_id,e),i):drizzleOrm.eq(a.thread_id,e);d=s.db.select(ce).from(a).where(u).orderBy(drizzleOrm.desc(a.started_at)).limit(1).get()??void 0;}if(d)return st(d)}catch(i){throw new f("DB_ERROR","Failed to find task status",i)}finally{s.close();}}}findChildTasks(e,n){let r=this.resolveDbPaths(),o=new Set,s=[];for(let i of r){if(!nu.existsSync(i))continue;let c=U(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),u=c.db.select(ce).from(a).where(d).orderBy(drizzleOrm.asc(a.started_at)).all();for(let l of u)o.has(l.id)||(o.add(l.id),s.push(st(l)));}catch(d){throw new f("DB_ERROR","Failed to find child tasks",d)}finally{c.close();}}return s}getWorkspaceUsageSummary(e){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.all(e?drizzleOrm.sql`
173
+ coding_agent_command = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN excluded.coding_agent_command ELSE tasks.coding_agent_command END${Ie}
174
+ WHERE tasks.status = 'running' OR (tasks.status = 'pending' AND tasks.pid IS NULL)`,[s.id,s.agent_id,s.prompt,s.mode,s.status,s.started_at,s.pid,s.parent_task_id,s.caller_agent_id,s.trace_id,s.command,s.metadata,s.workspace_id,...l?[s.cwd]:[],s.project_id,s.platform,s.crewx_version,s.thread_id,s.model,s.rendered_prompt,s.coding_agent_command,...p?[s.user_id]:[],..._?[s.actor_kind]:[],...h?[s.actor_id]:[],...m?[s.log_storage]:[]]);}r&&!o&&new Ro({dbPath:this.resolveDbPath()}).recordAccepted({workspaceId:e.workspaceId,actorId:e.actorId,actorKind:e.actorKind,agentId:e.agentId});}catch(r){throw r instanceof f?r:new f("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"||J(r.run_epoch)!==J(e.runEpoch))return !1;let o=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:da(e.pid,this.processControl)}).where(drizzleOrm.and(drizzleOrm.eq(a.id,e.id),drizzleOrm.eq(a.status,"running"),o)).run().changes>0}catch(r){throw r instanceof f?r:new f("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"||J(r.run_epoch)!==J(e.runEpoch))return !1;let o=Fm(r.metadata,e.runtime?.metadata);if(o.ownership=e.ownership,e.ownership==="runner"&&e.providerPid!==void 0){o.providerPid=e.providerPid;let c=da(e.providerPid,this.processControl);c!==null?o.providerPidStartedAt=c:delete o.providerPidStartedAt;}let s=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(o),model:Ko(r.model,e.runtime?.model),rendered_prompt:Ko(r.rendered_prompt,e.runtime?.renderedPrompt),security_key:Ko(r.security_key,e.runtime?.securityKey),coding_agent_command:Ko(r.coding_agent_command,e.runtime?.codingAgentCommand)}).where(drizzleOrm.and(drizzleOrm.eq(a.id,e.id),drizzleOrm.eq(a.status,"running"),s)).run();return i.changes>0&&J(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"),s,drizzleOrm.sql`${a.stop_requested_at} IS NOT NULL
175
+ AND COALESCE(${a.stop_requested_epoch}, 0) <> COALESCE(${a.run_epoch}, 0)`)).run(),i.changes>0}catch(r){throw r instanceof f?r:new f("DB_ERROR","Failed to update task ownership",r)}finally{n.close();}}adoptPendingTask(e){let n=this.openHandle(true);try{return n.db.update(a).set({status:"running"}).where(drizzleOrm.and(drizzleOrm.eq(a.id,e),drizzleOrm.eq(a.status,"pending"),drizzleOrm.isNull(a.pid))).run().changes===1}catch(r){throw r instanceof f?r:new f("DB_ERROR","Failed to adopt pending task",r)}finally{n.close();}}failPendingTask(e,n,r=new Date().toISOString()){let o=this.openHandle(true);try{return o.db.update(a).set({status:"failed",error:n,completed_at:r}).where(drizzleOrm.and(drizzleOrm.eq(a.id,e),drizzleOrm.eq(a.status,"pending"))).run().changes>0}catch(s){throw s instanceof f?s:new f("DB_ERROR","Failed to fail pending task",s)}finally{o.close();}}stopPendingTask(e,n,r=new Date().toISOString(),o={}){let s=this.openHandle(true);try{let i=!1;return s.db.transaction(c=>{let d=c.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 u=aa(fe(d.metadata),n),l={...u.metadata,stopMethod:"cooperative",stopRequest:Jo(o,r)};i=c.update(a).set({status:"stopped",error:u.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 f?i:new f("DB_ERROR","Failed to stop pending task",i)}finally{s.close();}}listTasksByProjectId(e){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.select(le).from(a).where(drizzleOrm.eq(a.project_id,e)).orderBy(drizzleOrm.desc(a.started_at)).all().map(ct)}catch(r){throw r instanceof f?r:new f("DB_ERROR","Failed to list tasks by project",r)}finally{n.close();}}finishTask(e){let n=this.openHandle(true),r,o;try{n.db.transaction(s=>{let i=s.select({status:a.status,run_epoch:a.run_epoch,stop_requested_at:a.stop_requested_at,stop_requested_epoch:a.stop_requested_epoch,started_at:a.started_at,duration_ms:a.duration_ms,result:a.result,exit_code:a.exit_code,error:a.error,metadata:a.metadata,model:a.model,input_tokens:a.input_tokens,output_tokens:a.output_tokens,cached_input_tokens:a.cached_input_tokens,cost_usd:a.cost_usd}).from(a).where(drizzleOrm.eq(a.id,e.id)).limit(1).get();if(!i)return;let c=J(i.run_epoch),d=J(e.runEpoch),u=i.status==="running"&&c===d,l=i.stop_requested_at!==null&&J(i.stop_requested_epoch)===c,p=u&&l,_=i.status==="stopped"&&c===d&&l,h=fe(i.metadata),m=En(h[Ur])?h[Ur]:{},k=String(d),w=qm(i),C=w&&c===d&&!pa(i)&&!Object.prototype.hasOwnProperty.call(m,k),T=w&&c===d&&!Object.prototype.hasOwnProperty.call(m,k),P=c>0||d>0||e.runEpoch!==void 0&&e.runEpoch!==null||e.usageComplete!==void 0||c!==d,A={},x;if(i.status!=="running"&&(r=i.status,o=e.result?.trim()||e.error?.trim()||`task:end status=${e.status}`),P&&(i.status==="running"||T)){x=fe(i.metadata);let I=En(x[ia])?{...x[ia]}:{},K=String(d),re=wl(e),Ue=Br(I[K]);e.usageComplete!==void 0?I[K]={...re,accounting:e.usagePresent===!0?e.usageComplete?"recorded":"partial":"unavailable"}:Ue!==void 0?I[K]={...re,accounting:Ue}:I[K]=re,x[ia]=I;let Ie=zm(I),rn=_a(Ie),Zr=Object.values(I).some(Gm),gp=Object.values(I).some(hp=>Br(hp)!==void 0);e.usageComplete!==void 0||gp?(x[Ze]=Zr?"recorded":"unavailable",jm(I)?x.usageIncomplete=!0:delete x.usageIncomplete):rn&&h[Ze]==="unavailable"?x[Ze]="recorded":i.status!=="running"&&!rn&&h[Ze]===void 0&&(x[Ze]="unavailable"),A.metadata=JSON.stringify(x),A.input_tokens=Ie.inputTokens,A.output_tokens=Ie.outputTokens,A.cached_input_tokens=Ie.cachedInputTokens,A.cost_usd=Ie.costUsd;}else if(u||C)if(u)A.input_tokens=Re(e.inputTokens??0),A.output_tokens=Re(e.outputTokens??0),A.cached_input_tokens=Re(e.cachedInputTokens??0),A.cost_usd=Re(e.costUsd??0);else {let I=wl(e),K=e.usageComplete!==void 0?e.usagePresent===!0:_a(I);K&&(A.input_tokens=I.inputTokens,A.output_tokens=I.outputTokens,A.cached_input_tokens=I.cachedInputTokens,A.cost_usd=I.costUsd),x={...h};let re=En(h[Ur])?{...h[Ur]}:{};re[k]={at:e.completedAt},x[Ur]=re,x[Ze]===void 0?x[Ze]=K?"recorded":"unavailable":K&&x[Ze]==="unavailable"&&(x[Ze]="recorded"),A.metadata=JSON.stringify(x);}if((u||C)&&e.model!==void 0&&e.model!==null&&(!C||i.model===null)&&(A.model=e.model),p){x??=fe(i.metadata);let I=aa(x,e.error);x={...I.metadata,...e.partialResultRecovered===!0?{partialResultRecovered:!0}:{},stopMethod:jo(i.stop_requested_at,e.completedAt)},A.status="stopped",A.result=e.result??i.result,A.error=I.error,A.completed_at=e.completedAt,A.duration_ms=i.duration_ms??e.durationMs??Vo(i.started_at,e.completedAt,void 0),A.exit_code=e.exitCode??i.exit_code,A.metadata=JSON.stringify(x);}else if(u)e.partialResultRecovered===!0&&(x??=fe(i.metadata),x.partialResultRecovered=!0,A.metadata=JSON.stringify(x)),A.status=e.status,A.result=e.result??null,A.error=e.error??null,A.completed_at=e.completedAt,A.duration_ms=c>0?Vo(i.started_at,e.completedAt,e.durationMs):e.durationMs??null,A.exit_code=e.exitCode??null;else if(_){let I=!1;i.result===null&&e.result!==void 0&&e.result!==null&&(A.result=e.result,I=!0),i.exit_code===null&&e.exitCode!==void 0&&e.exitCode!==null&&(A.exit_code=e.exitCode),e.partialResultRecovered===!0&&(x??=fe(i.metadata),x.partialResultRecovered=!0,A.metadata=JSON.stringify(x)),I&&(r=void 0,o=void 0);}Object.keys(A).length>0&&s.update(a).set(A).where(drizzleOrm.eq(a.id,e.id)).run();},{behavior:"immediate"});}catch(s){throw s instanceof f?s:new f("DB_ERROR","Failed to finish task",s)}finally{n.close();}if(r!==void 0){try{this.taskLogRepository.appendLog(e.id,{timestamp:e.completedAt,level:"late-result",message:o??`task:end status=${e.status}`});}catch(s){console.error(`[crewx] failed to preserve late task result for ${e.id}: ${s instanceof Error?s.message:String(s)}`);}process.stderr.write(`Task ${e.id} was already finalized (${r}); late result kept in task log
176
+ `);}}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)),o={status:e.status,error:e.error,completed_at:e.completedAt,duration_ms:e.durationMs};if(e.terminalReason){let s=n.db.select({metadata:a.metadata}).from(a).where(r).limit(1).get(),i=fe(s?.metadata??null);i.terminalReason=e.terminalReason,o.metadata=JSON.stringify(i);}n.db.update(a).set(o).where(r).run();}catch(r){throw r instanceof f?r:new f("DB_ERROR","Failed to update task lifecycle",r)}finally{n.close();}}appendLog(e,n){this.taskLogRepository.appendLog(e,n);}appendLogs(e,n){this.taskLogRepository.appendLogs(e,n);}readLogs(e){return this.taskLogRepository.readLogs(e)}readLogsTail(e,n){return this.taskLogRepository.readLogsTail(e,n)}getLogState(e){return this.taskLogRepository.getLogState(e)}getRunningTasks(){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select(le).from(a).where(drizzleOrm.eq(a.status,"running")).orderBy(drizzleOrm.desc(a.started_at)).all().map(ct)}catch(n){throw new f("DB_ERROR","Failed to get running tasks",n)}finally{e.close();}}getActiveTasks(){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select(le).from(a).where(drizzleOrm.inArray(a.status,["pending","running"])).orderBy(drizzleOrm.desc(a.started_at)).all().map(ct)}catch(n){throw new f("DB_ERROR","Failed to get active tasks",n)}finally{e.close();}}getAllTasks(){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select(le).from(a).orderBy(drizzleOrm.desc(a.started_at)).limit(100).all().map(ct)}catch(n){throw new f("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 f("DB_ERROR","Failed to read task security key",r)}finally{n.close();}}recordProviderInput(e){if(!this.dbExists())return false;let n=J(e.runEpoch);if(n===0&&e.interceptedRequest!==true)return false;let r=e.recordedAt??new Date(this.clock()).toISOString(),o=this.openHandle(true);try{let s=!1;return o.db.transaction(i=>{let c=i.select({run_epoch:a.run_epoch}).from(a).where(drizzleOrm.eq(a.id,e.id)).limit(1).get();if(!c||J(c.run_epoch)!==n)return;s=i.insert(vt).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;}),s}catch(s){throw s instanceof f?s:new f("DB_ERROR","Failed to record provider input",s)}finally{o.close();}}listProviderInputEpochs(e,n={}){if(!this.dbExists())return [];let r=this.openHandle(false);try{let o=r.db.select({run_epoch:a.run_epoch}).from(a).where(drizzleOrm.eq(a.id,e)).limit(1).get();if(!o)return [];let s=J(o.run_epoch),i=r.db.select({run_epoch:vt.run_epoch,key_wrap_skipped:vt.key_wrap_skipped}).from(vt).where(drizzleOrm.eq(vt.task_id,e)).all(),c=new Map(i.map(u=>[u.run_epoch,u])),d=[];for(let u=1;u<=s;u++){let l=c.get(u);l?d.push({runEpoch:u,available:!0,...l.key_wrap_skipped===1?{keyWrapSkipped:!0}:{}}):d.push({runEpoch:u,available:!1,reason:n.archivedRunEpochs?.has(u)?"pruned":"absent"});}return d}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to list provider inputs",o)}finally{r.close();}}readProviderInput(e,n){if(!this.dbExists())return;let r=this.openHandle(false);try{let o=r.db.select().from(vt).where(drizzleOrm.and(drizzleOrm.eq(vt.task_id,e),drizzleOrm.eq(vt.run_epoch,J(n)))).limit(1).get();return o?{runEpoch:o.run_epoch,input:o.input,keyWrapSkipped:o.key_wrap_skipped===1,recordedAt:o.recorded_at}:void 0}catch(o){throw new f("DB_ERROR","Failed to read provider input",o)}finally{r.close();}}getTask(e){if(!this.dbExists())return;let n=this.openHandle(false);try{let r=n.db.select(le).from(a).where(drizzleOrm.eq(a.id,e)).limit(1).get();return r?ct(r):void 0}catch(r){throw new f("DB_ERROR","Failed to get task",r)}finally{n.close();}}async killTask(e){let n=await this.stopTask(e);return n.status==="stopped"?{status:"terminated",killed:n.method==="forced"||n.method==="cooperative",...n.pid?{pid:n.pid}:{}}:n.status==="not_running"?{status:"not_running",killed:false,...n.pid?{pid:n.pid}:{},...n.error?{error:n.error}:{}}:{status:"failed",killed:false,...n.pid?{pid:n.pid}:{},...n.error?{error:n.error}:{}}}reapOrphanedTasks(e={}){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(),o=this.clock(),s=Math.max(1,Math.trunc(e.tickIntervalMs??Nl)),i=this.lastReaperTickAt,c=i===void 0?Number.POSITIVE_INFINITY:o-i,d=i!==void 0&&c>=0&&c<=s*2;this.lastReaperTickAt=o;let u=Vn(),l=Wo(),p=new Date(o-Al).toISOString(),_=new Date(o).toISOString(),h=new Set,m=[],k=0,w=(T,P)=>{let A=fe(la(T.metadata,"runner_lost")),x=typeof A.provider=="string"?A.provider:void 0,I;try{I=Bo({taskLogRepository:this.taskLogRepository,taskId:T.id,provider:x,model:T.model})?.usage;}catch{}let K={status:"failed",error:P,completed_at:_};I?(K.input_tokens=I.inputTokens,K.output_tokens=I.outputTokens,K.cached_input_tokens=I.cachedInputTokens,K.cost_usd=I.costUsd,T.model===null&&I.model!==null&&(K.model=I.model),A[Ze]="recorded"):!pa(T)&&A[Ze]!=="recorded"&&(A[Ze]="unavailable"),K.metadata=JSON.stringify(A);let re=T.run_epoch===null?drizzleOrm.isNull(a.run_epoch):drizzleOrm.eq(a.run_epoch,T.run_epoch),Ue=T.heartbeat_at===null?drizzleOrm.isNull(a.heartbeat_at):drizzleOrm.eq(a.heartbeat_at,T.heartbeat_at),Ie=n.db.update(a).set(K).where(drizzleOrm.and(drizzleOrm.eq(a.id,T.id),drizzleOrm.eq(a.status,"running"),re,Ue)).run();return Ie.changes>0&&k++,Ie.changes>0};for(let T of r){if(T.status==="pending"){if(T.pid!==null||T.started_at>=p)continue;let I=la(T.metadata,"launch_failed");n.db.update(a).set({status:"failed",error:"Reaped: runner never adopted task (pending timeout)",completed_at:_,metadata:I}).where(drizzleOrm.and(drizzleOrm.eq(a.id,T.id),drizzleOrm.eq(a.status,"pending"),drizzleOrm.isNull(a.pid),drizzleOrm.lt(a.started_at,p))).run().changes>0&&k++;continue}if(Hm.has(T.platform??"cli"))continue;if(T.pid===null){let I=`${T.id}:${T.run_epoch??0}`;h.add(I);let K=this.pidNullObservedSince.get(I);if(K===void 0){this.pidNullObservedSince.set(I,o);continue}o-K>=fa&&w(T,"Reaped: pid never recorded after resume (stale running_instruction)")&&this.pidNullObservedSince.delete(I);continue}if(T.heartbeat_at===null){zt(T.pid,this.processControl.kill)==="not_found"&&w(T,"Reaped: process not found (orphaned task)");continue}let P=Date.parse(T.heartbeat_at),A=Number.isFinite(P)?o-P:Number.POSITIVE_INFINITY;if(A<=u)continue;let x=Xi(T).filter(I=>zt(I.pid,this.processControl.kill)!=="not_found");x.length===0?w(T,"Reaped: process not found (orphaned task)"):A>l&&d&&m.push({row:T,targets:x});}let C=new Map;for(let T of m){let{row:P,targets:A}=T,x=n.db.select({status:a.status,run_epoch:a.run_epoch,heartbeat_at:a.heartbeat_at}).from(a).where(drizzleOrm.eq(a.id,P.id)).get();if(!x||x.status!=="running"||J(x.run_epoch)!==J(P.run_epoch)||x.heartbeat_at!==P.heartbeat_at)continue;let I=await this.judgeRecordedTargets(P,A);if(I.unproven!==void 0){console.warn("[crewx] reaper left running task",{taskId:P.id,reason:I.unproven});continue}if(I.owned.length>0){let K=await this.terminateRecordedProcesses(I.owned,C);if(K!==void 0){console.warn("[crewx] reaper left running task",{taskId:P.id,reason:K});continue}}w(P,"Reaped: heartbeat stale beyond hard limit (orphaned task)")&&I.reused.length>0&&console.warn("[crewx] reaper reaped task whose recorded pid was reused",{taskId:P.id,reason:I.reused.join("; ")});}for(let T of Array.from(this.pidNullObservedSince.keys()))h.has(T)||this.pidNullObservedSince.delete(T);return k}finally{n.close();}}async judgeRecordedTargets(e,n){let r=e.heartbeat_at===null?Number.NaN:Date.parse(e.heartbeat_at),o=Number.isFinite(r)?r+Pr()+To:void 0,s=[],i=[];for(let c of n){let d=await Yi(c,{processControlOptions:this.processControl,legacyStartBoundaryMs:o});if(d.verdict==="owned")s.push(c);else if(d.verdict==="reused")i.push(`pid ${c.pid} reused (${d.reason})`);else return {owned:s,reused:i,unproven:`pid ${c.pid} not proven owned (${d.ownership}): ${d.reason}`}}return {owned:s,reused:i}}async terminateRecordedProcesses(e,n){for(let r of e){if(!n.has(r.pid)){let o;try{o=(await Jt(r.pid,{...this.processControl,signal:Kt})).status==="failed"?"failed":"terminated";}catch{o="failed";}n.set(r.pid,o);}if(n.get(r.pid)==="failed")return `pid ${r.pid} termination not confirmed`;if(zt(r.pid,this.processControl.kill)!=="not_found")return `pid ${r.pid} still alive after termination`}}reapRunningWorkflowTasks(e=fa){if(!this.dbExists())return 0;let n=this.openHandle(true);try{let r=new Date(Date.now()-e).toISOString(),o=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),yl())),s=n.db.select({id:a.id,metadata:a.metadata}).from(a).where(o).all(),i=new Date().toISOString(),c=0;for(let d of s){let u=fe(d.metadata);u.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(u)}).where(drizzleOrm.and(drizzleOrm.eq(a.id,d.id),drizzleOrm.eq(a.status,"running"))).run();c+=l.changes??0;}return c}finally{n.close();}}findTaskStatus(e,n){let r=this.resolveDbPaths();for(let o of r){if(!Iu.existsSync(o))continue;let s=H(o);try{let i=n?drizzleOrm.eq(a.workspace_id,n):void 0,c=i?drizzleOrm.and(drizzleOrm.eq(a.id,e),i):drizzleOrm.eq(a.id,e),d=s.db.select(le).from(a).where(c).limit(1).get()??void 0;if(!d){let u=i?drizzleOrm.and(drizzleOrm.eq(a.thread_id,e),i):drizzleOrm.eq(a.thread_id,e);d=s.db.select(le).from(a).where(u).orderBy(drizzleOrm.desc(a.started_at)).limit(1).get()??void 0;}if(d)return ct(d)}catch(i){throw new f("DB_ERROR","Failed to find task status",i)}finally{s.close();}}}findChildTasks(e,n){let r=this.resolveDbPaths(),o=new Set,s=[];for(let i of r){if(!Iu.existsSync(i))continue;let c=H(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),u=c.db.select(le).from(a).where(d).orderBy(drizzleOrm.asc(a.started_at)).all();for(let l of u)o.has(l.id)||(o.add(l.id),s.push(ct(l)));}catch(d){throw new f("DB_ERROR","Failed to find child tasks",d)}finally{c.close();}}return s}getWorkspaceUsageSummary(e){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.all(e?drizzleOrm.sql`
177
177
  SELECT
178
178
  COALESCE(workspace_id, 'unknown') AS workspace_id,
179
179
  COALESCE(SUM(input_tokens), 0) AS input_tokens,
@@ -194,14 +194,14 @@ ${r.join(`
194
194
  FROM tasks
195
195
  GROUP BY workspace_id
196
196
  ORDER BY (COALESCE(SUM(input_tokens), 0) + COALESCE(SUM(output_tokens), 0)) DESC
197
- `)}catch(r){throw new f("DB_ERROR","Failed to get workspace usage summary",r)}finally{n.close();}}getThreadTokenUsage(e,n){let r=this.resolveDbPaths(),o=new Set,s=0,i=0,c=0;for(let d of r){if(!nu.existsSync(d))continue;let u=U(d);try{let l=drizzleOrm.eq(a.thread_id,e),p=n?drizzleOrm.and(l,drizzleOrm.eq(a.workspace_id,n)):l,_=u.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 _)o.has(h.id)||(o.add(h.id),s+=h.input_tokens??0,i+=h.output_tokens??0,c+=h.cost_usd??0);}catch(l){throw new f("DB_ERROR","Failed to get thread token usage",l)}finally{u.close();}}return {inputTokens:s,outputTokens:i,costUsd:c}}findTasksByThread(e,n,r){let o=this.resolveDbPaths(),s=new Set,i=[],c=r?.projection==="activity-log";for(let d of o){if(!nu.existsSync(d))continue;let u=U(d);try{let l=drizzleOrm.eq(a.thread_id,e),p=n?drizzleOrm.and(l,drizzleOrm.eq(a.workspace_id,n)):l,_=c?u.db.select({id:a.id,thread_id:a.thread_id,agent_id:a.agent_id,parent_task_id:a.parent_task_id,started_at:a.started_at,completed_at:a.completed_at}).from(a).where(p).orderBy(drizzleOrm.asc(a.started_at)).all():u.db.select(ce).from(a).where(p).orderBy(drizzleOrm.asc(a.started_at)).all().map(st);for(let h of _)s.has(h.id)||(s.add(h.id),i.push(h));}catch(l){throw new f("DB_ERROR","Failed to find tasks by thread",l)}finally{u.close();}}return i}parseWorkflowCardMetadata(e){if(!e)return {};try{let n=JSON.parse(e);return {kind:typeof n.kind=="string"?n.kind:void 0,workflowRunId:typeof n.workflowRunId=="string"?n.workflowRunId:void 0}}catch{return {}}}extractThreadIdFromCommand(e){return e?/--thread=(\S+)/.exec(e)?.[1]??null:null}findRunningWorkflowParentTasks(){if(!this.dbExists())return [];let e=[];for(let n of this.resolveDbPaths()){if(!nu.existsSync(n))continue;let r=U(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"]),Fi())).orderBy(drizzleOrm.desc(a.started_at)).all().map(qi));}catch(o){throw new f("DB_ERROR","Failed to find workflow parent tasks",o)}finally{r.close();}}return e}findWorkflowParentTasksByWorkspace(e){let n=[],r=new Map;for(let o of this.resolveDbPaths()){if(!nu.existsSync(o))continue;let s=U(o);try{let i=s.db.select({id:a.id,agent_id:a.agent_id,thread_id:a.thread_id,workspace_id:a.workspace_id,platform:a.platform,status:a.status,error:a.error,completed_at:a.completed_at,duration_ms:a.duration_ms,started_at:a.started_at,metadata:a.metadata}).from(a).where(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 c of i){let d=this.parseWorkflowCardMetadata(c.metadata);if(!or(d.kind)||typeof d.workflowRunId!="string")continue;let u=d.kind,l=r.get(u)??new Set;l.has(d.workflowRunId)||(l.add(d.workflowRunId),r.set(u,l),n.push(qi(c)));}}catch(i){throw new f("DB_ERROR","Failed to find workflow parent tasks by workspace",i)}finally{s.close();}}return n}findWorkflowParentTask(e){if(this.dbExists())for(let n of this.resolveDbPaths()){if(!nu.existsSync(n))continue;let r=U(n);try{let o=r.db.select({id:a.id,agent_id:a.agent_id,thread_id:a.thread_id,workspace_id:a.workspace_id,platform:a.platform,status:a.status,error:a.error,completed_at:a.completed_at,duration_ms:a.duration_ms,started_at:a.started_at,metadata:a.metadata}).from(a).where(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 s of o){let i=this.parseWorkflowCardMetadata(s.metadata);if(i.kind===e.kind&&i.workflowRunId===e.workflowRunId)return qi(s)}}catch(o){throw new f("DB_ERROR","Failed to find workflow parent task",o)}finally{r.close();}}}batchFetchWorkflowCards(e,n){let r=new Map;if(e.length===0)return r;let o=new Set(e),s=new Map,i=n?drizzleOrm.eq(a.workspace_id,n):void 0,c=(d,u)=>{if(!d)return;let l=s.get(d);if(l&&u.started_at<=l)return;let p=this.parseWorkflowCardMetadata(u.metadata);or(p.kind)&&(s.set(d,u.started_at),r.set(d,{taskId:u.id,workflowRunId:p.workflowRunId,raw:u.result??void 0}));};for(let d of this.resolveDbPaths()){if(!nu.existsSync(d))continue;let u=U(d);try{let l=drizzleOrm.and(drizzleOrm.inArray(a.thread_id,e),Fi()),p=u.db.select({id:a.id,thread_id:a.thread_id,metadata:a.metadata,result:a.result,started_at:a.started_at}).from(a).where(i?drizzleOrm.and(l,i):l).all();for(let m of p)c(m.thread_id,m);let _=drizzleOrm.and(drizzleOrm.isNull(a.thread_id),Fi()),h=u.db.select({id:a.id,command:a.command,metadata:a.metadata,result:a.result,started_at:a.started_at}).from(a).where(i?drizzleOrm.and(_,i):_).all();for(let m of h){let k=this.extractThreadIdFromCommand(m.command);!k||!o.has(k)||c(k,m);}}catch(l){throw new f("DB_ERROR","Failed to batch fetch workflow cards",l)}finally{u.close();}}return r}findAllTasks(e){if(!this.dbExists())return {rows:[],total:0};let n=this.openHandle(false);try{let r=[];e.workspaceId&&r.push(drizzleOrm.eq(a.workspace_id,e.workspaceId));let o=e.agents&&e.agents.length>0?e.agents:e.agentId?[e.agentId]:null;o&&r.push(drizzleOrm.inArray(a.agent_id,o));let s=e.statuses&&e.statuses.length>0?e.statuses:e.status?[e.status]:null;s&&r.push(drizzleOrm.inArray(a.status,Ti(s)));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 c=r.length>0?drizzleOrm.and(...r):void 0,d=n.db.select({count:drizzleOrm.sql`count(*)`}).from(a).where(c).get(),u=(e.sortDir??"DESC")==="ASC"?drizzleOrm.asc(a.started_at):drizzleOrm.desc(a.started_at);return {rows:n.db.select(ce).from(a).where(c).orderBy(u).limit(e.limit).offset(e.offset).all().map(st),total:d?.count??0}}catch(r){throw new f("DB_ERROR","Failed to find all tasks",r)}finally{n.close();}}getAgentUsage(e,n,r){if(!this.dbExists())return [];let o=this.openHandle(false);try{let s=Wi(drizzleOrm.sql.raw("t.model"),drizzleOrm.sql.raw("t.metadata")),i=Nr(drizzleOrm.sql.raw("t.status")),c=Po(drizzleOrm.sql.raw("t.metadata")),d=drizzleOrm.sql`
197
+ `)}catch(r){throw new f("DB_ERROR","Failed to get workspace usage summary",r)}finally{n.close();}}getThreadTokenUsage(e,n){let r=this.resolveDbPaths(),o=new Set,s=0,i=0,c=0;for(let d of r){if(!Iu.existsSync(d))continue;let u=H(d);try{let l=drizzleOrm.eq(a.thread_id,e),p=n?drizzleOrm.and(l,drizzleOrm.eq(a.workspace_id,n)):l,_=u.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 _)o.has(h.id)||(o.add(h.id),s+=h.input_tokens??0,i+=h.output_tokens??0,c+=h.cost_usd??0);}catch(l){throw new f("DB_ERROR","Failed to get thread token usage",l)}finally{u.close();}}return {inputTokens:s,outputTokens:i,costUsd:c}}findTasksByThread(e,n,r){let o=this.resolveDbPaths(),s=new Set,i=[],c=r?.projection==="activity-log";for(let d of o){if(!Iu.existsSync(d))continue;let u=H(d);try{let l=drizzleOrm.eq(a.thread_id,e),p=n?drizzleOrm.and(l,drizzleOrm.eq(a.workspace_id,n)):l,_=c?u.db.select({id:a.id,thread_id:a.thread_id,agent_id:a.agent_id,parent_task_id:a.parent_task_id,started_at:a.started_at,completed_at:a.completed_at}).from(a).where(p).orderBy(drizzleOrm.asc(a.started_at)).all():u.db.select(le).from(a).where(p).orderBy(drizzleOrm.asc(a.started_at)).all().map(ct);for(let h of _)s.has(h.id)||(s.add(h.id),i.push(h));}catch(l){throw new f("DB_ERROR","Failed to find tasks by thread",l)}finally{u.close();}}return i}parseWorkflowCardMetadata(e){if(!e)return {};try{let n=JSON.parse(e);return {kind:typeof n.kind=="string"?n.kind:void 0,workflowRunId:typeof n.workflowRunId=="string"?n.workflowRunId:void 0}}catch{return {}}}extractThreadIdFromCommand(e){return e?/--thread=(\S+)/.exec(e)?.[1]??null:null}findRunningWorkflowParentTasks(){if(!this.dbExists())return [];let e=[];for(let n of this.resolveDbPaths()){if(!Iu.existsSync(n))continue;let r=H(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"]),ra())).orderBy(drizzleOrm.desc(a.started_at)).all().map(na));}catch(o){throw new f("DB_ERROR","Failed to find workflow parent tasks",o)}finally{r.close();}}return e}findWorkflowParentTasksByWorkspace(e){let n=[],r=new Map;for(let o of this.resolveDbPaths()){if(!Iu.existsSync(o))continue;let s=H(o);try{let i=s.db.select({id:a.id,agent_id:a.agent_id,thread_id:a.thread_id,workspace_id:a.workspace_id,platform:a.platform,status:a.status,error:a.error,completed_at:a.completed_at,duration_ms:a.duration_ms,started_at:a.started_at,metadata:a.metadata}).from(a).where(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 c of i){let d=this.parseWorkflowCardMetadata(c.metadata);if(!kr(d.kind)||typeof d.workflowRunId!="string")continue;let u=d.kind,l=r.get(u)??new Set;l.has(d.workflowRunId)||(l.add(d.workflowRunId),r.set(u,l),n.push(na(c)));}}catch(i){throw new f("DB_ERROR","Failed to find workflow parent tasks by workspace",i)}finally{s.close();}}return n}findWorkflowParentTask(e){if(this.dbExists())for(let n of this.resolveDbPaths()){if(!Iu.existsSync(n))continue;let r=H(n);try{let o=r.db.select({id:a.id,agent_id:a.agent_id,thread_id:a.thread_id,workspace_id:a.workspace_id,platform:a.platform,status:a.status,error:a.error,completed_at:a.completed_at,duration_ms:a.duration_ms,started_at:a.started_at,metadata:a.metadata}).from(a).where(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 s of o){let i=this.parseWorkflowCardMetadata(s.metadata);if(i.kind===e.kind&&i.workflowRunId===e.workflowRunId)return na(s)}}catch(o){throw new f("DB_ERROR","Failed to find workflow parent task",o)}finally{r.close();}}}batchFetchWorkflowCards(e,n){let r=new Map;if(e.length===0)return r;let o=new Set(e),s=new Map,i=n?drizzleOrm.eq(a.workspace_id,n):void 0,c=(d,u)=>{if(!d)return;let l=s.get(d);if(l&&u.started_at<=l)return;let p=this.parseWorkflowCardMetadata(u.metadata);kr(p.kind)&&(s.set(d,u.started_at),r.set(d,{taskId:u.id,workflowRunId:p.workflowRunId,raw:u.result??void 0}));};for(let d of this.resolveDbPaths()){if(!Iu.existsSync(d))continue;let u=H(d);try{let l=drizzleOrm.and(drizzleOrm.inArray(a.thread_id,e),ra()),p=u.db.select({id:a.id,thread_id:a.thread_id,metadata:a.metadata,result:a.result,started_at:a.started_at}).from(a).where(i?drizzleOrm.and(l,i):l).all();for(let m of p)c(m.thread_id,m);let _=drizzleOrm.and(drizzleOrm.isNull(a.thread_id),ra()),h=u.db.select({id:a.id,command:a.command,metadata:a.metadata,result:a.result,started_at:a.started_at}).from(a).where(i?drizzleOrm.and(_,i):_).all();for(let m of h){let k=this.extractThreadIdFromCommand(m.command);!k||!o.has(k)||c(k,m);}}catch(l){throw new f("DB_ERROR","Failed to batch fetch workflow cards",l)}finally{u.close();}}return r}findAllTasks(e){if(!this.dbExists())return {rows:[],total:0};let n=this.openHandle(false);try{let r=[];e.workspaceId&&r.push(drizzleOrm.eq(a.workspace_id,e.workspaceId));let o=e.agents&&e.agents.length>0?e.agents:e.agentId?[e.agentId]:null;o&&r.push(drizzleOrm.inArray(a.agent_id,o));let s=e.statuses&&e.statuses.length>0?e.statuses:e.status?[e.status]:null;s&&r.push(drizzleOrm.inArray(a.status,Mi(s)));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 c=r.length>0?drizzleOrm.and(...r):void 0,d=n.db.select({count:drizzleOrm.sql`count(*)`}).from(a).where(c).get(),u=(e.sortDir??"DESC")==="ASC"?drizzleOrm.asc(a.started_at):drizzleOrm.desc(a.started_at);return {rows:n.db.select(le).from(a).where(c).orderBy(u).limit(e.limit).offset(e.offset).all().map(ct),total:d?.count??0}}catch(r){throw new f("DB_ERROR","Failed to find all tasks",r)}finally{n.close();}}getAgentUsage(e,n,r){if(!this.dbExists())return [];let o=this.openHandle(false);try{let s=sa(drizzleOrm.sql.raw("t.model"),drizzleOrm.sql.raw("t.metadata")),i=qr(drizzleOrm.sql.raw("t.status")),c=zo(drizzleOrm.sql.raw("t.metadata")),d=drizzleOrm.sql`
198
198
  COALESCE(t.input_tokens, 0)
199
199
  + CASE
200
- WHEN t.started_at >= ${Mn}
200
+ WHEN t.started_at >= ${Xn}
201
201
  AND (
202
202
  t.crewx_version IS NULL
203
203
  OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
204
- OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${$n}) AS INTEGER) < ${Hn})
204
+ OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${Yn}) AS INTEGER) < ${Qn})
205
205
  )
206
206
  THEN COALESCE(t.cached_input_tokens, 0)
207
207
  ELSE 0
@@ -220,7 +220,7 @@ ${r.join(`
220
220
  FROM tasks t
221
221
  ${u}
222
222
  GROUP BY t.agent_id, t.workspace_id, ${s}
223
- `),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},b=m.workspace_id??null,T=JSON.stringify([m.agent_id,b]),P=p.get(T);if(!P){p.set(T,{agentId:m.agent_id,workspaceId:b,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}P.totalTasks+=m.total_tasks,P.unavailableTaskCount=(P.unavailableTaskCount??0)+m.unavailable_task_count,P.inputTokens+=m.input_tokens,P.outputTokens+=m.output_tokens,P.cachedInputTokens+=m.cached_input_tokens,P.costUsd+=m.cost_usd,P.totalTokens+=m.input_tokens+m.output_tokens;let A=P.providers.find(x=>x.provider===k);A?(A.inputTokens+=E.inputTokens,A.outputTokens+=E.outputTokens,A.cachedInputTokens+=E.cachedInputTokens,A.totalTokens+=E.totalTokens,A.costUsd+=E.costUsd,A.totalTasks+=E.totalTasks,A.unavailableTaskCount+=E.unavailableTaskCount):P.providers.push(E);}let _=[...p.values()];for(let m of _)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 _.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)}),_}catch(s){throw new f("DB_ERROR","Failed to get agent usage",s)}finally{o.close();}}getAgentUsageTrendRaw(e,n,r){if(!this.dbExists())return [];let o=this.openHandle(false);try{let s=Nr(drizzleOrm.sql.raw("t.status")),i=Po(drizzleOrm.sql.raw("t.metadata"));return o.db.all(r?drizzleOrm.sql`
223
+ `),p=new Map;for(let m of l){let k=typeof m.provider=="string"&&m.provider.trim()!==""?m.provider:"unknown",w={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},C=m.workspace_id??null,T=JSON.stringify([m.agent_id,C]),P=p.get(T);if(!P){p.set(T,{agentId:m.agent_id,workspaceId:C,totalTasks:m.total_tasks,unavailableTaskCount:m.unavailable_task_count,inputTokens:m.input_tokens,outputTokens:m.output_tokens,cachedInputTokens:m.cached_input_tokens,costUsd:m.cost_usd,totalTokens:m.input_tokens+m.output_tokens,providers:[w]});continue}P.totalTasks+=m.total_tasks,P.unavailableTaskCount=(P.unavailableTaskCount??0)+m.unavailable_task_count,P.inputTokens+=m.input_tokens,P.outputTokens+=m.output_tokens,P.cachedInputTokens+=m.cached_input_tokens,P.costUsd+=m.cost_usd,P.totalTokens+=m.input_tokens+m.output_tokens;let A=P.providers.find(x=>x.provider===k);A?(A.inputTokens+=w.inputTokens,A.outputTokens+=w.outputTokens,A.cachedInputTokens+=w.cachedInputTokens,A.totalTokens+=w.totalTokens,A.costUsd+=w.costUsd,A.totalTasks+=w.totalTasks,A.unavailableTaskCount+=w.unavailableTaskCount):P.providers.push(w);}let _=[...p.values()];for(let m of _)m.providers.sort((k,w)=>k.provider===w.provider?0:k.provider==="unknown"?1:w.provider==="unknown"?-1:k.totalTokens!==w.totalTokens?w.totalTokens-k.totalTokens:k.provider<w.provider?-1:1);let h=(m,k)=>m===k?0:m<k?-1:1;return _.sort((m,k)=>{if(m.totalTokens!==k.totalTokens)return k.totalTokens-m.totalTokens;let w=h(m.agentId,k.agentId);return w!==0?w:m.workspaceId===k.workspaceId?0:m.workspaceId===null?1:k.workspaceId===null?-1:h(m.workspaceId,k.workspaceId)}),_}catch(s){throw new f("DB_ERROR","Failed to get agent usage",s)}finally{o.close();}}getAgentUsageTrendRaw(e,n,r){if(!this.dbExists())return [];let o=this.openHandle(false);try{let s=qr(drizzleOrm.sql.raw("t.status")),i=zo(drizzleOrm.sql.raw("t.metadata"));return o.db.all(r?drizzleOrm.sql`
224
224
  SELECT
225
225
  date(t.started_at) AS date,
226
226
  t.agent_id,
@@ -228,11 +228,11 @@ ${r.join(`
228
228
  COALESCE(SUM(
229
229
  COALESCE(t.input_tokens, 0)
230
230
  + CASE
231
- WHEN t.started_at >= ${Mn}
231
+ WHEN t.started_at >= ${Xn}
232
232
  AND (
233
233
  t.crewx_version IS NULL
234
234
  OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
235
- OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${$n}) AS INTEGER) < ${Hn})
235
+ OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${Yn}) AS INTEGER) < ${Qn})
236
236
  )
237
237
  THEN COALESCE(t.cached_input_tokens, 0)
238
238
  ELSE 0
@@ -257,11 +257,11 @@ ${r.join(`
257
257
  COALESCE(SUM(
258
258
  COALESCE(t.input_tokens, 0)
259
259
  + CASE
260
- WHEN t.started_at >= ${Mn}
260
+ WHEN t.started_at >= ${Xn}
261
261
  AND (
262
262
  t.crewx_version IS NULL
263
263
  OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
264
- OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${$n}) AS INTEGER) < ${Hn})
264
+ OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${Yn}) AS INTEGER) < ${Qn})
265
265
  )
266
266
  THEN COALESCE(t.cached_input_tokens, 0)
267
267
  ELSE 0
@@ -277,14 +277,14 @@ ${r.join(`
277
277
  AND t.agent_id != 'workflow'
278
278
  GROUP BY date(t.started_at), t.agent_id
279
279
  ORDER BY date(t.started_at) ASC
280
- `).map(d=>({date:d.date,agentId:d.agent_id,unavailableTaskCount:d.unavailable_task_count,inputTokens:d.input_tokens,outputTokens:d.output_tokens,cachedInputTokens:d.cached_input_tokens,costUsd:d.cost_usd,totalTokens:d.input_tokens+d.output_tokens}))}catch(s){throw new f("DB_ERROR","Failed to get agent usage trend",s)}finally{o.close();}}findTaskForStop(e,n){if(!this.dbExists())return;let r=this.openHandle(false);try{let o=r.db.select(ce).from(a).where(drizzleOrm.and(drizzleOrm.eq(a.id,e),drizzleOrm.eq(a.workspace_id,n))).limit(1).get();return o?st(o):void 0}catch(o){throw new f("DB_ERROR","Failed to find task for stop",o)}finally{r.close();}}findLatestTaskByMetadata(e){if(!this.dbExists())return null;let n=this.openHandle(false);try{return n.db.select({id:a.id,thread_id:a.thread_id,status:a.status,result:a.result,error:a.error,started_at:a.started_at,completed_at:a.completed_at,metadata:a.metadata}).from(a).where(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 f("DB_ERROR","Failed to find latest task by metadata",r)}finally{n.close();}}markTaskFailed(e,n,r,o="failed",s){if(!this.dbExists())return;let i=this.openHandle(true);try{let c=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")),u=i.db.select({metadata:a.metadata}).from(a).where(d).limit(1).get();if(!u)return;let l={status:o,error:n,completed_at:c};if(s){let p=pe(u.metadata);p.terminalReason=s,l.metadata=JSON.stringify(p);}i.db.update(a).set(l).where(d).run();}catch(c){throw c instanceof f?c:new f("DB_ERROR","Failed to mark task failed",c)}finally{i.close();}}findTasksByPromptHint(e,n){let r=this.resolveDbPaths(),o=new Set,s=[];for(let i of r){if(!nu.existsSync(i))continue;let c=U(i);try{let d=n?drizzleOrm.and(drizzleOrm.like(a.prompt,`%${e}%`),drizzleOrm.eq(a.workspace_id,n)):drizzleOrm.like(a.prompt,`%${e}%`),u=c.db.select(ce).from(a).where(d).orderBy(drizzleOrm.asc(a.started_at)).all();for(let l of u)o.has(l.id)||(o.add(l.id),s.push(st(l)));}catch(d){throw new f("DB_ERROR","Failed to find tasks by prompt hint",d)}finally{c.close();}}return s}getProviderUsage(e,n,r){if(!this.dbExists())return [];let o=this.openHandle(false);try{let s=Wi(),i=Nr(a.status),c=Po(a.metadata),d=drizzleOrm.sql`
280
+ `).map(d=>({date:d.date,agentId:d.agent_id,unavailableTaskCount:d.unavailable_task_count,inputTokens:d.input_tokens,outputTokens:d.output_tokens,cachedInputTokens:d.cached_input_tokens,costUsd:d.cost_usd,totalTokens:d.input_tokens+d.output_tokens}))}catch(s){throw new f("DB_ERROR","Failed to get agent usage trend",s)}finally{o.close();}}findTaskForStop(e,n){if(!this.dbExists())return;let r=this.openHandle(false);try{let o=r.db.select(le).from(a).where(drizzleOrm.and(drizzleOrm.eq(a.id,e),drizzleOrm.eq(a.workspace_id,n))).limit(1).get();return o?ct(o):void 0}catch(o){throw new f("DB_ERROR","Failed to find task for stop",o)}finally{r.close();}}findLatestTaskByMetadata(e){if(!this.dbExists())return null;let n=this.openHandle(false);try{return n.db.select({id:a.id,thread_id:a.thread_id,status:a.status,result:a.result,error:a.error,started_at:a.started_at,completed_at:a.completed_at,metadata:a.metadata}).from(a).where(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 f("DB_ERROR","Failed to find latest task by metadata",r)}finally{n.close();}}markTaskFailed(e,n,r,o="failed",s){if(!this.dbExists())return;let i=this.openHandle(true);try{let c=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")),u=i.db.select({metadata:a.metadata}).from(a).where(d).limit(1).get();if(!u)return;let l={status:o,error:n,completed_at:c};if(s){let p=fe(u.metadata);p.terminalReason=s,l.metadata=JSON.stringify(p);}i.db.update(a).set(l).where(d).run();}catch(c){throw c instanceof f?c:new f("DB_ERROR","Failed to mark task failed",c)}finally{i.close();}}findTasksByPromptHint(e,n){let r=this.resolveDbPaths(),o=new Set,s=[];for(let i of r){if(!Iu.existsSync(i))continue;let c=H(i);try{let d=n?drizzleOrm.and(drizzleOrm.like(a.prompt,`%${e}%`),drizzleOrm.eq(a.workspace_id,n)):drizzleOrm.like(a.prompt,`%${e}%`),u=c.db.select(le).from(a).where(d).orderBy(drizzleOrm.asc(a.started_at)).all();for(let l of u)o.has(l.id)||(o.add(l.id),s.push(ct(l)));}catch(d){throw new f("DB_ERROR","Failed to find tasks by prompt hint",d)}finally{c.close();}}return s}getProviderUsage(e,n,r){if(!this.dbExists())return [];let o=this.openHandle(false);try{let s=sa(),i=qr(a.status),c=zo(a.metadata),d=drizzleOrm.sql`
281
281
  COALESCE(${a.input_tokens}, 0)
282
282
  + CASE
283
- WHEN ${a.started_at} >= ${Mn}
283
+ WHEN ${a.started_at} >= ${Xn}
284
284
  AND (
285
285
  ${a.crewx_version} IS NULL
286
286
  OR (${a.crewx_version} LIKE '0.8.%' AND ${a.crewx_version} NOT LIKE '0.8.9%')
287
- OR (${a.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${a.crewx_version}, ${$n}) AS INTEGER) < ${Hn})
287
+ OR (${a.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${a.crewx_version}, ${Yn}) AS INTEGER) < ${Qn})
288
288
  )
289
289
  THEN COALESCE(${a.cached_input_tokens}, 0)
290
290
  ELSE 0
@@ -304,14 +304,14 @@ ${r.join(`
304
304
  ${u}
305
305
  GROUP BY ${s}
306
306
  ORDER BY (COALESCE(SUM(${d}), 0) + COALESCE(SUM(${a.output_tokens}), 0)) DESC
307
- `).map(p=>({provider:p.provider,totalTasks:p.total_tasks,unavailableTaskCount:p.unavailable_task_count,inputTokens:p.input_tokens,outputTokens:p.output_tokens,cachedInputTokens:p.cached_input_tokens,costUsd:p.cost_usd,totalTokens:p.input_tokens+p.output_tokens,activeDurationMs:p.active_duration_ms??0,lastActiveAt:p.last_active_at??null}))}catch(s){throw new f("DB_ERROR","Failed to get provider usage",s)}finally{o.close();}}getModelUsage(e,n,r){if(!this.dbExists())return [];let o=this.openHandle(false);try{let s=Wi(),i=Nr(a.status),c=Po(a.metadata),d=drizzleOrm.sql`
307
+ `).map(p=>({provider:p.provider,totalTasks:p.total_tasks,unavailableTaskCount:p.unavailable_task_count,inputTokens:p.input_tokens,outputTokens:p.output_tokens,cachedInputTokens:p.cached_input_tokens,costUsd:p.cost_usd,totalTokens:p.input_tokens+p.output_tokens,activeDurationMs:p.active_duration_ms??0,lastActiveAt:p.last_active_at??null}))}catch(s){throw new f("DB_ERROR","Failed to get provider usage",s)}finally{o.close();}}getModelUsage(e,n,r){if(!this.dbExists())return [];let o=this.openHandle(false);try{let s=sa(),i=qr(a.status),c=zo(a.metadata),d=drizzleOrm.sql`
308
308
  COALESCE(${a.input_tokens}, 0)
309
309
  + CASE
310
- WHEN ${a.started_at} >= ${Mn}
310
+ WHEN ${a.started_at} >= ${Xn}
311
311
  AND (
312
312
  ${a.crewx_version} IS NULL
313
313
  OR (${a.crewx_version} LIKE '0.8.%' AND ${a.crewx_version} NOT LIKE '0.8.9%')
314
- OR (${a.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${a.crewx_version}, ${$n}) AS INTEGER) < ${Hn})
314
+ OR (${a.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${a.crewx_version}, ${Yn}) AS INTEGER) < ${Qn})
315
315
  )
316
316
  THEN COALESCE(${a.cached_input_tokens}, 0)
317
317
  ELSE 0
@@ -331,7 +331,7 @@ ${r.join(`
331
331
  FROM ${a}
332
332
  ${u}
333
333
  GROUP BY ${a.model}, ${s}
334
- `),p=new Map;for(let _ of l){let h=Ns(_.model??""),m=JSON.stringify([_.provider,h]),k=p.get(m);k?(k.totalTasks+=_.total_tasks,k.unavailableTaskCount=(k.unavailableTaskCount??0)+_.unavailable_task_count,k.inputTokens+=_.input_tokens,k.outputTokens+=_.output_tokens,k.cachedInputTokens+=_.cached_input_tokens,k.costUsd+=_.cost_usd,k.totalTokens+=_.input_tokens+_.output_tokens,k.activeDurationMs+=_.active_duration_ms??0,_.last_active_at&&(!k.lastActiveAt||_.last_active_at>k.lastActiveAt)&&(k.lastActiveAt=_.last_active_at)):p.set(m,{model:h,provider:_.provider,totalTasks:_.total_tasks,unavailableTaskCount:_.unavailable_task_count,inputTokens:_.input_tokens,outputTokens:_.output_tokens,cachedInputTokens:_.cached_input_tokens,costUsd:_.cost_usd,totalTokens:_.input_tokens+_.output_tokens,activeDurationMs:_.active_duration_ms??0,lastActiveAt:_.last_active_at??null});}return Array.from(p.values()).sort((_,h)=>h.costUsd-_.costUsd)}catch(s){throw new f("DB_ERROR","Failed to get model usage",s)}finally{o.close();}}getTasksForReport(e,n,r){if(!this.dbExists())return [];let o=this.openHandle(false);try{let s=r?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 o.db.all(drizzleOrm.sql`
334
+ `),p=new Map;for(let _ of l){let h=Ws(_.model??""),m=JSON.stringify([_.provider,h]),k=p.get(m);k?(k.totalTasks+=_.total_tasks,k.unavailableTaskCount=(k.unavailableTaskCount??0)+_.unavailable_task_count,k.inputTokens+=_.input_tokens,k.outputTokens+=_.output_tokens,k.cachedInputTokens+=_.cached_input_tokens,k.costUsd+=_.cost_usd,k.totalTokens+=_.input_tokens+_.output_tokens,k.activeDurationMs+=_.active_duration_ms??0,_.last_active_at&&(!k.lastActiveAt||_.last_active_at>k.lastActiveAt)&&(k.lastActiveAt=_.last_active_at)):p.set(m,{model:h,provider:_.provider,totalTasks:_.total_tasks,unavailableTaskCount:_.unavailable_task_count,inputTokens:_.input_tokens,outputTokens:_.output_tokens,cachedInputTokens:_.cached_input_tokens,costUsd:_.cost_usd,totalTokens:_.input_tokens+_.output_tokens,activeDurationMs:_.active_duration_ms??0,lastActiveAt:_.last_active_at??null});}return Array.from(p.values()).sort((_,h)=>h.costUsd-_.costUsd)}catch(s){throw new f("DB_ERROR","Failed to get model usage",s)}finally{o.close();}}getTasksForReport(e,n,r){if(!this.dbExists())return [];let o=this.openHandle(false);try{let s=r?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 o.db.all(drizzleOrm.sql`
335
335
  SELECT
336
336
  ${a.thread_id} AS thread_id,
337
337
  ${a.agent_id} AS agent_id,
@@ -343,19 +343,19 @@ ${r.join(`
343
343
  FROM ${a}
344
344
  ${s}
345
345
  ORDER BY ${a.started_at} ASC
346
- `).map(c=>({threadId:c.thread_id,agentId:c.agent_id,startedAt:c.started_at,status:c.status,error:c.error,exitCode:c.exit_code,terminalReason:rt({status:c.status,error:c.error,metadata:c.metadata})??null}))}catch(s){throw new f("DB_ERROR","Failed to get tasks for report",s)}finally{o.close();}}getDelegationMatrix(e,n,r){if(!this.dbExists())return {edges:[],truncated:false};let o=this.openHandle(false);try{let s=drizzleOrm.sql`
346
+ `).map(c=>({threadId:c.thread_id,agentId:c.agent_id,startedAt:c.started_at,status:c.status,error:c.error,exitCode:c.exit_code,terminalReason:at({status:c.status,error:c.error,metadata:c.metadata})??null}))}catch(s){throw new f("DB_ERROR","Failed to get tasks for report",s)}finally{o.close();}}getDelegationMatrix(e,n,r){if(!this.dbExists())return {edges:[],truncated:false};let o=this.openHandle(false);try{let s=drizzleOrm.sql`
347
347
  COALESCE(${a.input_tokens}, 0)
348
348
  + CASE
349
- WHEN ${a.started_at} >= ${Mn}
349
+ WHEN ${a.started_at} >= ${Xn}
350
350
  AND (
351
351
  ${a.crewx_version} IS NULL
352
352
  OR (${a.crewx_version} LIKE '0.8.%' AND ${a.crewx_version} NOT LIKE '0.8.9%')
353
- OR (${a.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${a.crewx_version}, ${$n}) AS INTEGER) < ${Hn})
353
+ OR (${a.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${a.crewx_version}, ${Yn}) AS INTEGER) < ${Qn})
354
354
  )
355
355
  THEN COALESCE(${a.cached_input_tokens}, 0)
356
356
  ELSE 0
357
357
  END
358
- `,i=Nr(a.status),c=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=o.db.all(drizzleOrm.sql`
358
+ `,i=qr(a.status),c=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=o.db.all(drizzleOrm.sql`
359
359
  SELECT
360
360
  ${a.caller_agent_id} AS caller_agent_id,
361
361
  ${a.agent_id} AS agent_id,
@@ -366,28 +366,28 @@ ${r.join(`
366
366
  ${c}
367
367
  GROUP BY ${a.caller_agent_id}, ${a.agent_id}
368
368
  ORDER BY task_count DESC, ${a.caller_agent_id} ASC, ${a.agent_id} ASC
369
- LIMIT ${Bi+1}
370
- `),u=d.length>Bi;return {edges:d.slice(0,Bi).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:u}}catch(s){throw new f("DB_ERROR","Failed to get delegation matrix",s)}finally{o.close();}}findTaskEvidence(e){if(!this.dbExists())return [];let n=this.openHandle(false);try{let r=[];e.workspaceId&&r.push(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,Ti(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 o=r.length>0?drizzleOrm.and(...r):void 0,s=(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(o).orderBy(s).limit(e.limit).all():n.db.select(i).from(a).where(o).orderBy(s).all()).map(({error:d,metadata:u,...l})=>({...l,status:Ue({status:l.status,error:d,metadata:u}),terminalReason:rt({status:l.status,error:d,metadata:u})??null}))}catch(r){throw new f("DB_ERROR","Failed to find task evidence",r)}finally{n.close();}}findThreadChains(e){if(!this.dbExists())return [];let n=this.openHandle(false);try{let r=e.maxThreads??8,o=e.maxTurnsPerThread??4,s=[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),Xu()),drizzleOrm.or(drizzleOrm.isNull(a.metadata),drizzleOrm.notLike(a.metadata,'%"retriedFromTaskId"%'))];e.workspaceId&&s.push(drizzleOrm.eq(a.workspace_id,e.workspaceId)),e.from&&s.push(drizzleOrm.gte(a.started_at,e.from)),e.to&&s.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(...s)).orderBy(drizzleOrm.asc(a.started_at),drizzleOrm.asc(a.id)).all(),c=new Map;for(let u of i){if(!u.thread_id)continue;let l={id:u.id,agentId:u.agent_id,status:u.status,prompt:u.prompt,startedAt:u.started_at,completedAt:u.completed_at},p=c.get(u.thread_id);p?p.push(l):c.set(u.thread_id,[l]);}let d=[];for(let[u,l]of c){let p=l.filter(_=>_.agentId===e.targetAgentId).length;p<2||d.push({threadId:u,targetAgentTurnCount:p,turns:l});}return d.sort((u,l)=>{let p=u.turns[u.turns.length-1].startedAt,_=l.turns[l.turns.length-1].startedAt;return p<_?1:p>_?-1:0}),d.slice(0,r).map(u=>({threadId:u.threadId,targetAgentTurnCount:u.targetAgentTurnCount,turns:u.turns.slice(-o)}))}catch(r){throw new f("DB_ERROR","Failed to find thread chains",r)}finally{n.close();}}},sl=["up","down"],Zi=1e3,il=200,_m=64,Cr=class extends f{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;}},fm=new Set(ln);});g();g();g();var Ot=class{detach(e){}};g();function ga(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 es(t){let e=t.toISOString();return `${e.slice(0,10)} ${e.slice(11,19)} UTC`}var ts=class extends Ot{name="file-logger";unsubs=[];logFiles=new Map;logsDir;version;constructor(e){super(),this.logsDir=Re.join(e?.workspaceRoot??process.cwd(),".crewx","logs"),this.version=e?.version??"unknown";}attach(e){this.unsubs.push(e.on("task:start",n=>{try{nu.existsSync(this.logsDir)||nu.mkdirSync(this.logsDir,{recursive:!0});let r=ga(n.timestamp),o=Re.join(this.logsDir,`${r}_${n.traceId}.log`);this.logFiles.set(n.traceId,o);let s=`=== TASK LOG: ${n.traceId} ===
369
+ LIMIT ${oa+1}
370
+ `),u=d.length>oa;return {edges:d.slice(0,oa).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:u}}catch(s){throw new f("DB_ERROR","Failed to get delegation matrix",s)}finally{o.close();}}findTaskEvidence(e){if(!this.dbExists())return [];let n=this.openHandle(false);try{let r=[];e.workspaceId&&r.push(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,Mi(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 o=r.length>0?drizzleOrm.and(...r):void 0,s=(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(o).orderBy(s).limit(e.limit).all():n.db.select(i).from(a).where(o).orderBy(s).all()).map(({error:d,metadata:u,...l})=>({...l,status:xe({status:l.status,error:d,metadata:u}),terminalReason:at({status:l.status,error:d,metadata:u})??null}))}catch(r){throw new f("DB_ERROR","Failed to find task evidence",r)}finally{n.close();}}findThreadChains(e){if(!this.dbExists())return [];let n=this.openHandle(false);try{let r=e.maxThreads??8,o=e.maxTurnsPerThread??4,s=[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),yl()),drizzleOrm.or(drizzleOrm.isNull(a.metadata),drizzleOrm.notLike(a.metadata,'%"retriedFromTaskId"%'))];e.workspaceId&&s.push(drizzleOrm.eq(a.workspace_id,e.workspaceId)),e.from&&s.push(drizzleOrm.gte(a.started_at,e.from)),e.to&&s.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(...s)).orderBy(drizzleOrm.asc(a.started_at),drizzleOrm.asc(a.id)).all(),c=new Map;for(let u of i){if(!u.thread_id)continue;let l={id:u.id,agentId:u.agent_id,status:u.status,prompt:u.prompt,startedAt:u.started_at,completedAt:u.completed_at},p=c.get(u.thread_id);p?p.push(l):c.set(u.thread_id,[l]);}let d=[];for(let[u,l]of c){let p=l.filter(_=>_.agentId===e.targetAgentId).length;p<2||d.push({threadId:u,targetAgentTurnCount:p,turns:l});}return d.sort((u,l)=>{let p=u.turns[u.turns.length-1].startedAt,_=l.turns[l.turns.length-1].startedAt;return p<_?1:p>_?-1:0}),d.slice(0,r).map(u=>({threadId:u.threadId,targetAgentTurnCount:u.targetAgentTurnCount,turns:u.turns.slice(-o)}))}catch(r){throw new f("DB_ERROR","Failed to find thread chains",r)}finally{n.close();}}},Ol=["up","down"],ga=1e3,vl=200,Km=64,Wr=class extends f{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;}},Jm=new Set(wn);});g();g();g();var Ut=class{detach(e){}};g();function Ma(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 fs(t){let e=t.toISOString();return `${e.slice(0,10)} ${e.slice(11,19)} UTC`}var gs=class extends Ut{name="file-logger";unsubs=[];logFiles=new Map;logsDir;version;constructor(e){super(),this.logsDir=Ne.join(e?.workspaceRoot??process.cwd(),".crewx","logs"),this.version=e?.version??"unknown";}attach(e){this.unsubs.push(e.on("task:start",n=>{try{Iu.existsSync(this.logsDir)||Iu.mkdirSync(this.logsDir,{recursive:!0});let r=Ma(n.timestamp),o=Ne.join(this.logsDir,`${r}_${n.traceId}.log`);this.logFiles.set(n.traceId,o);let s=`=== TASK LOG: ${n.traceId} ===
371
371
  CrewX Version: ${this.version}
372
372
  Mode: ${n.mode}
373
373
  Agent: ${n.agentRef}
374
- Started: ${es(n.timestamp)}
374
+ Started: ${fs(n.timestamp)}
375
375
  Message: ${n.message}
376
376
 
377
- `;nu.writeFileSync(o,s,{encoding:"utf8",mode:384});}catch{}}),e.on("task:output",n=>{try{let r=this.logFiles.get(n.traceId);if(!r)return;let o=new Date().toISOString();nu.appendFileSync(r,`[${o}] STDOUT: ${n.output}
378
- `,"utf8");}catch{}}),e.on("task:end",n=>{try{let r=this.logFiles.get(n.traceId);if(!r)return;let o=es(new Date),s=n.error?`failed: ${n.error.message}`:"completed successfully",i=`[${o}] INFO: Task ${s} in ${n.durationMs}ms
377
+ `;Iu.writeFileSync(o,s,{encoding:"utf8",mode:384});}catch{}}),e.on("task:output",n=>{try{let r=this.logFiles.get(n.traceId);if(!r)return;let o=new Date().toISOString();Iu.appendFileSync(r,`[${o}] STDOUT: ${n.output}
378
+ `,"utf8");}catch{}}),e.on("task:end",n=>{try{let r=this.logFiles.get(n.traceId);if(!r)return;let o=fs(new Date),s=n.error?`failed: ${n.error.message}`:"completed successfully",i=`[${o}] INFO: Task ${s} in ${n.durationMs}ms
379
379
  [${o}] INFO: Process closed with exit code: ${n.error?1:0}
380
- `;nu.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 ka=Symbol.for("crewx.interceptor.run-stops");function Gl(){let t=globalThis,e=t[ka];if(e)return e;let n=new Map;return t[ka]=n,n}function ya(t){let e=Gl().get(t);return e?(e.abort(),true):false}g();var gn=new Map;function Br(t){let e=Re__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 Ea(t){let e=Br(t);return crypto.createHash("sha256").update(e).digest("hex")}function Ra(t){let e=Br(t),n=gn.get(e);if(n!==void 0)return n;let r=e;try{let o=Re__namespace.join(e,".git");if(!nu.lstatSync(o).isFile())return gn.set(e,r),r;let s=/^gitdir:\s*(.+?)\s*$/i.exec(nu.readFileSync(o,"utf8").trim());if(!s)return gn.set(e,r),r;let i=s[1],c=Re__namespace.isAbsolute(i)?i:Re__namespace.resolve(Re__namespace.dirname(o),i),d=nu.readFileSync(Re__namespace.join(c,"commondir"),"utf8").trim();if(!d)return gn.set(e,r),r;let u=Re__namespace.isAbsolute(d)?d:Re__namespace.resolve(c,d);if(Re__namespace.basename(u)!==".git"||!nu.statSync(u).isDirectory())return gn.set(e,r),r;let l=Br(nu.realpathSync.native(e)),p=Br(nu.realpathSync.native(Re__namespace.dirname(u)));(l===p||(p.endsWith("/")?l.startsWith(p):l.startsWith(`${p}/`)))&&(r=p);}catch{}return gn.set(e,r),r}vt();Hi();Sn();ki();Rr();$i();co();var ym=200,Tm=200;function wm(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 Em(t){let e=t instanceof f?t.code:void 0,n=t instanceof f?t.cause:t,r=wm(n);return {code:e??r??"DB_ERROR",cause:r??(n instanceof Error?n.name:e??typeof n)}}function ul(t){return Buffer.byteLength(JSON.stringify(t),"utf8")}function Rm(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function ll(t){if(!t)return {};try{let e=JSON.parse(t);return Rm(e)?e:{}}catch{return {}}}function qn(t){return typeof t=="number"&&Number.isFinite(t)?Math.trunc(t):0}var Sm=new Set(["workflow","mcp"]),ta=class extends Ot{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?Re.join(e.dbRoot,".crewx","crewx.db"):n??Re.join(Na.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 vr({dbPath:this.dbPath});n.resolveDbPath(),this.taskRepo=n;let r=process.cwd(),o=nu.existsSync(Re.join(r,"crewx.yaml"))||nu.existsSync(Re.join(r,"crewx.yml")),s=this.inheritWorktreeOwner?Ra(r):r,i=o?Ea(s):null,c=process.argv.join(" ");this.unsubs.push(e.on("task:start",d=>{try{let u=d.callerAgentId??null,l=d.parentTaskId??null,p=d.rootTraceId??d.traceId,{detachedRunner:_,assignedTaskId:h}=this.runnerIdentity,m=h??d.traceId,k=qn(d.metadata?.runEpoch),E=_?"runner":"caller",b=d.workspaceId??i,T=_?n.getTask(m):void 0,P=d.pid??null,A={...d.metadata??{provider:d.provider??"cli/claude"},ownership:E,..._&&P!==null?{providerPid:P}:{}},x=JSON.stringify(A);if(_&&T?.status==="running"&&T.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:_?process.pid:P,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:c,codingAgentCommand:d.codingAgentCommand??null,workspaceId:b,projectId:d.projectId??null,callerAgentId:u,parentTaskId:l,traceId:p,metadata:x,threadId:d.threadId??null,cwd:d.cwd??null}),n.updateTaskOwnership({id:m,runEpoch:k,ownership:E,..._?{providerPid:P}:{},runtime:{model:d.model??null,renderedPrompt:d.renderedPrompt??null,codingAgentCommand:d.codingAgentCommand??null,metadata:A}})?this.recordOwnedTaskRun({taskId:m,runEpoch:k,workspaceId:b,ownership:E}):console.warn("[crewx] task execution metadata not recorded",{taskId:m,runEpoch:k,ownership:E}),Sm.has(d.platform??"cli")||Fu(n,{taskId:m,runEpoch:k,onStopRequested:De=>this.handleStopRequested(n,De)})&&this.heartbeatTaskIds.add(m);}catch(u){console.warn("[crewx] task:start tracing failed",{cause:u instanceof Error?u.name:typeof u});}}),e.on("task:output",d=>{try{let u=this.resolveTaskId(d.traceId);if(this.ignoredDetachedTaskIds.has(u))return;this.enqueueLog(u,{timestamp:d.timestamp.toISOString(),level:d.level??"stdout",message:d.output});}catch(u){let l={timestamp:d.timestamp.toISOString(),level:d.level??"stdout",message:d.output};this.recordAppendFailure(u,[l],ul(l));}}),e.on("task:run-update",d=>{try{let u=this.resolveTaskId(d.traceId);if(this.ignoredDetachedTaskIds.has(u))return;let l=qn(d.runEpoch),p=this.runnerIdentity.detachedRunner;n.updateTaskOwnership({id:u,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:u,runEpoch:l,pid:d.pid});}catch(u){console.warn("[crewx] task:run-update tracing failed",{cause:u instanceof Error?u.name:typeof u});}}),e.on("task:provider-input",d=>{try{let u=this.resolveTaskId(d.traceId);if(this.ignoredDetachedTaskIds.has(u))return;n.recordProviderInput({id:u,runEpoch:d.runEpoch,input:d.input,keyWrapSkipped:d.keyWrapSkipped,interceptedRequest:d.interceptedRequest===!0,recordedAt:d.timestamp.toISOString()});}catch(u){console.warn("[crewx] task:provider-input tracing failed",{cause:u instanceof Error?u.name:typeof u});}}),e.on("task:end",d=>{try{let u=this.resolveTaskId(d.traceId);if(this.ignoredDetachedTaskIds.delete(u))return;let l=typeof d.metadata?.runEpoch=="number"?d.metadata.runEpoch:null;this.removeOwnedTaskRun(u,qn(l)),Er(u,l)&&this.heartbeatTaskIds.delete(u),this.flushTaskLogs(u);let _=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(u,d,l);E&&(h=E,m=!0);}n.finishTask({id:u,status:d.error?"failed":"success",result:h,error:_,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)Er(n);this.heartbeatTaskIds.clear(),this.ownedTaskRuns.clear(),this.unsubs.forEach(n=>n()),this.unsubs=[],this.queues.clear(),this.ignoredDetachedTaskIds.clear(),this.taskRepo=void 0;}}listOwnedRunningTasks(){return Array.from(this.ownedTaskRuns.values(),e=>({...e}))}async stopOwnedRunningTasksForHostShutdown(){let e=this.taskRepo;if(!e)return;let n=this.listOwnedRunningTasks();for(let r of n)try{let o=await zu(e,{taskId:r.taskId,expectedRunEpoch:r.runEpoch,workspaceId:r.workspaceId});(o.status==="failed"||o.status==="ownership_unverified")&&console.warn("[crewx] host-shutdown task stop failed",{taskId:r.taskId,runEpoch:r.runEpoch,status:o.status,...o.error?{error:o.error}:{}});}catch(o){console.warn("[crewx] host-shutdown task stop failed",{taskId:r.taskId,runEpoch:r.runEpoch,cause:o instanceof Error?o.name:typeof o});}}getMetrics(){let e=0,n=0;for(let r of this.queues.values())e+=r.entries.length,n+=r.bytes;return {...this.metrics,appendFailureByCode:{...this.metrics.appendFailureByCode},appendFailureByCause:{...this.metrics.appendFailureByCause},pendingQueueEntries:e,pendingQueueBytes:n}}resolveTaskId(e){return this.runnerIdentity.detachedRunner?this.runnerIdentity.assignedTaskId??e:e}recordOwnedTaskRun(e){let n=this.ownedTaskRuns.get(e.taskId);n&&n.runEpoch>e.runEpoch||this.ownedTaskRuns.set(e.taskId,{...e});}removeOwnedTaskRun(e,n){let r=this.ownedTaskRuns.get(e);!r||r.runEpoch!==n||this.ownedTaskRuns.delete(e);}enqueueLog(e,n){let r=this.queues.get(e);if(r||(r={entries:[],bytes:0},this.queues.set(e,r)),r.entries.push(n),r.bytes+=ul(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>=ym){this.flushTaskLogs(e);return}if(!r.timer){let o=setTimeout(()=>{let s=this.queues.get(e);!s||s.timer!==o||(s.timer=void 0,this.flushTaskLogs(e));},Tm);r.timer=o;}}recoverPartialResult(e,n,r){try{let o=this.taskRepo;if(!o)return;let s=o.getTask(e);if(!s||s.status!=="running"||qn(s.run_epoch)!==qn(r))return;let i=ll(s.metadata),c=typeof i.provider=="string"?i.provider:typeof n.metadata?.provider=="string"?n.metadata.provider:void 0;if(!c)return;let d=vo({taskLogRepository:o,taskId:e,provider:c,model:s.model});if(!d?.adapter.extractPartialText)return;let u=d.adapter.extractPartialText(d.stdout);return !u||!u.trim()||mt(u,c)?void 0:u}catch{return}}async handleStopRequested(e,n){let r=n.id;if(!r)return;let o=qn(n.run_epoch),s=ll(n.metadata??null),i=s.ownership==="runner"?"runner":"caller";if(i==="runner"&&n.pid!==process.pid){console.warn("[crewx] ignored stop request for task owned by another runner",{taskId:r});return}let c=typeof s.providerPid=="number"&&Number.isSafeInteger(s.providerPid)&&s.providerPid>0?s.providerPid:void 0,d=i==="runner"?c:typeof n.pid=="number"&&n.pid>0?n.pid:void 0;if(ya(r),d!==void 0){let u;try{u=await Mt(d,{signal:Lt});}catch(l){console.warn("[crewx] cooperative task stop failed",{taskId:r,cause:l instanceof Error?l.name:typeof l});return}if(u.status==="failed"){console.warn("[crewx] cooperative task stop failed",{taskId:r,cause:u.error??"process termination failed"});return}}try{let u=e.finalizeTaskStop({id:r,runEpoch:o,method:Do(n.stop_requested_at)}),l=e.getTask(r);(u||l?.status!=="running")&&Er(r,o)&&this.heartbeatTaskIds.delete(r);}catch(u){console.warn("[crewx] cooperative task stop finalization failed",{taskId:r,cause:u instanceof Error?u.name:typeof u});}}flushTaskLogs(e){let n=this.queues.get(e);if(!n||n.entries.length===0){n?.timer&&clearTimeout(n.timer),this.queues.delete(e);return}n.timer&&(clearTimeout(n.timer),n.timer=void 0);let r=n.entries,o=n.bytes;n.entries=[],n.bytes=0,this.metrics.flushCount+=1;try{this.taskRepo?.appendLogs(e,r),this.metrics.flushedEntries+=r.length;}catch(i){this.recordAppendFailure(i,r,o);}let s=this.queues.get(e);s&&s.entries.length===0&&(s.timer&&clearTimeout(s.timer),this.queues.delete(e));}flushAllTaskLogs(){for(let e of [...this.queues.keys()])this.flushTaskLogs(e);}clearAllTimers(){for(let e of this.queues.values())e.timer&&(clearTimeout(e.timer),e.timer=void 0);}recordAppendFailure(e,n,r){let o=Em(e);this.metrics.appendFailureCount+=1,this.metrics.appendFailureEntries+=n.length,this.metrics.appendFailureBytes+=r,this.metrics.appendFailureByCode[o.code]=(this.metrics.appendFailureByCode[o.code]??0)+1,this.metrics.appendFailureByCause[o.cause]=(this.metrics.appendFailureByCause[o.cause]??0)+1,console.warn("[crewx] sqlite tracing append failed",{code:o.code,cause:o.cause,pendingEntries:n.length,pendingBytes:r});}};g();g();g();Ct();Kt();zt();vt();rn();ro();yr();g();function Fo(t){return t!==null&&t!==""}function Im(t){return t.schedule_id!==null&&t.schedule_id!==void 0?"system":Fo(t.parent_task_id)||Fo(t.caller_agent_id)?"agent":t.platform==="workflow"?"system":"human"}function pl(t,e){return {origin:t==="human"?"direct":"delegated",delegatedByAgentId:t==="agent"&&Fo(e)?e:null}}function Bo(t){let e=Im(t),n=Fo(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 _l(t,e,n){return t.creator_task_id!==null&&t.creator_pointer_unverified===0?t.creator_actor_kind!==null?pl(t.creator_actor_kind,t.creator_actor_id):e?Bo(e):{origin:"direct",delegatedByAgentId:null}:t.created_by_kind!==null?pl(t.created_by_kind,t.created_by_id):n?Bo(n):void 0}function xr(t){return kr(t)}function xm({metadata:t,...e}){return {...e,status:Ue({...e,metadata:t}),terminalReason:rt({...e,metadata:t})??null}}var br=32,gl=100,bm=["running","failed"];function Dm(t){return t==="running"?0:t==="failed"?1:2}function hl(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 Pm(t){return Buffer.from(JSON.stringify(t),"utf8").toString("base64url")}function Lm(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 f("VALIDATION","Invalid descendant cursor")}function ml(t,e,n){return t===void 0||!Number.isFinite(t)?e:Math.min(n,Math.max(1,Math.trunc(t)))}function na(t){return {total:0,running:0,pending:0,paused:0,success:0,failed:0,stopped:0,runnerLost:0,checkedAt:t}}function Mm(t){switch(t){case "running":case "pending":case "paused":case "success":case "failed":case "stopped":return t;default:return}}function ra(t,e,n,r){let o=Mm(e);o&&(t[o]+=r,t.total+=r,o==="failed"&&n==="runner_lost"&&(t.runnerLost+=r));}var Go=900,kl=20;function yl(t,e){return (t?.origin??"direct")===e}function Tl(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 Fn=class extends f{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 $m(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 wl(t,e,n){return t.get(drizzleOrm.sql`
380
+ `;Iu.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 Ua=Symbol.for("crewx.interceptor.run-stops");function Ep(){let t=globalThis,e=t[Ua];if(e)return e;let n=new Map;return t[Ua]=n,n}function qa(t){let e=Ep().get(t);return e?(e.abort(),true):false}g();var An=new Map;function eo(t){let e=Ne__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 Wa(t){let e=eo(t);return crypto.createHash("sha256").update(e).digest("hex")}function Ga(t){let e=eo(t),n=An.get(e);if(n!==void 0)return n;let r=e;try{let o=Ne__namespace.join(e,".git");if(!Iu.lstatSync(o).isFile())return An.set(e,r),r;let s=/^gitdir:\s*(.+?)\s*$/i.exec(Iu.readFileSync(o,"utf8").trim());if(!s)return An.set(e,r),r;let i=s[1],c=Ne__namespace.isAbsolute(i)?i:Ne__namespace.resolve(Ne__namespace.dirname(o),i),d=Iu.readFileSync(Ne__namespace.join(c,"commondir"),"utf8").trim();if(!d)return An.set(e,r),r;let u=Ne__namespace.isAbsolute(d)?d:Ne__namespace.resolve(c,d);if(Ne__namespace.basename(u)!==".git"||!Iu.statSync(u).isDirectory())return An.set(e,r),r;let l=eo(Iu.realpathSync.native(e)),p=eo(Iu.realpathSync.native(Ne__namespace.dirname(u)));(l===p||(p.endsWith("/")?l.startsWith(p):l.startsWith(`${p}/`)))&&(r=p);}catch{}return An.set(e,r),r}Nt();ea();$n();Pi();Mr();Zi();wo();var Zm=200,ek=200;function tk(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 nk(t){let e=t instanceof f?t.code:void 0,n=t instanceof f?t.cause:t,r=tk(n);return {code:e??r??"DB_ERROR",cause:r??(n instanceof Error?n.name:e??typeof n)}}function Dl(t){return Buffer.byteLength(JSON.stringify(t),"utf8")}function rk(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Pl(t){if(!t)return {};try{let e=JSON.parse(t);return rk(e)?e:{}}catch{return {}}}function er(t){return typeof t=="number"&&Number.isFinite(t)?Math.trunc(t):0}var ok=new Set(["workflow","mcp"]),ma=class extends Ut{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?Ne.join(e.dbRoot,".crewx","crewx.db"):n??Ne.join(Ja.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 Fr({dbPath:this.dbPath});n.resolveDbPath(),this.taskRepo=n;let r=process.cwd(),o=Iu.existsSync(Ne.join(r,"crewx.yaml"))||Iu.existsSync(Ne.join(r,"crewx.yml")),s=this.inheritWorktreeOwner?Ga(r):r,i=o?Wa(s):null,c=process.argv.join(" ");this.unsubs.push(e.on("task:start",d=>{try{let u=d.callerAgentId??null,l=d.parentTaskId??null,p=d.rootTraceId??d.traceId,{detachedRunner:_,assignedTaskId:h}=this.runnerIdentity,m=h??d.traceId,k=er(d.metadata?.runEpoch),w=_?"runner":"caller",C=d.workspaceId??i,T=_?n.getTask(m):void 0,P=d.pid??null,A={...d.metadata??{provider:d.provider??"cli/claude"},ownership:w,..._&&P!==null?{providerPid:P}:{}},x=JSON.stringify(A);if(_&&T?.status==="running"&&T.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:_?process.pid:P,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:c,codingAgentCommand:d.codingAgentCommand??null,workspaceId:C,projectId:d.projectId??null,callerAgentId:u,parentTaskId:l,traceId:p,metadata:x,threadId:d.threadId??null,cwd:d.cwd??null}),n.updateTaskOwnership({id:m,runEpoch:k,ownership:w,..._?{providerPid:P}:{},runtime:{model:d.model??null,renderedPrompt:d.renderedPrompt??null,codingAgentCommand:d.codingAgentCommand??null,metadata:A}})?this.recordOwnedTaskRun({taskId:m,runEpoch:k,workspaceId:C,ownership:w}):console.warn("[crewx] task execution metadata not recorded",{taskId:m,runEpoch:k,ownership:w}),ok.has(d.platform??"cli")||ul(n,{taskId:m,runEpoch:k,onStopRequested:Ue=>this.handleStopRequested(n,Ue)})&&this.heartbeatTaskIds.add(m);}catch(u){console.warn("[crewx] task:start tracing failed",{cause:u instanceof Error?u.name:typeof u});}}),e.on("task:output",d=>{try{let u=this.resolveTaskId(d.traceId);if(this.ignoredDetachedTaskIds.has(u))return;this.enqueueLog(u,{timestamp:d.timestamp.toISOString(),level:d.level??"stdout",message:d.output});}catch(u){let l={timestamp:d.timestamp.toISOString(),level:d.level??"stdout",message:d.output};this.recordAppendFailure(u,[l],Dl(l));}}),e.on("task:run-update",d=>{try{let u=this.resolveTaskId(d.traceId);if(this.ignoredDetachedTaskIds.has(u))return;let l=er(d.runEpoch),p=this.runnerIdentity.detachedRunner;n.updateTaskOwnership({id:u,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:u,runEpoch:l,pid:d.pid});}catch(u){console.warn("[crewx] task:run-update tracing failed",{cause:u instanceof Error?u.name:typeof u});}}),e.on("task:provider-input",d=>{try{let u=this.resolveTaskId(d.traceId);if(this.ignoredDetachedTaskIds.has(u))return;n.recordProviderInput({id:u,runEpoch:d.runEpoch,input:d.input,keyWrapSkipped:d.keyWrapSkipped,interceptedRequest:d.interceptedRequest===!0,recordedAt:d.timestamp.toISOString()});}catch(u){console.warn("[crewx] task:provider-input tracing failed",{cause:u instanceof Error?u.name:typeof u});}}),e.on("task:end",d=>{try{let u=this.resolveTaskId(d.traceId);if(this.ignoredDetachedTaskIds.delete(u))return;let l=typeof d.metadata?.runEpoch=="number"?d.metadata.runEpoch:null;this.removeOwnedTaskRun(u,er(l)),Lr(u,l)&&this.heartbeatTaskIds.delete(u),this.flushTaskLogs(u);let _=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 w=this.recoverPartialResult(u,d,l);w&&(h=w,m=!0);}n.finishTask({id:u,status:d.error?"failed":"success",result:h,error:_,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)Lr(n);this.heartbeatTaskIds.clear(),this.ownedTaskRuns.clear(),this.unsubs.forEach(n=>n()),this.unsubs=[],this.queues.clear(),this.ignoredDetachedTaskIds.clear(),this.taskRepo=void 0;}}listOwnedRunningTasks(){return Array.from(this.ownedTaskRuns.values(),e=>({...e}))}async stopOwnedRunningTasksForHostShutdown(){let e=this.taskRepo;if(!e)return;let n=this.listOwnedRunningTasks();for(let r of n)try{let o=await hl(e,{taskId:r.taskId,expectedRunEpoch:r.runEpoch,workspaceId:r.workspaceId});(o.status==="failed"||o.status==="ownership_unverified")&&console.warn("[crewx] host-shutdown task stop failed",{taskId:r.taskId,runEpoch:r.runEpoch,status:o.status,...o.error?{error:o.error}:{}});}catch(o){console.warn("[crewx] host-shutdown task stop failed",{taskId:r.taskId,runEpoch:r.runEpoch,cause:o instanceof Error?o.name:typeof o});}}getMetrics(){let e=0,n=0;for(let r of this.queues.values())e+=r.entries.length,n+=r.bytes;return {...this.metrics,appendFailureByCode:{...this.metrics.appendFailureByCode},appendFailureByCause:{...this.metrics.appendFailureByCause},pendingQueueEntries:e,pendingQueueBytes:n}}resolveTaskId(e){return this.runnerIdentity.detachedRunner?this.runnerIdentity.assignedTaskId??e:e}recordOwnedTaskRun(e){let n=this.ownedTaskRuns.get(e.taskId);n&&n.runEpoch>e.runEpoch||this.ownedTaskRuns.set(e.taskId,{...e});}removeOwnedTaskRun(e,n){let r=this.ownedTaskRuns.get(e);!r||r.runEpoch!==n||this.ownedTaskRuns.delete(e);}enqueueLog(e,n){let r=this.queues.get(e);if(r||(r={entries:[],bytes:0},this.queues.set(e,r)),r.entries.push(n),r.bytes+=Dl(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>=Zm){this.flushTaskLogs(e);return}if(!r.timer){let o=setTimeout(()=>{let s=this.queues.get(e);!s||s.timer!==o||(s.timer=void 0,this.flushTaskLogs(e));},ek);r.timer=o;}}recoverPartialResult(e,n,r){try{let o=this.taskRepo;if(!o)return;let s=o.getTask(e);if(!s||s.status!=="running"||er(s.run_epoch)!==er(r))return;let i=Pl(s.metadata),c=typeof i.provider=="string"?i.provider:typeof n.metadata?.provider=="string"?n.metadata.provider:void 0;if(!c)return;let d=Bo({taskLogRepository:o,taskId:e,provider:c,model:s.model});if(!d?.adapter.extractPartialText)return;let u=d.adapter.extractPartialText(d.stdout);return !u||!u.trim()||Et(u,c)?void 0:u}catch{return}}async handleStopRequested(e,n){let r=n.id;if(!r)return;let o=er(n.run_epoch),s=Pl(n.metadata??null),i=s.ownership==="runner"?"runner":"caller";if(i==="runner"&&n.pid!==process.pid){console.warn("[crewx] ignored stop request for task owned by another runner",{taskId:r});return}let c=typeof s.providerPid=="number"&&Number.isSafeInteger(s.providerPid)&&s.providerPid>0?s.providerPid:void 0,d=i==="runner"?c:typeof n.pid=="number"&&n.pid>0?n.pid:void 0;if(qa(r),d!==void 0){let u;try{u=await Jt(d,{signal:Kt});}catch(l){console.warn("[crewx] cooperative task stop failed",{taskId:r,cause:l instanceof Error?l.name:typeof l});return}if(u.status==="failed"){console.warn("[crewx] cooperative task stop failed",{taskId:r,cause:u.error??"process termination failed"});return}}try{let u=e.finalizeTaskStop({id:r,runEpoch:o,method:jo(n.stop_requested_at)}),l=e.getTask(r);(u||l?.status!=="running")&&Lr(r,o)&&this.heartbeatTaskIds.delete(r);}catch(u){console.warn("[crewx] cooperative task stop finalization failed",{taskId:r,cause:u instanceof Error?u.name:typeof u});}}flushTaskLogs(e){let n=this.queues.get(e);if(!n||n.entries.length===0){n?.timer&&clearTimeout(n.timer),this.queues.delete(e);return}n.timer&&(clearTimeout(n.timer),n.timer=void 0);let r=n.entries,o=n.bytes;n.entries=[],n.bytes=0,this.metrics.flushCount+=1;try{this.taskRepo?.appendLogs(e,r),this.metrics.flushedEntries+=r.length;}catch(i){this.recordAppendFailure(i,r,o);}let s=this.queues.get(e);s&&s.entries.length===0&&(s.timer&&clearTimeout(s.timer),this.queues.delete(e));}flushAllTaskLogs(){for(let e of [...this.queues.keys()])this.flushTaskLogs(e);}clearAllTimers(){for(let e of this.queues.values())e.timer&&(clearTimeout(e.timer),e.timer=void 0);}recordAppendFailure(e,n,r){let o=nk(e);this.metrics.appendFailureCount+=1,this.metrics.appendFailureEntries+=n.length,this.metrics.appendFailureBytes+=r,this.metrics.appendFailureByCode[o.code]=(this.metrics.appendFailureByCode[o.code]??0)+1,this.metrics.appendFailureByCause[o.cause]=(this.metrics.appendFailureByCause[o.cause]??0)+1,console.warn("[crewx] sqlite tracing append failed",{code:o.code,cause:o.cause,pendingEntries:n.length,pendingBytes:r});}};g();g();g();Ot();qt();Bt();Nt();Gt();ho();Kn();g();function Zo(t){return t!==null&&t!==""}function sk(t){return t.schedule_id!==null&&t.schedule_id!==void 0?"system":Zo(t.parent_task_id)||Zo(t.caller_agent_id)?"agent":t.platform==="workflow"?"system":"human"}function Ll(t,e){return {origin:t==="human"?"direct":"delegated",delegatedByAgentId:t==="agent"&&Zo(e)?e:null}}function es(t){let e=sk(t),n=Zo(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 Ml(t,e,n){return t.creator_task_id!==null&&t.creator_pointer_unverified===0?t.creator_actor_kind!==null?Ll(t.creator_actor_kind,t.creator_actor_id):e?es(e):{origin:"direct",delegatedByAgentId:null}:t.created_by_kind!==null?Ll(t.created_by_kind,t.created_by_id):n?es(n):void 0}function Gr(t){return xr(t)}function lk({metadata:t,...e}){return {...e,status:xe({...e,metadata:t}),terminalReason:at({...e,metadata:t})??null}}var jr=32,Hl=100,pk=["running","failed"];function _k(t){return t==="running"?0:t==="failed"?1:2}function Ul(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 fk(t){return Buffer.from(JSON.stringify(t),"utf8").toString("base64url")}function gk(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 f("VALIDATION","Invalid descendant cursor")}function ql(t,e,n){return t===void 0||!Number.isFinite(t)?e:Math.min(n,Math.max(1,Math.trunc(t)))}function ka(t){return {total:0,running:0,pending:0,paused:0,success:0,failed:0,stopped:0,runnerLost:0,checkedAt:t}}function hk(t){switch(t){case "running":case "pending":case "paused":case "success":case "failed":case "stopped":return t;default:return}}function ya(t,e,n,r){let o=hk(e);o&&(t[o]+=r,t.total+=r,o==="failed"&&n==="runner_lost"&&(t.runnerLost+=r));}var ns=900,Bl=20;function Fl(t,e){return (t?.origin??"direct")===e}function Wl(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 tr=class extends f{reason;constructor(e,n=e){super("VALIDATION",n),this.name="ThreadTitleMetadataPatchError",this.reason=e;}};function nr(t){if(!t)return {};try{let e=JSON.parse(t);return !e||typeof e!="object"||Array.isArray(e)?{}:e}catch{return {}}}function mk(t){let n=nr(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 Gl(t,e,n){return t.get(drizzleOrm.sql`
381
381
  SELECT id
382
382
  FROM tasks INDEXED BY idx_tasks_thread_id
383
383
  WHERE thread_id = ${e}
384
384
  AND id <> ${n}
385
385
  LIMIT 1
386
- `)!==void 0}function Hm(t,e,n){let r=n?drizzleOrm.and(drizzleOrm.eq(y.id,e),drizzleOrm.eq(y.workspace_id,n)):drizzleOrm.eq(y.id,e),o=t.select({pinned:y.pinned,metadata:y.metadata}).from(y).where(r).get();if(!o)return null;let s=o.pinned?0:1,i=Bn(o.metadata);if(s){let c=n?drizzleOrm.and(drizzleOrm.eq(y.pinned,1),drizzleOrm.eq(y.workspace_id,n)):drizzleOrm.eq(y.pinned,1),d=t.select({metadata:y.metadata}).from(y).where(c).all(),u=null;for(let l of d){let p=Bn(l.metadata);typeof p.pinOrder=="number"&&(u===null||p.pinOrder<u)&&(u=p.pinOrder);}i.pinOrder=u===null?0:u-1;}else delete i.pinOrder;return t.update(y).set({pinned:s,metadata:Object.keys(i).length>0?JSON.stringify(i):null}).where(r).run(),{pinned:!!s}}function Um(t,e,n){for(let r=0;r<e.length;r++){let o=n?drizzleOrm.and(drizzleOrm.eq(y.id,e[r]),drizzleOrm.eq(y.workspace_id,n)):drizzleOrm.eq(y.id,e[r]),s=t.select({metadata:y.metadata}).from(y).where(o).get();if(!s)continue;let i=Bn(s.metadata);i.pinOrder=r+1,t.update(y).set({metadata:JSON.stringify(i)}).where(o).run();}}var jo=class extends ve{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=Re.join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let n=this.resolveDbPath();if(e){let o=Re.dirname(n);nu.existsSync(o)||nu.mkdirSync(o,{recursive:true});}else if(!nu.existsSync(n))throw new f("NOT_FOUND","Database not found");let r=U(n);if(e)try{Be(r.db,n);}catch(o){throw r.close(),o}return r}topLevelTaskPredicateSql(e="child",n){let r=n?`tasks parent INDEXED BY ${n}`:"tasks parent";return drizzleOrm.sql.raw(`NOT EXISTS (
386
+ `)!==void 0}function kk(t,e,n){let r=n?drizzleOrm.and(drizzleOrm.eq(y.id,e),drizzleOrm.eq(y.workspace_id,n)):drizzleOrm.eq(y.id,e),o=t.select({pinned:y.pinned,metadata:y.metadata}).from(y).where(r).get();if(!o)return null;let s=o.pinned?0:1,i=nr(o.metadata);if(s){let c=n?drizzleOrm.and(drizzleOrm.eq(y.pinned,1),drizzleOrm.eq(y.workspace_id,n)):drizzleOrm.eq(y.pinned,1),d=t.select({metadata:y.metadata}).from(y).where(c).all(),u=null;for(let l of d){let p=nr(l.metadata);typeof p.pinOrder=="number"&&(u===null||p.pinOrder<u)&&(u=p.pinOrder);}i.pinOrder=u===null?0:u-1;}else delete i.pinOrder;return t.update(y).set({pinned:s,metadata:Object.keys(i).length>0?JSON.stringify(i):null}).where(r).run(),{pinned:!!s}}function yk(t,e,n){for(let r=0;r<e.length;r++){let o=n?drizzleOrm.and(drizzleOrm.eq(y.id,e[r]),drizzleOrm.eq(y.workspace_id,n)):drizzleOrm.eq(y.id,e[r]),s=t.select({metadata:y.metadata}).from(y).where(o).get();if(!s)continue;let i=nr(s.metadata);i.pinOrder=r+1,t.update(y).set({metadata:JSON.stringify(i)}).where(o).run();}}var rs=class extends me{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=Ne.join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let n=this.resolveDbPath();if(e){let o=Ne.dirname(n);Iu.existsSync(o)||Iu.mkdirSync(o,{recursive:true});}else if(!Iu.existsSync(n))throw new f("NOT_FOUND","Database not found");let r=H(n);if(e)try{Pe(r.db,n);}catch(o){throw r.close(),o}return r}topLevelTaskPredicateSql(e="child",n){let r=n?`tasks parent INDEXED BY ${n}`:"tasks parent";return drizzleOrm.sql.raw(`NOT EXISTS (
387
387
  SELECT 1 FROM ${r}
388
388
  WHERE parent.id = ${e}.parent_task_id
389
389
  AND parent.thread_id = ${e}.thread_id
390
- )`)}workflowAnchorPredicateSql(e){let n=Dt.map(r=>`OR ${e}.metadata LIKE '%"kind":"${r}"%'`).join(`
390
+ )`)}workflowAnchorPredicateSql(e){let n=jt.map(r=>`OR ${e}.metadata LIKE '%"kind":"${r}"%'`).join(`
391
391
  `);return drizzleOrm.sql.raw(`COALESCE(
392
392
  ${e}.agent_id = 'workflow'
393
393
  ${n}
@@ -426,17 +426,17 @@ Message: ${n.message}
426
426
  )
427
427
  )`}findAllThreadsQuery(e,n){let r=[];e&&r.push(drizzleOrm.sql`workspace_id = ${e}`),n&&r.push(drizzleOrm.sql`created_by_kind = ${n}`);let o=r.length>0?drizzleOrm.sql` WHERE ${drizzleOrm.sql.join(r,drizzleOrm.sql` AND `)}`:drizzleOrm.sql``;return drizzleOrm.sql`SELECT * FROM threads${o} ORDER BY updated_at DESC`}findThreadIdsQuery(e){return e?drizzleOrm.sql`SELECT id FROM threads INDEXED BY idx_threads_ws_updated
428
428
  WHERE workspace_id = ${e}
429
- ORDER BY updated_at DESC`:drizzleOrm.sql`SELECT id FROM threads`}readThreadIds(e,n="Failed to find thread ids"){let r=this.resolveDbPaths(),o=new Set,s=[];for(let i of r){if(!nu.existsSync(i))continue;let c=U(i);try{let d=c.db.all(this.findThreadIdsQuery(e));for(let u of d)o.has(u.id)||(o.add(u.id),s.push(u.id));}catch(d){throw new f("DB_ERROR",n,d)}finally{c.close();}}return s}findThreadSortKeysQuery(e){return drizzleOrm.sql`SELECT id, updated_at
429
+ ORDER BY updated_at DESC`:drizzleOrm.sql`SELECT id FROM threads`}readThreadIds(e,n="Failed to find thread ids"){let r=this.resolveDbPaths(),o=new Set,s=[];for(let i of r){if(!Iu.existsSync(i))continue;let c=H(i);try{let d=c.db.all(this.findThreadIdsQuery(e));for(let u of d)o.has(u.id)||(o.add(u.id),s.push(u.id));}catch(d){throw new f("DB_ERROR",n,d)}finally{c.close();}}return s}findThreadSortKeysQuery(e){return drizzleOrm.sql`SELECT id, updated_at
430
430
  FROM threads INDEXED BY idx_threads_ws_updated
431
- WHERE workspace_id = ${e}`}readThreadSortKeys(e){let n=this.resolveDbPaths(),r=new Set,o=[];for(let s of n){if(!nu.existsSync(s))continue;let i=U(s);try{let c=i.db.all(this.findThreadSortKeysQuery(e));for(let d of c)r.has(d.id)||(r.add(d.id),o.push(d));}catch(c){throw new f("DB_ERROR","Failed to find recent direct threads",c)}finally{i.close();}}return o}readThreadRowsByIds(e,n,r="Failed to find threads by ids"){if(e.length===0)return [];let o=this.resolveDbPaths(),s=new Set,i=[];for(let c of o){if(!nu.existsSync(c))continue;let d=U(c);try{for(let u=0;u<e.length;u+=Go){let l=e.slice(u,u+Go),p=drizzleOrm.inArray(y.id,l),_=n?drizzleOrm.and(p,drizzleOrm.eq(y.workspace_id,n)):p,h=d.db.select().from(y).where(_).all();for(let m of h)s.has(m.id)||(s.add(m.id),i.push(m));}}catch(u){throw new f("DB_ERROR",r,u)}finally{d.close();}}return i}readThreadRows(e,n,r="Failed to find all threads"){let o=this.resolveDbPaths(),s=new Set,i=[];for(let c of o){if(!nu.existsSync(c))continue;let d=U(c);try{let u=d.db.all(this.findAllThreadsQuery(e,n));for(let l of u)s.has(l.id)||(s.add(l.id),i.push(l));}catch(u){throw new f("DB_ERROR",r,u)}finally{d.close();}}return i}findAllThreads(e,n){return this.readThreadRows(e,n)}explainFindAllThreadsPlan(e,n){let r=this.resolveDbPaths();for(let o of r){if(!nu.existsSync(o))continue;let s=U(o);try{return s.db.all(drizzleOrm.sql`EXPLAIN QUERY PLAN ${this.findAllThreadsQuery(e,n)}`).map(c=>c.detail)}finally{s.close();}}return []}findThreadsByIdsOrTitles(e,n){if(e.length===0)return [];let r=this.resolveDbPaths(),o=new Set,s=[];for(let i of r){if(!nu.existsSync(i))continue;let c=U(i);try{let d=drizzleOrm.or(drizzleOrm.inArray(y.id,e),drizzleOrm.inArray(y.title,e)),u=n?drizzleOrm.and(d,drizzleOrm.eq(y.workspace_id,n)):d,l=c.db.select().from(y).where(u).orderBy(drizzleOrm.desc(y.updated_at)).all();for(let p of l)o.has(p.id)||(o.add(p.id),s.push(p));}catch(d){throw new f("DB_ERROR","Failed to find threads by ids or titles",d)}finally{c.close();}}return s}findThreadById(e,n){let r=this.resolveDbPaths();for(let o of r){if(!nu.existsSync(o))continue;let s=U(o);try{let i=drizzleOrm.eq(y.id,e),c=n?drizzleOrm.and(i,drizzleOrm.eq(y.workspace_id,n)):i,d=s.db.select().from(y).where(c).limit(1).get()??void 0;if(d)return d}catch(i){throw new f("DB_ERROR","Failed to find thread by id",i)}finally{s.close();}}}createAppLaunchThread(e){let n=this.openHandle(true);try{return n.db.transaction(r=>{if(!r.select({id:de.id}).from(de).where(drizzleOrm.eq(de.id,e.workspaceId)).limit(1).get())throw new f("NOT_FOUND","Workspace not found");let s=r.select().from(y).where(drizzleOrm.eq(y.id,e.threadId)).limit(1).get();if(s){let l=Bn(s.metadata).appLaunch,p=l&&typeof l=="object"&&!Array.isArray(l)?l.appId:void 0,_=r.get(drizzleOrm.sql`
431
+ WHERE workspace_id = ${e}`}readThreadSortKeys(e){let n=this.resolveDbPaths(),r=new Set,o=[];for(let s of n){if(!Iu.existsSync(s))continue;let i=H(s);try{let c=i.db.all(this.findThreadSortKeysQuery(e));for(let d of c)r.has(d.id)||(r.add(d.id),o.push(d));}catch(c){throw new f("DB_ERROR","Failed to find recent direct threads",c)}finally{i.close();}}return o}readThreadRowsByIds(e,n,r="Failed to find threads by ids"){if(e.length===0)return [];let o=this.resolveDbPaths(),s=new Set,i=[];for(let c of o){if(!Iu.existsSync(c))continue;let d=H(c);try{for(let u=0;u<e.length;u+=ns){let l=e.slice(u,u+ns),p=drizzleOrm.inArray(y.id,l),_=n?drizzleOrm.and(p,drizzleOrm.eq(y.workspace_id,n)):p,h=d.db.select().from(y).where(_).all();for(let m of h)s.has(m.id)||(s.add(m.id),i.push(m));}}catch(u){throw new f("DB_ERROR",r,u)}finally{d.close();}}return i}readThreadRows(e,n,r="Failed to find all threads"){let o=this.resolveDbPaths(),s=new Set,i=[];for(let c of o){if(!Iu.existsSync(c))continue;let d=H(c);try{let u=d.db.all(this.findAllThreadsQuery(e,n));for(let l of u)s.has(l.id)||(s.add(l.id),i.push(l));}catch(u){throw new f("DB_ERROR",r,u)}finally{d.close();}}return i}findAllThreads(e,n){return this.readThreadRows(e,n)}explainFindAllThreadsPlan(e,n){let r=this.resolveDbPaths();for(let o of r){if(!Iu.existsSync(o))continue;let s=H(o);try{return s.db.all(drizzleOrm.sql`EXPLAIN QUERY PLAN ${this.findAllThreadsQuery(e,n)}`).map(c=>c.detail)}finally{s.close();}}return []}findThreadsByIdsOrTitles(e,n){if(e.length===0)return [];let r=this.resolveDbPaths(),o=new Set,s=[];for(let i of r){if(!Iu.existsSync(i))continue;let c=H(i);try{let d=drizzleOrm.or(drizzleOrm.inArray(y.id,e),drizzleOrm.inArray(y.title,e)),u=n?drizzleOrm.and(d,drizzleOrm.eq(y.workspace_id,n)):d,l=c.db.select().from(y).where(u).orderBy(drizzleOrm.desc(y.updated_at)).all();for(let p of l)o.has(p.id)||(o.add(p.id),s.push(p));}catch(d){throw new f("DB_ERROR","Failed to find threads by ids or titles",d)}finally{c.close();}}return s}findThreadById(e,n){let r=this.resolveDbPaths();for(let o of r){if(!Iu.existsSync(o))continue;let s=H(o);try{let i=drizzleOrm.eq(y.id,e),c=n?drizzleOrm.and(i,drizzleOrm.eq(y.workspace_id,n)):i,d=s.db.select().from(y).where(c).limit(1).get()??void 0;if(d)return d}catch(i){throw new f("DB_ERROR","Failed to find thread by id",i)}finally{s.close();}}}createAppLaunchThread(e){let n=this.openHandle(true);try{return n.db.transaction(r=>{if(!r.select({id:ue.id}).from(ue).where(drizzleOrm.eq(ue.id,e.workspaceId)).limit(1).get())throw new f("NOT_FOUND","Workspace not found");let s=r.select().from(y).where(drizzleOrm.eq(y.id,e.threadId)).limit(1).get();if(s){let l=nr(s.metadata).appLaunch,p=l&&typeof l=="object"&&!Array.isArray(l)?l.appId:void 0,_=r.get(drizzleOrm.sql`
432
432
  SELECT COUNT(*) AS count FROM tasks WHERE thread_id = ${e.threadId}
433
- `)?.count??0;return s.workspace_id===e.workspaceId&&p===e.appId&&s.message_count===0&&s.first_message===null&&s.last_message===null&&_===0?{status:"existing",thread:s}:{status:"conflict"}}let i=new Date().toISOString(),c=JSON.stringify({appLaunch:{appId:e.appId,...e.initialAgentId===void 0?{}:{initialAgentId:e.initialAgentId}}});r.insert(y).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:c,created_at:i,updated_at:i}).run();let d=r.select().from(y).where(drizzleOrm.eq(y.id,e.threadId)).limit(1).get();if(!d)throw new f("DB_ERROR","App-launch thread could not be read after insert");return {status:"created",thread:d}},{behavior:"immediate"})}catch(r){throw r instanceof f?r:new f("DB_ERROR","Failed to create App-launch thread",r)}finally{n.close();}}threadExists(e,n){let r=this.resolveDbPaths();for(let o of r){if(!nu.existsSync(o))continue;let s=U(o);try{let i=drizzleOrm.eq(y.id,e),c=n?drizzleOrm.and(i,drizzleOrm.eq(y.workspace_id,n)):i;if(s.db.select({id:y.id}).from(y).where(c).limit(1).get())return !0}catch(i){throw new f("DB_ERROR","Failed to check thread existence",i)}finally{s.close();}}return false}aggregateTaskStats(e,n){let r=this.resolveDbPaths(),o=0,s=0,i=0,c=0,d=0,u=0,l=0,p=0,_=0,h=0,m=new Set;for(let k of r){if(!nu.existsSync(k))continue;let E=U(k);try{let b=E.db.get(drizzleOrm.sql`
433
+ `)?.count??0;return s.workspace_id===e.workspaceId&&p===e.appId&&s.message_count===0&&s.first_message===null&&s.last_message===null&&_===0?{status:"existing",thread:s}:{status:"conflict"}}let i=new Date().toISOString(),c=JSON.stringify({appLaunch:{appId:e.appId,...e.initialAgentId===void 0?{}:{initialAgentId:e.initialAgentId}}});r.insert(y).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:c,created_at:i,updated_at:i}).run();let d=r.select().from(y).where(drizzleOrm.eq(y.id,e.threadId)).limit(1).get();if(!d)throw new f("DB_ERROR","App-launch thread could not be read after insert");return {status:"created",thread:d}},{behavior:"immediate"})}catch(r){throw r instanceof f?r:new f("DB_ERROR","Failed to create App-launch thread",r)}finally{n.close();}}threadExists(e,n){let r=this.resolveDbPaths();for(let o of r){if(!Iu.existsSync(o))continue;let s=H(o);try{let i=drizzleOrm.eq(y.id,e),c=n?drizzleOrm.and(i,drizzleOrm.eq(y.workspace_id,n)):i;if(s.db.select({id:y.id}).from(y).where(c).limit(1).get())return !0}catch(i){throw new f("DB_ERROR","Failed to check thread existence",i)}finally{s.close();}}return false}aggregateTaskStats(e,n){let r=this.resolveDbPaths(),o=0,s=0,i=0,c=0,d=0,u=0,l=0,p=0,_=0,h=0,m=new Set;for(let k of r){if(!Iu.existsSync(k))continue;let w=H(k);try{let C=w.db.get(drizzleOrm.sql`
434
434
  SELECT count(*) AS cnt
435
435
  FROM tasks child INDEXED BY idx_tasks_thread_id
436
436
  WHERE child.thread_id = ${e}
437
437
  AND ${this.topLevelTaskPredicateSql()}
438
438
  ${n?drizzleOrm.sql`AND child.workspace_id = ${n}`:drizzleOrm.sql``}
439
- `);b&&(o+=b.cnt);let T=E.db.get(drizzleOrm.sql`
439
+ `);C&&(o+=C.cnt);let T=w.db.get(drizzleOrm.sql`
440
440
  SELECT
441
441
  COALESCE(SUM(child.input_tokens), 0) AS total_input,
442
442
  COALESCE(SUM(child.output_tokens), 0) AS total_output,
@@ -445,7 +445,7 @@ Message: ${n.message}
445
445
  FROM tasks child INDEXED BY idx_tasks_thread_id
446
446
  WHERE child.thread_id = ${e}
447
447
  ${n?drizzleOrm.sql`AND child.workspace_id = ${n}`:drizzleOrm.sql``}
448
- `);T&&(s+=T.total_input,i+=T.total_output,c+=T.total_cached,d+=T.total_cost);let P=E.db.get(drizzleOrm.sql`
448
+ `);T&&(s+=T.total_input,i+=T.total_output,c+=T.total_cached,d+=T.total_cost);let P=w.db.get(drizzleOrm.sql`
449
449
  WITH RECURSIVE
450
450
  own_tasks(task_id) AS (
451
451
  SELECT own.id
@@ -460,7 +460,7 @@ Message: ${n.message}
460
460
  FROM descendants
461
461
  JOIN tasks child INDEXED BY idx_tasks_parent_task_id
462
462
  ON child.parent_task_id = descendants.task_id
463
- WHERE descendants.depth < ${br}
463
+ WHERE descendants.depth < ${jr}
464
464
  ),
465
465
  delegated_ids(task_id) AS (
466
466
  SELECT DISTINCT descendants.task_id
@@ -479,20 +479,20 @@ Message: ${n.message}
479
479
  COALESCE(SUM(task.cost_usd), 0) AS total_cost
480
480
  FROM delegated_ids
481
481
  JOIN tasks task ON task.id = delegated_ids.task_id
482
- `);P&&(u+=P.cnt,l+=P.total_input,p+=P.total_output,_+=P.total_cached,h+=P.total_cost);let A=E.db.all(drizzleOrm.sql`
482
+ `);P&&(u+=P.cnt,l+=P.total_input,p+=P.total_output,_+=P.total_cached,h+=P.total_cost);let A=w.db.all(drizzleOrm.sql`
483
483
  SELECT DISTINCT child.agent_id FROM tasks child INDEXED BY idx_tasks_thread_id
484
484
  WHERE child.thread_id = ${e}
485
485
  AND child.agent_id IS NOT NULL AND child.agent_id != ''
486
486
  AND child.agent_id != 'workflow'
487
487
  AND ${this.topLevelTaskPredicateSql()}
488
488
  ${n?drizzleOrm.sql`AND child.workspace_id = ${n}`:drizzleOrm.sql``}
489
- `);for(let x of A)m.add(x.agent_id);}catch(b){throw new f("DB_ERROR","Failed to aggregate task stats",b)}finally{E.close();}}return {taskCount:o,inputTokens:s,outputTokens:i,cachedInputTokens:c,costUsd:d,agentIds:Array.from(m),delegated:{taskCount:u,inputTokens:l,outputTokens:p,cachedInputTokens:_,costUsd:h}}}getDescendantSummaryByTaskId(e,n){let r=this.resolveDbPaths(),o={},s=new Date().toISOString();for(let i of r){if(!nu.existsSync(i))continue;let c=U(i);try{let d=drizzleOrm.sql`
489
+ `);for(let x of A)m.add(x.agent_id);}catch(C){throw new f("DB_ERROR","Failed to aggregate task stats",C)}finally{w.close();}}return {taskCount:o,inputTokens:s,outputTokens:i,cachedInputTokens:c,costUsd:d,agentIds:Array.from(m),delegated:{taskCount:u,inputTokens:l,outputTokens:p,cachedInputTokens:_,costUsd:h}}}getDescendantSummaryByTaskId(e,n){let r=this.resolveDbPaths(),o={},s=new Date().toISOString();for(let i of r){if(!Iu.existsSync(i))continue;let c=H(i);try{let d=drizzleOrm.sql`
490
490
  SELECT own.id
491
491
  FROM tasks own INDEXED BY idx_tasks_thread_id
492
492
  WHERE own.thread_id = ${e}
493
493
  ${n?drizzleOrm.sql`AND own.workspace_id = ${n}`:drizzleOrm.sql``}
494
494
  `,u=c.db.all(drizzleOrm.sql`
495
- ${this.descendantTraversalSql(d,drizzleOrm.sql`SELECT own.task_id FROM own_tasks own`,br)}
495
+ ${this.descendantTraversalSql(d,drizzleOrm.sql`SELECT own.task_id FROM own_tasks own`,jr)}
496
496
  SELECT
497
497
  descendant_ids.root_task_id AS root_task_id,
498
498
  task.status AS status,
@@ -503,7 +503,7 @@ Message: ${n.message}
503
503
  JOIN tasks task ON task.id = descendant_ids.task_id
504
504
  WHERE NOT ${this.descendantSkippedSql("task")}
505
505
  GROUP BY descendant_ids.root_task_id, task.status, task.error, task.metadata
506
- `);for(let l of u){let p=o[l.root_task_id]??=na(s);ra(p,Ue(l),rt(l),l.task_count);}}catch(d){throw new f("DB_ERROR","Failed to aggregate task descendant summaries",d)}finally{c.close();}}return o}listUnreadReplyCandidates(e,n){let r=new Map,o=new Map;for(let{threadId:i,readThroughAt:c}of e)c!==null&&o.set(i,c);if(o.size===0)return r;let s=new Set;for(let i of this.resolveDbPaths()){if(!nu.existsSync(i))continue;let c=U(i);try{let d=c.db.all(this.unreadReplyCandidatesQuery(o,n));for(let u of d){if(s.has(u.id))continue;s.add(u.id);let l={id:u.id,threadId:u.thread_id,completedAt:u.completed_at,status:Ue(u),result:u.result,error:u.error,metadata:u.metadata},p=r.get(u.thread_id);p?p.push(l):r.set(u.thread_id,[l]);}}catch(d){throw d instanceof f?d:new f("DB_ERROR","Failed to list unread reply candidates",d)}finally{c.close();}}return r}unreadReplyCandidatesQuery(e,n){let r=drizzleOrm.sql.join([...e].map(([s,i])=>drizzleOrm.sql`(${s}, ${i})`),drizzleOrm.sql`, `),o=drizzleOrm.sql.join(ln.map(s=>drizzleOrm.sql`${s}`),drizzleOrm.sql`, `);return drizzleOrm.sql`
506
+ `);for(let l of u){let p=o[l.root_task_id]??=ka(s);ya(p,xe(l),at(l),l.task_count);}}catch(d){throw new f("DB_ERROR","Failed to aggregate task descendant summaries",d)}finally{c.close();}}return o}listUnreadReplyCandidates(e,n){let r=new Map,o=new Map;for(let{threadId:i,readThroughAt:c}of e)c!==null&&o.set(i,c);if(o.size===0)return r;let s=new Set;for(let i of this.resolveDbPaths()){if(!Iu.existsSync(i))continue;let c=H(i);try{let d=c.db.all(this.unreadReplyCandidatesQuery(o,n));for(let u of d){if(s.has(u.id))continue;s.add(u.id);let l={id:u.id,threadId:u.thread_id,completedAt:u.completed_at,status:xe(u),result:u.result,error:u.error,metadata:u.metadata},p=r.get(u.thread_id);p?p.push(l):r.set(u.thread_id,[l]);}}catch(d){throw d instanceof f?d:new f("DB_ERROR","Failed to list unread reply candidates",d)}finally{c.close();}}return r}unreadReplyCandidatesQuery(e,n){let r=drizzleOrm.sql.join([...e].map(([s,i])=>drizzleOrm.sql`(${s}, ${i})`),drizzleOrm.sql`, `),o=drizzleOrm.sql.join(wn.map(s=>drizzleOrm.sql`${s}`),drizzleOrm.sql`, `);return drizzleOrm.sql`
507
507
  WITH watermarks(thread_id, read_through_at) AS (VALUES ${r})
508
508
  SELECT child.id, child.thread_id, child.completed_at, child.status,
509
509
  child.result, child.error, child.metadata
@@ -521,8 +521,8 @@ Message: ${n.message}
521
521
  FROM tasks own INDEXED BY idx_tasks_thread_id
522
522
  WHERE own.thread_id IN (${c})
523
523
  ${n?drizzleOrm.sql`AND own.workspace_id = ${n}`:drizzleOrm.sql``}
524
- `;for(let u of this.resolveDbPaths()){if(!nu.existsSync(u))continue;let l=U(u);try{let p=l.db.all(drizzleOrm.sql`
525
- ${this.descendantTraversalSql(d,drizzleOrm.sql`SELECT own.task_id FROM own_tasks own`,br)}
524
+ `;for(let u of this.resolveDbPaths()){if(!Iu.existsSync(u))continue;let l=H(u);try{let p=l.db.all(drizzleOrm.sql`
525
+ ${this.descendantTraversalSql(d,drizzleOrm.sql`SELECT own.task_id FROM own_tasks own`,jr)}
526
526
  SELECT
527
527
  descendant_ids.root_task_id AS root_task_id,
528
528
  task.status AS status,
@@ -533,7 +533,7 @@ Message: ${n.message}
533
533
  JOIN tasks task ON task.id = descendant_ids.task_id
534
534
  WHERE NOT ${this.descendantSkippedSql("task")}
535
535
  GROUP BY descendant_ids.root_task_id, task.status, task.error, task.metadata
536
- `);for(let _ of p){let h=s[_.root_task_id]??=na(i);ra(h,Ue(_),rt(_),_.task_count);}}catch(p){throw p instanceof f?p:new f("DB_ERROR","Failed to batch summarize thread task statuses",p)}finally{l.close();}}return {tasksByThread:o,descendantSummaryByTaskId:s}}listDescendantsByTaskId(e,n,r={}){let o=new Set(r.states??bm),s=ml(r.limit,gl,gl),i=ml(r.maxDepth,br,br),c=r.cursor?Lm(r.cursor):void 0;for(let d of this.resolveDbPaths()){if(!nu.existsSync(d))continue;let u=U(d);try{if(!u.db.get(drizzleOrm.sql`
536
+ `);for(let _ of p){let h=s[_.root_task_id]??=ka(i);ya(h,xe(_),at(_),_.task_count);}}catch(p){throw p instanceof f?p:new f("DB_ERROR","Failed to batch summarize thread task statuses",p)}finally{l.close();}}return {tasksByThread:o,descendantSummaryByTaskId:s}}listDescendantsByTaskId(e,n,r={}){let o=new Set(r.states??pk),s=ql(r.limit,Hl,Hl),i=ql(r.maxDepth,jr,jr),c=r.cursor?gk(r.cursor):void 0;for(let d of this.resolveDbPaths()){if(!Iu.existsSync(d))continue;let u=H(d);try{if(!u.db.get(drizzleOrm.sql`
537
537
  SELECT anchor.id FROM tasks anchor
538
538
  WHERE anchor.id = ${e} AND anchor.workspace_id = ${n}
539
539
  `))continue;let p=drizzleOrm.sql`
@@ -567,11 +567,11 @@ Message: ${n.message}
567
567
  FROM descendant_ids
568
568
  JOIN tasks task ON task.id = descendant_ids.task_id
569
569
  LEFT JOIN tasks parent ON parent.id = task.parent_task_id
570
- `),h=na(new Date().toISOString()),m=!1,k=[];for(let x of _){if(x.has_deeper&&(m=!0),x.skipped)continue;let S=Ue(x);ra(h,S,rt(x),1),o.has(S)&&k.push({row:x,key:[Dm(S),x.started_at?x.started_at:null,x.task_id]});}k.sort((x,S)=>hl(x.key,S.key));let E=c?k.filter(x=>hl(x.key,c)>0):k,b=E.slice(0,s),T=E.length>b.length?Pm(b[b.length-1].key):null,P=new Map;if(b.length>0){let x=u.db.select(ce).from(a).where(drizzleOrm.inArray(a.id,b.map(S=>S.row.task_id))).all();for(let S of x)P.set(S.id,xr(S));}let A=[];for(let{row:x}of b){let S=P.get(x.task_id);!S||!x.parent_task_id||A.push({task:S,parentTaskId:x.parent_task_id,parentAgentId:x.parent_agent_id,depth:x.depth});}return {rows:A,summary:h,nextCursor:T,traversalTruncated:m}}catch(l){throw l instanceof f?l:new f("DB_ERROR","Failed to list task descendants",l)}finally{u.close();}}}findInterceptedRequests(e){let n=new Map;if(e.length===0)return n;for(let r of this.resolveDbPaths()){if(!nu.existsSync(r))continue;let o=U(r);try{let s=o.db.all(drizzleOrm.sql`
570
+ `),h=ka(new Date().toISOString()),m=!1,k=[];for(let x of _){if(x.has_deeper&&(m=!0),x.skipped)continue;let I=xe(x);ya(h,I,at(x),1),o.has(I)&&k.push({row:x,key:[_k(I),x.started_at?x.started_at:null,x.task_id]});}k.sort((x,I)=>Ul(x.key,I.key));let w=c?k.filter(x=>Ul(x.key,c)>0):k,C=w.slice(0,s),T=w.length>C.length?fk(C[C.length-1].key):null,P=new Map;if(C.length>0){let x=u.db.select(le).from(a).where(drizzleOrm.inArray(a.id,C.map(I=>I.row.task_id))).all();for(let I of x)P.set(I.id,Gr(I));}let A=[];for(let{row:x}of C){let I=P.get(x.task_id);!I||!x.parent_task_id||A.push({task:I,parentTaskId:x.parent_task_id,parentAgentId:x.parent_agent_id,depth:x.depth});}return {rows:A,summary:h,nextCursor:T,traversalTruncated:m}}catch(l){throw l instanceof f?l:new f("DB_ERROR","Failed to list task descendants",l)}finally{u.close();}}}findInterceptedRequests(e){let n=new Map;if(e.length===0)return n;for(let r of this.resolveDbPaths()){if(!Iu.existsSync(r))continue;let o=H(r);try{let s=o.db.all(drizzleOrm.sql`
571
571
  SELECT task_id, input FROM task_provider_inputs
572
572
  WHERE run_epoch = 0
573
573
  AND task_id IN (${drizzleOrm.sql.join(e.map(i=>drizzleOrm.sql`${i}`),drizzleOrm.sql`, `)})
574
- `);for(let i of s)n.set(i.task_id,i.input);}catch{}finally{o.close();}}return n}findTopLevelTasks(e,n,r,o){let s=this.resolveDbPaths(),i=o?drizzleOrm.sql`(${this.topLevelTaskPredicateSql()} OR child.agent_id = ${o})`:this.topLevelTaskPredicateSql(),c=new Set,d=[];for(let u of s){if(!nu.existsSync(u))continue;let l=U(u);try{let p;r!==void 0?p=l.db.all(drizzleOrm.sql`
574
+ `);for(let i of s)n.set(i.task_id,i.input);}catch{}finally{o.close();}}return n}findTopLevelTasks(e,n,r,o){let s=this.resolveDbPaths(),i=o?drizzleOrm.sql`(${this.topLevelTaskPredicateSql()} OR child.agent_id = ${o})`:this.topLevelTaskPredicateSql(),c=new Set,d=[];for(let u of s){if(!Iu.existsSync(u))continue;let l=H(u);try{let p;r!==void 0?p=l.db.all(drizzleOrm.sql`
575
575
  SELECT * FROM (
576
576
  SELECT child.*,
577
577
  ROW_NUMBER() OVER (PARTITION BY child.agent_id ORDER BY child.started_at DESC) AS rn
@@ -588,7 +588,7 @@ Message: ${n.message}
588
588
  AND ${i}
589
589
  ${n?drizzleOrm.sql`AND child.workspace_id = ${n}`:drizzleOrm.sql``}
590
590
  ORDER BY child.started_at ASC
591
- `);for(let _ of p)c.has(_.id)||(c.add(_.id),d.push(xr(_)));}catch(p){throw new f("DB_ERROR","Failed to find top-level tasks",p)}finally{l.close();}}if(r!==void 0&&s.length>1){let u=new Map;for(let l of d){let p=l.agent_id??"";u.has(p)||u.set(p,[]),u.get(p).push(l);}d=[];for(let l of u.values())l.sort((p,_)=>(_.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(),o=new Set,s=[];for(let i of r){if(!nu.existsSync(i))continue;let c=U(i);try{let d=drizzleOrm.eq(a.thread_id,e),u=n?drizzleOrm.and(d,drizzleOrm.eq(a.workspace_id,n)):d,l=c.db.select(ce).from(a).where(u).orderBy(drizzleOrm.asc(a.started_at)).all();for(let p of l)o.has(p.id)||(o.add(p.id),s.push(xr(p)));}catch(d){throw new f("DB_ERROR","Failed to find all tasks for thread",d)}finally{c.close();}}return s}findRespondedAgents(e,n){let r=this.resolveDbPaths(),o=new Map;for(let s of r){if(!nu.existsSync(s))continue;let i=U(s,{readOnly:true});try{let c=[drizzleOrm.eq(a.thread_id,e),drizzleOrm.sql`${a.completed_at} IS NOT NULL`,drizzleOrm.sql`length(trim(coalesce(${a.result}, ''))) > 0`];n&&c.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(...c)).groupBy(a.agent_id).all();for(let u of d){let l=o.get(u.agentId);u.lastRepliedAt&&(!l||u.lastRepliedAt>l)&&o.set(u.agentId,u.lastRepliedAt);}}catch(c){throw new f("DB_ERROR","Failed to find responded agents for thread",c)}finally{i.close();}}return [...o.entries()].map(([s,i])=>({agentId:s,lastRepliedAt:i})).sort((s,i)=>(s.lastRepliedAt===i.lastRepliedAt?0:s.lastRepliedAt>i.lastRepliedAt?-1:1)||(s.agentId===i.agentId?0:s.agentId<i.agentId?-1:1))}findTaskById(e,n,r){let o=this.resolveDbPaths();for(let s of o){if(!nu.existsSync(s))continue;let i=U(s);try{let c=drizzleOrm.and(drizzleOrm.eq(a.id,n),drizzleOrm.eq(a.thread_id,e)),d=r?drizzleOrm.and(c,drizzleOrm.eq(a.workspace_id,r)):c,u=i.db.select(ce).from(a).where(d).limit(1).get();if(!u)continue;let l=i.db.select(ce).from(a).where(drizzleOrm.eq(a.parent_task_id,u.id)).orderBy(drizzleOrm.asc(a.started_at)).all().map(xr);return {task:xr(u),children:l}}catch(c){throw new f("DB_ERROR","Failed to find task by id",c)}finally{i.close();}}}batchFetchTasksQuery(e,n){return drizzleOrm.sql`
591
+ `);for(let _ of p)c.has(_.id)||(c.add(_.id),d.push(Gr(_)));}catch(p){throw new f("DB_ERROR","Failed to find top-level tasks",p)}finally{l.close();}}if(r!==void 0&&s.length>1){let u=new Map;for(let l of d){let p=l.agent_id??"";u.has(p)||u.set(p,[]),u.get(p).push(l);}d=[];for(let l of u.values())l.sort((p,_)=>(_.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(),o=new Set,s=[];for(let i of r){if(!Iu.existsSync(i))continue;let c=H(i);try{let d=drizzleOrm.eq(a.thread_id,e),u=n?drizzleOrm.and(d,drizzleOrm.eq(a.workspace_id,n)):d,l=c.db.select(le).from(a).where(u).orderBy(drizzleOrm.asc(a.started_at)).all();for(let p of l)o.has(p.id)||(o.add(p.id),s.push(Gr(p)));}catch(d){throw new f("DB_ERROR","Failed to find all tasks for thread",d)}finally{c.close();}}return s}findRespondedAgents(e,n){let r=this.resolveDbPaths(),o=new Map;for(let s of r){if(!Iu.existsSync(s))continue;let i=H(s,{readOnly:true});try{let c=[drizzleOrm.eq(a.thread_id,e),drizzleOrm.sql`${a.completed_at} IS NOT NULL`,drizzleOrm.sql`length(trim(coalesce(${a.result}, ''))) > 0`];n&&c.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(...c)).groupBy(a.agent_id).all();for(let u of d){let l=o.get(u.agentId);u.lastRepliedAt&&(!l||u.lastRepliedAt>l)&&o.set(u.agentId,u.lastRepliedAt);}}catch(c){throw new f("DB_ERROR","Failed to find responded agents for thread",c)}finally{i.close();}}return [...o.entries()].map(([s,i])=>({agentId:s,lastRepliedAt:i})).sort((s,i)=>(s.lastRepliedAt===i.lastRepliedAt?0:s.lastRepliedAt>i.lastRepliedAt?-1:1)||(s.agentId===i.agentId?0:s.agentId<i.agentId?-1:1))}findTaskById(e,n,r){let o=this.resolveDbPaths();for(let s of o){if(!Iu.existsSync(s))continue;let i=H(s);try{let c=drizzleOrm.and(drizzleOrm.eq(a.id,n),drizzleOrm.eq(a.thread_id,e)),d=r?drizzleOrm.and(c,drizzleOrm.eq(a.workspace_id,r)):c,u=i.db.select(le).from(a).where(d).limit(1).get();if(!u)continue;let l=i.db.select(le).from(a).where(drizzleOrm.eq(a.parent_task_id,u.id)).orderBy(drizzleOrm.asc(a.started_at)).all().map(Gr);return {task:Gr(u),children:l}}catch(c){throw new f("DB_ERROR","Failed to find task by id",c)}finally{i.close();}}}batchFetchTasksQuery(e,n){return drizzleOrm.sql`
592
592
  SELECT child.id, child.thread_id, child.agent_id, child.status,
593
593
  child.parent_task_id, child.started_at, child.completed_at,
594
594
  child.duration_ms, child.input_tokens, child.output_tokens,
@@ -598,7 +598,7 @@ Message: ${n.message}
598
598
  AND ${this.topLevelTaskPredicateSql()}
599
599
  ${n?drizzleOrm.sql`AND child.workspace_id = ${n}`:drizzleOrm.sql``}
600
600
  ORDER BY child.started_at ASC
601
- `}batchFetchTasks(e,n){let r=new Map;if(e.length===0)return r;let o=this.resolveDbPaths();for(let s of o){if(!nu.existsSync(s))continue;let i=U(s);try{let c=i.db.all(this.batchFetchTasksQuery(e,n));for(let d of c){let u=d.thread_id;r.has(u)||r.set(u,[]),r.get(u).push(xm(d));}}catch(c){throw new f("DB_ERROR","Failed to batch fetch tasks",c)}finally{i.close();}}return r}findThreadOriginsQuery(e,n){return drizzleOrm.sql`
601
+ `}batchFetchTasks(e,n){let r=new Map;if(e.length===0)return r;let o=this.resolveDbPaths();for(let s of o){if(!Iu.existsSync(s))continue;let i=H(s);try{let c=i.db.all(this.batchFetchTasksQuery(e,n));for(let d of c){let u=d.thread_id;r.has(u)||r.set(u,[]),r.get(u).push(lk(d));}}catch(c){throw new f("DB_ERROR","Failed to batch fetch tasks",c)}finally{i.close();}}return r}findThreadOriginsQuery(e,n){return drizzleOrm.sql`
602
602
  WITH root AS (
603
603
  SELECT child.thread_id, child.id, child.caller_agent_id, child.parent_task_id,
604
604
  CASE
@@ -650,7 +650,7 @@ Message: ${n.message}
650
650
  FROM tasks AS child
651
651
  LEFT JOIN tasks AS parent ON parent.id = child.parent_task_id
652
652
  WHERE child.id IN (${drizzleOrm.sql.join(e.map(n=>drizzleOrm.sql`${n}`),drizzleOrm.sql`, `)})
653
- `}findThreadOrigins(e,n){let r=new Map;if(e.length===0)return r;let o=this.resolveDbPaths();for(let s of o){if(!nu.existsSync(s))continue;let i=U(s);try{for(let c=0;c<e.length;c+=Go){let d=e.slice(c,c+Go),l=i.db.all(this.findCreatorPointersQuery(d,n)).filter(T=>!r.has(T.thread_id)),p=l.filter(T=>T.creator_task_id!==null&&T.creator_pointer_unverified===0&&T.creator_actor_kind===null).map(T=>T.creator_task_id),_=p.length>0?i.db.all(this.findTaskOriginLineageQuery(p)):[],h=new Map(_.map(T=>[T.task_id,T])),m=new Map(l.map(T=>[T.thread_id,T])),k=d.filter(T=>{if(r.has(T))return !1;let P=m.get(T);return P?!(P.creator_task_id!==null&&P.creator_pointer_unverified===0)&&P.created_by_kind===null:!0}),E=k.length>0?i.db.all(this.findThreadOriginsQuery(k,n)):[],b=new Map(E.map(T=>[T.thread_id,T]));for(let T of l){if(r.has(T.thread_id))continue;let P=_l(T,T.created_by_task_id!==null?h.get(T.created_by_task_id):void 0,b.get(T.thread_id));P&&r.set(T.thread_id,P);}for(let T of E)r.has(T.thread_id)||m.has(T.thread_id)||r.set(T.thread_id,Bo(T));}}catch(c){throw new f("DB_ERROR","Failed to fetch thread origins",c)}finally{i.close();}}return r}findThreadsByOrigin(e,n){let r=this.readThreadIds(n,"Failed to find threads by origin"),o=this.findThreadOrigins(r,n),s=r.filter(c=>yl(o.get(c),e));return this.readThreadRowsByIds(s,n,"Failed to find threads by origin").sort(Tl)}findRecentDirectThreads(e,n=5){if(typeof e!="string"||e.trim().length===0)throw new f("VALIDATION","workspaceId is required");if(!Number.isInteger(n)||n<=0)throw new f("VALIDATION","limit must be a positive integer");let r=this.readThreadSortKeys(e).sort(Tl),o=[],s=new Map;for(let u=0;u<r.length;u+=kl){let l=r.slice(u,u+kl),p=this.findThreadOrigins(l.map(_=>_.id),e);for(let[_,h]of p)s.set(_,h);for(let _ of l)if(yl(p.get(_.id),"direct")&&(o.push(_.id),o.length===n))break;if(o.length===n)break}let i=new Map;if(o.length>0){let u=this.readThreadRowsByIds(o,e,"Failed to find recent direct threads");for(let l of u)i.set(l.id,l);}let c=[],d=new Map;for(let u of o){let l=i.get(u);if(!l)continue;c.push(l);let p=s.get(u);p&&d.set(u,p);}return {threads:c,originsByThread:d}}explainBatchFetchTasksPlan(e,n){let r=this.resolveDbPaths();for(let o of r){if(!nu.existsSync(o))continue;let s=U(o);try{return s.db.all(drizzleOrm.sql`EXPLAIN QUERY PLAN ${this.batchFetchTasksQuery(e,n)}`).map(c=>c.detail)}finally{s.close();}}return []}explainFindThreadOriginsPlan(e,n){if(e.length===0)return [];let r=this.resolveDbPaths();for(let o of r){if(!nu.existsSync(o))continue;let s=U(o);try{let i=s.db.all(drizzleOrm.sql`EXPLAIN QUERY PLAN ${this.findCreatorPointersQuery(e,n)}`),c=s.db.all(drizzleOrm.sql`EXPLAIN QUERY PLAN ${this.findTaskOriginLineageQuery(e)}`),d=s.db.all(drizzleOrm.sql`EXPLAIN QUERY PLAN ${this.findThreadOriginsQuery(e,n)}`);return [...i,...c,...d].map(u=>u.detail)}finally{s.close();}}return []}explainFindThreadsByOriginPlan(e,n){let r=`__thread_origin_${e}_plan__`,o=this.resolveDbPaths();for(let s of o){if(!nu.existsSync(s))continue;let i=U(s);try{let c=i.db.all(drizzleOrm.sql`EXPLAIN QUERY PLAN ${this.findThreadIdsQuery(n)}`),d=i.db.all(drizzleOrm.sql`EXPLAIN QUERY PLAN ${this.findCreatorPointersQuery([r],n)}`),u=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 [...c,...d,...u,...l].map(p=>p.detail)}finally{i.close();}}return []}updateThreadTitle(e,n,r){if(!this.dbExists())return;let o=this.openHandle(true);try{let s=drizzleOrm.eq(y.id,e),i=r?drizzleOrm.and(s,drizzleOrm.eq(y.workspace_id,r)):s;if(!o.db.select({id:y.id}).from(y).where(i).limit(1).get())return;o.db.update(y).set({title:n,title_locked:1,updated_at:new Date().toISOString()}).where(drizzleOrm.eq(y.id,e)).run();}catch(s){throw s instanceof f?s:new f("DB_ERROR","Failed to update thread title",s)}finally{o.close();}}upsertThread(e,n){let r=this.openHandle(true);try{r.db.transaction(o=>{let i=(n.workspaceId?o.select({id:de.id}).from(de).where(drizzleOrm.eq(de.id,n.workspaceId)).limit(1).get():void 0)?n.workspaceId:null,c=new Date().toISOString(),d=o.select({id:y.id,message_count:y.message_count,created_by_task_id:y.created_by_task_id}).from(y).where(drizzleOrm.eq(y.id,e)).limit(1).get();if(d){let u={updated_at:c};n.title!==void 0&&(u.title=n.title),n.titleLocked!==void 0&&(u.title_locked=n.titleLocked?1:0),d.created_by_task_id===null&&n.createdByTaskId!=null&&d.message_count===0&&!wl(o,e,n.createdByTaskId)&&(u.created_by_task_id=n.createdByTaskId),o.update(y).set(u).where(drizzleOrm.eq(y.id,e)).run();}else o.insert(y).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:c,updated_at:c}).run();},{behavior:"immediate"});}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to upsert thread",o)}finally{r.close();}}ensureThread(e,n,r,o){let s=this.openHandle(true);try{s.db.transaction(i=>{let d=(r?i.select({id:de.id}).from(de).where(drizzleOrm.eq(de.id,r)).limit(1).get():void 0)?r:null,u=i.select({id:y.id,platform:y.platform,workspace_id:y.workspace_id,message_count:y.message_count,created_by_task_id:y.created_by_task_id}).from(y).where(drizzleOrm.eq(y.id,e)).limit(1).get();if(u){let p={};d&&!u.workspace_id&&(p.workspace_id=d),u.created_by_task_id===null&&o?.createdByTaskId!=null&&u.message_count===0&&!wl(i,e,o.createdByTaskId)&&(p.created_by_task_id=o.createdByTaskId),Object.keys(p).length>0&&i.update(y).set(p).where(drizzleOrm.eq(y.id,e)).run();return}let l=new Date().toISOString();i.insert(y).values({id:e,platform:n,workspace_id:d,created_by_kind:null,created_by_id:null,created_by_task_id:o?.createdByTaskId??null,message_count:0,created_at:l,updated_at:l}).run();},{behavior:"immediate"});}catch(i){throw i instanceof f?i:new f("DB_ERROR","Failed to ensure thread",i)}finally{s.close();}}saveUserMessage(e,n,r){if(!this.dbExists())return {firstMessage:false};let o=this.openHandle(true);try{let s=new Date().toISOString();return {firstMessage:o.db.transaction(c=>{let u=c.select({message_count:y.message_count}).from(y).where(drizzleOrm.eq(y.id,e)).limit(1).get()?.message_count===0;return c.run(drizzleOrm.sql`
653
+ `}findThreadOrigins(e,n){let r=new Map;if(e.length===0)return r;let o=this.resolveDbPaths();for(let s of o){if(!Iu.existsSync(s))continue;let i=H(s);try{for(let c=0;c<e.length;c+=ns){let d=e.slice(c,c+ns),l=i.db.all(this.findCreatorPointersQuery(d,n)).filter(T=>!r.has(T.thread_id)),p=l.filter(T=>T.creator_task_id!==null&&T.creator_pointer_unverified===0&&T.creator_actor_kind===null).map(T=>T.creator_task_id),_=p.length>0?i.db.all(this.findTaskOriginLineageQuery(p)):[],h=new Map(_.map(T=>[T.task_id,T])),m=new Map(l.map(T=>[T.thread_id,T])),k=d.filter(T=>{if(r.has(T))return !1;let P=m.get(T);return P?!(P.creator_task_id!==null&&P.creator_pointer_unverified===0)&&P.created_by_kind===null:!0}),w=k.length>0?i.db.all(this.findThreadOriginsQuery(k,n)):[],C=new Map(w.map(T=>[T.thread_id,T]));for(let T of l){if(r.has(T.thread_id))continue;let P=Ml(T,T.created_by_task_id!==null?h.get(T.created_by_task_id):void 0,C.get(T.thread_id));P&&r.set(T.thread_id,P);}for(let T of w)r.has(T.thread_id)||m.has(T.thread_id)||r.set(T.thread_id,es(T));}}catch(c){throw new f("DB_ERROR","Failed to fetch thread origins",c)}finally{i.close();}}return r}findThreadsByOrigin(e,n){let r=this.readThreadIds(n,"Failed to find threads by origin"),o=this.findThreadOrigins(r,n),s=r.filter(c=>Fl(o.get(c),e));return this.readThreadRowsByIds(s,n,"Failed to find threads by origin").sort(Wl)}findRecentDirectThreads(e,n=5){if(typeof e!="string"||e.trim().length===0)throw new f("VALIDATION","workspaceId is required");if(!Number.isInteger(n)||n<=0)throw new f("VALIDATION","limit must be a positive integer");let r=this.readThreadSortKeys(e).sort(Wl),o=[],s=new Map;for(let u=0;u<r.length;u+=Bl){let l=r.slice(u,u+Bl),p=this.findThreadOrigins(l.map(_=>_.id),e);for(let[_,h]of p)s.set(_,h);for(let _ of l)if(Fl(p.get(_.id),"direct")&&(o.push(_.id),o.length===n))break;if(o.length===n)break}let i=new Map;if(o.length>0){let u=this.readThreadRowsByIds(o,e,"Failed to find recent direct threads");for(let l of u)i.set(l.id,l);}let c=[],d=new Map;for(let u of o){let l=i.get(u);if(!l)continue;c.push(l);let p=s.get(u);p&&d.set(u,p);}return {threads:c,originsByThread:d}}explainBatchFetchTasksPlan(e,n){let r=this.resolveDbPaths();for(let o of r){if(!Iu.existsSync(o))continue;let s=H(o);try{return s.db.all(drizzleOrm.sql`EXPLAIN QUERY PLAN ${this.batchFetchTasksQuery(e,n)}`).map(c=>c.detail)}finally{s.close();}}return []}explainFindThreadOriginsPlan(e,n){if(e.length===0)return [];let r=this.resolveDbPaths();for(let o of r){if(!Iu.existsSync(o))continue;let s=H(o);try{let i=s.db.all(drizzleOrm.sql`EXPLAIN QUERY PLAN ${this.findCreatorPointersQuery(e,n)}`),c=s.db.all(drizzleOrm.sql`EXPLAIN QUERY PLAN ${this.findTaskOriginLineageQuery(e)}`),d=s.db.all(drizzleOrm.sql`EXPLAIN QUERY PLAN ${this.findThreadOriginsQuery(e,n)}`);return [...i,...c,...d].map(u=>u.detail)}finally{s.close();}}return []}explainFindThreadsByOriginPlan(e,n){let r=`__thread_origin_${e}_plan__`,o=this.resolveDbPaths();for(let s of o){if(!Iu.existsSync(s))continue;let i=H(s);try{let c=i.db.all(drizzleOrm.sql`EXPLAIN QUERY PLAN ${this.findThreadIdsQuery(n)}`),d=i.db.all(drizzleOrm.sql`EXPLAIN QUERY PLAN ${this.findCreatorPointersQuery([r],n)}`),u=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 [...c,...d,...u,...l].map(p=>p.detail)}finally{i.close();}}return []}updateThreadTitle(e,n,r){if(!this.dbExists())return;let o=this.openHandle(true);try{let s=drizzleOrm.eq(y.id,e),i=r?drizzleOrm.and(s,drizzleOrm.eq(y.workspace_id,r)):s;if(!o.db.select({id:y.id}).from(y).where(i).limit(1).get())return;o.db.update(y).set({title:n,title_locked:1,updated_at:new Date().toISOString()}).where(drizzleOrm.eq(y.id,e)).run();}catch(s){throw s instanceof f?s:new f("DB_ERROR","Failed to update thread title",s)}finally{o.close();}}upsertThread(e,n){let r=this.openHandle(true);try{r.db.transaction(o=>{let i=(n.workspaceId?o.select({id:ue.id}).from(ue).where(drizzleOrm.eq(ue.id,n.workspaceId)).limit(1).get():void 0)?n.workspaceId:null,c=new Date().toISOString(),d=o.select({id:y.id,message_count:y.message_count,created_by_task_id:y.created_by_task_id}).from(y).where(drizzleOrm.eq(y.id,e)).limit(1).get();if(d){let u={updated_at:c};n.title!==void 0&&(u.title=n.title),n.titleLocked!==void 0&&(u.title_locked=n.titleLocked?1:0),d.created_by_task_id===null&&n.createdByTaskId!=null&&d.message_count===0&&!Gl(o,e,n.createdByTaskId)&&(u.created_by_task_id=n.createdByTaskId),o.update(y).set(u).where(drizzleOrm.eq(y.id,e)).run();}else o.insert(y).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:c,updated_at:c}).run();},{behavior:"immediate"});}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to upsert thread",o)}finally{r.close();}}ensureThread(e,n,r,o){let s=this.openHandle(true);try{s.db.transaction(i=>{let d=(r?i.select({id:ue.id}).from(ue).where(drizzleOrm.eq(ue.id,r)).limit(1).get():void 0)?r:null,u=i.select({id:y.id,platform:y.platform,workspace_id:y.workspace_id,message_count:y.message_count,created_by_task_id:y.created_by_task_id}).from(y).where(drizzleOrm.eq(y.id,e)).limit(1).get();if(u){let p={};d&&!u.workspace_id&&(p.workspace_id=d),u.created_by_task_id===null&&o?.createdByTaskId!=null&&u.message_count===0&&!Gl(i,e,o.createdByTaskId)&&(p.created_by_task_id=o.createdByTaskId),Object.keys(p).length>0&&i.update(y).set(p).where(drizzleOrm.eq(y.id,e)).run();return}let l=new Date().toISOString();i.insert(y).values({id:e,platform:n,workspace_id:d,created_by_kind:null,created_by_id:null,created_by_task_id:o?.createdByTaskId??null,message_count:0,created_at:l,updated_at:l}).run();},{behavior:"immediate"});}catch(i){throw i instanceof f?i:new f("DB_ERROR","Failed to ensure thread",i)}finally{s.close();}}saveUserMessage(e,n,r){if(!this.dbExists())return {firstMessage:false};let o=this.openHandle(true);try{let s=new Date().toISOString();return {firstMessage:o.db.transaction(c=>{let u=c.select({message_count:y.message_count}).from(y).where(drizzleOrm.eq(y.id,e)).limit(1).get()?.message_count===0;return c.run(drizzleOrm.sql`
654
654
  UPDATE threads
655
655
  SET first_message = COALESCE(first_message, ${n}),
656
656
  title = CASE WHEN title_locked = 0 AND title IS NULL THEN substr(${n}, 1, 60) ELSE title END,
@@ -658,11 +658,46 @@ Message: ${n.message}
658
658
  message_count = message_count + 1,
659
659
  updated_at = ${s}
660
660
  WHERE id = ${e}
661
- `),u},{behavior:"immediate"})}}catch(s){throw s instanceof f?s:new f("DB_ERROR","Failed to save user message",s)}finally{o.close();}}saveAssistantMessage(e,n,r){if(!this.dbExists())return;let o=this.openHandle(true);try{let s=new Date().toISOString();o.db.update(y).set({last_message:n,updated_at:s}).where(drizzleOrm.eq(y.id,e)).run();}catch(s){throw s instanceof f?s:new f("DB_ERROR","Failed to save assistant message",s)}finally{o.close();}}updateThread(e,n){if(!this.dbExists())return;let r=this.openHandle(true);try{let o={updated_at:new Date().toISOString()};n.title!==void 0&&(o.title=n.title,o.title_locked=1),n.titleLocked!==void 0&&(o.title_locked=n.titleLocked?1:0),r.db.update(y).set(o).where(drizzleOrm.eq(y.id,e)).run();}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to update thread",o)}finally{r.close();}}patchThreadTitleMetadata(e,n,r){let o=n;if(!o||typeof o!="object"||Array.isArray(o))return new Fn("THREAD_TITLE_PATCH_INVALID","Thread-title metadata patch must be an object");if(Object.keys(o).some(d=>d!=="priority"&&d!=="state"))return new Fn("THREAD_TITLE_PATCH_INVALID","Thread-title metadata patch only supports priority and state");let i=o;if(i.priority===void 0&&i.state===void 0)return new Fn("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 Fn("THREAD_TITLE_PATCH_INVALID","Thread-title metadata values must be non-empty strings or null");let c=this.openHandle(true);try{let d=r?drizzleOrm.and(drizzleOrm.eq(y.id,e),drizzleOrm.eq(y.workspace_id,r)):drizzleOrm.eq(y.id,e);return c.db.transaction(u=>{let l=u.select({metadata:y.metadata}).from(y).where(d).get();if(!l)return null;let p=Bn(l.metadata),_=p.threadTitle,h=_&&typeof _=="object"&&!Array.isArray(_)?{..._}:{};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();u.update(y).set({metadata:m,updated_at:k}).where(d).run();let E=u.select({metadata:y.metadata}).from(y).where(d).get();if(!E)throw new f("DB_ERROR","Thread-title metadata update could not be read back");let b=$m(E.metadata);return {threadId:e,priority:b.priority,state:b.state}},{behavior:"immediate"})}catch(d){throw d instanceof f?d:new f("DB_ERROR","Failed to patch thread-title metadata",d)}finally{c.close();}}togglePin(e,n){let r=this.openHandle(true);try{return r.db.transaction(o=>Hm(o,e,n),{behavior:"immediate"})}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to toggle pin",o)}finally{r.close();}}reorderPins(e,n){let r=this.openHandle(true);try{r.db.transaction(o=>Um(o,e,n),{behavior:"immediate"});}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to reorder pins",o)}finally{r.close();}}toggleStar(e,n){let r=this.openHandle(true);try{let o=n?drizzleOrm.and(drizzleOrm.eq(y.id,e),drizzleOrm.eq(y.workspace_id,n)):drizzleOrm.eq(y.id,e),s=r.db.select({starred:y.starred}).from(y).where(o).get();if(!s)return null;let i=s.starred?0:1;return r.db.update(y).set({starred:i}).where(o).run(),{starred:!!i}}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to toggle star",o)}finally{r.close();}}resolveOverdriveForRequest(e,n,r,o){let i=this.openHandle(true);try{let c=n?drizzleOrm.and(drizzleOrm.eq(y.id,e),drizzleOrm.eq(y.workspace_id,n)):drizzleOrm.eq(y.id,e);return i.db.transaction(u=>{let l=u.select({metadata:y.metadata}).from(y).where(c).get();if(!l)return null;let p=l.metadata?JSON.parse(l.metadata):{},_=p.overdrive??{},h=o?.defaultTurns??_.defaultTurns??3,m=o?.updatedBy??"ui",k=new Date().toISOString(),E,b,T,P;switch(r){case "enable-count":{let A=o?.turns??h,x=o?.consumeCurrent?Math.max(A-1,0):A;E=x>0?"count":"off",b=x,T=!0,P="count";break}case "enable-latch":{E="latch",b=0,T=!0,P="latch";break}case "disable":{E="off",b=0,T=!1;break}default:{let A=_.state??"off",x=typeof _.remaining=="number"?_.remaining:0;if(A==="count"&&x>0){let S=x-1;S<=0?(E="off",b=0):(E="count",b=S),T=!0,P="count";}else A==="latch"?(E="latch",b=0,T=!0,P="latch"):(E="off",b=0,T=!1);break}}return p.overdrive={state:E,remaining:b,defaultTurns:h,updatedAt:k,updatedBy:m},u.update(y).set({metadata:JSON.stringify(p),updated_at:k}).where(c).run(),{applied:T,appliedMode:P,state:E,remaining:b}},{behavior:"immediate"})}catch(c){throw c instanceof f?c:new f("DB_ERROR","Failed to resolve overdrive",c)}finally{i.close();}}};g();Ct();Kt();zt();vt();g();var oa="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function qm(t){let e=crypto.randomBytes(t*2),n="";for(let r=0;r<e.length&&n.length<t;r++){let o=e[r];o<248&&(n+=oa[o%62]);}for(;n.length<t;)n+=oa[crypto.randomBytes(1)[0]%62];return n}function Dr(t){return `${t}_${qm(8)}`}function Rl(t,e){let{createHash:n}=fn("crypto"),r=n("sha256").update(e).digest(),o=Buffer.alloc(8);for(let i=0;i<32;i++)o[i%8]^=r[i];let s="";for(let i of o)s+=oa[i%62];return `${t}_${s}`}rn();g();var Fm=["urgent","high","medium","low"],Bm=["investigating","in-progress","in-review","on-hold","done"],Sl="custom:";var Wm=new Set(Fm),Gm=new Set(Bm);function sa(t){return typeof t=="string"&&Wm.has(t)}function ia(t){if(typeof t!="string")return false;if(Gm.has(t))return true;if(t.startsWith("c_"))return t.length>2;if(!t.startsWith(Sl))return false;let e=t.slice(Sl.length);return e.length>=1&&e.length<=20}function Il(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 aa(t){let e=Il(t);if(!e)return {};let n=e.threadTitle;if(!n||typeof n!="object"||Array.isArray(n))return {};let r=n,o={};return sa(r.priority)&&(o.priority=r.priority),ia(r.state)&&(o.state=r.state),o}function Al(t,e){let n=Il(t)??{},r={...aa(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)}yr();var Vm="regeneration_replaced";var Xm="THREAD_HIGHLIGHT_REGENERATION_INTERRUPTED";var Ym="THREAD_HIGHLIGHT_REGENERATION_COMMIT_FAILED",ua=class extends f{threadId;highlightId;expectedRevision;currentRevision;constructor(e,n,r,o){super("CONFLICT",`Highlight revision conflict: expected ${r}, current ${o}`),this.name="ThreadHistoryConflictError",this.threadId=e,this.highlightId=n,this.expectedRevision=r,this.currentRevision=o;}},qr=class extends ua{},la=class extends f{stableCode="THREAD_HIGHLIGHT_REGENERATION_IN_PROGRESS";run;constructor(e){super("CONFLICT","THREAD_HIGHLIGHT_REGENERATION_IN_PROGRESS"),this.name="ThreadHighlightRegenerationConflictError",this.run=e;}},Qm=new Set(fd),Zm=new Set(_d),ek=new Set(gd),tk=new Set(hd),nk=50,Ol=100,vl=280,Cl=40,rk=new Set(md),Ko=["queued","running"];function ca(t){return rk.has(t)}function Y(t){throw new f("VALIDATION",t)}function dt(t){throw new f("NOT_FOUND",t)}function q(t,e){(typeof t!="string"||t.trim().length===0)&&Y(`${e} is required`);}function Lr(t={}){let e=t.actor??t,n=e.actorType??"system";return Qm.has(n)||Y(`invalid actorType: ${String(n)}`),e.actorId!==void 0&&e.actorId!==null&&typeof e.actorId!="string"&&Y("actorId must be a string or null"),{actorType:n,actorId:e.actorId??null}}function ok(t){q(t.threadId,"threadId"),t.workspaceId!==void 0&&t.workspaceId!==null&&q(t.workspaceId,"workspaceId"),t.title!==void 0&&t.title!==null&&((typeof t.title!="string"||t.title.trim().length===0)&&Y("title must not be empty"),t.title.length>120&&Y("title must be at most 120 characters")),t.priority!==void 0&&t.priority!==null&&!sa(t.priority)&&Y(`invalid priority: ${String(t.priority)}`),t.state!==void 0&&t.state!==null&&!ia(t.state)&&Y(`invalid state: ${String(t.state)}`);}function sk(t){t.beforeSeq!==void 0&&t.afterSeq!==void 0&&Y("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)&&Y(`${n} must be a non-negative integer`);let e=t.limit??nk;return (!Number.isInteger(e)||e<1||e>Ol)&&Y(`limit must be between 1 and ${Ol}`),e}function pa(t){typeof t!="string"&&Y("text is required");let e=t.trim();return e.length===0&&Y("text must not be empty"),e.length>vl&&Y(`text must be at most ${vl} characters`),e}function Nt(t,e){return q(t??"",e),t}function _a(t){tk.has(t)||Y(`invalid highlight kind: ${String(t)}`);}function ik(t){ek.has(t)||Y(`invalid highlight source: ${String(t)}`);}function ak(t){q(t.threadId,"threadId"),q(t.workspaceId,"workspaceId");let e=t.source??"manual";ik(e),_a(t.kind);let n=pa(t.text),r=t.coversFromTaskId??t.fromTaskId??t.taskId,o=t.coversToTaskId??t.toTaskId??t.taskId;if(e==="manual"){let l=t.taskId??(r&&o&&r===o?r:void 0),p=Nt(l,"taskId");return (r!==p||o!==p)&&Y("manual highlights must cover exactly one task"),{source:e,kind:t.kind,text:n,coversFromTaskId:p,coversToTaskId:p,agentId:t.agentId??null,sourceTaskId:null,detectorVersion:null,contentFingerprint:null}}let s=Nt(r,"coversFromTaskId"),i=Nt(o,"coversToTaskId"),c=t.sourceTaskId??s,d=t.detectorVersion??(t.idempotencyKey!==void 0?"default":null),u=t.contentFingerprint??t.idempotencyKey??null;return Nt(c??void 0,"sourceTaskId"),Nt(d??void 0,"detectorVersion"),Nt(u??void 0,"contentFingerprint"),{source:e,kind:t.kind,text:n,coversFromTaskId:s,coversToTaskId:i,agentId:t.agentId??null,sourceTaskId:c,detectorVersion:d,contentFingerprint:u}}function dk(t,e){(!t||typeof t!="object")&&Y(`candidates[${e}] is required`),_a(t.kind);let n=pa(t.text),r=Nt(t.anchorTaskId,`candidates[${e}].anchorTaskId`),o=Nt(t.coversFromTaskId,`candidates[${e}].coversFromTaskId`),s=Nt(t.coversToTaskId,`candidates[${e}].coversToTaskId`),i=t.contentFingerprint?.trim()||Rl("thl",JSON.stringify({kind:t.kind,text:n,anchorTaskId:r,coversFromTaskId:o,coversToTaskId:s}));return q(i,`candidates[${e}].contentFingerprint`),{kind:t.kind,text:n,anchorTaskId:r,coversFromTaskId:o,coversToTaskId:s,contentFingerprint:i}}function ck(t){Array.isArray(t)||Y("candidates must be an array"),t.length>Cl&&Y(`candidates must contain at most ${Cl} items`);let e=new Map;for(let[n,r]of t.entries()){let o=dk(r,n);e.set(o.contentFingerprint,o);}return [...e.values()]}function Ur(t){let e=aa(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 uk(t){try{let e=JSON.stringify(t);return (!e||e==="null"||e.startsWith("["))&&Y("event payload must be a JSON object"),e}catch(e){throw new f("VALIDATION","event payload must be JSON serializable",e)}}function Mr(t,e){return t.select({maxSeq:drizzleOrm.sql`COALESCE(MAX(${V.seq}), 0)`}).from(V).where(drizzleOrm.eq(V.thread_id,e)).get()?.maxSeq??0}function $r(t,e){return !!t.select({id:V.id}).from(V).where(drizzleOrm.eq(V.thread_id,e)).limit(1).get()}function _n(t,e){Zm.has(e.type)||Y(`invalid thread event type: ${String(e.type)}`);let n=Dr("the");t.insert(V).values({id:n,thread_id:e.threadId,seq:e.seq,type:e.type,actor_type:e.actorType,actor_id:e.actorId,task_id:e.taskId??null,highlight_id:e.highlightId??null,payload_json:uk(e.payload),created_at:e.createdAt}).run();let r=t.select().from(V).where(drizzleOrm.eq(V.id,n)).get();if(!r)throw new f("DB_ERROR","Thread event insert did not return a row");return r}function Hr(t,e,n,r,o){let s=Ur(e);_n(t,{threadId:e.id,seq:o,type:"thread.snapshot.imported",actorType:n.actorType,actorId:n.actorId,createdAt:r,payload:{title:s.title,priority:s.priority,state:s.state}});}function Jo(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 zo(t,e,n,r,o,s,i){let c=o==="thread.highlight.created"?Jo(e):{before:i?Jo({...e,...i,id:e.id}):void 0,after:Jo(e)};return _n(t,{threadId:e.thread_id,seq:s,type:o,actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.source==="manual"?e.covers_from_task_id:e.source_task_id??e.covers_from_task_id,highlightId:e.id,payload:c})}function lk(t,e,n,r,o,s){return _n(t,{threadId:e.thread_id,seq:o,type:"thread.highlight.deleted",actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.source_task_id??e.covers_from_task_id,highlightId:e.id,payload:{before:Jo(e),...s??{}}})}var Vo=class extends ve{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=Re.join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath??super.resolveDbPath()}openHandle(e){let n=this.resolveDbPath();if(!e&&!nu.existsSync(n))throw new f("NOT_FOUND","Database not found");if(e){let o=Re.dirname(n);nu.existsSync(o)||nu.mkdirSync(o,{recursive:true});}let r=U(n);if(e)try{Be(r.db,n);}catch(o){throw r.close(),o}return r}findThread(e,n,r){let o=drizzleOrm.eq(y.id,n),s=r===void 0?o:r===null?drizzleOrm.and(o,drizzleOrm.isNull(y.workspace_id)):drizzleOrm.and(o,drizzleOrm.eq(y.workspace_id,r));return e.select().from(y).where(s).limit(1).get()}findRegenerationRun(e,n,r){let o=e.select().from(j).where(drizzleOrm.eq(j.id,n)).limit(1).get();if(o&&!(r!==void 0&&!this.findThread(e,o.thread_id,r)))return o}resolveWorkspaceId(e){if(q(e,"threadId"),!nu.existsSync(this.resolveDbPath()))return null;let n=this.openHandle(false);try{return n.db.select({workspaceId:y.workspace_id}).from(y).where(drizzleOrm.eq(y.id,e)).limit(1).get()?.workspaceId??null}catch(r){throw r instanceof f?r:new f("DB_ERROR","Failed to resolve thread workspace",r)}finally{n.close();}}getSnapshot(e,n){if(q(e,"threadId"),!nu.existsSync(this.resolveDbPath()))return null;let r=this.openHandle(false);try{let o=this.findThread(r.db,e,n);return o?Ur(o):null}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to read thread snapshot",o)}finally{r.close();}}updateSnapshot(e){ok(e);let n=Lr(e),r=new Date().toISOString(),o=this.openHandle(true);try{return o.db.transaction(s=>{let i=this.findThread(s,e.threadId,e.workspaceId);i||dt(`Thread ${e.threadId} not found`);let c=Ur(i),d=e.title!==void 0,u=d&&e.title!==c.title,l=d&&i.title_locked!==1,p=e.priority!==void 0&&e.priority!==c.priority,_=e.state!==void 0&&e.state!==c.state,h=u||p||_;if(!h&&!l)return c;let m=i.metadata;(p||_)&&(m=Al(i.metadata,{priority:e.priority,state:e.state}));let k={};if(h&&(k.metadata=m,k.updated_at=r),u&&(k.title=e.title),d&&(k.title_locked=1),s.update(y).set(k).where(e.workspaceId===void 0?drizzleOrm.eq(y.id,e.threadId):e.workspaceId===null?drizzleOrm.and(drizzleOrm.eq(y.id,e.threadId),drizzleOrm.isNull(y.workspace_id)):drizzleOrm.and(drizzleOrm.eq(y.id,e.threadId),drizzleOrm.eq(y.workspace_id,e.workspaceId))).run(),!h){let T={...i,title_locked:1};return Ur(T)}let E=Mr(s,i.id)+1;$r(s,i.id)||(Hr(s,i,n,r,E),E+=1),u&&(_n(s,{threadId:i.id,seq:E,type:"thread.title.changed",actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.taskId,payload:{before:c.title,after:e.title}}),E+=1),p&&(_n(s,{threadId:i.id,seq:E,type:"thread.priority.changed",actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.taskId,payload:{before:c.priority,after:e.priority}}),E+=1),_&&_n(s,{threadId:i.id,seq:E,type:"thread.state.changed",actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.taskId,payload:{before:c.state,after:e.state}});let b={...i,title:u?e.title:i.title,metadata:m,title_locked:d?1:i.title_locked,updated_at:r};return Ur(b)},{behavior:"immediate"})}catch(s){throw s instanceof f?s:new f("DB_ERROR","Failed to update thread snapshot",s)}finally{o.close();}}mutateSnapshot(e){return this.updateSnapshot(e)}updateThreadSnapshot(e){return this.updateSnapshot(e)}getLatestSeq(e,n){if(q(e,"threadId"),!nu.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(${V.seq}), 0)`}).from(V).where(drizzleOrm.eq(V.thread_id,e)).get()?.maxSeq??0:null}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to read latest thread event sequence",o)}finally{r.close();}}listCompletedThreadHighlightTurns(e,n){if(q(e,"threadId"),q(n,"workspaceId"),!nu.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,[...ln]),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(o){throw o instanceof f?o:new f("DB_ERROR","Failed to read completed thread highlight turns",o)}finally{r.close();}}createHighlightRegenerationRun(e){q(e.threadId,"threadId"),q(e.workspaceId,"workspaceId"),q(e.requestId,"requestId"),q(e.detectorVersion,"detectorVersion"),e.runId!==void 0&&q(e.runId,"runId");let n=new Date().toISOString(),r=this.openHandle(true);try{return r.db.transaction(o=>{let s=this.findThread(o,e.threadId,e.workspaceId);s||dt(`Thread ${e.threadId} not found`);let i=o.select().from(j).where(drizzleOrm.and(drizzleOrm.eq(j.thread_id,s.id),drizzleOrm.eq(j.request_id,e.requestId))).orderBy(drizzleOrm.desc(j.requested_at),drizzleOrm.desc(j.id)).limit(1).get();if(i)return {run:i,created:!1};let c=o.select().from(j).where(drizzleOrm.and(drizzleOrm.eq(j.thread_id,s.id),drizzleOrm.inArray(j.status,Ko))).orderBy(drizzleOrm.asc(j.requested_at),drizzleOrm.asc(j.id)).limit(1).get();if(c)throw new la(c);let d=e.runId??Dr("thr");o.insert(j).values({id:d,thread_id:s.id,request_id:e.requestId,status:"queued",detector_version:e.detectorVersion,requested_at:n,started_at:null,completed_at:null,error_code:null,previous_auto_count:null,new_auto_count:null}).run();let u=o.select().from(j).where(drizzleOrm.eq(j.id,d)).get();if(!u)throw new f("DB_ERROR","Highlight regeneration run insert did not return a row");return {run:u,created:!0}},{behavior:"immediate"})}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to create highlight regeneration run",o)}finally{r.close();}}beginHighlightRegenerationRun(e){return this.createHighlightRegenerationRun(e)}queueHighlightRegenerationRun(e){return this.createHighlightRegenerationRun(e)}getHighlightRegenerationRun(e,n){if(q(e,"runId"),n!==void 0&&q(n,"workspaceId"),!nu.existsSync(this.resolveDbPath()))return null;let r=this.openHandle(false);try{return this.findRegenerationRun(r.db,e,n)??null}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to read highlight regeneration run",o)}finally{r.close();}}getHighlightRegenerationRunByRequest(e,n,r){if(q(e,"threadId"),q(n,"workspaceId"),q(r,"requestId"),!nu.existsSync(this.resolveDbPath()))return null;let o=this.openHandle(false);try{return this.findThread(o.db,e,n)?o.db.select().from(j).where(drizzleOrm.and(drizzleOrm.eq(j.thread_id,e),drizzleOrm.eq(j.request_id,r))).orderBy(drizzleOrm.desc(j.requested_at),drizzleOrm.desc(j.id)).limit(1).get()??null:null}catch(s){throw s instanceof f?s:new f("DB_ERROR","Failed to read highlight regeneration request",s)}finally{o.close();}}findHighlightRegenerationRun(e,n,r){return this.getHighlightRegenerationRunByRequest(e,n,r)}startHighlightRegenerationRun(e,n){q(e,"runId"),n!==void 0&&q(n,"workspaceId");let r=new Date().toISOString(),o=this.openHandle(true);try{return o.db.transaction(s=>{let i=this.findRegenerationRun(s,e,n);if(i||dt(`Highlight regeneration run ${e} not found`),ca(i.status)||Y(`invalid highlight regeneration status: ${i.status}`),i.status!=="queued")return i;s.update(j).set({status:"running",started_at:r}).where(drizzleOrm.and(drizzleOrm.eq(j.id,i.id),drizzleOrm.eq(j.status,"queued"))).run();let c=s.select().from(j).where(drizzleOrm.eq(j.id,i.id)).get();if(!c)throw new f("DB_ERROR","Highlight regeneration run start did not return a row");return c},{behavior:"immediate"})}catch(s){throw s instanceof f?s:new f("DB_ERROR","Failed to start highlight regeneration run",s)}finally{o.close();}}startHighlightRegeneration(e,n){return this.startHighlightRegenerationRun(e,n)}failHighlightRegenerationRun(e){q(e.runId,"runId"),q(e.errorCode,"errorCode"),e.workspaceId!==void 0&&q(e.workspaceId,"workspaceId");let n=new Date().toISOString(),r=this.openHandle(true);try{return r.db.transaction(o=>{let s=this.findRegenerationRun(o,e.runId,e.workspaceId);if(s||dt(`Highlight regeneration run ${e.runId} not found`),ca(s.status)||Y(`invalid highlight regeneration status: ${s.status}`),s.status==="completed"||s.status==="failed")return s;o.update(j).set({status:"failed",completed_at:n,error_code:e.errorCode}).where(drizzleOrm.and(drizzleOrm.eq(j.id,s.id),drizzleOrm.inArray(j.status,Ko))).run();let i=o.select().from(j).where(drizzleOrm.eq(j.id,s.id)).get();if(!i)throw new f("DB_ERROR","Highlight regeneration run failure did not return a row");return i},{behavior:"immediate"})}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to fail highlight regeneration run",o)}finally{r.close();}}failHighlightRegeneration(e){return this.failHighlightRegenerationRun(e)}recoverInterruptedHighlightRegenerationRuns(e=Xm){q(e,"errorCode");let n=new Date().toISOString(),r=this.openHandle(true);try{return r.db.transaction(o=>o.update(j).set({status:"failed",completed_at:n,error_code:e}).where(drizzleOrm.inArray(j.status,Ko)).run().changes,{behavior:"immediate"})}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to recover interrupted highlight runs",o)}finally{r.close();}}completeHighlightRegenerationRun(e){q(e.runId,"runId"),q(e.threadId,"threadId"),q(e.workspaceId,"workspaceId"),q(e.detectorVersion,"detectorVersion");let n=ck(e.candidates),r=Lr(e),o=this.openHandle(true),s=false;try{return o.db.transaction(i=>{let c=this.findRegenerationRun(i,e.runId,e.workspaceId);if((!c||c.thread_id!==e.threadId)&&dt(`Highlight regeneration run ${e.runId} not found`),ca(c.status)||Y(`invalid highlight regeneration status: ${c.status}`),c.status==="failed")throw new f("CONFLICT","Highlight regeneration run has already failed");if(c.status==="completed")return {run:c,deletedCount:0,createdCount:0,previousAutoCount:c.previous_auto_count??0,newAutoCount:c.new_auto_count??0};s=!0;let d=this.findThread(i,e.threadId,e.workspaceId);d||dt(`Thread ${e.threadId} not found`),c.detector_version!==e.detectorVersion&&Y("detectorVersion does not match the regeneration run");let u=i.select().from(F).where(drizzleOrm.eq(F.thread_id,d.id)).orderBy(drizzleOrm.asc(F.created_at),drizzleOrm.asc(F.id)).all(),l=new Set(n.map(S=>S.contentFingerprint)),p=u.filter(S=>S.source==="auto"&&S.status==="active"&&S.revision===0&&!l.has(S.content_fingerprint??"")),_=u.filter(S=>S.source==="auto"&&S.status==="active").length,h=new Set(u.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=Mr(i,d.id)+1;$r(i,d.id)||(Hr(i,d,r,k,E),E+=1);for(let S of p)i.delete(F).where(drizzleOrm.eq(F.id,S.id)).run(),lk(i,S,r,k,E,{runId:e.runId,reason:Vm}),E+=1;let b=0,T=e.agentId??(r.actorType==="agent"?r.actorId:null);for(let S of m){let K=Dr("thl");i.insert(F).values({id:K,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:T,source_task_id:S.anchorTaskId,detector_version:e.detectorVersion,content_fingerprint:S.contentFingerprint,dismissed_at:null}).run();let te=i.select().from(F).where(drizzleOrm.eq(F.id,K)).get();if(!te)throw new f("DB_ERROR","Regenerated highlight insert did not return a row");zo(i,te,r,k,"thread.highlight.created",E),E+=1,b+=1;}let A=i.select().from(F).where(drizzleOrm.eq(F.thread_id,d.id)).all().filter(S=>S.source==="auto"&&S.status==="active").length;_n(i,{threadId:d.id,seq:E,type:"thread.highlights.regenerated",actorType:r.actorType,actorId:r.actorId,createdAt:k,payload:{runId:c.id,detectorVersion:e.detectorVersion,previousAutoCount:_,newAutoCount:A,deletedCount:p.length,createdCount:b}}),i.update(j).set({status:"completed",started_at:c.started_at??k,completed_at:k,error_code:null,previous_auto_count:_,new_auto_count:A}).where(drizzleOrm.and(drizzleOrm.eq(j.id,c.id),drizzleOrm.inArray(j.status,Ko))).run();let x=i.select().from(j).where(drizzleOrm.eq(j.id,c.id)).get();if(!x)throw new f("DB_ERROR","Highlight regeneration completion did not return a row");return {run:x,deletedCount:p.length,createdCount:b,previousAutoCount:_,newAutoCount:A}},{behavior:"immediate"})}catch(i){if(s)try{this.failHighlightRegenerationRun({runId:e.runId,workspaceId:e.workspaceId,errorCode:Ym});}catch{}throw i instanceof f?i:new f("DB_ERROR","Failed to complete highlight regeneration",i)}finally{o.close();}}completeHighlightRegeneration(e){return this.completeHighlightRegenerationRun(e)}replaceAutoHighlightsAtomically(e){return this.completeHighlightRegenerationRun(e)}listTimeline(e,n,r={}){let o=typeof e=="string"?{...r,threadId:e,workspaceId:n}:e;q(o.threadId,"threadId"),q(o.workspaceId,"workspaceId");let s=sk(o);if(!nu.existsSync(this.resolveDbPath()))return null;let i=this.openHandle(false);try{if(!this.findThread(i.db,o.threadId,o.workspaceId))return null;let c=i.db.select({maxSeq:drizzleOrm.sql`COALESCE(MAX(${V.seq}), 0)`}).from(V).where(drizzleOrm.eq(V.thread_id,o.threadId)).get()?.maxSeq??0,d;o.beforeSeq!==void 0?d=i.db.select().from(V).where(drizzleOrm.and(drizzleOrm.eq(V.thread_id,o.threadId),drizzleOrm.lt(V.seq,o.beforeSeq))).orderBy(drizzleOrm.desc(V.seq)).limit(s+1).all().reverse():o.afterSeq!==void 0?d=i.db.select().from(V).where(drizzleOrm.and(drizzleOrm.eq(V.thread_id,o.threadId),drizzleOrm.sql`${V.seq} > ${o.afterSeq}`)).orderBy(drizzleOrm.asc(V.seq)).limit(s+1).all():d=i.db.select().from(V).where(drizzleOrm.eq(V.thread_id,o.threadId)).orderBy(drizzleOrm.desc(V.seq)).limit(s+1).all().reverse();let u=d.length>s,l=o.afterSeq!==void 0?d.slice(0,s):u?d.slice(1):d,p=!1,_=l[0];return _&&(p=!!i.db.select({id:V.id}).from(V).where(drizzleOrm.and(drizzleOrm.eq(V.thread_id,o.threadId),drizzleOrm.lt(V.seq,_.seq))).limit(1).get()),{items:l,latestSeq:c,hasMoreOlder:p}}catch(c){throw c instanceof f?c:new f("DB_ERROR","Failed to list thread timeline",c)}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=ak(e),r=Lr(e),o=new Date().toISOString(),s=this.openHandle(true);try{return s.db.transaction(i=>{let c=this.findThread(i,e.threadId,e.workspaceId);if(c||dt(`Thread ${e.threadId} not found`),n.source==="auto"){let _=i.select().from(F).where(drizzleOrm.and(drizzleOrm.eq(F.thread_id,e.threadId),drizzleOrm.eq(F.source_task_id,n.sourceTaskId),drizzleOrm.eq(F.detector_version,n.detectorVersion),drizzleOrm.eq(F.content_fingerprint,n.contentFingerprint))).orderBy(drizzleOrm.asc(F.created_at),drizzleOrm.asc(F.id)).limit(1).get();if(_)return _}let d=e.id??Dr("thl"),u={id:d,thread_id:e.threadId,source:n.source,kind:n.kind,status:"active",text:n.text,covers_from_task_id:n.coversFromTaskId,covers_to_task_id:n.coversToTaskId,revision:0,created_at:o,updated_at:o,agent_id:n.agentId,source_task_id:n.sourceTaskId,detector_version:n.detectorVersion,content_fingerprint:n.contentFingerprint,dismissed_at:null};i.insert(F).values(u).run();let l=i.select().from(F).where(drizzleOrm.eq(F.id,d)).get();if(!l)throw new f("DB_ERROR","Highlight insert did not return a row");let p=Mr(i,c.id)+1;return $r(i,c.id)||(Hr(i,c,r,o,p),p+=1),zo(i,l,r,o,"thread.highlight.created",p),l},{behavior:"immediate"})}catch(i){throw i instanceof f?i:new f("DB_ERROR","Failed to create thread highlight",i)}finally{s.close();}}updateHighlight(e){q(e.threadId,"threadId"),q(e.workspaceId,"workspaceId"),q(e.highlightId,"highlightId"),(!Number.isInteger(e.expectedRevision)||e.expectedRevision<0)&&Y("expectedRevision must be a non-negative integer"),e.text===void 0&&e.kind===void 0&&e.coversFromTaskId===void 0&&e.coversToTaskId===void 0&&Y("highlight update requires at least one field"),e.kind!==void 0&&_a(e.kind);let n=e.text===void 0?void 0:pa(e.text),r=Lr(e),o=new Date().toISOString(),s=this.openHandle(true);try{return s.db.transaction(i=>{let c=this.findThread(i,e.threadId,e.workspaceId);c||dt(`Thread ${e.threadId} not found`);let d=i.select().from(F).where(drizzleOrm.and(drizzleOrm.eq(F.id,e.highlightId),drizzleOrm.eq(F.thread_id,c.id))).limit(1).get();if(d||dt(`Highlight ${e.highlightId} not found`),d.revision!==e.expectedRevision)throw new qr(c.id,d.id,e.expectedRevision,d.revision);if(d.status!=="active")throw new qr(c.id,d.id,e.expectedRevision,d.revision);let u=e.kind??d.kind,l=n??d.text,p=e.coversFromTaskId??d.covers_from_task_id,_=e.coversToTaskId??d.covers_to_task_id;(!l||p.length===0||_.length===0)&&Y("highlight projection is incomplete");let h=u!==d.kind||l!==d.text||p!==d.covers_from_task_id||_!==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(F).set({source:m,kind:u,text:l,covers_from_task_id:p,covers_to_task_id:_,revision:E,updated_at:o}).where(drizzleOrm.and(drizzleOrm.eq(F.id,d.id),drizzleOrm.eq(F.revision,d.revision))).run();let b=i.select().from(F).where(drizzleOrm.eq(F.id,d.id)).get();if(!b)throw new f("DB_ERROR","Highlight update did not return a row");let T=Mr(i,c.id)+1;return $r(i,c.id)||(Hr(i,c,r,o,T),T+=1),zo(i,b,r,o,"thread.highlight.updated",T,d),b},{behavior:"immediate"})}catch(i){throw i instanceof f?i:new f("DB_ERROR","Failed to update thread highlight",i)}finally{s.close();}}dismissHighlight(e){q(e.threadId,"threadId"),q(e.workspaceId,"workspaceId"),q(e.highlightId,"highlightId"),(!Number.isInteger(e.expectedRevision)||e.expectedRevision<0)&&Y("expectedRevision must be a non-negative integer");let n=Lr(e),r=new Date().toISOString(),o=this.openHandle(true);try{return o.db.transaction(s=>{let i=this.findThread(s,e.threadId,e.workspaceId);i||dt(`Thread ${e.threadId} not found`);let c=s.select().from(F).where(drizzleOrm.and(drizzleOrm.eq(F.id,e.highlightId),drizzleOrm.eq(F.thread_id,i.id))).limit(1).get();if(c||dt(`Highlight ${e.highlightId} not found`),c.revision!==e.expectedRevision)throw new qr(i.id,c.id,e.expectedRevision,c.revision);if(c.status==="dismissed")return c;let d=c.revision+1;s.update(F).set({status:"dismissed",text:null,revision:d,updated_at:r,dismissed_at:r}).where(drizzleOrm.and(drizzleOrm.eq(F.id,c.id),drizzleOrm.eq(F.revision,c.revision))).run();let u=s.select().from(F).where(drizzleOrm.eq(F.id,c.id)).get();if(!u)throw new f("DB_ERROR","Highlight dismissal did not return a row");let l=Mr(s,i.id)+1;return $r(s,i.id)||(Hr(s,i,n,r,l),l+=1),zo(s,u,n,r,"thread.highlight.deleted",l,c),u},{behavior:"immediate"})}catch(s){throw s instanceof f?s:new f("DB_ERROR","Failed to dismiss thread highlight",s)}finally{o.close();}}listActiveHighlights(e,n,r={}){if(q(e,"threadId"),q(n,"workspaceId"),r.taskId!==void 0&&q(r.taskId,"taskId"),r.coversFromTaskId!==void 0&&q(r.coversFromTaskId,"coversFromTaskId"),r.coversToTaskId!==void 0&&q(r.coversToTaskId,"coversToTaskId"),!nu.existsSync(this.resolveDbPath()))return null;let o=this.openHandle(false);try{if(!this.findThread(o.db,e,n))return null;let i=o.db.select().from(F).where(drizzleOrm.and(drizzleOrm.eq(F.thread_id,e),drizzleOrm.eq(F.status,"active"))).orderBy(drizzleOrm.asc(F.created_at),drizzleOrm.asc(F.id)).all();if(r.taskId===void 0&&r.coversFromTaskId===void 0&&r.coversToTaskId===void 0)return i;let c=o.db.all(drizzleOrm.sql`
661
+ `),u},{behavior:"immediate"})}}catch(s){throw s instanceof f?s:new f("DB_ERROR","Failed to save user message",s)}finally{o.close();}}saveAssistantMessage(e,n,r){if(!this.dbExists())return;let o=this.openHandle(true);try{let s=new Date().toISOString();o.db.update(y).set({last_message:n,updated_at:s}).where(drizzleOrm.eq(y.id,e)).run();}catch(s){throw s instanceof f?s:new f("DB_ERROR","Failed to save assistant message",s)}finally{o.close();}}updateThread(e,n){if(!this.dbExists())return;let r=this.openHandle(true);try{let o={updated_at:new Date().toISOString()};n.title!==void 0&&(o.title=n.title,o.title_locked=1),n.titleLocked!==void 0&&(o.title_locked=n.titleLocked?1:0),r.db.update(y).set(o).where(drizzleOrm.eq(y.id,e)).run();}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to update thread",o)}finally{r.close();}}patchThreadTitleMetadata(e,n,r){let o=n;if(!o||typeof o!="object"||Array.isArray(o))return new tr("THREAD_TITLE_PATCH_INVALID","Thread-title metadata patch must be an object");if(Object.keys(o).some(d=>d!=="priority"&&d!=="state"))return new tr("THREAD_TITLE_PATCH_INVALID","Thread-title metadata patch only supports priority and state");let i=o;if(i.priority===void 0&&i.state===void 0)return new tr("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 tr("THREAD_TITLE_PATCH_INVALID","Thread-title metadata values must be non-empty strings or null");let c=this.openHandle(true);try{let d=r?drizzleOrm.and(drizzleOrm.eq(y.id,e),drizzleOrm.eq(y.workspace_id,r)):drizzleOrm.eq(y.id,e);return c.db.transaction(u=>{let l=u.select({metadata:y.metadata}).from(y).where(d).get();if(!l)return null;let p=nr(l.metadata),_=p.threadTitle,h=_&&typeof _=="object"&&!Array.isArray(_)?{..._}:{};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();u.update(y).set({metadata:m,updated_at:k}).where(d).run();let w=u.select({metadata:y.metadata}).from(y).where(d).get();if(!w)throw new f("DB_ERROR","Thread-title metadata update could not be read back");let C=mk(w.metadata);return {threadId:e,priority:C.priority,state:C.state}},{behavior:"immediate"})}catch(d){throw d instanceof f?d:new f("DB_ERROR","Failed to patch thread-title metadata",d)}finally{c.close();}}togglePin(e,n){let r=this.openHandle(true);try{return r.db.transaction(o=>kk(o,e,n),{behavior:"immediate"})}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to toggle pin",o)}finally{r.close();}}reorderPins(e,n){let r=this.openHandle(true);try{r.db.transaction(o=>yk(o,e,n),{behavior:"immediate"});}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to reorder pins",o)}finally{r.close();}}toggleStar(e,n){let r=this.openHandle(true);try{let o=n?drizzleOrm.and(drizzleOrm.eq(y.id,e),drizzleOrm.eq(y.workspace_id,n)):drizzleOrm.eq(y.id,e),s=r.db.select({starred:y.starred}).from(y).where(o).get();if(!s)return null;let i=s.starred?0:1;return r.db.update(y).set({starred:i}).where(o).run(),{starred:!!i}}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to toggle star",o)}finally{r.close();}}resolveOverdriveForRequest(e,n,r,o){let i=this.openHandle(true);try{let c=n?drizzleOrm.and(drizzleOrm.eq(y.id,e),drizzleOrm.eq(y.workspace_id,n)):drizzleOrm.eq(y.id,e);return i.db.transaction(u=>{let l=u.select({metadata:y.metadata}).from(y).where(c).get();if(!l)return null;let p=l.metadata?JSON.parse(l.metadata):{},_=p.overdrive??{},h=o?.defaultTurns??_.defaultTurns??3,m=o?.updatedBy??"ui",k=new Date().toISOString(),w,C,T,P;switch(r){case "enable-count":{let A=o?.turns??h,x=o?.consumeCurrent?Math.max(A-1,0):A;w=x>0?"count":"off",C=x,T=!0,P="count";break}case "enable-latch":{w="latch",C=0,T=!0,P="latch";break}case "disable":{w="off",C=0,T=!1;break}default:{let A=_.state??"off",x=typeof _.remaining=="number"?_.remaining:0;if(A==="count"&&x>0){let I=x-1;I<=0?(w="off",C=0):(w="count",C=I),T=!0,P="count";}else A==="latch"?(w="latch",C=0,T=!0,P="latch"):(w="off",C=0,T=!1);break}}return p.overdrive={state:w,remaining:C,defaultTurns:h,updatedAt:k,updatedBy:m},u.update(y).set({metadata:JSON.stringify(p),updated_at:k}).where(c).run(),{applied:T,appliedMode:P,state:w,remaining:C}},{behavior:"immediate"})}catch(c){throw c instanceof f?c:new f("DB_ERROR","Failed to resolve overdrive",c)}finally{i.close();}}};g();Ot();qt();Bt();Nt();g();var Ta="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function Tk(t){let e=crypto.randomBytes(t*2),n="";for(let r=0;r<e.length&&n.length<t;r++){let o=e[r];o<248&&(n+=Ta[o%62]);}for(;n.length<t;)n+=Ta[crypto.randomBytes(1)[0]%62];return n}function Lt(t){return `${t}_${Tk(8)}`}function zl(t,e){let{createHash:n}=In("crypto"),r=n("sha256").update(e).digest(),o=Buffer.alloc(8);for(let i=0;i<32;i++)o[i%8]^=r[i];let s="";for(let i of o)s+=Ta[i%62];return `${t}_${s}`}Gt();g();var wk=["urgent","high","medium","low"],Ek=["investigating","in-progress","in-review","on-hold","done"],Kl="custom:";var Rk=new Set(wk),Sk=new Set(Ek);function wa(t){return typeof t=="string"&&Rk.has(t)}function Ea(t){if(typeof t!="string")return false;if(Sk.has(t))return true;if(t.startsWith("c_"))return t.length>2;if(!t.startsWith(Kl))return false;let e=t.slice(Kl.length);return e.length>=1&&e.length<=20}function Jl(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 Ra(t){let e=Jl(t);if(!e)return {};let n=e.threadTitle;if(!n||typeof n!="object"||Array.isArray(n))return {};let r=n,o={};return wa(r.priority)&&(o.priority=r.priority),Ea(r.state)&&(o.state=r.state),o}function Vl(t,e){let n=Jl(t)??{},r={...Ra(t)};return e.priority===null?delete r.priority:e.priority!==void 0&&(r.priority=e.priority),e.state===null?delete r.state:e.state!==void 0&&(r.state=e.state),r.priority===void 0&&r.state===void 0?delete n.threadTitle:n.threadTitle=r,Object.keys(n).length===0?null:JSON.stringify(n)}Kn();var vk="regeneration_replaced";var bk="THREAD_HIGHLIGHT_REGENERATION_INTERRUPTED";var Ck="THREAD_HIGHLIGHT_REGENERATION_COMMIT_FAILED",Aa=class extends f{threadId;highlightId;expectedRevision;currentRevision;constructor(e,n,r,o){super("CONFLICT",`Highlight revision conflict: expected ${r}, current ${o}`),this.name="ThreadHistoryConflictError",this.threadId=e,this.highlightId=n,this.expectedRevision=r,this.currentRevision=o;}},Qr=class extends Aa{},Na=class extends f{stableCode="THREAD_HIGHLIGHT_REGENERATION_IN_PROGRESS";run;constructor(e){super("CONFLICT","THREAD_HIGHLIGHT_REGENERATION_IN_PROGRESS"),this.name="ThreadHighlightRegenerationConflictError",this.run=e;}},xk=new Set($d),Dk=new Set(Md),Pk=new Set(Hd),Lk=new Set(Ud),Mk=50,Yl=100,Ql=280,Zl=40,$k=new Set(qd),os=["queued","running"];function Ia(t){return $k.has(t)}function Q(t){throw new f("VALIDATION",t)}function pt(t){throw new f("NOT_FOUND",t)}function q(t,e){(typeof t!="string"||t.trim().length===0)&&Q(`${e} is required`);}function Kr(t={}){let e=t.actor??t,n=e.actorType??"system";return xk.has(n)||Q(`invalid actorType: ${String(n)}`),e.actorId!==void 0&&e.actorId!==null&&typeof e.actorId!="string"&&Q("actorId must be a string or null"),{actorType:n,actorId:e.actorId??null}}function Hk(t){q(t.threadId,"threadId"),t.workspaceId!==void 0&&t.workspaceId!==null&&q(t.workspaceId,"workspaceId"),t.title!==void 0&&t.title!==null&&((typeof t.title!="string"||t.title.trim().length===0)&&Q("title must not be empty"),t.title.length>120&&Q("title must be at most 120 characters")),t.priority!==void 0&&t.priority!==null&&!wa(t.priority)&&Q(`invalid priority: ${String(t.priority)}`),t.state!==void 0&&t.state!==null&&!Ea(t.state)&&Q(`invalid state: ${String(t.state)}`);}function Uk(t){t.beforeSeq!==void 0&&t.afterSeq!==void 0&&Q("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)&&Q(`${n} must be a non-negative integer`);let e=t.limit??Mk;return (!Number.isInteger(e)||e<1||e>Yl)&&Q(`limit must be between 1 and ${Yl}`),e}function Oa(t){typeof t!="string"&&Q("text is required");let e=t.trim();return e.length===0&&Q("text must not be empty"),e.length>Ql&&Q(`text must be at most ${Ql} characters`),e}function Mt(t,e){return q(t??"",e),t}function va(t){Lk.has(t)||Q(`invalid highlight kind: ${String(t)}`);}function qk(t){Pk.has(t)||Q(`invalid highlight source: ${String(t)}`);}function Bk(t){q(t.threadId,"threadId"),q(t.workspaceId,"workspaceId");let e=t.source??"manual";qk(e),va(t.kind);let n=Oa(t.text),r=t.coversFromTaskId??t.fromTaskId??t.taskId,o=t.coversToTaskId??t.toTaskId??t.taskId;if(e==="manual"){let l=t.taskId??(r&&o&&r===o?r:void 0),p=Mt(l,"taskId");return (r!==p||o!==p)&&Q("manual highlights must cover exactly one task"),{source:e,kind:t.kind,text:n,coversFromTaskId:p,coversToTaskId:p,agentId:t.agentId??null,sourceTaskId:null,detectorVersion:null,contentFingerprint:null}}let s=Mt(r,"coversFromTaskId"),i=Mt(o,"coversToTaskId"),c=t.sourceTaskId??s,d=t.detectorVersion??(t.idempotencyKey!==void 0?"default":null),u=t.contentFingerprint??t.idempotencyKey??null;return Mt(c??void 0,"sourceTaskId"),Mt(d??void 0,"detectorVersion"),Mt(u??void 0,"contentFingerprint"),{source:e,kind:t.kind,text:n,coversFromTaskId:s,coversToTaskId:i,agentId:t.agentId??null,sourceTaskId:c,detectorVersion:d,contentFingerprint:u}}function Fk(t,e){(!t||typeof t!="object")&&Q(`candidates[${e}] is required`),va(t.kind);let n=Oa(t.text),r=Mt(t.anchorTaskId,`candidates[${e}].anchorTaskId`),o=Mt(t.coversFromTaskId,`candidates[${e}].coversFromTaskId`),s=Mt(t.coversToTaskId,`candidates[${e}].coversToTaskId`),i=t.contentFingerprint?.trim()||zl("thl",JSON.stringify({kind:t.kind,text:n,anchorTaskId:r,coversFromTaskId:o,coversToTaskId:s}));return q(i,`candidates[${e}].contentFingerprint`),{kind:t.kind,text:n,anchorTaskId:r,coversFromTaskId:o,coversToTaskId:s,contentFingerprint:i}}function Wk(t){Array.isArray(t)||Q("candidates must be an array"),t.length>Zl&&Q(`candidates must contain at most ${Zl} items`);let e=new Map;for(let[n,r]of t.entries()){let o=Fk(r,n);e.set(o.contentFingerprint,o);}return [...e.values()]}function Yr(t){let e=Ra(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 Gk(t){try{let e=JSON.stringify(t);return (!e||e==="null"||e.startsWith("["))&&Q("event payload must be a JSON object"),e}catch(e){throw new f("VALIDATION","event payload must be JSON serializable",e)}}function Jr(t,e){return t.select({maxSeq:drizzleOrm.sql`COALESCE(MAX(${X.seq}), 0)`}).from(X).where(drizzleOrm.eq(X.thread_id,e)).get()?.maxSeq??0}function Vr(t,e){return !!t.select({id:X.id}).from(X).where(drizzleOrm.eq(X.thread_id,e)).limit(1).get()}function Rn(t,e){Dk.has(e.type)||Q(`invalid thread event type: ${String(e.type)}`);let n=Lt("the");t.insert(X).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:Gk(e.payload),created_at:e.createdAt}).run();let r=t.select().from(X).where(drizzleOrm.eq(X.id,n)).get();if(!r)throw new f("DB_ERROR","Thread event insert did not return a row");return r}function Xr(t,e,n,r,o){let s=Yr(e);Rn(t,{threadId:e.id,seq:o,type:"thread.snapshot.imported",actorType:n.actorType,actorId:n.actorId,createdAt:r,payload:{title:s.title,priority:s.priority,state:s.state}});}function is(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 ss(t,e,n,r,o,s,i){let c=o==="thread.highlight.created"?is(e):{before:i?is({...e,...i,id:e.id}):void 0,after:is(e)};return Rn(t,{threadId:e.thread_id,seq:s,type:o,actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.source==="manual"?e.covers_from_task_id:e.source_task_id??e.covers_from_task_id,highlightId:e.id,payload:c})}function jk(t,e,n,r,o,s){return Rn(t,{threadId:e.thread_id,seq:o,type:"thread.highlight.deleted",actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.source_task_id??e.covers_from_task_id,highlightId:e.id,payload:{before:is(e),...s??{}}})}var as=class extends me{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=Ne.join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath??super.resolveDbPath()}openHandle(e){let n=this.resolveDbPath();if(!e&&!Iu.existsSync(n))throw new f("NOT_FOUND","Database not found");if(e){let o=Ne.dirname(n);Iu.existsSync(o)||Iu.mkdirSync(o,{recursive:true});}let r=H(n);if(e)try{Pe(r.db,n);}catch(o){throw r.close(),o}return r}findThread(e,n,r){let o=drizzleOrm.eq(y.id,n),s=r===void 0?o:r===null?drizzleOrm.and(o,drizzleOrm.isNull(y.workspace_id)):drizzleOrm.and(o,drizzleOrm.eq(y.workspace_id,r));return e.select().from(y).where(s).limit(1).get()}findRegenerationRun(e,n,r){let o=e.select().from(z).where(drizzleOrm.eq(z.id,n)).limit(1).get();if(o&&!(r!==void 0&&!this.findThread(e,o.thread_id,r)))return o}resolveWorkspaceId(e){if(q(e,"threadId"),!Iu.existsSync(this.resolveDbPath()))return null;let n=this.openHandle(false);try{return n.db.select({workspaceId:y.workspace_id}).from(y).where(drizzleOrm.eq(y.id,e)).limit(1).get()?.workspaceId??null}catch(r){throw r instanceof f?r:new f("DB_ERROR","Failed to resolve thread workspace",r)}finally{n.close();}}getSnapshot(e,n){if(q(e,"threadId"),!Iu.existsSync(this.resolveDbPath()))return null;let r=this.openHandle(false);try{let o=this.findThread(r.db,e,n);return o?Yr(o):null}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to read thread snapshot",o)}finally{r.close();}}updateSnapshot(e){Hk(e);let n=Kr(e),r=new Date().toISOString(),o=this.openHandle(true);try{return o.db.transaction(s=>{let i=this.findThread(s,e.threadId,e.workspaceId);i||pt(`Thread ${e.threadId} not found`);let c=Yr(i),d=e.title!==void 0,u=d&&e.title!==c.title,l=d&&i.title_locked!==1,p=e.priority!==void 0&&e.priority!==c.priority,_=e.state!==void 0&&e.state!==c.state,h=u||p||_;if(!h&&!l)return c;let m=i.metadata;(p||_)&&(m=Vl(i.metadata,{priority:e.priority,state:e.state}));let k={};if(h&&(k.metadata=m,k.updated_at=r),u&&(k.title=e.title),d&&(k.title_locked=1),s.update(y).set(k).where(e.workspaceId===void 0?drizzleOrm.eq(y.id,e.threadId):e.workspaceId===null?drizzleOrm.and(drizzleOrm.eq(y.id,e.threadId),drizzleOrm.isNull(y.workspace_id)):drizzleOrm.and(drizzleOrm.eq(y.id,e.threadId),drizzleOrm.eq(y.workspace_id,e.workspaceId))).run(),!h){let T={...i,title_locked:1};return Yr(T)}let w=Jr(s,i.id)+1;Vr(s,i.id)||(Xr(s,i,n,r,w),w+=1),u&&(Rn(s,{threadId:i.id,seq:w,type:"thread.title.changed",actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.taskId,payload:{before:c.title,after:e.title}}),w+=1),p&&(Rn(s,{threadId:i.id,seq:w,type:"thread.priority.changed",actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.taskId,payload:{before:c.priority,after:e.priority}}),w+=1),_&&Rn(s,{threadId:i.id,seq:w,type:"thread.state.changed",actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.taskId,payload:{before:c.state,after:e.state}});let C={...i,title:u?e.title:i.title,metadata:m,title_locked:d?1:i.title_locked,updated_at:r};return Yr(C)},{behavior:"immediate"})}catch(s){throw s instanceof f?s:new f("DB_ERROR","Failed to update thread snapshot",s)}finally{o.close();}}mutateSnapshot(e){return this.updateSnapshot(e)}updateThreadSnapshot(e){return this.updateSnapshot(e)}getLatestSeq(e,n){if(q(e,"threadId"),!Iu.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(${X.seq}), 0)`}).from(X).where(drizzleOrm.eq(X.thread_id,e)).get()?.maxSeq??0:null}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to read latest thread event sequence",o)}finally{r.close();}}listCompletedThreadHighlightTurns(e,n){if(q(e,"threadId"),q(n,"workspaceId"),!Iu.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,[...wn]),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(o){throw o instanceof f?o:new f("DB_ERROR","Failed to read completed thread highlight turns",o)}finally{r.close();}}createHighlightRegenerationRun(e){q(e.threadId,"threadId"),q(e.workspaceId,"workspaceId"),q(e.requestId,"requestId"),q(e.detectorVersion,"detectorVersion"),e.runId!==void 0&&q(e.runId,"runId");let n=new Date().toISOString(),r=this.openHandle(true);try{return r.db.transaction(o=>{let s=this.findThread(o,e.threadId,e.workspaceId);s||pt(`Thread ${e.threadId} not found`);let i=o.select().from(z).where(drizzleOrm.and(drizzleOrm.eq(z.thread_id,s.id),drizzleOrm.eq(z.request_id,e.requestId))).orderBy(drizzleOrm.desc(z.requested_at),drizzleOrm.desc(z.id)).limit(1).get();if(i)return {run:i,created:!1};let c=o.select().from(z).where(drizzleOrm.and(drizzleOrm.eq(z.thread_id,s.id),drizzleOrm.inArray(z.status,os))).orderBy(drizzleOrm.asc(z.requested_at),drizzleOrm.asc(z.id)).limit(1).get();if(c)throw new Na(c);let d=e.runId??Lt("thr");o.insert(z).values({id:d,thread_id:s.id,request_id:e.requestId,status:"queued",detector_version:e.detectorVersion,requested_at:n,started_at:null,completed_at:null,error_code:null,previous_auto_count:null,new_auto_count:null}).run();let u=o.select().from(z).where(drizzleOrm.eq(z.id,d)).get();if(!u)throw new f("DB_ERROR","Highlight regeneration run insert did not return a row");return {run:u,created:!0}},{behavior:"immediate"})}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to create highlight regeneration run",o)}finally{r.close();}}beginHighlightRegenerationRun(e){return this.createHighlightRegenerationRun(e)}queueHighlightRegenerationRun(e){return this.createHighlightRegenerationRun(e)}getHighlightRegenerationRun(e,n){if(q(e,"runId"),n!==void 0&&q(n,"workspaceId"),!Iu.existsSync(this.resolveDbPath()))return null;let r=this.openHandle(false);try{return this.findRegenerationRun(r.db,e,n)??null}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to read highlight regeneration run",o)}finally{r.close();}}getHighlightRegenerationRunByRequest(e,n,r){if(q(e,"threadId"),q(n,"workspaceId"),q(r,"requestId"),!Iu.existsSync(this.resolveDbPath()))return null;let o=this.openHandle(false);try{return this.findThread(o.db,e,n)?o.db.select().from(z).where(drizzleOrm.and(drizzleOrm.eq(z.thread_id,e),drizzleOrm.eq(z.request_id,r))).orderBy(drizzleOrm.desc(z.requested_at),drizzleOrm.desc(z.id)).limit(1).get()??null:null}catch(s){throw s instanceof f?s:new f("DB_ERROR","Failed to read highlight regeneration request",s)}finally{o.close();}}findHighlightRegenerationRun(e,n,r){return this.getHighlightRegenerationRunByRequest(e,n,r)}startHighlightRegenerationRun(e,n){q(e,"runId"),n!==void 0&&q(n,"workspaceId");let r=new Date().toISOString(),o=this.openHandle(true);try{return o.db.transaction(s=>{let i=this.findRegenerationRun(s,e,n);if(i||pt(`Highlight regeneration run ${e} not found`),Ia(i.status)||Q(`invalid highlight regeneration status: ${i.status}`),i.status!=="queued")return i;s.update(z).set({status:"running",started_at:r}).where(drizzleOrm.and(drizzleOrm.eq(z.id,i.id),drizzleOrm.eq(z.status,"queued"))).run();let c=s.select().from(z).where(drizzleOrm.eq(z.id,i.id)).get();if(!c)throw new f("DB_ERROR","Highlight regeneration run start did not return a row");return c},{behavior:"immediate"})}catch(s){throw s instanceof f?s:new f("DB_ERROR","Failed to start highlight regeneration run",s)}finally{o.close();}}startHighlightRegeneration(e,n){return this.startHighlightRegenerationRun(e,n)}failHighlightRegenerationRun(e){q(e.runId,"runId"),q(e.errorCode,"errorCode"),e.workspaceId!==void 0&&q(e.workspaceId,"workspaceId");let n=new Date().toISOString(),r=this.openHandle(true);try{return r.db.transaction(o=>{let s=this.findRegenerationRun(o,e.runId,e.workspaceId);if(s||pt(`Highlight regeneration run ${e.runId} not found`),Ia(s.status)||Q(`invalid highlight regeneration status: ${s.status}`),s.status==="completed"||s.status==="failed")return s;o.update(z).set({status:"failed",completed_at:n,error_code:e.errorCode}).where(drizzleOrm.and(drizzleOrm.eq(z.id,s.id),drizzleOrm.inArray(z.status,os))).run();let i=o.select().from(z).where(drizzleOrm.eq(z.id,s.id)).get();if(!i)throw new f("DB_ERROR","Highlight regeneration run failure did not return a row");return i},{behavior:"immediate"})}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to fail highlight regeneration run",o)}finally{r.close();}}failHighlightRegeneration(e){return this.failHighlightRegenerationRun(e)}recoverInterruptedHighlightRegenerationRuns(e=bk){q(e,"errorCode");let n=new Date().toISOString(),r=this.openHandle(true);try{return r.db.transaction(o=>o.update(z).set({status:"failed",completed_at:n,error_code:e}).where(drizzleOrm.inArray(z.status,os)).run().changes,{behavior:"immediate"})}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to recover interrupted highlight runs",o)}finally{r.close();}}completeHighlightRegenerationRun(e){q(e.runId,"runId"),q(e.threadId,"threadId"),q(e.workspaceId,"workspaceId"),q(e.detectorVersion,"detectorVersion");let n=Wk(e.candidates),r=Kr(e),o=this.openHandle(true),s=false;try{return o.db.transaction(i=>{let c=this.findRegenerationRun(i,e.runId,e.workspaceId);if((!c||c.thread_id!==e.threadId)&&pt(`Highlight regeneration run ${e.runId} not found`),Ia(c.status)||Q(`invalid highlight regeneration status: ${c.status}`),c.status==="failed")throw new f("CONFLICT","Highlight regeneration run has already failed");if(c.status==="completed")return {run:c,deletedCount:0,createdCount:0,previousAutoCount:c.previous_auto_count??0,newAutoCount:c.new_auto_count??0};s=!0;let d=this.findThread(i,e.threadId,e.workspaceId);d||pt(`Thread ${e.threadId} not found`),c.detector_version!==e.detectorVersion&&Q("detectorVersion does not match the regeneration run");let u=i.select().from(B).where(drizzleOrm.eq(B.thread_id,d.id)).orderBy(drizzleOrm.asc(B.created_at),drizzleOrm.asc(B.id)).all(),l=new Set(n.map(I=>I.contentFingerprint)),p=u.filter(I=>I.source==="auto"&&I.status==="active"&&I.revision===0&&!l.has(I.content_fingerprint??"")),_=u.filter(I=>I.source==="auto"&&I.status==="active").length,h=new Set(u.filter(I=>!p.includes(I)&&I.content_fingerprint).map(I=>I.content_fingerprint)),m=n.filter(I=>!h.has(I.contentFingerprint)),k=new Date().toISOString(),w=Jr(i,d.id)+1;Vr(i,d.id)||(Xr(i,d,r,k,w),w+=1);for(let I of p)i.delete(B).where(drizzleOrm.eq(B.id,I.id)).run(),jk(i,I,r,k,w,{runId:e.runId,reason:vk}),w+=1;let C=0,T=e.agentId??(r.actorType==="agent"?r.actorId:null);for(let I of m){let K=Lt("thl");i.insert(B).values({id:K,thread_id:d.id,source:"auto",kind:I.kind,status:"active",text:I.text,covers_from_task_id:I.coversFromTaskId,covers_to_task_id:I.coversToTaskId,revision:0,created_at:k,updated_at:k,agent_id:T,source_task_id:I.anchorTaskId,detector_version:e.detectorVersion,content_fingerprint:I.contentFingerprint,dismissed_at:null}).run();let re=i.select().from(B).where(drizzleOrm.eq(B.id,K)).get();if(!re)throw new f("DB_ERROR","Regenerated highlight insert did not return a row");ss(i,re,r,k,"thread.highlight.created",w),w+=1,C+=1;}let A=i.select().from(B).where(drizzleOrm.eq(B.thread_id,d.id)).all().filter(I=>I.source==="auto"&&I.status==="active").length;Rn(i,{threadId:d.id,seq:w,type:"thread.highlights.regenerated",actorType:r.actorType,actorId:r.actorId,createdAt:k,payload:{runId:c.id,detectorVersion:e.detectorVersion,previousAutoCount:_,newAutoCount:A,deletedCount:p.length,createdCount:C}}),i.update(z).set({status:"completed",started_at:c.started_at??k,completed_at:k,error_code:null,previous_auto_count:_,new_auto_count:A}).where(drizzleOrm.and(drizzleOrm.eq(z.id,c.id),drizzleOrm.inArray(z.status,os))).run();let x=i.select().from(z).where(drizzleOrm.eq(z.id,c.id)).get();if(!x)throw new f("DB_ERROR","Highlight regeneration completion did not return a row");return {run:x,deletedCount:p.length,createdCount:C,previousAutoCount:_,newAutoCount:A}},{behavior:"immediate"})}catch(i){if(s)try{this.failHighlightRegenerationRun({runId:e.runId,workspaceId:e.workspaceId,errorCode:Ck});}catch{}throw i instanceof f?i:new f("DB_ERROR","Failed to complete highlight regeneration",i)}finally{o.close();}}completeHighlightRegeneration(e){return this.completeHighlightRegenerationRun(e)}replaceAutoHighlightsAtomically(e){return this.completeHighlightRegenerationRun(e)}listTimeline(e,n,r={}){let o=typeof e=="string"?{...r,threadId:e,workspaceId:n}:e;q(o.threadId,"threadId"),q(o.workspaceId,"workspaceId");let s=Uk(o);if(!Iu.existsSync(this.resolveDbPath()))return null;let i=this.openHandle(false);try{if(!this.findThread(i.db,o.threadId,o.workspaceId))return null;let c=i.db.select({maxSeq:drizzleOrm.sql`COALESCE(MAX(${X.seq}), 0)`}).from(X).where(drizzleOrm.eq(X.thread_id,o.threadId)).get()?.maxSeq??0,d;o.beforeSeq!==void 0?d=i.db.select().from(X).where(drizzleOrm.and(drizzleOrm.eq(X.thread_id,o.threadId),drizzleOrm.lt(X.seq,o.beforeSeq))).orderBy(drizzleOrm.desc(X.seq)).limit(s+1).all().reverse():o.afterSeq!==void 0?d=i.db.select().from(X).where(drizzleOrm.and(drizzleOrm.eq(X.thread_id,o.threadId),drizzleOrm.sql`${X.seq} > ${o.afterSeq}`)).orderBy(drizzleOrm.asc(X.seq)).limit(s+1).all():d=i.db.select().from(X).where(drizzleOrm.eq(X.thread_id,o.threadId)).orderBy(drizzleOrm.desc(X.seq)).limit(s+1).all().reverse();let u=d.length>s,l=o.afterSeq!==void 0?d.slice(0,s):u?d.slice(1):d,p=!1,_=l[0];return _&&(p=!!i.db.select({id:X.id}).from(X).where(drizzleOrm.and(drizzleOrm.eq(X.thread_id,o.threadId),drizzleOrm.lt(X.seq,_.seq))).limit(1).get()),{items:l,latestSeq:c,hasMoreOlder:p}}catch(c){throw c instanceof f?c:new f("DB_ERROR","Failed to list thread timeline",c)}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=Bk(e),r=Kr(e),o=new Date().toISOString(),s=this.openHandle(true);try{return s.db.transaction(i=>{let c=this.findThread(i,e.threadId,e.workspaceId);if(c||pt(`Thread ${e.threadId} not found`),n.source==="auto"){let _=i.select().from(B).where(drizzleOrm.and(drizzleOrm.eq(B.thread_id,e.threadId),drizzleOrm.eq(B.source_task_id,n.sourceTaskId),drizzleOrm.eq(B.detector_version,n.detectorVersion),drizzleOrm.eq(B.content_fingerprint,n.contentFingerprint))).orderBy(drizzleOrm.asc(B.created_at),drizzleOrm.asc(B.id)).limit(1).get();if(_)return _}let d=e.id??Lt("thl"),u={id:d,thread_id:e.threadId,source:n.source,kind:n.kind,status:"active",text:n.text,covers_from_task_id:n.coversFromTaskId,covers_to_task_id:n.coversToTaskId,revision:0,created_at:o,updated_at:o,agent_id:n.agentId,source_task_id:n.sourceTaskId,detector_version:n.detectorVersion,content_fingerprint:n.contentFingerprint,dismissed_at:null};i.insert(B).values(u).run();let l=i.select().from(B).where(drizzleOrm.eq(B.id,d)).get();if(!l)throw new f("DB_ERROR","Highlight insert did not return a row");let p=Jr(i,c.id)+1;return Vr(i,c.id)||(Xr(i,c,r,o,p),p+=1),ss(i,l,r,o,"thread.highlight.created",p),l},{behavior:"immediate"})}catch(i){throw i instanceof f?i:new f("DB_ERROR","Failed to create thread highlight",i)}finally{s.close();}}updateHighlight(e){q(e.threadId,"threadId"),q(e.workspaceId,"workspaceId"),q(e.highlightId,"highlightId"),(!Number.isInteger(e.expectedRevision)||e.expectedRevision<0)&&Q("expectedRevision must be a non-negative integer"),e.text===void 0&&e.kind===void 0&&e.coversFromTaskId===void 0&&e.coversToTaskId===void 0&&Q("highlight update requires at least one field"),e.kind!==void 0&&va(e.kind);let n=e.text===void 0?void 0:Oa(e.text),r=Kr(e),o=new Date().toISOString(),s=this.openHandle(true);try{return s.db.transaction(i=>{let c=this.findThread(i,e.threadId,e.workspaceId);c||pt(`Thread ${e.threadId} not found`);let d=i.select().from(B).where(drizzleOrm.and(drizzleOrm.eq(B.id,e.highlightId),drizzleOrm.eq(B.thread_id,c.id))).limit(1).get();if(d||pt(`Highlight ${e.highlightId} not found`),d.revision!==e.expectedRevision)throw new Qr(c.id,d.id,e.expectedRevision,d.revision);if(d.status!=="active")throw new Qr(c.id,d.id,e.expectedRevision,d.revision);let u=e.kind??d.kind,l=n??d.text,p=e.coversFromTaskId??d.covers_from_task_id,_=e.coversToTaskId??d.covers_to_task_id;(!l||p.length===0||_.length===0)&&Q("highlight projection is incomplete");let h=u!==d.kind||l!==d.text||p!==d.covers_from_task_id||_!==d.covers_to_task_id,m=r.actorType==="user"&&d.source==="auto"&&h?"manual":d.source;if(!(h||m!==d.source))return d;let w=d.revision+1;i.update(B).set({source:m,kind:u,text:l,covers_from_task_id:p,covers_to_task_id:_,revision:w,updated_at:o}).where(drizzleOrm.and(drizzleOrm.eq(B.id,d.id),drizzleOrm.eq(B.revision,d.revision))).run();let C=i.select().from(B).where(drizzleOrm.eq(B.id,d.id)).get();if(!C)throw new f("DB_ERROR","Highlight update did not return a row");let T=Jr(i,c.id)+1;return Vr(i,c.id)||(Xr(i,c,r,o,T),T+=1),ss(i,C,r,o,"thread.highlight.updated",T,d),C},{behavior:"immediate"})}catch(i){throw i instanceof f?i:new f("DB_ERROR","Failed to update thread highlight",i)}finally{s.close();}}dismissHighlight(e){q(e.threadId,"threadId"),q(e.workspaceId,"workspaceId"),q(e.highlightId,"highlightId"),(!Number.isInteger(e.expectedRevision)||e.expectedRevision<0)&&Q("expectedRevision must be a non-negative integer");let n=Kr(e),r=new Date().toISOString(),o=this.openHandle(true);try{return o.db.transaction(s=>{let i=this.findThread(s,e.threadId,e.workspaceId);i||pt(`Thread ${e.threadId} not found`);let c=s.select().from(B).where(drizzleOrm.and(drizzleOrm.eq(B.id,e.highlightId),drizzleOrm.eq(B.thread_id,i.id))).limit(1).get();if(c||pt(`Highlight ${e.highlightId} not found`),c.revision!==e.expectedRevision)throw new Qr(i.id,c.id,e.expectedRevision,c.revision);if(c.status==="dismissed")return c;let d=c.revision+1;s.update(B).set({status:"dismissed",text:null,revision:d,updated_at:r,dismissed_at:r}).where(drizzleOrm.and(drizzleOrm.eq(B.id,c.id),drizzleOrm.eq(B.revision,c.revision))).run();let u=s.select().from(B).where(drizzleOrm.eq(B.id,c.id)).get();if(!u)throw new f("DB_ERROR","Highlight dismissal did not return a row");let l=Jr(s,i.id)+1;return Vr(s,i.id)||(Xr(s,i,n,r,l),l+=1),ss(s,u,n,r,"thread.highlight.deleted",l,c),u},{behavior:"immediate"})}catch(s){throw s instanceof f?s:new f("DB_ERROR","Failed to dismiss thread highlight",s)}finally{o.close();}}listActiveHighlights(e,n,r={}){if(q(e,"threadId"),q(n,"workspaceId"),r.taskId!==void 0&&q(r.taskId,"taskId"),r.coversFromTaskId!==void 0&&q(r.coversFromTaskId,"coversFromTaskId"),r.coversToTaskId!==void 0&&q(r.coversToTaskId,"coversToTaskId"),!Iu.existsSync(this.resolveDbPath()))return null;let o=this.openHandle(false);try{if(!this.findThread(o.db,e,n))return null;let i=o.db.select().from(B).where(drizzleOrm.and(drizzleOrm.eq(B.thread_id,e),drizzleOrm.eq(B.status,"active"))).orderBy(drizzleOrm.asc(B.created_at),drizzleOrm.asc(B.id)).all();if(r.taskId===void 0&&r.coversFromTaskId===void 0&&r.coversToTaskId===void 0)return i;let c=o.db.all(drizzleOrm.sql`
662
662
  SELECT id, started_at FROM tasks WHERE thread_id = ${e}
663
663
  ORDER BY started_at ASC, id ASC
664
- `),d=new Map(c.map((_,h)=>[_.id,h])),u=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(_=>{let h=d.get(_.covers_from_task_id),m=d.get(_.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 !(u!==void 0&&(u<k||u>E)||l!==void 0&&E<l||p!==void 0&&k>p)})}catch(s){throw s instanceof f?s:new f("DB_ERROR","Failed to list active thread highlights",s)}finally{o.close();}}listHighlights(e,n,r){return this.listActiveHighlights(e,n,r)}getActiveHighlights(e,n,r){return this.listActiveHighlights(e,n,r)}};g();Ct();Kt();zt();vt();rn();hs();var re=class extends f{reason;constructor(e,n="VALIDATION",r=e,o){super(n,r,o),this.name="CommonCodeRepositoryError",this.reason=e;}},bl="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function Tk(){let t=crypto.randomBytes(16),e="";for(let n of t)e+=bl[n%bl.length];return e.slice(0,12)}function Dl(){return `c_${Tk()}`}function wk(t){return typeof t=="string"&&fs.includes(t)}function Ek(t){return typeof t=="string"&&gs.includes(t)}function Kn(t){if(!wk(t))throw new re("COMMON_CODE_GROUP_INVALID","VALIDATION",`Unsupported common-code group: ${t}`)}function Pl(t){if(!Ek(t))throw new re("COMMON_CODE_COLOR_INVALID","VALIDATION",`Unsupported common-code color: ${t}`)}function Ll(t){let e=typeof t=="string"?t.trim():"",n=[...e].length;if(n<1||n>20)throw new re("COMMON_CODE_NAME_INVALID","VALIDATION","Common-code names must contain 1 to 20 Unicode characters");return e}function zn(t){if(typeof t!="string"||t.trim().length===0)throw new re("COMMON_CODE_WORKSPACE_INVALID","VALIDATION","Workspace id is required for a user common code")}function Xo(t){if(typeof t!="string"||t.trim().length===0)throw new re("COMMON_CODE_CODE_INVALID","VALIDATION","Common-code code is required")}function Wt(t,e){return drizzleOrm.and(drizzleOrm.eq(L.code_group,t),drizzleOrm.or(drizzleOrm.isNull(L.workspace_id),drizzleOrm.eq(L.workspace_id,e)))}var Yo=class extends ve{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=Re.join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath??super.resolveDbPath()}openHandle(e){let n=this.resolveDbPath();if(!e&&!nu.existsSync(n))throw new f("NOT_FOUND","Database not found");e&&nu.mkdirSync(Re.dirname(n),{recursive:true});let r=U(n);if(e)try{Be(r.db,n);}catch(o){throw r.close(),o}return r}listSelectable(e,n){if(Kn(e),zn(n),!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.select().from(L).where(drizzleOrm.and(Wt(e,n),drizzleOrm.eq(L.is_archived,0))).orderBy(drizzleOrm.asc(L.sort_order),drizzleOrm.asc(L.code)).all()}catch(o){throw new f("DB_ERROR","Failed to list selectable common codes",o)}finally{r.close();}}listForHistory(e,n){if(Kn(e),zn(n),!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.select().from(L).where(Wt(e,n)).orderBy(drizzleOrm.asc(L.sort_order),drizzleOrm.asc(L.code)).all()}catch(o){throw new f("DB_ERROR","Failed to list common-code history",o)}finally{r.close();}}reorder(e){let n=e.group;if(Kn(n),zn(e.workspaceId),!Array.isArray(e.codes)||e.codes.length===0)throw new re("COMMON_CODE_REORDER_INVALID","VALIDATION","At least one common-code code is required for reordering");for(let o of e.codes)Xo(o);if(new Set(e.codes).size!==e.codes.length)throw new re("COMMON_CODE_REORDER_INVALID","VALIDATION","Common-code reorder entries must be unique");if(!this.dbExists())throw new re("COMMON_CODE_REORDER_INVALID","VALIDATION","Common-code reorder scope does not exist");let r=this.openHandle(true);try{return r.db.transaction(o=>{let s=o.select().from(L).where(Wt(n,e.workspaceId)).all(),i=s.filter(h=>h.is_archived===0),c=new Set(s.map(h=>h.code)),d=new Set(i.map(h=>h.code)),u=e.codes.find(h=>!c.has(h));if(u)throw new re("COMMON_CODE_REORDER_INVALID","VALIDATION",`Common code is not available in this scope: ${n}/${u}`);if(e.codes.length!==i.length||e.codes.some(h=>!d.has(h)))throw new re("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 re("COMMON_CODE_REORDER_INVALID","VALIDATION",`Common code is not selectable in this scope: ${n}/${h}`);return m}),_;for(let[h,m]of p.entries())m.sort_order!==h&&(_??=new Date().toISOString(),o.update(L).set({sort_order:h,updated_at:_}).where(drizzleOrm.and(drizzleOrm.eq(L.code_group,n),drizzleOrm.eq(L.code,m.code))).run());return o.select().from(L).where(Wt(n,e.workspaceId)).orderBy(drizzleOrm.asc(L.sort_order),drizzleOrm.asc(L.code)).all()},{behavior:"immediate"})}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to reorder common codes",o)}finally{r.close();}}resolve(e,n){if(Kn(e),Xo(n),!this.dbExists())return null;let r=this.openHandle(false);try{return r.db.select().from(L).where(drizzleOrm.and(drizzleOrm.eq(L.code_group,e),drizzleOrm.eq(L.code,n))).limit(1).get()??null}catch(o){throw new f("DB_ERROR","Failed to resolve common code",o)}finally{r.close();}}createThreadState(e){zn(e.workspaceId);let n=Ll(e.name);Pl(e.color);let r=this.openHandle(true);try{return r.db.transaction(o=>{if(o.select({code:L.code}).from(L).where(drizzleOrm.and(Wt("THREAD_STATE",e.workspaceId),drizzleOrm.eq(L.is_archived,0),drizzleOrm.eq(L.code_name,n))).limit(1).get())throw new re("COMMON_CODE_NAME_CONFLICT","CONFLICT",`Common-code name is already in use: ${n}`);let i=o.select({maxSortOrder:drizzleOrm.sql`max(${L.sort_order})`}).from(L).where(Wt("THREAD_STATE",e.workspaceId)).get(),c=new Date().toISOString(),d=Dl();for(;o.select({code:L.code}).from(L).where(drizzleOrm.and(drizzleOrm.eq(L.code_group,"THREAD_STATE"),drizzleOrm.eq(L.code,d))).limit(1).get();)d=Dl();o.insert(L).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:c,updated_at:c}).run();let u=o.select().from(L).where(drizzleOrm.and(drizzleOrm.eq(L.code_group,"THREAD_STATE"),drizzleOrm.eq(L.code,d))).limit(1).get();if(!u)throw new f("DB_ERROR","Created common code could not be read back");return u},{behavior:"immediate"})}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to create thread state common code",o)}finally{r.close();}}updateDisplay(e){if(Kn(e.group),Xo(e.code),zn(e.workspaceId),e.name===void 0&&e.color===void 0)throw new re("COMMON_CODE_UPDATE_EMPTY","VALIDATION","At least one display value is required");let n=e.name===void 0||e.name===null?e.name:Ll(e.name);e.color!==void 0&&Pl(e.color);let r=this.openHandle(true);try{return r.db.transaction(o=>{let s=o.select().from(L).where(drizzleOrm.and(drizzleOrm.eq(L.code_group,e.group),drizzleOrm.eq(L.code,e.code))).limit(1).get();if(!s)throw new re("COMMON_CODE_NOT_FOUND","NOT_FOUND",`Common code not found: ${e.group}/${e.code}`);if(this.assertOwnership(s,e.workspaceId),n===null&&s.is_builtin!==1)throw new re("COMMON_CODE_NAME_INVALID","VALIDATION","User common-code names cannot be cleared");if(typeof n=="string"&&s.is_archived===0){let d=drizzleOrm.and(Wt(e.group,e.workspaceId),drizzleOrm.eq(L.is_archived,0));if(o.select({code:L.code}).from(L).where(drizzleOrm.and(d,drizzleOrm.eq(L.code_name,n),drizzleOrm.sql`${L.code} <> ${e.code}`)).limit(1).get())throw new re("COMMON_CODE_NAME_CONFLICT","CONFLICT",`Common-code name is already in use: ${n}`)}let i={updated_at:new Date().toISOString()};e.name!==void 0&&(i.code_name=n??null),e.color!==void 0&&(i.color=e.color),o.update(L).set(i).where(drizzleOrm.and(drizzleOrm.eq(L.code_group,e.group),drizzleOrm.eq(L.code,e.code))).run();let c=o.select().from(L).where(drizzleOrm.and(drizzleOrm.eq(L.code_group,e.group),drizzleOrm.eq(L.code,e.code))).limit(1).get();if(!c)throw new f("DB_ERROR","Updated common code could not be read back");return c},{behavior:"immediate"})}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to update common-code display values",o)}finally{r.close();}}archive(e,n,r,o=true){if(Kn(e),Xo(n),zn(r),typeof o!="boolean")throw new re("COMMON_CODE_ARCHIVE_INVALID","VALIDATION","Archive state must be boolean");let s=this.openHandle(true);try{return s.db.transaction(i=>{let c=i.select().from(L).where(drizzleOrm.and(drizzleOrm.eq(L.code_group,e),drizzleOrm.eq(L.code,n))).limit(1).get();if(!c)throw new re("COMMON_CODE_NOT_FOUND","NOT_FOUND",`Common code not found: ${e}/${n}`);if(c.is_builtin===1)throw new re("COMMON_CODE_BUILTIN_ARCHIVE_FORBIDDEN","VALIDATION","Builtin common codes cannot be archived");if(this.assertOwnership(c,r),!o&&c.code_name!==null&&i.select({code:L.code}).from(L).where(drizzleOrm.and(Wt(e,r),drizzleOrm.eq(L.is_archived,0),drizzleOrm.eq(L.code_name,c.code_name),drizzleOrm.ne(L.code,n))).limit(1).get())throw new re("COMMON_CODE_NAME_CONFLICT","CONFLICT",`Common-code name is already in use: ${c.code_name}`);i.update(L).set({is_archived:o?1:0,updated_at:new Date().toISOString()}).where(drizzleOrm.and(drizzleOrm.eq(L.code_group,e),drizzleOrm.eq(L.code,n))).run();let d=i.select().from(L).where(drizzleOrm.and(drizzleOrm.eq(L.code_group,e),drizzleOrm.eq(L.code,n))).limit(1).get();if(!d)throw new f("DB_ERROR","Archived common code could not be read back");return d},{behavior:"immediate"})}catch(i){throw i instanceof f?i:new f("DB_ERROR","Failed to archive common code",i)}finally{s.close();}}assertOwnership(e,n){if(e.workspace_id!==null&&e.workspace_id!==n)throw new re("COMMON_CODE_SCOPE_FORBIDDEN","VALIDATION","Workspace does not own this common code")}};Sn();yr();g();var ct={threadContext:"crewx_thread_context",apps:"apps",appsGuidance:"apps_guidance",availableApps:"available_apps",crewxUiState:"crewx_ui_state"};function Ik(t){return t.replace(new RegExp(`<${ct.threadContext}\\b[^>]*>[\\s\\S]*?<\\/${ct.threadContext}>`,"g"),"").replace(new RegExp(`<${ct.apps}\\b[^>]*>[\\s\\S]*?<\\/${ct.apps}>`,"g"),"").replace(new RegExp(`<${ct.appsGuidance}\\b[^>]*>[\\s\\S]*?<\\/${ct.appsGuidance}>`,"g"),"").replace(new RegExp(`<${ct.availableApps}\\b[^>]*>[\\s\\S]*?<\\/${ct.availableApps}>`,"g"),"").replace(new RegExp(`<${ct.crewxUiState}\\b[^>]*>[\\s\\S]*?<\\/${ct.crewxUiState}>`,"g"),"").replace(/<conversation_history[^>]*>[\s\S]*?<\/conversation_history>/g,"").split(`
664
+ `),d=new Map(c.map((_,h)=>[_.id,h])),u=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(_=>{let h=d.get(_.covers_from_task_id),m=d.get(_.covers_to_task_id);if(h===void 0||m===void 0)return !1;let k=Math.min(h,m),w=Math.max(h,m);return !(u!==void 0&&(u<k||u>w)||l!==void 0&&w<l||p!==void 0&&k>p)})}catch(s){throw s instanceof f?s:new f("DB_ERROR","Failed to list active thread highlights",s)}finally{o.close();}}listHighlights(e,n,r){return this.listActiveHighlights(e,n,r)}getActiveHighlights(e,n,r){return this.listActiveHighlights(e,n,r)}};g();qt();Ot();Nt();Bt();Kn();Gt();var Sn=12e3,Vk=4,Da=512*1024,sr=1,Z=class extends Error{code;constructor(e,n=e,r){super(n,r===void 0?void 0:{cause:r}),this.name="ThreadBranchRepositoryError",this.code=e;}};function At(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Xk(t){if(!t)return {};try{let e=JSON.parse(t);return At(e)?e:{}}catch{return {}}}function Ht(t){let e="";for(let n=0;n<t.length;n+=1){let r=t.charCodeAt(n);if(r!==0){if(r>=55296&&r<=56319){let o=t.charCodeAt(n+1);o>=56320&&o<=57343&&(e+=t.slice(n,n+2),n+=1);continue}r>=56320&&r<=57343||(e+=t[n]);}}return e.replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/\{\{/g,"&#123;&#123;")}function ds(t){if(!t)return;let e=Date.parse(t);return Number.isFinite(e)?e:void 0}function ap(t){if(!t)return "";try{let e=JSON.parse(t);if(Array.isArray(e)){let n=e.filter(r=>At(r)&&r.type==="text"&&typeof r.text=="string").map(r=>r.text);if(n.length>0)return n.join(`
665
+ `)}else if(At(e)&&e.result!==void 0)return typeof e.result=="string"?e.result:JSON.stringify(e.result)}catch{}return t}function dp(t){let e=Xk(t),n=[e.attachments,e.files,e.images,e.attachmentReceiptContext],r=[];for(let o of n)if(Array.isArray(o))for(let s of o){if(!At(s))continue;let i=[s.filename,s.fileName,s.name].find(d=>typeof d=="string");if(i===void 0)continue;let c=[s.size,s.sizeBytes,s.bytes].find(d=>typeof d=="number"&&Number.isFinite(d)&&d>=0);r.push({filename:Ht(i),size:c===void 0?0:Math.floor(c)});}return r}function Yk(t){return t.reduce((e,n)=>e+n.filename.length+String(n.size).length,0)}function Qk(t){return t.user.length+t.assistant.length+Yk(t.attachments)}function $t(t){return t.reduce((e,n)=>e+Qk(n),0)}function Pa(t){return `[truncated task=${Ht(t)}]`}function tp(t,e,n){if(t.length<=e)return t;let r=Pa(n);if(e<=r.length)return r.slice(0,e);let o=e-r.length,s=Math.ceil(o/2),i=o-s;return `${t.slice(0,s)}${r}${i>0?t.slice(-i):""}`}function Zk(t){return t.map(e=>({taskId:e.id,user:Ht(e.prompt),assistant:Ht(ap(e.result)),attachments:dp(e.metadata),truncated:false}))}function np(t,e,n){let r=$t(t);if(r<=e)return false;let o=false,s=[];for(let i of [...t].reverse()){s.push({turn:i,key:"assistant"},{turn:i,key:"user"});for(let c=i.attachments.length-1;c>=0;c-=1)s.push({turn:i,key:"filename",attachmentIndex:c});}for(let i of s){if(r<=e)break;let c=i.turn;if(i.key==="filename"){let h=i.attachmentIndex,m=c.attachments[h];if(!m.filename)continue;let k=Pa(c.taskId),w=c.taskId===n?k.length+1:k.length;if(m.filename.length<=w)continue;let C=Math.max(w,m.filename.length-(r-e)),T=tp(m.filename,C,c.taskId);if(T.length>=m.filename.length)continue;c.attachments[h]={...m,filename:T},r=$t(t),c.truncated=true,o=true;continue}let d=c[i.key];if(!d)continue;let u=Pa(c.taskId),l=c.taskId===n?u.length+1:u.length;if(d.length<=l)continue;let p=Math.max(l,d.length-(r-e)),_=tp(d,p,c.taskId);_.length>=d.length||(c[i.key]=_,c.truncated=true,r=$t(t),o=true);}return o}function ey(t){let e=Zk(t),n=e.at(-1).taskId,r=Math.min(Vk,e.length),o=e.slice(-r),s=false;$t(o)>Sn&&(s=np(o,Sn,n)||s);let i=[...o];for(let u=e.length-r-1;u>=0;u-=1){let l=e[u],p=[l,...i];if($t(p)<=Sn){i=p;continue}let _=Sn-$t(i);if(_>0){let h=[{...l,attachments:[...l.attachments]},...i];np([h[0]],_,n)&&$t(h)<=Sn&&(i=h);}s=true;break}let c=i.map(u=>({taskId:u.taskId,user:u.user,assistant:u.assistant,attachments:u.attachments.map(l=>({...l})),...u.truncated?{truncated:true}:{}})),d=$t(i);if(d>Sn)throw new Z("DATABASE_ERROR","Carry snapshot exceeded its character limit");return {version:sr,turns:c,turnsCount:c.length,chars:d,truncated:s||i.some(u=>u.truncated)}}function ty(t){return t.map(e=>{let n=dp(e.metadata),r={taskId:e.id,text:e.prompt,isAssistant:false,...ds(e.started_at)===void 0?{}:{timestamp:ds(e.started_at)},...n.length>0?{files:n}:{}},o={taskId:e.id,text:ap(e.result),isAssistant:true,...ds(e.completed_at??e.started_at)===void 0?{}:{timestamp:ds(e.completed_at??e.started_at)}};return {taskId:e.id,user:r,assistant:o}})}function rp(t,e){let n={version:1,messages:t.flatMap(({user:r,assistant:o})=>[r,o]),...e?{truncated_before_task_id:e}:{}};return JSON.stringify(n)}function ny(t){let e=ty(t),n,r=rp(e);for(;Buffer.byteLength(r,"utf8")>Da&&e.length>1;){let s=e.shift();n??=s.taskId,r=rp(e,n);}let o=Buffer.byteLength(r,"utf8");if(o>Da)throw new Z("BRANCH_SOURCE_TOO_LARGE","Newest completed turn exceeds the branch history limit");return {sourceJson:r,bytes:o}}function op(t,e,n){try{let r=JSON.parse(t);if(!At(r)||r.version!==sr||!Array.isArray(r.turns)||typeof r.turnsCount!="number"||typeof r.chars!="number"||typeof r.truncated!="boolean"||r.turnsCount!==e||r.chars!==n||r.turnsCount!==r.turns.length)throw new Error("invalid carry header");let o=r.turns.map(s=>{if(!At(s)||typeof s.taskId!="string"||typeof s.user!="string"||typeof s.assistant!="string"||!Array.isArray(s.attachments))throw new Error("invalid carry turn");let i=s.attachments.map(c=>{if(!At(c)||typeof c.filename!="string"||typeof c.size!="number")throw new Error("invalid carry attachment");return {filename:Ht(c.filename),size:Math.max(0,Math.floor(c.size))}});return {taskId:s.taskId,user:Ht(s.user),assistant:Ht(s.assistant),attachments:i,...s.truncated===!0?{truncated:!0}:{}}});if($t(o)!==r.chars||r.chars>Sn)throw new Error("carry metrics do not match");return {version:sr,turns:o,turnsCount:r.turnsCount,chars:r.chars,truncated:r.truncated}}catch(r){throw new Z("CORRUPT_BRANCH","Stored branch carry snapshot is invalid",r)}}function sp(t,e){try{if(Buffer.byteLength(t,"utf8")!==e||e>Da)throw new Error("source byte count mismatch");let n=JSON.parse(t);if(!At(n)||n.version!==1||!Array.isArray(n.messages))throw new Error("invalid source header");return {version:1,messages:n.messages.map(o=>{if(!At(o)||typeof o.taskId!="string"||typeof o.text!="string"||typeof o.isAssistant!="boolean")throw new Error("invalid source message");let s=Array.isArray(o.files)?o.files.map(i=>{if(!At(i)||typeof i.filename!="string"||typeof i.size!="number")throw new Error("invalid source attachment");return {filename:i.filename,size:i.size}}):void 0;return {taskId:o.taskId,text:o.text,isAssistant:o.isAssistant,...typeof o.timestamp=="number"?{timestamp:o.timestamp}:{},...s&&s.length>0?{files:s}:{}}}),...typeof n.truncated_before_task_id=="string"?{truncated_before_task_id:n.truncated_before_task_id}:{}}}catch(n){throw new Z("CORRUPT_BRANCH","Stored branch history source is invalid",n)}}function ry(t){let e={workspaceId:t.workspaceId,parentThreadId:t.parentThreadId,actorId:t.actorId,prompt:t.prompt,model:t.model??null,provider:t.provider??null,effort:t.effort??null,attachments:(t.attachments??[]).map(n=>({filename:n.filename,size:n.size}))};return crypto.createHash("sha256").update(JSON.stringify(e)).digest("hex")}function Ca(t){if(t.status!=="active"&&t.status!=="undone")throw new Z("CORRUPT_BRANCH","Stored branch has an unknown status");return {id:t.id,workspaceId:t.workspace_id,parentThreadId:t.parent_thread_id,childThreadId:t.child_thread_id,...t.child_title===null?{}:{childTitle:t.child_title},branchPointTaskId:t.branch_point_task_id,branchAnswerNo:t.branch_answer_no,firstTaskId:t.first_task_id,parentTitle:Ht(t.parent_title),actorId:t.actor_id,requestId:t.request_id,carriedTurns:t.carried_turns,carriedChars:t.carried_chars,carriedTruncated:t.carried_truncated===1,status:t.status,createdAt:t.created_at,...t.undone_at===null?{}:{undoneAt:t.undone_at}}}function ip(t,e){return t.get(drizzleOrm.sql`
666
+ SELECT thread_branches.id, thread_branches.workspace_id, thread_branches.parent_thread_id,
667
+ thread_branches.child_thread_id, child.title AS child_title,
668
+ thread_branches.branch_point_task_id, thread_branches.branch_answer_no,
669
+ thread_branches.first_task_id, thread_branches.parent_title, thread_branches.actor_id,
670
+ thread_branches.request_id, thread_branches.carried_turns, thread_branches.carried_chars,
671
+ thread_branches.carried_truncated, thread_branches.status, thread_branches.created_at,
672
+ thread_branches.undone_at
673
+ FROM thread_branches
674
+ LEFT JOIN threads AS child ON child.id = thread_branches.child_thread_id
675
+ WHERE ${e}
676
+ LIMIT 1
677
+ `)??void 0}var cs=class extends me{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=Ne.join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath??super.resolveDbPath()}openHandle(e){let n=this.resolveDbPath();if(!e&&!Iu.existsSync(n))throw new f("NOT_FOUND","Database not found");e&&!Iu.existsSync(Ne.dirname(n))&&Iu.mkdirSync(Ne.dirname(n),{recursive:true});let r=H(n);if(e)try{Pe(r.db,n);}catch(o){throw r.close(),o}return r}async create(e){if(!e||typeof e.workspaceId!="string"||!e.workspaceId.trim()||typeof e.parentThreadId!="string"||!e.parentThreadId.trim()||typeof e.actorId!="string"||!e.actorId.trim()||typeof e.requestId!="string"||!e.requestId.trim()||typeof e.prompt!="string"||(e.attachments??[]).some(s=>!s||typeof s.filename!="string"||!s.filename||!Number.isFinite(s.size)||s.size<0))throw new Z("INVALID_INPUT","Thread branch input is incomplete");let n=ry(e),r=this.openHandle(true),o;try{o=r.db.transaction(s=>{let i=s.select({id:j.id,child_thread_id:j.child_thread_id,first_task_id:j.first_task_id,branch_point_task_id:j.branch_point_task_id,branch_answer_no:j.branch_answer_no,carried_turns:j.carried_turns,carried_chars:j.carried_chars,carried_truncated:j.carried_truncated,payload_hash:j.payload_hash}).from(j).where(drizzleOrm.and(drizzleOrm.eq(j.workspace_id,e.workspaceId),drizzleOrm.eq(j.actor_id,e.actorId),drizzleOrm.eq(j.request_id,e.requestId))).limit(1).get();if(i){if(i.payload_hash!==n)throw new Z("BRANCH_REQUEST_CONFLICT","Request id was already used for a different branch payload");return {branchId:i.id,childThreadId:i.child_thread_id,firstTaskId:i.first_task_id,taskId:i.first_task_id,branchPointTaskId:i.branch_point_task_id,branchAnswerNo:i.branch_answer_no,carriedTurns:i.carried_turns,carriedChars:i.carried_chars,carriedTruncated:i.carried_truncated===1,created:!1}}let c=s.select({id:y.id,workspace_id:y.workspace_id,platform:y.platform,title:y.title}).from(y).where(drizzleOrm.and(drizzleOrm.eq(y.id,e.parentThreadId),drizzleOrm.eq(y.workspace_id,e.workspaceId))).limit(1).get();if(!c)throw new Z("PARENT_NOT_FOUND","Parent thread was not found in this workspace");let u=s.all(drizzleOrm.sql`
678
+ SELECT child.id, child.agent_id, child.prompt, child.result, child.status,
679
+ child.error, child.started_at, child.completed_at, child.metadata, child.workspace_id
680
+ FROM tasks AS child
681
+ WHERE child.thread_id = ${e.parentThreadId}
682
+ AND (child.workspace_id = ${e.workspaceId} OR child.workspace_id IS NULL)
683
+ AND NOT EXISTS (
684
+ SELECT 1 FROM tasks AS parent_task
685
+ WHERE parent_task.id = child.parent_task_id
686
+ AND parent_task.thread_id = child.thread_id
687
+ )
688
+ ORDER BY child.started_at ASC, child.id ASC
689
+ `).filter(A=>xe(A)==="success"),l=u.at(-1);if(!l)throw new Z("PARENT_NO_COMPLETED_TURN","Parent thread has no completed turn");let p=ey(u),_=ny(u),h=Lt("brn"),m=Lt("thd"),k=Lt("tsk"),w=new Date().toISOString(),C=Ht(c.title??"Untitled conversation"),T=JSON.stringify(p),P=JSON.stringify({branchId:h,...e.provider?{provider:e.provider}:{},...e.effort?{effort:e.effort}:{}});return s.insert(y).values({id:m,workspace_id:e.workspaceId,created_by_kind:"human",created_by_id:e.actorId,created_by_task_id:k,platform:c.platform,title:null,first_message:e.prompt,last_message:e.prompt,message_count:1,created_at:w,updated_at:w,metadata:null}).run(),s.insert(a).values({id:k,agent_id:l.agent_id,user_id:e.actorId,actor_kind:"human",actor_id:e.actorId,prompt:e.prompt,mode:"execute",status:"pending",result:null,error:null,started_at:w,completed_at:null,metadata:P,workspace_id:e.workspaceId,thread_id:m,model:e.model??null,platform:c.platform}).run(),s.insert(j).values({id:h,workspace_id:e.workspaceId,parent_thread_id:e.parentThreadId,child_thread_id:m,branch_point_task_id:l.id,branch_answer_no:u.length,first_task_id:k,parent_title:C,actor_id:e.actorId,request_id:e.requestId,payload_hash:n,snapshot_version:sr,carry_json:T,carried_turns:p.turnsCount,carried_chars:p.chars,carried_truncated:p.truncated?1:0,status:"active",created_at:w,undone_at:null}).run(),s.insert(mt).values({branch_id:h,source_json:_.sourceJson,bytes:_.bytes}).run(),{branchId:h,childThreadId:m,firstTaskId:k,taskId:k,branchPointTaskId:l.id,branchAnswerNo:u.length,carriedTurns:p.turnsCount,carriedChars:p.chars,carriedTruncated:p.truncated,created:!0}},{behavior:"immediate"});}catch(s){throw s instanceof Z?s:new Z("DATABASE_ERROR","Failed to create thread branch",s)}finally{r.close();}return o.created&&e.afterCommit&&await e.afterCommit(o),o}getByChild(e){if(!Iu.existsSync(this.resolveDbPath()))return;let n=this.openHandle(false);try{let r=ip(n.db,drizzleOrm.eq(j.child_thread_id,e));return r?Ca(r):void 0}catch(r){throw r instanceof Z?r:new Z("DATABASE_ERROR","Failed to read thread branch summary",r)}finally{n.close();}}listByParent(e){if(!Iu.existsSync(this.resolveDbPath()))return [];let n=this.openHandle(false);try{return n.db.all(drizzleOrm.sql`
690
+ SELECT branch.id, branch.workspace_id, branch.parent_thread_id, branch.child_thread_id,
691
+ child.title AS child_title, branch.branch_point_task_id, branch.branch_answer_no,
692
+ branch.first_task_id, branch.parent_title, branch.actor_id, branch.request_id,
693
+ branch.carried_turns, branch.carried_chars, branch.carried_truncated,
694
+ branch.status, branch.created_at, branch.undone_at
695
+ FROM thread_branches AS branch
696
+ LEFT JOIN threads AS child ON child.id = branch.child_thread_id
697
+ WHERE branch.parent_thread_id = ${e}
698
+ ORDER BY branch.created_at ASC, branch.id ASC
699
+ `).map(Ca)}catch(r){throw r instanceof Z?r:new Z("DATABASE_ERROR","Failed to list parent thread branches",r)}finally{n.close();}}getCarry(e){if(!Iu.existsSync(this.resolveDbPath()))return;let n=this.openHandle(false);try{let r=n.db.select({status:j.status,carry_json:j.carry_json,carried_turns:j.carried_turns,carried_chars:j.carried_chars,snapshot_version:j.snapshot_version}).from(j).where(drizzleOrm.eq(j.id,e)).limit(1).get();if(!r||r.status==="undone")return;if(r.status!=="active"||r.snapshot_version!==sr)throw new Z("CORRUPT_BRANCH","Stored branch snapshot version or status is invalid");return op(r.carry_json,r.carried_turns,r.carried_chars)}catch(r){throw r instanceof Z?r:new Z("DATABASE_ERROR","Failed to read branch carry snapshot",r)}finally{n.close();}}getSource(e){if(!Iu.existsSync(this.resolveDbPath()))return;let n=this.openHandle(false);try{let r=n.db.select({status:j.status,source_json:mt.source_json,bytes:mt.bytes}).from(j).leftJoin(mt,drizzleOrm.eq(mt.branch_id,j.id)).where(drizzleOrm.eq(j.id,e)).limit(1).get();if(!r||r.status==="undone")return;if(r.status!=="active"||typeof r.source_json!="string"||r.bytes===null)throw new Z("CORRUPT_BRANCH","Stored branch history source is missing");return sp(r.source_json,r.bytes)}catch(r){throw r instanceof Z?r:new Z("DATABASE_ERROR","Failed to read branch history source",r)}finally{n.close();}}getActiveContextByChild(e){if(!Iu.existsSync(this.resolveDbPath()))return;let n=this.openHandle(false);try{let r=ip(n.db,drizzleOrm.eq(j.child_thread_id,e));if(!r||r.status==="undone")return;if(r.status!=="active")throw new Z("CORRUPT_BRANCH","Stored branch is not readable");let o=n.db.select({snapshot_version:j.snapshot_version,carry_json:j.carry_json,carried_turns:j.carried_turns,carried_chars:j.carried_chars}).from(j).where(drizzleOrm.eq(j.id,r.id)).limit(1).get();if(!o||o.snapshot_version!==sr)throw new Z("CORRUPT_BRANCH","Stored branch snapshot version is invalid");let s=n.db.select({source_json:mt.source_json,bytes:mt.bytes}).from(mt).where(drizzleOrm.eq(mt.branch_id,r.id)).limit(1).get();if(!s)throw new Z("CORRUPT_BRANCH","Stored branch history source is missing");return {branch:Ca(r),carry:op(o.carry_json,o.carried_turns,o.carried_chars),source:sp(s.source_json,s.bytes)}}catch(r){throw r instanceof Z?r:new Z("DATABASE_ERROR","Failed to read active branch context",r)}finally{n.close();}}markUndone(e){if(!Iu.existsSync(this.resolveDbPath()))return false;let n=this.openHandle(true);try{return n.db.update(j).set({status:"undone",undone_at:new Date().toISOString()}).where(drizzleOrm.and(drizzleOrm.eq(j.id,e),drizzleOrm.eq(j.status,"active"))).run().changes>0}catch(r){throw new Z("DATABASE_ERROR","Failed to mark thread branch undone",r)}finally{n.close();}}};g();Ot();qt();Bt();Nt();Gt();xs();var se=class extends f{reason;constructor(e,n="VALIDATION",r=e,o){super(n,r,o),this.name="CommonCodeRepositoryError",this.reason=e;}},up="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function py(){let t=crypto.randomBytes(16),e="";for(let n of t)e+=up[n%up.length];return e.slice(0,12)}function lp(){return `c_${py()}`}function _y(t){return typeof t=="string"&&bs.includes(t)}function fy(t){return typeof t=="string"&&Cs.includes(t)}function ar(t){if(!_y(t))throw new se("COMMON_CODE_GROUP_INVALID","VALIDATION",`Unsupported common-code group: ${t}`)}function pp(t){if(!fy(t))throw new se("COMMON_CODE_COLOR_INVALID","VALIDATION",`Unsupported common-code color: ${t}`)}function _p(t){let e=typeof t=="string"?t.trim():"",n=[...e].length;if(n<1||n>20)throw new se("COMMON_CODE_NAME_INVALID","VALIDATION","Common-code names must contain 1 to 20 Unicode characters");return e}function dr(t){if(typeof t!="string"||t.trim().length===0)throw new se("COMMON_CODE_WORKSPACE_INVALID","VALIDATION","Workspace id is required for a user common code")}function us(t){if(typeof t!="string"||t.trim().length===0)throw new se("COMMON_CODE_CODE_INVALID","VALIDATION","Common-code code is required")}function nn(t,e){return drizzleOrm.and(drizzleOrm.eq(L.code_group,t),drizzleOrm.or(drizzleOrm.isNull(L.workspace_id),drizzleOrm.eq(L.workspace_id,e)))}var ls=class extends me{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=Ne.join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath??super.resolveDbPath()}openHandle(e){let n=this.resolveDbPath();if(!e&&!Iu.existsSync(n))throw new f("NOT_FOUND","Database not found");e&&Iu.mkdirSync(Ne.dirname(n),{recursive:true});let r=H(n);if(e)try{Pe(r.db,n);}catch(o){throw r.close(),o}return r}listSelectable(e,n){if(ar(e),dr(n),!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.select().from(L).where(drizzleOrm.and(nn(e,n),drizzleOrm.eq(L.is_archived,0))).orderBy(drizzleOrm.asc(L.sort_order),drizzleOrm.asc(L.code)).all()}catch(o){throw new f("DB_ERROR","Failed to list selectable common codes",o)}finally{r.close();}}listForHistory(e,n){if(ar(e),dr(n),!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.select().from(L).where(nn(e,n)).orderBy(drizzleOrm.asc(L.sort_order),drizzleOrm.asc(L.code)).all()}catch(o){throw new f("DB_ERROR","Failed to list common-code history",o)}finally{r.close();}}reorder(e){let n=e.group;if(ar(n),dr(e.workspaceId),!Array.isArray(e.codes)||e.codes.length===0)throw new se("COMMON_CODE_REORDER_INVALID","VALIDATION","At least one common-code code is required for reordering");for(let o of e.codes)us(o);if(new Set(e.codes).size!==e.codes.length)throw new se("COMMON_CODE_REORDER_INVALID","VALIDATION","Common-code reorder entries must be unique");if(!this.dbExists())throw new se("COMMON_CODE_REORDER_INVALID","VALIDATION","Common-code reorder scope does not exist");let r=this.openHandle(true);try{return r.db.transaction(o=>{let s=o.select().from(L).where(nn(n,e.workspaceId)).all(),i=s.filter(h=>h.is_archived===0),c=new Set(s.map(h=>h.code)),d=new Set(i.map(h=>h.code)),u=e.codes.find(h=>!c.has(h));if(u)throw new se("COMMON_CODE_REORDER_INVALID","VALIDATION",`Common code is not available in this scope: ${n}/${u}`);if(e.codes.length!==i.length||e.codes.some(h=>!d.has(h)))throw new se("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 se("COMMON_CODE_REORDER_INVALID","VALIDATION",`Common code is not selectable in this scope: ${n}/${h}`);return m}),_;for(let[h,m]of p.entries())m.sort_order!==h&&(_??=new Date().toISOString(),o.update(L).set({sort_order:h,updated_at:_}).where(drizzleOrm.and(drizzleOrm.eq(L.code_group,n),drizzleOrm.eq(L.code,m.code))).run());return o.select().from(L).where(nn(n,e.workspaceId)).orderBy(drizzleOrm.asc(L.sort_order),drizzleOrm.asc(L.code)).all()},{behavior:"immediate"})}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to reorder common codes",o)}finally{r.close();}}resolve(e,n){if(ar(e),us(n),!this.dbExists())return null;let r=this.openHandle(false);try{return r.db.select().from(L).where(drizzleOrm.and(drizzleOrm.eq(L.code_group,e),drizzleOrm.eq(L.code,n))).limit(1).get()??null}catch(o){throw new f("DB_ERROR","Failed to resolve common code",o)}finally{r.close();}}createThreadState(e){dr(e.workspaceId);let n=_p(e.name);pp(e.color);let r=this.openHandle(true);try{return r.db.transaction(o=>{if(o.select({code:L.code}).from(L).where(drizzleOrm.and(nn("THREAD_STATE",e.workspaceId),drizzleOrm.eq(L.is_archived,0),drizzleOrm.eq(L.code_name,n))).limit(1).get())throw new se("COMMON_CODE_NAME_CONFLICT","CONFLICT",`Common-code name is already in use: ${n}`);let i=o.select({maxSortOrder:drizzleOrm.sql`max(${L.sort_order})`}).from(L).where(nn("THREAD_STATE",e.workspaceId)).get(),c=new Date().toISOString(),d=lp();for(;o.select({code:L.code}).from(L).where(drizzleOrm.and(drizzleOrm.eq(L.code_group,"THREAD_STATE"),drizzleOrm.eq(L.code,d))).limit(1).get();)d=lp();o.insert(L).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:c,updated_at:c}).run();let u=o.select().from(L).where(drizzleOrm.and(drizzleOrm.eq(L.code_group,"THREAD_STATE"),drizzleOrm.eq(L.code,d))).limit(1).get();if(!u)throw new f("DB_ERROR","Created common code could not be read back");return u},{behavior:"immediate"})}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to create thread state common code",o)}finally{r.close();}}updateDisplay(e){if(ar(e.group),us(e.code),dr(e.workspaceId),e.name===void 0&&e.color===void 0)throw new se("COMMON_CODE_UPDATE_EMPTY","VALIDATION","At least one display value is required");let n=e.name===void 0||e.name===null?e.name:_p(e.name);e.color!==void 0&&pp(e.color);let r=this.openHandle(true);try{return r.db.transaction(o=>{let s=o.select().from(L).where(drizzleOrm.and(drizzleOrm.eq(L.code_group,e.group),drizzleOrm.eq(L.code,e.code))).limit(1).get();if(!s)throw new se("COMMON_CODE_NOT_FOUND","NOT_FOUND",`Common code not found: ${e.group}/${e.code}`);if(this.assertOwnership(s,e.workspaceId),n===null&&s.is_builtin!==1)throw new se("COMMON_CODE_NAME_INVALID","VALIDATION","User common-code names cannot be cleared");if(typeof n=="string"&&s.is_archived===0){let d=drizzleOrm.and(nn(e.group,e.workspaceId),drizzleOrm.eq(L.is_archived,0));if(o.select({code:L.code}).from(L).where(drizzleOrm.and(d,drizzleOrm.eq(L.code_name,n),drizzleOrm.sql`${L.code} <> ${e.code}`)).limit(1).get())throw new se("COMMON_CODE_NAME_CONFLICT","CONFLICT",`Common-code name is already in use: ${n}`)}let i={updated_at:new Date().toISOString()};e.name!==void 0&&(i.code_name=n??null),e.color!==void 0&&(i.color=e.color),o.update(L).set(i).where(drizzleOrm.and(drizzleOrm.eq(L.code_group,e.group),drizzleOrm.eq(L.code,e.code))).run();let c=o.select().from(L).where(drizzleOrm.and(drizzleOrm.eq(L.code_group,e.group),drizzleOrm.eq(L.code,e.code))).limit(1).get();if(!c)throw new f("DB_ERROR","Updated common code could not be read back");return c},{behavior:"immediate"})}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to update common-code display values",o)}finally{r.close();}}archive(e,n,r,o=true){if(ar(e),us(n),dr(r),typeof o!="boolean")throw new se("COMMON_CODE_ARCHIVE_INVALID","VALIDATION","Archive state must be boolean");let s=this.openHandle(true);try{return s.db.transaction(i=>{let c=i.select().from(L).where(drizzleOrm.and(drizzleOrm.eq(L.code_group,e),drizzleOrm.eq(L.code,n))).limit(1).get();if(!c)throw new se("COMMON_CODE_NOT_FOUND","NOT_FOUND",`Common code not found: ${e}/${n}`);if(c.is_builtin===1)throw new se("COMMON_CODE_BUILTIN_ARCHIVE_FORBIDDEN","VALIDATION","Builtin common codes cannot be archived");if(this.assertOwnership(c,r),!o&&c.code_name!==null&&i.select({code:L.code}).from(L).where(drizzleOrm.and(nn(e,r),drizzleOrm.eq(L.is_archived,0),drizzleOrm.eq(L.code_name,c.code_name),drizzleOrm.ne(L.code,n))).limit(1).get())throw new se("COMMON_CODE_NAME_CONFLICT","CONFLICT",`Common-code name is already in use: ${c.code_name}`);i.update(L).set({is_archived:o?1:0,updated_at:new Date().toISOString()}).where(drizzleOrm.and(drizzleOrm.eq(L.code_group,e),drizzleOrm.eq(L.code,n))).run();let d=i.select().from(L).where(drizzleOrm.and(drizzleOrm.eq(L.code_group,e),drizzleOrm.eq(L.code,n))).limit(1).get();if(!d)throw new f("DB_ERROR","Archived common code could not be read back");return d},{behavior:"immediate"})}catch(i){throw i instanceof f?i:new f("DB_ERROR","Failed to archive common code",i)}finally{s.close();}}assertOwnership(e,n){if(e.workspace_id!==null&&e.workspace_id!==n)throw new se("COMMON_CODE_SCOPE_FORBIDDEN","VALIDATION","Workspace does not own this common code")}};$n();Kn();g();var _t={threadContext:"crewx_thread_context",apps:"apps",appsGuidance:"apps_guidance",availableApps:"available_apps",crewxUiState:"crewx_ui_state"};function my(t){return t.replace(new RegExp(`<${_t.threadContext}\\b[^>]*>[\\s\\S]*?<\\/${_t.threadContext}>`,"g"),"").replace(new RegExp(`<${_t.apps}\\b[^>]*>[\\s\\S]*?<\\/${_t.apps}>`,"g"),"").replace(new RegExp(`<${_t.appsGuidance}\\b[^>]*>[\\s\\S]*?<\\/${_t.appsGuidance}>`,"g"),"").replace(new RegExp(`<${_t.availableApps}\\b[^>]*>[\\s\\S]*?<\\/${_t.availableApps}>`,"g"),"").replace(new RegExp(`<${_t.crewxUiState}\\b[^>]*>[\\s\\S]*?<\\/${_t.crewxUiState}>`,"g"),"").replace(/<conversation_history[^>]*>[\s\S]*?<\/conversation_history>/g,"").split(`
665
700
  `).filter(o=>!(o.startsWith("Loaded ")&&o.includes("layouts from")||o.includes("[dotenv@")||o.includes("[Nest]")&&o.includes("DEBUG")||o.startsWith("Registered custom layout:")||o.startsWith("Updated custom layout:"))).join(`
666
- `).trim()}function Ak(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 Nk(t,e,n){if(!t||e&&mt(t,n))return "";let r=t;try{let o=JSON.parse(r);Array.isArray(o)?r=o.filter(s=>s?.type==="text"&&s?.text).map(s=>s.text).join(`
667
- `):o&&typeof o=="object"&&o.result!==void 0&&(r=o.result||"");}catch{r=Ik(r);}return r}var Ok=new Set(["success","failed","stopped","running"]),vk=new Set(["failed","stopped"]),Ck={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"},Qo=200;function Ml(t){if(t.length<=Qo)return t;let e=t.charCodeAt(Qo-1),n=e>=55296&&e<=56319?Qo-1:Qo;return t.slice(0,n)}function xk(t){let e=rt(t),n=typeof t.error=="string"?t.error.split(`
668
- `)[0]??"":"";if(e){let r=Ck[e];return Ml(n?`${r}; ${n}`:r)}return n?Ml(n):void 0}var Zo=class{dbPath;constructor(e){this.dbPath=e??Re.join(Na.homedir(),".crewx","crewx.db");}getThreadRepo(){return new jo({dbPath:this.dbPath})}getThreadHistoryRepo(){return new Vo({dbPath:this.dbPath})}updateThread(e,n){this.getThreadRepo().updateThread(e,{title:n.title});}async ensureThread(e,n,r,o){let s=this.getThreadRepo(),i=s.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 s.ensureThread(e,n,r,o),{created:false}}return s.ensureThread(e,n,r,o),{created:true}}async fetchHistory(e,n){let r=n?.limit??100,o=this.getThreadRepo(),s=o.findThreadById(e),i=o.findTopLevelTasks(e,void 0,r,n?.agentId||void 0),c=new Set(["queued","cancelled"]),d=n?.currentTraceId;i=i.filter(h=>(!h.status||!c.has(h.status))&&(!d||h.trace_id!==d&&h.id!==d));let u=o.findInterceptedRequests(i.map(h=>h.id));u.size>0&&(i=i.map(h=>u.has(h.id)?{...h,prompt:u.get(h.id)}:h));let l=s?.platform??"cli",p=this.rowsToMessages(i),_=n?.includeHighlights===false?void 0:this.readActiveHighlights(e,s?.workspace_id??null);return {threadId:e,platform:l,messages:p,..._?{highlights:_}:{},metadata:{title:s?.title??void 0,firstMessage:s?.first_message??void 0,lastMessage:s?.last_message??void 0,messageCount:s?.message_count??0,updatedAt:s?.updated_at?new Date(s.updated_at).getTime():void 0}}}async fetchThreadState(e){try{let n=this.getThreadHistoryRepo().getSnapshot(e);if(!n)return;let r=new Yo({dbPath:this.dbPath}),o=(s,i)=>{try{return r.resolve(s,i)?.code_name||i}catch{return i}};return {...n.title?{title:n.title}:{},...n.priority?{priority:{code:n.priority,name:o("THREAD_PRIORITY",n.priority)}}:{},...n.state?{state:{code:n.state,name:o("THREAD_STATE",n.state)}}:{}}}catch{return}}async fetchHighlights(e){let n=this.getThreadRepo().findThreadById(e);return this.readActiveHighlights(e,n?.workspace_id??null)}async saveUserMessage(e,n,r,o){let{firstMessage:s}=this.getThreadRepo().saveUserMessage(e,n);return {id:e,firstMessage:s}}async saveAssistantMessage(e,n,r,o){return this.getThreadRepo().saveAssistantMessage(e,n),{id:e}}close(){}readActiveHighlights(e,n){if(!n)return [];try{return (this.getThreadHistoryRepo().listActiveHighlights(e,n)??[]).filter(o=>typeof o.text=="string"&&o.text.length>0).map(o=>({id:o.id,text:o.text,kind:o.kind,source:o.source,coversFromTaskId:o.covers_from_task_id,coversToTaskId:o.covers_to_task_id,createdAt:o.created_at}))}catch{return}}rowsToMessages(e){let n=[];for(let r of e){r.prompt&&n.push({id:`${r.id}-user`,text:r.prompt,isAssistant:false,timestamp:new Date(r.started_at).getTime(),taskId:r.id,metadata:{caller_agent_id:r.caller_agent_id,task_id:r.id}});let o={status:r.status??"",error:r.error,metadata:r.metadata},s=r.status?Ue(o):void 0,i=Ak(r.metadata),c=Nk(r.result,s!==void 0&&vk.has(s),i);if(c||s!==void 0&&Ok.has(s)){let d={agent_id:r.agent_id,task_id:r.id};if(s&&s!=="success"){d.status=s;let u=xk(o);u&&(d.reason=u);}n.push({id:`${r.id}-assistant`,text:c,isAssistant:true,timestamp:new Date(r.started_at).getTime(),taskId:r.id,metadata:d});}}return n}};var fa=class extends Ot{name="conversation";_provider;unsubStart=null;unsubEnd=null;constructor(e){super(),this._provider=new Zo(e?.dbPath);}get conversationProvider(){return this._provider}async afterUserMessage(e,n,r,o){}async afterAssistantMessage(e,n,r){}attach(e){this.unsubStart=e.on("task:start",async n=>{if(!n.threadId)return;let r=n.platform??"cli";try{let o=await this._provider.ensureThread(n.threadId,r,n.workspaceId,{createdByTaskId:n.traceId}),s=await this._provider.saveUserMessage(n.threadId,n.message??"");await this.afterUserMessage(n.threadId,s.id,o.created||s.firstMessage,n);}catch{}}),this.unsubEnd=e.on("task:end",async n=>{if(!n.result)return;let r=n.metadata?.threadId;if(!r)return;let o=n.agentRef?.replace(/^@/,"")??"";try{let{id:s}=await this._provider.saveAssistantMessage(r,n.result,o);await this.afterAssistantMessage(r,s,n);}catch{}});}detach(e){this.unsubStart?.(),this.unsubStart=null,this.unsubEnd?.(),this.unsubEnd=null,this._provider.close?.();}};exports.ConversationPlugin=fa;exports.FileLoggerPlugin=ts;exports.SqliteTracingPlugin=ta;
701
+ `).trim()}function ky(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 yy(t,e,n){if(!t||e&&Et(t,n))return "";let r=t;try{let o=JSON.parse(r);Array.isArray(o)?r=o.filter(s=>s?.type==="text"&&s?.text).map(s=>s.text).join(`
702
+ `):o&&typeof o=="object"&&o.result!==void 0&&(r=o.result||"");}catch{r=my(r);}return r}var Ty=new Set(["success","failed","stopped","running"]),wy=new Set(["failed","stopped"]),Ey={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 fp(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 Ry(t){let e=at(t),n=typeof t.error=="string"?t.error.split(`
703
+ `)[0]??"":"";if(e){let r=Ey[e];return fp(n?`${r}; ${n}`:r)}return n?fp(n):void 0}var _s=class{dbPath;constructor(e){this.dbPath=e??Ne.join(Ja.homedir(),".crewx","crewx.db");}getThreadRepo(){return new rs({dbPath:this.dbPath})}getThreadHistoryRepo(){return new as({dbPath:this.dbPath})}getThreadBranchRepo(){return new cs({dbPath:this.dbPath})}updateThread(e,n){this.getThreadRepo().updateThread(e,{title:n.title});}async ensureThread(e,n,r,o){let s=this.getThreadRepo(),i=s.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 s.ensureThread(e,n,r,o),{created:false}}return s.ensureThread(e,n,r,o),{created:true}}async fetchHistory(e,n){let r=n?.limit??100,o=this.getThreadRepo(),s=o.findThreadById(e),i=o.findTopLevelTasks(e,void 0,r,n?.agentId||void 0),c=new Set(["queued","cancelled"]),d=n?.currentTraceId;i=i.filter(h=>(!h.status||!c.has(h.status))&&(!d||h.trace_id!==d&&h.id!==d));let u=o.findInterceptedRequests(i.map(h=>h.id));u.size>0&&(i=i.map(h=>u.has(h.id)?{...h,prompt:u.get(h.id)}:h));let l=s?.platform??"cli",p=this.rowsToMessages(i),_=n?.includeHighlights===false?void 0:this.readActiveHighlights(e,s?.workspace_id??null);return {threadId:e,platform:l,messages:p,..._?{highlights:_}:{},metadata:{title:s?.title??void 0,firstMessage:s?.first_message??void 0,lastMessage:s?.last_message??void 0,messageCount:s?.message_count??0,updatedAt:s?.updated_at?new Date(s.updated_at).getTime():void 0}}}async fetchThreadState(e){try{let n=this.getThreadHistoryRepo().getSnapshot(e);if(!n)return;let r=new ls({dbPath:this.dbPath}),o=(s,i)=>{try{return r.resolve(s,i)?.code_name||i}catch{return i}};return {...n.title?{title:n.title}:{},...n.priority?{priority:{code:n.priority,name:o("THREAD_PRIORITY",n.priority)}}:{},...n.state?{state:{code:n.state,name:o("THREAD_STATE",n.state)}}:{}}}catch{return}}async fetchBranchContext(e){return this.getThreadBranchRepo().getActiveContextByChild(e)}async fetchBranchMarkers(e){return this.getThreadBranchRepo().listByParent(e).filter(n=>n.status==="active").map(n=>({branchPointTaskId:n.branchPointTaskId,childTitle:n.childTitle?.trim()||"Untitled conversation"}))}async fetchHighlights(e){let n=this.getThreadRepo().findThreadById(e);return this.readActiveHighlights(e,n?.workspace_id??null)}async saveUserMessage(e,n,r,o){let{firstMessage:s}=this.getThreadRepo().saveUserMessage(e,n);return {id:e,firstMessage:s}}async saveAssistantMessage(e,n,r,o){return this.getThreadRepo().saveAssistantMessage(e,n),{id:e}}close(){}readActiveHighlights(e,n){if(!n)return [];try{return (this.getThreadHistoryRepo().listActiveHighlights(e,n)??[]).filter(o=>typeof o.text=="string"&&o.text.length>0).map(o=>({id:o.id,text:o.text,kind:o.kind,source:o.source,coversFromTaskId:o.covers_from_task_id,coversToTaskId:o.covers_to_task_id,createdAt:o.created_at}))}catch{return}}rowsToMessages(e){let n=[];for(let r of e){r.prompt&&n.push({id:`${r.id}-user`,text:r.prompt,isAssistant:false,timestamp:new Date(r.started_at).getTime(),taskId:r.id,metadata:{caller_agent_id:r.caller_agent_id,task_id:r.id}});let o={status:r.status??"",error:r.error,metadata:r.metadata},s=r.status?xe(o):void 0,i=ky(r.metadata),c=yy(r.result,s!==void 0&&wy.has(s),i);if(c||s!==void 0&&Ty.has(s)){let d={agent_id:r.agent_id,task_id:r.id};if(s&&s!=="success"){d.status=s;let u=Ry(o);u&&(d.reason=u);}n.push({id:`${r.id}-assistant`,text:c,isAssistant:true,timestamp:new Date(r.started_at).getTime(),taskId:r.id,metadata:d});}}return n}};var La=class extends Ut{name="conversation";_provider;unsubStart=null;unsubEnd=null;constructor(e){super(),this._provider=new _s(e?.dbPath);}get conversationProvider(){return this._provider}async afterUserMessage(e,n,r,o){}async afterAssistantMessage(e,n,r){}attach(e){this.unsubStart=e.on("task:start",async n=>{if(!n.threadId)return;let r=n.platform??"cli";try{let o=await this._provider.ensureThread(n.threadId,r,n.workspaceId,{createdByTaskId:n.traceId}),s=await this._provider.saveUserMessage(n.threadId,n.message??"");await this.afterUserMessage(n.threadId,s.id,o.created||s.firstMessage,n);}catch{}}),this.unsubEnd=e.on("task:end",async n=>{if(!n.result)return;let r=n.metadata?.threadId;if(!r)return;let o=n.agentRef?.replace(/^@/,"")??"";try{let{id:s}=await this._provider.saveAssistantMessage(r,n.result,o);await this.afterAssistantMessage(r,s,n);}catch{}});}detach(e){this.unsubStart?.(),this.unsubStart=null,this.unsubEnd?.(),this.unsubEnd=null,this._provider.close?.();}};exports.ConversationPlugin=La;exports.FileLoggerPlugin=gs;exports.SqliteTracingPlugin=ma;