@vibecontrols/agent 2026.1124.1 → 2026.1125.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{app-k7z7tjem.js → app-xc9c1d71.js} +1 -1
- package/dist/cli.js +1 -1
- package/dist/{index-4q8y6k1e.js → index-4rasb3ph.js} +3 -3
- package/dist/{index-3cbesatx.js → index-5ccmrpb5.js} +1 -1
- package/dist/{index-9bj65n3s.js → index-7s7ee1y9.js} +1 -1
- package/dist/{index-06bmw4xf.js → index-er5k6qtr.js} +1 -1
- package/dist/{index-wr888ydc.js → index-fqz9n560.js} +1 -1
- package/dist/{index-p0bbp16g.js → index-thm1bzpj.js} +1 -1
- package/dist/{index-3b5xejjs.js → index-tts92sdm.js} +3 -3
- package/dist/{index-aav1drxa.js → index-x83tcr8f.js} +23 -23
- package/dist/{index-m942hydk.js → index-zcmhy3jv.js} +2 -2
- package/dist/index.js +2 -2
- package/dist/{plugin-system-kvg955t3.js → plugin-system-byzwda4c.js} +1 -1
- package/dist/{register-core-31wm1d8m.js → register-core-ws2axmcf.js} +1 -1
- package/dist/{secondary-profile-attach-95kmnrhf.js → secondary-profile-attach-em1tq7vq.js} +1 -1
- package/dist/{tunnel-bootstrap-rym0b0x5.js → tunnel-bootstrap-tjwz90pb.js} +1 -1
- package/package.json +1 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{z,ii,Vt,It,T,O,C,N,e,it}from"./index-0qjbnyg4.js";import{M,X}from"./index-kwhx023z.js";import{_e,W}from"./index-3b5xejjs.js";import{K}from"./index-mmx2kp76.js";import{pt}from"./index-qfxwk38p.js";import{Te,Ee,ke}from"./index-06bmw4xf.js";import{b}from"./index-w4jqdhc2.js";import{existsSync as Wa,readFileSync as Ja}from"fs";import{dirname as Ei,join as Ya}from"path";import{fileURLToPath as Qa}from"url";import{closeSync as Za,existsSync as eo,mkdirSync as to,openSync as io,readFileSync as ro,unlinkSync as Nr,writeFileSync as so}from"fs";import{join as no}from"path";import ao from"crypto";import rt from"path";import G from"fs";import xi from"zlib";import oo from"http";import{closeSync as lo,existsSync as co,mkdirSync as uo,openSync as ho,readFileSync as fo,unlinkSync as $r,writeFileSync as _o}from"fs";import{join as po}from"path";import go from"crypto";import st from"path";import H from"fs";import Si from"zlib";import mo from"http";import{closeSync as yo,existsSync as wo,mkdirSync as Ao,openSync as vo,readFileSync as Eo,unlinkSync as kr,writeFileSync as xo}from"fs";import{join as So}from"path";import Io from"crypto";import nt from"path";import J from"fs";import Ii from"zlib";import bo from"http";import{closeSync as To,existsSync as Oo,mkdirSync as Ro,openSync as Co,readFileSync as No,unlinkSync as Dr,writeFileSync as $o}from"fs";import{join as ko}from"path";import Do from"crypto";import at from"path";import Y from"fs";import bi from"zlib";import Lo from"http";function Po(){let t=Date.now().toString(16),i;try{i=ao.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 Lr(t,i){let r=t instanceof Error?t.message:t;if(i==="error")console.error(r);else console.log(r)}var Pr=new Set(["__proto__","constructor","prototype"]);function ni(t,i){if(!i.includes(".")){if(Pr.has(i))return;return t[i]}let r=t;for(let s of i.split(".")){if(Pr.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 Re extends Je{}class Ve extends Je{}class Se extends Je{}class ut extends Je{}function Li(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(!Li(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(!Li(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=ni(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(!Li(n,s))return!1}else if(n!==s)return!1}return!0}function Mo(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 Pi=new Set(["string","number","boolean","object","array","date","any"]);function zi(t){if(Array.isArray(t))return"array";if(t instanceof Date)return"date";return typeof t}function Ds(t){let i=new Map,r=[];for(let[s,n]of Object.entries(t)){let a;if(typeof n==="string"){if(!Pi.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(!Pi.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 Mr(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=zi(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 jr(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(zi(n)!==a.type)continue}if(a.enum&&!a.enum.includes(n))continue;r[s]=n}return r}function jo(t){let i={};for(let[r,s]of Object.entries(t)){if(r.startsWith("_"))continue;let n=zi(s);i[r]=Pi.has(n)?n:"any"}return i}function qo(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 Uo(t){return new Date(Date.now()+qo(t))}function Fo(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 qr(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 Ko(t){return t.length}function zo(t,i){let r=0;for(let s of t){let n=ni(s,i);if(typeof n==="number"&&!isNaN(n))r+=n}return r}function Bo(t,i){let r=0,s=0;for(let n of t){let a=ni(n,i);if(typeof a==="number"&&!isNaN(a))r+=a,s++}return s===0?null:r/s}function Xo(t,i){let r=Object.create(null);for(let s of t){let n=String(ni(s,i)??"__null__");if(!r[n])r[n]=[];r[n].push(s)}return r}class Ls{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 Re("ERR_SKALEX_TX_ABORTED",`Transaction ${f} was aborted. No further mutations allowed.`);if(h!==null&&d._abortedIds.has(h))throw new Re("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 Vo(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 Ps=new Set(["__proto__","constructor","prototype"]);function Ms(t){if(typeof t!=="object"||t===null||Array.isArray(t))return t;let i={};for(let r of Object.keys(t)){if(Ps.has(r))continue;i[r]=Ms(t[r])}return i}class js{constructor(t,i){this.name=t.collectionName,this.database=i,this._ctx=i._buildCollectionContext(),this._store=t,this._pipeline=new Ls(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(Ps.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]=Ms(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=Mr(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=jr(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({...Vo(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(),Ko(this._findAllRaw(t))}async sum(t,i={}){return await this._ctx.ensureConnected(),zo(this._findAllRaw(i),t)}async avg(t,i={}){return await this._ctx.ensureConnected(),Bo(this._findAllRaw(i),t)}async groupBy(t,i={}){return await this._ctx.ensureConnected(),Xo(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=Mo(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 _=qr(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=qr(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,ii,Vt,It,T,O,C,N,e,it}from"./index-0qjbnyg4.js";import{M,X}from"./index-kwhx023z.js";import{_e,W}from"./index-tts92sdm.js";import{K}from"./index-mmx2kp76.js";import{pt}from"./index-qfxwk38p.js";import{Te,Ee,ke}from"./index-er5k6qtr.js";import{b}from"./index-w4jqdhc2.js";import{existsSync as Wa,readFileSync as Ja}from"fs";import{dirname as Ei,join as Ya}from"path";import{fileURLToPath as Qa}from"url";import{closeSync as Za,existsSync as eo,mkdirSync as to,openSync as io,readFileSync as ro,unlinkSync as Nr,writeFileSync as so}from"fs";import{join as no}from"path";import ao from"crypto";import rt from"path";import G from"fs";import xi from"zlib";import oo from"http";import{closeSync as lo,existsSync as co,mkdirSync as uo,openSync as ho,readFileSync as fo,unlinkSync as $r,writeFileSync as _o}from"fs";import{join as po}from"path";import go from"crypto";import st from"path";import H from"fs";import Si from"zlib";import mo from"http";import{closeSync as yo,existsSync as wo,mkdirSync as Ao,openSync as vo,readFileSync as Eo,unlinkSync as kr,writeFileSync as xo}from"fs";import{join as So}from"path";import Io from"crypto";import nt from"path";import J from"fs";import Ii from"zlib";import bo from"http";import{closeSync as To,existsSync as Oo,mkdirSync as Ro,openSync as Co,readFileSync as No,unlinkSync as Dr,writeFileSync as $o}from"fs";import{join as ko}from"path";import Do from"crypto";import at from"path";import Y from"fs";import bi from"zlib";import Lo from"http";function Po(){let t=Date.now().toString(16),i;try{i=ao.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 Lr(t,i){let r=t instanceof Error?t.message:t;if(i==="error")console.error(r);else console.log(r)}var Pr=new Set(["__proto__","constructor","prototype"]);function ni(t,i){if(!i.includes(".")){if(Pr.has(i))return;return t[i]}let r=t;for(let s of i.split(".")){if(Pr.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 Re extends Je{}class Ve extends Je{}class Se extends Je{}class ut extends Je{}function Li(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(!Li(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(!Li(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=ni(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(!Li(n,s))return!1}else if(n!==s)return!1}return!0}function Mo(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 Pi=new Set(["string","number","boolean","object","array","date","any"]);function zi(t){if(Array.isArray(t))return"array";if(t instanceof Date)return"date";return typeof t}function Ds(t){let i=new Map,r=[];for(let[s,n]of Object.entries(t)){let a;if(typeof n==="string"){if(!Pi.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(!Pi.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 Mr(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=zi(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 jr(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(zi(n)!==a.type)continue}if(a.enum&&!a.enum.includes(n))continue;r[s]=n}return r}function jo(t){let i={};for(let[r,s]of Object.entries(t)){if(r.startsWith("_"))continue;let n=zi(s);i[r]=Pi.has(n)?n:"any"}return i}function qo(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 Uo(t){return new Date(Date.now()+qo(t))}function Fo(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 qr(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 Ko(t){return t.length}function zo(t,i){let r=0;for(let s of t){let n=ni(s,i);if(typeof n==="number"&&!isNaN(n))r+=n}return r}function Bo(t,i){let r=0,s=0;for(let n of t){let a=ni(n,i);if(typeof a==="number"&&!isNaN(a))r+=a,s++}return s===0?null:r/s}function Xo(t,i){let r=Object.create(null);for(let s of t){let n=String(ni(s,i)??"__null__");if(!r[n])r[n]=[];r[n].push(s)}return r}class Ls{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 Re("ERR_SKALEX_TX_ABORTED",`Transaction ${f} was aborted. No further mutations allowed.`);if(h!==null&&d._abortedIds.has(h))throw new Re("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 Vo(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 Ps=new Set(["__proto__","constructor","prototype"]);function Ms(t){if(typeof t!=="object"||t===null||Array.isArray(t))return t;let i={};for(let r of Object.keys(t)){if(Ps.has(r))continue;i[r]=Ms(t[r])}return i}class js{constructor(t,i){this.name=t.collectionName,this.database=i,this._ctx=i._buildCollectionContext(),this._store=t,this._pipeline=new Ls(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(Ps.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]=Ms(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=Mr(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=jr(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({...Vo(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(),Ko(this._findAllRaw(t))}async sum(t,i={}){return await this._ctx.ensureConnected(),zo(this._findAllRaw(i),t)}async avg(t,i={}){return await this._ctx.ensureConnected(),Bo(this._findAllRaw(i),t)}async groupBy(t,i={}){return await this._ctx.ensureConnected(),Xo(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=Mo(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 _=qr(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=qr(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 Se("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=Mr(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 jr(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??Po)(),createdAt:new Date,updatedAt:new Date},n=i??this._defaultTtl;if(n)s._expiresAt=Uo(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 Bi{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 qs extends Bi{constructor({dir:t,format:i="gz"}){super();this.dir=rt.resolve(t),this.format=i,this._ensureDir(this.dir)}_ensureDir(t){if(!G.existsSync(t))G.mkdirSync(t,{recursive:!0})}_filePath(t){return rt.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=xi.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=rt.join(this.dir,`${t}_${globalThis.crypto.randomUUID()}.tmp.${this.format}`);if(this.format==="gz"){let n=xi.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=rt.join(this.dir,`${r}_${globalThis.crypto.randomUUID()}.tmp.${this.format}`);if(this.format==="gz"){let o=xi.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 rt.join(...t)}ensureDir(t){this._ensureDir(t)}async writeRaw(t,i){this._ensureDir(rt.dirname(t)),await G.promises.writeFile(t,i,"utf8")}async readRaw(t){return G.promises.readFile(rt.resolve(t),"utf8")}}class Us{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 Ur={[Symbol.iterator](){return{next(){return{done:!0}}}},size:0};function Fr(t){return{[Symbol.iterator](){return t[Symbol.iterator]()},get size(){return t.size}}}function Ti(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 ei{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=Ti(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?Fr(s):Ur}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=Ti(r.fields.map((o)=>t[o])),a=r.map.get(n);return a?Fr(a):Ur}}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=Ti(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 Fs{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 Go=0;class Ks{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:++Go,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 Re("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 Re("ERR_SKALEX_TX_STALE_PROXY",`Transaction ${o.id} has ended. This proxy is no longer usable.`);if(h==="collections")throw new Re("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 Re("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 Re("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 zs{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=Ds(i);let _=f.uniqueFields;if(r.length||_.length)h=new ei(r,_)}else if(r.length)h=new ei(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 jo(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 Xi{async embed(t){throw Error("EmbeddingAdapter.embed() not implemented")}}var we=(t)=>globalThis.process?.env?.[t]??globalThis.Deno?.env?.get(t);class Bs extends Xi{constructor({apiKey:t=we("OPENAI_API_KEY"),model:i=we("OPENAI_EMBED_MODEL")??"text-embedding-3-small",baseUrl:r=we("OPENAI_EMBED_BASE_URL")??"https://api.openai.com/v1/embeddings",dimensions:s=we("OPENAI_EMBED_DIMENSIONS")!=null?Number(we("OPENAI_EMBED_DIMENSIONS")):void 0,organization:n=we("OPENAI_ORGANIZATION")??void 0,timeout:a=we("OPENAI_EMBED_TIMEOUT")!=null?Number(we("OPENAI_EMBED_TIMEOUT")):void 0,retries:o=Number(we("OPENAI_EMBED_RETRIES")??0),retryDelay:c=Number(we("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 Xs extends Xi{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 ai{async generate(t,i){throw Error("LLMAdapter.generate() not implemented")}async summarize(t){throw Error("LLMAdapter.summarize() not implemented")}}var Vi=`You are a database query assistant. Convert the user's natural language request into a JSON filter object for a document database.
|
|
5
5
|
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{rt,Ct,$i,Fe,Yt,O,I,C}from"./index-0qjbnyg4.js";import{_e}from"./index-
|
|
2
|
+
import{rt,Ct,$i,Fe,Yt,O,I,C}from"./index-0qjbnyg4.js";import{_e}from"./index-tts92sdm.js";import{b}from"./index-w4jqdhc2.js";import{existsSync as f,readdirSync as R,readFileSync as h,writeFileSync as m,mkdirSync as y,openSync as P,closeSync as w,unlinkSync as v}from"fs";import{join as l}from"path";import{tmpdir as k}from"os";import{spawn as A}from"child_process";class D{registryPath;logsDir;productDir;constructor(){let t=C();this.productDir=t,this.registryPath=l(t,"agents.json");let s=I();this.logsDir=l(s,"logs"),y(t,{recursive:!0}),y(s,{recursive:!0}),y(this.logsDir,{recursive:!0})}async startDaemon(t){return O(t.name),this.withInstanceLock(t.name,async()=>{let s=await this.findProcessByName(t.name);if(s&&s.status==="running"){let u=s.version,g=_e();if(u===g){console.log(`\u26A0\uFE0F Agent '${t.name}' is already running on port ${s.port}`);return}console.log(`\uD83D\uDD04 Agent '${t.name}' is running an older build (${u??"unknown"} \u2192 ${g}) \u2014 restarting to apply the update`);try{await this.stopInternal(t.name)}catch(d){console.log(`\u26A0\uFE0F Could not cleanly stop the stale daemon (${d instanceof Error?d.message:String(d)}); proceeding to start the new build`)}}let e=l(this.logsDir,`${t.name}.log`),n=P(e,"a"),i=l(import.meta.dir,"index.js"),r=l(import.meta.dir,"..","index.ts"),c=f(i)?i:r,a=A(process.execPath,["run",c],{detached:!0,windowsHide:!0,stdio:["ignore",n,n],env:{...process.env,VIBECONTROLS_PROFILE:t.profile||"default",PORT:t.port.toString(),DB_PATH:t.dbPath,NODE_ENV:"production",AGENT_LOG_FILE:e}});a.on("error",()=>{}),w(n),await new Promise((u)=>setTimeout(u,2000));let o=a.pid;if(!(o!==void 0&&await this.isProcessRunning(o))){let u="";try{u=h(e,"utf8").split(/\r?\n/).filter((S)=>S.trim()).slice(-25).join(`
|
|
3
3
|
`)}catch{}let g=`See ${e}`;throw Error(u?`Failed to start agent '${t.name}'. ${g}
|
|
4
4
|
--- last log lines ---
|
|
5
5
|
${u}`:`Failed to start agent '${t.name}'. ${g}`)}a.unref(),await this.saveProcessInfo(t.name,o,t),console.log(`\uD83D\uDE80 Agent '${t.name}' started (PID: ${o}, Port: ${t.port})`)})}async stop(t){return O(t),this.withInstanceLock(t,()=>this.stopInternal(t))}async stopInternal(t){let s=await this.findProcessByName(t);if(!s||s.status!=="running"){console.log(`\u26A0\uFE0F Agent '${t}' is not running`);return}try{if(process.kill(s.pid,"SIGTERM"),await new Promise((n)=>setTimeout(n,3000)),await this.isProcessRunning(s.pid))process.kill(s.pid,"SIGKILL");await this.updateProcessStatus(t,"stopped"),console.log(`\u2705 Agent '${t}' stopped (tunnel + API key preserved)`)}catch(e){throw Error(`Failed to stop agent '${t}': ${e}`,{cause:e})}}async restart(t,s){O(t),O(s.name);let e=await this.findProcessByName(t);if(e&&e.status==="running")await this.stop(t);await this.startDaemon(s),console.log(`\uD83D\uDD04 Agent '${t}' restarted (tunnel + API key preserved)`)}async kill(t){return O(t),this.withInstanceLock(t,async()=>{let s=await this.findProcessByName(t);if(!s||s.status!=="running"){console.log(`\u26A0\uFE0F Agent '${t}' is not running`);return}let e=l(k(),`.boff-vibecontrols-kill-${s.pid}`);try{await Bun.write(e,"kill")}catch{}try{process.kill(s.pid,"SIGTERM"),await new Promise((i)=>setTimeout(i,5000))}catch{}if(await this.isProcessRunning(s.pid))await this.killProcessTree(s.pid);await this.updateProcessStatus(t,"stopped"),console.log(`\uD83D\uDC80 Agent '${t}' killed (tunnel + state torn down)`)})}async getStatus(t){return O(t),this.findProcessByName(t)}discoverRuntimeInstances(){let t=l(this.productDir,"agents");if(!f(t))return[];let s;try{s=R(t,{withFileTypes:!0}).filter((n)=>n.isDirectory()).map((n)=>n.name)}catch{return[]}let e=[];for(let n of s){let i=l(t,n,"runtime.json");if(!f(i))continue;try{let r=JSON.parse(h(i,"utf8"));if(typeof r.pid!=="number"||typeof r.port!=="number")continue;let c=r.profile||n;try{O(c)}catch{continue}e.push({name:c,pid:r.pid,port:r.port,config:{name:c,port:r.port,daemon:!0,dbPath:l(t,n,"agent-db"),host:r.host,profile:c},startTime:r.startedAt??new Date(0).toISOString(),status:"unknown",version:r.version})}catch{}}return e}async getStatusAll(){let t=this.loadRegistry(),s=new Set(t.map((r)=>r.name)),e=[...t];for(let r of this.discoverRuntimeInstances())if(!s.has(r.name))e.push(r);let n=[];for(let r of e){let c=await this.isManagedProcessRunning(r);if(!s.has(r.name)&&!c)continue;n.push({...r,status:c?"running":"stopped"})}let i=n.filter((r)=>r.status==="running"&&!s.has(r.name));if(i.length>0)try{await rt(()=>{let r=this.loadRegistry(),c=new Set(r.map((o)=>o.name)),a=i.filter((o)=>!c.has(o.name));if(a.length>0)this.saveRegistry([...r,...a.map((o)=>({...o,status:"running"}))])})}catch{}return n}async listInstances(){return this.getStatusAll()}getDefaultProfile(){return Fe()}setDefaultProfile(t){Yt(O(t))}async showLogs(t,s){O(t);let e=l(this.logsDir,`${t}.log`);if(!f(e)){console.log(`No logs found for agent '${t}'`);return}if(s.follow)try{let n=async(o)=>{let p=await Bun.file(e).text(),g=p.split(`
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{e}from"./index-0qjbnyg4.js";import{E}from"./index-w0m3jm0s.js";import{Mr}from"./index-
|
|
2
|
+
import{e}from"./index-0qjbnyg4.js";import{E}from"./index-w0m3jm0s.js";import{Mr}from"./index-tts92sdm.js";import{Ke,Lt,de,mt,Xe,ze,K}from"./index-mmx2kp76.js";var T=["tunnel","session","ai","plan","gitops","security","desk"];class Te{providers=new Map;providerOrder=new Map;defaults=new Map;services=new Map;db;constructor(t){this.db=t}getDb(){return this.db}setProviderDefault(t,r){this.defaults.set(t,r)}clearProviderDefault(t,r){if(!r||this.defaults.get(t)===r)this.defaults.delete(t)}async hydrateDefaultsFromDb(){if(!this.db)return;for(let t of T)try{let r=await this.db.getConfig(`provider:default:${t}`);if(r)this.defaults.set(t,r)}catch{}}registerProvider(t,r,i){if(!this.providers.has(t))this.providers.set(t,new Map),this.providerOrder.set(t,[]);let n=this.providers.get(t),o=this.providerOrder.get(t);if(n.has(i))e().logger.info("service-registry",`Updating ${t} provider from plugin '${i}'`);else e().logger.info("service-registry",`Registered ${t} provider from plugin '${i}'`);if(n.set(i,{provider:r,pluginName:i,registeredAt:new Date}),!o.includes(i))o.push(i)}getProvider(t){let r=this.providers.get(t);if(!r||r.size===0)return;let i=this.defaults.get(t);if(i&&r.has(i))return r.get(i).provider;let n=this.providerOrder.get(t);if(n&&n.length>0){let o=n[0];return r.get(o)?.provider}return}getProviderByName(t,r){let i=this.providers.get(t);if(!i)return;return i.get(r)?.provider}hasProvider(t){let r=this.providers.get(t);return!!r&&r.size>0}unregisterProvider(t,r){let i=this.providers.get(t);if(!i)return!1;let n=i.delete(r);if(n){let o=this.providerOrder.get(t);if(o){let s=o.indexOf(r);if(s!==-1)o.splice(s,1)}this.clearProviderDefault(t,r),e().logger.info("service-registry",`Unregistered ${t} provider from plugin '${r}'`)}return n}unregisterPlugin(t){for(let r of T)this.unregisterProvider(r,t);this.unregisterServices(t)}listProvidersForType(t){let r=this.providers.get(t);if(!r)return[];let i=this.defaults.get(t);if(!i||!r.has(i)){let n=this.providerOrder.get(t);i=n&&n.length>0?n[0]:void 0}return Array.from(r.keys()).map((n)=>({pluginName:n,isDefault:n===i}))}registerService(t,r,i){let n=`${t}:${r}`;this.services.set(n,{service:i,pluginName:t}),e().logger.debug("service-registry",`Registered service '${n}'`)}getService(t,r){let i=`${t}:${r}`;return this.services.get(i)?.service}unregisterServices(t){let r=[];for(let[i,n]of this.services)if(n.pluginName===t)r.push(i);for(let i of r)this.services.delete(i);if(r.length>0)e().logger.info("service-registry",`Unregistered ${r.length} services from ${t}`)}listProviders(){let t=[];for(let[r,i]of this.providers)for(let[n,o]of i)t.push({type:r,name:n,pluginName:o.pluginName});return t}listServices(){return Array.from(this.services.entries()).map(([t,r])=>({pluginName:r.pluginName,serviceName:t.split(":").slice(1).join(":")}))}clear(){this.providers.clear(),this.providerOrder.clear(),this.defaults.clear(),this.services.clear()}}class Ee{statusSections=[];doctorChecks=[];addStatusSection(t){this.statusSections.push(t)}addDoctorCheck(t){this.doctorChecks.push(t)}getStatusSections(){return this.statusSections}getDoctorChecks(){return this.doctorChecks}}var y=null;function Ti(t){y=t}function Pt(){if(!y)y=new Ee;return y}import{extname as N,relative as j,resolve as O}from"path";import{realpath as b}from"fs/promises";var B=["'self'","http://localhost:*","http://127.0.0.1:*","https://localhost:*","https://127.0.0.1:*","https://*.local.burdenoff.com","https://vibecontrols.com","https://*.vibecontrols.com","https://burdenoff.com","https://app.burdenoff.com","https://alphaapp.burdenoff.com"],R=!1;function f(){let t=process.env.VIBE_UI_FRAME_ANCESTORS?.trim(),r=t?t.split(/[\s,]+/).filter(Boolean):B;if(t&&!R&&(r.includes("*")||!r.includes("'self'")))R=!0,console.warn(`[ui-server] VIBE_UI_FRAME_ANCESTORS override does not include "'self'" or contains "*". This significantly weakens CSP frame-ancestors and is almost never intended. Override: ${t}`);return`frame-ancestors ${r.join(" ")}`}var M={".html":"text/html",".js":"application/javascript",".mjs":"application/javascript",".css":"text/css",".json":"application/json",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".map":"application/json",".wasm":"application/wasm"};function F(t){return M[N(t).toLowerCase()]||"application/octet-stream"}var k=`<script>
|
|
3
3
|
window.__VIBE_AUTH__={apiKey:null};
|
|
4
4
|
(function(){
|
|
5
5
|
var p=new URLSearchParams(window.location.search);
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Y,ye,Mt}from"./index-
|
|
2
|
+
import{Y,ye,Mt}from"./index-tts92sdm.js";import{Ht,It,T,R,I,ne,se,B,e}from"./index-0qjbnyg4.js";import{Z}from"./index-ywnfz6nm.js";import{D}from"./index-7s7ee1y9.js";import{b}from"./index-w4jqdhc2.js";import{Re}from"./index-byerrz46.js";import{existsSync as q,readFileSync as S,unlinkSync as ht,writeFileSync as U}from"fs";import{join as X}from"path";var Q=".consent.json";function He(t){try{let r=S(P(t),"utf8"),n=JSON.parse(r);if(Array.isArray(n.abilities)&&n.abilities.length>0)return new Set(n.abilities)}catch{}return null}function qt(t){try{let r=S(P(t),"utf8"),n=JSON.parse(r);if(Array.isArray(n.providers))return n.providers.filter((o)=>typeof o==="string")}catch{}return[]}function Ei(t){let r=new Set;for(let n of t.split(",").map((o)=>o.trim()).filter(Boolean)){let o=Mt(n);if(o)r.add(o)}return[...r]}function P(t){return X(t,Q)}function _i(t,r){let n=r??new Set(Y.filter((i)=>i.defaultSelected||i.mandatory).map((i)=>i.key)),o=t.skipPluginInstall?[]:ye(process.platform,n).filter((i)=>!t.skipPlugins.includes(i.packageName)&&!t.skipPlugins.includes(i.pluginName)).map((i)=>({packageName:i.packageName,pluginName:i.pluginName,reason:i.description}));return{tools:[],plugins:o}}async function er(){let t=new Set(Y.filter((n)=>n.defaultSelected||n.mandatory).map((n)=>n.key));for(let n of Y)if(n.mandatory)t.add(n.key);if(!(Boolean(process.stdin.isTTY)&&process.env.VIBE_AUTO_ACCEPT!=="1"))return t;try{let{interactiveCheckboxes:n}=await import("./interactive-vbz68zh5.js"),o=await n("Select the agent abilities to install",Y.map((i)=>({key:i.key,label:i.label,description:i.description,mandatory:i.mandatory})),t);if(o){for(let i of Y)if(i.mandatory)o.add(i.key);return o}return t}catch(n){process.stdout.write(`
|
|
3
3
|
[vibe] Falling back to plain prompt \u2014 ${n instanceof Error?n.message:String(n)}
|
|
4
4
|
|
|
5
5
|
`);let o=await ee("Select the agent abilities to install",Y.map((i)=>({key:i.key,label:i.label,description:i.description,mandatory:i.mandatory})),t);if(o){for(let i of Y)if(i.mandatory)o.add(i.key);return o}return t}}async function ee(t,r,n){let o=new Set(n);for(let s of r)if(s.mandatory)o.add(s.key);let i=()=>{process.stdout.write(`
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{r,E}from"./index-w0m3jm0s.js";import{Me,st}from"./index-652f9scs.js";import{T,R,si,I,ne,B,e}from"./index-0qjbnyg4.js";import{M}from"./index-kwhx023z.js";import"./index-5021rk8n.js";import{be,Nt,K,Mi,k,V}from"./index-mmx2kp76.js";import{i,d,s,A,l,o,g,n,c,F,v,Gr,Qe,G}from"./index-7f2k4g6q.js";import{U}from"./index-vtsd74g0.js";import{jr}from"./index-d59kp6zr.js";import{ci,ui,li}from"./index-
|
|
2
|
+
import{r,E}from"./index-w0m3jm0s.js";import{Me,st}from"./index-652f9scs.js";import{T,R,si,I,ne,B,e}from"./index-0qjbnyg4.js";import{M}from"./index-kwhx023z.js";import"./index-5021rk8n.js";import{be,Nt,K,Mi,k,V}from"./index-mmx2kp76.js";import{i,d,s,A,l,o,g,n,c,F,v,Gr,Qe,G}from"./index-7f2k4g6q.js";import{U}from"./index-vtsd74g0.js";import{jr}from"./index-d59kp6zr.js";import{ci,ui,li}from"./index-5ccmrpb5.js";import"./index-tts92sdm.js";import"./index-qfxwk38p.js";import{Ge,Be,Pe}from"./index-c4whjk5r.js";import{mi}from"./index-akk3rxnn.js";import{D}from"./index-7s7ee1y9.js";import{Pt}from"./index-er5k6qtr.js";import{L}from"./index-b3v08awy.js";import{ve}from"./index-4z1y39jt.js";import{_,y,u}from"./index-t5cfkz1e.js";import{f,Re,m,S,q}from"./index-byerrz46.js";function re(b){let{name:O,onInit:w,onShutdown:a,onNuke:p,telemetryEventName:t,skipPlatforms:h}=b;return{onServerStart:async(P,C)=>{if(h&&h.includes(process.platform)){process.stderr.write(`[${O}] skipping init on unsupported platform '${process.platform}'
|
|
3
3
|
`);return}if(w)await w(C);if(t)C.telemetry?.emit(t,{plugin:O})},onServerStop:async(P)=>{if(a)await a(P)},onNuke:async(P,C)=>{if(p)return p(P,C)}}}var ie=class{logger;source;constructor(b,O){this.logger=b,this.source=O}info(b,O){this.logger?.info?.(this.source,b,O)}warn(b,O){this.logger?.warn?.(this.source,b,O)}error(b,O){this.logger?.error?.(this.source,b,O)}debug(b,O){this.logger?.debug?.(this.source,b,O)}};import{existsSync as qe,rmSync as Je,statSync as We}from"fs";import{resolve as ze}from"path";function ae(b=I()){let O=[],w=ze(b),a=ne();if(!si(a,w))throw Error("Refusing to reset a path outside the agents directory");if(qe(w)&&We(w).isDirectory())Je(w,{recursive:!0,force:!0}),O.push(w);return{removed:O,agentDir:w}}var X="alias",ce=/^[a-zA-Z0-9_-]{1,64}$/,le=16384,ue=256,me=1024,Ye=new Set(["help","start","stop","restart","kill","list","status","setup","update","completion","autostart","export","import","diagnostics","nuke","doctor","log-level","gc","deploy","network","profile","peer-bootstrap","gateway-auth","info","key","system","url","health","notify","tunnel","session","git","config","log","plugin","ai","audit","alias","run"]);class H extends Error{code;constructor(b,O){super(O);this.code=b,this.name="AliasValidationError"}}class Q extends Error{constructor(b){super(`alias '${b}' already exists`);this.name="AliasConflictError"}}class W extends Error{constructor(b){super(`alias '${b}' not found`);this.name="AliasNotFoundError"}}function Xe(b){if(typeof b!=="string"||!ce.test(b))throw new H("invalid_name",`alias name must match ${ce} (got '${b}')`);if(Ye.has(b))throw new H("reserved_name",`alias name '${b}' is reserved`)}function ge(b){if(typeof b!=="string"||b.length===0)throw new H("invalid_command","alias command must be a non-empty string");if(b.length>le)throw new H("command_too_long",`alias command exceeds ${le} bytes`)}function pe(b){if(b===void 0)return;if(typeof b!=="string")throw new H("invalid_description","alias description must be a string");if(b.length>ue)throw new H("description_too_long",`alias description exceeds ${ue} chars`)}function fe(b){if(b===void 0||b===null||b==="")return;if(typeof b!=="string")throw new H("invalid_cwd","alias cwd must be a string");if(b.length>me)throw new H("cwd_too_long",`alias cwd exceeds ${me} chars`);if(b.includes("\x00"))throw new H("invalid_cwd","alias cwd must not contain NUL bytes")}function Ze(b){if(!b)return;try{return JSON.parse(b)}catch{return}}async function se(b){let O=await b.getAllPluginState(X),w=[];for(let a of O){let p=Ze(a.value);if(p)w.push(p)}return w.sort((a,p)=>a.name.localeCompare(p.name)),w}async function z(b,O){return(await se(b)).find((a)=>a.name===O)}function de(b){if(b===void 0||b===null)return null;let O=b.trim();return O===""?null:O}async function he(b,O){if(Xe(O.name),ge(O.command),pe(O.description),fe(O.cwd),await z(b,O.name))throw new Q(O.name);let a=new Date().toISOString(),p={id:crypto.randomUUID(),name:O.name,command:O.command,description:O.description,cwd:de(O.cwd),profile:R(),createdAt:a,updatedAt:a};return await b.setPluginState(X,p.id,JSON.stringify(p)),p}async function ye(b,O,w){let a=await z(b,O);if(!a)throw new W(O);if(w.command!==void 0)ge(w.command);if(w.description!==void 0)pe(w.description);if(w.cwd!==void 0)fe(w.cwd);let p={...a,command:w.command??a.command,description:w.description!==void 0?w.description:a.description,cwd:w.cwd!==void 0?de(w.cwd):a.cwd,updatedAt:new Date().toISOString()};return await b.setPluginState(X,p.id,JSON.stringify(p)),p}async function we(b,O){let w=await z(b,O);if(!w)throw new W(O);await b.deletePluginState(X,w.id)}function Z(){let b=B()??e();return{dir:b.dataDir,scope:b.name}}function Se(b){let{serviceRegistry:O,db:w}=b;return new E().get("/api-key",({request:a,set:p})=>{if(Ge(a))return p.status=403,{error:"Forbidden",message:"Browser requests are not permitted on /api/agent/api-key"};let t=k(Object.fromEntries(a.headers.entries()));if(!V(t))return p.status=401,{error:"Unauthorized",message:"Invalid or missing API key"};return{apiKey:K()}}).post("/reset-key",async({body:a,set:p})=>{let t=a.apiKey;if(!t||typeof t!=="string")return p.status=400,{error:"Missing required field: apiKey"};try{return await Mi(t),await e().keyVault.bindApiKey(t),e().logger.info("auth","Adopted backend-rotated agent API key via /reset-key"),{success:!0}}catch(h){return p.status=400,{error:"reset-key failed",message:h instanceof Error?h.message:String(h)}}},{body:r.Object({apiKey:r.String()})}).get("/audit",({query:a})=>{let p=a,t=p.limit?Math.min(5000,Math.max(1,Number.parseInt(p.limit,10)||100)):100,h=e().audit.listEvents({since:p.since,limit:t,event:p.event});return{events:h,count:h.length}},{query:r.Object({since:r.Optional(r.String()),limit:r.Optional(r.String()),event:r.Optional(r.String())})}).get("/setup/check",()=>{let a=Me();return{ready:a.filter((t)=>t.required).every((t)=>t.installed),dependencies:a}}).post("/setup/install",async({request:a,server:p,set:t})=>{let h=await Pe(a,"VIBECONTROLS_ALLOW_REMOTE_SETUP_INSTALL",p);if(h)return t.status=403,{error:"Forbidden",message:h};return await st()}).get("/url",async()=>{let a=O.getProvider("tunnel"),p=a&&a.getActiveTunnelUrl?await a.getActiveTunnelUrl():null,t=`http://localhost:${process.env.PORT||3005}`;return{url:p||t,tunnelUrl:p,localUrl:t,source:p?"tunnel":"local"}}).get("/lifecycle/state",()=>({state:O.getService("agent","lifecycle")?.getState()??"running"})).post("/lifecycle/stop",async({set:a})=>{let p=O.getService("agent","lifecycle");if(!p)return a.status=500,{error:"Lifecycle manager not initialized"};return await p.stop(),{state:"stopped"}}).post("/lifecycle/start",async({set:a})=>{let p=O.getService("agent","lifecycle");if(!p)return a.status=500,{error:"Lifecycle manager not initialized"};return await p.start(),{state:"running"}}).post("/lifecycle/kill",async({set:a})=>{let p=O.getService("agent","lifecycle");if(!p)return a.status=500,{error:"Lifecycle manager not initialized"};return setTimeout(()=>p.kill(),100),{state:"killing"}}).post("/log-level",async({body:a,request:p,server:t,set:h})=>{let P=await Pe(p,"VIBECONTROLS_ALLOW_REMOTE_LOG_LEVEL",t);if(P)return h.status=403,{error:"Forbidden",message:P};let C=String(a.level??"").toLowerCase();if(!["debug","info","warn","error"].includes(C))return h.status=400,{error:"Invalid level",message:"level must be debug | info | warn | error"};return e().logger.setLevel(C),e().logger.info("agent",`Log level set to ${C} via API`),{ok:!0,level:C}},{body:r.Object({level:r.String()})}).post("/reset",async({body:a,request:p,server:t,set:h})=>{if(!a.confirm)return h.status=400,{error:"Reset confirmation required",message:"Send { confirm: true } to reset local agent state."};let P=await Pe(p,"VIBECONTROLS_ALLOW_REMOTE_RESET",t);if(P)return h.status=403,{error:"Forbidden",message:P};let C=O.getService("agent","lifecycle");try{if(C)await C.prepareForReset()}catch(Y){e().logger.warn("agent","prepareForReset failed during reset \u2014 proceeding to wipe anyway",{error:String(Y)})}try{T.configure({globalGatewayUrl:"",workspaceGatewayUrl:void 0,clientId:"",clientSecret:"",workspaceId:void 0})}catch{}await w.close();let{removed:x,agentDir:N}=ae();e().logger.info("agent","Reset wiped local agent state",{agentDir:N,removed:x});let j=new Uint8Array(32);crypto.getRandomValues(j);let J=`vcak_${Buffer.from(j).toString("base64url")}`;return M({"static-api-key":J},Z()),e().setBootState("awaiting-config"),h.status=200,{success:!0,state:"awaiting-config",...Be(p,t)||process.env.VIBECONTROLS_RETURN_RESET_API_KEY==="1"?{newApiKey:J}:{},agentDir:N,removed:x}},{body:r.Object({confirm:r.Boolean()})}).post("/sessions/:sessionId/share",async({params:a,body:p,server:t,request:h,set:P})=>{if(!Be(h,t)&&process.env.VIBECONTROLS_ALLOW_REMOTE_SESSION_SHARE!=="1")return P.status=403,{error:"Forbidden",message:"Session-share mint must come from a local request unless VIBECONTROLS_ALLOW_REMOTE_SESSION_SHARE=1."};if(!be(a.sessionId))return P.status=400,{error:"BadRequest",message:"invalid sessionId"};let C=et(p?.expiresIn)??1800000,x=crypto.randomUUID(),N=new Uint8Array(32);crypto.getRandomValues(N);let j=`vcak_${Buffer.from(N).toString("base64url")}`,J=new Date(Date.now()+C).toISOString(),oe=[...(await import("./agent-config-v9d7gcz0.js")).readAgentConfig({dir:Z().dir}).apiKeys??[],{id:x,name:`session-share:${a.sessionId}:${p?.label??"viewer"}`,key:j,scopes:["read"],expiresAt:J,createdAt:new Date().toISOString()}];(await import("./agent-config-v9d7gcz0.js")).writeAgentConfig({apiKeys:oe},Z());let Y=O.getProvider("tunnel"),_e=(Y&&Y.getActiveTunnelUrl?await Y.getActiveTunnelUrl():null)??`http://localhost:${process.env.PORT||3005}`,je=Nt({pathPrefixes:[`/terminal/${a.sessionId}`],methods:["GET"]},Math.min(600,Math.floor(C/1000))),He=`${_e.replace(/\/$/,"")}/terminal/${encodeURIComponent(a.sessionId)}/#vt=${encodeURIComponent(je.token)}`;return e().logger.info("session-share","Minted share credential",{sessionId:a.sessionId,keyId:x,expiresAt:J}),{ok:!0,keyId:x,apiKey:j,joinUrl:He,sessionId:a.sessionId,expiresAt:J}},{params:r.Object({sessionId:r.String()}),body:r.Optional(r.Object({permissions:r.Optional(r.Array(r.String())),expiresIn:r.Optional(r.String()),label:r.Optional(r.String())}))}).get("/aliases",async()=>({aliases:await se(w)})).get("/aliases/:name",async({params:a,set:p})=>{let t=await z(w,a.name);if(!t)return p.status=404,{error:"Alias not found"};return t},{params:r.Object({name:r.String()})}).post("/aliases",async({body:a,set:p})=>{try{let t=await he(w,a);return p.status=201,t}catch(t){if(t instanceof Q)return p.status=409,{error:"Alias already exists",message:t.message};if(t instanceof H)return p.status=400,{error:t.code,message:t.message};throw t}},{body:r.Object({name:r.String(),command:r.String(),description:r.Optional(r.String()),cwd:r.Optional(r.Union([r.String(),r.Null()]))})}).put("/aliases/:name",async({params:a,body:p,set:t})=>{try{return await ye(w,a.name,p)}catch(h){if(h instanceof W)return t.status=404,{error:"Alias not found"};if(h instanceof H)return t.status=400,{error:h.code,message:h.message};throw h}},{params:r.Object({name:r.String()}),body:r.Object({command:r.Optional(r.String()),description:r.Optional(r.String()),cwd:r.Optional(r.Union([r.String(),r.Null()]))})}).delete("/aliases/:name",async({params:a,set:p})=>{try{return await we(w,a.name),p.status=204,null}catch(t){if(t instanceof W)return p.status=404,{error:"Alias not found"};throw t}},{params:r.Object({name:r.String()})}).post("/aliases/:name/execute",async({params:a,body:p,set:t})=>{let h=await z(w,a.name);if(!h)return t.status=404,{error:"Alias not found"};let P=p?.args??[],C=await mi(h,P);e().audit.emit("agent","alias.executed",{exit_code:C.exit_code});let x=ve("alias.executed",{exit_code:C.exit_code});if(!x.ok)e().logger.debug("alias",`telemetry validate failed: ${x.reason}`);if(C.timed_out)t.status=408;return{exit_code:C.exit_code,stdout:C.stdout,stderr:C.stderr,duration_ms:C.duration_ms,truncated:C.truncated,cwd:C.cwd}},{params:r.Object({name:r.String()}),body:r.Optional(r.Object({args:r.Optional(r.Array(r.String()))}))}).post("/sessions/share/:keyId/revoke",async({params:a,server:p,request:t,set:h})=>{if(!Be(t,p)&&process.env.VIBECONTROLS_ALLOW_REMOTE_SESSION_SHARE!=="1")return h.status=403,{error:"Forbidden"};let P=await import("./agent-config-v9d7gcz0.js"),C=Z(),x=P.readAgentConfig({dir:C.dir}),N=(x.apiKeys??[]).length,j=(x.apiKeys??[]).filter((J)=>J.id!==a.keyId);if(j.length===N)return h.status=404,{error:"No such share key"};return P.writeAgentConfig({apiKeys:j},C),{ok:!0,revoked:a.keyId}},{params:r.Object({keyId:r.String()})})}function et(b){if(!b)return null;let O=/^(\d+)([smhdw]?)$/.exec(b.trim());if(!O)return null;let w=Number(O[1]),a=O[2]||"m";return a==="s"?w*1000:a==="m"?w*60000:a==="h"?w*3600000:a==="d"?w*86400000:w*7*86400000}var tt="http://localhost:3005";function Ae(b){b.command("health").description("Check health of a VibeControls agent instance").option("-n, --name <name>","Agent instance name").option("--agent-url <url>","Agent URL",tt).option("--json","Emit JSON").option("--plain","Force plain text output").action(async function(O){try{let w={...b.opts(),...O};await y({mode:_(w),fetchData:async()=>{if(w.name){let t=await new D().checkHealth(w.name);return{mode:"named",agentUrl:f(w),name:w.name,healthy:t.healthy,details:t.details??{}}}let a=f(w);try{let p=await S(a,"/health");return{mode:"url",agentUrl:a,healthy:!0,details:p}}catch(p){return{mode:"url",agentUrl:a,healthy:!1,details:{status:"unhealthy",...p instanceof Error?{error:A(p)}:{}}}}},plain:(a)=>{if(g("Agent Health"),c(),a.mode==="named"){if(!a.healthy){s(`Agent instance ${i.bold(a.name??"")} is not responding.`);return}let p=a.details;if(n("Instance",a.name??""),n("Status",G(p.status??"healthy")),p.uptime!==void 0)n("Uptime",`${p.uptime}s`);if(p.checks){c(),o(`${d.info} Health checks:`);for(let[t,h]of Object.entries(p.checks)){let P=h.status==="healthy"?d.success:d.error;n(` ${P} ${t}`,G(h.status))}}}else{if(n("URL",a.agentUrl),n("Status",G(a.details.status??"unhealthy")),a.details.version)n("Version",a.details.version);if(a.details.uptime!==void 0)n("Uptime",`${a.details.uptime}s`);if(a.details.timestamp)n("Timestamp",a.details.timestamp);if(a.details.checks){c(),o(`${d.info} Health checks:`);for(let[p,t]of Object.entries(a.details.checks)){let h=t.status==="healthy"?d.success:d.error;n(` ${h} ${p}`,G(t.status))}}}if(c(),a.healthy)l(`${d.success} Agent is healthy.`)},interactive:async(a)=>{let p=[];if(a.mode==="named")p.push(`Instance: ${a.name??""}`);else p.push(`URL: ${a.agentUrl}`);if(p.push(`Status: ${G(a.details.status??(a.healthy?"healthy":"unhealthy"))}`),a.details.version)p.push(`Version: ${a.details.version}`);if(a.details.uptime!==void 0)p.push(`Uptime: ${a.details.uptime}s`);if(a.details.timestamp)p.push(`Time: ${a.details.timestamp}`);if(a.details.checks){p.push(""),p.push("Checks:");for(let[t,h]of Object.entries(a.details.checks))p.push(` ${t}: ${h.status}`)}await U({title:"Agent Health",body:p.join(`
|
|
4
4
|
`),footer:"press q to exit"})},json:(a)=>({mode:a.mode,agentUrl:a.agentUrl,name:a.name??null,healthy:a.healthy,details:a.details})})}catch(w){s(`Health check failed: ${A(w)}`)}})}import{platform as nt,arch as rt,release as it,hostname as ot,cpus as at,totalmem as ct}from"os";var lt="http://localhost:3005";function $e(b){b.command("info").description("Show local and remote VibeControls agent information").option("--agent-url <url>","Agent URL",lt).option("--json","Emit JSON").option("--plain","Force plain text output").action(async function(O){try{let w={...b.opts(),...O},a=f(w),p=encodeURIComponent(m(w));await y({mode:_(w),fetchData:async()=>{let t={hostname:ot(),platform:nt(),arch:rt(),release:it(),cpus:at().length,totalMemory:ct(),nodeVersion:process.version,bunVersion:process.versions.bun};try{let h=await S(a,`/api/profiles/${p}/agent/version`);return{local:t,agentUrl:a,remote:h}}catch(h){return{local:t,agentUrl:a,remote:null,remoteError:h instanceof Error?A(h):String(h)}}},plain:(t)=>{if(g("VibeControls Agent Info"),c(),o(`${d.info} Local System`),n("Hostname",t.local.hostname),n("Platform",`${t.local.platform} ${t.local.arch}`),n("OS Release",t.local.release),n("CPUs",String(t.local.cpus)),n("Total Memory",Qe(t.local.totalMemory)),n("Node.js",t.local.nodeVersion),t.local.bunVersion)n("Bun",t.local.bunVersion);if(c(),o(`${d.info} Remote Agent`),n("URL",t.agentUrl),t.remote){if(n("Version",i.bold(t.remote.version)),t.remote.build)n("Build",t.remote.build);if(t.remote.commit)n("Commit",t.remote.commit);if(t.remote.nodeVersion)n("Node.js (remote)",t.remote.nodeVersion);if(t.remote.bunVersion)n("Bun (remote)",t.remote.bunVersion)}else n("Status",i.dim("not reachable"));c()},interactive:async(t)=>{let h=[];if(h.push("Local System"),h.push(` Hostname: ${t.local.hostname}`),h.push(` Platform: ${t.local.platform} ${t.local.arch}`),h.push(` OS Release: ${t.local.release}`),h.push(` CPUs: ${t.local.cpus}`),h.push(` Total Memory: ${Qe(t.local.totalMemory)}`),h.push(` Node.js: ${t.local.nodeVersion}`),t.local.bunVersion)h.push(` Bun: ${t.local.bunVersion}`);if(h.push(""),h.push("Remote Agent"),h.push(` URL: ${t.agentUrl}`),t.remote){if(h.push(` Version: ${t.remote.version}`),t.remote.build)h.push(` Build: ${t.remote.build}`);if(t.remote.commit)h.push(` Commit: ${t.remote.commit}`);if(t.remote.nodeVersion)h.push(` Node.js: ${t.remote.nodeVersion} (remote)`);if(t.remote.bunVersion)h.push(` Bun: ${t.remote.bunVersion} (remote)`)}else h.push(" Status: not reachable");await U({title:"VibeControls Agent Info",body:h.join(`
|
|
5
5
|
`),footer:"press q to exit"})},json:(t)=>({local:t.local,agentUrl:t.agentUrl,remote:t.remote,remoteError:t.remoteError??null})})}catch(w){s(`Failed to get info: ${A(w)}`)}})}var ut="http://localhost:3005";function ke(b){b.command("system").description("Show system information for a running VibeControls agent").option("--agent-url <url>","Agent URL",ut).option("--json","Emit JSON").option("--plain","Force plain text output").action(async function(O){try{let w={...b.opts(),...O},a=f(w),p=encodeURIComponent(m(w));await y({mode:_(w),fetchData:()=>S(a,`/api/profiles/${p}/agent/system`),plain:(t)=>{if(g("Agent System Information"),c(),o(`${d.info} Agent`),n("Version",i.bold(t.agentVersion)),t.bunVersion)n("Bun",t.bunVersion);if(t.environment)n("Environment",t.environment);n("Uptime",Gr(t.uptime)),c(),o(`${d.info} Platform`),n("OS",`${t.platform} ${t.arch}`),n("Hostname",t.hostname),n("Release",t.release),c(),o(`${d.info} Resources`),n("CPUs",String(t.cpus)),n("Total Memory",Qe(t.totalMemory)),n("Free Memory",Qe(t.freeMemory)),c(),o(`${d.info} Paths`),n("Home",t.homeDir),n("CWD",t.cwd),c()},interactive:async(t)=>{let h=["Agent",` Version: ${t.agentVersion}`,...t.bunVersion?[` Bun: ${t.bunVersion}`]:[],...t.environment?[` Environment: ${t.environment}`]:[],` Uptime: ${Gr(t.uptime)}`,"","Platform",` OS: ${t.platform} ${t.arch}`,` Hostname: ${t.hostname}`,` Release: ${t.release}`,"","Resources",` CPUs: ${t.cpus}`,` Total Mem: ${Qe(t.totalMemory)}`,` Free Mem: ${Qe(t.freeMemory)}`,"","Paths",` Home: ${t.homeDir}`,` CWD: ${t.cwd}`];await U({title:"Agent System Information",body:h.join(`
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Ht,I,se,N,e}from"./index-0qjbnyg4.js";import{b}from"./index-w4jqdhc2.js";import{existsSync as y,mkdirSync as F,readdirSync as ve,readFileSync as x,renameSync as Pe,realpathSync as B,rmSync as h,statSync as we,writeFileSync as M}from"fs";import{homedir as Se}from"os";import{dirname as S,isAbsolute as be,join as p,relative as Ee,sep as j}from"path";import{fileURLToPath as L}from"url";import{existsSync as X,readFileSync as ee}from"fs";import{dirname as k,join as te}from"path";import{fileURLToPath as re}from"url";var ne="@vibecontrols/agent",P;function _e(){if(P)return P;try{let t=k(re(import.meta.url));for(let r=0;r<10&&t&&t!==k(t);r++){let i=te(t,"package.json");if(X(i))try{let n=JSON.parse(ee(i,"utf8"));if(n.name===ne&&typeof n.version==="string")return P=n.version,P}catch{}t=k(t)}}catch{}return P??"0.0.0"}function _(){let t=process.env.VIBECONTROLS_PLUGIN_CONTRACT_V2_ENFORCE;return t==="1"||t==="true"||t==="on"}var D={storage:"rw",secrets:"rw",gateway:!0,broadcast:!0,subprocess:!0,audit:!0,telemetry:!0,singletonOnly:!1,requiresIsolation:!1},O={storage:"none",secrets:"none",gateway:!1,broadcast:!1,subprocess:!1,audit:!1,telemetry:!1,singletonOnly:!1,requiresIsolation:!1};function V(){let t=process.env.VIBECONTROLS_STRICT_PLUGIN_CAPS;return t==="1"||t==="true"||t==="on"}function H(t,r,i,n,s=!1){return new Proxy(t,{get(a,o,l){if(o==="plugins"){if(!s)return;return Reflect.get(a,o,l)}if(o==="storage")return oe(a.storage,i.storage??"none",r,n);if(o==="broadcast"&&!i.broadcast)return w(r,"broadcast",n);if(o==="workspaceQuery"&&!i.gateway)return w(r,"workspaceQuery",n);if(o==="getAgentRecordId"&&!i.gateway)return w(r,"getAgentRecordId",n);if(o==="getWorkspaceId"&&!i.gateway)return w(r,"getWorkspaceId",n);if(o==="iframeBridge"&&!s){let g=Reflect.get(a,o,l);if(!g)return g;return{...g,getAgentApiKey:w(r,"iframeBridge.getAgentApiKey",n)}}if(o==="telemetry"){if(!i.telemetry)return;return Reflect.get(a,o,l)}return Reflect.get(a,o,l)}})}function oe(t,r,i,n){if(r==="rw")return t;return new Proxy(t,{get(s,a,o){let l=String(a),g=l==="set"||l==="delete"||l==="deleteAll";if(r==="none"||r==="read"&&g)return(...d)=>{throw n("plugin.capability.denied",{pluginName:i,surface:"storage",op:l,mode:r}),Error(`plugin '${i}' lacks storage:${g?"rw":"read"} capability (op=${l})`)};return Reflect.get(s,a,o)}})}function w(t,r,i){return(...n)=>{throw i("plugin.capability.denied",{pluginName:t,op:r}),Error(`plugin '${t}' lacks capability for ${r}`)}}import{Worker as ae}from"worker_threads";import{fileURLToPath as ge}from"url";import{randomUUID as ue}from"crypto";function ce(){let t=ge(import.meta.url),r=t.lastIndexOf("/"),i=r>=0?t.slice(0,r):t,n=`${i}/plugin-worker-runtime.ts`,s=`${i}/plugin-worker-runtime.js`;if(t.endsWith(".ts"))return n;return s}class R{worker;pending=new Map;spec;initPromise;terminated=!1;constructor(t){this.spec=t}async start(){if(this.initPromise)return this.initPromise;return this.initPromise=this.spawn(),this.initPromise}async spawn(){let t=this.spec.runtimeEntry??ce(),r=["PATH","HOME","USERPROFILE","TMPDIR","TMP","TEMP","LANG","LC_ALL","LC_CTYPE","TZ","SystemRoot","SystemDrive","ComSpec","PATHEXT","windir"],i={};for(let s of r){let a=process.env[s];if(typeof a==="string")i[s]=a}let n=new ae(t,{env:i});this.worker=n,n.on("message",(s)=>this.onMessage(s)),n.on("error",(s)=>this.onWorkerError(s instanceof Error?s:Error(String(s)))),n.on("exit",(s)=>this.onWorkerExit(s)),await this.call("init",{modulePath:this.spec.modulePath,ctxStub:{name:this.spec.ctx.name,dataDir:this.spec.ctx.dataDir}})}async dispatch(t,r=[]){if(this.terminated)throw Error("PluginWorkerHost terminated");if(!this.worker)await this.start();return this.call("dispatch",{method:t,params:r})}call(t,r){if(!this.worker)return Promise.reject(Error("worker not spawned"));let i=ue();return new Promise((n,s)=>{this.pending.set(i,{resolve:n,reject:s});try{this.worker?.postMessage({id:i,op:t,args:r})}catch(a){this.pending.delete(i),s(a instanceof Error?a:Error(String(a)))}})}onMessage(t){let r=this.pending.get(t.id);if(!r)return;if(this.pending.delete(t.id),t.ok)r.resolve(t.result);else{let i=Error(t.error?.message??"worker error");if(t.error?.stack)i.stack=t.error.stack;r.reject(i)}}onWorkerError(t){for(let[,r]of this.pending)r.reject(t);this.pending.clear()}onWorkerExit(t){if(this.pending.size>0){let r=Error(`worker exited (code=${t}) with pending calls`);for(let[,i]of this.pending)i.reject(r);this.pending.clear()}this.terminated=!0}async terminate(){if(this.terminated=!0,!this.worker)return;try{await this.worker.terminate()}catch{}this.worker=void 0}}var de=[{packageName:"@vibecontrols/vibe-plugin-storage",pluginName:"storage",label:"Storage facade",description:"Storage provider registry \u2014 owns AgentDatabase contract. Bundled with the agent; the storage meta lazy-loads the configured provider by name.",category:"storage",trusted:!0,isCore:!0,isDefault:!0,isCritical:!0,removable:!1,integrity:"sha512-E0agrBuSwO7R5z7dBA6Jb0Mq5zibhkFzvEh0lcb4N+byt25yStrDcsJqJ3bJpVdavw/OkAjB+MAC06zkTtHraQ=="},...["agent","task","config","git","plugin-mgr","log"].map((t)=>({packageName:`@vibecontrols/vibe-plugin-${t}`,pluginName:t,label:`${t} (built-in)`,description:`Built-in ${t} plugin bundled with the agent.`,category:"core",trusted:!0,isCore:!0,removable:!1}))],pe=[{packageName:"@vibecontrols/vibe-plugin-tunnel",pluginName:"tunnel",label:"Tunnel manager",description:"Owns TunnelProvider interface. Routes to a registered tunnel provider.",category:"tunnel",trusted:!0,isDefault:!0,isCritical:!0,cliCommand:"tunnel",apiPrefix:"/api/tunnel",integrity:"sha512-FFqJjvPNCAYZwMjOKt1vHiBuzd+6W9sYI6vZqls7kr3Za+m++tIueT9OV2DlpAJT8XU+fidrgsWgQi8AcjPHWQ=="},{packageName:"@vibecontrols/vibe-plugin-session-manager",pluginName:"session-manager",label:"Session manager",description:"Owns SessionProvider interface. Routes to a registered session backend.",category:"session",trusted:!0,isCore:!0,isDefault:!0,isCritical:!0,cliCommand:"session",apiPrefix:"/api/sessions",integrity:"sha512-1841STCBKRDc0h0BFgcZ3ZJydThKUkHKtDdnC2YMZOiSYVB4N/+7fJQhyMSq3bc6zj/FO7jBne9Gmg+PLoXiQA=="},{packageName:"@vibecontrols/vibe-plugin-ai",pluginName:"ai",label:"AI orchestration",description:"Owns AIAgentProvider interface. Prompts, contexts, sessions, dispatch, logs.",category:"ai",trusted:!0,isDefault:!0,isCritical:!0,cliCommand:"ai",apiPrefix:"/api/ai",integrity:"sha512-mIkzkzMDU38ILFa2lRsjeaJqAidtlUBWoQ3KaFxkpG88AHWUtcA6Vha/wZQ5Ns16h0g4vRKxtbOLfFSTEgRerA=="},{packageName:"@vibecontrols/vibe-plugin-plan",pluginName:"plan",label:"Plan orchestration",description:"Owns PlanProvider interface. Routes plan sessions to a registered provider.",category:"plan",trusted:!0,isDefault:!1,cliCommand:"plan",apiPrefix:"/api/plan",integrity:"sha512-SSCFLFkmAhHesLYgETeEyAZs2Gu8tDEaMMuJtMMKG5eKGQIXYJaJZnQBuXP/vKOAlLd//l8es5hPqhmiNSi4Gw=="},{packageName:"@vibecontrols/vibe-plugin-gitops",pluginName:"gitops",label:"GitOps orchestrator",description:"Owns GitOpsProvider interface. Routes repo / PR / CI / security queries to a registered provider.",category:"gitops",trusted:!0,isDefault:!1,cliCommand:"gitops",apiPrefix:"/api/gitops",integrity:"sha512-KzoSmBDgQ5mbSFxAuIyIBnC/HKwYhtXluGp06DvzQmwqOQ4vEC72PuSiVx3doWrt+Z6fZ6i6gxNzmYNpdhPLXA=="},{packageName:"@vibecontrols/vibe-plugin-security",pluginName:"security",label:"Security lifecycle",description:"Security lifecycle orchestrator \u2014 owns /api/security and dispatches to per-stage providers.",category:"security",trusted:!0,isDefault:!1,cliCommand:"security",apiPrefix:"/api/security",integrity:"sha512-K6w3tC7qnCotvnNWWdmHnjqGgCNJoPNMs8gCwWFbcNI5MmbIrUQfFQdcjwGudwryvN2+TrX12MhfhWz4p1qcMA=="}],fe=[{packageName:"@vibecontrols/vibe-plugin-tool-code-server",pluginName:"code-server",label:"Browser code editor",description:"Browser-based VS Code via code-server \u2014 open any Vibe in an in-browser editor.",category:"tool",trusted:!0,isDefault:!1,cliCommand:"code-server",apiPrefix:"/api/code-server"}],me=[{packageName:"@vibecontrols/vibe-plugin-agent-backup",pluginName:"agent-backup",label:"Agent backup",description:"Backup and restore agent state.",category:"agent",trusted:!0,isDefault:!0,integrity:"sha512-KhN2Vaahtnl4IKRbaHKtlEbsuvW9dbgC2l4kkIXcme55DaSmLy5kYkiysnwyZdC4PRQu4NKM4GQLoW9hD86dRw=="}],ie=[...de,...pe,...fe,...me],Y=[{key:"storage",label:"Storage",description:"Encrypted local state for the agent.",categories:["storage"],mandatory:!0,defaultSelected:!0},{key:"tunnel",label:"Tunnels",description:"Expose the agent for remote access + share links.",categories:["tunnel"],mandatory:!0,defaultSelected:!0},{key:"backup",label:"Backup",description:"Backup + restore agent state.",categories:["agent"],mandatory:!0,defaultSelected:!0},{key:"session",label:"Terminal sessions",description:"Long-lived terminal / AI agent sessions.",categories:["session"],mandatory:!1,defaultSelected:!0},{key:"editor",label:"Browser code editor",description:"Open any Vibe in an in-browser VS Code editor (code-server).",categories:["tool"],mandatory:!1,defaultSelected:!0},{key:"ai",label:"AI orchestration",description:"AI agent harnesses, prompts + dispatch.",categories:["ai"],mandatory:!1,defaultSelected:!0},{key:"plan",label:"Plan review",description:"Review / approve AI-proposed plans.",categories:["plan"],mandatory:!1,defaultSelected:!1},{key:"gitops",label:"GitOps",description:"Repo / PR / CI / security integration.",categories:["gitops"],mandatory:!1,defaultSelected:!1},{key:"security",label:"Security",description:"Security scanning lifecycle.",categories:["security"],mandatory:!1,defaultSelected:!1}],C=ie.filter((t)=>t.isCore&&t.category==="core").map((t)=>t.pluginName),U=ie.filter((t)=>t.isDefault===!0);function A(t){return U}function ye(t,r){let i=r instanceof Set?r:new Set(r),n=new Set;for(let s of Y)if(s.mandatory||i.has(s.key))for(let a of s.categories)n.add(a);return ie.filter((s)=>n.has(s.category))}var G=new Set(ie.filter((t)=>t.trusted).map((t)=>t.packageName));function he(){let t=ie.filter((i)=>i.isCritical).flatMap((i)=>[i.packageName,i.pluginName]),r=process.env.VIBECONTROLS_CRITICAL_PLUGINS;if(r){let i=r.split(",").map((n)=>n.trim()).filter(Boolean);return new Set([...t,...i])}return new Set(t)}function ht(t){return he().has(t)}var bi=ie.filter((t)=>!t.isCore||t.category!=="core");function wi(t){return ie.find((r)=>r.packageName===t)}function qi(t){return new Set}function ft(t){return t.startsWith("@vibecontrols/vibe-plugin-")||G.has(t)}function Pr(t){let r=t.trim();if(!r)return;if(r.startsWith("@vibecontrols/"))return ie.find((n)=>n.packageName===r);if(r.startsWith("vibe-plugin-"))return ie.find((n)=>n.packageName===`@vibecontrols/${r}`);let i=ie.find((n)=>n.pluginName===r);if(i)return i;return ie.find((n)=>n.packageName===`@vibecontrols/vibe-plugin-${r}`)}function Mt(t){let r=t.trim();if(!r)return;let i=Pr(r);if(i)return i.packageName;if(r.startsWith("@vibecontrols/"))return r;if(r.startsWith("vibe-plugin-"))return`@vibecontrols/${r}`;return`@vibecontrols/vibe-plugin-${r}`}function q(t){return ie.find((r)=>r.pluginName===t)}function ke(t){return ie.find((r)=>r.packageName===t)}function Re(t,r){if(t.length!==r.length)return!1;let i=0;for(let n=0;n<t.length;n++)i|=t.charCodeAt(n)^r.charCodeAt(n);return i===0}async function Ce(t,r,i){let n=ke(t),s=process.env.VIBECONTROLS_REQUIRE_PLUGIN_INTEGRITY==="1";if(!n?.integrity){if(s)throw Error(`Refusing to install ${t}: catalog has no pinned integrity and VIBECONTROLS_REQUIRE_PLUGIN_INTEGRITY=1`);return}let a=i,o;try{let g=`${r.replace(/\/+$/,"")}/${t.replace("/","%2F")}`,u=await fetch(g,{headers:{accept:"application/json"},signal:AbortSignal.timeout(20000)});if(!u.ok)throw Error(`registry packument fetch failed (HTTP ${u.status})`);let d=await u.json();if(a=a??d["dist-tags"]?.latest,!a)throw Error("could not resolve version from registry");if(o=d.versions?.[a]?.dist?.integrity,typeof o!=="string"||o.length===0)throw Error(`registry did not return dist.integrity for ${t}@${a}`)}catch(l){let g=l instanceof Error?l.message:String(l);throw Error(`Pre-install integrity gate refused ${t}: ${g}`,{cause:l})}if(!Re(n.integrity,o)){let l=process.env.VIBECONTROLS_STRICT_PLUGIN_INTEGRITY==="1";if(ft(t)&&!l){e().logger.warn("plugin-manager",`Integrity pin for ${t} is stale \u2014 catalog expects ${n.integrity}, the allowlisted registry has ${o} for ${a}. Proceeding (first-party package, registry allowlisted). Re-pin plugins.config.ts to silence this.`);return}throw Error(`Pre-install integrity gate refused ${t}: integrity mismatch for ${a}: expected ${n.integrity}, got ${o}`)}}var $e=["https://registry.npmjs.org/","https://registry.npmjs.org"];function Ae(){let t=process.env.VIBECONTROLS_REGISTRY_ALLOWLIST,r=[...$e];if(typeof t==="string"&&t.length>0)for(let i of t.split(",").map((n)=>n.trim()).filter(Boolean))r.push(i);return r}function Ie(t){let r=Ae(),i;try{i=new URL(t).origin}catch{throw Error(`Invalid plugin registry URL: ${t}`)}for(let n of r)try{if(new URL(n).origin===i)return}catch{}throw Error(`Plugin registry '${t}' is not in the allow-list. Add it to VIBECONTROLS_REGISTRY_ALLOWLIST at daemon start.`)}var K="plugins.json",xe=/^@vibecontrols\/vibe-plugin-[a-z0-9][a-z0-9-]{0,80}$/,z=/^[a-z0-9][a-z0-9-]{0,63}$/,Le=/^\/api\/[A-Za-z0-9][A-Za-z0-9/_-]{0,127}$/,Te=/^\/[A-Za-z0-9][A-Za-z0-9/_-]{0,159}$/,Q=Symbol.for("vibecontrols.pluginPackageRoot");function Mr(t){return t[Q]}function le(t){let r=t.trim();if(!xe.test(r))throw Error("Plugin package must be a @vibecontrols/vibe-plugin-* package name.");if(!ft(r)&&process.env.VIBECONTROLS_ALLOW_UNTRUSTED_PLUGINS!=="1")throw Error("Plugin package is not in the trusted VibeControls catalog.");return r}function Ne(t,r){let i=Ee(t,r);return i===""||!!i&&!i.startsWith("..")&&!be(i)}function Z(){return p(I(),"agent-plugins","node_modules")}function De(){try{let t=Z();return y(t)&&ve(t).length>0}catch{return!1}}function T(){let t=(process.env.VIBECONTROLS_PLUGIN_INSTALL_SCOPE??process.env.VIBECONTROLS_PLUGIN_INSTALL_MODE??"").toLowerCase();if(t==="local")return"local";if(t==="global")return"global";return De()?"local":"global"}var J="provider:default:";function Oe(t){if(!t||typeof t!=="object")return!1;let r=t;return typeof r.packageName==="string"&&typeof r.version==="string"&&typeof r.pluginName==="string"&&typeof r.installedAt==="string"}class W{registry=[];loaded=new Map;corePlugins=new Map;db;forcedIsolation=new Set;workerHosts=new Map;lifecycleChain=Promise.resolve();withLifecycleLock(t){let i=this.lifecycleChain.then(t,t);return this.lifecycleChain=i.then(()=>{return},()=>{return}),i}async terminateWorkerHost(t){let r=this.workerHosts.get(t);if(!r)return;try{await r.terminate()}catch(i){e().logger.warn("plugin-manager",`Failed to terminate worker for '${t}': ${i instanceof Error?i.message:String(i)}`)}finally{this.workerHosts.delete(t)}}async terminateAllWorkerHosts(){let t=Array.from(this.workerHosts.keys());await Promise.all(t.map((r)=>this.terminateWorkerHost(r)))}constructor(t){this.db=t,this.ensureDir(),this.loadRegistry();let r=process.env.VIBE_ISOLATE_PLUGINS;if(typeof r==="string"&&r.length>0)this.setForcedIsolation(r.split(",").map((i)=>i.trim()).filter((i)=>i.length>0))}setForcedIsolation(t){this.forcedIsolation=new Set(t.filter((r)=>r.length>0))}shouldIsolate(t){if(this.forcedIsolation.has(t.name))return!0;return t.capabilities?.requiresIsolation===!0}getWorkerHost(t){return this.workerHosts.get(t)}registerWorkerHost(t,r){this.workerHosts.set(t,r)}auditSink=(t,r)=>{e().logger.warn("plugin-capability",t,r)};static resolveEffectiveCapabilities(t,r){if(t.capabilities)return t.capabilities;return r?D:O}wrapHostServices(t,r){let i=this.corePlugins.has(t.name),n=W.resolveEffectiveCapabilities(t,i),s=i||this.isTrustedLoadedPlugin(t);return H(r,t.name,n,this.auditSink,s)}routeDepsFor(t,r){if(this.corePlugins.has(t.name)||this.isTrustedLoadedPlugin(t))return r;let n=W.resolveEffectiveCapabilities(t,!1),s=r.hostServices?this.wrapHostServices(t,r.hostServices):void 0,a=this.auditSink,o=(l)=>{throw a("plugin.capability.denied",{plugin:t.name,capability:`routeDeps.${l}`}),Error(`Plugin '${t.name}' may not use routeDeps.${l}: untrusted plugins receive only capability-scoped host services`)};return new Proxy({},{get(l,g){if(g==="hostServices")return s;if(g==="broadcast")return n.broadcast?r.broadcast:()=>o("broadcast");if(typeof g==="string")return o(g);return}})}isTrustedLoadedPlugin(t){for(let[r,i]of this.loaded)if(i===t)return ft(r);return!1}acceptCapabilities(t,r){if(t.capabilities?.singletonOnly===!0&&N.size()>1)return e().logger.error("plugin-manager",`[plugin] '${t.name}' refused to load: singletonOnly capability incompatible with multi-profile daemon (profiles=${N.size()}, source=${r})`),!1;if(t.capabilities)return!0;if(V())return e().logger.error("plugin-manager",`[plugin] '${t.name}' refused to load: missing required capabilities declaration (source=${r})`),!1;if(r.startsWith("core:"))e().logger.warn("plugin-manager",`[plugin] '${t.name}' loaded without a capabilities declaration \u2014 granting full trust (core plugin). Declare capabilities explicitly. (source=${r})`);else e().logger.warn("plugin-manager",`[plugin] '${t.name}' loaded without a capabilities declaration \u2014 defaulting to EMPTY capability set (deny by default). External plugins MUST declare capabilities explicitly to access host services. (source=${r})`);return!0}ensureDir(){let t=I();if(!y(t))F(t,{recursive:!0})}loadRegistry(){let t=p(I(),K);try{if(y(t)){let r=x(t,"utf-8"),i=JSON.parse(r);if(Array.isArray(i)&&i.every(Oe))this.registry=i.filter((n)=>{try{return le(n.packageName),!0}catch(s){return e().logger.warn("plugin-manager","Ignoring invalid plugin entry",{packageName:n.packageName,error:String(s)}),!1}});else throw Error("plugins.json has an invalid schema")}}catch(r){e().logger.warn("plugin-manager","Failed to load plugin registry",{path:t,error:String(r)}),this.registry=[]}}saveRegistry(){this.ensureDir();let t=p(I(),K),r=`${t}.${process.pid}.tmp`;M(r,`${JSON.stringify(this.registry,null,2)}
|
|
3
|
-
`,{encoding:"utf-8",mode:384}),Pe(r,t)}async loadCorePlugins(){let t=await Promise.allSettled([import("./index-
|
|
4
|
-
`);if(n&&l){let m=this.readInstalledVersion(p(c,"node_modules"),t);if(m&&m!==l){e().logger.info("plugin-manager",`Pre-clean ${t}: on-disk v${m} != target v${l} \u2014 removing stale copy + lockfile to force fresh resolve`);try{h(p(c,"node_modules",t),{recursive:!0,force:!0})}catch{}try{h(p(c,"bun.lock"),{force:!0}),h(p(c,"bun.lockb"),{force:!0})}catch{}}try{h(p(c,"bun.lock"),{force:!0}),h(p(c,"bun.lockb"),{force:!0})}catch{}}if(Bun.spawnSync(["bun","add",g,"--registry",a],{cwd:c,timeout:120000,stdout:"pipe",stderr:"pipe"}).exitCode!==0){let m=Bun.spawnSync(["npm","install",g,"--registry",a],{cwd:c,timeout:120000,stdout:"pipe",stderr:"pipe"});if(m.exitCode!==0)throw Error(m.stderr.toString().trim())}if(n&&l){let m=this.readInstalledVersion(p(c,"node_modules"),t);if(m!==l){e().logger.warn("plugin-manager",`bun kept ${t}@${m??"missing"} after requesting ${l}; retrying with npm after removing stale local copy`);try{h(p(c,"node_modules",t),{recursive:!0,force:!0}),h(p(c,"bun.lock"),{force:!0}),h(p(c,"bun.lockb"),{force:!0}),h(p(c,"package-lock.json"),{force:!0})}catch{}let E=Bun.spawnSync(["npm","install",g,"--registry",a,"--save-exact"],{cwd:c,timeout:120000,stdout:"pipe",stderr:"pipe"});if(E.exitCode!==0)throw Error(E.stderr.toString().trim())}}}else if(Bun.spawnSync(["bun","install","-g",g,"--registry",a],{timeout:120000,stdout:"pipe",stderr:"pipe"}).exitCode!==0){let f=Bun.spawnSync(["npm","install","-g",g,"--registry",a],{timeout:120000,stdout:"pipe",stderr:"pipe"});if(f.exitCode!==0)throw Error(f.stderr.toString().trim())}this.pluginRoots=void 0}catch(c){let f=c instanceof Error?c.message:String(c);if(n)try{await import(t),e().logger.warn("plugin-manager",`Could not refresh ${t} to @latest (${f}); using the already-installed copy`),this.pluginRoots=void 0;let v=await this.importPlugin(t),m={packageName:t,version:v.version,pluginName:v.name,installedAt:new Date().toISOString()};return this.registry=this.registry.filter((E)=>E.packageName!==t),this.registry.push(m),this.saveRegistry(),m}catch{}throw Error(`Failed to install ${t}: ${f}`,{cause:c})}let u=await this.importPlugin(t);if(n&&l&&u.version!==l)e().logger.warn("plugin-manager",`${t} refreshed to ${u.version} but registry latest is ${l} \u2014 a stale resolver/cache may still be in play`);if(this.corePlugins.has(u.name))e().logger.info("plugin-manager",`External plugin '${t}' overrides core plugin '${u.name}'`);let d={packageName:t,version:u.version,pluginName:u.name,installedAt:new Date().toISOString()};return this.registry=this.registry.filter((c)=>c.packageName!==t),this.registry.push(d),this.saveRegistry(),e().logger.info("plugin-manager",`Installed ${t}@${u.version} (${u.name})`),d}async ensureDefaultPlugins(t,r=[],i){let n=[],s=new Set(r),a=i?ye(process.platform,i):A(process.platform);for(let o of a){if(s.has(o.packageName)||s.has(o.pluginName)){e().logger.info("plugin-manager",`${o.packageName} skipped by --skip-plugin`);continue}if(o.isCore&&o.category==="core"){e().logger.info("plugin-manager",`${o.packageName} is bundled with the agent \u2014 skipping auto-install`);continue}if(this.registry.some((g)=>g.packageName===o.packageName)){e().logger.info("plugin-manager",`${o.packageName} already installed, skipping auto-install`);continue}t?.(`Installing ${o.label} (${o.packageName})...`);try{await this.install(o.packageName,{refreshLatest:!0}),n.push(o),t?.(`Installed ${o.label} (${o.packageName})`)}catch(g){let u=g instanceof Error?g.message:String(g);e().logger.error("plugin-manager",`Failed to auto-install ${o.packageName}: ${u}`),t?.(`Failed to install ${o.label}: ${u}`)}}if(n.length>0)this.loadRegistry();return n}async installAndLoad(t,r,i){let n=await this.install(t),s=this.loaded.get(n.packageName);if(s){this.registerPluginProviders(s,i);let a=this.wrapHostServices(s,i);if(s.onServerStart)await s.onServerStart(r,a);if(s.onServerReady)await s.onServerReady(r,a)}return n}async update(t,r){return this.withLifecycleLock(()=>this.updateLocked(t,r))}async updateLocked(t,r){if(t=le(t),e().logger.info("plugin-manager",`Updating ${t}${r?`@${r}`:""}...`),!this.registry.find((a)=>a.packageName===t))throw Error(`Plugin ${t} is not installed. Use 'install' first.`);let n=this.loaded.get(t);if(n)await this.terminateWorkerHost(n.name);this.loaded.delete(t);let s=await this.installLocked(t,{refreshLatest:!0,version:r});return e().logger.info("plugin-manager",`Updated ${t} to v${s.version}`),s}async updateAll(){let t=[];for(let r of[...this.registry])try{let i=await this.update(r.packageName);t.push({packageName:r.packageName,success:!0,version:i.version})}catch(i){t.push({packageName:r.packageName,success:!1,error:i instanceof Error?i.message:String(i)})}return t}async removeAll(t){let r=[],i=[...this.registry];for(let n of i)try{await this.remove(n.packageName,t),r.push({packageName:n.packageName,success:!0})}catch(s){r.push({packageName:n.packageName,success:!1,error:s instanceof Error?s.message:String(s)})}return r}async remove(t,r){return this.withLifecycleLock(()=>this.removeLocked(t,r))}async removeLocked(t,r){t=le(t),e().logger.info("plugin-manager",`Removing ${t}...`);let i=this.loaded.get(t);if(i?.onServerStop)try{await i.onServerStop()}catch(a){e().logger.warn("plugin-manager",`Error stopping ${t}: ${a}`)}if(i)await this.terminateWorkerHost(i.name),r?.serviceRegistry.unregisterPlugin(i.name),this.loaded.delete(t);let n=this.registry.find((a)=>a.packageName===t);if(!i&&n)r?.serviceRegistry.unregisterPlugin(n.pluginName);let s=p(I(),"agent-plugins");try{if(y(p(s,"package.json")))Bun.spawnSync(["bun","remove",t],{cwd:s,timeout:60000,stdout:"pipe",stderr:"pipe"})}catch{}try{Bun.spawnSync(["bun","remove","-g",t],{timeout:60000,stdout:"pipe",stderr:"pipe"})}catch{try{Bun.spawnSync(["npm","uninstall","-g",t],{timeout:60000,stdout:"pipe",stderr:"pipe"})}catch{}}this.pluginRoots=void 0,this.registry=this.registry.filter((a)=>a.packageName!==t),this.saveRegistry(),e().logger.info("plugin-manager",`Removed ${t}`)}async loadAll(){this.loaded.clear();let t=[];for(let r of this.registry)try{le(r.packageName),await this.importPlugin(r.packageName),e().logger.info("plugin-manager",`Loaded ${r.packageName} (${r.pluginName})`)}catch(i){let n=i.code;if(n==="ENOENT_PLUGIN")e().logger.info("plugin-manager",`${r.packageName} not present on disk \u2014 dropping from registry`),t.push(r.packageName);else if(n==="EPLUGIN_LEGACY_SINGLETON")e().logger.warn("plugin-manager",`Skipping ${r.packageName}: ${i instanceof Error?i.message:String(i)}`);else e().logger.warn("plugin-manager",`Failed to load ${r.packageName} \u2014 dropping from registry: ${i}`),t.push(r.packageName)}if(t.length>0){this.registry=this.registry.filter((r)=>!t.includes(r.packageName));try{this.saveRegistry()}catch(r){e().logger.warn("plugin-manager",`Failed to persist pruned registry: ${r}`)}}}async importPlugin(t){t=le(t);let r={},i;{let s=this.getGlobalRoots(),a=!1,o=[],l=!0;for(let g of s){let u=p(g,t);if(!y(u)){o.push({path:u,error:"directory missing"});continue}l=!1;try{i=u,r=await import(u),a=!0;break}catch(d){o.push({path:u,error:d instanceof Error?d.message:String(d)})}try{let d=p(u,"package.json");if(!y(d)){o.push({path:d,error:"package.json missing"});continue}let c=JSON.parse(x(d,"utf8")),f=c.module??c.main??"./index.js",v=p(u,f);i=u,r=await import(v),a=!0;break}catch(d){o.push({path:u,error:d instanceof Error?d.message:String(d)})}}if(!a)try{i=this.resolvePackageRoot(t)??i,r=await import(t),a=!0}catch(g){o.push({path:`bare:${t}`,error:g instanceof Error?g.message:String(g)})}if(!a){let g=o.map((d)=>`${d.path} (${d.error})`).join("; "),u=Error(`Cannot find module '${t}': explicit root attempts and bare import failed: ${g||"(no roots probed)"}`);if(l&&s.length>0)u.code="ENOENT_PLUGIN";throw u}}let n=this.extractPlugin(r,`external:${t}`,e());if(!n){if(this.hasLegacySingleton(r)){let s=Error(`${t} uses removed singleton contract; upgrade to createPlugin(ctx) factory (set VIBECONTROLS_PLUGIN_CONTRACT_V2_ENFORCE=1 to refuse strictly)`);throw s.code="EPLUGIN_LEGACY_SINGLETON",s}throw Error(`${t} does not export a valid createPlugin(ctx) factory`)}if(this.validatePluginExport(n,t,i),!this.acceptCapabilities(n,`external:${t}`))throw Error(`${t} refused to load: missing required capabilities declaration`);if(i)Object.defineProperty(n,Q,{value:i,enumerable:!1,configurable:!1});if(this.logResolvedPlugin(t,n.version,i),this.loaded.set(t,n),this.shouldIsolate(n)){let s=e(),a=new R({modulePath:t,pluginName:n.name,ctx:{name:s.name,dataDir:s.dataDir}});try{await a.start(),this.workerHosts.set(n.name,a),s.logger.info("plugin-manager",`Isolated plugin '${n.name}' running in worker_threads`)}catch(o){try{await a.terminate()}catch{}this.loaded.delete(t);let l=o instanceof Error?o.message:String(o);throw s.logger.error("plugin-manager",`Isolation required for '${n.name}' but worker failed to start (${l}); refusing to load in host process`),Error(`Plugin '${n.name}' requires isolation but the worker failed to start: ${l}`,{cause:o})}}return n}resolvePackageRoot(t){let r=import.meta;if(typeof r.resolve!=="function")return;try{let i=r.resolve(t);if(!i.startsWith("file:"))return;let n=S(L(i));while(n&&n!==S(n)){if(y(p(n,"package.json")))return n;n=S(n)}}catch{return}return}validatePluginExport(t,r,i){if(!z.test(t.name))throw Error(`${r} exports an invalid plugin name`);if(!t.version||t.version.length>64)throw Error(`${r} exports an invalid plugin version`);if(t.description&&t.description.length>500)throw Error(`${r} description is too long`);if(t.cliCommand&&!z.test(t.cliCommand))throw Error(`${r} exports an invalid CLI command`);if(t.apiPrefix){if(!Le.test(t.apiPrefix)||t.apiPrefix.includes("..")||t.apiPrefix.includes("//"))throw Error(`${r} exports an invalid API prefix`)}if(t.publicPaths){if(t.publicPaths.length>20)throw Error(`${r} exports too many public paths`);for(let n of t.publicPaths)if(!Te.test(n)||n.includes("..")||n.includes("//"))throw Error(`${r} exports an invalid public path`)}if(t.dependencies&&t.dependencies.length>20)throw Error(`${r} exports too many dependencies`);if(t.tags){let n=new Set(["backend","frontend","cli","provider","adapter","integration"]);if(t.tags.length>n.size)throw Error(`${r} exports too many tags`);for(let s of t.tags)if(!n.has(s))throw Error(`${r} exports an invalid tag`)}if(t.ui){if(t.ui.title&&t.ui.title.length>120)throw Error(`${r} UI title is too long`);if(t.ui.staticDir){if(!i)throw Error(`${r} UI staticDir requires a package root`);let n=B(i),s=B(t.ui.staticDir);if(!we(s).isDirectory()||!Ne(n,s))throw Error(`${r} UI staticDir must be inside the plugin package`)}}}pluginRoots;getPluginRoots(){if(this.pluginRoots!==void 0)return this.pluginRoots;let t=b(),r=[],i=new Set,n=(a)=>{if(!a||i.has(a)||!y(a))return;i.add(a),r.push(a)},s=process.env.VIBECONTROLS_PLUGIN_ROOTS;if(s)for(let a of s.split(t.pathSep).map((o)=>o.trim()).filter(Boolean))n(a);if(T()==="local")n(Z());else n(p(Se(),".bun","install","global","node_modules")),n(t.npmGlobalRoot());if(this.isRunningFromSource())n(this.agentOwnNodeModules());return this.pluginRoots=r,r}isRunningFromSource(){try{let t=L(import.meta.url);return t.includes(`${j}src${j}`)||t.includes("/src/")}catch{return!1}}agentOwnNodeModules(){try{let t=S(L(import.meta.url)),r="";while(t&&t!==r){if(y(p(t,"package.json")))return p(t,"node_modules");r=t,t=S(t)}}catch{}return null}getGlobalRoots(){return this.getPluginRoots()}readInstalledVersion(t,r){try{let i=p(t,r,"package.json");if(!y(i))return;let n=JSON.parse(x(i,"utf8"));return typeof n.version==="string"?n.version:void 0}catch{return}}logResolvedPlugin(t,r,i){let n=e().logger;n.debug("plugin-manager",`Resolved ${t}@${r}`,{from:i??"(bare import)"});try{let s=[];for(let a of this.getPluginRoots()){let o=p(a,t);if(i&&o===i)continue;let l=this.readInstalledVersion(a,t);if(l&&l!==r)s.push(`${o} (v${l})`)}if(s.length>0)n.warn("plugin-manager",`${t}: loaded v${r} but stale duplicate copy(ies) exist at a different version \u2014 these shadow the active copy across reinstalls. Run \`vibe nuke --all\` to purge them.`,{loadedVersion:r,loadedFrom:i??"(bare import)",shadows:s})}catch{}}extractPlugin(t,r,i){let n=this.findFactory(t);if(n){let s=n(i);if(!this.isVibePlugin(s))throw Error(`plugin '${r}' createPlugin(ctx) factory returned an invalid VibePlugin`);return s}if(this.hasLegacySingleton(t)){let s=`plugin '${r}' uses removed singleton contract; upgrade to createPlugin(ctx) factory`;if(_())throw Error(s);e().logger.warn("plugin-manager",s);return}return}findFactory(t){if(typeof t.createPlugin==="function")return t.createPlugin;let r=t.default;if(r&&typeof r.createPlugin==="function")return r.createPlugin;return}hasLegacySingleton(t){if(this.isVibePlugin(t.vibePlugin))return!0;let r=t.default;if(r&&this.isVibePlugin(r.vibePlugin))return!0;if(this.isVibePlugin(r))return!0;return!1}isVibePlugin(t){if(!t||typeof t!=="object")return!1;let r=t;return typeof r.name==="string"&&typeof r.version==="string"}registerProviders(t,r){this.registerPluginProviders(t,r)}registerPluginProviders(t,r){let n=q(t.name)?.isDefault===!0,s=(a)=>{if(!n)return;r.serviceRegistry.setProviderDefault(a,t.name)};if(t.providers?.tunnel){if(r.serviceRegistry.registerProvider("tunnel",t.providers.tunnel,t.name),s("tunnel"),t.tunnelDomainSuffixes)for(let a of t.tunnelDomainSuffixes)Ht(a)}if(t.providers?.session)r.serviceRegistry.registerProvider("session",t.providers.session,t.name),s("session");if(t.providers?.ai)r.serviceRegistry.registerProvider("ai",t.providers.ai,t.name),s("ai")}async dispatchCliSetup(t,r){for(let i of this.getAllPlugins())if(i.onCliSetup)try{await i.onCliSetup(t,this.wrapHostServices(i,r))}catch(n){e().logger.warn("plugin-manager",`onCliSetup failed for ${i.name}: ${n}`)}}async dispatchServerStart(t,r){let i=this.sortAllByDependencies(),n=[];for(let s of i){if(this.registerPluginProviders(s,r),s.onServerStart){let a=Date.now();try{await s.onServerStart(t,this.wrapHostServices(s,r)),(async()=>{try{let{telemetryService:o}=await import("./telemetry-nmtywcba.js");o.emit("plugin.activated",{plugin_name:s.name,version:s.version,duration_ms:Date.now()-a})}catch{}})()}catch(o){let l=o instanceof Error?o.message:String(o);e().logger.error("plugin-manager",`onServerStart failed for ${s.name}: ${l}`),(async()=>{try{let{telemetryService:u}=await import("./telemetry-nmtywcba.js");u.emit("plugin.failed",{plugin_name:s.name,error_class:o instanceof Error?o.constructor.name:"Error"})}catch{}})();let g=this.registry.find((u)=>u.pluginName===s.name);n.push({plugin:s.name,packageName:g?.packageName,error:l})}}this.registerPluginProviders(s,r)}return{failures:n}}async dispatchServerReady(t,r){for(let i of this.getAllPlugins())if(i.onServerReady)try{await i.onServerReady(t,this.wrapHostServices(i,r))}catch(n){e().logger.warn("plugin-manager",`onServerReady failed for ${i.name}: ${n}`)}}async provisionDefaultPrereqs(t,r,i,n){let s=process.env.VIBE_SKIP_PREREQ_INSTALL==="1",a=process.platform;e().logger.info("plugin-manager",`Provisioning default providers \u2014 agent build v${_e()}, platform=${a}, pluginInstallScope=${T()}, skipInstall=${s}`);let o=(n?ye(process.platform,n):A(process.platform)).map((u)=>u.packageName);if(!s)for(let u of o){if(this.loaded.has(u))continue;try{e().logger.info("plugin-manager",`Installing default meta ${u}`),await this.install(u,{refreshLatest:!0})}catch(d){e().logger.warn("plugin-manager",`Failed to install default meta ${u}: ${d}`)}}let l=this.buildHostPluginsFacade(t,r,i),g=this.attachPluginsFacade(r,l);for(let[u,d]of this.getAllLoaded()){if(!d.provisionProviders)continue;try{await d.provisionProviders(this.wrapHostServices(d,g)),e().logger.info("plugin-manager",`${u}: providers provisioned`)}catch(c){e().logger.warn("plugin-manager",`${u}: provisionProviders failed: ${c}`)}}}buildHostPluginsFacade(t,r,i){return{install:async(n,s)=>{await this.install(n,s??{})},loadProvider:async(n)=>{await this.loadAndStartProvider(n,t,r,i)},runPrereqs:async(n,s)=>{let{runPluginPrereqs:a}=await import("./prereqs-runner-gca0bytz.js"),o=this.loaded.get(n);if(!o)return{satisfied:!1};let l=await a(o,n,t,this.db??null,{skipInstall:s?.skipInstall===!0});return{satisfied:l.noProtocol?!0:l.satisfied}},electDefault:async(n,s)=>{await this.electProviderDefault(n,s,r)},isProviderRegistered:(n,s)=>r.serviceRegistry.listProvidersForType(n).some((a)=>a.pluginName===s),skipInstall:()=>process.env.VIBE_SKIP_PREREQ_INSTALL==="1"}}attachPluginsFacade(t,r){return new Proxy(t,{get(i,n,s){if(n==="plugins")return r;return Reflect.get(i,n,s)}})}async loadAndStartProvider(t,r,i,n){let s=this.loaded.get(t);if(!s)s=await this.importPlugin(t);if(s.createRoutes&&n?.(s))e().logger.info("plugin-manager",`${t}: mounted routes after provisioning`);this.registerPluginProviders(s,i);let a=this.wrapHostServices(s,i);if(s.onServerStart)await s.onServerStart(r,a);if(s.onServerReady)await s.onServerReady(r,a)}async electProviderDefault(t,r,i){if(!i.serviceRegistry.listProvidersForType(t).some((s)=>s.pluginName===r))return;try{let s=await this.getDefaultProvider(t);if(s&&s!==r)return;if(i.serviceRegistry.setProviderDefault(t,r),!s)await this.setDefaultProvider(t,r).catch(()=>{});e().logger.info("plugin-manager",`Elected platform-default '${t}' provider '${r}'`)}catch(s){e().logger.warn("plugin-manager",`Failed to elect default '${t}' provider '${r}': ${s}`)}}async dispatchServerStop(t){for(let r of this.getAllPlugins())if(r.onServerStop)try{await r.onServerStop(t)}catch(i){e().logger.warn("plugin-manager",`onServerStop failed for ${r.name}: ${i}`)}if(t?.reason==="shutdown")await this.terminateAllWorkerHosts()}async runPluginNuke(t,r,i){let n=t?this.loaded.has(t)?[[t,this.loaded.get(t)]]:[]:Array.from(this.loaded.entries()),s=[];for(let[a,o]of n){if(!o.onNuke)continue;try{let l=this.wrapHostServices(o,r),g=await o.onNuke(l,i);s.push({plugin:a,ok:!0,reaped:g?.reaped??[],notes:g?.notes??[]}),e().logger.info("plugin-manager",`onNuke ${i.dryRun?"(dry-run) ":""}completed for ${a}`,{reaped:g?.reaped??[]})}catch(l){let g=l instanceof Error?l.message:String(l);s.push({plugin:a,ok:!1,reaped:[],notes:[],error:g}),e().logger.warn("plugin-manager",`onNuke failed for ${a}: ${g}`)}}return{results:s}}async reloadAll(t,r){await this.dispatchServerStop({reason:"reload"}),await this.terminateAllWorkerHosts();for(let i of this.loaded.values())r.serviceRegistry.unregisterPlugin(i.name);this.loaded.clear(),this.corePlugins.clear(),this.loadRegistry(),await this.loadCorePlugins(),await this.loadAll(),await this.dispatchServerStart(t,r),await this.dispatchServerReady(t,r)}sortAllByDependencies(){let t=this.getAllPlugins(),r=new Map;for(let o of t)r.set(o.name,o);let i=new Set,n=new Set,s=[],a=(o)=>{if(i.has(o))return;if(n.has(o))throw Error(`Plugin dependency cycle detected at '${o}'`);let l=r.get(o);if(!l)return;if(n.add(o),l.dependencies)for(let g of l.dependencies){if(!r.has(g)){e().logger.warn("plugin-manager",`Plugin '${l.name}' depends on missing plugin '${g}'`);continue}a(g)}n.delete(o),i.add(o),s.push(l)};for(let o of t)a(o.name);return s}sortByDependencies(){let t=Array.from(this.loaded.entries()),r=new Map;for(let[a,o]of t)r.set(o.name,a);let i=new Set,n=[],s=(a)=>{if(i.has(a))return;i.add(a);let o=this.loaded.get(a);if(o?.dependencies)for(let g of o.dependencies){let u=r.get(g);if(u&&this.loaded.has(u))s(u)}let l=this.loaded.get(a);if(l)n.push([a,l])};for(let[a]of t)s(a);return n}getPluginByKey(t){for(let[,r]of this.loaded)if(r.name===t)return r;return this.corePlugins.get(t)}getAllPlugins(){let t=new Map;for(let[r,i]of this.corePlugins)t.set(r,i);for(let[,r]of this.loaded)t.set(r.name,r);return Array.from(t.values())}getAllPluginsByTag(t){return this.getAllPlugins().filter((r)=>r.tags?.includes(t)??!1)}resolvePluginChain(t){let r=new Set;for(let s of this.getAllPlugins())r.add(s.name);let i=[],n=-1;for(let s=0;s<t.length;s++){if(t[s].startsWith("-")){n=s;break}if(r.has(t[s]))i.push(t[s]);else{n=s;break}}if(n===-1)return{chain:i,command:"",args:[]};return{chain:i,command:t[n],args:t.slice(n+1)}}async getDefaultProvider(t){if(!this.db)return null;return await this.db.getConfig(`${J}${t}`)??null}async setDefaultProvider(t,r){if(!this.db)throw Error("Cannot set default provider: PluginManager was constructed without a database reference");if(!this.getPluginByKey(r))throw Error(`Plugin '${r}' not found`);await this.db.setConfig(`${J}${t}`,r),e().logger.info("plugin-manager",`Set default '${t}' provider to '${r}'`)}getPluginDetails(){let t=this.getCorePluginDetails(),r=this.getExternalPluginDetails(),i=new Map;for(let n of t)i.set(n.pluginName,n);for(let n of r)i.set(n.pluginName,n);return Array.from(i.values())}getCorePluginDetails(){let t=[];for(let[r,i]of this.corePlugins)t.push({packageName:`@vibecontrols/plugin-${r}`,pluginName:r,version:i.version,description:i.description,tags:i.tags,cliCommand:i.cliCommand,apiPrefix:i.apiPrefix,dependencies:i.dependencies,installedAt:"",loaded:!0,isCore:!0,hasUI:!!i.ui,uiUrl:i.ui?`/ui/${r}`:void 0,hasCliSetup:!!i.onCliSetup,hasServerStart:!!i.onServerStart,hasServerStop:!!i.onServerStop,hasServerReady:!!i.onServerReady,hasProviders:!!(i.providers?.tunnel||i.providers?.session||i.providers?.ai)});return t}getExternalPluginDetails(){return this.registry.map((t)=>{let r=this.loaded.get(t.packageName),i=q(t.pluginName);return{packageName:t.packageName,pluginName:t.pluginName,version:r?.version??t.version,description:r?.description,tags:r?.tags,cliCommand:r?.cliCommand,apiPrefix:r?.apiPrefix,dependencies:r?.dependencies,installedAt:t.installedAt,loaded:!!r,isCore:i?.isCore===!0,hasUI:!!r?.ui,uiUrl:r?.ui?`/ui/${t.pluginName}`:void 0,hasCliSetup:!!r?.onCliSetup,hasServerStart:!!r?.onServerStart,hasServerStop:!!r?.onServerStop,hasServerReady:!!r?.onServerReady,hasProviders:!!(r?.providers?.tunnel||r?.providers?.session||r?.providers?.ai)}})}getRegistry(){return[...this.registry]}getLoaded(t){return this.loaded.get(t)}getAllLoaded(){return new Map(this.loaded)}isInstalled(t){return this.registry.some((r)=>r.packageName===t)}isLoaded(t){return this.loaded.has(t)}}
|
|
2
|
+
import{Ht,I,se,N,e}from"./index-0qjbnyg4.js";import{b}from"./index-w4jqdhc2.js";import{existsSync as y,mkdirSync as F,readdirSync as ve,readFileSync as x,renameSync as Pe,realpathSync as B,rmSync as h,statSync as we,writeFileSync as M}from"fs";import{homedir as Se}from"os";import{dirname as S,isAbsolute as be,join as p,relative as ke,sep as j}from"path";import{fileURLToPath as L}from"url";import{existsSync as X,readFileSync as ee}from"fs";import{dirname as E,join as te}from"path";import{fileURLToPath as re}from"url";var ne="@vibecontrols/agent",P;function _e(){if(P)return P;try{let t=E(re(import.meta.url));for(let r=0;r<10&&t&&t!==E(t);r++){let i=te(t,"package.json");if(X(i))try{let n=JSON.parse(ee(i,"utf8"));if(n.name===ne&&typeof n.version==="string")return P=n.version,P}catch{}t=E(t)}}catch{}return P??"0.0.0"}function _(){let t=process.env.VIBECONTROLS_PLUGIN_CONTRACT_V2_ENFORCE;return t==="1"||t==="true"||t==="on"}var D={storage:"rw",secrets:"rw",gateway:!0,broadcast:!0,subprocess:!0,audit:!0,telemetry:!0,singletonOnly:!1,requiresIsolation:!1},O={storage:"none",secrets:"none",gateway:!1,broadcast:!1,subprocess:!1,audit:!1,telemetry:!1,singletonOnly:!1,requiresIsolation:!1};function V(){let t=process.env.VIBECONTROLS_STRICT_PLUGIN_CAPS;return t==="1"||t==="true"||t==="on"}function H(t,r,i,n,s=!1){return new Proxy(t,{get(a,o,l){if(o==="plugins"){if(!s)return;return Reflect.get(a,o,l)}if(o==="storage")return oe(a.storage,i.storage??"none",r,n);if(o==="broadcast"&&!i.broadcast)return w(r,"broadcast",n);if(o==="workspaceQuery"&&!i.gateway)return w(r,"workspaceQuery",n);if(o==="getAgentRecordId"&&!i.gateway)return w(r,"getAgentRecordId",n);if(o==="getWorkspaceId"&&!i.gateway)return w(r,"getWorkspaceId",n);if(o==="iframeBridge"&&!s){let g=Reflect.get(a,o,l);if(!g)return g;return{...g,getAgentApiKey:w(r,"iframeBridge.getAgentApiKey",n)}}if(o==="telemetry"){if(!i.telemetry)return;return Reflect.get(a,o,l)}return Reflect.get(a,o,l)}})}function oe(t,r,i,n){if(r==="rw")return t;return new Proxy(t,{get(s,a,o){let l=String(a),g=l==="set"||l==="delete"||l==="deleteAll";if(r==="none"||r==="read"&&g)return(...d)=>{throw n("plugin.capability.denied",{pluginName:i,surface:"storage",op:l,mode:r}),Error(`plugin '${i}' lacks storage:${g?"rw":"read"} capability (op=${l})`)};return Reflect.get(s,a,o)}})}function w(t,r,i){return(...n)=>{throw i("plugin.capability.denied",{pluginName:t,op:r}),Error(`plugin '${t}' lacks capability for ${r}`)}}import{Worker as ae}from"worker_threads";import{fileURLToPath as ge}from"url";import{randomUUID as ue}from"crypto";function ce(){let t=ge(import.meta.url),r=t.lastIndexOf("/"),i=r>=0?t.slice(0,r):t,n=`${i}/plugin-worker-runtime.ts`,s=`${i}/plugin-worker-runtime.js`;if(t.endsWith(".ts"))return n;return s}class R{worker;pending=new Map;spec;initPromise;terminated=!1;constructor(t){this.spec=t}async start(){if(this.initPromise)return this.initPromise;return this.initPromise=this.spawn(),this.initPromise}async spawn(){let t=this.spec.runtimeEntry??ce(),r=["PATH","HOME","USERPROFILE","TMPDIR","TMP","TEMP","LANG","LC_ALL","LC_CTYPE","TZ","SystemRoot","SystemDrive","ComSpec","PATHEXT","windir"],i={};for(let s of r){let a=process.env[s];if(typeof a==="string")i[s]=a}let n=new ae(t,{env:i});this.worker=n,n.on("message",(s)=>this.onMessage(s)),n.on("error",(s)=>this.onWorkerError(s instanceof Error?s:Error(String(s)))),n.on("exit",(s)=>this.onWorkerExit(s)),await this.call("init",{modulePath:this.spec.modulePath,ctxStub:{name:this.spec.ctx.name,dataDir:this.spec.ctx.dataDir}})}async dispatch(t,r=[]){if(this.terminated)throw Error("PluginWorkerHost terminated");if(!this.worker)await this.start();return this.call("dispatch",{method:t,params:r})}call(t,r){if(!this.worker)return Promise.reject(Error("worker not spawned"));let i=ue();return new Promise((n,s)=>{this.pending.set(i,{resolve:n,reject:s});try{this.worker?.postMessage({id:i,op:t,args:r})}catch(a){this.pending.delete(i),s(a instanceof Error?a:Error(String(a)))}})}onMessage(t){let r=this.pending.get(t.id);if(!r)return;if(this.pending.delete(t.id),t.ok)r.resolve(t.result);else{let i=Error(t.error?.message??"worker error");if(t.error?.stack)i.stack=t.error.stack;r.reject(i)}}onWorkerError(t){for(let[,r]of this.pending)r.reject(t);this.pending.clear()}onWorkerExit(t){if(this.pending.size>0){let r=Error(`worker exited (code=${t}) with pending calls`);for(let[,i]of this.pending)i.reject(r);this.pending.clear()}this.terminated=!0}async terminate(){if(this.terminated=!0,!this.worker)return;try{await this.worker.terminate()}catch{}this.worker=void 0}}var de=[{packageName:"@vibecontrols/vibe-plugin-storage",pluginName:"storage",label:"Storage facade",description:"Storage provider registry \u2014 owns AgentDatabase contract. Bundled with the agent; the storage meta lazy-loads the configured provider by name.",category:"storage",trusted:!0,isCore:!0,isDefault:!0,isCritical:!0,removable:!1,integrity:"sha512-E0agrBuSwO7R5z7dBA6Jb0Mq5zibhkFzvEh0lcb4N+byt25yStrDcsJqJ3bJpVdavw/OkAjB+MAC06zkTtHraQ=="},...["agent","task","config","git","plugin-mgr","log"].map((t)=>({packageName:`@vibecontrols/vibe-plugin-${t}`,pluginName:t,label:`${t} (built-in)`,description:`Built-in ${t} plugin bundled with the agent.`,category:"core",trusted:!0,isCore:!0,removable:!1}))],pe=[{packageName:"@vibecontrols/vibe-plugin-tunnel",pluginName:"tunnel",label:"Tunnel manager",description:"Owns TunnelProvider interface. Routes to a registered tunnel provider.",category:"tunnel",trusted:!0,isDefault:!0,isCritical:!0,cliCommand:"tunnel",apiPrefix:"/api/tunnel",integrity:"sha512-FFqJjvPNCAYZwMjOKt1vHiBuzd+6W9sYI6vZqls7kr3Za+m++tIueT9OV2DlpAJT8XU+fidrgsWgQi8AcjPHWQ=="},{packageName:"@vibecontrols/vibe-plugin-session-manager",pluginName:"session-manager",label:"Session manager",description:"Owns SessionProvider interface. Routes to a registered session backend.",category:"session",trusted:!0,isCore:!0,isDefault:!0,isCritical:!0,cliCommand:"session",apiPrefix:"/api/sessions",integrity:"sha512-1841STCBKRDc0h0BFgcZ3ZJydThKUkHKtDdnC2YMZOiSYVB4N/+7fJQhyMSq3bc6zj/FO7jBne9Gmg+PLoXiQA=="},{packageName:"@vibecontrols/vibe-plugin-ai",pluginName:"ai",label:"AI orchestration",description:"Owns AIAgentProvider interface. Prompts, contexts, sessions, dispatch, logs.",category:"ai",trusted:!0,isDefault:!0,isCritical:!0,cliCommand:"ai",apiPrefix:"/api/ai",integrity:"sha512-mIkzkzMDU38ILFa2lRsjeaJqAidtlUBWoQ3KaFxkpG88AHWUtcA6Vha/wZQ5Ns16h0g4vRKxtbOLfFSTEgRerA=="},{packageName:"@vibecontrols/vibe-plugin-plan",pluginName:"plan",label:"Plan orchestration",description:"Owns PlanProvider interface. Routes plan sessions to a registered provider.",category:"plan",trusted:!0,isDefault:!1,cliCommand:"plan",apiPrefix:"/api/plan",integrity:"sha512-SSCFLFkmAhHesLYgETeEyAZs2Gu8tDEaMMuJtMMKG5eKGQIXYJaJZnQBuXP/vKOAlLd//l8es5hPqhmiNSi4Gw=="},{packageName:"@vibecontrols/vibe-plugin-gitops",pluginName:"gitops",label:"GitOps orchestrator",description:"Owns GitOpsProvider interface. Routes repo / PR / CI / security queries to a registered provider.",category:"gitops",trusted:!0,isDefault:!1,cliCommand:"gitops",apiPrefix:"/api/gitops",integrity:"sha512-KzoSmBDgQ5mbSFxAuIyIBnC/HKwYhtXluGp06DvzQmwqOQ4vEC72PuSiVx3doWrt+Z6fZ6i6gxNzmYNpdhPLXA=="},{packageName:"@vibecontrols/vibe-plugin-security",pluginName:"security",label:"Security lifecycle",description:"Security lifecycle orchestrator \u2014 owns /api/security and dispatches to per-stage providers.",category:"security",trusted:!0,isDefault:!1,cliCommand:"security",apiPrefix:"/api/security",integrity:"sha512-K6w3tC7qnCotvnNWWdmHnjqGgCNJoPNMs8gCwWFbcNI5MmbIrUQfFQdcjwGudwryvN2+TrX12MhfhWz4p1qcMA=="},{packageName:"@vibecontrols/vibe-plugin-desk",pluginName:"desk",label:"Steward desk",description:"Owns the desk provider routing. Lets a BotManor Steward use this machine's browser or desktop, with remote control off until the owner turns it on.",category:"desk",trusted:!1,isDefault:!1,apiPrefix:"/api/desk",integrity:"sha512-5LHgI8OzBOZxFIE1PgL05sf2QYdd0qCA5fSu4Km9rt41sMjDvqcNQaWDo7hyYalqE/vY6LCJzrQ6xs47Vlx2Xw=="}],fe=[{packageName:"@vibecontrols/vibe-plugin-tool-code-server",pluginName:"code-server",label:"Browser code editor",description:"Browser-based VS Code via code-server \u2014 open any Vibe in an in-browser editor.",category:"tool",trusted:!0,isDefault:!1,cliCommand:"code-server",apiPrefix:"/api/code-server"}],me=[{packageName:"@vibecontrols/vibe-plugin-agent-backup",pluginName:"agent-backup",label:"Agent backup",description:"Backup and restore agent state.",category:"agent",trusted:!0,isDefault:!0,integrity:"sha512-KhN2Vaahtnl4IKRbaHKtlEbsuvW9dbgC2l4kkIXcme55DaSmLy5kYkiysnwyZdC4PRQu4NKM4GQLoW9hD86dRw=="}],ie=[...de,...pe,...fe,...me],Y=[{key:"storage",label:"Storage",description:"Encrypted local state for the agent.",categories:["storage"],mandatory:!0,defaultSelected:!0},{key:"tunnel",label:"Tunnels",description:"Expose the agent for remote access + share links.",categories:["tunnel"],mandatory:!0,defaultSelected:!0},{key:"backup",label:"Backup",description:"Backup + restore agent state.",categories:["agent"],mandatory:!0,defaultSelected:!0},{key:"session",label:"Terminal sessions",description:"Long-lived terminal / AI agent sessions.",categories:["session"],mandatory:!1,defaultSelected:!0},{key:"editor",label:"Browser code editor",description:"Open any Vibe in an in-browser VS Code editor (code-server).",categories:["tool"],mandatory:!1,defaultSelected:!0},{key:"ai",label:"AI orchestration",description:"AI agent harnesses, prompts + dispatch.",categories:["ai"],mandatory:!1,defaultSelected:!0},{key:"plan",label:"Plan review",description:"Review / approve AI-proposed plans.",categories:["plan"],mandatory:!1,defaultSelected:!1},{key:"gitops",label:"GitOps",description:"Repo / PR / CI / security integration.",categories:["gitops"],mandatory:!1,defaultSelected:!1},{key:"security",label:"Security",description:"Security scanning lifecycle.",categories:["security"],mandatory:!1,defaultSelected:!1}],C=ie.filter((t)=>t.isCore&&t.category==="core").map((t)=>t.pluginName),U=ie.filter((t)=>t.isDefault===!0);function A(t){return U}function ye(t,r){let i=r instanceof Set?r:new Set(r),n=new Set;for(let s of Y)if(s.mandatory||i.has(s.key))for(let a of s.categories)n.add(a);return ie.filter((s)=>n.has(s.category))}var G=new Set(ie.filter((t)=>t.trusted).map((t)=>t.packageName));function he(){let t=ie.filter((i)=>i.isCritical).flatMap((i)=>[i.packageName,i.pluginName]),r=process.env.VIBECONTROLS_CRITICAL_PLUGINS;if(r){let i=r.split(",").map((n)=>n.trim()).filter(Boolean);return new Set([...t,...i])}return new Set(t)}function ht(t){return he().has(t)}var bi=ie.filter((t)=>!t.isCore||t.category!=="core");function wi(t){return ie.find((r)=>r.packageName===t)}function qi(t){return new Set}function ft(t){return t.startsWith("@vibecontrols/vibe-plugin-")||G.has(t)}function Pr(t){let r=t.trim();if(!r)return;if(r.startsWith("@vibecontrols/"))return ie.find((n)=>n.packageName===r);if(r.startsWith("vibe-plugin-"))return ie.find((n)=>n.packageName===`@vibecontrols/${r}`);let i=ie.find((n)=>n.pluginName===r);if(i)return i;return ie.find((n)=>n.packageName===`@vibecontrols/vibe-plugin-${r}`)}function Mt(t){let r=t.trim();if(!r)return;let i=Pr(r);if(i)return i.packageName;if(r.startsWith("@vibecontrols/"))return r;if(r.startsWith("vibe-plugin-"))return`@vibecontrols/${r}`;return`@vibecontrols/vibe-plugin-${r}`}function q(t){return ie.find((r)=>r.pluginName===t)}function Ee(t){return ie.find((r)=>r.packageName===t)}function Re(t,r){if(t.length!==r.length)return!1;let i=0;for(let n=0;n<t.length;n++)i|=t.charCodeAt(n)^r.charCodeAt(n);return i===0}async function Ce(t,r,i){let n=Ee(t),s=process.env.VIBECONTROLS_REQUIRE_PLUGIN_INTEGRITY==="1";if(!n?.integrity){if(s)throw Error(`Refusing to install ${t}: catalog has no pinned integrity and VIBECONTROLS_REQUIRE_PLUGIN_INTEGRITY=1`);return}let a=i,o;try{let g=`${r.replace(/\/+$/,"")}/${t.replace("/","%2F")}`,u=await fetch(g,{headers:{accept:"application/json"},signal:AbortSignal.timeout(20000)});if(!u.ok)throw Error(`registry packument fetch failed (HTTP ${u.status})`);let d=await u.json();if(a=a??d["dist-tags"]?.latest,!a)throw Error("could not resolve version from registry");if(o=d.versions?.[a]?.dist?.integrity,typeof o!=="string"||o.length===0)throw Error(`registry did not return dist.integrity for ${t}@${a}`)}catch(l){let g=l instanceof Error?l.message:String(l);throw Error(`Pre-install integrity gate refused ${t}: ${g}`,{cause:l})}if(!Re(n.integrity,o)){let l=process.env.VIBECONTROLS_STRICT_PLUGIN_INTEGRITY==="1";if(ft(t)&&!l){e().logger.warn("plugin-manager",`Integrity pin for ${t} is stale \u2014 catalog expects ${n.integrity}, the allowlisted registry has ${o} for ${a}. Proceeding (first-party package, registry allowlisted). Re-pin plugins.config.ts to silence this.`);return}throw Error(`Pre-install integrity gate refused ${t}: integrity mismatch for ${a}: expected ${n.integrity}, got ${o}`)}}var $e=["https://registry.npmjs.org/","https://registry.npmjs.org"];function Ae(){let t=process.env.VIBECONTROLS_REGISTRY_ALLOWLIST,r=[...$e];if(typeof t==="string"&&t.length>0)for(let i of t.split(",").map((n)=>n.trim()).filter(Boolean))r.push(i);return r}function Ie(t){let r=Ae(),i;try{i=new URL(t).origin}catch{throw Error(`Invalid plugin registry URL: ${t}`)}for(let n of r)try{if(new URL(n).origin===i)return}catch{}throw Error(`Plugin registry '${t}' is not in the allow-list. Add it to VIBECONTROLS_REGISTRY_ALLOWLIST at daemon start.`)}var K="plugins.json",xe=/^@vibecontrols\/vibe-plugin-[a-z0-9][a-z0-9-]{0,80}$/,z=/^[a-z0-9][a-z0-9-]{0,63}$/,Le=/^\/api\/[A-Za-z0-9][A-Za-z0-9/_-]{0,127}$/,Te=/^\/[A-Za-z0-9][A-Za-z0-9/_-]{0,159}$/,Q=Symbol.for("vibecontrols.pluginPackageRoot");function Mr(t){return t[Q]}function le(t){let r=t.trim();if(!xe.test(r))throw Error("Plugin package must be a @vibecontrols/vibe-plugin-* package name.");if(!ft(r)&&process.env.VIBECONTROLS_ALLOW_UNTRUSTED_PLUGINS!=="1")throw Error("Plugin package is not in the trusted VibeControls catalog.");return r}function Ne(t,r){let i=ke(t,r);return i===""||!!i&&!i.startsWith("..")&&!be(i)}function Z(){return p(I(),"agent-plugins","node_modules")}function De(){try{let t=Z();return y(t)&&ve(t).length>0}catch{return!1}}function T(){let t=(process.env.VIBECONTROLS_PLUGIN_INSTALL_SCOPE??process.env.VIBECONTROLS_PLUGIN_INSTALL_MODE??"").toLowerCase();if(t==="local")return"local";if(t==="global")return"global";return De()?"local":"global"}var J="provider:default:";function Oe(t){if(!t||typeof t!=="object")return!1;let r=t;return typeof r.packageName==="string"&&typeof r.version==="string"&&typeof r.pluginName==="string"&&typeof r.installedAt==="string"}class W{registry=[];loaded=new Map;corePlugins=new Map;db;forcedIsolation=new Set;workerHosts=new Map;lifecycleChain=Promise.resolve();withLifecycleLock(t){let i=this.lifecycleChain.then(t,t);return this.lifecycleChain=i.then(()=>{return},()=>{return}),i}async terminateWorkerHost(t){let r=this.workerHosts.get(t);if(!r)return;try{await r.terminate()}catch(i){e().logger.warn("plugin-manager",`Failed to terminate worker for '${t}': ${i instanceof Error?i.message:String(i)}`)}finally{this.workerHosts.delete(t)}}async terminateAllWorkerHosts(){let t=Array.from(this.workerHosts.keys());await Promise.all(t.map((r)=>this.terminateWorkerHost(r)))}constructor(t){this.db=t,this.ensureDir(),this.loadRegistry();let r=process.env.VIBE_ISOLATE_PLUGINS;if(typeof r==="string"&&r.length>0)this.setForcedIsolation(r.split(",").map((i)=>i.trim()).filter((i)=>i.length>0))}setForcedIsolation(t){this.forcedIsolation=new Set(t.filter((r)=>r.length>0))}shouldIsolate(t){if(this.forcedIsolation.has(t.name))return!0;return t.capabilities?.requiresIsolation===!0}getWorkerHost(t){return this.workerHosts.get(t)}registerWorkerHost(t,r){this.workerHosts.set(t,r)}auditSink=(t,r)=>{e().logger.warn("plugin-capability",t,r)};static resolveEffectiveCapabilities(t,r){if(t.capabilities)return t.capabilities;return r?D:O}hostServicesFor(t,r){return this.wrapHostServices(t,r)}wrapHostServices(t,r){let i=this.corePlugins.has(t.name),n=W.resolveEffectiveCapabilities(t,i),s=i||this.isTrustedLoadedPlugin(t);return H(r,t.name,n,this.auditSink,s)}routeDepsFor(t,r){if(this.corePlugins.has(t.name)||this.isTrustedLoadedPlugin(t))return r;let n=W.resolveEffectiveCapabilities(t,!1),s=r.hostServices?this.wrapHostServices(t,r.hostServices):void 0,a=this.auditSink,o=(l)=>{throw a("plugin.capability.denied",{plugin:t.name,capability:`routeDeps.${l}`}),Error(`Plugin '${t.name}' may not use routeDeps.${l}: untrusted plugins receive only capability-scoped host services`)};return new Proxy({},{get(l,g){if(g==="hostServices")return s;if(g==="broadcast")return n.broadcast?r.broadcast:()=>o("broadcast");if(typeof g==="string")return o(g);return}})}isTrustedLoadedPlugin(t){for(let[r,i]of this.loaded)if(i===t)return ft(r);return!1}acceptCapabilities(t,r){if(t.capabilities?.singletonOnly===!0&&N.size()>1)return e().logger.error("plugin-manager",`[plugin] '${t.name}' refused to load: singletonOnly capability incompatible with multi-profile daemon (profiles=${N.size()}, source=${r})`),!1;if(t.capabilities)return!0;if(V())return e().logger.error("plugin-manager",`[plugin] '${t.name}' refused to load: missing required capabilities declaration (source=${r})`),!1;if(r.startsWith("core:"))e().logger.warn("plugin-manager",`[plugin] '${t.name}' loaded without a capabilities declaration \u2014 granting full trust (core plugin). Declare capabilities explicitly. (source=${r})`);else e().logger.warn("plugin-manager",`[plugin] '${t.name}' loaded without a capabilities declaration \u2014 defaulting to EMPTY capability set (deny by default). External plugins MUST declare capabilities explicitly to access host services. (source=${r})`);return!0}ensureDir(){let t=I();if(!y(t))F(t,{recursive:!0})}loadRegistry(){let t=p(I(),K);try{if(y(t)){let r=x(t,"utf-8"),i=JSON.parse(r);if(Array.isArray(i)&&i.every(Oe))this.registry=i.filter((n)=>{try{return le(n.packageName),!0}catch(s){return e().logger.warn("plugin-manager","Ignoring invalid plugin entry",{packageName:n.packageName,error:String(s)}),!1}});else throw Error("plugins.json has an invalid schema")}}catch(r){e().logger.warn("plugin-manager","Failed to load plugin registry",{path:t,error:String(r)}),this.registry=[]}}saveRegistry(){this.ensureDir();let t=p(I(),K),r=`${t}.${process.pid}.tmp`;M(r,`${JSON.stringify(this.registry,null,2)}
|
|
3
|
+
`,{encoding:"utf-8",mode:384}),Pe(r,t)}async loadCorePlugins(){let t=await Promise.allSettled([import("./index-thm1bzpj.js"),import("./index-t6p4szqx.js"),import("./index-hsrt2v87.js"),import("./index-xtd0j8ve.js"),import("./index-x83tcr8f.js"),import("./index-7gk1x74m.js")]),r=e();for(let i=0;i<t.length;i++){let n=t[i],s=C[i];if(n.status==="fulfilled"){let a=n.value,o;try{o=this.extractPlugin(a,`core:${s}`,r)}catch(l){e().logger.error("plugin-manager",`Core plugin '${s}' refused to load: ${l instanceof Error?l.message:String(l)}`);continue}if(o?.name){if(!this.acceptCapabilities(o,`core:${s}`))continue;this.corePlugins.set(o.name,o),e().logger.info("plugin-manager",`Core plugin loaded: ${o.name} v${o.version}`)}else e().logger.warn("plugin-manager",`Core plugin '${s}' did not export a valid createPlugin(ctx) factory`)}else e().logger.warn("plugin-manager",`Failed to load core plugin '${s}': ${n.reason}`)}e().logger.info("plugin-manager",`Core plugins loaded: ${this.corePlugins.size}/${C.length}`)}async resolveConcreteLatest(t,r){try{let n=`${r.replace(/\/+$/,"")}/${t.replace("/","%2F")}`,s=await fetch(n,{headers:{accept:"application/json"},signal:AbortSignal.timeout(20000)});if(!s.ok)return;let o=(await s.json())["dist-tags"]?.latest;if(typeof o==="string"&&/^\d+\.\d+\.\d+/.test(o))return o}catch{}return}async install(t,r={}){return this.withLifecycleLock(()=>this.installLocked(t,r))}async installLocked(t,r={}){t=le(t);let i=r.version?.trim()||void 0,n=r.refreshLatest===!0||!!i;e().logger.info("plugin-manager",`Installing ${t}${n?"@latest (refresh)":""}...`);let s=se();if(Ie(s),await Ce(t,s,void 0),!n)try{await import(t),e().logger.info("plugin-manager",`${t} already resolvable \u2014 skipping global install`);let c=await this.importPlugin(t),f={packageName:t,version:c.version,pluginName:c.name,installedAt:new Date().toISOString()};return this.registry=this.registry.filter((v)=>v.packageName!==t),this.registry.push(f),this.saveRegistry(),f}catch{}let a=se(),o=T(),l=i?i:n?await this.resolveConcreteLatest(t,a):void 0,g=n?`${t}@${l??"latest"}`:t;try{if(o==="local"){let c=p(I(),"agent-plugins");if(!y(c))F(c,{recursive:!0});let f=p(c,"package.json");if(!y(f))M(f,JSON.stringify({name:"vibecontrols-agent-plugins",private:!0,version:"0.0.0",dependencies:{}},null,2)+`
|
|
4
|
+
`);if(n&&l){let m=this.readInstalledVersion(p(c,"node_modules"),t);if(m&&m!==l){e().logger.info("plugin-manager",`Pre-clean ${t}: on-disk v${m} != target v${l} \u2014 removing stale copy + lockfile to force fresh resolve`);try{h(p(c,"node_modules",t),{recursive:!0,force:!0})}catch{}try{h(p(c,"bun.lock"),{force:!0}),h(p(c,"bun.lockb"),{force:!0})}catch{}}try{h(p(c,"bun.lock"),{force:!0}),h(p(c,"bun.lockb"),{force:!0})}catch{}}if(Bun.spawnSync(["bun","add",g,"--registry",a],{cwd:c,timeout:120000,stdout:"pipe",stderr:"pipe"}).exitCode!==0){let m=Bun.spawnSync(["npm","install",g,"--registry",a],{cwd:c,timeout:120000,stdout:"pipe",stderr:"pipe"});if(m.exitCode!==0)throw Error(m.stderr.toString().trim())}if(n&&l){let m=this.readInstalledVersion(p(c,"node_modules"),t);if(m!==l){e().logger.warn("plugin-manager",`bun kept ${t}@${m??"missing"} after requesting ${l}; retrying with npm after removing stale local copy`);try{h(p(c,"node_modules",t),{recursive:!0,force:!0}),h(p(c,"bun.lock"),{force:!0}),h(p(c,"bun.lockb"),{force:!0}),h(p(c,"package-lock.json"),{force:!0})}catch{}let k=Bun.spawnSync(["npm","install",g,"--registry",a,"--save-exact"],{cwd:c,timeout:120000,stdout:"pipe",stderr:"pipe"});if(k.exitCode!==0)throw Error(k.stderr.toString().trim())}}}else if(Bun.spawnSync(["bun","install","-g",g,"--registry",a],{timeout:120000,stdout:"pipe",stderr:"pipe"}).exitCode!==0){let f=Bun.spawnSync(["npm","install","-g",g,"--registry",a],{timeout:120000,stdout:"pipe",stderr:"pipe"});if(f.exitCode!==0)throw Error(f.stderr.toString().trim())}this.pluginRoots=void 0}catch(c){let f=c instanceof Error?c.message:String(c);if(n)try{await import(t),e().logger.warn("plugin-manager",`Could not refresh ${t} to @latest (${f}); using the already-installed copy`),this.pluginRoots=void 0;let v=await this.importPlugin(t),m={packageName:t,version:v.version,pluginName:v.name,installedAt:new Date().toISOString()};return this.registry=this.registry.filter((k)=>k.packageName!==t),this.registry.push(m),this.saveRegistry(),m}catch{}throw Error(`Failed to install ${t}: ${f}`,{cause:c})}let u=await this.importPlugin(t);if(n&&l&&u.version!==l)e().logger.warn("plugin-manager",`${t} refreshed to ${u.version} but registry latest is ${l} \u2014 a stale resolver/cache may still be in play`);if(this.corePlugins.has(u.name))e().logger.info("plugin-manager",`External plugin '${t}' overrides core plugin '${u.name}'`);let d={packageName:t,version:u.version,pluginName:u.name,installedAt:new Date().toISOString()};return this.registry=this.registry.filter((c)=>c.packageName!==t),this.registry.push(d),this.saveRegistry(),e().logger.info("plugin-manager",`Installed ${t}@${u.version} (${u.name})`),d}async ensureDefaultPlugins(t,r=[],i){let n=[],s=new Set(r),a=i?ye(process.platform,i):A(process.platform);for(let o of a){if(s.has(o.packageName)||s.has(o.pluginName)){e().logger.info("plugin-manager",`${o.packageName} skipped by --skip-plugin`);continue}if(o.isCore&&o.category==="core"){e().logger.info("plugin-manager",`${o.packageName} is bundled with the agent \u2014 skipping auto-install`);continue}if(this.registry.some((g)=>g.packageName===o.packageName)){e().logger.info("plugin-manager",`${o.packageName} already installed, skipping auto-install`);continue}t?.(`Installing ${o.label} (${o.packageName})...`);try{await this.install(o.packageName,{refreshLatest:!0}),n.push(o),t?.(`Installed ${o.label} (${o.packageName})`)}catch(g){let u=g instanceof Error?g.message:String(g);e().logger.error("plugin-manager",`Failed to auto-install ${o.packageName}: ${u}`),t?.(`Failed to install ${o.label}: ${u}`)}}if(n.length>0)this.loadRegistry();return n}async installAndLoad(t,r,i){let n=await this.install(t),s=this.loaded.get(n.packageName);if(s){this.registerPluginProviders(s,i);let a=this.wrapHostServices(s,i);if(s.onServerStart)await s.onServerStart(r,a);if(s.onServerReady)await s.onServerReady(r,a)}return n}async update(t,r){return this.withLifecycleLock(()=>this.updateLocked(t,r))}async updateLocked(t,r){if(t=le(t),e().logger.info("plugin-manager",`Updating ${t}${r?`@${r}`:""}...`),!this.registry.find((a)=>a.packageName===t))throw Error(`Plugin ${t} is not installed. Use 'install' first.`);let n=this.loaded.get(t);if(n)await this.terminateWorkerHost(n.name);this.loaded.delete(t);let s=await this.installLocked(t,{refreshLatest:!0,version:r});return e().logger.info("plugin-manager",`Updated ${t} to v${s.version}`),s}async updateAll(){let t=[];for(let r of[...this.registry])try{let i=await this.update(r.packageName);t.push({packageName:r.packageName,success:!0,version:i.version})}catch(i){t.push({packageName:r.packageName,success:!1,error:i instanceof Error?i.message:String(i)})}return t}async removeAll(t){let r=[],i=[...this.registry];for(let n of i)try{await this.remove(n.packageName,t),r.push({packageName:n.packageName,success:!0})}catch(s){r.push({packageName:n.packageName,success:!1,error:s instanceof Error?s.message:String(s)})}return r}async remove(t,r){return this.withLifecycleLock(()=>this.removeLocked(t,r))}async removeLocked(t,r){t=le(t),e().logger.info("plugin-manager",`Removing ${t}...`);let i=this.loaded.get(t);if(i?.onServerStop)try{await i.onServerStop()}catch(a){e().logger.warn("plugin-manager",`Error stopping ${t}: ${a}`)}if(i)await this.terminateWorkerHost(i.name),r?.serviceRegistry.unregisterPlugin(i.name),this.loaded.delete(t);let n=this.registry.find((a)=>a.packageName===t);if(!i&&n)r?.serviceRegistry.unregisterPlugin(n.pluginName);let s=p(I(),"agent-plugins");try{if(y(p(s,"package.json")))Bun.spawnSync(["bun","remove",t],{cwd:s,timeout:60000,stdout:"pipe",stderr:"pipe"})}catch{}try{Bun.spawnSync(["bun","remove","-g",t],{timeout:60000,stdout:"pipe",stderr:"pipe"})}catch{try{Bun.spawnSync(["npm","uninstall","-g",t],{timeout:60000,stdout:"pipe",stderr:"pipe"})}catch{}}this.pluginRoots=void 0,this.registry=this.registry.filter((a)=>a.packageName!==t),this.saveRegistry(),e().logger.info("plugin-manager",`Removed ${t}`)}async loadAll(){this.loaded.clear();let t=[];for(let r of this.registry)try{le(r.packageName),await this.importPlugin(r.packageName),e().logger.info("plugin-manager",`Loaded ${r.packageName} (${r.pluginName})`)}catch(i){let n=i.code;if(n==="ENOENT_PLUGIN")e().logger.info("plugin-manager",`${r.packageName} not present on disk \u2014 dropping from registry`),t.push(r.packageName);else if(n==="EPLUGIN_LEGACY_SINGLETON")e().logger.warn("plugin-manager",`Skipping ${r.packageName}: ${i instanceof Error?i.message:String(i)}`);else e().logger.warn("plugin-manager",`Failed to load ${r.packageName} \u2014 dropping from registry: ${i}`),t.push(r.packageName)}if(t.length>0){this.registry=this.registry.filter((r)=>!t.includes(r.packageName));try{this.saveRegistry()}catch(r){e().logger.warn("plugin-manager",`Failed to persist pruned registry: ${r}`)}}}async importPlugin(t){t=le(t);let r={},i;{let s=this.getGlobalRoots(),a=!1,o=[],l=!0;for(let g of s){let u=p(g,t);if(!y(u)){o.push({path:u,error:"directory missing"});continue}l=!1;try{i=u,r=await import(u),a=!0;break}catch(d){o.push({path:u,error:d instanceof Error?d.message:String(d)})}try{let d=p(u,"package.json");if(!y(d)){o.push({path:d,error:"package.json missing"});continue}let c=JSON.parse(x(d,"utf8")),f=c.module??c.main??"./index.js",v=p(u,f);i=u,r=await import(v),a=!0;break}catch(d){o.push({path:u,error:d instanceof Error?d.message:String(d)})}}if(!a)try{i=this.resolvePackageRoot(t)??i,r=await import(t),a=!0}catch(g){o.push({path:`bare:${t}`,error:g instanceof Error?g.message:String(g)})}if(!a){let g=o.map((d)=>`${d.path} (${d.error})`).join("; "),u=Error(`Cannot find module '${t}': explicit root attempts and bare import failed: ${g||"(no roots probed)"}`);if(l&&s.length>0)u.code="ENOENT_PLUGIN";throw u}}let n=this.extractPlugin(r,`external:${t}`,e());if(!n){if(this.hasLegacySingleton(r)){let s=Error(`${t} uses removed singleton contract; upgrade to createPlugin(ctx) factory (set VIBECONTROLS_PLUGIN_CONTRACT_V2_ENFORCE=1 to refuse strictly)`);throw s.code="EPLUGIN_LEGACY_SINGLETON",s}throw Error(`${t} does not export a valid createPlugin(ctx) factory`)}if(this.validatePluginExport(n,t,i),!this.acceptCapabilities(n,`external:${t}`))throw Error(`${t} refused to load: missing required capabilities declaration`);if(i)Object.defineProperty(n,Q,{value:i,enumerable:!1,configurable:!1});if(this.logResolvedPlugin(t,n.version,i),this.loaded.set(t,n),this.shouldIsolate(n)){let s=e(),a=new R({modulePath:t,pluginName:n.name,ctx:{name:s.name,dataDir:s.dataDir}});try{await a.start(),this.workerHosts.set(n.name,a),s.logger.info("plugin-manager",`Isolated plugin '${n.name}' running in worker_threads`)}catch(o){try{await a.terminate()}catch{}this.loaded.delete(t);let l=o instanceof Error?o.message:String(o);throw s.logger.error("plugin-manager",`Isolation required for '${n.name}' but worker failed to start (${l}); refusing to load in host process`),Error(`Plugin '${n.name}' requires isolation but the worker failed to start: ${l}`,{cause:o})}}return n}resolvePackageRoot(t){let r=import.meta;if(typeof r.resolve!=="function")return;try{let i=r.resolve(t);if(!i.startsWith("file:"))return;let n=S(L(i));while(n&&n!==S(n)){if(y(p(n,"package.json")))return n;n=S(n)}}catch{return}return}validatePluginExport(t,r,i){if(!z.test(t.name))throw Error(`${r} exports an invalid plugin name`);if(!t.version||t.version.length>64)throw Error(`${r} exports an invalid plugin version`);if(t.description&&t.description.length>500)throw Error(`${r} description is too long`);if(t.cliCommand&&!z.test(t.cliCommand))throw Error(`${r} exports an invalid CLI command`);if(t.apiPrefix){if(!Le.test(t.apiPrefix)||t.apiPrefix.includes("..")||t.apiPrefix.includes("//"))throw Error(`${r} exports an invalid API prefix`)}if(t.publicPaths){if(t.publicPaths.length>20)throw Error(`${r} exports too many public paths`);for(let n of t.publicPaths)if(!Te.test(n)||n.includes("..")||n.includes("//"))throw Error(`${r} exports an invalid public path`)}if(t.dependencies&&t.dependencies.length>20)throw Error(`${r} exports too many dependencies`);if(t.tags){let n=new Set(["backend","frontend","cli","provider","adapter","integration"]);if(t.tags.length>n.size)throw Error(`${r} exports too many tags`);for(let s of t.tags)if(!n.has(s))throw Error(`${r} exports an invalid tag`)}if(t.ui){if(t.ui.title&&t.ui.title.length>120)throw Error(`${r} UI title is too long`);if(t.ui.staticDir){if(!i)throw Error(`${r} UI staticDir requires a package root`);let n=B(i),s=B(t.ui.staticDir);if(!we(s).isDirectory()||!Ne(n,s))throw Error(`${r} UI staticDir must be inside the plugin package`)}}}pluginRoots;getPluginRoots(){if(this.pluginRoots!==void 0)return this.pluginRoots;let t=b(),r=[],i=new Set,n=(a)=>{if(!a||i.has(a)||!y(a))return;i.add(a),r.push(a)},s=process.env.VIBECONTROLS_PLUGIN_ROOTS;if(s)for(let a of s.split(t.pathSep).map((o)=>o.trim()).filter(Boolean))n(a);if(T()==="local")n(Z());else n(p(Se(),".bun","install","global","node_modules")),n(t.npmGlobalRoot());if(this.isRunningFromSource())n(this.agentOwnNodeModules());return this.pluginRoots=r,r}isRunningFromSource(){try{let t=L(import.meta.url);return t.includes(`${j}src${j}`)||t.includes("/src/")}catch{return!1}}agentOwnNodeModules(){try{let t=S(L(import.meta.url)),r="";while(t&&t!==r){if(y(p(t,"package.json")))return p(t,"node_modules");r=t,t=S(t)}}catch{}return null}getGlobalRoots(){return this.getPluginRoots()}readInstalledVersion(t,r){try{let i=p(t,r,"package.json");if(!y(i))return;let n=JSON.parse(x(i,"utf8"));return typeof n.version==="string"?n.version:void 0}catch{return}}logResolvedPlugin(t,r,i){let n=e().logger;n.debug("plugin-manager",`Resolved ${t}@${r}`,{from:i??"(bare import)"});try{let s=[];for(let a of this.getPluginRoots()){let o=p(a,t);if(i&&o===i)continue;let l=this.readInstalledVersion(a,t);if(l&&l!==r)s.push(`${o} (v${l})`)}if(s.length>0)n.warn("plugin-manager",`${t}: loaded v${r} but stale duplicate copy(ies) exist at a different version \u2014 these shadow the active copy across reinstalls. Run \`vibe nuke --all\` to purge them.`,{loadedVersion:r,loadedFrom:i??"(bare import)",shadows:s})}catch{}}extractPlugin(t,r,i){let n=this.findFactory(t);if(n){let s=n(i);if(!this.isVibePlugin(s))throw Error(`plugin '${r}' createPlugin(ctx) factory returned an invalid VibePlugin`);return s}if(this.hasLegacySingleton(t)){let s=`plugin '${r}' uses removed singleton contract; upgrade to createPlugin(ctx) factory`;if(_())throw Error(s);e().logger.warn("plugin-manager",s);return}return}findFactory(t){if(typeof t.createPlugin==="function")return t.createPlugin;let r=t.default;if(r&&typeof r.createPlugin==="function")return r.createPlugin;return}hasLegacySingleton(t){if(this.isVibePlugin(t.vibePlugin))return!0;let r=t.default;if(r&&this.isVibePlugin(r.vibePlugin))return!0;if(this.isVibePlugin(r))return!0;return!1}isVibePlugin(t){if(!t||typeof t!=="object")return!1;let r=t;return typeof r.name==="string"&&typeof r.version==="string"}registerProviders(t,r){this.registerPluginProviders(t,r)}registerPluginProviders(t,r){let n=q(t.name)?.isDefault===!0,s=(a)=>{if(!n)return;r.serviceRegistry.setProviderDefault(a,t.name)};if(t.providers?.tunnel){if(r.serviceRegistry.registerProvider("tunnel",t.providers.tunnel,t.name),s("tunnel"),t.tunnelDomainSuffixes)for(let a of t.tunnelDomainSuffixes)Ht(a)}if(t.providers?.session)r.serviceRegistry.registerProvider("session",t.providers.session,t.name),s("session");if(t.providers?.ai)r.serviceRegistry.registerProvider("ai",t.providers.ai,t.name),s("ai")}async dispatchCliSetup(t,r){for(let i of this.getAllPlugins())if(i.onCliSetup)try{await i.onCliSetup(t,this.wrapHostServices(i,r))}catch(n){e().logger.warn("plugin-manager",`onCliSetup failed for ${i.name}: ${n}`)}}async dispatchServerStart(t,r){let i=this.sortAllByDependencies(),n=[];for(let s of i){if(this.registerPluginProviders(s,r),s.onServerStart){let a=Date.now();try{await s.onServerStart(t,this.wrapHostServices(s,r)),(async()=>{try{let{telemetryService:o}=await import("./telemetry-nmtywcba.js");o.emit("plugin.activated",{plugin_name:s.name,version:s.version,duration_ms:Date.now()-a})}catch{}})()}catch(o){let l=o instanceof Error?o.message:String(o);e().logger.error("plugin-manager",`onServerStart failed for ${s.name}: ${l}`),(async()=>{try{let{telemetryService:u}=await import("./telemetry-nmtywcba.js");u.emit("plugin.failed",{plugin_name:s.name,error_class:o instanceof Error?o.constructor.name:"Error"})}catch{}})();let g=this.registry.find((u)=>u.pluginName===s.name);n.push({plugin:s.name,packageName:g?.packageName,error:l})}}this.registerPluginProviders(s,r)}return{failures:n}}async dispatchServerReady(t,r){for(let i of this.getAllPlugins())if(i.onServerReady)try{await i.onServerReady(t,this.wrapHostServices(i,r))}catch(n){e().logger.warn("plugin-manager",`onServerReady failed for ${i.name}: ${n}`)}}async provisionDefaultPrereqs(t,r,i,n){let s=process.env.VIBE_SKIP_PREREQ_INSTALL==="1",a=process.platform;e().logger.info("plugin-manager",`Provisioning default providers \u2014 agent build v${_e()}, platform=${a}, pluginInstallScope=${T()}, skipInstall=${s}`);let o=(n?ye(process.platform,n):A(process.platform)).map((u)=>u.packageName);if(!s)for(let u of o){if(this.loaded.has(u))continue;try{e().logger.info("plugin-manager",`Installing default meta ${u}`),await this.install(u,{refreshLatest:!0})}catch(d){e().logger.warn("plugin-manager",`Failed to install default meta ${u}: ${d}`)}}let l=this.buildHostPluginsFacade(t,r,i),g=this.attachPluginsFacade(r,l);for(let[u,d]of this.getAllLoaded()){if(!d.provisionProviders)continue;try{await d.provisionProviders(this.wrapHostServices(d,g)),e().logger.info("plugin-manager",`${u}: providers provisioned`)}catch(c){e().logger.warn("plugin-manager",`${u}: provisionProviders failed: ${c}`)}}}buildHostPluginsFacade(t,r,i){return{install:async(n,s)=>{await this.install(n,s??{})},loadProvider:async(n)=>{await this.loadAndStartProvider(n,t,r,i)},runPrereqs:async(n,s)=>{let{runPluginPrereqs:a}=await import("./prereqs-runner-gca0bytz.js"),o=this.loaded.get(n);if(!o)return{satisfied:!1};let l=await a(o,n,t,this.db??null,{skipInstall:s?.skipInstall===!0});return{satisfied:l.noProtocol?!0:l.satisfied}},electDefault:async(n,s)=>{await this.electProviderDefault(n,s,r)},isProviderRegistered:(n,s)=>r.serviceRegistry.listProvidersForType(n).some((a)=>a.pluginName===s),skipInstall:()=>process.env.VIBE_SKIP_PREREQ_INSTALL==="1"}}attachPluginsFacade(t,r){return new Proxy(t,{get(i,n,s){if(n==="plugins")return r;return Reflect.get(i,n,s)}})}async loadAndStartProvider(t,r,i,n){let s=this.loaded.get(t);if(!s)s=await this.importPlugin(t);if(s.createRoutes&&n?.(s))e().logger.info("plugin-manager",`${t}: mounted routes after provisioning`);this.registerPluginProviders(s,i);let a=this.wrapHostServices(s,i);if(s.onServerStart)await s.onServerStart(r,a);if(s.onServerReady)await s.onServerReady(r,a)}async electProviderDefault(t,r,i){if(!i.serviceRegistry.listProvidersForType(t).some((s)=>s.pluginName===r))return;try{let s=await this.getDefaultProvider(t);if(s&&s!==r)return;if(i.serviceRegistry.setProviderDefault(t,r),!s)await this.setDefaultProvider(t,r).catch(()=>{});e().logger.info("plugin-manager",`Elected platform-default '${t}' provider '${r}'`)}catch(s){e().logger.warn("plugin-manager",`Failed to elect default '${t}' provider '${r}': ${s}`)}}async dispatchServerStop(t){for(let r of this.getAllPlugins())if(r.onServerStop)try{await r.onServerStop(t)}catch(i){e().logger.warn("plugin-manager",`onServerStop failed for ${r.name}: ${i}`)}if(t?.reason==="shutdown")await this.terminateAllWorkerHosts()}async runPluginNuke(t,r,i){let n=t?this.loaded.has(t)?[[t,this.loaded.get(t)]]:[]:Array.from(this.loaded.entries()),s=[];for(let[a,o]of n){if(!o.onNuke)continue;try{let l=this.wrapHostServices(o,r),g=await o.onNuke(l,i);s.push({plugin:a,ok:!0,reaped:g?.reaped??[],notes:g?.notes??[]}),e().logger.info("plugin-manager",`onNuke ${i.dryRun?"(dry-run) ":""}completed for ${a}`,{reaped:g?.reaped??[]})}catch(l){let g=l instanceof Error?l.message:String(l);s.push({plugin:a,ok:!1,reaped:[],notes:[],error:g}),e().logger.warn("plugin-manager",`onNuke failed for ${a}: ${g}`)}}return{results:s}}async reloadAll(t,r){await this.dispatchServerStop({reason:"reload"}),await this.terminateAllWorkerHosts();for(let i of this.loaded.values())r.serviceRegistry.unregisterPlugin(i.name);this.loaded.clear(),this.corePlugins.clear(),this.loadRegistry(),await this.loadCorePlugins(),await this.loadAll(),await this.dispatchServerStart(t,r),await this.dispatchServerReady(t,r)}sortAllByDependencies(){let t=this.getAllPlugins(),r=new Map;for(let o of t)r.set(o.name,o);let i=new Set,n=new Set,s=[],a=(o)=>{if(i.has(o))return;if(n.has(o))throw Error(`Plugin dependency cycle detected at '${o}'`);let l=r.get(o);if(!l)return;if(n.add(o),l.dependencies)for(let g of l.dependencies){if(!r.has(g)){e().logger.warn("plugin-manager",`Plugin '${l.name}' depends on missing plugin '${g}'`);continue}a(g)}n.delete(o),i.add(o),s.push(l)};for(let o of t)a(o.name);return s}sortByDependencies(){let t=Array.from(this.loaded.entries()),r=new Map;for(let[a,o]of t)r.set(o.name,a);let i=new Set,n=[],s=(a)=>{if(i.has(a))return;i.add(a);let o=this.loaded.get(a);if(o?.dependencies)for(let g of o.dependencies){let u=r.get(g);if(u&&this.loaded.has(u))s(u)}let l=this.loaded.get(a);if(l)n.push([a,l])};for(let[a]of t)s(a);return n}getPluginByKey(t){for(let[,r]of this.loaded)if(r.name===t)return r;return this.corePlugins.get(t)}getAllPlugins(){let t=new Map;for(let[r,i]of this.corePlugins)t.set(r,i);for(let[,r]of this.loaded)t.set(r.name,r);return Array.from(t.values())}getAllPluginsByTag(t){return this.getAllPlugins().filter((r)=>r.tags?.includes(t)??!1)}resolvePluginChain(t){let r=new Set;for(let s of this.getAllPlugins())r.add(s.name);let i=[],n=-1;for(let s=0;s<t.length;s++){if(t[s].startsWith("-")){n=s;break}if(r.has(t[s]))i.push(t[s]);else{n=s;break}}if(n===-1)return{chain:i,command:"",args:[]};return{chain:i,command:t[n],args:t.slice(n+1)}}async getDefaultProvider(t){if(!this.db)return null;return await this.db.getConfig(`${J}${t}`)??null}async setDefaultProvider(t,r){if(!this.db)throw Error("Cannot set default provider: PluginManager was constructed without a database reference");if(!this.getPluginByKey(r))throw Error(`Plugin '${r}' not found`);await this.db.setConfig(`${J}${t}`,r),e().logger.info("plugin-manager",`Set default '${t}' provider to '${r}'`)}getPluginDetails(){let t=this.getCorePluginDetails(),r=this.getExternalPluginDetails(),i=new Map;for(let n of t)i.set(n.pluginName,n);for(let n of r)i.set(n.pluginName,n);return Array.from(i.values())}getCorePluginDetails(){let t=[];for(let[r,i]of this.corePlugins)t.push({packageName:`@vibecontrols/plugin-${r}`,pluginName:r,version:i.version,description:i.description,tags:i.tags,cliCommand:i.cliCommand,apiPrefix:i.apiPrefix,dependencies:i.dependencies,installedAt:"",loaded:!0,isCore:!0,hasUI:!!i.ui,uiUrl:i.ui?`/ui/${r}`:void 0,hasCliSetup:!!i.onCliSetup,hasServerStart:!!i.onServerStart,hasServerStop:!!i.onServerStop,hasServerReady:!!i.onServerReady,hasProviders:!!(i.providers?.tunnel||i.providers?.session||i.providers?.ai)});return t}getExternalPluginDetails(){return this.registry.map((t)=>{let r=this.loaded.get(t.packageName),i=q(t.pluginName);return{packageName:t.packageName,pluginName:t.pluginName,version:r?.version??t.version,description:r?.description,tags:r?.tags,cliCommand:r?.cliCommand,apiPrefix:r?.apiPrefix,dependencies:r?.dependencies,installedAt:t.installedAt,loaded:!!r,isCore:i?.isCore===!0,hasUI:!!r?.ui,uiUrl:r?.ui?`/ui/${t.pluginName}`:void 0,hasCliSetup:!!r?.onCliSetup,hasServerStart:!!r?.onServerStart,hasServerStop:!!r?.onServerStop,hasServerReady:!!r?.onServerReady,hasProviders:!!(r?.providers?.tunnel||r?.providers?.session||r?.providers?.ai)}})}getRegistry(){return[...this.registry]}getLoaded(t){return this.loaded.get(t)}getAllLoaded(){return new Map(this.loaded)}isInstalled(t){return this.registry.some((r)=>r.packageName===t)}isLoaded(t){return this.loaded.has(t)}}
|
|
5
5
|
export{_e,ie,Y,ye,ht,bi,wi,qi,ft,Pr,Mt,Mr,le,W};
|