@vpxa/aikit 0.1.210 → 0.1.212

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.210",
3
+ "version": "0.1.212",
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",
@@ -256,6 +256,12 @@ declare const WasmDiagnostics: {
256
256
  */
257
257
  /** All supported extensions. */
258
258
  declare const SUPPORTED_EXTENSIONS: Set<string>;
259
+ /**
260
+ * Find the package's own bundled wasm/ directory (always present in published package).
261
+ * Checks ONLY package-relative paths, NOT user cache.
262
+ * Used by heal to know where to copy FROM.
263
+ */
264
+ declare function findBundledWasmDir(): string | null;
259
265
  /**
260
266
  * Resolve the absolute path to a vendored .wasm grammar file for a given extension.
261
267
  * Returns null if the extension is not supported or the file doesn't exist.
@@ -452,6 +458,12 @@ declare class WasmRuntime {
452
458
  * parser and creating a fresh one.
453
459
  */
454
460
  private recoverParser;
461
+ /**
462
+ * Auto-populate the user WASM cache after successful init.
463
+ * This ensures future startups are instant even if the package install layout changes.
464
+ * Non-throwing - failures are logged but do not affect runtime.
465
+ */
466
+ private autoPopulateUserCache;
455
467
  /** Check if a grammar is available (loaded or loadable) for the given extension. */
456
468
  hasLanguage(ext: string): boolean;
457
469
  /** Check if a grammar is already loaded for the given extension. */
@@ -486,4 +498,4 @@ declare class WasmChunker implements IChunker {
486
498
  private singleChunk;
487
499
  }
488
500
  //#endregion
489
- export { type CallEdge as AstCallEdge, type CallEdge$1 as CallEdge, type CaptureInfo, CodeChunker, type EntryPoint, GenericChunker, type IChunker, type ImportInfo, MarkdownChunker, type PatternMatch, QueryExecutor, type QueryResult, type QueryType, SUPPORTED_EXTENSIONS, type ScopeInfo, type SymbolInfo, WasmChunker, type WasmDiagnosticInfo, WasmDiagnostics, type WasmLanguage, type WasmParser, type WasmParserModule, type WasmPoint, type WasmQuery, type WasmQueryCapture, type WasmQueryMatch, WasmRuntime, type WasmSyntaxNode, type WasmTree, createChunker, createChunkerSync, detectEntryPoints, detectPatterns, extractCallEdges, extractCalls, extractImports, extractSymbols, initializeWasm, resolveGrammarPath, resolveParserWasmPath, resolveScopes };
501
+ export { type CallEdge as AstCallEdge, type CallEdge$1 as CallEdge, type CaptureInfo, CodeChunker, type EntryPoint, GenericChunker, type IChunker, type ImportInfo, MarkdownChunker, type PatternMatch, QueryExecutor, type QueryResult, type QueryType, SUPPORTED_EXTENSIONS, type ScopeInfo, type SymbolInfo, WasmChunker, type WasmDiagnosticInfo, WasmDiagnostics, type WasmLanguage, type WasmParser, type WasmParserModule, type WasmPoint, type WasmQuery, type WasmQueryCapture, type WasmQueryMatch, WasmRuntime, type WasmSyntaxNode, type WasmTree, createChunker, createChunkerSync, detectEntryPoints, detectPatterns, extractCallEdges, extractCalls, extractImports, extractSymbols, findBundledWasmDir, initializeWasm, resolveGrammarPath, resolveParserWasmPath, resolveScopes };
@@ -1,4 +1,4 @@
1
- import{createRequire as e}from"node:module";import{dirname as t,extname as n,join as r}from"node:path";import{CHUNK_SIZES as i,createLogger as a}from"../../core/dist/index.js";import{copyFileSync as o,existsSync as s,mkdirSync as c,readFileSync as l,readdirSync as u,realpathSync as d,renameSync as ee}from"node:fs";import{homedir as f}from"node:os";import{fileURLToPath as p}from"node:url";function m(){return{mode:`unknown`,reason:``,pathsChecked:[],os:process.platform,arch:process.arch,nodeVersion:process.version,webTreeSitterImportable:!1,healAttempted:!1,healSuccess:!1,healError:null,initError:null,wasmDir:null,grammarCount:0}}let h=m();const g={get(){return{...h,pathsChecked:h.pathsChecked.map(e=>({...e}))}},update(e){Object.assign(h,e)},reset(){h=m()}},te=[`CI`,`GITHUB_ACTIONS`,`JENKINS_URL`,`GITLAB_CI`,`TF_BUILD`];function _(){return te.some(e=>!!process.env[e])}function v(){if(_())return g.update({healAttempted:!1,healSuccess:!1,healError:null,reason:`CI environment detected - skipping auto-heal`}),null;g.update({healAttempted:!0,healSuccess:!1,healError:null,reason:`Attempting to heal WASM cache from node_modules`});let n=r(f(),`.aikit`,`cache`,`wasm`);try{let i=e(import.meta.url),a;try{a=t(i.resolve(`web-tree-sitter/package.json`)),g.update({webTreeSitterImportable:!0})}catch{return g.update({webTreeSitterImportable:!1,healSuccess:!1,healError:`web-tree-sitter not found in node_modules`,reason:`Cannot heal WASM cache without web-tree-sitter runtime`}),null}let l;try{l=t(i.resolve(`tree-sitter-wasms/package.json`))}catch{return g.update({healSuccess:!1,healError:`tree-sitter-wasms not found in node_modules (devDependency only)`,reason:`Cannot heal WASM cache without tree-sitter-wasms package`}),null}c(n,{recursive:!0});function d(e,t){let n=`${t}.tmp-${process.pid}`;o(e,n),ee(n,t)}let f=r(a,`tree-sitter.wasm`);s(f)&&d(f,r(n,`tree-sitter.wasm`));let p=r(l,`out`),m=0;if(s(p)){let e=u(p).filter(e=>e.endsWith(`.wasm`));m=e.length;for(let t of e)d(r(p,t),r(n,t))}return s(r(n,`tree-sitter.wasm`))?(g.update({healSuccess:!0,healError:null,wasmDir:n,grammarCount:m,reason:`Healed WASM cache from node_modules`}),n):(g.update({healSuccess:!1,healError:`tree-sitter.wasm not found after copy`,reason:`WASM cache heal completed without parser runtime`}),null)}catch(e){return g.update({healSuccess:!1,healError:String(e),reason:`WASM cache heal failed`}),null}}const ne=t(p(import.meta.url));function y(e){try{return d(e)}catch{return e}}const b={".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`},x=new Set(Object.keys(b));let S;function C(e){return[...new Set(Object.values(b))].filter(t=>s(r(e,t))).length}function w(){let e=y(ne),t=[r(f(),`.aikit`,`cache`,`wasm`),r(e,`..`,`..`,`wasm`),r(e,`..`,`wasm`),r(process.cwd(),`node_modules`,`@aikit`,`chunker`,`wasm`)],n=[];for(let e of t){let t=y(e),i=s(r(t,`tree-sitter.wasm`));if(n.push({path:t,exists:i}),i)return g.update({mode:`wasm`,reason:`Resolved WASM directory`,pathsChecked:n,wasmDir:t,grammarCount:C(t),initError:null}),t}return g.update({mode:`unknown`,reason:`No WASM directory containing tree-sitter.wasm was found`,pathsChecked:n,wasmDir:null,grammarCount:0}),null}function T(){return S===void 0&&(S=w()),S}function E(e){S=e===null?null:y(e),g.update({mode:S?`wasm`:`unknown`,reason:S?`WASM directory overridden at runtime`:`WASM directory override cleared`,wasmDir:S,grammarCount:S?C(S):0})}function D(e){let t=b[e];if(!t)return null;let n=T();if(!n)return null;let i=r(n,t);return s(i)?i:null}function O(){let e=T();if(!e)return null;let t=r(e,`tree-sitter.wasm`);return s(t)?t:null}const k=a(`wasm-runtime`);async function A(){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 j=class e{static instance=null;parser=null;languages=new Map;loadedGrammars=new Map;recoveryAttempts=0;static MAX_RECOVERIES=3;static MAX_PARSE_SIZE=1e6;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;try{e=await A(),g.update({webTreeSitterImportable:!0})}catch(e){return g.update({webTreeSitterImportable:!1,mode:`regex`,reason:`web-tree-sitter import failed: ${String(e)}`,initError:String(e)}),k.warn(`web-tree-sitter module not importable`,{error:String(e)}),!1}let t=O();if(!t){k.info(`Parser WASM not found, attempting auto-heal...`);let e=v();e&&(E(e),t=O(),k.info(`Auto-heal succeeded`,{dir:e}))}if(!t)return g.update({mode:`regex`,reason:`Parser WASM file not found after heal attempt`}),k.warn(`Parser WASM file not found (auto-heal failed or skipped)`),!1;let n=t;return await e.init({locateFile:()=>n}),this.parser=new e,g.update({mode:`wasm`,reason:`WASM parser initialized successfully`,initError:null}),k.info(`WASM tree-sitter parser initialized`),!0}catch(e){return g.update({mode:`regex`,reason:`WASM initialization failed: ${String(e)}`,initError:String(e)}),k.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=D(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 A()).Language.load(n);return this.loadedGrammars.set(n,t),this.languages.set(e,t),k.debug(`Loaded grammar`,{ext:e}),t}catch(t){return k.warn(`Failed to load grammar`,{ext:e,error:String(t)}),null}}async parse(t,n){if(!this.parser)return null;if(t.length>e.MAX_PARSE_SIZE)return k.warn(`File too large for WASM parser, skipping`,{ext:n,size:t.length}),null;let r=await this.loadLanguage(n);if(!r)return null;try{return this.parser.setLanguage(r),this.parser.parse(t)}catch(r){if(k.warn(`WASM parser crashed, attempting recovery...`,{ext:n,error:String(r)}),this.recoveryAttempts>=e.MAX_RECOVERIES)return k.error(`WASM parser recovery limit reached, falling back to null`,{attempts:this.recoveryAttempts}),null;if(!await this.recoverParser(n))return k.error(`WASM parser recovery failed, falling back to null`),null;try{return this.parser?.parse(t)??null}catch(e){return k.error(`WASM parser crashed again after recovery, falling back to null`,{error:String(e)}),null}}}async recoverParser(e){this.recoveryAttempts++;try{this.parser?.delete(),this.parser=null,this.languages.clear(),this.loadedGrammars.clear();let t=await A(),n=O();if(!n)return k.error(`Cannot recover: parser WASM file not found`),!1;let r=n;await t.init({locateFile:()=>r}),this.parser=new t;let i=await this.loadLanguage(e);return i?(this.parser.setLanguage(i),k.info(`WASM parser recovered successfully`,{attempt:this.recoveryAttempts}),!0):(k.error(`Cannot recover: failed to reload language`,{ext:e}),!1)}catch(e){return k.error(`WASM parser recovery threw`,{error:String(e)}),!1}}hasLanguage(e){return x.has(e)}isLanguageLoaded(e){return this.languages.has(e)}getParser(){return this.parser}getLanguage(e){return this.languages.get(e)??null}};async function M(){return await j.initialize()!==null}const re=a(`call-graph`),ie=new Set([`function_declaration`,`method_definition`,`arrow_function`,`function_definition`,`function_declaration`,`method_declaration`,`function_item`,`method_declaration`,`constructor_declaration`]),ae=new Set([`call_expression`,`new_expression`,`call`]);function oe(e,t){let r=n(t).toLowerCase(),i=j.get();if(i?.isLanguageLoaded(r)){let n=i.getParser(),a=i.getLanguage(r);if(n&&a){n.setLanguage(a);let r;try{r=n.parse(e)}catch(e){return re.warn(`WASM parser.parse() crashed in call-graph extraction`,{file:t,error:String(e)}),null}if(r){let e=[];return N(r.rootNode,t,`<module>`,e),e}}}return null}function N(e,t,n,r){if(!e)return;let i=n;if(ie.has(e.type)&&(i=se(e)??n),ae.has(e.type)){let n=ce(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&&N(a,t,i,r)}}function se(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 ce(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 P=class{maxChunkSize;constructor(e){this.maxChunkSize=e?.maxChunkSize??i.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{createRequire as e}from"node:module";import{dirname as t,extname as n,join as r}from"node:path";import{CHUNK_SIZES as i,createLogger as a}from"../../core/dist/index.js";import{copyFileSync as o,existsSync as s,mkdirSync as c,readFileSync as l,readdirSync as u,realpathSync as d,renameSync as f}from"node:fs";import{homedir as p}from"node:os";import{fileURLToPath as m,pathToFileURL as ee}from"node:url";function h(){return{mode:`unknown`,reason:``,pathsChecked:[],os:process.platform,arch:process.arch,nodeVersion:process.version,webTreeSitterImportable:!1,healAttempted:!1,healSuccess:!1,healError:null,initError:null,wasmDir:null,grammarCount:0}}let g=h();const _={get(){return{...g,pathsChecked:g.pathsChecked.map(e=>({...e}))}},update(e){Object.assign(g,e)},reset(){g=h()}},v=t(m(import.meta.url));function y(e){try{return d(e)}catch{return e}}const b={".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`},x=new Set(Object.keys(b));let S;function C(e){return[...new Set(Object.values(b))].filter(t=>s(r(e,t))).length}function w(){let e=y(v),t=[r(e,`..`,`..`,`wasm`),r(e,`..`,`wasm`)];for(let e of t){let t=y(e);if(s(r(t,`tree-sitter.wasm`)))return t}return null}function T(){let e=y(v),t=[r(p(),`.aikit`,`cache`,`wasm`),r(e,`..`,`..`,`wasm`),r(e,`..`,`wasm`),r(process.cwd(),`node_modules`,`@aikit`,`chunker`,`wasm`)],n=[];for(let e of t){let t=y(e),i=s(r(t,`tree-sitter.wasm`));if(n.push({path:t,exists:i}),i)return _.update({mode:`wasm`,reason:`Resolved WASM directory`,pathsChecked:n,wasmDir:t,grammarCount:C(t),initError:null}),t}return _.update({mode:`unknown`,reason:`No WASM directory containing tree-sitter.wasm was found`,pathsChecked:n,wasmDir:null,grammarCount:0}),null}function E(){return S===void 0&&(S=T()),S}function D(e){S=e===null?null:y(e),_.update({mode:S?`wasm`:`unknown`,reason:S?`WASM directory overridden at runtime`:`WASM directory override cleared`,wasmDir:S,grammarCount:S?C(S):0})}function O(e){let t=b[e];if(!t)return null;let n=E();if(!n)return null;let i=r(n,t);return s(i)?i:null}function k(){let e=E();if(!e)return null;let t=r(e,`tree-sitter.wasm`);return s(t)?t:null}const te=[`CI`,`GITHUB_ACTIONS`,`JENKINS_URL`,`GITLAB_CI`,`TF_BUILD`];function ne(){return te.some(e=>!!process.env[e])}function A(e,t){let n=`${t}.tmp-${process.pid}`;o(e,n),f(n,t)}function j(e){let t=r(p(),`.aikit`,`cache`,`wasm`);try{c(t,{recursive:!0});let n=u(e).filter(e=>e.endsWith(`.wasm`)),i=0;for(let a of n){let n=r(e,a),o=r(t,a);s(o)||(A(n,o),i++)}if(s(r(t,`tree-sitter.wasm`))){let e=u(t).filter(e=>e.endsWith(`.wasm`)&&e!==`tree-sitter.wasm`).length;return _.update({healSuccess:!0,healError:null,wasmDir:t,grammarCount:e,reason:`Populated user WASM cache from bundled dir (${i} files copied)`}),t}return _.update({healSuccess:!1,healError:`tree-sitter.wasm not present in cache after copy`}),null}catch(e){return _.update({healSuccess:!1,healError:String(e),reason:`Failed to populate user WASM cache`}),null}}function M(){if(ne())return _.update({healAttempted:!1,healSuccess:!1,healError:null,reason:`CI environment detected - skipping auto-heal`}),null;_.update({healAttempted:!0,healSuccess:!1,healError:null,reason:`Attempting to heal WASM cache`});let n=w();if(n){let e=j(n);if(e)return e}try{let i=e(import.meta.url),a=r(p(),`.aikit`,`cache`,`wasm`),o;try{o=t(i.resolve(`web-tree-sitter/package.json`))}catch{return _.update({healSuccess:!1,healError:n?`Bundled copy failed and web-tree-sitter not in node_modules`:`Bundled WASM dir not found and web-tree-sitter not in node_modules`,reason:`Cannot heal WASM cache - no source available`}),null}let l;try{l=t(i.resolve(`tree-sitter-wasms/package.json`))}catch{c(a,{recursive:!0});let e=r(o,`tree-sitter.wasm`);return s(e)&&(A(e,r(a,`tree-sitter.wasm`)),s(r(a,`tree-sitter.wasm`)))?(_.update({healSuccess:!0,healError:null,wasmDir:a,grammarCount:0,reason:`Healed parser WASM from web-tree-sitter (no grammar wasms available)`}),a):(_.update({healSuccess:!1,healError:`tree-sitter-wasms not found (devDependency only)`,reason:`Cannot heal grammar WASM cache without tree-sitter-wasms package`}),null)}c(a,{recursive:!0});let d=r(o,`tree-sitter.wasm`);s(d)&&A(d,r(a,`tree-sitter.wasm`));let f=r(l,`out`),m=0;if(s(f)){let e=u(f).filter(e=>e.endsWith(`.wasm`));m=e.length;for(let t of e)A(r(f,t),r(a,t))}return s(r(a,`tree-sitter.wasm`))?(_.update({healSuccess:!0,healError:null,wasmDir:a,grammarCount:m,reason:`Healed WASM cache from node_modules (dev environment)`}),a):(_.update({healSuccess:!1,healError:`tree-sitter.wasm not found after copy`,reason:`WASM cache heal completed without parser runtime`}),null)}catch(e){return _.update({healSuccess:!1,healError:String(e),reason:`WASM cache heal failed`}),null}}const N=a(`wasm-runtime`);async function re(){try{return await import(`web-tree-sitter`)}catch{}try{return e(import.meta.url)(`web-tree-sitter`)}catch{}let n=t(m(import.meta.url)),i=[r(n,`..`,`node_modules`,`web-tree-sitter`,`tree-sitter.js`),r(n,`..`,`..`,`..`,`..`,`web-tree-sitter`,`tree-sitter.js`),r(n,`..`,`..`,`..`,`..`,`..`,`node_modules`,`web-tree-sitter`,`tree-sitter.js`)];for(let e of i)if(s(e))try{return await import(ee(e).href)}catch{}throw Error(`web-tree-sitter module not found. Tried: ESM import, createRequire, and path-based resolution from ${n}`)}async function P(){let e=await re(),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 F=class e{static instance=null;parser=null;languages=new Map;loadedGrammars=new Map;recoveryAttempts=0;static MAX_RECOVERIES=3;static MAX_PARSE_SIZE=1e6;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;try{e=await P(),_.update({webTreeSitterImportable:!0})}catch(e){return _.update({webTreeSitterImportable:!1,mode:`regex`,reason:`web-tree-sitter import failed: ${String(e)}`,initError:String(e)}),N.warn(`web-tree-sitter module not importable`,{error:String(e)}),!1}let t=k();if(!t){N.info(`Parser WASM not found, attempting auto-heal...`);let e=M();e&&(D(e),t=k(),N.info(`Auto-heal succeeded`,{dir:e}))}if(!t)return _.update({mode:`regex`,reason:`Parser WASM file not found after heal attempt`}),N.warn(`Parser WASM file not found (auto-heal failed or skipped)`),!1;let n=t;return await e.init({locateFile:()=>n}),this.parser=new e,this.autoPopulateUserCache(),_.update({mode:`wasm`,reason:`WASM parser initialized successfully`,initError:null}),N.info(`WASM tree-sitter parser initialized`),!0}catch(e){return _.update({mode:`regex`,reason:`WASM initialization failed: ${String(e)}`,initError:String(e)}),N.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=O(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 P()).Language.load(n);return this.loadedGrammars.set(n,t),this.languages.set(e,t),N.debug(`Loaded grammar`,{ext:e}),t}catch(t){return N.warn(`Failed to load grammar`,{ext:e,error:String(t)}),null}}async parse(t,n){if(!this.parser)return null;if(t.length>e.MAX_PARSE_SIZE)return N.warn(`File too large for WASM parser, skipping`,{ext:n,size:t.length}),null;let r=await this.loadLanguage(n);if(!r)return null;try{return this.parser.setLanguage(r),this.parser.parse(t)}catch(r){if(N.warn(`WASM parser crashed, attempting recovery...`,{ext:n,error:String(r)}),this.recoveryAttempts>=e.MAX_RECOVERIES)return N.error(`WASM parser recovery limit reached, falling back to null`,{attempts:this.recoveryAttempts}),null;if(!await this.recoverParser(n))return N.error(`WASM parser recovery failed, falling back to null`),null;try{return this.parser?.parse(t)??null}catch(e){return N.error(`WASM parser crashed again after recovery, falling back to null`,{error:String(e)}),null}}}async recoverParser(e){this.recoveryAttempts++;try{this.parser?.delete(),this.parser=null,this.languages.clear(),this.loadedGrammars.clear();let t=await P(),n=k();if(!n)return N.error(`Cannot recover: parser WASM file not found`),!1;let r=n;await t.init({locateFile:()=>r}),this.parser=new t;let i=await this.loadLanguage(e);return i?(this.parser.setLanguage(i),N.info(`WASM parser recovered successfully`,{attempt:this.recoveryAttempts}),!0):(N.error(`Cannot recover: failed to reload language`,{ext:e}),!1)}catch(e){return N.error(`WASM parser recovery threw`,{error:String(e)}),!1}}autoPopulateUserCache(){try{if(s(r(r(p(),`.aikit`,`cache`,`wasm`),`tree-sitter.wasm`)))return;let e=w();if(!e)return;N.info(`Auto-populating user WASM cache for future reliability`,{from:e}),j(e)}catch(e){N.debug(`Auto-populate user cache failed (non-fatal)`,{error:String(e)})}}hasLanguage(e){return x.has(e)}isLanguageLoaded(e){return this.languages.has(e)}getParser(){return this.parser}getLanguage(e){return this.languages.get(e)??null}};async function I(){return await F.initialize()!==null}const ie=a(`call-graph`),ae=new Set([`function_declaration`,`method_definition`,`arrow_function`,`function_definition`,`function_declaration`,`method_declaration`,`function_item`,`method_declaration`,`constructor_declaration`]),oe=new Set([`call_expression`,`new_expression`,`call`]);function se(e,t){let r=n(t).toLowerCase(),i=F.get();if(i?.isLanguageLoaded(r)){let n=i.getParser(),a=i.getLanguage(r);if(n&&a){n.setLanguage(a);let r;try{r=n.parse(e)}catch(e){return ie.warn(`WASM parser.parse() crashed in call-graph extraction`,{file:t,error:String(e)}),null}if(r){let e=[];return L(r.rootNode,t,`<module>`,e),e}}}return null}function L(e,t,n,r){if(!e)return;let i=n;if(ae.has(e.type)&&(i=ce(e)??n),oe.has(e.type)){let n=le(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&&L(a,t,i,r)}}function ce(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 le(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 R=class{maxChunkSize;constructor(e){this.maxChunkSize=e?.maxChunkSize??i.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{createRequire as e}from"node:module";import{dirname as t,extname as n,joi
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}},F=class{maxChunkSize;overlap;constructor(e){this.maxChunkSize=e?.maxChunkSize??i.default.max,this.overlap=e?.overlap??i.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}},z=class{maxChunkSize;overlap;constructor(e){this.maxChunkSize=e?.maxChunkSize??i.default.max,this.overlap=e?.overlap??i.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}))}},I=class{maxChunkSize;minChunkSize;constructor(e){this.maxChunkSize=e?.maxChunkSize??i.markdown.max,this.minChunkSize=e?.minChunkSize??i.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}))}},B=class{maxChunkSize;minChunkSize;constructor(e){this.maxChunkSize=e?.maxChunkSize??i.markdown.max,this.minChunkSize=e?.minChunkSize??i.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 L=a(`wasm-chunker`),R=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`]),z=new Set([`import_statement`,`import_from_statement`,`import_declaration`,`package_declaration`,`use_declaration`,`extern_crate_declaration`,`import_spec`,`package_clause`]);var B=class{maxChunkSize;constructor(e){this.maxChunkSize=e?.maxChunkSize??i.code.max}chunk(e,t){let n=j.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;try{o=a.parse(e)}catch(n){return L.warn(`WASM parser.parse() crashed, falling back to single chunk`,{path:t.sourcePath,error:String(n)}),this.singleChunk(e,t)}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=R.has(t.type),r=z.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 V=a(`wasm-chunker`),H=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`]),U=new Set([`import_statement`,`import_from_statement`,`import_declaration`,`package_declaration`,`use_declaration`,`extern_crate_declaration`,`import_spec`,`package_clause`]);var W=class{maxChunkSize;constructor(e){this.maxChunkSize=e?.maxChunkSize??i.code.max}chunk(e,t){let n=F.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;try{o=a.parse(e)}catch(n){return V.warn(`WASM parser.parse() crashed, falling back to single chunk`,{path:t.sourcePath,error:String(n)}),this.singleChunk(e,t)}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=H.has(t.type),r=U.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 V(e){let t=e.toLowerCase();switch(t){case`.md`:case`.mdx`:return new I;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(x.has(t)){let e=await j.initialize();if(e)return await e.loadLanguage(t),new B}return new P;default:return new F}}function H(e){let t=e.toLowerCase();switch(t){case`.md`:case`.mdx`:return new I;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 j.get()?.isLanguageLoaded(t)?new B:new P;default:return new F}}const U=a(`query-executor`),W=t(p(import.meta.url));function G(e=W){let t=[r(e,`..`,`queries`),r(e,`..`,`src`,`queries`)];for(let e of t)if(s(e))return e;return t[0]}const K=G(),le={".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 q=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=>J(e)):[]}executeCaptures(e,t,n,r){let i=this.getOrCompile(t,n,r);return i?i.captures(e).map(e=>Y(e)):[]}executeRaw(e,t,n){return t.query(n).matches(e).map(e=>J(e))}getOrCompile(e,t,n){let r=le[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 U.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 n=`${e}:${t}`,i=this.scmCache.get(n);if(i!==void 0)return i;let a=r(K,e,`${t}.scm`);try{let e=l(a,`utf-8`);return this.scmCache.set(n,e),e}catch{return U.info(`Query file not found (graceful skip)`,{langDir:e,queryType:t}),this.scmCache.set(n,``),null}}dispose(){this.queryCache.clear(),this.scmCache.clear()}static resolveQueryDir(e){return r(K,e)}};function J(e){let t=new Map;for(let n of e.captures)t.set(n.name,Y(n));return{pattern:e.pattern,captures:t}}function Y(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 ue=a(`call-extractor`),de=new q,fe=new Set([`function_declaration`,`method_definition`,`arrow_function`,`function_definition`,`method_declaration`,`constructor_declaration`,`function_declaration`,`method_declaration`,`function_item`]);async function pe(e,t,n=``){let r=await j.ensure(),i;try{i=await r.parse(e,t)}catch(e){return ue.warn(`WASM parse failed in call extraction`,{ext:t,error:String(e)}),[]}if(!i)return[];let a=r.getLanguage(t);return a?de.execute(i.rootNode,a,t,`calls`).map(e=>me(e,i.rootNode,n)).filter(e=>e!==null):[]}function me(e,t,n){let r=e.captures.get(`callee`);if(!r)return null;let i=e.captures.get(`node`);return{callerFile:n,callerName:he(i?.node??r.node),calleeName:r.text,line:(i?.startLine??r.startLine)+1}}function he(e){let t=e.parent;for(;t;){if(fe.has(t.type)){let e=ge(t);if(e)return e}t=t.parent}return`<module>`}function ge(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 _e=a(`entry-point-detector`),ve=new q,ye={handler:`lambda-handler`,lambdaHandler:`lambda-handler`,main:`main`,__name__:`main`,app:`server`,server:`server`,router:`server`,urlpatterns:`server`,init:`main`},be={SpringBootApplication:`server`,RestController:`server`,Controller:`server`};async function X(e,t,n=``){let r=await j.ensure(),i;try{i=await r.parse(e,t)}catch(e){return _e.warn(`WASM parse failed in entry-point detection`,{ext:t,error:String(e)}),[]}if(!i)return[];let a=r.getLanguage(t);if(!a)return[];let o=ve.execute(i.rootNode,a,t,`entry-points`),s=[],c=new Set;for(let e of o){let r=xe(e,t,n);if(r){let e=`${r.name}:${r.type}`;c.has(e)||(c.add(e),s.push(r))}}return s}function xe(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=be[o.text];if(e)return{name:i,type:e,filePath:n}}let s=ye[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 Se=new q;async function Ce(e,t,n=``){let r=await j.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,`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=Ee(r.text,t);e&&s.push({source:e.source,specifiers:e.specifiers,filePath:n,isExternal:Z(e.source,t),confidence:`high`})}continue}let i=r.text,a=we(i,t),o=Te(e.captures.get(`node`)?.text??``,t,a);s.push({source:a,specifiers:o,filePath:n,isExternal:Z(a,t),confidence:`high`})}return s}function we(e,t){let n=e.replace(/^['"`]|['"`]$/g,``);return t===`.go`&&(n=n.replace(/^"|"$/g,``)),n}function Z(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 Te(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 Ee(e,t){if(t===`.py`){let t=e.match(/^import\s+([\w.]+)/);if(t)return{source:t[1],specifiers:[t[1]]}}return null}const De=a(`pattern-detector`),Oe=new q;async function ke(e,t,n=``){let r=await j.ensure(),i;try{i=await r.parse(e,t)}catch(e){return De.warn(`WASM parse failed in pattern detection`,{ext:t,error:String(e)}),[]}if(!i)return[];let a=r.getLanguage(t);if(!a)return[];let o=Oe.execute(i.rootNode,a,t,`patterns`),s=new Map;for(let e of o){let r=Ae(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 Ae(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 je=a(`scope-resolver`),Me=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 Ne(e,t,n){let r=await j.ensure(),i;try{i=await r.parse(e,t)}catch(e){return je.warn(`WASM parse failed in scope resolution`,{ext:t,error:String(e)}),[{name:`<module>`,type:`module`,line:1}]}if(!i)return[{name:`<module>`,type:`module`,line:1}];let a=Pe(i.rootNode,n-1);if(!a)return[{name:`<module>`,type:`module`,line:1}];let o=[];return Fe(a,o),o.push({name:`<module>`,type:`module`,line:1}),o}function Pe(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 Fe(e,t){let n=e.parent;for(;n;){if(Me.has(n.type)){let e=Ie(n),r=Le(n.type);t.push({name:e??`<anonymous>`,type:r,line:n.startPosition.row+1})}n=n.parent}}function Ie(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 Le(e){return e.includes(`class`)||e===`impl_item`?`class`:`function`}const Re=a(`symbol-extractor`),ze=new q,Be={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 j.ensure(),i;try{i=await r.parse(e,t)}catch(e){return Re.warn(`WASM parse failed in symbol extraction`,{ext:t,error:String(e)}),[]}if(!i)return[];let a=r.getLanguage(t);return a?He(ze.execute(i.rootNode,a,t,`symbols`),t,n):[]}function He(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=Ue(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=Be[o?.nodeType??r.nodeType]??`variable`,c=(o?.startLine??r.startLine)+1,l=We(s,o?.node,t),u=o?.node??r.node;i.push({name:r.text,kind:l,exported:a,filePath:n,line:c,signature:Ge(o?.node,l),returnType:Ye(o?.node,l),jsdoc:Xe(u),decorators:Ze(u),typeBody:Qe(o?.node,l)})}return i}function Ue(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 We(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 Ge(e,t){if(e){if(t===`function`||t===`method`)return Ke(e);if(t===`class`)return qe(e);if(t===`interface`)return Je(e)}}function Ke(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 qe(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 Je(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 Ye(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 Xe(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 ue(e){let t=e.toLowerCase();switch(t){case`.md`:case`.mdx`:return new B;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(x.has(t)){let e=await F.initialize();if(e)return await e.loadLanguage(t),new W}return new R;default:return new z}}function de(e){let t=e.toLowerCase();switch(t){case`.md`:case`.mdx`:return new B;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 F.get()?.isLanguageLoaded(t)?new W:new R;default:return new z}}const G=a(`query-executor`),fe=t(m(import.meta.url));function pe(e=fe){let t=[r(e,`..`,`queries`),r(e,`..`,`src`,`queries`)];for(let e of t)if(s(e))return e;return t[0]}const K=pe(),me={".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 q=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=>J(e)):[]}executeCaptures(e,t,n,r){let i=this.getOrCompile(t,n,r);return i?i.captures(e).map(e=>Y(e)):[]}executeRaw(e,t,n){return t.query(n).matches(e).map(e=>J(e))}getOrCompile(e,t,n){let r=me[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 G.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 n=`${e}:${t}`,i=this.scmCache.get(n);if(i!==void 0)return i;let a=r(K,e,`${t}.scm`);try{let e=l(a,`utf-8`);return this.scmCache.set(n,e),e}catch{return G.info(`Query file not found (graceful skip)`,{langDir:e,queryType:t}),this.scmCache.set(n,``),null}}dispose(){this.queryCache.clear(),this.scmCache.clear()}static resolveQueryDir(e){return r(K,e)}};function J(e){let t=new Map;for(let n of e.captures)t.set(n.name,Y(n));return{pattern:e.pattern,captures:t}}function Y(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 he=a(`call-extractor`),ge=new q,_e=new Set([`function_declaration`,`method_definition`,`arrow_function`,`function_definition`,`method_declaration`,`constructor_declaration`,`function_declaration`,`method_declaration`,`function_item`]);async function ve(e,t,n=``){let r=await F.ensure(),i;try{i=await r.parse(e,t)}catch(e){return he.warn(`WASM parse failed in call extraction`,{ext:t,error:String(e)}),[]}if(!i)return[];let a=r.getLanguage(t);return a?ge.execute(i.rootNode,a,t,`calls`).map(e=>ye(e,i.rootNode,n)).filter(e=>e!==null):[]}function ye(e,t,n){let r=e.captures.get(`callee`);if(!r)return null;let i=e.captures.get(`node`);return{callerFile:n,callerName:be(i?.node??r.node),calleeName:r.text,line:(i?.startLine??r.startLine)+1}}function be(e){let t=e.parent;for(;t;){if(_e.has(t.type)){let e=xe(t);if(e)return e}t=t.parent}return`<module>`}function xe(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 Se=a(`entry-point-detector`),X=new q,Ce={handler:`lambda-handler`,lambdaHandler:`lambda-handler`,main:`main`,__name__:`main`,app:`server`,server:`server`,router:`server`,urlpatterns:`server`,init:`main`},we={SpringBootApplication:`server`,RestController:`server`,Controller:`server`};async function Te(e,t,n=``){let r=await F.ensure(),i;try{i=await r.parse(e,t)}catch(e){return Se.warn(`WASM parse failed in entry-point detection`,{ext:t,error:String(e)}),[]}if(!i)return[];let a=r.getLanguage(t);if(!a)return[];let o=X.execute(i.rootNode,a,t,`entry-points`),s=[],c=new Set;for(let e of o){let r=Ee(e,t,n);if(r){let e=`${r.name}:${r.type}`;c.has(e)||(c.add(e),s.push(r))}}return s}function Ee(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=we[o.text];if(e)return{name:i,type:e,filePath:n}}let s=Ce[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 De=new q;async function Oe(e,t,n=``){let r=await F.ensure(),i=await r.parse(e,t);if(!i)return[];let a=r.getLanguage(t);if(!a)return[];let o=De.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=je(r.text,t);e&&s.push({source:e.source,specifiers:e.specifiers,filePath:n,isExternal:Z(e.source,t),confidence:`high`})}continue}let i=r.text,a=ke(i,t),o=Ae(e.captures.get(`node`)?.text??``,t,a);s.push({source:a,specifiers:o,filePath:n,isExternal:Z(a,t),confidence:`high`})}return s}function ke(e,t){let n=e.replace(/^['"`]|['"`]$/g,``);return t===`.go`&&(n=n.replace(/^"|"$/g,``)),n}function Z(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 je(e,t){if(t===`.py`){let t=e.match(/^import\s+([\w.]+)/);if(t)return{source:t[1],specifiers:[t[1]]}}return null}const Me=a(`pattern-detector`),Ne=new q;async function Pe(e,t,n=``){let r=await F.ensure(),i;try{i=await r.parse(e,t)}catch(e){return Me.warn(`WASM parse failed in pattern detection`,{ext:t,error:String(e)}),[]}if(!i)return[];let a=r.getLanguage(t);if(!a)return[];let o=Ne.execute(i.rootNode,a,t,`patterns`),s=new Map;for(let e of o){let r=Fe(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 Fe(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 Ie=a(`scope-resolver`),Le=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 Re(e,t,n){let r=await F.ensure(),i;try{i=await r.parse(e,t)}catch(e){return Ie.warn(`WASM parse failed in scope resolution`,{ext:t,error:String(e)}),[{name:`<module>`,type:`module`,line:1}]}if(!i)return[{name:`<module>`,type:`module`,line:1}];let a=ze(i.rootNode,n-1);if(!a)return[{name:`<module>`,type:`module`,line:1}];let o=[];return Be(a,o),o.push({name:`<module>`,type:`module`,line:1}),o}function ze(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 Be(e,t){let n=e.parent;for(;n;){if(Le.has(n.type)){let e=Ve(n),r=He(n.type);t.push({name:e??`<anonymous>`,type:r,line:n.startPosition.row+1})}n=n.parent}}function Ve(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 Ue=a(`symbol-extractor`),We=new q,Ge={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 Ke(e,t,n=``){let r=await F.ensure(),i;try{i=await r.parse(e,t)}catch(e){return Ue.warn(`WASM parse failed in symbol extraction`,{ext:t,error:String(e)}),[]}if(!i)return[];let a=r.getLanguage(t);return a?qe(We.execute(i.rootNode,a,t,`symbols`),t,n):[]}function qe(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=Je(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=Ge[o?.nodeType??r.nodeType]??`variable`,c=(o?.startLine??r.startLine)+1,l=Ye(s,o?.node,t),u=o?.node??r.node;i.push({name:r.text,kind:l,exported:a,filePath:n,line:c,signature:Xe(o?.node,l),returnType:et(o?.node,l),jsdoc:tt(u),decorators:nt(u),typeBody:rt(o?.node,l)})}return i}function Je(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 Ye(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 Xe(e,t){if(e){if(t===`function`||t===`method`)return Ze(e);if(t===`class`)return Qe(e);if(t===`interface`)return $e(e)}}function Ze(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 Qe(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 $e(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 et(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 tt(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 Ze(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 Qe(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{P as CodeChunker,F as GenericChunker,I as MarkdownChunker,q as QueryExecutor,x as SUPPORTED_EXTENSIONS,B as WasmChunker,g as WasmDiagnostics,j as WasmRuntime,V as createChunker,H as createChunkerSync,X as detectEntryPoints,ke as detectPatterns,oe as extractCallEdges,pe as extractCalls,Ce as extractImports,Ve as extractSymbols,M as initializeWasm,D as resolveGrammarPath,O as resolveParserWasmPath,Ne as resolveScopes};
24
+ `)[0]?.trim()?.slice(0,200)||void 0}}}function nt(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 rt(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{R as CodeChunker,z as GenericChunker,B as MarkdownChunker,q as QueryExecutor,x as SUPPORTED_EXTENSIONS,W as WasmChunker,_ as WasmDiagnostics,F as WasmRuntime,ue as createChunker,de as createChunkerSync,Te as detectEntryPoints,Pe as detectPatterns,se as extractCallEdges,ve as extractCalls,Oe as extractImports,Ke as extractSymbols,w as findBundledWasmDir,I as initializeWasm,O as resolveGrammarPath,k as resolveParserWasmPath,Re as resolveScopes};
@@ -17,6 +17,6 @@ Edges:`);for(let e of f.edges){let t=e.weight===1?``:` (weight: ${e.weight})`;co
17
17
  `:`🧹 Pruning storage...
18
18
  `);let c=await t({dryRun:i,maxAgeDays:s});console.log(`Results:`),console.log(` Forge-ground orphans: ${c.forgeGroundOrphans.count} dirs (${n(c.forgeGroundOrphans.bytesFreed)})`),console.log(` Legacy LanceDB: ${c.legacyLance.count} dirs (${n(c.legacyLance.bytesFreed)})`),console.log(` Empty ephemeral dirs: ${c.emptyEphemeral.count} dirs`),console.log(` Stale partitions: ${c.stalePartitions.count} dirs (${n(c.stalePartitions.bytesFreed)})`),console.log(` Browser profiles: ${c.browserProfiles.count} dirs (${n(c.browserProfiles.bytesFreed)})`),console.log(`\n Total freed: ${n(c.totalBytesFreed)}`),i||(r(),console.log(`
19
19
  ✅ Cleanup complete.`))}},{name:`audit`,description:`Run a unified project audit (structure, deps, patterns, health, dead symbols, check)`,usage:`aikit audit [path] [--checks structure,dependencies,patterns,health,dead_symbols,check,entry_points] [--detail efficient|normal|full]`,run:async e=>{let{store:t,embedder:n}=await Q(),r=y(e,`--detail`,`efficient`)||`efficient`,i=y(e,`--checks`,``),a=i?i.split(`,`).map(e=>e.trim()):void 0,o=await ve(t,n,{path:e.shift()||`.`,checks:a,detail:r});if(o.ok){if(console.log(o.summary),o.next&&o.next.length>0){console.log(`
20
- Suggested next steps:`);for(let e of o.next)console.log(` → ${e.tool}: ${e.reason}`)}}else console.error(o.error?.message??`Audit failed`),process.exitCode=1}},{name:`guide`,description:`Tool discovery — recommend AI Kit tools for a given goal`,usage:`aikit guide <goal> [--max N]`,run:async e=>{let t=e.indexOf(`--max`),n=5;t!==-1&&t+1<e.length&&(n=Number.parseInt(e.splice(t,2)[1],10)||5);let r=e.join(` `).trim();r||(console.error(`Usage: aikit guide <goal> [--max N]`),console.error(`Example: aikit guide "audit this project"`),process.exit(1));let i=ze(r,n);console.log(`Workflow: ${i.workflow}`),console.log(` ${i.description}\n`),console.log(`Recommended tools:`);for(let e of i.tools){let t=e.suggestedArgs?` ${JSON.stringify(e.suggestedArgs)}`:``;console.log(` ${e.order}. ${e.tool} — ${e.reason}${t}`)}i.alternativeWorkflows.length>0&&console.log(`\nAlternatives: ${i.alternativeWorkflows.join(`, `)}`)}},{name:`replay`,description:`Show recent tool invocation audit trail`,usage:`aikit replay [--last N] [--tool <name>] [--source mcp|cli]`,run:async e=>{let t=ft({last:Number.parseInt(e[e.indexOf(`--last`)+1],10)||20,tool:e.includes(`--tool`)?e[e.indexOf(`--tool`)+1]:void 0,source:e.includes(`--source`)?e[e.indexOf(`--source`)+1]:void 0});if(t.length===0){console.log(`No replay entries. Activity is logged when tools are invoked.`);return}console.log(`Replay Log (${t.length} entries)\n`);for(let e of t){let t=e.ts.split(`T`)[1]?.split(`.`)[0]??e.ts,n=e.status===`ok`?`✓`:`✗`;console.log(`${t} ${n} ${e.tool} (${e.durationMs}ms) [${e.source}]`),console.log(` in: ${e.input}`),console.log(` out: ${e.output}`)}pt().catch(()=>{})}},{name:`replay-clear`,description:`Clear the replay audit trail`,run:async()=>{dt(),console.log(`Replay log cleared.`)}},{name:`dashboard`,description:`Launch web dashboard for knowledge graph visualization`,usage:`aikit dashboard [--port <port>] [--no-open]`,run:async e=>{let t=e.indexOf(`--port`),n=t!==-1&&e[t+1]?Number.parseInt(e[t+1],10):3210,r=Number.isFinite(n)?n:3210,i=e.includes(`--no-open`);console.log(`Starting AI Kit server on port ${r}...`);let{spawn:a}=await import(`node:child_process`),{platform:o}=await import(`node:os`),s=w(),c=a(process.execPath,[s,`--transport`,`http`,`--port`,String(r)],{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env,AIKIT_TRANSPORT:`http`,AIKIT_PORT:String(r)}}),l=`http://localhost:${r}/_dashboard/`,u=`http://localhost:${r}/health`,d=!1;for(let e=0;e<30;e+=1){try{if((await fetch(u)).ok){d=!0;break}}catch{}await new Promise(e=>setTimeout(e,1e3))}if(d||(console.error(`Server failed to start within 30 seconds.`),c.kill(),process.exit(1)),console.log(`AI Kit Dashboard: ${l}`),console.log(`Press Ctrl+C to stop.`),!i){let e=o();e===`win32`?a(`cmd`,[`/c`,`start`,``,l],{stdio:`ignore`,detached:!0}).unref():a(e===`darwin`?`open`:`xdg-open`,[l],{stdio:`ignore`,detached:!0}).unref()}let f=()=>{c.kill(),process.exit(0)};process.on(`SIGINT`,f),process.on(`SIGTERM`,f),await new Promise(e=>{c.on(`exit`,()=>e())})}},{name:`settings`,description:`Launch web UI to manage AI Kit configuration and environment variables`,usage:`aikit settings [--port <port>] [--no-open]`,run:async e=>{let t=e.indexOf(`--port`),n=t!==-1&&e[t+1]?Number.parseInt(e[t+1],10):3210,r=Number.isFinite(n)?n:3210,i=e.includes(`--no-open`);console.log(`Starting AI Kit server on port ${r}...`);let{spawn:a}=await import(`node:child_process`),{platform:o}=await import(`node:os`),s=w(),c=a(process.execPath,[s,`--transport`,`http`,`--port`,String(r)],{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env,AIKIT_TRANSPORT:`http`,AIKIT_PORT:String(r)}}),l=`http://localhost:${r}/settings/`,u=`http://localhost:${r}/health`,d=!1;for(let e=0;e<30;e+=1){try{if((await fetch(u)).ok){d=!0;break}}catch{}await new Promise(e=>setTimeout(e,1e3))}if(d||(console.error(`Server failed to start within 30 seconds.`),c.kill(),process.exit(1)),console.log(`AI Kit Settings: ${l}`),console.log(`Press Ctrl+C to stop.`),!i){let e=o();e===`win32`?a(`cmd`,[`/c`,`start`,``,l],{stdio:`ignore`,detached:!0}).unref():a(e===`darwin`?`open`:`xdg-open`,[l],{stdio:`ignore`,detached:!0}).unref()}let f=()=>{c.kill(),process.exit(0)};process.on(`SIGINT`,f),process.on(`SIGTERM`,f),await new Promise(e=>{c.on(`exit`,()=>e())})}}],ar=[{name:`upgrade`,description:`Upgrade AI Kit agents, prompts, and skills to the latest version (user-level and workspace-level)`,usage:`aikit upgrade`,run:async()=>{await J({force:!0});let e=process.cwd(),t=A(L(e,`.github`,`.aikit-scaffold.json`)),n=A(L(e,`.github`,`agents`)),r=A(L(e,`.github`,`prompts`)),i=A(L(e,`.claude`,`commands`));if(t||n||r||i){let{initScaffoldOnly:e}=await import(`./init-CYp6FjZO.js`);await e({force:!0})}if(A(L(e,`.github`,`skills`))){let{smartCopySkills:t}=await import(`./scaffold-BdUnq1xy.js`).then(e=>e.a),n=ie(),r=te();await t(e,n,[...re],r,!0);let{smartCopyFlows:i}=await import(`./scaffold-BdUnq1xy.js`).then(e=>e.a);await i(e,n,[...ae],r,!0)}let{homedir:a}=await import(`node:os`),{rmSync:o}=await import(`node:fs`),s=F(a(),`.aikit`,`cache`,`wasm`);if(A(s))try{o(s,{recursive:!0,force:!0}),console.log(`✓ WASM cache cleared (will re-resolve on next start)`)}catch{console.warn(`⚠ Could not clear WASM cache at`,s)}}}],or=[{name:`workset`,description:`Manage saved file sets`,usage:`aikit workset <action> [name] [--files f1,f2] [--description desc]`,run:async e=>{let t=e.shift()?.trim(),n=f(y(e,`--files`,``)),r=y(e,`--description`,``).trim()||void 0,i=e.shift()?.trim();switch(t||(console.error(`Usage: aikit workset <action> [name] [--files f1,f2] [--description desc]`),console.error(`Actions: save, get, list, delete, add, remove`),process.exit(1)),t){case`save`:{(!i||n.length===0)&&(console.error(`Usage: aikit workset save <name> --files f1,f2 [--description desc]`),process.exit(1));let e=mt(i,n,{description:r});console.log(`Saved workset: ${e.name}`),T(e);return}case`get`:{i||(console.error(`Usage: aikit workset get <name>`),process.exit(1));let e=Ie(i);if(!e){console.log(`No workset found: ${i}`);return}T(e);return}case`list`:{let e=qe();if(e.length===0){console.log(`No worksets saved.`);return}console.log(`Worksets (${e.length})`),console.log(`─`.repeat(60));for(let t of e)T(t),console.log(``);return}case`delete`:{i||(console.error(`Usage: aikit workset delete <name>`),process.exit(1));let e=ke(i);console.log(e?`Deleted workset: ${i}`:`No workset found: ${i}`);return}case`add`:{(!i||n.length===0)&&(console.error(`Usage: aikit workset add <name> --files f1,f2`),process.exit(1));let e=_e(i,n);console.log(`Updated workset: ${e.name}`),T(e);return}case`remove`:{(!i||n.length===0)&&(console.error(`Usage: aikit workset remove <name> --files f1,f2`),process.exit(1));let e=lt(i,n);if(!e){console.log(`No workset found: ${i}`);return}console.log(`Updated workset: ${e.name}`),T(e);return}default:console.error(`Unknown workset action: ${t}`),console.error(`Actions: save, get, list, delete, add, remove`),process.exit(1)}}},{name:`stash`,description:`Persist and retrieve named intermediate values`,usage:`aikit stash <set|get|list|delete|clear> [key] [value]`,run:async e=>{let t=e.shift()?.trim(),n=e.shift()?.trim();t||(console.error(`Usage: aikit stash <set|get|list|delete|clear> [key] [value]`),process.exit(1));let r=await v();switch(t){case`set`:{n||(console.error(`Usage: aikit stash set <key> <value>`),process.exit(1));let t=e.join(` `),i=t.trim()?``:await s(),a=bt(r,n,S(t||i));console.log(`Stored stash entry: ${a.key}`),console.log(` Type: ${a.type}`),console.log(` Stored: ${a.storedAt}`);return}case`get`:{n||(console.error(`Usage: aikit stash get <key>`),process.exit(1));let e=vt(r,n);if(!e){console.log(`No stash entry found: ${n}`);return}console.log(JSON.stringify(e,null,2));return}case`list`:{let e=yt(r);if(e.length===0){console.log(`No stash entries saved.`);return}console.log(`Stash entries (${e.length})`),console.log(`─`.repeat(60));for(let t of e)console.log(`${t.key} (${t.type})`),console.log(` Stored: ${t.storedAt}`);return}case`delete`:{n||(console.error(`Usage: aikit stash delete <key>`),process.exit(1));let e=_t(r,n);console.log(e?`Deleted stash entry: ${n}`:`No stash entry found: ${n}`);return}case`clear`:{let e=gt(r);console.log(`Cleared ${e} stash entr${e===1?`y`:`ies`}.`);return}default:console.error(`Unknown stash action: ${t}`),console.error(`Actions: set, get, list, delete, clear`),process.exit(1)}}},{name:`lane`,description:`Manage verified lanes — isolated file copies for parallel exploration`,usage:`aikit lane <create|list|status|diff|merge|discard> [name] [--files f1,f2]`,run:async e=>{let t=e.shift();if((!t||![`create`,`list`,`status`,`diff`,`merge`,`discard`].includes(t))&&(console.error(`Usage: aikit lane <create|list|status|diff|merge|discard> [name] [--files f1,f2]`),process.exit(1)),t===`list`){let e=We();if(e.length===0){console.log(`No active lanes.`);return}for(let t of e)console.log(`${t.name} (${t.sourceFiles.length} files, created ${t.createdAt})`);return}let n=e.shift();switch(n||(console.error(`Lane name is required for "${t}".`),process.exit(1)),t){case`create`:{let t=y(e,`--files`,``);t||(console.error(`Usage: aikit lane create <name> --files file1.ts,file2.ts`),process.exit(1));let r=Ve(n,t.split(`,`).map(e=>e.trim()));console.log(`Lane "${r.name}" created with ${r.sourceFiles.length} files.`);break}case`status`:{let e=Ke(n);console.log(`Lane: ${e.name}`),console.log(`Modified: ${e.modified} | Added: ${e.added} | Deleted: ${e.deleted}`);for(let t of e.entries)console.log(` ${t.status.padEnd(10)} ${t.file}`);break}case`diff`:{let e=He(n);console.log(`Lane: ${e.name} — ${e.modified} modified, ${e.added} added, ${e.deleted} deleted`);for(let t of e.entries)t.diff&&(console.log(`\n--- ${t.file} (${t.status})`),console.log(t.diff));break}case`merge`:{let e=Ge(n);console.log(`Merged ${e.filesMerged} files from lane "${e.name}".`);for(let t of e.files)console.log(` ${t}`);break}case`discard`:{let e=Ue(n);console.log(e?`Lane "${n}" discarded.`:`Lane "${n}" not found.`);break}}}},{name:`queue`,description:`Manage task queues for sequential agent operations`,usage:`aikit queue <create|push|next|done|fail|get|list|clear|delete> [name] [args]`,run:async e=>{let t=e.shift();if((!t||![`create`,`push`,`next`,`done`,`fail`,`get`,`list`,`clear`,`delete`].includes(t))&&(console.error(`Usage: aikit queue <create|push|next|done|fail|get|list|clear|delete> [name] [args]`),process.exit(1)),t===`list`){let e=ot();if(e.length===0){console.log(`No queues.`);return}for(let t of e)console.log(`${t.name} pending:${t.pending} done:${t.done} failed:${t.failed} total:${t.total}`);return}let n=e.shift();switch(n||(console.error(`Queue name is required for "${t}".`),process.exit(1)),t){case`create`:{let e=tt(n);console.log(`Queue "${e.name}" created.`);break}case`push`:{let t=ct(n,e.join(` `)||`Untitled task`);console.log(`Pushed "${t.title}" (${t.id}) to queue "${n}".`);break}case`next`:{let e=st(n);console.log(e?`Next: ${e.title} (${e.id})`:`No pending items in queue "${n}".`);break}case`done`:{let t=e.shift();t||(console.error(`Usage: aikit queue done <name> <id>`),process.exit(1));let r=rt(n,t);console.log(`Marked "${r.item.title}" as done.`);break}case`fail`:{let t=e.shift(),r=e.join(` `)||`Unknown error`;t||(console.error(`Usage: aikit queue fail <name> <id> [error message]`),process.exit(1));let i=it(n,t,r);console.log(`Marked "${i.title}" as failed: ${r}`);break}case`get`:{let e=at(n);if(!e){console.log(`Queue "${n}" not found.`);return}console.log(`Queue: ${e.name} (${e.items.length} items)`);for(let t of e.items){let e=t.error?` — ${t.error}`:``;console.log(` ${t.status.padEnd(12)} ${t.id} ${t.title}${e}`)}break}case`clear`:{let e=et(n);console.log(`Cleared ${e} completed/failed items from queue "${n}".`);break}case`delete`:{let e=nt(n);console.log(e?`Queue "${n}" deleted.`:`Queue "${n}" not found.`);break}}}}],$=[...rr,...nr,...Gt,...tr,...ir,...Un,...Kt,...or,...Hn,...ar,...Qn,...Vn];$.push({name:`help`,description:`Show available commands`,run:async()=>{cr()}});async function sr(e){let t=[...e],n=t.shift();if(!n||n===`--help`||n===`-h`){cr();return}if(n===`--version`||n===`-v`){let e=L(P(ge(import.meta.url)),`..`,`..`,`..`,`package.json`),t=JSON.parse(M(e,`utf-8`));console.log(t.version);return}if(n&&new Set([`--user`,`--workspace`,`--guide`,`--smart`]).has(n)){let e=$.find(e=>e.name===`init`);if(e){await e.run([n,...t]);return}}let r=$.find(e=>e.name===n);r||(console.error(`Unknown command: ${n}`),cr(),process.exit(1));try{await r.run(t)}finally{let e=er();e&&await e.store.close()}}function cr(){console.log(`@vpxa/aikit — Local-first AI developer toolkit
20
+ Suggested next steps:`);for(let e of o.next)console.log(` → ${e.tool}: ${e.reason}`)}}else console.error(o.error?.message??`Audit failed`),process.exitCode=1}},{name:`guide`,description:`Tool discovery — recommend AI Kit tools for a given goal`,usage:`aikit guide <goal> [--max N]`,run:async e=>{let t=e.indexOf(`--max`),n=5;t!==-1&&t+1<e.length&&(n=Number.parseInt(e.splice(t,2)[1],10)||5);let r=e.join(` `).trim();r||(console.error(`Usage: aikit guide <goal> [--max N]`),console.error(`Example: aikit guide "audit this project"`),process.exit(1));let i=ze(r,n);console.log(`Workflow: ${i.workflow}`),console.log(` ${i.description}\n`),console.log(`Recommended tools:`);for(let e of i.tools){let t=e.suggestedArgs?` ${JSON.stringify(e.suggestedArgs)}`:``;console.log(` ${e.order}. ${e.tool} — ${e.reason}${t}`)}i.alternativeWorkflows.length>0&&console.log(`\nAlternatives: ${i.alternativeWorkflows.join(`, `)}`)}},{name:`replay`,description:`Show recent tool invocation audit trail`,usage:`aikit replay [--last N] [--tool <name>] [--source mcp|cli]`,run:async e=>{let t=ft({last:Number.parseInt(e[e.indexOf(`--last`)+1],10)||20,tool:e.includes(`--tool`)?e[e.indexOf(`--tool`)+1]:void 0,source:e.includes(`--source`)?e[e.indexOf(`--source`)+1]:void 0});if(t.length===0){console.log(`No replay entries. Activity is logged when tools are invoked.`);return}console.log(`Replay Log (${t.length} entries)\n`);for(let e of t){let t=e.ts.split(`T`)[1]?.split(`.`)[0]??e.ts,n=e.status===`ok`?`✓`:`✗`;console.log(`${t} ${n} ${e.tool} (${e.durationMs}ms) [${e.source}]`),console.log(` in: ${e.input}`),console.log(` out: ${e.output}`)}pt().catch(()=>{})}},{name:`replay-clear`,description:`Clear the replay audit trail`,run:async()=>{dt(),console.log(`Replay log cleared.`)}},{name:`dashboard`,description:`Launch web dashboard for knowledge graph visualization`,usage:`aikit dashboard [--port <port>] [--no-open]`,run:async e=>{let t=e.indexOf(`--port`),n=t!==-1&&e[t+1]?Number.parseInt(e[t+1],10):3210,r=Number.isFinite(n)?n:3210,i=e.includes(`--no-open`);console.log(`Starting AI Kit server on port ${r}...`);let{spawn:a}=await import(`node:child_process`),{platform:o}=await import(`node:os`),s=w(),c=a(process.execPath,[s,`--transport`,`http`,`--port`,String(r)],{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env,AIKIT_TRANSPORT:`http`,AIKIT_PORT:String(r)}}),l=`http://localhost:${r}/_dashboard/`,u=`http://localhost:${r}/health`,d=!1;for(let e=0;e<30;e+=1){try{if((await fetch(u)).ok){d=!0;break}}catch{}await new Promise(e=>setTimeout(e,1e3))}if(d||(console.error(`Server failed to start within 30 seconds.`),c.kill(),process.exit(1)),console.log(`AI Kit Dashboard: ${l}`),console.log(`Press Ctrl+C to stop.`),!i){let e=o();e===`win32`?a(`cmd`,[`/c`,`start`,``,l],{stdio:`ignore`,detached:!0}).unref():a(e===`darwin`?`open`:`xdg-open`,[l],{stdio:`ignore`,detached:!0}).unref()}let f=()=>{c.kill(),process.exit(0)};process.on(`SIGINT`,f),process.on(`SIGTERM`,f),await new Promise(e=>{c.on(`exit`,()=>e())})}},{name:`settings`,description:`Launch web UI to manage AI Kit configuration and environment variables`,usage:`aikit settings [--port <port>] [--no-open]`,run:async e=>{let t=e.indexOf(`--port`),n=t!==-1&&e[t+1]?Number.parseInt(e[t+1],10):3210,r=Number.isFinite(n)?n:3210,i=e.includes(`--no-open`);console.log(`Starting AI Kit server on port ${r}...`);let{spawn:a}=await import(`node:child_process`),{platform:o}=await import(`node:os`),s=w(),c=a(process.execPath,[s,`--transport`,`http`,`--port`,String(r)],{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env,AIKIT_TRANSPORT:`http`,AIKIT_PORT:String(r)}}),l=`http://localhost:${r}/settings/`,u=`http://localhost:${r}/health`,d=!1;for(let e=0;e<30;e+=1){try{if((await fetch(u)).ok){d=!0;break}}catch{}await new Promise(e=>setTimeout(e,1e3))}if(d||(console.error(`Server failed to start within 30 seconds.`),c.kill(),process.exit(1)),console.log(`AI Kit Settings: ${l}`),console.log(`Press Ctrl+C to stop.`),!i){let e=o();e===`win32`?a(`cmd`,[`/c`,`start`,``,l],{stdio:`ignore`,detached:!0}).unref():a(e===`darwin`?`open`:`xdg-open`,[l],{stdio:`ignore`,detached:!0}).unref()}let f=()=>{c.kill(),process.exit(0)};process.on(`SIGINT`,f),process.on(`SIGTERM`,f),await new Promise(e=>{c.on(`exit`,()=>e())})}}],ar=[{name:`upgrade`,description:`Upgrade AI Kit agents, prompts, and skills to the latest version (user-level and workspace-level)`,usage:`aikit upgrade`,run:async()=>{await J({force:!0});let e=process.cwd();if(A(L(e,`.github`,`.aikit-scaffold.json`))){let{initScaffoldOnly:e}=await import(`./init-CYp6FjZO.js`);await e({force:!0})}if(A(L(e,`.github`,`skills`))){let{smartCopySkills:t}=await import(`./scaffold-BdUnq1xy.js`).then(e=>e.a),n=ie(),r=te();await t(e,n,[...re],r,!0);let{smartCopyFlows:i}=await import(`./scaffold-BdUnq1xy.js`).then(e=>e.a);await i(e,n,[...ae],r,!0)}let{homedir:t}=await import(`node:os`),{rmSync:n}=await import(`node:fs`),r=F(t(),`.aikit`,`cache`,`wasm`);if(A(r))try{n(r,{recursive:!0,force:!0}),console.log(`✓ WASM cache cleared (will re-resolve on next start)`)}catch{console.warn(`⚠ Could not clear WASM cache at`,r)}}}],or=[{name:`workset`,description:`Manage saved file sets`,usage:`aikit workset <action> [name] [--files f1,f2] [--description desc]`,run:async e=>{let t=e.shift()?.trim(),n=f(y(e,`--files`,``)),r=y(e,`--description`,``).trim()||void 0,i=e.shift()?.trim();switch(t||(console.error(`Usage: aikit workset <action> [name] [--files f1,f2] [--description desc]`),console.error(`Actions: save, get, list, delete, add, remove`),process.exit(1)),t){case`save`:{(!i||n.length===0)&&(console.error(`Usage: aikit workset save <name> --files f1,f2 [--description desc]`),process.exit(1));let e=mt(i,n,{description:r});console.log(`Saved workset: ${e.name}`),T(e);return}case`get`:{i||(console.error(`Usage: aikit workset get <name>`),process.exit(1));let e=Ie(i);if(!e){console.log(`No workset found: ${i}`);return}T(e);return}case`list`:{let e=qe();if(e.length===0){console.log(`No worksets saved.`);return}console.log(`Worksets (${e.length})`),console.log(`─`.repeat(60));for(let t of e)T(t),console.log(``);return}case`delete`:{i||(console.error(`Usage: aikit workset delete <name>`),process.exit(1));let e=ke(i);console.log(e?`Deleted workset: ${i}`:`No workset found: ${i}`);return}case`add`:{(!i||n.length===0)&&(console.error(`Usage: aikit workset add <name> --files f1,f2`),process.exit(1));let e=_e(i,n);console.log(`Updated workset: ${e.name}`),T(e);return}case`remove`:{(!i||n.length===0)&&(console.error(`Usage: aikit workset remove <name> --files f1,f2`),process.exit(1));let e=lt(i,n);if(!e){console.log(`No workset found: ${i}`);return}console.log(`Updated workset: ${e.name}`),T(e);return}default:console.error(`Unknown workset action: ${t}`),console.error(`Actions: save, get, list, delete, add, remove`),process.exit(1)}}},{name:`stash`,description:`Persist and retrieve named intermediate values`,usage:`aikit stash <set|get|list|delete|clear> [key] [value]`,run:async e=>{let t=e.shift()?.trim(),n=e.shift()?.trim();t||(console.error(`Usage: aikit stash <set|get|list|delete|clear> [key] [value]`),process.exit(1));let r=await v();switch(t){case`set`:{n||(console.error(`Usage: aikit stash set <key> <value>`),process.exit(1));let t=e.join(` `),i=t.trim()?``:await s(),a=bt(r,n,S(t||i));console.log(`Stored stash entry: ${a.key}`),console.log(` Type: ${a.type}`),console.log(` Stored: ${a.storedAt}`);return}case`get`:{n||(console.error(`Usage: aikit stash get <key>`),process.exit(1));let e=vt(r,n);if(!e){console.log(`No stash entry found: ${n}`);return}console.log(JSON.stringify(e,null,2));return}case`list`:{let e=yt(r);if(e.length===0){console.log(`No stash entries saved.`);return}console.log(`Stash entries (${e.length})`),console.log(`─`.repeat(60));for(let t of e)console.log(`${t.key} (${t.type})`),console.log(` Stored: ${t.storedAt}`);return}case`delete`:{n||(console.error(`Usage: aikit stash delete <key>`),process.exit(1));let e=_t(r,n);console.log(e?`Deleted stash entry: ${n}`:`No stash entry found: ${n}`);return}case`clear`:{let e=gt(r);console.log(`Cleared ${e} stash entr${e===1?`y`:`ies`}.`);return}default:console.error(`Unknown stash action: ${t}`),console.error(`Actions: set, get, list, delete, clear`),process.exit(1)}}},{name:`lane`,description:`Manage verified lanes — isolated file copies for parallel exploration`,usage:`aikit lane <create|list|status|diff|merge|discard> [name] [--files f1,f2]`,run:async e=>{let t=e.shift();if((!t||![`create`,`list`,`status`,`diff`,`merge`,`discard`].includes(t))&&(console.error(`Usage: aikit lane <create|list|status|diff|merge|discard> [name] [--files f1,f2]`),process.exit(1)),t===`list`){let e=We();if(e.length===0){console.log(`No active lanes.`);return}for(let t of e)console.log(`${t.name} (${t.sourceFiles.length} files, created ${t.createdAt})`);return}let n=e.shift();switch(n||(console.error(`Lane name is required for "${t}".`),process.exit(1)),t){case`create`:{let t=y(e,`--files`,``);t||(console.error(`Usage: aikit lane create <name> --files file1.ts,file2.ts`),process.exit(1));let r=Ve(n,t.split(`,`).map(e=>e.trim()));console.log(`Lane "${r.name}" created with ${r.sourceFiles.length} files.`);break}case`status`:{let e=Ke(n);console.log(`Lane: ${e.name}`),console.log(`Modified: ${e.modified} | Added: ${e.added} | Deleted: ${e.deleted}`);for(let t of e.entries)console.log(` ${t.status.padEnd(10)} ${t.file}`);break}case`diff`:{let e=He(n);console.log(`Lane: ${e.name} — ${e.modified} modified, ${e.added} added, ${e.deleted} deleted`);for(let t of e.entries)t.diff&&(console.log(`\n--- ${t.file} (${t.status})`),console.log(t.diff));break}case`merge`:{let e=Ge(n);console.log(`Merged ${e.filesMerged} files from lane "${e.name}".`);for(let t of e.files)console.log(` ${t}`);break}case`discard`:{let e=Ue(n);console.log(e?`Lane "${n}" discarded.`:`Lane "${n}" not found.`);break}}}},{name:`queue`,description:`Manage task queues for sequential agent operations`,usage:`aikit queue <create|push|next|done|fail|get|list|clear|delete> [name] [args]`,run:async e=>{let t=e.shift();if((!t||![`create`,`push`,`next`,`done`,`fail`,`get`,`list`,`clear`,`delete`].includes(t))&&(console.error(`Usage: aikit queue <create|push|next|done|fail|get|list|clear|delete> [name] [args]`),process.exit(1)),t===`list`){let e=ot();if(e.length===0){console.log(`No queues.`);return}for(let t of e)console.log(`${t.name} pending:${t.pending} done:${t.done} failed:${t.failed} total:${t.total}`);return}let n=e.shift();switch(n||(console.error(`Queue name is required for "${t}".`),process.exit(1)),t){case`create`:{let e=tt(n);console.log(`Queue "${e.name}" created.`);break}case`push`:{let t=ct(n,e.join(` `)||`Untitled task`);console.log(`Pushed "${t.title}" (${t.id}) to queue "${n}".`);break}case`next`:{let e=st(n);console.log(e?`Next: ${e.title} (${e.id})`:`No pending items in queue "${n}".`);break}case`done`:{let t=e.shift();t||(console.error(`Usage: aikit queue done <name> <id>`),process.exit(1));let r=rt(n,t);console.log(`Marked "${r.item.title}" as done.`);break}case`fail`:{let t=e.shift(),r=e.join(` `)||`Unknown error`;t||(console.error(`Usage: aikit queue fail <name> <id> [error message]`),process.exit(1));let i=it(n,t,r);console.log(`Marked "${i.title}" as failed: ${r}`);break}case`get`:{let e=at(n);if(!e){console.log(`Queue "${n}" not found.`);return}console.log(`Queue: ${e.name} (${e.items.length} items)`);for(let t of e.items){let e=t.error?` — ${t.error}`:``;console.log(` ${t.status.padEnd(12)} ${t.id} ${t.title}${e}`)}break}case`clear`:{let e=et(n);console.log(`Cleared ${e} completed/failed items from queue "${n}".`);break}case`delete`:{let e=nt(n);console.log(e?`Queue "${n}" deleted.`:`Queue "${n}" not found.`);break}}}}],$=[...rr,...nr,...Gt,...tr,...ir,...Un,...Kt,...or,...Hn,...ar,...Qn,...Vn];$.push({name:`help`,description:`Show available commands`,run:async()=>{cr()}});async function sr(e){let t=[...e],n=t.shift();if(!n||n===`--help`||n===`-h`){cr();return}if(n===`--version`||n===`-v`){let e=L(P(ge(import.meta.url)),`..`,`..`,`..`,`package.json`),t=JSON.parse(M(e,`utf-8`));console.log(t.version);return}if(n&&new Set([`--user`,`--workspace`,`--guide`,`--smart`]).has(n)){let e=$.find(e=>e.name===`init`);if(e){await e.run([n,...t]);return}}let r=$.find(e=>e.name===n);r||(console.error(`Unknown command: ${n}`),cr(),process.exit(1));try{await r.run(t)}finally{let e=er();e&&await e.store.close()}}function cr(){console.log(`@vpxa/aikit — Local-first AI developer toolkit
21
21
  `),console.log(`Usage: aikit <command> [options]
22
22
  `),console.log(`Commands:`);let e=Math.max(...$.map(e=>e.name.length));for(let t of $)console.log(` ${t.name.padEnd(e+2)}${t.description}`);console.log(``),console.log(`Options:`),console.log(` --help, -h Show this help`),console.log(` --version, -v Show version`)}export{sr as run};
@@ -11,4 +11,4 @@ import"node:module";import{createHash as e,randomUUID as t}from"node:crypto";imp
11
11
  `).length,fileHash:this.hash(e.content),indexedAt:i,origin:`curated`,tags:e.frontmatter.tags,category:e.frontmatter.category,version:e.frontmatter.version}});return await this.store.upsert(a,r),{indexed:n.length,errors:t}}gitCommitKnowledge(e,t,n){try{if(!b(this.curatedDir))return;let r=this.knowledgeRefForPath(e);if(!r)return;x(r,`entry.md`,t,n,this.curatedDir)}catch{}}gitDeleteKnowledgeRef(e){try{if(!b(this.curatedDir))return;let t=this.knowledgeRefForPath(e);if(!t)return;S([`update-ref`,`-d`,t],this.curatedDir)}catch{}}knowledgeRefForPath(e){let t=e.replace(/\.md$/,``).split(`/`).map(e=>w(e)).join(`/`);return t.split(`/`).every(e=>y.test(e))?`${X}/${t}`:null}async indexCuratedFile(e,t,n){let r=await this.embedder.embed(t),i=`.ai/curated/${e}`,a=new Date().toISOString(),o={id:this.hashId(i,0),content:t,sourcePath:i,contentType:`curated-knowledge`,headingPath:n.title,chunkIndex:0,totalChunks:1,startLine:1,endLine:t.split(`
12
12
  `).length,fileHash:this.hash(t),indexedAt:a,origin:`curated`,tags:n.tags,category:n.category,version:n.version};await this.store.upsert([o],[r])}async discoverCategories(){return this.adapter.listDirectories()}guardPath(e){let t=e.replace(/^\.ai\/curated\//,``);if(t.endsWith(`.md`)||(t+=`.md`),t.includes(`..`)||i(t))throw Error(`Invalid path: ${t}. Must be relative within .ai/curated/ directory.`);let n=t.split(`/`)[0];return this.validateCategoryName(n),t}validateCategoryName(e){if(!/^[a-z][a-z0-9-]*$/.test(e))throw Error(`Invalid category name: "${e}". Must be lowercase kebab-case (e.g., "decisions", "api-contracts").`)}validateContentSize(e){if(Buffer.byteLength(e,`utf-8`)>Fe)throw Error(`Content exceeds maximum size of ${Fe/1024}KB`)}slugify(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-|-$/g,``).slice(0,80)}async uniqueRelativePath(e,t){let n=`${e}/${t}.md`;if(!await this.adapter.exists(n))return n;for(let n=2;n<=100;n++){let r=`${e}/${t}-${n}.md`;if(!await this.adapter.exists(r))return r}throw Error(`Too many entries with slug "${t}" in category "${e}"`)}hash(t){return e(`sha256`).update(t).digest(`hex`).slice(0,16)}hashId(e,t){return this.hash(`${e}::${t}`)}serializeFile(e,t){return`${[`---`,`title: "${t.title.replace(/"/g,`\\"`)}"`,`category: ${t.category}`,`tags: [${t.tags.map(e=>`"${e}"`).join(`, `)}]`,`created: ${t.created}`,`updated: ${t.updated}`,`version: ${t.version}`,`origin: ${t.origin}`,`changelog:`,...t.changelog.map(e=>` - version: ${e.version}\n date: ${e.date}\n reason: "${e.reason.replace(/"/g,`\\"`)}"`),`---`].join(`
13
13
  `)}\n\n${e}\n`}parseFile(e){let t=e.match(/^---\n([\s\S]*?)\n---\n\n?([\s\S]*)$/);if(!t)return{frontmatter:{title:`Untitled`,category:`notes`,tags:[],created:``,updated:``,version:1,origin:`curated`,changelog:[]},content:e};let n=t[1],r=t[2].trim(),i={},a=[],o=n.split(`
14
- `),s=!1,c={};for(let e of o){if(/^changelog:\s*$/.test(e)){s=!0;continue}if(s){let t=e.match(/^\s+-\s+version:\s*(\d+)$/);if(t){c.version!=null&&a.push(c),c={version:parseInt(t[1],10)};continue}let n=e.match(/^\s+date:\s*(.+)$/);if(n){c.date=n[1].trim();continue}let r=e.match(/^\s+reason:\s*"?(.*?)"?\s*$/);if(r){c.reason=r[1];continue}/^\w/.test(e)&&(s=!1,c.version!=null&&a.push(c),c={});continue}let t=e.match(/^(\w+):\s*(.*)$/);if(t){let e=t[1],n=t[2];typeof n==`string`&&n.startsWith(`[`)&&n.endsWith(`]`)?n=n.slice(1,-1).split(`,`).map(e=>e.trim().replace(/^"|"$/g,``)).filter(e=>e.length>0):typeof n==`string`&&/^\d+$/.test(n)?n=parseInt(n,10):typeof n==`string`&&n.startsWith(`"`)&&n.endsWith(`"`)&&(n=n.slice(1,-1)),i[e]=n}}return c.version!=null&&a.push(c),{frontmatter:{title:i.title??`Untitled`,category:i.category??`notes`,tags:i.tags??[],created:i.created??``,updated:i.updated??``,version:i.version??1,origin:`curated`,changelog:a},content:r}}};function Re(){try{let e=o(r(s(import.meta.url)),`..`,`..`,`..`,`package.json`);return JSON.parse(n(e,`utf-8`)).version??`0.0.0`}catch{return`0.0.0`}}const Z=u(`server`),ze=/^https?:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/i;function Be({requestOrigin:e,configuredOrigin:t,allowAnyOrigin:n,fallbackOrigin:r}){let i=t??r;return i===`*`?n?{allowOrigin:`*`,warn:!1}:e?ze.test(e)?{allowOrigin:e,warn:!1}:{allowOrigin:null,warn:!0}:{allowOrigin:r,warn:!1}:{allowOrigin:i,warn:!1}}function Ve({limit:e,windowMs:t}){let n=new Map,r=(e,r)=>{let i=r-t,a=n.get(e)?.filter(e=>e>i)??[];return a.length===0?(n.delete(e),[]):(n.set(e,a),a)};return{allow(t,i=Date.now()){let a=r(t,i);return a.length>=e?!1:(a.push(i),n.set(t,a),!0)},getRetryAfterMs(n,i=Date.now()){let a=r(n,i);return a.length<e?0:Math.max(0,a[0]+t-i)}}}function He(){return process.env.AIKIT_TRANSPORT?process.env.AIKIT_TRANSPORT:process.stdin.isTTY?`http`:`stdio`}function Ue(){let e=process.argv[1];if(!e)return!1;try{return import.meta.url===c(e).href}catch{return!1}}function Q(e){let t=e.headers[`mcp-session-id`];return Array.isArray(t)?t[0]:t}function $(e,t){let n=process.env[e];if(!n)return t;let r=Number.parseInt(n,10);return Number.isFinite(r)&&r>0?r:t}function We(){return Ue()?l({allowPositionals:!0,options:{transport:{type:`string`,default:He()},port:{type:`string`,default:process.env.AIKIT_PORT??`3210`}}}).values:{transport:He(),port:process.env.AIKIT_PORT??`3210`}}function Ge(e){return`## Context\n${e.context}\n\n## Insight\n${e.insight}\n\n## Evidence\n${e.evidence}`}function Ke(e){ke(t=>{(async()=>{let n=e();if(!n)return;let{jaccardSimilarity:r}=await Promise.resolve().then(()=>ne),i=await n.curated.list({category:`lessons`});for(let e of t)i.some(t=>r(e.title,t.title)>.6)||(await n.curated.remember(e.title,Ge(e),`lessons`,[`lesson`,`auto-observed`,`detector:${e.detector}`]),i.push({path:`lessons/${e.title}`,title:e.title,category:`lessons`,tags:[`lesson`,`auto-observed`,`detector:${e.detector}`],version:1,created:new Date().toISOString(),updated:new Date().toISOString(),contentPreview:e.insight.slice(0,200)}))})().catch(()=>{})})}async function qe(){let e=Re(),n=We();process.on(`unhandledRejection`,e=>{Z.error(`Unhandled rejection`,d(e))}),process.on(`uncaughtException`,e=>{Z.error(`Uncaught exception — exiting`,d(e)),process.exit(1)});let r=(e,t)=>{e.then(async()=>{try{let{markPromoteRun:e,markPruneRun:n,prune:r,shouldRunStartupPrune:i,shouldRunWeeklyPromote:a}=await import(`../../tools/dist/index.js`),o=t();if(!o)return;if(i()){let e=await r({});n(),e.totalBytesFreed>0&&Z.info(`Storage maintenance complete`,{forgeOrphans:e.forgeGroundOrphans.count,legacyLance:e.legacyLance.count,bytesFreed:e.totalBytesFreed});let{groupLessons:t,pruneLessons:i}=await import(`./evolution-9hXRopDC.js`).then(e=>e.t),a=await i(o.curated,o.stateStore,{dryRun:!1});a.pruned.length>0&&Z.info(`Startup lesson prune complete`,{pruned:a.pruned.length});let s=await t(o.curated,o.stateStore,{dryRun:!1});(s.groupsCreated>0||s.lessonsGrouped>0)&&Z.info(`Startup lesson grouping complete`,{groupsCreated:s.groupsCreated,lessonsGrouped:s.lessonsGrouped})}if(a()){let{DEFAULT_PROMOTE_CONFIG:t,collectWorkspaceLessons:n,getGlobalCuratedDir:r,promoteLessons:i,scanForDuplicates:a}=await import(`./promotion-Bd_YB7E1.js`).then(e=>e.o),{CuratedKnowledgeManager:s}=await Promise.resolve().then(()=>Pe),c=o.curated,l=new s(r(),c.store,c.embedder),u=await n(),d={...t,dryRun:!1},f=await i(a(u,d),l,d);e(),f.promoted.length>0&&Z.info(`Weekly lesson promotion complete`,{promoted:f.promoted.length,candidates:f.candidates.length})}}catch(e){Z.warn(`Startup maintenance failed (non-critical)`,d(e))}}).catch(()=>{})};if(Z.info(`Starting MCP AI Kit server`,{version:e}),n.transport===`http`){let[{default:e},{loadConfig:i,resolveIndexMode:a},{registerDashboardRoutes:o,resolveDashboardDir:s},{registerSettingsRoutes:c,resolveSettingsDir:l},{createSettingsRouter:u},{authMiddleware:f,getOrCreateToken:p}]=await Promise.all([import(`express`),import(`./config-C4mVyqAF.js`),import(`./dashboard-static-CRfR1yKU.js`),import(`./settings-static-B3lnYvcb.js`),import(`./routes-Afg7J7xK.js`),import(`./auth-lzZKfxlV.js`)]),m=i();Z.info(`Config loaded`,{sourceCount:m.sources.length,storePath:m.store.path});let h=e();h.use(e.json({limit:`1mb`}));let g=Number(n.port),_=`http://localhost:${g}`,v=process.env.AIKIT_CORS_ORIGIN??_,y=process.env.AIKIT_ALLOW_ANY_ORIGIN===`true`,b=$(`AIKIT_HTTP_MAX_SESSIONS`,8),x=$(`AIKIT_HTTP_SESSION_TIMEOUT_MINUTES`,30),S=$(`AIKIT_HTTP_SESSION_GC_INTERVAL_MINUTES`,5),C=Ve({limit:100,windowMs:6e4}),w=!1;h.use((e,t,n)=>{let r=Array.isArray(e.headers.origin)?e.headers.origin[0]:e.headers.origin,i=Be({requestOrigin:r,configuredOrigin:v,allowAnyOrigin:y,fallbackOrigin:_});if(i.warn&&!w&&(w=!0,Z.warn(`Rejected non-local CORS origin while AIKIT_CORS_ORIGIN=*`,{origin:r,allowAnyOriginEnv:`AIKIT_ALLOW_ANY_ORIGIN=true`})),r&&!i.allowOrigin){t.status(403).json({error:`Origin not allowed`});return}if(i.allowOrigin&&t.setHeader(`Access-Control-Allow-Origin`,i.allowOrigin),t.setHeader(`Access-Control-Allow-Methods`,`GET, POST, PUT, PATCH, DELETE, OPTIONS`),t.setHeader(`Access-Control-Allow-Headers`,`Content-Type, Authorization, Mcp-Session-Id, Mcp-Protocol-Version, Last-Event-ID`),t.setHeader(`Access-Control-Expose-Headers`,`Mcp-Session-Id`),e.method===`OPTIONS`){t.status(204).end();return}n()});let T=p();console.error(`[aikit] Auth token: ~/.aikit/token`),h.use(f(T)),h.use(`/mcp`,(e,t,n)=>{let r=Q(e)??e.ip??e.socket.remoteAddress??`anonymous`;if(C.allow(r)){n();return}let i=Math.max(1,Math.ceil(C.getRetryAfterMs(r)/1e3));t.setHeader(`Retry-After`,String(i)),t.status(429).json({jsonrpc:`2.0`,error:{code:-32003,message:`Rate limit exceeded`},id:null})}),o(h,s(),Z);let E=new Date().toISOString();h.use(`/settings/api`,u({log:Z,mcpInfo:()=>({transport:`http`,port:g,pid:process.pid,startedAt:E})})),c(h,l(),Z),h.get(`/health`,(e,t)=>{t.json({status:`ok`})});let D=!1,O=null,k=null,A=null,j=null,M=null,N=null,P=null,F=Promise.resolve(),te=async(e,n)=>{if(!D||!A||!j){n.status(503).json({jsonrpc:`2.0`,error:{code:-32603,message:`Server initializing — please retry in a few seconds`},id:null});return}let r=F,i;F=new Promise(e=>{i=e}),await r;try{let r=Q(e);if(!N){if(r){n.status(404).json({jsonrpc:`2.0`,error:{code:-32001,message:`Session not found`},id:null});return}let e=new j({sessionIdGenerator:()=>t(),onsessioninitialized:async e=>{P=e,k?.onSessionStart(e,{transport:`http`})},onsessionclosed:async e=>{e&&k?.onSessionEnd(e),P=null}});e.onclose=()=>{N===e&&(N=null),P===e.sessionId&&(P=null)},N=e,await A.connect(e)}let i=N;await i.handleRequest(e,n,e.body),e.method!==`DELETE`&&(!r&&i.sessionId?(P=i.sessionId,k?.onSessionStart(i.sessionId,{transport:`http`}),k?.onSessionActivity(i.sessionId)):r&&k?.onSessionActivity(r))}catch(e){if(Z.error(`MCP handler error`,d(e)),!n.headersSent){let t=e instanceof Error?e.message:String(e),r=t.includes(`Not Acceptable`);n.status(r?406:500).json({jsonrpc:`2.0`,error:{code:r?-32e3:-32603,message:r?t:`Internal server error`},id:null})}}finally{i()}},I=async(e,t)=>{let n=Q(e);if(M&&(!N||n!==P)){await M.handleRequest(e,t,e.body);return}await te(e,t)};h.post(`/mcp`,I),h.get(`/mcp`,I),h.delete(`/mcp`,I);let ne=h.listen(g,`127.0.0.1`,()=>{Z.info(`MCP server listening`,{url:`http://127.0.0.1:${g}/mcp`,port:g}),setTimeout(async()=>{try{let[{createLazyServer:e,createMcpServer:t,ALL_TOOL_NAMES:n},{StreamableHTTPServerTransport:i},{checkForUpdates:o,autoUpgradeScaffold:s}]=await Promise.all([import(`./server-BA1mIjBc.js`),import(`@modelcontextprotocol/sdk/server/streamableHttp.js`),import(`./version-check-gazMo-D4.js`)]);o(),s();let c=a(m),l=e(m,c);A=l.server,j=i,D=!0,Z.info(`MCP server configured (lazy — AI Kit initializing in background)`,{toolCount:n.length,resourceCount:2}),l.startInit(),l.ready.then(()=>{if(!l.aikit)throw Error(`AI Kit components are not available after initialization`);k=new Me(l.aikit.stateStore,{staleTimeoutMinutes:x,gcIntervalMinutes:S,onBeforeSessionDelete:e=>{if(P===e&&N){let e=N;N=null,P=null,e.close().catch(()=>void 0)}M?.closeSession(e,{notifySessionEnd:!1})},onSessionEndMaintenance:async()=>{if(!l.aikit?.curated||!l.aikit?.stateStore)return;let{pruneLessons:e}=await import(`./evolution-9hXRopDC.js`).then(e=>e.t),t=await e(l.aikit.curated,l.aikit.stateStore,{dryRun:!1});t.pruned.length>0&&Z.info(`Session-end lesson prune`,{pruned:t.pruned.length})}}),M=new ee({createServer:()=>{if(!l.aikit)throw Error(`AI Kit components are not available after initialization`);return t(l.aikit,m)},createTransport:e=>new i(e),maxSessions:b,sessionTimeoutMinutes:x,onSessionStart:e=>k?.onSessionStart(e,{transport:`http`}),onSessionActivity:e=>k?.onSessionActivity(e),onSessionEnd:e=>k?.onSessionEnd(e)}),k.startGC(),P&&(k.onSessionStart(P,{transport:`http`}),k.onSessionActivity(P)),Ke(()=>l.aikit?{curated:l.aikit.curated,stateStore:l.aikit.stateStore}:null),Z.info(`HTTP session runtime ready`,{maxSessions:b,sessionTimeoutMinutes:x,gcIntervalMinutes:S})}).catch(e=>Z.error(`Failed to start session manager`,d(e))),c===`auto`?l.ready.then(async()=>{try{let e=m.sources.map(e=>e.path).join(`, `);Z.info(`Running initial index`,{sourcePaths:e}),await l.runInitialIndex(),Z.info(`Initial index complete`)}catch(e){Z.error(`Initial index failed; will retry on aikit_reindex`,d(e))}}).catch(e=>Z.error(`AI Kit init or indexing failed`,d(e))):c===`smart`?l.ready.then(async()=>{try{if(!l.aikit)throw Error(`AI Kit components are not available after initialization`);let{SmartIndexScheduler:e}=await import(`../../indexer/dist/index.js`),t=new e(l.aikit.indexer,m,l.aikit.store),n=l.aikit.store;O=t,t.start(),n.onBeforeClose&&n.onBeforeClose(()=>t.stop()),l.setSmartScheduler(t),Z.info(`Smart index scheduler started (HTTP mode)`)}catch(e){Z.error(`Failed to start smart index scheduler`,d(e))}}).catch(e=>Z.error(`AI Kit initialization failed`,d(e))):(l.ready.catch(e=>Z.error(`AI Kit initialization failed`,d(e))),Z.info(`Initial full indexing skipped in HTTP mode`,{indexMode:c})),r(l.ready,()=>l.aikit?{curated:l.aikit.curated,stateStore:l.aikit.stateStore}:null)}catch(e){Z.error(`Failed to load server modules`,d(e))}},100)}),L=async e=>{Z.info(`Shutdown signal received`,{signal:e}),O?.stop(),k?.stop(),await M?.closeAll().catch(()=>void 0),P&&k?.onSessionEnd(P),N&&(await N.close().catch(()=>void 0),N=null,P=null),ne.close(),A&&await A.close(),process.exit(0)};process.on(`SIGINT`,()=>L(`SIGINT`)),process.on(`SIGTERM`,()=>L(`SIGTERM`))}else{let[{loadConfig:e,reconfigureForWorkspace:t,resolveIndexMode:n},{createLazyServer:i},{checkForUpdates:a,autoUpgradeScaffold:o},{RootsListChangedNotificationSchema:c}]=await Promise.all([import(`./config-C4mVyqAF.js`),import(`./server-BA1mIjBc.js`),import(`./version-check-gazMo-D4.js`),import(`@modelcontextprotocol/sdk/types.js`)]),l=e();Z.info(`Config loaded`,{sourceCount:l.sources.length,storePath:l.store.path}),a(),o();let u=n(l),f=i(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),Z.info(`MCP server started`,{transport:`stdio`});let y=e=>{if(e.length===0)return!1;let n=e[0].uri,r=n.startsWith(`file://`)?s(n):n;return Z.info(`MCP roots resolved`,{rootUri:n,rootPath:r,rootCount:e.length}),t(l,r),l.allRoots=e.map(e=>{let t=e.uri;return t.startsWith(`file://`)?s(t):t}),!0},b=!1;try{b=y((await p.server.listRoots()).roots),b||Z.info(`No MCP roots yet; waiting for roots/list_changed notification`)}catch(e){Z.warn(`MCP roots/list not supported by client; using cwd fallback`,{cwd:process.cwd(),...d(e)}),b=!0}b||=await new Promise(e=>{let t=setTimeout(()=>{Z.warn(`Timed out waiting for MCP roots/list_changed; using cwd fallback`,{cwd:process.cwd()}),e(!1)},5e3);p.server.setNotificationHandler(c,async()=>{clearTimeout(t);try{e(y((await p.server.listRoots()).roots))}catch(t){Z.warn(`roots/list retry failed after notification`,d(t)),e(!1)}})}),m();let x=null,S=()=>{x&&clearTimeout(x),x=setTimeout(async()=>{Z.info(`Auto-shutdown: no activity for 30 minutes — shutting down gracefully`);try{let e=f.aikit;e&&await Promise.all([e.embedder.shutdown?.().catch(()=>{})??Promise.resolve(),e.graphStore.close().catch(()=>{}),e.store.close().catch(()=>{})])}catch{}process.exit(0)},18e5),x.unref&&x.unref()};S(),process.stdin.on(`data`,()=>S()),h.catch(e=>{Z.error(`Initialization failed — server will continue with limited tools`,d(e))}),h.then(()=>{Ke(()=>f.aikit?{curated:f.aikit.curated,stateStore:f.aikit.stateStore}:null)}).catch(()=>{}),u===`auto`?g().catch(e=>Z.error(`Initial index failed`,d(e))):u===`smart`?h.then(async()=>{try{if(!f.aikit)throw Error(`AI Kit components are not available after initialization`);let{SmartIndexScheduler:e}=await import(`../../indexer/dist/index.js`),t=new e(f.aikit.indexer,l,f.aikit.store),n=f.aikit.store;t.start(),n.onBeforeClose&&n.onBeforeClose(()=>t.stop()),f.setSmartScheduler(t),Z.info(`Smart index scheduler started (stdio mode)`)}catch(e){Z.error(`Failed to start smart index scheduler`,d(e))}}).catch(e=>Z.error(`AI Kit init failed for smart scheduler`,d(e))):Z.warn(`Initial full indexing skipped; use aikit_reindex to index manually`,{indexMode:u}),r(h,()=>f.aikit?{curated:f.aikit.curated,stateStore:f.aikit.stateStore}:null)}}qe();export{V as a,L as c,ie as d,R as f,De as i,re as l,E as m,Ne as n,ve as o,I as p,Ae as r,_e as s,Le as t,B as u};
14
+ `),s=!1,c={};for(let e of o){if(/^changelog:\s*$/.test(e)){s=!0;continue}if(s){let t=e.match(/^\s+-\s+version:\s*(\d+)$/);if(t){c.version!=null&&a.push(c),c={version:parseInt(t[1],10)};continue}let n=e.match(/^\s+date:\s*(.+)$/);if(n){c.date=n[1].trim();continue}let r=e.match(/^\s+reason:\s*"?(.*?)"?\s*$/);if(r){c.reason=r[1];continue}/^\w/.test(e)&&(s=!1,c.version!=null&&a.push(c),c={});continue}let t=e.match(/^(\w+):\s*(.*)$/);if(t){let e=t[1],n=t[2];typeof n==`string`&&n.startsWith(`[`)&&n.endsWith(`]`)?n=n.slice(1,-1).split(`,`).map(e=>e.trim().replace(/^"|"$/g,``)).filter(e=>e.length>0):typeof n==`string`&&/^\d+$/.test(n)?n=parseInt(n,10):typeof n==`string`&&n.startsWith(`"`)&&n.endsWith(`"`)&&(n=n.slice(1,-1)),i[e]=n}}return c.version!=null&&a.push(c),{frontmatter:{title:i.title??`Untitled`,category:i.category??`notes`,tags:i.tags??[],created:i.created??``,updated:i.updated??``,version:i.version??1,origin:`curated`,changelog:a},content:r}}};function Re(){try{let e=o(r(s(import.meta.url)),`..`,`..`,`..`,`package.json`);return JSON.parse(n(e,`utf-8`)).version??`0.0.0`}catch{return`0.0.0`}}const Z=u(`server`),ze=/^https?:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/i;function Be({requestOrigin:e,configuredOrigin:t,allowAnyOrigin:n,fallbackOrigin:r}){let i=t??r;return i===`*`?n?{allowOrigin:`*`,warn:!1}:e?ze.test(e)?{allowOrigin:e,warn:!1}:{allowOrigin:null,warn:!0}:{allowOrigin:r,warn:!1}:{allowOrigin:i,warn:!1}}function Ve({limit:e,windowMs:t}){let n=new Map,r=(e,r)=>{let i=r-t,a=n.get(e)?.filter(e=>e>i)??[];return a.length===0?(n.delete(e),[]):(n.set(e,a),a)};return{allow(t,i=Date.now()){let a=r(t,i);return a.length>=e?!1:(a.push(i),n.set(t,a),!0)},getRetryAfterMs(n,i=Date.now()){let a=r(n,i);return a.length<e?0:Math.max(0,a[0]+t-i)}}}function He(){return process.env.AIKIT_TRANSPORT?process.env.AIKIT_TRANSPORT:process.stdin.isTTY?`http`:`stdio`}function Ue(){let e=process.argv[1];if(!e)return!1;try{return import.meta.url===c(e).href}catch{return!1}}function Q(e){let t=e.headers[`mcp-session-id`];return Array.isArray(t)?t[0]:t}function $(e,t){let n=process.env[e];if(!n)return t;let r=Number.parseInt(n,10);return Number.isFinite(r)&&r>0?r:t}function We(){return Ue()?l({allowPositionals:!0,options:{transport:{type:`string`,default:He()},port:{type:`string`,default:process.env.AIKIT_PORT??`3210`}}}).values:{transport:He(),port:process.env.AIKIT_PORT??`3210`}}function Ge(e){return`## Context\n${e.context}\n\n## Insight\n${e.insight}\n\n## Evidence\n${e.evidence}`}function Ke(e){ke(t=>{(async()=>{let n=e();if(!n)return;let{jaccardSimilarity:r}=await Promise.resolve().then(()=>ne),i=await n.curated.list({category:`lessons`});for(let e of t)i.some(t=>r(e.title,t.title)>.6)||(await n.curated.remember(e.title,Ge(e),`lessons`,[`lesson`,`auto-observed`,`detector:${e.detector}`]),i.push({path:`lessons/${e.title}`,title:e.title,category:`lessons`,tags:[`lesson`,`auto-observed`,`detector:${e.detector}`],version:1,created:new Date().toISOString(),updated:new Date().toISOString(),contentPreview:e.insight.slice(0,200)}))})().catch(()=>{})})}async function qe(){let e=Re(),n=We();process.on(`unhandledRejection`,e=>{Z.error(`Unhandled rejection`,d(e))}),process.on(`uncaughtException`,e=>{Z.error(`Uncaught exception — exiting`,d(e)),process.exit(1)});let r=(e,t)=>{e.then(async()=>{try{let{markPromoteRun:e,markPruneRun:n,prune:r,shouldRunStartupPrune:i,shouldRunWeeklyPromote:a}=await import(`../../tools/dist/index.js`),o=t();if(!o)return;if(i()){let e=await r({});n(),e.totalBytesFreed>0&&Z.info(`Storage maintenance complete`,{forgeOrphans:e.forgeGroundOrphans.count,legacyLance:e.legacyLance.count,bytesFreed:e.totalBytesFreed});let{groupLessons:t,pruneLessons:i}=await import(`./evolution-9hXRopDC.js`).then(e=>e.t),a=await i(o.curated,o.stateStore,{dryRun:!1});a.pruned.length>0&&Z.info(`Startup lesson prune complete`,{pruned:a.pruned.length});let s=await t(o.curated,o.stateStore,{dryRun:!1});(s.groupsCreated>0||s.lessonsGrouped>0)&&Z.info(`Startup lesson grouping complete`,{groupsCreated:s.groupsCreated,lessonsGrouped:s.lessonsGrouped})}if(a()){let{DEFAULT_PROMOTE_CONFIG:t,collectWorkspaceLessons:n,getGlobalCuratedDir:r,promoteLessons:i,scanForDuplicates:a}=await import(`./promotion-Bd_YB7E1.js`).then(e=>e.o),{CuratedKnowledgeManager:s}=await Promise.resolve().then(()=>Pe),c=o.curated,l=new s(r(),c.store,c.embedder),u=await n(),d={...t,dryRun:!1},f=await i(a(u,d),l,d);e(),f.promoted.length>0&&Z.info(`Weekly lesson promotion complete`,{promoted:f.promoted.length,candidates:f.candidates.length})}}catch(e){Z.warn(`Startup maintenance failed (non-critical)`,d(e))}}).catch(()=>{})};if(Z.info(`Starting MCP AI Kit server`,{version:e}),n.transport===`http`){let[{default:e},{loadConfig:i,resolveIndexMode:a},{registerDashboardRoutes:o,resolveDashboardDir:s},{registerSettingsRoutes:c,resolveSettingsDir:l},{createSettingsRouter:u},{authMiddleware:f,getOrCreateToken:p}]=await Promise.all([import(`express`),import(`./config-C4mVyqAF.js`),import(`./dashboard-static-CRfR1yKU.js`),import(`./settings-static-B3lnYvcb.js`),import(`./routes-Afg7J7xK.js`),import(`./auth-lzZKfxlV.js`)]),m=i();Z.info(`Config loaded`,{sourceCount:m.sources.length,storePath:m.store.path});let h=e();h.use(e.json({limit:`1mb`}));let g=Number(n.port),_=`http://localhost:${g}`,v=process.env.AIKIT_CORS_ORIGIN??_,y=process.env.AIKIT_ALLOW_ANY_ORIGIN===`true`,b=$(`AIKIT_HTTP_MAX_SESSIONS`,8),x=$(`AIKIT_HTTP_SESSION_TIMEOUT_MINUTES`,30),S=$(`AIKIT_HTTP_SESSION_GC_INTERVAL_MINUTES`,5),C=Ve({limit:100,windowMs:6e4}),w=!1;h.use((e,t,n)=>{let r=Array.isArray(e.headers.origin)?e.headers.origin[0]:e.headers.origin,i=Be({requestOrigin:r,configuredOrigin:v,allowAnyOrigin:y,fallbackOrigin:_});if(i.warn&&!w&&(w=!0,Z.warn(`Rejected non-local CORS origin while AIKIT_CORS_ORIGIN=*`,{origin:r,allowAnyOriginEnv:`AIKIT_ALLOW_ANY_ORIGIN=true`})),r&&!i.allowOrigin){t.status(403).json({error:`Origin not allowed`});return}if(i.allowOrigin&&t.setHeader(`Access-Control-Allow-Origin`,i.allowOrigin),t.setHeader(`Access-Control-Allow-Methods`,`GET, POST, PUT, PATCH, DELETE, OPTIONS`),t.setHeader(`Access-Control-Allow-Headers`,`Content-Type, Authorization, Mcp-Session-Id, Mcp-Protocol-Version, Last-Event-ID`),t.setHeader(`Access-Control-Expose-Headers`,`Mcp-Session-Id`),e.method===`OPTIONS`){t.status(204).end();return}n()});let T=p();console.error(`[aikit] Auth token: ~/.aikit/token`),h.use(f(T)),h.use(`/mcp`,(e,t,n)=>{let r=Q(e)??e.ip??e.socket.remoteAddress??`anonymous`;if(C.allow(r)){n();return}let i=Math.max(1,Math.ceil(C.getRetryAfterMs(r)/1e3));t.setHeader(`Retry-After`,String(i)),t.status(429).json({jsonrpc:`2.0`,error:{code:-32003,message:`Rate limit exceeded`},id:null})}),o(h,s(),Z);let E=new Date().toISOString();h.use(`/settings/api`,u({log:Z,mcpInfo:()=>({transport:`http`,port:g,pid:process.pid,startedAt:E})})),c(h,l(),Z),h.get(`/health`,(e,t)=>{t.json({status:`ok`})});let D=!1,O=null,k=null,A=null,j=null,M=null,N=null,P=null,F=Promise.resolve(),te=async(e,n)=>{if(!D||!A||!j){n.status(503).json({jsonrpc:`2.0`,error:{code:-32603,message:`Server initializing — please retry in a few seconds`},id:null});return}let r=F,i;F=new Promise(e=>{i=e}),await r;try{let r=Q(e);if(!N){if(r){n.status(404).json({jsonrpc:`2.0`,error:{code:-32001,message:`Session not found`},id:null});return}let e=new j({sessionIdGenerator:()=>t(),onsessioninitialized:async e=>{P=e,k?.onSessionStart(e,{transport:`http`})},onsessionclosed:async e=>{e&&k?.onSessionEnd(e),P=null}});e.onclose=()=>{N===e&&(N=null),P===e.sessionId&&(P=null)},N=e,await A.connect(e)}let i=N;await i.handleRequest(e,n,e.body),e.method!==`DELETE`&&(!r&&i.sessionId?(P=i.sessionId,k?.onSessionStart(i.sessionId,{transport:`http`}),k?.onSessionActivity(i.sessionId)):r&&k?.onSessionActivity(r))}catch(e){if(Z.error(`MCP handler error`,d(e)),!n.headersSent){let t=e instanceof Error?e.message:String(e),r=t.includes(`Not Acceptable`);n.status(r?406:500).json({jsonrpc:`2.0`,error:{code:r?-32e3:-32603,message:r?t:`Internal server error`},id:null})}}finally{i()}},I=async(e,t)=>{let n=Q(e);if(M&&(!N||n!==P)){await M.handleRequest(e,t,e.body);return}await te(e,t)};h.post(`/mcp`,I),h.get(`/mcp`,I),h.delete(`/mcp`,I);let ne=h.listen(g,`127.0.0.1`,()=>{Z.info(`MCP server listening`,{url:`http://127.0.0.1:${g}/mcp`,port:g}),setTimeout(async()=>{try{let[{createLazyServer:e,createMcpServer:t,ALL_TOOL_NAMES:n},{StreamableHTTPServerTransport:i},{checkForUpdates:o,autoUpgradeScaffold:s}]=await Promise.all([import(`./server-SleKFw4B.js`),import(`@modelcontextprotocol/sdk/server/streamableHttp.js`),import(`./version-check-gazMo-D4.js`)]);o(),s();let c=a(m),l=e(m,c);A=l.server,j=i,D=!0,Z.info(`MCP server configured (lazy — AI Kit initializing in background)`,{toolCount:n.length,resourceCount:2}),l.startInit(),l.ready.then(()=>{if(!l.aikit)throw Error(`AI Kit components are not available after initialization`);k=new Me(l.aikit.stateStore,{staleTimeoutMinutes:x,gcIntervalMinutes:S,onBeforeSessionDelete:e=>{if(P===e&&N){let e=N;N=null,P=null,e.close().catch(()=>void 0)}M?.closeSession(e,{notifySessionEnd:!1})},onSessionEndMaintenance:async()=>{if(!l.aikit?.curated||!l.aikit?.stateStore)return;let{pruneLessons:e}=await import(`./evolution-9hXRopDC.js`).then(e=>e.t),t=await e(l.aikit.curated,l.aikit.stateStore,{dryRun:!1});t.pruned.length>0&&Z.info(`Session-end lesson prune`,{pruned:t.pruned.length})}}),M=new ee({createServer:()=>{if(!l.aikit)throw Error(`AI Kit components are not available after initialization`);return t(l.aikit,m)},createTransport:e=>new i(e),maxSessions:b,sessionTimeoutMinutes:x,onSessionStart:e=>k?.onSessionStart(e,{transport:`http`}),onSessionActivity:e=>k?.onSessionActivity(e),onSessionEnd:e=>k?.onSessionEnd(e)}),k.startGC(),P&&(k.onSessionStart(P,{transport:`http`}),k.onSessionActivity(P)),Ke(()=>l.aikit?{curated:l.aikit.curated,stateStore:l.aikit.stateStore}:null),Z.info(`HTTP session runtime ready`,{maxSessions:b,sessionTimeoutMinutes:x,gcIntervalMinutes:S})}).catch(e=>Z.error(`Failed to start session manager`,d(e))),c===`auto`?l.ready.then(async()=>{try{let e=m.sources.map(e=>e.path).join(`, `);Z.info(`Running initial index`,{sourcePaths:e}),await l.runInitialIndex(),Z.info(`Initial index complete`)}catch(e){Z.error(`Initial index failed; will retry on aikit_reindex`,d(e))}}).catch(e=>Z.error(`AI Kit init or indexing failed`,d(e))):c===`smart`?l.ready.then(async()=>{try{if(!l.aikit)throw Error(`AI Kit components are not available after initialization`);let{SmartIndexScheduler:e}=await import(`../../indexer/dist/index.js`),t=new e(l.aikit.indexer,m,l.aikit.store),n=l.aikit.store;O=t,t.start(),n.onBeforeClose&&n.onBeforeClose(()=>t.stop()),l.setSmartScheduler(t),Z.info(`Smart index scheduler started (HTTP mode)`)}catch(e){Z.error(`Failed to start smart index scheduler`,d(e))}}).catch(e=>Z.error(`AI Kit initialization failed`,d(e))):(l.ready.catch(e=>Z.error(`AI Kit initialization failed`,d(e))),Z.info(`Initial full indexing skipped in HTTP mode`,{indexMode:c})),r(l.ready,()=>l.aikit?{curated:l.aikit.curated,stateStore:l.aikit.stateStore}:null)}catch(e){Z.error(`Failed to load server modules`,d(e))}},100)}),L=async e=>{Z.info(`Shutdown signal received`,{signal:e}),O?.stop(),k?.stop(),await M?.closeAll().catch(()=>void 0),P&&k?.onSessionEnd(P),N&&(await N.close().catch(()=>void 0),N=null,P=null),ne.close(),A&&await A.close(),process.exit(0)};process.on(`SIGINT`,()=>L(`SIGINT`)),process.on(`SIGTERM`,()=>L(`SIGTERM`))}else{let[{loadConfig:e,reconfigureForWorkspace:t,resolveIndexMode:n},{createLazyServer:i},{checkForUpdates:a,autoUpgradeScaffold:o},{RootsListChangedNotificationSchema:c}]=await Promise.all([import(`./config-C4mVyqAF.js`),import(`./server-SleKFw4B.js`),import(`./version-check-gazMo-D4.js`),import(`@modelcontextprotocol/sdk/types.js`)]),l=e();Z.info(`Config loaded`,{sourceCount:l.sources.length,storePath:l.store.path}),a(),o();let u=n(l),f=i(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),Z.info(`MCP server started`,{transport:`stdio`});let y=e=>{if(e.length===0)return!1;let n=e[0].uri,r=n.startsWith(`file://`)?s(n):n;return Z.info(`MCP roots resolved`,{rootUri:n,rootPath:r,rootCount:e.length}),t(l,r),l.allRoots=e.map(e=>{let t=e.uri;return t.startsWith(`file://`)?s(t):t}),!0},b=!1;try{b=y((await p.server.listRoots()).roots),b||Z.info(`No MCP roots yet; waiting for roots/list_changed notification`)}catch(e){Z.warn(`MCP roots/list not supported by client; using cwd fallback`,{cwd:process.cwd(),...d(e)}),b=!0}b||=await new Promise(e=>{let t=setTimeout(()=>{Z.warn(`Timed out waiting for MCP roots/list_changed; using cwd fallback`,{cwd:process.cwd()}),e(!1)},5e3);p.server.setNotificationHandler(c,async()=>{clearTimeout(t);try{e(y((await p.server.listRoots()).roots))}catch(t){Z.warn(`roots/list retry failed after notification`,d(t)),e(!1)}})}),m();let x=null,S=()=>{x&&clearTimeout(x),x=setTimeout(async()=>{Z.info(`Auto-shutdown: no activity for 30 minutes — shutting down gracefully`);try{let e=f.aikit;e&&await Promise.all([e.embedder.shutdown?.().catch(()=>{})??Promise.resolve(),e.graphStore.close().catch(()=>{}),e.store.close().catch(()=>{})])}catch{}process.exit(0)},18e5),x.unref&&x.unref()};S(),process.stdin.on(`data`,()=>S()),h.catch(e=>{Z.error(`Initialization failed — server will continue with limited tools`,d(e))}),h.then(()=>{Ke(()=>f.aikit?{curated:f.aikit.curated,stateStore:f.aikit.stateStore}:null)}).catch(()=>{}),u===`auto`?g().catch(e=>Z.error(`Initial index failed`,d(e))):u===`smart`?h.then(async()=>{try{if(!f.aikit)throw Error(`AI Kit components are not available after initialization`);let{SmartIndexScheduler:e}=await import(`../../indexer/dist/index.js`),t=new e(f.aikit.indexer,l,f.aikit.store),n=f.aikit.store;t.start(),n.onBeforeClose&&n.onBeforeClose(()=>t.stop()),f.setSmartScheduler(t),Z.info(`Smart index scheduler started (stdio mode)`)}catch(e){Z.error(`Failed to start smart index scheduler`,d(e))}}).catch(e=>Z.error(`AI Kit init failed for smart scheduler`,d(e))):Z.warn(`Initial full indexing skipped; use aikit_reindex to index manually`,{indexMode:u}),r(h,()=>f.aikit?{curated:f.aikit.curated,stateStore:f.aikit.stateStore}:null)}}qe();export{V as a,L as c,ie as d,R as f,De as i,re as l,E as m,Ne as n,ve as o,I as p,Ae as r,_e as s,Le as t,B as u};
@@ -1 +1 @@
1
- import{r as e}from"./replay-interceptor-CGLyom5f.js";import{t}from"./curated-manager-D1u5qOwK.js";import{randomUUID as n}from"node:crypto";import{readFileSync as r}from"node:fs";import{dirname as i,resolve as a}from"node:path";import{fileURLToPath as o,pathToFileURL as s}from"node:url";import{parseArgs as c}from"node:util";import{createLogger as l,serializeError as u}from"../../core/dist/index.js";const d=`__pending__:`;function f(e){return e.startsWith(d)}function p(e){let t=e.headers[`mcp-session-id`];return Array.isArray(t)?t[0]:t}function m(e,t,n,r){e.status(t).json({jsonrpc:`2.0`,error:{code:n,message:r},id:null})}var h=class{options;runtimes=new Map;maxSessions;sessionTimeoutMs;now;constructor(e){this.options=e,this.maxSessions=e.maxSessions??8,this.sessionTimeoutMs=(e.sessionTimeoutMinutes??30)*60*1e3,this.now=e.now??(()=>Date.now())}hasSession(e){return this.runtimes.has(e)}getSessionCount(){return this.runtimes.size}async handleRequest(e,t,n=e.body){let r=p(e),i=r?this.runtimes.get(r):void 0;if(r&&!i){m(t,404,-32001,`Session not found`);return}if(!i){if(e.method!==`POST`){m(t,400,-32e3,`Session required`);return}if(i=await this.createRuntime(t),!i)return}await this.withRuntimeLock(i,async()=>{await i.transport.handleRequest(e,t,n),i.lastAccessAt=this.now();let r=i.transport.sessionId??i.id;e.method!==`DELETE`&&!f(r)&&this.options.onSessionActivity?.(r),e.method===`DELETE`&&!f(r)&&await this.closeSession(r,{closeTransport:!1})})}async closeExpiredSessions(){let e=[...this.runtimes.values()].filter(e=>this.now()-e.lastAccessAt>=this.sessionTimeoutMs).map(e=>e.id);for(let t of e)await this.closeSession(t);return e.length}async closeSession(e,t={}){let n=this.runtimes.get(e);return n?(this.runtimes.delete(e),t.notifySessionEnd!==!1&&!f(e)&&this.options.onSessionEnd?.(e),t.closeTransport!==!1&&await n.transport.close().catch(()=>void 0),await n.server.close().catch(()=>void 0),!0):!1}async closeAll(){let e=[...this.runtimes.keys()];for(let t of e)await this.closeSession(t)}async createRuntime(e){if(await this.closeExpiredSessions(),this.runtimes.size>=this.maxSessions){m(e,503,-32003,`Session capacity reached`);return}let t=this.now(),r=await this.options.createServer(),i={id:`${d}${n()}`,transport:void 0,createdAt:t,lastAccessAt:t,server:r,requestChain:Promise.resolve()},a=this.options.createTransport({sessionIdGenerator:()=>n(),onsessioninitialized:async e=>{this.runtimes.delete(i.id),i.id=e,this.runtimes.set(e,i),this.options.onSessionStart?.(e)},onsessionclosed:async e=>{e&&await this.closeSession(e,{closeTransport:!1})}});return i.transport=a,a.onclose=()=>{let e=i.transport.sessionId??i.id;this.closeSession(e,{closeTransport:!1})},this.runtimes.set(i.id,i),await r.connect(a),i}async withRuntimeLock(e,t){let n=e.requestChain,r;e.requestChain=new Promise(e=>{r=e}),await n;try{await t()}finally{r()}}};function g(e){let t=e.includes(`T`)?e:`${e.replace(` `,`T`)}Z`;return Date.parse(t)}var _=class{stateStore;options;gcTimer=null;constructor(e,t={}){this.stateStore=e,this.options=t}onSessionStart(e,t){this.stateStore.sessionCreate(e,t)}onSessionActivity(e){this.stateStore.sessionTouch(e)}onSessionEnd(e){this.stateStore.sessionDelete(e),Promise.resolve(this.options.onSessionEndMaintenance?.(e)).catch(()=>{})}startGC(){if(this.gcTimer)return;let e=(this.options.gcIntervalMinutes??5)*60*1e3;this.gcTimer=setInterval(()=>{this.runGC()},e),this.gcTimer.unref()}runGC(){let e=this.getStaleSessionIds();for(let t of e)this.options.onBeforeSessionDelete?.(t),Promise.resolve(this.options.onSessionEndMaintenance?.(t)).catch(()=>{}),this.stateStore.sessionDelete(t);return e.length}stop(){this.gcTimer&&=(clearInterval(this.gcTimer),null)}getActiveSessions(){return this.stateStore.sessionList().length}listSessions(){return this.stateStore.sessionList()}getStaleSessionIds(e=Date.now()){let t=(this.options.staleTimeoutMinutes??30)*60*1e3;return this.stateStore.sessionList().filter(n=>{let r=g(n.lastActivity);return Number.isFinite(r)&&e-r>=t}).map(e=>e.sessionId)}};function v(){try{let e=a(i(o(import.meta.url)),`..`,`..`,`..`,`package.json`);return JSON.parse(r(e,`utf-8`)).version??`0.0.0`}catch{return`0.0.0`}}const y=l(`server`),b=/^https?:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/i;function x({requestOrigin:e,configuredOrigin:t,allowAnyOrigin:n,fallbackOrigin:r}){let i=t??r;return i===`*`?n?{allowOrigin:`*`,warn:!1}:e?b.test(e)?{allowOrigin:e,warn:!1}:{allowOrigin:null,warn:!0}:{allowOrigin:r,warn:!1}:{allowOrigin:i,warn:!1}}function S({limit:e,windowMs:t}){let n=new Map,r=(e,r)=>{let i=r-t,a=n.get(e)?.filter(e=>e>i)??[];return a.length===0?(n.delete(e),[]):(n.set(e,a),a)};return{allow(t,i=Date.now()){let a=r(t,i);return a.length>=e?!1:(a.push(i),n.set(t,a),!0)},getRetryAfterMs(n,i=Date.now()){let a=r(n,i);return a.length<e?0:Math.max(0,a[0]+t-i)}}}function C(){return process.env.AIKIT_TRANSPORT?process.env.AIKIT_TRANSPORT:process.stdin.isTTY?`http`:`stdio`}function w(){let e=process.argv[1];if(!e)return!1;try{return import.meta.url===s(e).href}catch{return!1}}function T(e){let t=e.headers[`mcp-session-id`];return Array.isArray(t)?t[0]:t}function E(e,t){let n=process.env[e];if(!n)return t;let r=Number.parseInt(n,10);return Number.isFinite(r)&&r>0?r:t}function D(){return w()?c({allowPositionals:!0,options:{transport:{type:`string`,default:C()},port:{type:`string`,default:process.env.AIKIT_PORT??`3210`}}}).values:{transport:C(),port:process.env.AIKIT_PORT??`3210`}}function O(e){return`## Context\n${e.context}\n\n## Insight\n${e.insight}\n\n## Evidence\n${e.evidence}`}function k(t){e(e=>{(async()=>{let n=t();if(!n)return;let{jaccardSimilarity:r}=await import(`./supersession-9edUDEQ8.js`).then(e=>e.o),i=await n.curated.list({category:`lessons`});for(let t of e)i.some(e=>r(t.title,e.title)>.6)||(await n.curated.remember(t.title,O(t),`lessons`,[`lesson`,`auto-observed`,`detector:${t.detector}`]),i.push({path:`lessons/${t.title}`,title:t.title,category:`lessons`,tags:[`lesson`,`auto-observed`,`detector:${t.detector}`],version:1,created:new Date().toISOString(),updated:new Date().toISOString(),contentPreview:t.insight.slice(0,200)}))})().catch(()=>{})})}async function A(){let e=v(),t=D();process.on(`unhandledRejection`,e=>{y.error(`Unhandled rejection`,u(e))}),process.on(`uncaughtException`,e=>{y.error(`Uncaught exception — exiting`,u(e)),process.exit(1)});let r=(e,t)=>{e.then(async()=>{try{let{markPromoteRun:e,markPruneRun:n,prune:r,shouldRunStartupPrune:i,shouldRunWeeklyPromote:a}=await import(`../../tools/dist/index.js`),o=t();if(!o)return;if(i()){let e=await r({});n(),e.totalBytesFreed>0&&y.info(`Storage maintenance complete`,{forgeOrphans:e.forgeGroundOrphans.count,legacyLance:e.legacyLance.count,bytesFreed:e.totalBytesFreed});let{groupLessons:t,pruneLessons:i}=await import(`./evolution-DJhTM6nu.js`).then(e=>e.t),a=await i(o.curated,o.stateStore,{dryRun:!1});a.pruned.length>0&&y.info(`Startup lesson prune complete`,{pruned:a.pruned.length});let s=await t(o.curated,o.stateStore,{dryRun:!1});(s.groupsCreated>0||s.lessonsGrouped>0)&&y.info(`Startup lesson grouping complete`,{groupsCreated:s.groupsCreated,lessonsGrouped:s.lessonsGrouped})}if(a()){let{DEFAULT_PROMOTE_CONFIG:t,collectWorkspaceLessons:n,getGlobalCuratedDir:r,promoteLessons:i,scanForDuplicates:a}=await import(`./promotion-OY53YCsT.js`).then(e=>e.o),{CuratedKnowledgeManager:s}=await import(`./curated-manager-D1u5qOwK.js`).then(e=>e.n),c=o.curated,l=new s(r(),c.store,c.embedder),u=await n(),d={...t,dryRun:!1},f=await i(a(u,d),l,d);e(),f.promoted.length>0&&y.info(`Weekly lesson promotion complete`,{promoted:f.promoted.length,candidates:f.candidates.length})}}catch(e){y.warn(`Startup maintenance failed (non-critical)`,u(e))}}).catch(()=>{})};if(y.info(`Starting MCP AI Kit server`,{version:e}),t.transport===`http`){let[{default:e},{loadConfig:i,resolveIndexMode:a},{registerDashboardRoutes:o,resolveDashboardDir:s},{registerSettingsRoutes:c,resolveSettingsDir:l},{createSettingsRouter:d},{authMiddleware:f,getOrCreateToken:p}]=await Promise.all([import(`express`),import(`./config-jGZ91cRx.js`),import(`./dashboard-static-FmfoS46e.js`),import(`./settings-static-BtvyIrza.js`),import(`./routes-CR3fI-HJ.js`),import(`./auth-Bz5dmZgR.js`).then(e=>e.t)]),m=i();y.info(`Config loaded`,{sourceCount:m.sources.length,storePath:m.store.path});let g=e();g.use(e.json({limit:`1mb`}));let v=Number(t.port),b=`http://localhost:${v}`,C=process.env.AIKIT_CORS_ORIGIN??b,w=process.env.AIKIT_ALLOW_ANY_ORIGIN===`true`,D=E(`AIKIT_HTTP_MAX_SESSIONS`,8),O=E(`AIKIT_HTTP_SESSION_TIMEOUT_MINUTES`,30),A=E(`AIKIT_HTTP_SESSION_GC_INTERVAL_MINUTES`,5),j=S({limit:100,windowMs:6e4}),M=!1;g.use((e,t,n)=>{let r=Array.isArray(e.headers.origin)?e.headers.origin[0]:e.headers.origin,i=x({requestOrigin:r,configuredOrigin:C,allowAnyOrigin:w,fallbackOrigin:b});if(i.warn&&!M&&(M=!0,y.warn(`Rejected non-local CORS origin while AIKIT_CORS_ORIGIN=*`,{origin:r,allowAnyOriginEnv:`AIKIT_ALLOW_ANY_ORIGIN=true`})),r&&!i.allowOrigin){t.status(403).json({error:`Origin not allowed`});return}if(i.allowOrigin&&t.setHeader(`Access-Control-Allow-Origin`,i.allowOrigin),t.setHeader(`Access-Control-Allow-Methods`,`GET, POST, PUT, PATCH, DELETE, OPTIONS`),t.setHeader(`Access-Control-Allow-Headers`,`Content-Type, Authorization, Mcp-Session-Id, Mcp-Protocol-Version, Last-Event-ID`),t.setHeader(`Access-Control-Expose-Headers`,`Mcp-Session-Id`),e.method===`OPTIONS`){t.status(204).end();return}n()});let N=p();console.error(`[aikit] Auth token: ~/.aikit/token`),g.use(f(N)),g.use(`/mcp`,(e,t,n)=>{let r=T(e)??e.ip??e.socket.remoteAddress??`anonymous`;if(j.allow(r)){n();return}let i=Math.max(1,Math.ceil(j.getRetryAfterMs(r)/1e3));t.setHeader(`Retry-After`,String(i)),t.status(429).json({jsonrpc:`2.0`,error:{code:-32003,message:`Rate limit exceeded`},id:null})}),o(g,s(),y);let P=new Date().toISOString();g.use(`/settings/api`,d({log:y,mcpInfo:()=>({transport:`http`,port:v,pid:process.pid,startedAt:P})})),c(g,l(),y),g.get(`/health`,(e,t)=>{t.json({status:`ok`})});let F=!1,I=null,L=null,R=null,z=null,B=null,V=null,H=null,U=Promise.resolve(),W=async(e,t)=>{if(!F||!R||!z){t.status(503).json({jsonrpc:`2.0`,error:{code:-32603,message:`Server initializing — please retry in a few seconds`},id:null});return}let r=U,i;U=new Promise(e=>{i=e}),await r;try{let r=T(e);if(!V){if(r){t.status(404).json({jsonrpc:`2.0`,error:{code:-32001,message:`Session not found`},id:null});return}let e=new z({sessionIdGenerator:()=>n(),onsessioninitialized:async e=>{H=e,L?.onSessionStart(e,{transport:`http`})},onsessionclosed:async e=>{e&&L?.onSessionEnd(e),H=null}});e.onclose=()=>{V===e&&(V=null),H===e.sessionId&&(H=null)},V=e,await R.connect(e)}let i=V;await i.handleRequest(e,t,e.body),e.method!==`DELETE`&&(!r&&i.sessionId?(H=i.sessionId,L?.onSessionStart(i.sessionId,{transport:`http`}),L?.onSessionActivity(i.sessionId)):r&&L?.onSessionActivity(r))}catch(e){if(y.error(`MCP handler error`,u(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{i()}},G=async(e,t)=>{let n=T(e);if(B&&(!V||n!==H)){await B.handleRequest(e,t,e.body);return}await W(e,t)};g.post(`/mcp`,G),g.get(`/mcp`,G),g.delete(`/mcp`,G);let K=g.listen(v,`127.0.0.1`,()=>{y.info(`MCP server listening`,{url:`http://127.0.0.1:${v}/mcp`,port:v}),setTimeout(async()=>{try{let[{createLazyServer:e,createMcpServer:t,ALL_TOOL_NAMES:n},{StreamableHTTPServerTransport:i},{checkForUpdates:o,autoUpgradeScaffold:s}]=await Promise.all([import(`./server-CtFr8YsZ.js`),import(`@modelcontextprotocol/sdk/server/streamableHttp.js`),import(`./version-check-D_uN0n0Y.js`)]);o(),s();let c=a(m),l=e(m,c);R=l.server,z=i,F=!0,y.info(`MCP server configured (lazy — AI Kit initializing in background)`,{toolCount:n.length,resourceCount:2}),l.startInit(),l.ready.then(()=>{if(!l.aikit)throw Error(`AI Kit components are not available after initialization`);L=new _(l.aikit.stateStore,{staleTimeoutMinutes:O,gcIntervalMinutes:A,onBeforeSessionDelete:e=>{if(H===e&&V){let e=V;V=null,H=null,e.close().catch(()=>void 0)}B?.closeSession(e,{notifySessionEnd:!1})},onSessionEndMaintenance:async()=>{if(!l.aikit?.curated||!l.aikit?.stateStore)return;let{pruneLessons:e}=await import(`./evolution-DJhTM6nu.js`).then(e=>e.t),t=await e(l.aikit.curated,l.aikit.stateStore,{dryRun:!1});t.pruned.length>0&&y.info(`Session-end lesson prune`,{pruned:t.pruned.length})}}),B=new h({createServer:()=>{if(!l.aikit)throw Error(`AI Kit components are not available after initialization`);return t(l.aikit,m)},createTransport:e=>new i(e),maxSessions:D,sessionTimeoutMinutes:O,onSessionStart:e=>L?.onSessionStart(e,{transport:`http`}),onSessionActivity:e=>L?.onSessionActivity(e),onSessionEnd:e=>L?.onSessionEnd(e)}),L.startGC(),H&&(L.onSessionStart(H,{transport:`http`}),L.onSessionActivity(H)),k(()=>l.aikit?{curated:l.aikit.curated,stateStore:l.aikit.stateStore}:null),y.info(`HTTP session runtime ready`,{maxSessions:D,sessionTimeoutMinutes:O,gcIntervalMinutes:A})}).catch(e=>y.error(`Failed to start session manager`,u(e))),c===`auto`?l.ready.then(async()=>{try{let e=m.sources.map(e=>e.path).join(`, `);y.info(`Running initial index`,{sourcePaths:e}),await l.runInitialIndex(),y.info(`Initial index complete`)}catch(e){y.error(`Initial index failed; will retry on aikit_reindex`,u(e))}}).catch(e=>y.error(`AI Kit init or indexing failed`,u(e))):c===`smart`?l.ready.then(async()=>{try{if(!l.aikit)throw Error(`AI Kit components are not available after initialization`);let{SmartIndexScheduler:e}=await import(`../../indexer/dist/index.js`),t=new e(l.aikit.indexer,m,l.aikit.store),n=l.aikit.store;I=t,t.start(),n.onBeforeClose&&n.onBeforeClose(()=>t.stop()),l.setSmartScheduler(t),y.info(`Smart index scheduler started (HTTP mode)`)}catch(e){y.error(`Failed to start smart index scheduler`,u(e))}}).catch(e=>y.error(`AI Kit initialization failed`,u(e))):(l.ready.catch(e=>y.error(`AI Kit initialization failed`,u(e))),y.info(`Initial full indexing skipped in HTTP mode`,{indexMode:c})),r(l.ready,()=>l.aikit?{curated:l.aikit.curated,stateStore:l.aikit.stateStore}:null)}catch(e){y.error(`Failed to load server modules`,u(e))}},100)}),q=async e=>{y.info(`Shutdown signal received`,{signal:e}),I?.stop(),L?.stop(),await B?.closeAll().catch(()=>void 0),H&&L?.onSessionEnd(H),V&&(await V.close().catch(()=>void 0),V=null,H=null),K.close(),R&&await R.close(),process.exit(0)};process.on(`SIGINT`,()=>q(`SIGINT`)),process.on(`SIGTERM`,()=>q(`SIGTERM`))}else{let[{loadConfig:e,reconfigureForWorkspace:t,resolveIndexMode:n},{createLazyServer:i},{checkForUpdates:a,autoUpgradeScaffold:s},{RootsListChangedNotificationSchema:c}]=await Promise.all([import(`./config-jGZ91cRx.js`),import(`./server-CtFr8YsZ.js`),import(`./version-check-D_uN0n0Y.js`),import(`@modelcontextprotocol/sdk/types.js`)]),l=e();y.info(`Config loaded`,{sourceCount:l.sources.length,storePath:l.store.path}),a(),s();let d=n(l),f=i(l,d),{server:p,startInit:m,ready:h,runInitialIndex:g}=f,{StdioServerTransport:_}=await import(`@modelcontextprotocol/sdk/server/stdio.js`),v=new _;await p.connect(v),y.info(`MCP server started`,{transport:`stdio`});let b=e=>{if(e.length===0)return!1;let n=e[0].uri,r=n.startsWith(`file://`)?o(n):n;return y.info(`MCP roots resolved`,{rootUri:n,rootPath:r,rootCount:e.length}),t(l,r),l.allRoots=e.map(e=>{let t=e.uri;return t.startsWith(`file://`)?o(t):t}),!0},x=!1;try{x=b((await p.server.listRoots()).roots),x||y.info(`No MCP roots yet; waiting for roots/list_changed notification`)}catch(e){y.warn(`MCP roots/list not supported by client; using cwd fallback`,{cwd:process.cwd(),...u(e)}),x=!0}x||=await new Promise(e=>{let t=setTimeout(()=>{y.warn(`Timed out waiting for MCP roots/list_changed; using cwd fallback`,{cwd:process.cwd()}),e(!1)},5e3);p.server.setNotificationHandler(c,async()=>{clearTimeout(t);try{e(b((await p.server.listRoots()).roots))}catch(t){y.warn(`roots/list retry failed after notification`,u(t)),e(!1)}})}),m();let S=null,C=()=>{S&&clearTimeout(S),S=setTimeout(async()=>{y.info(`Auto-shutdown: no activity for 30 minutes — shutting down gracefully`);try{let e=f.aikit;e&&await Promise.all([e.embedder.shutdown?.().catch(()=>{})??Promise.resolve(),e.graphStore.close().catch(()=>{}),e.store.close().catch(()=>{})])}catch{}process.exit(0)},18e5),S.unref&&S.unref()};C(),process.stdin.on(`data`,()=>C()),h.catch(e=>{y.error(`Initialization failed — server will continue with limited tools`,u(e))}),h.then(()=>{k(()=>f.aikit?{curated:f.aikit.curated,stateStore:f.aikit.stateStore}:null)}).catch(()=>{}),d===`auto`?g().catch(e=>y.error(`Initial index failed`,u(e))):d===`smart`?h.then(async()=>{try{if(!f.aikit)throw Error(`AI Kit components are not available after initialization`);let{SmartIndexScheduler:e}=await import(`../../indexer/dist/index.js`),t=new e(f.aikit.indexer,l,f.aikit.store),n=f.aikit.store;t.start(),n.onBeforeClose&&n.onBeforeClose(()=>t.stop()),f.setSmartScheduler(t),y.info(`Smart index scheduler started (stdio mode)`)}catch(e){y.error(`Failed to start smart index scheduler`,u(e))}}).catch(e=>y.error(`AI Kit init failed for smart scheduler`,u(e))):y.warn(`Initial full indexing skipped; use aikit_reindex to index manually`,{indexMode:d}),r(h,()=>f.aikit?{curated:f.aikit.curated,stateStore:f.aikit.stateStore}:null)}}export{t as CuratedKnowledgeManager,S as createSlidingWindowRateLimiter,A as main,x as resolveCorsOrigin};
1
+ import{r as e}from"./replay-interceptor-CGLyom5f.js";import{t}from"./curated-manager-D1u5qOwK.js";import{randomUUID as n}from"node:crypto";import{readFileSync as r}from"node:fs";import{dirname as i,resolve as a}from"node:path";import{fileURLToPath as o,pathToFileURL as s}from"node:url";import{parseArgs as c}from"node:util";import{createLogger as l,serializeError as u}from"../../core/dist/index.js";const d=`__pending__:`;function f(e){return e.startsWith(d)}function p(e){let t=e.headers[`mcp-session-id`];return Array.isArray(t)?t[0]:t}function m(e,t,n,r){e.status(t).json({jsonrpc:`2.0`,error:{code:n,message:r},id:null})}var h=class{options;runtimes=new Map;maxSessions;sessionTimeoutMs;now;constructor(e){this.options=e,this.maxSessions=e.maxSessions??8,this.sessionTimeoutMs=(e.sessionTimeoutMinutes??30)*60*1e3,this.now=e.now??(()=>Date.now())}hasSession(e){return this.runtimes.has(e)}getSessionCount(){return this.runtimes.size}async handleRequest(e,t,n=e.body){let r=p(e),i=r?this.runtimes.get(r):void 0;if(r&&!i){m(t,404,-32001,`Session not found`);return}if(!i){if(e.method!==`POST`){m(t,400,-32e3,`Session required`);return}if(i=await this.createRuntime(t),!i)return}await this.withRuntimeLock(i,async()=>{await i.transport.handleRequest(e,t,n),i.lastAccessAt=this.now();let r=i.transport.sessionId??i.id;e.method!==`DELETE`&&!f(r)&&this.options.onSessionActivity?.(r),e.method===`DELETE`&&!f(r)&&await this.closeSession(r,{closeTransport:!1})})}async closeExpiredSessions(){let e=[...this.runtimes.values()].filter(e=>this.now()-e.lastAccessAt>=this.sessionTimeoutMs).map(e=>e.id);for(let t of e)await this.closeSession(t);return e.length}async closeSession(e,t={}){let n=this.runtimes.get(e);return n?(this.runtimes.delete(e),t.notifySessionEnd!==!1&&!f(e)&&this.options.onSessionEnd?.(e),t.closeTransport!==!1&&await n.transport.close().catch(()=>void 0),await n.server.close().catch(()=>void 0),!0):!1}async closeAll(){let e=[...this.runtimes.keys()];for(let t of e)await this.closeSession(t)}async createRuntime(e){if(await this.closeExpiredSessions(),this.runtimes.size>=this.maxSessions){m(e,503,-32003,`Session capacity reached`);return}let t=this.now(),r=await this.options.createServer(),i={id:`${d}${n()}`,transport:void 0,createdAt:t,lastAccessAt:t,server:r,requestChain:Promise.resolve()},a=this.options.createTransport({sessionIdGenerator:()=>n(),onsessioninitialized:async e=>{this.runtimes.delete(i.id),i.id=e,this.runtimes.set(e,i),this.options.onSessionStart?.(e)},onsessionclosed:async e=>{e&&await this.closeSession(e,{closeTransport:!1})}});return i.transport=a,a.onclose=()=>{let e=i.transport.sessionId??i.id;this.closeSession(e,{closeTransport:!1})},this.runtimes.set(i.id,i),await r.connect(a),i}async withRuntimeLock(e,t){let n=e.requestChain,r;e.requestChain=new Promise(e=>{r=e}),await n;try{await t()}finally{r()}}};function g(e){let t=e.includes(`T`)?e:`${e.replace(` `,`T`)}Z`;return Date.parse(t)}var _=class{stateStore;options;gcTimer=null;constructor(e,t={}){this.stateStore=e,this.options=t}onSessionStart(e,t){this.stateStore.sessionCreate(e,t)}onSessionActivity(e){this.stateStore.sessionTouch(e)}onSessionEnd(e){this.stateStore.sessionDelete(e),Promise.resolve(this.options.onSessionEndMaintenance?.(e)).catch(()=>{})}startGC(){if(this.gcTimer)return;let e=(this.options.gcIntervalMinutes??5)*60*1e3;this.gcTimer=setInterval(()=>{this.runGC()},e),this.gcTimer.unref()}runGC(){let e=this.getStaleSessionIds();for(let t of e)this.options.onBeforeSessionDelete?.(t),Promise.resolve(this.options.onSessionEndMaintenance?.(t)).catch(()=>{}),this.stateStore.sessionDelete(t);return e.length}stop(){this.gcTimer&&=(clearInterval(this.gcTimer),null)}getActiveSessions(){return this.stateStore.sessionList().length}listSessions(){return this.stateStore.sessionList()}getStaleSessionIds(e=Date.now()){let t=(this.options.staleTimeoutMinutes??30)*60*1e3;return this.stateStore.sessionList().filter(n=>{let r=g(n.lastActivity);return Number.isFinite(r)&&e-r>=t}).map(e=>e.sessionId)}};function v(){try{let e=a(i(o(import.meta.url)),`..`,`..`,`..`,`package.json`);return JSON.parse(r(e,`utf-8`)).version??`0.0.0`}catch{return`0.0.0`}}const y=l(`server`),b=/^https?:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/i;function x({requestOrigin:e,configuredOrigin:t,allowAnyOrigin:n,fallbackOrigin:r}){let i=t??r;return i===`*`?n?{allowOrigin:`*`,warn:!1}:e?b.test(e)?{allowOrigin:e,warn:!1}:{allowOrigin:null,warn:!0}:{allowOrigin:r,warn:!1}:{allowOrigin:i,warn:!1}}function S({limit:e,windowMs:t}){let n=new Map,r=(e,r)=>{let i=r-t,a=n.get(e)?.filter(e=>e>i)??[];return a.length===0?(n.delete(e),[]):(n.set(e,a),a)};return{allow(t,i=Date.now()){let a=r(t,i);return a.length>=e?!1:(a.push(i),n.set(t,a),!0)},getRetryAfterMs(n,i=Date.now()){let a=r(n,i);return a.length<e?0:Math.max(0,a[0]+t-i)}}}function C(){return process.env.AIKIT_TRANSPORT?process.env.AIKIT_TRANSPORT:process.stdin.isTTY?`http`:`stdio`}function w(){let e=process.argv[1];if(!e)return!1;try{return import.meta.url===s(e).href}catch{return!1}}function T(e){let t=e.headers[`mcp-session-id`];return Array.isArray(t)?t[0]:t}function E(e,t){let n=process.env[e];if(!n)return t;let r=Number.parseInt(n,10);return Number.isFinite(r)&&r>0?r:t}function D(){return w()?c({allowPositionals:!0,options:{transport:{type:`string`,default:C()},port:{type:`string`,default:process.env.AIKIT_PORT??`3210`}}}).values:{transport:C(),port:process.env.AIKIT_PORT??`3210`}}function O(e){return`## Context\n${e.context}\n\n## Insight\n${e.insight}\n\n## Evidence\n${e.evidence}`}function k(t){e(e=>{(async()=>{let n=t();if(!n)return;let{jaccardSimilarity:r}=await import(`./supersession-9edUDEQ8.js`).then(e=>e.o),i=await n.curated.list({category:`lessons`});for(let t of e)i.some(e=>r(t.title,e.title)>.6)||(await n.curated.remember(t.title,O(t),`lessons`,[`lesson`,`auto-observed`,`detector:${t.detector}`]),i.push({path:`lessons/${t.title}`,title:t.title,category:`lessons`,tags:[`lesson`,`auto-observed`,`detector:${t.detector}`],version:1,created:new Date().toISOString(),updated:new Date().toISOString(),contentPreview:t.insight.slice(0,200)}))})().catch(()=>{})})}async function A(){let e=v(),t=D();process.on(`unhandledRejection`,e=>{y.error(`Unhandled rejection`,u(e))}),process.on(`uncaughtException`,e=>{y.error(`Uncaught exception — exiting`,u(e)),process.exit(1)});let r=(e,t)=>{e.then(async()=>{try{let{markPromoteRun:e,markPruneRun:n,prune:r,shouldRunStartupPrune:i,shouldRunWeeklyPromote:a}=await import(`../../tools/dist/index.js`),o=t();if(!o)return;if(i()){let e=await r({});n(),e.totalBytesFreed>0&&y.info(`Storage maintenance complete`,{forgeOrphans:e.forgeGroundOrphans.count,legacyLance:e.legacyLance.count,bytesFreed:e.totalBytesFreed});let{groupLessons:t,pruneLessons:i}=await import(`./evolution-DJhTM6nu.js`).then(e=>e.t),a=await i(o.curated,o.stateStore,{dryRun:!1});a.pruned.length>0&&y.info(`Startup lesson prune complete`,{pruned:a.pruned.length});let s=await t(o.curated,o.stateStore,{dryRun:!1});(s.groupsCreated>0||s.lessonsGrouped>0)&&y.info(`Startup lesson grouping complete`,{groupsCreated:s.groupsCreated,lessonsGrouped:s.lessonsGrouped})}if(a()){let{DEFAULT_PROMOTE_CONFIG:t,collectWorkspaceLessons:n,getGlobalCuratedDir:r,promoteLessons:i,scanForDuplicates:a}=await import(`./promotion-OY53YCsT.js`).then(e=>e.o),{CuratedKnowledgeManager:s}=await import(`./curated-manager-D1u5qOwK.js`).then(e=>e.n),c=o.curated,l=new s(r(),c.store,c.embedder),u=await n(),d={...t,dryRun:!1},f=await i(a(u,d),l,d);e(),f.promoted.length>0&&y.info(`Weekly lesson promotion complete`,{promoted:f.promoted.length,candidates:f.candidates.length})}}catch(e){y.warn(`Startup maintenance failed (non-critical)`,u(e))}}).catch(()=>{})};if(y.info(`Starting MCP AI Kit server`,{version:e}),t.transport===`http`){let[{default:e},{loadConfig:i,resolveIndexMode:a},{registerDashboardRoutes:o,resolveDashboardDir:s},{registerSettingsRoutes:c,resolveSettingsDir:l},{createSettingsRouter:d},{authMiddleware:f,getOrCreateToken:p}]=await Promise.all([import(`express`),import(`./config-jGZ91cRx.js`),import(`./dashboard-static-FmfoS46e.js`),import(`./settings-static-BtvyIrza.js`),import(`./routes-CR3fI-HJ.js`),import(`./auth-Bz5dmZgR.js`).then(e=>e.t)]),m=i();y.info(`Config loaded`,{sourceCount:m.sources.length,storePath:m.store.path});let g=e();g.use(e.json({limit:`1mb`}));let v=Number(t.port),b=`http://localhost:${v}`,C=process.env.AIKIT_CORS_ORIGIN??b,w=process.env.AIKIT_ALLOW_ANY_ORIGIN===`true`,D=E(`AIKIT_HTTP_MAX_SESSIONS`,8),O=E(`AIKIT_HTTP_SESSION_TIMEOUT_MINUTES`,30),A=E(`AIKIT_HTTP_SESSION_GC_INTERVAL_MINUTES`,5),j=S({limit:100,windowMs:6e4}),M=!1;g.use((e,t,n)=>{let r=Array.isArray(e.headers.origin)?e.headers.origin[0]:e.headers.origin,i=x({requestOrigin:r,configuredOrigin:C,allowAnyOrigin:w,fallbackOrigin:b});if(i.warn&&!M&&(M=!0,y.warn(`Rejected non-local CORS origin while AIKIT_CORS_ORIGIN=*`,{origin:r,allowAnyOriginEnv:`AIKIT_ALLOW_ANY_ORIGIN=true`})),r&&!i.allowOrigin){t.status(403).json({error:`Origin not allowed`});return}if(i.allowOrigin&&t.setHeader(`Access-Control-Allow-Origin`,i.allowOrigin),t.setHeader(`Access-Control-Allow-Methods`,`GET, POST, PUT, PATCH, DELETE, OPTIONS`),t.setHeader(`Access-Control-Allow-Headers`,`Content-Type, Authorization, Mcp-Session-Id, Mcp-Protocol-Version, Last-Event-ID`),t.setHeader(`Access-Control-Expose-Headers`,`Mcp-Session-Id`),e.method===`OPTIONS`){t.status(204).end();return}n()});let N=p();console.error(`[aikit] Auth token: ~/.aikit/token`),g.use(f(N)),g.use(`/mcp`,(e,t,n)=>{let r=T(e)??e.ip??e.socket.remoteAddress??`anonymous`;if(j.allow(r)){n();return}let i=Math.max(1,Math.ceil(j.getRetryAfterMs(r)/1e3));t.setHeader(`Retry-After`,String(i)),t.status(429).json({jsonrpc:`2.0`,error:{code:-32003,message:`Rate limit exceeded`},id:null})}),o(g,s(),y);let P=new Date().toISOString();g.use(`/settings/api`,d({log:y,mcpInfo:()=>({transport:`http`,port:v,pid:process.pid,startedAt:P})})),c(g,l(),y),g.get(`/health`,(e,t)=>{t.json({status:`ok`})});let F=!1,I=null,L=null,R=null,z=null,B=null,V=null,H=null,U=Promise.resolve(),W=async(e,t)=>{if(!F||!R||!z){t.status(503).json({jsonrpc:`2.0`,error:{code:-32603,message:`Server initializing — please retry in a few seconds`},id:null});return}let r=U,i;U=new Promise(e=>{i=e}),await r;try{let r=T(e);if(!V){if(r){t.status(404).json({jsonrpc:`2.0`,error:{code:-32001,message:`Session not found`},id:null});return}let e=new z({sessionIdGenerator:()=>n(),onsessioninitialized:async e=>{H=e,L?.onSessionStart(e,{transport:`http`})},onsessionclosed:async e=>{e&&L?.onSessionEnd(e),H=null}});e.onclose=()=>{V===e&&(V=null),H===e.sessionId&&(H=null)},V=e,await R.connect(e)}let i=V;await i.handleRequest(e,t,e.body),e.method!==`DELETE`&&(!r&&i.sessionId?(H=i.sessionId,L?.onSessionStart(i.sessionId,{transport:`http`}),L?.onSessionActivity(i.sessionId)):r&&L?.onSessionActivity(r))}catch(e){if(y.error(`MCP handler error`,u(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{i()}},G=async(e,t)=>{let n=T(e);if(B&&(!V||n!==H)){await B.handleRequest(e,t,e.body);return}await W(e,t)};g.post(`/mcp`,G),g.get(`/mcp`,G),g.delete(`/mcp`,G);let K=g.listen(v,`127.0.0.1`,()=>{y.info(`MCP server listening`,{url:`http://127.0.0.1:${v}/mcp`,port:v}),setTimeout(async()=>{try{let[{createLazyServer:e,createMcpServer:t,ALL_TOOL_NAMES:n},{StreamableHTTPServerTransport:i},{checkForUpdates:o,autoUpgradeScaffold:s}]=await Promise.all([import(`./server-DGu2FgFO.js`),import(`@modelcontextprotocol/sdk/server/streamableHttp.js`),import(`./version-check-D_uN0n0Y.js`)]);o(),s();let c=a(m),l=e(m,c);R=l.server,z=i,F=!0,y.info(`MCP server configured (lazy — AI Kit initializing in background)`,{toolCount:n.length,resourceCount:2}),l.startInit(),l.ready.then(()=>{if(!l.aikit)throw Error(`AI Kit components are not available after initialization`);L=new _(l.aikit.stateStore,{staleTimeoutMinutes:O,gcIntervalMinutes:A,onBeforeSessionDelete:e=>{if(H===e&&V){let e=V;V=null,H=null,e.close().catch(()=>void 0)}B?.closeSession(e,{notifySessionEnd:!1})},onSessionEndMaintenance:async()=>{if(!l.aikit?.curated||!l.aikit?.stateStore)return;let{pruneLessons:e}=await import(`./evolution-DJhTM6nu.js`).then(e=>e.t),t=await e(l.aikit.curated,l.aikit.stateStore,{dryRun:!1});t.pruned.length>0&&y.info(`Session-end lesson prune`,{pruned:t.pruned.length})}}),B=new h({createServer:()=>{if(!l.aikit)throw Error(`AI Kit components are not available after initialization`);return t(l.aikit,m)},createTransport:e=>new i(e),maxSessions:D,sessionTimeoutMinutes:O,onSessionStart:e=>L?.onSessionStart(e,{transport:`http`}),onSessionActivity:e=>L?.onSessionActivity(e),onSessionEnd:e=>L?.onSessionEnd(e)}),L.startGC(),H&&(L.onSessionStart(H,{transport:`http`}),L.onSessionActivity(H)),k(()=>l.aikit?{curated:l.aikit.curated,stateStore:l.aikit.stateStore}:null),y.info(`HTTP session runtime ready`,{maxSessions:D,sessionTimeoutMinutes:O,gcIntervalMinutes:A})}).catch(e=>y.error(`Failed to start session manager`,u(e))),c===`auto`?l.ready.then(async()=>{try{let e=m.sources.map(e=>e.path).join(`, `);y.info(`Running initial index`,{sourcePaths:e}),await l.runInitialIndex(),y.info(`Initial index complete`)}catch(e){y.error(`Initial index failed; will retry on aikit_reindex`,u(e))}}).catch(e=>y.error(`AI Kit init or indexing failed`,u(e))):c===`smart`?l.ready.then(async()=>{try{if(!l.aikit)throw Error(`AI Kit components are not available after initialization`);let{SmartIndexScheduler:e}=await import(`../../indexer/dist/index.js`),t=new e(l.aikit.indexer,m,l.aikit.store),n=l.aikit.store;I=t,t.start(),n.onBeforeClose&&n.onBeforeClose(()=>t.stop()),l.setSmartScheduler(t),y.info(`Smart index scheduler started (HTTP mode)`)}catch(e){y.error(`Failed to start smart index scheduler`,u(e))}}).catch(e=>y.error(`AI Kit initialization failed`,u(e))):(l.ready.catch(e=>y.error(`AI Kit initialization failed`,u(e))),y.info(`Initial full indexing skipped in HTTP mode`,{indexMode:c})),r(l.ready,()=>l.aikit?{curated:l.aikit.curated,stateStore:l.aikit.stateStore}:null)}catch(e){y.error(`Failed to load server modules`,u(e))}},100)}),q=async e=>{y.info(`Shutdown signal received`,{signal:e}),I?.stop(),L?.stop(),await B?.closeAll().catch(()=>void 0),H&&L?.onSessionEnd(H),V&&(await V.close().catch(()=>void 0),V=null,H=null),K.close(),R&&await R.close(),process.exit(0)};process.on(`SIGINT`,()=>q(`SIGINT`)),process.on(`SIGTERM`,()=>q(`SIGTERM`))}else{let[{loadConfig:e,reconfigureForWorkspace:t,resolveIndexMode:n},{createLazyServer:i},{checkForUpdates:a,autoUpgradeScaffold:s},{RootsListChangedNotificationSchema:c}]=await Promise.all([import(`./config-jGZ91cRx.js`),import(`./server-DGu2FgFO.js`),import(`./version-check-D_uN0n0Y.js`),import(`@modelcontextprotocol/sdk/types.js`)]),l=e();y.info(`Config loaded`,{sourceCount:l.sources.length,storePath:l.store.path}),a(),s();let d=n(l),f=i(l,d),{server:p,startInit:m,ready:h,runInitialIndex:g}=f,{StdioServerTransport:_}=await import(`@modelcontextprotocol/sdk/server/stdio.js`),v=new _;await p.connect(v),y.info(`MCP server started`,{transport:`stdio`});let b=e=>{if(e.length===0)return!1;let n=e[0].uri,r=n.startsWith(`file://`)?o(n):n;return y.info(`MCP roots resolved`,{rootUri:n,rootPath:r,rootCount:e.length}),t(l,r),l.allRoots=e.map(e=>{let t=e.uri;return t.startsWith(`file://`)?o(t):t}),!0},x=!1;try{x=b((await p.server.listRoots()).roots),x||y.info(`No MCP roots yet; waiting for roots/list_changed notification`)}catch(e){y.warn(`MCP roots/list not supported by client; using cwd fallback`,{cwd:process.cwd(),...u(e)}),x=!0}x||=await new Promise(e=>{let t=setTimeout(()=>{y.warn(`Timed out waiting for MCP roots/list_changed; using cwd fallback`,{cwd:process.cwd()}),e(!1)},5e3);p.server.setNotificationHandler(c,async()=>{clearTimeout(t);try{e(b((await p.server.listRoots()).roots))}catch(t){y.warn(`roots/list retry failed after notification`,u(t)),e(!1)}})}),m();let S=null,C=()=>{S&&clearTimeout(S),S=setTimeout(async()=>{y.info(`Auto-shutdown: no activity for 30 minutes — shutting down gracefully`);try{let e=f.aikit;e&&await Promise.all([e.embedder.shutdown?.().catch(()=>{})??Promise.resolve(),e.graphStore.close().catch(()=>{}),e.store.close().catch(()=>{})])}catch{}process.exit(0)},18e5),S.unref&&S.unref()};C(),process.stdin.on(`data`,()=>C()),h.catch(e=>{y.error(`Initialization failed — server will continue with limited tools`,u(e))}),h.then(()=>{k(()=>f.aikit?{curated:f.aikit.curated,stateStore:f.aikit.stateStore}:null)}).catch(()=>{}),d===`auto`?g().catch(e=>y.error(`Initial index failed`,u(e))):d===`smart`?h.then(async()=>{try{if(!f.aikit)throw Error(`AI Kit components are not available after initialization`);let{SmartIndexScheduler:e}=await import(`../../indexer/dist/index.js`),t=new e(f.aikit.indexer,l,f.aikit.store),n=f.aikit.store;t.start(),n.onBeforeClose&&n.onBeforeClose(()=>t.stop()),f.setSmartScheduler(t),y.info(`Smart index scheduler started (stdio mode)`)}catch(e){y.error(`Failed to start smart index scheduler`,u(e))}}).catch(e=>y.error(`AI Kit init failed for smart scheduler`,u(e))):y.warn(`Initial full indexing skipped; use aikit_reindex to index manually`,{indexMode:d}),r(h,()=>f.aikit?{curated:f.aikit.curated,stateStore:f.aikit.stateStore}:null)}}export{t as CuratedKnowledgeManager,S as createSlidingWindowRateLimiter,A as main,x as resolveCorsOrigin};