@vibecontrols/vibe-plugin-storage 2026.509.4 → 2026.509.5

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/index.d.ts CHANGED
@@ -22,7 +22,7 @@
22
22
  * adapter-registry types) STAY inline because they are storage-domain
23
23
  * shapes, not SDK surface.
24
24
  */
25
- import { type VibePlugin, type VibePluginFactory } from "@vibecontrols/plugin-sdk/contract";
25
+ import { type VibePluginFactory } from "@vibecontrols/plugin-sdk/contract";
26
26
  /**
27
27
  * Plugin Contract v2 factory. Returns a meta plugin that has no routes
28
28
  * or CLI surface of its own — actual storage capability is exposed via
@@ -31,13 +31,6 @@ import { type VibePlugin, type VibePluginFactory } from "@vibecontrols/plugin-sd
31
31
  * loader so we can announce readiness via telemetry on start.
32
32
  */
33
33
  export declare const createPlugin: VibePluginFactory;
34
- /**
35
- * Static manifest export — kept for the agent's defensive plugin loader
36
- * that reads `vibePlugin` directly without invoking the factory.
37
- * Lifecycle hooks here are no-ops; real registration happens via the
38
- * factory above.
39
- */
40
- export declare const vibePlugin: VibePlugin;
41
34
  export default createPlugin;
42
35
  export { AgentDatabase, type AgentStorageAdapterFactory, type AgentStorageAdapterOptions, type StorageEntry, type Task, type GitRepository, type BookmarkedCommand, type Notification, } from "./types.js";
43
36
  export { registerAdapter, getAdapter, listAdapters } from "./registry.js";
package/dist/index.js CHANGED
@@ -52,4 +52,4 @@ data: /message
52
52
 
53
53
  `),this._clients.add(res),req.on("close",()=>{this._clients.delete(res)})}async _handleMessage(req,res){let body="";req.setEncoding("utf8"),req.on("data",(c)=>{if(body+=c,body.length>this._maxBodySize)req.destroy(),res.writeHead(413,{"Content-Type":"application/json"}),res.end(JSON.stringify({error:"Request body too large"}))}),req.on("end",async()=>{res.writeHead(202,{"Content-Type":"application/json"}),res.end("{}");let msg;try{msg=JSON.parse(body)}catch(_){this.send(error2(null,PARSE_ERROR2,"Parse error"));return}if(this._onMessage)await this._onMessage(msg).catch(()=>{})})}get port(){return this._port}get host(){return this._host}get url(){return`http://${this._host}:${this._port}`}get sseUrl(){return`${this.url}/sse`}}class StdioTransport2{constructor(){this._onMessage=null,this._buffer="",this._started=!1}onMessage(fn){this._onMessage=fn}send(msg){process.stdout.write(JSON.stringify(msg)+`
54
54
  `)}start(){if(this._started)return;this._started=!0,process.stdin.setEncoding("utf8"),process.stdin.on("data",(chunk)=>{this._buffer+=chunk;let idx;while((idx=this._buffer.indexOf(`
