@vpxa/aikit 0.1.205 → 0.1.206
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/package.json
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{t as e}from"./curated-manager-BnP6VqvL.js";import{randomUUID as t}from"node:crypto";import{readFileSync as n}from"node:fs";import{dirname as r,resolve as i}from"node:path";import{fileURLToPath as a,pathToFileURL as o}from"node:url";import{parseArgs as s}from"node:util";import{createLogger as c,serializeError as l}from"../../core/dist/index.js";var u=class{stateStore;options;gcTimer=null;constructor(e,t={}){this.stateStore=e,this.options=t}onSessionStart(e,t){this.stateStore.sessionCreate(e,t)}onSessionActivity(e){this.stateStore.sessionTouch(e)}onSessionEnd(e){this.stateStore.sessionDelete(e)}startGC(){if(this.gcTimer)return;let e=(this.options.gcIntervalMinutes??5)*60*1e3;this.gcTimer=setInterval(()=>{this.runGC()},e),this.gcTimer.unref()}runGC(){let e=this.options.staleTimeoutMinutes??30;return this.stateStore.sessionDeleteStale(e)}stop(){this.gcTimer&&=(clearInterval(this.gcTimer),null)}getActiveSessions(){return this.stateStore.sessionList().length}};const d=r(a(import.meta.url)),f=(()=>{try{let e=i(d,`..`,`..`,`..`,`package.json`);return JSON.parse(n(e,`utf-8`)).version??`0.0.0`}catch{return`0.0.0`}})(),p=c(`server`);function m(){return process.env.AIKIT_TRANSPORT?process.env.AIKIT_TRANSPORT:process.stdin.isTTY?`http`:`stdio`}const h=(()=>{let e=process.argv[1];if(!e)return!1;try{return import.meta.url===o(e).href}catch{return!1}})();function g(e){let t=e.headers[`mcp-session-id`];return Array.isArray(t)?t[0]:t}const{values:_}=h?s({allowPositionals:!0,options:{transport:{type:`string`,default:m()},port:{type:`string`,default:process.env.AIKIT_PORT??`3210`}}}):{values:{transport:m(),port:process.env.AIKIT_PORT??`3210`}};async function v(){process.on(`unhandledRejection`,e=>{p.error(`Unhandled rejection`,l(e))}),process.on(`uncaughtException`,e=>{p.error(`Uncaught exception — exiting`,l(e)),process.exit(1)});let e=e=>{e.then(async()=>{try{let{shouldRunStartupPrune:e,prune:t,markPruneRun:n}=await import(`../../tools/dist/index.js`);if(!e())return;let r=await t({});n(),r.totalBytesFreed>0&&p.info(`Storage maintenance complete`,{forgeOrphans:r.forgeGroundOrphans.count,legacyLance:r.legacyLance.count,bytesFreed:r.totalBytesFreed})}catch(e){p.warn(`Startup maintenance failed (non-critical)`,l(e))}}).catch(()=>{})};if(p.info(`Starting MCP AI Kit server`,{version:f}),_.transport===`http`){let[{default:n},{loadConfig:r,resolveIndexMode:i},{registerDashboardRoutes:a,resolveDashboardDir:o},{registerSettingsRoutes:s,resolveSettingsDir:c},{createSettingsRouter:d},{authMiddleware:f,getOrCreateToken:m}]=await Promise.all([import(`express`),import(`./config-DAnAxrUW.js`),import(`./dashboard-static-FmfoS46e.js`),import(`./settings-static-BtvyIrza.js`),import(`./routes-CR3fI-HJ.js`),import(`./auth-BfqgawfR.js`).then(e=>e.t)]),h=r();p.info(`Config loaded`,{sourceCount:h.sources.length,storePath:h.store.path});let v=n();v.use(n.json());let y=Number(_.port);v.use((e,t,n)=>{if(t.setHeader(`Access-Control-Allow-Origin`,process.env.AIKIT_CORS_ORIGIN??`http://localhost:${y}`),t.setHeader(`Access-Control-Allow-Methods`,`GET, POST, PUT, PATCH, DELETE, OPTIONS`),t.setHeader(`Access-Control-Allow-Headers`,`Content-Type, Authorization, Mcp-Session-Id, Mcp-Protocol-Version, Last-Event-ID`),t.setHeader(`Access-Control-Expose-Headers`,`Mcp-Session-Id`),e.method===`OPTIONS`){t.status(204).end();return}n()});let b=m();console.error(`[aikit] Auth token: ~/.aikit/token`),v.use(f(b)),a(v,o(),p);let x=new Date().toISOString();v.use(`/settings/api`,d({log:p,mcpInfo:()=>({transport:`http`,port:y,pid:process.pid,startedAt:x})})),s(v,c(),p),v.get(`/health`,(e,t)=>{t.json({status:`ok`})});let S=!1,C=null,w=null,T=null,E=null,D=null,O=null,k=Promise.resolve(),A=async(e,n)=>{if(!S||!T||!E){n.status(503).json({jsonrpc:`2.0`,error:{code:-32603,message:`Server initializing — please retry in a few seconds`},id:null});return}let r=k,i;k=new Promise(e=>{i=e}),await r;try{let r=g(e);if(!D){if(r){n.status(404).json({jsonrpc:`2.0`,error:{code:-32001,message:`Session not found`},id:null});return}let e=new E({sessionIdGenerator:()=>t(),onsessioninitialized:async e=>{O=e,w?.onSessionStart(e,{transport:`http`})},onsessionclosed:async e=>{e&&w?.onSessionEnd(e),O=null}});e.onclose=()=>{D===e&&(D=null),O===e.sessionId&&(O=null)},D=e,await T.connect(e)}let i=D;await i.handleRequest(e,n,e.body),e.method!==`DELETE`&&(!r&&i.sessionId?(O=i.sessionId,w?.onSessionStart(i.sessionId,{transport:`http`}),w?.onSessionActivity(i.sessionId)):r&&w?.onSessionActivity(r))}catch(e){if(p.error(`MCP handler error`,l(e)),!n.headersSent){let t=e instanceof Error?e.message:String(e),r=t.includes(`Not Acceptable`);n.status(r?406:500).json({jsonrpc:`2.0`,error:{code:r?-32e3:-32603,message:r?t:`Internal server error`},id:null})}}finally{i()}};v.post(`/mcp`,A),v.get(`/mcp`,A),v.delete(`/mcp`,A);let j=v.listen(y,`127.0.0.1`,()=>{p.info(`MCP server listening`,{url:`http://127.0.0.1:${y}/mcp`,port:y}),setTimeout(async()=>{try{let[{createLazyServer:t,ALL_TOOL_NAMES:n},{StreamableHTTPServerTransport:r},{checkForUpdates:a,autoUpgradeScaffold:o}]=await Promise.all([import(`./server-
|
|
1
|
+
import{t as e}from"./curated-manager-BnP6VqvL.js";import{randomUUID as t}from"node:crypto";import{readFileSync as n}from"node:fs";import{dirname as r,resolve as i}from"node:path";import{fileURLToPath as a,pathToFileURL as o}from"node:url";import{parseArgs as s}from"node:util";import{createLogger as c,serializeError as l}from"../../core/dist/index.js";var u=class{stateStore;options;gcTimer=null;constructor(e,t={}){this.stateStore=e,this.options=t}onSessionStart(e,t){this.stateStore.sessionCreate(e,t)}onSessionActivity(e){this.stateStore.sessionTouch(e)}onSessionEnd(e){this.stateStore.sessionDelete(e)}startGC(){if(this.gcTimer)return;let e=(this.options.gcIntervalMinutes??5)*60*1e3;this.gcTimer=setInterval(()=>{this.runGC()},e),this.gcTimer.unref()}runGC(){let e=this.options.staleTimeoutMinutes??30;return this.stateStore.sessionDeleteStale(e)}stop(){this.gcTimer&&=(clearInterval(this.gcTimer),null)}getActiveSessions(){return this.stateStore.sessionList().length}};const d=r(a(import.meta.url)),f=(()=>{try{let e=i(d,`..`,`..`,`..`,`package.json`);return JSON.parse(n(e,`utf-8`)).version??`0.0.0`}catch{return`0.0.0`}})(),p=c(`server`);function m(){return process.env.AIKIT_TRANSPORT?process.env.AIKIT_TRANSPORT:process.stdin.isTTY?`http`:`stdio`}const h=(()=>{let e=process.argv[1];if(!e)return!1;try{return import.meta.url===o(e).href}catch{return!1}})();function g(e){let t=e.headers[`mcp-session-id`];return Array.isArray(t)?t[0]:t}const{values:_}=h?s({allowPositionals:!0,options:{transport:{type:`string`,default:m()},port:{type:`string`,default:process.env.AIKIT_PORT??`3210`}}}):{values:{transport:m(),port:process.env.AIKIT_PORT??`3210`}};async function v(){process.on(`unhandledRejection`,e=>{p.error(`Unhandled rejection`,l(e))}),process.on(`uncaughtException`,e=>{p.error(`Uncaught exception — exiting`,l(e)),process.exit(1)});let e=e=>{e.then(async()=>{try{let{shouldRunStartupPrune:e,prune:t,markPruneRun:n}=await import(`../../tools/dist/index.js`);if(!e())return;let r=await t({});n(),r.totalBytesFreed>0&&p.info(`Storage maintenance complete`,{forgeOrphans:r.forgeGroundOrphans.count,legacyLance:r.legacyLance.count,bytesFreed:r.totalBytesFreed})}catch(e){p.warn(`Startup maintenance failed (non-critical)`,l(e))}}).catch(()=>{})};if(p.info(`Starting MCP AI Kit server`,{version:f}),_.transport===`http`){let[{default:n},{loadConfig:r,resolveIndexMode:i},{registerDashboardRoutes:a,resolveDashboardDir:o},{registerSettingsRoutes:s,resolveSettingsDir:c},{createSettingsRouter:d},{authMiddleware:f,getOrCreateToken:m}]=await Promise.all([import(`express`),import(`./config-DAnAxrUW.js`),import(`./dashboard-static-FmfoS46e.js`),import(`./settings-static-BtvyIrza.js`),import(`./routes-CR3fI-HJ.js`),import(`./auth-BfqgawfR.js`).then(e=>e.t)]),h=r();p.info(`Config loaded`,{sourceCount:h.sources.length,storePath:h.store.path});let v=n();v.use(n.json());let y=Number(_.port);v.use((e,t,n)=>{if(t.setHeader(`Access-Control-Allow-Origin`,process.env.AIKIT_CORS_ORIGIN??`http://localhost:${y}`),t.setHeader(`Access-Control-Allow-Methods`,`GET, POST, PUT, PATCH, DELETE, OPTIONS`),t.setHeader(`Access-Control-Allow-Headers`,`Content-Type, Authorization, Mcp-Session-Id, Mcp-Protocol-Version, Last-Event-ID`),t.setHeader(`Access-Control-Expose-Headers`,`Mcp-Session-Id`),e.method===`OPTIONS`){t.status(204).end();return}n()});let b=m();console.error(`[aikit] Auth token: ~/.aikit/token`),v.use(f(b)),a(v,o(),p);let x=new Date().toISOString();v.use(`/settings/api`,d({log:p,mcpInfo:()=>({transport:`http`,port:y,pid:process.pid,startedAt:x})})),s(v,c(),p),v.get(`/health`,(e,t)=>{t.json({status:`ok`})});let S=!1,C=null,w=null,T=null,E=null,D=null,O=null,k=Promise.resolve(),A=async(e,n)=>{if(!S||!T||!E){n.status(503).json({jsonrpc:`2.0`,error:{code:-32603,message:`Server initializing — please retry in a few seconds`},id:null});return}let r=k,i;k=new Promise(e=>{i=e}),await r;try{let r=g(e);if(!D){if(r){n.status(404).json({jsonrpc:`2.0`,error:{code:-32001,message:`Session not found`},id:null});return}let e=new E({sessionIdGenerator:()=>t(),onsessioninitialized:async e=>{O=e,w?.onSessionStart(e,{transport:`http`})},onsessionclosed:async e=>{e&&w?.onSessionEnd(e),O=null}});e.onclose=()=>{D===e&&(D=null),O===e.sessionId&&(O=null)},D=e,await T.connect(e)}let i=D;await i.handleRequest(e,n,e.body),e.method!==`DELETE`&&(!r&&i.sessionId?(O=i.sessionId,w?.onSessionStart(i.sessionId,{transport:`http`}),w?.onSessionActivity(i.sessionId)):r&&w?.onSessionActivity(r))}catch(e){if(p.error(`MCP handler error`,l(e)),!n.headersSent){let t=e instanceof Error?e.message:String(e),r=t.includes(`Not Acceptable`);n.status(r?406:500).json({jsonrpc:`2.0`,error:{code:r?-32e3:-32603,message:r?t:`Internal server error`},id:null})}}finally{i()}};v.post(`/mcp`,A),v.get(`/mcp`,A),v.delete(`/mcp`,A);let j=v.listen(y,`127.0.0.1`,()=>{p.info(`MCP server listening`,{url:`http://127.0.0.1:${y}/mcp`,port:y}),setTimeout(async()=>{try{let[{createLazyServer:t,ALL_TOOL_NAMES:n},{StreamableHTTPServerTransport:r},{checkForUpdates:a,autoUpgradeScaffold:o}]=await Promise.all([import(`./server-DdnaotHn.js`),import(`@modelcontextprotocol/sdk/server/streamableHttp.js`),import(`./version-check-BgHzxxCW.js`)]);a(),o();let s=i(h),c=t(h,s);T=c.server,E=r,S=!0,p.info(`MCP server configured (lazy — AI Kit initializing in background)`,{toolCount:n.length,resourceCount:2}),c.startInit(),c.ready.then(()=>{if(!c.aikit)throw Error(`AI Kit components are not available after initialization`);w=new u(c.aikit.stateStore),w.startGC(),O&&(w.onSessionStart(O,{transport:`http`}),w.onSessionActivity(O))}).catch(e=>p.error(`Failed to start session manager`,l(e))),s===`auto`?c.ready.then(async()=>{try{let e=h.sources.map(e=>e.path).join(`, `);p.info(`Running initial index`,{sourcePaths:e}),await c.runInitialIndex(),p.info(`Initial index complete`)}catch(e){p.error(`Initial index failed; will retry on aikit_reindex`,l(e))}}).catch(e=>p.error(`AI Kit init or indexing failed`,l(e))):s===`smart`?c.ready.then(async()=>{try{if(!c.aikit)throw Error(`AI Kit components are not available after initialization`);let{SmartIndexScheduler:e}=await import(`../../indexer/dist/index.js`),t=new e(c.aikit.indexer,h,c.aikit.store),n=c.aikit.store;C=t,t.start(),n.onBeforeClose&&n.onBeforeClose(()=>t.stop()),c.setSmartScheduler(t),p.info(`Smart index scheduler started (HTTP mode)`)}catch(e){p.error(`Failed to start smart index scheduler`,l(e))}}).catch(e=>p.error(`AI Kit initialization failed`,l(e))):(c.ready.catch(e=>p.error(`AI Kit initialization failed`,l(e))),p.info(`Initial full indexing skipped in HTTP mode`,{indexMode:s})),e(c.ready)}catch(e){p.error(`Failed to load server modules`,l(e))}},100)}),M=async e=>{p.info(`Shutdown signal received`,{signal:e}),C?.stop(),w?.stop(),O&&w?.onSessionEnd(O),D&&(await D.close().catch(()=>void 0),D=null,O=null),j.close(),T&&await T.close(),process.exit(0)};process.on(`SIGINT`,()=>M(`SIGINT`)),process.on(`SIGTERM`,()=>M(`SIGTERM`))}else{let[{loadConfig:t,reconfigureForWorkspace:n,resolveIndexMode:r},{createLazyServer:i},{checkForUpdates:o,autoUpgradeScaffold:s},{RootsListChangedNotificationSchema:c}]=await Promise.all([import(`./config-DAnAxrUW.js`),import(`./server-DdnaotHn.js`),import(`./version-check-BgHzxxCW.js`),import(`@modelcontextprotocol/sdk/types.js`)]),u=t();p.info(`Config loaded`,{sourceCount:u.sources.length,storePath:u.store.path}),o(),s();let d=r(u),f=i(u,d),{server:m,startInit:h,ready:g,runInitialIndex:_}=f,{StdioServerTransport:v}=await import(`@modelcontextprotocol/sdk/server/stdio.js`),y=new v;await m.connect(y),p.info(`MCP server started`,{transport:`stdio`});let b=e=>{if(e.length===0)return!1;let t=e[0].uri,r=t.startsWith(`file://`)?a(t):t;return p.info(`MCP roots resolved`,{rootUri:t,rootPath:r,rootCount:e.length}),n(u,r),u.allRoots=e.map(e=>{let t=e.uri;return t.startsWith(`file://`)?a(t):t}),!0},x=!1;try{x=b((await m.server.listRoots()).roots),x||p.info(`No MCP roots yet; waiting for roots/list_changed notification`)}catch(e){p.warn(`MCP roots/list not supported by client; using cwd fallback`,{cwd:process.cwd(),...l(e)}),x=!0}x||=await new Promise(e=>{let t=setTimeout(()=>{p.warn(`Timed out waiting for MCP roots/list_changed; using cwd fallback`,{cwd:process.cwd()}),e(!1)},5e3);m.server.setNotificationHandler(c,async()=>{clearTimeout(t);try{e(b((await m.server.listRoots()).roots))}catch(t){p.warn(`roots/list retry failed after notification`,l(t)),e(!1)}})}),h();let S=null,C=()=>{S&&clearTimeout(S),S=setTimeout(async()=>{p.info(`Auto-shutdown: no activity for 30 minutes — shutting down gracefully`);try{let e=f.aikit;e&&await Promise.all([e.embedder.shutdown?.().catch(()=>{})??Promise.resolve(),e.graphStore.close().catch(()=>{}),e.store.close().catch(()=>{})])}catch{}process.exit(0)},18e5),S.unref&&S.unref()};C(),process.stdin.on(`data`,()=>C()),g.catch(e=>{p.error(`Initialization failed — server will continue with limited tools`,l(e))}),d===`auto`?_().catch(e=>p.error(`Initial index failed`,l(e))):d===`smart`?g.then(async()=>{try{if(!f.aikit)throw Error(`AI Kit components are not available after initialization`);let{SmartIndexScheduler:e}=await import(`../../indexer/dist/index.js`),t=new e(f.aikit.indexer,u,f.aikit.store),n=f.aikit.store;t.start(),n.onBeforeClose&&n.onBeforeClose(()=>t.stop()),f.setSmartScheduler(t),p.info(`Smart index scheduler started (stdio mode)`)}catch(e){p.error(`Failed to start smart index scheduler`,l(e))}}).catch(e=>p.error(`AI Kit init failed for smart scheduler`,l(e))):p.warn(`Initial full indexing skipped; use aikit_reindex to index manually`,{indexMode:d}),e(g)}}v().catch(e=>{p.error(`Fatal error`,l(e)),process.exit(1)});export{e as CuratedKnowledgeManager};
|
|
@@ -2987,6 +2987,6 @@ Data matches the schema.`}]};let r=[`## Validation: FAILED`,``,`**${n.errors.len
|
|
|
2987
2987
|
│ To enable: install/rebuild better-sqlite3 (native module). │
|
|
2988
2988
|
└──────────────────────────────────────────────────────────────────┘`);let t=M(i,`lance`);O(t)&&Q.info(`Old LanceDB data found at ${t} — ignored. Safe to delete after verifying sqlite-vec works.`)}let o;if(a)o=a;else{let e=M(i,`aikit-state.db`);O(i)||k(i,{recursive:!0}),o=await nr(e),ar(o,tr),Q.info(`State store adapter ready`,{type:o.type,dbPath:e})}let[s,c,l,u]=await Promise.all([(async()=>{if(n.embedding.childProcess!==!1){let e=new _r({model:n.embedding.model,dimensions:n.embedding.dimensions,interOpNumThreads:n.embedding.interOpNumThreads,intraOpNumThreads:n.embedding.intraOpNumThreads,idleTimeoutMs:n.embedding.idleTimeoutMs});return await e.initialize(),Q.info(`Embedder loaded (child process)`,{modelId:e.modelId,dimensions:e.dimensions}),e}let{OnnxEmbedder:e}=await import(`../../embeddings/dist/index.js`),t=new e({model:n.embedding.model,dimensions:n.embedding.dimensions,interOpNumThreads:n.embedding.interOpNumThreads,intraOpNumThreads:n.embedding.intraOpNumThreads});return await t.initialize(),Q.info(`Embedder loaded (in-process)`,{modelId:t.modelId,dimensions:t.dimensions}),t})(),(async()=>{let e=await ir({backend:r,path:i,adapter:a??void 0,embeddingDim:n.embedding.dimensions});return await e.initialize(),Q.info(`Store initialized`,{backend:r}),e})(),(async()=>{let e=a?new er({adapter:a}):new er({path:i});return await e.initialize(),Q.info(`Graph store initialized`,{shared:!!a}),e})(),(async()=>{let e=await Wn();if(e){let e=Hn.get();Q.info(`WASM tree-sitter enabled`,{grammars:e.grammarCount,dir:e.wasmDir})}else{let e=Hn.get();Q.warn(`WASM tree-sitter not available; analyzers will use regex fallback`,{reason:e.reason,os:e.os,arch:e.arch,healAttempted:e.healAttempted,healSuccess:e.healSuccess,healError:e.healError,pathsChecked:e.pathsChecked.map(e=>`${e.path} (${e.exists?`found`:`missing`})`)})}return e})()]),d=new yr(s,c),f=rr(o),p=new vr(n.store.path);p.load(),d.setHashCache(p);let m=n.curated.path,h=new e(m);await h.initialize();let g=new t(m,c,s,h);d.setGraphStore(l);let _=As(n.er),v=_?new Jn(n.curated.path):void 0;v&&Q.info(`Policy store initialized`,{ruleCount:v.getRules().length});let y=_?new qn:void 0,b=N(n.sources[0]?.path??process.cwd(),de.aiContext),x=O(b),S=n.onboardDir?O(n.onboardDir):!1,C=x||S,w,T=x?b:n.onboardDir;if(C&&T)try{w=ie(T).mtime.toISOString()}catch{}return Q.info(`Onboard state detected`,{onboardComplete:C,onboardTimestamp:w,aiKbExists:x,onboardDirExists:S}),{embedder:s,store:c,stateStore:f,closeStateStore:o===a?void 0:async()=>o.close(),indexer:d,curated:g,graphStore:l,fileCache:new Ce,bridge:_,policyStore:v,evolutionCollector:y,onboardComplete:C,onboardTimestamp:w}}function mm(e,t,n){if(e.serverInstructions)return e.serverInstructions;let r=new Set;for(let e of t){let t=n[e];if(t?.category)for(let e of t.category)r.add(e)}let i=[`This server provides ${t.size} tools across ${r.size} categories: ${[...r].sort().join(`, `)}.`,`TOOL ROUTING:`,`- Understand a file -> file_summary (structure) or compact (extract section)`,`- Find code/symbols -> search (hybrid) or symbol (definition + refs)`,`- Validate changes -> check (typecheck+lint) or test_run (tests)`,`- Read file for editing -> read_file (only for exact lines before edits)`,`FORBIDDEN: DO NOT USE native equivalents when AI Kit provides same:`,`- grep/find -> search or find tool`,`- cat/read_file (for understanding) -> file_summary or compact`,`- terminal tsc/lint -> check tool`,`- terminal test -> test_run tool`];return e.readOnly&&i.push(`Server is in read-only mode. Mutating operations are disabled.`),e.features?.length&&i.push(`Active feature groups: ${e.features.join(`, `)}.`),i.join(`
|
|
2989
2989
|
`)}const hm=P(`background-task`);var gm=class{queue=[];running=null;get isRunning(){return this.running!==null}get currentTask(){return this.running}get pendingCount(){return this.queue.length}schedule(e){return new Promise((t,n)=>{this.queue.push({...e,resolve:t,reject:n}),this.running||this.processQueue()})}async processQueue(){for(;this.queue.length>0;){let e=this.queue.shift();if(!e)break;this.running=e.name,hm.info(`Background task started`,{task:e.name,pending:this.queue.length});let t=Date.now();try{await e.fn();let n=Date.now()-t;hm.info(`Background task completed`,{task:e.name,durationMs:n}),e.resolve()}catch(n){let r=Date.now()-t;hm.error(`Background task failed`,{task:e.name,durationMs:r,err:n}),e.reject(n instanceof Error?n:Error(String(n)))}}this.running=null}};const _m=P(`idle-timer`);var vm=class{timer=null;cleanupFns=[];idleMs;disposed=!1;sessionActive=!1;_busy=!1;constructor(e){this.idleMs=e?.idleMs??3e5}setBusy(e){this._busy=e,e?this.cancel():this.touch()}onIdle(e){this.cleanupFns.push(e)}markSessionActive(){this.sessionActive=!0}touch(){this.disposed||this._busy||(this.cancel(),this.timer=setTimeout(()=>{this.runCleanup()},this.idleMs),this.timer.unref&&this.timer.unref())}cancel(){this.timer&&=(clearTimeout(this.timer),null)}dispose(){this.cancel(),this.cleanupFns.length=0,this.disposed=!0}async runCleanup(){if(!this.sessionActive){_m.info(`Idle timeout reached with no active session — skipping cleanup (waiting for first tool call)`);return}if(this._busy){_m.info(`Skipping idle cleanup — background work in progress`);return}_m.info(`Idle for ${this.idleMs/1e3}s — running cleanup`);let e=await Promise.allSettled(this.cleanupFns.map(e=>e()));for(let t of e)t.status===`rejected`&&_m.warn(`Idle cleanup callback failed`,{error:String(t.reason)})}};const ym=P(`memory-monitor`);var bm=class{timer=null;warningBytes;criticalBytes;intervalMs;pressureFns=[];memoryPressureFns=[];lastLevel=`normal`;constructor(e){this.warningBytes=e?.warningBytes??4294967296,this.criticalBytes=e?.criticalBytes??8589934592,this.intervalMs=e?.intervalMs??6e4}onPressure(e){this.pressureFns.push(e)}registerMemoryPressureCallback(e){this.memoryPressureFns.push(e)}start(){this.timer||(this.timer=setInterval(()=>this.check(),this.intervalMs),this.timer.unref&&this.timer.unref(),ym.info(`Memory monitor started`,{warningMB:Math.round(this.warningBytes/1024/1024),criticalMB:Math.round(this.criticalBytes/1024/1024),intervalSec:Math.round(this.intervalMs/1e3)}))}stop(){this.timer&&=(clearInterval(this.timer),null)}getRssBytes(){return process.memoryUsage.rss()}check(){let e=this.getRssBytes(),t=`normal`;if(e>=this.criticalBytes?t=`critical`:e>=this.warningBytes&&(t=`warning`),t!==this.lastLevel||t===`critical`){let n=Math.round(e/1024/1024);t===`critical`?ym.warn(`Memory CRITICAL: ${n}MB RSS — consider restarting the server`):t===`warning`?ym.warn(`Memory WARNING: ${n}MB RSS`):this.lastLevel!==`normal`&&ym.info(`Memory returned to normal: ${n}MB RSS`),this.lastLevel=t}if(t!==`normal`)for(let n of this.pressureFns)try{n(t,e)}catch{}if(t===`critical`)for(let e of this.memoryPressureFns)try{let t=e();t&&typeof t.catch==`function`&&t.catch(()=>{})}catch{}return t===`critical`&&typeof globalThis.gc==`function`&&globalThis.gc(),t}};const xm=P(`tool-timeout`),Sm=new Set([`onboard`,`reindex`,`produce_knowledge`,`analyze`,`codemod`,`audit`]);var Cm=class extends Error{toolName;timeoutMs;constructor(e,t){super(`Tool "${e}" timed out after ${t}ms`),this.toolName=e,this.timeoutMs=t,this.name=`ToolTimeoutError`}};function wm(e){return Sm.has(e)?6e5:12e4}function Tm(e,t,n){return new Promise((r,i)=>{let a=!1,o=setTimeout(()=>{if(!a){a=!0;let e=new Cm(n,t);xm.warn(e.message),i(e)}},t);o.unref&&o.unref(),e().then(e=>{a||(a=!0,clearTimeout(o),r(e))},e=>{a||(a=!0,clearTimeout(o),i(e))})})}const $=P(`server`),Em=new Set([`status`,`list_tools`,`describe_tool`,`config`,`env`]);function Dm(e,t=28){let n=e.replace(/\s+/g,` `).trim();return n.length<=t?n:`${n.slice(0,t-3)}...`}function Om(e){let t=[`query`,`path`,`task`,`name`,`start`,`symbol`,`file`,`pattern`],n=[];for(let r of t){let t=e[r];typeof t==`string`&&t.length>0&&t.length<200&&n.push(t)}return n.join(` `).slice(0,200)}async function km(e,t,n){let r=[];try{t.statePath&&Je(e.stateStore,{stateDir:t.statePath});let i=e.stateStore.stashList().map(e=>e.key);if(i.length>0){let e=n.toLowerCase().split(/\s+/).filter(e=>e.length>2);if(e.length===0)r.push(`stash: ${i.length} entries available`);else{let t=i.filter(t=>e.some(e=>t.toLowerCase().includes(e))).slice(0,3);t.length>0?r.push(`stash: ${t.map(e=>`"${Dm(e)}"`).join(`, `)}${i.length>t.length?` (${i.length} total)`:``}`):r.push(`stash: ${i.length} entries available`)}}}catch{}try{if(n){let t=await Promise.race([e.store.ftsSearch(n,{limit:3}),new Promise(e=>setTimeout(()=>e(null),50))]);if(Array.isArray(t)&&t.length>0){let e=t.filter(e=>e&&typeof e==`object`&&`record`in e&&(e.record.origin===`produced`||e.record.origin===`curated`));if(e.length>0){let t=e.slice(0,2).map(e=>{let t=e.record;return`"${Dm(t.headingPath||t.sourcePath||`knowledge`)}"`});r.push(`knowledge: ${t.join(`, `)}`)}}}}catch{}return r.length===0?null:`\n---\nContext available: ${r.join(` | `)}\nPull with: stash({action:'get', key:'...'}) or search({query:'...', origin:'produced'})\n---`}function Am(e,t,n){let r=3;for(let[i,a]of Object.entries(e)){let e=a.handler;a.handler=async(...a)=>{let o=await e(...a);if(!o||typeof o!=`object`||r<=0||o.isError||Em.has(i))return o;try{r--;let e=a[0],i=await km(t,n,Om(e&&typeof e==`object`?e:{}));i&&(o.content=Array.isArray(o.content)?o.content:[],o.content.push({type:`text`,text:i}))}catch{}return o}}}function jm(e){let t=e.toLowerCase();return[`protobuf`,`invalid model`,`invalid onnx`,`unexpected end`,`unexpected token`,`failed to load`,`failed to initialize embedding`,`checksum`,`corrupt`,`malformed`,`could not load`,`onnx`,`database disk image is malformed`,`file is not a database`,`lance`,`cannot find module`,`module not found`].some(e=>t.includes(e))}function Mm(e){let t=e.indexOf(`node_modules`);return t>0?e.substring(0,t-1):null}async function Nm(e,t){let n=t.toLowerCase(),r;try{({rm:r}=await import(`node:fs/promises`))}catch{return}if(n.includes(`transformers.node.mjs`)&&n.includes(`cannot find module`)){let e=t.match(/Cannot find module '([^']+transformers\.node\.mjs)'/);if(e){let t=e[1],n=t.replace(/\.mjs$/,`.cjs`);try{let{existsSync:e,writeFileSync:r}=await import(`node:fs`);e(n)&&!e(t)&&(r(t,[`// Auto-generated ESM shim — published package missing this file`,`import { createRequire } from 'node:module';`,`const require = createRequire(import.meta.url);`,`const mod = require('./transformers.node.cjs');`,`export default mod;`,``].join(`
|
|
2990
|
-
`),`utf8`),$.info(`Auto-heal: created ESM shim for @huggingface/transformers (.mjs wrapper → .cjs)`,{path:t}))}catch(e){$.warn(`Auto-heal: failed to create ESM shim`,{error:e instanceof Error?e.message:String(e),path:t})}}}if(n.includes(`embedding`)||n.includes(`onnx`)||n.includes(`protobuf`)||n.includes(`model`)){let t=e.embedding?.model??pe.model,n=M(Tn(),`.cache`,`huggingface`,`transformers-js`,t);try{await r(n,{recursive:!0,force:!0}),$.info(`Auto-heal: cleared embedding model cache`,{path:n})}catch{}}if(n.includes(`lance`)||n.includes(`database`)||n.includes(`store`)){let t=M(e.store.path,`lance`);try{await r(t,{recursive:!0,force:!0}),$.info(`Auto-heal: cleared LanceDB store`,{path:t})}catch{}}if(n.includes(`sqlite`)||n.includes(`database disk image`)||n.includes(`graph`)){let t=M(e.store.path,`graph.db`);try{await r(t,{force:!0}),$.info(`Auto-heal: cleared graph database`,{path:t})}catch{}let n=M(e.store.path,`aikit.db`);try{await r(n,{force:!0}),await r(`${n}-wal`,{force:!0}).catch(()=>{}),await r(`${n}-shm`,{force:!0}).catch(()=>{}),$.info(`Auto-heal: cleared corrupted aikit database`,{path:n})}catch{}}if(n.includes(`cannot find module`)&&!n.includes(`huggingface`)&&!n.includes(`.cache`)){let{fileURLToPath:e}=await import(`node:url`),t=e(import.meta.url);if(t.includes(`_npx`)||t.includes(`npm-cache`)){let e=Mm(t);if(e)try{let{execSync:t}=await import(`node:child_process`);t(`npm install --prefer-offline --no-audit --no-fund`,{cwd:e,stdio:`ignore`,timeout:6e4})
|
|
2990
|
+
`),`utf8`),$.info(`Auto-heal: created ESM shim for @huggingface/transformers (.mjs wrapper → .cjs)`,{path:t}))}catch(e){$.warn(`Auto-heal: failed to create ESM shim`,{error:e instanceof Error?e.message:String(e),path:t})}}}if(n.includes(`embedding`)||n.includes(`onnx`)||n.includes(`protobuf`)||n.includes(`model`)){let t=e.embedding?.model??pe.model,n=M(Tn(),`.cache`,`huggingface`,`transformers-js`,t);try{await r(n,{recursive:!0,force:!0}),$.info(`Auto-heal: cleared embedding model cache`,{path:n})}catch{}}if(n.includes(`lance`)||n.includes(`database`)||n.includes(`store`)){let t=M(e.store.path,`lance`);try{await r(t,{recursive:!0,force:!0}),$.info(`Auto-heal: cleared LanceDB store`,{path:t})}catch{}}if(n.includes(`sqlite`)||n.includes(`database disk image`)||n.includes(`graph`)){let t=M(e.store.path,`graph.db`);try{await r(t,{force:!0}),$.info(`Auto-heal: cleared graph database`,{path:t})}catch{}let n=M(e.store.path,`aikit.db`);try{await r(n,{force:!0}),await r(`${n}-wal`,{force:!0}).catch(()=>{}),await r(`${n}-shm`,{force:!0}).catch(()=>{}),$.info(`Auto-heal: cleared corrupted aikit database`,{path:n})}catch{}}if(n.includes(`cannot find module`)&&!n.includes(`huggingface`)&&!n.includes(`.cache`)){let{fileURLToPath:e}=await import(`node:url`),t=e(import.meta.url);if(t.includes(`_npx`)||t.includes(`npm-cache`)){let e=Mm(t);if(e)try{let{execSync:t}=await import(`node:child_process`);try{t(`npm install --prefer-offline --no-audit --no-fund`,{cwd:e,stdio:`ignore`,timeout:6e4})}catch{t(`npm install --no-audit --no-fund`,{cwd:e,stdio:`ignore`,timeout:6e4})}$.info(`Auto-heal: re-ran npm install to restore missing module`,{path:e})}catch{$.warn(`Auto-heal: npm install failed during module restoration`,{hint:`Run: npm cache clean --force && npx -y @vpxa/aikit serve`})}}}}function Pm(e,t){let n=po(e,za,H,Fa(e)),r=mm(e,n,H),i=new En({name:e.serverName??`aikit`,version:S()},{capabilities:{logging:{},completions:{},prompts:{}},instructions:r}),a=`initializing`,o=``,s=!1,c=null,l=null,u=null;function d(e){if(!e||typeof e!=`object`)return[];let t=e,n=[];for(let e of[`path`,`file`,`source_path`,`sourcePath`,`filePath`]){let r=t[e];typeof r==`string`&&r&&n.push(r)}for(let e of[`changed_files`,`paths`,`files`]){let r=t[e];if(Array.isArray(r))for(let e of r){if(typeof e==`string`){n.push(e);continue}e&&typeof e==`object`&&typeof e.path==`string`&&n.push(e.path)}}if(Array.isArray(t.sources))for(let e of t.sources)e&&typeof e==`object`&&typeof e.path==`string`&&n.push(e.path);return n}let f=()=>a===`failed`?[`❌ AI Kit initialization failed — this tool is unavailable.`,``,o?`Error: ${o}`:``,``,`**${Ra.size} tools are still available** and fully functional:`,`check, eval, test_run, git_context, health, measure, web_fetch, web_search,`,`flow, regex_test, encode,`,`stash, checkpoint, lane, process, time, env, and more.`,``,`To fix embedding errors, try deleting the cached model:`,` rm -rf ~/.cache/huggingface/transformers-js/mixedbread-ai/`,`Then restart the server to re-download a fresh copy.`,``,`Try restarting the MCP server to retry initialization.`].filter(Boolean).join(`
|
|
2991
2991
|
`):[`AI Kit is still initializing (loading embeddings model & store).`,``,`**${Ra.size} tools are already available** while initialization completes — including:`,`check, eval, test_run, git_context, health, measure, web_fetch, web_search,`,`flow, regex_test, encode,`,`stash, checkpoint, lane, process, time, env, and more.`,``,`This tool requires the AI Kit index. Please retry in a few seconds,`,`or use one of the available tools above in the meantime.`].join(`
|
|
2992
|
-
`);Sr(i);let p=new ca;p.use(Va(),{order:1,name:`structured-content-guard`}),Za(i,p,e.toolPrefix??``);let m=i.sendToolListChanged.bind(i);i.sendToolListChanged=()=>{};let h=[];for(let e of za){if(!n.has(e))continue;let t=U(e),r=i.registerTool(e,{title:t.title,description:`${t.title} — initializing, available shortly`,inputSchema:{},annotations:t.annotations},async()=>({content:[{type:`text`,text:f()}]}));Ra.has(e)?r.remove():h.push(r)}um(i,e,n),i.sendToolListChanged=m;let g=i.registerResource(`aikit-status`,`aikit://status`,{description:`AI Kit status (initializing...)`,mimeType:`text/plain`},async()=>({contents:[{uri:`aikit://status`,text:`AI Kit is initializing...`,mimeType:`text/plain`}]})),_=i.registerPrompt(`_init`,{description:`Initializing AI Kit…`,argsSchema:{_dummy:jn(I.string(),()=>[])}},async()=>({messages:[]})),v,y,b=new Promise((e,t)=>{v=e,y=t}),x,C=new Promise(e=>{x=e}),w=()=>x?.(),T=(async()=>{await C;try{let{createRequire:e}=await import(`node:module`),{readFileSync:t,existsSync:n}=await import(`node:fs`),{fileURLToPath:r}=await import(`node:url`),{resolve:i,dirname:a}=await import(`node:path`),o=e(import.meta.url),s=a(r(import.meta.url)),c=i(s,`..`,`package.json`),l=i(s,`..`,`..`),u=i(s,`..`,`..`,`..`),d=JSON.parse(t(c,`utf8`)),f=Object.keys(d.dependencies??{}),p=[`@mixmark-io/domino`],m=[...f,...p.filter(e=>!f.includes(e))],h=m.filter(e=>!e.startsWith(`@aikit/`)),g=m.filter(e=>e.startsWith(`@aikit/`)),_=[];for(let e of h)try{o.resolve(e)}catch{_.push(e)}let v=[];if(g.length>0){for(let e of g)n(i(l,e.slice(7),`dist`))||v.push(e);v.length>0&&$.warn(`Workspace sibling packages missing dist — server may have degraded features`,{missing:v,hint:`Reinstall: npm cache clean --force && npx -y @vpxa/aikit serve`})}if([..._,...v],_.length>0){$.warn(`${_.length} dependencies not resolvable — attempting auto-repair`,{missing:_});let e=r(import.meta.url);if(e.includes(`_npx`)||e.includes(`npm-cache`))try{let{execSync:t}=await import(`node:child_process`),r=Mm(e),a=n(i(u,`package.json`))?u:r;if(a){$.info(`Auto-heal: running npm install to restore missing deps`,{path:a,missing:_}),t(`npm install --prefer-offline --no-audit --no-fund`,{cwd:a,stdio:`ignore`,timeout:6e4});let e=[];for(let t of h)try{o.resolve(t)}catch{e.push(t)}e.length===0?$.info(`Auto-heal: all missing dependencies restored successfully`):($.warn(`Auto-heal: some deps still missing after npm install`,{stillMissing:e,hint:`Run: npm cache clean --force && npx -y @vpxa/aikit serve`}),[...e,...v])}}catch(e){$.warn(`Auto-heal: npm install failed — server may operate in degraded mode`,{error:e instanceof Error?e.message:String(e),hint:`Run: npm cache clean --force && npx -y @vpxa/aikit serve`})}else $.warn(`Missing dependencies detected in non-npx environment`,{missing:_,hint:`Run: npm install (or pnpm install) to restore missing packages`})}}catch{}let n;try{n=await pm(e)}catch(t){let r=t instanceof Error?t.message:String(t);if(jm(r)){$.warn(`AI Kit initialization failed with recoverable error — attempting auto-heal retry`,{error:r}),await Nm(e,r);try{n=await pm(e),$.info(`AI Kit auto-heal successful — initialization recovered after retry`)}catch(e){a=`failed`,o=e instanceof Error?e.message:String(e),$.error(`AI Kit initialization failed after auto-heal attempt — server continuing with zero-dep tools only`,{error:o,originalError:r}),y?.(e instanceof Error?e:Error(o));return}}else{a=`failed`,o=r,$.error(`AI Kit initialization failed — server continuing with zero-dep tools only`,{error:o}),y?.(t instanceof Error?t:Error(o));return}}let r=i.sendToolListChanged.bind(i);i.sendToolListChanged=()=>{};let f=i.sendPromptListChanged.bind(i);i.sendPromptListChanged=()=>{};let p=i.sendResourceListChanged.bind(i);i.sendResourceListChanged=()=>{};for(let e of h)e.remove();g.remove(),_.remove();let m=i._registeredTools??{};for(let e of Ra)m[e]?.remove();let b=new fm(i),x=Mc(i);lm(i,n,e,br(i),b,x,t,t===`smart`?(()=>{let e=u;return e?.getState?e.getState():null}):null,t===`smart`?()=>{let e=u;return e?{prioritize:e.prioritize.bind(e)}:null}:null),Nr(i,{curated:n.curated,store:n.store,graphStore:n.graphStore,stateStore:n.stateStore},t),i.sendToolListChanged=r,i.sendPromptListChanged=f,i.sendResourceListChanged=p,Promise.resolve(i.sendToolListChanged()).catch(()=>{}),Promise.resolve(i.sendPromptListChanged()).catch(()=>{}),Promise.resolve(i.sendResourceListChanged()).catch(()=>{});let S=i._registeredTools??{};for(let[e,t]of Object.entries(S)){if(Ia.has(e))continue;let r=t.handler;t.handler=async(...i)=>{if(!n.indexer.isIndexing)return r(...i);let a=s?`re-indexing`:`running initial index`,o=new Promise(n=>setTimeout(()=>n({content:[{type:`text`,text:`⏳ AI Kit is ${a}. The tool "${e}" timed out waiting for index data (${La/1e3}s).\n\nThe existing index may be temporarily locked. Please retry shortly — indexing will complete automatically.`}],...t.config?.outputSchema?{structuredContent:qa(t.config.outputSchema)}:{}}),La));return Promise.race([r(...i),o])}}for(let[e,t]of Object.entries(S)){let n=t.handler,r=wm(e);t.handler=async(...i)=>{try{return await Tm(()=>n(...i),r,e)}catch(n){if(n instanceof Cm)return{content:[{type:`text`,text:`⏳ Tool "${e}" timed out after ${r/1e3}s. This may indicate a long-running operation. Please retry or break the task into smaller steps.`}],...t.config?.outputSchema?{structuredContent:qa(t.config.outputSchema)}:{}};throw n}}}let w=Object.keys(S).length;w<za.length&&$.warn(`ALL_TOOL_NAMES count mismatch`,{expectedToolCount:za.length,registeredToolCount:w}),$.info(`MCP server configured`,{toolCount:za.length,resourceCount:4});let T=new bm;T.onPressure((e,t)=>{e===`warning`&&Er(),e===`critical`&&($.warn(`Memory pressure critical — consider restarting`,{rssMB:Math.round(t/1024/1024)}),Er())}),T.registerMemoryPressureCallback(()=>n.embedder.shutdown?.()),T.start();let E=new vm;l=E,E.onIdle(async()=>{if(D.isRunning||n.indexer.isIndexing){$.info(`Idle cleanup deferred — background tasks still running`),E.touch();return}$.info(`Idle cleanup: releasing cached memory (connections stay open)`);try{n.store.releaseMemory?.(),n.graphStore.releaseMemory?.()}catch{}}),E.touch();let ee=!1;for(let e of Object.values(S)){let t=e.handler;e.handler=async(...e)=>{if(ee||(ee=!0,E.markSessionActive()),E.touch(),u){let t=d(e[0]);t.length>0&&u.prioritize(...t)}return t(...e)}}Am(S,n,{statePath:e.stateDir??``}),process.stdin.on(`end`,()=>($.info(`stdin closed — MCP client disconnected. Shutting down.`),process.exit(0))),process.stdin.on(`error`,()=>($.info(`stdin error — MCP client disconnected. Shutting down.`),process.exit(0))),c=n,v?.(n)})(),E=async()=>{let t;try{t=await b}catch{$.warn(`Skipping initial index — AI Kit initialization failed`);return}l?.setBusy(!0);try{let n=e.sources.map(e=>e.path).join(`, `);$.info(`Running initial index`,{sourcePaths:n});let r=await t.indexer.index(e,e=>{e.phase===`crawling`||e.phase===`done`||(e.phase===`chunking`&&e.currentFile&&$.debug(`Indexing file`,{current:e.filesProcessed+1,total:e.filesTotal,file:e.currentFile}),e.phase===`cleanup`&&$.debug(`Index cleanup`,{staleEntries:e.filesTotal-e.filesProcessed}))});s=!0,$.info(`Initial index complete`,{filesProcessed:r.filesProcessed,filesSkipped:r.filesSkipped,chunksCreated:r.chunksCreated,durationMs:r.durationMs});try{await t.store.createFtsIndex()}catch(e){$.warn(`FTS index creation failed`,F(e))}try{let e=await t.curated.reindexAll();$.info(`Curated re-index complete`,{indexed:e.indexed})}catch(e){$.error(`Curated re-index failed`,F(e))}}catch(e){$.error(`Initial index failed; will retry on aikit_reindex`,F(e))}finally{l?.setBusy(!1)}},D=new gm,ee=()=>D.schedule({name:`initial-index`,fn:E}),O=process.ppid,k=setInterval(()=>{try{process.kill(O,0)}catch{$.info(`Parent process died; shutting down`,{parentPid:O}),clearInterval(k),u?.stop&&u.stop(),import(`../../tools/dist/index.js`).then(({processStopAll:e})=>e()).catch(()=>{}),b.then(async e=>{await Promise.all([e.embedder.shutdown?.().catch(()=>{})??Promise.resolve(),e.graphStore.close().catch(()=>{}),e.closeStateStore?.().catch(()=>{})??Promise.resolve(),e.store.close().catch(()=>{})])}).catch(()=>{}).finally(()=>process.exit(0))}},5e3);return k.unref(),{server:i,startInit:w,ready:T,runInitialIndex:ee,get aikit(){return c},scheduler:D,setSmartScheduler(e){u=e}}}const Fm=P(`server`);function Im(e,t){let n=po(t,[...za,...Na],H,Fa(t)),r=mm(t,n,H),i=new En({name:t.serverName??`aikit`,version:S()},{capabilities:{logging:{},completions:{},prompts:{}},instructions:r});return Sr(i),lm(i,e,t,br(i),new fm(i),Mc(i),void 0,null,null,n),Nr(i,{curated:e.curated,store:e.store,graphStore:e.graphStore,stateStore:e.stateStore},t.indexMode),i}async function Lm(e){let t=await pm(e),n=Im(t,e);Fm.info(`MCP server configured`,{toolCount:za.length,resourceCount:2});let r=async()=>{try{let n=e.sources.map(e=>e.path).join(`, `);Fm.info(`Running initial index`,{sourcePaths:n});let r=await t.indexer.index(e,e=>{e.phase===`crawling`||e.phase===`done`||(e.phase===`chunking`&&e.currentFile&&Fm.debug(`Indexing file`,{current:e.filesProcessed+1,total:e.filesTotal,file:e.currentFile}),e.phase===`cleanup`&&Fm.debug(`Index cleanup`,{staleEntries:e.filesTotal-e.filesProcessed}))});Fm.info(`Initial index complete`,{filesProcessed:r.filesProcessed,filesSkipped:r.filesSkipped,chunksCreated:r.chunksCreated,durationMs:r.durationMs});try{await t.store.createFtsIndex()}catch(e){Fm.warn(`FTS index creation failed`,F(e))}try{let e=await t.curated.reindexAll();Fm.info(`Curated re-index complete`,{indexed:e.indexed})}catch(e){Fm.error(`Curated re-index failed`,F(e))}}catch(e){Fm.error(`Initial index failed; will retry on aikit_reindex`,F(e))}},i=async()=>{Fm.info(`Shutting down`),await Promise.all([t.embedder.shutdown?.().catch(()=>{})??Promise.resolve(),t.graphStore.close().catch(()=>{}),t.closeStateStore?.().catch(()=>{})??Promise.resolve(),t.store.close().catch(()=>{})]),process.exit(0)};process.on(`SIGINT`,i),process.on(`SIGTERM`,i);let a=process.ppid,o=setInterval(()=>{try{process.kill(a,0)}catch{Fm.info(`Parent process died; shutting down`,{parentPid:a}),clearInterval(o),i()}},5e3);return o.unref(),{server:n,runInitialIndex:r,shutdown:i}}export{za as ALL_TOOL_NAMES,Pm as createLazyServer,Im as createMcpServer,Lm as createServer,pm as initializeAikit,lm as registerMcpTools};
|
|
2992
|
+
`);Sr(i);let p=new ca;p.use(Va(),{order:1,name:`structured-content-guard`}),Za(i,p,e.toolPrefix??``);let m=i.sendToolListChanged.bind(i);i.sendToolListChanged=()=>{};let h=[];for(let e of za){if(!n.has(e))continue;let t=U(e),r=i.registerTool(e,{title:t.title,description:`${t.title} — initializing, available shortly`,inputSchema:{},annotations:t.annotations},async()=>({content:[{type:`text`,text:f()}]}));Ra.has(e)?r.remove():h.push(r)}um(i,e,n),i.sendToolListChanged=m;let g=i.registerResource(`aikit-status`,`aikit://status`,{description:`AI Kit status (initializing...)`,mimeType:`text/plain`},async()=>({contents:[{uri:`aikit://status`,text:`AI Kit is initializing...`,mimeType:`text/plain`}]})),_=i.registerPrompt(`_init`,{description:`Initializing AI Kit…`,argsSchema:{_dummy:jn(I.string(),()=>[])}},async()=>({messages:[]})),v,y,b=new Promise((e,t)=>{v=e,y=t}),x,C=new Promise(e=>{x=e}),w=()=>x?.(),T=(async()=>{await C;try{let{createRequire:e}=await import(`node:module`),{readFileSync:t,existsSync:n}=await import(`node:fs`),{fileURLToPath:r}=await import(`node:url`),{resolve:i,dirname:a}=await import(`node:path`),o=e(import.meta.url),s=a(r(import.meta.url)),c=i(s,`..`,`package.json`),l=i(s,`..`,`..`),u=i(s,`..`,`..`,`..`),d=JSON.parse(t(c,`utf8`)),f=Object.keys(d.dependencies??{}),p=[`@mixmark-io/domino`],m=[...f,...p.filter(e=>!f.includes(e))],h=m.filter(e=>!e.startsWith(`@aikit/`)),g=m.filter(e=>e.startsWith(`@aikit/`)),_=[];for(let e of h)try{o.resolve(e)}catch{_.push(e)}let v=[];if(g.length>0){for(let e of g)n(i(l,e.slice(7),`dist`))||v.push(e);v.length>0&&$.warn(`Workspace sibling packages missing dist — server may have degraded features`,{missing:v,hint:`Reinstall: npm cache clean --force && npx -y @vpxa/aikit serve`})}if(_.length>0){$.warn(`${_.length} dependencies not resolvable — attempting auto-repair`,{missing:_});let e=r(import.meta.url);if(e.includes(`_npx`)||e.includes(`npm-cache`))try{let{execSync:t}=await import(`node:child_process`),r=Mm(e),a=n(i(u,`package.json`))?u:r;if(a){$.info(`Auto-heal: running npm install to restore missing deps`,{path:a,missing:_}),t(`npm install --prefer-offline --no-audit --no-fund`,{cwd:a,stdio:`ignore`,timeout:6e4});let e=[];for(let t of h)try{o.resolve(t)}catch{e.push(t)}if(e.length===0)$.info(`Auto-heal: all missing dependencies restored successfully`);else{$.info(`Auto-heal: retrying online install for missing packages`,{packages:e});try{t(`npm install ${e.join(` `)} --no-audit --no-fund`,{cwd:a,stdio:`ignore`,timeout:6e4})}catch{}let n=[];for(let t of e)try{o.resolve(t)}catch{n.push(t)}n.length===0?$.info(`Auto-heal: all missing dependencies restored on retry`):$.warn(`Auto-heal: some deps still missing after online retry`,{stillMissing:n,hint:`Run: npm cache clean --force && npx -y @vpxa/aikit serve`})}}}catch(e){$.warn(`Auto-heal: npm install failed — server may operate in degraded mode`,{error:e instanceof Error?e.message:String(e),hint:`Run: npm cache clean --force && npx -y @vpxa/aikit serve`})}else $.warn(`Missing dependencies detected in non-npx environment`,{missing:_,hint:`Run: npm install (or pnpm install) to restore missing packages`})}}catch{}let n;try{n=await pm(e)}catch(t){let r=t instanceof Error?t.message:String(t);if(jm(r)){$.warn(`AI Kit initialization failed with recoverable error — attempting auto-heal retry`,{error:r}),await Nm(e,r);try{n=await pm(e),$.info(`AI Kit auto-heal successful — initialization recovered after retry`)}catch(e){a=`failed`,o=e instanceof Error?e.message:String(e),$.error(`AI Kit initialization failed after auto-heal attempt — server continuing with zero-dep tools only`,{error:o,originalError:r}),y?.(e instanceof Error?e:Error(o));return}}else{a=`failed`,o=r,$.error(`AI Kit initialization failed — server continuing with zero-dep tools only`,{error:o}),y?.(t instanceof Error?t:Error(o));return}}let r=i.sendToolListChanged.bind(i);i.sendToolListChanged=()=>{};let f=i.sendPromptListChanged.bind(i);i.sendPromptListChanged=()=>{};let p=i.sendResourceListChanged.bind(i);i.sendResourceListChanged=()=>{};for(let e of h)e.remove();g.remove(),_.remove();let m=i._registeredTools??{};for(let e of Ra)m[e]?.remove();let b=new fm(i),x=Mc(i);lm(i,n,e,br(i),b,x,t,t===`smart`?(()=>{let e=u;return e?.getState?e.getState():null}):null,t===`smart`?()=>{let e=u;return e?{prioritize:e.prioritize.bind(e)}:null}:null),Nr(i,{curated:n.curated,store:n.store,graphStore:n.graphStore,stateStore:n.stateStore},t),i.sendToolListChanged=r,i.sendPromptListChanged=f,i.sendResourceListChanged=p,Promise.resolve(i.sendToolListChanged()).catch(()=>{}),Promise.resolve(i.sendPromptListChanged()).catch(()=>{}),Promise.resolve(i.sendResourceListChanged()).catch(()=>{});let S=i._registeredTools??{};for(let[e,t]of Object.entries(S)){if(Ia.has(e))continue;let r=t.handler;t.handler=async(...i)=>{if(!n.indexer.isIndexing)return r(...i);let a=s?`re-indexing`:`running initial index`,o=new Promise(n=>setTimeout(()=>n({content:[{type:`text`,text:`⏳ AI Kit is ${a}. The tool "${e}" timed out waiting for index data (${La/1e3}s).\n\nThe existing index may be temporarily locked. Please retry shortly — indexing will complete automatically.`}],...t.config?.outputSchema?{structuredContent:qa(t.config.outputSchema)}:{}}),La));return Promise.race([r(...i),o])}}for(let[e,t]of Object.entries(S)){let n=t.handler,r=wm(e);t.handler=async(...i)=>{try{return await Tm(()=>n(...i),r,e)}catch(n){if(n instanceof Cm)return{content:[{type:`text`,text:`⏳ Tool "${e}" timed out after ${r/1e3}s. This may indicate a long-running operation. Please retry or break the task into smaller steps.`}],...t.config?.outputSchema?{structuredContent:qa(t.config.outputSchema)}:{}};throw n}}}let w=Object.keys(S).length;w<za.length&&$.warn(`ALL_TOOL_NAMES count mismatch`,{expectedToolCount:za.length,registeredToolCount:w}),$.info(`MCP server configured`,{toolCount:za.length,resourceCount:4});let T=new bm;T.onPressure((e,t)=>{e===`warning`&&Er(),e===`critical`&&($.warn(`Memory pressure critical — consider restarting`,{rssMB:Math.round(t/1024/1024)}),Er())}),T.registerMemoryPressureCallback(()=>n.embedder.shutdown?.()),T.start();let E=new vm;l=E,E.onIdle(async()=>{if(D.isRunning||n.indexer.isIndexing){$.info(`Idle cleanup deferred — background tasks still running`),E.touch();return}$.info(`Idle cleanup: releasing cached memory (connections stay open)`);try{n.store.releaseMemory?.(),n.graphStore.releaseMemory?.()}catch{}}),E.touch();let ee=!1;for(let e of Object.values(S)){let t=e.handler;e.handler=async(...e)=>{if(ee||(ee=!0,E.markSessionActive()),E.touch(),u){let t=d(e[0]);t.length>0&&u.prioritize(...t)}return t(...e)}}Am(S,n,{statePath:e.stateDir??``}),process.stdin.on(`end`,()=>($.info(`stdin closed — MCP client disconnected. Shutting down.`),process.exit(0))),process.stdin.on(`error`,()=>($.info(`stdin error — MCP client disconnected. Shutting down.`),process.exit(0))),c=n,v?.(n)})(),E=async()=>{let t;try{t=await b}catch{$.warn(`Skipping initial index — AI Kit initialization failed`);return}l?.setBusy(!0);try{let n=e.sources.map(e=>e.path).join(`, `);$.info(`Running initial index`,{sourcePaths:n});let r=await t.indexer.index(e,e=>{e.phase===`crawling`||e.phase===`done`||(e.phase===`chunking`&&e.currentFile&&$.debug(`Indexing file`,{current:e.filesProcessed+1,total:e.filesTotal,file:e.currentFile}),e.phase===`cleanup`&&$.debug(`Index cleanup`,{staleEntries:e.filesTotal-e.filesProcessed}))});s=!0,$.info(`Initial index complete`,{filesProcessed:r.filesProcessed,filesSkipped:r.filesSkipped,chunksCreated:r.chunksCreated,durationMs:r.durationMs});try{await t.store.createFtsIndex()}catch(e){$.warn(`FTS index creation failed`,F(e))}try{let e=await t.curated.reindexAll();$.info(`Curated re-index complete`,{indexed:e.indexed})}catch(e){$.error(`Curated re-index failed`,F(e))}}catch(e){$.error(`Initial index failed; will retry on aikit_reindex`,F(e))}finally{l?.setBusy(!1)}},D=new gm,ee=()=>D.schedule({name:`initial-index`,fn:E}),O=process.ppid,k=setInterval(()=>{try{process.kill(O,0)}catch{$.info(`Parent process died; shutting down`,{parentPid:O}),clearInterval(k),u?.stop&&u.stop(),import(`../../tools/dist/index.js`).then(({processStopAll:e})=>e()).catch(()=>{}),b.then(async e=>{await Promise.all([e.embedder.shutdown?.().catch(()=>{})??Promise.resolve(),e.graphStore.close().catch(()=>{}),e.closeStateStore?.().catch(()=>{})??Promise.resolve(),e.store.close().catch(()=>{})])}).catch(()=>{}).finally(()=>process.exit(0))}},5e3);return k.unref(),{server:i,startInit:w,ready:T,runInitialIndex:ee,get aikit(){return c},scheduler:D,setSmartScheduler(e){u=e}}}const Fm=P(`server`);function Im(e,t){let n=po(t,[...za,...Na],H,Fa(t)),r=mm(t,n,H),i=new En({name:t.serverName??`aikit`,version:S()},{capabilities:{logging:{},completions:{},prompts:{}},instructions:r});return Sr(i),lm(i,e,t,br(i),new fm(i),Mc(i),void 0,null,null,n),Nr(i,{curated:e.curated,store:e.store,graphStore:e.graphStore,stateStore:e.stateStore},t.indexMode),i}async function Lm(e){let t=await pm(e),n=Im(t,e);Fm.info(`MCP server configured`,{toolCount:za.length,resourceCount:2});let r=async()=>{try{let n=e.sources.map(e=>e.path).join(`, `);Fm.info(`Running initial index`,{sourcePaths:n});let r=await t.indexer.index(e,e=>{e.phase===`crawling`||e.phase===`done`||(e.phase===`chunking`&&e.currentFile&&Fm.debug(`Indexing file`,{current:e.filesProcessed+1,total:e.filesTotal,file:e.currentFile}),e.phase===`cleanup`&&Fm.debug(`Index cleanup`,{staleEntries:e.filesTotal-e.filesProcessed}))});Fm.info(`Initial index complete`,{filesProcessed:r.filesProcessed,filesSkipped:r.filesSkipped,chunksCreated:r.chunksCreated,durationMs:r.durationMs});try{await t.store.createFtsIndex()}catch(e){Fm.warn(`FTS index creation failed`,F(e))}try{let e=await t.curated.reindexAll();Fm.info(`Curated re-index complete`,{indexed:e.indexed})}catch(e){Fm.error(`Curated re-index failed`,F(e))}}catch(e){Fm.error(`Initial index failed; will retry on aikit_reindex`,F(e))}},i=async()=>{Fm.info(`Shutting down`),await Promise.all([t.embedder.shutdown?.().catch(()=>{})??Promise.resolve(),t.graphStore.close().catch(()=>{}),t.closeStateStore?.().catch(()=>{})??Promise.resolve(),t.store.close().catch(()=>{})]),process.exit(0)};process.on(`SIGINT`,i),process.on(`SIGTERM`,i);let a=process.ppid,o=setInterval(()=>{try{process.kill(a,0)}catch{Fm.info(`Parent process died; shutting down`,{parentPid:a}),clearInterval(o),i()}},5e3);return o.unref(),{server:n,runInitialIndex:r,shutdown:i}}export{za as ALL_TOOL_NAMES,Pm as createLazyServer,Im as createMcpServer,Lm as createServer,pm as initializeAikit,lm as registerMcpTools};
|