@vpxa/aikit 0.1.184 → 0.1.185
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(){if(process.on(`unhandledRejection`,e=>{p.error(`Unhandled rejection`,l(e))}),process.on(`uncaughtException`,e=>{p.error(`Uncaught exception — exiting`,l(e)),process.exit(1)}),p.info(`Starting MCP AI Kit server`,{version:f}),_.transport===`http`){let[{default:e},{loadConfig:n,resolveIndexMode:r},{registerDashboardRoutes:i,resolveDashboardDir:a},{registerSettingsRoutes:o,resolveSettingsDir:s},{createSettingsRouter:c},{authMiddleware:d,getOrCreateToken:f}]=await Promise.all([import(`express`),import(`./config-DAnAxrUW.js`),import(`./dashboard-static-CnXafYTs.js`),import(`./settings-static-BkVLqWOr.js`),import(`./routes-CR3fI-HJ.js`),import(`./auth-BfqgawfR.js`).then(e=>e.t)]),m=n();p.info(`Config loaded`,{sourceCount:m.sources.length,storePath:m.store.path});let h=e();h.use(e.json());let v=Number(_.port);h.use((e,t,n)=>{if(t.setHeader(`Access-Control-Allow-Origin`,process.env.AIKIT_CORS_ORIGIN??`http://localhost:${v}`),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 y=f();console.error(`[aikit] Auth token: ~/.aikit/token`),h.use(d(y)),i(h,a(),p);let b=new Date().toISOString();h.use(`/settings/api`,c({log:p,mcpInfo:()=>({transport:`http`,port:v,pid:process.pid,startedAt:b})})),o(h,s(),p),h.get(`/health`,(e,t)=>{t.json({status:`ok`})});let x=!1,S=null,C=null,w=null,T=null,E=null,D=null,O=Promise.resolve(),k=async(e,n)=>{if(!x||!w||!T){n.status(503).json({jsonrpc:`2.0`,error:{code:-32603,message:`Server initializing — please retry in a few seconds`},id:null});return}let r=O,i;O=new Promise(e=>{i=e}),await r;try{let r=g(e);if(!E){if(r){n.status(404).json({jsonrpc:`2.0`,error:{code:-32001,message:`Session not found`},id:null});return}let e=new T({sessionIdGenerator:()=>t(),onsessioninitialized:async e=>{D=e,C?.onSessionStart(e,{transport:`http`})},onsessionclosed:async e=>{e&&C?.onSessionEnd(e),D=null}});e.onclose=()=>{E===e&&(E=null),D===e.sessionId&&(D=null)},E=e,await w.connect(e)}let i=E;await i.handleRequest(e,n,e.body),e.method!==`DELETE`&&(!r&&i.sessionId?(D=i.sessionId,C?.onSessionStart(i.sessionId,{transport:`http`}),C?.onSessionActivity(i.sessionId)):r&&C?.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()}};h.post(`/mcp`,k),h.get(`/mcp`,k),h.delete(`/mcp`,k);let A=h.listen(v,`127.0.0.1`,()=>{p.info(`MCP server listening`,{url:`http://127.0.0.1:${v}/mcp`,port:v}),setTimeout(async()=>{try{let[{createLazyServer:e,ALL_TOOL_NAMES:t},{StreamableHTTPServerTransport:n},{checkForUpdates:i,autoUpgradeScaffold:a}]=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(){if(process.on(`unhandledRejection`,e=>{p.error(`Unhandled rejection`,l(e))}),process.on(`uncaughtException`,e=>{p.error(`Uncaught exception — exiting`,l(e)),process.exit(1)}),p.info(`Starting MCP AI Kit server`,{version:f}),_.transport===`http`){let[{default:e},{loadConfig:n,resolveIndexMode:r},{registerDashboardRoutes:i,resolveDashboardDir:a},{registerSettingsRoutes:o,resolveSettingsDir:s},{createSettingsRouter:c},{authMiddleware:d,getOrCreateToken:f}]=await Promise.all([import(`express`),import(`./config-DAnAxrUW.js`),import(`./dashboard-static-CnXafYTs.js`),import(`./settings-static-BkVLqWOr.js`),import(`./routes-CR3fI-HJ.js`),import(`./auth-BfqgawfR.js`).then(e=>e.t)]),m=n();p.info(`Config loaded`,{sourceCount:m.sources.length,storePath:m.store.path});let h=e();h.use(e.json());let v=Number(_.port);h.use((e,t,n)=>{if(t.setHeader(`Access-Control-Allow-Origin`,process.env.AIKIT_CORS_ORIGIN??`http://localhost:${v}`),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 y=f();console.error(`[aikit] Auth token: ~/.aikit/token`),h.use(d(y)),i(h,a(),p);let b=new Date().toISOString();h.use(`/settings/api`,c({log:p,mcpInfo:()=>({transport:`http`,port:v,pid:process.pid,startedAt:b})})),o(h,s(),p),h.get(`/health`,(e,t)=>{t.json({status:`ok`})});let x=!1,S=null,C=null,w=null,T=null,E=null,D=null,O=Promise.resolve(),k=async(e,n)=>{if(!x||!w||!T){n.status(503).json({jsonrpc:`2.0`,error:{code:-32603,message:`Server initializing — please retry in a few seconds`},id:null});return}let r=O,i;O=new Promise(e=>{i=e}),await r;try{let r=g(e);if(!E){if(r){n.status(404).json({jsonrpc:`2.0`,error:{code:-32001,message:`Session not found`},id:null});return}let e=new T({sessionIdGenerator:()=>t(),onsessioninitialized:async e=>{D=e,C?.onSessionStart(e,{transport:`http`})},onsessionclosed:async e=>{e&&C?.onSessionEnd(e),D=null}});e.onclose=()=>{E===e&&(E=null),D===e.sessionId&&(D=null)},E=e,await w.connect(e)}let i=E;await i.handleRequest(e,n,e.body),e.method!==`DELETE`&&(!r&&i.sessionId?(D=i.sessionId,C?.onSessionStart(i.sessionId,{transport:`http`}),C?.onSessionActivity(i.sessionId)):r&&C?.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()}};h.post(`/mcp`,k),h.get(`/mcp`,k),h.delete(`/mcp`,k);let A=h.listen(v,`127.0.0.1`,()=>{p.info(`MCP server listening`,{url:`http://127.0.0.1:${v}/mcp`,port:v}),setTimeout(async()=>{try{let[{createLazyServer:e,ALL_TOOL_NAMES:t},{StreamableHTTPServerTransport:n},{checkForUpdates:i,autoUpgradeScaffold:a}]=await Promise.all([import(`./server-BCnhTdUy.js`),import(`@modelcontextprotocol/sdk/server/streamableHttp.js`),import(`./version-check-BgHzxxCW.js`)]);i(),a();let o=r(m),s=e(m,o);w=s.server,T=n,x=!0,p.info(`MCP server configured (lazy — AI Kit initializing in background)`,{toolCount:t.length,resourceCount:2}),s.startInit(),s.ready.then(()=>{if(!s.aikit)throw Error(`AI Kit components are not available after initialization`);C=new u(s.aikit.stateStore),C.startGC(),D&&(C.onSessionStart(D,{transport:`http`}),C.onSessionActivity(D))}).catch(e=>p.error(`Failed to start session manager`,l(e))),o===`auto`?s.ready.then(async()=>{try{let e=m.sources.map(e=>e.path).join(`, `);p.info(`Running initial index`,{sourcePaths:e}),await s.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))):o===`smart`?s.ready.then(async()=>{try{if(!s.aikit)throw Error(`AI Kit components are not available after initialization`);let{SmartIndexScheduler:e}=await import(`../../indexer/dist/index.js`),t=new e(s.aikit.indexer,m,s.aikit.store),n=s.aikit.store;S=t,t.start(),n.onBeforeClose&&n.onBeforeClose(()=>t.stop()),s.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))):(s.ready.catch(e=>p.error(`AI Kit initialization failed`,l(e))),p.info(`Initial full indexing skipped in HTTP mode`,{indexMode:o}))}catch(e){p.error(`Failed to load server modules`,l(e))}},100)}),j=async e=>{p.info(`Shutdown signal received`,{signal:e}),S?.stop(),C?.stop(),D&&C?.onSessionEnd(D),E&&(await E.close().catch(()=>void 0),E=null,D=null),A.close(),w&&await w.close(),process.exit(0)};process.on(`SIGINT`,()=>j(`SIGINT`)),process.on(`SIGTERM`,()=>j(`SIGTERM`))}else{let[{loadConfig:e,reconfigureForWorkspace:t,resolveIndexMode:n},{createLazyServer:r},{checkForUpdates:i,autoUpgradeScaffold:o},{RootsListChangedNotificationSchema:s}]=await Promise.all([import(`./config-DAnAxrUW.js`),import(`./server-BCnhTdUy.js`),import(`./version-check-BgHzxxCW.js`),import(`@modelcontextprotocol/sdk/types.js`)]),c=e();p.info(`Config loaded`,{sourceCount:c.sources.length,storePath:c.store.path}),i(),o();let u=n(c),d=r(c,u),{server:f,startInit:m,ready:h,runInitialIndex:g}=d,{StdioServerTransport:_}=await import(`@modelcontextprotocol/sdk/server/stdio.js`),v=new _;await f.connect(v),p.info(`MCP server started`,{transport:`stdio`});let y=e=>{if(e.length===0)return!1;let n=e[0].uri,r=n.startsWith(`file://`)?a(n):n;return p.info(`MCP roots resolved`,{rootUri:n,rootPath:r,rootCount:e.length}),t(c,r),c.allRoots=e.map(e=>{let t=e.uri;return t.startsWith(`file://`)?a(t):t}),!0},b=!1;try{b=y((await f.server.listRoots()).roots),b||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)}),b=!0}b||=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);f.server.setNotificationHandler(s,async()=>{clearTimeout(t);try{e(y((await f.server.listRoots()).roots))}catch(t){p.warn(`roots/list retry failed after notification`,l(t)),e(!1)}})}),m();let x=null,S=()=>{x&&clearTimeout(x),x=setTimeout(async()=>{p.info(`Auto-shutdown: no activity for 30 minutes — shutting down gracefully`);try{let e=d.aikit;e&&await Promise.all([e.embedder.shutdown?.().catch(()=>{})??Promise.resolve(),e.graphStore.close().catch(()=>{}),e.store.close().catch(()=>{})])}catch{}process.exit(0)},18e5),x.unref&&x.unref()};S(),process.stdin.on(`data`,()=>S()),h.catch(e=>{p.error(`Initialization failed — server will continue with limited tools`,l(e))}),u===`auto`?g().catch(e=>p.error(`Initial index failed`,l(e))):u===`smart`?h.then(async()=>{try{if(!d.aikit)throw Error(`AI Kit components are not available after initialization`);let{SmartIndexScheduler:e}=await import(`../../indexer/dist/index.js`),t=new e(d.aikit.indexer,c,d.aikit.store),n=d.aikit.store;t.start(),n.onBeforeClose&&n.onBeforeClose(()=>t.stop()),d.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:u})}}v().catch(e=>{p.error(`Fatal error`,l(e)),process.exit(1)});export{e as CuratedKnowledgeManager};
|