55
- `))!==-1){let line=this._buffer.slice(0,idx).trim();if(this._buffer=this._buffer.slice(idx+1),line&&this._onMessage){let msg;try{msg=JSON.parse(line)}catch(_){this.send(error2(null,PARSE_ERROR2,"Parse error"));continue}this._onMessage(msg).catch(()=>{})}}}),process.stdin.on("end",()=>{process.exit(0)})}stop(){process.stdin.removeAllListeners("data"),process.stdin.removeAllListeners("end"),this._started=!1}}var SERVER_INFO2={name:"skalex",version:"4.0.0-alpha"},PROTOCOL_VERSION2="2024-11-05";class SkalexMCPServer2{constructor(db,opts={}){this._db=db,this._transport=opts.transport||"stdio",this._port=opts.port||3000,this._host=opts.host||"127.0.0.1",this._allowedOrigin=opts.allowedOrigin??null,this._maxBodySize=opts.maxBodySize??1048576,this._scopes=opts.scopes||{"*":["read"]},this._t=null}async listen(){if(this._transport==="http")this._t=new HttpTransport2({port:this._port,host:this._host,allowedOrigin:this._allowedOrigin,maxBodySize:this._maxBodySize});else this._t=new StdioTransport2;this._t.onMessage((msg)=>this._handleMessage(msg)),await this._t.start()}async connect(transport){if(this._t=transport,this._t.onMessage((msg)=>this._handleMessage(msg)),typeof this._t.start==="function")await this._t.start()}async close(){if(this._t&&typeof this._t.stop==="function")await this._t.stop();this._t=null}get transport(){return this._transport}get url(){return this._t?.url}async _handleMessage(raw){let{msg,parseError}=typeof raw==="string"?parse2(raw):{msg:raw};if(parseError){this._send(parseError);return}let{id,method,params}=msg;if(id===void 0){if(method==="notifications/initialized")return;return}try{switch(method){case"initialize":this._send(ok2(id,{protocolVersion:PROTOCOL_VERSION2,capabilities:{tools:{}},serverInfo:SERVER_INFO2}));break;case"tools/list":this._send(ok2(id,{tools:this._visibleTools()}));break;case"tools/call":await this._handleToolCall(id,params);break;case"ping":this._send(ok2(id,{}));break;default:this._send(error2(id,METHOD_NOT_FOUND2,`Method not found: ${method}`))}}catch(err){this._send(error2(id,INTERNAL_ERROR2,err.message||"Internal error"))}}async _handleToolCall(id,params){let name=params?.name,args=params?.arguments??{};if(!name){this._send(error2(id,INVALID_PARAMS2,"tools/call requires params.name"));return}let def=TOOL_DEFS2.find((t)=>t.name===name);if(!def){this._send(error2(id,METHOD_NOT_FOUND2,`Unknown tool: ${name}`));return}let collection=args.collection||args.collection_name||null;if(!this._hasScope(collection,def.scope)){this._send(ok2(id,toolError2(`Access denied: "${name}" requires "${def.scope}" scope on collection "${collection}".`)));return}try{let result=await callTool2(name,args,this._db);this._send(ok2(id,toolResult2(JSON.stringify(result,null,2))))}catch(err){this._send(ok2(id,toolError2(err.message||String(err))))}}_visibleTools(){return TOOL_DEFS2.filter((def)=>{let global=this._scopes["*"];if(global&&(global.includes(def.scope)||global.includes("admin")))return!0;for(let[,perms]of Object.entries(this._scopes))if(perms.includes(def.scope)||perms.includes("admin"))return!0;return!1})}_hasScope(collection,scope){let check=(perms)=>perms.includes("admin")||perms.includes(scope);if(collection&&this._scopes[collection])return check(this._scopes[collection]);if(this._scopes["*"])return check(this._scopes["*"]);return!1}_send(msg){this._t?.send(msg)}}var META_KEY2="migrations",_serialize2=(value)=>JSON.stringify(value,function(key,v){let raw=this[key];if(raw instanceof Date)return{__skalex_date__:raw.toISOString()};if(typeof v==="bigint")return{__skalex_bigint__:v.toString()};return v}),_deserialize2=(text)=>JSON.parse(text,(_,v)=>{if(v&&typeof v==="object"){if("__skalex_bigint__"in v)return BigInt(v.__skalex_bigint__);if("__skalex_date__"in v)return new Date(v.__skalex_date__)}return v});class Skalex2{constructor({path="./.db",format="gz",debug=!1,adapter,ai,encrypt,slowQueryLog,queryCache,memory,logger:logger$1,plugins,llmAdapter,embeddingAdapter,regexMaxLength,idGenerator,serializer,deserializer,autoSave,ttlSweepInterval,lenientLoad}={}){if(this.dataDirectory=path,this.dataFormat=format,this.debug=debug,!Skalex2._errorsAttached)Skalex2.SkalexError=SkalexError2,Skalex2.ValidationError=ValidationError2,Skalex2.UniqueConstraintError=UniqueConstraintError2,Skalex2.TransactionError=TransactionError2,Skalex2.PersistenceError=PersistenceError2,Skalex2.AdapterError=AdapterError2,Skalex2.QueryError=QueryError2,Skalex2._errorsAttached=!0;this._adapterConfig=adapter??null;let fs=adapter||new FsAdapter2({dir:path,format});if(encrypt)fs=new EncryptedAdapter2(fs,encrypt.key);if(this.fs=fs,this._registry=new CollectionRegistry2(Collection2),this.collections=this._registry.stores,this._collectionInstances=this._registry._instances,this._migrations=new MigrationEngine2,this._connectPromise=null,this.isConnected=!1,this._aiConfig=ai||null,this._encryptConfig=encrypt||null,this._pluginsConfig=Array.isArray(plugins)?plugins:null,this._memoryConfig=memory||null,this._regexMaxLength=regexMaxLength??500,this._idGenerator=idGenerator??null,this._serializer=serializer??_serialize2,this._deserializer=deserializer??_deserialize2,this._autoSave=autoSave??!1,this._txManager=new TransactionManager2,this._ttlSweepInterval=ttlSweepInterval??0,this._ttlTimer=null,this._logger=logger$1??logger2,this._embeddingAdapter=embeddingAdapter??(ai?createEmbeddingAdapter2(ai):null),this._aiAdapter=llmAdapter??(ai?createLLMAdapter2(ai):null),this._persistence=new PersistenceManager2({adapter:this.fs,serializer:this._serializer,deserializer:this._deserializer,logger:this._logger,debug:this.debug,lenientLoad:lenientLoad??!1}),this._changeLog=new ChangeLog2(this),this._queryCache=new QueryCache2(queryCache||{}),this._eventBus=new EventBus2,this._queryLog=slowQueryLog?new QueryLog2(slowQueryLog):null,this._sessionStats=new SessionStats2,this._plugins=new PluginEngine2,Array.isArray(plugins))for(let p of plugins)this._plugins.register(p)}async connect(){if(this._connectPromise)return this._connectPromise;return this._connectPromise=this._doConnect(),this._connectPromise}async _doConnect(){try{await this.loadData();let meta=this._getMeta();if(meta.queryCache)this._queryCache.fromJSON(meta.queryCache);if(this._migrations._migrations.length>0){let applied=meta.appliedVersions||[],newApplied=await this._migrations.run((version)=>this.useCollection(`_migration_${version}`),applied);this._saveMeta({appliedVersions:newApplied})}if(this._sweepTtl(),this._ttlSweepInterval>0){if(this._ttlTimer=setInterval(()=>this._sweepTtl(),this._ttlSweepInterval),this._ttlTimer?.unref)this._ttlTimer.unref()}this.isConnected=!0,this._log("> - Connected to the database (\u221A)")}catch(error22){throw this._logger(`Error connecting to the database: ${error22}`,"error"),error22}}async disconnect(){try{if(this._ttlTimer)clearInterval(this._ttlTimer),this._ttlTimer=null;await this.saveData(),this._registry.clear(),this.collections=this._registry.stores,this._collectionInstances=this._registry._instances,this._connectPromise=null,this.isConnected=!1,this._log("> - Disconnected from the database (\u221A)")}catch(error22){throw this._logger(`Error disconnecting from the database: ${error22}`,"error"),error22}}async _ensureConnected(){if(this.isConnected)return;return this.connect()}useCollection(collectionName){return this._registry.get(collectionName,this)}createCollection(collectionName,options={}){return this._registry.create(collectionName,options,this)}_createCollectionStore(collectionName,options={}){this._registry.createStore(collectionName,options)}async renameCollection(from,to){this._registry.rename(from,to),await this.saveData(to),await this.fs.delete(from)}async loadData(){await this._persistence.loadAll(this.collections,{parseSchema:parseSchema2,buildIndex:this._registry.buildIndex,IndexEngine:IndexEngine2});for(let name in this._collectionInstances){let store=this.collections[name];if(store&&this._collectionInstances[name]._store!==store)this._collectionInstances[name]._store=store}}async saveData(collectionName){await this._persistence.save(this.collections,collectionName)}buildIndex(data,keyField){return this._registry.buildIndex(data,keyField)}addMigration(migration){this._migrations.add(migration)}migrationStatus(){let meta=this._getMeta();return this._migrations.status(meta.appliedVersions||[])}namespace(id){if(this._adapterConfig)throw new AdapterError2("ERR_SKALEX_ADAPTER_NAMESPACE_REQUIRES_FS","namespace() requires the default FsAdapter. When a custom storage adapter is configured, create a separate Skalex instance with your adapter instead.");let safeId=String(id).replace(/[^a-zA-Z0-9_-]/g,"_");if(!safeId)throw new ValidationError2("ERR_SKALEX_VALIDATION_NAMESPACE_ID","namespace: id must contain at least one alphanumeric character",{id});return new Skalex2({path:`${this.dataDirectory}/${safeId}`,format:this.dataFormat,debug:this.debug,ai:this._aiConfig||void 0,encrypt:this._encryptConfig||void 0,slowQueryLog:this._queryLog?{threshold:this._queryLog._threshold,maxEntries:this._queryLog._maxEntries}:void 0,queryCache:this._queryCache?{maxSize:this._queryCache._maxSize,ttl:this._queryCache._ttl}:void 0,plugins:this._pluginsConfig||void 0,memory:this._memoryConfig||void 0,logger:this._logger!==logger2?this._logger:void 0,llmAdapter:this._aiAdapter&&!this._aiConfig?this._aiAdapter:void 0,embeddingAdapter:this._embeddingAdapter&&!this._aiConfig?this._embeddingAdapter:void 0,regexMaxLength:this._regexMaxLength!==500?this._regexMaxLength:void 0,idGenerator:this._idGenerator||void 0,serializer:this._serializer!==_serialize2?this._serializer:void 0,deserializer:this._deserializer!==_deserialize2?this._deserializer:void 0,autoSave:this._autoSave||void 0,ttlSweepInterval:this._ttlSweepInterval||void 0})}use(plugin){this._plugins.register(plugin)}watch(callback){return this._eventBus.on("*",callback)}sessionStats(sessionId){if(sessionId!==void 0)return this._sessionStats.get(sessionId);return this._sessionStats.all()}get _inTransaction(){return this._txManager.active}_emitEvent(collectionName,data){if(!this._txManager.defer(()=>this._eventBus.emit(collectionName,data)))this._eventBus.emit(collectionName,data)}async _runAfterHook(hook,data){if(!this._txManager.defer(()=>this._plugins.run(hook,data)))await this._plugins.run(hook,data)}async _logChange(op,collectionName,doc,prev,session){if(!this._txManager.defer(()=>this._changeLog.log(op,collectionName,doc,prev,session)))await this._changeLog.log(op,collectionName,doc,prev,session)}async transaction(fn,opts={}){return this._txManager.run(fn,this,opts)}async seed(fixtures,{reset=!1}={}){for(let[name,docs]of Object.entries(fixtures)){if(reset&&this.collections[name])this._applySnapshot(name,{data:[],index:new Map}),delete this._collectionInstances[name];await this.useCollection(name).insertMany(docs)}await this.saveData()}dump(){return this._registry.dump()}inspect(collectionName){return this._registry.inspect(collectionName)}async import(filePath){let content=await this.fs.readRaw(filePath),docs;try{docs=JSON.parse(content)}catch{throw new PersistenceError2("ERR_SKALEX_PERSISTENCE_INVALID_JSON",`import: invalid JSON in file "${filePath}"`,{filePath})}let name=filePath.split("/").pop().replace(/\.[^.]+$/,"");return this.useCollection(name).insertMany(Array.isArray(docs)?docs:[docs],{save:!0})}async embed(text){if(!this._embeddingAdapter)throw new AdapterError2("ERR_SKALEX_ADAPTER_EMBEDDING_REQUIRED","db.embed() requires an AI adapter. Pass { ai: { provider, apiKey } } to the Skalex constructor.");return this._embeddingAdapter.embed(text)}async ask(collectionName,nlQuery,{limit=20}={}){if(!this._aiAdapter)throw new AdapterError2("ERR_SKALEX_ADAPTER_LLM_REQUIRED",'db.ask() requires a language model adapter. Configure { ai: { provider, model: "..." } }.');let col=this.useCollection(collectionName),schema=this.schema(collectionName),filter=this._queryCache.get(collectionName,schema,nlQuery);if(!filter){filter=await this._aiAdapter.generate(schema,nlQuery);let warnings=validateLLMFilter2(filter,schema);if(warnings.length)warnings.forEach((w)=>this._log(`[ask] ${w}`));this._queryCache.set(collectionName,schema,nlQuery,filter),this._saveMeta({queryCache:this._queryCache.toJSON()})}return col.find(processLLMFilter2(filter,{regexMaxLength:this._regexMaxLength}),{limit})}schema(collectionName){return this._registry.schema(collectionName)}useMemory(sessionId){return new Memory2(sessionId,this)}changelog(){return this._changeLog}async restore(collectionName,timestamp,opts={}){return this._changeLog.restore(collectionName,timestamp,opts)}stats(collectionName){return this._registry.stats(collectionName)}slowQueries(opts={}){if(!this._queryLog)return[];return this._queryLog.entries(opts)}slowQueryCount(){return this._queryLog?this._queryLog.size:0}clearSlowQueries(){this._queryLog?.clear()}mcp(opts={}){return new SkalexMCPServer2(this,opts)}_getMeta(){let metaCol=this.collections._meta;if(!metaCol)return{};return metaCol.index.get(META_KEY2)||{}}_saveMeta(data){if(!this.collections._meta)this._createCollectionStore("_meta");let col=this.collections._meta,existing=col.index.get(META_KEY2);if(existing)Object.assign(existing,data);else{let doc={_id:META_KEY2,...data};col.data.push(doc),col.index.set(META_KEY2,doc)}this._persistence.markDirty(this.collections,"_meta")}_sweepTtl(){for(let name in this.collections){let col=this.collections[name],removed=sweep2(col.data,col.index,col.fieldIndex?(doc)=>col.fieldIndex.remove(doc):null);if(removed>0)this._persistence.markDirty(this.collections,name),this._log(`TTL sweep: removed ${removed} expired docs from "${name}"`)}}_buildCollectionContext(){let db=this;return{ensureConnected:()=>db._ensureConnected(),get txManager(){return db._txManager},get plugins(){return db._plugins},get eventBus(){return db._eventBus},get sessionStats(){return db._sessionStats},get queryLog(){return db._queryLog},get logger(){return db._logger},get persistence(){return db._persistence},get collections(){return db.collections},embed:(text)=>db.embed(text),get idGenerator(){return db._idGenerator},get autoSave(){return db._autoSave},saveCollection:(name)=>db.saveData(name),snapshotCollection:(col)=>db._snapshotCollection(col),getCollection:(name)=>db.useCollection(name),emitEvent:(name,data)=>db._emitEvent(name,data),runAfterHook:(hook,data)=>db._runAfterHook(hook,data),logChange:(op,col,doc,prev,session)=>db._logChange(op,col,doc,prev,session),get fs(){return db.fs},get dataDirectory(){return db.dataDirectory}}}_log(msg){if(this.debug)this._logger(msg,"info")}_snapshotCollection(col){return{data:structuredClone(col.data)}}_applySnapshot(name,snap){let col=this.collections[name];if(!col)return;if(col.data=snap.data,col.index=this.buildIndex(snap.data,"_id"),col.fieldIndex)col.fieldIndex.buildFromData(snap.data)}}class AgentDatabase{}var registry=new Map;function registerAdapter(name,factory){registry.set(name,factory)}var nowIso=()=>new Date().toISOString();function cleanDoc(doc){if(!doc)return doc;let{_id:_ignoredId,createdAt:rawCreatedAt,updatedAt:rawUpdatedAt,_version:_ignoredVersion,_expiresAt:_ignoredExpires,...rest}=doc,out={...rest};if(out.createdAt==null&&rawCreatedAt!=null)out.createdAt=rawCreatedAt instanceof Date?rawCreatedAt.toISOString():String(rawCreatedAt);if(out.updatedAt==null&&rawUpdatedAt!=null)out.updatedAt=rawUpdatedAt instanceof Date?rawUpdatedAt.toISOString():String(rawUpdatedAt);return out}class SkalexAgentDatabase extends AgentDatabase{dataDir;encryptionKey;lockPath;lockFd=null;db;tasks;config;gitRepos;bookmarks;notifications;pluginState;constructor(opts){super();this.dataDir=opts.dataDir,this.encryptionKey=opts.encryptionKey,this.lockPath=join(opts.dataDir,".agent-db.lock")}static async create(opts){if(!existsSync(opts.dataDir))mkdirSync(opts.dataDir,{recursive:!0});let instance=new SkalexAgentDatabase(opts);instance.acquireLock();try{await instance.init()}catch(err){throw instance.releaseLock(),err}return instance}acquireLock(){try{this.lockFd=openSync(this.lockPath,"wx",384),writeFileSync(this.lockFd,JSON.stringify({pid:process.pid,createdAt:new Date().toISOString()}));return}catch(err){if(err.code!=="EEXIST")throw err}let stale=!1;try{let raw=JSON.parse(readFileSync(this.lockPath,"utf8"));if(!raw.pid)stale=!0;else try{process.kill(raw.pid,0)}catch{stale=!0}}catch{stale=!0}if(stale){try{unlinkSync(this.lockPath)}catch{}this.acquireLock();return}throw Error(`Agent database is already open by another process (${this.lockPath})`)}releaseLock(){if(this.lockFd!==null){try{closeSync(this.lockFd)}catch{}this.lockFd=null}try{unlinkSync(this.lockPath)}catch{}}async init(){this.db=new Skalex2({path:this.dataDir,encrypt:{key:this.encryptionKey},autoSave:!0,format:"gz",lenientLoad:!0}),this.tasks=this.db.createCollection("tasks",{schema:{id:{type:"string",required:!0,unique:!0},type:{type:"string",required:!0,enum:["command","script","file_operation"]},status:{type:"string",required:!0,enum:["pending","running","completed","failed"]},payload:{type:"string",required:!0},result:{type:"string"},error:{type:"string"},calendarTaskId:{type:"string"},exitCode:{type:"number"},timeout:{type:"number"}},indexes:["status","type"]}),this.config=this.db.createCollection("agent_config",{schema:{key:{type:"string",required:!0,unique:!0},value:{type:"string",required:!0}}}),this.gitRepos=this.db.createCollection("git_repositories",{schema:{id:{type:"string",required:!0,unique:!0},path:{type:"string",required:!0,unique:!0},name:{type:"string",required:!0},parentPath:{type:"string"},isSubmodule:{type:"boolean"},projectType:{type:"string"},vitePort:{type:"number"},lastScanned:{type:"string"}},indexes:["parentPath"]}),this.bookmarks=this.db.createCollection("bookmarked_commands",{schema:{id:{type:"string",required:!0,unique:!0},projectId:{type:"string"},command:{type:"string",required:!0},description:{type:"string"},category:{type:"string"}},indexes:["projectId","category"]}),this.notifications=this.db.createCollection("notifications",{schema:{id:{type:"string",required:!0,unique:!0},sessionName:{type:"string"},projectId:{type:"string"},type:{type:"string",required:!0,enum:["info","success","warning","error"]},title:{type:"string",required:!0},message:{type:"string",required:!0},status:{type:"string",required:!0,enum:["unread","read"]}},indexes:["status","projectId"]}),this.pluginState=this.db.createCollection("plugin_state",{schema:{pluginName:{type:"string",required:!0},key:{type:"string",required:!0},value:{type:"string",required:!0}},indexes:["pluginName"]}),await this.db.connect()}async close(){if(this.db?.isConnected)await this.db.disconnect();this.releaseLock()}getDbPath(){return this.dataDir}async createTask(task){let doc={id:task.id,type:task.type,status:task.status,payload:task.payload};if(task.result!=null)doc.result=task.result;if(task.error!=null)doc.error=task.error;if(task.calendarTaskId!=null)doc.calendarTaskId=task.calendarTaskId;if(task.exitCode!=null)doc.exitCode=task.exitCode;if(task.timeout!=null)doc.timeout=task.timeout;let inserted=await this.tasks.insertOne(doc);return cleanDoc(inserted)}async getTask(id){let doc=await this.tasks.findOne({id});return doc?cleanDoc(doc):void 0}async getAllTasks(){return(await this.tasks.find(void 0,{sort:{createdAt:-1}})).docs.map((d)=>cleanDoc(d))}async getPendingTasks(){return(await this.tasks.find({status:"pending"},{sort:{createdAt:1}})).docs.map((d)=>cleanDoc(d))}async updateTask(id,updates){let patch={};for(let[k,v]of Object.entries(updates)){if(k==="id"||k==="createdAt"||k==="updatedAt")continue;patch[k]=v??null}if(Object.keys(patch).length===0)return;await this.tasks.updateOne({id},patch)}async cancelTask(id){let existing=await this.tasks.findOne({id});if(!existing||existing.status!=="pending"&&existing.status!=="running")return!1;return await this.tasks.updateOne({id},{status:"failed",error:"Cancelled"}),!0}async getConfig(key){return(await this.config.findOne({key}))?.value}async setConfig(key,value){await this.config.upsert({key},{key,value})}async deleteConfig(key){return await this.config.deleteOne({key})!==null}async getAllConfig(){let res=await this.config.find(),out={};for(let doc of res.docs)out[doc.key]=doc.value;return out}async bulkSetConfig(entries){for(let[key,value]of Object.entries(entries))await this.config.upsert({key},{key,value})}async getConfigStatus(){let res=await this.config.find(),latest=null;for(let doc of res.docs){let raw=doc.updatedAt,iso=raw instanceof Date?raw.toISOString():typeof raw==="string"?raw:null;if(iso&&(!latest||iso>latest))latest=iso}return{totalKeys:res.docs.length,lastUpdated:latest}}async createGitRepository(repo){let doc={id:repo.id,path:repo.path,name:repo.name,isSubmodule:Boolean(repo.isSubmodule),lastScanned:nowIso()};if(repo.parentPath!=null)doc.parentPath=repo.parentPath;if(repo.projectType!=null)doc.projectType=repo.projectType;if(repo.vitePort!=null)doc.vitePort=repo.vitePort;let inserted=await this.gitRepos.insertOne(doc);return cleanDoc(inserted)}async getGitRepository(id){let doc=await this.gitRepos.findOne({id});return doc?cleanDoc(doc):void 0}async getGitRepositoryByPath(path){let doc=await this.gitRepos.findOne({path});return doc?cleanDoc(doc):void 0}async getAllGitRepositories(){return(await this.gitRepos.find(void 0,{sort:{path:1}})).docs.map((d)=>cleanDoc(d))}async updateGitRepository(id,updates){let patch={lastScanned:nowIso()};for(let[k,v]of Object.entries(updates)){if(k==="id"||k==="createdAt"||k==="updatedAt")continue;if(k==="isSubmodule"){patch[k]=Boolean(v);continue}patch[k]=v??null}await this.gitRepos.updateOne({id},patch)}async deleteGitRepository(id){return await this.gitRepos.deleteOne({id})!==null}async fixGitHierarchy(){let repos=await this.getAllGitRepositories(),fixed=0;for(let repo of repos){if(repo.isSubmodule)continue;let parent=repos.find((r)=>r.id!==repo.id&&repo.path.startsWith(`${r.path}/`)&&!r.isSubmodule);if(parent&&repo.parentPath!==parent.path)await this.updateGitRepository(repo.id,{parentPath:parent.path}),fixed++}return{fixed}}async createBookmarkedCommand(cmd){let doc={id:cmd.id,command:cmd.command};if(cmd.projectId!=null)doc.projectId=cmd.projectId;if(cmd.description!=null)doc.description=cmd.description;if(cmd.category!=null)doc.category=cmd.category;let inserted=await this.bookmarks.insertOne(doc);return cleanDoc(inserted)}async getBookmarkedCommand(id){let doc=await this.bookmarks.findOne({id});return doc?cleanDoc(doc):void 0}async getAllBookmarkedCommands(){return(await this.bookmarks.find(void 0,{sort:{createdAt:-1}})).docs.map((d)=>cleanDoc(d))}async getBookmarkedCommandsByProject(projectId){let filter=projectId===null?{projectId:{$fn:(v)=>v==null}}:{projectId};return(await this.bookmarks.find(filter,{sort:{createdAt:-1}})).docs.map((d)=>cleanDoc(d))}async getBookmarkedCommandsByCategory(category){return(await this.bookmarks.find({category},{sort:{createdAt:-1}})).docs.map((d)=>cleanDoc(d))}async updateBookmarkedCommand(id,updates){let patch={};for(let[k,v]of Object.entries(updates)){if(k==="id"||k==="createdAt"||k==="updatedAt")continue;patch[k]=v??null}if(Object.keys(patch).length===0)return;await this.bookmarks.updateOne({id},patch)}async deleteBookmarkedCommand(id){return await this.bookmarks.deleteOne({id})!==null}async executeBookmarkedCommand(id){return this.getBookmarkedCommand(id)}async createNotification(notification){let doc={id:notification.id,type:notification.type,title:notification.title,message:notification.message,status:notification.status};if(notification.sessionName!=null)doc.sessionName=notification.sessionName;if(notification.projectId!=null)doc.projectId=notification.projectId;let inserted=await this.notifications.insertOne(doc);return cleanDoc(inserted)}async getNotification(id){let doc=await this.notifications.findOne({id});return doc?cleanDoc(doc):void 0}async getAllNotifications(){return(await this.notifications.find(void 0,{sort:{createdAt:-1}})).docs.map((d)=>cleanDoc(d))}async getNotificationsByProject(projectId){let filter=projectId===null?{projectId:{$fn:(v)=>v==null}}:{projectId};return(await this.notifications.find(filter,{sort:{createdAt:-1}})).docs.map((d)=>cleanDoc(d))}async getGlobalNotifications(){return this.getNotificationsByProject(null)}async getUnreadNotifications(){return(await this.notifications.find({status:"unread"},{sort:{createdAt:-1}})).docs.map((d)=>cleanDoc(d))}async updateNotificationStatus(id,status){await this.notifications.updateOne({id},{status})}async markAllNotificationsRead(){return(await this.notifications.updateMany({status:"unread"},{status:"read"})).length}async deleteNotification(id){return await this.notifications.deleteOne({id})!==null}async clearOldNotifications(olderThanDays=30){let cutoff=new Date(Date.now()-olderThanDays*24*60*60*1000);return(await this.notifications.deleteMany({createdAt:{$fn:(v)=>v instanceof Date&&v<cutoff}})).length}async getPluginState(pluginName,key){return(await this.pluginState.findOne({$and:[{pluginName},{key}]}))?.value}async setPluginState(pluginName,key,value){await this.pluginState.upsert({$and:[{pluginName},{key}]},{pluginName,key,value})}async deletePluginState(pluginName,key){return await this.pluginState.deleteOne({$and:[{pluginName},{key}]})!==null}async getAllPluginState(pluginName){return(await this.pluginState.find({pluginName},{sort:{key:1}})).docs.map((doc)=>{let raw=doc.updatedAt,updatedAt=raw instanceof Date?raw.toISOString():typeof raw==="string"?raw:void 0;return{key:doc.key,value:doc.value,updatedAt}})}async deleteAllPluginState(pluginName){return(await this.pluginState.deleteMany({pluginName})).length}}var createSkalexAgentDatabase=(opts)=>SkalexAgentDatabase.create(opts);registerAdapter("skalex",createSkalexAgentDatabase);var registry2=new Map;function registerAdapter2(name,factory){registry2.set(name,factory)}class AgentDatabase2{}registerAdapter2("skalex",createSkalexAgentDatabase);var nowIso2=()=>new Date().toISOString();function cleanDoc2(doc){if(!doc)return doc;let{_id:_ignoredId,createdAt:rawCreatedAt,updatedAt:rawUpdatedAt,_version:_ignoredVersion,_expiresAt:_ignoredExpires,...rest}=doc,out={...rest};if(out.createdAt==null&&rawCreatedAt!=null)out.createdAt=rawCreatedAt instanceof Date?rawCreatedAt.toISOString():String(rawCreatedAt);if(out.updatedAt==null&&rawUpdatedAt!=null)out.updatedAt=rawUpdatedAt instanceof Date?rawUpdatedAt.toISOString():String(rawUpdatedAt);return out}class SkalexAgentDatabase2 extends AgentDatabase2{dataDir;encryptionKey;lockPath;lockFd=null;db;tasks;config;gitRepos;bookmarks;notifications;pluginState;constructor(opts){super();this.dataDir=opts.dataDir,this.encryptionKey=opts.encryptionKey,this.lockPath=join2(opts.dataDir,".agent-db.lock")}static async create(opts){if(!existsSync2(opts.dataDir))mkdirSync2(opts.dataDir,{recursive:!0});let instance=new SkalexAgentDatabase2(opts);instance.acquireLock();try{await instance.init()}catch(err){throw instance.releaseLock(),err}return instance}acquireLock(){try{this.lockFd=openSync2(this.lockPath,"wx",384),writeFileSync2(this.lockFd,JSON.stringify({pid:process.pid,createdAt:new Date().toISOString()}));return}catch(err){if(err.code!=="EEXIST")throw err}let stale=!1;try{let raw=JSON.parse(readFileSync2(this.lockPath,"utf8"));if(!raw.pid)stale=!0;else try{process.kill(raw.pid,0)}catch{stale=!0}}catch{stale=!0}if(stale){try{unlinkSync2(this.lockPath)}catch{}this.acquireLock();return}throw Error(`Agent database is already open by another process (${this.lockPath})`)}releaseLock(){if(this.lockFd!==null){try{closeSync2(this.lockFd)}catch{}this.lockFd=null}try{unlinkSync2(this.lockPath)}catch{}}async init(){this.db=new Skalex({path:this.dataDir,encrypt:{key:this.encryptionKey},autoSave:!0,format:"gz",lenientLoad:!0}),this.tasks=this.db.createCollection("tasks",{schema:{id:{type:"string",required:!0,unique:!0},type:{type:"string",required:!0,enum:["command","script","file_operation"]},status:{type:"string",required:!0,enum:["pending","running","completed","failed"]},payload:{type:"string",required:!0},result:{type:"string"},error:{type:"string"},calendarTaskId:{type:"string"},exitCode:{type:"number"},timeout:{type:"number"}},indexes:["status","type"]}),this.config=this.db.createCollection("agent_config",{schema:{key:{type:"string",required:!0,unique:!0},value:{type:"string",required:!0}}}),this.gitRepos=this.db.createCollection("git_repositories",{schema:{id:{type:"string",required:!0,unique:!0},path:{type:"string",required:!0,unique:!0},name:{type:"string",required:!0},parentPath:{type:"string"},isSubmodule:{type:"boolean"},projectType:{type:"string"},vitePort:{type:"number"},lastScanned:{type:"string"}},indexes:["parentPath"]}),this.bookmarks=this.db.createCollection("bookmarked_commands",{schema:{id:{type:"string",required:!0,unique:!0},projectId:{type:"string"},command:{type:"string",required:!0},description:{type:"string"},category:{type:"string"}},indexes:["projectId","category"]}),this.notifications=this.db.createCollection("notifications",{schema:{id:{type:"string",required:!0,unique:!0},sessionName:{type:"string"},projectId:{type:"string"},type:{type:"string",required:!0,enum:["info","success","warning","error"]},title:{type:"string",required:!0},message:{type:"string",required:!0},status:{type:"string",required:!0,enum:["unread","read"]}},indexes:["status","projectId"]}),this.pluginState=this.db.createCollection("plugin_state",{schema:{pluginName:{type:"string",required:!0},key:{type:"string",required:!0},value:{type:"string",required:!0}},indexes:["pluginName"]}),await this.db.connect()}async close(){if(this.db?.isConnected)await this.db.disconnect();this.releaseLock()}getDbPath(){return this.dataDir}async createTask(task){let doc={id:task.id,type:task.type,status:task.status,payload:task.payload};if(task.result!=null)doc.result=task.result;if(task.error!=null)doc.error=task.error;if(task.calendarTaskId!=null)doc.calendarTaskId=task.calendarTaskId;if(task.exitCode!=null)doc.exitCode=task.exitCode;if(task.timeout!=null)doc.timeout=task.timeout;let inserted=await this.tasks.insertOne(doc);return cleanDoc2(inserted)}async getTask(id){let doc=await this.tasks.findOne({id});return doc?cleanDoc2(doc):void 0}async getAllTasks(){return(await this.tasks.find(void 0,{sort:{createdAt:-1}})).docs.map((d)=>cleanDoc2(d))}async getPendingTasks(){return(await this.tasks.find({status:"pending"},{sort:{createdAt:1}})).docs.map((d)=>cleanDoc2(d))}async updateTask(id,updates){let patch={};for(let[k,v]of Object.entries(updates)){if(k==="id"||k==="createdAt"||k==="updatedAt")continue;patch[k]=v??null}if(Object.keys(patch).length===0)return;await this.tasks.updateOne({id},patch)}async cancelTask(id){let existing=await this.tasks.findOne({id});if(!existing||existing.status!=="pending"&&existing.status!=="running")return!1;return await this.tasks.updateOne({id},{status:"failed",error:"Cancelled"}),!0}async getConfig(key){return(await this.config.findOne({key}))?.value}async setConfig(key,value){await this.config.upsert({key},{key,value})}async deleteConfig(key){return await this.config.deleteOne({key})!==null}async getAllConfig(){let res=await this.config.find(),out={};for(let doc of res.docs)out[doc.key]=doc.value;return out}async bulkSetConfig(entries){for(let[key,value]of Object.entries(entries))await this.config.upsert({key},{key,value})}async getConfigStatus(){let res=await this.config.find(),latest=null;for(let doc of res.docs){let raw=doc.updatedAt,iso=raw instanceof Date?raw.toISOString():typeof raw==="string"?raw:null;if(iso&&(!latest||iso>latest))latest=iso}return{totalKeys:res.docs.length,lastUpdated:latest}}async createGitRepository(repo){let doc={id:repo.id,path:repo.path,name:repo.name,isSubmodule:Boolean(repo.isSubmodule),lastScanned:nowIso2()};if(repo.parentPath!=null)doc.parentPath=repo.parentPath;if(repo.projectType!=null)doc.projectType=repo.projectType;if(repo.vitePort!=null)doc.vitePort=repo.vitePort;let inserted=await this.gitRepos.insertOne(doc);return cleanDoc2(inserted)}async getGitRepository(id){let doc=await this.gitRepos.findOne({id});return doc?cleanDoc2(doc):void 0}async getGitRepositoryByPath(path){let doc=await this.gitRepos.findOne({path});return doc?cleanDoc2(doc):void 0}async getAllGitRepositories(){return(await this.gitRepos.find(void 0,{sort:{path:1}})).docs.map((d)=>cleanDoc2(d))}async updateGitRepository(id,updates){let patch={lastScanned:nowIso2()};for(let[k,v]of Object.entries(updates)){if(k==="id"||k==="createdAt"||k==="updatedAt")continue;if(k==="isSubmodule"){patch[k]=Boolean(v);continue}patch[k]=v??null}await this.gitRepos.updateOne({id},patch)}async deleteGitRepository(id){return await this.gitRepos.deleteOne({id})!==null}async fixGitHierarchy(){let repos=await this.getAllGitRepositories(),fixed=0;for(let repo of repos){if(repo.isSubmodule)continue;let parent=repos.find((r)=>r.id!==repo.id&&repo.path.startsWith(`${r.path}/`)&&!r.isSubmodule);if(parent&&repo.parentPath!==parent.path)await this.updateGitRepository(repo.id,{parentPath:parent.path}),fixed++}return{fixed}}async createBookmarkedCommand(cmd){let doc={id:cmd.id,command:cmd.command};if(cmd.projectId!=null)doc.projectId=cmd.projectId;if(cmd.description!=null)doc.description=cmd.description;if(cmd.category!=null)doc.category=cmd.category;let inserted=await this.bookmarks.insertOne(doc);return cleanDoc2(inserted)}async getBookmarkedCommand(id){let doc=await this.bookmarks.findOne({id});return doc?cleanDoc2(doc):void 0}async getAllBookmarkedCommands(){return(await this.bookmarks.find(void 0,{sort:{createdAt:-1}})).docs.map((d)=>cleanDoc2(d))}async getBookmarkedCommandsByProject(projectId){let filter=projectId===null?{projectId:{$fn:(v)=>v==null}}:{projectId};return(await this.bookmarks.find(filter,{sort:{createdAt:-1}})).docs.map((d)=>cleanDoc2(d))}async getBookmarkedCommandsByCategory(category){return(await this.bookmarks.find({category},{sort:{createdAt:-1}})).docs.map((d)=>cleanDoc2(d))}async updateBookmarkedCommand(id,updates){let patch={};for(let[k,v]of Object.entries(updates)){if(k==="id"||k==="createdAt"||k==="updatedAt")continue;patch[k]=v??null}if(Object.keys(patch).length===0)return;await this.bookmarks.updateOne({id},patch)}async deleteBookmarkedCommand(id){return await this.bookmarks.deleteOne({id})!==null}async executeBookmarkedCommand(id){return this.getBookmarkedCommand(id)}async createNotification(notification){let doc={id:notification.id,type:notification.type,title:notification.title,message:notification.message,status:notification.status};if(notification.sessionName!=null)doc.sessionName=notification.sessionName;if(notification.projectId!=null)doc.projectId=notification.projectId;let inserted=await this.notifications.insertOne(doc);return cleanDoc2(inserted)}async getNotification(id){let doc=await this.notifications.findOne({id});return doc?cleanDoc2(doc):void 0}async getAllNotifications(){return(await this.notifications.find(void 0,{sort:{createdAt:-1}})).docs.map((d)=>cleanDoc2(d))}async getNotificationsByProject(projectId){let filter=projectId===null?{projectId:{$fn:(v)=>v==null}}:{projectId};return(await this.notifications.find(filter,{sort:{createdAt:-1}})).docs.map((d)=>cleanDoc2(d))}async getGlobalNotifications(){return this.getNotificationsByProject(null)}async getUnreadNotifications(){return(await this.notifications.find({status:"unread"},{sort:{createdAt:-1}})).docs.map((d)=>cleanDoc2(d))}async updateNotificationStatus(id,status){await this.notifications.updateOne({id},{status})}async markAllNotificationsRead(){return(await this.notifications.updateMany({status:"unread"},{status:"read"})).length}async deleteNotification(id){return await this.notifications.deleteOne({id})!==null}async clearOldNotifications(olderThanDays=30){let cutoff=new Date(Date.now()-olderThanDays*24*60*60*1000);return(await this.notifications.deleteMany({createdAt:{$fn:(v)=>v instanceof Date&&v<cutoff}})).length}async getPluginState(pluginName,key){return(await this.pluginState.findOne({$and:[{pluginName},{key}]}))?.value}async setPluginState(pluginName,key,value){await this.pluginState.upsert({$and:[{pluginName},{key}]},{pluginName,key,value})}async deletePluginState(pluginName,key){return await this.pluginState.deleteOne({$and:[{pluginName},{key}]})!==null}async getAllPluginState(pluginName){return(await this.pluginState.find({pluginName},{sort:{key:1}})).docs.map((doc)=>{let raw=doc.updatedAt,updatedAt=raw instanceof Date?raw.toISOString():typeof raw==="string"?raw:void 0;return{key:doc.key,value:doc.value,updatedAt}})}async deleteAllPluginState(pluginName){return(await this.pluginState.deleteMany({pluginName})).length}}var createSkalexAgentDatabase2=(opts)=>SkalexAgentDatabase2.create(opts);registerAdapter2("skalex",createSkalexAgentDatabase2);var registry3=new Map;function registerAdapter3(name,factory){registry3.set(name,factory)}function getAdapter(name){return registry3.get(name)}function listAdapters(){return Array.from(registry3.keys())}class AgentDatabase3{}async function resolveFactory(options){if(options.adapterFactory)return options.adapterFactory;let name=options.adapterName??process.env.VIBE_STORAGE_ADAPTER??"skalex";if(name.startsWith("custom:")){let modPath=name.slice(7);if(!modPath)throw Error("VIBE_STORAGE_ADAPTER=custom: requires a module path after the colon");let mod=await import(modPath),factory2=mod.default??mod.createAdapter;if(typeof factory2!=="function")throw Error(`Custom storage adapter at ${modPath} must export a default function (or \`createAdapter\`) of type AgentStorageAdapterFactory`);return factory2}let factory=getAdapter(name);if(!factory){let candidate={skalex:"@vibecontrols/vibe-plugin-storage-skalex",postgres:"@vibecontrols/vibe-plugin-storage-postgres",postgresql:"@vibecontrols/vibe-plugin-storage-postgres"}[name];if(candidate)try{await import(candidate),factory=getAdapter(name)}catch{}}if(!factory)throw Error(`Unknown storage adapter: "${name}". Registered adapters: ${listAdapters().join(", ")||`(none \u2014 did you install @vibecontrols/vibe-plugin-storage-${name})?`}`);return factory}async function createAgentDatabase(options){if(!options.encryptionKey)throw Error("createAgentDatabase(): encryptionKey is required. Storage is always encrypted at rest.");if(!options.dbPath)throw Error("createAgentDatabase(): dbPath is required.");return(await resolveFactory(options))({dataDir:options.dbPath,encryptionKey:options.encryptionKey,adapterOptions:options.adapterOptions})}registerAdapter3("skalex",createSkalexAgentDatabase2);var PLUGIN_NAME="storage",PLUGIN_VERSION="2026.509.2",createPlugin=(ctx)=>{let log=new BoundLogger(ctx.logger,PLUGIN_NAME),lifecycle=createLifecycleHooks({name:PLUGIN_NAME,telemetryEventName:"storage.ready",onInit:(hostServices)=>{new TelemetryEmitter(PLUGIN_NAME,PLUGIN_VERSION,hostServices).emitReady(),log.info("storage meta plugin ready (skalex adapter auto-registered)")}});return{name:PLUGIN_NAME,version:PLUGIN_VERSION,description:"Storage facade \u2014 owns AgentDatabase contract and adapter registry",tags:["backend","adapter"],capabilities:{storage:"rw"},onServerStart:lifecycle.onServerStart,onServerStop:lifecycle.onServerStop}},vibePlugin={name:PLUGIN_NAME,version:PLUGIN_VERSION,description:"Storage facade \u2014 owns AgentDatabase contract and adapter registry",tags:["backend","adapter"],capabilities:{storage:"rw"}},src_default=createPlugin;export{vibePlugin,registerAdapter3 as registerAdapter,listAdapters,getAdapter,src_default as default,createPlugin,createAgentDatabase,AgentDatabase3 as AgentDatabase};
55
+ `))!==-1){let line=this._buffer.slice(0,idx).trim();if(this._buffer=this._buffer.slice(idx+1),line&&this._onMessage){let msg;try{msg=JSON.parse(line)}catch(_){this.send(error2(null,PARSE_ERROR2,"Parse error"));continue}this._onMessage(msg).catch(()=>{})}}}),process.stdin.on("end",()=>{process.exit(0)})}stop(){process.stdin.removeAllListeners("data"),process.stdin.removeAllListeners("end"),this._started=!1}}var SERVER_INFO2={name:"skalex",version:"4.0.0-alpha"},PROTOCOL_VERSION2="2024-11-05";class SkalexMCPServer2{constructor(db,opts={}){this._db=db,this._transport=opts.transport||"stdio",this._port=opts.port||3000,this._host=opts.host||"127.0.0.1",this._allowedOrigin=opts.allowedOrigin??null,this._maxBodySize=opts.maxBodySize??1048576,this._scopes=opts.scopes||{"*":["read"]},this._t=null}async listen(){if(this._transport==="http")this._t=new HttpTransport2({port:this._port,host:this._host,allowedOrigin:this._allowedOrigin,maxBodySize:this._maxBodySize});else this._t=new StdioTransport2;this._t.onMessage((msg)=>this._handleMessage(msg)),await this._t.start()}async connect(transport){if(this._t=transport,this._t.onMessage((msg)=>this._handleMessage(msg)),typeof this._t.start==="function")await this._t.start()}async close(){if(this._t&&typeof this._t.stop==="function")await this._t.stop();this._t=null}get transport(){return this._transport}get url(){return this._t?.url}async _handleMessage(raw){let{msg,parseError}=typeof raw==="string"?parse2(raw):{msg:raw};if(parseError){this._send(parseError);return}let{id,method,params}=msg;if(id===void 0){if(method==="notifications/initialized")return;return}try{switch(method){case"initialize":this._send(ok2(id,{protocolVersion:PROTOCOL_VERSION2,capabilities:{tools:{}},serverInfo:SERVER_INFO2}));break;case"tools/list":this._send(ok2(id,{tools:this._visibleTools()}));break;case"tools/call":await this._handleToolCall(id,params);break;case"ping":this._send(ok2(id,{}));break;default:this._send(error2(id,METHOD_NOT_FOUND2,`Method not found: ${method}`))}}catch(err){this._send(error2(id,INTERNAL_ERROR2,err.message||"Internal error"))}}async _handleToolCall(id,params){let name=params?.name,args=params?.arguments??{};if(!name){this._send(error2(id,INVALID_PARAMS2,"tools/call requires params.name"));return}let def=TOOL_DEFS2.find((t)=>t.name===name);if(!def){this._send(error2(id,METHOD_NOT_FOUND2,`Unknown tool: ${name}`));return}let collection=args.collection||args.collection_name||null;if(!this._hasScope(collection,def.scope)){this._send(ok2(id,toolError2(`Access denied: "${name}" requires "${def.scope}" scope on collection "${collection}".`)));return}try{let result=await callTool2(name,args,this._db);this._send(ok2(id,toolResult2(JSON.stringify(result,null,2))))}catch(err){this._send(ok2(id,toolError2(err.message||String(err))))}}_visibleTools(){return TOOL_DEFS2.filter((def)=>{let global=this._scopes["*"];if(global&&(global.includes(def.scope)||global.includes("admin")))return!0;for(let[,perms]of Object.entries(this._scopes))if(perms.includes(def.scope)||perms.includes("admin"))return!0;return!1})}_hasScope(collection,scope){let check=(perms)=>perms.includes("admin")||perms.includes(scope);if(collection&&this._scopes[collection])return check(this._scopes[collection]);if(this._scopes["*"])return check(this._scopes["*"]);return!1}_send(msg){this._t?.send(msg)}}var META_KEY2="migrations",_serialize2=(value)=>JSON.stringify(value,function(key,v){let raw=this[key];if(raw instanceof Date)return{__skalex_date__:raw.toISOString()};if(typeof v==="bigint")return{__skalex_bigint__:v.toString()};return v}),_deserialize2=(text)=>JSON.parse(text,(_,v)=>{if(v&&typeof v==="object"){if("__skalex_bigint__"in v)return BigInt(v.__skalex_bigint__);if("__skalex_date__"in v)return new Date(v.__skalex_date__)}return v});class Skalex2{constructor({path="./.db",format="gz",debug=!1,adapter,ai,encrypt,slowQueryLog,queryCache,memory,logger:logger$1,plugins,llmAdapter,embeddingAdapter,regexMaxLength,idGenerator,serializer,deserializer,autoSave,ttlSweepInterval,lenientLoad}={}){if(this.dataDirectory=path,this.dataFormat=format,this.debug=debug,!Skalex2._errorsAttached)Skalex2.SkalexError=SkalexError2,Skalex2.ValidationError=ValidationError2,Skalex2.UniqueConstraintError=UniqueConstraintError2,Skalex2.TransactionError=TransactionError2,Skalex2.PersistenceError=PersistenceError2,Skalex2.AdapterError=AdapterError2,Skalex2.QueryError=QueryError2,Skalex2._errorsAttached=!0;this._adapterConfig=adapter??null;let fs=adapter||new FsAdapter2({dir:path,format});if(encrypt)fs=new EncryptedAdapter2(fs,encrypt.key);if(this.fs=fs,this._registry=new CollectionRegistry2(Collection2),this.collections=this._registry.stores,this._collectionInstances=this._registry._instances,this._migrations=new MigrationEngine2,this._connectPromise=null,this.isConnected=!1,this._aiConfig=ai||null,this._encryptConfig=encrypt||null,this._pluginsConfig=Array.isArray(plugins)?plugins:null,this._memoryConfig=memory||null,this._regexMaxLength=regexMaxLength??500,this._idGenerator=idGenerator??null,this._serializer=serializer??_serialize2,this._deserializer=deserializer??_deserialize2,this._autoSave=autoSave??!1,this._txManager=new TransactionManager2,this._ttlSweepInterval=ttlSweepInterval??0,this._ttlTimer=null,this._logger=logger$1??logger2,this._embeddingAdapter=embeddingAdapter??(ai?createEmbeddingAdapter2(ai):null),this._aiAdapter=llmAdapter??(ai?createLLMAdapter2(ai):null),this._persistence=new PersistenceManager2({adapter:this.fs,serializer:this._serializer,deserializer:this._deserializer,logger:this._logger,debug:this.debug,lenientLoad:lenientLoad??!1}),this._changeLog=new ChangeLog2(this),this._queryCache=new QueryCache2(queryCache||{}),this._eventBus=new EventBus2,this._queryLog=slowQueryLog?new QueryLog2(slowQueryLog):null,this._sessionStats=new SessionStats2,this._plugins=new PluginEngine2,Array.isArray(plugins))for(let p of plugins)this._plugins.register(p)}async connect(){if(this._connectPromise)return this._connectPromise;return this._connectPromise=this._doConnect(),this._connectPromise}async _doConnect(){try{await this.loadData();let meta=this._getMeta();if(meta.queryCache)this._queryCache.fromJSON(meta.queryCache);if(this._migrations._migrations.length>0){let applied=meta.appliedVersions||[],newApplied=await this._migrations.run((version)=>this.useCollection(`_migration_${version}`),applied);this._saveMeta({appliedVersions:newApplied})}if(this._sweepTtl(),this._ttlSweepInterval>0){if(this._ttlTimer=setInterval(()=>this._sweepTtl(),this._ttlSweepInterval),this._ttlTimer?.unref)this._ttlTimer.unref()}this.isConnected=!0,this._log("> - Connected to the database (\u221A)")}catch(error22){throw this._logger(`Error connecting to the database: ${error22}`,"error"),error22}}async disconnect(){try{if(this._ttlTimer)clearInterval(this._ttlTimer),this._ttlTimer=null;await this.saveData(),this._registry.clear(),this.collections=this._registry.stores,this._collectionInstances=this._registry._instances,this._connectPromise=null,this.isConnected=!1,this._log("> - Disconnected from the database (\u221A)")}catch(error22){throw this._logger(`Error disconnecting from the database: ${error22}`,"error"),error22}}async _ensureConnected(){if(this.isConnected)return;return this.connect()}useCollection(collectionName){return this._registry.get(collectionName,this)}createCollection(collectionName,options={}){return this._registry.create(collectionName,options,this)}_createCollectionStore(collectionName,options={}){this._registry.createStore(collectionName,options)}async renameCollection(from,to){this._registry.rename(from,to),await this.saveData(to),await this.fs.delete(from)}async loadData(){await this._persistence.loadAll(this.collections,{parseSchema:parseSchema2,buildIndex:this._registry.buildIndex,IndexEngine:IndexEngine2});for(let name in this._collectionInstances){let store=this.collections[name];if(store&&this._collectionInstances[name]._store!==store)this._collectionInstances[name]._store=store}}async saveData(collectionName){await this._persistence.save(this.collections,collectionName)}buildIndex(data,keyField){return this._registry.buildIndex(data,keyField)}addMigration(migration){this._migrations.add(migration)}migrationStatus(){let meta=this._getMeta();return this._migrations.status(meta.appliedVersions||[])}namespace(id){if(this._adapterConfig)throw new AdapterError2("ERR_SKALEX_ADAPTER_NAMESPACE_REQUIRES_FS","namespace() requires the default FsAdapter. When a custom storage adapter is configured, create a separate Skalex instance with your adapter instead.");let safeId=String(id).replace(/[^a-zA-Z0-9_-]/g,"_");if(!safeId)throw new ValidationError2("ERR_SKALEX_VALIDATION_NAMESPACE_ID","namespace: id must contain at least one alphanumeric character",{id});return new Skalex2({path:`${this.dataDirectory}/${safeId}`,format:this.dataFormat,debug:this.debug,ai:this._aiConfig||void 0,encrypt:this._encryptConfig||void 0,slowQueryLog:this._queryLog?{threshold:this._queryLog._threshold,maxEntries:this._queryLog._maxEntries}:void 0,queryCache:this._queryCache?{maxSize:this._queryCache._maxSize,ttl:this._queryCache._ttl}:void 0,plugins:this._pluginsConfig||void 0,memory:this._memoryConfig||void 0,logger:this._logger!==logger2?this._logger:void 0,llmAdapter:this._aiAdapter&&!this._aiConfig?this._aiAdapter:void 0,embeddingAdapter:this._embeddingAdapter&&!this._aiConfig?this._embeddingAdapter:void 0,regexMaxLength:this._regexMaxLength!==500?this._regexMaxLength:void 0,idGenerator:this._idGenerator||void 0,serializer:this._serializer!==_serialize2?this._serializer:void 0,deserializer:this._deserializer!==_deserialize2?this._deserializer:void 0,autoSave:this._autoSave||void 0,ttlSweepInterval:this._ttlSweepInterval||void 0})}use(plugin){this._plugins.register(plugin)}watch(callback){return this._eventBus.on("*",callback)}sessionStats(sessionId){if(sessionId!==void 0)return this._sessionStats.get(sessionId);return this._sessionStats.all()}get _inTransaction(){return this._txManager.active}_emitEvent(collectionName,data){if(!this._txManager.defer(()=>this._eventBus.emit(collectionName,data)))this._eventBus.emit(collectionName,data)}async _runAfterHook(hook,data){if(!this._txManager.defer(()=>this._plugins.run(hook,data)))await this._plugins.run(hook,data)}async _logChange(op,collectionName,doc,prev,session){if(!this._txManager.defer(()=>this._changeLog.log(op,collectionName,doc,prev,session)))await this._changeLog.log(op,collectionName,doc,prev,session)}async transaction(fn,opts={}){return this._txManager.run(fn,this,opts)}async seed(fixtures,{reset=!1}={}){for(let[name,docs]of Object.entries(fixtures)){if(reset&&this.collections[name])this._applySnapshot(name,{data:[],index:new Map}),delete this._collectionInstances[name];await this.useCollection(name).insertMany(docs)}await this.saveData()}dump(){return this._registry.dump()}inspect(collectionName){return this._registry.inspect(collectionName)}async import(filePath){let content=await this.fs.readRaw(filePath),docs;try{docs=JSON.parse(content)}catch{throw new PersistenceError2("ERR_SKALEX_PERSISTENCE_INVALID_JSON",`import: invalid JSON in file "${filePath}"`,{filePath})}let name=filePath.split("/").pop().replace(/\.[^.]+$/,"");return this.useCollection(name).insertMany(Array.isArray(docs)?docs:[docs],{save:!0})}async embed(text){if(!this._embeddingAdapter)throw new AdapterError2("ERR_SKALEX_ADAPTER_EMBEDDING_REQUIRED","db.embed() requires an AI adapter. Pass { ai: { provider, apiKey } } to the Skalex constructor.");return this._embeddingAdapter.embed(text)}async ask(collectionName,nlQuery,{limit=20}={}){if(!this._aiAdapter)throw new AdapterError2("ERR_SKALEX_ADAPTER_LLM_REQUIRED",'db.ask() requires a language model adapter. Configure { ai: { provider, model: "..." } }.');let col=this.useCollection(collectionName),schema=this.schema(collectionName),filter=this._queryCache.get(collectionName,schema,nlQuery);if(!filter){filter=await this._aiAdapter.generate(schema,nlQuery);let warnings=validateLLMFilter2(filter,schema);if(warnings.length)warnings.forEach((w)=>this._log(`[ask] ${w}`));this._queryCache.set(collectionName,schema,nlQuery,filter),this._saveMeta({queryCache:this._queryCache.toJSON()})}return col.find(processLLMFilter2(filter,{regexMaxLength:this._regexMaxLength}),{limit})}schema(collectionName){return this._registry.schema(collectionName)}useMemory(sessionId){return new Memory2(sessionId,this)}changelog(){return this._changeLog}async restore(collectionName,timestamp,opts={}){return this._changeLog.restore(collectionName,timestamp,opts)}stats(collectionName){return this._registry.stats(collectionName)}slowQueries(opts={}){if(!this._queryLog)return[];return this._queryLog.entries(opts)}slowQueryCount(){return this._queryLog?this._queryLog.size:0}clearSlowQueries(){this._queryLog?.clear()}mcp(opts={}){return new SkalexMCPServer2(this,opts)}_getMeta(){let metaCol=this.collections._meta;if(!metaCol)return{};return metaCol.index.get(META_KEY2)||{}}_saveMeta(data){if(!this.collections._meta)this._createCollectionStore("_meta");let col=this.collections._meta,existing=col.index.get(META_KEY2);if(existing)Object.assign(existing,data);else{let doc={_id:META_KEY2,...data};col.data.push(doc),col.index.set(META_KEY2,doc)}this._persistence.markDirty(this.collections,"_meta")}_sweepTtl(){for(let name in this.collections){let col=this.collections[name],removed=sweep2(col.data,col.index,col.fieldIndex?(doc)=>col.fieldIndex.remove(doc):null);if(removed>0)this._persistence.markDirty(this.collections,name),this._log(`TTL sweep: removed ${removed} expired docs from "${name}"`)}}_buildCollectionContext(){let db=this;return{ensureConnected:()=>db._ensureConnected(),get txManager(){return db._txManager},get plugins(){return db._plugins},get eventBus(){return db._eventBus},get sessionStats(){return db._sessionStats},get queryLog(){return db._queryLog},get logger(){return db._logger},get persistence(){return db._persistence},get collections(){return db.collections},embed:(text)=>db.embed(text),get idGenerator(){return db._idGenerator},get autoSave(){return db._autoSave},saveCollection:(name)=>db.saveData(name),snapshotCollection:(col)=>db._snapshotCollection(col),getCollection:(name)=>db.useCollection(name),emitEvent:(name,data)=>db._emitEvent(name,data),runAfterHook:(hook,data)=>db._runAfterHook(hook,data),logChange:(op,col,doc,prev,session)=>db._logChange(op,col,doc,prev,session),get fs(){return db.fs},get dataDirectory(){return db.dataDirectory}}}_log(msg){if(this.debug)this._logger(msg,"info")}_snapshotCollection(col){return{data:structuredClone(col.data)}}_applySnapshot(name,snap){let col=this.collections[name];if(!col)return;if(col.data=snap.data,col.index=this.buildIndex(snap.data,"_id"),col.fieldIndex)col.fieldIndex.buildFromData(snap.data)}}class AgentDatabase{}var registry=new Map;function registerAdapter(name,factory){registry.set(name,factory)}var nowIso=()=>new Date().toISOString();function cleanDoc(doc){if(!doc)return doc;let{_id:_ignoredId,createdAt:rawCreatedAt,updatedAt:rawUpdatedAt,_version:_ignoredVersion,_expiresAt:_ignoredExpires,...rest}=doc,out={...rest};if(out.createdAt==null&&rawCreatedAt!=null)out.createdAt=rawCreatedAt instanceof Date?rawCreatedAt.toISOString():String(rawCreatedAt);if(out.updatedAt==null&&rawUpdatedAt!=null)out.updatedAt=rawUpdatedAt instanceof Date?rawUpdatedAt.toISOString():String(rawUpdatedAt);return out}class SkalexAgentDatabase extends AgentDatabase{dataDir;encryptionKey;lockPath;lockFd=null;db;tasks;config;gitRepos;bookmarks;notifications;pluginState;constructor(opts){super();this.dataDir=opts.dataDir,this.encryptionKey=opts.encryptionKey,this.lockPath=join(opts.dataDir,".agent-db.lock")}static async create(opts){if(!existsSync(opts.dataDir))mkdirSync(opts.dataDir,{recursive:!0});let instance=new SkalexAgentDatabase(opts);instance.acquireLock();try{await instance.init()}catch(err){throw instance.releaseLock(),err}return instance}acquireLock(){try{this.lockFd=openSync(this.lockPath,"wx",384),writeFileSync(this.lockFd,JSON.stringify({pid:process.pid,createdAt:new Date().toISOString()}));return}catch(err){if(err.code!=="EEXIST")throw err}let stale=!1;try{let raw=JSON.parse(readFileSync(this.lockPath,"utf8"));if(!raw.pid)stale=!0;else try{process.kill(raw.pid,0)}catch{stale=!0}}catch{stale=!0}if(stale){try{unlinkSync(this.lockPath)}catch{}this.acquireLock();return}throw Error(`Agent database is already open by another process (${this.lockPath})`)}releaseLock(){if(this.lockFd!==null){try{closeSync(this.lockFd)}catch{}this.lockFd=null}try{unlinkSync(this.lockPath)}catch{}}async init(){this.db=new Skalex2({path:this.dataDir,encrypt:{key:this.encryptionKey},autoSave:!0,format:"gz",lenientLoad:!0}),this.tasks=this.db.createCollection("tasks",{schema:{id:{type:"string",required:!0,unique:!0},type:{type:"string",required:!0,enum:["command","script","file_operation"]},status:{type:"string",required:!0,enum:["pending","running","completed","failed"]},payload:{type:"string",required:!0},result:{type:"string"},error:{type:"string"},calendarTaskId:{type:"string"},exitCode:{type:"number"},timeout:{type:"number"}},indexes:["status","type"]}),this.config=this.db.createCollection("agent_config",{schema:{key:{type:"string",required:!0,unique:!0},value:{type:"string",required:!0}}}),this.gitRepos=this.db.createCollection("git_repositories",{schema:{id:{type:"string",required:!0,unique:!0},path:{type:"string",required:!0,unique:!0},name:{type:"string",required:!0},parentPath:{type:"string"},isSubmodule:{type:"boolean"},projectType:{type:"string"},vitePort:{type:"number"},lastScanned:{type:"string"}},indexes:["parentPath"]}),this.bookmarks=this.db.createCollection("bookmarked_commands",{schema:{id:{type:"string",required:!0,unique:!0},projectId:{type:"string"},command:{type:"string",required:!0},description:{type:"string"},category:{type:"string"}},indexes:["projectId","category"]}),this.notifications=this.db.createCollection("notifications",{schema:{id:{type:"string",required:!0,unique:!0},sessionName:{type:"string"},projectId:{type:"string"},type:{type:"string",required:!0,enum:["info","success","warning","error"]},title:{type:"string",required:!0},message:{type:"string",required:!0},status:{type:"string",required:!0,enum:["unread","read"]}},indexes:["status","projectId"]}),this.pluginState=this.db.createCollection("plugin_state",{schema:{pluginName:{type:"string",required:!0},key:{type:"string",required:!0},value:{type:"string",required:!0}},indexes:["pluginName"]}),await this.db.connect()}async close(){if(this.db?.isConnected)await this.db.disconnect();this.releaseLock()}getDbPath(){return this.dataDir}async createTask(task){let doc={id:task.id,type:task.type,status:task.status,payload:task.payload};if(task.result!=null)doc.result=task.result;if(task.error!=null)doc.error=task.error;if(task.calendarTaskId!=null)doc.calendarTaskId=task.calendarTaskId;if(task.exitCode!=null)doc.exitCode=task.exitCode;if(task.timeout!=null)doc.timeout=task.timeout;let inserted=await this.tasks.insertOne(doc);return cleanDoc(inserted)}async getTask(id){let doc=await this.tasks.findOne({id});return doc?cleanDoc(doc):void 0}async getAllTasks(){return(await this.tasks.find(void 0,{sort:{createdAt:-1}})).docs.map((d)=>cleanDoc(d))}async getPendingTasks(){return(await this.tasks.find({status:"pending"},{sort:{createdAt:1}})).docs.map((d)=>cleanDoc(d))}async updateTask(id,updates){let patch={};for(let[k,v]of Object.entries(updates)){if(k==="id"||k==="createdAt"||k==="updatedAt")continue;patch[k]=v??null}if(Object.keys(patch).length===0)return;await this.tasks.updateOne({id},patch)}async cancelTask(id){let existing=await this.tasks.findOne({id});if(!existing||existing.status!=="pending"&&existing.status!=="running")return!1;return await this.tasks.updateOne({id},{status:"failed",error:"Cancelled"}),!0}async getConfig(key){return(await this.config.findOne({key}))?.value}async setConfig(key,value){await this.config.upsert({key},{key,value})}async deleteConfig(key){return await this.config.deleteOne({key})!==null}async getAllConfig(){let res=await this.config.find(),out={};for(let doc of res.docs)out[doc.key]=doc.value;return out}async bulkSetConfig(entries){for(let[key,value]of Object.entries(entries))await this.config.upsert({key},{key,value})}async getConfigStatus(){let res=await this.config.find(),latest=null;for(let doc of res.docs){let raw=doc.updatedAt,iso=raw instanceof Date?raw.toISOString():typeof raw==="string"?raw:null;if(iso&&(!latest||iso>latest))latest=iso}return{totalKeys:res.docs.length,lastUpdated:latest}}async createGitRepository(repo){let doc={id:repo.id,path:repo.path,name:repo.name,isSubmodule:Boolean(repo.isSubmodule),lastScanned:nowIso()};if(repo.parentPath!=null)doc.parentPath=repo.parentPath;if(repo.projectType!=null)doc.projectType=repo.projectType;if(repo.vitePort!=null)doc.vitePort=repo.vitePort;let inserted=await this.gitRepos.insertOne(doc);return cleanDoc(inserted)}async getGitRepository(id){let doc=await this.gitRepos.findOne({id});return doc?cleanDoc(doc):void 0}async getGitRepositoryByPath(path){let doc=await this.gitRepos.findOne({path});return doc?cleanDoc(doc):void 0}async getAllGitRepositories(){return(await this.gitRepos.find(void 0,{sort:{path:1}})).docs.map((d)=>cleanDoc(d))}async updateGitRepository(id,updates){let patch={lastScanned:nowIso()};for(let[k,v]of Object.entries(updates)){if(k==="id"||k==="createdAt"||k==="updatedAt")continue;if(k==="isSubmodule"){patch[k]=Boolean(v);continue}patch[k]=v??null}await this.gitRepos.updateOne({id},patch)}async deleteGitRepository(id){return await this.gitRepos.deleteOne({id})!==null}async fixGitHierarchy(){let repos=await this.getAllGitRepositories(),fixed=0;for(let repo of repos){if(repo.isSubmodule)continue;let parent=repos.find((r)=>r.id!==repo.id&&repo.path.startsWith(`${r.path}/`)&&!r.isSubmodule);if(parent&&repo.parentPath!==parent.path)await this.updateGitRepository(repo.id,{parentPath:parent.path}),fixed++}return{fixed}}async createBookmarkedCommand(cmd){let doc={id:cmd.id,command:cmd.command};if(cmd.projectId!=null)doc.projectId=cmd.projectId;if(cmd.description!=null)doc.description=cmd.description;if(cmd.category!=null)doc.category=cmd.category;let inserted=await this.bookmarks.insertOne(doc);return cleanDoc(inserted)}async getBookmarkedCommand(id){let doc=await this.bookmarks.findOne({id});return doc?cleanDoc(doc):void 0}async getAllBookmarkedCommands(){return(await this.bookmarks.find(void 0,{sort:{createdAt:-1}})).docs.map((d)=>cleanDoc(d))}async getBookmarkedCommandsByProject(projectId){let filter=projectId===null?{projectId:{$fn:(v)=>v==null}}:{projectId};return(await this.bookmarks.find(filter,{sort:{createdAt:-1}})).docs.map((d)=>cleanDoc(d))}async getBookmarkedCommandsByCategory(category){return(await this.bookmarks.find({category},{sort:{createdAt:-1}})).docs.map((d)=>cleanDoc(d))}async updateBookmarkedCommand(id,updates){let patch={};for(let[k,v]of Object.entries(updates)){if(k==="id"||k==="createdAt"||k==="updatedAt")continue;patch[k]=v??null}if(Object.keys(patch).length===0)return;await this.bookmarks.updateOne({id},patch)}async deleteBookmarkedCommand(id){return await this.bookmarks.deleteOne({id})!==null}async executeBookmarkedCommand(id){return this.getBookmarkedCommand(id)}async createNotification(notification){let doc={id:notification.id,type:notification.type,title:notification.title,message:notification.message,status:notification.status};if(notification.sessionName!=null)doc.sessionName=notification.sessionName;if(notification.projectId!=null)doc.projectId=notification.projectId;let inserted=await this.notifications.insertOne(doc);return cleanDoc(inserted)}async getNotification(id){let doc=await this.notifications.findOne({id});return doc?cleanDoc(doc):void 0}async getAllNotifications(){return(await this.notifications.find(void 0,{sort:{createdAt:-1}})).docs.map((d)=>cleanDoc(d))}async getNotificationsByProject(projectId){let filter=projectId===null?{projectId:{$fn:(v)=>v==null}}:{projectId};return(await this.notifications.find(filter,{sort:{createdAt:-1}})).docs.map((d)=>cleanDoc(d))}async getGlobalNotifications(){return this.getNotificationsByProject(null)}async getUnreadNotifications(){return(await this.notifications.find({status:"unread"},{sort:{createdAt:-1}})).docs.map((d)=>cleanDoc(d))}async updateNotificationStatus(id,status){await this.notifications.updateOne({id},{status})}async markAllNotificationsRead(){return(await this.notifications.updateMany({status:"unread"},{status:"read"})).length}async deleteNotification(id){return await this.notifications.deleteOne({id})!==null}async clearOldNotifications(olderThanDays=30){let cutoff=new Date(Date.now()-olderThanDays*24*60*60*1000);return(await this.notifications.deleteMany({createdAt:{$fn:(v)=>v instanceof Date&&v<cutoff}})).length}async getPluginState(pluginName,key){return(await this.pluginState.findOne({$and:[{pluginName},{key}]}))?.value}async setPluginState(pluginName,key,value){await this.pluginState.upsert({$and:[{pluginName},{key}]},{pluginName,key,value})}async deletePluginState(pluginName,key){return await this.pluginState.deleteOne({$and:[{pluginName},{key}]})!==null}async getAllPluginState(pluginName){return(await this.pluginState.find({pluginName},{sort:{key:1}})).docs.map((doc)=>{let raw=doc.updatedAt,updatedAt=raw instanceof Date?raw.toISOString():typeof raw==="string"?raw:void 0;return{key:doc.key,value:doc.value,updatedAt}})}async deleteAllPluginState(pluginName){return(await this.pluginState.deleteMany({pluginName})).length}}var createSkalexAgentDatabase=(opts)=>SkalexAgentDatabase.create(opts);registerAdapter("skalex",createSkalexAgentDatabase);var registry2=new Map;function registerAdapter2(name,factory){registry2.set(name,factory)}class AgentDatabase2{}registerAdapter2("skalex",createSkalexAgentDatabase);var nowIso2=()=>new Date().toISOString();function cleanDoc2(doc){if(!doc)return doc;let{_id:_ignoredId,createdAt:rawCreatedAt,updatedAt:rawUpdatedAt,_version:_ignoredVersion,_expiresAt:_ignoredExpires,...rest}=doc,out={...rest};if(out.createdAt==null&&rawCreatedAt!=null)out.createdAt=rawCreatedAt instanceof Date?rawCreatedAt.toISOString():String(rawCreatedAt);if(out.updatedAt==null&&rawUpdatedAt!=null)out.updatedAt=rawUpdatedAt instanceof Date?rawUpdatedAt.toISOString():String(rawUpdatedAt);return out}class SkalexAgentDatabase2 extends AgentDatabase2{dataDir;encryptionKey;lockPath;lockFd=null;db;tasks;config;gitRepos;bookmarks;notifications;pluginState;constructor(opts){super();this.dataDir=opts.dataDir,this.encryptionKey=opts.encryptionKey,this.lockPath=join2(opts.dataDir,".agent-db.lock")}static async create(opts){if(!existsSync2(opts.dataDir))mkdirSync2(opts.dataDir,{recursive:!0});let instance=new SkalexAgentDatabase2(opts);instance.acquireLock();try{await instance.init()}catch(err){throw instance.releaseLock(),err}return instance}acquireLock(){try{this.lockFd=openSync2(this.lockPath,"wx",384),writeFileSync2(this.lockFd,JSON.stringify({pid:process.pid,createdAt:new Date().toISOString()}));return}catch(err){if(err.code!=="EEXIST")throw err}let stale=!1;try{let raw=JSON.parse(readFileSync2(this.lockPath,"utf8"));if(!raw.pid)stale=!0;else try{process.kill(raw.pid,0)}catch{stale=!0}}catch{stale=!0}if(stale){try{unlinkSync2(this.lockPath)}catch{}this.acquireLock();return}throw Error(`Agent database is already open by another process (${this.lockPath})`)}releaseLock(){if(this.lockFd!==null){try{closeSync2(this.lockFd)}catch{}this.lockFd=null}try{unlinkSync2(this.lockPath)}catch{}}async init(){this.db=new Skalex({path:this.dataDir,encrypt:{key:this.encryptionKey},autoSave:!0,format:"gz",lenientLoad:!0}),this.tasks=this.db.createCollection("tasks",{schema:{id:{type:"string",required:!0,unique:!0},type:{type:"string",required:!0,enum:["command","script","file_operation"]},status:{type:"string",required:!0,enum:["pending","running","completed","failed"]},payload:{type:"string",required:!0},result:{type:"string"},error:{type:"string"},calendarTaskId:{type:"string"},exitCode:{type:"number"},timeout:{type:"number"}},indexes:["status","type"]}),this.config=this.db.createCollection("agent_config",{schema:{key:{type:"string",required:!0,unique:!0},value:{type:"string",required:!0}}}),this.gitRepos=this.db.createCollection("git_repositories",{schema:{id:{type:"string",required:!0,unique:!0},path:{type:"string",required:!0,unique:!0},name:{type:"string",required:!0},parentPath:{type:"string"},isSubmodule:{type:"boolean"},projectType:{type:"string"},vitePort:{type:"number"},lastScanned:{type:"string"}},indexes:["parentPath"]}),this.bookmarks=this.db.createCollection("bookmarked_commands",{schema:{id:{type:"string",required:!0,unique:!0},projectId:{type:"string"},command:{type:"string",required:!0},description:{type:"string"},category:{type:"string"}},indexes:["projectId","category"]}),this.notifications=this.db.createCollection("notifications",{schema:{id:{type:"string",required:!0,unique:!0},sessionName:{type:"string"},projectId:{type:"string"},type:{type:"string",required:!0,enum:["info","success","warning","error"]},title:{type:"string",required:!0},message:{type:"string",required:!0},status:{type:"string",required:!0,enum:["unread","read"]}},indexes:["status","projectId"]}),this.pluginState=this.db.createCollection("plugin_state",{schema:{pluginName:{type:"string",required:!0},key:{type:"string",required:!0},value:{type:"string",required:!0}},indexes:["pluginName"]}),await this.db.connect()}async close(){if(this.db?.isConnected)await this.db.disconnect();this.releaseLock()}getDbPath(){return this.dataDir}async createTask(task){let doc={id:task.id,type:task.type,status:task.status,payload:task.payload};if(task.result!=null)doc.result=task.result;if(task.error!=null)doc.error=task.error;if(task.calendarTaskId!=null)doc.calendarTaskId=task.calendarTaskId;if(task.exitCode!=null)doc.exitCode=task.exitCode;if(task.timeout!=null)doc.timeout=task.timeout;let inserted=await this.tasks.insertOne(doc);return cleanDoc2(inserted)}async getTask(id){let doc=await this.tasks.findOne({id});return doc?cleanDoc2(doc):void 0}async getAllTasks(){return(await this.tasks.find(void 0,{sort:{createdAt:-1}})).docs.map((d)=>cleanDoc2(d))}async getPendingTasks(){return(await this.tasks.find({status:"pending"},{sort:{createdAt:1}})).docs.map((d)=>cleanDoc2(d))}async updateTask(id,updates){let patch={};for(let[k,v]of Object.entries(updates)){if(k==="id"||k==="createdAt"||k==="updatedAt")continue;patch[k]=v??null}if(Object.keys(patch).length===0)return;await this.tasks.updateOne({id},patch)}async cancelTask(id){let existing=await this.tasks.findOne({id});if(!existing||existing.status!=="pending"&&existing.status!=="running")return!1;return await this.tasks.updateOne({id},{status:"failed",error:"Cancelled"}),!0}async getConfig(key){return(await this.config.findOne({key}))?.value}async setConfig(key,value){await this.config.upsert({key},{key,value})}async deleteConfig(key){return await this.config.deleteOne({key})!==null}async getAllConfig(){let res=await this.config.find(),out={};for(let doc of res.docs)out[doc.key]=doc.value;return out}async bulkSetConfig(entries){for(let[key,value]of Object.entries(entries))await this.config.upsert({key},{key,value})}async getConfigStatus(){let res=await this.config.find(),latest=null;for(let doc of res.docs){let raw=doc.updatedAt,iso=raw instanceof Date?raw.toISOString():typeof raw==="string"?raw:null;if(iso&&(!latest||iso>latest))latest=iso}return{totalKeys:res.docs.length,lastUpdated:latest}}async createGitRepository(repo){let doc={id:repo.id,path:repo.path,name:repo.name,isSubmodule:Boolean(repo.isSubmodule),lastScanned:nowIso2()};if(repo.parentPath!=null)doc.parentPath=repo.parentPath;if(repo.projectType!=null)doc.projectType=repo.projectType;if(repo.vitePort!=null)doc.vitePort=repo.vitePort;let inserted=await this.gitRepos.insertOne(doc);return cleanDoc2(inserted)}async getGitRepository(id){let doc=await this.gitRepos.findOne({id});return doc?cleanDoc2(doc):void 0}async getGitRepositoryByPath(path){let doc=await this.gitRepos.findOne({path});return doc?cleanDoc2(doc):void 0}async getAllGitRepositories(){return(await this.gitRepos.find(void 0,{sort:{path:1}})).docs.map((d)=>cleanDoc2(d))}async updateGitRepository(id,updates){let patch={lastScanned:nowIso2()};for(let[k,v]of Object.entries(updates)){if(k==="id"||k==="createdAt"||k==="updatedAt")continue;if(k==="isSubmodule"){patch[k]=Boolean(v);continue}patch[k]=v??null}await this.gitRepos.updateOne({id},patch)}async deleteGitRepository(id){return await this.gitRepos.deleteOne({id})!==null}async fixGitHierarchy(){let repos=await this.getAllGitRepositories(),fixed=0;for(let repo of repos){if(repo.isSubmodule)continue;let parent=repos.find((r)=>r.id!==repo.id&&repo.path.startsWith(`${r.path}/`)&&!r.isSubmodule);if(parent&&repo.parentPath!==parent.path)await this.updateGitRepository(repo.id,{parentPath:parent.path}),fixed++}return{fixed}}async createBookmarkedCommand(cmd){let doc={id:cmd.id,command:cmd.command};if(cmd.projectId!=null)doc.projectId=cmd.projectId;if(cmd.description!=null)doc.description=cmd.description;if(cmd.category!=null)doc.category=cmd.category;let inserted=await this.bookmarks.insertOne(doc);return cleanDoc2(inserted)}async getBookmarkedCommand(id){let doc=await this.bookmarks.findOne({id});return doc?cleanDoc2(doc):void 0}async getAllBookmarkedCommands(){return(await this.bookmarks.find(void 0,{sort:{createdAt:-1}})).docs.map((d)=>cleanDoc2(d))}async getBookmarkedCommandsByProject(projectId){let filter=projectId===null?{projectId:{$fn:(v)=>v==null}}:{projectId};return(await this.bookmarks.find(filter,{sort:{createdAt:-1}})).docs.map((d)=>cleanDoc2(d))}async getBookmarkedCommandsByCategory(category){return(await this.bookmarks.find({category},{sort:{createdAt:-1}})).docs.map((d)=>cleanDoc2(d))}async updateBookmarkedCommand(id,updates){let patch={};for(let[k,v]of Object.entries(updates)){if(k==="id"||k==="createdAt"||k==="updatedAt")continue;patch[k]=v??null}if(Object.keys(patch).length===0)return;await this.bookmarks.updateOne({id},patch)}async deleteBookmarkedCommand(id){return await this.bookmarks.deleteOne({id})!==null}async executeBookmarkedCommand(id){return this.getBookmarkedCommand(id)}async createNotification(notification){let doc={id:notification.id,type:notification.type,title:notification.title,message:notification.message,status:notification.status};if(notification.sessionName!=null)doc.sessionName=notification.sessionName;if(notification.projectId!=null)doc.projectId=notification.projectId;let inserted=await this.notifications.insertOne(doc);return cleanDoc2(inserted)}async getNotification(id){let doc=await this.notifications.findOne({id});return doc?cleanDoc2(doc):void 0}async getAllNotifications(){return(await this.notifications.find(void 0,{sort:{createdAt:-1}})).docs.map((d)=>cleanDoc2(d))}async getNotificationsByProject(projectId){let filter=projectId===null?{projectId:{$fn:(v)=>v==null}}:{projectId};return(await this.notifications.find(filter,{sort:{createdAt:-1}})).docs.map((d)=>cleanDoc2(d))}async getGlobalNotifications(){return this.getNotificationsByProject(null)}async getUnreadNotifications(){return(await this.notifications.find({status:"unread"},{sort:{createdAt:-1}})).docs.map((d)=>cleanDoc2(d))}async updateNotificationStatus(id,status){await this.notifications.updateOne({id},{status})}async markAllNotificationsRead(){return(await this.notifications.updateMany({status:"unread"},{status:"read"})).length}async deleteNotification(id){return await this.notifications.deleteOne({id})!==null}async clearOldNotifications(olderThanDays=30){let cutoff=new Date(Date.now()-olderThanDays*24*60*60*1000);return(await this.notifications.deleteMany({createdAt:{$fn:(v)=>v instanceof Date&&v<cutoff}})).length}async getPluginState(pluginName,key){return(await this.pluginState.findOne({$and:[{pluginName},{key}]}))?.value}async setPluginState(pluginName,key,value){await this.pluginState.upsert({$and:[{pluginName},{key}]},{pluginName,key,value})}async deletePluginState(pluginName,key){return await this.pluginState.deleteOne({$and:[{pluginName},{key}]})!==null}async getAllPluginState(pluginName){return(await this.pluginState.find({pluginName},{sort:{key:1}})).docs.map((doc)=>{let raw=doc.updatedAt,updatedAt=raw instanceof Date?raw.toISOString():typeof raw==="string"?raw:void 0;return{key:doc.key,value:doc.value,updatedAt}})}async deleteAllPluginState(pluginName){return(await this.pluginState.deleteMany({pluginName})).length}}var createSkalexAgentDatabase2=(opts)=>SkalexAgentDatabase2.create(opts);registerAdapter2("skalex",createSkalexAgentDatabase2);var registry3=new Map;function registerAdapter3(name,factory){registry3.set(name,factory)}function getAdapter(name){return registry3.get(name)}function listAdapters(){return Array.from(registry3.keys())}class AgentDatabase3{}async function resolveFactory(options){if(options.adapterFactory)return options.adapterFactory;let name=options.adapterName??process.env.VIBE_STORAGE_ADAPTER??"skalex";if(name.startsWith("custom:")){let modPath=name.slice(7);if(!modPath)throw Error("VIBE_STORAGE_ADAPTER=custom: requires a module path after the colon");let mod=await import(modPath),factory2=mod.default??mod.createAdapter;if(typeof factory2!=="function")throw Error(`Custom storage adapter at ${modPath} must export a default function (or \`createAdapter\`) of type AgentStorageAdapterFactory`);return factory2}let factory=getAdapter(name);if(!factory){let candidate={skalex:"@vibecontrols/vibe-plugin-storage-skalex",postgres:"@vibecontrols/vibe-plugin-storage-postgres",postgresql:"@vibecontrols/vibe-plugin-storage-postgres"}[name];if(candidate)try{await import(candidate),factory=getAdapter(name)}catch{}}if(!factory)throw Error(`Unknown storage adapter: "${name}". Registered adapters: ${listAdapters().join(", ")||`(none \u2014 did you install @vibecontrols/vibe-plugin-storage-${name})?`}`);return factory}async function createAgentDatabase(options){if(!options.encryptionKey)throw Error("createAgentDatabase(): encryptionKey is required. Storage is always encrypted at rest.");if(!options.dbPath)throw Error("createAgentDatabase(): dbPath is required.");return(await resolveFactory(options))({dataDir:options.dbPath,encryptionKey:options.encryptionKey,adapterOptions:options.adapterOptions})}registerAdapter3("skalex",createSkalexAgentDatabase2);var PLUGIN_NAME="storage",PLUGIN_VERSION="2026.509.5",createPlugin=(ctx)=>{let log=new BoundLogger(ctx.logger,PLUGIN_NAME),lifecycle=createLifecycleHooks({name:PLUGIN_NAME,telemetryEventName:"storage.ready",onInit:(hostServices)=>{new TelemetryEmitter(PLUGIN_NAME,PLUGIN_VERSION,hostServices).emitReady(),log.info("storage meta plugin ready (skalex adapter auto-registered)")}});return{name:PLUGIN_NAME,version:PLUGIN_VERSION,description:"Storage facade \u2014 owns AgentDatabase contract and adapter registry",tags:["backend","adapter"],capabilities:{storage:"rw"},onServerStart:lifecycle.onServerStart,onServerStop:lifecycle.onServerStop}},src_default=createPlugin;export{registerAdapter3 as registerAdapter,listAdapters,getAdapter,src_default as default,createPlugin,createAgentDatabase,AgentDatabase3 as AgentDatabase};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vibecontrols/vibe-plugin-storage",
3
- "version": "2026.509.4",
3
+ "version": "2026.509.5",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",