@vpxa/aikit 0.1.251 → 0.1.253

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.251",
3
+ "version": "0.1.253",
4
4
  "type": "module",
5
5
  "description": "Local-first AI developer toolkit — knowledge base, code analysis, context management, and developer tools for LLM agents",
6
6
  "license": "MIT",
@@ -1,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 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.cleanupParser(),null)}cleanupParser(){this.parser?.delete(),this.parser=null,this.languages.clear(),this.loadedGrammars.clear()}disableWasmParsing(){this.cleanupParser(),this.recoveryAttempts=e.MAX_RECOVERIES}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.debug(`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}),this.disableWasmParsing(),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.cleanupParser();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.debug(`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(`
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.cleanupParser(),null)}cleanupParser(){this.parser?.delete(),this.parser=null,this.languages.clear(),this.loadedGrammars.clear()}disableWasmParsing(){this.cleanupParser(),this.recoveryAttempts=e.MAX_RECOVERIES}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.debug(`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.debug(`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}),this.disableWasmParsing(),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.cleanupParser();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.debug(`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(`
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- import{rm as e}from"node:fs/promises";import{homedir as t}from"node:os";import{join as n}from"node:path";import{EMBEDDING_DEFAULTS as r}from"../../core/dist/index.js";let i=null;async function a(){if(!i){try{i=await import(`@huggingface/transformers`)}catch(e){if(e instanceof Error&&e.message.includes(`Cannot find module`)){let{createRequire:e}=await import(`node:module`);i=e(import.meta.url)(`@huggingface/transformers`)}else throw e}i.env.cacheDir=n(t(),`.cache`,`huggingface`,`transformers-js`)}return i}var o=class{pipe=null;shutdownPromise=null;dimensions;modelId;nativeDim;queryPrefix;threadConfig;constructor(e={}){if(this.modelId=e.model??r.model,this.nativeDim=e.nativeDim??r.nativeDim,this.dimensions=e.dimensions??r.dimensions,this.dimensions>this.nativeDim)throw Error(`Configured dimensions (${this.dimensions}) exceeds model native output (${this.nativeDim}). Matryoshka truncation cannot upscale — dimensions must be <= nativeDim.`);this.queryPrefix=e.queryPrefix??this.detectQueryPrefix(this.modelId),this.threadConfig={interOp:e.interOpNumThreads??1,intraOp:e.intraOpNumThreads??4}}detectQueryPrefix(e){let t=e.toLowerCase();return t.includes(`bge`)||t.includes(`mxbai-embed`)?`Represent this sentence for searching relevant passages: `:t.includes(`/e5-`)||t.includes(`multilingual-e5`)?`query: `:``}getPipelineOptions(e){let t=e.backends.onnx;t.wasm||={};let n=t.wasm;return n.numThreads=this.threadConfig.intraOp,{dtype:`q8`,session_options:{interOpNumThreads:this.threadConfig.interOp,intraOpNumThreads:this.threadConfig.intraOp}}}computeNorm(e){let t=0;for(let n=0;n<e.length;n++)t+=e[n]*e[n];return Math.sqrt(t)}truncateAndRenorm(e){if(this.dimensions>=this.nativeDim){let t=this.computeNorm(e);if(!Number.isFinite(t))throw Error(`Embedding produced non-finite norm — output contained NaN or Infinity`);if(t===0)throw Error(`Embedding produced zero-norm vector from ONNX output`);return e}let t=e.subarray(0,this.dimensions),n=this.computeNorm(t);if(!Number.isFinite(n))throw Error(`Embedding produced non-finite norm — output contained NaN or Infinity`);if(n===0)throw Error(`Embedding produced zero-norm vector after truncation — input may be degenerate`);let r=new Float32Array(this.dimensions);for(let e=0;e<this.dimensions;e++)r[e]=t[e]/n;return r}async initialize(){if(this.pipe)return;this.shutdownPromise=null;let{pipeline:r,env:i}=await a();try{this.pipe=await r(`feature-extraction`,this.modelId,this.getPipelineOptions(i))}catch(a){let o=a.message?.toLowerCase()??``;if(this.isCorruptionError(o)){let a=n(i.cacheDir??n(t(),`.cache`,`huggingface`,`transformers-js`),this.modelId);console.error(`[aikit:auto-heal] Detected corrupted model cache for "${this.modelId}". Clearing cache at ${a} and retrying download...`);try{await e(a,{recursive:!0,force:!0})}catch{}try{this.pipe=await r(`feature-extraction`,this.modelId,this.getPipelineOptions(i)),console.error(`[aikit:auto-heal] Model "${this.modelId}" re-downloaded successfully.`);return}catch(e){throw Error(`Failed to initialize embedding model "${this.modelId}" after auto-heal: ${e.message}`)}}throw Error(`Failed to initialize embedding model "${this.modelId}": ${a.message}`)}}isCorruptionError(e){return[`protobuf`,`invalid model`,`invalid onnx`,`unexpected end`,`unexpected token`,`failed to load`,`checksum`,`corrupt`,`could not load`,`onnx`,`malformed`].some(t=>e.includes(t))}async shutdown(){return this.shutdownPromise||=this._doShutdown(),this.shutdownPromise}async _doShutdown(){let e=this.pipe;if(e)try{let t=e;typeof t.dispose==`function`?await t.dispose():typeof t.model?.dispose==`function`&&await t.model.dispose()}catch{}finally{this.pipe=null}}async embed(e){this.pipe||await this.initialize();let t=await this.pipe?.(e,{pooling:`mean`,normalize:!0});if(!t?.data)throw Error(`Embedding pipeline returned no output`);try{let e=new Float32Array(t.data);return this.truncateAndRenorm(e)}finally{t.dispose?.()}}async embedQuery(e){return this.embed(this.queryPrefix+e)}async embedBatch(e,t=64){if(e.length===0)return[];this.pipe||await this.initialize();let n=[];for(let r=0;r<e.length;r+=t){let i=e.slice(r,r+t),a=await this.pipe?.(i,{pooling:`mean`,normalize:!0});if(!a?.data)throw Error(`Embedding pipeline returned no output`);try{if(i.length===1){let e=new Float32Array(a.data);n.push(this.truncateAndRenorm(e))}else for(let e=0;e<i.length;e++){let t=e*this.nativeDim,r=a.data.slice(t,t+this.nativeDim);n.push(this.truncateAndRenorm(new Float32Array(r)))}}finally{a.dispose?.()}}return n}};let s=null,c=null,l=!1;const u=Number(process.env.AIKIT_EMBED_IDLE_MS),d=Number.isFinite(u)&&u>=0?u:6e4,f=Number(process.env.AIKIT_EMBED_MAX_RSS_MB),p=Number.isFinite(f)&&f>0?f:1536;function m(){let e=process.memoryUsage;return(typeof e.rss==`function`?e.rss():e().rss)/(1024*1024)>p}function h(e){process.send?.(e)}function g(){c&&=(clearTimeout(c),null)}async function _(){if(!s)return;let e=s;s=null,await e.shutdown?.()}async function v(e,t){l&&process.exit(e),l=!0,g(),t?.notifyIdle&&h({type:`idle-exit`});try{await _()}finally{process.exit(e)}}function y(){g(),d!==0&&(c=setTimeout(()=>{v(0,{notifyIdle:!0})},d))}function b(e){return Array.from(e)}function x(e){return e instanceof Error?e.message:String(e)}function S(){if(!s)throw Error(`Embedder not initialized`);return s}async function C(e,t){h({type:`error`,id:e,message:x(t)})}async function w(e){g();try{switch(e.type){case`init`:await _(),s=new o(e.config),await s.initialize(),await s.embed(`warmup`),h({type:`ready`,dimensions:s.dimensions,modelId:s.modelId});break;case`embed`:{let t=await S().embed(e.text);h({type:`result`,id:e.id,data:b(t)});break}case`embedBatch`:{let t=await S().embedBatch(e.texts,e.batchSize);h({type:`batchResult`,id:e.id,data:t.map(e=>b(e))});break}case`embedQuery`:{let t=await S().embedQuery(e.text);h({type:`result`,id:e.id,data:b(t)});break}case`shutdown`:await v(0);return}}catch(t){if(await C(e.type===`shutdown`?`shutdown`:e.type===`init`?`init`:e.id,t),e.type===`init`){await v(1);return}}if(m()){await v(0,{notifyIdle:!0});return}y()}async function T(e,t){await C(e,t),await v(1)}process.on(`message`,e=>{w(e)}),process.on(`SIGTERM`,()=>{v(0)}),process.on(`uncaughtException`,e=>{T(`fatal`,e)}),process.on(`unhandledRejection`,e=>{T(`fatal`,e)});export{};
2
+ import{rm as e}from"node:fs/promises";import{homedir as t}from"node:os";import{join as n}from"node:path";import{EMBEDDING_DEFAULTS as r}from"../../core/dist/index.js";let i=null;function a(e){if(!(e instanceof Error))return!1;let t=e.code;return t===`ERR_MODULE_NOT_FOUND`||t===`MODULE_NOT_FOUND`?!0:/cannot find (module|package)|module not found/i.test(e.message)}async function o(){if(!i){try{i=await import(`@huggingface/transformers`)}catch(e){if(a(e)){let{createRequire:t}=await import(`node:module`),n=t(import.meta.url);try{i=n("@huggingface/transformers")}catch(t){let n=e instanceof Error?e.message:String(e),r=t instanceof Error?t.message:String(t);throw Error(`Unable to load @huggingface/transformers via ESM or CJS. ESM: ${n}; CJS: ${r}`)}}else throw e}i.env.cacheDir=n(t(),`.cache`,`huggingface`,`transformers-js`)}return i}var s=class{pipe=null;shutdownPromise=null;dimensions;modelId;nativeDim;queryPrefix;threadConfig;constructor(e={}){if(this.modelId=e.model??r.model,this.nativeDim=e.nativeDim??r.nativeDim,this.dimensions=e.dimensions??r.dimensions,this.dimensions>this.nativeDim)throw Error(`Configured dimensions (${this.dimensions}) exceeds model native output (${this.nativeDim}). Matryoshka truncation cannot upscale — dimensions must be <= nativeDim.`);this.queryPrefix=e.queryPrefix??this.detectQueryPrefix(this.modelId),this.threadConfig={interOp:e.interOpNumThreads??1,intraOp:e.intraOpNumThreads??4}}detectQueryPrefix(e){let t=e.toLowerCase();return t.includes(`bge`)||t.includes(`mxbai-embed`)?`Represent this sentence for searching relevant passages: `:t.includes(`/e5-`)||t.includes(`multilingual-e5`)?`query: `:``}getPipelineOptions(e){let t=e.backends.onnx;t.wasm||={};let n=t.wasm;return n.numThreads=this.threadConfig.intraOp,{dtype:`q8`,session_options:{interOpNumThreads:this.threadConfig.interOp,intraOpNumThreads:this.threadConfig.intraOp}}}computeNorm(e){let t=0;for(let n=0;n<e.length;n++)t+=e[n]*e[n];return Math.sqrt(t)}truncateAndRenorm(e){if(this.dimensions>=this.nativeDim){let t=this.computeNorm(e);if(!Number.isFinite(t))throw Error(`Embedding produced non-finite norm — output contained NaN or Infinity`);if(t===0)throw Error(`Embedding produced zero-norm vector from ONNX output`);return e}let t=e.subarray(0,this.dimensions),n=this.computeNorm(t);if(!Number.isFinite(n))throw Error(`Embedding produced non-finite norm — output contained NaN or Infinity`);if(n===0)throw Error(`Embedding produced zero-norm vector after truncation — input may be degenerate`);let r=new Float32Array(this.dimensions);for(let e=0;e<this.dimensions;e++)r[e]=t[e]/n;return r}async initialize(){if(this.pipe)return;this.shutdownPromise=null;let{pipeline:r,env:i}=await o();try{this.pipe=await r(`feature-extraction`,this.modelId,this.getPipelineOptions(i))}catch(a){let o=a.message?.toLowerCase()??``;if(this.isCorruptionError(o)){let a=n(i.cacheDir??n(t(),`.cache`,`huggingface`,`transformers-js`),this.modelId);console.error(`[aikit:auto-heal] Detected corrupted model cache for "${this.modelId}". Clearing cache at ${a} and retrying download...`);try{await e(a,{recursive:!0,force:!0})}catch{}try{this.pipe=await r(`feature-extraction`,this.modelId,this.getPipelineOptions(i)),console.error(`[aikit:auto-heal] Model "${this.modelId}" re-downloaded successfully.`);return}catch(e){throw Error(`Failed to initialize embedding model "${this.modelId}" after auto-heal: ${e.message}`)}}throw Error(`Failed to initialize embedding model "${this.modelId}": ${a.message}`)}}isCorruptionError(e){return[`protobuf`,`invalid model`,`invalid onnx`,`unexpected end`,`unexpected token`,`failed to load`,`checksum`,`corrupt`,`could not load`,`onnx`,`malformed`].some(t=>e.includes(t))}async shutdown(){return this.shutdownPromise||=this._doShutdown(),this.shutdownPromise}async _doShutdown(){let e=this.pipe;if(e)try{let t=e;typeof t.dispose==`function`?await t.dispose():typeof t.model?.dispose==`function`&&await t.model.dispose()}catch{}finally{this.pipe=null}}async embed(e){this.pipe||await this.initialize();let t=await this.pipe?.(e,{pooling:`mean`,normalize:!0});if(!t?.data)throw Error(`Embedding pipeline returned no output`);try{let e=new Float32Array(t.data);return this.truncateAndRenorm(e)}finally{t.dispose?.()}}async embedQuery(e){return this.embed(this.queryPrefix+e)}async embedBatch(e,t=64){if(e.length===0)return[];this.pipe||await this.initialize();let n=[];for(let r=0;r<e.length;r+=t){let i=e.slice(r,r+t),a=await this.pipe?.(i,{pooling:`mean`,normalize:!0});if(!a?.data)throw Error(`Embedding pipeline returned no output`);try{if(i.length===1){let e=new Float32Array(a.data);n.push(this.truncateAndRenorm(e))}else for(let e=0;e<i.length;e++){let t=e*this.nativeDim,r=a.data.slice(t,t+this.nativeDim);n.push(this.truncateAndRenorm(new Float32Array(r)))}}finally{a.dispose?.()}}return n}};let c=null,l=null,u=!1;const d=Number(process.env.AIKIT_EMBED_IDLE_MS),f=Number.isFinite(d)&&d>=0?d:6e4,p=Number(process.env.AIKIT_EMBED_MAX_RSS_MB),m=Number.isFinite(p)&&p>0?p:1536;function h(){let e=process.memoryUsage;return(typeof e.rss==`function`?e.rss():e().rss)/(1024*1024)>m}function g(e){process.send?.(e)}async function _(e){await new Promise(t=>{if(!process.send){t();return}let n=!1,r=()=>{n||(n=!0,t())};try{process.send.length<2?(process.send(e),r()):(process.send(e,()=>r()),setTimeout(r,25).unref?.())}catch{r()}})}function v(){l&&=(clearTimeout(l),null)}async function y(){if(!c)return;let e=c;c=null,await e.shutdown?.()}async function b(e,t){u&&process.exit(e),u=!0,v(),t?.notifyIdle&&g({type:`idle-exit`});try{await y()}finally{process.exit(e)}}function x(){v(),f!==0&&(l=setTimeout(()=>{b(0,{notifyIdle:!0})},f))}function S(e){return Array.from(e)}function C(e){return e instanceof Error?e.message:String(e)}function w(){if(!c)throw Error(`Embedder not initialized`);return c}async function T(e,t){await _({type:`error`,id:e,message:C(t)})}async function E(e){v();try{switch(e.type){case`init`:await y(),c=new s(e.config),await c.initialize(),await c.embed(`warmup`),g({type:`ready`,dimensions:c.dimensions,modelId:c.modelId});break;case`embed`:{let t=await w().embed(e.text);g({type:`result`,id:e.id,data:S(t)});break}case`embedBatch`:{let t=await w().embedBatch(e.texts,e.batchSize);g({type:`batchResult`,id:e.id,data:t.map(e=>S(e))});break}case`embedQuery`:{let t=await w().embedQuery(e.text);g({type:`result`,id:e.id,data:S(t)});break}case`shutdown`:await b(0);return}}catch(t){if(await T(e.type===`shutdown`?`shutdown`:e.type===`init`?`init`:e.id,t),e.type===`init`){await b(1);return}}if(h()){await b(0,{notifyIdle:!0});return}x()}async function D(e,t){await T(e,t),await b(1)}process.on(`message`,e=>{E(e)}),process.on(`SIGTERM`,()=>{b(0)}),process.on(`uncaughtException`,e=>{D(`fatal`,e)}),process.on(`unhandledRejection`,e=>{D(`fatal`,e)});export{};
@@ -54,6 +54,7 @@ declare class EmbedderProxy implements IEmbedder {
54
54
  private readonly workerPath;
55
55
  private readonly pendingRequests;
56
56
  private readonly childState;
57
+ private readonly childErrors;
57
58
  private child;
58
59
  private readyChild;
59
60
  private pendingInit;
@@ -1 +1 @@
1
- import{fork as e}from"node:child_process";import{randomUUID as t}from"node:crypto";import{existsSync as n}from"node:fs";import{dirname as r,join as i}from"node:path";import{fileURLToPath as a}from"node:url";import{CircuitBreaker as o,CircuitOpenError as s,EMBEDDING_DEFAULTS as c,HealthBus as l}from"../../core/dist/index.js";import{rm as u}from"node:fs/promises";import{homedir as d}from"node:os";var f=class{options;logger;healthBus=l.instance();cb;initTimeoutMs;requestTimeoutMs;maxRetries;retryBaseDelayMs;workerAvailable=!0;workerPath=i(r(a(import.meta.url)),`embedder-worker.js`);pendingRequests=new Map;childState=new WeakMap;child=null;readyChild=null;pendingInit=null;pendingShutdown=null;initializePromise=null;shutdownPromise=null;cooldownRespawnTimer=null;currentDimensions;currentModelId;coldStart=!0;constructor(e={}){this.options=e,this.logger=e.logger,this.healthBus.register(`embedder`),this.cb=new o({threshold:3,cooldownMs:6e4,name:`embedder`}),this.cb.on(`open`,()=>{this.healthBus.reportDegraded(`embedder`,`Circuit breaker open — consecutive timeouts`),this.startCooldownRespawn()}),this.cb.on(`closed`,()=>{this.healthBus.reportRecovered(`embedder`)}),this.initTimeoutMs=Math.max(0,e.initTimeoutMs??6e4),this.requestTimeoutMs=Math.max(0,e.requestTimeoutMs??(process.platform===`win32`?6e4:3e4)),this.maxRetries=Math.max(0,e.maxRetries??3),this.retryBaseDelayMs=Math.max(0,e.retryBaseDelayMs??500),this.currentDimensions=e.dimensions??c.dimensions,this.currentModelId=e.model??c.model}get dimensions(){return this.currentDimensions}get modelId(){return this.currentModelId}get isCircuitOpen(){return this.cb.isOpen()}async initialize(){if(!(this.readyChild&&this.child===this.readyChild)&&this.workerAvailable){if(!n(this.workerPath)){this.workerAvailable=!1,console.warn(`[aikit] Embedder worker not found at ${this.workerPath}. Embedding disabled - search will use keyword matching only. This usually means the npx cache is corrupted; restart to fix.`);return}if(this.initializePromise)return this.initializePromise;if(this.shutdownPromise){try{await this.shutdownPromise}catch{}if(this.readyChild&&this.child===this.readyChild)return}return this.initializePromise=this.startWorker().finally(()=>{this.initializePromise=null}),this.initializePromise}}async embed(e){if(!this.workerAvailable||(this.assertCircuitClosed(),await this.initialize(),!this.workerAvailable))throw Error(`Embedding worker is not available — embeddings cannot be computed. Check server logs for initialization errors.`);return this.sendVectorRequestWithRetry({type:`embed`,text:e})}async embedQuery(e){if(!this.workerAvailable||(this.assertCircuitClosed(),await this.initialize(),!this.workerAvailable))throw Error(`Embedding worker is not available — embeddings cannot be computed. Check server logs for initialization errors.`);return this.sendVectorRequestWithRetry({type:`embedQuery`,text:e})}async embedBatch(e,t){if(e.length===0)return[];if(!this.workerAvailable||(this.assertCircuitClosed(),await this.initialize(),!this.workerAvailable))throw Error(`Embedding worker is not available — embeddings cannot be computed. Check server logs for initialization errors.`);return this.withWorkerExitRetry(`embedBatch`,()=>this.sendBatchRequest(e,t))}async sendBatchRequest(e,n){await this.initialize();let r=this.requireReadyChild(),i=t(),a=new Promise((e,t)=>{this.pendingRequests.set(i,{child:r,resolve:t=>e(t),reject:t})});try{r.send({type:`embedBatch`,id:i,texts:e,batchSize:n})}catch(e){throw this.pendingRequests.delete(i),this.toError(e,`Failed to send embedBatch request to worker`)}let o=this.requestTimeoutMs>0?Math.max(this.requestTimeoutMs*3,9e4):0;if(o>0){let t,n=new Promise((n,r)=>{t=setTimeout(()=>{this.pendingRequests.delete(i),this.markWorkerUnresponsive(),r(Error(`Embedder embedBatch request timed out after ${o/1e3}s (${e.length} texts). The worker has been killed and will attempt to respawn automatically.`))},o)});try{return await Promise.race([a,n])}finally{t!==void 0&&clearTimeout(t)}}return a}async shutdown(){if(this.clearCooldownRespawnTimer(),this.shutdownPromise)return this.shutdownPromise;let e=this.child;if(!e)return;let t=this.requireChildState(e);t.shutdownRequested=!0,this.readyChild===e&&(this.readyChild=null),this.shutdownPromise=new Promise((t,n)=>{this.pendingShutdown={child:e,resolve:t,reject:n}}).finally(()=>{this.shutdownPromise=null});try{e.send({type:`shutdown`})}catch(t){let n=this.toError(t,`Failed to send shutdown request to worker`);throw this.clearChildReference(e),this.rejectPendingForChild(e,n),this.rejectLifecycleIfOwned(`shutdown`,e,n),n}return this.shutdownPromise}async startWorker(){this.child&&this.readyChild!==this.child&&(this.child=null),this.clearCooldownRespawnTimer(),this.coldStart=!0;let e=this.spawnChild();this.child=e,this.readyChild=null;let t=new Promise((t,n)=>{this.pendingInit={child:e,resolve:t,reject:n}});try{e.send({type:`init`,config:this.buildInitConfig()})}catch(t){let n=this.toError(t,`Failed to send init request to worker`);throw this.pendingInit=null,this.clearChildReference(e),n}if(this.initTimeoutMs>0){let n,r=new Promise((e,t)=>{n=setTimeout(()=>{t(Error(`Embedder worker initialization timed out after ${this.initTimeoutMs/1e3}s. The ONNX model may be downloading or the child process is stuck. Check network connectivity and disk space, or restart the server.`))},this.initTimeoutMs)});try{await Promise.race([t,r]);return}catch(t){this.pendingInit=null;try{e.kill()}catch{}throw this.clearChildReference(e),t}finally{n!==void 0&&clearTimeout(n)}}await t}spawnChild(){let t=e(this.workerPath,[],{env:this.buildChildEnv()});return this.childState.set(t,{idleExitNotified:!1,shutdownRequested:!1,terminated:!1}),t.on(`message`,e=>{this.handleChildMessage(t,e)}),t.once(`error`,e=>{this.handleChildFailure(t,this.toError(e,`Embedder worker failed`))}),t.once(`exit`,(e,n)=>{this.handleChildExit(t,e,n)}),t}handleChildMessage(e,t){switch(t.type){case`ready`:{this.currentDimensions=t.dimensions,this.currentModelId=t.modelId,this.healthBus.reportRecovered(`embedder`),this.child===e&&(this.readyChild=e,this.cb.getState()!==`closed`&&this.cb.reset());let n=this.pendingInit;n?.child===e&&(this.pendingInit=null,n.resolve());return}case`result`:{let n=this.pendingRequests.get(t.id);if(!n||n.child!==e)return;this.pendingRequests.delete(t.id),this.coldStart=!1,this.cb.recordSuccess(),n.resolve(new Float32Array(t.data));return}case`batchResult`:{let n=this.pendingRequests.get(t.id);if(!n||n.child!==e)return;if(this.pendingRequests.delete(t.id),!t.data||!Array.isArray(t.data)||t.data.length===0)n.reject(Error(`Worker returned empty or invalid batch result`));else{let e=t.data.map(e=>new Float32Array(e)),r=e.findIndex(e=>e.length===0);r>=0?n.reject(Error(`Worker returned zero-length vector at index ${r}`)):(this.coldStart=!1,this.cb.recordSuccess(),n.resolve(e))}return}case`error`:{let n=Error(t.message);if(t.id===`init`){this.clearChildReference(e),this.rejectLifecycleIfOwned(`init`,e,n);return}if(t.id===`shutdown`){this.rejectLifecycleIfOwned(`shutdown`,e,n);return}let r=this.pendingRequests.get(t.id);if(!r||r.child!==e)return;this.pendingRequests.delete(t.id),r.reject(n);return}case`idle-exit`:{let t=this.requireChildState(e);t.idleExitNotified=!0,this.clearChildReference(e);return}}}handleChildExit(e,t,n){let r=this.requireChildState(e);if(r.terminated)return;r.terminated=!0,this.clearChildReference(e);let i=r.shutdownRequested||r.idleExitNotified,a=Error(i?`Embedder worker exited before completing request`:`Embedder worker exited unexpectedly (code ${t??`null`}${n?`, signal ${n}`:``})`);this.rejectLifecycleIfOwned(`init`,e,a),i?this.resolveLifecycleIfOwned(`shutdown`,e):this.rejectLifecycleIfOwned(`shutdown`,e,a),this.rejectPendingForChild(e,a),i||this.cb.recordFailure()}handleChildFailure(e,t){let n=this.requireChildState(e);n.terminated||(n.terminated=!0,this.clearChildReference(e),this.rejectLifecycleIfOwned(`init`,e,t),this.rejectLifecycleIfOwned(`shutdown`,e,t),this.rejectPendingForChild(e,t))}async sendVectorRequestWithRetry(e){return this.withWorkerExitRetry(e.type,()=>this.sendVectorRequest(e))}async sendVectorRequest(e){await this.initialize();let n=this.requireReadyChild(),r=t(),i=this.requestTimeoutMs>0?this.coldStart?this.requestTimeoutMs*2:this.requestTimeoutMs:0,a=new Promise((e,t)=>{this.pendingRequests.set(r,{child:n,resolve:t=>e(t),reject:t})});try{n.send({...e,id:r})}catch(t){throw this.pendingRequests.delete(r),this.toError(t,`Failed to send ${e.type} request to worker`)}if(i>0){let t,n=new Promise((n,a)=>{t=setTimeout(()=>{this.pendingRequests.delete(r),this.markWorkerUnresponsive(),a(Error(`Embedder ${e.type} request timed out after ${i/1e3}s. The worker has been killed and will attempt to respawn automatically.`))},i)});try{return await Promise.race([a,n])}finally{t!==void 0&&clearTimeout(t)}}return a}async withWorkerExitRetry(e,t){let n=null,r=this.maxRetries;for(let i=0;i<=r;i++)try{return await t()}catch(t){let a=this.toError(t,`Failed to process ${e} request`);if(!this.isWorkerExitError(a))throw a;if(n??=a,i===0&&/exited/i.test(a.message)&&!/timed out/i.test(a.message)&&(r=Math.min(r,1)),i===r)throw n;let o=i+1,s=this.retryBaseDelayMs*2**i;if(this.healthBus.reportDegraded(`embedder`,`Worker crashed during ${e} — retrying (${o}/${r})`),this.logger?.warn?.(`Embedder retry ${o}/${r} after ${s}ms`,{requestType:e,delayMs:s,error:a.message}),this.child=null,this.readyChild=null,await this.wait(s),this.cb.isOpen())throw n??a}throw n??Error(`Failed to process ${e} request`)}isWorkerExitError(e){return/embedder worker exited|EPIPE|ECONNRESET|ERR_IPC_CHANNEL_CLOSED|channel closed|write after end/i.test(e.message)}wait(e){return new Promise(t=>{setTimeout(t,e)})}requireReadyChild(){if(!this.child||this.readyChild!==this.child)throw Error(`Embedder worker is not initialized`);return this.child}buildInitConfig(){return{model:this.options.model,dimensions:this.options.dimensions,nativeDim:this.options.nativeDim,queryPrefix:this.options.queryPrefix,interOpNumThreads:this.options.interOpNumThreads,intraOpNumThreads:this.options.intraOpNumThreads}}buildChildEnv(){return this.options.idleTimeoutMs===void 0?process.env:{...process.env,AIKIT_EMBED_IDLE_MS:String(this.options.idleTimeoutMs)}}requireChildState(e){let t=this.childState.get(e);if(!t)throw Error(`Embedder worker state not found`);return t}clearChildReference(e){this.child===e&&(this.child=null),this.readyChild===e&&(this.readyChild=null)}clearCooldownRespawnTimer(){this.cooldownRespawnTimer&&=(clearTimeout(this.cooldownRespawnTimer),null)}startCooldownRespawn(){this.clearCooldownRespawnTimer(),this.cooldownRespawnTimer=setTimeout(()=>{this.cooldownRespawnTimer=null,!this.child&&!this.shutdownPromise&&this.workerAvailable&&this.initialize().catch(()=>{})},6e4),this.logger?.warn?.(`Embedder circuit breaker OPEN — too many consecutive failures`,{cooldownMs:6e4})}markWorkerUnresponsive(){let e=this.child;if(e){try{e.kill()}catch{}this.clearChildReference(e),this.cb.recordFailure(),this.cb.isOpen()||setImmediate(()=>{!this.child&&this.workerAvailable&&!this.shutdownPromise&&this.initialize().catch(()=>{})})}}assertCircuitClosed(){if(this.cb.isOpen())throw new s(this.cb.remainingCooldownMs())}rejectPendingForChild(e,t){for(let[n,r]of this.pendingRequests)r.child===e&&(this.pendingRequests.delete(n),r.reject(t))}resolveLifecycleIfOwned(e,t){let n=this.pendingShutdown;!n||n.child!==t||(this.pendingShutdown=null,n.resolve())}rejectLifecycleIfOwned(e,t,n){let r=e===`init`?this.pendingInit:this.pendingShutdown;!r||r.child!==t||(e===`init`?this.pendingInit=null:this.pendingShutdown=null,r.reject(n))}toError(e,t){return e instanceof Error?e:Error(`${t}: ${String(e)}`)}};let p=null;async function m(){if(!p){try{p=await import(`@huggingface/transformers`)}catch(e){if(e instanceof Error&&e.message.includes(`Cannot find module`)){let{createRequire:e}=await import(`node:module`);p=e(import.meta.url)(`@huggingface/transformers`)}else throw e}p.env.cacheDir=i(d(),`.cache`,`huggingface`,`transformers-js`)}return p}var h=class{pipe=null;shutdownPromise=null;dimensions;modelId;nativeDim;queryPrefix;threadConfig;constructor(e={}){if(this.modelId=e.model??c.model,this.nativeDim=e.nativeDim??c.nativeDim,this.dimensions=e.dimensions??c.dimensions,this.dimensions>this.nativeDim)throw Error(`Configured dimensions (${this.dimensions}) exceeds model native output (${this.nativeDim}). Matryoshka truncation cannot upscale — dimensions must be <= nativeDim.`);this.queryPrefix=e.queryPrefix??this.detectQueryPrefix(this.modelId),this.threadConfig={interOp:e.interOpNumThreads??1,intraOp:e.intraOpNumThreads??4}}detectQueryPrefix(e){let t=e.toLowerCase();return t.includes(`bge`)||t.includes(`mxbai-embed`)?`Represent this sentence for searching relevant passages: `:t.includes(`/e5-`)||t.includes(`multilingual-e5`)?`query: `:``}getPipelineOptions(e){let t=e.backends.onnx;t.wasm||={};let n=t.wasm;return n.numThreads=this.threadConfig.intraOp,{dtype:`q8`,session_options:{interOpNumThreads:this.threadConfig.interOp,intraOpNumThreads:this.threadConfig.intraOp}}}computeNorm(e){let t=0;for(let n=0;n<e.length;n++)t+=e[n]*e[n];return Math.sqrt(t)}truncateAndRenorm(e){if(this.dimensions>=this.nativeDim){let t=this.computeNorm(e);if(!Number.isFinite(t))throw Error(`Embedding produced non-finite norm — output contained NaN or Infinity`);if(t===0)throw Error(`Embedding produced zero-norm vector from ONNX output`);return e}let t=e.subarray(0,this.dimensions),n=this.computeNorm(t);if(!Number.isFinite(n))throw Error(`Embedding produced non-finite norm — output contained NaN or Infinity`);if(n===0)throw Error(`Embedding produced zero-norm vector after truncation — input may be degenerate`);let r=new Float32Array(this.dimensions);for(let e=0;e<this.dimensions;e++)r[e]=t[e]/n;return r}async initialize(){if(this.pipe)return;this.shutdownPromise=null;let{pipeline:e,env:t}=await m();try{this.pipe=await e(`feature-extraction`,this.modelId,this.getPipelineOptions(t))}catch(n){let r=n.message?.toLowerCase()??``;if(this.isCorruptionError(r)){let n=i(t.cacheDir??i(d(),`.cache`,`huggingface`,`transformers-js`),this.modelId);console.error(`[aikit:auto-heal] Detected corrupted model cache for "${this.modelId}". Clearing cache at ${n} and retrying download...`);try{await u(n,{recursive:!0,force:!0})}catch{}try{this.pipe=await e(`feature-extraction`,this.modelId,this.getPipelineOptions(t)),console.error(`[aikit:auto-heal] Model "${this.modelId}" re-downloaded successfully.`);return}catch(e){throw Error(`Failed to initialize embedding model "${this.modelId}" after auto-heal: ${e.message}`)}}throw Error(`Failed to initialize embedding model "${this.modelId}": ${n.message}`)}}isCorruptionError(e){return[`protobuf`,`invalid model`,`invalid onnx`,`unexpected end`,`unexpected token`,`failed to load`,`checksum`,`corrupt`,`could not load`,`onnx`,`malformed`].some(t=>e.includes(t))}async shutdown(){return this.shutdownPromise||=this._doShutdown(),this.shutdownPromise}async _doShutdown(){let e=this.pipe;if(e)try{let t=e;typeof t.dispose==`function`?await t.dispose():typeof t.model?.dispose==`function`&&await t.model.dispose()}catch{}finally{this.pipe=null}}async embed(e){this.pipe||await this.initialize();let t=await this.pipe?.(e,{pooling:`mean`,normalize:!0});if(!t?.data)throw Error(`Embedding pipeline returned no output`);try{let e=new Float32Array(t.data);return this.truncateAndRenorm(e)}finally{t.dispose?.()}}async embedQuery(e){return this.embed(this.queryPrefix+e)}async embedBatch(e,t=64){if(e.length===0)return[];this.pipe||await this.initialize();let n=[];for(let r=0;r<e.length;r+=t){let i=e.slice(r,r+t),a=await this.pipe?.(i,{pooling:`mean`,normalize:!0});if(!a?.data)throw Error(`Embedding pipeline returned no output`);try{if(i.length===1){let e=new Float32Array(a.data);n.push(this.truncateAndRenorm(e))}else for(let e=0;e<i.length;e++){let t=e*this.nativeDim,r=a.data.slice(t,t+this.nativeDim);n.push(this.truncateAndRenorm(new Float32Array(r)))}}finally{a.dispose?.()}}return n}};export{f as EmbedderProxy,h as OnnxEmbedder};
1
+ import{fork as e}from"node:child_process";import{randomUUID as t}from"node:crypto";import{existsSync as n}from"node:fs";import{dirname as r,join as i}from"node:path";import{fileURLToPath as a}from"node:url";import{CircuitBreaker as o,CircuitOpenError as s,EMBEDDING_DEFAULTS as c,HealthBus as l}from"../../core/dist/index.js";import{rm as u}from"node:fs/promises";import{homedir as d}from"node:os";var f=class{options;logger;healthBus=l.instance();cb;initTimeoutMs;requestTimeoutMs;maxRetries;retryBaseDelayMs;workerAvailable=!0;workerPath=i(r(a(import.meta.url)),`embedder-worker.js`);pendingRequests=new Map;childState=new WeakMap;childErrors=new WeakMap;child=null;readyChild=null;pendingInit=null;pendingShutdown=null;initializePromise=null;shutdownPromise=null;cooldownRespawnTimer=null;currentDimensions;currentModelId;coldStart=!0;constructor(e={}){this.options=e,this.logger=e.logger,this.healthBus.register(`embedder`),this.cb=new o({threshold:3,cooldownMs:6e4,name:`embedder`}),this.cb.on(`open`,()=>{this.healthBus.reportDegraded(`embedder`,`Circuit breaker open — consecutive timeouts`),this.startCooldownRespawn()}),this.cb.on(`closed`,()=>{this.healthBus.reportRecovered(`embedder`)}),this.initTimeoutMs=Math.max(0,e.initTimeoutMs??6e4),this.requestTimeoutMs=Math.max(0,e.requestTimeoutMs??(process.platform===`win32`?6e4:3e4)),this.maxRetries=Math.max(0,e.maxRetries??3),this.retryBaseDelayMs=Math.max(0,e.retryBaseDelayMs??500),this.currentDimensions=e.dimensions??c.dimensions,this.currentModelId=e.model??c.model}get dimensions(){return this.currentDimensions}get modelId(){return this.currentModelId}get isCircuitOpen(){return this.cb.isOpen()}async initialize(){if(!(this.readyChild&&this.child===this.readyChild)&&this.workerAvailable){if(!n(this.workerPath)){this.workerAvailable=!1,console.warn(`[aikit] Embedder worker not found at ${this.workerPath}. Embedding disabled - search will use keyword matching only. This usually means the npx cache is corrupted; restart to fix.`);return}if(this.initializePromise)return this.initializePromise;if(this.shutdownPromise){try{await this.shutdownPromise}catch{}if(this.readyChild&&this.child===this.readyChild)return}return this.initializePromise=this.startWorker().finally(()=>{this.initializePromise=null}),this.initializePromise}}async embed(e){if(!this.workerAvailable||(this.assertCircuitClosed(),await this.initialize(),!this.workerAvailable))throw Error(`Embedding worker is not available — embeddings cannot be computed. Check server logs for initialization errors.`);return this.sendVectorRequestWithRetry({type:`embed`,text:e})}async embedQuery(e){if(!this.workerAvailable||(this.assertCircuitClosed(),await this.initialize(),!this.workerAvailable))throw Error(`Embedding worker is not available — embeddings cannot be computed. Check server logs for initialization errors.`);return this.sendVectorRequestWithRetry({type:`embedQuery`,text:e})}async embedBatch(e,t){if(e.length===0)return[];if(!this.workerAvailable||(this.assertCircuitClosed(),await this.initialize(),!this.workerAvailable))throw Error(`Embedding worker is not available — embeddings cannot be computed. Check server logs for initialization errors.`);return this.withWorkerExitRetry(`embedBatch`,()=>this.sendBatchRequest(e,t))}async sendBatchRequest(e,n){await this.initialize();let r=this.requireReadyChild(),i=t(),a=new Promise((e,t)=>{this.pendingRequests.set(i,{child:r,resolve:t=>e(t),reject:t})});try{r.send({type:`embedBatch`,id:i,texts:e,batchSize:n})}catch(e){throw this.pendingRequests.delete(i),this.toError(e,`Failed to send embedBatch request to worker`)}let o=this.requestTimeoutMs>0?Math.max(this.requestTimeoutMs*3,9e4):0;if(o>0){let t,n=new Promise((n,r)=>{t=setTimeout(()=>{this.pendingRequests.delete(i),this.markWorkerUnresponsive(),r(Error(`Embedder embedBatch request timed out after ${o/1e3}s (${e.length} texts). The worker has been killed and will attempt to respawn automatically.`))},o)});try{return await Promise.race([a,n])}finally{t!==void 0&&clearTimeout(t)}}return a}async shutdown(){if(this.clearCooldownRespawnTimer(),this.shutdownPromise)return this.shutdownPromise;let e=this.child;if(!e)return;let t=this.requireChildState(e);t.shutdownRequested=!0,this.readyChild===e&&(this.readyChild=null),this.shutdownPromise=new Promise((t,n)=>{this.pendingShutdown={child:e,resolve:t,reject:n}}).finally(()=>{this.shutdownPromise=null});try{e.send({type:`shutdown`})}catch(t){let n=this.toError(t,`Failed to send shutdown request to worker`);throw this.clearChildReference(e),this.rejectPendingForChild(e,n),this.rejectLifecycleIfOwned(`shutdown`,e,n),n}return this.shutdownPromise}async startWorker(){this.child&&this.readyChild!==this.child&&(this.child=null),this.clearCooldownRespawnTimer(),this.coldStart=!0;let e=this.spawnChild();this.child=e,this.readyChild=null;let t=new Promise((t,n)=>{this.pendingInit={child:e,resolve:t,reject:n}});try{e.send({type:`init`,config:this.buildInitConfig()})}catch(t){let n=this.toError(t,`Failed to send init request to worker`);throw this.pendingInit=null,this.clearChildReference(e),n}if(this.initTimeoutMs>0){let n,r=new Promise((e,t)=>{n=setTimeout(()=>{t(Error(`Embedder worker initialization timed out after ${this.initTimeoutMs/1e3}s. The ONNX model may be downloading or the child process is stuck. Check network connectivity and disk space, or restart the server.`))},this.initTimeoutMs)});try{await Promise.race([t,r]);return}catch(t){this.pendingInit=null;try{e.kill()}catch{}throw this.clearChildReference(e),t}finally{n!==void 0&&clearTimeout(n)}}await t}spawnChild(){let t=e(this.workerPath,[],{env:this.buildChildEnv()});return this.childState.set(t,{idleExitNotified:!1,shutdownRequested:!1,terminated:!1}),t.on(`message`,e=>{this.handleChildMessage(t,e)}),t.once(`error`,e=>{this.handleChildFailure(t,this.toError(e,`Embedder worker failed`))}),t.once(`exit`,(e,n)=>{this.handleChildExit(t,e,n)}),t}handleChildMessage(e,t){switch(t.type){case`ready`:{this.currentDimensions=t.dimensions,this.currentModelId=t.modelId,this.healthBus.reportRecovered(`embedder`),this.child===e&&(this.readyChild=e,this.cb.getState()!==`closed`&&this.cb.reset());let n=this.pendingInit;n?.child===e&&(this.pendingInit=null,n.resolve());return}case`result`:{let n=this.pendingRequests.get(t.id);if(!n||n.child!==e)return;this.pendingRequests.delete(t.id),this.coldStart=!1,this.cb.recordSuccess(),n.resolve(new Float32Array(t.data));return}case`batchResult`:{let n=this.pendingRequests.get(t.id);if(!n||n.child!==e)return;if(this.pendingRequests.delete(t.id),!t.data||!Array.isArray(t.data)||t.data.length===0)n.reject(Error(`Worker returned empty or invalid batch result`));else{let e=t.data.map(e=>new Float32Array(e)),r=e.findIndex(e=>e.length===0);r>=0?n.reject(Error(`Worker returned zero-length vector at index ${r}`)):(this.coldStart=!1,this.cb.recordSuccess(),n.resolve(e))}return}case`error`:{let n=Error(t.message);if(this.childErrors.set(e,n),t.id===`init`){this.clearChildReference(e),this.rejectLifecycleIfOwned(`init`,e,n);return}if(t.id===`shutdown`){this.rejectLifecycleIfOwned(`shutdown`,e,n);return}let r=this.pendingRequests.get(t.id);if(!r||r.child!==e)return;this.pendingRequests.delete(t.id),r.reject(n);return}case`idle-exit`:{let t=this.requireChildState(e);t.idleExitNotified=!0,this.clearChildReference(e);return}}}handleChildExit(e,t,n){let r=this.requireChildState(e);if(r.terminated)return;r.terminated=!0,this.clearChildReference(e);let i=r.shutdownRequested||r.idleExitNotified,a=this.childErrors.get(e)??Error(i?`Embedder worker exited before completing request`:`Embedder worker exited unexpectedly (code ${t??`null`}${n?`, signal ${n}`:``})`);this.rejectLifecycleIfOwned(`init`,e,a),i?this.resolveLifecycleIfOwned(`shutdown`,e):this.rejectLifecycleIfOwned(`shutdown`,e,a),this.rejectPendingForChild(e,a),i||this.cb.recordFailure()}handleChildFailure(e,t){let n=this.requireChildState(e);n.terminated||(n.terminated=!0,this.clearChildReference(e),this.rejectLifecycleIfOwned(`init`,e,t),this.rejectLifecycleIfOwned(`shutdown`,e,t),this.rejectPendingForChild(e,t))}async sendVectorRequestWithRetry(e){return this.withWorkerExitRetry(e.type,()=>this.sendVectorRequest(e))}async sendVectorRequest(e){await this.initialize();let n=this.requireReadyChild(),r=t(),i=this.requestTimeoutMs>0?this.coldStart?this.requestTimeoutMs*2:this.requestTimeoutMs:0,a=new Promise((e,t)=>{this.pendingRequests.set(r,{child:n,resolve:t=>e(t),reject:t})});try{n.send({...e,id:r})}catch(t){throw this.pendingRequests.delete(r),this.toError(t,`Failed to send ${e.type} request to worker`)}if(i>0){let t,n=new Promise((n,a)=>{t=setTimeout(()=>{this.pendingRequests.delete(r),this.markWorkerUnresponsive(),a(Error(`Embedder ${e.type} request timed out after ${i/1e3}s. The worker has been killed and will attempt to respawn automatically.`))},i)});try{return await Promise.race([a,n])}finally{t!==void 0&&clearTimeout(t)}}return a}async withWorkerExitRetry(e,t){let n=null,r=this.maxRetries;for(let i=0;i<=r;i++)try{return await t()}catch(t){let a=this.toError(t,`Failed to process ${e} request`);if(!this.isWorkerExitError(a))throw a;if(n??=a,i===0&&/exited/i.test(a.message)&&!/timed out/i.test(a.message)&&(r=Math.min(r,1)),i===r)throw n;let o=i+1,s=this.retryBaseDelayMs*2**i;if(this.healthBus.reportDegraded(`embedder`,`Worker crashed during ${e} — retrying (${o}/${r})`),this.logger?.warn?.(`Embedder retry ${o}/${r} after ${s}ms`,{requestType:e,delayMs:s,error:a.message}),this.child=null,this.readyChild=null,await this.wait(s),this.cb.isOpen())throw n??a}throw n??Error(`Failed to process ${e} request`)}isWorkerExitError(e){return/embedder worker exited|EPIPE|ECONNRESET|ERR_IPC_CHANNEL_CLOSED|channel closed|write after end/i.test(e.message)}wait(e){return new Promise(t=>{setTimeout(t,e)})}requireReadyChild(){if(!this.child||this.readyChild!==this.child)throw Error(`Embedder worker is not initialized`);return this.child}buildInitConfig(){return{model:this.options.model,dimensions:this.options.dimensions,nativeDim:this.options.nativeDim,queryPrefix:this.options.queryPrefix,interOpNumThreads:this.options.interOpNumThreads,intraOpNumThreads:this.options.intraOpNumThreads}}buildChildEnv(){return this.options.idleTimeoutMs===void 0?process.env:{...process.env,AIKIT_EMBED_IDLE_MS:String(this.options.idleTimeoutMs)}}requireChildState(e){let t=this.childState.get(e);if(!t)throw Error(`Embedder worker state not found`);return t}clearChildReference(e){this.child===e&&(this.child=null),this.readyChild===e&&(this.readyChild=null)}clearCooldownRespawnTimer(){this.cooldownRespawnTimer&&=(clearTimeout(this.cooldownRespawnTimer),null)}startCooldownRespawn(){this.clearCooldownRespawnTimer(),this.cooldownRespawnTimer=setTimeout(()=>{this.cooldownRespawnTimer=null,!this.child&&!this.shutdownPromise&&this.workerAvailable&&this.initialize().catch(()=>{})},6e4),this.logger?.warn?.(`Embedder circuit breaker OPEN — too many consecutive failures`,{cooldownMs:6e4})}markWorkerUnresponsive(){let e=this.child;if(e){try{e.kill()}catch{}this.clearChildReference(e),this.cb.recordFailure(),this.cb.isOpen()||setImmediate(()=>{!this.child&&this.workerAvailable&&!this.shutdownPromise&&this.initialize().catch(()=>{})})}}assertCircuitClosed(){if(this.cb.isOpen())throw new s(this.cb.remainingCooldownMs())}rejectPendingForChild(e,t){for(let[n,r]of this.pendingRequests)r.child===e&&(this.pendingRequests.delete(n),r.reject(t))}resolveLifecycleIfOwned(e,t){let n=this.pendingShutdown;!n||n.child!==t||(this.pendingShutdown=null,n.resolve())}rejectLifecycleIfOwned(e,t,n){let r=e===`init`?this.pendingInit:this.pendingShutdown;!r||r.child!==t||(e===`init`?this.pendingInit=null:this.pendingShutdown=null,r.reject(n))}toError(e,t){return e instanceof Error?e:Error(`${t}: ${String(e)}`)}};let p=null;function m(e){if(!(e instanceof Error))return!1;let t=e.code;return t===`ERR_MODULE_NOT_FOUND`||t===`MODULE_NOT_FOUND`?!0:/cannot find (module|package)|module not found/i.test(e.message)}async function h(){if(!p){try{p=await import(`@huggingface/transformers`)}catch(e){if(m(e)){let{createRequire:t}=await import(`node:module`),n=t(import.meta.url);try{p=n("@huggingface/transformers")}catch(t){let n=e instanceof Error?e.message:String(e),r=t instanceof Error?t.message:String(t);throw Error(`Unable to load @huggingface/transformers via ESM or CJS. ESM: ${n}; CJS: ${r}`)}}else throw e}p.env.cacheDir=i(d(),`.cache`,`huggingface`,`transformers-js`)}return p}var g=class{pipe=null;shutdownPromise=null;dimensions;modelId;nativeDim;queryPrefix;threadConfig;constructor(e={}){if(this.modelId=e.model??c.model,this.nativeDim=e.nativeDim??c.nativeDim,this.dimensions=e.dimensions??c.dimensions,this.dimensions>this.nativeDim)throw Error(`Configured dimensions (${this.dimensions}) exceeds model native output (${this.nativeDim}). Matryoshka truncation cannot upscale — dimensions must be <= nativeDim.`);this.queryPrefix=e.queryPrefix??this.detectQueryPrefix(this.modelId),this.threadConfig={interOp:e.interOpNumThreads??1,intraOp:e.intraOpNumThreads??4}}detectQueryPrefix(e){let t=e.toLowerCase();return t.includes(`bge`)||t.includes(`mxbai-embed`)?`Represent this sentence for searching relevant passages: `:t.includes(`/e5-`)||t.includes(`multilingual-e5`)?`query: `:``}getPipelineOptions(e){let t=e.backends.onnx;t.wasm||={};let n=t.wasm;return n.numThreads=this.threadConfig.intraOp,{dtype:`q8`,session_options:{interOpNumThreads:this.threadConfig.interOp,intraOpNumThreads:this.threadConfig.intraOp}}}computeNorm(e){let t=0;for(let n=0;n<e.length;n++)t+=e[n]*e[n];return Math.sqrt(t)}truncateAndRenorm(e){if(this.dimensions>=this.nativeDim){let t=this.computeNorm(e);if(!Number.isFinite(t))throw Error(`Embedding produced non-finite norm — output contained NaN or Infinity`);if(t===0)throw Error(`Embedding produced zero-norm vector from ONNX output`);return e}let t=e.subarray(0,this.dimensions),n=this.computeNorm(t);if(!Number.isFinite(n))throw Error(`Embedding produced non-finite norm — output contained NaN or Infinity`);if(n===0)throw Error(`Embedding produced zero-norm vector after truncation — input may be degenerate`);let r=new Float32Array(this.dimensions);for(let e=0;e<this.dimensions;e++)r[e]=t[e]/n;return r}async initialize(){if(this.pipe)return;this.shutdownPromise=null;let{pipeline:e,env:t}=await h();try{this.pipe=await e(`feature-extraction`,this.modelId,this.getPipelineOptions(t))}catch(n){let r=n.message?.toLowerCase()??``;if(this.isCorruptionError(r)){let n=i(t.cacheDir??i(d(),`.cache`,`huggingface`,`transformers-js`),this.modelId);console.error(`[aikit:auto-heal] Detected corrupted model cache for "${this.modelId}". Clearing cache at ${n} and retrying download...`);try{await u(n,{recursive:!0,force:!0})}catch{}try{this.pipe=await e(`feature-extraction`,this.modelId,this.getPipelineOptions(t)),console.error(`[aikit:auto-heal] Model "${this.modelId}" re-downloaded successfully.`);return}catch(e){throw Error(`Failed to initialize embedding model "${this.modelId}" after auto-heal: ${e.message}`)}}throw Error(`Failed to initialize embedding model "${this.modelId}": ${n.message}`)}}isCorruptionError(e){return[`protobuf`,`invalid model`,`invalid onnx`,`unexpected end`,`unexpected token`,`failed to load`,`checksum`,`corrupt`,`could not load`,`onnx`,`malformed`].some(t=>e.includes(t))}async shutdown(){return this.shutdownPromise||=this._doShutdown(),this.shutdownPromise}async _doShutdown(){let e=this.pipe;if(e)try{let t=e;typeof t.dispose==`function`?await t.dispose():typeof t.model?.dispose==`function`&&await t.model.dispose()}catch{}finally{this.pipe=null}}async embed(e){this.pipe||await this.initialize();let t=await this.pipe?.(e,{pooling:`mean`,normalize:!0});if(!t?.data)throw Error(`Embedding pipeline returned no output`);try{let e=new Float32Array(t.data);return this.truncateAndRenorm(e)}finally{t.dispose?.()}}async embedQuery(e){return this.embed(this.queryPrefix+e)}async embedBatch(e,t=64){if(e.length===0)return[];this.pipe||await this.initialize();let n=[];for(let r=0;r<e.length;r+=t){let i=e.slice(r,r+t),a=await this.pipe?.(i,{pooling:`mean`,normalize:!0});if(!a?.data)throw Error(`Embedding pipeline returned no output`);try{if(i.length===1){let e=new Float32Array(a.data);n.push(this.truncateAndRenorm(e))}else for(let e=0;e<i.length;e++){let t=e*this.nativeDim,r=a.data.slice(t,t+this.nativeDim);n.push(this.truncateAndRenorm(new Float32Array(r)))}}finally{a.dispose?.()}}return n}};export{f as EmbedderProxy,g as OnnxEmbedder};
@@ -1969,8 +1969,8 @@ container holding the app. Specify either width or maxWidth, and either height o
1969
1969
  accent-color: var(--dt-accent-fg);
1970
1970
  }
1971
1971
  `;function pC(e){let t=e.createElement(`style`);return t.textContent=fC,t}function mC(e,t){let n=t.filter(e=>e.getAttribute(`data-checked`)===`true`).length,r=t.length;return e.textContent=`${n}/${r} complete`,{complete:n,total:r}}function hC(e,t={}){let n=Array.from(e.querySelectorAll(`.bk-checklist-item`));if(n.length===0)return()=>{};let r=e.ownerDocument,i=pC(r),a=r.createElement(`div`);a.className=`bk-checklist-progress`,e.parentElement?.insertBefore(a,e),r.head?.appendChild(i);let o=[];for(let[e,i]of n.entries()){let s=i.querySelector(`.bk-checklist-icon`),c=i.querySelector(`.bk-checklist-label`)?.textContent?.trim()??``,l=r.createElement(`input`);l.type=`checkbox`,l.className=`bk-checklist-box`,l.checked=i.getAttribute(`data-checked`)===`true`;let u=()=>{i.setAttribute(`data-checked`,String(l.checked));let r=mC(a,n);t.onAction?.(`checklist`,JSON.stringify({index:e,label:c,checked:l.checked,complete:r.complete,total:r.total}))};l.addEventListener(`change`,u),o.push(()=>{l.removeEventListener(`change`,u)}),s?s.replaceWith(l):i.insertBefore(l,i.firstChild)}return mC(a,n),()=>{for(let e of o)e();a.remove(),i.remove();for(let e of n){let t=e.querySelector(`.bk-checklist-box`);if(!t)continue;let n=r.createElement(`span`);n.className=`bk-checklist-icon`,n.textContent=e.getAttribute(`data-checked`)===`true`?`✓`:`×`,t.replaceWith(n)}}}var gC=`data-sort-label`,_C=`data-sort-dir`,vC=new Intl.Collator(void 0,{numeric:!0,sensitivity:`base`});function yC(e){let t=e.getAttribute(gC);if(t!==null)return t;let n=e.textContent?.trim()??``;return e.setAttribute(gC,n),n}function bC(e,t,n){for(let[r,i]of e.entries())i.textContent=yC(i),r===t?(i.setAttribute(_C,n),i.append(` ${n===`asc`?`▲`:`▼`}`)):i.removeAttribute(_C)}function xC(e,t){return e.querySelectorAll(`td`)[t]?.textContent?.trim()??``}function SC(e){let t=Array.from(e.querySelectorAll(`thead th`)),n=e.querySelector(`tbody`);if(!n||t.length===0)return()=>{};let r=Array.from(n.querySelectorAll(`tr`)),i=e.parentElement,a=null,o=`asc`,s=``,c=null,l=[],u=()=>{let e=[...r];if(a!==null){let t=a;e.sort((e,n)=>{let r=vC.compare(xC(e,t),xC(n,t));return o===`asc`?r:-r})}for(let t of e){n.appendChild(t);let e=t.textContent?.toLowerCase()??``;t.hidden=s.length>0&&!e.includes(s)}bC(t,a,o)};for(let[e,n]of t.entries()){yC(n);let t=()=>{a===e?o=o===`asc`?`desc`:`asc`:(a=e,o=`asc`),u()};n.style.cursor=`pointer`,n.addEventListener(`click`,t),l.push(()=>{n.removeEventListener(`click`,t)})}if(r.length>5&&i){c=i.ownerDocument.createElement(`input`),c.className=`bk-table-filter`,c.placeholder=`Filter...`;let t=()=>{s=c?.value.toLowerCase().trim()??``,u()};i.insertBefore(c,e),c.addEventListener(`input`,t),l.push(()=>{c?.removeEventListener(`input`,t),c?.remove(),c=null})}return u(),()=>{for(let e of l)e();for(let e of t)e.textContent=yC(e),e.removeAttribute(_C),e.removeAttribute(gC),e.style.removeProperty(`cursor`);for(let e of r)e.hidden=!1}}function CC(e){for(let t of Array.from(e.children))if(t.tagName===`SUMMARY`)return t;return null}function wC(e){let t=e.closest(`details`);if(!t)return null;let n=t.parentElement;for(;n;){if(n.tagName===`DETAILS`)return CC(n);n=n.parentElement}return null}function TC(e){return Array.from(e.querySelectorAll(`summary`))}function EC(e){return e.open||e.hasAttribute(`open`)}function DC(e,t){e.open=t,t?e.setAttribute(`open`,``):e.removeAttribute(`open`)}function OC(e,t){e.textContent=t.every(e=>EC(e))?`Collapse all`:`Expand all`}function kC(e){let t=Array.from(e.querySelectorAll(`details`));if(t.length===0)return()=>{};let n=e.ownerDocument.createElement(`button`);n.type=`button`,n.className=`bk-tree-toggle-all`,e.insertBefore(n,e.firstChild);let r=()=>{let e=t.some(e=>!EC(e));for(let n of t)DC(n,e);OC(n,t)},i=()=>{r()};n.addEventListener(`click`,i);let a=t.map(e=>{let r=()=>{OC(n,t)};return e.addEventListener(`toggle`,r),()=>{e.removeEventListener(`toggle`,r)}}),o=TC(e).map(t=>{t.tabIndex=0;let n=n=>{let r=TC(e),i=r.indexOf(t);if(i===-1)return;let a=t.closest(`details`);if(n.key===`ArrowDown`){r[i+1]?.focus(),n.preventDefault();return}if(n.key===`ArrowUp`){r[i-1]?.focus(),n.preventDefault();return}if(n.key===`ArrowRight`){if(a&&!EC(a))DC(a,!0);else{let e=r[i+1];e&&a?.contains(e)&&e.focus()}n.preventDefault();return}n.key===`ArrowLeft`&&(a&&EC(a)?DC(a,!1):wC(t)?.focus(),n.preventDefault())};return t.addEventListener(`keydown`,n),()=>{t.removeEventListener(`keydown`,n)}});return OC(n,t),()=>{n.removeEventListener(`click`,i);for(let e of a)e();for(let e of o)e();n.remove()}}var AC=`data-hydrated`;function jC(e,t){let n=[];return e.matches(t)&&n.push(e),n.push(...Array.from(e.querySelectorAll(t))),n}function MC(e,t,n){e.push(()=>{n(),t.removeAttribute(AC)})}function NC(e={}){let t=e.container??document.body,n=[];for(let e of jC(t,`.bk-table`))e.hasAttribute(AC)||(e.setAttribute(AC,``),MC(n,e,SC(e)));for(let e of jC(t,`.bk-tree`))e.hasAttribute(AC)||(e.setAttribute(AC,``),MC(n,e,kC(e)));for(let r of jC(t,`.bk-checklist`))r.hasAttribute(AC)||(r.setAttribute(AC,``),MC(n,r,hC(r,e)));for(let r of jC(t,`.bk-actions`))if(!r.hasAttribute(AC)){if(r.setAttribute(AC,``),e.onAction){MC(n,r,dC(r,e.onAction));continue}n.push(()=>{r.removeAttribute(AC)})}return()=>{for(let e of n)e();n.length=0}}var PC=`bk-styles`,FC=new Set;function IC(e){for(let t of e.css)t.trim().length>0&&FC.add(t);return[...FC].join(`
1972
- `)}function LC(e){return di(e,{transport:`browser`})}function RC(e,t=document){let n=IC(e),r=t.getElementById(PC);r||(r=t.createElement(`style`),r.id=PC,t.head.appendChild(r)),r.textContent=n}function zC(e,t){let n=LC(t);return RC(n,e.ownerDocument),e.innerHTML=n.html,n}function BC(e,t,n){return zC(e,{schemaVersion:1,title:`AI Kit Present`,blocks:t}),NC({container:e,onAction:n})}function VC(e){return function(t,n){let r=n??t.label;if(!e){fetch(`/callback`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({actionId:t.id,value:r})});return}e.updateModelContext({content:[{type:`text`,text:`Latest UI action: ${t.label}${n?` → ${n}`:``}`}],structuredContent:{actionId:t.id,actionType:t.type,label:t.label,value:r,timestamp:new Date().toISOString()}}),e.sendMessage({role:`user`,content:[{type:`text`,text:`User selected: ${t.label}${n?` → ${n}`:``}`}]})}}function HC(e){return typeof e==`object`&&!!e}function UC(e,t){let n=e.id.split(`@`)[0];return n===`timeline`&&HC(t)&&Array.isArray(t.events)?t.events:n===`tree`&&Array.isArray(t)?{root:{label:`Root`,children:t}}:t}function WC(e,t,n){let r=oi.get(e);if(!r?.supportedTransports.includes(`browser`))return null;let i=UC(r,t);return{blocks:r.blocksFromData(i,{colorScheme:n.colorScheme,transport:`browser`,lang:n.lang,dir:n.dir}),actions:r.actionsFromData?.(i)??[]}}var GC=`present-data`;function KC(e=document,t=GC){let n=e.getElementById(t);return n?.textContent?JSON.parse(n.textContent):null}function qC(e){return e?{callTool:(t,n)=>e.callServerTool({name:t,arguments:n}),sendMessage:async t=>{await e.sendMessage({role:`user`,content:[{type:`text`,text:t}]})},updateContext:async t=>{await e.updateModelContext({content:[{type:`text`,text:t}]})}}:{callTool:async()=>{throw Error(`callTool is not available in browser mode`)},sendMessage:async()=>{},updateContext:async()=>{}}}var JC=class{app;currentMode=`inline`;availableModes=[];toolbar=null;constructor(e){this.app=e}apply(e){e.displayMode&&(this.currentMode=e.displayMode),e.availableDisplayModes&&(this.availableModes=e.availableDisplayModes),this.updateToolbar()}async requestMode(e){try{let t=await this.app.requestDisplayMode({mode:e});return this.currentMode=t.mode,document.documentElement.dataset.display=t.mode,this.updateToolbar(),t.mode}catch{return this.currentMode}}updateToolbar(){if(this.availableModes.length<=1){this.toolbar?.remove(),this.toolbar=null;return}this.toolbar||=this.createToolbar(),this.renderButtons()}createToolbar(){let e=document.createElement(`div`);return e.className=`display-mode-toolbar`,document.body.appendChild(e),e}renderButtons(){if(!this.toolbar)return;this.toolbar.innerHTML=``;let e={inline:`▣`,fullscreen:`⛶`,pip:`◱`};for(let t of this.availableModes){let n=document.createElement(`button`);n.className=`dm-btn${t===this.currentMode?` dm-active`:``}`,n.textContent=e[t]??t,n.title=t,n.addEventListener(`click`,()=>this.requestMode(t)),this.toolbar.appendChild(n)}}},YC=new Set;function XC(e,t){if(YC.has(e))return;YC.add(e);let n=document.createElement(`style`);n.textContent=t,document.head.appendChild(n)}function Q(e,t,n){let r=document.createElement(e);return t&&(r.className=t),n&&(r.textContent=n),r}function ZC(e){return e==null?`null`:Array.isArray(e)?`[${e.map(ZC).join(`, `)}]`:String(e)}function QC(e){return typeof e==`object`&&!!e&&`type`in e}var $C=[[400,`compact`],[800,`comfortable`]],ew=class{root;displayMode=`inline`;sizeClass=`comfortable`;constructor(e){this.root=e??document.documentElement}apply(e){this.applyDisplayMode(e),this.applyContainerDimensions(e),this.applySafeArea(e),this.applyPlatform(e),this.applyDeviceCapabilities(e)}getDisplayMode(){return this.displayMode}getSize(){return this.sizeClass}applyDisplayMode(e){e.displayMode&&(this.displayMode=e.displayMode,this.root.dataset.display=e.displayMode)}applyContainerDimensions(e){let t=e.containerDimensions;if(!t)return;let n=this.root.style,r=`width`in t?t.width:`maxWidth`in t?t.maxWidth:void 0,i=`height`in t?t.height:`maxHeight`in t?t.maxHeight:void 0;r!==void 0&&(n.setProperty(`--aikit-container-w`,`${r}px`),this.sizeClass=this.deriveSizeClass(r),this.root.dataset.size=this.sizeClass,n.setProperty(`--aikit-content-max-width`,this.deriveMaxWidth(r)),n.setProperty(`--aikit-body-pad-x`,this.derivePadX()),n.setProperty(`--aikit-grid-cols`,this.deriveGridCols()),n.setProperty(`--aikit-card-min`,this.deriveCardMin()),n.setProperty(`--aikit-metric-min`,this.deriveMetricMin())),i!==void 0&&(n.setProperty(`--aikit-container-h`,`${i}px`),n.setProperty(`--aikit-body-pad-y`,this.derivePadY()))}applySafeArea(e){let t=e.safeAreaInsets;if(!t)return;let n=this.root.style;n.setProperty(`--aikit-safe-top`,`${t.top}px`),n.setProperty(`--aikit-safe-right`,`${t.right}px`),n.setProperty(`--aikit-safe-bottom`,`${t.bottom}px`),n.setProperty(`--aikit-safe-left`,`${t.left}px`)}applyPlatform(e){e.platform&&(this.root.dataset.platform=e.platform)}applyDeviceCapabilities(e){let t=e.deviceCapabilities;t&&(t.touch!==void 0&&(this.root.dataset.touch=String(t.touch)),t.hover!==void 0&&(this.root.dataset.hover=String(t.hover)))}deriveSizeClass(e){for(let[t,n]of $C)if(e<t)return n;return`full`}deriveMaxWidth(e){return this.displayMode===`pip`?`100%`:this.displayMode===`fullscreen`?`none`:e<960?`100%`:`900px`}derivePadX(){return this.sizeClass===`compact`?`8px`:`16px`}derivePadY(){return this.sizeClass===`compact`?`8px`:`16px`}deriveGridCols(){switch(this.sizeClass){case`compact`:return`1`;case`comfortable`:return`2`;case`full`:return`3`}}deriveCardMin(){return this.sizeClass===`compact`?`100%`:`250px`}deriveMetricMin(){return this.sizeClass===`compact`?`100px`:`150px`}},tw=`AI Kit Present`;function nw(e){if(!Array.isArray(e)&&typeof e==`object`&&e){let t=e;if(Array.isArray(t.blocks)&&t.blocks.length>0)return t.blocks}return e}function rw(e){if(Array.isArray(e))return e.length===0?[{type:`markdown`,value:`*Empty array*`}]:QC(e[0])?e.filter(QC):typeof e[0]==`object`&&e[0]!==null?[{type:`table`,value:e}]:[{type:`markdown`,value:e.map(e=>`- ${String(e)}`).join(`
1973
- `)}];if(typeof e==`string`)return[{type:`markdown`,value:e}];if(typeof e==`object`&&e){let t=e;return Array.isArray(t.nodes)&&Array.isArray(t.edges)?[{type:`graph`,value:t}]:Array.isArray(t.metrics)?[{type:`metrics`,value:t.metrics}]:[{type:`json`,value:t}]}return[{type:`text`,value:String(e??``)}]}function iw(e){return{...e,options:e.options?.map(e=>typeof e==`string`?{label:e,value:e}:e)}}function aw(e){let t=nw(e.content);return{schemaVersion:1,title:e.title??tw,template:e.template,data:t,blocks:rw(t),actions:e.actions?.map(iw)}}var ow=class{templates=new Map;register(e){this.templates.set(e.name,e)}get(e){return this.templates.get(e)}detect(e){let t,n=0;for(let r of this.templates.values()){let i=r.detect(e);i>n&&(n=i,t=r)}return n>0?t:void 0}getAll(){return[...this.templates.values()]}},sw={"--color-background-primary":`--aikit-bg`,"--color-background-secondary":`--aikit-surface`,"--color-background-tertiary":`--aikit-surface2`,"--color-text-primary":`--aikit-text`,"--color-text-secondary":`--aikit-muted`,"--color-border-primary":`--aikit-border`,"--color-ring-primary":`--aikit-accent`,"--color-text-success":`--aikit-success`,"--color-text-danger":`--aikit-error`,"--color-text-warning":`--aikit-warning`,"--color-text-info":`--aikit-info`,"--font-sans":`--aikit-font-sans`,"--font-mono":`--aikit-font-mono`,"--border-radius-md":`--aikit-radius`,"--shadow-sm":`--aikit-shadow`},cw={"--aikit-bg":`--bg`,"--aikit-text":`--fg`,"--aikit-surface":`--surface`,"--aikit-border":`--border`,"--aikit-accent":`--accent`,"--aikit-success":`--success`,"--aikit-warning":`--warning`,"--aikit-error":`--error`,"--aikit-font-sans":`--font-sans`,"--aikit-font-mono":`--font-mono`,"--aikit-radius":`--radius`,"--aikit-shadow":`--shadow`},lw=`aikit-design-token-bridge`,uw={light:{"--bg":`#ffffff`,"--fg":`rgb(26 26 46)`,"--surface":`#f8f9fa`,"--border":`#e2e8f0`,"--accent":`#58a6ff`,"--accent-light":`#79c0ff`,"--success":`#22c55e`,"--warning":`#f59e0b`,"--error":`#ef4444`,"--code-bg":`#1e1e2e`,"--code-fg":`#cdd6f4`,"--radius":`8px`,"--shadow":`0 1px 3px rgba(0,0,0,0.08), 0 1px 2px rgba(0,0,0,0.06)`,"--font-sans":`-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif`,"--font-mono":`'Cascadia Code', 'Fira Code', 'JetBrains Mono', Consolas, monospace`,"--aikit-bg":`#ffffff`,"--aikit-surface":`#f8f9fa`,"--aikit-surface2":`#f8f9fa`,"--aikit-text":`rgb(26 26 46)`,"--aikit-muted":`#94a3b8`,"--aikit-border":`#e2e8f0`,"--aikit-accent":`#58a6ff`,"--aikit-accent-light":`#79c0ff`,"--aikit-success":`#22c55e`,"--aikit-warning":`#f59e0b`,"--aikit-error":`#ef4444`,"--aikit-info":`#58a6ff`,"--aikit-code-bg":`#1e1e2e`,"--aikit-code-fg":`#cdd6f4`,"--aikit-font-sans":`-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif`,"--aikit-font-mono":`'Cascadia Code', 'Fira Code', 'JetBrains Mono', Consolas, monospace`,"--aikit-radius":`8px`,"--aikit-shadow":`0 1px 3px rgba(0,0,0,0.08), 0 1px 2px rgba(0,0,0,0.06)`,"--aikit-hover-bg":`color-mix(in srgb, #58a6ff 10%, transparent)`},dark:{"--bg":`#0d1117`,"--fg":`#e6edf3`,"--surface":`#161b22`,"--border":`#30363d`,"--accent":`#58a6ff`,"--accent-light":`#79c0ff`,"--success":`#22c55e`,"--warning":`#f59e0b`,"--error":`#ef4444`,"--code-bg":`#161b22`,"--code-fg":`#cdd6f4`,"--radius":`8px`,"--shadow":`0 1px 3px rgba(0,0,0,0.3)`,"--font-sans":`-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif`,"--font-mono":`'Cascadia Code', 'Fira Code', 'JetBrains Mono', Consolas, monospace`,"--aikit-bg":`#0d1117`,"--aikit-surface":`#161b22`,"--aikit-surface2":`#161b22`,"--aikit-text":`#e6edf3`,"--aikit-muted":`#94a3b8`,"--aikit-border":`#30363d`,"--aikit-accent":`#58a6ff`,"--aikit-accent-light":`#79c0ff`,"--aikit-success":`#22c55e`,"--aikit-warning":`#f59e0b`,"--aikit-error":`#ef4444`,"--aikit-info":`#58a6ff`,"--aikit-code-bg":`#161b22`,"--aikit-code-fg":`#cdd6f4`,"--aikit-font-sans":`-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif`,"--aikit-font-mono":`'Cascadia Code', 'Fira Code', 'JetBrains Mono', Consolas, monospace`,"--aikit-radius":`8px`,"--aikit-shadow":`0 1px 3px rgba(0,0,0,0.3)`,"--aikit-hover-bg":`color-mix(in srgb, #58a6ff 10%, transparent)`}},dw={"--chart-1":`#79c0ff`,"--chart-2":`#38bdf8`,"--chart-3":`#34d399`,"--chart-4":`#fbbf24`,"--chart-5":`#f87171`,"--chart-6":`#a78bfa`,"--chart-7":`#f472b6`,"--chart-8":`#2dd4bf`,"--chart-9":`#fb923c`,"--chart-10":`#22d3ee`,"--chart-11":`#c084fc`,"--chart-12":`#a3e635`,"--chart-others":`#a8a29e`},fw=`
1972
+ `)}function LC(e){return di(e,{transport:`browser`})}function RC(e,t=document){let n=IC(e),r=t.getElementById(PC);r||(r=t.createElement(`style`),r.id=PC,t.head.appendChild(r)),r.textContent=n}function zC(e,t){let n=LC(t);return RC(n,e.ownerDocument),e.innerHTML=n.html,n}function BC(e,t,n){return zC(e,{schemaVersion:1,title:`AI Kit Present`,blocks:t}),NC({container:e,onAction:n})}function VC(e){return function(t,n){let r=n??t.label;if(!e){fetch(`/callback`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({actionId:t.id,value:r})});return}e.updateModelContext({content:[{type:`text`,text:`Latest UI action: ${t.label}${n?` → ${n}`:``}`}],structuredContent:{actionId:t.id,actionType:t.type,label:t.label,value:r,timestamp:new Date().toISOString()}}),e.sendMessage({role:`user`,content:[{type:`text`,text:`User selected: ${t.label}${n?` → ${n}`:``}`}]})}}function HC(e){return typeof e==`object`&&!!e}function UC(e,t){let n=e.id.split(`@`)[0];return n===`timeline`&&HC(t)&&Array.isArray(t.events)?t.events:n===`tree`&&Array.isArray(t)?{root:{label:`Root`,children:t}}:t}function WC(e,t,n){let r=oi.get(e);if(!r?.supportedTransports.includes(`browser`))return null;let i=UC(r,t);return{blocks:r.blocksFromData(i,{colorScheme:n.colorScheme,transport:`browser`,lang:n.lang,dir:n.dir}),actions:r.actionsFromData?.(i)??[]}}var GC=`present-data`;function KC(e=document,t=GC){let n=e.getElementById(t);return n?.textContent?JSON.parse(n.textContent):null}function qC(e){return e?{callTool:(t,n)=>e.callServerTool({name:t,arguments:n}),sendMessage:async t=>{await e.sendMessage({role:`user`,content:[{type:`text`,text:t}]})},updateContext:async t=>{await e.updateModelContext({content:[{type:`text`,text:t}]})}}:{callTool:async()=>{throw Error(`callTool is not available in browser mode`)},sendMessage:async()=>{},updateContext:async()=>{}}}var JC=class{app;currentMode=`inline`;availableModes=[];toolbar=null;constructor(e){this.app=e}apply(e){e.displayMode&&(this.currentMode=e.displayMode),e.availableDisplayModes&&(this.availableModes=e.availableDisplayModes),this.updateToolbar()}async requestMode(e){try{let t=await this.app.requestDisplayMode({mode:e});return this.currentMode=t.mode,document.documentElement.dataset.display=t.mode,this.updateToolbar(),t.mode}catch{return this.currentMode}}updateToolbar(){if(this.availableModes.length<=1){this.toolbar?.remove(),this.toolbar=null;return}this.toolbar||=this.createToolbar(),this.renderButtons()}createToolbar(){let e=document.createElement(`div`);return e.className=`display-mode-toolbar`,document.body.appendChild(e),e}renderButtons(){if(!this.toolbar)return;this.toolbar.innerHTML=``;let e={inline:`▣`,fullscreen:`⛶`,pip:`◱`};for(let t of this.availableModes){let n=document.createElement(`button`);n.className=`dm-btn${t===this.currentMode?` dm-active`:``}`,n.textContent=e[t]??t,n.title=t,n.addEventListener(`click`,()=>this.requestMode(t)),this.toolbar.appendChild(n)}}},YC=new Set;function XC(e,t){if(YC.has(e))return;YC.add(e);let n=document.createElement(`style`);n.textContent=t,document.head.appendChild(n)}function Q(e,t,n){let r=document.createElement(e);return t&&(r.className=t),n&&(r.textContent=n),r}function ZC(e){return e==null?`null`:Array.isArray(e)?`[${e.map(ZC).join(`, `)}]`:String(e)}function QC(e){return typeof e==`object`&&!!e&&`type`in e}var $C=[[400,`compact`],[800,`comfortable`]],ew=class{root;displayMode=`inline`;sizeClass=`comfortable`;constructor(e){this.root=e??document.documentElement}apply(e){this.applyDisplayMode(e),this.applyContainerDimensions(e),this.applySafeArea(e),this.applyPlatform(e),this.applyDeviceCapabilities(e)}getDisplayMode(){return this.displayMode}getSize(){return this.sizeClass}applyDisplayMode(e){e.displayMode&&(this.displayMode=e.displayMode,this.root.dataset.display=e.displayMode)}applyContainerDimensions(e){let t=e.containerDimensions;if(!t)return;let n=this.root.style,r=`width`in t?t.width:`maxWidth`in t?t.maxWidth:void 0,i=`height`in t?t.height:`maxHeight`in t?t.maxHeight:void 0;r!==void 0&&(n.setProperty(`--aikit-container-w`,`${r}px`),this.sizeClass=this.deriveSizeClass(r),this.root.dataset.size=this.sizeClass,n.setProperty(`--aikit-content-max-width`,this.deriveMaxWidth(r)),n.setProperty(`--aikit-body-pad-x`,this.derivePadX()),n.setProperty(`--aikit-grid-cols`,this.deriveGridCols()),n.setProperty(`--aikit-card-min`,this.deriveCardMin()),n.setProperty(`--aikit-metric-min`,this.deriveMetricMin())),i!==void 0&&(n.setProperty(`--aikit-container-h`,`${i}px`),n.setProperty(`--aikit-body-pad-y`,this.derivePadY()))}applySafeArea(e){let t=e.safeAreaInsets;if(!t)return;let n=this.root.style;n.setProperty(`--aikit-safe-top`,`${t.top}px`),n.setProperty(`--aikit-safe-right`,`${t.right}px`),n.setProperty(`--aikit-safe-bottom`,`${t.bottom}px`),n.setProperty(`--aikit-safe-left`,`${t.left}px`)}applyPlatform(e){e.platform&&(this.root.dataset.platform=e.platform)}applyDeviceCapabilities(e){let t=e.deviceCapabilities;t&&(t.touch!==void 0&&(this.root.dataset.touch=String(t.touch)),t.hover!==void 0&&(this.root.dataset.hover=String(t.hover)))}deriveSizeClass(e){for(let[t,n]of $C)if(e<t)return n;return`full`}deriveMaxWidth(e){return this.displayMode===`pip`?`100%`:this.displayMode===`fullscreen`?`none`:e<960?`100%`:`900px`}derivePadX(){return this.sizeClass===`compact`?`8px`:`16px`}derivePadY(){return this.sizeClass===`compact`?`8px`:`16px`}deriveGridCols(){switch(this.sizeClass){case`compact`:return`1`;case`comfortable`:return`2`;case`full`:return`3`}}deriveCardMin(){return this.sizeClass===`compact`?`100%`:`250px`}deriveMetricMin(){return this.sizeClass===`compact`?`100px`:`150px`}},tw=`AI Kit Present`;function nw(e){return e.schemaVersion===1}function rw(e){if(!Array.isArray(e)&&typeof e==`object`&&e){let t=e;if(Array.isArray(t.blocks)&&t.blocks.length>0)return t.blocks}return e}function iw(e){if(Array.isArray(e))return e.length===0?[{type:`markdown`,value:`*Empty array*`}]:QC(e[0])?e.filter(QC):typeof e[0]==`object`&&e[0]!==null?[{type:`table`,value:e}]:[{type:`markdown`,value:e.map(e=>`- ${String(e)}`).join(`
1973
+ `)}];if(typeof e==`string`)return[{type:`markdown`,value:e}];if(typeof e==`object`&&e){let t=e;return Array.isArray(t.nodes)&&Array.isArray(t.edges)?[{type:`graph`,value:t}]:Array.isArray(t.metrics)?[{type:`metrics`,value:t.metrics}]:[{type:`json`,value:t}]}return[{type:`text`,value:String(e??``)}]}function aw(e){return{...e,options:e.options?.map(e=>typeof e==`string`?{label:e,value:e}:e)}}function ow(e){if(nw(e)){let t=e.data??e.content??e.blocks;return{schemaVersion:1,title:e.title??tw,description:e.description,template:e.template,data:t,blocks:e.blocks??iw(t),actions:e.actions?.map(aw),colorScheme:e.colorScheme,lang:e.lang,dir:e.dir}}let t=rw(e.content);return{schemaVersion:1,title:e.title??tw,template:e.template,data:t,blocks:iw(t),actions:e.actions?.map(aw)}}var sw=class{templates=new Map;register(e){this.templates.set(e.name,e)}get(e){return this.templates.get(e)}detect(e){let t,n=0;for(let r of this.templates.values()){let i=r.detect(e);i>n&&(n=i,t=r)}return n>0?t:void 0}getAll(){return[...this.templates.values()]}},cw={"--color-background-primary":`--aikit-bg`,"--color-background-secondary":`--aikit-surface`,"--color-background-tertiary":`--aikit-surface2`,"--color-text-primary":`--aikit-text`,"--color-text-secondary":`--aikit-muted`,"--color-border-primary":`--aikit-border`,"--color-ring-primary":`--aikit-accent`,"--color-text-success":`--aikit-success`,"--color-text-danger":`--aikit-error`,"--color-text-warning":`--aikit-warning`,"--color-text-info":`--aikit-info`,"--font-sans":`--aikit-font-sans`,"--font-mono":`--aikit-font-mono`,"--border-radius-md":`--aikit-radius`,"--shadow-sm":`--aikit-shadow`},lw={"--aikit-bg":`--bg`,"--aikit-text":`--fg`,"--aikit-surface":`--surface`,"--aikit-border":`--border`,"--aikit-accent":`--accent`,"--aikit-success":`--success`,"--aikit-warning":`--warning`,"--aikit-error":`--error`,"--aikit-font-sans":`--font-sans`,"--aikit-font-mono":`--font-mono`,"--aikit-radius":`--radius`,"--aikit-shadow":`--shadow`},uw=`aikit-design-token-bridge`,dw={light:{"--bg":`#ffffff`,"--fg":`rgb(26 26 46)`,"--surface":`#f8f9fa`,"--border":`#e2e8f0`,"--accent":`#58a6ff`,"--accent-light":`#79c0ff`,"--success":`#22c55e`,"--warning":`#f59e0b`,"--error":`#ef4444`,"--code-bg":`#1e1e2e`,"--code-fg":`#cdd6f4`,"--radius":`8px`,"--shadow":`0 1px 3px rgba(0,0,0,0.08), 0 1px 2px rgba(0,0,0,0.06)`,"--font-sans":`-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif`,"--font-mono":`'Cascadia Code', 'Fira Code', 'JetBrains Mono', Consolas, monospace`,"--aikit-bg":`#ffffff`,"--aikit-surface":`#f8f9fa`,"--aikit-surface2":`#f8f9fa`,"--aikit-text":`rgb(26 26 46)`,"--aikit-muted":`#94a3b8`,"--aikit-border":`#e2e8f0`,"--aikit-accent":`#58a6ff`,"--aikit-accent-light":`#79c0ff`,"--aikit-success":`#22c55e`,"--aikit-warning":`#f59e0b`,"--aikit-error":`#ef4444`,"--aikit-info":`#58a6ff`,"--aikit-code-bg":`#1e1e2e`,"--aikit-code-fg":`#cdd6f4`,"--aikit-font-sans":`-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif`,"--aikit-font-mono":`'Cascadia Code', 'Fira Code', 'JetBrains Mono', Consolas, monospace`,"--aikit-radius":`8px`,"--aikit-shadow":`0 1px 3px rgba(0,0,0,0.08), 0 1px 2px rgba(0,0,0,0.06)`,"--aikit-hover-bg":`color-mix(in srgb, #58a6ff 10%, transparent)`},dark:{"--bg":`#0d1117`,"--fg":`#e6edf3`,"--surface":`#161b22`,"--border":`#30363d`,"--accent":`#58a6ff`,"--accent-light":`#79c0ff`,"--success":`#22c55e`,"--warning":`#f59e0b`,"--error":`#ef4444`,"--code-bg":`#161b22`,"--code-fg":`#cdd6f4`,"--radius":`8px`,"--shadow":`0 1px 3px rgba(0,0,0,0.3)`,"--font-sans":`-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif`,"--font-mono":`'Cascadia Code', 'Fira Code', 'JetBrains Mono', Consolas, monospace`,"--aikit-bg":`#0d1117`,"--aikit-surface":`#161b22`,"--aikit-surface2":`#161b22`,"--aikit-text":`#e6edf3`,"--aikit-muted":`#94a3b8`,"--aikit-border":`#30363d`,"--aikit-accent":`#58a6ff`,"--aikit-accent-light":`#79c0ff`,"--aikit-success":`#22c55e`,"--aikit-warning":`#f59e0b`,"--aikit-error":`#ef4444`,"--aikit-info":`#58a6ff`,"--aikit-code-bg":`#161b22`,"--aikit-code-fg":`#cdd6f4`,"--aikit-font-sans":`-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif`,"--aikit-font-mono":`'Cascadia Code', 'Fira Code', 'JetBrains Mono', Consolas, monospace`,"--aikit-radius":`8px`,"--aikit-shadow":`0 1px 3px rgba(0,0,0,0.3)`,"--aikit-hover-bg":`color-mix(in srgb, #58a6ff 10%, transparent)`}},fw={"--chart-1":`#79c0ff`,"--chart-2":`#38bdf8`,"--chart-3":`#34d399`,"--chart-4":`#fbbf24`,"--chart-5":`#f87171`,"--chart-6":`#a78bfa`,"--chart-7":`#f472b6`,"--chart-8":`#2dd4bf`,"--chart-9":`#fb923c`,"--chart-10":`#22d3ee`,"--chart-11":`#c084fc`,"--chart-12":`#a3e635`,"--chart-others":`#a8a29e`},pw=`
1974
1974
  :root {
1975
1975
  --dt-bg-primary: var(--aikit-bg, #0d1117);
1976
1976
  --dt-bg-secondary: var(--aikit-surface, #161b22);
@@ -2039,7 +2039,7 @@ container holding the app. Specify either width or maxWidth, and either height o
2039
2039
  [data-theme='light'] {
2040
2040
  color-scheme: light;
2041
2041
  }
2042
- `,pw=class{root;constructor(e){this.root=e??document.documentElement,this.applyFallbackVariables(),this.ensureDesignTokenBridge()}apply(e){e.theme&&cC(e.theme),this.applyFallbackVariables(e.theme),e.styles?.variables&&(lC(e.styles.variables),this.mapTokens(e.styles.variables)),e.styles?.css?.fonts&&this.injectFonts(e.styles.css.fonts)}getTheme(){return sC()}resolveFallbackTheme(e){if(e)return e;let t=this.root.dataset.theme;return t===`light`||t===`dark`?t:window.matchMedia(`(prefers-color-scheme: dark)`).matches?`dark`:`light`}applyFallbackVariables(e){let t=this.resolveFallbackTheme(e),n=this.root.style;for(let[e,r]of Object.entries(uw[t]))n.setProperty(e,r);for(let[e,t]of Object.entries(dw))n.setProperty(e,t);n.colorScheme=t}mapTokens(e){let t=this.root.style;for(let[n,r]of Object.entries(sw)){let i=e[n];if(i){t.setProperty(r,i);let e=cw[r];e&&t.setProperty(e,i)}}this.getTheme()===`dark`?(t.setProperty(`--code-bg`,e[`--color-background-tertiary`]??`#0f0f1a`),t.setProperty(`--code-fg`,`#cdd6f4`)):(t.setProperty(`--code-bg`,`#f0f0f5`),t.setProperty(`--code-fg`,`#1a1a2e`)),t.setProperty(`--aikit-code-bg`,t.getPropertyValue(`--code-bg`)),t.setProperty(`--aikit-code-fg`,t.getPropertyValue(`--code-fg`));let n=e[`--color-ring-primary`];n&&(t.setProperty(`--aikit-accent-light`,n),t.setProperty(`--accent-light`,n),t.setProperty(`--aikit-hover-bg`,`color-mix(in srgb, ${n} 10%, transparent)`))}injectFonts(e){let t=`aikit-host-fonts`;if(document.getElementById(t))return;let n=document.createElement(`style`);n.id=t,n.textContent=e,document.head.appendChild(n)}ensureDesignTokenBridge(){if(document.getElementById(lw))return;let e=document.createElement(`style`);e.id=lw,e.textContent=fw,document.head.appendChild(e)}},mw=`
2042
+ `,mw=class{root;constructor(e){this.root=e??document.documentElement,this.applyFallbackVariables(),this.ensureDesignTokenBridge()}apply(e){e.theme&&cC(e.theme),this.applyFallbackVariables(e.theme),e.styles?.variables&&(lC(e.styles.variables),this.mapTokens(e.styles.variables)),e.styles?.css?.fonts&&this.injectFonts(e.styles.css.fonts)}getTheme(){return sC()}resolveFallbackTheme(e){if(e)return e;let t=this.root.dataset.theme;return t===`light`||t===`dark`?t:window.matchMedia(`(prefers-color-scheme: dark)`).matches?`dark`:`light`}applyFallbackVariables(e){let t=this.resolveFallbackTheme(e),n=this.root.style;for(let[e,r]of Object.entries(dw[t]))n.setProperty(e,r);for(let[e,t]of Object.entries(fw))n.setProperty(e,t);n.colorScheme=t}mapTokens(e){let t=this.root.style;for(let[n,r]of Object.entries(cw)){let i=e[n];if(i){t.setProperty(r,i);let e=lw[r];e&&t.setProperty(e,i)}}this.getTheme()===`dark`?(t.setProperty(`--code-bg`,e[`--color-background-tertiary`]??`#0f0f1a`),t.setProperty(`--code-fg`,`#cdd6f4`)):(t.setProperty(`--code-bg`,`#f0f0f5`),t.setProperty(`--code-fg`,`#1a1a2e`)),t.setProperty(`--aikit-code-bg`,t.getPropertyValue(`--code-bg`)),t.setProperty(`--aikit-code-fg`,t.getPropertyValue(`--code-fg`));let n=e[`--color-ring-primary`];n&&(t.setProperty(`--aikit-accent-light`,n),t.setProperty(`--accent-light`,n),t.setProperty(`--aikit-hover-bg`,`color-mix(in srgb, ${n} 10%, transparent)`))}injectFonts(e){let t=`aikit-host-fonts`;if(document.getElementById(t))return;let n=document.createElement(`style`);n.id=t,n.textContent=e,document.head.appendChild(n)}ensureDesignTokenBridge(){if(document.getElementById(uw))return;let e=document.createElement(`style`);e.id=uw,e.textContent=pw,document.head.appendChild(e)}},hw=`
2043
2043
  .tpl-dashboard { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 14px; }
2044
2044
  .db-card { min-height: 136px; padding: 14px; border: 1px solid var(--aikit-border, #3c3c3c);
2045
2045
  border-left-width: 4px; border-radius: var(--aikit-radius, 10px); background: var(--aikit-surface, #252526);
@@ -2065,7 +2065,7 @@ container holding the app. Specify either width or maxWidth, and either height o
2065
2065
  .db-list-item { display: flex; align-items: center; justify-content: space-between; gap: 12px; color: var(--aikit-text, #e5e7eb);
2066
2066
  font: 500 13px var(--aikit-font-sans, Inter, sans-serif); }
2067
2067
  .db-list-item span:last-child { color: var(--aikit-muted, #9ca3af); font-family: var(--aikit-font-mono, Consolas, monospace); }
2068
- `,hw={name:`dashboard`,label:`Dashboard`,detect(e){if(typeof e!=`object`||!e||Array.isArray(e))return 0;let t=e,n=Array.isArray(t.metrics)?t.metrics[0]:void 0;return n&&typeof n.label==`string`&&`value`in n?.85:0},render(e,t,n){XC(`tpl-dashboard`,mw);let r=t,i=Q(`div`,`block tpl-dashboard`);for(let e of r.metrics){let t=Q(`article`,`db-card status-${e.status??`info`}`),n=Q(`div`,`db-header`);if(n.appendChild(Q(`div`,`db-label`,e.label)),e.trend){let t=e.trend.direction===`up`?`▲`:e.trend.direction===`down`?`▼`:`—`;n.appendChild(Q(`div`,`db-trend ${e.trend.direction}`,`${t} ${e.trend.value}`))}if(t.appendChild(n),t.appendChild(Q(`div`,`db-value`,ZC(e.value))),e.type===`progress`){let n=Q(`div`,`db-progress-track`),r=Q(`div`,`db-progress-fill`);r.style.width=`${Math.max(0,Math.min(100,e.progress??0))}%`,n.appendChild(r),t.appendChild(n),t.appendChild(Q(`div`,`db-progress-meta`,`${Math.max(0,Math.min(100,e.progress??0))}% complete`))}if(e.type===`list`&&e.items?.length){let n=Q(`ul`,`db-list`);for(let t of e.items){let e=Q(`li`,`db-list-item`);e.appendChild(Q(`span`,``,t.label)),e.appendChild(Q(`span`,``,t.value)),n.appendChild(e)}t.appendChild(n)}i.appendChild(t)}e.appendChild(i)},styles(){return mw}},gw=`
2068
+ `,gw={name:`dashboard`,label:`Dashboard`,detect(e){if(typeof e!=`object`||!e||Array.isArray(e))return 0;let t=e,n=Array.isArray(t.metrics)?t.metrics[0]:void 0;return n&&typeof n.label==`string`&&`value`in n?.85:0},render(e,t,n){XC(`tpl-dashboard`,hw);let r=t,i=Q(`div`,`block tpl-dashboard`);for(let e of r.metrics){let t=Q(`article`,`db-card status-${e.status??`info`}`),n=Q(`div`,`db-header`);if(n.appendChild(Q(`div`,`db-label`,e.label)),e.trend){let t=e.trend.direction===`up`?`▲`:e.trend.direction===`down`?`▼`:`—`;n.appendChild(Q(`div`,`db-trend ${e.trend.direction}`,`${t} ${e.trend.value}`))}if(t.appendChild(n),t.appendChild(Q(`div`,`db-value`,ZC(e.value))),e.type===`progress`){let n=Q(`div`,`db-progress-track`),r=Q(`div`,`db-progress-fill`);r.style.width=`${Math.max(0,Math.min(100,e.progress??0))}%`,n.appendChild(r),t.appendChild(n),t.appendChild(Q(`div`,`db-progress-meta`,`${Math.max(0,Math.min(100,e.progress??0))}% complete`))}if(e.type===`list`&&e.items?.length){let n=Q(`ul`,`db-list`);for(let t of e.items){let e=Q(`li`,`db-list-item`);e.appendChild(Q(`span`,``,t.label)),e.appendChild(Q(`span`,``,t.value)),n.appendChild(e)}t.appendChild(n)}i.appendChild(t)}e.appendChild(i)},styles(){return hw}},_w=`
2069
2069
  .fg-breadcrumb { display: flex; align-items: center; gap: 4px; padding: 8px 0; flex-wrap: wrap; }
2070
2070
  .fg-crumb { background: var(--aikit-surface, #252526); border: 1px solid var(--aikit-border, #3c3c3c);
2071
2071
  color: var(--aikit-text, #ccc); padding: 3px 10px; border-radius: 4px; cursor: pointer; font-size: 12px; }
@@ -2080,7 +2080,7 @@ container holding the app. Specify either width or maxWidth, and either height o
2080
2080
  text-overflow: ellipsis; font-weight: 500; }
2081
2081
  .fg-info { font-size: 12px; color: var(--aikit-muted, #858585); padding: 8px 0;
2082
2082
  border-top: 1px solid var(--aikit-border, #3c3c3c); margin-top: 8px; }
2083
- `;function _w(e){return{name:String(e.name??``),total:typeof e.total==`number`?e.total:typeof e.value==`number`?e.value:0,self:typeof e.self==`number`?e.self:void 0,children:Array.isArray(e.children)?e.children.map(e=>_w(e)):void 0}}var vw={name:`flame-graph`,label:`Flame Graph`,detect(e){if(typeof e!=`object`||!e||Array.isArray(e))return 0;let t=e.profile;return t&&typeof t==`object`&&t.children?.9:0},render(e,t,n){let r=t,i=Q(`div`,`block tpl-flame-graph`),a=_w(r.profile),o=a,s=[a],c=Q(`div`,`fg-breadcrumb`);i.appendChild(c);let l=Q(`div`,`fg-canvas`);i.appendChild(l);let u=Q(`div`,`fg-info`);i.appendChild(u);function d(){c.innerHTML=``;for(let e=0;e<s.length;e++){let t=s[e],n=document.createElement(`button`);n.className=`fg-crumb`,n.textContent=t.name,n.addEventListener(`click`,()=>{s.splice(e+1),o=t,d()}),c.appendChild(n),e<s.length-1&&c.appendChild(Q(`span`,`fg-sep`,`›`))}l.innerHTML=``,f(l,o,0,o.total),u.textContent=`${o.name} — total: ${o.total}${o.self==null?``:`, self: ${o.self}`}`}function f(e,t,r,i){let a=Q(`div`,`fg-row`);a.style.paddingLeft=`${r*2}px`;let c=Q(`div`,`fg-bar`),l=Math.max(2,t.total/i*100);c.style.width=`${l}%`,c.style.background=ee(r),c.title=`${t.name}: ${t.total}${t.self==null?``:` (self: ${t.self})`}`;let te=Q(`span`,`fg-bar-label`,`${t.name} (${t.total})`);if(c.appendChild(te),t.children?.length&&(c.style.cursor=`pointer`,c.addEventListener(`click`,()=>{o=t,s.push(t),d(),n.emitAction({type:`button`,id:`zoom`,label:`Zoom`},JSON.stringify({name:t.name,total:t.total}))})),c.addEventListener(`mouseenter`,()=>{u.textContent=`${t.name} — total: ${t.total}${t.self==null?``:`, self: ${t.self}`}`}),a.appendChild(c),e.appendChild(a),t.children)for(let n of t.children)f(e,n,r+1,i)}function ee(e){let t=getComputedStyle(document.documentElement),n=[t.getPropertyValue(`--chart-5`).trim()||`#e24d28`,t.getPropertyValue(`--chart-9`).trim()||`#e8602a`,t.getPropertyValue(`--chart-4`).trim()||`#edad2a`,t.getPropertyValue(`--chart-1`).trim()||`#f5c842`,t.getPropertyValue(`--chart-3`).trim()||`#fce94f`,t.getPropertyValue(`--chart-6`).trim()||`#c4a000`,t.getPropertyValue(`--chart-7`).trim()||`#e07028`,t.getPropertyValue(`--chart-8`).trim()||`#d45500`];return n[e%n.length]}d(),XC(`tpl-flame-graph`,gw),e.appendChild(i)},styles(){return gw}},yw=`
2083
+ `;function vw(e){return{name:String(e.name??``),total:typeof e.total==`number`?e.total:typeof e.value==`number`?e.value:0,self:typeof e.self==`number`?e.self:void 0,children:Array.isArray(e.children)?e.children.map(e=>vw(e)):void 0}}var yw={name:`flame-graph`,label:`Flame Graph`,detect(e){if(typeof e!=`object`||!e||Array.isArray(e))return 0;let t=e.profile;return t&&typeof t==`object`&&t.children?.9:0},render(e,t,n){let r=t,i=Q(`div`,`block tpl-flame-graph`),a=vw(r.profile),o=a,s=[a],c=Q(`div`,`fg-breadcrumb`);i.appendChild(c);let l=Q(`div`,`fg-canvas`);i.appendChild(l);let u=Q(`div`,`fg-info`);i.appendChild(u);function d(){c.innerHTML=``;for(let e=0;e<s.length;e++){let t=s[e],n=document.createElement(`button`);n.className=`fg-crumb`,n.textContent=t.name,n.addEventListener(`click`,()=>{s.splice(e+1),o=t,d()}),c.appendChild(n),e<s.length-1&&c.appendChild(Q(`span`,`fg-sep`,`›`))}l.innerHTML=``,f(l,o,0,o.total),u.textContent=`${o.name} — total: ${o.total}${o.self==null?``:`, self: ${o.self}`}`}function f(e,t,r,i){let a=Q(`div`,`fg-row`);a.style.paddingLeft=`${r*2}px`;let c=Q(`div`,`fg-bar`),l=Math.max(2,t.total/i*100);c.style.width=`${l}%`,c.style.background=ee(r),c.title=`${t.name}: ${t.total}${t.self==null?``:` (self: ${t.self})`}`;let te=Q(`span`,`fg-bar-label`,`${t.name} (${t.total})`);if(c.appendChild(te),t.children?.length&&(c.style.cursor=`pointer`,c.addEventListener(`click`,()=>{o=t,s.push(t),d(),n.emitAction({type:`button`,id:`zoom`,label:`Zoom`},JSON.stringify({name:t.name,total:t.total}))})),c.addEventListener(`mouseenter`,()=>{u.textContent=`${t.name} — total: ${t.total}${t.self==null?``:`, self: ${t.self}`}`}),a.appendChild(c),e.appendChild(a),t.children)for(let n of t.children)f(e,n,r+1,i)}function ee(e){let t=getComputedStyle(document.documentElement),n=[t.getPropertyValue(`--chart-5`).trim()||`#e24d28`,t.getPropertyValue(`--chart-9`).trim()||`#e8602a`,t.getPropertyValue(`--chart-4`).trim()||`#edad2a`,t.getPropertyValue(`--chart-1`).trim()||`#f5c842`,t.getPropertyValue(`--chart-3`).trim()||`#fce94f`,t.getPropertyValue(`--chart-6`).trim()||`#c4a000`,t.getPropertyValue(`--chart-7`).trim()||`#e07028`,t.getPropertyValue(`--chart-8`).trim()||`#d45500`];return n[e%n.length]}d(),XC(`tpl-flame-graph`,_w),e.appendChild(i)},styles(){return _w}},bw=`
2084
2084
  .tpl-kanban { overflow-x: auto; }
2085
2085
  .kbn-board { display: flex; gap: 14px; align-items: flex-start; min-width: min-content; padding-bottom: 4px; }
2086
2086
  .kbn-column { width: 280px; flex: 0 0 280px; border: 1px solid var(--aikit-border, #3c3c3c); border-radius: var(--aikit-radius, 10px);
@@ -2106,7 +2106,7 @@ container holding the app. Specify either width or maxWidth, and either height o
2106
2106
  .kbn-tags { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 10px; }
2107
2107
  .kbn-tag { padding: 2px 8px; border-radius: 999px; background: var(--aikit-surface, #252526); color: var(--aikit-muted, #9ca3af);
2108
2108
  font: 500 11px var(--aikit-font-sans, Inter, sans-serif); }
2109
- `,bw={name:`kanban`,label:`Kanban`,detect(e){if(typeof e!=`object`||!e||Array.isArray(e))return 0;let t=e,n=Array.isArray(t.cards)?t.cards[0]:void 0;return Array.isArray(t.columns)&&Array.isArray(t.cards)&&typeof n?.column==`string`?.85:0},render(e,t,n){XC(`tpl-kanban`,yw);let r=t,i=r.cards.map(e=>({...e,tags:e.tags?[...e.tags]:void 0})),a=new Set,o=``,s=Q(`div`,`block tpl-kanban`),c=Q(`div`,`kbn-board`);s.appendChild(c);let l=()=>{c.innerHTML=``;for(let e of r.columns){let t=Q(`section`,`kbn-column`),r=Q(`div`,`kbn-column-header`),s=Q(`div`,`kbn-column-title`),u=Q(`span`,`kbn-column-swatch`);e.color&&(u.style.background=e.color),s.appendChild(u),s.appendChild(Q(`span`,``,e.label)),r.appendChild(s);let d=i.filter(t=>t.column===e.id);r.appendChild(Q(`span`,`kbn-column-count`,String(d.length))),t.appendChild(r);let f=Q(`div`,`kbn-cards`);t.addEventListener(`dragover`,e=>{e.preventDefault(),t.classList.add(`drop-target`)}),t.addEventListener(`dragleave`,()=>{t.classList.remove(`drop-target`)}),t.addEventListener(`drop`,r=>{if(r.preventDefault(),t.classList.remove(`drop-target`),!o)return;let a=i.find(e=>e.id===o);!a||a.column===e.id||(a.column=e.id,l(),n.emitAction({type:`button`,id:`move-card`,label:`Move Card`},JSON.stringify({id:a.id,column:e.id})))});for(let e of d){let t=Q(`article`,`kbn-card priority-${e.priority??`low`}`);if(t.draggable=!0,t.appendChild(Q(`div`,`kbn-card-title`,e.title)),e.description){let n=Q(`div`,`kbn-card-description`,e.description);n.hidden=!a.has(e.id),t.appendChild(n),t.addEventListener(`click`,()=>{a.has(e.id)?a.delete(e.id):a.add(e.id),n.hidden=!a.has(e.id)})}else t.addEventListener(`click`,()=>{a.has(e.id)?a.delete(e.id):a.add(e.id)});if(e.tags?.length){let n=Q(`div`,`kbn-tags`);for(let t of e.tags)n.appendChild(Q(`span`,`kbn-tag`,t));t.appendChild(n)}t.addEventListener(`dragstart`,()=>{o=e.id,t.classList.add(`dragging`)}),t.addEventListener(`dragend`,()=>{t.classList.remove(`dragging`),o=``}),f.appendChild(t)}t.appendChild(f),c.appendChild(t)}};l(),e.appendChild(s)},styles(){return yw}},xw=`
2109
+ `,xw={name:`kanban`,label:`Kanban`,detect(e){if(typeof e!=`object`||!e||Array.isArray(e))return 0;let t=e,n=Array.isArray(t.cards)?t.cards[0]:void 0;return Array.isArray(t.columns)&&Array.isArray(t.cards)&&typeof n?.column==`string`?.85:0},render(e,t,n){XC(`tpl-kanban`,bw);let r=t,i=r.cards.map(e=>({...e,tags:e.tags?[...e.tags]:void 0})),a=new Set,o=``,s=Q(`div`,`block tpl-kanban`),c=Q(`div`,`kbn-board`);s.appendChild(c);let l=()=>{c.innerHTML=``;for(let e of r.columns){let t=Q(`section`,`kbn-column`),r=Q(`div`,`kbn-column-header`),s=Q(`div`,`kbn-column-title`),u=Q(`span`,`kbn-column-swatch`);e.color&&(u.style.background=e.color),s.appendChild(u),s.appendChild(Q(`span`,``,e.label)),r.appendChild(s);let d=i.filter(t=>t.column===e.id);r.appendChild(Q(`span`,`kbn-column-count`,String(d.length))),t.appendChild(r);let f=Q(`div`,`kbn-cards`);t.addEventListener(`dragover`,e=>{e.preventDefault(),t.classList.add(`drop-target`)}),t.addEventListener(`dragleave`,()=>{t.classList.remove(`drop-target`)}),t.addEventListener(`drop`,r=>{if(r.preventDefault(),t.classList.remove(`drop-target`),!o)return;let a=i.find(e=>e.id===o);!a||a.column===e.id||(a.column=e.id,l(),n.emitAction({type:`button`,id:`move-card`,label:`Move Card`},JSON.stringify({id:a.id,column:e.id})))});for(let e of d){let t=Q(`article`,`kbn-card priority-${e.priority??`low`}`);if(t.draggable=!0,t.appendChild(Q(`div`,`kbn-card-title`,e.title)),e.description){let n=Q(`div`,`kbn-card-description`,e.description);n.hidden=!a.has(e.id),t.appendChild(n),t.addEventListener(`click`,()=>{a.has(e.id)?a.delete(e.id):a.add(e.id),n.hidden=!a.has(e.id)})}else t.addEventListener(`click`,()=>{a.has(e.id)?a.delete(e.id):a.add(e.id)});if(e.tags?.length){let n=Q(`div`,`kbn-tags`);for(let t of e.tags)n.appendChild(Q(`span`,`kbn-tag`,t));t.appendChild(n)}t.addEventListener(`dragstart`,()=>{o=e.id,t.classList.add(`dragging`)}),t.addEventListener(`dragend`,()=>{t.classList.remove(`dragging`),o=``}),f.appendChild(t)}t.appendChild(f),c.appendChild(t)}};l(),e.appendChild(s)},styles(){return bw}},Sw=`
2110
2110
  .sort-list { list-style: none; padding: 0; margin: 0; }
2111
2111
  .sort-item { display: flex; align-items: center; gap: 10px; padding: 10px 14px; margin: 4px 0;
2112
2112
  background: var(--aikit-surface, #252526); border: 1px solid var(--aikit-border, #3c3c3c);
@@ -2117,7 +2117,7 @@ container holding the app. Specify either width or maxWidth, and either height o
2117
2117
  .drag-handle { font-size: 18px; color: var(--aikit-muted, #858585); cursor: grab; user-select: none; }
2118
2118
  .sort-label { flex: 1; color: var(--aikit-text, #ccc); }
2119
2119
  .sort-pos { font-size: 12px; color: var(--aikit-muted, #858585); font-variant-numeric: tabular-nums; }
2120
- `,Sw={name:`list-sort`,label:`Sortable List`,detect(e){if(typeof e!=`object`||!e||Array.isArray(e))return 0;let t=e;return t.items&&Array.isArray(t.items)&&!t.categories?.8:0},render(e,t,n){let r=t,i=Q(`div`,`block tpl-list-sort`);XC(`tpl-list-sort`,xw);function a(e){i.innerHTML=``;let t=Q(`ul`,`sort-list`),r=-1;for(let i=0;i<e.length;i++){let o=e[i],s=document.createElement(`li`);s.className=`sort-item`,s.draggable=!0,s.dataset.idx=String(i);let c=Q(`span`,`drag-handle`,`⠿`),l=Q(`span`,`sort-label`,o.label),u=Q(`span`,`sort-pos`,`#${i+1}`);s.appendChild(c),s.appendChild(l),s.appendChild(u),s.addEventListener(`dragstart`,()=>{r=Number(s.dataset.idx),s.classList.add(`dragging`)}),s.addEventListener(`dragend`,()=>{s.classList.remove(`dragging`)}),s.addEventListener(`dragenter`,e=>{e.preventDefault()}),s.addEventListener(`dragover`,e=>{e.preventDefault(),s.classList.add(`drag-over`)}),s.addEventListener(`dragleave`,()=>{s.classList.remove(`drag-over`)}),s.addEventListener(`drop`,t=>{t.preventDefault(),s.classList.remove(`drag-over`);let i=Number(s.dataset.idx);if(r>=0&&r!==i){let t=[...e],[o]=t.splice(r,1);t.splice(i,0,o),a(t),n.emitAction({type:`button`,id:`reorder`,label:`Reorder`},JSON.stringify(t.map(e=>e.id)))}}),t.appendChild(s)}i.appendChild(t)}a([...r.items??[]]),e.appendChild(i)},styles(){return xw}},Cw=document.getElementById(`app`);if(!Cw)throw Error(`Missing #app element`);var $=Cw,ww=KC(),Tw=ww?void 0:new uC({name:`AI Kit Present`,version:`1.0.0`}),Ew=new ow;Ew.register(Sw),Ew.register(vw),Ew.register(hw),Ew.register(bw);var Dw=VC(Tw),Ow={app:Tw,data:qC(Tw),emitAction:Dw},kw=new pw,Aw=new ew,jw=Tw?new JC(Tw):void 0,Mw=null;function Nw(){Mw?.(),Mw=null,zw?.destroy&&zw.destroy(),zw=null}function Pw(e,t){let n=new Map,r=e=>{n.set(o(e.id),e)};for(let e of t??[])r(e);for(let t of e)if(!(t.type!==`actions`||!Array.isArray(t.value)))for(let e of t.value)e&&typeof e==`object`&&`id`in e&&r(e);return n}function Fw(e,t,n){let r=Pw(t,n);Mw=BC(e,t,(e,t)=>{Dw(r.get(e)??{type:t===void 0?`button`:`select`,id:e,label:e},t)})}function Iw(e,t,n){let r=document.documentElement.dir,i=WC(e,t,{colorScheme:kw.getTheme(),lang:document.documentElement.lang||void 0,dir:r===`ltr`||r===`rtl`||r===`auto`?r:void 0});return i?{blocks:i.blocks,actions:n.actions}:null}var Lw;function Rw(e){Nw(),$.innerHTML=``;let t=aw(e);if(e.title){let t=Q(`div`,`header`);t.appendChild(Q(`h1`,``,e.title)),t.appendChild(Q(`span`,`badge streaming`,`⟳`)),$.appendChild(t)}let n=Q(`div`,`content`);Fw(n,t.blocks??[]),$.appendChild(n)}var zw=null;function Bw(e,t){$.innerHTML=``;let n=Q(`div`,`error-panel`);n.appendChild(Q(`h3`,``,`⚠ ${e}`)),n.appendChild(Q(`pre`,``,t instanceof Error?t.message:String(t))),$.appendChild(n)}function Vw(e){Nw(),$.innerHTML=``;let t=aw(e),n=t.data;if(!n){$.innerHTML=`<p class="no-data">No content data received.</p>`;return}if(e.title){let t=Q(`div`,`header`);t.appendChild(Q(`h1`,``,e.title)),t.appendChild(Q(`span`,`badge`,`AI KIT`)),$.appendChild(t)}let r=t.template?Ew.get(t.template):Ew.detect(n),i=Q(`div`,`content`);if(r)zw=r,r.render(i,n,Ow);else if(t.template){let r=Iw(t.template,n,e);r?Fw(i,r.blocks,r.actions):Fw(i,t.blocks??[],e.actions)}else Fw(i,t.blocks??[],e.actions);if($.appendChild(i),e.actions?.length){let t=Q(`div`,`actions-shell`),n=BC(t,[{type:`actions`,value:e.actions}],(t,n)=>{Dw(e.actions?.find(e=>o(e.id)===t)??{type:n===void 0?`button`:`select`,id:t,label:t},n)}),r=Mw;Mw=()=>{r?.(),n()},$.appendChild(t)}let a=Q(`div`,`footer`);a.innerHTML=`<span class="footer-brand">Powered by <strong>AI Kit</strong></span>`,$.appendChild(a)}Tw?(Tw.connect().then(()=>{let e=Tw.getHostContext();e&&(kw.apply(e),Aw.apply(e),jw?.apply(e))}),Tw.onhostcontextchanged=e=>{kw.apply(e),Aw.apply(e),jw?.apply(e),zw?.onThemeChange&&zw.onThemeChange(kw.getTheme())},Tw.ontoolinputpartial=e=>{let t=e.arguments;t&&($.dataset.streaming=`true`,clearTimeout(Lw),Lw=setTimeout(()=>{try{let e=t.content;if(!e)return;Rw({title:t.title,template:t.template,content:e})}catch{}},80))},Tw.ontoolinput=()=>{clearTimeout(Lw),delete $.dataset.streaming},Tw.ontoolresult=e=>{if(clearTimeout(Lw),delete $.dataset.streaming,e.structuredContent)try{Vw(e.structuredContent);return}catch(e){Bw(`Render error`,e);return}let t=e.content?.find(e=>e.type===`text`)?.text;if(!t){$.innerHTML=`<p>No data received.</p>`;return}try{Vw(JSON.parse(t))}catch{Vw({content:t})}}):ww&&(document.documentElement.dataset.theme=`dark`,Vw(ww));</script>
2120
+ `,Cw={name:`list-sort`,label:`Sortable List`,detect(e){if(typeof e!=`object`||!e||Array.isArray(e))return 0;let t=e;return t.items&&Array.isArray(t.items)&&!t.categories?.8:0},render(e,t,n){let r=t,i=Q(`div`,`block tpl-list-sort`);XC(`tpl-list-sort`,Sw);function a(e){i.innerHTML=``;let t=Q(`ul`,`sort-list`),r=-1;for(let i=0;i<e.length;i++){let o=e[i],s=document.createElement(`li`);s.className=`sort-item`,s.draggable=!0,s.dataset.idx=String(i);let c=Q(`span`,`drag-handle`,`⠿`),l=Q(`span`,`sort-label`,o.label),u=Q(`span`,`sort-pos`,`#${i+1}`);s.appendChild(c),s.appendChild(l),s.appendChild(u),s.addEventListener(`dragstart`,()=>{r=Number(s.dataset.idx),s.classList.add(`dragging`)}),s.addEventListener(`dragend`,()=>{s.classList.remove(`dragging`)}),s.addEventListener(`dragenter`,e=>{e.preventDefault()}),s.addEventListener(`dragover`,e=>{e.preventDefault(),s.classList.add(`drag-over`)}),s.addEventListener(`dragleave`,()=>{s.classList.remove(`drag-over`)}),s.addEventListener(`drop`,t=>{t.preventDefault(),s.classList.remove(`drag-over`);let i=Number(s.dataset.idx);if(r>=0&&r!==i){let t=[...e],[o]=t.splice(r,1);t.splice(i,0,o),a(t),n.emitAction({type:`button`,id:`reorder`,label:`Reorder`},JSON.stringify(t.map(e=>e.id)))}}),t.appendChild(s)}i.appendChild(t)}a([...r.items??[]]),e.appendChild(i)},styles(){return Sw}},ww=document.getElementById(`app`);if(!ww)throw Error(`Missing #app element`);var $=ww,Tw=KC(),Ew=Tw?void 0:new uC({name:`AI Kit Present`,version:`1.0.0`}),Dw=new sw;Dw.register(Cw),Dw.register(yw),Dw.register(gw),Dw.register(xw);var Ow=VC(Ew),kw={app:Ew,data:qC(Ew),emitAction:Ow},Aw=new mw,jw=new ew,Mw=Ew?new JC(Ew):void 0,Nw=null;function Pw(){Nw?.(),Nw=null,Bw?.destroy&&Bw.destroy(),Bw=null}function Fw(e,t){let n=new Map,r=e=>{n.set(o(e.id),e)};for(let e of t??[])r(e);for(let t of e)if(!(t.type!==`actions`||!Array.isArray(t.value)))for(let e of t.value)e&&typeof e==`object`&&`id`in e&&r(e);return n}function Iw(e,t,n){let r=Fw(t,n);Nw=BC(e,t,(e,t)=>{Ow(r.get(e)??{type:t===void 0?`button`:`select`,id:e,label:e},t)})}function Lw(e,t,n){let r=document.documentElement.dir,i=WC(e,t,{colorScheme:Aw.getTheme(),lang:document.documentElement.lang||void 0,dir:r===`ltr`||r===`rtl`||r===`auto`?r:void 0});return i?{blocks:i.blocks,actions:n.actions}:null}var Rw;function zw(e){Pw(),$.innerHTML=``;let t=ow(e);if(e.title){let t=Q(`div`,`header`);t.appendChild(Q(`h1`,``,e.title)),t.appendChild(Q(`span`,`badge streaming`,`⟳`)),$.appendChild(t)}let n=Q(`div`,`content`);Iw(n,t.blocks??[]),$.appendChild(n)}var Bw=null;function Vw(e,t){$.innerHTML=``;let n=Q(`div`,`error-panel`);n.appendChild(Q(`h3`,``,`⚠ ${e}`)),n.appendChild(Q(`pre`,``,t instanceof Error?t.message:String(t))),$.appendChild(n)}function Hw(e){Pw(),$.innerHTML=``;let t=ow(e),n=t.data;if(n==null){$.innerHTML=`<p class="no-data">No content data received.</p>`;return}if(e.title){let t=Q(`div`,`header`);t.appendChild(Q(`h1`,``,e.title)),t.appendChild(Q(`span`,`badge`,`AI KIT`)),$.appendChild(t)}let r=t.template?Dw.get(t.template):Dw.detect(n),i=Q(`div`,`content`);if(r)Bw=r,r.render(i,n,kw);else if(t.template){let r=Lw(t.template,n,e);r?Iw(i,r.blocks,r.actions):Iw(i,t.blocks??[],e.actions)}else Iw(i,t.blocks??[],e.actions);if($.appendChild(i),e.actions?.length){let t=Q(`div`,`actions-shell`),n=BC(t,[{type:`actions`,value:e.actions}],(t,n)=>{Ow(e.actions?.find(e=>o(e.id)===t)??{type:n===void 0?`button`:`select`,id:t,label:t},n)}),r=Nw;Nw=()=>{r?.(),n()},$.appendChild(t)}let a=Q(`div`,`footer`);a.innerHTML=`<span class="footer-brand">Powered by <strong>AI Kit</strong></span>`,$.appendChild(a)}Ew?(Ew.connect().then(()=>{let e=Ew.getHostContext();e&&(Aw.apply(e),jw.apply(e),Mw?.apply(e))}),Ew.onhostcontextchanged=e=>{Aw.apply(e),jw.apply(e),Mw?.apply(e),Bw?.onThemeChange&&Bw.onThemeChange(Aw.getTheme())},Ew.ontoolinputpartial=e=>{let t=e.arguments;t&&($.dataset.streaming=`true`,clearTimeout(Rw),Rw=setTimeout(()=>{try{let e=t.content??t.data??t.blocks;if(e==null)return;zw({schemaVersion:t.schemaVersion===1?1:void 0,title:t.title,template:t.template,content:e,data:t.data,blocks:Array.isArray(t.blocks)?t.blocks:void 0})}catch{}},80))},Ew.ontoolinput=()=>{clearTimeout(Rw),delete $.dataset.streaming},Ew.ontoolresult=e=>{if(clearTimeout(Rw),delete $.dataset.streaming,e.structuredContent)try{Hw(e.structuredContent);return}catch(e){Vw(`Render error`,e);return}let t=e.content?.find(e=>e.type===`text`)?.text;if(!t){$.innerHTML=`<p>No data received.</p>`;return}try{Hw(JSON.parse(t))}catch{Hw({content:t})}}):Tw&&(document.documentElement.dataset.theme=`dark`,Hw(Tw));</script>
2121
2121
  </head>
