@vibecontrols/agent 2026.1127.1 → 2026.1130.1

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,2 +1,2 @@
1
1
  // @bun
2
- import{br}from"./index-k12bymz4.js";import"./index-ednz6yz2.js";import"./index-6vsjepw2.js";import"./index-ppxayc0x.js";import"./index-bp82hgag.js";import"./index-he4hy261.js";import"./index-qqnb0axh.js";import"./index-awj0w14r.js";import"./index-wxb9dgwq.js";import"./index-cn4p1ks0.js";import"./index-p7fbnfwd.js";import"./index-qzwbctkv.js";import"./index-x4z055t8.js";import"./index-1t74r13z.js";import"./index-damc6cvc.js";import"./index-j99tkngg.js";import"./index-7wm4bqx5.js";export{br as createApp};
2
+ import{br}from"./index-85jn7v8t.js";import"./index-ednz6yz2.js";import"./index-5tghd67e.js";import"./index-ppxayc0x.js";import"./index-dr6rsnpk.js";import"./index-twtvt4yt.js";import"./index-br9bakfm.js";import"./index-8jk4a62x.js";import"./index-wxb9dgwq.js";import"./index-cn4p1ks0.js";import"./index-p7fbnfwd.js";import"./index-qzwbctkv.js";import"./index-x4z055t8.js";import"./index-1t74r13z.js";import"./index-damc6cvc.js";import"./index-j99tkngg.js";import"./index-7wm4bqx5.js";export{br as createApp};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import"./index-7wm4bqx5.js";import{He}from"./index-bk17490n.js";import{Ae}from"./index-awj0w14r.js";var s=new Set(["desk.session"]),c=new Set(["BAD_REQUEST","DESK_OFFLINE"]);async function i(n){try{return await n()}catch(e){let t=typeof e==="object"&&e!==null&&"code"in e?e.code:void 0;if(typeof t==="string"&&c.has(t))throw new He(t,e instanceof Error?e.message:t);throw e}}function p(n,e){let t={publishEvent(o){if(!s.has(o.topic))throw Error(`plugins may not publish '${o.topic}'`);if(typeof o.payload!=="object"||o.payload===null||Array.isArray(o.payload))throw Error("an event payload must be an object");e.publishEvent({topic:o.topic,payload:o.payload})}};n.registerService("agent","bridge",t)}function d(n){if(typeof n!=="object"||n===null)return!1;let e=n;return typeof e.act==="function"&&typeof e.fence==="function"&&typeof e.health==="function"}function a(n){let e=n.getService("desk","remote");if(!d(e))throw new He("DESK_OFFLINE","no desk plugin with remote control is loaded on this agent");return e}function u(n,e){let t=[n.handle("agent.ping",async()=>({pong:!0,version:Ae(),at:new Date().toISOString()})),n.handle("desk.act",(o,r)=>i(()=>a(e).act(o,{signal:r.signal}))),n.handle("desk.fence",(o,r)=>i(()=>a(e).fence(o,{signal:r.signal}))),n.handle("desk.health",(o,r)=>i(()=>a(e).health({signal:r.signal})))];return()=>{for(let o of t)o()}}export{u as registerBridgeCommands,p as registerPluginBridgeService};
2
+ import"./index-7wm4bqx5.js";import{He}from"./index-bk17490n.js";import{Ae}from"./index-8jk4a62x.js";var s=new Set(["desk.session"]),c=new Set(["BAD_REQUEST","DESK_OFFLINE"]);async function i(n){try{return await n()}catch(e){let t=typeof e==="object"&&e!==null&&"code"in e?e.code:void 0;if(typeof t==="string"&&c.has(t))throw new He(t,e instanceof Error?e.message:t);throw e}}function p(n,e){let t={publishEvent(o){if(!s.has(o.topic))throw Error(`plugins may not publish '${o.topic}'`);if(typeof o.payload!=="object"||o.payload===null||Array.isArray(o.payload))throw Error("an event payload must be an object");e.publishEvent({topic:o.topic,payload:o.payload})}};n.registerService("agent","bridge",t)}function d(n){if(typeof n!=="object"||n===null)return!1;let e=n;return typeof e.act==="function"&&typeof e.fence==="function"&&typeof e.health==="function"}function a(n){let e=n.getService("desk","remote");if(!d(e))throw new He("DESK_OFFLINE","no desk plugin with remote control is loaded on this agent");return e}function u(n,e){let t=[n.handle("agent.ping",async()=>({pong:!0,version:Ae(),at:new Date().toISOString()})),n.handle("desk.act",(o,r)=>i(()=>a(e).act(o,{signal:r.signal}))),n.handle("desk.fence",(o,r)=>i(()=>a(e).fence(o,{signal:r.signal}))),n.handle("desk.health",(o,r)=>i(()=>a(e).health({signal:r.signal})))];return()=>{for(let o of t)o()}}export{u as registerBridgeCommands,p as registerPluginBridgeService};
package/dist/cli.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env bun
2
2
  // @bun
