@vpxa/kb 0.1.7 → 0.1.8

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,6 +1,6 @@
1
1
  {
2
2
  "name": "@vpxa/kb",
3
- "version": "0.1.7",
3
+ "version": "0.1.8",
4
4
  "type": "module",
5
5
  "description": "Local-first AI developer toolkit — knowledge base, code analysis, context management, and developer tools for LLM agents",
6
6
  "license": "MIT",
@@ -1 +1 @@
1
- import{parseArgs as m}from"node:util";import{loadConfig as f}from"./config.js";import{createMcpServer as w,createServer as x,initializeKnowledgeBase as g}from"./server.js";const{values:u}=m({options:{transport:{type:"string",default:process.env.KB_TRANSPORT??"stdio"},port:{type:"string",default:process.env.KB_PORT??"3210"}}});async function I(){console.error("[KB] Starting MCP Knowledge Base server...");const t=f();if(console.error(`[KB] Config loaded: ${t.sources.length} source(s), store at ${t.store.path}`),u.transport==="http"){const{StreamableHTTPServerTransport:d}=await import("@modelcontextprotocol/sdk/server/streamableHttp.js"),a=(await import("express")).default,i=await g(t),c=w(i,t);console.error("[KB] MCP server configured with 46 tools and 2 resources");const n=a();n.use(a.json()),n.use((s,e,o)=>{if(e.setHeader("Access-Control-Allow-Origin",process.env.KB_CORS_ORIGIN??"*"),e.setHeader("Access-Control-Allow-Methods","GET, POST, DELETE, OPTIONS"),e.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization"),s.method==="OPTIONS"){e.status(204).end();return}o()}),n.get("/health",(s,e)=>{e.json({status:"ok"})}),n.post("/mcp",async(s,e)=>{try{const o=new d({sessionIdGenerator:void 0});await c.connect(o),await o.handleRequest(s,e,s.body),e.on("close",()=>{o.close()})}catch(o){console.error("[KB] MCP handler error:",o),e.headersSent||e.status(500).json({jsonrpc:"2.0",error:{code:-32603,message:"Internal server error"},id:null})}}),n.get("/mcp",(s,e)=>{e.writeHead(405).end(JSON.stringify({jsonrpc:"2.0",error:{code:-32e3,message:"Method not allowed."},id:null}))}),n.delete("/mcp",(s,e)=>{e.writeHead(405).end(JSON.stringify({jsonrpc:"2.0",error:{code:-32e3,message:"Method not allowed."},id:null}))});const l=Number(u.port),h=n.listen(l,()=>{console.error(`[KB] MCP server listening on http://0.0.0.0:${l}/mcp`),(async()=>{try{const e=t.sources.map(r=>r.path).join(", ");console.error(`[KB] Running initial index for sources: ${e}`);const o=await i.indexer.index(t,r=>{r.phase==="crawling"||r.phase==="done"||r.phase==="chunking"&&r.currentFile&&console.error(`[KB] [${r.filesProcessed+1}/${r.filesTotal}] ${r.currentFile}`)});console.error(`[KB] Indexed ${o.filesProcessed} files (${o.filesSkipped} skipped, ${o.chunksCreated} chunks) in ${(o.durationMs/1e3).toFixed(1)}s`);try{const r=await i.curated.reindexAll();console.error(`[KB] Curated re-index: ${r.indexed} entries restored to vector store`)}catch(r){console.error("[KB] Curated re-index failed:",r)}}catch(e){console.error("[KB] Initial index failed (will retry on kb_reindex):",e)}})()}),p=async s=>{console.error(`[KB] ${s} received \u2014 shutting down...`),h.close(),await c.close(),await i.store.close(),await i.embedder.shutdown(),process.exit(0)};process.on("SIGINT",()=>p("SIGINT")),process.on("SIGTERM",()=>p("SIGTERM"))}else{const{server:d,runInitialIndex:a}=await x(t),{StdioServerTransport:i}=await import("@modelcontextprotocol/sdk/server/stdio.js"),c=new i;await d.connect(c),console.error("[KB] MCP server started (stdio)"),process.env.KB_AUTO_INDEX!=="false"?a():console.error("[KB] Auto-index disabled (KB_AUTO_INDEX=false). Use kb_reindex to index manually.")}}I().catch(t=>{console.error("[KB] Fatal error:",t),process.exit(1)});
1
+ import{parseArgs as f}from"node:util";import{loadConfig as m}from"./config.js";import{createLazyServer as w,createMcpServer as x,initializeKnowledgeBase as g}from"./server.js";const{values:h}=f({options:{transport:{type:"string",default:process.env.KB_TRANSPORT??"stdio"},port:{type:"string",default:process.env.KB_PORT??"3210"}}});async function I(){console.error("[KB] Starting MCP Knowledge Base server...");const t=m();if(console.error(`[KB] Config loaded: ${t.sources.length} source(s), store at ${t.store.path}`),h.transport==="http"){const{StreamableHTTPServerTransport:l}=await import("@modelcontextprotocol/sdk/server/streamableHttp.js"),a=(await import("express")).default,i=await g(t),c=x(i,t);console.error("[KB] MCP server configured with 46 tools and 2 resources");const n=a();n.use(a.json()),n.use((s,e,o)=>{if(e.setHeader("Access-Control-Allow-Origin",process.env.KB_CORS_ORIGIN??"*"),e.setHeader("Access-Control-Allow-Methods","GET, POST, DELETE, OPTIONS"),e.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization"),s.method==="OPTIONS"){e.status(204).end();return}o()}),n.get("/health",(s,e)=>{e.json({status:"ok"})}),n.post("/mcp",async(s,e)=>{try{const o=new l({sessionIdGenerator:void 0});await c.connect(o),await o.handleRequest(s,e,s.body),e.on("close",()=>{o.close()})}catch(o){console.error("[KB] MCP handler error:",o),e.headersSent||e.status(500).json({jsonrpc:"2.0",error:{code:-32603,message:"Internal server error"},id:null})}}),n.get("/mcp",(s,e)=>{e.writeHead(405).end(JSON.stringify({jsonrpc:"2.0",error:{code:-32e3,message:"Method not allowed."},id:null}))}),n.delete("/mcp",(s,e)=>{e.writeHead(405).end(JSON.stringify({jsonrpc:"2.0",error:{code:-32e3,message:"Method not allowed."},id:null}))});const d=Number(h.port),p=n.listen(d,()=>{console.error(`[KB] MCP server listening on http://0.0.0.0:${d}/mcp`),(async()=>{try{const e=t.sources.map(r=>r.path).join(", ");console.error(`[KB] Running initial index for sources: ${e}`);const o=await i.indexer.index(t,r=>{r.phase==="crawling"||r.phase==="done"||r.phase==="chunking"&&r.currentFile&&console.error(`[KB] [${r.filesProcessed+1}/${r.filesTotal}] ${r.currentFile}`)});console.error(`[KB] Indexed ${o.filesProcessed} files (${o.filesSkipped} skipped, ${o.chunksCreated} chunks) in ${(o.durationMs/1e3).toFixed(1)}s`);try{const r=await i.curated.reindexAll();console.error(`[KB] Curated re-index: ${r.indexed} entries restored to vector store`)}catch(r){console.error("[KB] Curated re-index failed:",r)}}catch(e){console.error("[KB] Initial index failed (will retry on kb_reindex):",e)}})()}),u=async s=>{console.error(`[KB] ${s} received \u2014 shutting down...`),p.close(),await c.close(),await i.store.close(),await i.embedder.shutdown(),process.exit(0)};process.on("SIGINT",()=>u("SIGINT")),process.on("SIGTERM",()=>u("SIGTERM"))}else{const{server:l,ready:a,runInitialIndex:i}=w(t),{StdioServerTransport:c}=await import("@modelcontextprotocol/sdk/server/stdio.js"),n=new c;await l.connect(n),console.error("[KB] MCP server started (stdio)"),a.catch(p=>{console.error("[KB] Initialization failed:",p),process.exit(1)}),process.env.KB_AUTO_INDEX!=="false"?i():console.error("[KB] Auto-index disabled (KB_AUTO_INDEX=false). Use kb_reindex to index manually.")}}I().catch(t=>{console.error("[KB] Fatal error:",t),process.exit(1)});
@@ -15,9 +15,30 @@ export interface KnowledgeBaseComponents {
15
15
  export declare function initializeKnowledgeBase(config: KBConfig): Promise<KnowledgeBaseComponents>;
16
16
  export declare function createMcpServer(kb: KnowledgeBaseComponents, config: KBConfig): McpServer;
17
17
  export declare function registerMcpTools(server: McpServer, kb: KnowledgeBaseComponents, config: KBConfig): void;
18
+ /**
19
+ * Create a fully-initialized server (HTTP mode or when immediate readiness is needed).
20
+ */
18
21
  export declare function createServer(config: KBConfig): Promise<{
19
22
  server: McpServer;
20
23
  runInitialIndex: () => Promise<void>;
21
24
  shutdown: () => Promise<void>;
22
25
  }>;
26
+ /**
27
+ * Create an MCP server for stdio mode with lazy initialization.
28
+ *
29
+ * The MCP SDK forbids registering capabilities after connect(), but
30
+ * `setToolRequestHandlers()` (which registers the tools capability) is a
31
+ * one-time init guarded by `_toolHandlersInitialized`. So we register a
32
+ * temporary `status` tool before connect() to prime that flag, then after
33
+ * heavy init completes we remove it and register all 64 real tools.
34
+ * The SDK auto-sends `notifications/tools/list_changed` for each mutation.
35
+ *
36
+ * This lets the MCP handshake + initial tools/list complete in <1s
37
+ * (vs 5-7s when blocking on ONNX model load).
38
+ */
39
+ export declare function createLazyServer(config: KBConfig): {
40
+ server: McpServer;
41
+ ready: Promise<void>;
42
+ runInitialIndex: () => Promise<void>;
43
+ };
23
44
  //# sourceMappingURL=server.d.ts.map
@@ -1 +1 @@
1
- import{initializeTreeSitter as c}from"../../chunker/dist/index.js";import{OnnxEmbedder as m}from"../../embeddings/dist/index.js";import{IncrementalIndexer as g}from"../../indexer/dist/index.js";import{createStore as p,SqliteGraphStore as T}from"../../store/dist/index.js";import{McpServer as u}from"@modelcontextprotocol/sdk/server/mcp.js";import{CuratedKnowledgeManager as f}from"./curated-manager.js";import{installReplayInterceptor as h}from"./replay-interceptor.js";import{registerResources as S}from"./resources/resources.js";import{registerAnalyzeDependenciesTool as x,registerAnalyzeDiagramTool as w,registerAnalyzeEntryPointsTool as K,registerAnalyzePatternsTool as B,registerAnalyzeStructureTool as y,registerAnalyzeSymbolsTool as C,registerBlastRadiusTool as I}from"./tools/analyze.tools.js";import{registerDigestTool as P,registerEvidenceMapTool as z,registerForgeClassifyTool as M,registerForgeGroundTool as R,registerStratumCardTool as E}from"./tools/forge.tools.js";import{registerForgetTool as F}from"./tools/forget.tool.js";import{registerGraphTool as $}from"./tools/graph.tool.js";import{registerListTool as G}from"./tools/list.tool.js";import{registerLookupTool as A}from"./tools/lookup.tool.js";import{registerOnboardTool as D}from"./tools/onboard.tool.js";import{registerProduceKnowledgeTool as O}from"./tools/produce.tool.js";import{registerReadTool as W}from"./tools/read.tool.js";import{registerReindexTool as j}from"./tools/reindex.tool.js";import{registerRememberTool as L}from"./tools/remember.tool.js";import{registerReplayTool as H}from"./tools/replay.tool.js";import{registerSearchTool as q}from"./tools/search.tool.js";import{registerStatusTool as N}from"./tools/status.tool.js";import{registerBatchTool as Q,registerCheckpointTool as U,registerCheckTool as V,registerCodemodTool as _,registerCompactTool as J,registerDataTransformTool as X,registerDeadSymbolsTool as Y,registerDelegateTool as Z,registerDiffParseTool as b,registerEvalTool as k,registerFileSummaryTool as v,registerFindExamplesTool as ee,registerFindTool as oe,registerGitContextTool as re,registerHealthTool as te,registerLaneTool as ie,registerParseOutputTool as ne,registerProcessTool as se,registerQueueTool as ae,registerRenameTool as le,registerScopeMapTool as de,registerStashTool as ce,registerSymbolTool as me,registerTestRunTool as ge,registerTraceTool as pe,registerWatchTool as Te,registerWebFetchTool as ue,registerWorksetTool as fe}from"./tools/toolkit.tools.js";import{registerUpdateTool as he}from"./tools/update.tool.js";import{registerChangelogTool as Se,registerEncodeTool as xe,registerEnvTool as we,registerHttpTool as Ke,registerMeasureTool as Be,registerRegexTestTool as ye,registerSchemaValidateTool as Ce,registerSnippetTool as Ie,registerTimeTool as Pe,registerWebSearchTool as ze}from"./tools/utility.tools.js";async function Me(e){console.error("[KB] Initializing knowledge base components...");const o=new m({model:e.embedding.model,dimensions:e.embedding.dimensions});await o.initialize(),console.error(`[KB] Embedder loaded: ${o.modelId} (${o.dimensions}d)`);const t=await p({backend:e.store.backend,path:e.store.path});await t.initialize(),console.error("[KB] Store initialized");const a=new g(o,t),i=e.curated.path,d=new f(i,t,o),n=new T({path:e.store.path});await n.initialize(),console.error("[KB] Graph store initialized"),a.setGraphStore(n);const s=await c();return console.error(s?"[KB] Tree-sitter chunking enabled":"[KB] Tree-sitter not available \u2014 using regex-based code chunking"),{embedder:o,store:t,indexer:a,curated:d,graphStore:n}}function Re(e,o){const t=new u({name:"kb",version:"0.1.0"});return Ee(t,e,o),t}function Ee(e,o,t){h(e),q(e,o.embedder,o.store,o.graphStore),A(e,o.store),N(e,o.store,o.graphStore),j(e,o.indexer,t,o.curated,o.store),L(e,o.curated),he(e,o.curated),F(e,o.curated),W(e,o.curated),G(e,o.curated),y(e,o.store,o.embedder),x(e,o.store,o.embedder),C(e,o.store,o.embedder),B(e,o.store,o.embedder),K(e,o.store,o.embedder),w(e,o.store,o.embedder),I(e,o.store,o.embedder),O(e),D(e,o.store,o.embedder),$(e,o.graphStore),J(e,o.embedder),de(e,o.embedder,o.store),oe(e,o.embedder,o.store),ne(e),fe(e),V(e),Q(e,o.embedder,o.store),me(e,o.embedder,o.store),k(e),ge(e),ce(e),re(e),b(e),le(e),_(e),v(e),U(e),X(e),pe(e,o.embedder,o.store),ee(e,o.embedder,o.store),se(e),Te(e),Y(e,o.embedder,o.store),Z(e),te(e),ie(e),ae(e),ue(e),z(e),P(e,o.embedder),M(e),E(e,o.embedder),R(e,o.embedder,o.store),ze(e),Ke(e),ye(e),xe(e),Be(e),Se(e),Ce(e),Ie(e),we(e),Pe(e),S(e,o.store),H(e)}async function ro(e){const o=await Me(e),t=Re(o,e);console.error("[KB] MCP server configured with 64 tools and 2 resources");const a=async()=>{try{const s=e.sources.map(r=>r.path).join(", ");console.error(`[KB] Running initial index for sources: ${s}`);const l=await o.indexer.index(e,r=>{r.phase==="crawling"||r.phase==="done"||(r.phase==="chunking"&&r.currentFile&&console.error(`[KB] [${r.filesProcessed+1}/${r.filesTotal}] ${r.currentFile}`),r.phase==="cleanup"&&console.error(`[KB] cleanup: removing ${r.filesTotal-r.filesProcessed} stale entries`))});console.error(`[KB] Indexed ${l.filesProcessed} files (${l.filesSkipped} skipped, ${l.chunksCreated} chunks) in ${(l.durationMs/1e3).toFixed(1)}s`);try{await o.store.createFtsIndex()}catch(r){console.error("[KB] FTS index creation failed (non-fatal):",r)}try{const r=await o.curated.reindexAll();console.error(`[KB] Curated re-index: ${r.indexed} entries restored to vector store`)}catch(r){console.error("[KB] Curated re-index failed:",r)}}catch(s){console.error("[KB] Initial index failed (will retry on kb_reindex):",s)}},i=async()=>{console.error("[KB] Shutting down..."),await o.graphStore.close().catch(()=>{}),await o.store.close(),process.exit(0)};process.on("SIGINT",i),process.on("SIGTERM",i);const d=process.ppid,n=setInterval(()=>{try{process.kill(d,0)}catch{console.error("[KB] Parent process died \u2014 orphan detected, shutting down..."),clearInterval(n),i()}},5e3);return n.unref(),{server:t,runInitialIndex:a,shutdown:i}}export{Re as createMcpServer,ro as createServer,Me as initializeKnowledgeBase,Ee as registerMcpTools};
1
+ import{initializeTreeSitter as f}from"../../chunker/dist/index.js";import{OnnxEmbedder as x}from"../../embeddings/dist/index.js";import{IncrementalIndexer as w}from"../../indexer/dist/index.js";import{createStore as K,SqliteGraphStore as S}from"../../store/dist/index.js";import{McpServer as u}from"@modelcontextprotocol/sdk/server/mcp.js";import{CuratedKnowledgeManager as B}from"./curated-manager.js";import{installReplayInterceptor as y}from"./replay-interceptor.js";import{registerResources as C}from"./resources/resources.js";import{registerAnalyzeDependenciesTool as I,registerAnalyzeDiagramTool as P,registerAnalyzeEntryPointsTool as $,registerAnalyzePatternsTool as z,registerAnalyzeStructureTool as F,registerAnalyzeSymbolsTool as M,registerBlastRadiusTool as R}from"./tools/analyze.tools.js";import{registerDigestTool as E,registerEvidenceMapTool as A,registerForgeClassifyTool as G,registerForgeGroundTool as D,registerStratumCardTool as b}from"./tools/forge.tools.js";import{registerForgetTool as j}from"./tools/forget.tool.js";import{registerGraphTool as L}from"./tools/graph.tool.js";import{registerListTool as O}from"./tools/list.tool.js";import{registerLookupTool as W}from"./tools/lookup.tool.js";import{registerOnboardTool as H}from"./tools/onboard.tool.js";import{registerProduceKnowledgeTool as _}from"./tools/produce.tool.js";import{registerReadTool as q}from"./tools/read.tool.js";import{registerReindexTool as N}from"./tools/reindex.tool.js";import{registerRememberTool as Q}from"./tools/remember.tool.js";import{registerReplayTool as U}from"./tools/replay.tool.js";import{registerSearchTool as V}from"./tools/search.tool.js";import{registerStatusTool as J}from"./tools/status.tool.js";import{registerBatchTool as X,registerCheckpointTool as Y,registerCheckTool as Z,registerCodemodTool as k,registerCompactTool as v,registerDataTransformTool as ee,registerDeadSymbolsTool as oe,registerDelegateTool as re,registerDiffParseTool as te,registerEvalTool as ie,registerFileSummaryTool as ne,registerFindExamplesTool as se,registerFindTool as ae,registerGitContextTool as le,registerHealthTool as de,registerLaneTool as ce,registerParseOutputTool as me,registerProcessTool as pe,registerQueueTool as ge,registerRenameTool as ue,registerScopeMapTool as Te,registerStashTool as he,registerSymbolTool as fe,registerTestRunTool as xe,registerTraceTool as we,registerWatchTool as Ke,registerWebFetchTool as Se,registerWorksetTool as Be}from"./tools/toolkit.tools.js";import{registerUpdateTool as ye}from"./tools/update.tool.js";import{registerChangelogTool as Ce,registerEncodeTool as Ie,registerEnvTool as Pe,registerHttpTool as $e,registerMeasureTool as ze,registerRegexTestTool as Fe,registerSchemaValidateTool as Me,registerSnippetTool as Re,registerTimeTool as Ee,registerWebSearchTool as Ae}from"./tools/utility.tools.js";async function T(e){console.error("[KB] Initializing knowledge base components...");const o=new x({model:e.embedding.model,dimensions:e.embedding.dimensions});await o.initialize(),console.error(`[KB] Embedder loaded: ${o.modelId} (${o.dimensions}d)`);const i=await K({backend:e.store.backend,path:e.store.path});await i.initialize(),console.error("[KB] Store initialized");const d=new w(o,i),s=e.curated.path,c=new B(s,i,o),a=new S({path:e.store.path});await a.initialize(),console.error("[KB] Graph store initialized"),d.setGraphStore(a);const l=await f();return console.error(l?"[KB] Tree-sitter chunking enabled":"[KB] Tree-sitter not available \u2014 using regex-based code chunking"),{embedder:o,store:i,indexer:d,curated:c,graphStore:a}}function Ge(e,o){const i=new u({name:"kb",version:"0.1.0"});return h(i,e,o),i}function h(e,o,i){y(e),V(e,o.embedder,o.store,o.graphStore),W(e,o.store),J(e,o.store,o.graphStore),N(e,o.indexer,i,o.curated,o.store),Q(e,o.curated),ye(e,o.curated),j(e,o.curated),q(e,o.curated),O(e,o.curated),F(e,o.store,o.embedder),I(e,o.store,o.embedder),M(e,o.store,o.embedder),z(e,o.store,o.embedder),$(e,o.store,o.embedder),P(e,o.store,o.embedder),R(e,o.store,o.embedder),_(e),H(e,o.store,o.embedder),L(e,o.graphStore),v(e,o.embedder),Te(e,o.embedder,o.store),ae(e,o.embedder,o.store),me(e),Be(e),Z(e),X(e,o.embedder,o.store),fe(e,o.embedder,o.store),ie(e),xe(e),he(e),le(e),te(e),ue(e),k(e),ne(e),Y(e),ee(e),we(e,o.embedder,o.store),se(e,o.embedder,o.store),pe(e),Ke(e),oe(e,o.embedder,o.store),re(e),de(e),ce(e),ge(e),Se(e),A(e),E(e,o.embedder),G(e),b(e,o.embedder),D(e,o.embedder,o.store),Ae(e),$e(e),Fe(e),Ie(e),ze(e),Ce(e),Me(e),Re(e),Pe(e),Ee(e),C(e,o.store),U(e)}async function so(e){const o=await T(e),i=Ge(o,e);console.error("[KB] MCP server configured with 64 tools and 2 resources");const d=async()=>{try{const l=e.sources.map(r=>r.path).join(", ");console.error(`[KB] Running initial index for sources: ${l}`);const m=await o.indexer.index(e,r=>{r.phase==="crawling"||r.phase==="done"||(r.phase==="chunking"&&r.currentFile&&console.error(`[KB] [${r.filesProcessed+1}/${r.filesTotal}] ${r.currentFile}`),r.phase==="cleanup"&&console.error(`[KB] cleanup: removing ${r.filesTotal-r.filesProcessed} stale entries`))});console.error(`[KB] Indexed ${m.filesProcessed} files (${m.filesSkipped} skipped, ${m.chunksCreated} chunks) in ${(m.durationMs/1e3).toFixed(1)}s`);try{await o.store.createFtsIndex()}catch(r){console.error("[KB] FTS index creation failed (non-fatal):",r)}try{const r=await o.curated.reindexAll();console.error(`[KB] Curated re-index: ${r.indexed} entries restored to vector store`)}catch(r){console.error("[KB] Curated re-index failed:",r)}}catch(l){console.error("[KB] Initial index failed (will retry on kb_reindex):",l)}},s=async()=>{console.error("[KB] Shutting down..."),await o.graphStore.close().catch(()=>{}),await o.store.close(),process.exit(0)};process.on("SIGINT",s),process.on("SIGTERM",s);const c=process.ppid,a=setInterval(()=>{try{process.kill(c,0)}catch{console.error("[KB] Parent process died \u2014 orphan detected, shutting down..."),clearInterval(a),s()}},5e3);return a.unref(),{server:i,runInitialIndex:d,shutdown:s}}function ao(e){const o=new u({name:"kb",version:"0.1.0"}),i=o.registerTool("status",{description:"Knowledge base status (initializing...)",inputSchema:{}},async()=>({content:[{type:"text",text:"KB is still initializing, please retry in a few seconds."}]})),d=o.resource("kb-status","kb://status",{description:"Knowledge base status (initializing...)",mimeType:"text/plain"},async()=>({contents:[{uri:"kb://status",text:"KB is initializing...",mimeType:"text/plain"}]}));let s;const c=new Promise(n=>{s=n}),a=(async()=>{const n=await T(e);i.remove(),d.remove(),h(o,n,e),console.error("[KB] MCP server configured with 64 tools and 2 resources"),s?.(n)})(),l=async()=>{const n=await c;try{const g=e.sources.map(t=>t.path).join(", ");console.error(`[KB] Running initial index for sources: ${g}`);const p=await n.indexer.index(e,t=>{t.phase==="crawling"||t.phase==="done"||(t.phase==="chunking"&&t.currentFile&&console.error(`[KB] [${t.filesProcessed+1}/${t.filesTotal}] ${t.currentFile}`),t.phase==="cleanup"&&console.error(`[KB] cleanup: removing ${t.filesTotal-t.filesProcessed} stale entries`))});console.error(`[KB] Indexed ${p.filesProcessed} files (${p.filesSkipped} skipped, ${p.chunksCreated} chunks) in ${(p.durationMs/1e3).toFixed(1)}s`);try{await n.store.createFtsIndex()}catch(t){console.error("[KB] FTS index creation failed (non-fatal):",t)}try{const t=await n.curated.reindexAll();console.error(`[KB] Curated re-index: ${t.indexed} entries restored to vector store`)}catch(t){console.error("[KB] Curated re-index failed:",t)}}catch(g){console.error("[KB] Initial index failed (will retry on kb_reindex):",g)}},m=process.ppid,r=setInterval(()=>{try{process.kill(m,0)}catch{console.error("[KB] Parent process died \u2014 orphan detected, shutting down..."),clearInterval(r),c.then(n=>{n.graphStore.close().catch(()=>{}),n.store.close()}).catch(()=>{}),process.exit(0)}},5e3);return r.unref(),{server:o,ready:a,runInitialIndex:l}}export{ao as createLazyServer,Ge as createMcpServer,so as createServer,T as initializeKnowledgeBase,h as registerMcpTools};