@crewx/sdk 0.9.0-rc.53 → 0.9.0-rc.55

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 +1 @@
1
- 'use strict';var y=require('path'),d=require('fs'),G=require('crypto'),q=require('js-yaml'),O=require('os'),Y=require('tar'),zlib=require('zlib');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 y__namespace=/*#__PURE__*/_interopNamespace(y);var d__namespace=/*#__PURE__*/_interopNamespace(d);var G__namespace=/*#__PURE__*/_interopNamespace(G);var q__namespace=/*#__PURE__*/_interopNamespace(q);var O__namespace=/*#__PURE__*/_interopNamespace(O);var Y__namespace=/*#__PURE__*/_interopNamespace(Y);function ae(e){let t=n=>n.replace(/[.+^${}()|[\]\\]/g,"\\$&"),s=e.split("/").map(n=>n==="**"?".*":n.split("*").map(t).join("[^/]*"));return new RegExp(`^${s.join("\\/")}$`)}function E(e,t){try{return ae(t).test(e)}catch{return false}}function P(e,...t){let r=e.split("/");if(r.length<t.length)return false;let s=r.length-t.length;return t.every((n,i)=>E(r[s+i],n))}function ce(e,t){return e.split("/").some(r=>E(r,t))}var z=[{label:".env*",test:e=>E(e,".env*")},{label:".git/",test:(e,t,r)=>r&&e===".git"},{label:"memory/",test:(e,t,r)=>r&&e==="memory"},{label:"*.key",test:e=>E(e,"*.key")},{label:"*.pem",test:e=>E(e,"*.pem")},{label:"auth.json",test:e=>e==="auth.json"},{label:"node_modules/",test:(e,t,r)=>r&&e==="node_modules"},{label:"conversations/",test:(e,t,r)=>r&&e==="conversations"},{label:".crewx/threads/",test:(e,t,r)=>r&&P(t,".crewx","threads")},{label:".crewx/crewx.db",test:(e,t,r)=>!r&&P(t,".crewx","crewx.db")},{label:".crewx/*.log",test:(e,t,r)=>!r&&P(t,".crewx","*.log")},{label:".crewx/publish/",test:(e,t,r)=>r&&P(t,".crewx","publish")},{label:".crewx/",test:(e,t)=>ce(t,".crewx")}];function U(e,t,r){for(let s of z)if(s.test(e,t,r))return s.label;return null}function J(e){let t=[],r=[];function s(n,i,a){let m;try{m=d__namespace.readdirSync(n,{withFileTypes:!0});}catch{return}m.sort((c,u)=>c.name.localeCompare(u.name));for(let c of m){let u=i?`${i}/${c.name}`:c.name,l=y__namespace.join(n,c.name);if(c.isSymbolicLink()){let p;try{p=d__namespace.statSync(l);}catch{continue}if(p.isDirectory()){r.push({path:u,rule:a??"symlink-dir"});continue}let C=a??U(c.name,u,false);C?r.push({path:u,rule:C}):t.push(u);continue}if(c.isDirectory()){let p=a??U(c.name,u,true);s(l,u,p);continue}if(c.isFile()){let p=a??U(c.name,u,false);p?r.push({path:u,rule:p}):t.push(u);}}}return s(e,"",null),t.sort(),r.sort((n,i)=>n.path<i.path?-1:n.path>i.path?1:0),{included:t,excluded:r}}var ue=[{rule:"token-prefix",regex:/\b(?:sk-|ghp_|xoxb-)[A-Za-z0-9_-]{10,}/},{rule:"private-key",regex:/-----BEGIN [A-Z ]*PRIVATE KEY-----/},{rule:"aws-access-key",regex:/\bAKIA[0-9A-Z]{16}\b/}];function le(e){return e.includes(0)}function V(e,t){let r=[];for(let s of t){let n=y__namespace.join(e,s),i;try{i=d__namespace.readFileSync(n);}catch{continue}if(le(i))continue;i.toString("utf8").split(/\r\n|\r|\n/).forEach((m,c)=>{for(let{rule:u,regex:l}of ue)l.test(m)&&r.push({path:s,line:c+1,rule:u});});}return r}var X=/^[a-z0-9-]+$/,pe=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/,fe=/^[A-Za-z_][A-Za-z0-9_]*$/;function me(e){let t=y__namespace.join(e,"crewx.yaml");if(!d__namespace.existsSync(t))return {};let r;try{r=q__namespace.load(d__namespace.readFileSync(t,"utf8"));}catch{return {}}if(!r||typeof r!="object")return {};let s=r.metadata;if(!s||typeof s!="object")return {};let n=s;return {name:typeof n.name=="string"?n.name:void 0,version:typeof n.version=="string"?n.version:void 0,description:typeof n.description=="string"?n.description:void 0,requiredEnv:n.requiredEnv,crewxMinVersion:typeof n.crewxMinVersion=="string"?n.crewxMinVersion:void 0}}function he(e){return G__namespace.createHash("sha256").update(new Uint8Array(d__namespace.readFileSync(e))).digest("hex")}function W(e,t,r={}){let s=me(e),n=s.name??y__namespace.basename(e);if(!X.test(n))throw new Error(`publish: invalid name "${n}" \u2014 must match ${X} (lowercase letters, numbers, hyphen only)`);let i=r.version??s.version;if(!i)throw new Error("publish: version is required \u2014 set crewx.yaml metadata.version or pass opts.version");if(!pe.test(i))throw new Error(`publish: invalid version "${i}" \u2014 must be semver (e.g. 1.0.0)`);let a=Array.isArray(s.requiredEnv)?s.requiredEnv:[],m=[];for(let l of a){if(typeof l!="string"||!fe.test(l))throw new Error(`publish: requiredEnv must contain names only (no values), got "${String(l)}"`);m.push(l);}let c=t.map(l=>({path:l,sha256:he(y__namespace.join(e,l))})).sort((l,p)=>l.path<p.path?-1:l.path>p.path?1:0),u={name:n,version:i,type:"template",description:s.description??"",files:c,requiredEnv:m};return s.crewxMinVersion&&(u.crewxMinVersion=s.crewxMinVersion),u}async function Q(e,t){let r=y__namespace.join(e,".crewx","publish");d__namespace.mkdirSync(r,{recursive:true});let s=y__namespace.join(r,`${t.name}-${t.version}.tgz`),n=d__namespace.mkdtempSync(y__namespace.join(O__namespace.tmpdir(),"crewx-publish-"));try{d__namespace.writeFileSync(y__namespace.join(n,"manifest.json"),JSON.stringify(t,null,2));for(let i of t.files){let a=y__namespace.join(n,i.path);d__namespace.mkdirSync(y__namespace.dirname(a),{recursive:!0}),d__namespace.copyFileSync(y__namespace.join(e,i.path),a);}await Y__namespace.create({gzip:!0,file:s,cwd:n,portable:!0,noMtime:!0},["manifest.json",...t.files.map(i=>i.path)]);}finally{d__namespace.rmSync(n,{recursive:true,force:true});}return s}var A="/api/v1";var ye=201,be=409,I=401;function we(){return process.env.WI013_FAKE_UPLOAD==="1"}function Ee(e){let t=zlib.gunzipSync(new Uint8Array(e)),r=zlib.gzipSync(new Uint8Array(t),{level:1});if(Buffer.compare(new Uint8Array(r),new Uint8Array(e))===0)throw new Error("WI013_FAKE_UPLOAD: re-gzipped bytes are identical to the original \u2014 tamper is a no-op");return r}function Ae(e){return e.replace(/\/+$/,"")}async function v(e){try{return await e.json()}catch{return null}}function b(e){let t=e?.message;return typeof t=="string"?t:void 0}function ee(e,t,r){let s=e;if(!s||s.success!==true||s.data===void 0)throw new Error(`publish: ${t} response envelope malformed (expected { success: true, data }) \u2014 HTTP ${r}`);return s.data}async function Se(e){let t=Ae(e.baseUrl),r=e.accessPolicy??"private",s=e.manifest.name,n;try{n=await fetch(`${t}${A}/publisher/items`,{method:"POST",headers:{Authorization:`Bearer ${e.accessToken}`,"Content-Type":"application/json"},body:JSON.stringify({slug:s,displayName:s,description:e.manifest.description,type:"template",version:e.manifest.version,accessPolicy:r})});}catch(o){throw new Error(`publish: submit \uC694\uCCAD\uC774 \uC2E4\uD328\uD588\uC2B5\uB2C8\uB2E4 (\uB124\uD2B8\uC6CC\uD06C) \u2014 ${o instanceof Error?o.message:String(o)}`)}let i;if(n.status===ye)i="created";else if(n.status===be)i="existing";else {if(n.status===I)throw new Error("publish: \uC778\uC99D\uC774 \uB9CC\uB8CC\uB418\uC5C8\uAC70\uB098 \uC5C6\uC2B5\uB2C8\uB2E4 \u2014 \uB2E4\uC2DC \uB85C\uADF8\uC778\uD558\uC138\uC694");{let o=await v(n);throw new Error(`publish: submit \uC2E4\uD328 \u2014 HTTP ${n.status}${b(o)?` ${b(o)}`:""}`)}}let a="not-needed",m=null;if(i==="existing"){let o;try{o=await fetch(`${t}${A}/publisher/items`,{method:"GET",headers:{Authorization:`Bearer ${e.accessToken}`}});}catch(f){throw new Error(`publish: version \uC870\uD68C \uC694\uCCAD\uC774 \uC2E4\uD328\uD588\uC2B5\uB2C8\uB2E4 (\uB124\uD2B8\uC6CC\uD06C) \u2014 ${f instanceof Error?f.message:String(f)}`)}let M=await v(o);if(o.status!==200)throw new Error(`publish: publisher items \uC870\uD68C \uC2E4\uD328 \u2014 HTTP ${o.status}${b(M)?` ${b(M)}`:""}`);let H=ee(M,"publisher items",o.status)?.items;if(!Array.isArray(H))throw new Error(`publish: publisher items response malformed (expected data.items[]) \u2014 HTTP ${o.status}`);let $=H.find(f=>!f||typeof f!="object"?false:f.slug===s);if(!$||typeof $.version!="string")throw new Error(`publish: publisher items response does not contain slug "${s}" \u2014 HTTP ${o.status}`);if(m=$.version,m!==e.manifest.version){let f;try{f=await fetch(`${t}${A}/publisher/items/${encodeURIComponent(s)}`,{method:"PUT",headers:{Authorization:`Bearer ${e.accessToken}`,"Content-Type":"application/json"},body:JSON.stringify({version:e.manifest.version})});}catch(x){throw new Error(`publish: version update \uC694\uCCAD\uC774 \uC2E4\uD328\uD588\uC2B5\uB2C8\uB2E4 (\uB124\uD2B8\uC6CC\uD06C) \u2014 ${x instanceof Error?x.message:String(x)}`)}if(!f.ok){let x=await v(f),w=b(x);throw f.status===I?new Error(`publish: version update \uC778\uC99D\uC774 \uB9CC\uB8CC\uB418\uC5C8\uAC70\uB098 \uC5C6\uC2B5\uB2C8\uB2E4 \u2014 \uB2E4\uC2DC \uB85C\uADF8\uC778\uD558\uC138\uC694 (HTTP ${f.status})${w?` ${w}`:""}`):f.status===403?new Error(`publish: version update \uAD8C\uD55C\uC774 \uC5C6\uC2B5\uB2C8\uB2E4 \u2014 \uAE30\uC874 \uD56D\uBAA9\uC758 \uC18C\uC720\uC790\uB9CC \uBC84\uC804\uC744 \uAC31\uC2E0\uD560 \uC218 \uC788\uC2B5\uB2C8\uB2E4 (HTTP ${f.status})${w?` ${w}`:""}`):new Error(`publish: version update \uC2E4\uD328 \u2014 HTTP ${f.status}${w?` ${w}`:""}`)}a="applied";}}let c=d__namespace.readFileSync(e.tgzPath),u=we()?Ee(c):c,l=new FormData;l.set("archive",new Blob([new Uint8Array(u)],{type:"application/gzip"}),`${s}-${e.manifest.version}.tgz`);let p;try{p=await fetch(`${t}${A}/publisher/items/${encodeURIComponent(s)}/upload`,{method:"POST",headers:{Authorization:`Bearer ${e.accessToken}`},body:l});}catch(o){throw new Error(`publish: upload \uC694\uCCAD\uC774 \uC2E4\uD328\uD588\uC2B5\uB2C8\uB2E4 (\uB124\uD2B8\uC6CC\uD06C) \u2014 ${o instanceof Error?o.message:String(o)}`)}if(p.status===I)throw new Error("publish: \uC778\uC99D\uC774 \uB9CC\uB8CC\uB418\uC5C8\uAC70\uB098 \uC5C6\uC2B5\uB2C8\uB2E4 \u2014 \uB2E4\uC2DC \uB85C\uADF8\uC778\uD558\uC138\uC694");if(!p.ok){let o=await v(p);throw new Error(`publish: upload \uC2E4\uD328 \u2014 HTTP ${p.status}${b(o)?` ${b(o)}`:""}`)}let C=await v(p),F=ee(C,"upload",p.status);return {slug:s,version:e.manifest.version,artifactChecksum:F.artifactChecksum,artifactSizeBytes:F.artifactSizeBytes,submitOutcome:i,versionUpdate:a,serverVersionBefore:m}}function ne(){if(process.env.CREWX_HOME)try{return d__namespace.realpathSync(process.env.CREWX_HOME)}catch{return y__namespace.join(O__namespace.homedir(),".crewx")}return process.platform!=="win32"&&process.env.XDG_CONFIG_HOME?y__namespace.join(process.env.XDG_CONFIG_HOME,"crewx"):y__namespace.join(O__namespace.homedir(),".crewx")}var g=class extends Error{code;constructor(t,r){super(r),this.name="AccountAuthBoundaryError",this.code=t;}};function N(e=process.env){let t=e.CREWX_ACCOUNT_ISSUER?.trim(),r=e.CREWX_ACCOUNT_ANON_KEY?.trim();if(!t&&!r)throw new g("ACCOUNT_USER_PAIR_MISSING","CrewX user-realm issuer and anon/publishable key pair are not configured");if(!t)throw new g("ACCOUNT_USER_ISSUER_MISSING","CrewX user-realm issuer is not configured");if(!r)throw new g("ACCOUNT_USER_ANON_KEY_MISSING","CrewX user-realm anon/publishable key is not configured");return {issuer:t,anonKey:r}}function S(){throw new g("ACCOUNT_ACCESS_TOKEN_INVALID","Account access token could not be verified")}function se(e){try{return JSON.parse(Buffer.from(e,"base64url").toString("utf8"))}catch{return S()}}function ie(e){if(typeof e!="string")return S();let t=e.split(".");if(t.length!==3||t.some(i=>i.length===0))return S();let r=se(t[0]),s=se(t[1]);if(!r||typeof r!="object"||!s||typeof s!="object")return S();let n=s;return typeof n.iss!="string"||n.iss.length===0||typeof n.sub!="string"||n.sub.length===0?S():{issuer:n.iss,sub:n.sub}}function oe(e,t,r){let s=ie(e);if(s.issuer!==t.issuer)throw new g("ACCOUNT_TOKEN_ISSUER_MISMATCH","Account access token does not match the configured user realm");if(r!==void 0&&s.sub!==r)throw new g("ACCOUNT_TOKEN_SUB_MISMATCH","Account access token subject does not match the expected identity");return s}function j(e,t){if(e.issuer!==t.issuer)throw new g("ACCOUNT_AUTH_JSON_ISSUER_MISMATCH","auth.json does not match the configured user realm");let r=oe(e.access_token,t);if(r.sub!==e.sub)throw new g("ACCOUNT_AUTH_JSON_SUB_MISMATCH","auth.json subject does not match the access token identity");return r}function ve(e){if(!e||typeof e!="object")return false;let t=e;return t.version===1&&typeof t.sub=="string"&&typeof t.email=="string"&&typeof t.access_token=="string"&&typeof t.refresh_token=="string"&&typeof t.expires_at=="number"&&typeof t.issuer=="string"&&typeof t.updated_at=="string"}function Ce(){let e=y.join(ne(),"auth.json");if(!d.existsSync(e))throw new Error(`Login required \u2014 ${e} was not found (please log in first)`);let t;try{t=d.readFileSync(e,"utf8");}catch(n){throw new Error(`Could not read auth.json (${e}): ${n instanceof Error?n.message:String(n)}`)}let r;try{r=JSON.parse(t);}catch(n){throw new Error(`Failed to parse auth.json (${e}): ${n instanceof Error?n.message:String(n)}`)}if(!ve(r))throw new Error(`auth.json is malformed (${e}) \u2014 please log in again`);let s=N();return j(r,s),r}async function Pe(e,t={}){let r=y__namespace.resolve(e),{included:s,excluded:n}=J(r),i=W(r,s,{version:t.version}),a=V(r,s);return {manifest:i,included:s,excluded:n,secretFindings:a}}async function pt(e,t={}){let r=await Pe(e,t);if(r.secretFindings.length>0){let i=r.secretFindings.map(a=>`${a.path}:${a.line} (${a.rule})`).join(", ");throw new Error(`publish: aborted \u2014 secret findings must be resolved before packing: ${i}`)}let s=y__namespace.resolve(e),n=await Q(s,r.manifest);return {manifest:r.manifest,tgzPath:n}}exports.AccountAuthBoundaryError=g;exports.EXCLUDE_RULES=z;exports.MARKETPLACE_API_PREFIX=A;exports.assertAuthJsonUserRealm=j;exports.assertUserRealmAccessToken=oe;exports.decodeAccessTokenIdentity=ie;exports.packTemplate=pt;exports.planPublish=Pe;exports.readAuthJson=Ce;exports.resolveUserAccountConfig=N;exports.uploadToMarketplace=Se;
1
+ 'use strict';var y=require('path'),h=require('fs'),X=require('crypto'),W=require('js-yaml'),I=require('os'),Y=require('tar'),zlib=require('zlib');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 y__namespace=/*#__PURE__*/_interopNamespace(y);var h__namespace=/*#__PURE__*/_interopNamespace(h);var X__namespace=/*#__PURE__*/_interopNamespace(X);var W__namespace=/*#__PURE__*/_interopNamespace(W);var I__namespace=/*#__PURE__*/_interopNamespace(I);var Y__namespace=/*#__PURE__*/_interopNamespace(Y);function ae(e){let t=n=>n.replace(/[.+^${}()|[\]\\]/g,"\\$&"),s=e.split("/").map(n=>n==="**"?".*":n.split("*").map(t).join("[^/]*"));return new RegExp(`^${s.join("\\/")}$`)}function w(e,t){try{return ae(t).test(e)}catch{return false}}function C(e,...t){let r=e.split("/");if(r.length<t.length)return false;let s=r.length-t.length;return t.every((n,i)=>w(r[s+i],n))}function ce(e,t){return e.split("/").some(r=>w(r,t))}var D=[{label:".env*",test:e=>w(e,".env*")},{label:".git/",test:(e,t,r)=>r&&e===".git"},{label:"memory/",test:(e,t,r)=>r&&e==="memory"},{label:"*.key",test:e=>w(e,"*.key")},{label:"*.pem",test:e=>w(e,"*.pem")},{label:"auth.json",test:e=>e==="auth.json"},{label:"node_modules/",test:(e,t,r)=>r&&e==="node_modules"},{label:"conversations/",test:(e,t,r)=>r&&e==="conversations"},{label:".crewx/threads/",test:(e,t,r)=>r&&C(t,".crewx","threads")},{label:".crewx/crewx.db",test:(e,t,r)=>!r&&C(t,".crewx","crewx.db")},{label:".crewx/*.log",test:(e,t,r)=>!r&&C(t,".crewx","*.log")},{label:".crewx/publish/",test:(e,t,r)=>r&&C(t,".crewx","publish")},{label:".crewx/",test:(e,t)=>ce(t,".crewx")}];function v(e,t,r){for(let s of D)if(s.test(e,t,r))return s.label;return null}function J(e){let t=[],r=[];function s(n,i,a){let d;try{d=h__namespace.readdirSync(n,{withFileTypes:!0});}catch{return}d.sort((c,u)=>c.name.localeCompare(u.name));for(let c of d){let u=i?`${i}/${c.name}`:c.name,l=y__namespace.join(n,c.name);if(c.isSymbolicLink()){let p;try{p=h__namespace.statSync(l);}catch{continue}if(p.isDirectory()){r.push({path:u,rule:a??"symlink-dir"});continue}let U=a??v(c.name,u,false);U?r.push({path:u,rule:U}):t.push(u);continue}if(c.isDirectory()){let p=a??v(c.name,u,true);s(l,u,p);continue}if(c.isFile()){let p=a??v(c.name,u,false);p?r.push({path:u,rule:p}):t.push(u);}}}return s(e,"",null),t.sort(),r.sort((n,i)=>n.path<i.path?-1:n.path>i.path?1:0),{included:t,excluded:r}}var ue=[{rule:"token-prefix",regex:/\b(?:sk-|ghp_|xoxb-)[A-Za-z0-9_-]{10,}/},{rule:"private-key",regex:/-----BEGIN [A-Z ]*PRIVATE KEY-----/},{rule:"aws-access-key",regex:/\bAKIA[0-9A-Z]{16}\b/}];function le(e){return e.includes(0)}function L(e,t){let r=[];for(let s of t){let n=y__namespace.join(e,s),i;try{i=h__namespace.readFileSync(n);}catch{continue}if(le(i))continue;i.toString("utf8").split(/\r\n|\r|\n/).forEach((d,c)=>{for(let{rule:u,regex:l}of ue)l.test(d)&&r.push({path:s,line:c+1,rule:u});});}return r}var V=/^[a-z0-9-]+$/,pe=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/,fe=/^[A-Za-z_][A-Za-z0-9_]*$/;function de(e){let t=y__namespace.join(e,"crewx.yaml");if(!h__namespace.existsSync(t))return {};let r;try{r=W__namespace.load(h__namespace.readFileSync(t,"utf8"));}catch{return {}}if(!r||typeof r!="object")return {};let s=r.metadata;if(!s||typeof s!="object")return {};let n=s;return {name:typeof n.name=="string"?n.name:void 0,version:typeof n.version=="string"?n.version:void 0,description:typeof n.description=="string"?n.description:void 0,requiredEnv:n.requiredEnv,crewxMinVersion:typeof n.crewxMinVersion=="string"?n.crewxMinVersion:void 0}}function me(e){return X__namespace.createHash("sha256").update(new Uint8Array(h__namespace.readFileSync(e))).digest("hex")}function G(e,t,r={}){let s=de(e),n=s.name??y__namespace.basename(e);if(!V.test(n))throw new Error(`publish: invalid name "${n}" \u2014 must match ${V} (lowercase letters, numbers, hyphen only)`);let i=r.version??s.version;if(!i)throw new Error("publish: version is required \u2014 set crewx.yaml metadata.version or pass opts.version");if(!pe.test(i))throw new Error(`publish: invalid version "${i}" \u2014 must be semver (e.g. 1.0.0)`);let a=Array.isArray(s.requiredEnv)?s.requiredEnv:[],d=[];for(let l of a){if(typeof l!="string"||!fe.test(l))throw new Error(`publish: requiredEnv must contain names only (no values), got "${String(l)}"`);d.push(l);}let c=t.map(l=>({path:l,sha256:me(y__namespace.join(e,l))})).sort((l,p)=>l.path<p.path?-1:l.path>p.path?1:0),u={name:n,version:i,type:"template",description:s.description??"",files:c,requiredEnv:d};return s.crewxMinVersion&&(u.crewxMinVersion=s.crewxMinVersion),u}async function Q(e,t){let r=y__namespace.join(e,".crewx","publish");h__namespace.mkdirSync(r,{recursive:true});let s=y__namespace.join(r,`${t.name}-${t.version}.tgz`),n=h__namespace.mkdtempSync(y__namespace.join(I__namespace.tmpdir(),"crewx-publish-"));try{h__namespace.writeFileSync(y__namespace.join(n,"manifest.json"),JSON.stringify(t,null,2));for(let i of t.files){let a=y__namespace.join(n,i.path);h__namespace.mkdirSync(y__namespace.dirname(a),{recursive:!0}),h__namespace.copyFileSync(y__namespace.join(e,i.path),a);}await Y__namespace.create({gzip:!0,file:s,cwd:n,portable:!0,noMtime:!0},["manifest.json",...t.files.map(i=>i.path)]);}finally{h__namespace.rmSync(n,{recursive:true,force:true});}return s}var A="/api/v1";var ye=201,Ee=409,$=401;function be(){return process.env.WI013_FAKE_UPLOAD==="1"}function we(e){let t=zlib.gunzipSync(new Uint8Array(e)),r=zlib.gzipSync(new Uint8Array(t),{level:1});if(Buffer.compare(new Uint8Array(r),new Uint8Array(e))===0)throw new Error("publish: [E_MALFORMED] Re-gzipped upload bytes are identical to the original \u2014 tamper is a no-op");return r}function Ae(e){return e.replace(/\/+$/,"")}async function P(e){try{return await e.json()}catch{return null}}function E(e){let t=e?.message;return typeof t=="string"?t:void 0}function ee(e,t,r){let s=e;if(!s||s.success!==true||s.data===void 0)throw new Error(`publish: [E_MALFORMED] ${t} response envelope is malformed (expected { success: true, data }) \u2014 HTTP ${r}`);return s.data}async function _e(e){let t=Ae(e.baseUrl),r=e.accessPolicy??"private",s=e.manifest.name,n;try{n=await fetch(`${t}${A}/publisher/items`,{method:"POST",headers:{Authorization:`Bearer ${e.accessToken}`,"Content-Type":"application/json"},body:JSON.stringify({slug:s,displayName:s,description:e.manifest.description,type:"template",version:e.manifest.version,accessPolicy:r})});}catch(o){throw new Error(`publish: [E_NETWORK] Submit request failed (network) \u2014 ${o instanceof Error?o.message:String(o)}`)}let i;if(n.status===ye)i="created";else if(n.status===Ee)i="existing";else {if(n.status===$)throw new Error("publish: [E_AUTH_EXPIRED] Authentication is expired or missing \u2014 please log in again (HTTP 401)");{let o=await P(n);throw new Error(`publish: [E_HTTP] Submit request failed \u2014 HTTP ${n.status}${E(o)?` ${E(o)}`:""}`)}}let a="not-needed",d=null;if(i==="existing"){let o;try{o=await fetch(`${t}${A}/publisher/items`,{method:"GET",headers:{Authorization:`Bearer ${e.accessToken}`}});}catch(f){throw new Error(`publish: [E_NETWORK] Publisher items request failed (network) \u2014 ${f instanceof Error?f.message:String(f)}`)}let M=await P(o);if(o.status!==200)throw new Error(`publish: [E_HTTP] Publisher items request failed \u2014 HTTP ${o.status}${E(M)?` ${E(M)}`:""}`);let B=ee(M,"publisher items",o.status)?.items;if(!Array.isArray(B))throw new Error(`publish: [E_MALFORMED] Publisher items response is malformed (expected data.items[]) \u2014 HTTP ${o.status}`);let O=B.find(f=>!f||typeof f!="object"?false:f.slug===s);if(!O||typeof O.version!="string")throw new Error(`publish: [E_MALFORMED] Publisher items response does not contain slug "${s}" \u2014 HTTP ${o.status}`);if(d=O.version,d!==e.manifest.version){let f;try{f=await fetch(`${t}${A}/publisher/items/${encodeURIComponent(s)}`,{method:"PUT",headers:{Authorization:`Bearer ${e.accessToken}`,"Content-Type":"application/json"},body:JSON.stringify({version:e.manifest.version})});}catch(T){throw new Error(`publish: [E_NETWORK] Version update request failed (network) \u2014 ${T instanceof Error?T.message:String(T)}`)}if(!f.ok){let T=await P(f),b=E(T);throw f.status===$?new Error(`publish: [E_AUTH_EXPIRED] Authentication is expired or missing \u2014 please log in again (HTTP ${f.status})${b?` ${b}`:""}`):f.status===403?new Error(`publish: [E_FORBIDDEN] Version update is forbidden; only the item owner can update an existing item (HTTP ${f.status})${b?` ${b}`:""}`):new Error(`publish: [E_HTTP] Version update failed \u2014 HTTP ${f.status}${b?` ${b}`:""}`)}a="applied";}}let c=h__namespace.readFileSync(e.tgzPath),u=be()?we(c):c,l=new FormData;l.set("archive",new Blob([new Uint8Array(u)],{type:"application/gzip"}),`${s}-${e.manifest.version}.tgz`);let p;try{p=await fetch(`${t}${A}/publisher/items/${encodeURIComponent(s)}/upload`,{method:"POST",headers:{Authorization:`Bearer ${e.accessToken}`},body:l});}catch(o){throw new Error(`publish: [E_NETWORK] Upload request failed (network) \u2014 ${o instanceof Error?o.message:String(o)}`)}if(p.status===$)throw new Error("publish: [E_AUTH_EXPIRED] Authentication is expired or missing \u2014 please log in again (HTTP 401)");if(!p.ok){let o=await P(p);throw new Error(`publish: [E_HTTP] Upload request failed \u2014 HTTP ${p.status}${E(o)?` ${E(o)}`:""}`)}let U=await P(p),j=ee(U,"upload",p.status);return {slug:s,version:e.manifest.version,artifactChecksum:j.artifactChecksum,artifactSizeBytes:j.artifactSizeBytes,submitOutcome:i,versionUpdate:a,serverVersionBefore:d}}function ne(){if(process.env.CREWX_HOME)try{return h__namespace.realpathSync(process.env.CREWX_HOME)}catch{return y__namespace.join(I__namespace.homedir(),".crewx")}return process.platform!=="win32"&&process.env.XDG_CONFIG_HOME?y__namespace.join(process.env.XDG_CONFIG_HOME,"crewx"):y__namespace.join(I__namespace.homedir(),".crewx")}var g=class extends Error{code;constructor(t,r){super(r),this.name="AccountAuthBoundaryError",this.code=t;}};function N(e=process.env){let t=e.CREWX_ACCOUNT_ISSUER?.trim(),r=e.CREWX_ACCOUNT_ANON_KEY?.trim();if(!t&&!r)throw new g("ACCOUNT_USER_PAIR_MISSING","CrewX user-realm issuer and anon/publishable key pair are not configured");if(!t)throw new g("ACCOUNT_USER_ISSUER_MISSING","CrewX user-realm issuer is not configured");if(!r)throw new g("ACCOUNT_USER_ANON_KEY_MISSING","CrewX user-realm anon/publishable key is not configured");return {issuer:t,anonKey:r}}function _(){throw new g("ACCOUNT_ACCESS_TOKEN_INVALID","Account access token could not be verified")}function se(e){try{return JSON.parse(Buffer.from(e,"base64url").toString("utf8"))}catch{return _()}}function ie(e){if(typeof e!="string")return _();let t=e.split(".");if(t.length!==3||t.some(i=>i.length===0))return _();let r=se(t[0]),s=se(t[1]);if(!r||typeof r!="object"||!s||typeof s!="object")return _();let n=s;return typeof n.iss!="string"||n.iss.length===0||typeof n.sub!="string"||n.sub.length===0?_():{issuer:n.iss,sub:n.sub}}function oe(e,t,r){let s=ie(e);if(s.issuer!==t.issuer)throw new g("ACCOUNT_TOKEN_ISSUER_MISMATCH","Account access token does not match the configured user realm");if(r!==void 0&&s.sub!==r)throw new g("ACCOUNT_TOKEN_SUB_MISMATCH","Account access token subject does not match the expected identity");return s}function H(e,t){if(e.issuer!==t.issuer)throw new g("ACCOUNT_AUTH_JSON_ISSUER_MISMATCH","auth.json does not match the configured user realm");let r=oe(e.access_token,t);if(r.sub!==e.sub)throw new g("ACCOUNT_AUTH_JSON_SUB_MISMATCH","auth.json subject does not match the access token identity");return r}function Pe(e){if(!e||typeof e!="object")return false;let t=e;return t.version===1&&typeof t.sub=="string"&&typeof t.email=="string"&&typeof t.access_token=="string"&&typeof t.refresh_token=="string"&&typeof t.expires_at=="number"&&typeof t.issuer=="string"&&typeof t.updated_at=="string"}function Ue(){let e=y.join(ne(),"auth.json");if(!h.existsSync(e))throw new Error(`Login required \u2014 ${e} was not found (please log in first)`);let t;try{t=h.readFileSync(e,"utf8");}catch(n){throw new Error(`Could not read auth.json (${e}): ${n instanceof Error?n.message:String(n)}`)}let r;try{r=JSON.parse(t);}catch(n){throw new Error(`Failed to parse auth.json (${e}): ${n instanceof Error?n.message:String(n)}`)}if(!Pe(r))throw new Error(`auth.json is malformed (${e}) \u2014 please log in again`);let s=N();return H(r,s),r}async function Ce(e,t={}){let r=y__namespace.resolve(e),{included:s,excluded:n}=J(r),i=G(r,s,{version:t.version}),a=L(r,s);return {manifest:i,included:s,excluded:n,secretFindings:a}}async function pt(e,t={}){let r=await Ce(e,t);if(r.secretFindings.length>0){let i=r.secretFindings.map(a=>`${a.path}:${a.line} (${a.rule})`).join(", ");throw new Error(`publish: aborted \u2014 secret findings must be resolved before packing: ${i}`)}let s=y__namespace.resolve(e),n=await Q(s,r.manifest);return {manifest:r.manifest,tgzPath:n}}exports.AccountAuthBoundaryError=g;exports.EXCLUDE_RULES=D;exports.MARKETPLACE_API_PREFIX=A;exports.assertAuthJsonUserRealm=H;exports.assertUserRealmAccessToken=oe;exports.decodeAccessTokenIdentity=ie;exports.packTemplate=pt;exports.planPublish=Ce;exports.readAuthJson=Ue;exports.resolveUserAccountConfig=N;exports.uploadToMarketplace=_e;
@@ -1,14 +1,14 @@
1
- 'use strict';var me=require('fs'),Q=require('path'),Ye=require('os'),drizzleOrm=require('drizzle-orm'),crypto=require('crypto'),sqliteCore=require('drizzle-orm/sqlite-core');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var me__default=/*#__PURE__*/_interopDefault(me);var Q__namespace=/*#__PURE__*/_interopNamespace(Q);var Ye__default=/*#__PURE__*/_interopDefault(Ye);var xt=(a=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(a,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):a)(function(a){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+a+'" is not supported')});var x=class{resolveDbPath(){return process.env.CREWX_DB?process.env.CREWX_DB:process.env.CREWX_TRACES_DB?process.env.CREWX_TRACES_DB:Q.join(Ye__default.default.homedir(),".crewx","crewx.db")}resolveDbPaths(){return [this.resolveDbPath()]}isMissingTableError(t){return t instanceof Error&&/no such table:/i.test(t.message)}dbExists(t){return me.existsSync(t??this.resolveDbPath())}};var d=class extends Error{code;cause;constructor(t,n,e){super(n),this.name="RepositoryError",this.code=t,this.cause=e,Object.setPrototypeOf(this,new.target.prototype);}};function w(a){let t=xt("better-sqlite3"),{drizzle:n}=xt("drizzle-orm/better-sqlite3"),e=new t(a);return e.exec("PRAGMA journal_mode = WAL"),e.exec("PRAGMA busy_timeout = 5000"),e.exec("PRAGMA foreign_keys = ON"),e.exec("PRAGMA analysis_limit = 400"),e.exec("PRAGMA optimize"),{db:n(e),runRaw:(r,s=[])=>e.prepare(r).run(...s),close:()=>e.close()}}var re=new Set,Xe={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"};function $t(a,t){return (a.get(`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='${t}'`)?.cnt??0)>0}function Je(a,t){if(t>0||!$t(a,"tasks"))return;let n=a.all("PRAGMA table_info(tasks)"),e=new Set(n.map(r=>r.name));for(let[r,s]of Object.entries(Xe))e.has(r)||a.run(`ALTER TABLE tasks ADD COLUMN ${r} ${s}`);}var Ve={"0002_normalize_task_names":{workspace_name:"TEXT",project_name:"TEXT"}};function Qe(a,t,n){if(!$t(a,"__drizzle_migrations")||!$t(a,"tasks"))return;let e=a.all(n`SELECT hash FROM __drizzle_migrations`),r=new Set(e.map(i=>i.hash)),s=JSON.parse(me.readFileSync(Q__namespace.default.join(t,"meta/_journal.json"),"utf-8"));for(let i of s.entries){let l=Ve[i.tag];if(!l)continue;let u=Q__namespace.default.join(t,`${i.tag}.sql`);if(!me.existsSync(u))continue;let c=me.readFileSync(u,"utf-8"),p=crypto.createHash("sha256").update(c).digest("hex");if(r.has(p))continue;let f=a.all("PRAGMA table_info(tasks)"),h=new Set(f.map(S=>S.name));for(let[S,P]of Object.entries(l))h.has(S)||(a.run(`ALTER TABLE tasks ADD COLUMN ${S} ${P}`),h.add(S));}}function Ze(a,t,n){let e=a.all(n`SELECT hash FROM __drizzle_migrations`),r=new Set(e.map(i=>i.hash)),s=JSON.parse(me.readFileSync(Q__namespace.default.join(t,"meta/_journal.json"),"utf-8"));for(let i of s.entries){let l=Q__namespace.default.join(t,`${i.tag}.sql`);if(!me.existsSync(l))continue;let u=me.readFileSync(l,"utf-8"),c=crypto.createHash("sha256").update(u).digest("hex");if(r.has(c))continue;let p=/ALTER\s+TABLE\s+[`"]?(\w+)[`"]?\s+ADD\s+[`"]?(\w+)[`"]?/gi,f=[],h;for(;(h=p.exec(u))!==null;)f.push({table:h[1],column:h[2]});if(f.length===0||!u.split(/-->\s*statement-breakpoint/).map($=>$.trim()).filter(Boolean).every($=>/^ALTER\s+TABLE\s+.+\s+ADD\s+/i.test($)))continue;f.every(({table:$,column:H})=>a.all(`PRAGMA table_info("${$}")`).some(G=>G.name===H))&&a.run(n`INSERT INTO __drizzle_migrations (hash, created_at) VALUES (${c}, ${i.when})`);}}function ft(a){let{migrate:t}=xt("drizzle-orm/better-sqlite3/migrator"),{sql:n}=xt("drizzle-orm"),e=[Q__namespace.default.join(__dirname,"../migrations"),Q__namespace.default.join(__dirname,"migrations"),Q__namespace.default.join(__dirname,"../../../../drizzle/migrations"),Q__namespace.default.join(process.cwd(),"drizzle/migrations")],r=e.find(c=>me.existsSync(Q__namespace.default.join(c,"meta/_journal.json")));if(!r)throw new Error(`migrations folder not found. Searched:
1
+ 'use strict';var ge=require('fs'),Q=require('path'),Ye=require('os'),drizzleOrm=require('drizzle-orm'),crypto=require('crypto'),sqliteCore=require('drizzle-orm/sqlite-core');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var ge__default=/*#__PURE__*/_interopDefault(ge);var Q__namespace=/*#__PURE__*/_interopNamespace(Q);var Ye__default=/*#__PURE__*/_interopDefault(Ye);var xt=(a=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(a,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):a)(function(a){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+a+'" is not supported')});var x=class{resolveDbPath(){return process.env.CREWX_DB?process.env.CREWX_DB:process.env.CREWX_TRACES_DB?process.env.CREWX_TRACES_DB:Q.join(Ye__default.default.homedir(),".crewx","crewx.db")}resolveDbPaths(){return [this.resolveDbPath()]}isMissingTableError(t){return t instanceof Error&&/no such table:/i.test(t.message)}dbExists(t){return ge.existsSync(t??this.resolveDbPath())}};var d=class extends Error{code;cause;constructor(t,n,e){super(n),this.name="RepositoryError",this.code=t,this.cause=e,Object.setPrototypeOf(this,new.target.prototype);}};function w(a){let t=xt("better-sqlite3"),{drizzle:n}=xt("drizzle-orm/better-sqlite3"),e=new t(a);return e.exec("PRAGMA journal_mode = WAL"),e.exec("PRAGMA busy_timeout = 5000"),e.exec("PRAGMA foreign_keys = ON"),e.exec("PRAGMA analysis_limit = 400"),e.exec("PRAGMA optimize"),{db:n(e),runRaw:(r,s=[])=>e.prepare(r).run(...s),close:()=>e.close()}}var re=new Set,Xe={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"};function $t(a,t){return (a.get(`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='${t}'`)?.cnt??0)>0}function Je(a,t){if(t>0||!$t(a,"tasks"))return;let n=a.all("PRAGMA table_info(tasks)"),e=new Set(n.map(r=>r.name));for(let[r,s]of Object.entries(Xe))e.has(r)||a.run(`ALTER TABLE tasks ADD COLUMN ${r} ${s}`);}var Ve={"0002_normalize_task_names":{workspace_name:"TEXT",project_name:"TEXT"}};function Qe(a,t,n){if(!$t(a,"__drizzle_migrations")||!$t(a,"tasks"))return;let e=a.all(n`SELECT hash FROM __drizzle_migrations`),r=new Set(e.map(i=>i.hash)),s=JSON.parse(ge.readFileSync(Q__namespace.default.join(t,"meta/_journal.json"),"utf-8"));for(let i of s.entries){let l=Ve[i.tag];if(!l)continue;let u=Q__namespace.default.join(t,`${i.tag}.sql`);if(!ge.existsSync(u))continue;let c=ge.readFileSync(u,"utf-8"),p=crypto.createHash("sha256").update(c).digest("hex");if(r.has(p))continue;let f=a.all("PRAGMA table_info(tasks)"),h=new Set(f.map(S=>S.name));for(let[S,v]of Object.entries(l))h.has(S)||(a.run(`ALTER TABLE tasks ADD COLUMN ${S} ${v}`),h.add(S));}}function Ze(a,t,n){let e=a.all(n`SELECT hash FROM __drizzle_migrations`),r=new Set(e.map(i=>i.hash)),s=JSON.parse(ge.readFileSync(Q__namespace.default.join(t,"meta/_journal.json"),"utf-8"));for(let i of s.entries){let l=Q__namespace.default.join(t,`${i.tag}.sql`);if(!ge.existsSync(l))continue;let u=ge.readFileSync(l,"utf-8"),c=crypto.createHash("sha256").update(u).digest("hex");if(r.has(c))continue;let p=/ALTER\s+TABLE\s+[`"]?(\w+)[`"]?\s+ADD\s+[`"]?(\w+)[`"]?/gi,f=[],h;for(;(h=p.exec(u))!==null;)f.push({table:h[1],column:h[2]});if(f.length===0||!u.split(/-->\s*statement-breakpoint/).map($=>$.trim()).filter(Boolean).every($=>/^ALTER\s+TABLE\s+.+\s+ADD\s+/i.test($)))continue;f.every(({table:$,column:M})=>a.all(`PRAGMA table_info("${$}")`).some(G=>G.name===M))&&a.run(n`INSERT INTO __drizzle_migrations (hash, created_at) VALUES (${c}, ${i.when})`);}}function ft(a){let{migrate:t}=xt("drizzle-orm/better-sqlite3/migrator"),{sql:n}=xt("drizzle-orm"),e=[Q__namespace.default.join(__dirname,"../migrations"),Q__namespace.default.join(__dirname,"migrations"),Q__namespace.default.join(__dirname,"../../../../drizzle/migrations"),Q__namespace.default.join(process.cwd(),"drizzle/migrations")],r=e.find(c=>ge.existsSync(Q__namespace.default.join(c,"meta/_journal.json")));if(!r)throw new Error(`migrations folder not found. Searched:
2
2
  ${e.join(`
3
- `)}`);let s=a.get(n`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`),i=0;s?.cnt&&(i=a.get(n`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),Je(a,i),s?.cnt&&(Ze(a,r,n),Qe(a,r,n)),t(a,{migrationsFolder:r});let u=(a.get(n`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-i;if(u>0){let c=s?.cnt?"Database migrated":"Database initialized";console.error(`[crewx] ${c} (${u} migration${u>1?"s":""} applied).`);}}function A(a,t){re.has(t)||(ft(a),re.add(t));}var m=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()});var o=sqliteCore.sqliteTable("tasks",{id:sqliteCore.text("id").primaryKey(),agent_id:sqliteCore.text("agent_id").notNull(),user_id:sqliteCore.text("user_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"),rendered_prompt:sqliteCore.text("rendered_prompt"),command:sqliteCore.text("command"),coding_agent_command:sqliteCore.text("coding_agent_command"),exit_code:sqliteCore.integer("exit_code"),logs:sqliteCore.text("logs"),thread_id:sqliteCore.text("thread_id"),workspace_ref:sqliteCore.text("workspace_ref"),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)},a=>({idx_tasks_agent_id:sqliteCore.index("idx_tasks_agent_id").on(a.agent_id),idx_tasks_status:sqliteCore.index("idx_tasks_status").on(a.status),idx_tasks_started_at:sqliteCore.index("idx_tasks_started_at").on(a.started_at),idx_tasks_trace_id:sqliteCore.index("idx_tasks_trace_id").on(a.trace_id),idx_tasks_parent_task_id:sqliteCore.index("idx_tasks_parent_task_id").on(a.parent_task_id),idx_tasks_crewx_version:sqliteCore.index("idx_tasks_crewx_version").on(a.crewx_version),idx_tasks_pid:sqliteCore.index("idx_tasks_pid").on(a.pid),idx_tasks_thread_id:sqliteCore.index("idx_tasks_thread_id").on(a.thread_id),idx_tasks_workspace_id:sqliteCore.index("idx_tasks_workspace_id").on(a.workspace_id),idx_tasks_workspace_ref:sqliteCore.index("idx_tasks_workspace_ref").on(a.workspace_ref),idx_tasks_project_id:sqliteCore.index("idx_tasks_project_id").on(a.project_id),idx_tasks_ws_started:sqliteCore.index("idx_tasks_ws_started").on(a.workspace_id,a.started_at)}));var _=sqliteCore.sqliteTable("threads",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").references(()=>m.id,{onDelete:"set null"}),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)},a=>({idx_threads_updated_at:sqliteCore.index("idx_threads_updated_at").on(a.updated_at),idx_threads_workspace_id:sqliteCore.index("idx_threads_workspace_id").on(a.workspace_id),idx_threads_ws_updated:sqliteCore.index("idx_threads_ws_updated").on(a.workspace_id,a.updated_at),idx_threads_title:sqliteCore.index("idx_threads_title").on(a.title)}));var tt=sqliteCore.sqliteTable("spans",{id:sqliteCore.text("id").primaryKey(),task_id:sqliteCore.text("task_id").references(()=>o.id,{onDelete:"set null"}),parent_span_id:sqliteCore.text("parent_span_id").references(()=>tt.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")},a=>({idx_spans_task_id:sqliteCore.index("idx_spans_task_id").on(a.task_id),idx_spans_parent_span_id:sqliteCore.index("idx_spans_parent_span_id").on(a.parent_span_id)}));var J=sqliteCore.sqliteTable("tool_calls",{id:sqliteCore.text("id").primaryKey(),task_id:sqliteCore.text("task_id").references(()=>o.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()},a=>({idx_tool_calls_task_id:sqliteCore.index("idx_tool_calls_task_id").on(a.task_id),idx_tool_calls_tool_name:sqliteCore.index("idx_tool_calls_tool_name").on(a.tool_name),idx_tool_calls_timestamp:sqliteCore.index("idx_tool_calls_timestamp").on(a.timestamp)}));var j=sqliteCore.sqliteTable("thread_boxes",{id:sqliteCore.text("id").primaryKey(),thread_id:sqliteCore.text("thread_id").notNull().references(()=>_.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()},a=>({idx_thread_boxes_thread_id:sqliteCore.index("idx_thread_boxes_thread_id").on(a.thread_id),idx_thread_boxes_seq:sqliteCore.index("idx_thread_boxes_seq").on(a.thread_id,a.seq),uniq_thread_boxes_thread_seq:sqliteCore.unique().on(a.thread_id,a.seq)}));var ht=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")},a=>({idx_request_logs_timestamp:sqliteCore.index("idx_request_logs_timestamp").on(a.timestamp),idx_request_logs_path:sqliteCore.index("idx_request_logs_path").on(a.path),idx_request_logs_status_code:sqliteCore.index("idx_request_logs_status_code").on(a.status_code),idx_request_logs_partition_key:sqliteCore.index("idx_request_logs_partition_key").on(a.partition_key)}));var v=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")},a=>({uniq_usage_limit_snapshots_bucket:sqliteCore.uniqueIndex("uniq_usage_limit_snapshots_bucket").on(a.provider,a.account_ref,a.limit_window,a.bucket_start),idx_usage_limit_snapshots_window_bucket:sqliteCore.index("idx_usage_limit_snapshots_window_bucket").on(a.limit_window,a.bucket_start),idx_usage_limit_snapshots_provider_window_bucket:sqliteCore.index("idx_usage_limit_snapshots_provider_window_bucket").on(a.provider,a.limit_window,a.bucket_start)}));var M=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")},a=>({uniq_usage_reports_ws_month:sqliteCore.uniqueIndex("uniq_usage_reports_ws_month").on(a.workspace_id,a.month)}));var k=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")},a=>({idx_notifications_ws_created:sqliteCore.index("idx_notifications_ws_created").on(a.workspace_id,drizzleOrm.sql`${a.created_at} DESC`)})),C=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()},a=>({pk:sqliteCore.primaryKey({columns:[a.notification_id,a.user_id]})}));var R=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()},a=>({idx_agent_suggestions_ws_agent:sqliteCore.index("idx_agent_suggestions_ws_agent").on(a.workspace_id,a.agent_id),idx_agent_suggestions_ws_created:sqliteCore.index("idx_agent_suggestions_ws_created").on(a.workspace_id,a.created_at)}));function Ht(a){let t=Q__namespace.resolve(a);return process.platform==="win32"&&(t=t.replace(/\\/g,"/"),t=t.replace(/^([A-Z]):/,(n,e)=>`${e.toLowerCase()}:`)),t.length>1&&!/^[a-zA-Z]:\/$/.test(t)&&(t=t.replace(/\/+$/,"")),t}function _e(a){let t=Ht(a);return crypto.createHash("sha256").update(t).digest("hex")}function Ct(a){return a.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"")}var zt=class extends x{dbRoot;constructor(t={}){super(),this.dbRoot=t.dbRoot;}resolveDbPath(){return this.dbRoot?Q.join(this.dbRoot,".crewx","crewx.db"):super.resolveDbPath()}openHandle(t){let n=this.resolveDbPath();if(t){let r=Q.dirname(n);me.existsSync(r)||me.mkdirSync(r,{recursive:true});}else if(!me.existsSync(n))throw new d("NOT_FOUND","Database not found");let e=w(n);if(t)try{ft(e.db);}catch(r){throw e.close(),r}return e}resolveSlug(t,n,e){let r=Ct(Q.basename(e)),i=`${Ct(Q.basename(Q.dirname(e)))}-${r}`,l=[r,i];try{let u=c=>t.select({id:m.id}).from(m).where(drizzleOrm.and(drizzleOrm.eq(m.slug,c),drizzleOrm.ne(m.id,n))).limit(1).all().length>0;for(let c of l)if(!u(c))return c;for(let c=2;c<1e3;c+=1){let p=`${i}-${c}`;if(!u(p))return p}}catch{}return r}normalizeLegacySlugs(){if(!this.dbExists())return {updated:0,checked:0};let t=this.openHandle(true);try{let n=t.db.select({id:m.id,slug:m.slug}).from(m).all(),e=0;for(let r of n)if(r.slug.includes("/")){let s=Ct(r.slug.replace(/\//g,"-"));t.db.update(m).set({slug:s,updated_at:new Date().toISOString()}).where(drizzleOrm.eq(m.id,r.id)).run(),e+=1;}return {updated:e,checked:n.length}}catch(n){throw new d("DB_ERROR","Failed to normalize legacy slugs",n)}finally{t.close();}}ensureRow(t,n){let{id:e,slug:r,name:s,workspacePath:i}=n,l=new Date().toISOString();t.insert(m).values({id:e,slug:r,name:s,workspace_path:i,is_active:1,created_at:l,updated_at:l}).onConflictDoNothing().run(),t.update(m).set({workspace_path:i,updated_at:l}).where(drizzleOrm.and(drizzleOrm.eq(m.id,e),drizzleOrm.isNull(m.workspace_path))).run();}registerWorkspace(t){let n=Ht(t),e=this.openHandle(true);try{let r=_e(n),s=Q.basename(n),i=this.resolveSlug(e.db,r,n);return this.ensureRow(e.db,{id:r,slug:i,name:s,workspacePath:n}),{id:r,slug:i}}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to register workspace",r)}finally{e.close();}}listProjects(t){if(!this.dbExists())return {rows:[],total:0};let n=this.openHandle(false);try{let e=t.isActive!==void 0?drizzleOrm.eq(m.is_active,t.isActive?1:0):void 0,r=n.db.select({count:drizzleOrm.sql`count(*)`}).from(m).where(e).get();return {rows:n.db.select().from(m).where(e).orderBy(drizzleOrm.desc(m.updated_at)).limit(t.limit).offset(t.offset).all(),total:r?.count??0}}catch(e){throw new d("DB_ERROR","Failed to list projects",e)}finally{n.close();}}findById(t){if(!this.dbExists())return;let n=this.openHandle(false);try{return n.db.select().from(m).where(drizzleOrm.eq(m.id,t)).limit(1).get()??void 0}catch(e){throw new d("DB_ERROR","Failed to find workspace",e)}finally{n.close();}}findAgentsByProject(t){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.all(drizzleOrm.sql`SELECT DISTINCT agent_id FROM tasks WHERE workspace_id = ${t} AND agent_id IS NOT NULL ORDER BY agent_id`).map(r=>r.agent_id)}catch(e){throw new d("DB_ERROR","Failed to find agents by project",e)}finally{n.close();}}findThreadsByProject(t,n){if(!this.dbExists())return {rows:[],total:0};let e=this.openHandle(false);try{let r=e.db.get(drizzleOrm.sql`SELECT COUNT(*) as count FROM threads WHERE workspace_id = ${t}`);return {rows:e.db.all(drizzleOrm.sql`SELECT t.*,
3
+ `)}`);let s=a.get(n`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`),i=0;s?.cnt&&(i=a.get(n`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),Je(a,i),s?.cnt&&(Ze(a,r,n),Qe(a,r,n)),t(a,{migrationsFolder:r});let u=(a.get(n`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-i;if(u>0){let c=s?.cnt?"Database migrated":"Database initialized";console.error(`[crewx] ${c} (${u} migration${u>1?"s":""} applied).`);}}function N(a,t){re.has(t)||(ft(a),re.add(t));}var g=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()});var o=sqliteCore.sqliteTable("tasks",{id:sqliteCore.text("id").primaryKey(),agent_id:sqliteCore.text("agent_id").notNull(),user_id:sqliteCore.text("user_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"),rendered_prompt:sqliteCore.text("rendered_prompt"),command:sqliteCore.text("command"),coding_agent_command:sqliteCore.text("coding_agent_command"),exit_code:sqliteCore.integer("exit_code"),logs:sqliteCore.text("logs"),thread_id:sqliteCore.text("thread_id"),workspace_ref:sqliteCore.text("workspace_ref"),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)},a=>({idx_tasks_agent_id:sqliteCore.index("idx_tasks_agent_id").on(a.agent_id),idx_tasks_status:sqliteCore.index("idx_tasks_status").on(a.status),idx_tasks_started_at:sqliteCore.index("idx_tasks_started_at").on(a.started_at),idx_tasks_trace_id:sqliteCore.index("idx_tasks_trace_id").on(a.trace_id),idx_tasks_parent_task_id:sqliteCore.index("idx_tasks_parent_task_id").on(a.parent_task_id),idx_tasks_crewx_version:sqliteCore.index("idx_tasks_crewx_version").on(a.crewx_version),idx_tasks_pid:sqliteCore.index("idx_tasks_pid").on(a.pid),idx_tasks_thread_id:sqliteCore.index("idx_tasks_thread_id").on(a.thread_id),idx_tasks_workspace_id:sqliteCore.index("idx_tasks_workspace_id").on(a.workspace_id),idx_tasks_workspace_ref:sqliteCore.index("idx_tasks_workspace_ref").on(a.workspace_ref),idx_tasks_project_id:sqliteCore.index("idx_tasks_project_id").on(a.project_id),idx_tasks_ws_started:sqliteCore.index("idx_tasks_ws_started").on(a.workspace_id,a.started_at)}));var _=sqliteCore.sqliteTable("threads",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").references(()=>g.id,{onDelete:"set null"}),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)},a=>({idx_threads_updated_at:sqliteCore.index("idx_threads_updated_at").on(a.updated_at),idx_threads_workspace_id:sqliteCore.index("idx_threads_workspace_id").on(a.workspace_id),idx_threads_ws_updated:sqliteCore.index("idx_threads_ws_updated").on(a.workspace_id,a.updated_at),idx_threads_title:sqliteCore.index("idx_threads_title").on(a.title)}));var tt=sqliteCore.sqliteTable("spans",{id:sqliteCore.text("id").primaryKey(),task_id:sqliteCore.text("task_id").references(()=>o.id,{onDelete:"set null"}),parent_span_id:sqliteCore.text("parent_span_id").references(()=>tt.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")},a=>({idx_spans_task_id:sqliteCore.index("idx_spans_task_id").on(a.task_id),idx_spans_parent_span_id:sqliteCore.index("idx_spans_parent_span_id").on(a.parent_span_id)}));var J=sqliteCore.sqliteTable("tool_calls",{id:sqliteCore.text("id").primaryKey(),task_id:sqliteCore.text("task_id").references(()=>o.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()},a=>({idx_tool_calls_task_id:sqliteCore.index("idx_tool_calls_task_id").on(a.task_id),idx_tool_calls_tool_name:sqliteCore.index("idx_tool_calls_tool_name").on(a.tool_name),idx_tool_calls_timestamp:sqliteCore.index("idx_tool_calls_timestamp").on(a.timestamp)}));var j=sqliteCore.sqliteTable("thread_boxes",{id:sqliteCore.text("id").primaryKey(),thread_id:sqliteCore.text("thread_id").notNull().references(()=>_.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()},a=>({idx_thread_boxes_thread_id:sqliteCore.index("idx_thread_boxes_thread_id").on(a.thread_id),idx_thread_boxes_seq:sqliteCore.index("idx_thread_boxes_seq").on(a.thread_id,a.seq),uniq_thread_boxes_thread_seq:sqliteCore.unique().on(a.thread_id,a.seq)}));var ht=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")},a=>({idx_request_logs_timestamp:sqliteCore.index("idx_request_logs_timestamp").on(a.timestamp),idx_request_logs_path:sqliteCore.index("idx_request_logs_path").on(a.path),idx_request_logs_status_code:sqliteCore.index("idx_request_logs_status_code").on(a.status_code),idx_request_logs_partition_key:sqliteCore.index("idx_request_logs_partition_key").on(a.partition_key)}));var P=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")},a=>({uniq_usage_limit_snapshots_bucket:sqliteCore.uniqueIndex("uniq_usage_limit_snapshots_bucket").on(a.provider,a.account_ref,a.limit_window,a.bucket_start),idx_usage_limit_snapshots_window_bucket:sqliteCore.index("idx_usage_limit_snapshots_window_bucket").on(a.limit_window,a.bucket_start),idx_usage_limit_snapshots_provider_window_bucket:sqliteCore.index("idx_usage_limit_snapshots_provider_window_bucket").on(a.provider,a.limit_window,a.bucket_start)}));var H=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")},a=>({uniq_usage_reports_ws_month:sqliteCore.uniqueIndex("uniq_usage_reports_ws_month").on(a.workspace_id,a.month)}));var k=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")},a=>({idx_notifications_ws_created:sqliteCore.index("idx_notifications_ws_created").on(a.workspace_id,drizzleOrm.sql`${a.created_at} DESC`)})),I=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()},a=>({pk:sqliteCore.primaryKey({columns:[a.notification_id,a.user_id]})}));var R=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()},a=>({idx_agent_suggestions_ws_agent:sqliteCore.index("idx_agent_suggestions_ws_agent").on(a.workspace_id,a.agent_id),idx_agent_suggestions_ws_created:sqliteCore.index("idx_agent_suggestions_ws_created").on(a.workspace_id,a.created_at)}));function Mt(a){let t=Q__namespace.resolve(a);return process.platform==="win32"&&(t=t.replace(/\\/g,"/"),t=t.replace(/^([A-Z]):/,(n,e)=>`${e.toLowerCase()}:`)),t.length>1&&!/^[a-zA-Z]:\/$/.test(t)&&(t=t.replace(/\/+$/,"")),t}function _e(a){let t=Mt(a);return crypto.createHash("sha256").update(t).digest("hex")}function It(a){return a.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"")}var zt=class extends x{dbRoot;constructor(t={}){super(),this.dbRoot=t.dbRoot;}resolveDbPath(){return this.dbRoot?Q.join(this.dbRoot,".crewx","crewx.db"):super.resolveDbPath()}openHandle(t){let n=this.resolveDbPath();if(t){let r=Q.dirname(n);ge.existsSync(r)||ge.mkdirSync(r,{recursive:true});}else if(!ge.existsSync(n))throw new d("NOT_FOUND","Database not found");let e=w(n);if(t)try{ft(e.db);}catch(r){throw e.close(),r}return e}resolveSlug(t,n,e){let r=It(Q.basename(e)),i=`${It(Q.basename(Q.dirname(e)))}-${r}`,l=[r,i];try{let u=c=>t.select({id:g.id}).from(g).where(drizzleOrm.and(drizzleOrm.eq(g.slug,c),drizzleOrm.ne(g.id,n))).limit(1).all().length>0;for(let c of l)if(!u(c))return c;for(let c=2;c<1e3;c+=1){let p=`${i}-${c}`;if(!u(p))return p}}catch{}return r}normalizeLegacySlugs(){if(!this.dbExists())return {updated:0,checked:0};let t=this.openHandle(true);try{let n=t.db.select({id:g.id,slug:g.slug}).from(g).all(),e=0;for(let r of n)if(r.slug.includes("/")){let s=It(r.slug.replace(/\//g,"-"));t.db.update(g).set({slug:s,updated_at:new Date().toISOString()}).where(drizzleOrm.eq(g.id,r.id)).run(),e+=1;}return {updated:e,checked:n.length}}catch(n){throw new d("DB_ERROR","Failed to normalize legacy slugs",n)}finally{t.close();}}ensureRow(t,n){let{id:e,slug:r,name:s,workspacePath:i}=n,l=new Date().toISOString();t.insert(g).values({id:e,slug:r,name:s,workspace_path:i,is_active:1,created_at:l,updated_at:l}).onConflictDoNothing().run(),t.update(g).set({workspace_path:i,updated_at:l}).where(drizzleOrm.and(drizzleOrm.eq(g.id,e),drizzleOrm.isNull(g.workspace_path))).run();}registerWorkspace(t){let n=Mt(t),e=this.openHandle(true);try{let r=_e(n),s=Q.basename(n),i=this.resolveSlug(e.db,r,n);return this.ensureRow(e.db,{id:r,slug:i,name:s,workspacePath:n}),{id:r,slug:i}}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to register workspace",r)}finally{e.close();}}listProjects(t){if(!this.dbExists())return {rows:[],total:0};let n=this.openHandle(false);try{let e=t.isActive!==void 0?drizzleOrm.eq(g.is_active,t.isActive?1:0):void 0,r=n.db.select({count:drizzleOrm.sql`count(*)`}).from(g).where(e).get();return {rows:n.db.select().from(g).where(e).orderBy(drizzleOrm.desc(g.updated_at)).limit(t.limit).offset(t.offset).all(),total:r?.count??0}}catch(e){throw new d("DB_ERROR","Failed to list projects",e)}finally{n.close();}}findById(t){if(!this.dbExists())return;let n=this.openHandle(false);try{return n.db.select().from(g).where(drizzleOrm.eq(g.id,t)).limit(1).get()??void 0}catch(e){throw new d("DB_ERROR","Failed to find workspace",e)}finally{n.close();}}findAgentsByProject(t){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.all(drizzleOrm.sql`SELECT DISTINCT agent_id FROM tasks WHERE workspace_id = ${t} AND agent_id IS NOT NULL ORDER BY agent_id`).map(r=>r.agent_id)}catch(e){throw new d("DB_ERROR","Failed to find agents by project",e)}finally{n.close();}}findThreadsByProject(t,n){if(!this.dbExists())return {rows:[],total:0};let e=this.openHandle(false);try{let r=e.db.get(drizzleOrm.sql`SELECT COUNT(*) as count FROM threads WHERE workspace_id = ${t}`);return {rows:e.db.all(drizzleOrm.sql`SELECT t.*,
4
4
  (SELECT agent_id FROM tasks tk WHERE tk.thread_id = t.id AND tk.agent_id IS NOT NULL ORDER BY tk.started_at ASC LIMIT 1) AS agent_id
5
5
  FROM threads t
6
6
  WHERE t.workspace_id = ${t}
7
7
  ORDER BY t.updated_at DESC
8
- LIMIT ${n.limit} OFFSET ${n.offset}`),total:r?.count??0}}catch(r){throw new d("DB_ERROR","Failed to find threads by project",r)}finally{e.close();}}findBySlug(t){if(!this.dbExists())return;let n=this.openHandle(false);try{return n.db.select().from(m).where(drizzleOrm.eq(m.slug,t)).limit(1).get()??void 0}catch(e){throw new d("DB_ERROR","Failed to find workspace by slug",e)}finally{n.close();}}slugExists(t,n){if(!this.dbExists())return false;let e=this.openHandle(false);try{let r=n?drizzleOrm.and(drizzleOrm.eq(m.slug,t),drizzleOrm.ne(m.id,n)):drizzleOrm.eq(m.slug,t);return !!e.db.select({id:m.id}).from(m).where(r).limit(1).get()}catch(r){throw new d("DB_ERROR","Failed to check slug",r)}finally{e.close();}}insert(t,n,e,r){let s=this.openHandle(true);try{let i=new Date().toISOString();s.db.insert(m).values({id:t,slug:n,name:e,workspace_path:r,is_active:1,created_at:i,updated_at:i}).run();let l=s.db.select().from(m).where(drizzleOrm.eq(m.id,t)).limit(1).get();if(!l)throw new d("DB_ERROR","Insert did not return a row");return l}catch(i){throw i instanceof d?i:new d("DB_ERROR","Failed to insert workspace",i)}finally{s.close();}}update(t,n,e){let r=this.openHandle(true);try{r.runRaw(`UPDATE workspaces SET ${n.join(", ")} WHERE id = ?`,e);let s=r.db.select().from(m).where(drizzleOrm.eq(m.id,t)).limit(1).get();if(!s)throw new d("NOT_FOUND",`Workspace ${t} not found`);return s}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to update workspace",s)}finally{r.close();}}cleanupOrphanWorkspaces(){if(!this.dbExists())return {softDeleted:0,checked:0};let t=this.openHandle(true);try{let n=t.db.select({id:m.id,workspace_path:m.workspace_path}).from(m).where(drizzleOrm.and(drizzleOrm.eq(m.is_active,1),drizzleOrm.isNotNull(m.workspace_path))).all(),e=0;for(let r of n){let s=r.workspace_path;me.existsSync(Q.join(s,"crewx.yaml"))||me.existsSync(Q.join(s,"crewx.yml"))||(t.db.update(m).set({is_active:0,updated_at:new Date().toISOString()}).where(drizzleOrm.eq(m.id,r.id)).run(),e+=1);}return {softDeleted:e,checked:n.length}}catch(n){throw new d("DB_ERROR","Failed to cleanup orphan workspaces",n)}finally{t.close();}}delete(t){let n=this.openHandle(true);try{n.db.run(drizzleOrm.sql`UPDATE threads SET workspace_id = NULL WHERE workspace_id = ${t}`),n.db.delete(m).where(drizzleOrm.eq(m.id,t)).run();}catch(e){throw e instanceof d?e:new d("DB_ERROR","Failed to delete workspace",e)}finally{n.close();}}};var we=[m,o,_,tt,J,j,ht];function In(){return Q__namespace.default.join(Ye__default.default.homedir(),".crewx","crewx.db")}function vn(a){if(!me__default.default.existsSync(a))return null;let t=Math.floor(Date.now()/1e3),n=`${a}.bak-${t}`;return me__default.default.copyFileSync(a,n),n}function ke(a){let t=a.all("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'");return new Set(t.map(n=>n.name))}function Pn(a){return a==null||typeof a=="object"&&"queryChunks"in a?null:typeof a=="number"?String(a):typeof a=="boolean"?a?"1":"0":typeof a=="string"?`'${a.replace(/'/g,"''")}'`:String(a)}function Ln(a){let t=a.getSQLType(),n=`"${a.name}" ${t}`,e=Pn(a.default);return e!==null&&(n+=` DEFAULT ${e}`),a.notNull&&(n+=" NOT NULL"),n}function $n(a,t){let n=t?.dbPath??In(),e=t?.force??false,r=t?.dryRun??false,s=r?null:vn(n);if(e&&!r)try{a.run("DELETE FROM __drizzle_migrations");}catch{}let i=ke(a);if(!r)try{ft(a);}catch(f){let h=f instanceof Error?`${f.message} ${f.cause?.message??""}`:"";if(!e||!h.includes("duplicate column"))throw f}let l,u;r?(l=we.map(h=>sqliteCore.getTableConfig(h).name).filter(h=>!i.has(h)),u=i):(u=ke(a),l=[...u].filter(f=>!i.has(f)));let c=[],p=[];for(let f of we){let h=sqliteCore.getTableConfig(f),S=h.name;if(!u.has(S))continue;let P=a.all(`PRAGMA table_info("${S}")`),$=new Set(P.map(N=>N.name)),H=new Set(h.columns.map(N=>N.name));for(let N of h.columns)if(!$.has(N.name)){if(!r){let G=Ln(N);a.run(`ALTER TABLE "${S}" ADD COLUMN ${G}`);}c.push({table:S,column:N.name});}for(let N of P)H.has(N.name)||p.push(`${S}.${N.name} exists in DB but not in schema (untouched)`);}return {created:l,altered:c,warnings:p,backupPath:s}}function be(a){let t=a.toLowerCase().trim();t=t.replace(/\[[^\]]*\]$/g,"");let n=t.lastIndexOf("/");return n>=0&&(t=t.slice(n+1)),t=t.replace(/-\d{8}$/,""),t}var st="2026-05-09",qn="0.8.9-rc.13",it=10,at=parseInt(qn.split("rc.")[1]),jn=new Set(["workflow","mcp"]),Re=600*1e3,Wt=class extends x{dbPath;pidNullObservedSince=new Map;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=Q.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let n=this.resolveDbPath();if(t){let r=Q.dirname(n);me.existsSync(r)||me.mkdirSync(r,{recursive:true});}else if(!me.existsSync(n))throw new d("NOT_FOUND","Database not found");let e=w(n);if(t)try{A(e.db,n);}catch(r){throw e.close(),r}return e}startTask(t){let n=this.openHandle(true);try{n.db.insert(o).values({id:t.id,agent_id:t.agentId,prompt:t.prompt,mode:t.mode,status:t.status,started_at:t.startedAt,pid:t.pid??null,parent_task_id:t.parentTaskId??null,caller_agent_id:t.callerAgentId??null,trace_id:t.traceId??null,command:t.command??null,metadata:t.metadata??null,workspace_id:t.workspaceId??null,platform:t.platform??"cli",crewx_version:t.crewxVersion??null,thread_id:t.threadId??null,model:t.model??null,rendered_prompt:t.renderedPrompt??null,coding_agent_command:t.codingAgentCommand??null}).onConflictDoUpdate({target:o.id,set:{pid:drizzleOrm.sql`COALESCE(excluded.pid, ${o.pid})`},setWhere:drizzleOrm.eq(o.status,"running")}).run();}catch(e){throw e instanceof d?e:new d("DB_ERROR","Failed to start task",e)}finally{n.close();}}finishTask(t){let n=this.openHandle(true);try{let e=t.runEpoch??null;n.runRaw(`UPDATE tasks SET status=?, result=?, error=?, completed_at=?, duration_ms=?,
8
+ LIMIT ${n.limit} OFFSET ${n.offset}`),total:r?.count??0}}catch(r){throw new d("DB_ERROR","Failed to find threads by project",r)}finally{e.close();}}findBySlug(t){if(!this.dbExists())return;let n=this.openHandle(false);try{return n.db.select().from(g).where(drizzleOrm.eq(g.slug,t)).limit(1).get()??void 0}catch(e){throw new d("DB_ERROR","Failed to find workspace by slug",e)}finally{n.close();}}slugExists(t,n){if(!this.dbExists())return false;let e=this.openHandle(false);try{let r=n?drizzleOrm.and(drizzleOrm.eq(g.slug,t),drizzleOrm.ne(g.id,n)):drizzleOrm.eq(g.slug,t);return !!e.db.select({id:g.id}).from(g).where(r).limit(1).get()}catch(r){throw new d("DB_ERROR","Failed to check slug",r)}finally{e.close();}}insert(t,n,e,r){let s=this.openHandle(true);try{let i=new Date().toISOString();s.db.insert(g).values({id:t,slug:n,name:e,workspace_path:r,is_active:1,created_at:i,updated_at:i}).run();let l=s.db.select().from(g).where(drizzleOrm.eq(g.id,t)).limit(1).get();if(!l)throw new d("DB_ERROR","Insert did not return a row");return l}catch(i){throw i instanceof d?i:new d("DB_ERROR","Failed to insert workspace",i)}finally{s.close();}}update(t,n,e){let r=this.openHandle(true);try{r.runRaw(`UPDATE workspaces SET ${n.join(", ")} WHERE id = ?`,e);let s=r.db.select().from(g).where(drizzleOrm.eq(g.id,t)).limit(1).get();if(!s)throw new d("NOT_FOUND",`Workspace ${t} not found`);return s}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to update workspace",s)}finally{r.close();}}cleanupOrphanWorkspaces(){if(!this.dbExists())return {softDeleted:0,checked:0};let t=this.openHandle(true);try{let n=t.db.select({id:g.id,workspace_path:g.workspace_path}).from(g).where(drizzleOrm.and(drizzleOrm.eq(g.is_active,1),drizzleOrm.isNotNull(g.workspace_path))).all(),e=0;for(let r of n){let s=r.workspace_path;ge.existsSync(Q.join(s,"crewx.yaml"))||ge.existsSync(Q.join(s,"crewx.yml"))||(t.db.update(g).set({is_active:0,updated_at:new Date().toISOString()}).where(drizzleOrm.eq(g.id,r.id)).run(),e+=1);}return {softDeleted:e,checked:n.length}}catch(n){throw new d("DB_ERROR","Failed to cleanup orphan workspaces",n)}finally{t.close();}}delete(t){let n=this.openHandle(true);try{n.db.run(drizzleOrm.sql`UPDATE threads SET workspace_id = NULL WHERE workspace_id = ${t}`),n.db.delete(g).where(drizzleOrm.eq(g.id,t)).run();}catch(e){throw e instanceof d?e:new d("DB_ERROR","Failed to delete workspace",e)}finally{n.close();}}};var we=[g,o,_,tt,J,j,ht];function Cn(){return Q__namespace.default.join(Ye__default.default.homedir(),".crewx","crewx.db")}function Pn(a){if(!ge__default.default.existsSync(a))return null;let t=Math.floor(Date.now()/1e3),n=`${a}.bak-${t}`;return ge__default.default.copyFileSync(a,n),n}function ke(a){let t=a.all("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'");return new Set(t.map(n=>n.name))}function vn(a){return a==null||typeof a=="object"&&"queryChunks"in a?null:typeof a=="number"?String(a):typeof a=="boolean"?a?"1":"0":typeof a=="string"?`'${a.replace(/'/g,"''")}'`:String(a)}function Ln(a){let t=a.getSQLType(),n=`"${a.name}" ${t}`,e=vn(a.default);return e!==null&&(n+=` DEFAULT ${e}`),a.notNull&&(n+=" NOT NULL"),n}function $n(a,t){let n=t?.dbPath??Cn(),e=t?.force??false,r=t?.dryRun??false,s=r?null:Pn(n);if(e&&!r)try{a.run("DELETE FROM __drizzle_migrations");}catch{}let i=ke(a);if(!r)try{ft(a);}catch(f){let h=f instanceof Error?`${f.message} ${f.cause?.message??""}`:"";if(!e||!h.includes("duplicate column"))throw f}let l,u;r?(l=we.map(h=>sqliteCore.getTableConfig(h).name).filter(h=>!i.has(h)),u=i):(u=ke(a),l=[...u].filter(f=>!i.has(f)));let c=[],p=[];for(let f of we){let h=sqliteCore.getTableConfig(f),S=h.name;if(!u.has(S))continue;let v=a.all(`PRAGMA table_info("${S}")`),$=new Set(v.map(A=>A.name)),M=new Set(h.columns.map(A=>A.name));for(let A of h.columns)if(!$.has(A.name)){if(!r){let G=Ln(A);a.run(`ALTER TABLE "${S}" ADD COLUMN ${G}`);}c.push({table:S,column:A.name});}for(let A of v)M.has(A.name)||p.push(`${S}.${A.name} exists in DB but not in schema (untouched)`);}return {created:l,altered:c,warnings:p,backupPath:s}}function be(a){let t=a.toLowerCase().trim();t=t.replace(/\[[^\]]*\]$/g,"");let n=t.lastIndexOf("/");return n>=0&&(t=t.slice(n+1)),t=t.replace(/-\d{8}$/,""),t}var st="2026-05-09",jn="0.8.9-rc.13",it=10,at=parseInt(jn.split("rc.")[1]),Wn=new Set(["workflow","mcp"]),Re=600*1e3,Wt=class extends x{dbPath;pidNullObservedSince=new Map;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=Q.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let n=this.resolveDbPath();if(t){let r=Q.dirname(n);ge.existsSync(r)||ge.mkdirSync(r,{recursive:true});}else if(!ge.existsSync(n))throw new d("NOT_FOUND","Database not found");let e=w(n);if(t)try{N(e.db,n);}catch(r){throw e.close(),r}return e}startTask(t){let n=this.openHandle(true);try{n.db.insert(o).values({id:t.id,agent_id:t.agentId,prompt:t.prompt,mode:t.mode,status:t.status,started_at:t.startedAt,pid:t.pid??null,parent_task_id:t.parentTaskId??null,caller_agent_id:t.callerAgentId??null,trace_id:t.traceId??null,command:t.command??null,metadata:t.metadata??null,workspace_id:t.workspaceId??null,platform:t.platform??"cli",crewx_version:t.crewxVersion??null,thread_id:t.threadId??null,model:t.model??null,rendered_prompt:t.renderedPrompt??null,coding_agent_command:t.codingAgentCommand??null}).onConflictDoUpdate({target:o.id,set:{pid:drizzleOrm.sql`COALESCE(excluded.pid, ${o.pid})`},setWhere:drizzleOrm.eq(o.status,"running")}).run();}catch(e){throw e instanceof d?e:new d("DB_ERROR","Failed to start task",e)}finally{n.close();}}finishTask(t){let n=this.openHandle(true);try{let e=t.runEpoch??null;n.runRaw(`UPDATE tasks SET status=?, result=?, error=?, completed_at=?, duration_ms=?,
9
9
  exit_code=?, input_tokens=?, output_tokens=?, cached_input_tokens=?, cost_usd=?,
10
10
  model=COALESCE(?, model)
11
- WHERE id=? AND status='running' AND COALESCE(run_epoch, 0) = COALESCE(?, 0)`,[t.status,t.result??null,t.error??null,t.completedAt,t.durationMs??null,t.exitCode??null,t.inputTokens??0,t.outputTokens??0,t.cachedInputTokens??0,t.costUsd??0,t.model??null,t.id,e]);}catch(e){throw e instanceof d?e:new d("DB_ERROR","Failed to finish task",e)}finally{n.close();}}appendLog(t,n){let e=this.openHandle(true);try{e.db.transaction(r=>{let s=r.select({logs:o.logs}).from(o).where(drizzleOrm.eq(o.id,t)).limit(1).get(),i=s?.logs?JSON.parse(s.logs):[];i.push(n),r.update(o).set({logs:JSON.stringify(i)}).where(drizzleOrm.eq(o.id,t)).run();},{behavior:"immediate"});}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to append log",r)}finally{e.close();}}getRunningTasks(){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(o).where(drizzleOrm.eq(o.status,"running")).orderBy(drizzleOrm.desc(o.started_at)).all()}catch(n){throw new d("DB_ERROR","Failed to get running tasks",n)}finally{t.close();}}getAllTasks(){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(o).orderBy(drizzleOrm.desc(o.started_at)).limit(100).all()}catch(n){throw new d("DB_ERROR","Failed to get all tasks",n)}finally{t.close();}}getTask(t){if(!this.dbExists())return;let n=this.openHandle(false);try{return n.db.select().from(o).where(drizzleOrm.eq(o.id,t)).limit(1).get()??void 0}catch(e){throw new d("DB_ERROR","Failed to get task",e)}finally{n.close();}}killTask(t){if(!this.dbExists())return {killed:false};let n=this.openHandle(true);try{let e=n.db.select({id:o.id,status:o.status,pid:o.pid}).from(o).where(drizzleOrm.eq(o.id,t)).limit(1).get();if(!e||e.status!=="running")return {killed:!1};if(e.pid)try{process.kill(e.pid,"SIGTERM");}catch{}return n.db.update(o).set({status:"failed",error:"Killed by user",completed_at:new Date().toISOString()}).where(drizzleOrm.and(drizzleOrm.eq(o.id,t),drizzleOrm.eq(o.status,"running"))).run(),{killed:!0,pid:e.pid??void 0}}catch(e){throw e instanceof d?e:new d("DB_ERROR","Failed to kill task",e)}finally{n.close();}}reapOrphanedTasks(){if(!this.dbExists())return 0;let t=this.openHandle(true);try{let n=t.db.select({id:o.id,pid:o.pid,platform:o.platform,run_epoch:o.run_epoch}).from(o).where(drizzleOrm.eq(o.status,"running")).all(),e=Date.now(),r=new Set,s=0;for(let i of n){if(i.pid){let c=!1;try{process.kill(i.pid,0),c=!0;}catch{}c||(t.db.update(o).set({status:"failed",error:"Reaped: process not found (orphaned task)",completed_at:new Date().toISOString()}).where(drizzleOrm.and(drizzleOrm.eq(o.id,i.id),drizzleOrm.eq(o.status,"running"))).run(),s++);continue}if(jn.has(i.platform??"cli"))continue;let l=`${i.id}:${i.run_epoch??0}`;r.add(l);let u=this.pidNullObservedSince.get(l);if(u===void 0){this.pidNullObservedSince.set(l,e);continue}e-u>=Re&&(t.db.update(o).set({status:"failed",error:"Reaped: pid never recorded after resume (stale running_instruction)",completed_at:new Date().toISOString()}).where(drizzleOrm.and(drizzleOrm.eq(o.id,i.id),drizzleOrm.eq(o.status,"running"))).run(),s++,this.pidNullObservedSince.delete(l));}for(let i of Array.from(this.pidNullObservedSince.keys()))r.has(i)||this.pidNullObservedSince.delete(i);return s}finally{t.close();}}reapRunningWorkflowTasks(t=Re){if(!this.dbExists())return 0;let n=this.openHandle(true);try{let e=new Date(Date.now()-t).toISOString();return n.db.update(o).set({status:"failed",error:"Reaped: stale workflow run (finally not executed)",completed_at:new Date().toISOString()}).where(drizzleOrm.and(drizzleOrm.eq(o.status,"running"),drizzleOrm.eq(o.platform,"workflow"),drizzleOrm.isNull(o.pid),drizzleOrm.lt(o.started_at,e),drizzleOrm.or(drizzleOrm.isNull(o.metadata),drizzleOrm.notLike(o.metadata,'%"kind":"workflow_card"%')))).run().changes??0}finally{n.close();}}findTaskStatus(t,n){let e=this.resolveDbPaths();for(let r of e){if(!me.existsSync(r))continue;let s=w(r);try{let i=n?drizzleOrm.eq(o.workspace_id,n):void 0,l=i?drizzleOrm.and(drizzleOrm.eq(o.id,t),i):drizzleOrm.eq(o.id,t),u=s.db.select().from(o).where(l).limit(1).get()??void 0;if(!u){let c=drizzleOrm.or(drizzleOrm.eq(o.thread_id,t),drizzleOrm.and(drizzleOrm.isNull(o.thread_id),drizzleOrm.like(o.command,`%--thread=${t}%`))),p=i?drizzleOrm.and(c,i):c;u=s.db.select().from(o).where(p).orderBy(drizzleOrm.desc(o.started_at)).limit(1).get()??void 0;}if(u)return u}catch(i){throw new d("DB_ERROR","Failed to find task status",i)}finally{s.close();}}}findChildTasks(t,n){let e=this.resolveDbPaths(),r=new Set,s=[];for(let i of e){if(!me.existsSync(i))continue;let l=w(i);try{let u=n?drizzleOrm.and(drizzleOrm.eq(o.parent_task_id,t),drizzleOrm.eq(o.workspace_id,n)):drizzleOrm.eq(o.parent_task_id,t),c=l.db.select().from(o).where(u).orderBy(drizzleOrm.asc(o.started_at)).all();for(let p of c)r.has(p.id)||(r.add(p.id),s.push(p));}catch(u){throw new d("DB_ERROR","Failed to find child tasks",u)}finally{l.close();}}return s}getWorkspaceUsageSummary(t){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.all(t?drizzleOrm.sql`
11
+ WHERE id=? AND status='running' AND COALESCE(run_epoch, 0) = COALESCE(?, 0)`,[t.status,t.result??null,t.error??null,t.completedAt,t.durationMs??null,t.exitCode??null,t.inputTokens??0,t.outputTokens??0,t.cachedInputTokens??0,t.costUsd??0,t.model??null,t.id,e]);}catch(e){throw e instanceof d?e:new d("DB_ERROR","Failed to finish task",e)}finally{n.close();}}appendLog(t,n){let e=this.openHandle(true);try{e.db.transaction(r=>{let s=r.select({logs:o.logs}).from(o).where(drizzleOrm.eq(o.id,t)).limit(1).get(),i=s?.logs?JSON.parse(s.logs):[];i.push(n),r.update(o).set({logs:JSON.stringify(i)}).where(drizzleOrm.eq(o.id,t)).run();},{behavior:"immediate"});}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to append log",r)}finally{e.close();}}getRunningTasks(){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(o).where(drizzleOrm.eq(o.status,"running")).orderBy(drizzleOrm.desc(o.started_at)).all()}catch(n){throw new d("DB_ERROR","Failed to get running tasks",n)}finally{t.close();}}getAllTasks(){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(o).orderBy(drizzleOrm.desc(o.started_at)).limit(100).all()}catch(n){throw new d("DB_ERROR","Failed to get all tasks",n)}finally{t.close();}}getTask(t){if(!this.dbExists())return;let n=this.openHandle(false);try{return n.db.select().from(o).where(drizzleOrm.eq(o.id,t)).limit(1).get()??void 0}catch(e){throw new d("DB_ERROR","Failed to get task",e)}finally{n.close();}}killTask(t){if(!this.dbExists())return {killed:false};let n=this.openHandle(true);try{let e=n.db.select({id:o.id,status:o.status,pid:o.pid}).from(o).where(drizzleOrm.eq(o.id,t)).limit(1).get();if(!e||e.status!=="running")return {killed:!1};if(e.pid)try{process.kill(e.pid,"SIGTERM");}catch{}return n.db.update(o).set({status:"failed",error:"Killed by user",completed_at:new Date().toISOString()}).where(drizzleOrm.and(drizzleOrm.eq(o.id,t),drizzleOrm.eq(o.status,"running"))).run(),{killed:!0,pid:e.pid??void 0}}catch(e){throw e instanceof d?e:new d("DB_ERROR","Failed to kill task",e)}finally{n.close();}}reapOrphanedTasks(){if(!this.dbExists())return 0;let t=this.openHandle(true);try{let n=t.db.select({id:o.id,pid:o.pid,platform:o.platform,run_epoch:o.run_epoch}).from(o).where(drizzleOrm.eq(o.status,"running")).all(),e=Date.now(),r=new Set,s=0;for(let i of n){if(i.pid){let c=!1;try{process.kill(i.pid,0),c=!0;}catch{}c||(t.db.update(o).set({status:"failed",error:"Reaped: process not found (orphaned task)",completed_at:new Date().toISOString()}).where(drizzleOrm.and(drizzleOrm.eq(o.id,i.id),drizzleOrm.eq(o.status,"running"))).run(),s++);continue}if(Wn.has(i.platform??"cli"))continue;let l=`${i.id}:${i.run_epoch??0}`;r.add(l);let u=this.pidNullObservedSince.get(l);if(u===void 0){this.pidNullObservedSince.set(l,e);continue}e-u>=Re&&(t.db.update(o).set({status:"failed",error:"Reaped: pid never recorded after resume (stale running_instruction)",completed_at:new Date().toISOString()}).where(drizzleOrm.and(drizzleOrm.eq(o.id,i.id),drizzleOrm.eq(o.status,"running"))).run(),s++,this.pidNullObservedSince.delete(l));}for(let i of Array.from(this.pidNullObservedSince.keys()))r.has(i)||this.pidNullObservedSince.delete(i);return s}finally{t.close();}}reapRunningWorkflowTasks(t=Re){if(!this.dbExists())return 0;let n=this.openHandle(true);try{let e=new Date(Date.now()-t).toISOString();return n.db.update(o).set({status:"failed",error:"Reaped: stale workflow run (finally not executed)",completed_at:new Date().toISOString()}).where(drizzleOrm.and(drizzleOrm.eq(o.status,"running"),drizzleOrm.eq(o.platform,"workflow"),drizzleOrm.isNull(o.pid),drizzleOrm.lt(o.started_at,e),drizzleOrm.or(drizzleOrm.isNull(o.metadata),drizzleOrm.notLike(o.metadata,'%"kind":"workflow_card"%')))).run().changes??0}finally{n.close();}}findTaskStatus(t,n){let e=this.resolveDbPaths();for(let r of e){if(!ge.existsSync(r))continue;let s=w(r);try{let i=n?drizzleOrm.eq(o.workspace_id,n):void 0,l=i?drizzleOrm.and(drizzleOrm.eq(o.id,t),i):drizzleOrm.eq(o.id,t),u=s.db.select().from(o).where(l).limit(1).get()??void 0;if(!u){let c=drizzleOrm.or(drizzleOrm.eq(o.thread_id,t),drizzleOrm.and(drizzleOrm.isNull(o.thread_id),drizzleOrm.like(o.command,`%--thread=${t}%`))),p=i?drizzleOrm.and(c,i):c;u=s.db.select().from(o).where(p).orderBy(drizzleOrm.desc(o.started_at)).limit(1).get()??void 0;}if(u)return u}catch(i){throw new d("DB_ERROR","Failed to find task status",i)}finally{s.close();}}}findChildTasks(t,n){let e=this.resolveDbPaths(),r=new Set,s=[];for(let i of e){if(!ge.existsSync(i))continue;let l=w(i);try{let u=n?drizzleOrm.and(drizzleOrm.eq(o.parent_task_id,t),drizzleOrm.eq(o.workspace_id,n)):drizzleOrm.eq(o.parent_task_id,t),c=l.db.select().from(o).where(u).orderBy(drizzleOrm.asc(o.started_at)).all();for(let p of c)r.has(p.id)||(r.add(p.id),s.push(p));}catch(u){throw new d("DB_ERROR","Failed to find child tasks",u)}finally{l.close();}}return s}getWorkspaceUsageSummary(t){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.all(t?drizzleOrm.sql`
12
12
  SELECT
13
13
  COALESCE(workspace_id, 'unknown') AS workspace_id,
14
14
  COALESCE(SUM(input_tokens), 0) AS input_tokens,
@@ -29,7 +29,7 @@ ${e.join(`
29
29
  FROM tasks
30
30
  GROUP BY workspace_id
31
31
  ORDER BY (COALESCE(SUM(input_tokens), 0) + COALESCE(SUM(output_tokens), 0)) DESC
32
- `)}catch(e){throw new d("DB_ERROR","Failed to get workspace usage summary",e)}finally{n.close();}}getThreadTokenUsage(t,n){let e=this.resolveDbPaths(),r=new Set,s=0,i=0,l=0;for(let u of e){if(!me.existsSync(u))continue;let c=w(u);try{let p=drizzleOrm.or(drizzleOrm.eq(o.thread_id,t),drizzleOrm.and(drizzleOrm.isNull(o.thread_id),drizzleOrm.like(o.command,`%--thread=${t}%`))),f=n?drizzleOrm.and(p,drizzleOrm.eq(o.workspace_id,n)):p,h=c.db.select({id:o.id,input_tokens:o.input_tokens,output_tokens:o.output_tokens,cost_usd:o.cost_usd}).from(o).where(f).all();for(let S of h)r.has(S.id)||(r.add(S.id),s+=S.input_tokens??0,i+=S.output_tokens??0,l+=S.cost_usd??0);}catch(p){throw new d("DB_ERROR","Failed to get thread token usage",p)}finally{c.close();}}return {inputTokens:s,outputTokens:i,costUsd:l}}findTasksByThread(t,n){let e=this.resolveDbPaths(),r=new Set,s=[];for(let i of e){if(!me.existsSync(i))continue;let l=w(i);try{let u=drizzleOrm.or(drizzleOrm.eq(o.thread_id,t),drizzleOrm.and(drizzleOrm.isNull(o.thread_id),drizzleOrm.like(o.command,`%--thread=${t}%`))),c=n?drizzleOrm.and(u,drizzleOrm.eq(o.workspace_id,n)):u,p=l.db.select().from(o).where(c).orderBy(drizzleOrm.asc(o.started_at)).all();for(let f of p)r.has(f.id)||(r.add(f.id),s.push(f));}catch(u){throw new d("DB_ERROR","Failed to find tasks by thread",u)}finally{l.close();}}return s}parseWorkflowCardMetadata(t){if(!t)return {};try{let n=JSON.parse(t);return {kind:typeof n.kind=="string"?n.kind:void 0,workflowRunId:typeof n.workflowRunId=="string"?n.workflowRunId:void 0}}catch{return {}}}extractThreadIdFromCommand(t){return t?/--thread=(\S+)/.exec(t)?.[1]??null:null}findRunningWorkflowParentTasks(){if(!this.dbExists())return [];let t=[];for(let n of this.resolveDbPaths()){if(!me.existsSync(n))continue;let e=w(n);try{t.push(...e.db.select({id:o.id,agent_id:o.agent_id,thread_id:o.thread_id,workspace_id:o.workspace_id,platform:o.platform,status:o.status,error:o.error,completed_at:o.completed_at,duration_ms:o.duration_ms,started_at:o.started_at,metadata:o.metadata}).from(o).where(drizzleOrm.and(drizzleOrm.eq(o.platform,"workflow"),drizzleOrm.like(o.metadata,'%"kind":"workflow_card"%'))).orderBy(drizzleOrm.desc(o.started_at)).all());}catch(r){throw new d("DB_ERROR","Failed to find workflow parent tasks",r)}finally{e.close();}}return t}batchFetchWorkflowCards(t,n){let e=new Map;if(t.length===0)return e;let r=new Set(t),s=new Map,i=n?drizzleOrm.eq(o.workspace_id,n):void 0,l=(u,c)=>{if(!u)return;let p=s.get(u);if(p&&c.started_at<=p)return;let f=this.parseWorkflowCardMetadata(c.metadata);f.kind==="workflow_card"&&(s.set(u,c.started_at),e.set(u,{taskId:c.id,workflowRunId:f.workflowRunId,raw:c.result??void 0}));};for(let u of this.resolveDbPaths()){if(!me.existsSync(u))continue;let c=w(u);try{let p=drizzleOrm.and(drizzleOrm.inArray(o.thread_id,t),drizzleOrm.like(o.metadata,'%"kind":"workflow_card"%')),f=c.db.select({id:o.id,thread_id:o.thread_id,metadata:o.metadata,result:o.result,started_at:o.started_at}).from(o).where(i?drizzleOrm.and(p,i):p).all();for(let P of f)l(P.thread_id,P);let h=drizzleOrm.and(drizzleOrm.isNull(o.thread_id),drizzleOrm.like(o.metadata,'%"kind":"workflow_card"%')),S=c.db.select({id:o.id,command:o.command,metadata:o.metadata,result:o.result,started_at:o.started_at}).from(o).where(i?drizzleOrm.and(h,i):h).all();for(let P of S){let $=this.extractThreadIdFromCommand(P.command);!$||!r.has($)||l($,P);}}catch(p){throw new d("DB_ERROR","Failed to batch fetch workflow cards",p)}finally{c.close();}}return e}findAllTasks(t){if(!this.dbExists())return {rows:[],total:0};let n=this.openHandle(false);try{let e=[];t.workspaceId&&e.push(drizzleOrm.eq(o.workspace_id,t.workspaceId));let r=t.agents&&t.agents.length>0?t.agents:t.agentId?[t.agentId]:null;r&&e.push(drizzleOrm.inArray(o.agent_id,r));let s=t.statuses&&t.statuses.length>0?t.statuses:t.status?[t.status]:null;s&&e.push(drizzleOrm.inArray(o.status,s));let i=t.q??t.search;i&&e.push(drizzleOrm.like(o.prompt,`%${i}%`)),t.from&&e.push(drizzleOrm.gte(o.started_at,t.from)),t.to&&e.push(drizzleOrm.lt(o.started_at,t.to));let l=e.length>0?drizzleOrm.and(...e):void 0,u=n.db.select({count:drizzleOrm.sql`count(*)`}).from(o).where(l).get(),c=(t.sortDir??"DESC")==="ASC"?drizzleOrm.asc(o.started_at):drizzleOrm.desc(o.started_at);return {rows:n.db.select().from(o).where(l).orderBy(c).limit(t.limit).offset(t.offset).all(),total:u?.count??0}}catch(e){throw new d("DB_ERROR","Failed to find all tasks",e)}finally{n.close();}}getAgentUsage(t,n,e){if(!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.all(e?drizzleOrm.sql`
32
+ `)}catch(e){throw new d("DB_ERROR","Failed to get workspace usage summary",e)}finally{n.close();}}getThreadTokenUsage(t,n){let e=this.resolveDbPaths(),r=new Set,s=0,i=0,l=0;for(let u of e){if(!ge.existsSync(u))continue;let c=w(u);try{let p=drizzleOrm.or(drizzleOrm.eq(o.thread_id,t),drizzleOrm.and(drizzleOrm.isNull(o.thread_id),drizzleOrm.like(o.command,`%--thread=${t}%`))),f=n?drizzleOrm.and(p,drizzleOrm.eq(o.workspace_id,n)):p,h=c.db.select({id:o.id,input_tokens:o.input_tokens,output_tokens:o.output_tokens,cost_usd:o.cost_usd}).from(o).where(f).all();for(let S of h)r.has(S.id)||(r.add(S.id),s+=S.input_tokens??0,i+=S.output_tokens??0,l+=S.cost_usd??0);}catch(p){throw new d("DB_ERROR","Failed to get thread token usage",p)}finally{c.close();}}return {inputTokens:s,outputTokens:i,costUsd:l}}findTasksByThread(t,n){let e=this.resolveDbPaths(),r=new Set,s=[];for(let i of e){if(!ge.existsSync(i))continue;let l=w(i);try{let u=drizzleOrm.or(drizzleOrm.eq(o.thread_id,t),drizzleOrm.and(drizzleOrm.isNull(o.thread_id),drizzleOrm.like(o.command,`%--thread=${t}%`))),c=n?drizzleOrm.and(u,drizzleOrm.eq(o.workspace_id,n)):u,p=l.db.select().from(o).where(c).orderBy(drizzleOrm.asc(o.started_at)).all();for(let f of p)r.has(f.id)||(r.add(f.id),s.push(f));}catch(u){throw new d("DB_ERROR","Failed to find tasks by thread",u)}finally{l.close();}}return s}parseWorkflowCardMetadata(t){if(!t)return {};try{let n=JSON.parse(t);return {kind:typeof n.kind=="string"?n.kind:void 0,workflowRunId:typeof n.workflowRunId=="string"?n.workflowRunId:void 0}}catch{return {}}}extractThreadIdFromCommand(t){return t?/--thread=(\S+)/.exec(t)?.[1]??null:null}findRunningWorkflowParentTasks(){if(!this.dbExists())return [];let t=[];for(let n of this.resolveDbPaths()){if(!ge.existsSync(n))continue;let e=w(n);try{t.push(...e.db.select({id:o.id,agent_id:o.agent_id,thread_id:o.thread_id,workspace_id:o.workspace_id,platform:o.platform,status:o.status,error:o.error,completed_at:o.completed_at,duration_ms:o.duration_ms,started_at:o.started_at,metadata:o.metadata}).from(o).where(drizzleOrm.and(drizzleOrm.eq(o.platform,"workflow"),drizzleOrm.like(o.metadata,'%"kind":"workflow_card"%'))).orderBy(drizzleOrm.desc(o.started_at)).all());}catch(r){throw new d("DB_ERROR","Failed to find workflow parent tasks",r)}finally{e.close();}}return t}batchFetchWorkflowCards(t,n){let e=new Map;if(t.length===0)return e;let r=new Set(t),s=new Map,i=n?drizzleOrm.eq(o.workspace_id,n):void 0,l=(u,c)=>{if(!u)return;let p=s.get(u);if(p&&c.started_at<=p)return;let f=this.parseWorkflowCardMetadata(c.metadata);f.kind==="workflow_card"&&(s.set(u,c.started_at),e.set(u,{taskId:c.id,workflowRunId:f.workflowRunId,raw:c.result??void 0}));};for(let u of this.resolveDbPaths()){if(!ge.existsSync(u))continue;let c=w(u);try{let p=drizzleOrm.and(drizzleOrm.inArray(o.thread_id,t),drizzleOrm.like(o.metadata,'%"kind":"workflow_card"%')),f=c.db.select({id:o.id,thread_id:o.thread_id,metadata:o.metadata,result:o.result,started_at:o.started_at}).from(o).where(i?drizzleOrm.and(p,i):p).all();for(let v of f)l(v.thread_id,v);let h=drizzleOrm.and(drizzleOrm.isNull(o.thread_id),drizzleOrm.like(o.metadata,'%"kind":"workflow_card"%')),S=c.db.select({id:o.id,command:o.command,metadata:o.metadata,result:o.result,started_at:o.started_at}).from(o).where(i?drizzleOrm.and(h,i):h).all();for(let v of S){let $=this.extractThreadIdFromCommand(v.command);!$||!r.has($)||l($,v);}}catch(p){throw new d("DB_ERROR","Failed to batch fetch workflow cards",p)}finally{c.close();}}return e}findAllTasks(t){if(!this.dbExists())return {rows:[],total:0};let n=this.openHandle(false);try{let e=[];t.workspaceId&&e.push(drizzleOrm.eq(o.workspace_id,t.workspaceId));let r=t.agents&&t.agents.length>0?t.agents:t.agentId?[t.agentId]:null;r&&e.push(drizzleOrm.inArray(o.agent_id,r));let s=t.statuses&&t.statuses.length>0?t.statuses:t.status?[t.status]:null;s&&e.push(drizzleOrm.inArray(o.status,s));let i=t.q??t.search;i&&e.push(drizzleOrm.like(o.prompt,`%${i}%`)),t.from&&e.push(drizzleOrm.gte(o.started_at,t.from)),t.to&&e.push(drizzleOrm.lt(o.started_at,t.to));let l=e.length>0?drizzleOrm.and(...e):void 0,u=n.db.select({count:drizzleOrm.sql`count(*)`}).from(o).where(l).get(),c=(t.sortDir??"DESC")==="ASC"?drizzleOrm.asc(o.started_at):drizzleOrm.desc(o.started_at);return {rows:n.db.select().from(o).where(l).orderBy(c).limit(t.limit).offset(t.offset).all(),total:u?.count??0}}catch(e){throw new d("DB_ERROR","Failed to find all tasks",e)}finally{n.close();}}getAgentUsage(t,n,e){if(!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.all(e?drizzleOrm.sql`
33
33
  SELECT
34
34
  t.agent_id,
35
35
  t.workspace_id,
@@ -167,7 +167,7 @@ ${e.join(`
167
167
  AND t.started_at < ${n}
168
168
  GROUP BY date(t.started_at), t.agent_id
169
169
  ORDER BY date(t.started_at) ASC
170
- `).map(i=>({date:i.date,agentId:i.agent_id,inputTokens:i.input_tokens,outputTokens:i.output_tokens,cachedInputTokens:i.cached_input_tokens,costUsd:i.cost_usd,totalTokens:i.input_tokens+i.output_tokens}))}catch(s){throw new d("DB_ERROR","Failed to get agent usage trend",s)}finally{r.close();}}findTaskForStop(t,n){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(o).where(drizzleOrm.and(drizzleOrm.eq(o.id,t),drizzleOrm.eq(o.workspace_id,n))).limit(1).get()??void 0}catch(r){throw new d("DB_ERROR","Failed to find task for stop",r)}finally{e.close();}}findLatestTaskByMetadata(t){if(!this.dbExists())return null;let n=this.openHandle(false);try{return n.db.select({id:o.id,thread_id:o.thread_id,status:o.status,result:o.result,error:o.error,started_at:o.started_at,completed_at:o.completed_at}).from(o).where(drizzleOrm.and(drizzleOrm.eq(o.agent_id,t.agentId),drizzleOrm.eq(o.workspace_id,t.workspaceId),drizzleOrm.sql`${o.metadata} IS NOT NULL AND json_valid(${o.metadata}) AND json_extract(${o.metadata}, '$.' || ${t.metaKey}) = ${t.metaValue}`)).orderBy(drizzleOrm.desc(o.started_at)).limit(1).get()??null}catch(e){throw new d("DB_ERROR","Failed to find latest task by metadata",e)}finally{n.close();}}markTaskFailed(t,n,e){if(!this.dbExists())return;let r=this.openHandle(true);try{let s=new Date().toISOString(),i=e?drizzleOrm.and(drizzleOrm.eq(o.id,t),drizzleOrm.eq(o.status,"running"),drizzleOrm.eq(o.workspace_id,e)):drizzleOrm.and(drizzleOrm.eq(o.id,t),drizzleOrm.eq(o.status,"running"));r.db.update(o).set({status:"failed",error:n,completed_at:s}).where(i).run();}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to mark task failed",s)}finally{r.close();}}findTasksByPromptHint(t,n){let e=this.resolveDbPaths(),r=new Set,s=[];for(let i of e){if(!me.existsSync(i))continue;let l=w(i);try{let u=n?drizzleOrm.and(drizzleOrm.like(o.prompt,`%${t}%`),drizzleOrm.eq(o.workspace_id,n)):drizzleOrm.like(o.prompt,`%${t}%`),c=l.db.select().from(o).where(u).orderBy(drizzleOrm.asc(o.started_at)).all();for(let p of c)r.has(p.id)||(r.add(p.id),s.push(p));}catch(u){throw new d("DB_ERROR","Failed to find tasks by prompt hint",u)}finally{l.close();}}return s}getProviderUsage(t,n,e){if(!this.dbExists())return [];let r=this.openHandle(false);try{let s=drizzleOrm.sql`
170
+ `).map(i=>({date:i.date,agentId:i.agent_id,inputTokens:i.input_tokens,outputTokens:i.output_tokens,cachedInputTokens:i.cached_input_tokens,costUsd:i.cost_usd,totalTokens:i.input_tokens+i.output_tokens}))}catch(s){throw new d("DB_ERROR","Failed to get agent usage trend",s)}finally{r.close();}}findTaskForStop(t,n){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(o).where(drizzleOrm.and(drizzleOrm.eq(o.id,t),drizzleOrm.eq(o.workspace_id,n))).limit(1).get()??void 0}catch(r){throw new d("DB_ERROR","Failed to find task for stop",r)}finally{e.close();}}findLatestTaskByMetadata(t){if(!this.dbExists())return null;let n=this.openHandle(false);try{return n.db.select({id:o.id,thread_id:o.thread_id,status:o.status,result:o.result,error:o.error,started_at:o.started_at,completed_at:o.completed_at}).from(o).where(drizzleOrm.and(drizzleOrm.eq(o.agent_id,t.agentId),drizzleOrm.eq(o.workspace_id,t.workspaceId),drizzleOrm.sql`${o.metadata} IS NOT NULL AND json_valid(${o.metadata}) AND json_extract(${o.metadata}, '$.' || ${t.metaKey}) = ${t.metaValue}`)).orderBy(drizzleOrm.desc(o.started_at)).limit(1).get()??null}catch(e){throw new d("DB_ERROR","Failed to find latest task by metadata",e)}finally{n.close();}}markTaskFailed(t,n,e){if(!this.dbExists())return;let r=this.openHandle(true);try{let s=new Date().toISOString(),i=e?drizzleOrm.and(drizzleOrm.eq(o.id,t),drizzleOrm.eq(o.status,"running"),drizzleOrm.eq(o.workspace_id,e)):drizzleOrm.and(drizzleOrm.eq(o.id,t),drizzleOrm.eq(o.status,"running"));r.db.update(o).set({status:"failed",error:n,completed_at:s}).where(i).run();}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to mark task failed",s)}finally{r.close();}}findTasksByPromptHint(t,n){let e=this.resolveDbPaths(),r=new Set,s=[];for(let i of e){if(!ge.existsSync(i))continue;let l=w(i);try{let u=n?drizzleOrm.and(drizzleOrm.like(o.prompt,`%${t}%`),drizzleOrm.eq(o.workspace_id,n)):drizzleOrm.like(o.prompt,`%${t}%`),c=l.db.select().from(o).where(u).orderBy(drizzleOrm.asc(o.started_at)).all();for(let p of c)r.has(p.id)||(r.add(p.id),s.push(p));}catch(u){throw new d("DB_ERROR","Failed to find tasks by prompt hint",u)}finally{l.close();}}return s}getProviderUsage(t,n,e){if(!this.dbExists())return [];let r=this.openHandle(false);try{let s=drizzleOrm.sql`
171
171
  CASE
172
172
  WHEN ${o.model} LIKE 'claude-%' OR ${o.model} IN ('opus', 'sonnet', 'haiku', 'opus[1m]', 'sonnet[1m]') THEN 'claude'
173
173
  WHEN ${o.model} LIKE 'gpt-%' OR ${o.model} LIKE 'codex-%' THEN 'codex'
@@ -250,11 +250,11 @@ ${e.join(`
250
250
  FROM ${o}
251
251
  ${s}
252
252
  ORDER BY ${o.started_at} ASC
253
- `).map(l=>({threadId:l.thread_id,agentId:l.agent_id,startedAt:l.started_at,status:l.status,error:l.error,exitCode:l.exit_code}))}catch(s){throw new d("DB_ERROR","Failed to get tasks for report",s)}finally{r.close();}}findTaskEvidence(t){if(!this.dbExists())return [];let n=this.openHandle(false);try{let e=[];t.workspaceId&&e.push(drizzleOrm.eq(o.workspace_id,t.workspaceId)),t.agents&&t.agents.length>0&&e.push(drizzleOrm.inArray(o.agent_id,t.agents)),t.statuses&&t.statuses.length>0&&e.push(drizzleOrm.inArray(o.status,t.statuses)),t.from&&e.push(drizzleOrm.gte(o.started_at,t.from)),t.to&&e.push(drizzleOrm.lt(o.started_at,t.to));let r=e.length>0?drizzleOrm.and(...e):void 0,s=(t.order??"DESC")==="ASC"?drizzleOrm.asc(o.started_at):drizzleOrm.desc(o.started_at),i={id:o.id,agent_id:o.agent_id,status:o.status,prompt:o.prompt,started_at:o.started_at,completed_at:o.completed_at,thread_id:o.thread_id};return t.limit?n.db.select(i).from(o).where(r).orderBy(s).limit(t.limit).all():n.db.select(i).from(o).where(r).orderBy(s).all()}catch(e){throw new d("DB_ERROR","Failed to find task evidence",e)}finally{n.close();}}findThreadChains(t){if(!this.dbExists())return [];let n=this.openHandle(false);try{let e=t.maxThreads??8,r=t.maxTurnsPerThread??4,s=[drizzleOrm.isNotNull(o.thread_id),drizzleOrm.isNull(o.parent_task_id),drizzleOrm.isNull(o.caller_agent_id),drizzleOrm.or(drizzleOrm.isNull(o.platform),drizzleOrm.ne(o.platform,"workflow")),drizzleOrm.or(drizzleOrm.isNull(o.metadata),drizzleOrm.notLike(o.metadata,'%"kind":"workflow_card"%')),drizzleOrm.or(drizzleOrm.isNull(o.metadata),drizzleOrm.notLike(o.metadata,'%"retriedFromTaskId"%'))];t.workspaceId&&s.push(drizzleOrm.eq(o.workspace_id,t.workspaceId)),t.from&&s.push(drizzleOrm.gte(o.started_at,t.from)),t.to&&s.push(drizzleOrm.lt(o.started_at,t.to));let i=n.db.select({id:o.id,agent_id:o.agent_id,status:o.status,prompt:o.prompt,started_at:o.started_at,completed_at:o.completed_at,thread_id:o.thread_id}).from(o).where(drizzleOrm.and(...s)).orderBy(drizzleOrm.asc(o.started_at),drizzleOrm.asc(o.id)).all(),l=new Map;for(let c of i){if(!c.thread_id)continue;let p={id:c.id,agentId:c.agent_id,status:c.status,prompt:c.prompt,startedAt:c.started_at,completedAt:c.completed_at},f=l.get(c.thread_id);f?f.push(p):l.set(c.thread_id,[p]);}let u=[];for(let[c,p]of l){let f=p.filter(h=>h.agentId===t.targetAgentId).length;f<2||u.push({threadId:c,targetAgentTurnCount:f,turns:p});}return u.sort((c,p)=>{let f=c.turns[c.turns.length-1].startedAt,h=p.turns[p.turns.length-1].startedAt;return f<h?1:f>h?-1:0}),u.slice(0,e).map(c=>({threadId:c.threadId,targetAgentTurnCount:c.targetAgentTurnCount,turns:c.turns.slice(-r)}))}catch(e){throw new d("DB_ERROR","Failed to find thread chains",e)}finally{n.close();}}};var Kt=class extends x{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=Q.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let n=this.resolveDbPath();if(t){let r=Q.dirname(n);me.existsSync(r)||me.mkdirSync(r,{recursive:true});}else if(!me.existsSync(n))throw new d("NOT_FOUND","Database not found");let e=w(n);if(t)try{A(e.db,n);}catch(r){throw e.close(),r}return e}validateWorkspaceId(t,n){return t.db.select({id:m.id}).from(m).where(drizzleOrm.eq(m.id,n)).limit(1).get()?n:null}topLevelTaskPredicateSql(t="child"){return drizzleOrm.sql.raw(`NOT EXISTS (
253
+ `).map(l=>({threadId:l.thread_id,agentId:l.agent_id,startedAt:l.started_at,status:l.status,error:l.error,exitCode:l.exit_code}))}catch(s){throw new d("DB_ERROR","Failed to get tasks for report",s)}finally{r.close();}}findTaskEvidence(t){if(!this.dbExists())return [];let n=this.openHandle(false);try{let e=[];t.workspaceId&&e.push(drizzleOrm.eq(o.workspace_id,t.workspaceId)),t.agents&&t.agents.length>0&&e.push(drizzleOrm.inArray(o.agent_id,t.agents)),t.statuses&&t.statuses.length>0&&e.push(drizzleOrm.inArray(o.status,t.statuses)),t.from&&e.push(drizzleOrm.gte(o.started_at,t.from)),t.to&&e.push(drizzleOrm.lt(o.started_at,t.to));let r=e.length>0?drizzleOrm.and(...e):void 0,s=(t.order??"DESC")==="ASC"?drizzleOrm.asc(o.started_at):drizzleOrm.desc(o.started_at),i={id:o.id,agent_id:o.agent_id,status:o.status,prompt:o.prompt,started_at:o.started_at,completed_at:o.completed_at,thread_id:o.thread_id};return t.limit?n.db.select(i).from(o).where(r).orderBy(s).limit(t.limit).all():n.db.select(i).from(o).where(r).orderBy(s).all()}catch(e){throw new d("DB_ERROR","Failed to find task evidence",e)}finally{n.close();}}findThreadChains(t){if(!this.dbExists())return [];let n=this.openHandle(false);try{let e=t.maxThreads??8,r=t.maxTurnsPerThread??4,s=[drizzleOrm.isNotNull(o.thread_id),drizzleOrm.isNull(o.parent_task_id),drizzleOrm.isNull(o.caller_agent_id),drizzleOrm.or(drizzleOrm.isNull(o.platform),drizzleOrm.ne(o.platform,"workflow")),drizzleOrm.or(drizzleOrm.isNull(o.metadata),drizzleOrm.notLike(o.metadata,'%"kind":"workflow_card"%')),drizzleOrm.or(drizzleOrm.isNull(o.metadata),drizzleOrm.notLike(o.metadata,'%"retriedFromTaskId"%'))];t.workspaceId&&s.push(drizzleOrm.eq(o.workspace_id,t.workspaceId)),t.from&&s.push(drizzleOrm.gte(o.started_at,t.from)),t.to&&s.push(drizzleOrm.lt(o.started_at,t.to));let i=n.db.select({id:o.id,agent_id:o.agent_id,status:o.status,prompt:o.prompt,started_at:o.started_at,completed_at:o.completed_at,thread_id:o.thread_id}).from(o).where(drizzleOrm.and(...s)).orderBy(drizzleOrm.asc(o.started_at),drizzleOrm.asc(o.id)).all(),l=new Map;for(let c of i){if(!c.thread_id)continue;let p={id:c.id,agentId:c.agent_id,status:c.status,prompt:c.prompt,startedAt:c.started_at,completedAt:c.completed_at},f=l.get(c.thread_id);f?f.push(p):l.set(c.thread_id,[p]);}let u=[];for(let[c,p]of l){let f=p.filter(h=>h.agentId===t.targetAgentId).length;f<2||u.push({threadId:c,targetAgentTurnCount:f,turns:p});}return u.sort((c,p)=>{let f=c.turns[c.turns.length-1].startedAt,h=p.turns[p.turns.length-1].startedAt;return f<h?1:f>h?-1:0}),u.slice(0,e).map(c=>({threadId:c.threadId,targetAgentTurnCount:c.targetAgentTurnCount,turns:c.turns.slice(-r)}))}catch(e){throw new d("DB_ERROR","Failed to find thread chains",e)}finally{n.close();}}};var Kt=class extends x{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=Q.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let n=this.resolveDbPath();if(t){let r=Q.dirname(n);ge.existsSync(r)||ge.mkdirSync(r,{recursive:true});}else if(!ge.existsSync(n))throw new d("NOT_FOUND","Database not found");let e=w(n);if(t)try{N(e.db,n);}catch(r){throw e.close(),r}return e}validateWorkspaceId(t,n){return t.db.select({id:g.id}).from(g).where(drizzleOrm.eq(g.id,n)).limit(1).get()?n:null}topLevelTaskPredicateSql(t="child"){return drizzleOrm.sql.raw(`NOT EXISTS (
254
254
  SELECT 1 FROM tasks parent
255
255
  WHERE parent.id = ${t}.parent_task_id
256
256
  AND parent.thread_id = ${t}.thread_id
257
- )`)}findAllThreads(t){let n=this.resolveDbPaths(),e=new Set,r=[];for(let s of n){if(!me.existsSync(s))continue;let i=w(s);try{let l=t?drizzleOrm.eq(_.workspace_id,t):void 0,u=i.db.select().from(_).where(l).orderBy(drizzleOrm.desc(_.updated_at)).all();for(let c of u)e.has(c.id)||(e.add(c.id),r.push(c));}catch(l){throw new d("DB_ERROR","Failed to find all threads",l)}finally{i.close();}}return r}findThreadsByIdsOrTitles(t,n){if(t.length===0)return [];let e=this.resolveDbPaths(),r=new Set,s=[];for(let i of e){if(!me.existsSync(i))continue;let l=w(i);try{let u=drizzleOrm.or(drizzleOrm.inArray(_.id,t),drizzleOrm.inArray(_.title,t)),c=n?drizzleOrm.and(u,drizzleOrm.eq(_.workspace_id,n)):u,p=l.db.select().from(_).where(c).orderBy(drizzleOrm.desc(_.updated_at)).all();for(let f of p)r.has(f.id)||(r.add(f.id),s.push(f));}catch(u){throw new d("DB_ERROR","Failed to find threads by ids or titles",u)}finally{l.close();}}return s}findThreadById(t,n){let e=this.resolveDbPaths();for(let r of e){if(!me.existsSync(r))continue;let s=w(r);try{let i=drizzleOrm.eq(_.id,t),l=n?drizzleOrm.and(i,drizzleOrm.eq(_.workspace_id,n)):i,u=s.db.select().from(_).where(l).limit(1).get()??void 0;if(u)return u}catch(i){throw new d("DB_ERROR","Failed to find thread by id",i)}finally{s.close();}}}threadExists(t,n){let e=this.resolveDbPaths();for(let r of e){if(!me.existsSync(r))continue;let s=w(r);try{let i=drizzleOrm.eq(_.id,t),l=n?drizzleOrm.and(i,drizzleOrm.eq(_.workspace_id,n)):i;if(s.db.select({id:_.id}).from(_).where(l).limit(1).get())return !0}catch(i){throw new d("DB_ERROR","Failed to check thread existence",i)}finally{s.close();}}return false}aggregateTaskStats(t,n){let e=this.resolveDbPaths(),r=0,s=0,i=0,l=0,u=0,c=new Set;for(let p of e){if(!me.existsSync(p))continue;let f=w(p);try{let h=f.db.get(drizzleOrm.sql`
257
+ )`)}findAllThreads(t){let n=this.resolveDbPaths(),e=new Set,r=[];for(let s of n){if(!ge.existsSync(s))continue;let i=w(s);try{let l=t?drizzleOrm.eq(_.workspace_id,t):void 0,u=i.db.select().from(_).where(l).orderBy(drizzleOrm.desc(_.updated_at)).all();for(let c of u)e.has(c.id)||(e.add(c.id),r.push(c));}catch(l){throw new d("DB_ERROR","Failed to find all threads",l)}finally{i.close();}}return r}findThreadsByIdsOrTitles(t,n){if(t.length===0)return [];let e=this.resolveDbPaths(),r=new Set,s=[];for(let i of e){if(!ge.existsSync(i))continue;let l=w(i);try{let u=drizzleOrm.or(drizzleOrm.inArray(_.id,t),drizzleOrm.inArray(_.title,t)),c=n?drizzleOrm.and(u,drizzleOrm.eq(_.workspace_id,n)):u,p=l.db.select().from(_).where(c).orderBy(drizzleOrm.desc(_.updated_at)).all();for(let f of p)r.has(f.id)||(r.add(f.id),s.push(f));}catch(u){throw new d("DB_ERROR","Failed to find threads by ids or titles",u)}finally{l.close();}}return s}findThreadById(t,n){let e=this.resolveDbPaths();for(let r of e){if(!ge.existsSync(r))continue;let s=w(r);try{let i=drizzleOrm.eq(_.id,t),l=n?drizzleOrm.and(i,drizzleOrm.eq(_.workspace_id,n)):i,u=s.db.select().from(_).where(l).limit(1).get()??void 0;if(u)return u}catch(i){throw new d("DB_ERROR","Failed to find thread by id",i)}finally{s.close();}}}threadExists(t,n){let e=this.resolveDbPaths();for(let r of e){if(!ge.existsSync(r))continue;let s=w(r);try{let i=drizzleOrm.eq(_.id,t),l=n?drizzleOrm.and(i,drizzleOrm.eq(_.workspace_id,n)):i;if(s.db.select({id:_.id}).from(_).where(l).limit(1).get())return !0}catch(i){throw new d("DB_ERROR","Failed to check thread existence",i)}finally{s.close();}}return false}aggregateTaskStats(t,n){let e=this.resolveDbPaths(),r=0,s=0,i=0,l=0,u=0,c=new Set;for(let p of e){if(!ge.existsSync(p))continue;let f=w(p);try{let h=f.db.get(drizzleOrm.sql`
258
258
  SELECT
259
259
  count(*) AS cnt,
260
260
  COALESCE(SUM(child.input_tokens), 0) AS total_input,
@@ -271,7 +271,7 @@ ${e.join(`
271
271
  AND child.agent_id IS NOT NULL AND child.agent_id != ''
272
272
  AND ${this.topLevelTaskPredicateSql()}
273
273
  ${n?drizzleOrm.sql`AND child.workspace_id = ${n}`:drizzleOrm.sql``}
274
- `);for(let P of S)c.add(P.agent_id);}catch(h){throw new d("DB_ERROR","Failed to aggregate task stats",h)}finally{f.close();}}return {taskCount:r,inputTokens:s,outputTokens:i,cachedInputTokens:l,costUsd:u,agentIds:Array.from(c)}}findTopLevelTasks(t,n,e){let r=this.resolveDbPaths(),s=new Set,i=[];for(let l of r){if(!me.existsSync(l))continue;let u=w(l);try{let c;e!==void 0?c=u.db.all(drizzleOrm.sql`
274
+ `);for(let v of S)c.add(v.agent_id);}catch(h){throw new d("DB_ERROR","Failed to aggregate task stats",h)}finally{f.close();}}return {taskCount:r,inputTokens:s,outputTokens:i,cachedInputTokens:l,costUsd:u,agentIds:Array.from(c)}}findTopLevelTasks(t,n,e){let r=this.resolveDbPaths(),s=new Set,i=[];for(let l of r){if(!ge.existsSync(l))continue;let u=w(l);try{let c;e!==void 0?c=u.db.all(drizzleOrm.sql`
275
275
  SELECT * FROM (
276
276
  SELECT child.*,
277
277
  ROW_NUMBER() OVER (PARTITION BY child.agent_id ORDER BY child.started_at DESC) AS rn
@@ -288,7 +288,7 @@ ${e.join(`
288
288
  AND ${this.topLevelTaskPredicateSql()}
289
289
  ${n?drizzleOrm.sql`AND child.workspace_id = ${n}`:drizzleOrm.sql``}
290
290
  ORDER BY child.started_at ASC
291
- `);for(let p of c)s.has(p.id)||(s.add(p.id),i.push(p));}catch(c){throw new d("DB_ERROR","Failed to find top-level tasks",c)}finally{u.close();}}if(e!==void 0&&r.length>1){let l=new Map;for(let u of i){let c=u.agent_id??"";l.has(c)||l.set(c,[]),l.get(c).push(u);}i=[];for(let u of l.values())u.sort((c,p)=>(p.started_at??"").localeCompare(c.started_at??"")),i.push(...u.slice(0,e));i.sort((u,c)=>(u.started_at??"").localeCompare(c.started_at??""));}return i}findAllTasks(t,n){let e=this.resolveDbPaths(),r=new Set,s=[];for(let i of e){if(!me.existsSync(i))continue;let l=w(i);try{let u=drizzleOrm.eq(o.thread_id,t),c=n?drizzleOrm.and(u,drizzleOrm.eq(o.workspace_id,n)):u,p=l.db.select().from(o).where(c).orderBy(drizzleOrm.asc(o.started_at)).all();for(let f of p)r.has(f.id)||(r.add(f.id),s.push(f));}catch(u){throw new d("DB_ERROR","Failed to find all tasks for thread",u)}finally{l.close();}}return s}findTaskById(t,n,e){let r=this.resolveDbPaths();for(let s of r){if(!me.existsSync(s))continue;let i=w(s);try{let l=drizzleOrm.and(drizzleOrm.eq(o.id,n),drizzleOrm.eq(o.thread_id,t)),u=e?drizzleOrm.and(l,drizzleOrm.eq(o.workspace_id,e)):l,c=i.db.select().from(o).where(u).limit(1).get();if(!c)continue;let p=i.db.select().from(o).where(drizzleOrm.eq(o.parent_task_id,c.id)).orderBy(drizzleOrm.asc(o.started_at)).all();return {task:c,children:p}}catch(l){throw new d("DB_ERROR","Failed to find task by id",l)}finally{i.close();}}}batchFetchTasksQuery(t,n){return drizzleOrm.sql`
291
+ `);for(let p of c)s.has(p.id)||(s.add(p.id),i.push(p));}catch(c){throw new d("DB_ERROR","Failed to find top-level tasks",c)}finally{u.close();}}if(e!==void 0&&r.length>1){let l=new Map;for(let u of i){let c=u.agent_id??"";l.has(c)||l.set(c,[]),l.get(c).push(u);}i=[];for(let u of l.values())u.sort((c,p)=>(p.started_at??"").localeCompare(c.started_at??"")),i.push(...u.slice(0,e));i.sort((u,c)=>(u.started_at??"").localeCompare(c.started_at??""));}return i}findAllTasks(t,n){let e=this.resolveDbPaths(),r=new Set,s=[];for(let i of e){if(!ge.existsSync(i))continue;let l=w(i);try{let u=drizzleOrm.eq(o.thread_id,t),c=n?drizzleOrm.and(u,drizzleOrm.eq(o.workspace_id,n)):u,p=l.db.select().from(o).where(c).orderBy(drizzleOrm.asc(o.started_at)).all();for(let f of p)r.has(f.id)||(r.add(f.id),s.push(f));}catch(u){throw new d("DB_ERROR","Failed to find all tasks for thread",u)}finally{l.close();}}return s}findTaskById(t,n,e){let r=this.resolveDbPaths();for(let s of r){if(!ge.existsSync(s))continue;let i=w(s);try{let l=drizzleOrm.and(drizzleOrm.eq(o.id,n),drizzleOrm.eq(o.thread_id,t)),u=e?drizzleOrm.and(l,drizzleOrm.eq(o.workspace_id,e)):l,c=i.db.select().from(o).where(u).limit(1).get();if(!c)continue;let p=i.db.select().from(o).where(drizzleOrm.eq(o.parent_task_id,c.id)).orderBy(drizzleOrm.asc(o.started_at)).all();return {task:c,children:p}}catch(l){throw new d("DB_ERROR","Failed to find task by id",l)}finally{i.close();}}}batchFetchTasksQuery(t,n){return drizzleOrm.sql`
292
292
  SELECT child.id, child.thread_id, child.agent_id, child.status,
293
293
  child.parent_task_id, child.started_at, child.completed_at,
294
294
  child.duration_ms, child.input_tokens, child.output_tokens,
@@ -298,7 +298,7 @@ ${e.join(`
298
298
  AND ${this.topLevelTaskPredicateSql()}
299
299
  ${n?drizzleOrm.sql`AND child.workspace_id = ${n}`:drizzleOrm.sql``}
300
300
  ORDER BY child.started_at ASC
301
- `}batchFetchTasks(t,n){let e=new Map;if(t.length===0)return e;let r=this.resolveDbPaths();for(let s of r){if(!me.existsSync(s))continue;let i=w(s);try{let l=i.db.all(this.batchFetchTasksQuery(t,n));for(let u of l){let c=u.thread_id;e.has(c)||e.set(c,[]),e.get(c).push(u);}}catch(l){throw new d("DB_ERROR","Failed to batch fetch tasks",l)}finally{i.close();}}return e}explainBatchFetchTasksPlan(t,n){let e=this.resolveDbPaths();for(let r of e){if(!me.existsSync(r))continue;let s=w(r);try{return s.db.all(drizzleOrm.sql`EXPLAIN QUERY PLAN ${this.batchFetchTasksQuery(t,n)}`).map(l=>l.detail)}finally{s.close();}}return []}updateThreadTitle(t,n,e){if(!this.dbExists())return;let r=this.openHandle(true);try{let s=drizzleOrm.eq(_.id,t),i=e?drizzleOrm.and(s,drizzleOrm.eq(_.workspace_id,e)):s;if(!r.db.select({id:_.id}).from(_).where(i).limit(1).get())return;r.db.update(_).set({title:n,title_locked:1,updated_at:new Date().toISOString()}).where(drizzleOrm.eq(_.id,t)).run();}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to update thread title",s)}finally{r.close();}}upsertThread(t,n){let e=this.openHandle(true);try{let r=n.workspaceId?this.validateWorkspaceId(e,n.workspaceId):null,s=new Date().toISOString();if(e.db.select({id:_.id,message_count:_.message_count}).from(_).where(drizzleOrm.eq(_.id,t)).limit(1).get()){let l={updated_at:s};n.title!==void 0&&(l.title=n.title),n.titleLocked!==void 0&&(l.title_locked=n.titleLocked?1:0),e.db.update(_).set(l).where(drizzleOrm.eq(_.id,t)).run();}else e.db.insert(_).values({id:t,platform:n.platform,workspace_id:r,title:n.title??null,title_locked:n.titleLocked?1:0,message_count:0,created_at:s,updated_at:s}).run();}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to upsert thread",r)}finally{e.close();}}ensureThread(t,n,e){let r=this.openHandle(true);try{let s=e?this.validateWorkspaceId(r,e):null,i=r.db.select({id:_.id,platform:_.platform,workspace_id:_.workspace_id}).from(_).where(drizzleOrm.eq(_.id,t)).limit(1).get();if(i){s&&!i.workspace_id&&r.db.update(_).set({workspace_id:s}).where(drizzleOrm.eq(_.id,t)).run();return}let l=new Date().toISOString();r.db.insert(_).values({id:t,platform:n,workspace_id:s,message_count:0,created_at:l,updated_at:l}).run();}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to ensure thread",s)}finally{r.close();}}saveUserMessage(t,n,e){if(!this.dbExists())return {firstMessage:false};let r=this.openHandle(true);try{let s=new Date().toISOString();return {firstMessage:r.db.transaction(l=>{let c=l.select({message_count:_.message_count}).from(_).where(drizzleOrm.eq(_.id,t)).limit(1).get()?.message_count===0;return l.run(drizzleOrm.sql`
301
+ `}batchFetchTasks(t,n){let e=new Map;if(t.length===0)return e;let r=this.resolveDbPaths();for(let s of r){if(!ge.existsSync(s))continue;let i=w(s);try{let l=i.db.all(this.batchFetchTasksQuery(t,n));for(let u of l){let c=u.thread_id;e.has(c)||e.set(c,[]),e.get(c).push(u);}}catch(l){throw new d("DB_ERROR","Failed to batch fetch tasks",l)}finally{i.close();}}return e}explainBatchFetchTasksPlan(t,n){let e=this.resolveDbPaths();for(let r of e){if(!ge.existsSync(r))continue;let s=w(r);try{return s.db.all(drizzleOrm.sql`EXPLAIN QUERY PLAN ${this.batchFetchTasksQuery(t,n)}`).map(l=>l.detail)}finally{s.close();}}return []}updateThreadTitle(t,n,e){if(!this.dbExists())return;let r=this.openHandle(true);try{let s=drizzleOrm.eq(_.id,t),i=e?drizzleOrm.and(s,drizzleOrm.eq(_.workspace_id,e)):s;if(!r.db.select({id:_.id}).from(_).where(i).limit(1).get())return;r.db.update(_).set({title:n,title_locked:1,updated_at:new Date().toISOString()}).where(drizzleOrm.eq(_.id,t)).run();}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to update thread title",s)}finally{r.close();}}upsertThread(t,n){let e=this.openHandle(true);try{let r=n.workspaceId?this.validateWorkspaceId(e,n.workspaceId):null,s=new Date().toISOString();if(e.db.select({id:_.id,message_count:_.message_count}).from(_).where(drizzleOrm.eq(_.id,t)).limit(1).get()){let l={updated_at:s};n.title!==void 0&&(l.title=n.title),n.titleLocked!==void 0&&(l.title_locked=n.titleLocked?1:0),e.db.update(_).set(l).where(drizzleOrm.eq(_.id,t)).run();}else e.db.insert(_).values({id:t,platform:n.platform,workspace_id:r,title:n.title??null,title_locked:n.titleLocked?1:0,message_count:0,created_at:s,updated_at:s}).run();}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to upsert thread",r)}finally{e.close();}}ensureThread(t,n,e){let r=this.openHandle(true);try{let s=e?this.validateWorkspaceId(r,e):null,i=r.db.select({id:_.id,platform:_.platform,workspace_id:_.workspace_id}).from(_).where(drizzleOrm.eq(_.id,t)).limit(1).get();if(i){s&&!i.workspace_id&&r.db.update(_).set({workspace_id:s}).where(drizzleOrm.eq(_.id,t)).run();return}let l=new Date().toISOString();r.db.insert(_).values({id:t,platform:n,workspace_id:s,message_count:0,created_at:l,updated_at:l}).run();}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to ensure thread",s)}finally{r.close();}}saveUserMessage(t,n,e){if(!this.dbExists())return {firstMessage:false};let r=this.openHandle(true);try{let s=new Date().toISOString();return {firstMessage:r.db.transaction(l=>{let c=l.select({message_count:_.message_count}).from(_).where(drizzleOrm.eq(_.id,t)).limit(1).get()?.message_count===0;return l.run(drizzleOrm.sql`
302
302
  UPDATE threads
303
303
  SET first_message = COALESCE(first_message, ${n}),
304
304
  title = CASE WHEN title_locked = 0 AND title IS NULL THEN substr(${n}, 1, 60) ELSE title END,
@@ -306,4 +306,4 @@ ${e.join(`
306
306
  message_count = message_count + 1,
307
307
  updated_at = ${s}
308
308
  WHERE id = ${t}
309
- `),c},{behavior:"immediate"})}}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to save user message",s)}finally{r.close();}}saveAssistantMessage(t,n,e){if(!this.dbExists())return;let r=this.openHandle(true);try{let s=new Date().toISOString();r.db.update(_).set({last_message:n,updated_at:s}).where(drizzleOrm.eq(_.id,t)).run();}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to save assistant message",s)}finally{r.close();}}updateThread(t,n){if(!this.dbExists())return;let e=this.openHandle(true);try{let r={updated_at:new Date().toISOString()};n.title!==void 0&&(r.title=n.title,r.title_locked=1),n.titleLocked!==void 0&&(r.title_locked=n.titleLocked?1:0),e.db.update(_).set(r).where(drizzleOrm.eq(_.id,t)).run();}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to update thread",r)}finally{e.close();}}togglePin(t,n){let e=this.openHandle(true);try{let r=n?drizzleOrm.and(drizzleOrm.eq(_.id,t),drizzleOrm.eq(_.workspace_id,n)):drizzleOrm.eq(_.id,t),s=e.db.select({pinned:_.pinned,metadata:_.metadata}).from(_).where(r).get();if(!s)return null;let i=s.pinned?0:1,l=s.metadata?JSON.parse(s.metadata):{};if(i){let u=n?drizzleOrm.and(drizzleOrm.eq(_.pinned,1),drizzleOrm.eq(_.workspace_id,n)):drizzleOrm.eq(_.pinned,1),c=e.db.select({metadata:_.metadata}).from(_).where(u).all(),p=null;for(let f of c){let h=f.metadata?JSON.parse(f.metadata):{};typeof h.pinOrder=="number"&&(p===null||h.pinOrder<p)&&(p=h.pinOrder);}l.pinOrder=p===null?0:p-1;}else delete l.pinOrder;return e.db.update(_).set({pinned:i,metadata:Object.keys(l).length>0?JSON.stringify(l):null}).where(r).run(),{pinned:!!i}}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to toggle pin",r)}finally{e.close();}}reorderPins(t,n){let e=this.openHandle(true);try{for(let r=0;r<t.length;r++){let s=n?drizzleOrm.and(drizzleOrm.eq(_.id,t[r]),drizzleOrm.eq(_.workspace_id,n)):drizzleOrm.eq(_.id,t[r]),i=e.db.select({metadata:_.metadata}).from(_).where(s).get();if(!i)continue;let l=i.metadata?JSON.parse(i.metadata):{};l.pinOrder=r+1,e.db.update(_).set({metadata:JSON.stringify(l)}).where(s).run();}}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to reorder pins",r)}finally{e.close();}}toggleStar(t,n){let e=this.openHandle(true);try{let r=n?drizzleOrm.and(drizzleOrm.eq(_.id,t),drizzleOrm.eq(_.workspace_id,n)):drizzleOrm.eq(_.id,t),s=e.db.select({starred:_.starred}).from(_).where(r).get();if(!s)return null;let i=s.starred?0:1;return e.db.update(_).set({starred:i}).where(r).run(),{starred:!!i}}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to toggle star",r)}finally{e.close();}}resolveOverdriveForRequest(t,n,e,r){let i=this.openHandle(true);try{let l=n?drizzleOrm.and(drizzleOrm.eq(_.id,t),drizzleOrm.eq(_.workspace_id,n)):drizzleOrm.eq(_.id,t);return i.db.transaction(c=>{let p=c.select({metadata:_.metadata}).from(_).where(l).get();if(!p)return null;let f=p.metadata?JSON.parse(p.metadata):{},h=f.overdrive??{},S=r?.defaultTurns??h.defaultTurns??3,P=r?.updatedBy??"ui",$=new Date().toISOString(),H,N,G,wt;switch(e){case "enable-count":{let kt=r?.turns??S,bt=r?.consumeCurrent?Math.max(kt-1,0):kt;H=bt>0?"count":"off",N=bt,G=!0,wt="count";break}case "enable-latch":{H="latch",N=0,G=!0,wt="latch";break}case "disable":{H="off",N=0,G=!1;break}default:{let kt=h.state??"off",bt=typeof h.remaining=="number"?h.remaining:0;if(kt==="count"&&bt>0){let ne=bt-1;ne<=0?(H="off",N=0):(H="count",N=ne),G=!0,wt="count";}else kt==="latch"?(H="latch",N=0,G=!0,wt="latch"):(H="off",N=0,G=!1);break}}return f.overdrive={state:H,remaining:N,defaultTurns:S,updatedAt:$,updatedBy:P},c.update(_).set({metadata:JSON.stringify(f),updated_at:$}).where(l).run(),{applied:G,appliedMode:wt,state:H,remaining:N}},{behavior:"immediate"})}catch(l){throw l instanceof d?l:new d("DB_ERROR","Failed to resolve overdrive",l)}finally{i.close();}}};var Gt=class extends x{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=Q.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let n=this.resolveDbPath();if(t){let r=Q.dirname(n);me.existsSync(r)||me.mkdirSync(r,{recursive:true});}else if(!me.existsSync(n))throw new d("NOT_FOUND","Database not found");let e=w(n);if(t)try{A(e.db,n);}catch(r){throw e.close(),r}return e}insertSpan(t){let n=this.openHandle(true);try{n.db.insert(tt).values(t).run();}catch(e){throw e instanceof d?e:new d("DB_ERROR","Failed to insert span",e)}finally{n.close();}}findByTaskId(t){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.select().from(tt).where(drizzleOrm.eq(tt.task_id,t)).all()}catch(e){throw new d("DB_ERROR","Failed to find spans by task id",e)}finally{n.close();}}findById(t){if(!this.dbExists())return;let n=this.openHandle(false);try{return n.db.select().from(tt).where(drizzleOrm.eq(tt.id,t)).limit(1).get()??void 0}catch(e){throw new d("DB_ERROR","Failed to find span by id",e)}finally{n.close();}}};var Yt=class extends x{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=Q.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let n=this.resolveDbPath();if(t){let r=Q.dirname(n);me.existsSync(r)||me.mkdirSync(r,{recursive:true});}else if(!me.existsSync(n))throw new d("NOT_FOUND","Database not found");let e=w(n);if(t)try{A(e.db,n);}catch(r){throw e.close(),r}return e}insertToolCall(t){let n=this.openHandle(true);try{n.db.insert(J).values(t).run();}catch(e){throw e instanceof d?e:new d("DB_ERROR","Failed to insert tool call",e)}finally{n.close();}}findByTaskId(t){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.select().from(J).where(drizzleOrm.eq(J.task_id,t)).all()}catch(e){throw new d("DB_ERROR","Failed to find tool calls by task id",e)}finally{n.close();}}aggregateByName(t){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.select({toolName:J.tool_name,count:drizzleOrm.sql`count(*)`}).from(J).where(drizzleOrm.eq(J.task_id,t)).groupBy(J.tool_name).all().map(e=>({toolName:e.toolName,count:e.count}))}catch(e){throw new d("DB_ERROR","Failed to aggregate tool calls by name",e)}finally{n.close();}}};var Xt=class extends x{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=Q.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let n=this.resolveDbPath();if(t){let r=Q.dirname(n);me.existsSync(r)||me.mkdirSync(r,{recursive:true});}else if(!me.existsSync(n))throw new d("NOT_FOUND","Database not found");let e=w(n);if(t)try{A(e.db,n);}catch(r){throw e.close(),r}return e}ensureThreadExists(t,n){if(!t.db.select({id:_.id}).from(_).where(drizzleOrm.eq(_.id,n)).limit(1).get())throw new d("NOT_FOUND",`Thread not found: ${n}`)}findByThreadId(t){if(!this.dbExists())return [];let n=this.openHandle(false);try{return this.ensureThreadExists(n,t),n.db.select().from(j).where(drizzleOrm.eq(j.thread_id,t)).orderBy(drizzleOrm.asc(j.seq)).all()}catch(e){throw e instanceof d?e:new d("DB_ERROR","Failed to find boxes by thread id",e)}finally{n.close();}}findById(t,n){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(j).where(drizzleOrm.and(drizzleOrm.eq(j.id,n),drizzleOrm.eq(j.thread_id,t))).limit(1).get()??void 0}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to find box by id",r)}finally{e.close();}}insert(t){let n=this.openHandle(true);try{this.ensureThreadExists(n,t.threadId);try{n.db.insert(j).values({id:t.id,thread_id:t.threadId,seq:t.seq,first_task_id:t.first_task_id,mid_task_id:t.mid_task_id,last_task_id:t.last_task_id,task_count:t.task_count,summary:t.summary??null,source_tokens:t.source_tokens,summary_tokens:t.summary_tokens??null,created_at:t.created_at}).run();}catch(r){throw r instanceof Error&&/UNIQUE constraint failed/i.test(r.message)?new d("CONFLICT",`Duplicate seq ${String(t.seq)} for thread ${t.threadId}`,r):r}let e=n.db.select().from(j).where(drizzleOrm.eq(j.id,t.id)).limit(1).get();if(!e)throw new d("DB_ERROR","Insert did not return a row");return e}catch(e){throw e instanceof d?e:new d("DB_ERROR","Failed to insert thread box",e)}finally{n.close();}}};var Jt=class extends x{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=Q.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let n=this.resolveDbPath();if(t){let r=Q.dirname(n);me.existsSync(r)||me.mkdirSync(r,{recursive:true});}else if(!me.existsSync(n))throw new d("NOT_FOUND","Database not found");let e=w(n);if(t)try{A(e.db,n);}catch(r){throw e.close(),r}return e}bulkInsert(t){if(t.length===0)return;let n=this.openHandle(true);try{let e=new Date().toISOString();n.db.transaction(r=>{for(let s of t)r.insert(ht).values({id:crypto.randomUUID(),path:s.path,method:s.method,status_code:s.statusCode,duration_ms:s.durationMs,ip:s.ip??null,request_headers:s.requestHeaders??null,response_headers:s.responseHeaders??null,request_body:s.requestBody??null,response_body:s.responseBody??null,query:s.query??null,user_id:s.userId??null,project_id:s.projectId??null,partition_key:s.partitionKey??"default",timestamp:e,metadata:s.metadata??null}).run();});}catch(e){throw e instanceof d?e:new d("DB_ERROR","Failed to bulk insert request logs",e)}finally{n.close();}}findRecent(t=100){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.select().from(ht).orderBy(drizzleOrm.desc(ht.timestamp)).limit(t).all()}catch(e){throw new d("DB_ERROR","Failed to find recent request logs",e)}finally{n.close();}}};function Ie(a){return new Date(Math.floor(a/3e5)*3e5).toISOString()}var Vt=class extends x{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=Q.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let n=this.resolveDbPath();if(t){let r=Q.dirname(n);me.existsSync(r)||me.mkdirSync(r,{recursive:true});}else if(!me.existsSync(n))throw new d("NOT_FOUND","Database not found");let e=w(n);if(t)try{A(e.db,n);}catch(r){throw e.close(),r}return e}upsert(t){let n=this.openHandle(true);try{let e=Ie(t.bucketStartMs),r=t.accountRef??"default";n.db.insert(v).values({id:t.id,provider:t.provider,account_ref:r,limit_window:t.limitWindow,bucket_start:e,captured_at:t.capturedAt,used_percent:t.usedPercent,remaining_percent:t.remainingPercent,resets_at:t.resetsAt??null,source:t.source,metadata:t.metadata??null}).onConflictDoUpdate({target:[v.provider,v.account_ref,v.limit_window,v.bucket_start],set:{captured_at:t.capturedAt,used_percent:t.usedPercent,remaining_percent:t.remainingPercent,resets_at:t.resetsAt??null,metadata:t.metadata??null}}).run();}catch(e){throw e instanceof d?e:new d("DB_ERROR","Failed to upsert usage limit snapshot",e)}finally{n.close();}}getTrends(t){if(!this.dbExists())return [];let n=this.openHandle(false);try{let e=n.db.select({provider:v.provider,bucket_start:v.bucket_start,used_percent:v.used_percent,remaining_percent:v.remaining_percent,resets_at:v.resets_at}).from(v).where(drizzleOrm.and(drizzleOrm.eq(v.limit_window,t.window),drizzleOrm.gte(v.bucket_start,t.fromIso),drizzleOrm.lte(v.bucket_start,t.toIso))).orderBy(drizzleOrm.asc(v.bucket_start)).all(),r=new Map;for(let s of e)r.has(s.provider)||r.set(s.provider,[]),r.get(s.provider).push({bucketStart:s.bucket_start,usedPercent:s.used_percent,remainingPercent:s.remaining_percent,resetsAt:s.resets_at??null});return Array.from(r.entries()).map(([s,i])=>({provider:s,points:i}))}catch(e){throw new d("DB_ERROR","Failed to get usage limit trends",e)}finally{n.close();}}};var Qt=class extends x{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=Q.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let n=this.resolveDbPath();if(t){let r=Q.dirname(n);me.existsSync(r)||me.mkdirSync(r,{recursive:true});}else if(!me.existsSync(n))throw new d("NOT_FOUND","Database not found");let e=w(n);if(t)try{A(e.db,n);}catch(r){throw e.close(),r}return e}publish(t){let n=this.openHandle(true);try{n.db.insert(M).values({id:t.id,workspace_id:t.workspaceId,month:t.month,generated_at:t.generatedAt,source_range:t.sourceRange,tier:t.tier,total_tokens:t.totalTokens,total_cost_usd:t.totalCostUsd,payload:t.payload}).onConflictDoUpdate({target:[M.workspace_id,M.month],set:{generated_at:t.generatedAt,source_range:t.sourceRange,tier:t.tier,total_tokens:t.totalTokens,total_cost_usd:t.totalCostUsd,payload:t.payload}}).run();let e=n.db.select().from(M).where(drizzleOrm.and(drizzleOrm.eq(M.workspace_id,t.workspaceId),drizzleOrm.eq(M.month,t.month))).limit(1).get();if(!e)throw new d("DB_ERROR","Failed to read back published usage report");return e}catch(e){throw e instanceof d?e:new d("DB_ERROR","Failed to publish usage report",e)}finally{n.close();}}findByMonth(t,n){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(M).where(drizzleOrm.and(drizzleOrm.eq(M.workspace_id,t),drizzleOrm.eq(M.month,n))).limit(1).get()??void 0}catch(r){throw new d("DB_ERROR","Failed to find usage report",r)}finally{e.close();}}listByWorkspace(t){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.select().from(M).where(drizzleOrm.eq(M.workspace_id,t)).orderBy(drizzleOrm.desc(M.month)).all()}catch(e){throw new d("DB_ERROR","Failed to list usage reports",e)}finally{n.close();}}};var $e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function Sr(a){let t=crypto.randomBytes(a*2),n="";for(let e=0;e<t.length&&n.length<a;e++){let r=t[e];r<248&&(n+=$e[r%62]);}for(;n.length<a;)n+=$e[crypto.randomBytes(1)[0]%62];return n}function Lt(a){return `${a}_${Sr(8)}`}var Fe=500,ze=50,Zt=class extends x{dbPath;cap;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=Q.join(t.dbRoot,".crewx","crewx.db")),this.cap=t.cap??Fe;}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let n=this.resolveDbPath();if(t){let r=Q.dirname(n);me.existsSync(r)||me.mkdirSync(r,{recursive:true});}else if(!me.existsSync(n))throw new d("NOT_FOUND","Database not found");let e=w(n);if(t)try{A(e.db,n);}catch(r){throw e.close(),r}return e}create(t){let n=this.openHandle(true);try{let e=Lt("ntf"),r=new Date().toISOString();return n.db.insert(k).values({id:e,workspace_id:t.workspaceId,agent_id:t.agentId??null,task_id:t.taskId??null,thread_id:t.threadId??null,source:t.source??"agent",level:t.level??"info",title:t.title,body:t.body??null,target_user_id:t.targetUserId??null,created_at:r,metadata:t.metadata??null}).run(),this.enforceCap(n,t.workspaceId),{id:e}}catch(e){throw e instanceof d?e:new d("DB_ERROR","Failed to create notification",e)}finally{n.close();}}enforceCap(t,n){let s=(t.db.select({count:drizzleOrm.sql`count(*)`}).from(k).where(drizzleOrm.eq(k.workspace_id,n)).get()?.count??0)-this.cap;if(s<=0)return;let l=t.db.select({id:k.id}).from(k).innerJoin(C,drizzleOrm.eq(C.notification_id,k.id)).where(drizzleOrm.eq(k.workspace_id,n)).groupBy(k.id).orderBy(drizzleOrm.asc(k.created_at)).limit(s).all().map(u=>u.id);l.length!==0&&(t.db.delete(C).where(drizzleOrm.inArray(C.notification_id,l)).run(),t.db.delete(k).where(drizzleOrm.inArray(k.id,l)).run());}list(t){if(!this.dbExists())return [];let n=t.limit??ze,e=this.openHandle(false);try{return e.db.select({id:k.id,workspace_id:k.workspace_id,agent_id:k.agent_id,task_id:k.task_id,thread_id:k.thread_id,source:k.source,level:k.level,title:k.title,body:k.body,target_user_id:k.target_user_id,created_at:k.created_at,metadata:k.metadata,read_at:C.read_at}).from(k).leftJoin(C,drizzleOrm.and(drizzleOrm.eq(C.notification_id,k.id),drizzleOrm.eq(C.user_id,t.userId))).where(drizzleOrm.eq(k.workspace_id,t.workspaceId)).orderBy(drizzleOrm.desc(k.created_at)).limit(n).all().map(s=>({...s,read_at:s.read_at??null,read:s.read_at!=null}))}catch(r){throw new d("DB_ERROR","Failed to list notifications",r)}finally{e.close();}}unreadCount(t){if(!this.dbExists())return 0;let n=this.openHandle(false);try{return n.db.select({count:drizzleOrm.sql`count(*)`}).from(k).leftJoin(C,drizzleOrm.and(drizzleOrm.eq(C.notification_id,k.id),drizzleOrm.eq(C.user_id,t.userId))).where(drizzleOrm.and(drizzleOrm.eq(k.workspace_id,t.workspaceId),drizzleOrm.isNull(C.notification_id))).get()?.count??0}catch(e){throw new d("DB_ERROR","Failed to count unread notifications",e)}finally{n.close();}}markRead(t){let n=this.openHandle(true);try{if(!n.db.select({id:k.id}).from(k).where(drizzleOrm.and(drizzleOrm.eq(k.id,t.notificationId),drizzleOrm.eq(k.workspace_id,t.workspaceId))).get())throw new d("NOT_FOUND","Notification not found in workspace");return n.db.insert(C).values({notification_id:t.notificationId,user_id:t.userId,read_at:new Date().toISOString()}).onConflictDoNothing().run().changes>0}catch(e){throw e instanceof d?e:new d("DB_ERROR","Failed to mark notification read",e)}finally{n.close();}}markAllRead(t){let n=this.openHandle(true);try{let e=n.db.select({id:k.id}).from(k).leftJoin(C,drizzleOrm.and(drizzleOrm.eq(C.notification_id,k.id),drizzleOrm.eq(C.user_id,t.userId))).where(drizzleOrm.and(drizzleOrm.eq(k.workspace_id,t.workspaceId),drizzleOrm.isNull(C.notification_id))).all();if(e.length===0)return 0;let r=new Date().toISOString();return n.db.transaction(s=>{for(let i of e)s.insert(C).values({notification_id:i.id,user_id:t.userId,read_at:r}).onConflictDoNothing().run();}),e.length}catch(e){throw e instanceof d?e:new d("DB_ERROR","Failed to mark all notifications read",e)}finally{n.close();}}};var We=50,ee=class extends x{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=Q.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let n=this.resolveDbPath();if(t){let r=Q.dirname(n);me.existsSync(r)||me.mkdirSync(r,{recursive:true});}else if(!me.existsSync(n))throw new d("NOT_FOUND","Database not found");let e=w(n);if(t)try{A(e.db,n);}catch(r){throw e.close(),r}return e}create(t){let n=this.openHandle(true);try{let e=new Date().toISOString(),r=[],s=t.map(i=>{let l=Lt("sug");return r.push(l),{id:l,workspace_id:i.workspaceId,agent_id:i.agentId,task_id:i.taskId??null,type:i.type,status:i.status??"pending",payload:i.payload,applied_commit_sha:i.appliedCommitSha??null,created_at:e,updated_at:e}});return s.length>0&&n.db.insert(R).values(s).run(),{ids:r}}catch(e){throw e instanceof d?e:new d("DB_ERROR","Failed to create agent suggestions",e)}finally{n.close();}}findLatestSet(t,n){if(!this.dbExists())return [];let e=this.openHandle(false);try{let r=e.db.select({task_id:R.task_id}).from(R).where(drizzleOrm.and(drizzleOrm.eq(R.workspace_id,t),drizzleOrm.eq(R.agent_id,n))).orderBy(drizzleOrm.desc(R.created_at)).limit(1).get();if(!r)return [];let s=r.task_id===null?drizzleOrm.isNull(R.task_id):drizzleOrm.eq(R.task_id,r.task_id);return e.db.select().from(R).where(drizzleOrm.and(drizzleOrm.eq(R.workspace_id,t),drizzleOrm.eq(R.agent_id,n),s)).orderBy(drizzleOrm.asc(R.created_at)).all()}catch(r){throw new d("DB_ERROR","Failed to find latest agent suggestion set",r)}finally{e.close();}}findSetByTaskId(t,n,e){if(!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.select().from(R).where(drizzleOrm.and(drizzleOrm.eq(R.workspace_id,t),drizzleOrm.eq(R.agent_id,n),drizzleOrm.eq(R.task_id,e))).orderBy(drizzleOrm.asc(R.created_at)).all()}catch(s){throw new d("DB_ERROR","Failed to find agent suggestion set by task id",s)}finally{r.close();}}findById(t,n,e){if(!this.dbExists())return null;let r=this.openHandle(false);try{return r.db.select().from(R).where(drizzleOrm.and(drizzleOrm.eq(R.workspace_id,t),drizzleOrm.eq(R.agent_id,n),drizzleOrm.eq(R.id,e))).get()??null}catch(s){throw new d("DB_ERROR","Failed to find agent suggestion by id",s)}finally{r.close();}}updateStatus(t,n,e){let r=this.openHandle(true);try{let s={status:n,updated_at:new Date().toISOString()};return e!==void 0&&(s.applied_commit_sha=e),r.db.update(R).set(s).where(drizzleOrm.eq(R.id,t)).run().changes>0}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to update agent suggestion status",s)}finally{r.close();}}listByAgent(t,n,e=We){if(!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.select().from(R).where(drizzleOrm.and(drizzleOrm.eq(R.workspace_id,t),drizzleOrm.eq(R.agent_id,n))).orderBy(drizzleOrm.desc(R.created_at)).limit(e).all()}catch(s){throw new d("DB_ERROR","Failed to list agent suggestions",s)}finally{r.close();}}findDismissed(t,n,e=20){if(!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.select().from(R).where(drizzleOrm.and(drizzleOrm.eq(R.workspace_id,t),drizzleOrm.eq(R.agent_id,n),drizzleOrm.eq(R.status,"dismissed"))).orderBy(drizzleOrm.desc(R.updated_at)).limit(e).all()}catch(s){throw new d("DB_ERROR","Failed to find dismissed agent suggestions",s)}finally{r.close();}}};exports.AgentSuggestionRepository=ee;exports.BaseSqliteRepository=x;exports.DEFAULT_AGENT_SUGGESTION_LIST_LIMIT=We;exports.DEFAULT_NOTIFICATION_CAP=Fe;exports.DEFAULT_NOTIFICATION_LIST_LIMIT=ze;exports.NotificationRepository=Zt;exports.RepositoryError=d;exports.RequestLogRepository=Jt;exports.SpanRepository=Gt;exports.TaskRepository=Wt;exports.ThreadBoxRepository=Xt;exports.ThreadRepository=Kt;exports.ToolCallRepository=Yt;exports.UsageLimitSnapshotRepository=Vt;exports.UsageReportRepository=Qt;exports.WorkspaceRepository=zt;exports.calcBucketStart=Ie;exports.openDrizzleDb=w;exports.pushSchema=$n;exports.runMigrations=ft;exports.runMigrationsOnce=A;exports.tasks=o;
309
+ `),c},{behavior:"immediate"})}}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to save user message",s)}finally{r.close();}}saveAssistantMessage(t,n,e){if(!this.dbExists())return;let r=this.openHandle(true);try{let s=new Date().toISOString();r.db.update(_).set({last_message:n,updated_at:s}).where(drizzleOrm.eq(_.id,t)).run();}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to save assistant message",s)}finally{r.close();}}updateThread(t,n){if(!this.dbExists())return;let e=this.openHandle(true);try{let r={updated_at:new Date().toISOString()};n.title!==void 0&&(r.title=n.title,r.title_locked=1),n.titleLocked!==void 0&&(r.title_locked=n.titleLocked?1:0),e.db.update(_).set(r).where(drizzleOrm.eq(_.id,t)).run();}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to update thread",r)}finally{e.close();}}togglePin(t,n){let e=this.openHandle(true);try{let r=n?drizzleOrm.and(drizzleOrm.eq(_.id,t),drizzleOrm.eq(_.workspace_id,n)):drizzleOrm.eq(_.id,t),s=e.db.select({pinned:_.pinned,metadata:_.metadata}).from(_).where(r).get();if(!s)return null;let i=s.pinned?0:1,l=s.metadata?JSON.parse(s.metadata):{};if(i){let u=n?drizzleOrm.and(drizzleOrm.eq(_.pinned,1),drizzleOrm.eq(_.workspace_id,n)):drizzleOrm.eq(_.pinned,1),c=e.db.select({metadata:_.metadata}).from(_).where(u).all(),p=null;for(let f of c){let h=f.metadata?JSON.parse(f.metadata):{};typeof h.pinOrder=="number"&&(p===null||h.pinOrder<p)&&(p=h.pinOrder);}l.pinOrder=p===null?0:p-1;}else delete l.pinOrder;return e.db.update(_).set({pinned:i,metadata:Object.keys(l).length>0?JSON.stringify(l):null}).where(r).run(),{pinned:!!i}}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to toggle pin",r)}finally{e.close();}}reorderPins(t,n){let e=this.openHandle(true);try{for(let r=0;r<t.length;r++){let s=n?drizzleOrm.and(drizzleOrm.eq(_.id,t[r]),drizzleOrm.eq(_.workspace_id,n)):drizzleOrm.eq(_.id,t[r]),i=e.db.select({metadata:_.metadata}).from(_).where(s).get();if(!i)continue;let l=i.metadata?JSON.parse(i.metadata):{};l.pinOrder=r+1,e.db.update(_).set({metadata:JSON.stringify(l)}).where(s).run();}}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to reorder pins",r)}finally{e.close();}}toggleStar(t,n){let e=this.openHandle(true);try{let r=n?drizzleOrm.and(drizzleOrm.eq(_.id,t),drizzleOrm.eq(_.workspace_id,n)):drizzleOrm.eq(_.id,t),s=e.db.select({starred:_.starred}).from(_).where(r).get();if(!s)return null;let i=s.starred?0:1;return e.db.update(_).set({starred:i}).where(r).run(),{starred:!!i}}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to toggle star",r)}finally{e.close();}}resolveOverdriveForRequest(t,n,e,r){let i=this.openHandle(true);try{let l=n?drizzleOrm.and(drizzleOrm.eq(_.id,t),drizzleOrm.eq(_.workspace_id,n)):drizzleOrm.eq(_.id,t);return i.db.transaction(c=>{let p=c.select({metadata:_.metadata}).from(_).where(l).get();if(!p)return null;let f=p.metadata?JSON.parse(p.metadata):{},h=f.overdrive??{},S=r?.defaultTurns??h.defaultTurns??3,v=r?.updatedBy??"ui",$=new Date().toISOString(),M,A,G,wt;switch(e){case "enable-count":{let kt=r?.turns??S,bt=r?.consumeCurrent?Math.max(kt-1,0):kt;M=bt>0?"count":"off",A=bt,G=!0,wt="count";break}case "enable-latch":{M="latch",A=0,G=!0,wt="latch";break}case "disable":{M="off",A=0,G=!1;break}default:{let kt=h.state??"off",bt=typeof h.remaining=="number"?h.remaining:0;if(kt==="count"&&bt>0){let ne=bt-1;ne<=0?(M="off",A=0):(M="count",A=ne),G=!0,wt="count";}else kt==="latch"?(M="latch",A=0,G=!0,wt="latch"):(M="off",A=0,G=!1);break}}return f.overdrive={state:M,remaining:A,defaultTurns:S,updatedAt:$,updatedBy:v},c.update(_).set({metadata:JSON.stringify(f),updated_at:$}).where(l).run(),{applied:G,appliedMode:wt,state:M,remaining:A}},{behavior:"immediate"})}catch(l){throw l instanceof d?l:new d("DB_ERROR","Failed to resolve overdrive",l)}finally{i.close();}}};var Gt=class extends x{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=Q.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let n=this.resolveDbPath();if(t){let r=Q.dirname(n);ge.existsSync(r)||ge.mkdirSync(r,{recursive:true});}else if(!ge.existsSync(n))throw new d("NOT_FOUND","Database not found");let e=w(n);if(t)try{N(e.db,n);}catch(r){throw e.close(),r}return e}insertSpan(t){let n=this.openHandle(true);try{n.db.insert(tt).values(t).run();}catch(e){throw e instanceof d?e:new d("DB_ERROR","Failed to insert span",e)}finally{n.close();}}findByTaskId(t){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.select().from(tt).where(drizzleOrm.eq(tt.task_id,t)).all()}catch(e){throw new d("DB_ERROR","Failed to find spans by task id",e)}finally{n.close();}}findById(t){if(!this.dbExists())return;let n=this.openHandle(false);try{return n.db.select().from(tt).where(drizzleOrm.eq(tt.id,t)).limit(1).get()??void 0}catch(e){throw new d("DB_ERROR","Failed to find span by id",e)}finally{n.close();}}};var Yt=class extends x{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=Q.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let n=this.resolveDbPath();if(t){let r=Q.dirname(n);ge.existsSync(r)||ge.mkdirSync(r,{recursive:true});}else if(!ge.existsSync(n))throw new d("NOT_FOUND","Database not found");let e=w(n);if(t)try{N(e.db,n);}catch(r){throw e.close(),r}return e}insertToolCall(t){let n=this.openHandle(true);try{n.db.insert(J).values(t).run();}catch(e){throw e instanceof d?e:new d("DB_ERROR","Failed to insert tool call",e)}finally{n.close();}}findByTaskId(t){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.select().from(J).where(drizzleOrm.eq(J.task_id,t)).all()}catch(e){throw new d("DB_ERROR","Failed to find tool calls by task id",e)}finally{n.close();}}aggregateByName(t){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.select({toolName:J.tool_name,count:drizzleOrm.sql`count(*)`}).from(J).where(drizzleOrm.eq(J.task_id,t)).groupBy(J.tool_name).all().map(e=>({toolName:e.toolName,count:e.count}))}catch(e){throw new d("DB_ERROR","Failed to aggregate tool calls by name",e)}finally{n.close();}}};var Xt=class extends x{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=Q.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let n=this.resolveDbPath();if(t){let r=Q.dirname(n);ge.existsSync(r)||ge.mkdirSync(r,{recursive:true});}else if(!ge.existsSync(n))throw new d("NOT_FOUND","Database not found");let e=w(n);if(t)try{N(e.db,n);}catch(r){throw e.close(),r}return e}ensureThreadExists(t,n){if(!t.db.select({id:_.id}).from(_).where(drizzleOrm.eq(_.id,n)).limit(1).get())throw new d("NOT_FOUND",`Thread not found: ${n}`)}findByThreadId(t){if(!this.dbExists())return [];let n=this.openHandle(false);try{return this.ensureThreadExists(n,t),n.db.select().from(j).where(drizzleOrm.eq(j.thread_id,t)).orderBy(drizzleOrm.asc(j.seq)).all()}catch(e){throw e instanceof d?e:new d("DB_ERROR","Failed to find boxes by thread id",e)}finally{n.close();}}findById(t,n){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(j).where(drizzleOrm.and(drizzleOrm.eq(j.id,n),drizzleOrm.eq(j.thread_id,t))).limit(1).get()??void 0}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to find box by id",r)}finally{e.close();}}insert(t){let n=this.openHandle(true);try{this.ensureThreadExists(n,t.threadId);try{n.db.insert(j).values({id:t.id,thread_id:t.threadId,seq:t.seq,first_task_id:t.first_task_id,mid_task_id:t.mid_task_id,last_task_id:t.last_task_id,task_count:t.task_count,summary:t.summary??null,source_tokens:t.source_tokens,summary_tokens:t.summary_tokens??null,created_at:t.created_at}).run();}catch(r){throw r instanceof Error&&/UNIQUE constraint failed/i.test(r.message)?new d("CONFLICT",`Duplicate seq ${String(t.seq)} for thread ${t.threadId}`,r):r}let e=n.db.select().from(j).where(drizzleOrm.eq(j.id,t.id)).limit(1).get();if(!e)throw new d("DB_ERROR","Insert did not return a row");return e}catch(e){throw e instanceof d?e:new d("DB_ERROR","Failed to insert thread box",e)}finally{n.close();}}};var Jt=class extends x{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=Q.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let n=this.resolveDbPath();if(t){let r=Q.dirname(n);ge.existsSync(r)||ge.mkdirSync(r,{recursive:true});}else if(!ge.existsSync(n))throw new d("NOT_FOUND","Database not found");let e=w(n);if(t)try{N(e.db,n);}catch(r){throw e.close(),r}return e}bulkInsert(t){if(t.length===0)return;let n=this.openHandle(true);try{let e=new Date().toISOString();n.db.transaction(r=>{for(let s of t)r.insert(ht).values({id:crypto.randomUUID(),path:s.path,method:s.method,status_code:s.statusCode,duration_ms:s.durationMs,ip:s.ip??null,request_headers:s.requestHeaders??null,response_headers:s.responseHeaders??null,request_body:s.requestBody??null,response_body:s.responseBody??null,query:s.query??null,user_id:s.userId??null,project_id:s.projectId??null,partition_key:s.partitionKey??"default",timestamp:e,metadata:s.metadata??null}).run();});}catch(e){throw e instanceof d?e:new d("DB_ERROR","Failed to bulk insert request logs",e)}finally{n.close();}}findRecent(t=100){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.select().from(ht).orderBy(drizzleOrm.desc(ht.timestamp)).limit(t).all()}catch(e){throw new d("DB_ERROR","Failed to find recent request logs",e)}finally{n.close();}}};function Ce(a){return new Date(Math.floor(a/3e5)*3e5).toISOString()}var Vt=class extends x{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=Q.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let n=this.resolveDbPath();if(t){let r=Q.dirname(n);ge.existsSync(r)||ge.mkdirSync(r,{recursive:true});}else if(!ge.existsSync(n))throw new d("NOT_FOUND","Database not found");let e=w(n);if(t)try{N(e.db,n);}catch(r){throw e.close(),r}return e}upsert(t){let n=this.openHandle(true);try{let e=Ce(t.bucketStartMs),r=t.accountRef??"default";n.db.insert(P).values({id:t.id,provider:t.provider,account_ref:r,limit_window:t.limitWindow,bucket_start:e,captured_at:t.capturedAt,used_percent:t.usedPercent,remaining_percent:t.remainingPercent,resets_at:t.resetsAt??null,source:t.source,metadata:t.metadata??null}).onConflictDoUpdate({target:[P.provider,P.account_ref,P.limit_window,P.bucket_start],set:{captured_at:t.capturedAt,used_percent:t.usedPercent,remaining_percent:t.remainingPercent,resets_at:t.resetsAt??null,metadata:t.metadata??null}}).run();}catch(e){throw e instanceof d?e:new d("DB_ERROR","Failed to upsert usage limit snapshot",e)}finally{n.close();}}getTrends(t){if(!this.dbExists())return [];let n=this.openHandle(false);try{let e=n.db.select({provider:P.provider,bucket_start:P.bucket_start,used_percent:P.used_percent,remaining_percent:P.remaining_percent,resets_at:P.resets_at}).from(P).where(drizzleOrm.and(drizzleOrm.eq(P.limit_window,t.window),drizzleOrm.gte(P.bucket_start,t.fromIso),drizzleOrm.lte(P.bucket_start,t.toIso))).orderBy(drizzleOrm.asc(P.bucket_start)).all(),r=new Map;for(let s of e)r.has(s.provider)||r.set(s.provider,[]),r.get(s.provider).push({bucketStart:s.bucket_start,usedPercent:s.used_percent,remainingPercent:s.remaining_percent,resetsAt:s.resets_at??null});return Array.from(r.entries()).map(([s,i])=>({provider:s,points:i}))}catch(e){throw new d("DB_ERROR","Failed to get usage limit trends",e)}finally{n.close();}}};var Qt=class extends x{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=Q.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let n=this.resolveDbPath();if(t){let r=Q.dirname(n);ge.existsSync(r)||ge.mkdirSync(r,{recursive:true});}else if(!ge.existsSync(n))throw new d("NOT_FOUND","Database not found");let e=w(n);if(t)try{N(e.db,n);}catch(r){throw e.close(),r}return e}publish(t){let n=this.openHandle(true);try{n.db.insert(H).values({id:t.id,workspace_id:t.workspaceId,month:t.month,generated_at:t.generatedAt,source_range:t.sourceRange,tier:t.tier,total_tokens:t.totalTokens,total_cost_usd:t.totalCostUsd,payload:t.payload}).onConflictDoUpdate({target:[H.workspace_id,H.month],set:{generated_at:t.generatedAt,source_range:t.sourceRange,tier:t.tier,total_tokens:t.totalTokens,total_cost_usd:t.totalCostUsd,payload:t.payload}}).run();let e=n.db.select().from(H).where(drizzleOrm.and(drizzleOrm.eq(H.workspace_id,t.workspaceId),drizzleOrm.eq(H.month,t.month))).limit(1).get();if(!e)throw new d("DB_ERROR","Failed to read back published usage report");return e}catch(e){throw e instanceof d?e:new d("DB_ERROR","Failed to publish usage report",e)}finally{n.close();}}findByMonth(t,n){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(H).where(drizzleOrm.and(drizzleOrm.eq(H.workspace_id,t),drizzleOrm.eq(H.month,n))).limit(1).get()??void 0}catch(r){throw new d("DB_ERROR","Failed to find usage report",r)}finally{e.close();}}listByWorkspace(t){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.select().from(H).where(drizzleOrm.eq(H.workspace_id,t)).orderBy(drizzleOrm.desc(H.month)).all()}catch(e){throw new d("DB_ERROR","Failed to list usage reports",e)}finally{n.close();}}};var $e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function xr(a){let t=crypto.randomBytes(a*2),n="";for(let e=0;e<t.length&&n.length<a;e++){let r=t[e];r<248&&(n+=$e[r%62]);}for(;n.length<a;)n+=$e[crypto.randomBytes(1)[0]%62];return n}function Lt(a){return `${a}_${xr(8)}`}var Fe=500,ze=50,Zt=class extends x{dbPath;cap;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=Q.join(t.dbRoot,".crewx","crewx.db")),this.cap=t.cap??Fe;}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let n=this.resolveDbPath();if(t){let r=Q.dirname(n);ge.existsSync(r)||ge.mkdirSync(r,{recursive:true});}else if(!ge.existsSync(n))throw new d("NOT_FOUND","Database not found");let e=w(n);if(t)try{N(e.db,n);}catch(r){throw e.close(),r}return e}create(t){let n=this.openHandle(true);try{let e=Lt("ntf"),r=new Date().toISOString();return n.db.insert(k).values({id:e,workspace_id:t.workspaceId,agent_id:t.agentId??null,task_id:t.taskId??null,thread_id:t.threadId??null,source:t.source??"agent",level:t.level??"info",title:t.title,body:t.body??null,target_user_id:t.targetUserId??null,created_at:r,metadata:t.metadata??null}).run(),this.enforceCap(n,t.workspaceId),{id:e}}catch(e){throw e instanceof d?e:new d("DB_ERROR","Failed to create notification",e)}finally{n.close();}}enforceCap(t,n){let s=(t.db.select({count:drizzleOrm.sql`count(*)`}).from(k).where(drizzleOrm.eq(k.workspace_id,n)).get()?.count??0)-this.cap;if(s<=0)return;let l=t.db.select({id:k.id}).from(k).innerJoin(I,drizzleOrm.eq(I.notification_id,k.id)).where(drizzleOrm.eq(k.workspace_id,n)).groupBy(k.id).orderBy(drizzleOrm.asc(k.created_at)).limit(s).all().map(u=>u.id);l.length!==0&&(t.db.delete(I).where(drizzleOrm.inArray(I.notification_id,l)).run(),t.db.delete(k).where(drizzleOrm.inArray(k.id,l)).run());}list(t){if(!this.dbExists())return [];let n=t.limit??ze,e=this.openHandle(false);try{return e.db.select({id:k.id,workspace_id:k.workspace_id,agent_id:k.agent_id,task_id:k.task_id,thread_id:k.thread_id,source:k.source,level:k.level,title:k.title,body:k.body,target_user_id:k.target_user_id,created_at:k.created_at,metadata:k.metadata,read_at:I.read_at}).from(k).leftJoin(I,drizzleOrm.and(drizzleOrm.eq(I.notification_id,k.id),drizzleOrm.eq(I.user_id,t.userId))).where(drizzleOrm.eq(k.workspace_id,t.workspaceId)).orderBy(drizzleOrm.desc(k.created_at)).limit(n).all().map(s=>({...s,read_at:s.read_at??null,read:s.read_at!=null}))}catch(r){throw new d("DB_ERROR","Failed to list notifications",r)}finally{e.close();}}unreadCount(t){if(!this.dbExists())return 0;let n=this.openHandle(false);try{return n.db.select({count:drizzleOrm.sql`count(*)`}).from(k).leftJoin(I,drizzleOrm.and(drizzleOrm.eq(I.notification_id,k.id),drizzleOrm.eq(I.user_id,t.userId))).where(drizzleOrm.and(drizzleOrm.eq(k.workspace_id,t.workspaceId),drizzleOrm.isNull(I.notification_id))).get()?.count??0}catch(e){throw new d("DB_ERROR","Failed to count unread notifications",e)}finally{n.close();}}markRead(t){let n=this.openHandle(true);try{if(!n.db.select({id:k.id}).from(k).where(drizzleOrm.and(drizzleOrm.eq(k.id,t.notificationId),drizzleOrm.eq(k.workspace_id,t.workspaceId))).get())throw new d("NOT_FOUND","Notification not found in workspace");return n.db.insert(I).values({notification_id:t.notificationId,user_id:t.userId,read_at:new Date().toISOString()}).onConflictDoNothing().run().changes>0}catch(e){throw e instanceof d?e:new d("DB_ERROR","Failed to mark notification read",e)}finally{n.close();}}markAllRead(t){let n=this.openHandle(true);try{let e=n.db.select({id:k.id}).from(k).leftJoin(I,drizzleOrm.and(drizzleOrm.eq(I.notification_id,k.id),drizzleOrm.eq(I.user_id,t.userId))).where(drizzleOrm.and(drizzleOrm.eq(k.workspace_id,t.workspaceId),drizzleOrm.isNull(I.notification_id))).all();if(e.length===0)return 0;let r=new Date().toISOString();return n.db.transaction(s=>{for(let i of e)s.insert(I).values({notification_id:i.id,user_id:t.userId,read_at:r}).onConflictDoNothing().run();}),e.length}catch(e){throw e instanceof d?e:new d("DB_ERROR","Failed to mark all notifications read",e)}finally{n.close();}}};var We=50,ee=class extends x{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=Q.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let n=this.resolveDbPath();if(t){let r=Q.dirname(n);ge.existsSync(r)||ge.mkdirSync(r,{recursive:true});}else if(!ge.existsSync(n))throw new d("NOT_FOUND","Database not found");let e=w(n);if(t)try{N(e.db,n);}catch(r){throw e.close(),r}return e}create(t){let n=this.openHandle(true);try{let e=new Date().toISOString(),r=[],s=t.map(i=>{let l=Lt("sug");return r.push(l),{id:l,workspace_id:i.workspaceId,agent_id:i.agentId,task_id:i.taskId??null,type:i.type,status:i.status??"pending",payload:i.payload,applied_commit_sha:i.appliedCommitSha??null,created_at:e,updated_at:e}});return s.length>0&&n.db.insert(R).values(s).run(),{ids:r}}catch(e){throw e instanceof d?e:new d("DB_ERROR","Failed to create agent suggestions",e)}finally{n.close();}}findLatestSet(t,n){if(!this.dbExists())return [];let e=this.openHandle(false);try{let r=e.db.select({task_id:R.task_id}).from(R).where(drizzleOrm.and(drizzleOrm.eq(R.workspace_id,t),drizzleOrm.eq(R.agent_id,n))).orderBy(drizzleOrm.desc(R.created_at)).limit(1).get();if(!r)return [];let s=r.task_id===null?drizzleOrm.isNull(R.task_id):drizzleOrm.eq(R.task_id,r.task_id);return e.db.select().from(R).where(drizzleOrm.and(drizzleOrm.eq(R.workspace_id,t),drizzleOrm.eq(R.agent_id,n),s)).orderBy(drizzleOrm.asc(R.created_at)).all()}catch(r){throw new d("DB_ERROR","Failed to find latest agent suggestion set",r)}finally{e.close();}}findSetByTaskId(t,n,e){if(!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.select().from(R).where(drizzleOrm.and(drizzleOrm.eq(R.workspace_id,t),drizzleOrm.eq(R.agent_id,n),drizzleOrm.eq(R.task_id,e))).orderBy(drizzleOrm.asc(R.created_at)).all()}catch(s){throw new d("DB_ERROR","Failed to find agent suggestion set by task id",s)}finally{r.close();}}findById(t,n,e){if(!this.dbExists())return null;let r=this.openHandle(false);try{return r.db.select().from(R).where(drizzleOrm.and(drizzleOrm.eq(R.workspace_id,t),drizzleOrm.eq(R.agent_id,n),drizzleOrm.eq(R.id,e))).get()??null}catch(s){throw new d("DB_ERROR","Failed to find agent suggestion by id",s)}finally{r.close();}}updateStatus(t,n,e){let r=this.openHandle(true);try{let s={status:n,updated_at:new Date().toISOString()};return e!==void 0&&(s.applied_commit_sha=e),r.db.update(R).set(s).where(drizzleOrm.eq(R.id,t)).run().changes>0}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to update agent suggestion status",s)}finally{r.close();}}listByAgent(t,n,e=We){if(!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.select().from(R).where(drizzleOrm.and(drizzleOrm.eq(R.workspace_id,t),drizzleOrm.eq(R.agent_id,n))).orderBy(drizzleOrm.desc(R.created_at)).limit(e).all()}catch(s){throw new d("DB_ERROR","Failed to list agent suggestions",s)}finally{r.close();}}findDismissed(t,n,e=20){if(!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.select().from(R).where(drizzleOrm.and(drizzleOrm.eq(R.workspace_id,t),drizzleOrm.eq(R.agent_id,n),drizzleOrm.eq(R.status,"dismissed"))).orderBy(drizzleOrm.desc(R.updated_at)).limit(e).all()}catch(s){throw new d("DB_ERROR","Failed to find dismissed agent suggestions",s)}finally{r.close();}}};exports.AgentSuggestionRepository=ee;exports.BaseSqliteRepository=x;exports.DEFAULT_AGENT_SUGGESTION_LIST_LIMIT=We;exports.DEFAULT_NOTIFICATION_CAP=Fe;exports.DEFAULT_NOTIFICATION_LIST_LIMIT=ze;exports.NotificationRepository=Zt;exports.RepositoryError=d;exports.RequestLogRepository=Jt;exports.SpanRepository=Gt;exports.TaskRepository=Wt;exports.ThreadBoxRepository=Xt;exports.ThreadRepository=Kt;exports.ToolCallRepository=Yt;exports.UsageLimitSnapshotRepository=Vt;exports.UsageReportRepository=Qt;exports.WorkspaceRepository=zt;exports.calcBucketStart=Ce;exports.openDrizzleDb=w;exports.pushSchema=$n;exports.runMigrations=ft;exports.runMigrationsOnce=N;exports.tasks=o;
@@ -1 +1 @@
1
- 'use strict';function f(){let e=[];return {events:e,async log(t,o){e.push({event:t,payload:o});}}}function m(){let e={debug:[],info:[],warn:[],error:[]};return {entries:e,debug(t,o){e.debug.push({msg:t,meta:o});},info(t,o){e.info.push({msg:t,meta:o});},warn(t,o){e.warn.push({msg:t,meta:o});},error(t,o){e.error.push({msg:t,meta:o});}}}function b(){let e=200,t,o,r={},n={status(i){return e=i,n},set(i,s){return r[i]=s,n},send(i){return o=i,n},json(i){return t=i,n},end(){return n},getStatusCode:()=>e,getJsonBody:()=>t,getSentBody:()=>o,getHeaders:()=>({...r})};return n}function h(){let e=[];return {routes:e,registerRoute(o,r,n){e.push({path:o,handler:r,opts:n});},async simulate(o,r,n=Buffer.alloc(0),i={},s={},g={}){let c=e.find(p=>p.path===r);if(!c)return {status:404,body:{error:"Not found"},headers:{}};let l={method:o,url:r,headers:i,body:n,params:s,query:g},u=b();return await c.handler(l,u),{status:u.getStatusCode(),body:u.getJsonBody()??u.getSentBody(),headers:u.getHeaders()}}}}function M(e){let t=new Map,o=r=>r.startsWith(`${e}::`)?r:`${e}::${r}`;return {async get(r){let n=t.get(o(r));return n?n.value:void 0},async set(r,n){t.set(o(r),{value:n});},async delete(r){return t.delete(o(r))},async list(r){let n=r?o(r):`${e}::`,i=[];for(let s of t.keys())s.startsWith(n)&&i.push(s.slice(e.length+2));return i}}}function x(e){return M(e)}function y(){let e=new Map;return {blobs:e,async put(t,o,r){return e.set(t,{data:o,contentType:r}),t},async get(t){let o=e.get(t);return o?o.data:void 0},async delete(t){return e.delete(t)}}}function S(e){let t=e.instanceId??"mock-instance",o=f(),r=m(),n=h(),i=x(t),s=y(),g=[],c=[],l=[],u={run:async()=>({output:""}),...e.agentRunner},p=new AbortController,v=async a=>(g.push(a),{accepted:true}),k=async a=>(c.push(a),{accepted:true}),R=async(a,O)=>{l.push({messageId:a,patch:O});},E=async a=>({userId:a,displayName:a}),C=async()=>{},w=async()=>({messageId:"mock-proactive",sentAt:Date.now()});return {instanceId:t,installationId:e.installationId,config:e.config,capabilities:new Set(e.capabilities??[]),log:r,agentRunner:u,db:i,storage:s,audit:o,abortSignal:e.abortSignal??p.signal,httpRouter:n,router:n,inbound:v,emitEvent:k,updateMessage:R,resolveUser:E,respondSync:C,proactive:w,inboundCalls:g,emittedEvents:c,sentMessages:l}}function T(){}var P={claude:{models:[{id:"claude-fable-5",name:"Claude Fable 5",contextWindowTokens:1e6},{id:"claude-opus-5",name:"Claude Opus 5",contextWindowTokens:1e6},{id:"claude-sonnet-5",name:"Claude Sonnet 5",contextWindowTokens:1e6},{id:"claude-opus-4-8[1m]",name:"Claude Opus 4.8 (Extended)",contextWindowTokens:1e6},{id:"claude-opus-4-8",name:"Claude Opus 4.8",contextWindowTokens:1e6},{id:"claude-opus-4-7[1m]",name:"Claude Opus 4.7 (Extended)",contextWindowTokens:1e6},{id:"claude-opus-4-7",name:"Claude Opus 4.7",contextWindowTokens:1e6},{id:"claude-opus-4-6[1m]",name:"Claude Opus 4.6 (Extended)",contextWindowTokens:1e6},{id:"claude-opus-4-6",name:"Claude Opus 4.6",contextWindowTokens:1e6},{id:"claude-sonnet-4-6[1m]",name:"Claude Sonnet 4.6 (Extended)",contextWindowTokens:1e6},{id:"claude-sonnet-4-6",name:"Claude Sonnet 4.6",contextWindowTokens:1e6},{id:"claude-haiku-4-5",name:"Claude Haiku 4.5",contextWindowTokens:2e5}],modes:[{id:"default",name:"Default"},{id:"acceptEdits",name:"Accept Edits"},{id:"plan",name:"Plan"},{id:"auto",name:"Auto"},{id:"dontAsk",name:"Don't Ask"},{id:"bypassPermissions",name:"Bypass Permissions"}],effort:["low","medium","high"],modelOverrides:{"claude-fable-5":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-opus-5":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-sonnet-5":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-opus-4-8[1m]":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-opus-4-8":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-opus-4-7[1m]":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-opus-4-7":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-opus-4-6[1m]":{effort:["low","medium","high","max"],defaultEffort:"high"},"claude-opus-4-6":{effort:["low","medium","high","max"],defaultEffort:"high"},"claude-sonnet-4-6[1m]":{effort:["low","medium","high","max"],defaultEffort:"high"},"claude-sonnet-4-6":{effort:["low","medium","high","max"],defaultEffort:"high"},"claude-haiku-4-5":{effort:[]}}},codex:{models:[{id:"gpt-5.6-sol",name:"GPT-5.6 Sol",contextWindowTokens:105e4},{id:"gpt-5.6-terra",name:"GPT-5.6 Terra",contextWindowTokens:105e4},{id:"gpt-5.6-luna",name:"GPT-5.6 Luna",contextWindowTokens:105e4},{id:"gpt-5.5",name:"GPT-5.5"},{id:"gpt-5.4",name:"GPT-5.4"},{id:"gpt-5.4-mini",name:"GPT-5.4 Mini"},{id:"gpt-5.3-codex",name:"GPT-5.3 Codex"},{id:"gpt-5.3-codex-spark",name:"GPT-5.3 Codex Spark"}],modes:[{id:"agent",name:"Agent"},{id:"read-only",name:"Read Only"},{id:"plan",name:"Plan"},{id:"agent-full-access",name:"Agent Full Access"},{id:"yolo",name:"YOLO"}],effort:["minimal","low","medium","high"],modelOverrides:{"gpt-5.6-sol":{effort:["none","low","medium","high","xhigh","max"],defaultEffort:"xhigh"},"gpt-5.6-terra":{effort:["none","low","medium","high","xhigh","max"],defaultEffort:"high"},"gpt-5.6-luna":{effort:["none","low","medium","high","xhigh","max"],defaultEffort:"high"},"gpt-5.5":{effort:["minimal","low","medium","high","xhigh"],defaultEffort:"high"}}},copilot:{models:[{id:"auto",name:"Auto"},{id:"claude-sonnet-5",name:"Claude Sonnet 5"},{id:"claude-sonnet-4-6",name:"Claude Sonnet 4.6"},{id:"gpt-5.5",name:"GPT-5.5"},{id:"gpt-5.4",name:"GPT-5.4"},{id:"gemini-3.1-pro",name:"Gemini 3.1 Pro"}],modes:[{id:"interactive",name:"Interactive"},{id:"plan",name:"Plan"},{id:"autopilot",name:"Autopilot"}],effort:["none","low","medium","high","xhigh","max"],modelOverrides:{}},antigravity:{models:[{id:"Gemini 3.5 Flash (Medium)",name:"Gemini 3.5 Flash (Medium)"},{id:"Gemini 3.5 Flash (High)",name:"Gemini 3.5 Flash (High)"},{id:"Gemini 3.5 Flash (Low)",name:"Gemini 3.5 Flash (Low)"},{id:"Gemini 3.1 Pro (Low)",name:"Gemini 3.1 Pro (Low)"},{id:"Gemini 3.1 Pro (High)",name:"Gemini 3.1 Pro (High)"},{id:"Claude Sonnet 4.6 (Thinking)",name:"Claude Sonnet 4.6 (Thinking)"},{id:"Claude Opus 4.6 (Thinking)",name:"Claude Opus 4.6 (Thinking)"},{id:"GPT-OSS 120B (Medium)",name:"GPT-OSS 120B (Medium)"}],modes:[],effort:[],modelOverrides:{}}};Object.fromEntries(Object.entries(P).map(([e,t])=>[e,t.models]));function D(){}exports.createMockAudit=f;exports.createMockContext=S;exports.createMockLogger=m;exports.createMockRouter=h;exports.createMockStorage=y;exports.createMockStore=x;exports.resetModelsOverride=D;exports.resetPricingOverride=T;
1
+ 'use strict';function m(){let e=[];return {events:e,async log(t,o){e.push({event:t,payload:o});}}}function f(){let e={debug:[],info:[],warn:[],error:[]};return {entries:e,debug(t,o){e.debug.push({msg:t,meta:o});},info(t,o){e.info.push({msg:t,meta:o});},warn(t,o){e.warn.push({msg:t,meta:o});},error(t,o){e.error.push({msg:t,meta:o});}}}function O(){let e=200,t,o,n={},r={status(i){return e=i,r},set(i,d){return n[i]=d,r},send(i){return o=i,r},json(i){return t=i,r},end(){return r},getStatusCode:()=>e,getJsonBody:()=>t,getSentBody:()=>o,getHeaders:()=>({...n})};return r}function h(){let e=[];return {routes:e,registerRoute(o,n,r){e.push({path:o,handler:n,opts:r});},async simulate(o,n,r=Buffer.alloc(0),i={},d={},p={}){let u=e.find(g=>g.path===n);if(!u)return {status:404,body:{error:"Not found"},headers:{}};let l={method:o,url:n,headers:i,body:r,params:d,query:p},c=O();return await u.handler(l,c),{status:c.getStatusCode(),body:c.getJsonBody()??c.getSentBody(),headers:c.getHeaders()}}}}function P(e){let t=new Map,o=n=>n.startsWith(`${e}::`)?n:`${e}::${n}`;return {async get(n){let r=t.get(o(n));return r?r.value:void 0},async set(n,r){t.set(o(n),{value:r});},async delete(n){return t.delete(o(n))},async list(n){let r=n?o(n):`${e}::`,i=[];for(let d of t.keys())d.startsWith(r)&&i.push(d.slice(e.length+2));return i}}}function x(e){return P(e)}function M(){let e=new Map;return {blobs:e,async put(t,o,n){return e.set(t,{data:o,contentType:n}),t},async get(t){let o=e.get(t);return o?o.data:void 0},async delete(t){return e.delete(t)}}}function T(e){let t=e.instanceId??"mock-instance",o=m(),n=f(),r=h(),i=x(t),d=M(),p=[],u=[],l=[],c={run:async()=>({output:""}),...e.agentRunner},g=new AbortController,k=async a=>(p.push(a),{accepted:true}),v=async a=>(u.push(a),{accepted:true}),w=async(a,C)=>{l.push({messageId:a,patch:C});},E=async a=>({userId:a,displayName:a}),R=async()=>{},b=async()=>({messageId:"mock-proactive",sentAt:Date.now()});return {instanceId:t,installationId:e.installationId,config:e.config,capabilities:new Set(e.capabilities??[]),log:n,agentRunner:c,db:i,storage:d,audit:o,abortSignal:e.abortSignal??g.signal,httpRouter:r,router:r,inbound:k,emitEvent:v,updateMessage:w,resolveUser:E,respondSync:R,proactive:b,inboundCalls:p,emittedEvents:u,sentMessages:l}}function D(){}var y={claude:{models:[{id:"claude-fable-5",name:"Claude Fable 5",contextWindowTokens:1e6,tier:"flagship",recommended:true},{id:"claude-opus-5",name:"Claude Opus 5",contextWindowTokens:1e6,tier:"flagship",recommended:true},{id:"claude-sonnet-5",name:"Claude Sonnet 5",contextWindowTokens:1e6,tier:"balanced",recommended:true},{id:"claude-opus-4-8[1m]",name:"Claude Opus 4.8",contextWindowTokens:1e6,tier:"flagship"},{id:"claude-opus-4-7[1m]",name:"Claude Opus 4.7",contextWindowTokens:1e6,tier:"flagship"},{id:"claude-opus-4-6[1m]",name:"Claude Opus 4.6",contextWindowTokens:1e6,tier:"flagship"},{id:"claude-sonnet-4-6[1m]",name:"Claude Sonnet 4.6",contextWindowTokens:1e6,tier:"balanced"},{id:"claude-haiku-4-5",name:"Claude Haiku 4.5",contextWindowTokens:2e5,tier:"speed"}],modes:[{id:"default",name:"Default",description:"Uses Claude's default permission handling with normal approval prompts."},{id:"acceptEdits",name:"Accept Edits",description:"Allows file edits without approval; other permission checks remain in place."},{id:"plan",name:"Plan",description:"Keeps Claude in plan mode so it can inspect and propose changes without applying them."},{id:"dontAsk",name:"Don't Ask",description:"Does not ask for permissions; only pre-approved tool actions can proceed."},{id:"bypassPermissions",name:"Bypass Permissions",description:"Bypasses Claude permission checks so tools can run without approval prompts."}],effort:["low","medium","high"],modelOverrides:{"claude-fable-5":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-opus-5":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-sonnet-5":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-opus-4-8[1m]":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-opus-4-7[1m]":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-opus-4-6[1m]":{effort:["low","medium","high","max"],defaultEffort:"high"},"claude-sonnet-4-6[1m]":{effort:["low","medium","high","max"],defaultEffort:"high"},"claude-haiku-4-5":{effort:[]}}},codex:{models:[{id:"gpt-5.6-sol",name:"GPT-5.6 Sol",contextWindowTokens:105e4,tier:"flagship",recommended:true},{id:"gpt-5.6-terra",name:"GPT-5.6 Terra",contextWindowTokens:105e4,tier:"balanced",recommended:true},{id:"gpt-5.6-luna",name:"GPT-5.6 Luna",contextWindowTokens:105e4,tier:"speed",recommended:true},{id:"gpt-5.5",name:"GPT-5.5",contextWindowTokens:105e4,tier:"flagship"},{id:"gpt-5.4",name:"GPT-5.4",contextWindowTokens:105e4,tier:"flagship"},{id:"gpt-5.4-mini",name:"GPT-5.4 Mini",contextWindowTokens:4e5,tier:"speed"},{id:"gpt-5.3-codex",name:"GPT-5.3 Codex",contextWindowTokens:4e5,tier:"flagship"},{id:"gpt-5.3-codex-spark",name:"GPT-5.3 Codex Spark",contextWindowTokens:128e3,tier:"speed"}],modes:[{id:"agent",name:"Agent",description:"Uses the workspace-write sandbox; can read and modify workspace files without full machine access."},{id:"read-only",name:"Read Only",description:"Uses the read-only sandbox; can inspect files but cannot write to the workspace."},{id:"plan",name:"Plan",description:"Uses the read-only sandbox for planning and inspection; cannot write to the workspace."},{id:"agent-full-access",name:"Agent Full Access",description:"Bypasses approvals and the sandbox; can access and modify files beyond the workspace."},{id:"yolo",name:"YOLO",description:"Bypasses approvals and the sandbox for unrestricted execution and full filesystem access."}],effort:["minimal","low","medium","high"],modelOverrides:{"gpt-5.6-sol":{effort:["none","low","medium","high","xhigh","max"],defaultEffort:"xhigh"},"gpt-5.6-terra":{effort:["none","low","medium","high","xhigh","max"],defaultEffort:"high"},"gpt-5.6-luna":{effort:["none","low","medium","high","xhigh","max"],defaultEffort:"high"},"gpt-5.5":{effort:["minimal","low","medium","high","xhigh"],defaultEffort:"high"}}},opencode:{models:[],modes:[{id:"plan",name:"Plan",description:"Uses the plan agent without --auto; planning follows standard approval behavior."},{id:"plan-auto",name:"Plan \xB7 Auto",description:"Uses the plan agent with --auto; planning uses automatic approvals."},{id:"build",name:"Build",description:"Uses the build agent without --auto; work follows standard approval behavior."},{id:"build-auto",name:"Build \xB7 Auto",description:"Uses the build agent with --auto; work uses automatic approvals."}],effort:[],modelOverrides:{}},copilot:{models:[{id:"auto",name:"Auto"},{id:"claude-sonnet-5",name:"Claude Sonnet 5",contextWindowTokens:1e6,tier:"balanced"},{id:"claude-sonnet-4-6",name:"Claude Sonnet 4.6",contextWindowTokens:1e6,tier:"balanced"},{id:"gpt-5.5",name:"GPT-5.5",contextWindowTokens:105e4,tier:"flagship"},{id:"gpt-5.4",name:"GPT-5.4",contextWindowTokens:105e4,tier:"flagship"},{id:"gemini-3.1-pro",name:"Gemini 3.1 Pro",contextWindowTokens:1048576,tier:"flagship"}],modes:[{id:"interactive",name:"Interactive",description:"Passes --mode interactive; tool access follows Copilot's interactive mode behavior."},{id:"plan",name:"Plan",description:"Passes --mode plan; planning and permission behavior follow Copilot's plan mode."},{id:"autopilot",name:"Autopilot",description:"Passes --mode autopilot; execution behavior follows Copilot's autonomous mode."}],effort:["none","low","medium","high","xhigh","max"],modelOverrides:{}},antigravity:{models:[{id:"gemini-3.6-flash-high",name:"Gemini 3.6 Flash (High)",contextWindowTokens:1048576,tier:"balanced"},{id:"gemini-3.6-flash-medium",name:"Gemini 3.6 Flash (Medium)",contextWindowTokens:1048576,tier:"balanced"},{id:"gemini-3.6-flash-low",name:"Gemini 3.6 Flash (Low)",contextWindowTokens:1048576,tier:"balanced"},{id:"Gemini 3.5 Flash (Medium)",name:"Gemini 3.5 Flash (Medium)",contextWindowTokens:1048576,tier:"balanced"},{id:"Gemini 3.5 Flash (High)",name:"Gemini 3.5 Flash (High)",contextWindowTokens:1048576,tier:"balanced"},{id:"Gemini 3.5 Flash (Low)",name:"Gemini 3.5 Flash (Low)",contextWindowTokens:1048576,tier:"balanced"},{id:"Gemini 3.1 Pro (Low)",name:"Gemini 3.1 Pro (Low)",contextWindowTokens:1048576,tier:"flagship"},{id:"Gemini 3.1 Pro (High)",name:"Gemini 3.1 Pro (High)",contextWindowTokens:1048576,tier:"flagship"},{id:"Claude Sonnet 4.6 (Thinking)",name:"Claude Sonnet 4.6 (Thinking)",contextWindowTokens:1e6,tier:"balanced"},{id:"Claude Opus 4.6 (Thinking)",name:"Claude Opus 4.6 (Thinking)",contextWindowTokens:1e6,tier:"flagship"},{id:"GPT-OSS 120B (Medium)",name:"GPT-OSS 120B (Medium)",contextWindowTokens:128e3,tier:"balanced"}],modes:[],effort:[],modelOverrides:{}}};Object.fromEntries(Object.entries(y).map(([e,t])=>[e,t.models]));var L=[{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]"}];new Map(L.map(({baseModelId:e,catalogModelId:t})=>[e,t]));function G(){}exports.createMockAudit=m;exports.createMockContext=T;exports.createMockLogger=f;exports.createMockRouter=h;exports.createMockStorage=M;exports.createMockStore=x;exports.resetModelsOverride=G;exports.resetPricingOverride=D;
@@ -1 +1,2 @@
1
1
  export declare function formatTimestamp(date: Date): string;
2
+ export declare function formatDisplayTimestamp(date: Date): string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@crewx/sdk",
3
- "version": "0.9.0-rc.53",
3
+ "version": "0.9.0-rc.55",
4
4
  "license": "UNLICENSED",
5
5
  "engines": {
6
6
  "node": ">=20.19.0"
@@ -474,10 +474,10 @@ agents:
474
474
  options:
475
475
  query:
476
476
  effort: high
477
- mode: auto
477
+ mode: default
478
478
  execute:
479
479
  effort: high
480
- mode: auto
480
+ mode: default
481
481
  inline:
482
482
  layout: crewx/minimal
483
483
  prompt: |-