@vibecontrols/agent 2026.1124.1 → 2026.1125.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{app-k7z7tjem.js → app-a95wetk5.js} +1 -1
- package/dist/cli.js +1 -1
- package/dist/{index-3cbesatx.js → index-4527yp1c.js} +1 -1
- package/dist/{index-9bj65n3s.js → index-75hk5q9s.js} +1 -1
- package/dist/{index-m942hydk.js → index-ec08v08h.js} +2 -2
- package/dist/{index-3b5xejjs.js → index-g08z6z5v.js} +2 -2
- package/dist/{index-aav1drxa.js → index-gaztfvyz.js} +23 -23
- package/dist/{index-06bmw4xf.js → index-gnb8xw13.js} +1 -1
- package/dist/{index-4q8y6k1e.js → index-ne8q0a64.js} +3 -3
- package/dist/{index-p0bbp16g.js → index-nzfqdhsx.js} +1 -1
- package/dist/{index-wr888ydc.js → index-v35k2y31.js} +1 -1
- package/dist/index.js +2 -2
- package/dist/{plugin-system-kvg955t3.js → plugin-system-zj50tg4k.js} +1 -1
- package/dist/{register-core-31wm1d8m.js → register-core-vng5hdga.js} +1 -1
- package/dist/{secondary-profile-attach-95kmnrhf.js → secondary-profile-attach-pyqqf4ny.js} +1 -1
- package/dist/{tunnel-bootstrap-rym0b0x5.js → tunnel-bootstrap-zwyzxrkt.js} +1 -1
- package/package.json +1 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Er}from"./index-
|
|
2
|
+
import{Er}from"./index-ne8q0a64.js";import"./index-tahaxp6n.js";import"./index-4527yp1c.js";import"./index-jnxjjx2y.js";import"./index-v35k2y31.js";import"./index-75hk5q9s.js";import"./index-gnb8xw13.js";import"./index-g08z6z5v.js";import"./index-ywnfz6nm.js";import"./index-4z1y39jt.js";import"./index-qfxwk38p.js";import"./index-mmx2kp76.js";import"./index-5021rk8n.js";import"./index-w0m3jm0s.js";import"./index-byerrz46.js";import"./index-kwhx023z.js";import"./index-0qjbnyg4.js";export{Er as createApp};
|
package/dist/cli.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
// @bun
|
|
3
|
-
import{$e}from"./index-haww9jpq.js";import{I,se,e}from"./index-0qjbnyg4.js";import{W}from"./index-
|
|
3
|
+
import{$e}from"./index-haww9jpq.js";import{I,se,e}from"./index-0qjbnyg4.js";import{W}from"./index-g08z6z5v.js";import{Z}from"./index-ywnfz6nm.js";import{vi}from"./index-7f2k4g6q.js";import"./index-w0m3jm0s.js";import"./index-kwhx023z.js";import"./index-5021rk8n.js";import"./index-mmx2kp76.js";import{xr}from"./index-jmx5awkj.js";import"./index-vtsd74g0.js";import"./index-652f9scs.js";import"./index-cy97asyh.js";import{br,wr}from"./index-ec08v08h.js";import"./index-v35k2y31.js";import"./index-0gmhd3hs.js";import"./index-75hk5q9s.js";import{Te,Ee,Ti,ke}from"./index-gnb8xw13.js";import{b}from"./index-w4jqdhc2.js";import"./index-4z1y39jt.js";import"./index-t5cfkz1e.js";import"./index-byerrz46.js";import{join as m}from"path";if(typeof Bun>"u")console.error(`\x1B[31mError:\x1B[0m VibeControls Agent requires the Bun runtime.
|
|
4
4
|
Install Bun: https://bun.sh
|
|
5
5
|
Then run: bun run vibe ...`),process.exit(1);var a=process.argv.slice(2),l=a.includes("--plain")||a.includes("--json")||process.env.NO_COLOR==="1"||!process.stdout.isTTY;vi(!l);try{xr()}catch{}var s="1.0.0";try{let t=m(import.meta.dir,"..","package.json");s=(await Bun.file(t).json()).version}catch{}var r=new $e;r.name("vibe").description("VibeControls Agent CLI \u2014 Remote development environment management").version(s,"-v, --version").option("--provider <name>","Override the default provider for tunnel/session operations").option("-p, --profile <name>","Target a specific profile (one-off; doesn't change the persisted default). See `vibe profile`.").option("--json","Emit machine-readable JSON instead of human output.").option("--plain","Force plain-text output (no interactive UI).").hook("preAction",(t,o)=>{let n=t.opts().profile;if(n)process.env.VIBECONTROLS_PROFILE=n;try{Z.init(),Z.emit("command.executed",{command_name:o.name()})}catch{}});wr(r);async function g(){let t=new W;try{await t.loadCorePlugins()}catch{}try{await t.loadAll()}catch{}let o=new Te,n={storage:{async get(){return null},async set(){},async delete(){return!1},async list(){return[]},async deleteAll(){return 0}},logger:e().logger,serviceRegistry:o,getProvider:(i)=>o.getProvider(i),getAgentBaseUrl:()=>process.env.AGENT_URL||"http://localhost:3005",getAgentVersion:()=>s,broadcast:()=>{},workspaceQuery:async()=>({data:void 0,errors:[{message:"workspaceQuery is not available in CLI mode"}]}),isGatewayConfigured:()=>!1,getAgentRecordId:async()=>null,getWorkspaceId:async()=>null,getConfig:async()=>{return},getPluginRegistry:()=>se(),getDataDir:()=>I(),cliContributors:new Ee,telemetry:{emit:(i,p)=>{try{Z.emit(i,p??{})}catch{}}},os:b(),iframeBridge:ke()};Ti(n.cliContributors);try{await t.dispatchCliSetup(r,n)}catch{}r.configureHelp({formatHelp:()=>br(r,!0)}),await r.parseAsync()}g().then(()=>{process.exit(process.exitCode??0)}).catch((t)=>{console.error(`\x1B[31mFatal:\x1B[0m ${t instanceof Error?t.message:t}`),process.exit(1)});
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{z,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-g08z6z5v.js";import{K}from"./index-mmx2kp76.js";import{pt}from"./index-qfxwk38p.js";import{Te,Ee,ke}from"./index-gnb8xw13.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-g08z6z5v.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{z,R,I,ne,ee,C,e}from"./index-0qjbnyg4.js";import{J,$r,Ui,Qt,lr,fe,je,pe,jt,Hr,_t,et,Yr,gr,dr,tt,hr,w,M,yt}from"./index-kwhx023z.js";import{i,d,s,A,l,p,o,g,n,c,F,v,G,H,Ut}from"./index-7f2k4g6q.js";import{he,Q,U}from"./index-vtsd74g0.js";import{Me,st}from"./index-652f9scs.js";import{ie,Y,ye,qi,Pr,Mt,W}from"./index-3b5xejjs.js";import{qr}from"./index-cy97asyh.js";import{qe}from"./index-mmx2kp76.js";import{He,qt,Ei,_i,er,yi,tr,Si,ot,te,re,ae,Ii,at,De,Ci,Ve,Ye,Ne,Rt,Ze,nr,Le,Je,We,ct,ut,lt,gt,Or,dt,Ft,Ot,Bt,me}from"./index-wr888ydc.js";import{fi}from"./index-0gmhd3hs.js";import{pi}from"./index-akk3rxnn.js";import{D}from"./index-9bj65n3s.js";import{Pt}from"./index-06bmw4xf.js";import{b}from"./index-w4jqdhc2.js";import{Ri,L}from"./index-b3v08awy.js";import{ve}from"./index-4z1y39jt.js";import{Se,Ie,_,y,u,vt}from"./index-t5cfkz1e.js";import{f,m,S,q,Ce,Ae}from"./index-byerrz46.js";import{existsSync as Xt}from"fs";import{join as ho}from"path";import{createServer as fo}from"net";function go(k,a="0.0.0.0"){return new Promise((t)=>{let r=fo();r.once("error",()=>t(!1)),r.once("listening",()=>{r.close(()=>t(!0))}),r.listen({host:a,port:k,exclusive:!0})})}async function Zt(k,a="0.0.0.0"){let t=k;while(!await go(t,a))if(t++,t>65535)throw Error(`No free port found starting from ${k}`);return t}function en(k){k.command("start").description("Start a VibeControls agent instance").option("-p, --port <port>","Port to listen on. Default: 3005 for the 'default' profile, deterministic 3100-3399 for any other profile (FNV-1a hash) so multiple profiles run side-by-side without EADDRINUSE.").option("-n, --name <name>","Agent instance name","default").option("-f, --foreground","Run in foreground mode (default: daemon)",!1).option("--no-autostart","Don't configure OS-level autostart for this agent. Without it the daemon dies with the session that started it and will not come back.").option("--db-path <path>","Path to the agent storage directory").option("--profile <profile>","Profile name for isolated config (env: VIBECONTROLS_PROFILE)").option("--host <host>","Host to bind to","0.0.0.0").option("--skip-plugin-install","Skip automatic installation of default plugins",!1).option("--skip-plugin <name>","Skip a specific default plugin (repeatable). Accepts the short pluginName or the full package name.",(a,t=[])=>[...t,a],[]).option("--no-install-deps","Skip auto-installing missing tools (installed by their plugins on start by default)").option("-y, --yes","Skip the first-run install consent prompt. Equivalent to VIBE_AUTO_ACCEPT=1; useful for CI / Docker / nohup contexts.",!1).option("--client-id <id>","Gateway OAuth client ID (env: VIBE_CLIENT_ID)").option("--client-secret <secret>","Gateway OAuth client secret (env: VIBE_CLIENT_SECRET)").option("--global-gateway-url <url>","Global gateway URL (env: VIBE_GLOBAL_GATEWAY_URL)").option("--workspace-gateway-url <url>","Workspace gateway URL (env: VIBE_WORKSPACE_GATEWAY_URL)").option("--workspace-id <id>","Workspace ID for auto-report (env: VIBE_WORKSPACE_ID)").option("--isolate <plugins>","Comma-separated list of plugin names to force into worker_threads isolation (Phase 4 hostile-plugin mode). Sets VIBE_ISOLATE_PLUGINS in the daemon env.").option("--profiles <names>","Comma-separated list of profiles to host in this daemon (multi-profile boot). When unset, the daemon hosts a single profile resolved via --profile / VIBECONTROLS_PROFILE / 'default'. Sets VIBECONTROLS_PROFILES in the daemon env so app boot can spin up additional ProfileContexts via the in-process registry.").option("--strict-key-fetch","Refuse to boot if any profile's encryption-key fetch fails. Default lenient: a failed profile is marked degraded and the daemon stays up. Sets VIBE_STRICT_KEY_FETCH=1 in the daemon env.",!1).option("--json","Emit JSON").option("--plain","Plain text output (no interactive TUI). Implied for non-TTY / CI.").option("--abilities <list>","Comma-separated ability keys to install non-interactively (e.g. session,ai,gitops). Storage/tunnel/backup are always included.").option("--providers <list>","Comma-separated extra provider plugins to install beyond each meta's default (e.g. session-wezterm,ai-claude). Accepts short names or @vibecontrols/... packages. Persisted; manage later with `vibe capability`.").option("--wait-ready [seconds]","Block until the agent is fully ready (or fails). Polls /health/ready and renders phase transitions live. Without a value, defaults to 60s. Exits non-zero if the agent ends up degraded or times out. Useful for scripts/CI.").option("--no-wait","Skip the phase tracker entirely after spawning the daemon. Restores the old fire-and-print behavior \u2014 for users who want the previous quick-return UX.").action(async function(a){let t={...k.opts(),...a};try{let oe=function(le){if(le==="default")return 3005;let be=2166136261;for(let ge=0;ge<le.length;ge++)be=Math.imul(be^le.charCodeAt(ge),16777619);return 3100+Math.abs(be)%300},r=new D,h=a.profile||process.env.VIBECONTROLS_PROFILE||"default";if(process.env.VIBECONTROLS_PROFILE=h,typeof a.isolate==="string"&&a.isolate.length>0)process.env.VIBE_ISOLATE_PLUGINS=a.isolate;if(typeof a.profiles==="string"&&a.profiles.length>0){let le=a.profiles.split(",").map((be)=>be.trim()).filter(Boolean);if(le.length>0){if(process.env.VIBECONTROLS_PROFILES=le.join(","),process.env.VIBECONTROLS_PROFILE=le[0],le.length>1)p(`--profiles received ${le.length} entries; daemon boots with '${le[0]}'. Remaining (${le.slice(1).join(", ")}) will be attached via /api/profiles after listen.`)}}if(a.strictKeyFetch===!0)process.env.VIBE_STRICT_KEY_FETCH="1";yt();let P=a.dbPath||ee(),O=C(),E=!Xt(P)&&!Xt(ho(O,"agents.json")),N=_(t),x=N!=="json"&&N!=="plain"&&Se()&&a.yes!==!0,j=He(O),T;if(typeof t.abilities==="string"&&t.abilities.trim()!=="")T=yi(t.abilities);else if(j!==null)T=j;else if(x)T=await er();else T=tr();let Z=typeof t.providers==="string"&&t.providers.trim()!=="",B=Z?Ei(t.providers):qt(O);if(j===null){let le=_i({installDeps:a.installDeps===!0,skipPluginInstall:a.skipPluginInstall===!0,skipPlugins:Array.isArray(a.skipPlugin)?a.skipPlugin:[]},T);if(E&&le.plugins.length>0)c(),o(`Installing ${le.plugins.length} plugin(s) for the selected abilities.`),c();Si(O,le,T,process.env.VIBE_AGENT_VERSION,B)}else if(Z)ot(O,{providers:B,agentVersion:process.env.VIBE_AGENT_VERSION});if((E||Z)&&B.length>0&&a.skipPluginInstall!==!0){o(`Installing ${B.length} selected provider plugin(s)...`);try{let{PluginManager:le}=await import("./plugin-system-kvg955t3.js"),be=new le;for(let ge of B)try{await be.install(ge),l(`Installed provider ${ge}`)}catch(we){p(`Could not install provider ${ge}: ${we instanceof Error?we.message:String(we)}`)}}catch(le){p(`Provider install skipped: ${le instanceof Error?le.message:String(le)}`)}c()}if(E){o("First run detected \u2014 running setup..."),c();let le=Array.isArray(a.skipPlugin)?a.skipPlugin:[],be=a.skipPluginInstall?[]:ye(process.platform,T).filter((Re)=>!le.includes(Re.packageName)&&!le.includes(Re.pluginName)).map((Re)=>Re.packageName),ge=qi(be),ze=Me(ge).filter((Re)=>!Re.installed);if(ze.length>0)if(p(`Missing tools: ${ze.map((Re)=>Re.name).join(", ")}`),a.installDeps)o("Their plugins will install them automatically on startup.");else o("Auto-install skipped (`--no-install-deps`) \u2014 install them yourself or drop the flag.");else l("All plugin tools present.");c()}if(!a.skipPluginInstall){let le=Array.isArray(a.skipPlugin)?a.skipPlugin:[],be=new W;await be.loadCorePlugins(),await be.loadAll();let ge=await be.ensureDefaultPlugins((we)=>{if(we.startsWith("No "))p(we);else if(we.startsWith("Installed "))l(we);else if(we.startsWith("Failed "))p(we);else o(we)},le,T);if(ge.length>0)l(`Auto-installed ${ge.length} default plugin${ge.length>1?"s":""}.`),c()}let V=a.profile||process.env.VIBECONTROLS_PROFILE||a.name||"default",K=a.port?parseInt(a.port,10):oe(V);if(isNaN(K)||K<1||K>65535)s("Invalid port number. Must be between 1 and 65535.");let X=await Zt(K);if(X!==K)p(`Port ${K} is in use. Auto-selecting port ${i.bold(String(X))} instead.`),K=X;let se=a.host,Oe=`http://${se==="0.0.0.0"?"localhost":se}:${K}`,$e=a.clientId||process.env.VIBE_CLIENT_ID,ce=a.clientSecret||process.env.VIBE_CLIENT_SECRET,de=a.globalGatewayUrl||process.env.VIBE_GLOBAL_GATEWAY_URL,ue=a.workspaceGatewayUrl||process.env.VIBE_WORKSPACE_GATEWAY_URL,_e=a.workspaceId||process.env.VIBE_WORKSPACE_ID;if($e&&!ce)s("--client-secret is required when --client-id is provided.");if(ce&&!$e)s("--client-id is required when --client-secret is provided.");if($e&&ce){if(!de&&!process.env.VIBE_GLOBAL_GATEWAY_URL)s("--global-gateway-url is required when providing client credentials (none set in env).");if(process.env.VIBE_CLIENT_ID=$e,process.env.VIBE_CLIENT_SECRET=ce,de)process.env.VIBE_GLOBAL_GATEWAY_URL=de;let{writeAgentConfig:le}=await import("./agent-config-v9d7gcz0.js");if(le({clientId:$e,clientSecret:ce,workspaceId:_e,globalGatewayUrl:de,workspaceGatewayUrl:ue}),ue)process.env.VIBE_WORKSPACE_GATEWAY_URL=ue;if(_e)process.env.VIBE_WORKSPACE_ID=_e;l("Gateway credentials staged in env. Agent will authenticate and persist them on startup."),c()}else if(ue||_e||de){if(p("Workspace options provided without --client-id / --client-secret \u2014 they will be staged in env but unused until credentials are configured."),ue)process.env.VIBE_WORKSPACE_GATEWAY_URL=ue;if(_e)process.env.VIBE_WORKSPACE_ID=_e;if(de)process.env.VIBE_GLOBAL_GATEWAY_URL=de;c()}if(a.foreground){if(!t.json)g("Starting agent in foreground"),n("Name",a.name),n("Port",String(K)),n("Host",se),n("Database",P),c();let{bootstrapWorkspace:le}=await import("./bootstrap-workspace-3pb8qjsh.js");le();let{createApp:be}=await import("./app-k7z7tjem.js"),ge=await be({port:K,host:se,dbPath:P});if(await ge.start(),$e&&ce&&_e&&de&&ue){let ze=await ge.finalize({clientId:$e,clientSecret:ce,workspaceId:_e,globalGatewayUrl:de,workspaceGatewayUrl:ue});if(!ze.ok)p(`Finalize failed \u2014 agent remains in awaiting-config state: ${ze.error}`)}if(u(t,{ok:!0,name:a.name,port:K,host:se,pid:process.pid,url:Oe}));else await Ut(Oe);let we=async()=>{await ge.stop(),process.exit(0)};process.on("SIGTERM",we),process.on("SIGINT",we)}else{if(!t.json)g("Starting agent in daemon mode"),n("Name",a.name),n("Port",String(K)),n("Host",se),n("Database",P),c();if(a.installDeps===!1)process.env.VIBE_SKIP_PREREQ_INSTALL="1";await r.startDaemon({port:K,name:a.name,daemon:!0,dbPath:P,host:se,profile:h});let be=(await r.getStatus(a.name))?.port??K,ge;if(a.autostart!==!1){let{ensureAutostartConfigured:Te}=await import("./autostart.cmd-ahet7b1t.js"),ke=await Te({name:a.name,port:be,dbPath:P,host:se,profile:h});if(ge=ke,ke.installed&&!t.json)o(`Configured ${ke.serviceLabel} autostart \u2014 supervised from the next login/boot. `+"The daemon running now is not yet under it; hand it over with `vibe stop && vibe autostart install`.");else if(ke.failed&&!t.json)p(`Could not configure autostart (${ke.reason}). This agent will NOT come back after logout or reboot \u2014 fix the cause or run \`vibe autostart install\`.`)}let we=ge?{installed:ge.installed,failed:ge.failed??!1,reason:ge.reason}:{installed:!1,failed:!1,reason:"opted out"},Re=`http://${se==="0.0.0.0"?"localhost":se}:${be}`,kt=a.waitReady,$t=a.wait===!1,Ht=kt!==void 0;if($t&&Ht)p("--wait-ready is ignored because --no-wait was also passed.");let ft=!$t&&Ht,zt=!$t&&(ft||!t.json),Yt=(()=>{let Te=typeof kt==="string"?Number.parseInt(kt,10):NaN;if(Number.isInteger(Te)&&Te>0)return Te*1000;return ft?60000:25000})();if(t.json){if(zt){let{trackAgentReady:Te}=await import("./agent-ready-tracker-mewxehg9.js"),ke=await Te(Re,{timeoutMs:Yt,verbose:!1});if(ft&&(ke.outcome==="degraded"||ke.outcome==="timeout"))process.exitCode=1;u(t,{ok:ke.outcome==="ready"||ke.outcome==="awaiting-config",name:a.name,port:be,host:se,url:Re,abilities:[...T],outcome:ke.outcome,bootState:ke.bootState,degradedReasons:ke.degradedReasons,summary:ke.summary,autostart:we})}else u(t,{ok:!0,name:a.name,port:be,host:se,url:Re,autostart:we});return}if(await Ut(Re),zt){let{trackAgentReady:Te}=await import("./agent-ready-tracker-mewxehg9.js");c();let ke=await Te(Re,{timeoutMs:Yt,verbose:!0});if(ft&&(ke.outcome==="degraded"||ke.outcome==="timeout"))process.exitCode=1}}}catch(r){let h=r instanceof Error?A(r):String(r);if(t.json){u(t,{ok:!1,error:h});return}s(`Failed to start agent: ${h}`)}})}function tn(k){k.command("stop").description("Stop a running VibeControls agent instance").option("-n, --name <name>","Agent instance name","default").option("--all","Stop all running agent instances",!1).option("--json","Emit JSON").action(async function(a){let t={...k.opts(),...a};try{let r=new D;if(a.all){let h=await r.listInstances();if(!h||h.length===0){if(u(t,{ok:!0,stopped:[]}))return;g("Stopping all agent instances"),c(),o(`${d.info} No running agent instances found.`);return}let P=[];if(!t.json)g("Stopping all agent instances"),c();for(let O of h)try{if(await r.stop(O.name),P.push(O.name),!t.json)l(`${d.success} Stopped ${i.bold(O.name)}`)}catch{if(!t.json)s(`Failed to stop ${i.bold(O.name)}`)}if(u(t,{ok:!0,stopped:P,total:h.length}))return;c(),l(`${d.success} Stopped ${P.length}/${h.length} instance(s).`)}else{if(await r.stop(a.name),u(t,{ok:!0,name:a.name}))return;g(`Stopping agent: ${a.name}`),c(),l(`${d.success} Agent ${i.bold(a.name)} stopped.`)}}catch(r){if(t.json){u(t,{ok:!1,error:A(r)});return}s(`Failed to stop agent: ${A(r)}`)}})}function nn(k){k.command("restart").description("Restart a running VibeControls agent instance").option("-n, --name <name>","Agent instance name","default").option("-p, --port <port>","Port to listen on").option("--db-path <path>","Path to the agent storage directory").option("--json","Emit JSON").option("--no-autostart","Don't configure OS-level autostart for this agent. Without it the daemon dies with the session that started it and will not come back.").action(async function(a){let t={...k.opts(),...a};try{let r=new D;if(!t.json)g(`Restarting agent: ${a.name}`),c(),o(`${d.info} Stopping agent ${i.bold(a.name)}...`);let h=await r.getStatus(a.name);try{if(await r.stop(a.name),!t.json)l(`${d.success} Agent stopped.`)}catch{if(!t.json)o(`${d.info} Agent was not running.`)}let P=a.port??h?.port??3005,O=typeof P==="number"?P:parseInt(P,10);if(isNaN(O)||O<1||O>65535){if(t.json){u(t,{ok:!1,error:"Invalid port number"});return}s("Invalid port number. Must be between 1 and 65535.");return}let E=t.profile??h?.config?.profile??process.env.VIBECONTROLS_PROFILE??"default";process.env.VIBECONTROLS_PROFILE=E;let N={port:O,name:a.name,daemon:!0,dbPath:a.dbPath??h?.config?.dbPath??ee(),host:h?.config?.host,profile:E};if(!t.json)c(),o(`${d.info} Starting agent ${i.bold(a.name)}...`);await r.startDaemon(N);let x;if(a.autostart!==!1){let{ensureAutostartConfigured:T}=await import("./autostart.cmd-ahet7b1t.js");x=await T({name:a.name,port:O,dbPath:N.dbPath,host:N.host,profile:N.profile});let Z=x;if(Z.installed&&!t.json)o(`Configured ${Z.serviceLabel} autostart \u2014 supervised from the next login/boot. `+"The daemon running now is not yet under it; hand it over with `vibe stop && vibe autostart install`.");else if(Z.failed&&!t.json)p(`Could not configure autostart (${Z.reason}). This agent will NOT come back after logout or reboot \u2014 fix the cause or run \`vibe autostart install\`.`)}let j=`http://localhost:${O}`;if(u(t,{ok:!0,name:a.name,port:O,url:j,autostart:x?{installed:x.installed,failed:x.failed??!1,reason:x.reason}:{installed:!1,failed:!1,reason:"opted out"}}))return;c(),l(`${d.success} Agent ${i.bold(a.name)} restarted.`),c(),n("Port",String(O)),n("Database",N.dbPath),c(),Ut(j)}catch(r){if(t.json){u(t,{ok:!1,error:A(r)});return}s(`Failed to restart agent: ${A(r)}`)}})}import{existsSync as bo,readFileSync as yo,unlinkSync as on}from"fs";import{join as sn}from"path";function wo(k){let a=sn(ne(),k,"runtime.json");if(!bo(a))return null;try{let t=JSON.parse(yo(a,"utf8"));if(typeof t.pid!=="number")return null;return{...t,pid:t.pid,path:a}}catch{return null}}async function rn(k){let a=wo(k);if(!a)return null;if(!ae(a.pid)){try{on(a.path)}catch{}return`agent pid=${a.pid} (${k}) already gone (cleaned runtime.json).`}let t=b();if(!t.killProcessTree(a.pid,"SIGTERM"))return`failed to SIGTERM agent pid=${a.pid}.`;if(await new Promise((r)=>setTimeout(r,3000)),ae(a.pid))t.killProcessTree(a.pid,"SIGKILL");try{on(a.path)}catch{}return`agent ${k} pid=${a.pid}${a.port?` (port ${a.port})`:""} killed.`}async function ko(k){let a=sn(ne(),k),t=te(a);if(!t)return null;if(!ae(t.pid))return re(a),`tunnel pid=${t.pid} already gone (cleaned state).`;let r=b();if(!r.killProcessTree(t.pid,"SIGTERM"))return`failed to SIGTERM tunnel pid=${t.pid}.`;if(await new Promise((h)=>setTimeout(h,3000)),ae(t.pid))r.killProcessTree(t.pid,"SIGKILL");return re(a),`tunnel ${t.provider} pid=${t.pid} (${t.url??"no url"}) killed.`}function an(k){k.command("kill").description("Force-kill an agent instance and its tunnel. Defaults to active profile.").option("-n, --name <name>","Agent instance name (alias of --profile, kept for back-compat)").option("--profile <name>","Kill a specific profile (overrides --name and VIBECONTROLS_PROFILE)").option("--all","Kill every agent instance and every profile's tunnel",!1).option("-y, --yes","Skip the confirmation prompt (for scripts/CI)",!1).option("--json","Emit JSON").action(async function(a){let t={...k.opts(),...a},r=a.all?"ALL agent instances + every profile's tunnel":`agent '${t.profile??t.name??"active profile"}'`;if(!await vt(t,`Force-kill ${r}? This sends SIGKILL (no graceful shutdown).`)){o("Aborted.");return}let h=[];try{let P=new D;if(a.all){if(!t.json)g("Force killing all agent instances + tunnels"),c();let x=await P.listInstances()??[],j=0,T=new Set;for(let V of x)try{if(await P.kill(V.name),!t.json)l(`${d.success} agent ${i.bold(V.name)} (pid=${V.pid||"?"}) killed.`);h.push(V.name),j++,T.add(V.name)}catch{if(!t.json)p(`${d.warning} could not kill agent ${V.name}.`)}try{let V=await import("fs"),oe=ne(),K=V.existsSync(oe)?V.readdirSync(oe):[];for(let X of K){if(T.has(X))continue;let se=await rn(X);if(se)l(`${d.success} ${se}`),j++}}catch(V){p(`${d.warning} runtime.json sweep failed: ${V instanceof Error?A(V):String(V)}`)}let Z=Ii({allProfiles:!0}),B=0;for(let V of Z){if(!V.alive){re(V.profileDir);continue}let oe=b();if(oe.killProcessTree(V.pid,"SIGTERM"),await new Promise((K)=>setTimeout(K,3000)),ae(V.pid))oe.killProcessTree(V.pid,"SIGKILL");re(V.profileDir),l(`${d.success} tunnel ${V.provider} pid=${V.pid} (${V.url??"no url"}, ${V.profileDir.split("/").pop()}) killed.`),B++}if(u(t,{ok:!0,killed:h,tunnels:B}))return;c(),l(`${d.success} killed ${j} agent(s) and ${B} tunnel(s).`);return}let O=a.profile||a.name||R();if(!t.json)g(`Force killing profile: ${O}`),c();let E=await P.getStatus(O);if(E){if(await P.kill(O),h.push(O),!t.json)l(`${d.success} agent ${i.bold(O)} pid=${E.pid||"?"} killed.`)}else{let x=await rn(O);if(x){if(h.push(O),!t.json)l(`${d.success} ${x}`)}else if(!t.json)o(`${d.info} no running agent service for profile ${O}.`)}let N=await ko(O);if(N){if(!t.json)l(`${d.success} ${N}`)}else if(!t.json)o(`${d.info} no tunnel recorded for profile ${O}.`);u(t,{ok:!0,killed:h})}catch(P){if(t.json){u(t,{ok:!1,error:A(P)});return}s(`Failed to kill: ${A(P)}`)}})}function ln(k){k.command("list").alias("ls").description("List all VibeControls agent instances").option("--json","Emit JSON").option("--plain","Force plain text output").action(async function(a){try{let t={...k.opts(),...a},r=new D;await y({mode:_(t),fetchData:()=>r.listInstances(),plain:(h)=>{if(g("Agent Instances"),c(),!h||h.length===0){o(`${d.info} No agent instances found.`),o(`Run ${i.bold("vibe start")} to start an agent.`);return}let P=h.map((N)=>({Name:N.name,Status:G(N.status),PID:N.pid||"-",Port:N.port||"-",Host:N.config?.host||"-",Database:N.config?.dbPath||"-",Started:N.startTime?v(N.startTime):"-"}));F(P),c();let O=h.filter((N)=>N.status==="running").length,E=h.length-O;o(`${d.info} ${h.length} instance(s): ${i.green(String(O))} running, ${i.dim(String(E))} stopped`)},interactive:async(h)=>{if(!h||h.length===0){g("Agent Instances"),c(),o(`${d.info} No agent instances found.`),o(`Run ${i.bold("vibe start")} to start an agent.`);return}let P=h.map((O)=>{let E=[`${i.bold(O.name)} ${G(O.status)}`,"",` PID: ${O.pid??"-"}`,` Port: ${O.port??"-"}`,` Host: ${O.config?.host??"-"}`,` Database: ${O.config?.dbPath??"-"}`,` Started: ${O.startTime?v(O.startTime):"-"}`];return{id:O.name,label:O.name,hint:O.status==="running"?"running":"stopped",detail:E.join(`
|
|
2
|
+
import{z,R,I,ne,ee,C,e}from"./index-0qjbnyg4.js";import{J,$r,Ui,Qt,lr,fe,je,pe,jt,Hr,_t,et,Yr,gr,dr,tt,hr,w,M,yt}from"./index-kwhx023z.js";import{i,d,s,A,l,p,o,g,n,c,F,v,G,H,Ut}from"./index-7f2k4g6q.js";import{he,Q,U}from"./index-vtsd74g0.js";import{Me,st}from"./index-652f9scs.js";import{ie,Y,ye,qi,Pr,Mt,W}from"./index-g08z6z5v.js";import{qr}from"./index-cy97asyh.js";import{qe}from"./index-mmx2kp76.js";import{He,qt,Ei,_i,er,yi,tr,Si,ot,te,re,ae,Ii,at,De,Ci,Ve,Ye,Ne,Rt,Ze,nr,Le,Je,We,ct,ut,lt,gt,Or,dt,Ft,Ot,Bt,me}from"./index-v35k2y31.js";import{fi}from"./index-0gmhd3hs.js";import{pi}from"./index-akk3rxnn.js";import{D}from"./index-75hk5q9s.js";import{Pt}from"./index-gnb8xw13.js";import{b}from"./index-w4jqdhc2.js";import{Ri,L}from"./index-b3v08awy.js";import{ve}from"./index-4z1y39jt.js";import{Se,Ie,_,y,u,vt}from"./index-t5cfkz1e.js";import{f,m,S,q,Ce,Ae}from"./index-byerrz46.js";import{existsSync as Xt}from"fs";import{join as ho}from"path";import{createServer as fo}from"net";function go(k,a="0.0.0.0"){return new Promise((t)=>{let r=fo();r.once("error",()=>t(!1)),r.once("listening",()=>{r.close(()=>t(!0))}),r.listen({host:a,port:k,exclusive:!0})})}async function Zt(k,a="0.0.0.0"){let t=k;while(!await go(t,a))if(t++,t>65535)throw Error(`No free port found starting from ${k}`);return t}function en(k){k.command("start").description("Start a VibeControls agent instance").option("-p, --port <port>","Port to listen on. Default: 3005 for the 'default' profile, deterministic 3100-3399 for any other profile (FNV-1a hash) so multiple profiles run side-by-side without EADDRINUSE.").option("-n, --name <name>","Agent instance name","default").option("-f, --foreground","Run in foreground mode (default: daemon)",!1).option("--no-autostart","Don't configure OS-level autostart for this agent. Without it the daemon dies with the session that started it and will not come back.").option("--db-path <path>","Path to the agent storage directory").option("--profile <profile>","Profile name for isolated config (env: VIBECONTROLS_PROFILE)").option("--host <host>","Host to bind to","0.0.0.0").option("--skip-plugin-install","Skip automatic installation of default plugins",!1).option("--skip-plugin <name>","Skip a specific default plugin (repeatable). Accepts the short pluginName or the full package name.",(a,t=[])=>[...t,a],[]).option("--no-install-deps","Skip auto-installing missing tools (installed by their plugins on start by default)").option("-y, --yes","Skip the first-run install consent prompt. Equivalent to VIBE_AUTO_ACCEPT=1; useful for CI / Docker / nohup contexts.",!1).option("--client-id <id>","Gateway OAuth client ID (env: VIBE_CLIENT_ID)").option("--client-secret <secret>","Gateway OAuth client secret (env: VIBE_CLIENT_SECRET)").option("--global-gateway-url <url>","Global gateway URL (env: VIBE_GLOBAL_GATEWAY_URL)").option("--workspace-gateway-url <url>","Workspace gateway URL (env: VIBE_WORKSPACE_GATEWAY_URL)").option("--workspace-id <id>","Workspace ID for auto-report (env: VIBE_WORKSPACE_ID)").option("--isolate <plugins>","Comma-separated list of plugin names to force into worker_threads isolation (Phase 4 hostile-plugin mode). Sets VIBE_ISOLATE_PLUGINS in the daemon env.").option("--profiles <names>","Comma-separated list of profiles to host in this daemon (multi-profile boot). When unset, the daemon hosts a single profile resolved via --profile / VIBECONTROLS_PROFILE / 'default'. Sets VIBECONTROLS_PROFILES in the daemon env so app boot can spin up additional ProfileContexts via the in-process registry.").option("--strict-key-fetch","Refuse to boot if any profile's encryption-key fetch fails. Default lenient: a failed profile is marked degraded and the daemon stays up. Sets VIBE_STRICT_KEY_FETCH=1 in the daemon env.",!1).option("--json","Emit JSON").option("--plain","Plain text output (no interactive TUI). Implied for non-TTY / CI.").option("--abilities <list>","Comma-separated ability keys to install non-interactively (e.g. session,ai,gitops). Storage/tunnel/backup are always included.").option("--providers <list>","Comma-separated extra provider plugins to install beyond each meta's default (e.g. session-wezterm,ai-claude). Accepts short names or @vibecontrols/... packages. Persisted; manage later with `vibe capability`.").option("--wait-ready [seconds]","Block until the agent is fully ready (or fails). Polls /health/ready and renders phase transitions live. Without a value, defaults to 60s. Exits non-zero if the agent ends up degraded or times out. Useful for scripts/CI.").option("--no-wait","Skip the phase tracker entirely after spawning the daemon. Restores the old fire-and-print behavior \u2014 for users who want the previous quick-return UX.").action(async function(a){let t={...k.opts(),...a};try{let oe=function(le){if(le==="default")return 3005;let be=2166136261;for(let ge=0;ge<le.length;ge++)be=Math.imul(be^le.charCodeAt(ge),16777619);return 3100+Math.abs(be)%300},r=new D,h=a.profile||process.env.VIBECONTROLS_PROFILE||"default";if(process.env.VIBECONTROLS_PROFILE=h,typeof a.isolate==="string"&&a.isolate.length>0)process.env.VIBE_ISOLATE_PLUGINS=a.isolate;if(typeof a.profiles==="string"&&a.profiles.length>0){let le=a.profiles.split(",").map((be)=>be.trim()).filter(Boolean);if(le.length>0){if(process.env.VIBECONTROLS_PROFILES=le.join(","),process.env.VIBECONTROLS_PROFILE=le[0],le.length>1)p(`--profiles received ${le.length} entries; daemon boots with '${le[0]}'. Remaining (${le.slice(1).join(", ")}) will be attached via /api/profiles after listen.`)}}if(a.strictKeyFetch===!0)process.env.VIBE_STRICT_KEY_FETCH="1";yt();let P=a.dbPath||ee(),O=C(),E=!Xt(P)&&!Xt(ho(O,"agents.json")),N=_(t),x=N!=="json"&&N!=="plain"&&Se()&&a.yes!==!0,j=He(O),T;if(typeof t.abilities==="string"&&t.abilities.trim()!=="")T=yi(t.abilities);else if(j!==null)T=j;else if(x)T=await er();else T=tr();let Z=typeof t.providers==="string"&&t.providers.trim()!=="",B=Z?Ei(t.providers):qt(O);if(j===null){let le=_i({installDeps:a.installDeps===!0,skipPluginInstall:a.skipPluginInstall===!0,skipPlugins:Array.isArray(a.skipPlugin)?a.skipPlugin:[]},T);if(E&&le.plugins.length>0)c(),o(`Installing ${le.plugins.length} plugin(s) for the selected abilities.`),c();Si(O,le,T,process.env.VIBE_AGENT_VERSION,B)}else if(Z)ot(O,{providers:B,agentVersion:process.env.VIBE_AGENT_VERSION});if((E||Z)&&B.length>0&&a.skipPluginInstall!==!0){o(`Installing ${B.length} selected provider plugin(s)...`);try{let{PluginManager:le}=await import("./plugin-system-zj50tg4k.js"),be=new le;for(let ge of B)try{await be.install(ge),l(`Installed provider ${ge}`)}catch(we){p(`Could not install provider ${ge}: ${we instanceof Error?we.message:String(we)}`)}}catch(le){p(`Provider install skipped: ${le instanceof Error?le.message:String(le)}`)}c()}if(E){o("First run detected \u2014 running setup..."),c();let le=Array.isArray(a.skipPlugin)?a.skipPlugin:[],be=a.skipPluginInstall?[]:ye(process.platform,T).filter((Re)=>!le.includes(Re.packageName)&&!le.includes(Re.pluginName)).map((Re)=>Re.packageName),ge=qi(be),ze=Me(ge).filter((Re)=>!Re.installed);if(ze.length>0)if(p(`Missing tools: ${ze.map((Re)=>Re.name).join(", ")}`),a.installDeps)o("Their plugins will install them automatically on startup.");else o("Auto-install skipped (`--no-install-deps`) \u2014 install them yourself or drop the flag.");else l("All plugin tools present.");c()}if(!a.skipPluginInstall){let le=Array.isArray(a.skipPlugin)?a.skipPlugin:[],be=new W;await be.loadCorePlugins(),await be.loadAll();let ge=await be.ensureDefaultPlugins((we)=>{if(we.startsWith("No "))p(we);else if(we.startsWith("Installed "))l(we);else if(we.startsWith("Failed "))p(we);else o(we)},le,T);if(ge.length>0)l(`Auto-installed ${ge.length} default plugin${ge.length>1?"s":""}.`),c()}let V=a.profile||process.env.VIBECONTROLS_PROFILE||a.name||"default",K=a.port?parseInt(a.port,10):oe(V);if(isNaN(K)||K<1||K>65535)s("Invalid port number. Must be between 1 and 65535.");let X=await Zt(K);if(X!==K)p(`Port ${K} is in use. Auto-selecting port ${i.bold(String(X))} instead.`),K=X;let se=a.host,Oe=`http://${se==="0.0.0.0"?"localhost":se}:${K}`,$e=a.clientId||process.env.VIBE_CLIENT_ID,ce=a.clientSecret||process.env.VIBE_CLIENT_SECRET,de=a.globalGatewayUrl||process.env.VIBE_GLOBAL_GATEWAY_URL,ue=a.workspaceGatewayUrl||process.env.VIBE_WORKSPACE_GATEWAY_URL,_e=a.workspaceId||process.env.VIBE_WORKSPACE_ID;if($e&&!ce)s("--client-secret is required when --client-id is provided.");if(ce&&!$e)s("--client-id is required when --client-secret is provided.");if($e&&ce){if(!de&&!process.env.VIBE_GLOBAL_GATEWAY_URL)s("--global-gateway-url is required when providing client credentials (none set in env).");if(process.env.VIBE_CLIENT_ID=$e,process.env.VIBE_CLIENT_SECRET=ce,de)process.env.VIBE_GLOBAL_GATEWAY_URL=de;let{writeAgentConfig:le}=await import("./agent-config-v9d7gcz0.js");if(le({clientId:$e,clientSecret:ce,workspaceId:_e,globalGatewayUrl:de,workspaceGatewayUrl:ue}),ue)process.env.VIBE_WORKSPACE_GATEWAY_URL=ue;if(_e)process.env.VIBE_WORKSPACE_ID=_e;l("Gateway credentials staged in env. Agent will authenticate and persist them on startup."),c()}else if(ue||_e||de){if(p("Workspace options provided without --client-id / --client-secret \u2014 they will be staged in env but unused until credentials are configured."),ue)process.env.VIBE_WORKSPACE_GATEWAY_URL=ue;if(_e)process.env.VIBE_WORKSPACE_ID=_e;if(de)process.env.VIBE_GLOBAL_GATEWAY_URL=de;c()}if(a.foreground){if(!t.json)g("Starting agent in foreground"),n("Name",a.name),n("Port",String(K)),n("Host",se),n("Database",P),c();let{bootstrapWorkspace:le}=await import("./bootstrap-workspace-3pb8qjsh.js");le();let{createApp:be}=await import("./app-a95wetk5.js"),ge=await be({port:K,host:se,dbPath:P});if(await ge.start(),$e&&ce&&_e&&de&&ue){let ze=await ge.finalize({clientId:$e,clientSecret:ce,workspaceId:_e,globalGatewayUrl:de,workspaceGatewayUrl:ue});if(!ze.ok)p(`Finalize failed \u2014 agent remains in awaiting-config state: ${ze.error}`)}if(u(t,{ok:!0,name:a.name,port:K,host:se,pid:process.pid,url:Oe}));else await Ut(Oe);let we=async()=>{await ge.stop(),process.exit(0)};process.on("SIGTERM",we),process.on("SIGINT",we)}else{if(!t.json)g("Starting agent in daemon mode"),n("Name",a.name),n("Port",String(K)),n("Host",se),n("Database",P),c();if(a.installDeps===!1)process.env.VIBE_SKIP_PREREQ_INSTALL="1";await r.startDaemon({port:K,name:a.name,daemon:!0,dbPath:P,host:se,profile:h});let be=(await r.getStatus(a.name))?.port??K,ge;if(a.autostart!==!1){let{ensureAutostartConfigured:Te}=await import("./autostart.cmd-ahet7b1t.js"),ke=await Te({name:a.name,port:be,dbPath:P,host:se,profile:h});if(ge=ke,ke.installed&&!t.json)o(`Configured ${ke.serviceLabel} autostart \u2014 supervised from the next login/boot. `+"The daemon running now is not yet under it; hand it over with `vibe stop && vibe autostart install`.");else if(ke.failed&&!t.json)p(`Could not configure autostart (${ke.reason}). This agent will NOT come back after logout or reboot \u2014 fix the cause or run \`vibe autostart install\`.`)}let we=ge?{installed:ge.installed,failed:ge.failed??!1,reason:ge.reason}:{installed:!1,failed:!1,reason:"opted out"},Re=`http://${se==="0.0.0.0"?"localhost":se}:${be}`,kt=a.waitReady,$t=a.wait===!1,Ht=kt!==void 0;if($t&&Ht)p("--wait-ready is ignored because --no-wait was also passed.");let ft=!$t&&Ht,zt=!$t&&(ft||!t.json),Yt=(()=>{let Te=typeof kt==="string"?Number.parseInt(kt,10):NaN;if(Number.isInteger(Te)&&Te>0)return Te*1000;return ft?60000:25000})();if(t.json){if(zt){let{trackAgentReady:Te}=await import("./agent-ready-tracker-mewxehg9.js"),ke=await Te(Re,{timeoutMs:Yt,verbose:!1});if(ft&&(ke.outcome==="degraded"||ke.outcome==="timeout"))process.exitCode=1;u(t,{ok:ke.outcome==="ready"||ke.outcome==="awaiting-config",name:a.name,port:be,host:se,url:Re,abilities:[...T],outcome:ke.outcome,bootState:ke.bootState,degradedReasons:ke.degradedReasons,summary:ke.summary,autostart:we})}else u(t,{ok:!0,name:a.name,port:be,host:se,url:Re,autostart:we});return}if(await Ut(Re),zt){let{trackAgentReady:Te}=await import("./agent-ready-tracker-mewxehg9.js");c();let ke=await Te(Re,{timeoutMs:Yt,verbose:!0});if(ft&&(ke.outcome==="degraded"||ke.outcome==="timeout"))process.exitCode=1}}}catch(r){let h=r instanceof Error?A(r):String(r);if(t.json){u(t,{ok:!1,error:h});return}s(`Failed to start agent: ${h}`)}})}function tn(k){k.command("stop").description("Stop a running VibeControls agent instance").option("-n, --name <name>","Agent instance name","default").option("--all","Stop all running agent instances",!1).option("--json","Emit JSON").action(async function(a){let t={...k.opts(),...a};try{let r=new D;if(a.all){let h=await r.listInstances();if(!h||h.length===0){if(u(t,{ok:!0,stopped:[]}))return;g("Stopping all agent instances"),c(),o(`${d.info} No running agent instances found.`);return}let P=[];if(!t.json)g("Stopping all agent instances"),c();for(let O of h)try{if(await r.stop(O.name),P.push(O.name),!t.json)l(`${d.success} Stopped ${i.bold(O.name)}`)}catch{if(!t.json)s(`Failed to stop ${i.bold(O.name)}`)}if(u(t,{ok:!0,stopped:P,total:h.length}))return;c(),l(`${d.success} Stopped ${P.length}/${h.length} instance(s).`)}else{if(await r.stop(a.name),u(t,{ok:!0,name:a.name}))return;g(`Stopping agent: ${a.name}`),c(),l(`${d.success} Agent ${i.bold(a.name)} stopped.`)}}catch(r){if(t.json){u(t,{ok:!1,error:A(r)});return}s(`Failed to stop agent: ${A(r)}`)}})}function nn(k){k.command("restart").description("Restart a running VibeControls agent instance").option("-n, --name <name>","Agent instance name","default").option("-p, --port <port>","Port to listen on").option("--db-path <path>","Path to the agent storage directory").option("--json","Emit JSON").option("--no-autostart","Don't configure OS-level autostart for this agent. Without it the daemon dies with the session that started it and will not come back.").action(async function(a){let t={...k.opts(),...a};try{let r=new D;if(!t.json)g(`Restarting agent: ${a.name}`),c(),o(`${d.info} Stopping agent ${i.bold(a.name)}...`);let h=await r.getStatus(a.name);try{if(await r.stop(a.name),!t.json)l(`${d.success} Agent stopped.`)}catch{if(!t.json)o(`${d.info} Agent was not running.`)}let P=a.port??h?.port??3005,O=typeof P==="number"?P:parseInt(P,10);if(isNaN(O)||O<1||O>65535){if(t.json){u(t,{ok:!1,error:"Invalid port number"});return}s("Invalid port number. Must be between 1 and 65535.");return}let E=t.profile??h?.config?.profile??process.env.VIBECONTROLS_PROFILE??"default";process.env.VIBECONTROLS_PROFILE=E;let N={port:O,name:a.name,daemon:!0,dbPath:a.dbPath??h?.config?.dbPath??ee(),host:h?.config?.host,profile:E};if(!t.json)c(),o(`${d.info} Starting agent ${i.bold(a.name)}...`);await r.startDaemon(N);let x;if(a.autostart!==!1){let{ensureAutostartConfigured:T}=await import("./autostart.cmd-ahet7b1t.js");x=await T({name:a.name,port:O,dbPath:N.dbPath,host:N.host,profile:N.profile});let Z=x;if(Z.installed&&!t.json)o(`Configured ${Z.serviceLabel} autostart \u2014 supervised from the next login/boot. `+"The daemon running now is not yet under it; hand it over with `vibe stop && vibe autostart install`.");else if(Z.failed&&!t.json)p(`Could not configure autostart (${Z.reason}). This agent will NOT come back after logout or reboot \u2014 fix the cause or run \`vibe autostart install\`.`)}let j=`http://localhost:${O}`;if(u(t,{ok:!0,name:a.name,port:O,url:j,autostart:x?{installed:x.installed,failed:x.failed??!1,reason:x.reason}:{installed:!1,failed:!1,reason:"opted out"}}))return;c(),l(`${d.success} Agent ${i.bold(a.name)} restarted.`),c(),n("Port",String(O)),n("Database",N.dbPath),c(),Ut(j)}catch(r){if(t.json){u(t,{ok:!1,error:A(r)});return}s(`Failed to restart agent: ${A(r)}`)}})}import{existsSync as bo,readFileSync as yo,unlinkSync as on}from"fs";import{join as sn}from"path";function wo(k){let a=sn(ne(),k,"runtime.json");if(!bo(a))return null;try{let t=JSON.parse(yo(a,"utf8"));if(typeof t.pid!=="number")return null;return{...t,pid:t.pid,path:a}}catch{return null}}async function rn(k){let a=wo(k);if(!a)return null;if(!ae(a.pid)){try{on(a.path)}catch{}return`agent pid=${a.pid} (${k}) already gone (cleaned runtime.json).`}let t=b();if(!t.killProcessTree(a.pid,"SIGTERM"))return`failed to SIGTERM agent pid=${a.pid}.`;if(await new Promise((r)=>setTimeout(r,3000)),ae(a.pid))t.killProcessTree(a.pid,"SIGKILL");try{on(a.path)}catch{}return`agent ${k} pid=${a.pid}${a.port?` (port ${a.port})`:""} killed.`}async function ko(k){let a=sn(ne(),k),t=te(a);if(!t)return null;if(!ae(t.pid))return re(a),`tunnel pid=${t.pid} already gone (cleaned state).`;let r=b();if(!r.killProcessTree(t.pid,"SIGTERM"))return`failed to SIGTERM tunnel pid=${t.pid}.`;if(await new Promise((h)=>setTimeout(h,3000)),ae(t.pid))r.killProcessTree(t.pid,"SIGKILL");return re(a),`tunnel ${t.provider} pid=${t.pid} (${t.url??"no url"}) killed.`}function an(k){k.command("kill").description("Force-kill an agent instance and its tunnel. Defaults to active profile.").option("-n, --name <name>","Agent instance name (alias of --profile, kept for back-compat)").option("--profile <name>","Kill a specific profile (overrides --name and VIBECONTROLS_PROFILE)").option("--all","Kill every agent instance and every profile's tunnel",!1).option("-y, --yes","Skip the confirmation prompt (for scripts/CI)",!1).option("--json","Emit JSON").action(async function(a){let t={...k.opts(),...a},r=a.all?"ALL agent instances + every profile's tunnel":`agent '${t.profile??t.name??"active profile"}'`;if(!await vt(t,`Force-kill ${r}? This sends SIGKILL (no graceful shutdown).`)){o("Aborted.");return}let h=[];try{let P=new D;if(a.all){if(!t.json)g("Force killing all agent instances + tunnels"),c();let x=await P.listInstances()??[],j=0,T=new Set;for(let V of x)try{if(await P.kill(V.name),!t.json)l(`${d.success} agent ${i.bold(V.name)} (pid=${V.pid||"?"}) killed.`);h.push(V.name),j++,T.add(V.name)}catch{if(!t.json)p(`${d.warning} could not kill agent ${V.name}.`)}try{let V=await import("fs"),oe=ne(),K=V.existsSync(oe)?V.readdirSync(oe):[];for(let X of K){if(T.has(X))continue;let se=await rn(X);if(se)l(`${d.success} ${se}`),j++}}catch(V){p(`${d.warning} runtime.json sweep failed: ${V instanceof Error?A(V):String(V)}`)}let Z=Ii({allProfiles:!0}),B=0;for(let V of Z){if(!V.alive){re(V.profileDir);continue}let oe=b();if(oe.killProcessTree(V.pid,"SIGTERM"),await new Promise((K)=>setTimeout(K,3000)),ae(V.pid))oe.killProcessTree(V.pid,"SIGKILL");re(V.profileDir),l(`${d.success} tunnel ${V.provider} pid=${V.pid} (${V.url??"no url"}, ${V.profileDir.split("/").pop()}) killed.`),B++}if(u(t,{ok:!0,killed:h,tunnels:B}))return;c(),l(`${d.success} killed ${j} agent(s) and ${B} tunnel(s).`);return}let O=a.profile||a.name||R();if(!t.json)g(`Force killing profile: ${O}`),c();let E=await P.getStatus(O);if(E){if(await P.kill(O),h.push(O),!t.json)l(`${d.success} agent ${i.bold(O)} pid=${E.pid||"?"} killed.`)}else{let x=await rn(O);if(x){if(h.push(O),!t.json)l(`${d.success} ${x}`)}else if(!t.json)o(`${d.info} no running agent service for profile ${O}.`)}let N=await ko(O);if(N){if(!t.json)l(`${d.success} ${N}`)}else if(!t.json)o(`${d.info} no tunnel recorded for profile ${O}.`);u(t,{ok:!0,killed:h})}catch(P){if(t.json){u(t,{ok:!1,error:A(P)});return}s(`Failed to kill: ${A(P)}`)}})}function ln(k){k.command("list").alias("ls").description("List all VibeControls agent instances").option("--json","Emit JSON").option("--plain","Force plain text output").action(async function(a){try{let t={...k.opts(),...a},r=new D;await y({mode:_(t),fetchData:()=>r.listInstances(),plain:(h)=>{if(g("Agent Instances"),c(),!h||h.length===0){o(`${d.info} No agent instances found.`),o(`Run ${i.bold("vibe start")} to start an agent.`);return}let P=h.map((N)=>({Name:N.name,Status:G(N.status),PID:N.pid||"-",Port:N.port||"-",Host:N.config?.host||"-",Database:N.config?.dbPath||"-",Started:N.startTime?v(N.startTime):"-"}));F(P),c();let O=h.filter((N)=>N.status==="running").length,E=h.length-O;o(`${d.info} ${h.length} instance(s): ${i.green(String(O))} running, ${i.dim(String(E))} stopped`)},interactive:async(h)=>{if(!h||h.length===0){g("Agent Instances"),c(),o(`${d.info} No agent instances found.`),o(`Run ${i.bold("vibe start")} to start an agent.`);return}let P=h.map((O)=>{let E=[`${i.bold(O.name)} ${G(O.status)}`,"",` PID: ${O.pid??"-"}`,` Port: ${O.port??"-"}`,` Host: ${O.config?.host??"-"}`,` Database: ${O.config?.dbPath??"-"}`,` Started: ${O.startTime?v(O.startTime):"-"}`];return{id:O.name,label:O.name,hint:O.status==="running"?"running":"stopped",detail:E.join(`
|
|
3
3
|
`)}});await Q({title:`vibe list \u2014 ${h.length} instance(s)`,rows:P,footer:"\u2191/\u2193 navigate \xB7 q to quit"})},json:(h)=>h.map((P)=>({name:P.name,status:P.status,pid:P.pid??null,port:P.port??null,host:P.config?.host??null,database:P.config?.dbPath??null,startTime:P.startTime??null}))})}catch(t){s(`Failed to list instances: ${t.message}`)}})}var cn=5000;function dn(k){k.command("logs").description("View logs for a VibeControls agent instance").option("-n, --name <name>","Agent instance name","default").option("-f, --follow","Follow log output",!1).option("--tail <lines>","Number of lines to show from the end","100").option("--json","Emit JSON (one object per line, banners suppressed)").option("--plain","Force plain text output").action(async function(a){try{let t={...k.opts(),...a},r=new D,h=parseInt(t.tail??"100",10);if(isNaN(h)||h<1||h>cn){s(`Invalid tail value. Must be between 1 and ${cn}.`);return}let P=t.name??"default";if(!await r.getStatus(P)){s(`Agent instance ${i.bold(P)} not found.`);return}if(!t.json){if(t.follow)g(`Following logs: ${P}`),o(`${d.info} Press Ctrl+C to stop following.`);else g(`Logs: ${P}`);c()}await r.showLogs(P,{follow:!!t.follow,tail:h})}catch(t){s(`Failed to get logs: ${A(t)}`)}})}function un(k){k.command("setup").description("Install system dependencies and (optionally) write gateway auth config").option("--check","Only check dependencies without installing",!1).option("--client-id <id>","OAuth app client ID (for backend authentication)").option("--client-secret <secret>","OAuth app client secret").option("--workspace-id <id>","Workspace UUID this agent belongs to").option("--global-gateway-url <url>","Global public gateway URL (default: http://localhost:4000/global/graphql)").option("--workspace-gateway-url <url>","Workspace gateway URL (default: http://localhost:4001/workspaces/graphql)").option("--storage-adapter <name>","Named storage adapter (default: skalex, or custom:<path>)").option("--json","Emit JSON").action(async function(a){let t={...k.opts(),...a},r=[];try{if(!t.json)g("VibeControls Agent Setup");let h={};if(a.clientId)h.clientId=a.clientId;if(a.clientSecret)h.clientSecret=a.clientSecret;if(a.workspaceId)h.workspaceId=a.workspaceId;if(a.globalGatewayUrl)h.globalGatewayUrl=z(a.globalGatewayUrl,"globalGatewayUrl");if(a.workspaceGatewayUrl)h.workspaceGatewayUrl=z(a.workspaceGatewayUrl,"workspaceGatewayUrl");if(a.storageAdapter)h.storageAdapter=a.storageAdapter;if(Object.keys(h).length>0){let j=M(h);if(r.push(...Object.keys(h)),!t.json){l(`Agent config written to ${tt()}`),n("clientId",j.clientId?i.dim("(set)"):i.dim("(unset)")),n("clientSecret",j.clientSecret?i.dim("(set)"):i.dim("(unset)")),n("workspaceId",j.workspaceId??i.dim("(unset)"));let T=hr();if(n("globalGatewayUrl",j.globalGatewayUrl??T.globalGatewayUrl),n("workspaceGatewayUrl",j.workspaceGatewayUrl??T.workspaceGatewayUrl),j.storageAdapter)n("storageAdapter",j.storageAdapter);c()}}else{let j=w();if((j.clientId||j.clientSecret||j.workspaceId)&&!t.json)o(`Using existing agent config at ${tt()} (pass --client-id/--client-secret/--workspace-id to update).`),c()}if(!t.json)o("Checking dependencies..."),c();let P=Me(),O=[],E=[];for(let j of P){if(j.installed)E.push(j.name);if(!t.json){let T=j.installed?d.success:d.error,Z=j.version?i.dim(` (${j.version})`):"",B=j.required?"":i.dim(" [optional]");n(`${T} ${j.name}`,`${j.installed?i.green("installed"):i.red("missing")}${Z}${B}`)}if(!j.installed)O.push(j.name)}if(!t.json)c();if(O.length===0){if(u(t,{ok:!0,installed:E,configured:r}))return;l("All dependencies are installed.");return}if(a.check){if(t.json){u(t,{ok:!1,installed:E,missing:O,configured:r});return}p(`Missing: ${O.join(", ")}`),o(`Run ${i.bold("vibe setup")} to install them.`),process.exit(1)}if(!t.json)o(`Installing missing dependencies: ${O.join(", ")}...`),c();let N=await st(O),x=O.filter((j)=>!N.failed.includes(j));if(N.failed.length>0){if(t.json){u(t,{ok:!1,installed:[...E,...x],failed:N.failed,configured:r});return}p(`${N.failed.length} tool(s) failed: ${N.failed.join(", ")}`),o("You may need to install manually or use sudo."),process.exit(1)}else{if(u(t,{ok:!0,installed:[...E,...x],configured:r}))return;l("All dependencies installed successfully.")}}catch(h){let P=h instanceof Error?A(h):String(h);if(t.json){u(t,{ok:!1,error:P});return}s(`Setup failed: ${P}`)}})}function vo(k){let a=b();return a.which(k)??`${k}${a.executableSuffix}`}function pn(k){k.command("update").description("Check for and install VibeControls agent updates").option("--check","Only check for updates without installing",!1).option("--allow-incompatible","Override engines.bun compatibility check (use with care)",!1).option("--no-restart","Skip the post-install idle-aware restart of any running agent").option("-n, --name <name>","Agent profile name to restart after update","default").option("--version-target <version>","Install a specific version instead of the latest (e.g. 2026.601.21)").option("--json","Emit JSON").action(async function(a){let t={...k.opts(),...a};try{if(!t.json)g("VibeControls Agent Update"),c(),o(`${d.info} Checking for updates...`),c();let r=await Le();if(r.error&&!r.latest){if(u(t,{ok:!1,current:r.current,error:r.error}))return;s(r.error);return}if(!t.json)n("Package",i.bold(r.name)),n("Registry",i.bold(r.registry)),n("Current version",i.bold(r.current)),n("Latest version",i.bold(r.latest??"unknown")),c();if(a.check){if(u(t,{ok:!0,current:r.current,latest:r.latest,upToDate:!r.hasUpdate}))return;if(!r.hasUpdate)l(`${d.success} You are running the latest version.`);else p(`${d.warning} A new version is available: ${i.green(r.latest??"")}`),o(`${d.info} Run ${i.bold("vibe update")} to install the update.`);return}let h=a.versionTarget;if(!h&&!r.hasUpdate){if(u(t,{ok:!0,current:r.current,latest:r.latest,upToDate:!0}))return;l(`${d.success} You are running the latest version.`);return}if(!t.json)o(`${d.info} Updating to ${i.bold(h??r.latest??"latest")}...`),c();let P=await Je({targetVersion:h,allowIncompatible:!!a.allowIncompatible,restart:a.restart!==!1,name:a.name,onLog:t.json?void 0:(O)=>o(`${d.info} ${O}`)});if(!P.ok){if(u(t,{ok:!1,current:P.current,previous:P.previous,latest:P.latest,rolledBack:P.rolledBack,error:P.error}))return;s(P.error??"Update failed.");return}if(!t.json)switch(P.restart){case"restarted":l(`${d.success} Restarted agent ${i.bold(a.name)} on the new version.`);break;case"not-running":o(`${d.info} No running agent for profile ${i.bold(a.name)}; nothing to restart.`);break;case"still-busy":p(`${d.warning} Agent still serving requests \u2014 run ${i.bold("vibe restart")} when it's quiet.`);break;case"error":p(`${d.warning} Auto-restart failed: ${P.restartError}. Run ${i.bold("vibe restart")} manually.`);break}if(u(t,{ok:!0,current:P.current,previous:P.previous,latest:P.latest,updated:P.updated,restart:P.restart,...P.restartError?{restartError:P.restartError}:{}}))return;if(c(),P.updated)l(`${d.success} Updated to ${i.bold(P.current)} (smoke: ${P.smoke?.step??"ok"}).`);else l(`${d.success} You are running the latest version.`);if(a.restart===!1)o(`${d.info} --no-restart set \u2014 restart running agents manually for the update to take effect.`)}catch(r){let h=r instanceof Error?A(r):String(r);if(t.json){u(t,{ok:!1,error:h});return}s(`Update failed: ${h}`)}}),k.command("rollback").description("Roll the global agent install back to a specific version").argument("<version>","Target CalVer version (e.g. 2026.428.3)").action(async(a)=>{try{g("VibeControls Agent Rollback");let t=await nr();if(n("Package",i.bold(t.name)),n("Current version",i.bold(t.version)),n("Target version",i.bold(a)),c(),o(`${d.info} Rolling back\u2026`),Bun.spawnSync([vo("npm"),"install","-g",`${t.name}@${a}`,`--registry=${t.registry}`],{stdout:"inherit",stderr:"inherit"}).exitCode!==0){s("Rollback failed.");return}l(`${d.success} Rolled back to ${i.bold(a)}.`)}catch(t){s(`Rollback failed: ${t instanceof Error?A(t):String(t)}`)}})}import{existsSync as Ge,mkdirSync as $o,writeFileSync as At,unlinkSync as So,readFileSync as St}from"fs";import{join as Ue}from"path";import{homedir as Xe}from"os";var Co=/^[A-Za-z0-9][A-Za-z0-9:_-]{0,63}$/,Po=/^--[A-Za-z0-9][A-Za-z0-9-]{0,63}$/;function hn(k){return Co.test(k)?k:null}function bn(k){return k.filter((a)=>hn(a))}function Ro(k){return k.filter((a)=>Po.test(a))}function Qe(k){return k.commands.flatMap((a)=>{let t=hn(a.name());if(!t)return[];return[{name:t,description:a.description()||"",options:a.options.map((r)=>({flags:r.flags,description:r.description||""})),subcommands:Qe(a)}]})}function Ao(k){return bn(k.map((a)=>a.name))}function Io(k,a){let t=k.find((h)=>h.name===a);if(!t)return[];let r=[];for(let h of t.options){let P=h.flags.match(/--([\w-]+)/);if(P)r.push(`--${P[1]}`)}return Ro(r)}function yn(k){let a=Ao(k),r=k.filter((P)=>P.subcommands.length>0).map((P)=>({name:P.name,subs:bn(P.subcommands.map((O)=>O.name))})).map((P)=>` ${P.name})
|
|
4
4
|
COMPREPLY=($(compgen -W "${P.subs.join(" ")}" -- "\${cur}"))
|
|
5
5
|
return 0
|
|
@@ -112,5 +112,5 @@ Enter: print this help and exit
|
|
|
112
112
|
`);return}if(!r.plain&&Se()){if(await Zr(k))return}no(k,!!r.plain)}})}var Xr="http://localhost:3005",Qr=5000;function ei(k,a,t){let r=Number.parseInt(k,10);if(!Number.isInteger(r)||r<1)return a;return Math.min(r,t)}function io(k){k.command("audit").description("View persistent audit log").command("list").description("List recent audit events").option("--since <iso>","Lower-bound ISO 8601 timestamp").option("--limit <n>","Maximum events to show","100").option("--event <pattern>","Filter by event name (supports * glob)").option("--agent-url <url>","Agent URL",Xr).option("--json","Emit JSON (one object per line)").option("--plain","Force plain text output").action(async function(t){try{let r={...k.opts(),...t},h=f(r),P=encodeURIComponent(m(r)),O=new URLSearchParams;if(O.set("limit",String(ei(String(r.limit),100,Qr))),r.since)O.set("since",String(r.since));if(r.event)O.set("event",String(r.event));let N=(await S(h,`/api/profiles/${P}/agent/audit?${O.toString()}`)).events??[];if(r.json){for(let x of N)process.stdout.write(`${JSON.stringify(x)}
|
|
113
113
|
`);return}if(N.length===0){o("No audit events found.");return}g("Audit events"),c();for(let x of N){let j=x.timestamp?i.dim(v(x.timestamp)):"",T=x.source?i.cyan(`[${x.source}]`):"",Z=i.bold(x.event??"?"),B=x.payload?i.dim(JSON.stringify(x.payload)):"";console.log(` ${Z} ${T} ${B} ${j}`)}}catch(r){s(A(r))}})}function so(k){let a=k.command("alias").description("Manage per-profile aliases");a.command("list").description("List aliases for the current profile").option("--json","Emit JSON").option("--plain","Force plain text output").action(async function(t){try{let r={...k.opts(),...t},h=f(r),P=encodeURIComponent(m(r));await y({mode:_(r),fetchData:async()=>(await S(h,`/api/profiles/${P}/agent/aliases`)).aliases??[],plain:(O)=>{if(g("Aliases"),c(),!O.length){o("No aliases defined.");return}let E=O.map((N)=>({Name:N.name,Command:N.command.length>60?`${N.command.slice(0,57)}\u2026`:N.command,Description:N.description??"-",Updated:v(N.updatedAt)}));F(E),c()}})}catch(r){s(A(r))}}),a.command("get <name>").description("Show an alias by name").option("--json","Emit JSON").action(async function(t,r){try{let h={...k.opts(),...r},P=f(h),O=encodeURIComponent(m(h)),E=await S(P,`/api/profiles/${O}/agent/aliases/${encodeURIComponent(t)}`);if(h.json){process.stdout.write(`${JSON.stringify(E,null,2)}
|
|
114
114
|
`);return}g(`Alias: ${E.name}`),c(),console.log(` ${i.bold("Command: ")} ${E.command}`),console.log(` ${i.bold("Description:")} ${E.description??"-"}`),console.log(` ${i.bold("Cwd: ")} ${E.cwd??"$HOME (default)"}`),console.log(` ${i.bold("Profile: ")} ${E.profile}`),console.log(` ${i.bold("Created: ")} ${E.createdAt}`),console.log(` ${i.bold("Updated: ")} ${E.updatedAt}`),c()}catch(h){s(A(h))}}),a.command("create <name>").description("Create a new alias").requiredOption("--command <cmd>","The shell command to run").option("--description <text>","Optional description").option("--cwd <dir>","Working directory the command runs in (supports ~, absolute, or relative-to-$HOME). Defaults to $HOME.").action(async function(t,r){try{let h={...k.opts(),...r},P=f(h),O=encodeURIComponent(m(h)),E=await q(P,`/api/profiles/${O}/agent/aliases`,{name:t,command:r.command,description:r.description,cwd:r.cwd});l(`Created alias '${E.name}'`)}catch(h){s(A(h))}}),a.command("update <name>").description("Update an existing alias").option("--command <cmd>","Replacement shell command").option("--description <text>","Replacement description").option("--cwd <dir>","Replacement working directory. Pass an empty string to reset to $HOME.").action(async function(t,r){try{if(r.command===void 0&&r.description===void 0&&r.cwd===void 0){s("Provide --command, --description, or --cwd to update.");return}let h={...k.opts(),...r},P=f(h),O=encodeURIComponent(m(h)),E=await Ce(P,`/api/profiles/${O}/agent/aliases/${encodeURIComponent(t)}`,{command:r.command,description:r.description,cwd:r.cwd});l(`Updated alias '${E.name}'`)}catch(h){s(A(h))}}),a.command("delete <name>").description("Delete an alias").action(async function(t,r){try{let h={...k.opts(),...r},P=f(h),O=encodeURIComponent(m(h));await Ae(P,`/api/profiles/${O}/agent/aliases/${encodeURIComponent(t)}`),l(`Deleted alias '${t}'`)}catch(h){s(A(h))}})}function ao(k){k.command("run <name> [args...]").description("Run a stored alias by name").allowUnknownOption(!0).action(async function(a,t=[],r){try{let h={...k.opts(),...r},P=f(h),O=encodeURIComponent(m(h)),E;try{E=await S(P,`/api/profiles/${O}/agent/aliases/${encodeURIComponent(a)}`)}catch{console.error(`alias '${a}' not found`),e().audit.emit("agent","alias.executed",{exit_code:1}),process.exit(1)}let{exitCode:N}=await pi(E,t);e().audit.emit("agent","alias.executed",{exit_code:N}),ve("alias.executed",{exit_code:N}),process.exit(N)}catch(h){s(A(h))}})}function lo(k){k.command("retry-config").description("Force the background finalize-retry worker to attempt finalize immediately. Use when the gateway came back online and you don't want to wait the current backoff.").option("--json","Emit JSON").action(async function(a){let t={...k.opts(),...a};try{let r=f(t),h=await fetch(`${r}/api/agent/retry-config`,{method:"POST"}),P;try{P=await h.json()}catch{if(t.json)u(t,{ok:!1,error:`agent returned non-JSON (HTTP ${h.status})`}),process.exit(1);s(`Agent returned non-JSON response (HTTP ${h.status}). The daemon may be on an older build without /api/agent/retry-config.`),process.exit(1);return}if(t.json){if(u(t,P),P.state!=="ready")process.exit(P.ok?0:3);return}if(h.status===409){g("Retry not available"),o(P.error??"No active finalize-retry worker."),process.exit(2);return}if(g("Force finalize retry"),n("Result",P.ok?i.green("ok"):i.red("failed")),P.state)n("Boot state",P.state);if(P.worker){if(n("Attempt",String(P.worker.attempt)),P.worker.nextAttemptAt)n("Next attempt",P.worker.nextAttemptAt)}if(c(),P.ok&&P.state==="ready")o(`${i.green("\u2713")} Agent finalized \u2014 state=ready.`),process.exit(0);else if(P.ok)o(`${i.yellow("\u26A0")} Attempt completed but agent is still in '${P.state}'. The worker will continue to retry in the background; check ${i.bold("vibe status")} for progress.`),process.exit(0);else p(`Retry failed: ${P.error??"unknown error"}. The worker will keep retrying on the configured backoff. View the full trace with ${i.bold("vibe logs --since 10m")}.`),process.exit(3)}catch(r){let h=r instanceof Error?A(r):String(r);if(t.json){u(t,{ok:!1,error:h}),process.exit(1);return}s(`Failed to reach agent: ${h}`),process.exit(1)}})}var Ee="http://localhost:3005";function ti(k){return(k||[]).map((a)=>({id:a.id??null,name:a.name??null,status:a.status??null,port:a.port??null,project:a.project??a.projectId??null}))}async function co(k,a,t,r,h){await y({mode:_(h),fetchData:async()=>(await S(k,a)).sessions||[],plain:(P)=>{if(!P||P.length===0){o(r);return}g(t),F(P.map((O)=>({ID:H(O.id||""),Name:O.name||"-",Status:G(O.status||""),Port:O.port??"-",Project:O.project||O.projectId||"-"})))},interactive:async(P)=>{if(!P||P.length===0){g(t),o(r);return}let O=P.map((E)=>({id:String(E.id??""),label:E.name||H(E.id||""),hint:E.status||"",detail:[`ID: ${E.id??"-"}`,`Name: ${E.name??"-"}`,`Status: ${G(E.status||"")}`,`Port: ${E.port??"-"}`,`Project: ${E.project??E.projectId??"-"}`].join(`
|
|
115
|
-
`)}));await Q({title:`${t} \u2014 ${P.length} session(s)`,rows:O})},json:(P)=>ti(P)})}function uo(k){let a=k.command("session").description("Manage terminal sessions");a.command("system").description("List system sessions (alias for `session list --system`)").option("--agent-url <url>","Agent URL",Ee).option("--json","Emit JSON").option("--plain","Force plain text output").action(async function(t){let r={...k.opts(),...t};try{let h=f(t),P=encodeURIComponent(m(r));await co(h,`/api/profiles/${P}/sessions/system`,"System Sessions","No system sessions found.",r)}catch(h){s(A(h))}}),a.command("list").description("List all sessions").option("--system","Show system sessions instead of user sessions").option("--agent-url <url>","Agent URL",Ee).option("--json","Emit JSON").option("--plain","Force plain text output").action(async function(t){let r={...k.opts(),...t};try{let h=f(t),P=encodeURIComponent(m(r)),O=t.system?`/api/profiles/${P}/sessions/system`:`/api/profiles/${P}/sessions`;await co(h,O,"Sessions","No sessions found.",r)}catch(h){s(A(h))}}),a.command("create").description("Create a new session").requiredOption("--name <name>","Session name").option("--project <id>","Project ID","default").option("--command <cmd>","Initial command to run").option("--cwd <dir>","Working directory").option("--agent-url <url>","Agent URL",Ee).option("--json","Emit JSON").action(async function(t){let r={...k.opts(),...t};try{let h=f(t),P=encodeURIComponent(m(r)),O={sessionName:t.name,projectId:t.project};if(t.command)O.command=t.command;if(t.cwd)O.startDirectory=t.cwd;let E=await q(h,`/api/profiles/${P}/sessions/create`,O),N=E?.session?.id||E?.id||E?.sessionId;if(u(r,{ok:!0,id:N,name:t.name,project:t.project}))return;l(`Session created: ${H(N)}`),n("Name",t.name),n("Project",t.project)}catch(h){if(r.json){u(r,{ok:!1,error:A(h)});return}s(A(h))}}),a.command("kill").description("Kill a session").requiredOption("-i, --id <id>","Session ID").option("--agent-url <url>","Agent URL",Ee).option("--json","Emit JSON").action(async function(t){let r={...k.opts(),...t};try{let h=f(t),P=encodeURIComponent(m(r));if(await Ae(h,`/api/profiles/${P}/sessions/${t.id}`),u(r,{ok:!0,id:t.id}))return;l(`Session ${H(t.id)} killed.`)}catch(h){if(r.json){u(r,{ok:!1,error:A(h)});return}s(A(h))}}),a.command("exec").description("Execute a command in a session").requiredOption("-i, --id <id>","Session ID").requiredOption("-c, --command <cmd>","Command to execute").option("--agent-url <url>","Agent URL",Ee).option("--json","Emit JSON").action(async function(t){let r={...k.opts(),...t};try{let h=f(t),P=encodeURIComponent(m(r)),O=await q(h,`/api/profiles/${P}/sessions/${t.id}/command`,{command:t.command});if(u(r,{ok:!0,id:t.id,output:O?.output??null}))return;if(l("Command executed."),O?.output)c(),console.log(O.output)}catch(h){if(r.json){u(r,{ok:!1,error:A(h)});return}s(A(h))}}),a.command("capture").description("Capture session terminal output").requiredOption("-i, --id <id>","Session ID").option("--agent-url <url>","Agent URL",Ee).option("--json","Emit JSON").option("--plain","Force plain text output").action(async function(t){let r={...k.opts(),...t};try{let h=f(t),P=encodeURIComponent(m(r));await y({mode:_(r),fetchData:()=>S(h,`/api/profiles/${P}/sessions/${t.id}/capture`),plain:(O)=>{if(O?.content||O?.output)console.log(O.content||O.output);else o("No capture data available.")},json:(O)=>({id:t.id,content:O?.content??O?.output??null})})}catch(h){s(A(h))}}),a.command("keys").description("Send keys to a session").requiredOption("-i, --id <id>","Session ID").requiredOption("-k, --keys <keys>","Keys to send").option("--agent-url <url>","Agent URL",Ee).option("--json","Emit JSON").action(async function(t){let r={...k.opts(),...t};try{let h=f(t),P=encodeURIComponent(m(r));if(await q(h,`/api/profiles/${P}/sessions/${t.id}/keys`,{keys:t.keys}),u(r,{ok:!0,id:t.id}))return;l("Keys sent.")}catch(h){if(r.json){u(r,{ok:!1,error:A(h)});return}s(A(h))}}),a.command("interrupt").description("Send interrupt signal to a session").requiredOption("-i, --id <id>","Session ID").option("--agent-url <url>","Agent URL",Ee).option("--json","Emit JSON").action(async function(t){let r={...k.opts(),...t};try{let h=f(t),P=encodeURIComponent(m(r));if(await q(h,`/api/profiles/${P}/sessions/${t.id}/interrupt`,{}),u(r,{ok:!0,id:t.id}))return;l(`Session ${H(t.id)} interrupted.`)}catch(h){if(r.json){u(r,{ok:!1,error:A(h)});return}s(A(h))}}),a.command("rename").description("Rename a session").requiredOption("-i, --id <id>","Session ID").requiredOption("--name <name>","New session name").option("--agent-url <url>","Agent URL",Ee).option("--json","Emit JSON").action(async function(t){let r={...k.opts(),...t};try{let h=f(t),P=encodeURIComponent(m(r));if(await Ce(h,`/api/profiles/${P}/sessions/${t.id}/rename`,{newName:t.name}),u(r,{ok:!0,id:t.id,name:t.name}))return;l(`Session ${H(t.id)} renamed to "${t.name}".`)}catch(h){if(r.json){u(r,{ok:!1,error:A(h)});return}s(A(h))}}),a.command("toggle-mouse").description("Toggle mouse support in a session").requiredOption("-i, --id <id>","Session ID").option("--agent-url <url>","Agent URL",Ee).option("--json","Emit JSON").action(async function(t){let r={...k.opts(),...t};try{let h=f(t),P=encodeURIComponent(m(r)),O=await q(h,`/api/profiles/${P}/sessions/${t.id}/toggle-mouse`,{});if(u(r,{ok:!0,id:t.id,mouseEnabled:!!O?.mouseEnabled}))return;l(`Mouse support ${O?.mouseEnabled?"enabled":"toggled"} for session ${H(t.id)}.`)}catch(h){if(r.json){u(r,{ok:!1,error:A(h)});return}s(A(h))}}),a.command("terminal-start").description("Start terminal for a session").requiredOption("-i, --id <id>","Session ID").option("--agent-url <url>","Agent URL",Ee).option("--json","Emit JSON").action(async function(t){let r={...k.opts(),...t};try{let h=f(t),P=encodeURIComponent(m(r)),O=await q(h,`/api/profiles/${P}/sessions/${t.id}/terminal`,{});if(u(r,{ok:!0,id:t.id,port:O?.port??null}))return;if(l(`Terminal started for session ${H(t.id)}.`),O?.port)n("Port",O.port)}catch(h){if(r.json){u(r,{ok:!1,error:A(h)});return}s(A(h))}}),a.command("terminal-stop").description("Stop terminal for a session").requiredOption("-i, --id <id>","Session ID").option("--agent-url <url>","Agent URL",Ee).option("--json","Emit JSON").action(async function(t){let r={...k.opts(),...t};try{let h=f(t),P=encodeURIComponent(m(r));if(await q(h,`/api/profiles/${P}/sessions/${t.id}/terminal/stop`,{}),u(r,{ok:!0,id:t.id}))return;l(`Terminal stopped for session ${H(t.id)}.`)}catch(h){if(r.json){u(r,{ok:!1,error:A(h)});return}s(A(h))}}),a.command("health-check").description("Run health check on all sessions").option("--agent-url <url>","Agent URL",Ee).option("--json","Emit JSON").action(async function(t){let r={...k.opts(),...t};try{let h=f(t),P=encodeURIComponent(m(r)),O=await S(h,`/api/profiles/${P}/sessions`),E=await q(h,`/api/profiles/${P}/sessions/health-check`,{sessionIds:(O.sessions||[]).map((N)=>N.id)});if(u(r,{ok:!0,healthy:E?.healthy??null,checked:E?.checked??null,fixed:E?.fixed??null}))return;if(l("Health check completed."),E?.healthy!==void 0)n("Healthy",E.healthy);if(E?.checked!==void 0)n("Checked",E.checked);if(E?.fixed!==void 0)n("Fixed",E.fixed)}catch(h){if(r.json){u(r,{ok:!1,error:A(h)});return}s(A(h))}})}function po(k){k.command("reuse-db").description("Point this agent at an EXISTING database (reuse data from another same-workspace agent)").option("--adapter <name>","Storage adapter to use (e.g. postgres, skalex). Defaults to the configured/default adapter.").option("--connection-string <conn>","Connection string for the adapter (e.g. postgres://user:pass@host/db)").option("--storage-options <json>","Raw adapter options as a JSON object (alternative/in addition to --connection-string)").option("--db-path <path>","Data directory the adapter should use (e.g. an existing Skalex agent-db dir)").option("-y, --yes","Skip the confirmation prompt").option("--json","Emit JSON").action(async function(a){let t={...k.opts(),...a};try{let r={};if(a.storageOptions){let O;try{O=JSON.parse(a.storageOptions)}catch{s("--storage-options must be valid JSON.");return}if(!O||typeof O!=="object"||Array.isArray(O)){s("--storage-options must be a JSON object.");return}for(let[E,N]of Object.entries(O))r[E]=typeof N==="string"?N:JSON.stringify(N)}if(a.connectionString)r.connectionString=String(a.connectionString);if(!a.adapter&&!a.dbPath&&Object.keys(r).length===0){s("Nothing to set. Provide --adapter with --connection-string (or --storage-options), and/or --db-path.");return}if(!t.json){if(g("Reuse an existing database"),a.adapter)n("Adapter",i.bold(a.adapter));if(a.dbPath)n("Data path",i.bold(a.dbPath));if(Object.keys(r).length>0)n("Options",i.dim(Object.keys(r).join(", ")));c(),p(`${d.warning} Reuse is safe ONLY for a database from the SAME workspace \u2014 the encryption key is per-workspace, so a foreign DB won't decrypt (the agent will go degraded).`),p(`${d.warning} Two agents writing the same database concurrently can corrupt it. Keep this a single-writer setup unless your adapter is explicitly configured for shared writes.`),c()}if(!a.yes&&!t.json){if(!await Ie(i.bold("Write this storage configuration to the agent config?"))){o("Cancelled.");return}}let h={};if(a.adapter)h.storageAdapter=String(a.adapter);if(Object.keys(r).length>0)h.storageOptions=r;if(a.dbPath)h.dbPath=String(a.dbPath);M(h);let P=w();if(u(t,{ok:!0,storageAdapter:P.storageAdapter??null,dbPath:P.dbPath??null,storageOptionKeys:Object.keys(P.storageOptions??{})}))return;l(`${d.success} Storage configuration written. Run ${i.bold("vibe restart")} so the agent connects to the existing database.`)}catch(r){let h=r instanceof Error?A(r):String(r);if(t.json){u(t,{ok:!1,error:h});return}s(`reuse-db failed: ${h}`)}})}function Vt(k){return new Set([...He(k)??tr()])}function Kt(k){return ye(process.platform,new Set(k)).map((a)=>a.packageName)}async function Wt(){let{PluginManager:k}=await import("./plugin-system-kvg955t3.js"),a=new k;return{install:(t)=>a.install(t),remove:(t)=>a.remove(t)}}function mo(k){let a=k.command("capability").alias("cap").description("Select agent capabilities (abilities) + providers");a.command("list",{isDefault:!0}).description("List capabilities and whether each is enabled").option("--json","Emit JSON").action((t)=>{let r={...k.opts(),...t},h=C(),P=Vt(h),O=qt(h);if(u(r,{abilities:Y.map((E)=>({key:E.key,label:E.label,mandatory:E.mandatory,enabled:E.mandatory||P.has(E.key)})),providers:O}))return;if(g("Capabilities"),F(Y.map((E)=>({Key:E.key,Capability:E.label,Status:E.mandatory?"required":P.has(E.key)?"enabled":"disabled",Description:E.description}))),O.length>0){c(),g("Extra providers");for(let E of O)n("\u2022",E)}c(),o("Enable: vibe capability enable <key...> [--provider <pkg...>]"),o("Disable: vibe capability disable <key...>"),o("Re-run the interactive selector: vibe capability select")}),a.command("enable").description("Enable capabilities (installs their meta plugin) and/or extra providers").argument("[keys...]","Ability keys (e.g. gitops security)").option("--provider <pkg...>","Extra provider plugin(s) to install (short name or @vibecontrols/...)").option("--json","Emit JSON").action(async(t,r)=>{try{let h={...k.opts(),...r},P=C(),O=new Set(Y.map((oe)=>oe.key)),E=(t??[]).map((oe)=>oe.trim().toLowerCase()).filter((oe)=>O.has(oe));for(let oe of(t??[]).filter((K)=>!O.has(K.trim().toLowerCase())))p(`Unknown capability "${oe}" \u2014 see \`vibe capability list\`.`);let x=(Array.isArray(r.provider)?r.provider:r.provider?[r.provider]:[]).map((oe)=>Mt(oe)).filter((oe)=>Boolean(oe));if(E.length===0&&x.length===0){s("Provide at least one capability key or --provider <pkg>.");return}let j=Vt(P);for(let oe of E)j.add(oe);let T=[...new Set([...Kt(E),...x])],Z=await Wt(),B=[];for(let oe of T)try{await Z.install(oe),B.push({package:oe,ok:!0})}catch(K){B.push({package:oe,ok:!1,error:A(K)})}let V=[...new Set([...qt(P),...x])];if(ot(P,{abilities:j,providers:V}),u(h,{ok:!0,action:"enable",abilities:[...j],providers:V,installed:B}))return;for(let oe of B)if(oe.ok)l(`Installed ${oe.package}`);else p(`Failed to install ${oe.package}: ${oe.error}`);l("Capabilities updated. Restart the agent to load: vibe restart")}catch(h){s(A(h))}}),a.command("disable").description("Disable capabilities (removes their meta plugin)").argument("<keys...>","Ability keys").option("--json","Emit JSON").action(async(t,r)=>{try{let h={...k.opts(),...r},P=C(),O=new Set(Y.map((B)=>B.key)),E=new Set(Y.filter((B)=>B.mandatory).map((B)=>B.key)),N=(t??[]).map((B)=>B.trim().toLowerCase()).filter((B)=>O.has(B));for(let B of N.filter((V)=>E.has(V)))p(`"${B}" is required and cannot be disabled.`);let x=N.filter((B)=>!E.has(B));if(x.length===0){s("Nothing to disable.");return}let j=Vt(P);for(let B of x)j.delete(B);let T=await Wt(),Z=[];for(let B of Kt(x))try{await T.remove(B),Z.push({package:B,ok:!0})}catch(V){Z.push({package:B,ok:!1,error:A(V)})}if(ot(P,{abilities:j}),u(h,{ok:!0,action:"disable",abilities:[...j],removed:Z}))return;for(let B of Z)if(B.ok)l(`Removed ${B.package}`);else p(`Failed to remove ${B.package}: ${B.error}`);l("Capabilities updated. Restart the agent to apply: vibe restart")}catch(h){s(A(h))}}),a.command("select").description("Re-run the interactive capability selector and apply it").option("--json","Emit JSON").action(async(t)=>{try{let r={...k.opts(),...t},h=C(),P=await er(),O=await Wt();for(let E of Kt(P))try{await O.install(E)}catch{}if(ot(h,{abilities:P}),u(r,{ok:!0,action:"select",abilities:[...P]}))return;l(`Selection saved (${[...P].join(", ")||"none"}). Restart to apply: vibe restart`)}catch(r){s(A(r))}})}function wr(k){en(k),tn(k),nn(k),an(k),ln(k),dn(k),un(k),pn(k),Cn(k),qr(k),On(k),Dn(k),Tn(k),Gn(k),Vn(k),Kn(k),zn(k),Yn(k),Xn(k),Qn(k),eo(k),to(k),ro(k),io(k),so(k),ao(k),lo(k),uo(k),po(k),mo(k)}
|
|
115
|
+
`)}));await Q({title:`${t} \u2014 ${P.length} session(s)`,rows:O})},json:(P)=>ti(P)})}function uo(k){let a=k.command("session").description("Manage terminal sessions");a.command("system").description("List system sessions (alias for `session list --system`)").option("--agent-url <url>","Agent URL",Ee).option("--json","Emit JSON").option("--plain","Force plain text output").action(async function(t){let r={...k.opts(),...t};try{let h=f(t),P=encodeURIComponent(m(r));await co(h,`/api/profiles/${P}/sessions/system`,"System Sessions","No system sessions found.",r)}catch(h){s(A(h))}}),a.command("list").description("List all sessions").option("--system","Show system sessions instead of user sessions").option("--agent-url <url>","Agent URL",Ee).option("--json","Emit JSON").option("--plain","Force plain text output").action(async function(t){let r={...k.opts(),...t};try{let h=f(t),P=encodeURIComponent(m(r)),O=t.system?`/api/profiles/${P}/sessions/system`:`/api/profiles/${P}/sessions`;await co(h,O,"Sessions","No sessions found.",r)}catch(h){s(A(h))}}),a.command("create").description("Create a new session").requiredOption("--name <name>","Session name").option("--project <id>","Project ID","default").option("--command <cmd>","Initial command to run").option("--cwd <dir>","Working directory").option("--agent-url <url>","Agent URL",Ee).option("--json","Emit JSON").action(async function(t){let r={...k.opts(),...t};try{let h=f(t),P=encodeURIComponent(m(r)),O={sessionName:t.name,projectId:t.project};if(t.command)O.command=t.command;if(t.cwd)O.startDirectory=t.cwd;let E=await q(h,`/api/profiles/${P}/sessions/create`,O),N=E?.session?.id||E?.id||E?.sessionId;if(u(r,{ok:!0,id:N,name:t.name,project:t.project}))return;l(`Session created: ${H(N)}`),n("Name",t.name),n("Project",t.project)}catch(h){if(r.json){u(r,{ok:!1,error:A(h)});return}s(A(h))}}),a.command("kill").description("Kill a session").requiredOption("-i, --id <id>","Session ID").option("--agent-url <url>","Agent URL",Ee).option("--json","Emit JSON").action(async function(t){let r={...k.opts(),...t};try{let h=f(t),P=encodeURIComponent(m(r));if(await Ae(h,`/api/profiles/${P}/sessions/${t.id}`),u(r,{ok:!0,id:t.id}))return;l(`Session ${H(t.id)} killed.`)}catch(h){if(r.json){u(r,{ok:!1,error:A(h)});return}s(A(h))}}),a.command("exec").description("Execute a command in a session").requiredOption("-i, --id <id>","Session ID").requiredOption("-c, --command <cmd>","Command to execute").option("--agent-url <url>","Agent URL",Ee).option("--json","Emit JSON").action(async function(t){let r={...k.opts(),...t};try{let h=f(t),P=encodeURIComponent(m(r)),O=await q(h,`/api/profiles/${P}/sessions/${t.id}/command`,{command:t.command});if(u(r,{ok:!0,id:t.id,output:O?.output??null}))return;if(l("Command executed."),O?.output)c(),console.log(O.output)}catch(h){if(r.json){u(r,{ok:!1,error:A(h)});return}s(A(h))}}),a.command("capture").description("Capture session terminal output").requiredOption("-i, --id <id>","Session ID").option("--agent-url <url>","Agent URL",Ee).option("--json","Emit JSON").option("--plain","Force plain text output").action(async function(t){let r={...k.opts(),...t};try{let h=f(t),P=encodeURIComponent(m(r));await y({mode:_(r),fetchData:()=>S(h,`/api/profiles/${P}/sessions/${t.id}/capture`),plain:(O)=>{if(O?.content||O?.output)console.log(O.content||O.output);else o("No capture data available.")},json:(O)=>({id:t.id,content:O?.content??O?.output??null})})}catch(h){s(A(h))}}),a.command("keys").description("Send keys to a session").requiredOption("-i, --id <id>","Session ID").requiredOption("-k, --keys <keys>","Keys to send").option("--agent-url <url>","Agent URL",Ee).option("--json","Emit JSON").action(async function(t){let r={...k.opts(),...t};try{let h=f(t),P=encodeURIComponent(m(r));if(await q(h,`/api/profiles/${P}/sessions/${t.id}/keys`,{keys:t.keys}),u(r,{ok:!0,id:t.id}))return;l("Keys sent.")}catch(h){if(r.json){u(r,{ok:!1,error:A(h)});return}s(A(h))}}),a.command("interrupt").description("Send interrupt signal to a session").requiredOption("-i, --id <id>","Session ID").option("--agent-url <url>","Agent URL",Ee).option("--json","Emit JSON").action(async function(t){let r={...k.opts(),...t};try{let h=f(t),P=encodeURIComponent(m(r));if(await q(h,`/api/profiles/${P}/sessions/${t.id}/interrupt`,{}),u(r,{ok:!0,id:t.id}))return;l(`Session ${H(t.id)} interrupted.`)}catch(h){if(r.json){u(r,{ok:!1,error:A(h)});return}s(A(h))}}),a.command("rename").description("Rename a session").requiredOption("-i, --id <id>","Session ID").requiredOption("--name <name>","New session name").option("--agent-url <url>","Agent URL",Ee).option("--json","Emit JSON").action(async function(t){let r={...k.opts(),...t};try{let h=f(t),P=encodeURIComponent(m(r));if(await Ce(h,`/api/profiles/${P}/sessions/${t.id}/rename`,{newName:t.name}),u(r,{ok:!0,id:t.id,name:t.name}))return;l(`Session ${H(t.id)} renamed to "${t.name}".`)}catch(h){if(r.json){u(r,{ok:!1,error:A(h)});return}s(A(h))}}),a.command("toggle-mouse").description("Toggle mouse support in a session").requiredOption("-i, --id <id>","Session ID").option("--agent-url <url>","Agent URL",Ee).option("--json","Emit JSON").action(async function(t){let r={...k.opts(),...t};try{let h=f(t),P=encodeURIComponent(m(r)),O=await q(h,`/api/profiles/${P}/sessions/${t.id}/toggle-mouse`,{});if(u(r,{ok:!0,id:t.id,mouseEnabled:!!O?.mouseEnabled}))return;l(`Mouse support ${O?.mouseEnabled?"enabled":"toggled"} for session ${H(t.id)}.`)}catch(h){if(r.json){u(r,{ok:!1,error:A(h)});return}s(A(h))}}),a.command("terminal-start").description("Start terminal for a session").requiredOption("-i, --id <id>","Session ID").option("--agent-url <url>","Agent URL",Ee).option("--json","Emit JSON").action(async function(t){let r={...k.opts(),...t};try{let h=f(t),P=encodeURIComponent(m(r)),O=await q(h,`/api/profiles/${P}/sessions/${t.id}/terminal`,{});if(u(r,{ok:!0,id:t.id,port:O?.port??null}))return;if(l(`Terminal started for session ${H(t.id)}.`),O?.port)n("Port",O.port)}catch(h){if(r.json){u(r,{ok:!1,error:A(h)});return}s(A(h))}}),a.command("terminal-stop").description("Stop terminal for a session").requiredOption("-i, --id <id>","Session ID").option("--agent-url <url>","Agent URL",Ee).option("--json","Emit JSON").action(async function(t){let r={...k.opts(),...t};try{let h=f(t),P=encodeURIComponent(m(r));if(await q(h,`/api/profiles/${P}/sessions/${t.id}/terminal/stop`,{}),u(r,{ok:!0,id:t.id}))return;l(`Terminal stopped for session ${H(t.id)}.`)}catch(h){if(r.json){u(r,{ok:!1,error:A(h)});return}s(A(h))}}),a.command("health-check").description("Run health check on all sessions").option("--agent-url <url>","Agent URL",Ee).option("--json","Emit JSON").action(async function(t){let r={...k.opts(),...t};try{let h=f(t),P=encodeURIComponent(m(r)),O=await S(h,`/api/profiles/${P}/sessions`),E=await q(h,`/api/profiles/${P}/sessions/health-check`,{sessionIds:(O.sessions||[]).map((N)=>N.id)});if(u(r,{ok:!0,healthy:E?.healthy??null,checked:E?.checked??null,fixed:E?.fixed??null}))return;if(l("Health check completed."),E?.healthy!==void 0)n("Healthy",E.healthy);if(E?.checked!==void 0)n("Checked",E.checked);if(E?.fixed!==void 0)n("Fixed",E.fixed)}catch(h){if(r.json){u(r,{ok:!1,error:A(h)});return}s(A(h))}})}function po(k){k.command("reuse-db").description("Point this agent at an EXISTING database (reuse data from another same-workspace agent)").option("--adapter <name>","Storage adapter to use (e.g. postgres, skalex). Defaults to the configured/default adapter.").option("--connection-string <conn>","Connection string for the adapter (e.g. postgres://user:pass@host/db)").option("--storage-options <json>","Raw adapter options as a JSON object (alternative/in addition to --connection-string)").option("--db-path <path>","Data directory the adapter should use (e.g. an existing Skalex agent-db dir)").option("-y, --yes","Skip the confirmation prompt").option("--json","Emit JSON").action(async function(a){let t={...k.opts(),...a};try{let r={};if(a.storageOptions){let O;try{O=JSON.parse(a.storageOptions)}catch{s("--storage-options must be valid JSON.");return}if(!O||typeof O!=="object"||Array.isArray(O)){s("--storage-options must be a JSON object.");return}for(let[E,N]of Object.entries(O))r[E]=typeof N==="string"?N:JSON.stringify(N)}if(a.connectionString)r.connectionString=String(a.connectionString);if(!a.adapter&&!a.dbPath&&Object.keys(r).length===0){s("Nothing to set. Provide --adapter with --connection-string (or --storage-options), and/or --db-path.");return}if(!t.json){if(g("Reuse an existing database"),a.adapter)n("Adapter",i.bold(a.adapter));if(a.dbPath)n("Data path",i.bold(a.dbPath));if(Object.keys(r).length>0)n("Options",i.dim(Object.keys(r).join(", ")));c(),p(`${d.warning} Reuse is safe ONLY for a database from the SAME workspace \u2014 the encryption key is per-workspace, so a foreign DB won't decrypt (the agent will go degraded).`),p(`${d.warning} Two agents writing the same database concurrently can corrupt it. Keep this a single-writer setup unless your adapter is explicitly configured for shared writes.`),c()}if(!a.yes&&!t.json){if(!await Ie(i.bold("Write this storage configuration to the agent config?"))){o("Cancelled.");return}}let h={};if(a.adapter)h.storageAdapter=String(a.adapter);if(Object.keys(r).length>0)h.storageOptions=r;if(a.dbPath)h.dbPath=String(a.dbPath);M(h);let P=w();if(u(t,{ok:!0,storageAdapter:P.storageAdapter??null,dbPath:P.dbPath??null,storageOptionKeys:Object.keys(P.storageOptions??{})}))return;l(`${d.success} Storage configuration written. Run ${i.bold("vibe restart")} so the agent connects to the existing database.`)}catch(r){let h=r instanceof Error?A(r):String(r);if(t.json){u(t,{ok:!1,error:h});return}s(`reuse-db failed: ${h}`)}})}function Vt(k){return new Set([...He(k)??tr()])}function Kt(k){return ye(process.platform,new Set(k)).map((a)=>a.packageName)}async function Wt(){let{PluginManager:k}=await import("./plugin-system-zj50tg4k.js"),a=new k;return{install:(t)=>a.install(t),remove:(t)=>a.remove(t)}}function mo(k){let a=k.command("capability").alias("cap").description("Select agent capabilities (abilities) + providers");a.command("list",{isDefault:!0}).description("List capabilities and whether each is enabled").option("--json","Emit JSON").action((t)=>{let r={...k.opts(),...t},h=C(),P=Vt(h),O=qt(h);if(u(r,{abilities:Y.map((E)=>({key:E.key,label:E.label,mandatory:E.mandatory,enabled:E.mandatory||P.has(E.key)})),providers:O}))return;if(g("Capabilities"),F(Y.map((E)=>({Key:E.key,Capability:E.label,Status:E.mandatory?"required":P.has(E.key)?"enabled":"disabled",Description:E.description}))),O.length>0){c(),g("Extra providers");for(let E of O)n("\u2022",E)}c(),o("Enable: vibe capability enable <key...> [--provider <pkg...>]"),o("Disable: vibe capability disable <key...>"),o("Re-run the interactive selector: vibe capability select")}),a.command("enable").description("Enable capabilities (installs their meta plugin) and/or extra providers").argument("[keys...]","Ability keys (e.g. gitops security)").option("--provider <pkg...>","Extra provider plugin(s) to install (short name or @vibecontrols/...)").option("--json","Emit JSON").action(async(t,r)=>{try{let h={...k.opts(),...r},P=C(),O=new Set(Y.map((oe)=>oe.key)),E=(t??[]).map((oe)=>oe.trim().toLowerCase()).filter((oe)=>O.has(oe));for(let oe of(t??[]).filter((K)=>!O.has(K.trim().toLowerCase())))p(`Unknown capability "${oe}" \u2014 see \`vibe capability list\`.`);let x=(Array.isArray(r.provider)?r.provider:r.provider?[r.provider]:[]).map((oe)=>Mt(oe)).filter((oe)=>Boolean(oe));if(E.length===0&&x.length===0){s("Provide at least one capability key or --provider <pkg>.");return}let j=Vt(P);for(let oe of E)j.add(oe);let T=[...new Set([...Kt(E),...x])],Z=await Wt(),B=[];for(let oe of T)try{await Z.install(oe),B.push({package:oe,ok:!0})}catch(K){B.push({package:oe,ok:!1,error:A(K)})}let V=[...new Set([...qt(P),...x])];if(ot(P,{abilities:j,providers:V}),u(h,{ok:!0,action:"enable",abilities:[...j],providers:V,installed:B}))return;for(let oe of B)if(oe.ok)l(`Installed ${oe.package}`);else p(`Failed to install ${oe.package}: ${oe.error}`);l("Capabilities updated. Restart the agent to load: vibe restart")}catch(h){s(A(h))}}),a.command("disable").description("Disable capabilities (removes their meta plugin)").argument("<keys...>","Ability keys").option("--json","Emit JSON").action(async(t,r)=>{try{let h={...k.opts(),...r},P=C(),O=new Set(Y.map((B)=>B.key)),E=new Set(Y.filter((B)=>B.mandatory).map((B)=>B.key)),N=(t??[]).map((B)=>B.trim().toLowerCase()).filter((B)=>O.has(B));for(let B of N.filter((V)=>E.has(V)))p(`"${B}" is required and cannot be disabled.`);let x=N.filter((B)=>!E.has(B));if(x.length===0){s("Nothing to disable.");return}let j=Vt(P);for(let B of x)j.delete(B);let T=await Wt(),Z=[];for(let B of Kt(x))try{await T.remove(B),Z.push({package:B,ok:!0})}catch(V){Z.push({package:B,ok:!1,error:A(V)})}if(ot(P,{abilities:j}),u(h,{ok:!0,action:"disable",abilities:[...j],removed:Z}))return;for(let B of Z)if(B.ok)l(`Removed ${B.package}`);else p(`Failed to remove ${B.package}: ${B.error}`);l("Capabilities updated. Restart the agent to apply: vibe restart")}catch(h){s(A(h))}}),a.command("select").description("Re-run the interactive capability selector and apply it").option("--json","Emit JSON").action(async(t)=>{try{let r={...k.opts(),...t},h=C(),P=await er(),O=await Wt();for(let E of Kt(P))try{await O.install(E)}catch{}if(ot(h,{abilities:P}),u(r,{ok:!0,action:"select",abilities:[...P]}))return;l(`Selection saved (${[...P].join(", ")||"none"}). Restart to apply: vibe restart`)}catch(r){s(A(r))}})}function wr(k){en(k),tn(k),nn(k),an(k),ln(k),dn(k),un(k),pn(k),Cn(k),qr(k),On(k),Dn(k),Tn(k),Gn(k),Vn(k),Kn(k),zn(k),Yn(k),Xn(k),Qn(k),eo(k),to(k),ro(k),io(k),so(k),ao(k),lo(k),uo(k),po(k),mo(k)}
|
|
116
116
|
export{br,wr};
|