@vibecontrols/vibe-plugin-storage 2026.508.3 → 2026.508.4
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 +39 -0
- package/dist/index.js +1 -1
- package/package.json +1 -1
package/dist/index.d.ts
CHANGED
|
@@ -16,6 +16,45 @@
|
|
|
16
16
|
* skalex package directly. Override at runtime via VIBE_STORAGE_ADAPTER
|
|
17
17
|
* or pass `adapterFactory` to `createAgentDatabase()`.
|
|
18
18
|
*/
|
|
19
|
+
/**
|
|
20
|
+
* Minimal facade of the agent's ProfileContext. The plugin has no hard
|
|
21
|
+
* dependency on the agent package; it accepts whichever shape the agent
|
|
22
|
+
* passes that is structurally compatible with this interface.
|
|
23
|
+
*/
|
|
24
|
+
export interface ProfileContext {
|
|
25
|
+
name: string;
|
|
26
|
+
dataDir: string;
|
|
27
|
+
logger: {
|
|
28
|
+
info: (...args: unknown[]) => void;
|
|
29
|
+
warn: (...args: unknown[]) => void;
|
|
30
|
+
error: (...args: unknown[]) => void;
|
|
31
|
+
debug: (...args: unknown[]) => void;
|
|
32
|
+
};
|
|
33
|
+
audit?: {
|
|
34
|
+
emit: (event: string, payload?: unknown) => void;
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Minimal VibePlugin shape this meta package returns from its
|
|
39
|
+
* createPlugin(ctx) factory. The storage facade has no routes / CLI /
|
|
40
|
+
* lifecycle hooks of its own — it ships solely so concrete adapters
|
|
41
|
+
* (Skalex, Postgres) can register themselves on import. The factory is
|
|
42
|
+
* required to satisfy Plugin Contract v2 in the agent's loader.
|
|
43
|
+
*/
|
|
44
|
+
export interface VibeStoragePlugin {
|
|
45
|
+
name: string;
|
|
46
|
+
version: string;
|
|
47
|
+
description: string;
|
|
48
|
+
tags?: ReadonlyArray<string>;
|
|
49
|
+
}
|
|
50
|
+
export type VibePluginFactory = (ctx: ProfileContext) => VibeStoragePlugin;
|
|
51
|
+
/**
|
|
52
|
+
* Plugin Contract v2 factory. Returns a no-op meta plugin record; all
|
|
53
|
+
* actual storage capability is exposed via the named exports below
|
|
54
|
+
* (registerAdapter / createAgentDatabase / AgentDatabase).
|
|
55
|
+
*/
|
|
56
|
+
export declare const createPlugin: VibePluginFactory;
|
|
57
|
+
export default createPlugin;
|
|
19
58
|
export { AgentDatabase, type AgentStorageAdapterFactory, type AgentStorageAdapterOptions, type StorageEntry, type Task, type GitRepository, type BookmarkedCommand, type Notification, } from "./types.js";
|
|
20
59
|
export { registerAdapter, getAdapter, listAdapters } from "./registry.js";
|
|
21
60
|
export { createAgentDatabase, type AgentDatabaseCreateOptions, } from "./database.js";
|
package/dist/index.js
CHANGED
|
@@ -25,4 +25,4 @@ data: /message
|
|
|
25
25
|
|
|
26
26
|
`),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(error(null,PARSE_ERROR,"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 StdioTransport{constructor(){this._onMessage=null,this._buffer="",this._started=!1}onMessage(fn){this._onMessage=fn}send(msg){process.stdout.write(JSON.stringify(msg)+`
|
|
27
27
|
`)}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(`
|
|
28
|
-
`))!==-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(error(null,PARSE_ERROR,"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_INFO={name:"skalex",version:"4.0.0-alpha"},PROTOCOL_VERSION="2024-11-05";class SkalexMCPServer{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 HttpTransport({port:this._port,host:this._host,allowedOrigin:this._allowedOrigin,maxBodySize:this._maxBodySize});else this._t=new StdioTransport;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"?parse(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(ok(id,{protocolVersion:PROTOCOL_VERSION,capabilities:{tools:{}},serverInfo:SERVER_INFO}));break;case"tools/list":this._send(ok(id,{tools:this._visibleTools()}));break;case"tools/call":await this._handleToolCall(id,params);break;case"ping":this._send(ok(id,{}));break;default:this._send(error(id,METHOD_NOT_FOUND,`Method not found: ${method}`))}}catch(err){this._send(error(id,INTERNAL_ERROR,err.message||"Internal error"))}}async _handleToolCall(id,params){let name=params?.name,args=params?.arguments??{};if(!name){this._send(error(id,INVALID_PARAMS,"tools/call requires params.name"));return}let def=TOOL_DEFS.find((t)=>t.name===name);if(!def){this._send(error(id,METHOD_NOT_FOUND,`Unknown tool: ${name}`));return}let collection=args.collection||args.collection_name||null;if(!this._hasScope(collection,def.scope)){this._send(ok(id,toolError(`Access denied: "${name}" requires "${def.scope}" scope on collection "${collection}".`)));return}try{let result=await callTool(name,args,this._db);this._send(ok(id,toolResult(JSON.stringify(result,null,2))))}catch(err){this._send(ok(id,toolError(err.message||String(err))))}}_visibleTools(){return TOOL_DEFS.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_KEY="migrations",_serialize=(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}),_deserialize=(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 Skalex{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,!Skalex._errorsAttached)Skalex.SkalexError=SkalexError,Skalex.ValidationError=ValidationError,Skalex.UniqueConstraintError=UniqueConstraintError,Skalex.TransactionError=TransactionError,Skalex.PersistenceError=PersistenceError,Skalex.AdapterError=AdapterError,Skalex.QueryError=QueryError,Skalex._errorsAttached=!0;this._adapterConfig=adapter??null;let fs=adapter||new FsAdapter({dir:path,format});if(encrypt)fs=new EncryptedAdapter(fs,encrypt.key);if(this.fs=fs,this._registry=new CollectionRegistry(Collection),this.collections=this._registry.stores,this._collectionInstances=this._registry._instances,this._migrations=new MigrationEngine,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??_serialize,this._deserializer=deserializer??_deserialize,this._autoSave=autoSave??!1,this._txManager=new TransactionManager,this._ttlSweepInterval=ttlSweepInterval??0,this._ttlTimer=null,this._logger=logger$1??logger,this._embeddingAdapter=embeddingAdapter??(ai?createEmbeddingAdapter(ai):null),this._aiAdapter=llmAdapter??(ai?createLLMAdapter(ai):null),this._persistence=new PersistenceManager({adapter:this.fs,serializer:this._serializer,deserializer:this._deserializer,logger:this._logger,debug:this.debug,lenientLoad:lenientLoad??!1}),this._changeLog=new ChangeLog(this),this._queryCache=new QueryCache(queryCache||{}),this._eventBus=new EventBus,this._queryLog=slowQueryLog?new QueryLog(slowQueryLog):null,this._sessionStats=new SessionStats,this._plugins=new PluginEngine,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(error2){throw this._logger(`Error connecting to the database: ${error2}`,"error"),error2}}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(error2){throw this._logger(`Error disconnecting from the database: ${error2}`,"error"),error2}}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,buildIndex:this._registry.buildIndex,IndexEngine});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 AdapterError("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 ValidationError("ERR_SKALEX_VALIDATION_NAMESPACE_ID","namespace: id must contain at least one alphanumeric character",{id});return new Skalex({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!==logger?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!==_serialize?this._serializer:void 0,deserializer:this._deserializer!==_deserialize?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 PersistenceError("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 AdapterError("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 AdapterError("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=validateLLMFilter(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(processLLMFilter(filter,{regexMaxLength:this._regexMaxLength}),{limit})}schema(collectionName){return this._registry.schema(collectionName)}useMemory(sessionId){return new Memory(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 SkalexMCPServer(this,opts)}_getMeta(){let metaCol=this.collections._meta;if(!metaCol)return{};return metaCol.index.get(META_KEY)||{}}_saveMeta(data){if(!this.collections._meta)this._createCollectionStore("_meta");let col=this.collections._meta,existing=col.index.get(META_KEY);if(existing)Object.assign(existing,data);else{let doc={_id:META_KEY,...data};col.data.push(doc),col.index.set(META_KEY,doc)}this._persistence.markDirty(this.collections,"_meta")}_sweepTtl(){for(let name in this.collections){let col=this.collections[name],removed=sweep(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 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 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)}function getAdapter(name){return registry2.get(name)}function listAdapters(){return Array.from(registry2.keys())}class AgentDatabase2{}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})}registerAdapter2("skalex",createSkalexAgentDatabase);export{registerAdapter2 as registerAdapter,listAdapters,getAdapter,createAgentDatabase,AgentDatabase2 as AgentDatabase};
|
|
28
|
+
`))!==-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(error(null,PARSE_ERROR,"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_INFO={name:"skalex",version:"4.0.0-alpha"},PROTOCOL_VERSION="2024-11-05";class SkalexMCPServer{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 HttpTransport({port:this._port,host:this._host,allowedOrigin:this._allowedOrigin,maxBodySize:this._maxBodySize});else this._t=new StdioTransport;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"?parse(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(ok(id,{protocolVersion:PROTOCOL_VERSION,capabilities:{tools:{}},serverInfo:SERVER_INFO}));break;case"tools/list":this._send(ok(id,{tools:this._visibleTools()}));break;case"tools/call":await this._handleToolCall(id,params);break;case"ping":this._send(ok(id,{}));break;default:this._send(error(id,METHOD_NOT_FOUND,`Method not found: ${method}`))}}catch(err){this._send(error(id,INTERNAL_ERROR,err.message||"Internal error"))}}async _handleToolCall(id,params){let name=params?.name,args=params?.arguments??{};if(!name){this._send(error(id,INVALID_PARAMS,"tools/call requires params.name"));return}let def=TOOL_DEFS.find((t)=>t.name===name);if(!def){this._send(error(id,METHOD_NOT_FOUND,`Unknown tool: ${name}`));return}let collection=args.collection||args.collection_name||null;if(!this._hasScope(collection,def.scope)){this._send(ok(id,toolError(`Access denied: "${name}" requires "${def.scope}" scope on collection "${collection}".`)));return}try{let result=await callTool(name,args,this._db);this._send(ok(id,toolResult(JSON.stringify(result,null,2))))}catch(err){this._send(ok(id,toolError(err.message||String(err))))}}_visibleTools(){return TOOL_DEFS.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_KEY="migrations",_serialize=(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}),_deserialize=(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 Skalex{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,!Skalex._errorsAttached)Skalex.SkalexError=SkalexError,Skalex.ValidationError=ValidationError,Skalex.UniqueConstraintError=UniqueConstraintError,Skalex.TransactionError=TransactionError,Skalex.PersistenceError=PersistenceError,Skalex.AdapterError=AdapterError,Skalex.QueryError=QueryError,Skalex._errorsAttached=!0;this._adapterConfig=adapter??null;let fs=adapter||new FsAdapter({dir:path,format});if(encrypt)fs=new EncryptedAdapter(fs,encrypt.key);if(this.fs=fs,this._registry=new CollectionRegistry(Collection),this.collections=this._registry.stores,this._collectionInstances=this._registry._instances,this._migrations=new MigrationEngine,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??_serialize,this._deserializer=deserializer??_deserialize,this._autoSave=autoSave??!1,this._txManager=new TransactionManager,this._ttlSweepInterval=ttlSweepInterval??0,this._ttlTimer=null,this._logger=logger$1??logger,this._embeddingAdapter=embeddingAdapter??(ai?createEmbeddingAdapter(ai):null),this._aiAdapter=llmAdapter??(ai?createLLMAdapter(ai):null),this._persistence=new PersistenceManager({adapter:this.fs,serializer:this._serializer,deserializer:this._deserializer,logger:this._logger,debug:this.debug,lenientLoad:lenientLoad??!1}),this._changeLog=new ChangeLog(this),this._queryCache=new QueryCache(queryCache||{}),this._eventBus=new EventBus,this._queryLog=slowQueryLog?new QueryLog(slowQueryLog):null,this._sessionStats=new SessionStats,this._plugins=new PluginEngine,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(error2){throw this._logger(`Error connecting to the database: ${error2}`,"error"),error2}}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(error2){throw this._logger(`Error disconnecting from the database: ${error2}`,"error"),error2}}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,buildIndex:this._registry.buildIndex,IndexEngine});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 AdapterError("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 ValidationError("ERR_SKALEX_VALIDATION_NAMESPACE_ID","namespace: id must contain at least one alphanumeric character",{id});return new Skalex({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!==logger?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!==_serialize?this._serializer:void 0,deserializer:this._deserializer!==_deserialize?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 PersistenceError("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 AdapterError("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 AdapterError("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=validateLLMFilter(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(processLLMFilter(filter,{regexMaxLength:this._regexMaxLength}),{limit})}schema(collectionName){return this._registry.schema(collectionName)}useMemory(sessionId){return new Memory(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 SkalexMCPServer(this,opts)}_getMeta(){let metaCol=this.collections._meta;if(!metaCol)return{};return metaCol.index.get(META_KEY)||{}}_saveMeta(data){if(!this.collections._meta)this._createCollectionStore("_meta");let col=this.collections._meta,existing=col.index.get(META_KEY);if(existing)Object.assign(existing,data);else{let doc={_id:META_KEY,...data};col.data.push(doc),col.index.set(META_KEY,doc)}this._persistence.markDirty(this.collections,"_meta")}_sweepTtl(){for(let name in this.collections){let col=this.collections[name],removed=sweep(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 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 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)}function getAdapter(name){return registry2.get(name)}function listAdapters(){return Array.from(registry2.keys())}class AgentDatabase2{}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})}registerAdapter2("skalex",createSkalexAgentDatabase);var createPlugin=(_ctx)=>({name:"storage",version:"2026.508.4",description:"Storage facade \u2014 owns AgentDatabase contract and adapter registry",tags:["backend","adapter"]}),src_default=createPlugin;export{registerAdapter2 as registerAdapter,listAdapters,getAdapter,src_default as default,createPlugin,createAgentDatabase,AgentDatabase2 as AgentDatabase};
|