3
- import{Ye}from"./index-xetd52ad.js";import{I,se,e}from"./index-7wm4bqx5.js";import{W}from"./index-awj0w14r.js";import{Z}from"./index-wxb9dgwq.js";import{Gi}from"./index-12gb48hg.js";import"./index-1t74r13z.js";import"./index-j99tkngg.js";import"./index-x4z055t8.js";import"./index-qzwbctkv.js";import{Br}from"./index-62vfxd90.js";import"./index-sq5j8bjn.js";import"./index-4kf3nr14.js";import"./index-zcnfj1q4.js";import{Pr,Mr}from"./index-xjnanwbf.js";import"./index-bp82hgag.js";import"./index-0rmmrrfh.js";import"./index-he4hy261.js";import{xe,Ie,Fi,ve}from"./index-qqnb0axh.js";import{b}from"./index-w4jqdhc2.js";import"./index-cn4p1ks0.js";import"./index-v77bb0rm.js";import"./index-damc6cvc.js";import{join as m}from"path";if(typeof Bun>"u")console.error(`\x1B[31mError:\x1B[0m VibeControls Agent requires the Bun runtime.
3
+ import{Ye}from"./index-xetd52ad.js";import{I,se,e}from"./index-7wm4bqx5.js";import{W}from"./index-8jk4a62x.js";import{Z}from"./index-wxb9dgwq.js";import{Gi}from"./index-12gb48hg.js";import"./index-1t74r13z.js";import"./index-j99tkngg.js";import"./index-x4z055t8.js";import"./index-qzwbctkv.js";import{Br}from"./index-62vfxd90.js";import"./index-sq5j8bjn.js";import"./index-4kf3nr14.js";import"./index-zcnfj1q4.js";import{Pr,Mr}from"./index-q4fht6h2.js";import"./index-dr6rsnpk.js";import"./index-0rmmrrfh.js";import"./index-twtvt4yt.js";import{xe,Ie,Fi,ve}from"./index-br9bakfm.js";import{b}from"./index-w4jqdhc2.js";import"./index-cn4p1ks0.js";import"./index-v77bb0rm.js";import"./index-damc6cvc.js";import{join as m}from"path";if(typeof Bun>"u")console.error(`\x1B[31mError:\x1B[0m VibeControls Agent requires the Bun runtime.
4
4
  Install Bun: https://bun.sh
5
5
  Then run: bun run vibe ...`),process.exit(1);var a=process.argv.slice(2),l=a.includes("--plain")||a.includes("--json")||process.env.NO_COLOR==="1"||!process.stdout.isTTY;Gi(!l);try{Br()}catch{}var s="1.0.0";try{let t=m(import.meta.dir,"..","package.json");s=(await Bun.file(t).json()).version}catch{}var r=new Ye;r.name("vibe").description("VibeControls Agent CLI \u2014 Remote development environment management").version(s,"-v, --version").option("--provider <name>","Override the default provider for tunnel/session operations").option("-p, --profile <name>","Target a specific profile (one-off; doesn't change the persisted default). See `vibe profile`.").option("--json","Emit machine-readable JSON instead of human output.").option("--plain","Force plain-text output (no interactive UI).").hook("preAction",(t,o)=>{let n=t.opts().profile;if(n)process.env.VIBECONTROLS_PROFILE=n;try{Z.init(),Z.emit("command.executed",{command_name:o.name()})}catch{}});Mr(r);async function g(){let t=new W;try{await t.loadCorePlugins()}catch{}try{await t.loadAll()}catch{}let o=new xe,n={storage:{async get(){return null},async set(){},async delete(){return!1},async list(){return[]},async deleteAll(){return 0}},logger:e().logger,serviceRegistry:o,getProvider:(i)=>o.getProvider(i),getAgentBaseUrl:()=>process.env.AGENT_URL||"http://localhost:3005",getAgentVersion:()=>s,broadcast:()=>{},workspaceQuery:async()=>({data:void 0,errors:[{message:"workspaceQuery is not available in CLI mode"}]}),isGatewayConfigured:()=>!1,getAgentRecordId:async()=>null,getWorkspaceId:async()=>null,getConfig:async()=>{return},getPluginRegistry:()=>se(),getDataDir:()=>I(),cliContributors:new Ie,telemetry:{emit:(i,p)=>{try{Z.emit(i,p??{})}catch{}}},os:b(),iframeBridge:ve()};Fi(n.cliContributors);try{await t.dispatchCliSetup(r,n)}catch{}r.configureHelp({formatHelp:()=>Pr(r,!0)}),await r.parseAsync()}g().then(()=>{process.exit(process.exitCode??0)}).catch((t)=>{console.error(`\x1B[31mFatal:\x1B[0m ${t instanceof Error?t.message:t}`),process.exit(1)});
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{z,ci,Wt,xt,T,O,C,N,e,at}from"./index-7wm4bqx5.js";import{M,X}from"./index-j99tkngg.js";import{Ae,W}from"./index-awj0w14r.js";import{K}from"./index-qzwbctkv.js";import{_t}from"./index-p7fbnfwd.js";import{xe,Ie,ve}from"./index-qqnb0axh.js";import{b}from"./index-w4jqdhc2.js";import{existsSync as Ja,readFileSync as Ya}from"fs";import{dirname as wi,join as Qa}from"path";import{fileURLToPath as Za}from"url";import{closeSync as eo,existsSync as to,mkdirSync as io,openSync as ro,readFileSync as so,unlinkSync as $r,writeFileSync as no}from"fs";import{join as ao}from"path";import oo from"crypto";import it from"path";import G from"fs";import Ai from"zlib";import lo from"http";import{closeSync as co,existsSync as uo,mkdirSync as ho,openSync as fo,readFileSync as _o,unlinkSync as kr,writeFileSync as po}from"fs";import{join as go}from"path";import mo from"crypto";import rt from"path";import H from"fs";import vi from"zlib";import yo from"http";import{closeSync as wo,existsSync as Ao,mkdirSync as vo,openSync as Eo,readFileSync as xo,unlinkSync as Dr,writeFileSync as So}from"fs";import{join as Io}from"path";import bo from"crypto";import st from"path";import J from"fs";import Ei from"zlib";import To from"http";import{closeSync as Oo,existsSync as Ro,mkdirSync as Co,openSync as No,readFileSync as $o,unlinkSync as Lr,writeFileSync as ko}from"fs";import{join as Do}from"path";import Lo from"crypto";import nt from"path";import Y from"fs";import xi from"zlib";import Po from"http";function Mo(){let t=Date.now().toString(16),i;try{i=oo.randomBytes(8).toString("hex")}catch{let r=new Uint8Array(8);crypto.getRandomValues(r),i=Array.from(r).map((s)=>s.toString(16).padStart(2,"0")).join("")}return`${t}${i}`}function Pr(t,i){let r=t instanceof Error?t.message:t;if(i==="error")console.error(r);else console.log(r)}var Mr=new Set(["__proto__","constructor","prototype"]);function ti(t,i){if(!i.includes(".")){if(Mr.has(i))return;return t[i]}let r=t;for(let s of i.split(".")){if(Mr.has(s))return;if(r==null)return;r=r[s]}return r}class Je extends Error{constructor(t,i,r={}){super(i);this.name=this.constructor.name,this.code=t,this.details=r}}class D extends Je{}class De extends Je{}class Ce extends Je{}class Ve extends Je{}class be extends Je{}class ut extends Je{}function $i(t,i){if(t===i)return!0;if(t==null||i==null)return!1;if(typeof t!==typeof i)return!1;if(t instanceof Date&&i instanceof Date)return t.getTime()===i.getTime();if(t instanceof RegExp&&i instanceof RegExp)return t.source===i.source&&t.flags===i.flags;if(Array.isArray(t)){if(!Array.isArray(i)||t.length!==i.length)return!1;for(let r=0;r<t.length;r++)if(!$i(t[r],i[r]))return!1;return!0}if(typeof t==="object"){if(Array.isArray(i))return!1;let r=Object.keys(t);if(r.length!==Object.keys(i).length)return!1;for(let s of r){if(!Object.prototype.hasOwnProperty.call(i,s))return!1;if(!$i(t[s],i[s]))return!1}return!0}return!1}function ie(t,i){if(typeof i==="function")return i(t);if(i==null)return!0;if(typeof i==="object"&&Object.keys(i).length===0)return!0;if("$or"in i){let r=i.$or;if(!Array.isArray(r))throw new ut("ERR_SKALEX_QUERY_INVALID_OPERATOR","$or must be an array of filters",{operator:"$or"});if(!r.some((s)=>ie(t,s)))return!1}if("$and"in i){let r=i.$and;if(!Array.isArray(r))throw new ut("ERR_SKALEX_QUERY_INVALID_OPERATOR","$and must be an array of filters",{operator:"$and"});if(!r.every((s)=>ie(t,s)))return!1}if("$not"in i){if(ie(t,i.$not))return!1}for(let r in i){if(r==="$or"||r==="$and"||r==="$not")continue;let s=i[r],n;try{n=ti(t,r)}catch{return!1}if(s instanceof RegExp){if(!s.test(String(n)))return!1}else if(typeof s==="object"&&s!==null){if(Object.keys(s).some((a)=>a.startsWith("$"))){if("$eq"in s&&n!==s.$eq)return!1;if("$ne"in s&&n===s.$ne)return!1;if("$gt"in s&&!(n>s.$gt))return!1;if("$lt"in s&&!(n<s.$lt))return!1;if("$gte"in s&&!(n>=s.$gte))return!1;if("$lte"in s&&!(n<=s.$lte))return!1;if("$in"in s&&!s.$in.includes(n))return!1;if("$nin"in s&&s.$nin.includes(n))return!1;if("$regex"in s){if(!(s.$regex instanceof RegExp?s.$regex:new RegExp(s.$regex)).test(String(n)))return!1}if("$fn"in s&&!s.$fn(n))return!1}else if(!$i(n,s))return!1}else if(n!==s)return!1}return!0}function jo(t,i=new Set){if(typeof t!=="object"||t===null||typeof t==="function")return t;let r=[],s=[],n=[],a=[],o=[];for(let l in t){if(l==="$or"||l==="$and"||l==="$not"){o.push(l);continue}let d=t[l];if(i.has(l))r.push(l);else if(d instanceof RegExp||typeof d==="object"&&d!==null&&(("$regex"in d)||("$fn"in d))||typeof d==="function")a.push(l);else if(typeof d==="object"&&d!==null&&(("$gt"in d)||("$lt"in d)||("$gte"in d)||("$lte"in d)||("$ne"in d)||("$in"in d)||("$nin"in d)))n.push(l);else s.push(l)}let c={};for(let l of[...r,...s,...n,...a,...o])c[l]=t[l];return c}var ki=new Set(["string","number","boolean","object","array","date","any"]);function Ui(t){if(Array.isArray(t))return"array";if(t instanceof Date)return"date";return typeof t}function Ls(t){let i=new Map,r=[];for(let[s,n]of Object.entries(t)){let a;if(typeof n==="string"){if(!ki.has(n))throw new D("ERR_SKALEX_VALIDATION_UNKNOWN_TYPE",`Unknown schema type "${n}" for field "${s}"`,{field:s,type:n});a={type:n,required:!1,unique:!1}}else if(typeof n==="object"&&n!==null){let{type:o="any",required:c=!1,unique:l=!1,enum:d}=n;if(!ki.has(o))throw new D("ERR_SKALEX_VALIDATION_UNKNOWN_TYPE",`Unknown schema type "${o}" for field "${s}"`,{field:s,type:o});if(a={type:o,required:c,unique:l,enum:d},l)r.push(s)}else throw new D("ERR_SKALEX_VALIDATION_INVALID_SCHEMA",`Invalid schema definition for field "${s}"`,{field:s});i.set(s,a)}return{fields:i,uniqueFields:r}}function jr(t,i,r=!1){let s=[];for(let[n,a]of i){let o=t[n],c=o===void 0||o===null;if(a.required&&c){s.push(`Field "${n}" is required`);continue}if(c)continue;if(a.type!=="any"){let l=Ui(o);if(l!==a.type)s.push(`Field "${n}" must be of type "${a.type}", got "${l}"`)}if(a.enum&&!a.enum.includes(o))s.push(`Field "${n}" must be one of [${a.enum.map((l)=>JSON.stringify(l)).join(", ")}], got ${JSON.stringify(o)}`)}if(r){for(let n of Object.keys(t))if(!n.startsWith("_")&&!i.has(n))s.push(`Unknown field "${n}" (strict mode)`)}return s}function qr(t,i){let r={};for(let[s,n]of Object.entries(t)){if(s.startsWith("_")){r[s]=n;continue}if(!i.has(s))continue;let a=i.get(s);if(a.type!=="any"){if(Ui(n)!==a.type)continue}if(a.enum&&!a.enum.includes(n))continue;r[s]=n}return r}function qo(t){let i={};for(let[r,s]of Object.entries(t)){if(r.startsWith("_"))continue;let n=Ui(s);i[r]=ki.has(n)?n:"any"}return i}function Uo(t){if(typeof t==="number"){if(t<=0)throw new D("ERR_SKALEX_VALIDATION_TTL",`TTL must be positive, got ${t}`,{ttl:t});return t*1000}if(typeof t!=="string")throw new D("ERR_SKALEX_VALIDATION_TTL",`Invalid TTL value: ${t}`,{ttl:t});let i=t.match(/^(\d+(?:\.\d+)?)(ms|s|m|h|d)$/);if(!i)throw new D("ERR_SKALEX_VALIDATION_TTL_FORMAT",`Invalid TTL format: "${t}". Use e.g. 300 (seconds), "30m", "24h", "7d"`,{ttl:t});let r=parseFloat(i[1]);if(r<=0)throw new D("ERR_SKALEX_VALIDATION_TTL",`TTL must be positive, got "${t}"`,{ttl:t});let s=i[2],n=r*{ms:1,s:1000,m:60000,h:3600000,d:86400000}[s];if(!isFinite(n))throw new D("ERR_SKALEX_VALIDATION_TTL",`TTL value "${t}" is too large`,{ttl:t});return n}function Fo(t){return new Date(Date.now()+Uo(t))}function Ko(t,i,r=null){let s=Date.now(),n=0,a=t.length;while(a--){let o=t[a];if(o._expiresAt&&new Date(o._expiresAt).getTime()<=s){if(t.splice(a,1),i.delete(o._id),r)r(o);n++}}return n}function Ur(t,i){if(t.length!==i.length)throw new ut("ERR_SKALEX_QUERY_VECTOR_MISMATCH",`Vector dimension mismatch: ${t.length} vs ${i.length}`,{expected:t.length,got:i.length});let r=0,s=0,n=0;for(let o=0;o<t.length;o++)r+=t[o]*i[o],s+=t[o]*t[o],n+=i[o]*i[o];let a=Math.sqrt(s*n);return a===0?0:r/a}function Q(t){if(!("_vector"in t))return{...t};let{_vector:i,...r}=t;return r}function zo(t){return t.length}function Bo(t,i){let r=0;for(let s of t){let n=ti(s,i);if(typeof n==="number"&&!isNaN(n))r+=n}return r}function Xo(t,i){let r=0,s=0;for(let n of t){let a=ti(n,i);if(typeof a==="number"&&!isNaN(a))r+=a,s++}return s===0?null:r/s}function Vo(t,i){let r=Object.create(null);for(let s of t){let n=String(ti(s,i)??"__null__");if(!r[n])r[n]=[];r[n].push(s)}return r}class Ps{constructor(t){this._col=t}get _ctx(){return this._col._ctx}async execute({op:t,beforeHook:i,afterHook:r,hookPayload:s,mutate:n,afterHookPayload:a,save:o,session:c}){let l=this._ctx;await l.ensureConnected(),this._col._txSnapshotIfNeeded();let d=l.txManager,u=d.active&&this._col._activeTxId===d.context?.id,f=u?d.context.id:null,h=this._col._createdInTxId,_=()=>{if(f!==null&&d._abortedIds.has(f))throw new Ce("ERR_SKALEX_TX_ABORTED",`Transaction ${f} was aborted. No further mutations allowed.`);if(h!==null&&d._abortedIds.has(h))throw new Ce("ERR_SKALEX_TX_ABORTED",`Transaction ${h} was aborted. Collection obtained inside that transaction cannot be used for further mutations.`)};if(u||h!==null)_();if(i)await l.plugins.run(i,s);let{docs:p,prevDocs:g=[]}=await n(_);if(l.persistence.markDirty(l.collections,this._col.name),await this._col._saveIfNeeded(o),this._col._changelogEnabled)for(let m=0;m<p.length;m++)await l.logChange(t,this._col.name,p[m],g[m]??null,c||null);if(!u||!d.defer(()=>l.sessionStats.recordWrite(c)))l.sessionStats.recordWrite(c);for(let m of p)l.emitEvent(this._col.name,{op:t,collection:this._col.name,doc:Q(m)});if(r)if(a)await l.runAfterHook(r,a(p));else for(let m of p)await l.runAfterHook(r,{collection:this._col.name,doc:Q(m)});return{docs:p,prevDocs:g}}}function Go(t){let i={};for(let r in t){if(r.startsWith("$"))continue;let s=t[r];if(s&&typeof s==="object"&&!Array.isArray(s)){let n=Object.keys(s);if(n.length===1&&n[0]==="$eq")i[r]=s.$eq}else i[r]=s}return i}var Ms=new Set(["__proto__","constructor","prototype"]);function js(t){if(typeof t!=="object"||t===null||Array.isArray(t))return t;let i={};for(let r of Object.keys(t)){if(Ms.has(r))continue;i[r]=js(t[r])}return i}class qs{constructor(t,i){this.name=t.collectionName,this.database=i,this._ctx=i._buildCollectionContext(),this._store=t,this._pipeline=new Ps(this),this._createdInTxId=i._txManager.context?.id??null,this._activeTxId=null}get _data(){return this._store.data}set _data(t){this._store.data=t}get _index(){return this._store.index}get _fieldIndex(){return this._store.fieldIndex||null}get _schema(){return this._store.schema?this._store.schema.fields:null}get _changelogEnabled(){return this._store.changelog===!0}get _softDelete(){return this._store.softDelete===!0}get _versioning(){return this._store.versioning===!0}get _strict(){return this._store.strict===!0}get _onSchemaError(){return this._store.onSchemaError??"throw"}get _defaultTtl(){return this._store.defaultTtl||null}get _defaultEmbed(){return this._store.defaultEmbed||null}get _maxDocs(){return this._store.maxDocs||null}async insertOne(t,i={}){let{save:r,ifNotExists:s,ttl:n,embed:a,session:o}=i;if(s){await this._ctx.ensureConnected();let l=this._findRaw(t);if(l)return Q({...l})}let{docs:c}=await this._insertCore([t],{ttl:n,embed:a,session:o,save:r});return Q(c[0])}async insertMany(t,i={}){let{save:r,ttl:s,embed:n,session:a}=i,{docs:o}=await this._insertCore(t,{ttl:s,embed:n,session:a,save:r});return o.map(Q)}async _insertCore(t,{ttl:i,embed:r,session:s,save:n}){return this._pipeline.execute({op:"insert",beforeHook:null,afterHook:"afterInsert",hookPayload:null,save:n,session:s,mutate:async(a)=>{let o=[],c=new Set;for(let l of t){let d=this._applyValidation(l);await this._ctx.plugins.run("beforeInsert",{collection:this.name,doc:d});let u=await this._buildDoc(d,{ttl:i,embed:r});if(this._index.has(u._id)||c.has(u._id))throw new De("ERR_SKALEX_UNIQUE_DUPLICATE_ID",`Duplicate _id "${u._id}" in collection "${this.name}"`,{id:u._id,collection:this.name});c.add(u._id),o.push(u)}if(a(),this._fieldIndex)this._fieldIndex.assertUniqueBatch(o);for(let l of o)this._addToIndex(l);this._data.push(...o);for(let l of o)this._index.set(l._id,l);return this._enforceCapAfterInsert(),{docs:o}}})}async updateOne(t,i,r={}){await this._ctx.ensureConnected();let s=this._findRaw(t);if(!s)return null;let{save:n,session:a}=r,{docs:o}=await this._updateCore([s],t,i,{save:n,session:a});return Q(o[0])}async updateMany(t,i,r={}){await this._ctx.ensureConnected();let s=this._findAllRaw(t);if(s.length===0)return[];let{save:n,session:a}=r,{docs:o}=await this._updateCore(s,t,i,{save:n,session:a});return o.map(Q)}async _updateCore(t,i,r,{save:s,session:n}){return this._pipeline.execute({op:"update",beforeHook:"beforeUpdate",afterHook:"afterUpdate",hookPayload:{collection:this.name,filter:i,update:r},save:s,session:n,afterHookPayload:(a)=>({collection:this.name,filter:i,update:r,result:a.length===1?a[0]:a}),mutate:async(a)=>{let o=this._changelogEnabled?t.map((u)=>structuredClone(u)):t.map(()=>null),c=t.map((u)=>this._prepareUpdatedDoc(u,r));this._assertUniqueCandidates(t,c),a();let l=new Set(t),d=new Map;for(let u=0;u<this._data.length;u++)if(l.has(this._data[u]))d.set(this._data[u],u);for(let u=0;u<t.length;u++)this._commitUpdatedDoc(t[u],c[u],d);return{docs:c,prevDocs:o}}})}applyUpdate(t,i){for(let r in i){if(Ms.has(r))continue;if(r==="_id"||r==="createdAt")continue;let s=i[r];if(Array.isArray(s))t[r]=s;else if(typeof s==="object"&&s!==null){let n=Object.keys(s);if(n.some((a)=>a.startsWith("$"))){for(let a of n)if(a==="$inc"&&typeof t[r]==="number")t[r]+=s[a];else if(a==="$push"){if(!Array.isArray(t[r]))t[r]=[];t[r].push(s[a])}}else t[r]=js(s)}else t[r]=s}if(t.updatedAt=new Date,this._versioning)t._version=(t._version??0)+1;return t}_prepareUpdatedDoc(t,i){let r=structuredClone(t),s=structuredClone(t);if(this.applyUpdate(s,i),!this._schema)return s;let n=jr(s,this._schema,this._strict);if(!n.length)return s;switch(this._onSchemaError){case"throw":throw new D("ERR_SKALEX_VALIDATION_UPDATE",`Update validation failed on doc "${t._id}": ${n.join("; ")}`,{id:t._id,errors:n});case"strip":return this._stripCandidateToValid(s,r);default:return this._ctx.logger(`[${this.name}] Update validation warning: ${n.join("; ")}`,"warn"),s}}_stripCandidateToValid(t,i){let r=qr(t,this._schema),s=structuredClone(i);for(let[n,a]of Object.entries(r)){if(n.startsWith("_"))continue;s[n]=a}if(s.updatedAt=t.updatedAt,this._versioning)s._version=t._version;return s}_commitUpdatedDoc(t,i,r){let s=r?r.get(t):this._data.indexOf(t);if(s===void 0||s===-1)throw new Ve("ERR_SKALEX_PERSISTENCE_DOC_MISSING",`Document "${t._id}" no longer exists in collection "${this.name}"`,{id:t._id,collection:this.name});this._data[s]=i,this._index.set(i._id,i),this._updateInIndex(t,i)}_assertUniqueCandidates(t,i){this._fieldIndex?.assertUniqueCandidates(t,i)}async upsert(t,i,r={}){if(await this._ctx.ensureConnected(),this._findRaw(t))return this.updateOne(t,i,r);return this.insertOne({...Go(t),...i},r)}async upsertMany(t,i,r={}){await this._ctx.ensureConnected();let{save:s,...n}=r,a=[];for(let o of t)a.push(await this.upsert({[i]:o[i]},o,{...n,save:!1}));return await this._saveIfNeeded(s),a}async restore(t,i={}){if(!this._softDelete)throw new ut("ERR_SKALEX_QUERY_SOFT_DELETE_REQUIRED",`restore() requires softDelete on "${this.name}"`,{collection:this.name});await this._ctx.ensureConnected();let{save:r,session:s}=i,n=this._findRaw(t,{includeDeleted:!0});if(!n||!n._deletedAt)return null;let{docs:a}=await this._pipeline.execute({op:"restore",beforeHook:null,afterHook:null,hookPayload:null,save:r,session:s,mutate:async(o)=>(o(),delete n._deletedAt,n.updatedAt=new Date,this._index.set(n._id,n),{docs:[n]})});return Q(a[0])}watch(t,i){if(typeof t==="function")i=t,t=null;if(i)return this._ctx.eventBus.on(this.name,(r)=>{if(!t||ie(r.doc,t))i(r)});return this._watchIterator(t)}_watchIterator(t){let i=[],r=null,s=!1,n=this._ctx.eventBus.on(this.name,(a)=>{if(t&&!ie(a.doc,t))return;if(r){let o=r;r=null,o({value:a,done:!1})}else i.push(a)});return{[Symbol.asyncIterator](){return this},next(){if(i.length>0)return Promise.resolve({value:i.shift(),done:!1});if(s)return Promise.resolve({value:void 0,done:!0});return new Promise((a)=>{r=a})},return(){if(s=!0,n(),r){let a=r;r=null,a({value:void 0,done:!0})}return Promise.resolve({value:void 0,done:!0})}}}async count(t={}){return await this._ctx.ensureConnected(),zo(this._findAllRaw(t))}async sum(t,i={}){return await this._ctx.ensureConnected(),Bo(this._findAllRaw(i),t)}async avg(t,i={}){return await this._ctx.ensureConnected(),Xo(this._findAllRaw(i),t)}async groupBy(t,i={}){return await this._ctx.ensureConnected(),Vo(this._findAllRaw(i),t)}async findOne(t,i={}){await this._ctx.ensureConnected();let{populate:r,select:s,includeDeleted:n=!1}=i,a=this._findRaw(t,{includeDeleted:n});if(!a)return null;let o=this._projectDoc(a,s);if(r)await this._populateDoc(o,a,r);return o}async find(t,i={}){await this._ctx.ensureConnected();let r=Date.now(),{populate:s,select:n,sort:a,page:o=1,limit:c,session:l,includeDeleted:d=!1}=i;await this._ctx.plugins.run("beforeFind",{collection:this.name,filter:t,options:i});let u=this._getCandidates(t),f=jo(t,this._fieldIndex?this._fieldIndex.indexedFields:new Set),h=[];for(let p of u){if(this._softDelete&&p._deletedAt&&!d)continue;if(!ie(p,f))continue;let g=this._projectDoc(p,n);if(s)await this._populateDoc(g,p,s);h.push(g)}if(a){let p=Object.keys(a);h.sort((g,m)=>{for(let w of p){let v=a[w];if(g[w]<m[w])return-v;if(g[w]>m[w])return v}return 0})}let _;if(c){let p=h.length,g=Math.ceil(p/c),m=(o-1)*c;h=h.slice(m,m+c),_={page:o,totalDocs:p,totalPages:g}}return this._ctx.queryLog?.record({collection:this.name,op:"find",filter:t,duration:Date.now()-r,resultCount:h.length}),this._ctx.sessionStats.recordRead(l),await this._ctx.plugins.run("afterFind",{collection:this.name,filter:t,options:i,docs:h}),_?{docs:h,..._}:{docs:h}}async search(t,{filter:i,limit:r=10,minScore:s=0,session:n}={}){await this._ctx.ensureConnected();let a=Date.now();await this._ctx.plugins.run("beforeSearch",{collection:this.name,query:t,options:{filter:i,limit:r,minScore:s}});let o=await this._ctx.embed(t),c=i?this._findAllRaw(i):this._data,l=[];for(let h of c){if(!h._vector)continue;let _=Ur(o,h._vector);if(_>=s)l.push({doc:h,score:_})}l.sort((h,_)=>_.score-h.score);let d=l.slice(0,r);this._ctx.queryLog?.record({collection:this.name,op:"search",query:t,duration:Date.now()-a,resultCount:d.length}),this._ctx.sessionStats.recordRead(n);let u=d.map((h)=>Q(h.doc)),f=d.map((h)=>h.score);return await this._ctx.plugins.run("afterSearch",{collection:this.name,query:t,options:{filter:i,limit:r,minScore:s},docs:u,scores:f}),{docs:u,scores:f}}async similar(t,{limit:i=10,minScore:r=0}={}){await this._ctx.ensureConnected();let s=this._index.get(t);if(!s||!s._vector)return{docs:[],scores:[]};let n=[];for(let o of this._data){if(o._id===t||!o._vector)continue;let c=Ur(s._vector,o._vector);if(c>=r)n.push({doc:o,score:c})}n.sort((o,c)=>c.score-o.score);let a=n.slice(0,i);return{docs:a.map((o)=>Q(o.doc)),scores:a.map((o)=>o.score)}}async deleteOne(t,i={}){await this._ctx.ensureConnected();let{save:r,session:s}=i;if(this._softDelete){let a=this._findRaw(t);if(!a)return null;let{docs:o}=await this._deleteCore("soft",[a],t,{save:r,session:s});return Q(o[0])}let{docs:n}=await this._deleteCore("hard",null,t,{save:r,session:s});if(n.length===0)return null;return Q(n[0])}async deleteMany(t,i={}){await this._ctx.ensureConnected();let{save:r,session:s}=i;if(this._softDelete){let a=this._findAllRaw(t);if(a.length===0)return[];let{docs:o}=await this._deleteCore("soft",a,t,{save:r,session:s});return o.map(Q)}let{docs:n}=await this._deleteCore("hardMany",null,t,{save:r,session:s});return n.map(Q)}async _deleteCore(t,i,r,{save:s,session:n}){return this._pipeline.execute({op:"delete",beforeHook:"beforeDelete",afterHook:"afterDelete",hookPayload:{collection:this.name,filter:r},save:s,session:n,afterHookPayload:(a)=>({collection:this.name,filter:r,result:a.length===1?a[0]:a}),mutate:async(a)=>{if(a(),t==="soft"){let l=new Date;for(let d of i)d._deletedAt=l,d.updatedAt=l,this._index.set(d._id,d);return{docs:i}}if(t==="hard"){let l=this._findIndex(r);if(l===-1)return{docs:[]};let d=this._data.splice(l,1)[0];return this._index.delete(d._id),this._removeFromIndex(d),{docs:[d]}}let o=[],c=[];for(let l of this._data)if(ie(l,r))o.push(l),this._index.delete(l._id),this._removeFromIndex(l);else c.push(l);return this._data=c,{docs:o}}})}async export(t={},i={}){let{dir:r,name:s,format:n="json"}=i;try{let a=this._data.filter((u)=>ie(u,t));if(a.length===0)throw new ut("ERR_SKALEX_QUERY_EXPORT_EMPTY",`export(): no documents matched the filter in "${this.name}"`,{collection:this.name});let o;if(n==="json")o=JSON.stringify(a,null,2);else{let u=(_)=>{if(_==null)return"";let p=typeof _==="object"?JSON.stringify(_):String(_);return p.includes(",")||p.includes('"')||p.includes(`
2
+ import{z,ci,Wt,xt,T,O,C,N,e,at}from"./index-7wm4bqx5.js";import{M,X}from"./index-j99tkngg.js";import{Ae,W}from"./index-8jk4a62x.js";import{K}from"./index-qzwbctkv.js";import{_t}from"./index-p7fbnfwd.js";import{xe,Ie,ve}from"./index-br9bakfm.js";import{b}from"./index-w4jqdhc2.js";import{existsSync as Ja,readFileSync as Ya}from"fs";import{dirname as wi,join as Qa}from"path";import{fileURLToPath as Za}from"url";import{closeSync as eo,existsSync as to,mkdirSync as io,openSync as ro,readFileSync as so,unlinkSync as $r,writeFileSync as no}from"fs";import{join as ao}from"path";import oo from"crypto";import it from"path";import G from"fs";import Ai from"zlib";import lo from"http";import{closeSync as co,existsSync as uo,mkdirSync as ho,openSync as fo,readFileSync as _o,unlinkSync as kr,writeFileSync as po}from"fs";import{join as go}from"path";import mo from"crypto";import rt from"path";import H from"fs";import vi from"zlib";import yo from"http";import{closeSync as wo,existsSync as Ao,mkdirSync as vo,openSync as Eo,readFileSync as xo,unlinkSync as Dr,writeFileSync as So}from"fs";import{join as Io}from"path";import bo from"crypto";import st from"path";import J from"fs";import Ei from"zlib";import To from"http";import{closeSync as Oo,existsSync as Ro,mkdirSync as Co,openSync as No,readFileSync as $o,unlinkSync as Lr,writeFileSync as ko}from"fs";import{join as Do}from"path";import Lo from"crypto";import nt from"path";import Y from"fs";import xi from"zlib";import Po from"http";function Mo(){let t=Date.now().toString(16),i;try{i=oo.randomBytes(8).toString("hex")}catch{let r=new Uint8Array(8);crypto.getRandomValues(r),i=Array.from(r).map((s)=>s.toString(16).padStart(2,"0")).join("")}return`${t}${i}`}function Pr(t,i){let r=t instanceof Error?t.message:t;if(i==="error")console.error(r);else console.log(r)}var Mr=new Set(["__proto__","constructor","prototype"]);function ti(t,i){if(!i.includes(".")){if(Mr.has(i))return;return t[i]}let r=t;for(let s of i.split(".")){if(Mr.has(s))return;if(r==null)return;r=r[s]}return r}class Je extends Error{constructor(t,i,r={}){super(i);this.name=this.constructor.name,this.code=t,this.details=r}}class D extends Je{}class De extends Je{}class Ce extends Je{}class Ve extends Je{}class be extends Je{}class ut extends Je{}function $i(t,i){if(t===i)return!0;if(t==null||i==null)return!1;if(typeof t!==typeof i)return!1;if(t instanceof Date&&i instanceof Date)return t.getTime()===i.getTime();if(t instanceof RegExp&&i instanceof RegExp)return t.source===i.source&&t.flags===i.flags;if(Array.isArray(t)){if(!Array.isArray(i)||t.length!==i.length)return!1;for(let r=0;r<t.length;r++)if(!$i(t[r],i[r]))return!1;return!0}if(typeof t==="object"){if(Array.isArray(i))return!1;let r=Object.keys(t);if(r.length!==Object.keys(i).length)return!1;for(let s of r){if(!Object.prototype.hasOwnProperty.call(i,s))return!1;if(!$i(t[s],i[s]))return!1}return!0}return!1}function ie(t,i){if(typeof i==="function")return i(t);if(i==null)return!0;if(typeof i==="object"&&Object.keys(i).length===0)return!0;if("$or"in i){let r=i.$or;if(!Array.isArray(r))throw new ut("ERR_SKALEX_QUERY_INVALID_OPERATOR","$or must be an array of filters",{operator:"$or"});if(!r.some((s)=>ie(t,s)))return!1}if("$and"in i){let r=i.$and;if(!Array.isArray(r))throw new ut("ERR_SKALEX_QUERY_INVALID_OPERATOR","$and must be an array of filters",{operator:"$and"});if(!r.every((s)=>ie(t,s)))return!1}if("$not"in i){if(ie(t,i.$not))return!1}for(let r in i){if(r==="$or"||r==="$and"||r==="$not")continue;let s=i[r],n;try{n=ti(t,r)}catch{return!1}if(s instanceof RegExp){if(!s.test(String(n)))return!1}else if(typeof s==="object"&&s!==null){if(Object.keys(s).some((a)=>a.startsWith("$"))){if("$eq"in s&&n!==s.$eq)return!1;if("$ne"in s&&n===s.$ne)return!1;if("$gt"in s&&!(n>s.$gt))return!1;if("$lt"in s&&!(n<s.$lt))return!1;if("$gte"in s&&!(n>=s.$gte))return!1;if("$lte"in s&&!(n<=s.$lte))return!1;if("$in"in s&&!s.$in.includes(n))return!1;if("$nin"in s&&s.$nin.includes(n))return!1;if("$regex"in s){if(!(s.$regex instanceof RegExp?s.$regex:new RegExp(s.$regex)).test(String(n)))return!1}if("$fn"in s&&!s.$fn(n))return!1}else if(!$i(n,s))return!1}else if(n!==s)return!1}return!0}function jo(t,i=new Set){if(typeof t!=="object"||t===null||typeof t==="function")return t;let r=[],s=[],n=[],a=[],o=[];for(let l in t){if(l==="$or"||l==="$and"||l==="$not"){o.push(l);continue}let d=t[l];if(i.has(l))r.push(l);else if(d instanceof RegExp||typeof d==="object"&&d!==null&&(("$regex"in d)||("$fn"in d))||typeof d==="function")a.push(l);else if(typeof d==="object"&&d!==null&&(("$gt"in d)||("$lt"in d)||("$gte"in d)||("$lte"in d)||("$ne"in d)||("$in"in d)||("$nin"in d)))n.push(l);else s.push(l)}let c={};for(let l of[...r,...s,...n,...a,...o])c[l]=t[l];return c}var ki=new Set(["string","number","boolean","object","array","date","any"]);function Ui(t){if(Array.isArray(t))return"array";if(t instanceof Date)return"date";return typeof t}function Ls(t){let i=new Map,r=[];for(let[s,n]of Object.entries(t)){let a;if(typeof n==="string"){if(!ki.has(n))throw new D("ERR_SKALEX_VALIDATION_UNKNOWN_TYPE",`Unknown schema type "${n}" for field "${s}"`,{field:s,type:n});a={type:n,required:!1,unique:!1}}else if(typeof n==="object"&&n!==null){let{type:o="any",required:c=!1,unique:l=!1,enum:d}=n;if(!ki.has(o))throw new D("ERR_SKALEX_VALIDATION_UNKNOWN_TYPE",`Unknown schema type "${o}" for field "${s}"`,{field:s,type:o});if(a={type:o,required:c,unique:l,enum:d},l)r.push(s)}else throw new D("ERR_SKALEX_VALIDATION_INVALID_SCHEMA",`Invalid schema definition for field "${s}"`,{field:s});i.set(s,a)}return{fields:i,uniqueFields:r}}function jr(t,i,r=!1){let s=[];for(let[n,a]of i){let o=t[n],c=o===void 0||o===null;if(a.required&&c){s.push(`Field "${n}" is required`);continue}if(c)continue;if(a.type!=="any"){let l=Ui(o);if(l!==a.type)s.push(`Field "${n}" must be of type "${a.type}", got "${l}"`)}if(a.enum&&!a.enum.includes(o))s.push(`Field "${n}" must be one of [${a.enum.map((l)=>JSON.stringify(l)).join(", ")}], got ${JSON.stringify(o)}`)}if(r){for(let n of Object.keys(t))if(!n.startsWith("_")&&!i.has(n))s.push(`Unknown field "${n}" (strict mode)`)}return s}function qr(t,i){let r={};for(let[s,n]of Object.entries(t)){if(s.startsWith("_")){r[s]=n;continue}if(!i.has(s))continue;let a=i.get(s);if(a.type!=="any"){if(Ui(n)!==a.type)continue}if(a.enum&&!a.enum.includes(n))continue;r[s]=n}return r}function qo(t){let i={};for(let[r,s]of Object.entries(t)){if(r.startsWith("_"))continue;let n=Ui(s);i[r]=ki.has(n)?n:"any"}return i}function Uo(t){if(typeof t==="number"){if(t<=0)throw new D("ERR_SKALEX_VALIDATION_TTL",`TTL must be positive, got ${t}`,{ttl:t});return t*1000}if(typeof t!=="string")throw new D("ERR_SKALEX_VALIDATION_TTL",`Invalid TTL value: ${t}`,{ttl:t});let i=t.match(/^(\d+(?:\.\d+)?)(ms|s|m|h|d)$/);if(!i)throw new D("ERR_SKALEX_VALIDATION_TTL_FORMAT",`Invalid TTL format: "${t}". Use e.g. 300 (seconds), "30m", "24h", "7d"`,{ttl:t});let r=parseFloat(i[1]);if(r<=0)throw new D("ERR_SKALEX_VALIDATION_TTL",`TTL must be positive, got "${t}"`,{ttl:t});let s=i[2],n=r*{ms:1,s:1000,m:60000,h:3600000,d:86400000}[s];if(!isFinite(n))throw new D("ERR_SKALEX_VALIDATION_TTL",`TTL value "${t}" is too large`,{ttl:t});return n}function Fo(t){return new Date(Date.now()+Uo(t))}function Ko(t,i,r=null){let s=Date.now(),n=0,a=t.length;while(a--){let o=t[a];if(o._expiresAt&&new Date(o._expiresAt).getTime()<=s){if(t.splice(a,1),i.delete(o._id),r)r(o);n++}}return n}function Ur(t,i){if(t.length!==i.length)throw new ut("ERR_SKALEX_QUERY_VECTOR_MISMATCH",`Vector dimension mismatch: ${t.length} vs ${i.length}`,{expected:t.length,got:i.length});let r=0,s=0,n=0;for(let o=0;o<t.length;o++)r+=t[o]*i[o],s+=t[o]*t[o],n+=i[o]*i[o];let a=Math.sqrt(s*n);return a===0?0:r/a}function Q(t){if(!("_vector"in t))return{...t};let{_vector:i,...r}=t;return r}function zo(t){return t.length}function Bo(t,i){let r=0;for(let s of t){let n=ti(s,i);if(typeof n==="number"&&!isNaN(n))r+=n}return r}function Xo(t,i){let r=0,s=0;for(let n of t){let a=ti(n,i);if(typeof a==="number"&&!isNaN(a))r+=a,s++}return s===0?null:r/s}function Vo(t,i){let r=Object.create(null);for(let s of t){let n=String(ti(s,i)??"__null__");if(!r[n])r[n]=[];r[n].push(s)}return r}class Ps{constructor(t){this._col=t}get _ctx(){return this._col._ctx}async execute({op:t,beforeHook:i,afterHook:r,hookPayload:s,mutate:n,afterHookPayload:a,save:o,session:c}){let l=this._ctx;await l.ensureConnected(),this._col._txSnapshotIfNeeded();let d=l.txManager,u=d.active&&this._col._activeTxId===d.context?.id,f=u?d.context.id:null,h=this._col._createdInTxId,_=()=>{if(f!==null&&d._abortedIds.has(f))throw new Ce("ERR_SKALEX_TX_ABORTED",`Transaction ${f} was aborted. No further mutations allowed.`);if(h!==null&&d._abortedIds.has(h))throw new Ce("ERR_SKALEX_TX_ABORTED",`Transaction ${h} was aborted. Collection obtained inside that transaction cannot be used for further mutations.`)};if(u||h!==null)_();if(i)await l.plugins.run(i,s);let{docs:p,prevDocs:g=[]}=await n(_);if(l.persistence.markDirty(l.collections,this._col.name),await this._col._saveIfNeeded(o),this._col._changelogEnabled)for(let m=0;m<p.length;m++)await l.logChange(t,this._col.name,p[m],g[m]??null,c||null);if(!u||!d.defer(()=>l.sessionStats.recordWrite(c)))l.sessionStats.recordWrite(c);for(let m of p)l.emitEvent(this._col.name,{op:t,collection:this._col.name,doc:Q(m)});if(r)if(a)await l.runAfterHook(r,a(p));else for(let m of p)await l.runAfterHook(r,{collection:this._col.name,doc:Q(m)});return{docs:p,prevDocs:g}}}function Go(t){let i={};for(let r in t){if(r.startsWith("$"))continue;let s=t[r];if(s&&typeof s==="object"&&!Array.isArray(s)){let n=Object.keys(s);if(n.length===1&&n[0]==="$eq")i[r]=s.$eq}else i[r]=s}return i}var Ms=new Set(["__proto__","constructor","prototype"]);function js(t){if(typeof t!=="object"||t===null||Array.isArray(t))return t;let i={};for(let r of Object.keys(t)){if(Ms.has(r))continue;i[r]=js(t[r])}return i}class qs{constructor(t,i){this.name=t.collectionName,this.database=i,this._ctx=i._buildCollectionContext(),this._store=t,this._pipeline=new Ps(this),this._createdInTxId=i._txManager.context?.id??null,this._activeTxId=null}get _data(){return this._store.data}set _data(t){this._store.data=t}get _index(){return this._store.index}get _fieldIndex(){return this._store.fieldIndex||null}get _schema(){return this._store.schema?this._store.schema.fields:null}get _changelogEnabled(){return this._store.changelog===!0}get _softDelete(){return this._store.softDelete===!0}get _versioning(){return this._store.versioning===!0}get _strict(){return this._store.strict===!0}get _onSchemaError(){return this._store.onSchemaError??"throw"}get _defaultTtl(){return this._store.defaultTtl||null}get _defaultEmbed(){return this._store.defaultEmbed||null}get _maxDocs(){return this._store.maxDocs||null}async insertOne(t,i={}){let{save:r,ifNotExists:s,ttl:n,embed:a,session:o}=i;if(s){await this._ctx.ensureConnected();let l=this._findRaw(t);if(l)return Q({...l})}let{docs:c}=await this._insertCore([t],{ttl:n,embed:a,session:o,save:r});return Q(c[0])}async insertMany(t,i={}){let{save:r,ttl:s,embed:n,session:a}=i,{docs:o}=await this._insertCore(t,{ttl:s,embed:n,session:a,save:r});return o.map(Q)}async _insertCore(t,{ttl:i,embed:r,session:s,save:n}){return this._pipeline.execute({op:"insert",beforeHook:null,afterHook:"afterInsert",hookPayload:null,save:n,session:s,mutate:async(a)=>{let o=[],c=new Set;for(let l of t){let d=this._applyValidation(l);await this._ctx.plugins.run("beforeInsert",{collection:this.name,doc:d});let u=await this._buildDoc(d,{ttl:i,embed:r});if(this._index.has(u._id)||c.has(u._id))throw new De("ERR_SKALEX_UNIQUE_DUPLICATE_ID",`Duplicate _id "${u._id}" in collection "${this.name}"`,{id:u._id,collection:this.name});c.add(u._id),o.push(u)}if(a(),this._fieldIndex)this._fieldIndex.assertUniqueBatch(o);for(let l of o)this._addToIndex(l);this._data.push(...o);for(let l of o)this._index.set(l._id,l);return this._enforceCapAfterInsert(),{docs:o}}})}async updateOne(t,i,r={}){await this._ctx.ensureConnected();let s=this._findRaw(t);if(!s)return null;let{save:n,session:a}=r,{docs:o}=await this._updateCore([s],t,i,{save:n,session:a});return Q(o[0])}async updateMany(t,i,r={}){await this._ctx.ensureConnected();let s=this._findAllRaw(t);if(s.length===0)return[];let{save:n,session:a}=r,{docs:o}=await this._updateCore(s,t,i,{save:n,session:a});return o.map(Q)}async _updateCore(t,i,r,{save:s,session:n}){return this._pipeline.execute({op:"update",beforeHook:"beforeUpdate",afterHook:"afterUpdate",hookPayload:{collection:this.name,filter:i,update:r},save:s,session:n,afterHookPayload:(a)=>({collection:this.name,filter:i,update:r,result:a.length===1?a[0]:a}),mutate:async(a)=>{let o=this._changelogEnabled?t.map((u)=>structuredClone(u)):t.map(()=>null),c=t.map((u)=>this._prepareUpdatedDoc(u,r));this._assertUniqueCandidates(t,c),a();let l=new Set(t),d=new Map;for(let u=0;u<this._data.length;u++)if(l.has(this._data[u]))d.set(this._data[u],u);for(let u=0;u<t.length;u++)this._commitUpdatedDoc(t[u],c[u],d);return{docs:c,prevDocs:o}}})}applyUpdate(t,i){for(let r in i){if(Ms.has(r))continue;if(r==="_id"||r==="createdAt")continue;let s=i[r];if(Array.isArray(s))t[r]=s;else if(typeof s==="object"&&s!==null){let n=Object.keys(s);if(n.some((a)=>a.startsWith("$"))){for(let a of n)if(a==="$inc"&&typeof t[r]==="number")t[r]+=s[a];else if(a==="$push"){if(!Array.isArray(t[r]))t[r]=[];t[r].push(s[a])}}else t[r]=js(s)}else t[r]=s}if(t.updatedAt=new Date,this._versioning)t._version=(t._version??0)+1;return t}_prepareUpdatedDoc(t,i){let r=structuredClone(t),s=structuredClone(t);if(this.applyUpdate(s,i),!this._schema)return s;let n=jr(s,this._schema,this._strict);if(!n.length)return s;switch(this._onSchemaError){case"throw":throw new D("ERR_SKALEX_VALIDATION_UPDATE",`Update validation failed on doc "${t._id}": ${n.join("; ")}`,{id:t._id,errors:n});case"strip":return this._stripCandidateToValid(s,r);default:return this._ctx.logger(`[${this.name}] Update validation warning: ${n.join("; ")}`,"warn"),s}}_stripCandidateToValid(t,i){let r=qr(t,this._schema),s=structuredClone(i);for(let[n,a]of Object.entries(r)){if(n.startsWith("_"))continue;s[n]=a}if(s.updatedAt=t.updatedAt,this._versioning)s._version=t._version;return s}_commitUpdatedDoc(t,i,r){let s=r?r.get(t):this._data.indexOf(t);if(s===void 0||s===-1)throw new Ve("ERR_SKALEX_PERSISTENCE_DOC_MISSING",`Document "${t._id}" no longer exists in collection "${this.name}"`,{id:t._id,collection:this.name});this._data[s]=i,this._index.set(i._id,i),this._updateInIndex(t,i)}_assertUniqueCandidates(t,i){this._fieldIndex?.assertUniqueCandidates(t,i)}async upsert(t,i,r={}){if(await this._ctx.ensureConnected(),this._findRaw(t))return this.updateOne(t,i,r);return this.insertOne({...Go(t),...i},r)}async upsertMany(t,i,r={}){await this._ctx.ensureConnected();let{save:s,...n}=r,a=[];for(let o of t)a.push(await this.upsert({[i]:o[i]},o,{...n,save:!1}));return await this._saveIfNeeded(s),a}async restore(t,i={}){if(!this._softDelete)throw new ut("ERR_SKALEX_QUERY_SOFT_DELETE_REQUIRED",`restore() requires softDelete on "${this.name}"`,{collection:this.name});await this._ctx.ensureConnected();let{save:r,session:s}=i,n=this._findRaw(t,{includeDeleted:!0});if(!n||!n._deletedAt)return null;let{docs:a}=await this._pipeline.execute({op:"restore",beforeHook:null,afterHook:null,hookPayload:null,save:r,session:s,mutate:async(o)=>(o(),delete n._deletedAt,n.updatedAt=new Date,this._index.set(n._id,n),{docs:[n]})});return Q(a[0])}watch(t,i){if(typeof t==="function")i=t,t=null;if(i)return this._ctx.eventBus.on(this.name,(r)=>{if(!t||ie(r.doc,t))i(r)});return this._watchIterator(t)}_watchIterator(t){let i=[],r=null,s=!1,n=this._ctx.eventBus.on(this.name,(a)=>{if(t&&!ie(a.doc,t))return;if(r){let o=r;r=null,o({value:a,done:!1})}else i.push(a)});return{[Symbol.asyncIterator](){return this},next(){if(i.length>0)return Promise.resolve({value:i.shift(),done:!1});if(s)return Promise.resolve({value:void 0,done:!0});return new Promise((a)=>{r=a})},return(){if(s=!0,n(),r){let a=r;r=null,a({value:void 0,done:!0})}return Promise.resolve({value:void 0,done:!0})}}}async count(t={}){return await this._ctx.ensureConnected(),zo(this._findAllRaw(t))}async sum(t,i={}){return await this._ctx.ensureConnected(),Bo(this._findAllRaw(i),t)}async avg(t,i={}){return await this._ctx.ensureConnected(),Xo(this._findAllRaw(i),t)}async groupBy(t,i={}){return await this._ctx.ensureConnected(),Vo(this._findAllRaw(i),t)}async findOne(t,i={}){await this._ctx.ensureConnected();let{populate:r,select:s,includeDeleted:n=!1}=i,a=this._findRaw(t,{includeDeleted:n});if(!a)return null;let o=this._projectDoc(a,s);if(r)await this._populateDoc(o,a,r);return o}async find(t,i={}){await this._ctx.ensureConnected();let r=Date.now(),{populate:s,select:n,sort:a,page:o=1,limit:c,session:l,includeDeleted:d=!1}=i;await this._ctx.plugins.run("beforeFind",{collection:this.name,filter:t,options:i});let u=this._getCandidates(t),f=jo(t,this._fieldIndex?this._fieldIndex.indexedFields:new Set),h=[];for(let p of u){if(this._softDelete&&p._deletedAt&&!d)continue;if(!ie(p,f))continue;let g=this._projectDoc(p,n);if(s)await this._populateDoc(g,p,s);h.push(g)}if(a){let p=Object.keys(a);h.sort((g,m)=>{for(let w of p){let v=a[w];if(g[w]<m[w])return-v;if(g[w]>m[w])return v}return 0})}let _;if(c){let p=h.length,g=Math.ceil(p/c),m=(o-1)*c;h=h.slice(m,m+c),_={page:o,totalDocs:p,totalPages:g}}return this._ctx.queryLog?.record({collection:this.name,op:"find",filter:t,duration:Date.now()-r,resultCount:h.length}),this._ctx.sessionStats.recordRead(l),await this._ctx.plugins.run("afterFind",{collection:this.name,filter:t,options:i,docs:h}),_?{docs:h,..._}:{docs:h}}async search(t,{filter:i,limit:r=10,minScore:s=0,session:n}={}){await this._ctx.ensureConnected();let a=Date.now();await this._ctx.plugins.run("beforeSearch",{collection:this.name,query:t,options:{filter:i,limit:r,minScore:s}});let o=await this._ctx.embed(t),c=i?this._findAllRaw(i):this._data,l=[];for(let h of c){if(!h._vector)continue;let _=Ur(o,h._vector);if(_>=s)l.push({doc:h,score:_})}l.sort((h,_)=>_.score-h.score);let d=l.slice(0,r);this._ctx.queryLog?.record({collection:this.name,op:"search",query:t,duration:Date.now()-a,resultCount:d.length}),this._ctx.sessionStats.recordRead(n);let u=d.map((h)=>Q(h.doc)),f=d.map((h)=>h.score);return await this._ctx.plugins.run("afterSearch",{collection:this.name,query:t,options:{filter:i,limit:r,minScore:s},docs:u,scores:f}),{docs:u,scores:f}}async similar(t,{limit:i=10,minScore:r=0}={}){await this._ctx.ensureConnected();let s=this._index.get(t);if(!s||!s._vector)return{docs:[],scores:[]};let n=[];for(let o of this._data){if(o._id===t||!o._vector)continue;let c=Ur(s._vector,o._vector);if(c>=r)n.push({doc:o,score:c})}n.sort((o,c)=>c.score-o.score);let a=n.slice(0,i);return{docs:a.map((o)=>Q(o.doc)),scores:a.map((o)=>o.score)}}async deleteOne(t,i={}){await this._ctx.ensureConnected();let{save:r,session:s}=i;if(this._softDelete){let a=this._findRaw(t);if(!a)return null;let{docs:o}=await this._deleteCore("soft",[a],t,{save:r,session:s});return Q(o[0])}let{docs:n}=await this._deleteCore("hard",null,t,{save:r,session:s});if(n.length===0)return null;return Q(n[0])}async deleteMany(t,i={}){await this._ctx.ensureConnected();let{save:r,session:s}=i;if(this._softDelete){let a=this._findAllRaw(t);if(a.length===0)return[];let{docs:o}=await this._deleteCore("soft",a,t,{save:r,session:s});return o.map(Q)}let{docs:n}=await this._deleteCore("hardMany",null,t,{save:r,session:s});return n.map(Q)}async _deleteCore(t,i,r,{save:s,session:n}){return this._pipeline.execute({op:"delete",beforeHook:"beforeDelete",afterHook:"afterDelete",hookPayload:{collection:this.name,filter:r},save:s,session:n,afterHookPayload:(a)=>({collection:this.name,filter:r,result:a.length===1?a[0]:a}),mutate:async(a)=>{if(a(),t==="soft"){let l=new Date;for(let d of i)d._deletedAt=l,d.updatedAt=l,this._index.set(d._id,d);return{docs:i}}if(t==="hard"){let l=this._findIndex(r);if(l===-1)return{docs:[]};let d=this._data.splice(l,1)[0];return this._index.delete(d._id),this._removeFromIndex(d),{docs:[d]}}let o=[],c=[];for(let l of this._data)if(ie(l,r))o.push(l),this._index.delete(l._id),this._removeFromIndex(l);else c.push(l);return this._data=c,{docs:o}}})}async export(t={},i={}){let{dir:r,name:s,format:n="json"}=i;try{let a=this._data.filter((u)=>ie(u,t));if(a.length===0)throw new ut("ERR_SKALEX_QUERY_EXPORT_EMPTY",`export(): no documents matched the filter in "${this.name}"`,{collection:this.name});let o;if(n==="json")o=JSON.stringify(a,null,2);else{let u=(_)=>{if(_==null)return"";let p=typeof _==="object"?JSON.stringify(_):String(_);return p.includes(",")||p.includes('"')||p.includes(`
3
3
  `)||p.includes("\r")?`"${p.replace(/"/g,'""')}"`:p},f=Object.keys(a[0]).map(u).join(","),h=a.map((_)=>Object.values(_).map(u).join(","));o=[f,...h].join(`
4
4
  `)}if(typeof this._ctx.fs.writeRaw!=="function")throw new be("ERR_SKALEX_ADAPTER_NO_RAW_WRITE","export() requires a file-system adapter (FsAdapter). The current adapter does not support raw file writes.");let c=r||`${this._ctx.dataDirectory}/exports`,l=`${s||this.name}.${n}`,d=this._ctx.fs.join(c,l);this._ctx.fs.ensureDir(c),await this._ctx.fs.writeRaw(d,o)}catch(a){throw this._ctx.logger(`Error exporting "${this.name}": ${a.message}`,"error"),a}}_txSnapshotIfNeeded(){let t=this._ctx.txManager;if(!t.active)return;if(this._activeTxId!==t.context?.id)return;t.snapshotIfNeeded(this.name,this._store,(i)=>this._ctx.snapshotCollection(i))}async _saveIfNeeded(t){let i=this._ctx.txManager;if(i.active&&this._activeTxId===i.context?.id)return;if(t??this._ctx.autoSave)await this._ctx.saveCollection(this.name)}_applyValidation(t){if(!this._schema)return t;let i=jr(t,this._schema,this._strict);if(!i.length)return t;switch(this._onSchemaError){case"warn":return this._ctx.logger(`[${this.name}] Validation warning: ${i.join("; ")}`,"warn"),t;case"strip":return qr(t,this._schema);default:throw new D("ERR_SKALEX_VALIDATION_FAILED",`Validation failed: ${i.join("; ")}`,{errors:i})}}_enforceCapAfterInsert(){let t=this._maxDocs;if(!t||this._data.length<=t)return;let i=this._data.splice(0,this._data.length-t);for(let r of i)this._index.delete(r._id),this._removeFromIndex(r)}_findRaw(t,{includeDeleted:i=!1}={}){if(typeof t==="function"){for(let r of this._data){if(this._softDelete&&r._deletedAt&&!i)continue;if(t(r))return r}return null}if(t._id){let r=this._index.get(t._id)||null;if(!r)return null;if(this._softDelete&&r._deletedAt&&!i)return null;if(Object.keys(t).length>1)return ie(r,t)?r:null;return r}if(this._fieldIndex)for(let r in t){if(r==="$or"||r==="$and"||r==="$not")continue;let s=t[r];if(typeof s!=="object"||s===null){let n=this._fieldIndex._lookupIterable(r,s);if(n!==null){for(let a of n){if(this._softDelete&&a._deletedAt&&!i)continue;if(ie(a,t))return a}return null}}}for(let r of this._data){if(this._softDelete&&r._deletedAt&&!i)continue;if(ie(r,t))return r}return null}_findAllRaw(t,{includeDeleted:i=!1}={}){if(t&&typeof t!=="function"&&t._id){let s=this._index.get(t._id);if(!s)return[];if(this._softDelete&&s._deletedAt&&!i)return[];return ie(s,t)?[s]:[]}let r=[];for(let s of this._getCandidates(t)){if(this._softDelete&&s._deletedAt&&!i)continue;if(ie(s,t))r.push(s)}return r}_getCandidates(t){if(!this._fieldIndex)return this._data;if(this._fieldIndex._compoundIndexes.size>0){let i={};for(let r in t){if(r==="$or"||r==="$and"||r==="$not")continue;let s=t[r];if(typeof s!=="object"||s===null)i[r]=s}if(Object.keys(i).length>=2){let r=this._fieldIndex.lookupCompound(i);if(r!==null)return r}}for(let i in t){if(i==="$or"||i==="$and"||i==="$not")continue;let r=t[i];if(typeof r!=="object"||r===null){let s=this._fieldIndex._lookupIterable(i,r);if(s!==null)return s}}return this._data}_findIndex(t){for(let i=0;i<this._data.length;i++)if(ie(this._data[i],t))return i;return-1}_addToIndex(t){if(this._fieldIndex)this._fieldIndex.add(t)}_removeFromIndex(t){if(this._fieldIndex)this._fieldIndex.remove(t)}_updateInIndex(t,i){if(this._fieldIndex)this._fieldIndex.update(t,i)}async _buildDoc(t,{ttl:i,embed:r}={}){let s={...t,_id:t._id??(this._ctx.idGenerator??Mo)(),createdAt:new Date,updatedAt:new Date},n=i??this._defaultTtl;if(n)s._expiresAt=Fo(n);let a=r??this._defaultEmbed;if(a){let o=typeof a==="function"?a(s):s[a];s._vector=await this._ctx.embed(String(o))}if(this._versioning)s._version=1;return s}_projectDoc(t,i){if(i){let s={};for(let n of i){if(n==="_vector")continue;s[n]=t[n]}return s}let r={...t};return delete r._vector,r}async _populateDoc(t,i,r){for(let s of r){let n=await this._ctx.getCollection(s).findOne({_id:i[s]});if(n)t[s]=n}}}class Fi{async read(t){throw Error("StorageAdapter.read() not implemented")}async write(t,i){throw Error("StorageAdapter.write() not implemented")}async delete(t){throw Error("StorageAdapter.delete() not implemented")}async list(){throw Error("StorageAdapter.list() not implemented")}async writeAll(t){for(let{name:i,data:r}of t)await this.write(i,r)}}class Us extends Fi{constructor({dir:t,format:i="gz"}){super();this.dir=it.resolve(t),this.format=i,this._ensureDir(this.dir)}_ensureDir(t){if(!G.existsSync(t))G.mkdirSync(t,{recursive:!0})}_filePath(t){return it.join(this.dir,`${t}.${this.format}`)}async read(t){let i=this._filePath(t);try{let r=await G.promises.readFile(i);if(this.format==="gz")r=Ai.inflateSync(r);return r.toString("utf8")}catch(r){if(r.code==="ENOENT")return null;throw r}}async write(t,i){let r=this._filePath(t),s=it.join(this.dir,`${t}_${globalThis.crypto.randomUUID()}.tmp.${this.format}`);if(this.format==="gz"){let n=Ai.deflateSync(i);await G.promises.writeFile(s,n)}else await G.promises.writeFile(s,i,"utf8");await G.promises.rename(s,r)}async writeAll(t){let i=[];try{for(let{name:r,data:s}of t){let n=this._filePath(r),a=it.join(this.dir,`${r}_${globalThis.crypto.randomUUID()}.tmp.${this.format}`);if(this.format==="gz"){let o=Ai.deflateSync(s);await G.promises.writeFile(a,o)}else await G.promises.writeFile(a,s,"utf8");i.push({tmp:a,fp:n})}for(let{tmp:r,fp:s}of i)await G.promises.rename(r,s)}catch(r){for(let{tmp:s}of i)try{await G.promises.unlink(s)}catch{}throw r}}async delete(t){let i=this._filePath(t);try{await G.promises.unlink(i)}catch(r){if(r.code!=="ENOENT")throw r}}async list(){try{let t=await G.promises.readdir(this.dir),i=`.${this.format}`;return t.filter((r)=>r.endsWith(i)&&!r.includes(".tmp.")).map((r)=>r.slice(0,-i.length))}catch(t){if(t.code==="ENOENT")return[];throw t}}join(...t){return it.join(...t)}ensureDir(t){this._ensureDir(t)}async writeRaw(t,i){this._ensureDir(it.dirname(t)),await G.promises.writeFile(t,i,"utf8")}async readRaw(t){return G.promises.readFile(it.resolve(t),"utf8")}}class Fs{constructor(){this._migrations=[]}add(t){let{version:i,up:r}=t;if(typeof i!=="number"||i<1)throw new D("ERR_SKALEX_VALIDATION_MIGRATION",`Migration version must be a positive integer, got ${i}`,{version:i});if(typeof r!=="function")throw new D("ERR_SKALEX_VALIDATION_MIGRATION",`Migration version ${i} must have an "up" function`,{version:i});if(this._migrations.some((s)=>s.version===i))throw new D("ERR_SKALEX_VALIDATION_MIGRATION_DUPLICATE",`Migration version ${i} is already registered`,{version:i});this._migrations.push({...t}),this._migrations.sort((s,n)=>s.version-n.version)}async run(t,i=[]){let r=new Set(i),s=this._migrations.filter((n)=>!r.has(n.version));for(let n of s){let a=t(n.version);await n.up(a),r.add(n.version)}return[...r].sort((n,a)=>n-a)}status(t=[]){let i=new Set(t),r=this._migrations.map((s)=>s.version).filter((s)=>!i.has(s));return{current:t.length?Math.max(...t):0,applied:[...i].sort((s,n)=>s-n),pending:r}}}var Fr={[Symbol.iterator](){return{next(){return{done:!0}}}},size:0};function Kr(t){return{[Symbol.iterator](){return t[Symbol.iterator]()},get size(){return t.size}}}function Si(t){return t.map((i)=>{if(i===null||i===void 0)return"\x00";if(typeof i==="boolean")return i?"\x01T":"\x01F";if(typeof i==="number")return`\x02${i}`;return`\x03${String(i)}`}).join("\x1F")}class Yt{constructor(t=[],i=[]){this._fields=new Set,this._compoundFields=[];for(let r of t)if(Array.isArray(r)){for(let s of r)this._validateFieldName(s);this._compoundFields.push(r)}else this._validateFieldName(r),this._fields.add(r);for(let r of i)this._validateFieldName(r);this._uniqueFields=new Set(i),this._indexedFields=new Set([...this._fields,...this._uniqueFields]),this._fieldIndexes=new Map,this._uniqueIndexes=new Map;for(let r of this._fields)this._fieldIndexes.set(r,new Map);for(let r of this._uniqueFields)if(this._uniqueIndexes.set(r,new Map),!this._fieldIndexes.has(r))this._fieldIndexes.set(r,new Map);this._compoundIndexes=new Map;for(let r of this._compoundFields)this._compoundIndexes.set(r.join("\x00"),{fields:r,map:new Map})}get indexedFields(){return this._indexedFields}buildFromData(t){for(let[,i]of this._fieldIndexes)i.clear();for(let[,i]of this._uniqueIndexes)i.clear();for(let[,i]of this._compoundIndexes)i.map.clear();for(let i of t)this._indexDoc(i)}add(t){this._checkUnique(t,null),this._indexDoc(t)}remove(t){for(let[i,r]of this._fieldIndexes){let s=t[i];if(s!==void 0){let n=r.get(s);if(n){if(n.delete(t),n.size===0)r.delete(s)}}}for(let[i,r]of this._uniqueIndexes){let s=t[i];if(s!==void 0)r.delete(s)}for(let[,i]of this._compoundIndexes){let r=Si(i.fields.map((n)=>t[n])),s=i.map.get(r);if(s){if(s.delete(t),s.size===0)i.map.delete(r)}}}update(t,i){this._checkUnique(i,t),this.remove(t);try{this._indexDoc(i)}catch(r){try{this._indexDoc(t)}catch{}throw r}}lookup(t,i){let r=this._fieldIndexes.get(t);if(!r)return null;let s=r.get(i);return s?[...s]:[]}_lookupIterable(t,i){let r=this._fieldIndexes.get(t);if(!r)return null;let s=r.get(i);return s?Kr(s):Fr}lookupCompound(t){let i=Object.keys(t).sort();for(let[,r]of this._compoundIndexes){let s=[...r.fields].sort();if(s.length!==i.length)continue;if(s.every((n,a)=>n===i[a])){let n=Si(r.fields.map((o)=>t[o])),a=r.map.get(n);return a?Kr(a):Fr}}return null}isUniqueTaken(t,i){let r=this._uniqueIndexes.get(t);if(!r)return!1;return r.has(i)}assertUniqueCandidates(t,i){if(this._uniqueFields.size===0)return;let r=new Set(t.map((s)=>s._id));for(let s of this._uniqueFields){let n=new Set,a=this._uniqueIndexes.get(s);if(a){for(let[c,l]of a.entries())if(!r.has(l._id))n.add(c)}let o=new Map;for(let c=0;c<i.length;c++){let l=i[c][s];if(l===void 0)continue;if(n.has(l))throw new De("ERR_SKALEX_UNIQUE_VIOLATION",`Unique constraint violation: field "${s}" value "${l}" already exists`,{field:s,value:l});let d=o.get(l);if(d&&d!==t[c]._id)throw new De("ERR_SKALEX_UNIQUE_VIOLATION",`Unique constraint violation: field "${s}" value "${l}" already exists`,{field:s,value:l});o.set(l,t[c]._id)}}}assertUniqueBatch(t){if(this._uniqueFields.size===0)return;for(let i of this._uniqueFields){let r=this._uniqueIndexes.get(i),s=new Set;for(let n of t){let a=n[i];if(a===void 0)continue;if(r&&r.has(a))throw new De("ERR_SKALEX_UNIQUE_VIOLATION",`Unique constraint violation: field "${i}" value "${a}" already exists`,{field:i,value:a});if(s.has(a))throw new De("ERR_SKALEX_UNIQUE_VIOLATION",`Unique constraint violation: duplicate "${i}" value "${a}" within batch`,{field:i,value:a});s.add(a)}}}_validateFieldName(t){if(t.includes("."))throw new D("ERR_SKALEX_VALIDATION_INDEX_DOT_PATH",`Index fields cannot use dot-notation: "${t}". Use a flat field name.`,{field:t})}_indexDoc(t){for(let[i,r]of this._fieldIndexes){let s=t[i];if(s!==void 0){if(!r.has(s))r.set(s,new Set);r.get(s).add(t)}}for(let[i,r]of this._uniqueIndexes){let s=t[i];if(s!==void 0)r.set(s,t)}for(let[,i]of this._compoundIndexes){for(let s of i.fields){let n=t[s];if(n!==void 0&&n!==null&&typeof n==="object")throw new D("ERR_SKALEX_VALIDATION_COMPOUND_INDEX",`Compound index field "${s}" must be a scalar value (string, number, or boolean), got ${Array.isArray(n)?"array":typeof n}`,{field:s})}let r=Si(i.fields.map((s)=>t[s]));if(!i.map.has(r))i.map.set(r,new Set);i.map.get(r).add(t)}}_checkUnique(t,i){for(let r of this._uniqueFields){let s=t[r];if(s===void 0)continue;let n=this._uniqueIndexes.get(r);if(!n)continue;let a=n.get(s);if(a&&a._id!==i?._id)throw new De("ERR_SKALEX_UNIQUE_VIOLATION",`Unique constraint violation: field "${r}" value "${s}" already exists`,{field:r,value:s})}}}var jt="_flush",qt="migrations";class Ks{constructor({adapter:t,serializer:i,deserializer:r,logger:s,debug:n=!1,lenientLoad:a=!1}){this._adapter=t,this._serializer=i,this._deserializer=r,this._logger=s,this._debug=n,this._lenientLoad=a,this._saveLock=Promise.resolve()}_withSaveLock(t){let i=this._saveLock.then(t);return this._saveLock=i.catch(()=>{}),i}async loadAll(t,{parseSchema:i,buildIndex:r,IndexEngine:s}){try{let n=await this._adapter.list();await Promise.all(n.map(async(a)=>{try{let o=await this._adapter.read(a);if(!o)return;let c=this._deserializer(o),{collectionName:l,data:d}=c;if(!l)return;let u=t[l],f=u?.rawSchema??c.rawSchema??null,h=u?.schema??(f?i(f):null),_=u?.changelog??c.changelog??!1,p=u?.softDelete??c.softDelete??!1,g=u?.versioning??c.versioning??!1,m=u?.strict??c.strict??!1,w=u?.onSchemaError??c.onSchemaError??"throw",v=u?.defaultTtl??c.defaultTtl??null,q=u?.defaultEmbed??c.defaultEmbed??null,E=u?.maxDocs??c.maxDocs??null,A=u?u.fieldIndex:null;if(!A&&h?.uniqueFields?.length)A=new s([],h.uniqueFields);let tt=r(d,"_id");if(A)A.buildFromData(d);t[l]={collectionName:l,data:d,index:tt,isSaving:!1,_pendingSave:!1,_dirty:!1,schema:h,rawSchema:f,fieldIndex:A,changelog:_,softDelete:p,versioning:g,strict:m,onSchemaError:w,defaultTtl:v,defaultEmbed:q,maxDocs:E}}catch(o){if(o.code==="ENOENT")return;if(this._lenientLoad){this._logger(`WARNING: Could not load collection "${a}": ${o.message}. Collection will be empty.`,"error");return}throw new Ve("ERR_SKALEX_PERSISTENCE_CORRUPT",`Failed to load collection "${a}": ${o.message}`,{collection:a})}})),this._detectIncompleteFlush(t),await this._cleanOrphanTempFiles()}catch(n){if(n.code!=="ENOENT")throw this._logger(`Error loading data: ${n}`,"error"),n}}async save(t,i){if(i)await this._saveOne(t,i);else await Promise.all(Object.keys(t).map((r)=>this._saveOne(t,r)))}async saveDirty(t){let i=Object.keys(t).filter((r)=>t[r]._dirty);if(i.length===0)return;await Promise.all(i.map((r)=>this._saveOne(t,r)))}saveAtomic(t,i){return this._withSaveLock(async()=>{if(i.length===0)return;this._writeFlushSentinel(t,i);let r=new Set(i);r.add("_meta");let s=[...r].filter((n)=>t[n]).map((n)=>({name:n,data:this._serializeCollection(t[n])}));try{await this._adapter.writeAll(s)}catch(n){throw new Ve("ERR_SKALEX_PERSISTENCE_FLUSH_FAILED",`Batch save failed during writeAll: ${n.message}`,{collections:i})}for(let n of i)if(t[n])t[n]._dirty=!1;try{this._clearFlushSentinel(t),await this._adapter.write("_meta",this._serializeCollection(t._meta))}catch(n){this._logger(`WARNING: Batch data committed but sentinel clear failed: ${n.message}. Next load will report an incomplete flush (false positive).`,"error")}})}markDirty(t,i){let r=t[i];if(r)r._dirty=!0}_serializeCollection(t){let i={collectionName:t.collectionName,data:t.data};if(t.rawSchema)i.rawSchema=t.rawSchema;if(t.changelog)i.changelog=t.changelog;if(t.softDelete)i.softDelete=t.softDelete;if(t.versioning)i.versioning=t.versioning;if(t.strict)i.strict=t.strict;if(t.onSchemaError!=="throw")i.onSchemaError=t.onSchemaError;if(t.defaultTtl)i.defaultTtl=t.defaultTtl;if(t.defaultEmbed)i.defaultEmbed=t.defaultEmbed;if(t.maxDocs)i.maxDocs=t.maxDocs;return this._serializer(i)}async _saveOne(t,i){let r=t[i];if(!r)return;if(r.isSaving)return r._pendingSave=!0,new Promise((s,n)=>{(r._saveWaiters??=[]).push({resolve:s,reject:n})});r.isSaving=!0,r._pendingSave=!1;try{await this._writeCollection(i,r);while(r._pendingSave)r._pendingSave=!1,await this._writeCollection(i,r);this._resolveSaveWaiters(r)}catch(s){throw this._rejectSaveWaiters(r,s),s}finally{r.isSaving=!1}}async _writeCollection(t,i){try{await this._adapter.write(t,this._serializeCollection(i)),i._dirty=!1}catch(r){throw this._logger(`Error saving "${t}": ${r.message}`,"error"),r}}_resolveSaveWaiters(t){let i=t._saveWaiters?.splice(0)??[];for(let r of i)r.resolve()}_rejectSaveWaiters(t,i){let r=t._saveWaiters?.splice(0)??[];for(let s of r)s.reject(i)}_writeFlushSentinel(t,i){let r=this._getOrCreateMeta(t);r[jt]={startedAt:new Date().toISOString(),collections:i,completedAt:null}}_clearFlushSentinel(t){let i=this._getOrCreateMeta(t);if(i[jt])i[jt].completedAt=new Date().toISOString()}_detectIncompleteFlush(t){let i=t._meta;if(!i)return;let r=i.index.get(qt);if(!r)return;let s=r[jt];if(!s)return;if(s.startedAt&&!s.completedAt)this._logger(`WARNING: Incomplete flush detected (started ${s.startedAt}, collections: ${s.collections?.join(", ")}). Data may be inconsistent.`,"error")}async _cleanOrphanTempFiles(){if(typeof this._adapter.join!=="function")return;if(typeof this._adapter.list!=="function")return;try{let t=await import("fs"),i=await import("path"),r=this._adapter.dir;if(!r)return;let s=(await t.default.promises.readdir(r)).filter((n)=>n.includes(".tmp."));for(let n of s){let a=i.default.join(r,n);try{await t.default.promises.unlink(a),this._log(`Cleaned orphan temp file: ${n}`)}catch{}}}catch{}}_getOrCreateMeta(t){if(!t._meta)t._meta={collectionName:"_meta",data:[],index:new Map,isSaving:!1,_pendingSave:!1,_dirty:!1,schema:null,rawSchema:null,fieldIndex:null,changelog:!1,softDelete:!1,versioning:!1,strict:!1,onSchemaError:"throw",defaultTtl:null,defaultEmbed:null,maxDocs:null};let i=t._meta,r=i.index.get(qt);if(!r)r={_id:qt},i.data.push(r),i.index.set(qt,r);return r}_log(t){if(this._debug)this._logger(t,"info")}}var Ho=0;class zs{constructor(){this._txLock=Promise.resolve(),this._ctx=null,this._abortedIds=new Set}get active(){return this._ctx!==null&&!this._ctx.aborted}get context(){return this._ctx}async run(t,i,{timeout:r=0}={}){let s=async()=>{await i._ensureConnected();let a=new Set(Object.keys(i.collections)),o={id:++Ho,startedAt:Date.now(),aborted:!1,preExisting:a,touchedCollections:new Set,snapshots:new Map,deferredEffects:[],timeout:r};this._ctx=o;let c=null,l=r>0?new Promise((f,h)=>{c=setTimeout(()=>{o.aborted=!0,h(new Ce("ERR_SKALEX_TX_TIMEOUT",`Transaction ${o.id} timed out after ${r}ms`))},r)}):null,d=this,u=new Proxy(i,{get(f,h){if(h==="_txId")return o.id;if(o!==d._ctx)throw new Ce("ERR_SKALEX_TX_STALE_PROXY",`Transaction ${o.id} has ended. This proxy is no longer usable.`);if(h==="collections")throw new Ce("ERR_SKALEX_TX_DIRECT_ACCESS","Direct access to db.collections inside transaction() is not covered by rollback. Use the collection API (db.useCollection) instead.");if(h==="useCollection")return(p)=>{let g=f.useCollection(p);return g._activeTxId=o.id,g};let _=Reflect.get(f,h);return typeof _==="function"?_.bind(f):_}});try{let f=t(u),h=l?await Promise.race([f,l]):await f;if(o.aborted)throw new Ce("ERR_SKALEX_TX_ABORTED",`Transaction ${o.id} was aborted`);let _=[...o.touchedCollections];if(_.length>0)await i._persistence.saveAtomic(i.collections,_);for(let p of o.deferredEffects)await p();return h}catch(f){for(let[h,_]of o.snapshots)if(o.preExisting.has(h)){if(i._applySnapshot(h,_),i.collections[h])i.collections[h]._dirty=_._dirty}for(let h in i.collections)if(!o.preExisting.has(h))delete i.collections[h],delete i._collectionInstances[h];throw f}finally{if(c)clearTimeout(c);if(o.aborted)this._abortedIds.add(o.id);this._ctx=null;for(let f in i._collectionInstances){let h=i._collectionInstances[f];if(h._createdInTxId===o.id)h._createdInTxId=null;if(h._activeTxId===o.id)h._activeTxId=null}}},n=this._txLock.then(s);return this._txLock=n.catch(()=>{}),n}snapshotIfNeeded(t,i,r){let s=this._ctx;if(!s)return;if(this._assertCtxNotAborted(s),!s.snapshots.has(t)){let n=r(i);n._dirty=i._dirty??!1,s.snapshots.set(t,n)}s.touchedCollections.add(t)}assertNotAborted(){let t=this._ctx;if(t)this._assertCtxNotAborted(t)}_assertCtxNotAborted(t){if(t.aborted)throw new Ce("ERR_SKALEX_TX_ABORTED",`Transaction ${t.id} was aborted. No further mutations allowed.`)}defer(t){if(this._ctx)return this._ctx.deferredEffects.push(t),!0;return!1}}class Bs{constructor(t){this._CollectionClass=t,this.stores={},this._instances={}}get(t,i){if(this._instances[t])return this._instances[t];if(!this.stores[t])this.createStore(t);let r=new this._CollectionClass(this.stores[t],i);return this._instances[t]=r,r}create(t,i={},r){this.createStore(t,i);let s=new this._CollectionClass(this.stores[t],r);return this._instances[t]=s,s}createStore(t,{schema:i,indexes:r=[],changelog:s=!1,softDelete:n=!1,versioning:a=!1,strict:o=!1,onSchemaError:c="throw",defaultTtl:l=null,defaultEmbed:d=null,maxDocs:u=null}={}){let f=null,h=null;if(i){f=Ls(i);let _=f.uniqueFields;if(r.length||_.length)h=new Yt(r,_)}else if(r.length)h=new Yt(r,[]);this.stores[t]={collectionName:t,data:[],index:new Map,isSaving:!1,_pendingSave:!1,_dirty:!1,schema:f,rawSchema:i||null,fieldIndex:h,changelog:s,softDelete:n,versioning:a,strict:o,onSchemaError:c,defaultTtl:l,defaultEmbed:d,maxDocs:u}}rename(t,i){if(!this.stores[t])throw new Ve("ERR_SKALEX_PERSISTENCE_COLLECTION_NOT_FOUND",`Collection "${t}" not found`,{collection:t});if(this.stores[i])throw new Ve("ERR_SKALEX_PERSISTENCE_COLLECTION_EXISTS",`Collection "${i}" already exists`,{collection:i});let r=this.stores[t];if(r.collectionName=i,this.stores[i]=r,delete this.stores[t],this._instances[t]){let s=this._instances[t];s.name=i,this._instances[i]=s,delete this._instances[t]}}buildIndex(t,i){let r=new Map;for(let s of t)r.set(s[i],s);return r}inspect(t){if(t){let r=this.stores[t];if(!r)return null;return{name:t,count:r.data.length,schema:r.schema?Object.fromEntries(r.schema.fields):null,indexes:r.fieldIndex?[...r.fieldIndex.indexedFields]:[],softDelete:r.softDelete??!1,versioning:r.versioning??!1,strict:r.strict??!1,onSchemaError:r.onSchemaError??"throw",maxDocs:r.maxDocs??null}}let i={};for(let r in this.stores)i[r]=this.inspect(r);return i}dump(){let t={};for(let i in this.stores)if(!i.startsWith("_"))t[i]=structuredClone(this.stores[i].data);return t}schema(t){let i=this.stores[t];if(!i)return null;if(i.schema)return Object.fromEntries([...i.schema.fields.entries()].map(([r,s])=>[r,s.type]));if(i.data.length>0)return qo(i.data[0]);return null}stats(t){let i=(r)=>{let s=this.stores[r];if(!s)return null;let n=s.data.length,a=0;for(let o of s.data)try{a+=JSON.stringify(o).length}catch(c){}return{collection:r,count:n,estimatedSize:a,avgDocSize:n>0?Math.round(a/n):0}};if(t)return i(t);return Object.keys(this.stores).map(i)}clear(){this.stores={},this._instances={}}}class Ki{async embed(t){throw Error("EmbeddingAdapter.embed() not implemented")}}var ye=(t)=>globalThis.process?.env?.[t]??globalThis.Deno?.env?.get(t);class Xs extends Ki{constructor({apiKey:t=ye("OPENAI_API_KEY"),model:i=ye("OPENAI_EMBED_MODEL")??"text-embedding-3-small",baseUrl:r=ye("OPENAI_EMBED_BASE_URL")??"https://api.openai.com/v1/embeddings",dimensions:s=ye("OPENAI_EMBED_DIMENSIONS")!=null?Number(ye("OPENAI_EMBED_DIMENSIONS")):void 0,organization:n=ye("OPENAI_ORGANIZATION")??void 0,timeout:a=ye("OPENAI_EMBED_TIMEOUT")!=null?Number(ye("OPENAI_EMBED_TIMEOUT")):void 0,retries:o=Number(ye("OPENAI_EMBED_RETRIES")??0),retryDelay:c=Number(ye("OPENAI_EMBED_RETRY_DELAY")??1000),headers:l={},fetch:d=globalThis.fetch}={}){super();if(!t)throw Error("OpenAIEmbeddingAdapter requires an apiKey");this.apiKey=t,this.model=i,this.baseUrl=r,this.dimensions=s,this.organization=n,this.timeout=a,this.retries=o,this.retryDelay=c,this.headers=l,this._fetch=d}async embed(t){let i;for(let r=0;r<=this.retries;r++){let s=this.timeout!=null?new AbortController:null,n=s?setTimeout(()=>s.abort(),this.timeout):null;try{let a=await this._fetch(this.baseUrl,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,...this.organization&&{"OpenAI-Organization":this.organization},...this.headers},body:JSON.stringify({input:t,model:this.model,...this.dimensions!==void 0&&{dimensions:this.dimensions}}),...s&&{signal:s.signal}});if(!a.ok){let o=(await a.text()).slice(0,200);throw Error(`OpenAI embedding API error ${a.status}: ${o}`)}return(await a.json()).data[0].embedding}catch(a){if(i=a,r<this.retries)await new Promise((o)=>setTimeout(o,this.retryDelay*2**r))}finally{if(n!==null)clearTimeout(n)}}throw i}}var mt=(t)=>globalThis.process?.env?.[t]??globalThis.Deno?.env?.get(t);class Vs extends Ki{constructor({model:t=mt("OLLAMA_EMBED_MODEL")??"nomic-embed-text",host:i=mt("OLLAMA_HOST")??"http://localhost:11434",timeout:r=mt("OLLAMA_EMBED_TIMEOUT")!=null?Number(mt("OLLAMA_EMBED_TIMEOUT")):void 0,retries:s=Number(mt("OLLAMA_EMBED_RETRIES")??0),retryDelay:n=Number(mt("OLLAMA_EMBED_RETRY_DELAY")??1000),headers:a={},fetch:o=globalThis.fetch}={}){super();this.model=t,this.host=i,this.timeout=r,this.retries=s,this.retryDelay=n,this.headers=a,this._fetch=o}async embed(t){let i;for(let r=0;r<=this.retries;r++){let s=this.timeout!=null?new AbortController:null,n=s?setTimeout(()=>s.abort(),this.timeout):null;try{let a=await this._fetch(`${this.host}/api/embeddings`,{method:"POST",headers:{"Content-Type":"application/json",...this.headers},body:JSON.stringify({model:this.model,prompt:t}),...s&&{signal:s.signal}});if(!a.ok){let o=(await a.text()).slice(0,200);throw Error(`Ollama embedding API error ${a.status}: ${o}`)}return(await a.json()).embedding}catch(a){if(i=a,r<this.retries)await new Promise((o)=>setTimeout(o,this.retryDelay*2**r))}finally{if(n!==null)clearTimeout(n)}}throw i}}class ii{async generate(t,i){throw Error("LLMAdapter.generate() not implemented")}async summarize(t){throw Error("LLMAdapter.summarize() not implemented")}}var zi=`You are a database query assistant. Convert the user's natural language request into a JSON filter object for a document database.
5
5
 
@@ -174,5 +174,5 @@ data: /message
174
174
  mutation NotifyVibecontrolsAgentPluginChange($agentId: ID!) {
175
175
  notifyVibecontrolsAgentPluginChange(agentId: $agentId)
176
176
  }
177
- `;async function rr(t){try{if(!T.isConfigured())return;let i=await t.getConfig("gateway-auth:agentRecordId");if(!i)return;let r=await T.workspaceQuery(Fd,{agentId:i});if(r.errors?.length)e().logger.debug(y,"Plugin-change notify returned errors",{errors:r.errors.map((s)=>s.message)})}catch(i){e().logger.debug(y,`Plugin-change notify failed: ${i instanceof Error?i.message:String(i)}`)}}var Nt=null,gt=null,Ct=!1;function Pt(t,i,r){if(Nt)return;let s=Number(process.env.VIBE_TUNNEL_SYNC_MS),n=Number.isFinite(s)&&s>0?s:r??60000;Nt=setInterval(async()=>{if(!T.isConfigured())return;try{let a=i.getProvider("tunnel");if(!a||!a.getActiveTunnelUrl)return;let o=Wt(await a.getActiveTunnelUrl()),c=await t.getConfig("gateway-auth:agentRecordId");if(!c)return;if(await _i(c),!o){if(!Ct)Ct=!(await T.workspaceQuery(Mt,{id:c,input:{tunnelStatus:"DISCONNECTED"}})).errors?.length,e().logger.warn(y,"No active tunnel URL \u2014 reported tunnel as DISCONNECTED",{reported:Ct});return}let l=Ct,d=T.getConfig()?.workspaceId||"",u;if(d)u=(await T.workspaceQuery(gi,{workspaceId:d})).data?.vibecontrolsAgents?.find((g)=>g.id===c)?.tunnelUrl??null;let f=o!==gt,h=u!==void 0&&u!==o;if(!f&&!h&&!l)return;e().logger.info(y,"Re-publishing tunnel URL",{reason:l?"tunnel-recovered":h?"backend-drift":"local-change",backend:u,local:o,lastReported:gt});let _=await T.workspaceQuery(Mt,{id:c,input:{tunnelUrl:o,tunnelStatus:"CONNECTED"}});if(!_.errors?.length)gt=o,Ct=!1,e().logger.info(y,"Tunnel URL synced to backend",{tunnelUrl:o});else e().logger.warn(y,"Tunnel URL sync returned errors",{errors:_.errors.map((p)=>p.message)})}catch(a){e().logger.debug(y,`Tunnel sync check failed: ${a instanceof Error?a.message:String(a)}`)}},n),Nt.unref?.()}function pi(){if(Nt)clearInterval(Nt),Nt=null;Ct=!1,gt=null}async function Rr(t,i){if(process.env.VIBE_BRIDGE_DISABLED==="1")return;try{let{bridgeClient:r}=await import("./bridge-client-9ax1cvj6.js"),{registerBridgeCommands:s,registerPluginBridgeService:n}=await import("./bridge-commands-6dj7ewgx.js");s(r,t),n(t,r);let a=process.env.VIBECONTROLS_PROFILE||"default";r.start(i,a)}catch(r){e().logger.warn(y,`bridge-client start failed: ${r instanceof Error?r.message:String(r)}`)}}async function mi(t,i,r){if(!T.isConfigured()){e().logger.debug(y,"Gateway auth not configured \u2014 skipping auto-report");return}let s=await t.getConfig("gateway-auth:workspaceId");if(!s){e().logger.warn(y,"No workspaceId configured \u2014 skipping auto-report. "+"Configure via POST /api/agent/gateway-auth with workspaceId.");return}e().logger.info(y,"Starting auto-report to backend...");try{let n=process.env.VIBE_AGENT_NAME||ui.hostname(),a=ui.platform(),o=ui.arch(),c=Ae(),l=await qd(i),d=await Nr(t,n);if(d){e().logger.info(y,`Updating agent record ${d} via workspace gateway`);let f=await T.workspaceQuery(Mt,{id:d,input:{tunnelUrl:l||null,tunnelStatus:l?"CONNECTED":"DISCONNECTED",agentApiKey:r}});if(f.errors?.length){if(e().logger.warn(y,"Update mutation returned errors",{errors:f.errors.map((_)=>_.message)}),await Ud(s,d)){e().logger.warn(y,"Agent record still exists \u2014 treating update failure as transient; will retry on next sync (NOT registering a duplicate)",{agentRecordId:d}),await Rr(i,d),await Ha(s,{hostname:n,platform:a,arch:o,tunnelUrl:l,apiKey:r}),await _i(d),gt=l,Pt(t,i),Ot(t);return}e().logger.info(y,"Cached agent record no longer exists \u2014 clearing cache and registering fresh",{agentRecordId:d}),await t.setConfig("gateway-auth:agentRecordId",""),d=null}else{e().logger.info(y,"Agent record updated successfully",{agentRecordId:d,tunnelUrl:l}),await Rr(i,d),await Ga(d,l,s),await Ha(s,{hostname:n,platform:a,arch:o,tunnelUrl:l,apiKey:r}),await _i(d),gt=l,Pt(t,i),Ot(t);return}}e().logger.info(y,`Registering installed agent via workspace gateway (hostname: ${n})`);for(let f=1;f<=et&&!d;f++){if(f>1){let g=await Nr(t,n);if(g){d=g,e().logger.info(y,"Adopted an agent record discovered after a retry (not registering a duplicate)",{agentRecordId:d});break}}let h=await T.workspaceQuery(Wa,{workspaceId:s,input:{name:n,hostname:n,platform:a,architecture:o,tunnelUrl:l||null,agentApiKey:r}}),_=h.errors?.length?void 0:h.data?.registerInstalledAgent?.id;if(_){await t.setConfig("gateway-auth:agentRecordId",_),d=_,e().logger.info(y,"Agent registered successfully",{agentRecordId:_,name:h.data?.registerInstalledAgent?.name,tunnelUrl:l,version:c,attempt:f});break}let p=h.errors?.length?h.errors.map((g)=>g.message):["registerInstalledAgent returned no id"];if(f<et){let g=Math.min(30000,Cr*2**(f-1));e().logger.warn(y,`Register installed agent failed (attempt ${f}/${et}) \u2014 retrying in ${Math.round(g/1000)}s`,{errors:p}),await new Promise((m)=>setTimeout(m,g));continue}e().logger.error(y,"Register installed agent failed after retries \u2014 agent is running but NOT registered with the workspace",{errors:p}),e().recordDegradedReason("agent-registration",`registerInstalledAgent failed after ${et} attempts: ${p.join("; ")}`)}if(!d){Pt(t,i),Ot(t);return}let u=await T.workspaceQuery(Mt,{id:d,input:{tunnelUrl:l||null,tunnelStatus:l?"CONNECTED":"DISCONNECTED"}});if(u.errors?.length)e().logger.warn(y,"Post-registration agent update returned errors",{errors:u.errors.map((f)=>f.message)});else e().logger.info(y,"Post-registration agent sync completed",{agentRecordId:d,tunnelUrl:l});await Rr(i,d),await Ga(d,l,s),await _i(d),gt=l,Pt(t,i),Ot(t)}catch(n){e().logger.error(y,`Auto-report failed: ${n instanceof Error?n.message:String(n)}`);try{Pt(t,i),Ot(t)}catch{}}}var x="lifecycle";class Rt{serviceRegistry;pluginManager;db;app;hostServices;appStopFn;state="running";transition=Promise.resolve();constructor(t,i,r,s,n,a){this.serviceRegistry=t;this.pluginManager=i;this.db=r;this.app=s;this.hostServices=n;this.appStopFn=a}getState(){return this.state}enqueueTransition(t,i){let r=this.transition.then(i,i);return this.transition=r.catch((s)=>{e().logger.warn(x,`Lifecycle transition '${t}' failed`,{error:String(s)})}),r}async stop(){return this.enqueueTransition("stop",async()=>{if(this.state==="stopped"){e().logger.warn(x,"Agent is already stopped");return}e().logger.info(x,"Stopping agent..."),this.state="stopped";let t=this.serviceRegistry.getProvider("session");if(t)try{let i=await t.list();for(let r of i)if(r.status==="active")try{await t.kill(r.id),e().logger.debug(x,`Killed session ${r.id}`)}catch(s){e().logger.warn(x,`Failed to kill session ${r.id}`,{error:String(s)})}}catch(i){e().logger.warn(x,"Failed to list/stop sessions",{error:String(i)})}try{await this.pluginManager.dispatchServerStop()}catch(i){e().logger.warn(x,"Error during plugin stop dispatch",{error:String(i)})}e().logger.info(x,"Agent stopped (tunnel + HTTP still alive)");try{await yi(this.db,"stopped")}catch(i){e().logger.warn(x,"Failed to report stopped state to backend",{error:String(i)})}})}async start(){return this.enqueueTransition("start",async()=>{if(this.state==="running"){e().logger.warn(x,"Agent is already running");return}e().logger.info(x,"Starting agent..."),this.state="running";try{await this.pluginManager.dispatchServerStart(this.app,this.hostServices),await this.pluginManager.dispatchServerReady(this.app,this.hostServices)}catch(t){e().logger.warn(x,"Error during plugin start dispatch",{error:String(t)})}e().logger.info(x,"Agent started");try{await yi(this.db,"running")}catch(t){e().logger.warn(x,"Failed to report running state to backend",{error:String(t)})}})}async softStop(){return this.enqueueTransition("softStop",async()=>{e().logger.info(x,"Soft-stopping agent (hot-reload)...");try{await this.pluginManager.dispatchServerStop({reason:"reload"})}catch(t){e().logger.warn(x,"Error during plugin soft-stop dispatch",{error:String(t)})}try{await this.appStopFn({reason:"reload"})}catch{}e().logger.info(x,"Agent soft-stopped \u2014 exiting for reload"),process.exit(0)})}async prepareForReset(){return this.enqueueTransition("prepareForReset",async()=>{e().logger.info(x,"Preparing agent for reset..."),this.state="stopped";try{await this.pluginManager.dispatchServerStop({reason:"shutdown"})}catch(t){e().logger.warn(x,"Error during reset stop dispatch",{error:String(t)})}})}async kill(){return this.enqueueTransition("kill",async()=>{e().logger.info(x,"Killing agent...");try{await Promise.race([yi(this.db,"killed"),new Promise((i,r)=>setTimeout(()=>r(Error("Timeout")),5000))])}catch(i){e().logger.warn(x,"Failed to report killed state to backend",{error:String(i)})}let t=this.serviceRegistry.getProvider("tunnel");if(t)try{let i=await t.list();for(let r of i)try{await t.stop(r.id)}catch{}}catch(i){e().logger.warn(x,"Failed to stop tunnels",{error:String(i)})}try{await this.appStopFn()}catch{}e().logger.info(x,"Agent killed \u2014 exiting process"),process.exit(0)})}}
177
+ `;async function rr(t){try{if(!T.isConfigured())return;let i=await t.getConfig("gateway-auth:agentRecordId");if(!i)return;let r=await T.workspaceQuery(Fd,{agentId:i});if(r.errors?.length)e().logger.debug(y,"Plugin-change notify returned errors",{errors:r.errors.map((s)=>s.message)})}catch(i){e().logger.debug(y,`Plugin-change notify failed: ${i instanceof Error?i.message:String(i)}`)}}var Nt=null,gt=null,Ct=!1;function Pt(t,i,r){if(Nt)return;let s=Number(process.env.VIBE_TUNNEL_SYNC_MS),n=Number.isFinite(s)&&s>0?s:r??60000;Nt=setInterval(async()=>{if(!T.isConfigured())return;try{let a=i.getProvider("tunnel");if(!a||!a.getActiveTunnelUrl)return;let o=Wt(await a.getActiveTunnelUrl()),c=await t.getConfig("gateway-auth:agentRecordId");if(!c)return;if(await _i(c),!o){if(!Ct)Ct=!(await T.workspaceQuery(Mt,{id:c,input:{tunnelStatus:"DISCONNECTED"}})).errors?.length,e().logger.warn(y,"No active tunnel URL \u2014 reported tunnel as DISCONNECTED",{reported:Ct});return}let l=Ct,d=T.getConfig()?.workspaceId||"",u;if(d)u=(await T.workspaceQuery(gi,{workspaceId:d})).data?.vibecontrolsAgents?.find((g)=>g.id===c)?.tunnelUrl??null;let f=o!==gt,h=u!==void 0&&u!==o;if(!f&&!h&&!l)return;e().logger.info(y,"Re-publishing tunnel URL",{reason:l?"tunnel-recovered":h?"backend-drift":"local-change",backend:u,local:o,lastReported:gt});let _=await T.workspaceQuery(Mt,{id:c,input:{tunnelUrl:o,tunnelStatus:"CONNECTED"}});if(!_.errors?.length)gt=o,Ct=!1,e().logger.info(y,"Tunnel URL synced to backend",{tunnelUrl:o});else e().logger.warn(y,"Tunnel URL sync returned errors",{errors:_.errors.map((p)=>p.message)})}catch(a){e().logger.debug(y,`Tunnel sync check failed: ${a instanceof Error?a.message:String(a)}`)}},n),Nt.unref?.()}function pi(){if(Nt)clearInterval(Nt),Nt=null;Ct=!1,gt=null}async function Rr(t,i){if(process.env.VIBE_BRIDGE_DISABLED==="1")return;try{let{bridgeClient:r}=await import("./bridge-client-9ax1cvj6.js"),{registerBridgeCommands:s,registerPluginBridgeService:n}=await import("./bridge-commands-hc1gvngq.js");s(r,t),n(t,r);let a=process.env.VIBECONTROLS_PROFILE||"default";r.start(i,a)}catch(r){e().logger.warn(y,`bridge-client start failed: ${r instanceof Error?r.message:String(r)}`)}}async function mi(t,i,r){if(!T.isConfigured()){e().logger.debug(y,"Gateway auth not configured \u2014 skipping auto-report");return}let s=await t.getConfig("gateway-auth:workspaceId");if(!s){e().logger.warn(y,"No workspaceId configured \u2014 skipping auto-report. "+"Configure via POST /api/agent/gateway-auth with workspaceId.");return}e().logger.info(y,"Starting auto-report to backend...");try{let n=process.env.VIBE_AGENT_NAME||ui.hostname(),a=ui.platform(),o=ui.arch(),c=Ae(),l=await qd(i),d=await Nr(t,n);if(d){e().logger.info(y,`Updating agent record ${d} via workspace gateway`);let f=await T.workspaceQuery(Mt,{id:d,input:{tunnelUrl:l||null,tunnelStatus:l?"CONNECTED":"DISCONNECTED",agentApiKey:r}});if(f.errors?.length){if(e().logger.warn(y,"Update mutation returned errors",{errors:f.errors.map((_)=>_.message)}),await Ud(s,d)){e().logger.warn(y,"Agent record still exists \u2014 treating update failure as transient; will retry on next sync (NOT registering a duplicate)",{agentRecordId:d}),await Rr(i,d),await Ha(s,{hostname:n,platform:a,arch:o,tunnelUrl:l,apiKey:r}),await _i(d),gt=l,Pt(t,i),Ot(t);return}e().logger.info(y,"Cached agent record no longer exists \u2014 clearing cache and registering fresh",{agentRecordId:d}),await t.setConfig("gateway-auth:agentRecordId",""),d=null}else{e().logger.info(y,"Agent record updated successfully",{agentRecordId:d,tunnelUrl:l}),await Rr(i,d),await Ga(d,l,s),await Ha(s,{hostname:n,platform:a,arch:o,tunnelUrl:l,apiKey:r}),await _i(d),gt=l,Pt(t,i),Ot(t);return}}e().logger.info(y,`Registering installed agent via workspace gateway (hostname: ${n})`);for(let f=1;f<=et&&!d;f++){if(f>1){let g=await Nr(t,n);if(g){d=g,e().logger.info(y,"Adopted an agent record discovered after a retry (not registering a duplicate)",{agentRecordId:d});break}}let h=await T.workspaceQuery(Wa,{workspaceId:s,input:{name:n,hostname:n,platform:a,architecture:o,tunnelUrl:l||null,agentApiKey:r}}),_=h.errors?.length?void 0:h.data?.registerInstalledAgent?.id;if(_){await t.setConfig("gateway-auth:agentRecordId",_),d=_,e().logger.info(y,"Agent registered successfully",{agentRecordId:_,name:h.data?.registerInstalledAgent?.name,tunnelUrl:l,version:c,attempt:f});break}let p=h.errors?.length?h.errors.map((g)=>g.message):["registerInstalledAgent returned no id"];if(f<et){let g=Math.min(30000,Cr*2**(f-1));e().logger.warn(y,`Register installed agent failed (attempt ${f}/${et}) \u2014 retrying in ${Math.round(g/1000)}s`,{errors:p}),await new Promise((m)=>setTimeout(m,g));continue}e().logger.error(y,"Register installed agent failed after retries \u2014 agent is running but NOT registered with the workspace",{errors:p}),e().recordDegradedReason("agent-registration",`registerInstalledAgent failed after ${et} attempts: ${p.join("; ")}`)}if(!d){Pt(t,i),Ot(t);return}let u=await T.workspaceQuery(Mt,{id:d,input:{tunnelUrl:l||null,tunnelStatus:l?"CONNECTED":"DISCONNECTED"}});if(u.errors?.length)e().logger.warn(y,"Post-registration agent update returned errors",{errors:u.errors.map((f)=>f.message)});else e().logger.info(y,"Post-registration agent sync completed",{agentRecordId:d,tunnelUrl:l});await Rr(i,d),await Ga(d,l,s),await _i(d),gt=l,Pt(t,i),Ot(t)}catch(n){e().logger.error(y,`Auto-report failed: ${n instanceof Error?n.message:String(n)}`);try{Pt(t,i),Ot(t)}catch{}}}var x="lifecycle";class Rt{serviceRegistry;pluginManager;db;app;hostServices;appStopFn;state="running";transition=Promise.resolve();constructor(t,i,r,s,n,a){this.serviceRegistry=t;this.pluginManager=i;this.db=r;this.app=s;this.hostServices=n;this.appStopFn=a}getState(){return this.state}enqueueTransition(t,i){let r=this.transition.then(i,i);return this.transition=r.catch((s)=>{e().logger.warn(x,`Lifecycle transition '${t}' failed`,{error:String(s)})}),r}async stop(){return this.enqueueTransition("stop",async()=>{if(this.state==="stopped"){e().logger.warn(x,"Agent is already stopped");return}e().logger.info(x,"Stopping agent..."),this.state="stopped";let t=this.serviceRegistry.getProvider("session");if(t)try{let i=await t.list();for(let r of i)if(r.status==="active")try{await t.kill(r.id),e().logger.debug(x,`Killed session ${r.id}`)}catch(s){e().logger.warn(x,`Failed to kill session ${r.id}`,{error:String(s)})}}catch(i){e().logger.warn(x,"Failed to list/stop sessions",{error:String(i)})}try{await this.pluginManager.dispatchServerStop()}catch(i){e().logger.warn(x,"Error during plugin stop dispatch",{error:String(i)})}e().logger.info(x,"Agent stopped (tunnel + HTTP still alive)");try{await yi(this.db,"stopped")}catch(i){e().logger.warn(x,"Failed to report stopped state to backend",{error:String(i)})}})}async start(){return this.enqueueTransition("start",async()=>{if(this.state==="running"){e().logger.warn(x,"Agent is already running");return}e().logger.info(x,"Starting agent..."),this.state="running";try{await this.pluginManager.dispatchServerStart(this.app,this.hostServices),await this.pluginManager.dispatchServerReady(this.app,this.hostServices)}catch(t){e().logger.warn(x,"Error during plugin start dispatch",{error:String(t)})}e().logger.info(x,"Agent started");try{await yi(this.db,"running")}catch(t){e().logger.warn(x,"Failed to report running state to backend",{error:String(t)})}})}async softStop(){return this.enqueueTransition("softStop",async()=>{e().logger.info(x,"Soft-stopping agent (hot-reload)...");try{await this.pluginManager.dispatchServerStop({reason:"reload"})}catch(t){e().logger.warn(x,"Error during plugin soft-stop dispatch",{error:String(t)})}try{await this.appStopFn({reason:"reload"})}catch{}e().logger.info(x,"Agent soft-stopped \u2014 exiting for reload"),process.exit(0)})}async prepareForReset(){return this.enqueueTransition("prepareForReset",async()=>{e().logger.info(x,"Preparing agent for reset..."),this.state="stopped";try{await this.pluginManager.dispatchServerStop({reason:"shutdown"})}catch(t){e().logger.warn(x,"Error during reset stop dispatch",{error:String(t)})}})}async kill(){return this.enqueueTransition("kill",async()=>{e().logger.info(x,"Killing agent...");try{await Promise.race([yi(this.db,"killed"),new Promise((i,r)=>setTimeout(()=>r(Error("Timeout")),5000))])}catch(i){e().logger.warn(x,"Failed to report killed state to backend",{error:String(i)})}let t=this.serviceRegistry.getProvider("tunnel");if(t)try{let i=await t.list();for(let r of i)try{await t.stop(r.id)}catch{}}catch(i){e().logger.warn(x,"Failed to stop tunnels",{error:String(i)})}try{await this.appStopFn()}catch{}e().logger.info(x,"Agent killed \u2014 exiting process"),process.exit(0)})}}
178
178
  export{er,tr,Rt,hi,fi,rr,pi,mi};