@vpxa/aikit 0.1.79 → 0.1.81

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/aikit",
3
- "version": "0.1.79",
3
+ "version": "0.1.81",
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",
@@ -54,6 +54,7 @@
54
54
  "@mcp-ui/server": "^6.x",
55
55
  "@modelcontextprotocol/ext-apps": "^1.x",
56
56
  "@modelcontextprotocol/sdk": "^1.x",
57
+ "better-sqlite3": "^12.x",
57
58
  "diff": "^9.x",
58
59
  "express": "^5.x",
59
60
  "gpt-tokenizer": "^3.x",
@@ -61,7 +62,6 @@
61
62
  "lru-cache": "^11.x",
62
63
  "marked": "^18.x",
63
64
  "minimatch": "^10.x",
64
- "sql.js": "^1.x",
65
65
  "tree-sitter-wasms": "~0.1.13",
66
66
  "turndown": "^7.x",
67
67
  "web-tree-sitter": "~0.24.7",
@@ -1,4 +1,4 @@
1
- import{dirname as e,extname as t,join as n}from"node:path";import{CHUNK_SIZES as r,createLogger as i}from"../../core/dist/index.js";import{existsSync as a,readFileSync as o}from"node:fs";import{fileURLToPath as s}from"node:url";const c=e(s(import.meta.url));function l(){let e=[n(c,`..`,`..`,`wasm`),n(c,`..`,`wasm`)];for(let t of e)if(a(n(t,`tree-sitter.wasm`)))return t;return e[0]}const u=l(),d={".ts":`tree-sitter-typescript.wasm`,".tsx":`tree-sitter-typescript.wasm`,".mts":`tree-sitter-typescript.wasm`,".cts":`tree-sitter-typescript.wasm`,".js":`tree-sitter-javascript.wasm`,".jsx":`tree-sitter-javascript.wasm`,".mjs":`tree-sitter-javascript.wasm`,".cjs":`tree-sitter-javascript.wasm`,".py":`tree-sitter-python.wasm`,".go":`tree-sitter-go.wasm`,".rs":`tree-sitter-rust.wasm`,".java":`tree-sitter-java.wasm`,".kt":`tree-sitter-kotlin.wasm`,".kts":`tree-sitter-kotlin.wasm`,".scala":`tree-sitter-scala.wasm`,".sc":`tree-sitter-scala.wasm`,".c":`tree-sitter-c.wasm`,".h":`tree-sitter-c.wasm`,".cpp":`tree-sitter-cpp.wasm`,".cc":`tree-sitter-cpp.wasm`,".cxx":`tree-sitter-cpp.wasm`,".hpp":`tree-sitter-cpp.wasm`,".hxx":`tree-sitter-cpp.wasm`,".cs":`tree-sitter-c_sharp.wasm`,".swift":`tree-sitter-swift.wasm`,".rb":`tree-sitter-ruby.wasm`,".php":`tree-sitter-php.wasm`},f=new Set(Object.keys(d));function p(e){let t=d[e];if(!t)return null;let r=n(u,t);return a(r)?r:null}function m(){let e=n(u,`tree-sitter.wasm`);return a(e)?e:null}const h=i(`wasm-runtime`);async function g(){let e=await import(`web-tree-sitter`),t=typeof e.default?.init==`function`?e.default:e.Parser;if(!t||typeof t.init!=`function`)throw Error(`Unsupported web-tree-sitter export shape: ${Object.keys(e).join(`, `)}`);return t}var _=class e{static instance=null;parser=null;languages=new Map;loadedGrammars=new Map;static async initialize(){if(e.instance)return e.instance;let t=new e;return await t.init()?(e.instance=t,t):null}static get(){return e.instance}static async ensure(){let t=e.get();if(t)return t;let n=await e.initialize();if(!n)throw Error(`Failed to initialize WASM tree-sitter runtime`);return n}static dispose(){e.instance&&=(e.instance.parser?.delete(),e.instance.parser=null,e.instance.languages.clear(),e.instance.loadedGrammars.clear(),null)}async init(){try{let e=m();if(!e)return h.warn(`Parser WASM file not found`),!1;let t=await g();return await t.init({locateFile:()=>e}),this.parser=new t,h.info(`WASM tree-sitter parser initialized`),!0}catch(e){return h.warn(`Failed to initialize WASM tree-sitter`,{error:String(e)}),!1}}async loadLanguage(e){let t=this.languages.get(e);if(t)return t;let n=p(e);if(!n)return null;let r=this.loadedGrammars.get(n);if(r)return this.languages.set(e,r),r;try{let t=await(await g()).Language.load(n);return this.loadedGrammars.set(n,t),this.languages.set(e,t),h.info(`Loaded grammar`,{ext:e}),t}catch(t){return h.warn(`Failed to load grammar`,{ext:e,error:String(t)}),null}}async parse(e,t){if(!this.parser)return null;let n=await this.loadLanguage(t);return n?(this.parser.setLanguage(n),this.parser.parse(e)):null}hasLanguage(e){return f.has(e)}isLanguageLoaded(e){return this.languages.has(e)}getParser(){return this.parser}getLanguage(e){return this.languages.get(e)??null}};async function ee(){return await _.initialize()!==null}const v=new Set([`function_declaration`,`method_definition`,`arrow_function`,`function_definition`,`function_declaration`,`method_declaration`,`function_item`,`method_declaration`,`constructor_declaration`]),y=new Set([`call_expression`,`new_expression`,`call`]);function b(e,n){let r=t(n).toLowerCase(),i=_.get();if(i?.isLanguageLoaded(r)){let t=i.getParser(),a=i.getLanguage(r);if(t&&a){t.setLanguage(a);let r=t.parse(e);if(r){let e=[];return x(r.rootNode,n,`<module>`,e),e}}}return null}function x(e,t,n,r){if(!e)return;let i=n;if(v.has(e.type)&&(i=te(e)??n),y.has(e.type)){let n=S(e);n&&r.push({callerFile:t,callerName:i,calleeName:n,line:(e.startPosition?.row??0)+1})}for(let n=0;n<(e.childCount??0);n++){let a=e.child(n);a&&x(a,t,i,r)}}function te(e){for(let t=0;t<(e.childCount??0);t++){let n=e.child(t);if(n&&(n.type===`identifier`||n.type===`property_identifier`||n.type===`name`))return n.text??null}return null}function S(e){let t=e.childForFieldName?.(`function`)??e.child(0);return t?t.type===`identifier`||t.type===`name`?t.text??null:t.type===`member_expression`||t.type===`attribute`?(t.childForFieldName?.(`property`)??t.childForFieldName?.(`attribute`))?.text??null:e.type===`new_expression`?e.child(1)?.text??null:null:null}var C=class{maxChunkSize;constructor(e){this.maxChunkSize=e?.maxChunkSize??r.code.max}chunk(e,t){let n=this.findDeclarationBoundaries(e);if(n.length===0)return this.fallbackChunk(e,t);let r=[];for(let i=0;i<n.length;i++){let a=n[i].offset,o=i+1<n.length?n[i+1].offset:e.length,s=e.slice(a,o).trim();if(s=`// File: ${t.sourcePath}\n`+s,s.length>this.maxChunkSize){let n=this.splitByLines(s,this.maxChunkSize),i=this.getLineNumber(e,a);for(let e of n){let n=e.split(`
1
+ import{dirname as e,extname as t,join as n}from"node:path";import{CHUNK_SIZES as r,createLogger as i}from"../../core/dist/index.js";import{existsSync as a,readFileSync as o}from"node:fs";import{fileURLToPath as s}from"node:url";const c=e(s(import.meta.url));function l(){let e=[n(c,`..`,`..`,`wasm`),n(c,`..`,`wasm`)];for(let t of e)if(a(n(t,`tree-sitter.wasm`)))return t;return e[0]}const u=l(),d={".ts":`tree-sitter-typescript.wasm`,".tsx":`tree-sitter-typescript.wasm`,".mts":`tree-sitter-typescript.wasm`,".cts":`tree-sitter-typescript.wasm`,".js":`tree-sitter-javascript.wasm`,".jsx":`tree-sitter-javascript.wasm`,".mjs":`tree-sitter-javascript.wasm`,".cjs":`tree-sitter-javascript.wasm`,".py":`tree-sitter-python.wasm`,".go":`tree-sitter-go.wasm`,".rs":`tree-sitter-rust.wasm`,".java":`tree-sitter-java.wasm`,".kt":`tree-sitter-kotlin.wasm`,".kts":`tree-sitter-kotlin.wasm`,".scala":`tree-sitter-scala.wasm`,".sc":`tree-sitter-scala.wasm`,".c":`tree-sitter-c.wasm`,".h":`tree-sitter-c.wasm`,".cpp":`tree-sitter-cpp.wasm`,".cc":`tree-sitter-cpp.wasm`,".cxx":`tree-sitter-cpp.wasm`,".hpp":`tree-sitter-cpp.wasm`,".hxx":`tree-sitter-cpp.wasm`,".cs":`tree-sitter-c_sharp.wasm`,".swift":`tree-sitter-swift.wasm`,".rb":`tree-sitter-ruby.wasm`,".php":`tree-sitter-php.wasm`},f=new Set(Object.keys(d));function p(e){let t=d[e];if(!t)return null;let r=n(u,t);return a(r)?r:null}function m(){let e=n(u,`tree-sitter.wasm`);return a(e)?e:null}const h=i(`wasm-runtime`);async function g(){let e=await import(`web-tree-sitter`),t=typeof e.default?.init==`function`?e.default:e.Parser;if(!t||typeof t.init!=`function`)throw Error(`Unsupported web-tree-sitter export shape: ${Object.keys(e).join(`, `)}`);return t}var _=class e{static instance=null;parser=null;languages=new Map;loadedGrammars=new Map;static async initialize(){if(e.instance)return e.instance;let t=new e;return await t.init()?(e.instance=t,t):null}static get(){return e.instance}static async ensure(){let t=e.get();if(t)return t;let n=await e.initialize();if(!n)throw Error(`Failed to initialize WASM tree-sitter runtime`);return n}static dispose(){e.instance&&=(e.instance.parser?.delete(),e.instance.parser=null,e.instance.languages.clear(),e.instance.loadedGrammars.clear(),null)}async init(){try{let e=m();if(!e)return h.warn(`Parser WASM file not found`),!1;let t=await g();return await t.init({locateFile:()=>e}),this.parser=new t,h.info(`WASM tree-sitter parser initialized`),!0}catch(e){return h.warn(`Failed to initialize WASM tree-sitter`,{error:String(e)}),!1}}async loadLanguage(e){let t=this.languages.get(e);if(t)return t;let n=p(e);if(!n)return null;let r=this.loadedGrammars.get(n);if(r)return this.languages.set(e,r),r;try{let t=await(await g()).Language.load(n);return this.loadedGrammars.set(n,t),this.languages.set(e,t),h.info(`Loaded grammar`,{ext:e}),t}catch(t){return h.warn(`Failed to load grammar`,{ext:e,error:String(t)}),null}}async parse(e,t){if(!this.parser)return null;let n=await this.loadLanguage(t);return n?(this.parser.setLanguage(n),this.parser.parse(e)):null}hasLanguage(e){return f.has(e)}isLanguageLoaded(e){return this.languages.has(e)}getParser(){return this.parser}getLanguage(e){return this.languages.get(e)??null}};async function ee(){return await _.initialize()!==null}const v=new Set([`function_declaration`,`method_definition`,`arrow_function`,`function_definition`,`function_declaration`,`method_declaration`,`function_item`,`method_declaration`,`constructor_declaration`]),y=new Set([`call_expression`,`new_expression`,`call`]);function b(e,n){let r=t(n).toLowerCase(),i=_.get();if(i?.isLanguageLoaded(r)){let t=i.getParser(),a=i.getLanguage(r);if(t&&a){t.setLanguage(a);let r=t.parse(e);if(r){let e=[];return x(r.rootNode,n,`<module>`,e),e}}}return null}function x(e,t,n,r){if(!e)return;let i=n;if(v.has(e.type)&&(i=S(e)??n),y.has(e.type)){let n=C(e);n&&r.push({callerFile:t,callerName:i,calleeName:n,line:(e.startPosition?.row??0)+1})}for(let n=0;n<(e.childCount??0);n++){let a=e.child(n);a&&x(a,t,i,r)}}function S(e){for(let t=0;t<(e.childCount??0);t++){let n=e.child(t);if(n&&(n.type===`identifier`||n.type===`property_identifier`||n.type===`name`))return n.text??null}return null}function C(e){let t=e.childForFieldName?.(`function`)??e.child(0);return t?t.type===`identifier`||t.type===`name`?t.text??null:t.type===`member_expression`||t.type===`attribute`?(t.childForFieldName?.(`property`)??t.childForFieldName?.(`attribute`))?.text??null:e.type===`new_expression`?e.child(1)?.text??null:null:null}var w=class{maxChunkSize;constructor(e){this.maxChunkSize=e?.maxChunkSize??r.code.max}chunk(e,t){let n=this.findDeclarationBoundaries(e);if(n.length===0)return this.fallbackChunk(e,t);let r=[];for(let i=0;i<n.length;i++){let a=n[i].offset,o=i+1<n.length?n[i+1].offset:e.length,s=e.slice(a,o).trim();if(s=`// File: ${t.sourcePath}\n`+s,s.length>this.maxChunkSize){let n=this.splitByLines(s,this.maxChunkSize),i=this.getLineNumber(e,a);for(let e of n){let n=e.split(`
2
2
  `).length;r.push({text:e,sourcePath:t.sourcePath,contentType:t.contentType,chunkIndex:r.length,totalChunks:0,startLine:i,endLine:i+n-1}),i+=n}}else{let n=this.getLineNumber(e,a);r.push({text:s,sourcePath:t.sourcePath,contentType:t.contentType,chunkIndex:r.length,totalChunks:0,startLine:n,endLine:n+s.split(`
3
3
  `).length-1})}}if(n[0].offset>0){let i=e.slice(0,n[0].offset).trim();i.length>0&&r.unshift({text:`// File: ${t.sourcePath}\n${i}`,sourcePath:t.sourcePath,contentType:t.contentType,chunkIndex:0,totalChunks:0,startLine:1,endLine:this.getLineNumber(e,n[0].offset)-1})}return r.map((e,t)=>({...e,chunkIndex:t,totalChunks:r.length}))}findDeclarationBoundaries(e){let t=/^(?:export\s+)?(?:default\s+)?(?:async\s+)?(?:function|class|interface|type|const|enum|abstract\s+class)\s+(\w+)/gm,n=[],r;for(;(r=t.exec(e))!==null;){let t=e.lastIndexOf(`
4
4
  `,r.index-1)+1,i=t,a=e.slice(0,t).split(`
@@ -8,17 +8,17 @@ import{dirname as e,extname as t,join as n}from"node:path";import{CHUNK_SIZES as
8
8
  `),r=[],i=[],a=0;for(let e of n)a+e.length+1>t&&i.length>0?(r.push(i.join(`
9
9
  `)),i=[e],a=e.length):(i.push(e),a+=e.length+1);return i.length>0&&r.push(i.join(`
10
10
  `)),r}getLineNumber(e,t){return e.slice(0,t).split(`
11
- `).length}},w=class{maxChunkSize;overlap;constructor(e){this.maxChunkSize=e?.maxChunkSize??r.default.max,this.overlap=e?.overlap??r.default.overlap}chunk(e,t){if(e.length<=this.maxChunkSize)return[{text:e,sourcePath:t.sourcePath,contentType:t.contentType,chunkIndex:0,totalChunks:1,startLine:1,endLine:e.split(`
11
+ `).length}},T=class{maxChunkSize;overlap;constructor(e){this.maxChunkSize=e?.maxChunkSize??r.default.max,this.overlap=e?.overlap??r.default.overlap}chunk(e,t){if(e.length<=this.maxChunkSize)return[{text:e,sourcePath:t.sourcePath,contentType:t.contentType,chunkIndex:0,totalChunks:1,startLine:1,endLine:e.split(`
12
12
  `).length}];let n=e.split(`
13
13
  `),r=[],i=[],a=0,o=1;for(let e=0;e<n.length;e++){let s=n[e];if(a+s.length+1>this.maxChunkSize&&i.length>0){r.push({text:i.join(`
14
14
  `),sourcePath:t.sourcePath,contentType:t.contentType,chunkIndex:r.length,totalChunks:0,startLine:o,endLine:o+i.length-1});let e=[],n=0;for(let t=i.length-1;t>=0&&!(n+i[t].length+1>this.overlap);t--)e.unshift(i[t]),n+=i[t].length+1;o=o+i.length-e.length,i=[...e,s],a=n+s.length+1}else i.push(s),a+=s.length+1}return i.length>0&&r.push({text:i.join(`
15
- `),sourcePath:t.sourcePath,contentType:t.contentType,chunkIndex:r.length,totalChunks:0,startLine:o,endLine:o+i.length-1}),r.map((e,t)=>({...e,chunkIndex:t,totalChunks:r.length}))}},T=class{maxChunkSize;minChunkSize;constructor(e){this.maxChunkSize=e?.maxChunkSize??r.markdown.max,this.minChunkSize=e?.minChunkSize??r.markdown.min}chunk(e,t){let n=this.splitByHeadings(e),r=[];for(let e of n){if(e.text.trim().length<this.minChunkSize&&r.length>0){let t=r[r.length-1];t.text+=`\n\n${e.text}`,t.endLine=e.endLine;continue}if(e.text.length>this.maxChunkSize){let n=this.splitByParagraphs(e.text,this.maxChunkSize),i=e.startLine;for(let a of n){let n=a.split(`
15
+ `),sourcePath:t.sourcePath,contentType:t.contentType,chunkIndex:r.length,totalChunks:0,startLine:o,endLine:o+i.length-1}),r.map((e,t)=>({...e,chunkIndex:t,totalChunks:r.length}))}},E=class{maxChunkSize;minChunkSize;constructor(e){this.maxChunkSize=e?.maxChunkSize??r.markdown.max,this.minChunkSize=e?.minChunkSize??r.markdown.min}chunk(e,t){let n=this.splitByHeadings(e),r=[];for(let e of n){if(e.text.trim().length<this.minChunkSize&&r.length>0){let t=r[r.length-1];t.text+=`\n\n${e.text}`,t.endLine=e.endLine;continue}if(e.text.length>this.maxChunkSize){let n=this.splitByParagraphs(e.text,this.maxChunkSize),i=e.startLine;for(let a of n){let n=a.split(`
16
16
  `).length;r.push({text:a,sourcePath:t.sourcePath,contentType:t.contentType,headingPath:e.headingPath,chunkIndex:r.length,totalChunks:0,startLine:i,endLine:i+n-1}),i+=n}}else r.push({text:e.text,sourcePath:t.sourcePath,contentType:t.contentType,headingPath:e.headingPath,chunkIndex:r.length,totalChunks:0,startLine:e.startLine,endLine:e.endLine})}return r.map((e,t)=>({...e,chunkIndex:t,totalChunks:r.length}))}splitByHeadings(e){let t=e.split(`
17
- `),n=[],r=null,i=[],a=!1;for(let e=0;e<t.length;e++){/^```/.test(t[e])&&(a=!a);let o=a?null:t[e].match(/^(#{1,6})\s+(.+)/);if(o){r&&n.push(r);let a=o[1].length,s=o[2].trim();for(;i.length>=a;)i.pop();i.push(`${`#`.repeat(a)} ${s}`),r={text:t[e],headingPath:i.join(` > `),startLine:e+1,endLine:e+1}}else r?(r.text+=`\n${t[e]}`,r.endLine=e+1):r={text:t[e],headingPath:`(intro)`,startLine:e+1,endLine:e+1}}return r&&n.push(r),n}splitByParagraphs(e,t){let n=e.split(/\n\n+/),r=[],i=``;for(let e of n)`${i}\n\n${e}`.length>t&&i.length>0?(r.push(i.trim()),i=e):i=i?`${i}\n\n${e}`:e;return i.trim()&&r.push(i.trim()),r}};const E=new Set([`function_declaration`,`class_declaration`,`interface_declaration`,`type_alias_declaration`,`enum_declaration`,`lexical_declaration`,`variable_declaration`,`export_statement`,`function_definition`,`class_definition`,`decorated_definition`,`class_declaration`,`interface_declaration`,`enum_declaration`,`function_declaration`,`method_declaration`,`type_declaration`,`function_item`,`struct_item`,`enum_item`,`trait_item`,`impl_item`,`const_item`,`static_item`,`type_item`]),ne=new Set([`import_statement`,`import_from_statement`,`import_declaration`,`package_declaration`,`use_declaration`,`extern_crate_declaration`,`import_spec`,`package_clause`]);var D=class{maxChunkSize;constructor(e){this.maxChunkSize=e?.maxChunkSize??r.code.max}chunk(e,t){let n=_.get();if(!n)return this.singleChunk(e,t);let r=this.extractExt(t.sourcePath),i=n.getLanguage(r);if(!i)return this.singleChunk(e,t);let a=n.getParser();if(!a)return this.singleChunk(e,t);a.setLanguage(i);let o=a.parse(e);if(!o)return this.singleChunk(e,t);let s=this.findAstBoundaries(o.rootNode,e);return s.length===0?this.singleChunk(e,t):this.buildChunks(s,e,t)}findAstBoundaries(e,t){let n=[];for(let t of e.children){if(!t.isNamed)continue;let e=E.has(t.type),r=ne.has(t.type);(e||r)&&n.push({startOffset:t.startIndex,endOffset:t.endIndex,startLine:t.startPosition.row+1,endLine:t.endPosition.row+1,isPreamble:r})}return n}buildChunks(e,t,n){let r=[],i=null,a=0,o=0;for(let s of e){if(s.isPreamble){i===null&&(i=s.startLine),a=s.endOffset,o=s.endLine;continue}if(i!==null){let e=t.slice(0,a).trim();e.length>0&&r.push({text:`// File: ${n.sourcePath}\n${e}`,sourcePath:n.sourcePath,contentType:n.contentType,chunkIndex:0,totalChunks:0,startLine:i,endLine:o}),i=null}let e=t.slice(s.startOffset,s.endOffset).trim();if(e=`// File: ${n.sourcePath}\n`+e,e.length>this.maxChunkSize){let t=this.splitByLines(e,this.maxChunkSize),i=s.startLine;for(let e of t){let t=e.split(`
17
+ `),n=[],r=null,i=[],a=!1;for(let e=0;e<t.length;e++){/^```/.test(t[e])&&(a=!a);let o=a?null:t[e].match(/^(#{1,6})\s+(.+)/);if(o){r&&n.push(r);let a=o[1].length,s=o[2].trim();for(;i.length>=a;)i.pop();i.push(`${`#`.repeat(a)} ${s}`),r={text:t[e],headingPath:i.join(` > `),startLine:e+1,endLine:e+1}}else r?(r.text+=`\n${t[e]}`,r.endLine=e+1):r={text:t[e],headingPath:`(intro)`,startLine:e+1,endLine:e+1}}return r&&n.push(r),n}splitByParagraphs(e,t){let n=e.split(/\n\n+/),r=[],i=``;for(let e of n)`${i}\n\n${e}`.length>t&&i.length>0?(r.push(i.trim()),i=e):i=i?`${i}\n\n${e}`:e;return i.trim()&&r.push(i.trim()),r}};const te=new Set([`function_declaration`,`class_declaration`,`interface_declaration`,`type_alias_declaration`,`enum_declaration`,`lexical_declaration`,`variable_declaration`,`export_statement`,`function_definition`,`class_definition`,`decorated_definition`,`class_declaration`,`interface_declaration`,`enum_declaration`,`function_declaration`,`method_declaration`,`type_declaration`,`function_item`,`struct_item`,`enum_item`,`trait_item`,`impl_item`,`const_item`,`static_item`,`type_item`]),ne=new Set([`import_statement`,`import_from_statement`,`import_declaration`,`package_declaration`,`use_declaration`,`extern_crate_declaration`,`import_spec`,`package_clause`]);var D=class{maxChunkSize;constructor(e){this.maxChunkSize=e?.maxChunkSize??r.code.max}chunk(e,t){let n=_.get();if(!n)return this.singleChunk(e,t);let r=this.extractExt(t.sourcePath),i=n.getLanguage(r);if(!i)return this.singleChunk(e,t);let a=n.getParser();if(!a)return this.singleChunk(e,t);a.setLanguage(i);let o=a.parse(e);if(!o)return this.singleChunk(e,t);let s=this.findAstBoundaries(o.rootNode,e);return s.length===0?this.singleChunk(e,t):this.buildChunks(s,e,t)}findAstBoundaries(e,t){let n=[];for(let t of e.children){if(!t.isNamed)continue;let e=te.has(t.type),r=ne.has(t.type);(e||r)&&n.push({startOffset:t.startIndex,endOffset:t.endIndex,startLine:t.startPosition.row+1,endLine:t.endPosition.row+1,isPreamble:r})}return n}buildChunks(e,t,n){let r=[],i=null,a=0,o=0;for(let s of e){if(s.isPreamble){i===null&&(i=s.startLine),a=s.endOffset,o=s.endLine;continue}if(i!==null){let e=t.slice(0,a).trim();e.length>0&&r.push({text:`// File: ${n.sourcePath}\n${e}`,sourcePath:n.sourcePath,contentType:n.contentType,chunkIndex:0,totalChunks:0,startLine:i,endLine:o}),i=null}let e=t.slice(s.startOffset,s.endOffset).trim();if(e=`// File: ${n.sourcePath}\n`+e,e.length>this.maxChunkSize){let t=this.splitByLines(e,this.maxChunkSize),i=s.startLine;for(let e of t){let t=e.split(`
18
18
  `).length;r.push({text:e,sourcePath:n.sourcePath,contentType:n.contentType,chunkIndex:0,totalChunks:0,startLine:i,endLine:i+t-1}),i+=t}}else r.push({text:e,sourcePath:n.sourcePath,contentType:n.contentType,chunkIndex:0,totalChunks:0,startLine:s.startLine,endLine:s.endLine})}if(i!==null){let e=t.slice(0,a).trim();e.length>0&&r.push({text:`// File: ${n.sourcePath}\n${e}`,sourcePath:n.sourcePath,contentType:n.contentType,chunkIndex:0,totalChunks:0,startLine:i,endLine:o})}return r.map((e,t)=>({...e,chunkIndex:t,totalChunks:r.length}))}splitByLines(e,t){let n=e.split(`
19
19
  `),r=[],i=[],a=0;for(let e of n)a+e.length+1>t&&i.length>0&&(r.push(i.join(`
20
20
  `)),i=[],a=0),i.push(e),a+=e.length+1;return i.length>0&&r.push(i.join(`
21
21
  `)),r}extractExt(e){let t=e.lastIndexOf(`.`);return t>=0?e.slice(t).toLowerCase():``}singleChunk(e,t){return[{text:`// File: ${t.sourcePath}\n${e}`,sourcePath:t.sourcePath,contentType:t.contentType,chunkIndex:0,totalChunks:1,startLine:1,endLine:e.split(`
22
- `).length}]}};async function re(e){let t=e.toLowerCase();switch(t){case`.md`:case`.mdx`:return new T;case`.ts`:case`.tsx`:case`.mts`:case`.cts`:case`.js`:case`.jsx`:case`.mjs`:case`.cjs`:case`.py`:case`.go`:case`.rs`:case`.java`:if(f.has(t)){let e=await _.initialize();if(e)return await e.loadLanguage(t),new D}return new C;default:return new w}}function ie(e){let t=e.toLowerCase();switch(t){case`.md`:case`.mdx`:return new T;case`.ts`:case`.tsx`:case`.mts`:case`.cts`:case`.js`:case`.jsx`:case`.mjs`:case`.cjs`:case`.py`:case`.go`:case`.rs`:case`.java`:return _.get()?.isLanguageLoaded(t)?new D:new C;default:return new w}}const O=i(`query-executor`),k=e(s(import.meta.url));function A(){let e=n(k,`..`,`queries`);if(a(e))return e;let t=n(k,`..`,`..`,`src`,`queries`);return a(t)?t:e}const j=A(),M={".ts":`typescript`,".tsx":`typescript`,".mts":`typescript`,".cts":`typescript`,".js":`javascript`,".jsx":`javascript`,".mjs":`javascript`,".cjs":`javascript`,".py":`python`,".go":`go`,".rs":`rust`,".java":`java`};var N=class{queryCache=new Map;scmCache=new Map;execute(e,t,n,r){let i=this.getOrCompile(t,n,r);return i?i.matches(e).map(e=>P(e)):[]}executeCaptures(e,t,n,r){let i=this.getOrCompile(t,n,r);return i?i.captures(e).map(e=>F(e)):[]}executeRaw(e,t,n){return t.query(n).matches(e).map(e=>P(e))}getOrCompile(e,t,n){let r=M[t];if(!r)return null;let i=`${r}:${n}`,a=this.queryCache.get(i);if(a)return a;let o=this.loadScm(r,n);if(!o)return null;try{let t=e.query(o);return this.queryCache.set(i,t),t}catch(e){throw O.warn(`Failed to compile query`,{langDir:r,queryType:n,error:String(e)}),Error(`Failed to compile ${r}/${n}.scm: ${String(e)}`)}}loadScm(e,t){let r=`${e}:${t}`,i=this.scmCache.get(r);if(i!==void 0)return i;let a=n(j,e,`${t}.scm`);try{let e=o(a,`utf-8`);return this.scmCache.set(r,e),e}catch{return O.info(`Query file not found (graceful skip)`,{langDir:e,queryType:t}),null}}dispose(){this.queryCache.clear(),this.scmCache.clear()}static resolveQueryDir(e){return n(j,e)}};function P(e){let t=new Map;for(let n of e.captures)t.set(n.name,F(n));return{pattern:e.pattern,captures:t}}function F(e){let{node:t}=e;return{name:e.name,text:t.text,nodeType:t.type,startLine:t.startPosition.row,endLine:t.endPosition.row,startColumn:t.startPosition.column,endColumn:t.endPosition.column,node:t}}const I=new N,L=new Set([`function_declaration`,`method_definition`,`arrow_function`,`function_definition`,`method_declaration`,`constructor_declaration`,`function_declaration`,`method_declaration`,`function_item`]);async function R(e,t,n=``){let r=await _.ensure(),i=await r.parse(e,t);if(!i)return[];let a=r.getLanguage(t);return a?I.execute(i.rootNode,a,t,`calls`).map(e=>z(e,i.rootNode,n)).filter(e=>e!==null):[]}function z(e,t,n){let r=e.captures.get(`callee`);if(!r)return null;let i=e.captures.get(`node`);return{callerFile:n,callerName:B(i?.node??r.node),calleeName:r.text,line:(i?.startLine??r.startLine)+1}}function B(e){let t=e.parent;for(;t;){if(L.has(t.type)){let e=V(t);if(e)return e}t=t.parent}return`<module>`}function V(e){let t=e.childForFieldName(`name`);if(t)return t.text;for(let t of e.children)if(t.type===`identifier`||t.type===`property_identifier`||t.type===`field_identifier`)return t.text;return null}const H=new N,U={handler:`lambda-handler`,lambdaHandler:`lambda-handler`,main:`main`,__name__:`main`,app:`server`,server:`server`,router:`server`,urlpatterns:`server`,init:`main`},W={SpringBootApplication:`server`,RestController:`server`,Controller:`server`};async function G(e,t,n=``){let r=await _.ensure(),i=await r.parse(e,t);if(!i)return[];let a=r.getLanguage(t);if(!a)return[];let o=H.execute(i.rootNode,a,t,`entry-points`),s=[],c=new Set;for(let e of o){let r=K(e,t,n);if(r){let e=`${r.name}:${r.type}`;c.has(e)||(c.add(e),s.push(r))}}return s}function K(e,t,n){let r=e.captures.get(`name`);if(!r)return null;let i=r.text,a=e.captures.get(`_parent`);if(a){let e=a.text;if([`Construct`,`Stack`,`NestedStack`,`Stage`].includes(e))return{name:i,type:`cdk-construct`,filePath:n}}let o=e.captures.get(`_ann`);if(o){let e=W[o.text];if(e)return{name:i,type:e,filePath:n}}let s=U[i];return s?{name:i,type:s,filePath:n}:t===`.go`&&i.toLowerCase().startsWith(`handle`)?{name:i,type:`server`,filePath:n,trigger:`HTTP handler`}:{name:i,type:`main`,filePath:n}}const q=new N;async function J(e,t,n=``){let r=await _.ensure(),i=await r.parse(e,t);if(!i)return[];let a=r.getLanguage(t);if(!a)return[];let o=q.execute(i.rootNode,a,t,`imports`),s=[];for(let e of o){let r=e.captures.get(`source`);if(!r){let r=e.captures.get(`node`);if(r){let e=oe(r.text,t);e&&s.push({source:e.source,specifiers:e.specifiers,filePath:n,isExternal:X(e.source,t),confidence:`high`})}continue}let i=r.text,a=Y(i,t),o=ae(e.captures.get(`node`)?.text??``,t,a);s.push({source:a,specifiers:o,filePath:n,isExternal:X(a,t),confidence:`high`})}return s}function Y(e,t){let n=e.replace(/^['"`]|['"`]$/g,``);return t===`.go`&&(n=n.replace(/^"|"$/g,``)),n}function X(e,t){return t===`.py`?!e.startsWith(`.`):t===`.go`?e.includes(`/`)||e.includes(`.`):t===`.java`?!0:t===`.rs`?!e.startsWith(`self`)&&!e.startsWith(`super`)&&!e.startsWith(`crate`):!e.startsWith(`.`)&&!e.startsWith(`/`)}function ae(e,t,n){if(!e)return[n];if(t===`.py`){let t=e.match(/import\s+(.+)$/m);return t?t[1].split(`,`).map(e=>e.trim().split(/\s+as\s+/)[0].trim()).filter(Boolean):[n]}if(t===`.java`){let e=n.split(`.`);return[e[e.length-1]]}if(t===`.go`){let e=n.split(`/`);return[e[e.length-1]]}if(t===`.rs`){if(n.includes(`{`)){let e=n.match(/\{([^}]+)\}/);if(e)return e[1].split(`,`).map(e=>e.trim()).filter(Boolean)}let e=n.split(`::`);return[e[e.length-1]]}let r=e.match(/\{([^}]+)\}/);if(r)return r[1].split(`,`).map(e=>e.trim().split(/\s+as\s+/)[0].trim()).filter(Boolean);let i=e.match(/import\s+(\w+)/);return i?[i[1]]:[n]}function oe(e,t){if(t===`.py`){let t=e.match(/^import\s+([\w.]+)/);if(t)return{source:t[1],specifiers:[t[1]]}}return null}const se=new N;async function ce(e,t,n=``){let r=await _.ensure(),i=await r.parse(e,t);if(!i)return[];let a=r.getLanguage(t);if(!a)return[];let o=se.execute(i.rootNode,a,t,`patterns`),s=new Map;for(let e of o){let r=le(e,t);if(!r)continue;let i=e.captures.get(`name`),a=`${n}:${(e.captures.get(`node`)?.startLine??i?.startLine??0)+1}`,o=s.get(r.pattern);o?o.locations.push(a):s.set(r.pattern,{description:r.description,locations:[a]})}let c=[];for(let[e,{description:t,locations:n}]of s)c.push({pattern:e,description:t,locations:n,confidence:`high`});return c}function le(e,t){let n=e.captures.get(`name`)?.text;if(!n)return null;let r=e.captures.get(`node`)?.nodeType??``;if(/^(create|build)[A-Z]/.test(n)||/^(of|from|new)[A-Z]/.test(n))return{pattern:`factory`,description:`Factory function/method`};if(/^(register|bind)$/.test(n))return{pattern:`dependency-injection`,description:`DI container registration`};if(/^(Injectable|Component|Service|Controller|Module|Singleton|Repository|Bean)$/.test(n))return{pattern:`dependency-injection`,description:`Framework DI annotation`};if(/^(Map|WeakMap|Set)$/.test(n))return{pattern:`cached-instance`,description:`Cached Map/Set instance`};if(t===`.py`){if(n===`__new__`)return{pattern:`singleton`,description:`Singleton pattern (__new__ override)`};if(n===`__enter__`)return{pattern:`context-manager`,description:`Context manager pattern`};if(r===`decorated_definition`)return{pattern:`decorator`,description:`Decorator usage`}}if(t===`.go`){if(r===`type_declaration`)return{pattern:`interface`,description:`Interface definition`};if(r===`go_statement`)return{pattern:`concurrency`,description:`Goroutine concurrency pattern`};if(n===`make`)return{pattern:`concurrency`,description:`Channel/make pattern`}}if(t===`.rs`){if(r===`impl_item`)return{pattern:`trait-impl`,description:`Trait implementation`};if(r===`attribute_item`){if(n===`derive`)return{pattern:`derive`,description:`Derive macro attribute`};if(n===`test`)return{pattern:`test`,description:`Test attribute`}}}if(t===`.java`){if(r===`class_declaration`)return{pattern:`singleton`,description:`Singleton pattern (private constructor)`};if(r===`marker_annotation`)return{pattern:`dependency-injection`,description:`Framework DI annotation`}}if(/\.(ts|tsx|mts|cts|js|jsx|mjs|cjs)$/.test(t)){if(r===`class_declaration`)return{pattern:`singleton`,description:`Singleton pattern (private constructor)`};if(r===`decorator`)return{pattern:`decorator`,description:`Framework decorator pattern`}}return{pattern:r||`unknown`,description:`Detected pattern: ${n}`}}const ue=new Set([`function_declaration`,`method_definition`,`arrow_function`,`class_declaration`,`function_definition`,`class_definition`,`method_declaration`,`constructor_declaration`,`class_declaration`,`function_declaration`,`method_declaration`,`function_item`,`impl_item`]);async function de(e,t,n){let r=await(await _.ensure()).parse(e,t);if(!r)return[{name:`<module>`,type:`module`,line:1}];let i=fe(r.rootNode,n-1);if(!i)return[{name:`<module>`,type:`module`,line:1}];let a=[];return pe(i,a),a.push({name:`<module>`,type:`module`,line:1}),a}function fe(e,t){let n=null;function r(e){if(e.startPosition.row<=t&&e.endPosition.row>=t){n=e;for(let t of e.children)r(t)}}return r(e),n}function pe(e,t){let n=e.parent;for(;n;){if(ue.has(n.type)){let e=me(n),r=he(n.type);t.push({name:e??`<anonymous>`,type:r,line:n.startPosition.row+1})}n=n.parent}}function me(e){let t=e.childForFieldName(`name`);if(t)return t.text;for(let t of e.children)if(t.type===`identifier`||t.type===`type_identifier`||t.type===`property_identifier`||t.type===`field_identifier`)return t.text;return null}function he(e){return e.includes(`class`)||e===`impl_item`?`class`:`function`}const ge=new N,_e={function_declaration:`function`,class_declaration:`class`,interface_declaration:`interface`,type_alias_declaration:`type`,enum_declaration:`enum`,lexical_declaration:`const`,method_definition:`method`,public_field_definition:`variable`,field_definition:`variable`,function_definition:`function`,class_definition:`class`,expression_statement:`variable`,method_declaration:`method`,constructor_declaration:`method`,field_declaration:`variable`,type_spec:`type`,type_declaration:`type`,const_spec:`const`,var_spec:`variable`,function_item:`function`,struct_item:`class`,enum_item:`enum`,trait_item:`interface`,impl_item:`type`,const_item:`const`,static_item:`variable`,type_item:`type`};async function ve(e,t,n=``){let r=await _.ensure(),i=await r.parse(e,t);if(!i)return[];let a=r.getLanguage(t);return a?ye(ge.execute(i.rootNode,a,t,`symbols`),t,n):[]}function ye(e,t,n){let r=new Map;for(let n of e){let e=n.captures.get(`name`);if(!e)continue;let i=`${e.text}:${(n.captures.get(`node`)?.startLine??e.startLine)+1}`,a=be(n,t),o=r.get(i);(!o||!o.exported&&a)&&r.set(i,{match:n,exported:a})}let i=[];for(let{match:e,exported:a}of r.values()){let r=e.captures.get(`name`),o=e.captures.get(`node`);if(!r)continue;let s=_e[o?.nodeType??r.nodeType]??`variable`,c=(o?.startLine??r.startLine)+1,l=xe(s,o?.node,t),u=o?.node??r.node;i.push({name:r.text,kind:l,exported:a,filePath:n,line:c,signature:Se(o?.node,l),returnType:Te(o?.node,l),jsdoc:Ee(u),decorators:De(u),typeBody:Oe(o?.node,l)})}return i}function be(e,t){if(e.captures.has(`exported`))return!0;let n=e.captures.get(`name`)?.text;if(!n)return!1;if(t===`.py`)return!n.startsWith(`_`);if(t===`.go`)return/^[A-Z]/.test(n);if(t===`.java`){let t=e.captures.get(`node`)?.text??``;return/\bpublic\b/.test(t)}return!1}function xe(e,t,n){if(n===`.go`&&e===`type`&&t?.children){let e=t.type===`type_declaration`?t.children.flatMap(e=>e.children??[]):t.children;for(let t of e){if(t.type===`interface_type`)return`interface`;if(t.type===`struct_type`)return`class`}}return e}function Se(e,t){if(e){if(t===`function`||t===`method`)return Z(e);if(t===`class`)return Ce(e);if(t===`interface`)return we(e)}}function Z(e){let t=e.childForFieldName(`parameters`)??e.childForFieldName(`parameter_list`),n=e.childForFieldName(`return_type`)??e.childForFieldName(`type`),r=e.childForFieldName(`result`);if(!t){for(let t of e.children)if(t.type===`formal_parameters`||t.type===`parameter_list`||t.type===`parameters`){let e=t.text;return n&&(e+=n.text),r&&(e+=` ${r.text}`),e.length>120?`${e.slice(0,117)}...`:e}return}let i=t.text;return n&&(i+=n.text),r&&(i+=` ${r.text}`),i.length>120?`${i.slice(0,117)}...`:i}function Ce(e){let t=e.childForFieldName(`body`)??e.childForFieldName(`field_declaration_list`);if(!t){for(let t of e.children)if(t.type===`struct_type`||t.type===`class_body`)return Q(t);return}return Q(t)}function Q(e){let t=[];for(let n of e.children){if(n.type===`method_definition`){let e=n.childForFieldName(`name`);e&&t.push(e.text)}if(n.type===`method_declaration`){let e=n.childForFieldName(`name`);e&&t.push(e.text)}if(n.type===`field_declaration`){let e=n.childForFieldName(`name`);e&&t.push(e.text)}if(n.type===`function_definition`){let e=n.childForFieldName(`name`);e&&t.push(e.text)}}if(t.length===0)return;let n=t.join(`, `);return n.length>120?`${n.slice(0,117)}...`:n}function we(e){let t=e.childForFieldName(`body`);if(!t){for(let t of e.children)if(t.type===`interface_type`)return $(t);return}return $(t)}function $(e){let t=[];for(let n of e.children){if(n.type===`property_signature`||n.type===`method_signature`){let e=n.childForFieldName(`name`);e&&t.push(e.text)}if(n.type===`method_declaration`){let e=n.childForFieldName(`name`);e&&t.push(e.text)}if(n.type===`method_spec`){let e=n.childForFieldName(`name`);e&&t.push(e.text)}if(n.type===`function_signature_item`||n.type===`declaration_list`){let e=n.childForFieldName(`name`);e&&t.push(e.text)}}if(t.length===0)return;let n=t.join(`, `);return n.length>120?`${n.slice(0,117)}...`:n}function Te(e,t){if(!e||t!==`function`&&t!==`method`)return;let n=e.childForFieldName(`return_type`)??e.childForFieldName(`type`);if(n){let e=n.text.replace(/^:\s*/,``).trim();return e.length>200?`${e.slice(0,200)}…`:e}let r=e.childForFieldName(`result`);if(r)return r.text.trim()}function Ee(e){let t=e.parent;if(!t?.children)return;let n=t.children.indexOf(e);if(n<=0)return;let r=t.children[n-1];if(r){if(r.type===`comment`||r.type===`block_comment`||r.type===`doc_comment`)return r.text.replace(/^\/\*\*?\s*|\s*\*\/$/g,``).split(`
22
+ `).length}]}};async function re(e){let t=e.toLowerCase();switch(t){case`.md`:case`.mdx`:return new E;case`.ts`:case`.tsx`:case`.mts`:case`.cts`:case`.js`:case`.jsx`:case`.mjs`:case`.cjs`:case`.py`:case`.go`:case`.rs`:case`.java`:if(f.has(t)){let e=await _.initialize();if(e)return await e.loadLanguage(t),new D}return new w;default:return new T}}function ie(e){let t=e.toLowerCase();switch(t){case`.md`:case`.mdx`:return new E;case`.ts`:case`.tsx`:case`.mts`:case`.cts`:case`.js`:case`.jsx`:case`.mjs`:case`.cjs`:case`.py`:case`.go`:case`.rs`:case`.java`:return _.get()?.isLanguageLoaded(t)?new D:new w;default:return new T}}const O=i(`query-executor`),k=e(s(import.meta.url));function A(e=k){let t=[n(e,`..`,`queries`),n(e,`..`,`src`,`queries`)];for(let e of t)if(a(e))return e;return t[0]}const j=A(),M={".ts":`typescript`,".tsx":`typescript`,".mts":`typescript`,".cts":`typescript`,".js":`javascript`,".jsx":`javascript`,".mjs":`javascript`,".cjs":`javascript`,".py":`python`,".go":`go`,".rs":`rust`,".java":`java`};var N=class{queryCache=new Map;scmCache=new Map;execute(e,t,n,r){let i=this.getOrCompile(t,n,r);return i?i.matches(e).map(e=>P(e)):[]}executeCaptures(e,t,n,r){let i=this.getOrCompile(t,n,r);return i?i.captures(e).map(e=>F(e)):[]}executeRaw(e,t,n){return t.query(n).matches(e).map(e=>P(e))}getOrCompile(e,t,n){let r=M[t];if(!r)return null;let i=`${r}:${n}`,a=this.queryCache.get(i);if(a)return a;let o=this.loadScm(r,n);if(!o)return null;try{let t=e.query(o);return this.queryCache.set(i,t),t}catch(e){throw O.warn(`Failed to compile query`,{langDir:r,queryType:n,error:String(e)}),Error(`Failed to compile ${r}/${n}.scm: ${String(e)}`)}}loadScm(e,t){let r=`${e}:${t}`,i=this.scmCache.get(r);if(i!==void 0)return i;let a=n(j,e,`${t}.scm`);try{let e=o(a,`utf-8`);return this.scmCache.set(r,e),e}catch{return O.info(`Query file not found (graceful skip)`,{langDir:e,queryType:t}),this.scmCache.set(r,``),null}}dispose(){this.queryCache.clear(),this.scmCache.clear()}static resolveQueryDir(e){return n(j,e)}};function P(e){let t=new Map;for(let n of e.captures)t.set(n.name,F(n));return{pattern:e.pattern,captures:t}}function F(e){let{node:t}=e;return{name:e.name,text:t.text,nodeType:t.type,startLine:t.startPosition.row,endLine:t.endPosition.row,startColumn:t.startPosition.column,endColumn:t.endPosition.column,node:t}}const I=new N,L=new Set([`function_declaration`,`method_definition`,`arrow_function`,`function_definition`,`method_declaration`,`constructor_declaration`,`function_declaration`,`method_declaration`,`function_item`]);async function R(e,t,n=``){let r=await _.ensure(),i=await r.parse(e,t);if(!i)return[];let a=r.getLanguage(t);return a?I.execute(i.rootNode,a,t,`calls`).map(e=>z(e,i.rootNode,n)).filter(e=>e!==null):[]}function z(e,t,n){let r=e.captures.get(`callee`);if(!r)return null;let i=e.captures.get(`node`);return{callerFile:n,callerName:B(i?.node??r.node),calleeName:r.text,line:(i?.startLine??r.startLine)+1}}function B(e){let t=e.parent;for(;t;){if(L.has(t.type)){let e=V(t);if(e)return e}t=t.parent}return`<module>`}function V(e){let t=e.childForFieldName(`name`);if(t)return t.text;for(let t of e.children)if(t.type===`identifier`||t.type===`property_identifier`||t.type===`field_identifier`)return t.text;return null}const H=new N,U={handler:`lambda-handler`,lambdaHandler:`lambda-handler`,main:`main`,__name__:`main`,app:`server`,server:`server`,router:`server`,urlpatterns:`server`,init:`main`},W={SpringBootApplication:`server`,RestController:`server`,Controller:`server`};async function G(e,t,n=``){let r=await _.ensure(),i=await r.parse(e,t);if(!i)return[];let a=r.getLanguage(t);if(!a)return[];let o=H.execute(i.rootNode,a,t,`entry-points`),s=[],c=new Set;for(let e of o){let r=K(e,t,n);if(r){let e=`${r.name}:${r.type}`;c.has(e)||(c.add(e),s.push(r))}}return s}function K(e,t,n){let r=e.captures.get(`name`);if(!r)return null;let i=r.text,a=e.captures.get(`_parent`);if(a){let e=a.text;if([`Construct`,`Stack`,`NestedStack`,`Stage`].includes(e))return{name:i,type:`cdk-construct`,filePath:n}}let o=e.captures.get(`_ann`);if(o){let e=W[o.text];if(e)return{name:i,type:e,filePath:n}}let s=U[i];return s?{name:i,type:s,filePath:n}:t===`.go`&&i.toLowerCase().startsWith(`handle`)?{name:i,type:`server`,filePath:n,trigger:`HTTP handler`}:{name:i,type:`main`,filePath:n}}const q=new N;async function J(e,t,n=``){let r=await _.ensure(),i=await r.parse(e,t);if(!i)return[];let a=r.getLanguage(t);if(!a)return[];let o=q.execute(i.rootNode,a,t,`imports`),s=[];for(let e of o){let r=e.captures.get(`source`);if(!r){let r=e.captures.get(`node`);if(r){let e=oe(r.text,t);e&&s.push({source:e.source,specifiers:e.specifiers,filePath:n,isExternal:X(e.source,t),confidence:`high`})}continue}let i=r.text,a=Y(i,t),o=ae(e.captures.get(`node`)?.text??``,t,a);s.push({source:a,specifiers:o,filePath:n,isExternal:X(a,t),confidence:`high`})}return s}function Y(e,t){let n=e.replace(/^['"`]|['"`]$/g,``);return t===`.go`&&(n=n.replace(/^"|"$/g,``)),n}function X(e,t){return t===`.py`?!e.startsWith(`.`):t===`.go`?e.includes(`/`)||e.includes(`.`):t===`.java`?!0:t===`.rs`?!e.startsWith(`self`)&&!e.startsWith(`super`)&&!e.startsWith(`crate`):!e.startsWith(`.`)&&!e.startsWith(`/`)}function ae(e,t,n){if(!e)return[n];if(t===`.py`){let t=e.match(/import\s+(.+)$/m);return t?t[1].split(`,`).map(e=>e.trim().split(/\s+as\s+/)[0].trim()).filter(Boolean):[n]}if(t===`.java`){let e=n.split(`.`);return[e[e.length-1]]}if(t===`.go`){let e=n.split(`/`);return[e[e.length-1]]}if(t===`.rs`){if(n.includes(`{`)){let e=n.match(/\{([^}]+)\}/);if(e)return e[1].split(`,`).map(e=>e.trim()).filter(Boolean)}let e=n.split(`::`);return[e[e.length-1]]}let r=e.match(/\{([^}]+)\}/);if(r)return r[1].split(`,`).map(e=>e.trim().split(/\s+as\s+/)[0].trim()).filter(Boolean);let i=e.match(/import\s+(\w+)/);return i?[i[1]]:[n]}function oe(e,t){if(t===`.py`){let t=e.match(/^import\s+([\w.]+)/);if(t)return{source:t[1],specifiers:[t[1]]}}return null}const se=new N;async function ce(e,t,n=``){let r=await _.ensure(),i=await r.parse(e,t);if(!i)return[];let a=r.getLanguage(t);if(!a)return[];let o=se.execute(i.rootNode,a,t,`patterns`),s=new Map;for(let e of o){let r=le(e,t);if(!r)continue;let i=e.captures.get(`name`),a=`${n}:${(e.captures.get(`node`)?.startLine??i?.startLine??0)+1}`,o=s.get(r.pattern);o?o.locations.push(a):s.set(r.pattern,{description:r.description,locations:[a]})}let c=[];for(let[e,{description:t,locations:n}]of s)c.push({pattern:e,description:t,locations:n,confidence:`high`});return c}function le(e,t){let n=e.captures.get(`name`)?.text;if(!n)return null;let r=e.captures.get(`node`)?.nodeType??``;if(/^(create|build)[A-Z]/.test(n)||/^(of|from|new)[A-Z]/.test(n))return{pattern:`factory`,description:`Factory function/method`};if(/^(register|bind)$/.test(n))return{pattern:`dependency-injection`,description:`DI container registration`};if(/^(Injectable|Component|Service|Controller|Module|Singleton|Repository|Bean)$/.test(n))return{pattern:`dependency-injection`,description:`Framework DI annotation`};if(/^(Map|WeakMap|Set)$/.test(n))return{pattern:`cached-instance`,description:`Cached Map/Set instance`};if(t===`.py`){if(n===`__new__`)return{pattern:`singleton`,description:`Singleton pattern (__new__ override)`};if(n===`__enter__`)return{pattern:`context-manager`,description:`Context manager pattern`};if(r===`decorated_definition`)return{pattern:`decorator`,description:`Decorator usage`}}if(t===`.go`){if(r===`type_declaration`)return{pattern:`interface`,description:`Interface definition`};if(r===`go_statement`)return{pattern:`concurrency`,description:`Goroutine concurrency pattern`};if(n===`make`)return{pattern:`concurrency`,description:`Channel/make pattern`}}if(t===`.rs`){if(r===`impl_item`)return{pattern:`trait-impl`,description:`Trait implementation`};if(r===`attribute_item`){if(n===`derive`)return{pattern:`derive`,description:`Derive macro attribute`};if(n===`test`)return{pattern:`test`,description:`Test attribute`}}}if(t===`.java`){if(r===`class_declaration`)return{pattern:`singleton`,description:`Singleton pattern (private constructor)`};if(r===`marker_annotation`)return{pattern:`dependency-injection`,description:`Framework DI annotation`}}if(/\.(ts|tsx|mts|cts|js|jsx|mjs|cjs)$/.test(t)){if(r===`class_declaration`)return{pattern:`singleton`,description:`Singleton pattern (private constructor)`};if(r===`decorator`)return{pattern:`decorator`,description:`Framework decorator pattern`}}return{pattern:r||`unknown`,description:`Detected pattern: ${n}`}}const ue=new Set([`function_declaration`,`method_definition`,`arrow_function`,`class_declaration`,`function_definition`,`class_definition`,`method_declaration`,`constructor_declaration`,`class_declaration`,`function_declaration`,`method_declaration`,`function_item`,`impl_item`]);async function de(e,t,n){let r=await(await _.ensure()).parse(e,t);if(!r)return[{name:`<module>`,type:`module`,line:1}];let i=fe(r.rootNode,n-1);if(!i)return[{name:`<module>`,type:`module`,line:1}];let a=[];return pe(i,a),a.push({name:`<module>`,type:`module`,line:1}),a}function fe(e,t){let n=null;function r(e){if(e.startPosition.row<=t&&e.endPosition.row>=t){n=e;for(let t of e.children)r(t)}}return r(e),n}function pe(e,t){let n=e.parent;for(;n;){if(ue.has(n.type)){let e=me(n),r=he(n.type);t.push({name:e??`<anonymous>`,type:r,line:n.startPosition.row+1})}n=n.parent}}function me(e){let t=e.childForFieldName(`name`);if(t)return t.text;for(let t of e.children)if(t.type===`identifier`||t.type===`type_identifier`||t.type===`property_identifier`||t.type===`field_identifier`)return t.text;return null}function he(e){return e.includes(`class`)||e===`impl_item`?`class`:`function`}const ge=new N,_e={function_declaration:`function`,class_declaration:`class`,interface_declaration:`interface`,type_alias_declaration:`type`,enum_declaration:`enum`,lexical_declaration:`const`,method_definition:`method`,public_field_definition:`variable`,field_definition:`variable`,function_definition:`function`,class_definition:`class`,expression_statement:`variable`,method_declaration:`method`,constructor_declaration:`method`,field_declaration:`variable`,type_spec:`type`,type_declaration:`type`,const_spec:`const`,var_spec:`variable`,function_item:`function`,struct_item:`class`,enum_item:`enum`,trait_item:`interface`,impl_item:`type`,const_item:`const`,static_item:`variable`,type_item:`type`};async function ve(e,t,n=``){let r=await _.ensure(),i=await r.parse(e,t);if(!i)return[];let a=r.getLanguage(t);return a?ye(ge.execute(i.rootNode,a,t,`symbols`),t,n):[]}function ye(e,t,n){let r=new Map;for(let n of e){let e=n.captures.get(`name`);if(!e)continue;let i=`${e.text}:${(n.captures.get(`node`)?.startLine??e.startLine)+1}`,a=be(n,t),o=r.get(i);(!o||!o.exported&&a)&&r.set(i,{match:n,exported:a})}let i=[];for(let{match:e,exported:a}of r.values()){let r=e.captures.get(`name`),o=e.captures.get(`node`);if(!r)continue;let s=_e[o?.nodeType??r.nodeType]??`variable`,c=(o?.startLine??r.startLine)+1,l=xe(s,o?.node,t),u=o?.node??r.node;i.push({name:r.text,kind:l,exported:a,filePath:n,line:c,signature:Se(o?.node,l),returnType:Te(o?.node,l),jsdoc:Ee(u),decorators:De(u),typeBody:Oe(o?.node,l)})}return i}function be(e,t){if(e.captures.has(`exported`))return!0;let n=e.captures.get(`name`)?.text;if(!n)return!1;if(t===`.py`)return!n.startsWith(`_`);if(t===`.go`)return/^[A-Z]/.test(n);if(t===`.java`){let t=e.captures.get(`node`)?.text??``;return/\bpublic\b/.test(t)}return!1}function xe(e,t,n){if(n===`.go`&&e===`type`&&t?.children){let e=t.type===`type_declaration`?t.children.flatMap(e=>e.children??[]):t.children;for(let t of e){if(t.type===`interface_type`)return`interface`;if(t.type===`struct_type`)return`class`}}return e}function Se(e,t){if(e){if(t===`function`||t===`method`)return Z(e);if(t===`class`)return Ce(e);if(t===`interface`)return we(e)}}function Z(e){let t=e.childForFieldName(`parameters`)??e.childForFieldName(`parameter_list`),n=e.childForFieldName(`return_type`)??e.childForFieldName(`type`),r=e.childForFieldName(`result`);if(!t){for(let t of e.children)if(t.type===`formal_parameters`||t.type===`parameter_list`||t.type===`parameters`){let e=t.text;return n&&(e+=n.text),r&&(e+=` ${r.text}`),e.length>120?`${e.slice(0,117)}...`:e}return}let i=t.text;return n&&(i+=n.text),r&&(i+=` ${r.text}`),i.length>120?`${i.slice(0,117)}...`:i}function Ce(e){let t=e.childForFieldName(`body`)??e.childForFieldName(`field_declaration_list`);if(!t){for(let t of e.children)if(t.type===`struct_type`||t.type===`class_body`)return Q(t);return}return Q(t)}function Q(e){let t=[];for(let n of e.children){if(n.type===`method_definition`){let e=n.childForFieldName(`name`);e&&t.push(e.text)}if(n.type===`method_declaration`){let e=n.childForFieldName(`name`);e&&t.push(e.text)}if(n.type===`field_declaration`){let e=n.childForFieldName(`name`);e&&t.push(e.text)}if(n.type===`function_definition`){let e=n.childForFieldName(`name`);e&&t.push(e.text)}}if(t.length===0)return;let n=t.join(`, `);return n.length>120?`${n.slice(0,117)}...`:n}function we(e){let t=e.childForFieldName(`body`);if(!t){for(let t of e.children)if(t.type===`interface_type`)return $(t);return}return $(t)}function $(e){let t=[];for(let n of e.children){if(n.type===`property_signature`||n.type===`method_signature`){let e=n.childForFieldName(`name`);e&&t.push(e.text)}if(n.type===`method_declaration`){let e=n.childForFieldName(`name`);e&&t.push(e.text)}if(n.type===`method_spec`){let e=n.childForFieldName(`name`);e&&t.push(e.text)}if(n.type===`function_signature_item`||n.type===`declaration_list`){let e=n.childForFieldName(`name`);e&&t.push(e.text)}}if(t.length===0)return;let n=t.join(`, `);return n.length>120?`${n.slice(0,117)}...`:n}function Te(e,t){if(!e||t!==`function`&&t!==`method`)return;let n=e.childForFieldName(`return_type`)??e.childForFieldName(`type`);if(n){let e=n.text.replace(/^:\s*/,``).trim();return e.length>200?`${e.slice(0,200)}…`:e}let r=e.childForFieldName(`result`);if(r)return r.text.trim()}function Ee(e){let t=e.parent;if(!t?.children)return;let n=t.children.indexOf(e);if(n<=0)return;let r=t.children[n-1];if(r){if(r.type===`comment`||r.type===`block_comment`||r.type===`doc_comment`)return r.text.replace(/^\/\*\*?\s*|\s*\*\/$/g,``).split(`
23
23
  `).map(e=>e.replace(/^\s*\*\s?/,``).trim()).filter(e=>e.length>0&&!e.startsWith(`@`))[0]?.slice(0,200)||void 0;if(e.children[0]?.type===`expression_statement`){let t=e.children[0].children[0];if(t&&(t.type===`string`||t.type===`concatenated_string`))return t.text.replace(/^['"`]{1,3}|['"`]{1,3}$/g,``).trim().split(`
24
- `)[0]?.trim()?.slice(0,200)||void 0}}}function De(e){let t=e.parent;if(!t?.children)return;let n=t.children.indexOf(e),r=[];for(let e=n-1;e>=0;e--){let n=t.children[e];if(n.type===`decorator`||n.type===`annotation`||n.type===`marker_annotation`){let e=n.text.trim();r.unshift(e.length>100?`${e.slice(0,100)}…`:e)}else if(n.type!==`comment`&&n.type!==`block_comment`&&n.type!==`doc_comment`)break}return r.length>0?r:void 0}function Oe(e,t){if(!e||t!==`interface`&&t!==`type`)return;let n=e.childForFieldName(`body`)??e.childForFieldName(`value`)??e.children.find(e=>e.type===`object_type`||e.type===`interface_body`||e.type===`type_body`);if(!n)return;let r=n.text.replace(/\n\s*/g,` `).replace(/\s+/g,` `).trim();return r.length>500?`${r.slice(0,500)}…`:r}export{C as CodeChunker,w as GenericChunker,T as MarkdownChunker,N as QueryExecutor,f as SUPPORTED_EXTENSIONS,D as WasmChunker,_ as WasmRuntime,re as createChunker,ie as createChunkerSync,G as detectEntryPoints,ce as detectPatterns,b as extractCallEdges,R as extractCalls,J as extractImports,ve as extractSymbols,ee as initializeWasm,p as resolveGrammarPath,m as resolveParserWasmPath,de as resolveScopes};
24
+ `)[0]?.trim()?.slice(0,200)||void 0}}}function De(e){let t=e.parent;if(!t?.children)return;let n=t.children.indexOf(e),r=[];for(let e=n-1;e>=0;e--){let n=t.children[e];if(n.type===`decorator`||n.type===`annotation`||n.type===`marker_annotation`){let e=n.text.trim();r.unshift(e.length>100?`${e.slice(0,100)}…`:e)}else if(n.type!==`comment`&&n.type!==`block_comment`&&n.type!==`doc_comment`)break}return r.length>0?r:void 0}function Oe(e,t){if(!e||t!==`interface`&&t!==`type`)return;let n=e.childForFieldName(`body`)??e.childForFieldName(`value`)??e.children.find(e=>e.type===`object_type`||e.type===`interface_body`||e.type===`type_body`);if(!n)return;let r=n.text.replace(/\n\s*/g,` `).replace(/\s+/g,` `).trim();return r.length>500?`${r.slice(0,500)}…`:r}export{w as CodeChunker,T as GenericChunker,E as MarkdownChunker,N as QueryExecutor,f as SUPPORTED_EXTENSIONS,D as WasmChunker,_ as WasmRuntime,re as createChunker,ie as createChunkerSync,G as detectEntryPoints,ce as detectPatterns,b as extractCallEdges,R as extractCalls,J as extractImports,ve as extractSymbols,ee as initializeWasm,p as resolveGrammarPath,m as resolveParserWasmPath,de as resolveScopes};
@@ -17,5 +17,4 @@ Error generating stack: `+e.message+`
17
17
  `).find(e=>e.startsWith(`data: `));if(!e)throw Error(`Empty SSE response`);i=JSON.parse(e.slice(6))}else i=await n.json();if(i.error)throw Error(i.error.message??`Tool call failed`);return i.result}},mf=class{constructor(e){this.http=e}async getStatus(){let e=b(await this.http.callTool(`status`));return e?{totalRecords:e.totalRecords??0,totalFiles:e.totalFiles??0,lastIndexedAt:e.lastIndexedAt??null,onboarded:e.onboarded??!1}:{totalRecords:0,totalFiles:0,lastIndexedAt:null,onboarded:!1}}async search(e,t){let n=b(await this.http.callTool(`search`,{query:e,limit:t?.limit??10,search_mode:t?.mode??`hybrid`}));return n?.results?n.results.map(e=>({sourcePath:e.sourcePath??``,contentType:e.contentType??`unknown`,score:e.score??0,content:e.content??``})):[]}async listKnowledge(){let e=b(await this.http.callTool(`list`));return e?.entries?e.entries.map(e=>({path:e.path??``,title:e.title??``,category:e.category??``,tags:e.tags??[],content:e.content??``})):[]}async readKnowledge(e){try{let t=y(await this.http.callTool(`read`,{path:e}));return t?{path:e,title:e.split(`/`).pop()??e,category:``,tags:[],content:t}:null}catch{return null}}async getGraph(e){let t=await this.http.callTool(`graph`,{action:`find_nodes`,...e?{name_pattern:e}:{},limit:100}),n=(b(t)?.nodes??[]).map(e=>({id:e.id??`n-${Math.random().toString(36).slice(2)}`,name:e.name??``,type:e.type??`unknown`}));if(n.length===0){let e=hf(y(t));if(e.length===0)return{nodes:[],edges:[]};n.push(...e)}let r=await this.http.callTool(`graph`,{action:`find_edges`,limit:100}),i=(b(r)?.edges??[]).map(e=>({fromId:e.fromId??``,toId:e.toId??``,type:e.type??`unknown`}));if(i.length===0){let e=y(r);i.push(...gf(e))}return{nodes:n,edges:i}}async getFileTree(){let e=await this.http.callTool(`find`,{glob:`**/*`}),t=b(e);return t?.results?t.results.map(e=>e.path??e):y(e).split(`
18
18
  `).filter(e=>e.trim().length>0)}};function hf(e){let t=[];for(let n of e.split(`
19
19
  `)){let e=/\*\*(.+?)\*\*\s*\((\w+)(?:,\s*id:\s*`?(\w+)`?)?\)/.exec(n);e&&t.push({id:e[3]??`n-${t.length}`,name:e[1],type:e[2]})}return t}function gf(e){let t=[];for(let n of e.split(`
20
- `)){let e=/`?(\w+)`?\s*[—-]+\[(\w+)\][→>]\s*`?(\w+)`?/.exec(n);e&&t.push({fromId:e[1],toId:e[3],type:e[2]})}return t}function _f({client:e}){let{refetch:t}=P(e);return re(e,t),(0,F.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,height:`100vh`,width:`100vw`},children:[(0,F.jsx)(`div`,{style:{display:`flex`,alignItems:`center`,padding:`8px 16px`,borderBottom:`1px solid #30363d`,background:`#161b22`},children:(0,F.jsx)(`h1`,{style:{margin:0,fontSize:`16px`,color:`#58a6ff`,fontWeight:600},children:`AI Kit Dashboard`})}),(0,F.jsxs)(`div`,{style:{flex:1,position:`relative`,overflow:`hidden`},children:[(0,F.jsx)(df,{}),(0,F.jsx)(lf,{}),(0,F.jsx)(ff,{})]}),(0,F.jsx)(uf,{})]})}function vf(){let[e,t]=(0,_.useState)(null),{setError:n,setConnected:r}=N();return(0,_.useEffect)(()=>{let e=window.location.origin,i=new mf(new pf(e));i.getStatus().then(()=>{t(i),r(!0)}).catch(e=>{n(`Cannot connect to AI Kit server: ${e.message}`),r(!1),t(i)})},[n,r]),e?(0,F.jsx)(S,{value:e,children:(0,F.jsx)(_f,{client:e})}):(0,F.jsx)(`div`,{style:{display:`flex`,alignItems:`center`,justifyContent:`center`,height:`100vh`,color:`#8b949e`,fontSize:`14px`},children:`Connecting to AI Kit server...`})}var yf=document.getElementById(`root`);if(!yf)throw Error(`Root element not found`);(0,v.createRoot)(yf).render((0,F.jsx)(vf,{}));
21
- //# sourceMappingURL=index-C6D-PCp0.js.map
20
+ `)){let e=/`?(\w+)`?\s*[—-]+\[(\w+)\][→>]\s*`?(\w+)`?/.exec(n);e&&t.push({fromId:e[1],toId:e[3],type:e[2]})}return t}function _f({client:e}){let{refetch:t}=P(e);return re(e,t),(0,F.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,height:`100vh`,width:`100vw`},children:[(0,F.jsx)(`div`,{style:{display:`flex`,alignItems:`center`,padding:`8px 16px`,borderBottom:`1px solid #30363d`,background:`#161b22`},children:(0,F.jsx)(`h1`,{style:{margin:0,fontSize:`16px`,color:`#58a6ff`,fontWeight:600},children:`AI Kit Dashboard`})}),(0,F.jsxs)(`div`,{style:{flex:1,position:`relative`,overflow:`hidden`},children:[(0,F.jsx)(df,{}),(0,F.jsx)(lf,{}),(0,F.jsx)(ff,{})]}),(0,F.jsx)(uf,{})]})}function vf(){let[e,t]=(0,_.useState)(null),{setError:n,setConnected:r}=N();return(0,_.useEffect)(()=>{let e=window.location.origin,i=new mf(new pf(e));i.getStatus().then(()=>{t(i),r(!0)}).catch(e=>{n(`Cannot connect to AI Kit server: ${e.message}`),r(!1),t(i)})},[n,r]),e?(0,F.jsx)(S,{value:e,children:(0,F.jsx)(_f,{client:e})}):(0,F.jsx)(`div`,{style:{display:`flex`,alignItems:`center`,justifyContent:`center`,height:`100vh`,color:`#8b949e`,fontSize:`14px`},children:`Connecting to AI Kit server...`})}var yf=document.getElementById(`root`);if(!yf)throw Error(`Root element not found`);(0,v.createRoot)(yf).render((0,F.jsx)(vf,{}));
@@ -1 +1 @@
1
- import{t as e}from"./curated-manager-DX-_oJg0.js";import{readFileSync as t}from"node:fs";import{dirname as n,resolve as r}from"node:path";import{fileURLToPath as i,pathToFileURL as a}from"node:url";import{parseArgs as o}from"node:util";import{createLogger as s,serializeError as c}from"../../core/dist/index.js";const l=n(i(import.meta.url)),u=(()=>{try{let e=r(l,`..`,`..`,`..`,`package.json`);return JSON.parse(t(e,`utf-8`)).version??`0.0.0`}catch{return`0.0.0`}})(),d=s(`server`),{values:f}=(()=>{let e=process.argv[1];if(!e)return!1;try{return import.meta.url===a(e).href}catch{return!1}})()?o({allowPositionals:!0,options:{transport:{type:`string`,default:process.env.AIKIT_TRANSPORT??`stdio`},port:{type:`string`,default:process.env.AIKIT_PORT??`3210`}}}):{values:{transport:process.env.AIKIT_TRANSPORT??`stdio`,port:process.env.AIKIT_PORT??`3210`}};async function p(){if(process.on(`unhandledRejection`,e=>{d.error(`Unhandled rejection`,c(e))}),d.info(`Starting MCP AI Kit server`,{version:u}),f.transport===`http`){let[{default:e},{loadConfig:t,resolveIndexMode:n},{registerDashboardRoutes:r,resolveDashboardDir:i},{registerSettingsRoutes:a,resolveSettingsDir:o},{createSettingsRouter:s}]=await Promise.all([import(`express`),import(`./config-C5IU9Lau.js`),import(`./dashboard-static-BfIe0Si1.js`),import(`./settings-static-BosGZSPf.js`),import(`./routes-0OCkdgRe.js`)]),l=t();d.info(`Config loaded`,{sourceCount:l.sources.length,storePath:l.store.path});let u=e();u.use(e.json());let p=Number(f.port);u.use((e,t,n)=>{if(t.setHeader(`Access-Control-Allow-Origin`,process.env.AIKIT_CORS_ORIGIN??`http://localhost:${p}`),t.setHeader(`Access-Control-Allow-Methods`,`GET, POST, PUT, PATCH, DELETE, OPTIONS`),t.setHeader(`Access-Control-Allow-Headers`,`Content-Type, Authorization`),e.method===`OPTIONS`){t.status(204).end();return}n()}),r(u,i(),d);let m=new Date().toISOString();u.use(`/settings/api`,s({log:d,mcpInfo:()=>({transport:`http`,port:p,pid:process.pid,startedAt:m})})),a(u,o(),d),u.get(`/health`,(e,t)=>{t.json({status:`ok`})});let h=!1,g=null,_=null,v=null,y=Promise.resolve();u.post(`/mcp`,async(e,t)=>{if(!h||!_||!v){t.status(503).json({jsonrpc:`2.0`,error:{code:-32603,message:`Server initializing — please retry in a few seconds`},id:null});return}let n=y,r;y=new Promise(e=>{r=e}),await n;try{let n=new v({sessionIdGenerator:void 0});await _.connect(n),await n.handleRequest(e,t,e.body),n.close()}catch(e){if(d.error(`MCP handler error`,c(e)),!t.headersSent){let n=e instanceof Error?e.message:String(e),r=n.includes(`Not Acceptable`);t.status(r?406:500).json({jsonrpc:`2.0`,error:{code:r?-32e3:-32603,message:r?n:`Internal server error`},id:null})}}finally{r()}}),u.get(`/mcp`,(e,t)=>{t.writeHead(405).end(JSON.stringify({jsonrpc:`2.0`,error:{code:-32e3,message:`Method not allowed.`},id:null}))}),u.delete(`/mcp`,(e,t)=>{t.writeHead(405).end(JSON.stringify({jsonrpc:`2.0`,error:{code:-32e3,message:`Method not allowed.`},id:null}))});let b=u.listen(p,`127.0.0.1`,()=>{d.info(`MCP server listening`,{url:`http://127.0.0.1:${p}/mcp`,port:p}),setTimeout(async()=>{try{let[{createLazyServer:e,ALL_TOOL_NAMES:t},{StreamableHTTPServerTransport:r},{checkForUpdates:i,autoUpgradeScaffold:a}]=await Promise.all([import(`./server-VgZC6Q43.js`),import(`@modelcontextprotocol/sdk/server/streamableHttp.js`),import(`./version-check-D4j0Pykd.js`)]);i(),a();let o=n(l),s=e(l,o);_=s.server,v=r,h=!0,d.info(`MCP server configured (lazy — AI Kit initializing in background)`,{toolCount:t.length,resourceCount:2}),s.startInit(),o===`auto`?s.ready.then(async()=>{try{let e=l.sources.map(e=>e.path).join(`, `);d.info(`Running initial index`,{sourcePaths:e}),await s.runInitialIndex(),d.info(`Initial index complete`)}catch(e){d.error(`Initial index failed; will retry on aikit_reindex`,c(e))}}).catch(e=>d.error(`AI Kit init or indexing failed`,c(e))):o===`smart`?s.ready.then(async()=>{try{if(!s.kb)throw Error(`AI Kit components are not available after initialization`);let{SmartIndexScheduler:e}=await import(`../../indexer/dist/index.js`);g=new e(s.kb.indexer,l,s.kb.store),g.start(),s.setSmartScheduler(g),d.info(`Smart index scheduler started (HTTP mode)`)}catch(e){d.error(`Failed to start smart index scheduler`,c(e))}}).catch(e=>d.error(`AI Kit initialization failed`,c(e))):(s.ready.catch(e=>d.error(`AI Kit initialization failed`,c(e))),d.info(`Initial full indexing skipped in HTTP mode`,{indexMode:o}))}catch(e){d.error(`Failed to load server modules`,c(e))}},100)}),x=async e=>{d.info(`Shutdown signal received`,{signal:e}),g?.stop(),b.close(),_&&await _.close(),process.exit(0)};process.on(`SIGINT`,()=>x(`SIGINT`)),process.on(`SIGTERM`,()=>x(`SIGTERM`))}else{let[{loadConfig:e,reconfigureForWorkspace:t,resolveIndexMode:n},{createLazyServer:r},{checkForUpdates:a,autoUpgradeScaffold:o},{RootsListChangedNotificationSchema:s}]=await Promise.all([import(`./config-C5IU9Lau.js`),import(`./server-VgZC6Q43.js`),import(`./version-check-D4j0Pykd.js`),import(`@modelcontextprotocol/sdk/types.js`)]),l=e();d.info(`Config loaded`,{sourceCount:l.sources.length,storePath:l.store.path}),a(),o();let u=n(l),f=r(l,u),{server:p,startInit:m,ready:h,runInitialIndex:g}=f,{StdioServerTransport:_}=await import(`@modelcontextprotocol/sdk/server/stdio.js`),v=new _;await p.connect(v),d.info(`MCP server started`,{transport:`stdio`});let y=e=>{if(e.length===0)return!1;let n=e[0].uri,r=n.startsWith(`file://`)?i(n):n;return d.info(`MCP roots resolved`,{rootUri:n,rootPath:r,rootCount:e.length}),t(l,r),!0},b=!1;try{b=y((await p.server.listRoots()).roots),b||d.info(`No MCP roots yet; waiting for roots/list_changed notification`)}catch(e){d.warn(`MCP roots/list not supported by client; using cwd fallback`,{cwd:process.cwd(),...c(e)}),b=!0}b||=await new Promise(e=>{let t=setTimeout(()=>{d.warn(`Timed out waiting for MCP roots/list_changed; using cwd fallback`,{cwd:process.cwd()}),e(!1)},5e3);p.server.setNotificationHandler(s,async()=>{clearTimeout(t);try{e(y((await p.server.listRoots()).roots))}catch(t){d.warn(`roots/list retry failed after notification`,c(t)),e(!1)}})}),m();let x=null,S=()=>{x&&clearTimeout(x),x=setTimeout(()=>{d.info(`Auto-shutdown: no activity for 30 minutes — exiting`),process.exit(0)},18e5),x.unref&&x.unref()};S(),process.stdin.on(`data`,()=>S()),h.catch(e=>{d.error(`Initialization failed — server will continue with limited tools`,c(e))}),u===`auto`?g().catch(e=>d.error(`Initial index failed`,c(e))):u===`smart`?h.then(async()=>{try{if(!f.kb)throw Error(`AI Kit components are not available after initialization`);let{SmartIndexScheduler:e}=await import(`../../indexer/dist/index.js`),t=new e(f.kb.indexer,l,f.kb.store);t.start(),f.setSmartScheduler(t),d.info(`Smart index scheduler started (stdio mode)`)}catch(e){d.error(`Failed to start smart index scheduler`,c(e))}}).catch(e=>d.error(`AI Kit init failed for smart scheduler`,c(e))):d.warn(`Initial full indexing skipped; use aikit_reindex to index manually`,{indexMode:u})}}p().catch(e=>{d.error(`Fatal error`,c(e)),process.exit(1)});export{e as CuratedKnowledgeManager};
1
+ import{t as e}from"./curated-manager-DX-_oJg0.js";import{readFileSync as t}from"node:fs";import{dirname as n,resolve as r}from"node:path";import{fileURLToPath as i,pathToFileURL as a}from"node:url";import{parseArgs as o}from"node:util";import{createLogger as s,serializeError as c}from"../../core/dist/index.js";const l=n(i(import.meta.url)),u=(()=>{try{let e=r(l,`..`,`..`,`..`,`package.json`);return JSON.parse(t(e,`utf-8`)).version??`0.0.0`}catch{return`0.0.0`}})(),d=s(`server`);function f(){return process.env.AIKIT_TRANSPORT?process.env.AIKIT_TRANSPORT:process.stdin.isTTY?`http`:`stdio`}const{values:p}=(()=>{let e=process.argv[1];if(!e)return!1;try{return import.meta.url===a(e).href}catch{return!1}})()?o({allowPositionals:!0,options:{transport:{type:`string`,default:f()},port:{type:`string`,default:process.env.AIKIT_PORT??`3210`}}}):{values:{transport:f(),port:process.env.AIKIT_PORT??`3210`}};async function m(){if(process.on(`unhandledRejection`,e=>{d.error(`Unhandled rejection`,c(e))}),d.info(`Starting MCP AI Kit server`,{version:u}),p.transport===`http`){let[{default:e},{loadConfig:t,resolveIndexMode:n},{registerDashboardRoutes:r,resolveDashboardDir:i},{registerSettingsRoutes:a,resolveSettingsDir:o},{createSettingsRouter:s}]=await Promise.all([import(`express`),import(`./config-C5IU9Lau.js`),import(`./dashboard-static-BfIe0Si1.js`),import(`./settings-static-BosGZSPf.js`),import(`./routes-0OCkdgRe.js`)]),l=t();d.info(`Config loaded`,{sourceCount:l.sources.length,storePath:l.store.path});let u=e();u.use(e.json());let f=Number(p.port);u.use((e,t,n)=>{if(t.setHeader(`Access-Control-Allow-Origin`,process.env.AIKIT_CORS_ORIGIN??`http://localhost:${f}`),t.setHeader(`Access-Control-Allow-Methods`,`GET, POST, PUT, PATCH, DELETE, OPTIONS`),t.setHeader(`Access-Control-Allow-Headers`,`Content-Type, Authorization`),e.method===`OPTIONS`){t.status(204).end();return}n()}),r(u,i(),d);let m=new Date().toISOString();u.use(`/settings/api`,s({log:d,mcpInfo:()=>({transport:`http`,port:f,pid:process.pid,startedAt:m})})),a(u,o(),d),u.get(`/health`,(e,t)=>{t.json({status:`ok`})});let h=!1,g=null,_=null,v=null,y=Promise.resolve();u.post(`/mcp`,async(e,t)=>{if(!h||!_||!v){t.status(503).json({jsonrpc:`2.0`,error:{code:-32603,message:`Server initializing — please retry in a few seconds`},id:null});return}let n=y,r;y=new Promise(e=>{r=e}),await n;try{let n=new v({sessionIdGenerator:void 0});await _.connect(n),await n.handleRequest(e,t,e.body),n.close()}catch(e){if(d.error(`MCP handler error`,c(e)),!t.headersSent){let n=e instanceof Error?e.message:String(e),r=n.includes(`Not Acceptable`);t.status(r?406:500).json({jsonrpc:`2.0`,error:{code:r?-32e3:-32603,message:r?n:`Internal server error`},id:null})}}finally{r()}}),u.get(`/mcp`,(e,t)=>{t.writeHead(405).end(JSON.stringify({jsonrpc:`2.0`,error:{code:-32e3,message:`Method not allowed.`},id:null}))}),u.delete(`/mcp`,(e,t)=>{t.writeHead(405).end(JSON.stringify({jsonrpc:`2.0`,error:{code:-32e3,message:`Method not allowed.`},id:null}))});let b=u.listen(f,`127.0.0.1`,()=>{d.info(`MCP server listening`,{url:`http://127.0.0.1:${f}/mcp`,port:f}),setTimeout(async()=>{try{let[{createLazyServer:e,ALL_TOOL_NAMES:t},{StreamableHTTPServerTransport:r},{checkForUpdates:i,autoUpgradeScaffold:a}]=await Promise.all([import(`./server-VgZC6Q43.js`),import(`@modelcontextprotocol/sdk/server/streamableHttp.js`),import(`./version-check-D4j0Pykd.js`)]);i(),a();let o=n(l),s=e(l,o);_=s.server,v=r,h=!0,d.info(`MCP server configured (lazy — AI Kit initializing in background)`,{toolCount:t.length,resourceCount:2}),s.startInit(),o===`auto`?s.ready.then(async()=>{try{let e=l.sources.map(e=>e.path).join(`, `);d.info(`Running initial index`,{sourcePaths:e}),await s.runInitialIndex(),d.info(`Initial index complete`)}catch(e){d.error(`Initial index failed; will retry on aikit_reindex`,c(e))}}).catch(e=>d.error(`AI Kit init or indexing failed`,c(e))):o===`smart`?s.ready.then(async()=>{try{if(!s.kb)throw Error(`AI Kit components are not available after initialization`);let{SmartIndexScheduler:e}=await import(`../../indexer/dist/index.js`);g=new e(s.kb.indexer,l,s.kb.store),g.start(),s.setSmartScheduler(g),d.info(`Smart index scheduler started (HTTP mode)`)}catch(e){d.error(`Failed to start smart index scheduler`,c(e))}}).catch(e=>d.error(`AI Kit initialization failed`,c(e))):(s.ready.catch(e=>d.error(`AI Kit initialization failed`,c(e))),d.info(`Initial full indexing skipped in HTTP mode`,{indexMode:o}))}catch(e){d.error(`Failed to load server modules`,c(e))}},100)}),x=async e=>{d.info(`Shutdown signal received`,{signal:e}),g?.stop(),b.close(),_&&await _.close(),process.exit(0)};process.on(`SIGINT`,()=>x(`SIGINT`)),process.on(`SIGTERM`,()=>x(`SIGTERM`))}else{let[{loadConfig:e,reconfigureForWorkspace:t,resolveIndexMode:n},{createLazyServer:r},{checkForUpdates:a,autoUpgradeScaffold:o},{RootsListChangedNotificationSchema:s}]=await Promise.all([import(`./config-C5IU9Lau.js`),import(`./server-VgZC6Q43.js`),import(`./version-check-D4j0Pykd.js`),import(`@modelcontextprotocol/sdk/types.js`)]),l=e();d.info(`Config loaded`,{sourceCount:l.sources.length,storePath:l.store.path}),a(),o();let u=n(l),f=r(l,u),{server:p,startInit:m,ready:h,runInitialIndex:g}=f,{StdioServerTransport:_}=await import(`@modelcontextprotocol/sdk/server/stdio.js`),v=new _;await p.connect(v),d.info(`MCP server started`,{transport:`stdio`});let y=e=>{if(e.length===0)return!1;let n=e[0].uri,r=n.startsWith(`file://`)?i(n):n;return d.info(`MCP roots resolved`,{rootUri:n,rootPath:r,rootCount:e.length}),t(l,r),!0},b=!1;try{b=y((await p.server.listRoots()).roots),b||d.info(`No MCP roots yet; waiting for roots/list_changed notification`)}catch(e){d.warn(`MCP roots/list not supported by client; using cwd fallback`,{cwd:process.cwd(),...c(e)}),b=!0}b||=await new Promise(e=>{let t=setTimeout(()=>{d.warn(`Timed out waiting for MCP roots/list_changed; using cwd fallback`,{cwd:process.cwd()}),e(!1)},5e3);p.server.setNotificationHandler(s,async()=>{clearTimeout(t);try{e(y((await p.server.listRoots()).roots))}catch(t){d.warn(`roots/list retry failed after notification`,c(t)),e(!1)}})}),m();let x=null,S=()=>{x&&clearTimeout(x),x=setTimeout(()=>{d.info(`Auto-shutdown: no activity for 30 minutes — exiting`),process.exit(0)},18e5),x.unref&&x.unref()};S(),process.stdin.on(`data`,()=>S()),h.catch(e=>{d.error(`Initialization failed — server will continue with limited tools`,c(e))}),u===`auto`?g().catch(e=>d.error(`Initial index failed`,c(e))):u===`smart`?h.then(async()=>{try{if(!f.kb)throw Error(`AI Kit components are not available after initialization`);let{SmartIndexScheduler:e}=await import(`../../indexer/dist/index.js`),t=new e(f.kb.indexer,l,f.kb.store);t.start(),f.setSmartScheduler(t),d.info(`Smart index scheduler started (stdio mode)`)}catch(e){d.error(`Failed to start smart index scheduler`,c(e))}}).catch(e=>d.error(`AI Kit init failed for smart scheduler`,c(e))):d.warn(`Initial full indexing skipped; use aikit_reindex to index manually`,{indexMode:u})}}m().catch(e=>{d.error(`Fatal error`,c(e)),process.exit(1)});export{e as CuratedKnowledgeManager};