2122
2122
  <body>
2123
2123
  <div id="app">
@@ -5,4 +5,4 @@ import{t as e}from"./rolldown-runtime-yuFVEuWy.js";import{createHash as t,random
5
5
  `).length,fileHash:this.hash(e.content),indexedAt:t,origin:`curated`,tags:e.frontmatter.tags,category:e.frontmatter.category,version:e.frontmatter.version}});try{return await this.store.upsert(i,r),e.length}catch(t){I.error(`Failed to upsert curated batch`,{batchSize:e.length,...p(t)});for(let t of e)n.push(`${t.relativePath}: upsert failed`);return 0}}catch(r){if(e.length===1)return I.error(`Failed to embed curated item`,{relativePath:e[0].relativePath,...p(r)}),n.push(`${e[0].relativePath}: reindex failed`),0;I.warn(`Curated embed batch failed, retrying with smaller chunks`,{batchSize:e.length,...p(r)});let i=Math.ceil(e.length/2),a=e.slice(0,i),o=e.slice(i);return await this.embedAndUpsertBatch(a,t,n)+await this.embedAndUpsertBatch(o,t,n)}}gitCommitKnowledge(e,t,n){try{if(!h(this.curatedDir))return;let r=this.knowledgeRefForPath(e);if(!r)return;g(r,`entry.md`,t,n,this.curatedDir)}catch{}}gitDeleteKnowledgeRef(e){try{if(!h(this.curatedDir))return;let t=this.knowledgeRefForPath(e);if(!t)return;_([`update-ref`,`-d`,t],this.curatedDir)}catch{}}knowledgeRefForPath(e){let t=e.replace(/\.md$/,``).split(`/`).map(e=>v(e)).join(`/`);return t.split(`/`).every(e=>m.test(e))?`${F}/${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(`
6
6
  `).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 indexCuratedFileBestEffort(e,t,n,r){if(d.instance().isDegraded(`embedder`)){I.debug(`Skipping vector indexing — embedder degraded`,{relativePath:e,operation:r,subsystem:`embedder`});return}try{await this.indexCuratedFile(e,t,n)}catch(t){I.warn(`Curated file persisted but vector indexing deferred`,{relativePath:e,operation:r,...p(t)})}}async discoverCategories(){return this.adapter.listDirectories()}guardPath(e){let t=e.replace(/^\.ai\/curated\//,``);if(t.endsWith(`.md`)||(t+=`.md`),t.includes(`..`)||a(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`)>P)throw Error(`Content exceeds maximum size of ${P/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(e){return t(`sha256`).update(e).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(`
7
7
  `)}\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(`
8
- `),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 R(){try{let e=s(i(c(import.meta.url)),`..`,`..`,`..`,`package.json`);return JSON.parse(r(e,`utf-8`)).version??`0.0.0`}catch{return`0.0.0`}}const z=f(`server`),B=/^https?:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/i;function V({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 H({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 U(e){return e.startsWith(`file://`)?c(e):e}function W(e){let t=s(e);return process.platform===`win32`?t.toLowerCase():t}function G(e){let t=new Map;for(let n of e){let e=U(n.uri);t.set(W(e),e)}return[...t.values()].sort((e,t)=>W(e).localeCompare(W(t)))}function K({config:e,roots:t}){let n=G(t);if(n.length===0)return null;let r=e.sources?.[0]?.path;if(r){let e=W(r),t=n.find(t=>W(t)===e);if(t)return t}return n[0]}function q({config:e,log:t,reconfigureForWorkspace:n,roots:r}){let i=G(r);if(i.length===0)return!1;let a=K({config:e,roots:i.map(e=>({uri:e}))});if(!a)return!1;let o=e.sources?.[0]?.path,s=o&&W(o)===W(a)?`configured-source`:`stable-sorted-root`;return t.debug(`MCP roots resolved`,{rootPath:a,rootCount:i.length,selectedBy:s}),n(e,a),e.allRoots=i,!0}async function J({config:e,indexMode:t,log:n,rootsChangedNotificationSchema:r,reconfigureForWorkspace:i,runInitialIndex:a,server:o,startInit:s,timeoutMs:c=5e3,getCwd:l=()=>process.cwd()}){let u=!1,d=!1,f,m=o.server,h=e=>{let t=p(e),n=`${String(e)} ${String(t.message??``)}`.toLowerCase();return n.includes(`method not found`)||n.includes(`not supported`)||n.includes(`unsupported`)||n.includes(`unknown method`)||n.includes(`roots/list`)},g=()=>{u||(u=!0,s())},_=()=>{d||t!==`auto`||(d=!0,(async()=>{try{await a()}catch(e){n.error(`Initial index failed`,p(e))}})())},v=t=>t.length===0||(f&&=(clearTimeout(f),void 0),!q({config:e,log:n,reconfigureForWorkspace:i,roots:t}))?!1:(g(),_(),!0);try{if(v((await m.listRoots()).roots))return;n.debug(`No MCP roots yet; waiting for roots/list_changed notification`)}catch(e){if(h(e)){n.warn(`MCP roots/list not supported by client; using cwd fallback`,{cwd:l(),...p(e)}),g(),_();return}n.warn(`MCP roots/list failed during bootstrap; waiting for roots/list_changed notification`,{cwd:l(),...p(e)})}m.setNotificationHandler(r,async()=>{try{v((await m.listRoots()).roots)}catch(e){n.warn(`roots/list retry failed after notification`,p(e))}}),f=setTimeout(()=>{let t=l();n.debug(`Timed out waiting for MCP roots/list_changed; falling back to cwd workspace`,{cwd:t}),q({config:e,log:n,reconfigureForWorkspace:i,roots:[{uri:t}]})&&(g(),_())},c)}function Y(){return process.env.AIKIT_TRANSPORT?process.env.AIKIT_TRANSPORT:process.stdin.isTTY?`http`:`stdio`}function X(){let e=process.argv[1];if(!e)return!1;try{return import.meta.url===l(e).href}catch{return!1}}function Z(e){let t=e.headers[`mcp-session-id`];return Array.isArray(t)?t[0]:t}function Q(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 $(){return X()?u({allowPositionals:!0,options:{transport:{type:`string`,default:Y()},port:{type:`string`,default:process.env.AIKIT_PORT??`3210`}}}).values:{transport:Y(),port:process.env.AIKIT_PORT??`3210`}}async function ee(){let e=R(),t=$();process.on(`unhandledRejection`,e=>{z.error(`Unhandled rejection`,p(e))}),process.on(`uncaughtException`,e=>{z.error(`Uncaught exception — exiting`,p(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-DWaEE6XW.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-CJFYv4Ye.js`).then(e=>e.o),{CuratedKnowledgeManager:s}=await Promise.resolve().then(()=>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&&z.info(`Weekly lesson promotion complete`,{promoted:f.promoted.length,candidates:f.candidates.length})}}catch(e){z.warn(`Startup maintenance failed (non-critical)`,p(e))}}).catch(()=>{})};if(z.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:u},{authMiddleware:d,getOrCreateToken:f}]=await Promise.all([import(`express`),import(`./config-CCrLxwqC.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(t.port),_=`http://localhost:${g}`,v=process.env.AIKIT_CORS_ORIGIN??_,y=process.env.AIKIT_ALLOW_ANY_ORIGIN===`true`,b=Q(`AIKIT_HTTP_MAX_SESSIONS`,8),x=Q(`AIKIT_HTTP_SESSION_TIMEOUT_MINUTES`,30),S=Q(`AIKIT_HTTP_SESSION_GC_INTERVAL_MINUTES`,5),C=H({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=V({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=f();console.error(`[aikit] Auth token: ~/.aikit/token`),h.use(d(T)),h.use(`/mcp`,(e,t,n)=>{let r=Z(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,A=null,M=null,N=null,P=null,F=null,I=null,L=Promise.resolve(),R=async(e,t)=>{if(!D||!M||!N){t.status(503).json({jsonrpc:`2.0`,error:{code:-32603,message:`Server initializing — please retry in a few seconds`},id:null});return}let r=L,i;L=new Promise(e=>{i=e}),await r;try{let r=Z(e);if(!F){if(r){t.status(404).json({jsonrpc:`2.0`,error:{code:-32001,message:`Session not found`},id:null});return}let e=new N({sessionIdGenerator:()=>n(),onsessioninitialized:async e=>{I=e,A?.onSessionStart(e,{transport:`http`})},onsessionclosed:async e=>{e&&A?.onSessionEnd(e),I=null}});e.onclose=()=>{F===e&&(F=null),I===e.sessionId&&(I=null)},F=e,await M.connect(e)}let i=F;await i.handleRequest(e,t,e.body),e.method!==`DELETE`&&(!r&&i.sessionId?(I=i.sessionId,A?.onSessionStart(i.sessionId,{transport:`http`}),A?.onSessionActivity(i.sessionId)):r&&A?.onSessionActivity(r))}catch(e){if(z.error(`MCP handler error`,p(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()}},B=async(e,t)=>{let n=Z(e);if(P&&(!F||n!==I)){await P.handleRequest(e,t,e.body);return}await R(e,t)};h.post(`/mcp`,B),h.get(`/mcp`,B),h.delete(`/mcp`,B);let U=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-CzPRmJtW.js`),import(`@modelcontextprotocol/sdk/server/streamableHttp.js`),import(`./version-check-gazMo-D4.js`)]);o(),s();let c=a(m),l=e(m,c);M=l.server,N=i,D=!0,z.debug(`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`);A=new j(l.aikit.stateStore,{staleTimeoutMinutes:x,gcIntervalMinutes:S,onBeforeSessionDelete:e=>{if(I===e&&F){let e=F;F=null,I=null,e.close().catch(()=>void 0)}P?.closeSession(e,{notifySessionEnd:!1})},onSessionEndMaintenance:async()=>{if(!l.aikit?.curated||!l.aikit?.stateStore)return;let{pruneLessons:e}=await import(`./evolution-DWaEE6XW.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})}}),P=new k({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=>A?.onSessionStart(e,{transport:`http`}),onSessionActivity:e=>A?.onSessionActivity(e),onSessionEnd:e=>A?.onSessionEnd(e)}),A.startGC(),I&&(A.onSessionStart(I,{transport:`http`}),A.onSessionActivity(I)),z.info(`HTTP session runtime ready`,{maxSessions:b,sessionTimeoutMinutes:x,gcIntervalMinutes:S})}).catch(e=>z.error(`Failed to start session manager`,p(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`,p(e))}}).catch(e=>z.error(`AI Kit init or indexing failed`,p(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.debug(`Smart index scheduler started (HTTP mode)`)}catch(e){z.error(`Failed to start smart index scheduler`,p(e))}}).catch(e=>z.error(`AI Kit initialization failed`,p(e))):(l.ready.catch(e=>z.error(`AI Kit initialization failed`,p(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`,p(e))}},100)}),W=async e=>{z.info(`Shutdown signal received`,{signal:e}),O?.stop(),A?.stop(),await P?.closeAll().catch(()=>void 0),I&&A?.onSessionEnd(I),F&&(await F.close().catch(()=>void 0),F=null,I=null),U.close(),M&&await M.close(),process.exit(0)};process.on(`SIGINT`,()=>W(`SIGINT`)),process.on(`SIGTERM`,()=>W(`SIGTERM`))}else{let[{loadConfig:e,reconfigureForWorkspace:t,resolveIndexMode:n},{createLazyServer:i},{checkForUpdates:a,autoUpgradeScaffold:o},{RootsListChangedNotificationSchema:s}]=await Promise.all([import(`./config-CCrLxwqC.js`),import(`./server-CzPRmJtW.js`),import(`./version-check-gazMo-D4.js`),import(`@modelcontextprotocol/sdk/types.js`)]),c=e();z.info(`Config loaded`,{sourceCount:c.sources.length,storePath:c.store.path}),a(),o();let l=n(c),u=i(c,l),{server:d,startInit:f,ready:m,runInitialIndex:h}=u,{StdioServerTransport:g}=await import(`@modelcontextprotocol/sdk/server/stdio.js`),_=new g;await d.connect(_),z.debug(`MCP server started`,{transport:`stdio`}),await J({config:c,indexMode:l,log:z,rootsChangedNotificationSchema:s,reconfigureForWorkspace:t,runInitialIndex:h,server:d,startInit:f});let v=null,y=()=>{v&&clearTimeout(v),v=setTimeout(async()=>{z.info(`Auto-shutdown: no activity for 30 minutes — shutting down gracefully`);try{let e=u.aikit;e&&await Promise.all([e.embedder.shutdown?.().catch(()=>{})??Promise.resolve(),e.graphStore.close().catch(()=>{}),e.store.close().catch(()=>{})])}catch{}process.exit(0)},18e5),v.unref&&v.unref()};y(),process.stdin.on(`data`,()=>y()),m.catch(e=>{z.error(`Initialization failed — server will continue with limited tools`,p(e))}),l===`smart`?m.then(async()=>{try{if(!u.aikit)throw Error(`AI Kit components are not available after initialization`);let{SmartIndexScheduler:e}=await import(`../../indexer/dist/index.js`),t=new e(u.aikit.indexer,c,u.aikit.store),n=u.aikit.store;t.start(),n.onBeforeClose&&n.onBeforeClose(()=>t.stop()),u.setSmartScheduler(t),z.debug(`Smart index scheduler started (stdio mode)`)}catch(e){z.error(`Failed to start smart index scheduler`,p(e))}}).catch(e=>z.error(`AI Kit init failed for smart scheduler`,p(e))):z.warn(`Initial full indexing skipped; use aikit_reindex to index manually`,{indexMode:l}),r(m,()=>u.aikit?{curated:u.aikit.curated,stateStore:u.aikit.stateStore}:null)}}ee();export{M as n,L as t};
8
+ `),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 R(){try{let e=s(i(c(import.meta.url)),`..`,`..`,`..`,`package.json`);return JSON.parse(r(e,`utf-8`)).version??`0.0.0`}catch{return`0.0.0`}}const z=f(`server`),B=/^https?:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/i;function V({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 H({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 U(e){return e.startsWith(`file://`)?c(e):e}function W(e){let t=s(e);return process.platform===`win32`?t.toLowerCase():t}function G(e){let t=new Map;for(let n of e){let e=U(n.uri);t.set(W(e),e)}return[...t.values()].sort((e,t)=>W(e).localeCompare(W(t)))}function K({config:e,roots:t}){let n=G(t);if(n.length===0)return null;let r=e.sources?.[0]?.path;if(r){let e=W(r),t=n.find(t=>W(t)===e);if(t)return t}return n[0]}function q({config:e,log:t,reconfigureForWorkspace:n,roots:r}){let i=G(r);if(i.length===0)return!1;let a=K({config:e,roots:i.map(e=>({uri:e}))});if(!a)return!1;let o=e.sources?.[0]?.path,s=o&&W(o)===W(a)?`configured-source`:`stable-sorted-root`;return t.debug(`MCP roots resolved`,{rootPath:a,rootCount:i.length,selectedBy:s}),n(e,a),e.allRoots=i,!0}async function J({config:e,indexMode:t,log:n,rootsChangedNotificationSchema:r,reconfigureForWorkspace:i,runInitialIndex:a,server:o,startInit:s,timeoutMs:c=5e3,getCwd:l=()=>process.cwd()}){let u=!1,d=!1,f,m=o.server,h=e=>{let t=p(e),n=`${String(e)} ${String(t.message??``)}`.toLowerCase();return n.includes(`method not found`)||n.includes(`not supported`)||n.includes(`unsupported`)||n.includes(`unknown method`)||n.includes(`roots/list`)},g=()=>{u||(u=!0,s())},_=()=>{d||t!==`auto`||(d=!0,(async()=>{try{await a()}catch(e){n.error(`Initial index failed`,p(e))}})())},v=t=>t.length===0||(f&&=(clearTimeout(f),void 0),!q({config:e,log:n,reconfigureForWorkspace:i,roots:t}))?!1:(g(),_(),!0);try{if(v((await m.listRoots()).roots))return;n.debug(`No MCP roots yet; waiting for roots/list_changed notification`)}catch(e){if(h(e)){n.warn(`MCP roots/list not supported by client; using cwd fallback`,{cwd:l(),...p(e)}),g(),_();return}n.warn(`MCP roots/list failed during bootstrap; waiting for roots/list_changed notification`,{cwd:l(),...p(e)})}m.setNotificationHandler(r,async()=>{try{v((await m.listRoots()).roots)}catch(e){n.warn(`roots/list retry failed after notification`,p(e))}}),f=setTimeout(()=>{let t=l();n.debug(`Timed out waiting for MCP roots/list_changed; falling back to cwd workspace`,{cwd:t}),q({config:e,log:n,reconfigureForWorkspace:i,roots:[{uri:t}]})&&(g(),_())},c)}function Y(){return process.env.AIKIT_TRANSPORT?process.env.AIKIT_TRANSPORT:process.stdin.isTTY?`http`:`stdio`}function X(){let e=process.argv[1];if(!e)return!1;try{return import.meta.url===l(e).href}catch{return!1}}function Z(e){let t=e.headers[`mcp-session-id`];return Array.isArray(t)?t[0]:t}function Q(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 $(){return X()?u({allowPositionals:!0,options:{transport:{type:`string`,default:Y()},port:{type:`string`,default:process.env.AIKIT_PORT??`3210`}}}).values:{transport:Y(),port:process.env.AIKIT_PORT??`3210`}}async function ee(){let e=R(),t=$();process.on(`unhandledRejection`,e=>{z.error(`Unhandled rejection`,p(e))}),process.on(`uncaughtException`,e=>{z.error(`Uncaught exception — exiting`,p(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-DWaEE6XW.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-CJFYv4Ye.js`).then(e=>e.o),{CuratedKnowledgeManager:s}=await Promise.resolve().then(()=>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&&z.info(`Weekly lesson promotion complete`,{promoted:f.promoted.length,candidates:f.candidates.length})}}catch(e){z.warn(`Startup maintenance failed (non-critical)`,p(e))}}).catch(()=>{})};if(z.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:u},{authMiddleware:d,getOrCreateToken:f}]=await Promise.all([import(`express`),import(`./config-CCrLxwqC.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(t.port),_=`http://localhost:${g}`,v=process.env.AIKIT_CORS_ORIGIN??_,y=process.env.AIKIT_ALLOW_ANY_ORIGIN===`true`,b=Q(`AIKIT_HTTP_MAX_SESSIONS`,8),x=Q(`AIKIT_HTTP_SESSION_TIMEOUT_MINUTES`,30),S=Q(`AIKIT_HTTP_SESSION_GC_INTERVAL_MINUTES`,5),C=H({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=V({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=f();console.error(`[aikit] Auth token: ~/.aikit/token`),h.use(d(T)),h.use(`/mcp`,(e,t,n)=>{let r=Z(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,A=null,M=null,N=null,P=null,F=null,I=null,L=Promise.resolve(),R=async(e,t)=>{if(!D||!M||!N){t.status(503).json({jsonrpc:`2.0`,error:{code:-32603,message:`Server initializing — please retry in a few seconds`},id:null});return}let r=L,i;L=new Promise(e=>{i=e}),await r;try{let r=Z(e);if(!F){if(r){t.status(404).json({jsonrpc:`2.0`,error:{code:-32001,message:`Session not found`},id:null});return}let e=new N({sessionIdGenerator:()=>n(),onsessioninitialized:async e=>{I=e,A?.onSessionStart(e,{transport:`http`})},onsessionclosed:async e=>{e&&A?.onSessionEnd(e),I=null}});e.onclose=()=>{F===e&&(F=null),I===e.sessionId&&(I=null)},F=e,await M.connect(e)}let i=F;await i.handleRequest(e,t,e.body),e.method!==`DELETE`&&(!r&&i.sessionId?(I=i.sessionId,A?.onSessionStart(i.sessionId,{transport:`http`}),A?.onSessionActivity(i.sessionId)):r&&A?.onSessionActivity(r))}catch(e){if(z.error(`MCP handler error`,p(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()}},B=async(e,t)=>{let n=Z(e);if(P&&(!F||n!==I)){await P.handleRequest(e,t,e.body);return}await R(e,t)};h.post(`/mcp`,B),h.get(`/mcp`,B),h.delete(`/mcp`,B);let U=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-CgnBCmIO.js`),import(`@modelcontextprotocol/sdk/server/streamableHttp.js`),import(`./version-check-gazMo-D4.js`)]);o(),s();let c=a(m),l=e(m,c);M=l.server,N=i,D=!0,z.debug(`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`);A=new j(l.aikit.stateStore,{staleTimeoutMinutes:x,gcIntervalMinutes:S,onBeforeSessionDelete:e=>{if(I===e&&F){let e=F;F=null,I=null,e.close().catch(()=>void 0)}P?.closeSession(e,{notifySessionEnd:!1})},onSessionEndMaintenance:async()=>{if(!l.aikit?.curated||!l.aikit?.stateStore)return;let{pruneLessons:e}=await import(`./evolution-DWaEE6XW.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})}}),P=new k({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=>A?.onSessionStart(e,{transport:`http`}),onSessionActivity:e=>A?.onSessionActivity(e),onSessionEnd:e=>A?.onSessionEnd(e)}),A.startGC(),I&&(A.onSessionStart(I,{transport:`http`}),A.onSessionActivity(I)),z.info(`HTTP session runtime ready`,{maxSessions:b,sessionTimeoutMinutes:x,gcIntervalMinutes:S})}).catch(e=>z.error(`Failed to start session manager`,p(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`,p(e))}}).catch(e=>z.error(`AI Kit init or indexing failed`,p(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.debug(`Smart index scheduler started (HTTP mode)`)}catch(e){z.error(`Failed to start smart index scheduler`,p(e))}}).catch(e=>z.error(`AI Kit initialization failed`,p(e))):(l.ready.catch(e=>z.error(`AI Kit initialization failed`,p(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`,p(e))}},100)}),W=async e=>{z.info(`Shutdown signal received`,{signal:e}),O?.stop(),A?.stop(),await P?.closeAll().catch(()=>void 0),I&&A?.onSessionEnd(I),F&&(await F.close().catch(()=>void 0),F=null,I=null),U.close(),M&&await M.close(),process.exit(0)};process.on(`SIGINT`,()=>W(`SIGINT`)),process.on(`SIGTERM`,()=>W(`SIGTERM`))}else{let[{loadConfig:e,reconfigureForWorkspace:t,resolveIndexMode:n},{createLazyServer:i},{checkForUpdates:a,autoUpgradeScaffold:o},{RootsListChangedNotificationSchema:s}]=await Promise.all([import(`./config-CCrLxwqC.js`),import(`./server-CgnBCmIO.js`),import(`./version-check-gazMo-D4.js`),import(`@modelcontextprotocol/sdk/types.js`)]),c=e();z.info(`Config loaded`,{sourceCount:c.sources.length,storePath:c.store.path}),a(),o();let l=n(c),u=i(c,l),{server:d,startInit:f,ready:m,runInitialIndex:h}=u,{StdioServerTransport:g}=await import(`@modelcontextprotocol/sdk/server/stdio.js`),_=new g;await d.connect(_),z.debug(`MCP server started`,{transport:`stdio`}),await J({config:c,indexMode:l,log:z,rootsChangedNotificationSchema:s,reconfigureForWorkspace:t,runInitialIndex:h,server:d,startInit:f});let v=null,y=()=>{v&&clearTimeout(v),v=setTimeout(async()=>{z.info(`Auto-shutdown: no activity for 30 minutes — shutting down gracefully`);try{let e=u.aikit;e&&await Promise.all([e.embedder.shutdown?.().catch(()=>{})??Promise.resolve(),e.graphStore.close().catch(()=>{}),e.store.close().catch(()=>{})])}catch{}process.exit(0)},18e5),v.unref&&v.unref()};y(),process.stdin.on(`data`,()=>y()),m.catch(e=>{z.error(`Initialization failed — server will continue with limited tools`,p(e))}),l===`smart`?m.then(async()=>{try{if(!u.aikit)throw Error(`AI Kit components are not available after initialization`);let{SmartIndexScheduler:e}=await import(`../../indexer/dist/index.js`),t=new e(u.aikit.indexer,c,u.aikit.store),n=u.aikit.store;t.start(),n.onBeforeClose&&n.onBeforeClose(()=>t.stop()),u.setSmartScheduler(t),z.debug(`Smart index scheduler started (stdio mode)`)}catch(e){z.error(`Failed to start smart index scheduler`,p(e))}}).catch(e=>z.error(`AI Kit init failed for smart scheduler`,p(e))):z.warn(`Initial full indexing skipped; use aikit_reindex to index manually`,{indexMode:l}),r(m,()=>u.aikit?{curated:u.aikit.curated,stateStore:u.aikit.stateStore}:null)}}ee();export{M as n,L as t};
@@ -1 +1 @@
1
- import{t as e}from"./curated-manager-xTfPLFMR.js";import{randomUUID as t}from"node:crypto";import{readFileSync as n}from"node:fs";import{dirname as r,resolve as i}from"node:path";import{fileURLToPath as a,pathToFileURL as o}from"node:url";import{parseArgs as s}from"node:util";import{createLogger as c,serializeError as l}from"../../core/dist/index.js";const u=`__pending__:`;function d(e){return e.startsWith(u)}function f(e){let t=e.headers[`mcp-session-id`];return Array.isArray(t)?t[0]:t}function p(e,t,n,r){e.status(t).json({jsonrpc:`2.0`,error:{code:n,message:r},id:null})}var m=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=f(e),i=r?this.runtimes.get(r):void 0;if(r&&!i){p(t,404,-32001,`Session not found`);return}if(!i){if(e.method!==`POST`){p(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`&&!d(r)&&this.options.onSessionActivity?.(r),e.method===`DELETE`&&!d(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&&!d(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){p(e,503,-32003,`Session capacity reached`);return}let n=this.now(),r=await this.options.createServer(),i={id:`${u}${t()}`,transport:void 0,createdAt:n,lastAccessAt:n,server:r,requestChain:Promise.resolve()},a=this.options.createTransport({sessionIdGenerator:()=>t(),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 h(e){let t=e.includes(`T`)?e:`${e.replace(` `,`T`)}Z`;return Date.parse(t)}var g=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=h(n.lastActivity);return Number.isFinite(r)&&e-r>=t}).map(e=>e.sessionId)}};function _(){try{let e=i(r(a(import.meta.url)),`..`,`..`,`..`,`package.json`);return JSON.parse(n(e,`utf-8`)).version??`0.0.0`}catch{return`0.0.0`}}const v=c(`server`),y=/^https?:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/i;function b({requestOrigin:e,configuredOrigin:t,allowAnyOrigin:n,fallbackOrigin:r}){let i=t??r;return i===`*`?n?{allowOrigin:`*`,warn:!1}:e?y.test(e)?{allowOrigin:e,warn:!1}:{allowOrigin:null,warn:!0}:{allowOrigin:r,warn:!1}:{allowOrigin:i,warn:!1}}function x({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 S(e){return e.startsWith(`file://`)?a(e):e}function C(e){let t=i(e);return process.platform===`win32`?t.toLowerCase():t}function w(e){let t=new Map;for(let n of e){let e=S(n.uri);t.set(C(e),e)}return[...t.values()].sort((e,t)=>C(e).localeCompare(C(t)))}function T({config:e,roots:t}){let n=w(t);if(n.length===0)return null;let r=e.sources?.[0]?.path;if(r){let e=C(r),t=n.find(t=>C(t)===e);if(t)return t}return n[0]}function E({config:e,log:t,reconfigureForWorkspace:n,roots:r}){let i=w(r);if(i.length===0)return!1;let a=T({config:e,roots:i.map(e=>({uri:e}))});if(!a)return!1;let o=e.sources?.[0]?.path,s=o&&C(o)===C(a)?`configured-source`:`stable-sorted-root`;return t.debug(`MCP roots resolved`,{rootPath:a,rootCount:i.length,selectedBy:s}),n(e,a),e.allRoots=i,!0}async function D({config:e,indexMode:t,log:n,rootsChangedNotificationSchema:r,reconfigureForWorkspace:i,runInitialIndex:a,server:o,startInit:s,timeoutMs:c=5e3,getCwd:u=()=>process.cwd()}){let d=!1,f=!1,p,m=o.server,h=e=>{let t=l(e),n=`${String(e)} ${String(t.message??``)}`.toLowerCase();return n.includes(`method not found`)||n.includes(`not supported`)||n.includes(`unsupported`)||n.includes(`unknown method`)||n.includes(`roots/list`)},g=()=>{d||(d=!0,s())},_=()=>{f||t!==`auto`||(f=!0,(async()=>{try{await a()}catch(e){n.error(`Initial index failed`,l(e))}})())},v=t=>t.length===0||(p&&=(clearTimeout(p),void 0),!E({config:e,log:n,reconfigureForWorkspace:i,roots:t}))?!1:(g(),_(),!0);try{if(v((await m.listRoots()).roots))return;n.debug(`No MCP roots yet; waiting for roots/list_changed notification`)}catch(e){if(h(e)){n.warn(`MCP roots/list not supported by client; using cwd fallback`,{cwd:u(),...l(e)}),g(),_();return}n.warn(`MCP roots/list failed during bootstrap; waiting for roots/list_changed notification`,{cwd:u(),...l(e)})}m.setNotificationHandler(r,async()=>{try{v((await m.listRoots()).roots)}catch(e){n.warn(`roots/list retry failed after notification`,l(e))}}),p=setTimeout(()=>{let t=u();n.debug(`Timed out waiting for MCP roots/list_changed; falling back to cwd workspace`,{cwd:t}),E({config:e,log:n,reconfigureForWorkspace:i,roots:[{uri:t}]})&&(g(),_())},c)}function O(){return process.env.AIKIT_TRANSPORT?process.env.AIKIT_TRANSPORT:process.stdin.isTTY?`http`:`stdio`}function k(){let e=process.argv[1];if(!e)return!1;try{return import.meta.url===o(e).href}catch{return!1}}function A(e){let t=e.headers[`mcp-session-id`];return Array.isArray(t)?t[0]:t}function j(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 M(){return k()?s({allowPositionals:!0,options:{transport:{type:`string`,default:O()},port:{type:`string`,default:process.env.AIKIT_PORT??`3210`}}}).values:{transport:O(),port:process.env.AIKIT_PORT??`3210`}}async function N(){let e=_(),n=M();process.on(`unhandledRejection`,e=>{v.error(`Unhandled rejection`,l(e))}),process.on(`uncaughtException`,e=>{v.error(`Uncaught exception — exiting`,l(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&&v.info(`Storage maintenance complete`,{forgeOrphans:e.forgeGroundOrphans.count,legacyLance:e.legacyLance.count,bytesFreed:e.totalBytesFreed});let{groupLessons:t,pruneLessons:i}=await import(`./evolution-BX_zTSdj.js`).then(e=>e.t),a=await i(o.curated,o.stateStore,{dryRun:!1});a.pruned.length>0&&v.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)&&v.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-PdKQQktE.js`).then(e=>e.o),{CuratedKnowledgeManager:s}=await import(`./curated-manager-xTfPLFMR.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&&v.info(`Weekly lesson promotion complete`,{promoted:f.promoted.length,candidates:f.candidates.length})}}catch(e){v.warn(`Startup maintenance failed (non-critical)`,l(e))}}).catch(()=>{})};if(v.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:u},{createSettingsRouter:d},{authMiddleware:f,getOrCreateToken:p}]=await Promise.all([import(`express`),import(`./config-D_MQ_9Q7.js`),import(`./dashboard-static-FmfoS46e.js`),import(`./settings-static-BtvyIrza.js`),import(`./routes-CR3fI-HJ.js`),import(`./auth-Bz5dmZgR.js`).then(e=>e.t)]),h=i();v.info(`Config loaded`,{sourceCount:h.sources.length,storePath:h.store.path});let _=e();_.use(e.json({limit:`1mb`}));let y=Number(n.port),S=`http://localhost:${y}`,C=process.env.AIKIT_CORS_ORIGIN??S,w=process.env.AIKIT_ALLOW_ANY_ORIGIN===`true`,T=j(`AIKIT_HTTP_MAX_SESSIONS`,8),E=j(`AIKIT_HTTP_SESSION_TIMEOUT_MINUTES`,30),D=j(`AIKIT_HTTP_SESSION_GC_INTERVAL_MINUTES`,5),O=x({limit:100,windowMs:6e4}),k=!1;_.use((e,t,n)=>{let r=Array.isArray(e.headers.origin)?e.headers.origin[0]:e.headers.origin,i=b({requestOrigin:r,configuredOrigin:C,allowAnyOrigin:w,fallbackOrigin:S});if(i.warn&&!k&&(k=!0,v.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 M=p();console.error(`[aikit] Auth token: ~/.aikit/token`),_.use(f(M)),_.use(`/mcp`,(e,t,n)=>{let r=A(e)??e.ip??e.socket.remoteAddress??`anonymous`;if(O.allow(r)){n();return}let i=Math.max(1,Math.ceil(O.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(_,s(),v);let N=new Date().toISOString();_.use(`/settings/api`,d({log:v,mcpInfo:()=>({transport:`http`,port:y,pid:process.pid,startedAt:N})})),c(_,u(),v),_.get(`/health`,(e,t)=>{t.json({status:`ok`})});let P=!1,F=null,I=null,L=null,R=null,z=null,B=null,V=null,H=Promise.resolve(),U=async(e,n)=>{if(!P||!L||!R){n.status(503).json({jsonrpc:`2.0`,error:{code:-32603,message:`Server initializing — please retry in a few seconds`},id:null});return}let r=H,i;H=new Promise(e=>{i=e}),await r;try{let r=A(e);if(!B){if(r){n.status(404).json({jsonrpc:`2.0`,error:{code:-32001,message:`Session not found`},id:null});return}let e=new R({sessionIdGenerator:()=>t(),onsessioninitialized:async e=>{V=e,I?.onSessionStart(e,{transport:`http`})},onsessionclosed:async e=>{e&&I?.onSessionEnd(e),V=null}});e.onclose=()=>{B===e&&(B=null),V===e.sessionId&&(V=null)},B=e,await L.connect(e)}let i=B;await i.handleRequest(e,n,e.body),e.method!==`DELETE`&&(!r&&i.sessionId?(V=i.sessionId,I?.onSessionStart(i.sessionId,{transport:`http`}),I?.onSessionActivity(i.sessionId)):r&&I?.onSessionActivity(r))}catch(e){if(v.error(`MCP handler error`,l(e)),!n.headersSent){let t=e instanceof Error?e.message:String(e),r=t.includes(`Not Acceptable`);n.status(r?406:500).json({jsonrpc:`2.0`,error:{code:r?-32e3:-32603,message:r?t:`Internal server error`},id:null})}}finally{i()}},W=async(e,t)=>{let n=A(e);if(z&&(!B||n!==V)){await z.handleRequest(e,t,e.body);return}await U(e,t)};_.post(`/mcp`,W),_.get(`/mcp`,W),_.delete(`/mcp`,W);let G=_.listen(y,`127.0.0.1`,()=>{v.info(`MCP server listening`,{url:`http://127.0.0.1:${y}/mcp`,port:y}),setTimeout(async()=>{try{let[{createLazyServer:e,createMcpServer:t,ALL_TOOL_NAMES:n},{StreamableHTTPServerTransport:i},{checkForUpdates:o,autoUpgradeScaffold:s}]=await Promise.all([import(`./server-D-PQVQ3u.js`),import(`@modelcontextprotocol/sdk/server/streamableHttp.js`),import(`./version-check-BgHzxxCW.js`)]);o(),s();let c=a(h),u=e(h,c);L=u.server,R=i,P=!0,v.debug(`MCP server configured (lazy — AI Kit initializing in background)`,{toolCount:n.length,resourceCount:2}),u.startInit(),u.ready.then(()=>{if(!u.aikit)throw Error(`AI Kit components are not available after initialization`);I=new g(u.aikit.stateStore,{staleTimeoutMinutes:E,gcIntervalMinutes:D,onBeforeSessionDelete:e=>{if(V===e&&B){let e=B;B=null,V=null,e.close().catch(()=>void 0)}z?.closeSession(e,{notifySessionEnd:!1})},onSessionEndMaintenance:async()=>{if(!u.aikit?.curated||!u.aikit?.stateStore)return;let{pruneLessons:e}=await import(`./evolution-BX_zTSdj.js`).then(e=>e.t),t=await e(u.aikit.curated,u.aikit.stateStore,{dryRun:!1});t.pruned.length>0&&v.info(`Session-end lesson prune`,{pruned:t.pruned.length})}}),z=new m({createServer:()=>{if(!u.aikit)throw Error(`AI Kit components are not available after initialization`);return t(u.aikit,h)},createTransport:e=>new i(e),maxSessions:T,sessionTimeoutMinutes:E,onSessionStart:e=>I?.onSessionStart(e,{transport:`http`}),onSessionActivity:e=>I?.onSessionActivity(e),onSessionEnd:e=>I?.onSessionEnd(e)}),I.startGC(),V&&(I.onSessionStart(V,{transport:`http`}),I.onSessionActivity(V)),v.info(`HTTP session runtime ready`,{maxSessions:T,sessionTimeoutMinutes:E,gcIntervalMinutes:D})}).catch(e=>v.error(`Failed to start session manager`,l(e))),c===`auto`?u.ready.then(async()=>{try{let e=h.sources.map(e=>e.path).join(`, `);v.info(`Running initial index`,{sourcePaths:e}),await u.runInitialIndex(),v.info(`Initial index complete`)}catch(e){v.error(`Initial index failed; will retry on aikit_reindex`,l(e))}}).catch(e=>v.error(`AI Kit init or indexing failed`,l(e))):c===`smart`?u.ready.then(async()=>{try{if(!u.aikit)throw Error(`AI Kit components are not available after initialization`);let{SmartIndexScheduler:e}=await import(`../../indexer/dist/index.js`),t=new e(u.aikit.indexer,h,u.aikit.store),n=u.aikit.store;F=t,t.start(),n.onBeforeClose&&n.onBeforeClose(()=>t.stop()),u.setSmartScheduler(t),v.debug(`Smart index scheduler started (HTTP mode)`)}catch(e){v.error(`Failed to start smart index scheduler`,l(e))}}).catch(e=>v.error(`AI Kit initialization failed`,l(e))):(u.ready.catch(e=>v.error(`AI Kit initialization failed`,l(e))),v.info(`Initial full indexing skipped in HTTP mode`,{indexMode:c})),r(u.ready,()=>u.aikit?{curated:u.aikit.curated,stateStore:u.aikit.stateStore}:null)}catch(e){v.error(`Failed to load server modules`,l(e))}},100)}),K=async e=>{v.info(`Shutdown signal received`,{signal:e}),F?.stop(),I?.stop(),await z?.closeAll().catch(()=>void 0),V&&I?.onSessionEnd(V),B&&(await B.close().catch(()=>void 0),B=null,V=null),G.close(),L&&await L.close(),process.exit(0)};process.on(`SIGINT`,()=>K(`SIGINT`)),process.on(`SIGTERM`,()=>K(`SIGTERM`))}else{let[{loadConfig:e,reconfigureForWorkspace:t,resolveIndexMode:n},{createLazyServer:i},{checkForUpdates:a,autoUpgradeScaffold:o},{RootsListChangedNotificationSchema:s}]=await Promise.all([import(`./config-D_MQ_9Q7.js`),import(`./server-D-PQVQ3u.js`),import(`./version-check-BgHzxxCW.js`),import(`@modelcontextprotocol/sdk/types.js`)]),c=e();v.info(`Config loaded`,{sourceCount:c.sources.length,storePath:c.store.path}),a(),o();let u=n(c),d=i(c,u),{server:f,startInit:p,ready:m,runInitialIndex:h}=d,{StdioServerTransport:g}=await import(`@modelcontextprotocol/sdk/server/stdio.js`),_=new g;await f.connect(_),v.debug(`MCP server started`,{transport:`stdio`}),await D({config:c,indexMode:u,log:v,rootsChangedNotificationSchema:s,reconfigureForWorkspace:t,runInitialIndex:h,server:f,startInit:p});let y=null,b=()=>{y&&clearTimeout(y),y=setTimeout(async()=>{v.info(`Auto-shutdown: no activity for 30 minutes — shutting down gracefully`);try{let e=d.aikit;e&&await Promise.all([e.embedder.shutdown?.().catch(()=>{})??Promise.resolve(),e.graphStore.close().catch(()=>{}),e.store.close().catch(()=>{})])}catch{}process.exit(0)},18e5),y.unref&&y.unref()};b(),process.stdin.on(`data`,()=>b()),m.catch(e=>{v.error(`Initialization failed — server will continue with limited tools`,l(e))}),u===`smart`?m.then(async()=>{try{if(!d.aikit)throw Error(`AI Kit components are not available after initialization`);let{SmartIndexScheduler:e}=await import(`../../indexer/dist/index.js`),t=new e(d.aikit.indexer,c,d.aikit.store),n=d.aikit.store;t.start(),n.onBeforeClose&&n.onBeforeClose(()=>t.stop()),d.setSmartScheduler(t),v.debug(`Smart index scheduler started (stdio mode)`)}catch(e){v.error(`Failed to start smart index scheduler`,l(e))}}).catch(e=>v.error(`AI Kit init failed for smart scheduler`,l(e))):v.warn(`Initial full indexing skipped; use aikit_reindex to index manually`,{indexMode:u}),r(m,()=>d.aikit?{curated:d.aikit.curated,stateStore:d.aikit.stateStore}:null)}}export{e as CuratedKnowledgeManager,E as applyWorkspaceRoots,D as bootstrapWorkspaceRoots,x as createSlidingWindowRateLimiter,N as main,b as resolveCorsOrigin,T as selectWorkspaceRoot};
1
+ import{t as e}from"./curated-manager-xTfPLFMR.js";import{randomUUID as t}from"node:crypto";import{readFileSync as n}from"node:fs";import{dirname as r,resolve as i}from"node:path";import{fileURLToPath as a,pathToFileURL as o}from"node:url";import{parseArgs as s}from"node:util";import{createLogger as c,serializeError as l}from"../../core/dist/index.js";const u=`__pending__:`;function d(e){return e.startsWith(u)}function f(e){let t=e.headers[`mcp-session-id`];return Array.isArray(t)?t[0]:t}function p(e,t,n,r){e.status(t).json({jsonrpc:`2.0`,error:{code:n,message:r},id:null})}var m=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=f(e),i=r?this.runtimes.get(r):void 0;if(r&&!i){p(t,404,-32001,`Session not found`);return}if(!i){if(e.method!==`POST`){p(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`&&!d(r)&&this.options.onSessionActivity?.(r),e.method===`DELETE`&&!d(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&&!d(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){p(e,503,-32003,`Session capacity reached`);return}let n=this.now(),r=await this.options.createServer(),i={id:`${u}${t()}`,transport:void 0,createdAt:n,lastAccessAt:n,server:r,requestChain:Promise.resolve()},a=this.options.createTransport({sessionIdGenerator:()=>t(),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 h(e){let t=e.includes(`T`)?e:`${e.replace(` `,`T`)}Z`;return Date.parse(t)}var g=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=h(n.lastActivity);return Number.isFinite(r)&&e-r>=t}).map(e=>e.sessionId)}};function _(){try{let e=i(r(a(import.meta.url)),`..`,`..`,`..`,`package.json`);return JSON.parse(n(e,`utf-8`)).version??`0.0.0`}catch{return`0.0.0`}}const v=c(`server`),y=/^https?:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/i;function b({requestOrigin:e,configuredOrigin:t,allowAnyOrigin:n,fallbackOrigin:r}){let i=t??r;return i===`*`?n?{allowOrigin:`*`,warn:!1}:e?y.test(e)?{allowOrigin:e,warn:!1}:{allowOrigin:null,warn:!0}:{allowOrigin:r,warn:!1}:{allowOrigin:i,warn:!1}}function x({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 S(e){return e.startsWith(`file://`)?a(e):e}function C(e){let t=i(e);return process.platform===`win32`?t.toLowerCase():t}function w(e){let t=new Map;for(let n of e){let e=S(n.uri);t.set(C(e),e)}return[...t.values()].sort((e,t)=>C(e).localeCompare(C(t)))}function T({config:e,roots:t}){let n=w(t);if(n.length===0)return null;let r=e.sources?.[0]?.path;if(r){let e=C(r),t=n.find(t=>C(t)===e);if(t)return t}return n[0]}function E({config:e,log:t,reconfigureForWorkspace:n,roots:r}){let i=w(r);if(i.length===0)return!1;let a=T({config:e,roots:i.map(e=>({uri:e}))});if(!a)return!1;let o=e.sources?.[0]?.path,s=o&&C(o)===C(a)?`configured-source`:`stable-sorted-root`;return t.debug(`MCP roots resolved`,{rootPath:a,rootCount:i.length,selectedBy:s}),n(e,a),e.allRoots=i,!0}async function D({config:e,indexMode:t,log:n,rootsChangedNotificationSchema:r,reconfigureForWorkspace:i,runInitialIndex:a,server:o,startInit:s,timeoutMs:c=5e3,getCwd:u=()=>process.cwd()}){let d=!1,f=!1,p,m=o.server,h=e=>{let t=l(e),n=`${String(e)} ${String(t.message??``)}`.toLowerCase();return n.includes(`method not found`)||n.includes(`not supported`)||n.includes(`unsupported`)||n.includes(`unknown method`)||n.includes(`roots/list`)},g=()=>{d||(d=!0,s())},_=()=>{f||t!==`auto`||(f=!0,(async()=>{try{await a()}catch(e){n.error(`Initial index failed`,l(e))}})())},v=t=>t.length===0||(p&&=(clearTimeout(p),void 0),!E({config:e,log:n,reconfigureForWorkspace:i,roots:t}))?!1:(g(),_(),!0);try{if(v((await m.listRoots()).roots))return;n.debug(`No MCP roots yet; waiting for roots/list_changed notification`)}catch(e){if(h(e)){n.warn(`MCP roots/list not supported by client; using cwd fallback`,{cwd:u(),...l(e)}),g(),_();return}n.warn(`MCP roots/list failed during bootstrap; waiting for roots/list_changed notification`,{cwd:u(),...l(e)})}m.setNotificationHandler(r,async()=>{try{v((await m.listRoots()).roots)}catch(e){n.warn(`roots/list retry failed after notification`,l(e))}}),p=setTimeout(()=>{let t=u();n.debug(`Timed out waiting for MCP roots/list_changed; falling back to cwd workspace`,{cwd:t}),E({config:e,log:n,reconfigureForWorkspace:i,roots:[{uri:t}]})&&(g(),_())},c)}function O(){return process.env.AIKIT_TRANSPORT?process.env.AIKIT_TRANSPORT:process.stdin.isTTY?`http`:`stdio`}function k(){let e=process.argv[1];if(!e)return!1;try{return import.meta.url===o(e).href}catch{return!1}}function A(e){let t=e.headers[`mcp-session-id`];return Array.isArray(t)?t[0]:t}function j(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 M(){return k()?s({allowPositionals:!0,options:{transport:{type:`string`,default:O()},port:{type:`string`,default:process.env.AIKIT_PORT??`3210`}}}).values:{transport:O(),port:process.env.AIKIT_PORT??`3210`}}async function N(){let e=_(),n=M();process.on(`unhandledRejection`,e=>{v.error(`Unhandled rejection`,l(e))}),process.on(`uncaughtException`,e=>{v.error(`Uncaught exception — exiting`,l(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&&v.info(`Storage maintenance complete`,{forgeOrphans:e.forgeGroundOrphans.count,legacyLance:e.legacyLance.count,bytesFreed:e.totalBytesFreed});let{groupLessons:t,pruneLessons:i}=await import(`./evolution-BX_zTSdj.js`).then(e=>e.t),a=await i(o.curated,o.stateStore,{dryRun:!1});a.pruned.length>0&&v.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)&&v.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-PdKQQktE.js`).then(e=>e.o),{CuratedKnowledgeManager:s}=await import(`./curated-manager-xTfPLFMR.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&&v.info(`Weekly lesson promotion complete`,{promoted:f.promoted.length,candidates:f.candidates.length})}}catch(e){v.warn(`Startup maintenance failed (non-critical)`,l(e))}}).catch(()=>{})};if(v.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:u},{createSettingsRouter:d},{authMiddleware:f,getOrCreateToken:p}]=await Promise.all([import(`express`),import(`./config-D_MQ_9Q7.js`),import(`./dashboard-static-FmfoS46e.js`),import(`./settings-static-BtvyIrza.js`),import(`./routes-CR3fI-HJ.js`),import(`./auth-Bz5dmZgR.js`).then(e=>e.t)]),h=i();v.info(`Config loaded`,{sourceCount:h.sources.length,storePath:h.store.path});let _=e();_.use(e.json({limit:`1mb`}));let y=Number(n.port),S=`http://localhost:${y}`,C=process.env.AIKIT_CORS_ORIGIN??S,w=process.env.AIKIT_ALLOW_ANY_ORIGIN===`true`,T=j(`AIKIT_HTTP_MAX_SESSIONS`,8),E=j(`AIKIT_HTTP_SESSION_TIMEOUT_MINUTES`,30),D=j(`AIKIT_HTTP_SESSION_GC_INTERVAL_MINUTES`,5),O=x({limit:100,windowMs:6e4}),k=!1;_.use((e,t,n)=>{let r=Array.isArray(e.headers.origin)?e.headers.origin[0]:e.headers.origin,i=b({requestOrigin:r,configuredOrigin:C,allowAnyOrigin:w,fallbackOrigin:S});if(i.warn&&!k&&(k=!0,v.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 M=p();console.error(`[aikit] Auth token: ~/.aikit/token`),_.use(f(M)),_.use(`/mcp`,(e,t,n)=>{let r=A(e)??e.ip??e.socket.remoteAddress??`anonymous`;if(O.allow(r)){n();return}let i=Math.max(1,Math.ceil(O.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(_,s(),v);let N=new Date().toISOString();_.use(`/settings/api`,d({log:v,mcpInfo:()=>({transport:`http`,port:y,pid:process.pid,startedAt:N})})),c(_,u(),v),_.get(`/health`,(e,t)=>{t.json({status:`ok`})});let P=!1,F=null,I=null,L=null,R=null,z=null,B=null,V=null,H=Promise.resolve(),U=async(e,n)=>{if(!P||!L||!R){n.status(503).json({jsonrpc:`2.0`,error:{code:-32603,message:`Server initializing — please retry in a few seconds`},id:null});return}let r=H,i;H=new Promise(e=>{i=e}),await r;try{let r=A(e);if(!B){if(r){n.status(404).json({jsonrpc:`2.0`,error:{code:-32001,message:`Session not found`},id:null});return}let e=new R({sessionIdGenerator:()=>t(),onsessioninitialized:async e=>{V=e,I?.onSessionStart(e,{transport:`http`})},onsessionclosed:async e=>{e&&I?.onSessionEnd(e),V=null}});e.onclose=()=>{B===e&&(B=null),V===e.sessionId&&(V=null)},B=e,await L.connect(e)}let i=B;await i.handleRequest(e,n,e.body),e.method!==`DELETE`&&(!r&&i.sessionId?(V=i.sessionId,I?.onSessionStart(i.sessionId,{transport:`http`}),I?.onSessionActivity(i.sessionId)):r&&I?.onSessionActivity(r))}catch(e){if(v.error(`MCP handler error`,l(e)),!n.headersSent){let t=e instanceof Error?e.message:String(e),r=t.includes(`Not Acceptable`);n.status(r?406:500).json({jsonrpc:`2.0`,error:{code:r?-32e3:-32603,message:r?t:`Internal server error`},id:null})}}finally{i()}},W=async(e,t)=>{let n=A(e);if(z&&(!B||n!==V)){await z.handleRequest(e,t,e.body);return}await U(e,t)};_.post(`/mcp`,W),_.get(`/mcp`,W),_.delete(`/mcp`,W);let G=_.listen(y,`127.0.0.1`,()=>{v.info(`MCP server listening`,{url:`http://127.0.0.1:${y}/mcp`,port:y}),setTimeout(async()=>{try{let[{createLazyServer:e,createMcpServer:t,ALL_TOOL_NAMES:n},{StreamableHTTPServerTransport:i},{checkForUpdates:o,autoUpgradeScaffold:s}]=await Promise.all([import(`./server-CJeYNTxT.js`),import(`@modelcontextprotocol/sdk/server/streamableHttp.js`),import(`./version-check-BgHzxxCW.js`)]);o(),s();let c=a(h),u=e(h,c);L=u.server,R=i,P=!0,v.debug(`MCP server configured (lazy — AI Kit initializing in background)`,{toolCount:n.length,resourceCount:2}),u.startInit(),u.ready.then(()=>{if(!u.aikit)throw Error(`AI Kit components are not available after initialization`);I=new g(u.aikit.stateStore,{staleTimeoutMinutes:E,gcIntervalMinutes:D,onBeforeSessionDelete:e=>{if(V===e&&B){let e=B;B=null,V=null,e.close().catch(()=>void 0)}z?.closeSession(e,{notifySessionEnd:!1})},onSessionEndMaintenance:async()=>{if(!u.aikit?.curated||!u.aikit?.stateStore)return;let{pruneLessons:e}=await import(`./evolution-BX_zTSdj.js`).then(e=>e.t),t=await e(u.aikit.curated,u.aikit.stateStore,{dryRun:!1});t.pruned.length>0&&v.info(`Session-end lesson prune`,{pruned:t.pruned.length})}}),z=new m({createServer:()=>{if(!u.aikit)throw Error(`AI Kit components are not available after initialization`);return t(u.aikit,h)},createTransport:e=>new i(e),maxSessions:T,sessionTimeoutMinutes:E,onSessionStart:e=>I?.onSessionStart(e,{transport:`http`}),onSessionActivity:e=>I?.onSessionActivity(e),onSessionEnd:e=>I?.onSessionEnd(e)}),I.startGC(),V&&(I.onSessionStart(V,{transport:`http`}),I.onSessionActivity(V)),v.info(`HTTP session runtime ready`,{maxSessions:T,sessionTimeoutMinutes:E,gcIntervalMinutes:D})}).catch(e=>v.error(`Failed to start session manager`,l(e))),c===`auto`?u.ready.then(async()=>{try{let e=h.sources.map(e=>e.path).join(`, `);v.info(`Running initial index`,{sourcePaths:e}),await u.runInitialIndex(),v.info(`Initial index complete`)}catch(e){v.error(`Initial index failed; will retry on aikit_reindex`,l(e))}}).catch(e=>v.error(`AI Kit init or indexing failed`,l(e))):c===`smart`?u.ready.then(async()=>{try{if(!u.aikit)throw Error(`AI Kit components are not available after initialization`);let{SmartIndexScheduler:e}=await import(`../../indexer/dist/index.js`),t=new e(u.aikit.indexer,h,u.aikit.store),n=u.aikit.store;F=t,t.start(),n.onBeforeClose&&n.onBeforeClose(()=>t.stop()),u.setSmartScheduler(t),v.debug(`Smart index scheduler started (HTTP mode)`)}catch(e){v.error(`Failed to start smart index scheduler`,l(e))}}).catch(e=>v.error(`AI Kit initialization failed`,l(e))):(u.ready.catch(e=>v.error(`AI Kit initialization failed`,l(e))),v.info(`Initial full indexing skipped in HTTP mode`,{indexMode:c})),r(u.ready,()=>u.aikit?{curated:u.aikit.curated,stateStore:u.aikit.stateStore}:null)}catch(e){v.error(`Failed to load server modules`,l(e))}},100)}),K=async e=>{v.info(`Shutdown signal received`,{signal:e}),F?.stop(),I?.stop(),await z?.closeAll().catch(()=>void 0),V&&I?.onSessionEnd(V),B&&(await B.close().catch(()=>void 0),B=null,V=null),G.close(),L&&await L.close(),process.exit(0)};process.on(`SIGINT`,()=>K(`SIGINT`)),process.on(`SIGTERM`,()=>K(`SIGTERM`))}else{let[{loadConfig:e,reconfigureForWorkspace:t,resolveIndexMode:n},{createLazyServer:i},{checkForUpdates:a,autoUpgradeScaffold:o},{RootsListChangedNotificationSchema:s}]=await Promise.all([import(`./config-D_MQ_9Q7.js`),import(`./server-CJeYNTxT.js`),import(`./version-check-BgHzxxCW.js`),import(`@modelcontextprotocol/sdk/types.js`)]),c=e();v.info(`Config loaded`,{sourceCount:c.sources.length,storePath:c.store.path}),a(),o();let u=n(c),d=i(c,u),{server:f,startInit:p,ready:m,runInitialIndex:h}=d,{StdioServerTransport:g}=await import(`@modelcontextprotocol/sdk/server/stdio.js`),_=new g;await f.connect(_),v.debug(`MCP server started`,{transport:`stdio`}),await D({config:c,indexMode:u,log:v,rootsChangedNotificationSchema:s,reconfigureForWorkspace:t,runInitialIndex:h,server:f,startInit:p});let y=null,b=()=>{y&&clearTimeout(y),y=setTimeout(async()=>{v.info(`Auto-shutdown: no activity for 30 minutes — shutting down gracefully`);try{let e=d.aikit;e&&await Promise.all([e.embedder.shutdown?.().catch(()=>{})??Promise.resolve(),e.graphStore.close().catch(()=>{}),e.store.close().catch(()=>{})])}catch{}process.exit(0)},18e5),y.unref&&y.unref()};b(),process.stdin.on(`data`,()=>b()),m.catch(e=>{v.error(`Initialization failed — server will continue with limited tools`,l(e))}),u===`smart`?m.then(async()=>{try{if(!d.aikit)throw Error(`AI Kit components are not available after initialization`);let{SmartIndexScheduler:e}=await import(`../../indexer/dist/index.js`),t=new e(d.aikit.indexer,c,d.aikit.store),n=d.aikit.store;t.start(),n.onBeforeClose&&n.onBeforeClose(()=>t.stop()),d.setSmartScheduler(t),v.debug(`Smart index scheduler started (stdio mode)`)}catch(e){v.error(`Failed to start smart index scheduler`,l(e))}}).catch(e=>v.error(`AI Kit init failed for smart scheduler`,l(e))):v.warn(`Initial full indexing skipped; use aikit_reindex to index manually`,{indexMode:u}),r(m,()=>d.aikit?{curated:d.aikit.curated,stateStore:d.aikit.stateStore}:null)}}export{e as CuratedKnowledgeManager,E as applyWorkspaceRoots,D as bootstrapWorkspaceRoots,x as createSlidingWindowRateLimiter,N as main,b as resolveCorsOrigin,T as selectWorkspaceRoot};