@vpxa/aikit 0.1.70 → 0.1.71

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.70",
3
+ "version": "0.1.71",
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{dirname as e,extname as t,join as n}from"node:path";import{CHUNK_SIZES as r,createLogger as i}from"../../core/dist/index.js";import{existsSync as a,readFileSync as o}from"node:fs";import{fileURLToPath as s}from"node:url";const c=n(e(s(import.meta.url)),`..`,`..`,`wasm`),l={".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`},u=new Set(Object.keys(l));function d(e){let t=l[e];if(!t)return null;let r=n(c,t);return a(r)?r:null}function f(){let e=n(c,`tree-sitter.wasm`);return a(e)?e:null}const p=i(`wasm-runtime`);async function m(){let e=await import(`web-tree-sitter`),t=typeof e.default?.init==`function`?e.default:e.Parser;if(!t||typeof t.init!=`function`)throw Error(`Unsupported web-tree-sitter export shape: ${Object.keys(e).join(`, `)}`);return t}var h=class e{static instance=null;parser=null;languages=new Map;loadedGrammars=new Map;static async initialize(){if(e.instance)return e.instance;let t=new e;return await t.init()?(e.instance=t,t):null}static get(){return e.instance}static async ensure(){let t=e.get();if(t)return t;let n=await e.initialize();if(!n)throw Error(`Failed to initialize WASM tree-sitter runtime`);return n}static dispose(){e.instance&&=(e.instance.parser?.delete(),e.instance.parser=null,e.instance.languages.clear(),e.instance.loadedGrammars.clear(),null)}async init(){try{let e=f();if(!e)return p.warn(`Parser WASM file not found`),!1;let t=await m();return await t.init({locateFile:()=>e}),this.parser=new t,p.info(`WASM tree-sitter parser initialized`),!0}catch(e){return p.warn(`Failed to initialize WASM tree-sitter`,{error:String(e)}),!1}}async loadLanguage(e){let t=this.languages.get(e);if(t)return t;let n=d(e);if(!n)return null;let r=this.loadedGrammars.get(n);if(r)return this.languages.set(e,r),r;try{let t=await(await m()).Language.load(n);return this.loadedGrammars.set(n,t),this.languages.set(e,t),p.info(`Loaded grammar`,{ext:e}),t}catch(t){return p.warn(`Failed to load grammar`,{ext:e,error:String(t)}),null}}async parse(e,t){if(!this.parser)return null;let n=await this.loadLanguage(t);return n?(this.parser.setLanguage(n),this.parser.parse(e)):null}hasLanguage(e){return u.has(e)}isLanguageLoaded(e){return this.languages.has(e)}getParser(){return this.parser}getLanguage(e){return this.languages.get(e)??null}};async function ee(){return await h.initialize()!==null}const g=new Set([`function_declaration`,`method_definition`,`arrow_function`,`function_definition`,`function_declaration`,`method_declaration`,`function_item`,`method_declaration`,`constructor_declaration`]),_=new Set([`call_expression`,`new_expression`,`call`]);function v(e,n){let r=t(n).toLowerCase(),i=h.get();if(i?.isLanguageLoaded(r)){let t=i.getParser(),a=i.getLanguage(r);if(t&&a){t.setLanguage(a);let r=t.parse(e);if(r){let e=[];return y(r.rootNode,n,`<module>`,e),e}}}return null}function y(e,t,n,r){if(!e)return;let i=n;if(g.has(e.type)&&(i=te(e)??n),_.has(e.type)){let n=b(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&&y(a,t,i,r)}}function te(e){for(let t=0;t<(e.childCount??0);t++){let n=e.child(t);if(n&&(n.type===`identifier`||n.type===`property_identifier`||n.type===`name`))return n.text??null}return null}function b(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 x=class{maxChunkSize;constructor(e){this.maxChunkSize=e?.maxChunkSize??r.code.max}chunk(e,t){let n=this.findDeclarationBoundaries(e);if(n.length===0)return this.fallbackChunk(e,t);let r=[];for(let i=0;i<n.length;i++){let a=n[i].offset,o=i+1<n.length?n[i+1].offset:e.length,s=e.slice(a,o).trim();if(s=`// File: ${t.sourcePath}\n`+s,s.length>this.maxChunkSize){let n=this.splitByLines(s,this.maxChunkSize),i=this.getLineNumber(e,a);for(let e of n){let n=e.split(`
1
+ import{dirname as e,extname as t,join as n}from"node:path";import{CHUNK_SIZES as r,createLogger as i}from"../../core/dist/index.js";import{existsSync as a,readFileSync as o}from"node:fs";import{fileURLToPath as s}from"node:url";const c=e(s(import.meta.url));function l(){let e=[n(c,`..`,`..`,`wasm`),n(c,`..`,`wasm`)];for(let t of e)if(a(n(t,`tree-sitter.wasm`)))return t;return e[0]}const u=l(),d={".ts":`tree-sitter-typescript.wasm`,".tsx":`tree-sitter-typescript.wasm`,".mts":`tree-sitter-typescript.wasm`,".cts":`tree-sitter-typescript.wasm`,".js":`tree-sitter-javascript.wasm`,".jsx":`tree-sitter-javascript.wasm`,".mjs":`tree-sitter-javascript.wasm`,".cjs":`tree-sitter-javascript.wasm`,".py":`tree-sitter-python.wasm`,".go":`tree-sitter-go.wasm`,".rs":`tree-sitter-rust.wasm`,".java":`tree-sitter-java.wasm`,".kt":`tree-sitter-kotlin.wasm`,".kts":`tree-sitter-kotlin.wasm`,".scala":`tree-sitter-scala.wasm`,".sc":`tree-sitter-scala.wasm`,".c":`tree-sitter-c.wasm`,".h":`tree-sitter-c.wasm`,".cpp":`tree-sitter-cpp.wasm`,".cc":`tree-sitter-cpp.wasm`,".cxx":`tree-sitter-cpp.wasm`,".hpp":`tree-sitter-cpp.wasm`,".hxx":`tree-sitter-cpp.wasm`,".cs":`tree-sitter-c_sharp.wasm`,".swift":`tree-sitter-swift.wasm`,".rb":`tree-sitter-ruby.wasm`,".php":`tree-sitter-php.wasm`},f=new Set(Object.keys(d));function p(e){let t=d[e];if(!t)return null;let r=n(u,t);return a(r)?r:null}function m(){let e=n(u,`tree-sitter.wasm`);return a(e)?e:null}const h=i(`wasm-runtime`);async function g(){let e=await import(`web-tree-sitter`),t=typeof e.default?.init==`function`?e.default:e.Parser;if(!t||typeof t.init!=`function`)throw Error(`Unsupported web-tree-sitter export shape: ${Object.keys(e).join(`, `)}`);return t}var _=class e{static instance=null;parser=null;languages=new Map;loadedGrammars=new Map;static async initialize(){if(e.instance)return e.instance;let t=new e;return await t.init()?(e.instance=t,t):null}static get(){return e.instance}static async ensure(){let t=e.get();if(t)return t;let n=await e.initialize();if(!n)throw Error(`Failed to initialize WASM tree-sitter runtime`);return n}static dispose(){e.instance&&=(e.instance.parser?.delete(),e.instance.parser=null,e.instance.languages.clear(),e.instance.loadedGrammars.clear(),null)}async init(){try{let e=m();if(!e)return h.warn(`Parser WASM file not found`),!1;let t=await g();return await t.init({locateFile:()=>e}),this.parser=new t,h.info(`WASM tree-sitter parser initialized`),!0}catch(e){return h.warn(`Failed to initialize WASM tree-sitter`,{error:String(e)}),!1}}async loadLanguage(e){let t=this.languages.get(e);if(t)return t;let n=p(e);if(!n)return null;let r=this.loadedGrammars.get(n);if(r)return this.languages.set(e,r),r;try{let t=await(await g()).Language.load(n);return this.loadedGrammars.set(n,t),this.languages.set(e,t),h.info(`Loaded grammar`,{ext:e}),t}catch(t){return h.warn(`Failed to load grammar`,{ext:e,error:String(t)}),null}}async parse(e,t){if(!this.parser)return null;let n=await this.loadLanguage(t);return n?(this.parser.setLanguage(n),this.parser.parse(e)):null}hasLanguage(e){return f.has(e)}isLanguageLoaded(e){return this.languages.has(e)}getParser(){return this.parser}getLanguage(e){return this.languages.get(e)??null}};async function ee(){return await _.initialize()!==null}const v=new Set([`function_declaration`,`method_definition`,`arrow_function`,`function_definition`,`function_declaration`,`method_declaration`,`function_item`,`method_declaration`,`constructor_declaration`]),y=new Set([`call_expression`,`new_expression`,`call`]);function b(e,n){let r=t(n).toLowerCase(),i=_.get();if(i?.isLanguageLoaded(r)){let t=i.getParser(),a=i.getLanguage(r);if(t&&a){t.setLanguage(a);let r=t.parse(e);if(r){let e=[];return x(r.rootNode,n,`<module>`,e),e}}}return null}function x(e,t,n,r){if(!e)return;let i=n;if(v.has(e.type)&&(i=te(e)??n),y.has(e.type)){let n=S(e);n&&r.push({callerFile:t,callerName:i,calleeName:n,line:(e.startPosition?.row??0)+1})}for(let n=0;n<(e.childCount??0);n++){let a=e.child(n);a&&x(a,t,i,r)}}function te(e){for(let t=0;t<(e.childCount??0);t++){let n=e.child(t);if(n&&(n.type===`identifier`||n.type===`property_identifier`||n.type===`name`))return n.text??null}return null}function S(e){let t=e.childForFieldName?.(`function`)??e.child(0);return t?t.type===`identifier`||t.type===`name`?t.text??null:t.type===`member_expression`||t.type===`attribute`?(t.childForFieldName?.(`property`)??t.childForFieldName?.(`attribute`))?.text??null:e.type===`new_expression`?e.child(1)?.text??null:null:null}var C=class{maxChunkSize;constructor(e){this.maxChunkSize=e?.maxChunkSize??r.code.max}chunk(e,t){let n=this.findDeclarationBoundaries(e);if(n.length===0)return this.fallbackChunk(e,t);let r=[];for(let i=0;i<n.length;i++){let a=n[i].offset,o=i+1<n.length?n[i+1].offset:e.length,s=e.slice(a,o).trim();if(s=`// File: ${t.sourcePath}\n`+s,s.length>this.maxChunkSize){let n=this.splitByLines(s,this.maxChunkSize),i=this.getLineNumber(e,a);for(let e of n){let n=e.split(`
2
2
  `).length;r.push({text:e,sourcePath:t.sourcePath,contentType:t.contentType,chunkIndex:r.length,totalChunks:0,startLine:i,endLine:i+n-1}),i+=n}}else{let n=this.getLineNumber(e,a);r.push({text:s,sourcePath:t.sourcePath,contentType:t.contentType,chunkIndex:r.length,totalChunks:0,startLine:n,endLine:n+s.split(`
3
3
  `).length-1})}}if(n[0].offset>0){let i=e.slice(0,n[0].offset).trim();i.length>0&&r.unshift({text:`// File: ${t.sourcePath}\n${i}`,sourcePath:t.sourcePath,contentType:t.contentType,chunkIndex:0,totalChunks:0,startLine:1,endLine:this.getLineNumber(e,n[0].offset)-1})}return r.map((e,t)=>({...e,chunkIndex:t,totalChunks:r.length}))}findDeclarationBoundaries(e){let t=/^(?:export\s+)?(?:default\s+)?(?:async\s+)?(?:function|class|interface|type|const|enum|abstract\s+class)\s+(\w+)/gm,n=[],r;for(;(r=t.exec(e))!==null;){let t=e.lastIndexOf(`
4
4
  `,r.index-1)+1,i=t,a=e.slice(0,t).split(`
@@ -8,17 +8,17 @@ import{dirname as e,extname as t,join as n}from"node:path";import{CHUNK_SIZES as
8
8
  `),r=[],i=[],a=0;for(let e of n)a+e.length+1>t&&i.length>0?(r.push(i.join(`
9
9
  `)),i=[e],a=e.length):(i.push(e),a+=e.length+1);return i.length>0&&r.push(i.join(`
10
10
  `)),r}getLineNumber(e,t){return e.slice(0,t).split(`
11
- `).length}},S=class{maxChunkSize;overlap;constructor(e){this.maxChunkSize=e?.maxChunkSize??r.default.max,this.overlap=e?.overlap??r.default.overlap}chunk(e,t){if(e.length<=this.maxChunkSize)return[{text:e,sourcePath:t.sourcePath,contentType:t.contentType,chunkIndex:0,totalChunks:1,startLine:1,endLine:e.split(`
11
+ `).length}},w=class{maxChunkSize;overlap;constructor(e){this.maxChunkSize=e?.maxChunkSize??r.default.max,this.overlap=e?.overlap??r.default.overlap}chunk(e,t){if(e.length<=this.maxChunkSize)return[{text:e,sourcePath:t.sourcePath,contentType:t.contentType,chunkIndex:0,totalChunks:1,startLine:1,endLine:e.split(`
12
12
  `).length}];let n=e.split(`
13
13
  `),r=[],i=[],a=0,o=1;for(let e=0;e<n.length;e++){let s=n[e];if(a+s.length+1>this.maxChunkSize&&i.length>0){r.push({text:i.join(`
14
14
  `),sourcePath:t.sourcePath,contentType:t.contentType,chunkIndex:r.length,totalChunks:0,startLine:o,endLine:o+i.length-1});let e=[],n=0;for(let t=i.length-1;t>=0&&!(n+i[t].length+1>this.overlap);t--)e.unshift(i[t]),n+=i[t].length+1;o=o+i.length-e.length,i=[...e,s],a=n+s.length+1}else i.push(s),a+=s.length+1}return i.length>0&&r.push({text:i.join(`
15
- `),sourcePath:t.sourcePath,contentType:t.contentType,chunkIndex:r.length,totalChunks:0,startLine:o,endLine:o+i.length-1}),r.map((e,t)=>({...e,chunkIndex:t,totalChunks:r.length}))}},C=class{maxChunkSize;minChunkSize;constructor(e){this.maxChunkSize=e?.maxChunkSize??r.markdown.max,this.minChunkSize=e?.minChunkSize??r.markdown.min}chunk(e,t){let n=this.splitByHeadings(e),r=[];for(let e of n){if(e.text.trim().length<this.minChunkSize&&r.length>0){let t=r[r.length-1];t.text+=`\n\n${e.text}`,t.endLine=e.endLine;continue}if(e.text.length>this.maxChunkSize){let n=this.splitByParagraphs(e.text,this.maxChunkSize),i=e.startLine;for(let a of n){let n=a.split(`
15
+ `),sourcePath:t.sourcePath,contentType:t.contentType,chunkIndex:r.length,totalChunks:0,startLine:o,endLine:o+i.length-1}),r.map((e,t)=>({...e,chunkIndex:t,totalChunks:r.length}))}},T=class{maxChunkSize;minChunkSize;constructor(e){this.maxChunkSize=e?.maxChunkSize??r.markdown.max,this.minChunkSize=e?.minChunkSize??r.markdown.min}chunk(e,t){let n=this.splitByHeadings(e),r=[];for(let e of n){if(e.text.trim().length<this.minChunkSize&&r.length>0){let t=r[r.length-1];t.text+=`\n\n${e.text}`,t.endLine=e.endLine;continue}if(e.text.length>this.maxChunkSize){let n=this.splitByParagraphs(e.text,this.maxChunkSize),i=e.startLine;for(let a of n){let n=a.split(`
16
16
  `).length;r.push({text:a,sourcePath:t.sourcePath,contentType:t.contentType,headingPath:e.headingPath,chunkIndex:r.length,totalChunks:0,startLine:i,endLine:i+n-1}),i+=n}}else r.push({text:e.text,sourcePath:t.sourcePath,contentType:t.contentType,headingPath:e.headingPath,chunkIndex:r.length,totalChunks:0,startLine:e.startLine,endLine:e.endLine})}return r.map((e,t)=>({...e,chunkIndex:t,totalChunks:r.length}))}splitByHeadings(e){let t=e.split(`
17
- `),n=[],r=null,i=[],a=!1;for(let e=0;e<t.length;e++){/^```/.test(t[e])&&(a=!a);let o=a?null:t[e].match(/^(#{1,6})\s+(.+)/);if(o){r&&n.push(r);let a=o[1].length,s=o[2].trim();for(;i.length>=a;)i.pop();i.push(`${`#`.repeat(a)} ${s}`),r={text:t[e],headingPath:i.join(` > `),startLine:e+1,endLine:e+1}}else r?(r.text+=`\n${t[e]}`,r.endLine=e+1):r={text:t[e],headingPath:`(intro)`,startLine:e+1,endLine:e+1}}return r&&n.push(r),n}splitByParagraphs(e,t){let n=e.split(/\n\n+/),r=[],i=``;for(let e of n)`${i}\n\n${e}`.length>t&&i.length>0?(r.push(i.trim()),i=e):i=i?`${i}\n\n${e}`:e;return i.trim()&&r.push(i.trim()),r}};const w=new Set([`function_declaration`,`class_declaration`,`interface_declaration`,`type_alias_declaration`,`enum_declaration`,`lexical_declaration`,`variable_declaration`,`export_statement`,`function_definition`,`class_definition`,`decorated_definition`,`class_declaration`,`interface_declaration`,`enum_declaration`,`function_declaration`,`method_declaration`,`type_declaration`,`function_item`,`struct_item`,`enum_item`,`trait_item`,`impl_item`,`const_item`,`static_item`,`type_item`]),T=new Set([`import_statement`,`import_from_statement`,`import_declaration`,`package_declaration`,`use_declaration`,`extern_crate_declaration`,`import_spec`,`package_clause`]);var E=class{maxChunkSize;constructor(e){this.maxChunkSize=e?.maxChunkSize??r.code.max}chunk(e,t){let n=h.get();if(!n)return this.singleChunk(e,t);let r=this.extractExt(t.sourcePath),i=n.getLanguage(r);if(!i)return this.singleChunk(e,t);let a=n.getParser();if(!a)return this.singleChunk(e,t);a.setLanguage(i);let o=a.parse(e);if(!o)return this.singleChunk(e,t);let s=this.findAstBoundaries(o.rootNode,e);return s.length===0?this.singleChunk(e,t):this.buildChunks(s,e,t)}findAstBoundaries(e,t){let n=[];for(let t of e.children){if(!t.isNamed)continue;let e=w.has(t.type),r=T.has(t.type);(e||r)&&n.push({startOffset:t.startIndex,endOffset:t.endIndex,startLine:t.startPosition.row+1,endLine:t.endPosition.row+1,isPreamble:r})}return n}buildChunks(e,t,n){let r=[],i=null,a=0,o=0;for(let s of e){if(s.isPreamble){i===null&&(i=s.startLine),a=s.endOffset,o=s.endLine;continue}if(i!==null){let e=t.slice(0,a).trim();e.length>0&&r.push({text:`// File: ${n.sourcePath}\n${e}`,sourcePath:n.sourcePath,contentType:n.contentType,chunkIndex:0,totalChunks:0,startLine:i,endLine:o}),i=null}let e=t.slice(s.startOffset,s.endOffset).trim();if(e=`// File: ${n.sourcePath}\n`+e,e.length>this.maxChunkSize){let t=this.splitByLines(e,this.maxChunkSize),i=s.startLine;for(let e of t){let t=e.split(`
17
+ `),n=[],r=null,i=[],a=!1;for(let e=0;e<t.length;e++){/^```/.test(t[e])&&(a=!a);let o=a?null:t[e].match(/^(#{1,6})\s+(.+)/);if(o){r&&n.push(r);let a=o[1].length,s=o[2].trim();for(;i.length>=a;)i.pop();i.push(`${`#`.repeat(a)} ${s}`),r={text:t[e],headingPath:i.join(` > `),startLine:e+1,endLine:e+1}}else r?(r.text+=`\n${t[e]}`,r.endLine=e+1):r={text:t[e],headingPath:`(intro)`,startLine:e+1,endLine:e+1}}return r&&n.push(r),n}splitByParagraphs(e,t){let n=e.split(/\n\n+/),r=[],i=``;for(let e of n)`${i}\n\n${e}`.length>t&&i.length>0?(r.push(i.trim()),i=e):i=i?`${i}\n\n${e}`:e;return i.trim()&&r.push(i.trim()),r}};const E=new Set([`function_declaration`,`class_declaration`,`interface_declaration`,`type_alias_declaration`,`enum_declaration`,`lexical_declaration`,`variable_declaration`,`export_statement`,`function_definition`,`class_definition`,`decorated_definition`,`class_declaration`,`interface_declaration`,`enum_declaration`,`function_declaration`,`method_declaration`,`type_declaration`,`function_item`,`struct_item`,`enum_item`,`trait_item`,`impl_item`,`const_item`,`static_item`,`type_item`]),ne=new Set([`import_statement`,`import_from_statement`,`import_declaration`,`package_declaration`,`use_declaration`,`extern_crate_declaration`,`import_spec`,`package_clause`]);var D=class{maxChunkSize;constructor(e){this.maxChunkSize=e?.maxChunkSize??r.code.max}chunk(e,t){let n=_.get();if(!n)return this.singleChunk(e,t);let r=this.extractExt(t.sourcePath),i=n.getLanguage(r);if(!i)return this.singleChunk(e,t);let a=n.getParser();if(!a)return this.singleChunk(e,t);a.setLanguage(i);let o=a.parse(e);if(!o)return this.singleChunk(e,t);let s=this.findAstBoundaries(o.rootNode,e);return s.length===0?this.singleChunk(e,t):this.buildChunks(s,e,t)}findAstBoundaries(e,t){let n=[];for(let t of e.children){if(!t.isNamed)continue;let e=E.has(t.type),r=ne.has(t.type);(e||r)&&n.push({startOffset:t.startIndex,endOffset:t.endIndex,startLine:t.startPosition.row+1,endLine:t.endPosition.row+1,isPreamble:r})}return n}buildChunks(e,t,n){let r=[],i=null,a=0,o=0;for(let s of e){if(s.isPreamble){i===null&&(i=s.startLine),a=s.endOffset,o=s.endLine;continue}if(i!==null){let e=t.slice(0,a).trim();e.length>0&&r.push({text:`// File: ${n.sourcePath}\n${e}`,sourcePath:n.sourcePath,contentType:n.contentType,chunkIndex:0,totalChunks:0,startLine:i,endLine:o}),i=null}let e=t.slice(s.startOffset,s.endOffset).trim();if(e=`// File: ${n.sourcePath}\n`+e,e.length>this.maxChunkSize){let t=this.splitByLines(e,this.maxChunkSize),i=s.startLine;for(let e of t){let t=e.split(`
18
18
  `).length;r.push({text:e,sourcePath:n.sourcePath,contentType:n.contentType,chunkIndex:0,totalChunks:0,startLine:i,endLine:i+t-1}),i+=t}}else r.push({text:e,sourcePath:n.sourcePath,contentType:n.contentType,chunkIndex:0,totalChunks:0,startLine:s.startLine,endLine:s.endLine})}if(i!==null){let e=t.slice(0,a).trim();e.length>0&&r.push({text:`// File: ${n.sourcePath}\n${e}`,sourcePath:n.sourcePath,contentType:n.contentType,chunkIndex:0,totalChunks:0,startLine:i,endLine:o})}return r.map((e,t)=>({...e,chunkIndex:t,totalChunks:r.length}))}splitByLines(e,t){let n=e.split(`
19
19
  `),r=[],i=[],a=0;for(let e of n)a+e.length+1>t&&i.length>0&&(r.push(i.join(`
20
20
  `)),i=[],a=0),i.push(e),a+=e.length+1;return i.length>0&&r.push(i.join(`
21
21
  `)),r}extractExt(e){let t=e.lastIndexOf(`.`);return t>=0?e.slice(t).toLowerCase():``}singleChunk(e,t){return[{text:`// File: ${t.sourcePath}\n${e}`,sourcePath:t.sourcePath,contentType:t.contentType,chunkIndex:0,totalChunks:1,startLine:1,endLine:e.split(`
22
- `).length}]}};async function ne(e){let t=e.toLowerCase();switch(t){case`.md`:case`.mdx`:return new C;case`.ts`:case`.tsx`:case`.mts`:case`.cts`:case`.js`:case`.jsx`:case`.mjs`:case`.cjs`:case`.py`:case`.go`:case`.rs`:case`.java`:if(u.has(t)){let e=await h.initialize();if(e)return await e.loadLanguage(t),new E}return new x;default:return new S}}function re(e){let t=e.toLowerCase();switch(t){case`.md`:case`.mdx`:return new C;case`.ts`:case`.tsx`:case`.mts`:case`.cts`:case`.js`:case`.jsx`:case`.mjs`:case`.cjs`:case`.py`:case`.go`:case`.rs`:case`.java`:return h.get()?.isLanguageLoaded(t)?new E:new x;default:return new S}}const D=i(`query-executor`),O=e(s(import.meta.url));function k(){let e=n(O,`..`,`queries`);if(a(e))return e;let t=n(O,`..`,`..`,`src`,`queries`);return a(t)?t:e}const A=k(),j={".ts":`typescript`,".tsx":`typescript`,".mts":`typescript`,".cts":`typescript`,".js":`javascript`,".jsx":`javascript`,".mjs":`javascript`,".cjs":`javascript`,".py":`python`,".go":`go`,".rs":`rust`,".java":`java`};var M=class{queryCache=new Map;scmCache=new Map;execute(e,t,n,r){let i=this.getOrCompile(t,n,r);return i?i.matches(e).map(e=>N(e)):[]}executeCaptures(e,t,n,r){let i=this.getOrCompile(t,n,r);return i?i.captures(e).map(e=>P(e)):[]}executeRaw(e,t,n){return t.query(n).matches(e).map(e=>N(e))}getOrCompile(e,t,n){let r=j[t];if(!r)return null;let i=`${r}:${n}`,a=this.queryCache.get(i);if(a)return a;let o=this.loadScm(r,n);if(!o)return null;try{let t=e.query(o);return this.queryCache.set(i,t),t}catch(e){throw D.warn(`Failed to compile query`,{langDir:r,queryType:n,error:String(e)}),Error(`Failed to compile ${r}/${n}.scm: ${String(e)}`)}}loadScm(e,t){let r=`${e}:${t}`,i=this.scmCache.get(r);if(i!==void 0)return i;let a=n(A,e,`${t}.scm`);try{let e=o(a,`utf-8`);return this.scmCache.set(r,e),e}catch{return D.info(`Query file not found (graceful skip)`,{langDir:e,queryType:t}),null}}dispose(){this.queryCache.clear(),this.scmCache.clear()}static resolveQueryDir(e){return n(A,e)}};function N(e){let t=new Map;for(let n of e.captures)t.set(n.name,P(n));return{pattern:e.pattern,captures:t}}function P(e){let{node:t}=e;return{name:e.name,text:t.text,nodeType:t.type,startLine:t.startPosition.row,endLine:t.endPosition.row,startColumn:t.startPosition.column,endColumn:t.endPosition.column,node:t}}const F=new M,I=new Set([`function_declaration`,`method_definition`,`arrow_function`,`function_definition`,`method_declaration`,`constructor_declaration`,`function_declaration`,`method_declaration`,`function_item`]);async function L(e,t,n=``){let r=await h.ensure(),i=await r.parse(e,t);if(!i)return[];let a=r.getLanguage(t);return a?F.execute(i.rootNode,a,t,`calls`).map(e=>R(e,i.rootNode,n)).filter(e=>e!==null):[]}function R(e,t,n){let r=e.captures.get(`callee`);if(!r)return null;let i=e.captures.get(`node`);return{callerFile:n,callerName:z(i?.node??r.node),calleeName:r.text,line:(i?.startLine??r.startLine)+1}}function z(e){let t=e.parent;for(;t;){if(I.has(t.type)){let e=B(t);if(e)return e}t=t.parent}return`<module>`}function B(e){let t=e.childForFieldName(`name`);if(t)return t.text;for(let t of e.children)if(t.type===`identifier`||t.type===`property_identifier`||t.type===`field_identifier`)return t.text;return null}const V=new M,H={handler:`lambda-handler`,lambdaHandler:`lambda-handler`,main:`main`,__name__:`main`,app:`server`,server:`server`,router:`server`,urlpatterns:`server`,init:`main`},U={SpringBootApplication:`server`,RestController:`server`,Controller:`server`};async function W(e,t,n=``){let r=await h.ensure(),i=await r.parse(e,t);if(!i)return[];let a=r.getLanguage(t);if(!a)return[];let o=V.execute(i.rootNode,a,t,`entry-points`),s=[],c=new Set;for(let e of o){let r=G(e,t,n);if(r){let e=`${r.name}:${r.type}`;c.has(e)||(c.add(e),s.push(r))}}return s}function G(e,t,n){let r=e.captures.get(`name`);if(!r)return null;let i=r.text,a=e.captures.get(`_parent`);if(a){let e=a.text;if([`Construct`,`Stack`,`NestedStack`,`Stage`].includes(e))return{name:i,type:`cdk-construct`,filePath:n}}let o=e.captures.get(`_ann`);if(o){let e=U[o.text];if(e)return{name:i,type:e,filePath:n}}let s=H[i];return s?{name:i,type:s,filePath:n}:t===`.go`&&i.toLowerCase().startsWith(`handle`)?{name:i,type:`server`,filePath:n,trigger:`HTTP handler`}:{name:i,type:`main`,filePath:n}}const K=new M;async function q(e,t,n=``){let r=await h.ensure(),i=await r.parse(e,t);if(!i)return[];let a=r.getLanguage(t);if(!a)return[];let o=K.execute(i.rootNode,a,t,`imports`),s=[];for(let e of o){let r=e.captures.get(`source`);if(!r){let r=e.captures.get(`node`);if(r){let e=ie(r.text,t);e&&s.push({source:e.source,specifiers:e.specifiers,filePath:n,isExternal:Y(e.source,t),confidence:`high`})}continue}let i=r.text,a=J(i,t),o=X(e.captures.get(`node`)?.text??``,t,a);s.push({source:a,specifiers:o,filePath:n,isExternal:Y(a,t),confidence:`high`})}return s}function J(e,t){let n=e.replace(/^['"`]|['"`]$/g,``);return t===`.go`&&(n=n.replace(/^"|"$/g,``)),n}function Y(e,t){return t===`.py`?!e.startsWith(`.`):t===`.go`?e.includes(`/`)||e.includes(`.`):t===`.java`?!0:t===`.rs`?!e.startsWith(`self`)&&!e.startsWith(`super`)&&!e.startsWith(`crate`):!e.startsWith(`.`)&&!e.startsWith(`/`)}function X(e,t,n){if(!e)return[n];if(t===`.py`){let t=e.match(/import\s+(.+)$/m);return t?t[1].split(`,`).map(e=>e.trim().split(/\s+as\s+/)[0].trim()).filter(Boolean):[n]}if(t===`.java`){let e=n.split(`.`);return[e[e.length-1]]}if(t===`.go`){let e=n.split(`/`);return[e[e.length-1]]}if(t===`.rs`){if(n.includes(`{`)){let e=n.match(/\{([^}]+)\}/);if(e)return e[1].split(`,`).map(e=>e.trim()).filter(Boolean)}let e=n.split(`::`);return[e[e.length-1]]}let r=e.match(/\{([^}]+)\}/);if(r)return r[1].split(`,`).map(e=>e.trim().split(/\s+as\s+/)[0].trim()).filter(Boolean);let i=e.match(/import\s+(\w+)/);return i?[i[1]]:[n]}function ie(e,t){if(t===`.py`){let t=e.match(/^import\s+([\w.]+)/);if(t)return{source:t[1],specifiers:[t[1]]}}return null}const ae=new M;async function oe(e,t,n=``){let r=await h.ensure(),i=await r.parse(e,t);if(!i)return[];let a=r.getLanguage(t);if(!a)return[];let o=ae.execute(i.rootNode,a,t,`patterns`),s=new Map;for(let e of o){let r=se(e,t);if(!r)continue;let i=e.captures.get(`name`),a=`${n}:${(e.captures.get(`node`)?.startLine??i?.startLine??0)+1}`,o=s.get(r.pattern);o?o.locations.push(a):s.set(r.pattern,{description:r.description,locations:[a]})}let c=[];for(let[e,{description:t,locations:n}]of s)c.push({pattern:e,description:t,locations:n,confidence:`high`});return c}function se(e,t){let n=e.captures.get(`name`)?.text;if(!n)return null;let r=e.captures.get(`node`)?.nodeType??``;if(/^(create|build)[A-Z]/.test(n)||/^(of|from|new)[A-Z]/.test(n))return{pattern:`factory`,description:`Factory function/method`};if(/^(register|bind)$/.test(n))return{pattern:`dependency-injection`,description:`DI container registration`};if(/^(Injectable|Component|Service|Controller|Module|Singleton|Repository|Bean)$/.test(n))return{pattern:`dependency-injection`,description:`Framework DI annotation`};if(/^(Map|WeakMap|Set)$/.test(n))return{pattern:`cached-instance`,description:`Cached Map/Set instance`};if(t===`.py`){if(n===`__new__`)return{pattern:`singleton`,description:`Singleton pattern (__new__ override)`};if(n===`__enter__`)return{pattern:`context-manager`,description:`Context manager pattern`};if(r===`decorated_definition`)return{pattern:`decorator`,description:`Decorator usage`}}if(t===`.go`){if(r===`type_declaration`)return{pattern:`interface`,description:`Interface definition`};if(r===`go_statement`)return{pattern:`concurrency`,description:`Goroutine concurrency pattern`};if(n===`make`)return{pattern:`concurrency`,description:`Channel/make pattern`}}if(t===`.rs`){if(r===`impl_item`)return{pattern:`trait-impl`,description:`Trait implementation`};if(r===`attribute_item`){if(n===`derive`)return{pattern:`derive`,description:`Derive macro attribute`};if(n===`test`)return{pattern:`test`,description:`Test attribute`}}}if(t===`.java`){if(r===`class_declaration`)return{pattern:`singleton`,description:`Singleton pattern (private constructor)`};if(r===`marker_annotation`)return{pattern:`dependency-injection`,description:`Framework DI annotation`}}if(/\.(ts|tsx|mts|cts|js|jsx|mjs|cjs)$/.test(t)){if(r===`class_declaration`)return{pattern:`singleton`,description:`Singleton pattern (private constructor)`};if(r===`decorator`)return{pattern:`decorator`,description:`Framework decorator pattern`}}return{pattern:r||`unknown`,description:`Detected pattern: ${n}`}}const ce=new Set([`function_declaration`,`method_definition`,`arrow_function`,`class_declaration`,`function_definition`,`class_definition`,`method_declaration`,`constructor_declaration`,`class_declaration`,`function_declaration`,`method_declaration`,`function_item`,`impl_item`]);async function le(e,t,n){let r=await(await h.ensure()).parse(e,t);if(!r)return[{name:`<module>`,type:`module`,line:1}];let i=ue(r.rootNode,n-1);if(!i)return[{name:`<module>`,type:`module`,line:1}];let a=[];return de(i,a),a.push({name:`<module>`,type:`module`,line:1}),a}function ue(e,t){let n=null;function r(e){if(e.startPosition.row<=t&&e.endPosition.row>=t){n=e;for(let t of e.children)r(t)}}return r(e),n}function de(e,t){let n=e.parent;for(;n;){if(ce.has(n.type)){let e=fe(n),r=pe(n.type);t.push({name:e??`<anonymous>`,type:r,line:n.startPosition.row+1})}n=n.parent}}function fe(e){let t=e.childForFieldName(`name`);if(t)return t.text;for(let t of e.children)if(t.type===`identifier`||t.type===`type_identifier`||t.type===`property_identifier`||t.type===`field_identifier`)return t.text;return null}function pe(e){return e.includes(`class`)||e===`impl_item`?`class`:`function`}const me=new M,he={function_declaration:`function`,class_declaration:`class`,interface_declaration:`interface`,type_alias_declaration:`type`,enum_declaration:`enum`,lexical_declaration:`const`,method_definition:`method`,public_field_definition:`variable`,field_definition:`variable`,function_definition:`function`,class_definition:`class`,expression_statement:`variable`,method_declaration:`method`,constructor_declaration:`method`,field_declaration:`variable`,type_spec:`type`,type_declaration:`type`,const_spec:`const`,var_spec:`variable`,function_item:`function`,struct_item:`class`,enum_item:`enum`,trait_item:`interface`,impl_item:`type`,const_item:`const`,static_item:`variable`,type_item:`type`};async function ge(e,t,n=``){let r=await h.ensure(),i=await r.parse(e,t);if(!i)return[];let a=r.getLanguage(t);return a?_e(me.execute(i.rootNode,a,t,`symbols`),t,n):[]}function _e(e,t,n){let r=new Map;for(let n of e){let e=n.captures.get(`name`);if(!e)continue;let i=`${e.text}:${(n.captures.get(`node`)?.startLine??e.startLine)+1}`,a=ve(n,t),o=r.get(i);(!o||!o.exported&&a)&&r.set(i,{match:n,exported:a})}let i=[];for(let{match:e,exported:a}of r.values()){let r=e.captures.get(`name`),o=e.captures.get(`node`);if(!r)continue;let s=he[o?.nodeType??r.nodeType]??`variable`,c=(o?.startLine??r.startLine)+1,l=ye(s,o?.node,t),u=o?.node??r.node;i.push({name:r.text,kind:l,exported:a,filePath:n,line:c,signature:be(o?.node,l),returnType:$(o?.node,l),jsdoc:we(u),decorators:Te(u),typeBody:Ee(o?.node,l)})}return i}function ve(e,t){if(e.captures.has(`exported`))return!0;let n=e.captures.get(`name`)?.text;if(!n)return!1;if(t===`.py`)return!n.startsWith(`_`);if(t===`.go`)return/^[A-Z]/.test(n);if(t===`.java`){let t=e.captures.get(`node`)?.text??``;return/\bpublic\b/.test(t)}return!1}function ye(e,t,n){if(n===`.go`&&e===`type`&&t?.children){let e=t.type===`type_declaration`?t.children.flatMap(e=>e.children??[]):t.children;for(let t of e){if(t.type===`interface_type`)return`interface`;if(t.type===`struct_type`)return`class`}}return e}function be(e,t){if(e){if(t===`function`||t===`method`)return xe(e);if(t===`class`)return Se(e);if(t===`interface`)return Ce(e)}}function xe(e){let t=e.childForFieldName(`parameters`)??e.childForFieldName(`parameter_list`),n=e.childForFieldName(`return_type`)??e.childForFieldName(`type`),r=e.childForFieldName(`result`);if(!t){for(let t of e.children)if(t.type===`formal_parameters`||t.type===`parameter_list`||t.type===`parameters`){let e=t.text;return n&&(e+=n.text),r&&(e+=` ${r.text}`),e.length>120?`${e.slice(0,117)}...`:e}return}let i=t.text;return n&&(i+=n.text),r&&(i+=` ${r.text}`),i.length>120?`${i.slice(0,117)}...`:i}function Se(e){let t=e.childForFieldName(`body`)??e.childForFieldName(`field_declaration_list`);if(!t){for(let t of e.children)if(t.type===`struct_type`||t.type===`class_body`)return Z(t);return}return Z(t)}function Z(e){let t=[];for(let n of e.children){if(n.type===`method_definition`){let e=n.childForFieldName(`name`);e&&t.push(e.text)}if(n.type===`method_declaration`){let e=n.childForFieldName(`name`);e&&t.push(e.text)}if(n.type===`field_declaration`){let e=n.childForFieldName(`name`);e&&t.push(e.text)}if(n.type===`function_definition`){let e=n.childForFieldName(`name`);e&&t.push(e.text)}}if(t.length===0)return;let n=t.join(`, `);return n.length>120?`${n.slice(0,117)}...`:n}function Ce(e){let t=e.childForFieldName(`body`);if(!t){for(let t of e.children)if(t.type===`interface_type`)return Q(t);return}return Q(t)}function Q(e){let t=[];for(let n of e.children){if(n.type===`property_signature`||n.type===`method_signature`){let e=n.childForFieldName(`name`);e&&t.push(e.text)}if(n.type===`method_declaration`){let e=n.childForFieldName(`name`);e&&t.push(e.text)}if(n.type===`method_spec`){let e=n.childForFieldName(`name`);e&&t.push(e.text)}if(n.type===`function_signature_item`||n.type===`declaration_list`){let e=n.childForFieldName(`name`);e&&t.push(e.text)}}if(t.length===0)return;let n=t.join(`, `);return n.length>120?`${n.slice(0,117)}...`:n}function $(e,t){if(!e||t!==`function`&&t!==`method`)return;let n=e.childForFieldName(`return_type`)??e.childForFieldName(`type`);if(n){let e=n.text.replace(/^:\s*/,``).trim();return e.length>200?`${e.slice(0,200)}…`:e}let r=e.childForFieldName(`result`);if(r)return r.text.trim()}function we(e){let t=e.parent;if(!t?.children)return;let n=t.children.indexOf(e);if(n<=0)return;let r=t.children[n-1];if(r){if(r.type===`comment`||r.type===`block_comment`||r.type===`doc_comment`)return r.text.replace(/^\/\*\*?\s*|\s*\*\/$/g,``).split(`
22
+ `).length}]}};async function re(e){let t=e.toLowerCase();switch(t){case`.md`:case`.mdx`:return new T;case`.ts`:case`.tsx`:case`.mts`:case`.cts`:case`.js`:case`.jsx`:case`.mjs`:case`.cjs`:case`.py`:case`.go`:case`.rs`:case`.java`:if(f.has(t)){let e=await _.initialize();if(e)return await e.loadLanguage(t),new D}return new C;default:return new w}}function ie(e){let t=e.toLowerCase();switch(t){case`.md`:case`.mdx`:return new T;case`.ts`:case`.tsx`:case`.mts`:case`.cts`:case`.js`:case`.jsx`:case`.mjs`:case`.cjs`:case`.py`:case`.go`:case`.rs`:case`.java`:return _.get()?.isLanguageLoaded(t)?new D:new C;default:return new w}}const O=i(`query-executor`),k=e(s(import.meta.url));function A(){let e=n(k,`..`,`queries`);if(a(e))return e;let t=n(k,`..`,`..`,`src`,`queries`);return a(t)?t:e}const j=A(),M={".ts":`typescript`,".tsx":`typescript`,".mts":`typescript`,".cts":`typescript`,".js":`javascript`,".jsx":`javascript`,".mjs":`javascript`,".cjs":`javascript`,".py":`python`,".go":`go`,".rs":`rust`,".java":`java`};var N=class{queryCache=new Map;scmCache=new Map;execute(e,t,n,r){let i=this.getOrCompile(t,n,r);return i?i.matches(e).map(e=>P(e)):[]}executeCaptures(e,t,n,r){let i=this.getOrCompile(t,n,r);return i?i.captures(e).map(e=>F(e)):[]}executeRaw(e,t,n){return t.query(n).matches(e).map(e=>P(e))}getOrCompile(e,t,n){let r=M[t];if(!r)return null;let i=`${r}:${n}`,a=this.queryCache.get(i);if(a)return a;let o=this.loadScm(r,n);if(!o)return null;try{let t=e.query(o);return this.queryCache.set(i,t),t}catch(e){throw O.warn(`Failed to compile query`,{langDir:r,queryType:n,error:String(e)}),Error(`Failed to compile ${r}/${n}.scm: ${String(e)}`)}}loadScm(e,t){let r=`${e}:${t}`,i=this.scmCache.get(r);if(i!==void 0)return i;let a=n(j,e,`${t}.scm`);try{let e=o(a,`utf-8`);return this.scmCache.set(r,e),e}catch{return O.info(`Query file not found (graceful skip)`,{langDir:e,queryType:t}),null}}dispose(){this.queryCache.clear(),this.scmCache.clear()}static resolveQueryDir(e){return n(j,e)}};function P(e){let t=new Map;for(let n of e.captures)t.set(n.name,F(n));return{pattern:e.pattern,captures:t}}function F(e){let{node:t}=e;return{name:e.name,text:t.text,nodeType:t.type,startLine:t.startPosition.row,endLine:t.endPosition.row,startColumn:t.startPosition.column,endColumn:t.endPosition.column,node:t}}const I=new N,L=new Set([`function_declaration`,`method_definition`,`arrow_function`,`function_definition`,`method_declaration`,`constructor_declaration`,`function_declaration`,`method_declaration`,`function_item`]);async function R(e,t,n=``){let r=await _.ensure(),i=await r.parse(e,t);if(!i)return[];let a=r.getLanguage(t);return a?I.execute(i.rootNode,a,t,`calls`).map(e=>z(e,i.rootNode,n)).filter(e=>e!==null):[]}function z(e,t,n){let r=e.captures.get(`callee`);if(!r)return null;let i=e.captures.get(`node`);return{callerFile:n,callerName:B(i?.node??r.node),calleeName:r.text,line:(i?.startLine??r.startLine)+1}}function B(e){let t=e.parent;for(;t;){if(L.has(t.type)){let e=V(t);if(e)return e}t=t.parent}return`<module>`}function V(e){let t=e.childForFieldName(`name`);if(t)return t.text;for(let t of e.children)if(t.type===`identifier`||t.type===`property_identifier`||t.type===`field_identifier`)return t.text;return null}const H=new N,U={handler:`lambda-handler`,lambdaHandler:`lambda-handler`,main:`main`,__name__:`main`,app:`server`,server:`server`,router:`server`,urlpatterns:`server`,init:`main`},W={SpringBootApplication:`server`,RestController:`server`,Controller:`server`};async function G(e,t,n=``){let r=await _.ensure(),i=await r.parse(e,t);if(!i)return[];let a=r.getLanguage(t);if(!a)return[];let o=H.execute(i.rootNode,a,t,`entry-points`),s=[],c=new Set;for(let e of o){let r=K(e,t,n);if(r){let e=`${r.name}:${r.type}`;c.has(e)||(c.add(e),s.push(r))}}return s}function K(e,t,n){let r=e.captures.get(`name`);if(!r)return null;let i=r.text,a=e.captures.get(`_parent`);if(a){let e=a.text;if([`Construct`,`Stack`,`NestedStack`,`Stage`].includes(e))return{name:i,type:`cdk-construct`,filePath:n}}let o=e.captures.get(`_ann`);if(o){let e=W[o.text];if(e)return{name:i,type:e,filePath:n}}let s=U[i];return s?{name:i,type:s,filePath:n}:t===`.go`&&i.toLowerCase().startsWith(`handle`)?{name:i,type:`server`,filePath:n,trigger:`HTTP handler`}:{name:i,type:`main`,filePath:n}}const q=new N;async function J(e,t,n=``){let r=await _.ensure(),i=await r.parse(e,t);if(!i)return[];let a=r.getLanguage(t);if(!a)return[];let o=q.execute(i.rootNode,a,t,`imports`),s=[];for(let e of o){let r=e.captures.get(`source`);if(!r){let r=e.captures.get(`node`);if(r){let e=oe(r.text,t);e&&s.push({source:e.source,specifiers:e.specifiers,filePath:n,isExternal:X(e.source,t),confidence:`high`})}continue}let i=r.text,a=Y(i,t),o=ae(e.captures.get(`node`)?.text??``,t,a);s.push({source:a,specifiers:o,filePath:n,isExternal:X(a,t),confidence:`high`})}return s}function Y(e,t){let n=e.replace(/^['"`]|['"`]$/g,``);return t===`.go`&&(n=n.replace(/^"|"$/g,``)),n}function X(e,t){return t===`.py`?!e.startsWith(`.`):t===`.go`?e.includes(`/`)||e.includes(`.`):t===`.java`?!0:t===`.rs`?!e.startsWith(`self`)&&!e.startsWith(`super`)&&!e.startsWith(`crate`):!e.startsWith(`.`)&&!e.startsWith(`/`)}function ae(e,t,n){if(!e)return[n];if(t===`.py`){let t=e.match(/import\s+(.+)$/m);return t?t[1].split(`,`).map(e=>e.trim().split(/\s+as\s+/)[0].trim()).filter(Boolean):[n]}if(t===`.java`){let e=n.split(`.`);return[e[e.length-1]]}if(t===`.go`){let e=n.split(`/`);return[e[e.length-1]]}if(t===`.rs`){if(n.includes(`{`)){let e=n.match(/\{([^}]+)\}/);if(e)return e[1].split(`,`).map(e=>e.trim()).filter(Boolean)}let e=n.split(`::`);return[e[e.length-1]]}let r=e.match(/\{([^}]+)\}/);if(r)return r[1].split(`,`).map(e=>e.trim().split(/\s+as\s+/)[0].trim()).filter(Boolean);let i=e.match(/import\s+(\w+)/);return i?[i[1]]:[n]}function oe(e,t){if(t===`.py`){let t=e.match(/^import\s+([\w.]+)/);if(t)return{source:t[1],specifiers:[t[1]]}}return null}const se=new N;async function ce(e,t,n=``){let r=await _.ensure(),i=await r.parse(e,t);if(!i)return[];let a=r.getLanguage(t);if(!a)return[];let o=se.execute(i.rootNode,a,t,`patterns`),s=new Map;for(let e of o){let r=le(e,t);if(!r)continue;let i=e.captures.get(`name`),a=`${n}:${(e.captures.get(`node`)?.startLine??i?.startLine??0)+1}`,o=s.get(r.pattern);o?o.locations.push(a):s.set(r.pattern,{description:r.description,locations:[a]})}let c=[];for(let[e,{description:t,locations:n}]of s)c.push({pattern:e,description:t,locations:n,confidence:`high`});return c}function le(e,t){let n=e.captures.get(`name`)?.text;if(!n)return null;let r=e.captures.get(`node`)?.nodeType??``;if(/^(create|build)[A-Z]/.test(n)||/^(of|from|new)[A-Z]/.test(n))return{pattern:`factory`,description:`Factory function/method`};if(/^(register|bind)$/.test(n))return{pattern:`dependency-injection`,description:`DI container registration`};if(/^(Injectable|Component|Service|Controller|Module|Singleton|Repository|Bean)$/.test(n))return{pattern:`dependency-injection`,description:`Framework DI annotation`};if(/^(Map|WeakMap|Set)$/.test(n))return{pattern:`cached-instance`,description:`Cached Map/Set instance`};if(t===`.py`){if(n===`__new__`)return{pattern:`singleton`,description:`Singleton pattern (__new__ override)`};if(n===`__enter__`)return{pattern:`context-manager`,description:`Context manager pattern`};if(r===`decorated_definition`)return{pattern:`decorator`,description:`Decorator usage`}}if(t===`.go`){if(r===`type_declaration`)return{pattern:`interface`,description:`Interface definition`};if(r===`go_statement`)return{pattern:`concurrency`,description:`Goroutine concurrency pattern`};if(n===`make`)return{pattern:`concurrency`,description:`Channel/make pattern`}}if(t===`.rs`){if(r===`impl_item`)return{pattern:`trait-impl`,description:`Trait implementation`};if(r===`attribute_item`){if(n===`derive`)return{pattern:`derive`,description:`Derive macro attribute`};if(n===`test`)return{pattern:`test`,description:`Test attribute`}}}if(t===`.java`){if(r===`class_declaration`)return{pattern:`singleton`,description:`Singleton pattern (private constructor)`};if(r===`marker_annotation`)return{pattern:`dependency-injection`,description:`Framework DI annotation`}}if(/\.(ts|tsx|mts|cts|js|jsx|mjs|cjs)$/.test(t)){if(r===`class_declaration`)return{pattern:`singleton`,description:`Singleton pattern (private constructor)`};if(r===`decorator`)return{pattern:`decorator`,description:`Framework decorator pattern`}}return{pattern:r||`unknown`,description:`Detected pattern: ${n}`}}const ue=new Set([`function_declaration`,`method_definition`,`arrow_function`,`class_declaration`,`function_definition`,`class_definition`,`method_declaration`,`constructor_declaration`,`class_declaration`,`function_declaration`,`method_declaration`,`function_item`,`impl_item`]);async function de(e,t,n){let r=await(await _.ensure()).parse(e,t);if(!r)return[{name:`<module>`,type:`module`,line:1}];let i=fe(r.rootNode,n-1);if(!i)return[{name:`<module>`,type:`module`,line:1}];let a=[];return pe(i,a),a.push({name:`<module>`,type:`module`,line:1}),a}function fe(e,t){let n=null;function r(e){if(e.startPosition.row<=t&&e.endPosition.row>=t){n=e;for(let t of e.children)r(t)}}return r(e),n}function pe(e,t){let n=e.parent;for(;n;){if(ue.has(n.type)){let e=me(n),r=he(n.type);t.push({name:e??`<anonymous>`,type:r,line:n.startPosition.row+1})}n=n.parent}}function me(e){let t=e.childForFieldName(`name`);if(t)return t.text;for(let t of e.children)if(t.type===`identifier`||t.type===`type_identifier`||t.type===`property_identifier`||t.type===`field_identifier`)return t.text;return null}function he(e){return e.includes(`class`)||e===`impl_item`?`class`:`function`}const ge=new N,_e={function_declaration:`function`,class_declaration:`class`,interface_declaration:`interface`,type_alias_declaration:`type`,enum_declaration:`enum`,lexical_declaration:`const`,method_definition:`method`,public_field_definition:`variable`,field_definition:`variable`,function_definition:`function`,class_definition:`class`,expression_statement:`variable`,method_declaration:`method`,constructor_declaration:`method`,field_declaration:`variable`,type_spec:`type`,type_declaration:`type`,const_spec:`const`,var_spec:`variable`,function_item:`function`,struct_item:`class`,enum_item:`enum`,trait_item:`interface`,impl_item:`type`,const_item:`const`,static_item:`variable`,type_item:`type`};async function ve(e,t,n=``){let r=await _.ensure(),i=await r.parse(e,t);if(!i)return[];let a=r.getLanguage(t);return a?ye(ge.execute(i.rootNode,a,t,`symbols`),t,n):[]}function ye(e,t,n){let r=new Map;for(let n of e){let e=n.captures.get(`name`);if(!e)continue;let i=`${e.text}:${(n.captures.get(`node`)?.startLine??e.startLine)+1}`,a=be(n,t),o=r.get(i);(!o||!o.exported&&a)&&r.set(i,{match:n,exported:a})}let i=[];for(let{match:e,exported:a}of r.values()){let r=e.captures.get(`name`),o=e.captures.get(`node`);if(!r)continue;let s=_e[o?.nodeType??r.nodeType]??`variable`,c=(o?.startLine??r.startLine)+1,l=xe(s,o?.node,t),u=o?.node??r.node;i.push({name:r.text,kind:l,exported:a,filePath:n,line:c,signature:Se(o?.node,l),returnType:Te(o?.node,l),jsdoc:Ee(u),decorators:De(u),typeBody:Oe(o?.node,l)})}return i}function be(e,t){if(e.captures.has(`exported`))return!0;let n=e.captures.get(`name`)?.text;if(!n)return!1;if(t===`.py`)return!n.startsWith(`_`);if(t===`.go`)return/^[A-Z]/.test(n);if(t===`.java`){let t=e.captures.get(`node`)?.text??``;return/\bpublic\b/.test(t)}return!1}function xe(e,t,n){if(n===`.go`&&e===`type`&&t?.children){let e=t.type===`type_declaration`?t.children.flatMap(e=>e.children??[]):t.children;for(let t of e){if(t.type===`interface_type`)return`interface`;if(t.type===`struct_type`)return`class`}}return e}function Se(e,t){if(e){if(t===`function`||t===`method`)return Z(e);if(t===`class`)return Ce(e);if(t===`interface`)return we(e)}}function Z(e){let t=e.childForFieldName(`parameters`)??e.childForFieldName(`parameter_list`),n=e.childForFieldName(`return_type`)??e.childForFieldName(`type`),r=e.childForFieldName(`result`);if(!t){for(let t of e.children)if(t.type===`formal_parameters`||t.type===`parameter_list`||t.type===`parameters`){let e=t.text;return n&&(e+=n.text),r&&(e+=` ${r.text}`),e.length>120?`${e.slice(0,117)}...`:e}return}let i=t.text;return n&&(i+=n.text),r&&(i+=` ${r.text}`),i.length>120?`${i.slice(0,117)}...`:i}function Ce(e){let t=e.childForFieldName(`body`)??e.childForFieldName(`field_declaration_list`);if(!t){for(let t of e.children)if(t.type===`struct_type`||t.type===`class_body`)return Q(t);return}return Q(t)}function Q(e){let t=[];for(let n of e.children){if(n.type===`method_definition`){let e=n.childForFieldName(`name`);e&&t.push(e.text)}if(n.type===`method_declaration`){let e=n.childForFieldName(`name`);e&&t.push(e.text)}if(n.type===`field_declaration`){let e=n.childForFieldName(`name`);e&&t.push(e.text)}if(n.type===`function_definition`){let e=n.childForFieldName(`name`);e&&t.push(e.text)}}if(t.length===0)return;let n=t.join(`, `);return n.length>120?`${n.slice(0,117)}...`:n}function we(e){let t=e.childForFieldName(`body`);if(!t){for(let t of e.children)if(t.type===`interface_type`)return $(t);return}return $(t)}function $(e){let t=[];for(let n of e.children){if(n.type===`property_signature`||n.type===`method_signature`){let e=n.childForFieldName(`name`);e&&t.push(e.text)}if(n.type===`method_declaration`){let e=n.childForFieldName(`name`);e&&t.push(e.text)}if(n.type===`method_spec`){let e=n.childForFieldName(`name`);e&&t.push(e.text)}if(n.type===`function_signature_item`||n.type===`declaration_list`){let e=n.childForFieldName(`name`);e&&t.push(e.text)}}if(t.length===0)return;let n=t.join(`, `);return n.length>120?`${n.slice(0,117)}...`:n}function Te(e,t){if(!e||t!==`function`&&t!==`method`)return;let n=e.childForFieldName(`return_type`)??e.childForFieldName(`type`);if(n){let e=n.text.replace(/^:\s*/,``).trim();return e.length>200?`${e.slice(0,200)}…`:e}let r=e.childForFieldName(`result`);if(r)return r.text.trim()}function Ee(e){let t=e.parent;if(!t?.children)return;let n=t.children.indexOf(e);if(n<=0)return;let r=t.children[n-1];if(r){if(r.type===`comment`||r.type===`block_comment`||r.type===`doc_comment`)return r.text.replace(/^\/\*\*?\s*|\s*\*\/$/g,``).split(`
23
23
  `).map(e=>e.replace(/^\s*\*\s?/,``).trim()).filter(e=>e.length>0&&!e.startsWith(`@`))[0]?.slice(0,200)||void 0;if(e.children[0]?.type===`expression_statement`){let t=e.children[0].children[0];if(t&&(t.type===`string`||t.type===`concatenated_string`))return t.text.replace(/^['"`]{1,3}|['"`]{1,3}$/g,``).trim().split(`
24
- `)[0]?.trim()?.slice(0,200)||void 0}}}function Te(e){let t=e.parent;if(!t?.children)return;let n=t.children.indexOf(e),r=[];for(let e=n-1;e>=0;e--){let n=t.children[e];if(n.type===`decorator`||n.type===`annotation`||n.type===`marker_annotation`){let e=n.text.trim();r.unshift(e.length>100?`${e.slice(0,100)}…`:e)}else if(n.type!==`comment`&&n.type!==`block_comment`&&n.type!==`doc_comment`)break}return r.length>0?r:void 0}function Ee(e,t){if(!e||t!==`interface`&&t!==`type`)return;let n=e.childForFieldName(`body`)??e.childForFieldName(`value`)??e.children.find(e=>e.type===`object_type`||e.type===`interface_body`||e.type===`type_body`);if(!n)return;let r=n.text.replace(/\n\s*/g,` `).replace(/\s+/g,` `).trim();return r.length>500?`${r.slice(0,500)}…`:r}export{x as CodeChunker,S as GenericChunker,C as MarkdownChunker,M as QueryExecutor,u as SUPPORTED_EXTENSIONS,E as WasmChunker,h as WasmRuntime,ne as createChunker,re as createChunkerSync,W as detectEntryPoints,oe as detectPatterns,v as extractCallEdges,L as extractCalls,q as extractImports,ge as extractSymbols,ee as initializeWasm,d as resolveGrammarPath,f as resolveParserWasmPath,le as resolveScopes};
24
+ `)[0]?.trim()?.slice(0,200)||void 0}}}function De(e){let t=e.parent;if(!t?.children)return;let n=t.children.indexOf(e),r=[];for(let e=n-1;e>=0;e--){let n=t.children[e];if(n.type===`decorator`||n.type===`annotation`||n.type===`marker_annotation`){let e=n.text.trim();r.unshift(e.length>100?`${e.slice(0,100)}…`:e)}else if(n.type!==`comment`&&n.type!==`block_comment`&&n.type!==`doc_comment`)break}return r.length>0?r:void 0}function Oe(e,t){if(!e||t!==`interface`&&t!==`type`)return;let n=e.childForFieldName(`body`)??e.childForFieldName(`value`)??e.children.find(e=>e.type===`object_type`||e.type===`interface_body`||e.type===`type_body`);if(!n)return;let r=n.text.replace(/\n\s*/g,` `).replace(/\s+/g,` `).trim();return r.length>500?`${r.slice(0,500)}…`:r}export{C as CodeChunker,w as GenericChunker,T as MarkdownChunker,N as QueryExecutor,f as SUPPORTED_EXTENSIONS,D as WasmChunker,_ as WasmRuntime,re as createChunker,ie as createChunkerSync,G as detectEntryPoints,ce as detectPatterns,b as extractCallEdges,R as extractCalls,J as extractImports,ve as extractSymbols,ee as initializeWasm,p as resolveGrammarPath,m as resolveParserWasmPath,de as resolveScopes};
@@ -3957,7 +3957,7 @@ ${e.themeCSS}`),e.fontFamily!==void 0&&(n+=`
3957
3957
  .tree-metadata { color: var(--aikit-muted, #9ca3af); font: 500 11px var(--aikit-font-sans, Inter, sans-serif); }
3958
3958
  .tree-children { margin-left: 18px; padding-left: 12px; border-left: 1px dashed var(--aikit-border, #3c3c3c); }
3959
3959
  .tree-children[hidden] { display: none; }
3960
- `;function G9(e){return typeof e==`object`&&!!e&&typeof e.label==`string`}var Pdt={name:`tree`,label:`Tree`,detect(e){if(Array.isArray(e)){let t=e[0];return G9(t)&&Array.isArray(t.children)?.7:0}if(typeof e!=`object`||!e)return 0;let t=e;if(Array.isArray(t.root)){let e=t.root[0];return G9(e)&&Array.isArray(e.children)?.85:0}return G9(t.root)&&Array.isArray(t.root.children)?.85:0},render(e,t,n){Xu(`tpl-tree`,Ndt);let r=t,i=Array.isArray(r)?r:Array.isArray(r.root)?r.root:[r.root],a=Zu(`div`,`block tpl-tree`),o=(e,t)=>{let n=Zu(`div`,`tree-node`),r=Zu(`div`,`tree-row`);if(r.id=ed(e.id??`${e.label}-${t}`),e.children?.length){let i=document.createElement(`button`),a=t<1;i.className=`tree-toggle`,i.textContent=a?`▼`:`▶`,r.appendChild(i);let s=Zu(`div`,`tree-children`);s.dataset.depth=String(t),s.hidden=!a;for(let n of e.children)s.appendChild(o(n,t+1));i.addEventListener(`click`,()=>{s.hidden=!s.hidden,i.textContent=s.hidden?`▶`:`▼`}),n.appendChild(r),n.appendChild(s)}else r.appendChild(Zu(`span`,`tree-spacer`)),n.appendChild(r);if(e.icon&&r.appendChild(Zu(`span`,`tree-icon`,e.icon)),r.appendChild(Zu(`span`,`tree-label`,e.label)),e.metadata&&Object.keys(e.metadata).length>0){let t=Zu(`span`,`tree-metadata`);t.textContent=Object.entries(e.metadata).map(([e,t])=>`${e}: ${$u(t)}`).join(` · `),r.appendChild(t)}return n};for(let e of i)a.appendChild(o(e,0));e.appendChild(a)},styles(){return Ndt}},K9=new Xse({name:`AI Kit Present`,version:`1.0.0`}),Fdt=document.getElementById(`app`);if(!Fdt)throw Error(`Missing #app element`);var q9=Fdt,J9=new ldt;J9.register(Odt),J9.register(gdt),J9.register(Adt),J9.register(Sdt),J9.register(wdt),J9.register(Mdt),J9.register(mdt),J9.register(Edt),J9.register(Pdt),J9.register(ydt);var Idt=idt(K9),Y9={app:K9,data:adt(K9),emitAction:Idt},X9=new fdt,Ldt=new cdt,Rdt=new odt(K9);K9.connect().then(()=>{let e=K9.getHostContext();e&&(X9.apply(e),Ldt.apply(e),Rdt.apply(e))}),K9.onhostcontextchanged=e=>{X9.apply(e),Ldt.apply(e),Rdt.apply(e),Q9?.onThemeChange&&Q9.onThemeChange(X9.getTheme())};var Z9;K9.ontoolinputpartial=e=>{let t=e.arguments;t&&(q9.dataset.streaming=`true`,clearTimeout(Z9),Z9=setTimeout(()=>{try{let e=t.content;if(!e)return;zdt({title:t.title,template:t.template,content:e})}catch{}},80))},K9.ontoolinput=()=>{clearTimeout(Z9),delete q9.dataset.streaming};function zdt(e){if(q9.innerHTML=``,e.title){let t=Zu(`div`,`header`);t.appendChild(Zu(`h1`,``,e.title)),t.appendChild(Zu(`span`,`badge streaming`,`⟳`)),q9.appendChild(t)}let t=Zu(`div`,`content`);if(Array.isArray(e.content)&&e.content.length>0&&td(e.content[0]))for(let n of e.content)td(n)&&t.appendChild(Yut(n,Y9));else t.appendChild(B9(e.content));q9.appendChild(t)}K9.ontoolresult=e=>{if(clearTimeout(Z9),delete q9.dataset.streaming,e.structuredContent)try{$9(e.structuredContent);return}catch(e){Bdt(`Render error`,e);return}let t=e.content?.find(e=>e.type===`text`)?.text;if(!t){q9.innerHTML=`<p>No data received.</p>`;return}try{$9(JSON.parse(t))}catch{$9({content:t})}};var Q9=null;function Bdt(e,t){q9.innerHTML=``;let n=Zu(`div`,`error-panel`);n.appendChild(Zu(`h3`,``,`⚠ ${e}`)),n.appendChild(Zu(`pre`,``,t instanceof Error?t.message:String(t))),q9.appendChild(n)}function $9(e){if(Q9?.destroy&&Q9.destroy(),Q9=null,q9.innerHTML=``,!e.content){q9.innerHTML=`<p class="no-data">No content data received.</p>`;return}if(e.title){let t=Zu(`div`,`header`);t.appendChild(Zu(`h1`,``,e.title)),t.appendChild(Zu(`span`,`badge`,`AI KIT`)),q9.appendChild(t)}let t=e.template?J9.get(e.template):J9.detect(e.content),n=Zu(`div`,`content`);if(t)Q9=t,t.render(n,e.content,Y9);else if(Array.isArray(e.content)&&e.content.length>0&&td(e.content[0]))for(let t of e.content)td(t)&&n.appendChild(Yut(t,Y9));else n.appendChild(B9(e.content));q9.appendChild(n),e.actions?.length&&q9.appendChild(rdt(e.actions,Y9))}</script>
3960
+ `;function G9(e){return typeof e==`object`&&!!e&&typeof e.label==`string`}var Pdt={name:`tree`,label:`Tree`,detect(e){if(Array.isArray(e)){let t=e[0];return G9(t)&&Array.isArray(t.children)?.7:0}if(typeof e!=`object`||!e)return 0;let t=e;if(Array.isArray(t.root)){let e=t.root[0];return G9(e)&&Array.isArray(e.children)?.85:0}return G9(t.root)&&Array.isArray(t.root.children)?.85:0},render(e,t,n){Xu(`tpl-tree`,Ndt);let r=t,i=Array.isArray(r)?r:Array.isArray(r.root)?r.root:[r.root],a=Zu(`div`,`block tpl-tree`),o=(e,t)=>{let n=Zu(`div`,`tree-node`),r=Zu(`div`,`tree-row`);if(r.id=ed(e.id??`${e.label}-${t}`),e.children?.length){let i=document.createElement(`button`),a=t<1;i.className=`tree-toggle`,i.textContent=a?`▼`:`▶`,r.appendChild(i);let s=Zu(`div`,`tree-children`);s.dataset.depth=String(t),s.hidden=!a;for(let n of e.children)s.appendChild(o(n,t+1));i.addEventListener(`click`,()=>{s.hidden=!s.hidden,i.textContent=s.hidden?`▶`:`▼`}),n.appendChild(r),n.appendChild(s)}else r.appendChild(Zu(`span`,`tree-spacer`)),n.appendChild(r);if(e.icon&&r.appendChild(Zu(`span`,`tree-icon`,e.icon)),r.appendChild(Zu(`span`,`tree-label`,e.label)),e.metadata&&Object.keys(e.metadata).length>0){let t=Zu(`span`,`tree-metadata`);t.textContent=Object.entries(e.metadata).map(([e,t])=>`${e}: ${$u(t)}`).join(` · `),r.appendChild(t)}return n};for(let e of i)a.appendChild(o(e,0));e.appendChild(a)},styles(){return Ndt}},K9=new Xse({name:`AI Kit Present`,version:`1.0.0`}),Fdt=document.getElementById(`app`);if(!Fdt)throw Error(`Missing #app element`);var q9=Fdt,J9=new ldt;J9.register(Odt),J9.register(gdt),J9.register(Adt),J9.register(Sdt),J9.register(wdt),J9.register(Mdt),J9.register(mdt),J9.register(Edt),J9.register(Pdt),J9.register(ydt);var Idt=idt(K9),Y9={app:K9,data:adt(K9),emitAction:Idt},X9=new fdt,Ldt=new cdt,Rdt=new odt(K9);K9.connect().then(()=>{let e=K9.getHostContext();e&&(X9.apply(e),Ldt.apply(e),Rdt.apply(e))}),K9.onhostcontextchanged=e=>{X9.apply(e),Ldt.apply(e),Rdt.apply(e),Q9?.onThemeChange&&Q9.onThemeChange(X9.getTheme())};var Z9;K9.ontoolinputpartial=e=>{let t=e.arguments;t&&(q9.dataset.streaming=`true`,clearTimeout(Z9),Z9=setTimeout(()=>{try{let e=t.content;if(!e)return;zdt({title:t.title,template:t.template,content:e})}catch{}},80))},K9.ontoolinput=()=>{clearTimeout(Z9),delete q9.dataset.streaming};function zdt(e){if(q9.innerHTML=``,e.title){let t=Zu(`div`,`header`);t.appendChild(Zu(`h1`,``,e.title)),t.appendChild(Zu(`span`,`badge streaming`,`⟳`)),q9.appendChild(t)}let t=e.content;if(!Array.isArray(t)&&typeof t==`object`&&t){let e=t;Array.isArray(e.blocks)&&e.blocks.length>0&&(t=e.blocks)}let n=Zu(`div`,`content`);if(Array.isArray(t)&&t.length>0&&td(t[0]))for(let e of t)td(e)&&n.appendChild(Yut(e,Y9));else n.appendChild(B9(t));q9.appendChild(n)}K9.ontoolresult=e=>{if(clearTimeout(Z9),delete q9.dataset.streaming,e.structuredContent)try{$9(e.structuredContent);return}catch(e){Bdt(`Render error`,e);return}let t=e.content?.find(e=>e.type===`text`)?.text;if(!t){q9.innerHTML=`<p>No data received.</p>`;return}try{$9(JSON.parse(t))}catch{$9({content:t})}};var Q9=null;function Bdt(e,t){q9.innerHTML=``;let n=Zu(`div`,`error-panel`);n.appendChild(Zu(`h3`,``,`⚠ ${e}`)),n.appendChild(Zu(`pre`,``,t instanceof Error?t.message:String(t))),q9.appendChild(n)}function $9(e){Q9?.destroy&&Q9.destroy(),Q9=null,q9.innerHTML=``;let t=e.content;if(!Array.isArray(t)&&typeof t==`object`&&t){let e=t;Array.isArray(e.blocks)&&e.blocks.length>0&&(t=e.blocks)}if(!t){q9.innerHTML=`<p class="no-data">No content data received.</p>`;return}if(e.title){let t=Zu(`div`,`header`);t.appendChild(Zu(`h1`,``,e.title)),t.appendChild(Zu(`span`,`badge`,`AI KIT`)),q9.appendChild(t)}let n=e.template?J9.get(e.template):J9.detect(t),r=Zu(`div`,`content`);if(n)Q9=n,n.render(r,t,Y9);else if(Array.isArray(t)&&t.length>0&&td(t[0]))for(let e of t)td(e)&&r.appendChild(Yut(e,Y9));else r.appendChild(B9(t));q9.appendChild(r),e.actions?.length&&q9.appendChild(rdt(e.actions,Y9))}</script>
3961
3961
  </head>
3962
3962
  <body>
3963
3963
  <div id="app">
@@ -1 +1 @@
1
- import{t as e}from"./curated-manager-DX-_oJg0.js";import{readFileSync as t}from"node:fs";import{dirname as n,resolve as r}from"node:path";import{fileURLToPath as i}from"node:url";import{parseArgs as a}from"node:util";import{createLogger as o,serializeError as s}from"../../core/dist/index.js";const c=n(i(import.meta.url)),l=(()=>{try{let e=r(c,`..`,`..`,`..`,`package.json`);return JSON.parse(t(e,`utf-8`)).version??`0.0.0`}catch{return`0.0.0`}})(),u=o(`server`),{values:d}=a({options:{transport:{type:`string`,default:process.env.AIKIT_TRANSPORT??`stdio`},port:{type:`string`,default:process.env.AIKIT_PORT??`3210`}}});async function f(){if(process.on(`unhandledRejection`,e=>{u.error(`Unhandled rejection`,s(e))}),u.info(`Starting MCP AI Kit server`,{version:l}),d.transport===`http`){let[{default:e},{loadConfig:t,resolveIndexMode:n},{registerDashboardRoutes:r,resolveDashboardDir:i}]=await Promise.all([import(`express`),import(`./config-C5IU9Lau.js`),import(`./dashboard-static-BfIe0Si1.js`)]),a=t();u.info(`Config loaded`,{sourceCount:a.sources.length,storePath:a.store.path});let o=e();o.use(e.json());let c=Number(d.port);o.use((e,t,n)=>{if(t.setHeader(`Access-Control-Allow-Origin`,process.env.AIKIT_CORS_ORIGIN??`http://localhost:${c}`),t.setHeader(`Access-Control-Allow-Methods`,`GET, POST, DELETE, OPTIONS`),t.setHeader(`Access-Control-Allow-Headers`,`Content-Type, Authorization`),e.method===`OPTIONS`){t.status(204).end();return}n()}),r(o,i(),u),o.get(`/health`,(e,t)=>{t.json({status:`ok`})});let l=!1,f=null,p=null,m=null,h=Promise.resolve();o.post(`/mcp`,async(e,t)=>{if(!l||!p||!m){t.status(503).json({jsonrpc:`2.0`,error:{code:-32603,message:`Server initializing — please retry in a few seconds`},id:null});return}let n=h,r;h=new Promise(e=>{r=e}),await n;try{let n=new m({sessionIdGenerator:void 0});await p.connect(n),await n.handleRequest(e,t,e.body),n.close()}catch(e){if(u.error(`MCP handler error`,s(e)),!t.headersSent){let n=e instanceof Error?e.message:String(e),r=n.includes(`Not Acceptable`);t.status(r?406:500).json({jsonrpc:`2.0`,error:{code:r?-32e3:-32603,message:r?n:`Internal server error`},id:null})}}finally{r()}}),o.get(`/mcp`,(e,t)=>{t.writeHead(405).end(JSON.stringify({jsonrpc:`2.0`,error:{code:-32e3,message:`Method not allowed.`},id:null}))}),o.delete(`/mcp`,(e,t)=>{t.writeHead(405).end(JSON.stringify({jsonrpc:`2.0`,error:{code:-32e3,message:`Method not allowed.`},id:null}))});let g=o.listen(c,`127.0.0.1`,()=>{u.info(`MCP server listening`,{url:`http://127.0.0.1:${c}/mcp`,port:c}),setTimeout(async()=>{try{let[{createLazyServer:e,ALL_TOOL_NAMES:t},{StreamableHTTPServerTransport:r},{checkForUpdates:i,autoUpgradeScaffold:o}]=await Promise.all([import(`./server-CldM2UAM.js`),import(`@modelcontextprotocol/sdk/server/streamableHttp.js`),import(`./version-check-D4j0Pykd.js`)]);i(),o();let c=n(a),d=e(a,c);p=d.server,m=r,l=!0,u.info(`MCP server configured (lazy — AI Kit initializing in background)`,{toolCount:t.length,resourceCount:2}),d.startInit(),c===`auto`?d.ready.then(async()=>{try{let e=a.sources.map(e=>e.path).join(`, `);u.info(`Running initial index`,{sourcePaths:e}),await d.runInitialIndex(),u.info(`Initial index complete`)}catch(e){u.error(`Initial index failed; will retry on aikit_reindex`,s(e))}}).catch(e=>u.error(`AI Kit init or indexing failed`,s(e))):c===`smart`?d.ready.then(async()=>{try{if(!d.kb)throw Error(`AI Kit components are not available after initialization`);let{SmartIndexScheduler:e}=await import(`../../indexer/dist/index.js`);f=new e(d.kb.indexer,a,d.kb.store),f.start(),d.setSmartScheduler(f),u.info(`Smart index scheduler started (HTTP mode)`)}catch(e){u.error(`Failed to start smart index scheduler`,s(e))}}).catch(e=>u.error(`AI Kit initialization failed`,s(e))):(d.ready.catch(e=>u.error(`AI Kit initialization failed`,s(e))),u.info(`Initial full indexing skipped in HTTP mode`,{indexMode:c}))}catch(e){u.error(`Failed to load server modules`,s(e))}},100)}),_=async e=>{u.info(`Shutdown signal received`,{signal:e}),f?.stop(),g.close(),p&&await p.close(),process.exit(0)};process.on(`SIGINT`,()=>_(`SIGINT`)),process.on(`SIGTERM`,()=>_(`SIGTERM`))}else{let[{loadConfig:e,reconfigureForWorkspace:t,resolveIndexMode:n},{createLazyServer:r},{checkForUpdates:a,autoUpgradeScaffold:o},{RootsListChangedNotificationSchema:c}]=await Promise.all([import(`./config-C5IU9Lau.js`),import(`./server-CldM2UAM.js`),import(`./version-check-D4j0Pykd.js`),import(`@modelcontextprotocol/sdk/types.js`)]),l=e();u.info(`Config loaded`,{sourceCount:l.sources.length,storePath:l.store.path}),a(),o();let d=n(l),f=r(l,d),{server:p,startInit:m,ready:h,runInitialIndex:g}=f,{StdioServerTransport:_}=await import(`@modelcontextprotocol/sdk/server/stdio.js`),v=new _;await p.connect(v),u.info(`MCP server started`,{transport:`stdio`});let y=e=>{if(e.length===0)return!1;let n=e[0].uri,r=n.startsWith(`file://`)?i(n):n;return u.info(`MCP roots resolved`,{rootUri:n,rootPath:r,rootCount:e.length}),t(l,r),!0},b=!1;try{b=y((await p.server.listRoots()).roots),b||u.info(`No MCP roots yet; waiting for roots/list_changed notification`)}catch(e){u.warn(`MCP roots/list not supported by client; using cwd fallback`,{cwd:process.cwd(),...s(e)}),b=!0}b||=await new Promise(e=>{let t=setTimeout(()=>{u.warn(`Timed out waiting for MCP roots/list_changed; using cwd fallback`,{cwd:process.cwd()}),e(!1)},5e3);p.server.setNotificationHandler(c,async()=>{clearTimeout(t);try{e(y((await p.server.listRoots()).roots))}catch(t){u.warn(`roots/list retry failed after notification`,s(t)),e(!1)}})}),m();let x=null,S=()=>{x&&clearTimeout(x),x=setTimeout(()=>{u.info(`Auto-shutdown: no activity for 30 minutes — exiting`),process.exit(0)},18e5),x.unref&&x.unref()};S(),process.stdin.on(`data`,()=>S()),h.catch(e=>{u.error(`Initialization failed — server will continue with limited tools`,s(e))}),d===`auto`?g().catch(e=>u.error(`Initial index failed`,s(e))):d===`smart`?h.then(async()=>{try{if(!f.kb)throw Error(`AI Kit components are not available after initialization`);let{SmartIndexScheduler:e}=await import(`../../indexer/dist/index.js`),t=new e(f.kb.indexer,l,f.kb.store);t.start(),f.setSmartScheduler(t),u.info(`Smart index scheduler started (stdio mode)`)}catch(e){u.error(`Failed to start smart index scheduler`,s(e))}}).catch(e=>u.error(`AI Kit init failed for smart scheduler`,s(e))):u.warn(`Initial full indexing skipped; use aikit_reindex to index manually`,{indexMode:d})}}f().catch(e=>{u.error(`Fatal error`,s(e)),process.exit(1)});export{e as CuratedKnowledgeManager};
1
+ import{t as e}from"./curated-manager-DX-_oJg0.js";import{readFileSync as t}from"node:fs";import{dirname as n,resolve as r}from"node:path";import{fileURLToPath as i}from"node:url";import{parseArgs as a}from"node:util";import{createLogger as o,serializeError as s}from"../../core/dist/index.js";const c=n(i(import.meta.url)),l=(()=>{try{let e=r(c,`..`,`..`,`..`,`package.json`);return JSON.parse(t(e,`utf-8`)).version??`0.0.0`}catch{return`0.0.0`}})(),u=o(`server`),{values:d}=a({options:{transport:{type:`string`,default:process.env.AIKIT_TRANSPORT??`stdio`},port:{type:`string`,default:process.env.AIKIT_PORT??`3210`}}});async function f(){if(process.on(`unhandledRejection`,e=>{u.error(`Unhandled rejection`,s(e))}),u.info(`Starting MCP AI Kit server`,{version:l}),d.transport===`http`){let[{default:e},{loadConfig:t,resolveIndexMode:n},{registerDashboardRoutes:r,resolveDashboardDir:i}]=await Promise.all([import(`express`),import(`./config-C5IU9Lau.js`),import(`./dashboard-static-BfIe0Si1.js`)]),a=t();u.info(`Config loaded`,{sourceCount:a.sources.length,storePath:a.store.path});let o=e();o.use(e.json());let c=Number(d.port);o.use((e,t,n)=>{if(t.setHeader(`Access-Control-Allow-Origin`,process.env.AIKIT_CORS_ORIGIN??`http://localhost:${c}`),t.setHeader(`Access-Control-Allow-Methods`,`GET, POST, DELETE, OPTIONS`),t.setHeader(`Access-Control-Allow-Headers`,`Content-Type, Authorization`),e.method===`OPTIONS`){t.status(204).end();return}n()}),r(o,i(),u),o.get(`/health`,(e,t)=>{t.json({status:`ok`})});let l=!1,f=null,p=null,m=null,h=Promise.resolve();o.post(`/mcp`,async(e,t)=>{if(!l||!p||!m){t.status(503).json({jsonrpc:`2.0`,error:{code:-32603,message:`Server initializing — please retry in a few seconds`},id:null});return}let n=h,r;h=new Promise(e=>{r=e}),await n;try{let n=new m({sessionIdGenerator:void 0});await p.connect(n),await n.handleRequest(e,t,e.body),n.close()}catch(e){if(u.error(`MCP handler error`,s(e)),!t.headersSent){let n=e instanceof Error?e.message:String(e),r=n.includes(`Not Acceptable`);t.status(r?406:500).json({jsonrpc:`2.0`,error:{code:r?-32e3:-32603,message:r?n:`Internal server error`},id:null})}}finally{r()}}),o.get(`/mcp`,(e,t)=>{t.writeHead(405).end(JSON.stringify({jsonrpc:`2.0`,error:{code:-32e3,message:`Method not allowed.`},id:null}))}),o.delete(`/mcp`,(e,t)=>{t.writeHead(405).end(JSON.stringify({jsonrpc:`2.0`,error:{code:-32e3,message:`Method not allowed.`},id:null}))});let g=o.listen(c,`127.0.0.1`,()=>{u.info(`MCP server listening`,{url:`http://127.0.0.1:${c}/mcp`,port:c}),setTimeout(async()=>{try{let[{createLazyServer:e,ALL_TOOL_NAMES:t},{StreamableHTTPServerTransport:r},{checkForUpdates:i,autoUpgradeScaffold:o}]=await Promise.all([import(`./server-DOXU8yxT.js`),import(`@modelcontextprotocol/sdk/server/streamableHttp.js`),import(`./version-check-D4j0Pykd.js`)]);i(),o();let c=n(a),d=e(a,c);p=d.server,m=r,l=!0,u.info(`MCP server configured (lazy — AI Kit initializing in background)`,{toolCount:t.length,resourceCount:2}),d.startInit(),c===`auto`?d.ready.then(async()=>{try{let e=a.sources.map(e=>e.path).join(`, `);u.info(`Running initial index`,{sourcePaths:e}),await d.runInitialIndex(),u.info(`Initial index complete`)}catch(e){u.error(`Initial index failed; will retry on aikit_reindex`,s(e))}}).catch(e=>u.error(`AI Kit init or indexing failed`,s(e))):c===`smart`?d.ready.then(async()=>{try{if(!d.kb)throw Error(`AI Kit components are not available after initialization`);let{SmartIndexScheduler:e}=await import(`../../indexer/dist/index.js`);f=new e(d.kb.indexer,a,d.kb.store),f.start(),d.setSmartScheduler(f),u.info(`Smart index scheduler started (HTTP mode)`)}catch(e){u.error(`Failed to start smart index scheduler`,s(e))}}).catch(e=>u.error(`AI Kit initialization failed`,s(e))):(d.ready.catch(e=>u.error(`AI Kit initialization failed`,s(e))),u.info(`Initial full indexing skipped in HTTP mode`,{indexMode:c}))}catch(e){u.error(`Failed to load server modules`,s(e))}},100)}),_=async e=>{u.info(`Shutdown signal received`,{signal:e}),f?.stop(),g.close(),p&&await p.close(),process.exit(0)};process.on(`SIGINT`,()=>_(`SIGINT`)),process.on(`SIGTERM`,()=>_(`SIGTERM`))}else{let[{loadConfig:e,reconfigureForWorkspace:t,resolveIndexMode:n},{createLazyServer:r},{checkForUpdates:a,autoUpgradeScaffold:o},{RootsListChangedNotificationSchema:c}]=await Promise.all([import(`./config-C5IU9Lau.js`),import(`./server-DOXU8yxT.js`),import(`./version-check-D4j0Pykd.js`),import(`@modelcontextprotocol/sdk/types.js`)]),l=e();u.info(`Config loaded`,{sourceCount:l.sources.length,storePath:l.store.path}),a(),o();let d=n(l),f=r(l,d),{server:p,startInit:m,ready:h,runInitialIndex:g}=f,{StdioServerTransport:_}=await import(`@modelcontextprotocol/sdk/server/stdio.js`),v=new _;await p.connect(v),u.info(`MCP server started`,{transport:`stdio`});let y=e=>{if(e.length===0)return!1;let n=e[0].uri,r=n.startsWith(`file://`)?i(n):n;return u.info(`MCP roots resolved`,{rootUri:n,rootPath:r,rootCount:e.length}),t(l,r),!0},b=!1;try{b=y((await p.server.listRoots()).roots),b||u.info(`No MCP roots yet; waiting for roots/list_changed notification`)}catch(e){u.warn(`MCP roots/list not supported by client; using cwd fallback`,{cwd:process.cwd(),...s(e)}),b=!0}b||=await new Promise(e=>{let t=setTimeout(()=>{u.warn(`Timed out waiting for MCP roots/list_changed; using cwd fallback`,{cwd:process.cwd()}),e(!1)},5e3);p.server.setNotificationHandler(c,async()=>{clearTimeout(t);try{e(y((await p.server.listRoots()).roots))}catch(t){u.warn(`roots/list retry failed after notification`,s(t)),e(!1)}})}),m();let x=null,S=()=>{x&&clearTimeout(x),x=setTimeout(()=>{u.info(`Auto-shutdown: no activity for 30 minutes — exiting`),process.exit(0)},18e5),x.unref&&x.unref()};S(),process.stdin.on(`data`,()=>S()),h.catch(e=>{u.error(`Initialization failed — server will continue with limited tools`,s(e))}),d===`auto`?g().catch(e=>u.error(`Initial index failed`,s(e))):d===`smart`?h.then(async()=>{try{if(!f.kb)throw Error(`AI Kit components are not available after initialization`);let{SmartIndexScheduler:e}=await import(`../../indexer/dist/index.js`),t=new e(f.kb.indexer,l,f.kb.store);t.start(),f.setSmartScheduler(t),u.info(`Smart index scheduler started (stdio mode)`)}catch(e){u.error(`Failed to start smart index scheduler`,s(e))}}).catch(e=>u.error(`AI Kit init failed for smart scheduler`,s(e))):u.warn(`Initial full indexing skipped; use aikit_reindex to index manually`,{indexMode:d})}}f().catch(e=>{u.error(`Fatal error`,s(e)),process.exit(1)});export{e as CuratedKnowledgeManager};
@@ -595,26 +595,26 @@ Complements: \`symbol\` (single lookup), \`trace\` (call-chain AST), \`blast_rad
595
595
  ### Processes`);for(let e of n.processes)r.push(`- **${e.label}** (id: \`${e.id}\`) — ${e.steps.length} step(s)`)}if(n.depthGroups){r.push(`
596
596
  ### Depth Groups`);for(let[e,t]of Object.entries(n.depthGroups))r.push(`- **Depth ${e}**: ${t.map(e=>`${e.name} (${e.type})`).join(`, `)}`)}if(n.cohesionScore!==void 0&&r.push(`\n**Cohesion Score**: ${(n.cohesionScore*100).toFixed(1)}%`),n.symbol360){let e=n.symbol360;r.push(`
597
597
  ### 360° Symbol View`),r.push(`- **Node**: ${e.node.name} (${e.node.type})`),r.push(`- **Community**: ${e.community??`none`}`),r.push(`- **Incoming**: ${e.incoming.length} edge(s)`),r.push(`- **Outgoing**: ${e.outgoing.length} edge(s)`),r.push(`- **Processes**: ${e.processes.length}`)}return r.push("\n---\n_Next: Use `graph(traverse)` to explore connections, `graph(add)` to insert entities, `graph(symbol360)` for full node context, or `graph(detect_communities)` to find clusters._"),{content:[{type:`text`,text:r.join(`
598
- `)}],structuredContent:{nodes:(n.nodes??[]).map(e=>({id:e.id,name:e.name,type:e.type,...e.sourcePath?{sourcePath:e.sourcePath}:{}})),edges:(n.edges??[]).map(e=>({fromId:e.fromId,toId:e.toId,type:e.type})),totalNodes:n.stats?.nodeCount??n.nodes?.length??0,totalEdges:n.stats?.edgeCount??n.edges?.length??0,query:e.action}}}catch(e){return Mo.error(`Graph query failed`,A(e)),{content:[{type:`text`,text:`Graph query failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}const K=E(`tools:infra`);function Io(e){let t=L(`process`);e.registerTool(`process`,{title:t.title,description:`Start, stop, inspect, list, and tail logs for in-memory managed child processes.`,inputSchema:{action:F.enum([`start`,`stop`,`status`,`list`,`logs`]).describe(`Process action to perform`),id:F.string().optional().describe(`Managed process ID`),command:F.string().optional().describe(`Executable to start`),args:F.array(F.string()).optional().describe(`Arguments for start actions`),tail:F.number().min(1).max(500).optional().describe(`Log lines to return for logs actions`)},annotations:t.annotations},async({action:e,id:t,command:n,args:r,tail:i})=>{try{switch(e){case`start`:if(!t||!n)throw Error(`id and command are required for start`);return{content:[{type:`text`,text:JSON.stringify(pt(t,n,r??[]))}]};case`stop`:if(!t)throw Error(`id is required for stop`);return{content:[{type:`text`,text:JSON.stringify(ht(t)??null)}]};case`status`:if(!t)throw Error(`id is required for status`);return{content:[{type:`text`,text:JSON.stringify(mt(t)??null)}]};case`list`:return{content:[{type:`text`,text:JSON.stringify(dt())}]};case`logs`:if(!t)throw Error(`id is required for logs`);return{content:[{type:`text`,text:JSON.stringify(ft(t,i))}]}}}catch(e){return K.error(`Process action failed`,A(e)),{content:[{type:`text`,text:`Process action failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function Lo(e){let t=L(`watch`);e.registerTool(`watch`,{title:t.title,description:`Watch a directory for file changes (create/modify/delete). Actions: start (begin watching), stop (by ID), list (show active watchers). Events are emitted as structured JSON with path, event type, and timestamp.`,inputSchema:{action:F.enum([`start`,`stop`,`list`]).describe(`Watch action to perform`),path:F.string().optional().describe(`Directory path to watch for start actions`),id:F.string().optional().describe(`Watcher ID for stop actions`)},annotations:t.annotations},async({action:e,path:t,id:n})=>{try{switch(e){case`start`:if(!t)throw Error(`path is required for start`);return{content:[{type:`text`,text:JSON.stringify(Qt({path:t}))}]};case`stop`:if(!n)throw Error(`id is required for stop`);return{content:[{type:`text`,text:JSON.stringify({stopped:$t(n)})}]};case`list`:return{content:[{type:`text`,text:JSON.stringify(Zt())}]}}}catch(e){return K.error(`Watch action failed`,A(e)),{content:[{type:`text`,text:`Watch action failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function Ro(e){let t=L(`health`);e.registerTool(`health`,{title:t.title,description:`Run project health checks — verifies package.json, tsconfig, scripts, lockfile, README, LICENSE, .gitignore.`,outputSchema:mi,inputSchema:{path:F.string().optional().describe(`Root directory to check (defaults to cwd)`)},annotations:t.annotations},async({path:e})=>{try{let t=Qe(e),n={ok:t.checks.every(e=>e.status!==`fail`),checks:t.checks.map(e=>({name:e.name,ok:e.status===`pass`,message:e.message}))};return{content:[{type:`text`,text:JSON.stringify(t)}],structuredContent:n}}catch(e){return K.error(`Health check failed`,A(e)),{content:[{type:`text`,text:`Health check failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function zo(e){let t=L(`web_fetch`);e.registerTool(`web_fetch`,{title:t.title,description:`PREFERRED web fetcher — fetch one or many URLs and convert to LLM-optimized markdown. Pass one URL or multiple for parallel fetching. Supports CSS selectors, 4 output modes (markdown/raw/links/outline), smart paragraph-boundary truncation. Strips scripts/styles/nav automatically.`,inputSchema:{urls:F.array(F.string().url()).min(1).max(10).describe('URLs to fetch (1–10). Single URL: `["https://..."]`. Multiple fetched in parallel.'),mode:F.enum([`markdown`,`raw`,`links`,`outline`]).default(`markdown`).describe(`Output mode: markdown (clean content), raw (HTML), links (extracted URLs), outline (heading hierarchy)`),selector:F.string().optional().describe(`CSS selector to extract a specific element instead of auto-detecting main content`),max_length:F.number().min(500).max(1e5).default(15e3).describe(`Max characters in output — truncates at paragraph boundaries`),include_metadata:F.boolean().default(!0).describe(`Include page title, description, and URL as a header`),include_links:F.boolean().default(!1).describe(`Append extracted links list at the end`),include_images:F.boolean().default(!1).describe(`Include image alt texts inline`),timeout:F.number().min(1e3).max(12e4).default(3e4).describe(`Request timeout in milliseconds`)},annotations:t.annotations},async({urls:e,mode:t,selector:n,max_length:r,include_metadata:i,include_links:a,include_images:o,timeout:s})=>{let c=e,l=async(e,c)=>{let l=await en({url:e,mode:t,selector:n,maxLength:r,includeMetadata:i,includeLinks:a,includeImages:o,timeout:s}),u=[c?`## ${c} ${l.title||`Web Page`}\n> Source: ${e}`:`## ${l.title||`Web Page`}`,``,l.content];return l.truncated&&u.push(``,`_Original length: ${l.originalLength.toLocaleString()} chars_`),u.join(`
599
- `)};if(c.length===1)try{return{content:[{type:`text`,text:await l(c[0])+"\n\n---\n_Next: Use `remember` to save key findings, or `web_fetch` with a `selector` to extract a specific section._"}]}}catch(e){let t=e instanceof Error?e.message:String(e);return/HTTP [45]\d{2}/.test(t)?K.warn(`Web fetch failed`,{error:t}):K.error(`Web fetch failed`,A(e)),{content:[{type:`text`,text:`Web fetch failed: ${t}`}],isError:!0}}let u=c.length,d=await Promise.allSettled(c.map((e,t)=>l(e,`[${t+1}/${u}]`))),f=[],p=0;for(let e=0;e<d.length;e++){let t=d[e];if(t.status===`fulfilled`)f.push(t.value);else{p++;let n=t.reason instanceof Error?t.reason.message:String(t.reason);/HTTP [45]\d{2}/.test(n)?K.warn(`Web fetch failed`,{url:c[e],error:n}):K.error(`Web fetch failed`,{url:c[e],...A(t.reason)}),f.push(`## ❌ Failed: ${c[e]}\n\n${n}`)}}let m=`_Fetched ${d.length-p}/${d.length} URLs successfully._`;return f.push(``,`---`,m,"_Next: Use `remember` to save key findings, or `web_fetch` with a `selector` to extract a specific section._"),{content:[{type:`text`,text:f.join(`
598
+ `)}],structuredContent:{nodes:(n.nodes??[]).map(e=>({id:e.id,name:e.name,type:e.type,...e.sourcePath?{sourcePath:e.sourcePath}:{}})),edges:(n.edges??[]).map(e=>({fromId:e.fromId,toId:e.toId,type:e.type})),totalNodes:n.stats?.nodeCount??n.nodes?.length??0,totalEdges:n.stats?.edgeCount??n.edges?.length??0,query:e.action}}}catch(e){return Mo.error(`Graph query failed`,A(e)),{content:[{type:`text`,text:`Graph query failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}const Io=E(`tools:infra`);function Lo(e){let t=L(`process`);e.registerTool(`process`,{title:t.title,description:`Start, stop, inspect, list, and tail logs for in-memory managed child processes.`,inputSchema:{action:F.enum([`start`,`stop`,`status`,`list`,`logs`]).describe(`Process action to perform`),id:F.string().optional().describe(`Managed process ID`),command:F.string().optional().describe(`Executable to start`),args:F.array(F.string()).optional().describe(`Arguments for start actions`),tail:F.number().min(1).max(500).optional().describe(`Log lines to return for logs actions`)},annotations:t.annotations},async({action:e,id:t,command:n,args:r,tail:i})=>{try{switch(e){case`start`:if(!t||!n)throw Error(`id and command are required for start`);return{content:[{type:`text`,text:JSON.stringify(pt(t,n,r??[]))}]};case`stop`:if(!t)throw Error(`id is required for stop`);return{content:[{type:`text`,text:JSON.stringify(ht(t)??null)}]};case`status`:if(!t)throw Error(`id is required for status`);return{content:[{type:`text`,text:JSON.stringify(mt(t)??null)}]};case`list`:return{content:[{type:`text`,text:JSON.stringify(dt())}]};case`logs`:if(!t)throw Error(`id is required for logs`);return{content:[{type:`text`,text:JSON.stringify(ft(t,i))}]}}}catch(e){return Io.error(`Process action failed`,A(e)),{content:[{type:`text`,text:`Process action failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function Ro(e){let t=L(`watch`);e.registerTool(`watch`,{title:t.title,description:`Watch a directory for file changes (create/modify/delete). Actions: start (begin watching), stop (by ID), list (show active watchers). Events are emitted as structured JSON with path, event type, and timestamp.`,inputSchema:{action:F.enum([`start`,`stop`,`list`]).describe(`Watch action to perform`),path:F.string().optional().describe(`Directory path to watch for start actions`),id:F.string().optional().describe(`Watcher ID for stop actions`)},annotations:t.annotations},async({action:e,path:t,id:n})=>{try{switch(e){case`start`:if(!t)throw Error(`path is required for start`);return{content:[{type:`text`,text:JSON.stringify(Qt({path:t}))}]};case`stop`:if(!n)throw Error(`id is required for stop`);return{content:[{type:`text`,text:JSON.stringify({stopped:$t(n)})}]};case`list`:return{content:[{type:`text`,text:JSON.stringify(Zt())}]}}}catch(e){return Io.error(`Watch action failed`,A(e)),{content:[{type:`text`,text:`Watch action failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function zo(e){let t=L(`health`);e.registerTool(`health`,{title:t.title,description:`Run project health checks — verifies package.json, tsconfig, scripts, lockfile, README, LICENSE, .gitignore.`,outputSchema:mi,inputSchema:{path:F.string().optional().describe(`Root directory to check (defaults to cwd)`)},annotations:t.annotations},async({path:e})=>{try{let t=Qe(e),n={ok:t.checks.every(e=>e.status!==`fail`),checks:t.checks.map(e=>({name:e.name,ok:e.status===`pass`,message:e.message}))};return{content:[{type:`text`,text:JSON.stringify(t)}],structuredContent:n}}catch(e){return Io.error(`Health check failed`,A(e)),{content:[{type:`text`,text:`Health check failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function Bo(e){let t=L(`web_fetch`);e.registerTool(`web_fetch`,{title:t.title,description:`PREFERRED web fetcher — fetch one or many URLs and convert to LLM-optimized markdown. Pass one URL or multiple for parallel fetching. Supports CSS selectors, 4 output modes (markdown/raw/links/outline), smart paragraph-boundary truncation. Strips scripts/styles/nav automatically.`,inputSchema:{urls:F.array(F.string().url()).min(1).max(10).describe('URLs to fetch (1–10). Single URL: `["https://..."]`. Multiple fetched in parallel.'),mode:F.enum([`markdown`,`raw`,`links`,`outline`]).default(`markdown`).describe(`Output mode: markdown (clean content), raw (HTML), links (extracted URLs), outline (heading hierarchy)`),selector:F.string().optional().describe(`CSS selector to extract a specific element instead of auto-detecting main content`),max_length:F.number().min(500).max(1e5).default(15e3).describe(`Max characters in output — truncates at paragraph boundaries`),include_metadata:F.boolean().default(!0).describe(`Include page title, description, and URL as a header`),include_links:F.boolean().default(!1).describe(`Append extracted links list at the end`),include_images:F.boolean().default(!1).describe(`Include image alt texts inline`),timeout:F.number().min(1e3).max(12e4).default(3e4).describe(`Request timeout in milliseconds`)},annotations:t.annotations},async({urls:e,mode:t,selector:n,max_length:r,include_metadata:i,include_links:a,include_images:o,timeout:s})=>{let c=e,l=async(e,c)=>{let l=await en({url:e,mode:t,selector:n,maxLength:r,includeMetadata:i,includeLinks:a,includeImages:o,timeout:s}),u=[c?`## ${c} ${l.title||`Web Page`}\n> Source: ${e}`:`## ${l.title||`Web Page`}`,``,l.content];return l.truncated&&u.push(``,`_Original length: ${l.originalLength.toLocaleString()} chars_`),u.join(`
599
+ `)};if(c.length===1)try{return{content:[{type:`text`,text:await l(c[0])+"\n\n---\n_Next: Use `remember` to save key findings, or `web_fetch` with a `selector` to extract a specific section._"}]}}catch(e){let t=e instanceof Error?e.message:String(e);return/HTTP [45]\d{2}/.test(t)?Io.warn(`Web fetch failed`,{error:t}):Io.error(`Web fetch failed`,A(e)),{content:[{type:`text`,text:`Web fetch failed: ${t}`}],isError:!0}}let u=c.length,d=await Promise.allSettled(c.map((e,t)=>l(e,`[${t+1}/${u}]`))),f=[],p=0;for(let e=0;e<d.length;e++){let t=d[e];if(t.status===`fulfilled`)f.push(t.value);else{p++;let n=t.reason instanceof Error?t.reason.message:String(t.reason);/HTTP [45]\d{2}/.test(n)?Io.warn(`Web fetch failed`,{url:c[e],error:n}):Io.error(`Web fetch failed`,{url:c[e],...A(t.reason)}),f.push(`## ❌ Failed: ${c[e]}\n\n${n}`)}}let m=`_Fetched ${d.length-p}/${d.length} URLs successfully._`;return f.push(``,`---`,m,"_Next: Use `remember` to save key findings, or `web_fetch` with a `selector` to extract a specific section._"),{content:[{type:`text`,text:f.join(`
600
600
 
601
- `)}],...p===d.length?{isError:!0}:{}}})}function Bo(e,t){let n=L(`guide`);e.registerTool(`guide`,{title:n.title,description:`Tool discovery — given a goal description, recommends which AI Kit tools to use and in what order. Matches against 10 predefined workflows: onboard, audit, bugfix, implement, refactor, search, context, memory, validate, analyze.`,inputSchema:{goal:F.string().describe(`What you want to accomplish (e.g., "audit this monorepo", "fix a failing test")`),max_recommendations:F.number().min(1).max(10).default(5).describe(`Maximum number of tool recommendations`)},annotations:n.annotations},async({goal:e,max_recommendations:n})=>{try{let r=Ze(e,n,t),i=[`## Recommended Workflow: **${r.workflow}**`,r.description,``,`### Tools`,...r.tools.map(e=>{let t=e.suggestedArgs?` — \`${JSON.stringify(e.suggestedArgs)}\``:``;return`${e.order}. **${e.tool}** — ${e.reason}${t}`})];return r.alternativeWorkflows.length>0&&i.push(``,`_Alternative workflows: ${r.alternativeWorkflows.join(`, `)}_`),i.push(``,`---`,"_Next: Run the first recommended tool, or use `guide` again with a more specific goal._"),{content:[{type:`text`,text:i.join(`
602
- `)}]}}catch(e){return K.error(`Guide failed`,A(e)),{content:[{type:`text`,text:`Guide failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function Vo(e,t,n){if(!(!e||typeof e!=`string`)&&!(e.includes(`..`)||e.startsWith(`/`)||e.startsWith(`[`)))return{type:`resource_link`,uri:`aikit://curated/${e}`,name:t??e,mimeType:`text/markdown`,...n?{description:n}:{}}}function Ho(e){let t=new Set,n=[];for(let r of e){let e=Vo(r.path,r.title,r.category?`[${r.category}]`:void 0);e&&!t.has(e.uri)&&(t.add(e.uri),n.push(e))}return n}function Uo(e){if(e.startsWith(`.ai/curated/`))return e.slice(12)}const Wo=E(`tools`);function Go(e,t){let n=L(`list`);e.registerTool(`list`,{title:n.title,description:`List curated knowledge entries stored via remember. Returns path, title, category, tags, and content preview for each entry. Filter by category (decisions, patterns, conventions) or tag.`,outputSchema:pi,inputSchema:{category:F.string().optional().describe(`Filter by category (e.g., "decisions", "patterns")`),tag:F.string().optional().describe(`Filter by tag`)},annotations:n.annotations},async({category:e,tag:n})=>{try{let r=await t.list({category:e,tag:n}),i={entries:r.map(e=>({path:e.path,title:e.title,category:e.category,tags:e.tags,version:e.version,preview:e.contentPreview?.slice(0,120)??``})),totalCount:r.length};if(r.length===0)return{content:[{type:`text`,text:`No curated knowledge entries found.`+(e?` (category: ${e})`:``)+(n?` (tag: ${n})`:``)}],structuredContent:i};let a=r.map(e=>{let t=e.tags.length>0?` [${e.tags.join(`, `)}]`:``;return`- **${e.title}** (v${e.version})${t}\n \`${e.path}\` — ${e.contentPreview.slice(0,80)}…`}).join(`
603
- `),o=Ho(r);return{content:[{type:`text`,text:`## Curated Knowledge (${r.length} entries)\n\n${a}\n\n---\n_Next: Use \`read\` to view full content of any entry, or \`remember\` to store new knowledge._`},...o],structuredContent:i}}catch(e){return Wo.error(`List failed`,A(e)),{content:[{type:`text`,text:`List failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}const Ko=E(`tools`);function qo(e,t){let n=L(`lookup`);e.registerTool(`lookup`,{title:n.title,description:`Get all indexed content for a known file path, sorted by position. Use when you know the exact file. For discovery across files use search.`,inputSchema:{path:F.string().describe(`Relative file path to look up (e.g., "src/index.ts")`)},annotations:n.annotations},async({path:e})=>{try{let n=await t.getBySourcePath(e);if(n.length===0)return{content:[{type:`text`,text:`No indexed content found for: ${e}`}]};n.sort((e,t)=>e.chunkIndex-t.chunkIndex);let r=`## ${e}\n**Chunks**: ${n.length} | **Type**: ${n[0].contentType}\n`,i=n.map(e=>{let t=e.startLine?` (lines ${e.startLine}-${e.endLine})`:``;return`### Chunk ${e.chunkIndex+1}/${e.totalChunks}${t}\n${e.content}`}).join(`
601
+ `)}],...p===d.length?{isError:!0}:{}}})}function Vo(e,t){let n=L(`guide`);e.registerTool(`guide`,{title:n.title,description:`Tool discovery — given a goal description, recommends which AI Kit tools to use and in what order. Matches against 10 predefined workflows: onboard, audit, bugfix, implement, refactor, search, context, memory, validate, analyze.`,inputSchema:{goal:F.string().describe(`What you want to accomplish (e.g., "audit this monorepo", "fix a failing test")`),max_recommendations:F.number().min(1).max(10).default(5).describe(`Maximum number of tool recommendations`)},annotations:n.annotations},async({goal:e,max_recommendations:n})=>{try{let r=Ze(e,n,t),i=[`## Recommended Workflow: **${r.workflow}**`,r.description,``,`### Tools`,...r.tools.map(e=>{let t=e.suggestedArgs?` — \`${JSON.stringify(e.suggestedArgs)}\``:``;return`${e.order}. **${e.tool}** — ${e.reason}${t}`})];return r.alternativeWorkflows.length>0&&i.push(``,`_Alternative workflows: ${r.alternativeWorkflows.join(`, `)}_`),i.push(``,`---`,"_Next: Run the first recommended tool, or use `guide` again with a more specific goal._"),{content:[{type:`text`,text:i.join(`
602
+ `)}]}}catch(e){return Io.error(`Guide failed`,A(e)),{content:[{type:`text`,text:`Guide failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function Ho(e,t,n){if(!(!e||typeof e!=`string`)&&!(e.includes(`..`)||e.startsWith(`/`)||e.startsWith(`[`)))return{type:`resource_link`,uri:`aikit://curated/${e}`,name:t??e,mimeType:`text/markdown`,...n?{description:n}:{}}}function Uo(e){let t=new Set,n=[];for(let r of e){let e=Ho(r.path,r.title,r.category?`[${r.category}]`:void 0);e&&!t.has(e.uri)&&(t.add(e.uri),n.push(e))}return n}function Wo(e){if(e.startsWith(`.ai/curated/`))return e.slice(12)}const Go=E(`tools`);function Ko(e,t){let n=L(`list`);e.registerTool(`list`,{title:n.title,description:`List curated knowledge entries stored via remember. Returns path, title, category, tags, and content preview for each entry. Filter by category (decisions, patterns, conventions) or tag.`,outputSchema:pi,inputSchema:{category:F.string().optional().describe(`Filter by category (e.g., "decisions", "patterns")`),tag:F.string().optional().describe(`Filter by tag`)},annotations:n.annotations},async({category:e,tag:n})=>{try{let r=await t.list({category:e,tag:n}),i={entries:r.map(e=>({path:e.path,title:e.title,category:e.category,tags:e.tags,version:e.version,preview:e.contentPreview?.slice(0,120)??``})),totalCount:r.length};if(r.length===0)return{content:[{type:`text`,text:`No curated knowledge entries found.`+(e?` (category: ${e})`:``)+(n?` (tag: ${n})`:``)}],structuredContent:i};let a=r.map(e=>{let t=e.tags.length>0?` [${e.tags.join(`, `)}]`:``;return`- **${e.title}** (v${e.version})${t}\n \`${e.path}\` — ${e.contentPreview.slice(0,80)}…`}).join(`
603
+ `),o=Uo(r);return{content:[{type:`text`,text:`## Curated Knowledge (${r.length} entries)\n\n${a}\n\n---\n_Next: Use \`read\` to view full content of any entry, or \`remember\` to store new knowledge._`},...o],structuredContent:i}}catch(e){return Go.error(`List failed`,A(e)),{content:[{type:`text`,text:`List failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}const qo=E(`tools`);function Jo(e,t){let n=L(`lookup`);e.registerTool(`lookup`,{title:n.title,description:`Get all indexed content for a known file path, sorted by position. Use when you know the exact file. For discovery across files use search.`,inputSchema:{path:F.string().describe(`Relative file path to look up (e.g., "src/index.ts")`)},annotations:n.annotations},async({path:e})=>{try{let n=await t.getBySourcePath(e);if(n.length===0)return{content:[{type:`text`,text:`No indexed content found for: ${e}`}]};n.sort((e,t)=>e.chunkIndex-t.chunkIndex);let r=`## ${e}\n**Chunks**: ${n.length} | **Type**: ${n[0].contentType}\n`,i=n.map(e=>{let t=e.startLine?` (lines ${e.startLine}-${e.endLine})`:``;return`### Chunk ${e.chunkIndex+1}/${e.totalChunks}${t}\n${e.content}`}).join(`
604
604
 
605
- `),a=Uo(e),o=a?Vo(a):void 0;return{content:[{type:`text`,text:`${r}\n${i}\n\n---\n_Next: Use \`search\` to find related content, or \`analyze_dependencies\` to see what this file imports._`},...o?[o]:[]]}}catch(e){return Ko.error(`Lookup failed`,A(e)),{content:[{type:`text`,text:`Lookup failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}const Jo=E(`tools:manipulation`);function Yo(e){let t=L(`git_context`);e.registerTool(`git_context`,{title:t.title,description:`Summarize the current Git branch, working tree state, recent commits, and optional diff statistics for the repository.`,inputSchema:{cwd:F.string().optional().describe(`Repository root or working directory`),commit_count:F.number().min(1).max(50).default(5).optional().describe(`How many recent commits to include`),include_diff:F.boolean().default(!1).optional().describe(`Include diff stat for working tree changes`)},annotations:t.annotations,outputSchema:Li},async({cwd:e,commit_count:t,include_diff:n})=>{try{let r=await Je({cwd:e,commitCount:t,includeDiff:n});return{content:[{type:`text`,text:es(r)}],structuredContent:{gitRoot:r.gitRoot,branch:r.branch,commitCount:r.recentCommits.length,hasUncommitted:r.status.staged.length>0||r.status.modified.length>0||r.status.untracked.length>0,recentCommits:r.recentCommits.map(e=>({hash:e.hash,message:e.message,author:e.author,date:e.date}))}}}catch(e){return Jo.error(`Git context failed`,A(e)),{content:[{type:`text`,text:`Git context failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function Xo(e){let t=L(`diff_parse`);e.registerTool(`diff_parse`,{title:t.title,description:`Parse raw unified diff text into file-level and hunk-level structural changes.`,inputSchema:{diff:F.string().max(1e6).describe(`Raw unified diff text`)},annotations:t.annotations},async({diff:e})=>{try{return{content:[{type:`text`,text:ts(Fe({diff:e.replace(/\\n/g,`
606
- `).replace(/\\t/g,` `)}))}]}}catch(e){return Jo.error(`Diff parse failed`,A(e)),{content:[{type:`text`,text:`Diff parse failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function Zo(e){let t=L(`rename`);e.registerTool(`rename`,{title:t.title,description:`Rename a symbol across files using whole-word regex matching for exports, imports, and general usage references.`,inputSchema:{old_name:F.string().describe(`Existing symbol name to replace`),new_name:F.string().describe(`New symbol name to use`),root_path:F.string().describe(`Root directory to search within`),extensions:F.array(F.string()).optional().describe(`Optional file extensions to include, such as .ts,.tsx,.js,.jsx`),dry_run:F.boolean().default(!0).describe(`Preview changes without writing files`)},annotations:t.annotations},async({old_name:e,new_name:t,root_path:n,extensions:r,dry_run:i})=>{try{let a=await Dt({oldName:e,newName:t,rootPath:n,extensions:r,dryRun:i});return{content:[{type:`text`,text:JSON.stringify(a)}]}}catch(e){return Jo.error(`Rename failed`,A(e)),{content:[{type:`text`,text:`Rename failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function Qo(e){let t=L(`codemod`);e.registerTool(`codemod`,{title:t.title,description:`Apply regex-based codemod rules across files and return structured before/after changes for each affected line.`,inputSchema:{root_path:F.string().describe(`Root directory to transform within`),rules:F.array(F.object({description:F.string().describe(`What the codemod rule does`),pattern:F.string().describe(`Regex pattern in string form`),replacement:F.string().describe(`Replacement string with optional capture groups`)})).min(1).describe(`Codemod rules to apply`),dry_run:F.boolean().default(!0).describe(`Preview changes without writing files`)},annotations:t.annotations},async({root_path:e,rules:t,dry_run:n})=>{try{let r=await De({rootPath:e,rules:t,dryRun:n});return{content:[{type:`text`,text:JSON.stringify(r)}]}}catch(e){return Jo.error(`Codemod failed`,A(e)),{content:[{type:`text`,text:`Codemod failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function $o(e){let t=L(`data_transform`);e.registerTool(`data_transform`,{title:t.title,description:`Apply small jq-like transforms to JSON input for filtering, projection, grouping, and path extraction.`,inputSchema:{input:F.string().max(5e5).describe(`Input JSON string`),expression:F.string().max(1e4).describe(`Transform expression to apply`)},annotations:t.annotations},async({input:e,expression:t})=>{try{return{content:[{type:`text`,text:je({input:e,expression:t}).outputString}]}}catch(e){return Jo.error(`Data transform failed`,A(e)),{content:[{type:`text`,text:`Data transform failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function es(e){let t=[`Git root: ${e.gitRoot}`,`Branch: ${e.branch}`,`Staged: ${e.status.staged.length}`,...e.status.staged.map(e=>` - ${e}`),`Modified: ${e.status.modified.length}`,...e.status.modified.map(e=>` - ${e}`),`Untracked: ${e.status.untracked.length}`,...e.status.untracked.map(e=>` - ${e}`),``,`Recent commits:`];if(e.recentCommits.length===0)t.push(` none`);else for(let n of e.recentCommits)t.push(` - ${n.hash} ${n.message}`),t.push(` ${n.author} @ ${n.date}`);return e.diff&&t.push(``,`Diff stat:`,e.diff),t.join(`
607
- `)}function ts(e){if(e.length===0)return`No diff files found.`;let t=[];for(let n of e){let e=n.oldPath?` (from ${n.oldPath})`:``;t.push(`${n.path}${e} [${n.status}] +${n.additions} -${n.deletions} (${n.hunks.length} hunks)`);for(let e of n.hunks){let n=e.header?` ${e.header}`:``;t.push(` @@ -${e.oldStart},${e.oldLines} +${e.newStart},${e.newLines} @@${n}`)}}return t.join(`
608
- `)}const ns=[`list_tools`,`describe_tool`,`search_tools`];function rs(e,t,n){let r=[...new Set(n)].sort();e.registerTool(`list_tools`,{title:L(`list_tools`).title,description:`List the available AI Kit tools with names, titles, and categories. Use this before describe_tool when you need to discover the active toolset.`,inputSchema:{category:F.string().optional().describe(`Optional category filter`)},annotations:L(`list_tools`).annotations},async({category:e})=>{let t=e?.trim().toLowerCase();return{content:[{type:`text`,text:r.filter(e=>t?(ur[e]?.category??[]).some(e=>e.toLowerCase()===t):!0).map(e=>{let t=ur[e]??{title:e,category:[]},n=t.category?.join(`, `)||`uncategorized`;return`${e}: ${t.title} [${n}]`}).join(`
605
+ `),a=Wo(e),o=a?Ho(a):void 0;return{content:[{type:`text`,text:`${r}\n${i}\n\n---\n_Next: Use \`search\` to find related content, or \`analyze_dependencies\` to see what this file imports._`},...o?[o]:[]]}}catch(e){return qo.error(`Lookup failed`,A(e)),{content:[{type:`text`,text:`Lookup failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}const Yo=E(`tools:manipulation`);function Xo(e){let t=L(`git_context`);e.registerTool(`git_context`,{title:t.title,description:`Summarize the current Git branch, working tree state, recent commits, and optional diff statistics for the repository.`,inputSchema:{cwd:F.string().optional().describe(`Repository root or working directory`),commit_count:F.number().min(1).max(50).default(5).optional().describe(`How many recent commits to include`),include_diff:F.boolean().default(!1).optional().describe(`Include diff stat for working tree changes`)},annotations:t.annotations,outputSchema:Li},async({cwd:e,commit_count:t,include_diff:n})=>{try{let r=await Je({cwd:e,commitCount:t,includeDiff:n});return{content:[{type:`text`,text:ts(r)}],structuredContent:{gitRoot:r.gitRoot,branch:r.branch,commitCount:r.recentCommits.length,hasUncommitted:r.status.staged.length>0||r.status.modified.length>0||r.status.untracked.length>0,recentCommits:r.recentCommits.map(e=>({hash:e.hash,message:e.message,author:e.author,date:e.date}))}}}catch(e){return Yo.error(`Git context failed`,A(e)),{content:[{type:`text`,text:`Git context failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function Zo(e){let t=L(`diff_parse`);e.registerTool(`diff_parse`,{title:t.title,description:`Parse raw unified diff text into file-level and hunk-level structural changes.`,inputSchema:{diff:F.string().max(1e6).describe(`Raw unified diff text`)},annotations:t.annotations},async({diff:e})=>{try{return{content:[{type:`text`,text:ns(Fe({diff:e.replace(/\\n/g,`
606
+ `).replace(/\\t/g,` `)}))}]}}catch(e){return Yo.error(`Diff parse failed`,A(e)),{content:[{type:`text`,text:`Diff parse failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function Qo(e){let t=L(`rename`);e.registerTool(`rename`,{title:t.title,description:`Rename a symbol across files using whole-word regex matching for exports, imports, and general usage references.`,inputSchema:{old_name:F.string().describe(`Existing symbol name to replace`),new_name:F.string().describe(`New symbol name to use`),root_path:F.string().describe(`Root directory to search within`),extensions:F.array(F.string()).optional().describe(`Optional file extensions to include, such as .ts,.tsx,.js,.jsx`),dry_run:F.boolean().default(!0).describe(`Preview changes without writing files`)},annotations:t.annotations},async({old_name:e,new_name:t,root_path:n,extensions:r,dry_run:i})=>{try{let a=await Dt({oldName:e,newName:t,rootPath:n,extensions:r,dryRun:i});return{content:[{type:`text`,text:JSON.stringify(a)}]}}catch(e){return Yo.error(`Rename failed`,A(e)),{content:[{type:`text`,text:`Rename failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function $o(e){let t=L(`codemod`);e.registerTool(`codemod`,{title:t.title,description:`Apply regex-based codemod rules across files and return structured before/after changes for each affected line.`,inputSchema:{root_path:F.string().describe(`Root directory to transform within`),rules:F.array(F.object({description:F.string().describe(`What the codemod rule does`),pattern:F.string().describe(`Regex pattern in string form`),replacement:F.string().describe(`Replacement string with optional capture groups`)})).min(1).describe(`Codemod rules to apply`),dry_run:F.boolean().default(!0).describe(`Preview changes without writing files`)},annotations:t.annotations},async({root_path:e,rules:t,dry_run:n})=>{try{let r=await De({rootPath:e,rules:t,dryRun:n});return{content:[{type:`text`,text:JSON.stringify(r)}]}}catch(e){return Yo.error(`Codemod failed`,A(e)),{content:[{type:`text`,text:`Codemod failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function es(e){let t=L(`data_transform`);e.registerTool(`data_transform`,{title:t.title,description:`Apply small jq-like transforms to JSON input for filtering, projection, grouping, and path extraction.`,inputSchema:{input:F.string().max(5e5).describe(`Input JSON string`),expression:F.string().max(1e4).describe(`Transform expression to apply`)},annotations:t.annotations},async({input:e,expression:t})=>{try{return{content:[{type:`text`,text:je({input:e,expression:t}).outputString}]}}catch(e){return Yo.error(`Data transform failed`,A(e)),{content:[{type:`text`,text:`Data transform failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function ts(e){let t=[`Git root: ${e.gitRoot}`,`Branch: ${e.branch}`,`Staged: ${e.status.staged.length}`,...e.status.staged.map(e=>` - ${e}`),`Modified: ${e.status.modified.length}`,...e.status.modified.map(e=>` - ${e}`),`Untracked: ${e.status.untracked.length}`,...e.status.untracked.map(e=>` - ${e}`),``,`Recent commits:`];if(e.recentCommits.length===0)t.push(` none`);else for(let n of e.recentCommits)t.push(` - ${n.hash} ${n.message}`),t.push(` ${n.author} @ ${n.date}`);return e.diff&&t.push(``,`Diff stat:`,e.diff),t.join(`
607
+ `)}function ns(e){if(e.length===0)return`No diff files found.`;let t=[];for(let n of e){let e=n.oldPath?` (from ${n.oldPath})`:``;t.push(`${n.path}${e} [${n.status}] +${n.additions} -${n.deletions} (${n.hunks.length} hunks)`);for(let e of n.hunks){let n=e.header?` ${e.header}`:``;t.push(` @@ -${e.oldStart},${e.oldLines} +${e.newStart},${e.newLines} @@${n}`)}}return t.join(`
608
+ `)}const rs=[`list_tools`,`describe_tool`,`search_tools`];function is(e,t,n){let r=[...new Set(n)].sort();e.registerTool(`list_tools`,{title:L(`list_tools`).title,description:`List the available AI Kit tools with names, titles, and categories. Use this before describe_tool when you need to discover the active toolset.`,inputSchema:{category:F.string().optional().describe(`Optional category filter`)},annotations:L(`list_tools`).annotations},async({category:e})=>{let t=e?.trim().toLowerCase();return{content:[{type:`text`,text:r.filter(e=>t?(ur[e]?.category??[]).some(e=>e.toLowerCase()===t):!0).map(e=>{let t=ur[e]??{title:e,category:[]},n=t.category?.join(`, `)||`uncategorized`;return`${e}: ${t.title} [${n}]`}).join(`
609
609
  `)||`No tools matched the filter.`}]}}),e.registerTool(`describe_tool`,{title:L(`describe_tool`).title,description:`Describe a specific active AI Kit tool using centralized metadata. Use this after list_tools when you need a tool title, categories, and annotations before calling it directly.`,inputSchema:{tool_name:F.string().describe(`The active tool name to describe`)},annotations:L(`describe_tool`).annotations},async({tool_name:e})=>{if(!r.includes(e))return{content:[{type:`text`,text:`Unknown or inactive tool: ${e}`}],isError:!0};let t=ur[e],n={name:e,title:t?.title??e,categories:t?.category??[],annotations:t?.annotations??{},note:`Call the tool directly after discovery. AI Kit does not expose an execute_tool proxy.`};return{content:[{type:`text`,text:JSON.stringify(n,null,2)}]}}),e.registerTool(`search_tools`,{title:L(`search_tools`).title,description:`Search active AI Kit tools by keyword across tool names, titles, and categories.`,inputSchema:{query:F.string().min(1).describe(`Keyword query to match against active tools`)},annotations:L(`search_tools`).annotations},async({query:e})=>{let t=e.trim().toLowerCase(),n=r.filter(e=>{let n=ur[e];return e.toLowerCase().includes(t)||n?.title.toLowerCase().includes(t)||(n?.category??[]).some(e=>e.toLowerCase().includes(t))}).map(e=>{let t=ur[e]??{title:e,category:[]},n=t.category?.join(`, `)||`uncategorized`;return`${e}: ${t.title} [${n}]`});return{content:[{type:`text`,text:n.length>0?n.join(`
610
- `):`No tools found matching "${e}"`}]}})}const is=E(`tools`);let as=!1;async function os(e,t,n){for(let r of n.steps)if(!(r.status!==`success`||!r.output))try{let i=j(`sha256`).update(n.path).digest(`hex`).slice(0,12),a=`produced/onboard/${r.name}/${i}.md`,o=j(`sha256`).update(r.output).digest(`hex`).slice(0,16),s=new Date().toISOString(),c=r.output.length>2e3?r.output.split(/(?=^## )/m).filter(e=>e.trim().length>0):[r.output],l=c.map((e,t)=>({id:j(`sha256`).update(`${a}::${t}`).digest(`hex`).slice(0,16),content:e.trim(),sourcePath:a,contentType:`produced-knowledge`,chunkIndex:t,totalChunks:c.length,startLine:0,endLine:0,fileHash:o,indexedAt:s,origin:`produced`,tags:[`onboard`,r.name],category:`analysis`,version:1})),u=await t.embedBatch(l.map(e=>e.content));await e.upsert(l,u)}catch(e){is.warn(`Auto-persist onboard step failed`,{stepName:r.name,...A(e)})}}async function ss(e,t,n){if(n.autoRemember?.length)for(let r of n.autoRemember)try{let n=j(`sha256`).update(`onboard-remember::${r.title}`).digest(`hex`).slice(0,16),i=new Date().toISOString(),a={id:n,content:`# ${r.title}\n\n${r.content}`,sourcePath:`curated/onboard/${r.category}/${n}.md`,contentType:`curated`,chunkIndex:0,totalChunks:1,startLine:0,endLine:0,fileHash:j(`sha256`).update(r.content).digest(`hex`).slice(0,16),indexedAt:i,origin:`curated`,tags:r.tags,category:r.category,version:1},[o]=await t.embedBatch([a.content]);await e.upsert([a],[o])}catch(e){is.warn(`Auto-persist remember entry failed`,{title:r.title,...A(e)})}}function cs(e,t,n,r,i){let a=L(`onboard`);e.registerTool(`onboard`,{title:a.title,description:`First-time codebase onboarding: runs all analysis tools (structure, dependencies, entry-points, symbols, patterns, diagram) in one command. Results are auto-persisted to KB. Use mode=generate to also write structured output to .ai/context/ directory.`,inputSchema:{path:F.string().describe(`Root path of the codebase to onboard`),mode:F.enum([`memory`,`generate`]).default(`generate`).describe(`Output mode: generate (default) = persist to AI Kit + write .ai/context/ files; memory = AI Kit vector store only`),out_dir:F.string().optional().describe(`Custom output directory for generate mode (default: <path>/.ai/context)`)},annotations:a.annotations},async({path:e,mode:a,out_dir:o},s)=>{try{if(as)return{content:[{type:`text`,text:`Onboard is already running. Please wait for it to complete before starting another.`}]};as=!0,is.info(`Starting onboard`,{path:e,mode:a});let c=await lt({path:e,mode:a,outDir:o??r?.onboardDir}),l=na(s).createTask(`Onboard`,c.steps.length);for(let e=0;e<c.steps.length;e++){let t=c.steps[e];l.progress(e,`${t.name}: ${t.status}`)}l.complete(`Onboard complete: ${c.steps.filter(e=>e.status===`success`).length}/${c.steps.length} steps succeeded`),os(t,n,c),c.autoRemember?.length&&ss(t,n,c).catch(e=>{is.warn(`Auto-persist autoRemember failed`,A(e))}),i&&(i.onboardComplete=!0,i.onboardTimestamp=new Date().toISOString());let u=[`## Onboard Complete`,``,`**Path:** \`${c.path}\``,`**Mode:** ${c.mode}`,`**Duration:** ${c.totalDurationMs}ms`,``];c.outDir&&(u.push(`**Output directory:** \`${c.outDir}\``),u.push(``)),u.push(`### Analysis Results`,``);let d=[],f=[];for(let e of c.steps)e.status===`success`?d.push(`- ✓ **${e.name}** (${e.durationMs}ms) — ${e.output.length} chars`):f.push(`- ✗ **${e.name}** — ${e.error}`);u.push(...d),f.length>0&&u.push(``,`### Failed`,``,...f),u.push(``,`---`,``);for(let e of c.steps)e.status===`success`&&u.push(`### ${e.name}`,``,e.output,``,`---`,``);return u.push(`_All results auto-saved to KB.`,c.mode===`generate`?` Files written to \`${c.outDir}\`.`:``," Next: Use `search` to query the knowledge, or `remember` to add custom insights._"),{content:[{type:`text`,text:u.join(`
611
- `)}]}}catch(e){return is.error(`Onboard failed`,A(e)),{content:[{type:`text`,text:`Onboard failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}finally{as=!1}})}const ls=E(`tools:persistence`);function us(e){let t=L(`workset`);e.registerTool(`workset`,{title:t.title,description:`Manage named file sets (worksets). Save, load, list, add/remove files. Worksets persist across sessions in .aikit-state/worksets.json.`,inputSchema:{action:F.enum([`save`,`get`,`list`,`delete`,`add`,`remove`]).describe(`Operation to perform`),name:F.string().optional().describe(`Workset name (required for all except list)`),files:F.array(F.string()).optional().describe(`File paths (required for save, add, remove)`),description:F.string().optional().describe(`Description (for save)`)},annotations:t.annotations},async({action:e,name:t,files:n,description:r})=>{try{switch(e){case`save`:{if(!t||!n)throw Error(`name and files required for save`);let e=Nt(t,n,{description:r});return{content:[{type:`text`,text:`Saved workset "${e.name}" with ${e.files.length} files.`}]}}case`get`:{if(!t)throw Error(`name required for get`);let e=qe(t);return e?{content:[{type:`text`,text:JSON.stringify(e)}]}:{content:[{type:`text`,text:`Workset "${t}" not found.`}]}}case`list`:{let e=st();return e.length===0?{content:[{type:`text`,text:`No worksets.`}]}:{content:[{type:`text`,text:e.map(e=>`- **${e.name}** (${e.files.length} files) — ${e.description??`no description`}`).join(`
612
- `)}]}}case`delete`:if(!t)throw Error(`name required for delete`);return{content:[{type:`text`,text:Pe(t)?`Deleted workset "${t}".`:`Workset "${t}" not found.`}]};case`add`:{if(!t||!n)throw Error(`name and files required for add`);let e=_e(t,n);return{content:[{type:`text`,text:`Added to workset "${e.name}": now ${e.files.length} files.`}]}}case`remove`:{if(!t||!n)throw Error(`name and files required for remove`);let e=Et(t,n);return e?{content:[{type:`text`,text:`Removed from workset "${e.name}": now ${e.files.length} files.`}]}:{content:[{type:`text`,text:`Workset "${t}" not found.`}]}}}}catch(e){return ls.error(`Workset operation failed`,A(e)),{content:[{type:`text`,text:`Workset operation failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function ds(e){let t=L(`stash`);e.registerTool(`stash`,{title:t.title,description:`Persist and retrieve named values in .aikit-state/stash.json for intermediate results between tool calls.`,inputSchema:{action:F.enum([`set`,`get`,`list`,`delete`,`clear`]).describe(`Operation to perform on the stash`),key:F.string().optional().describe(`Entry key for set/get/delete operations`),value:F.string().optional().describe(`String or JSON value for set operations`)},annotations:t.annotations},async({action:e,key:t,value:n})=>{try{switch(e){case`set`:{if(!t)throw Error(`key required for set`);let e=Ut(t,gs(n??``));return{content:[{type:`text`,text:`Stored stash entry "${e.key}" (${e.type}) at ${e.storedAt}.`}]}}case`get`:{if(!t)throw Error(`key required for get`);let e=Vt(t);return{content:[{type:`text`,text:e?JSON.stringify(e):`Stash entry "${t}" not found.`}]}}case`list`:{let e=Ht();return{content:[{type:`text`,text:e.length===0?`Stash is empty.`:e.map(e=>`- ${e.key} (${e.type}) — ${e.storedAt}`).join(`
613
- `)}]}}case`delete`:if(!t)throw Error(`key required for delete`);return{content:[{type:`text`,text:Bt(t)?`Deleted stash entry "${t}".`:`Stash entry "${t}" not found.`}]};case`clear`:{let e=zt();return{content:[{type:`text`,text:`Cleared ${e} stash entr${e===1?`y`:`ies`}.`}]}}}}catch(e){return ls.error(`Stash operation failed`,A(e)),{content:[{type:`text`,text:`Stash operation failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function fs(e){let t=L(`checkpoint`);e.registerTool(`checkpoint`,{title:t.title,description:`Save and restore lightweight session checkpoints in .aikit-state/checkpoints for cross-session continuity.`,inputSchema:{action:F.enum([`save`,`load`,`list`,`latest`]).describe(`Checkpoint action to perform`),label:F.string().optional().describe(`Checkpoint label for save, or checkpoint id for load`),data:F.string().max(5e5).optional().describe(`JSON object string for save actions`),notes:F.string().max(1e4).optional().describe(`Optional notes for save actions`)},annotations:t.annotations},async({action:e,label:t,data:n,notes:r})=>{try{switch(e){case`save`:if(!t)throw Error(`label required for save`);return{content:[{type:`text`,text:hs(Ee(t,_s(n),{notes:r}))}]};case`load`:{if(!t)throw Error(`label required for load`);let e=Te(t);return{content:[{type:`text`,text:e?hs(e):`Checkpoint "${t}" not found.`}]}}case`list`:{let e=we();return{content:[{type:`text`,text:e.length===0?`No checkpoints saved.`:e.map(e=>`- ${e.id} — ${e.label} (${e.createdAt})`).join(`
614
- `)}]}}case`latest`:{let e=Ce();return{content:[{type:`text`,text:e?hs(e):`No checkpoints saved.`}]}}}}catch(e){return ls.error(`Checkpoint failed`,A(e)),{content:[{type:`text`,text:`Checkpoint failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function ps(e){let t=L(`lane`);e.registerTool(`lane`,{title:t.title,description:`Manage verified lanes — isolated file copies for parallel exploration. Create a lane, make changes, diff, merge back, or discard.`,inputSchema:{action:F.enum([`create`,`list`,`status`,`diff`,`merge`,`discard`]).describe(`Lane action to perform`),name:F.string().optional().describe(`Lane name (required for create/status/diff/merge/discard)`),files:F.array(F.string()).optional().describe(`File paths to copy into the lane (required for create)`)},annotations:t.annotations},async({action:e,name:t,files:n})=>{try{switch(e){case`create`:{if(!t)throw Error(`name is required for create`);if(!n||n.length===0)throw Error(`files are required for create`);let e=et(t,n);return{content:[{type:`text`,text:JSON.stringify(e)}]}}case`list`:return{content:[{type:`text`,text:JSON.stringify(rt())}]};case`status`:if(!t)throw Error(`name is required for status`);return{content:[{type:`text`,text:JSON.stringify(at(t))}]};case`diff`:if(!t)throw Error(`name is required for diff`);return{content:[{type:`text`,text:JSON.stringify(tt(t))}]};case`merge`:if(!t)throw Error(`name is required for merge`);return{content:[{type:`text`,text:JSON.stringify(it(t))}]};case`discard`:if(!t)throw Error(`name is required for discard`);return{content:[{type:`text`,text:JSON.stringify({discarded:nt(t)})}]}}}catch(e){return ls.error(`Lane action failed`,A(e)),{content:[{type:`text`,text:`Lane action failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function ms(e){let t=L(`queue`);e.registerTool(`queue`,{title:t.title,description:`Manage task queues for sequential agent operations. Push items, take next, mark done/failed, list queues.`,inputSchema:{action:F.enum([`create`,`push`,`next`,`done`,`fail`,`get`,`list`,`clear`,`delete`]).describe(`Queue action`),name:F.string().optional().describe(`Queue name (required for most actions)`),title:F.string().optional().describe(`Item title (required for push)`),id:F.string().optional().describe(`Item ID (required for done/fail)`),data:F.unknown().optional().describe(`Arbitrary data to attach to a queue item`),error:F.string().optional().describe(`Error message (required for fail)`)},annotations:t.annotations},async({action:e,name:t,title:n,id:r,data:i,error:a})=>{try{switch(e){case`create`:if(!t)throw Error(`name is required for create`);return{content:[{type:`text`,text:JSON.stringify(_t(t))}]};case`push`:if(!t)throw Error(`name is required for push`);if(!n)throw Error(`title is required for push`);return{content:[{type:`text`,text:JSON.stringify(wt(t,n,i))}]};case`next`:{if(!t)throw Error(`name is required for next`);let e=Ct(t);return{content:[{type:`text`,text:JSON.stringify(e)}]}}case`done`:if(!t)throw Error(`name is required for done`);if(!r)throw Error(`id is required for done`);return{content:[{type:`text`,text:JSON.stringify(yt(t,r))}]};case`fail`:if(!t)throw Error(`name is required for fail`);if(!r)throw Error(`id is required for fail`);if(!a)throw Error(`error is required for fail`);return{content:[{type:`text`,text:JSON.stringify(bt(t,r,a))}]};case`get`:if(!t)throw Error(`name is required for get`);return{content:[{type:`text`,text:JSON.stringify(xt(t))}]};case`list`:return{content:[{type:`text`,text:JSON.stringify(St())}]};case`clear`:if(!t)throw Error(`name is required for clear`);return{content:[{type:`text`,text:JSON.stringify({cleared:gt(t)})}]};case`delete`:if(!t)throw Error(`name is required for delete`);return{content:[{type:`text`,text:JSON.stringify({deleted:vt(t)})}]}}}catch(e){return ls.error(`Queue action failed`,A(e)),{content:[{type:`text`,text:`Queue action failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function hs(e){let t=[e.id,`Label: ${e.label}`,`Created: ${e.createdAt}`];if(e.notes&&t.push(`Notes: ${e.notes}`),e.files?.length){t.push(`Files: ${e.files.length}`);for(let n of e.files)t.push(` - ${n}`)}return t.push(``,`Data:`,JSON.stringify(e.data)),t.join(`
615
- `)}function gs(e){let t=e.trim();if(!t)return``;try{return JSON.parse(t)}catch{return e}}function _s(e){let t=e?.trim();if(!t)return{};let n;try{n=JSON.parse(t)}catch{throw Error(`data must be a valid JSON object string`)}if(!n||typeof n!=`object`||Array.isArray(n))throw Error(`data must be a JSON object string`);return n}const vs=E(`tools`);function ys(e){let t=[`## Rule: ${e.id}`,``,`- **Status**: ${e.enabled?`enabled`:`disabled`}`,`- **Description**: ${e.description??`—`}`,`- **Category**: ${e.category??`—`}`,`- **Push weight**: ${e.pushWeight??`—`}`];return e.patterns?.length&&t.push(`- **Patterns**: ${e.patterns.join(`, `)}`),e.examples?.length&&t.push(`- **Examples**: ${e.examples.join(`, `)}`),t.join(`
616
- `)}function bs(e,t){let n=L(`er_update_policy`);e.registerTool(`er_update_policy`,{title:n.title,description:`Manage ER push classification rules. Supports listing, updating, creating, and deleting rules that determine when knowledge should be pushed to Enterprise RAG.`,inputSchema:{action:F.enum([`list`,`get`,`update`,`create`,`delete`]).describe(`Action to perform on classification rules`),rule_id:F.string().optional().describe(`Rule ID (required for get, update, delete)`),changes:F.object({patterns:F.array(F.string()).optional(),category:F.string().optional(),pushWeight:F.number().min(0).max(1).optional(),description:F.string().optional(),examples:F.array(F.string()).optional(),enabled:F.boolean().optional()}).optional().describe(`Changes to apply (for update action)`),new_rule:F.object({id:F.string().regex(/^[a-z][a-z0-9-]*$/),patterns:F.array(F.string()).min(1),category:F.string(),pushWeight:F.number().min(0).max(1),description:F.string(),examples:F.array(F.string()).default([]),enabled:F.boolean().default(!0)}).optional().describe(`New rule definition (for create action)`)},annotations:n.annotations},async({action:e,rule_id:n,changes:r,new_rule:i})=>{try{if(e===`list`){let e=t.getRules();return{content:[{type:`text`,text:`## Classification Rules\n\n${e.map(e=>`- **${e.id}** (${e.enabled?`enabled`:`disabled`}) — ${e.description}\n Category: ${e.category} | Weight: ${e.pushWeight} | Patterns: ${e.patterns.join(`, `)}`).join(`
617
- `)}\n\n---\n_${e.length} rules total. Use \`action: "update"\` to modify a rule._`}]}}if(e===`get`){if(!n)return{content:[{type:`text`,text:'`rule_id` is required for "get" action.'}],isError:!0};let e=t.getRule(n);return e?{content:[{type:`text`,text:ys(e)}]}:{content:[{type:`text`,text:`Rule "${n}" not found.`}],isError:!0}}if(e===`update`){if(!n||!r)return{content:[{type:`text`,text:'`rule_id` and `changes` are required for "update" action.'}],isError:!0};let e=t.updateRule(n,r);return e?{content:[{type:`text`,text:`${ys(e)}\n\n---\n_Updated. Next: Use \`action: "list"\` to verify._`}]}:{content:[{type:`text`,text:`Rule "${n}" not found.`}],isError:!0}}return e===`create`?i?{content:[{type:`text`,text:`${ys(t.addRule(i))}\n\n---\n_Created. Next: Test classification with \`remember\`._`}]}:{content:[{type:`text`,text:'`new_rule` is required for "create" action.'}],isError:!0}:e===`delete`?n?t.deleteRule(n)?{content:[{type:`text`,text:`Deleted rule **${n}**.\n\n---\n_Next: Use \`action: "list"\` to verify._`}]}:{content:[{type:`text`,text:`Rule "${n}" not found.`}],isError:!0}:{content:[{type:`text`,text:'`rule_id` is required for "delete" action.'}],isError:!0}:{content:[{type:`text`,text:`Unknown action: ${e}`}],isError:!0}}catch(e){return vs.error(`Policy update failed`,A(e)),{content:[{type:`text`,text:`Policy update failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function xs(){return`
610
+ `):`No tools found matching "${e}"`}]}})}const as=E(`tools`);let os=!1;async function ss(e,t,n){for(let r of n.steps)if(!(r.status!==`success`||!r.output))try{let i=j(`sha256`).update(n.path).digest(`hex`).slice(0,12),a=`produced/onboard/${r.name}/${i}.md`,o=j(`sha256`).update(r.output).digest(`hex`).slice(0,16),s=new Date().toISOString(),c=r.output.length>2e3?r.output.split(/(?=^## )/m).filter(e=>e.trim().length>0):[r.output],l=c.map((e,t)=>({id:j(`sha256`).update(`${a}::${t}`).digest(`hex`).slice(0,16),content:e.trim(),sourcePath:a,contentType:`produced-knowledge`,chunkIndex:t,totalChunks:c.length,startLine:0,endLine:0,fileHash:o,indexedAt:s,origin:`produced`,tags:[`onboard`,r.name],category:`analysis`,version:1})),u=await t.embedBatch(l.map(e=>e.content));await e.upsert(l,u)}catch(e){as.warn(`Auto-persist onboard step failed`,{stepName:r.name,...A(e)})}}async function cs(e,t,n){if(n.autoRemember?.length)for(let r of n.autoRemember)try{let n=j(`sha256`).update(`onboard-remember::${r.title}`).digest(`hex`).slice(0,16),i=new Date().toISOString(),a={id:n,content:`# ${r.title}\n\n${r.content}`,sourcePath:`curated/onboard/${r.category}/${n}.md`,contentType:`curated`,chunkIndex:0,totalChunks:1,startLine:0,endLine:0,fileHash:j(`sha256`).update(r.content).digest(`hex`).slice(0,16),indexedAt:i,origin:`curated`,tags:r.tags,category:r.category,version:1},[o]=await t.embedBatch([a.content]);await e.upsert([a],[o])}catch(e){as.warn(`Auto-persist remember entry failed`,{title:r.title,...A(e)})}}function ls(e,t,n,r,i){let a=L(`onboard`);e.registerTool(`onboard`,{title:a.title,description:`First-time codebase onboarding: runs all analysis tools (structure, dependencies, entry-points, symbols, patterns, diagram) in one command. Results are auto-persisted to KB. Use mode=generate to also write structured output to .ai/context/ directory.`,inputSchema:{path:F.string().describe(`Root path of the codebase to onboard`),mode:F.enum([`memory`,`generate`]).default(`generate`).describe(`Output mode: generate (default) = persist to AI Kit + write .ai/context/ files; memory = AI Kit vector store only`),out_dir:F.string().optional().describe(`Custom output directory for generate mode (default: <path>/.ai/context)`)},annotations:a.annotations},async({path:e,mode:a,out_dir:o},s)=>{try{if(os)return{content:[{type:`text`,text:`Onboard is already running. Please wait for it to complete before starting another.`}]};os=!0,as.info(`Starting onboard`,{path:e,mode:a});let c=await lt({path:e,mode:a,outDir:o??r?.onboardDir}),l=na(s).createTask(`Onboard`,c.steps.length);for(let e=0;e<c.steps.length;e++){let t=c.steps[e];l.progress(e,`${t.name}: ${t.status}`)}l.complete(`Onboard complete: ${c.steps.filter(e=>e.status===`success`).length}/${c.steps.length} steps succeeded`),ss(t,n,c),c.autoRemember?.length&&cs(t,n,c).catch(e=>{as.warn(`Auto-persist autoRemember failed`,A(e))}),i&&(i.onboardComplete=!0,i.onboardTimestamp=new Date().toISOString());let u=[`## Onboard Complete`,``,`**Path:** \`${c.path}\``,`**Mode:** ${c.mode}`,`**Duration:** ${c.totalDurationMs}ms`,``];c.outDir&&(u.push(`**Output directory:** \`${c.outDir}\``),u.push(``)),u.push(`### Analysis Results`,``);let d=[],f=[];for(let e of c.steps)e.status===`success`?d.push(`- ✓ **${e.name}** (${e.durationMs}ms) — ${e.output.length} chars`):f.push(`- ✗ **${e.name}** — ${e.error}`);u.push(...d),f.length>0&&u.push(``,`### Failed`,``,...f),u.push(``,`---`,``);for(let e of c.steps)e.status===`success`&&u.push(`### ${e.name}`,``,e.output,``,`---`,``);return u.push(`_All results auto-saved to KB.`,c.mode===`generate`?` Files written to \`${c.outDir}\`.`:``," Next: Use `search` to query the knowledge, or `remember` to add custom insights._"),{content:[{type:`text`,text:u.join(`
611
+ `)}]}}catch(e){return as.error(`Onboard failed`,A(e)),{content:[{type:`text`,text:`Onboard failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}finally{os=!1}})}const us=E(`tools:persistence`);function ds(e){let t=L(`workset`);e.registerTool(`workset`,{title:t.title,description:`Manage named file sets (worksets). Save, load, list, add/remove files. Worksets persist across sessions in .aikit-state/worksets.json.`,inputSchema:{action:F.enum([`save`,`get`,`list`,`delete`,`add`,`remove`]).describe(`Operation to perform`),name:F.string().optional().describe(`Workset name (required for all except list)`),files:F.array(F.string()).optional().describe(`File paths (required for save, add, remove)`),description:F.string().optional().describe(`Description (for save)`)},annotations:t.annotations},async({action:e,name:t,files:n,description:r})=>{try{switch(e){case`save`:{if(!t||!n)throw Error(`name and files required for save`);let e=Nt(t,n,{description:r});return{content:[{type:`text`,text:`Saved workset "${e.name}" with ${e.files.length} files.`}]}}case`get`:{if(!t)throw Error(`name required for get`);let e=qe(t);return e?{content:[{type:`text`,text:JSON.stringify(e)}]}:{content:[{type:`text`,text:`Workset "${t}" not found.`}]}}case`list`:{let e=st();return e.length===0?{content:[{type:`text`,text:`No worksets.`}]}:{content:[{type:`text`,text:e.map(e=>`- **${e.name}** (${e.files.length} files) — ${e.description??`no description`}`).join(`
612
+ `)}]}}case`delete`:if(!t)throw Error(`name required for delete`);return{content:[{type:`text`,text:Pe(t)?`Deleted workset "${t}".`:`Workset "${t}" not found.`}]};case`add`:{if(!t||!n)throw Error(`name and files required for add`);let e=_e(t,n);return{content:[{type:`text`,text:`Added to workset "${e.name}": now ${e.files.length} files.`}]}}case`remove`:{if(!t||!n)throw Error(`name and files required for remove`);let e=Et(t,n);return e?{content:[{type:`text`,text:`Removed from workset "${e.name}": now ${e.files.length} files.`}]}:{content:[{type:`text`,text:`Workset "${t}" not found.`}]}}}}catch(e){return us.error(`Workset operation failed`,A(e)),{content:[{type:`text`,text:`Workset operation failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function fs(e){let t=L(`stash`);e.registerTool(`stash`,{title:t.title,description:`Persist and retrieve named values in .aikit-state/stash.json for intermediate results between tool calls.`,inputSchema:{action:F.enum([`set`,`get`,`list`,`delete`,`clear`]).describe(`Operation to perform on the stash`),key:F.string().optional().describe(`Entry key for set/get/delete operations`),value:F.string().optional().describe(`String or JSON value for set operations`)},annotations:t.annotations},async({action:e,key:t,value:n})=>{try{switch(e){case`set`:{if(!t)throw Error(`key required for set`);let e=Ut(t,_s(n??``));return{content:[{type:`text`,text:`Stored stash entry "${e.key}" (${e.type}) at ${e.storedAt}.`}]}}case`get`:{if(!t)throw Error(`key required for get`);let e=Vt(t);return{content:[{type:`text`,text:e?JSON.stringify(e):`Stash entry "${t}" not found.`}]}}case`list`:{let e=Ht();return{content:[{type:`text`,text:e.length===0?`Stash is empty.`:e.map(e=>`- ${e.key} (${e.type}) — ${e.storedAt}`).join(`
613
+ `)}]}}case`delete`:if(!t)throw Error(`key required for delete`);return{content:[{type:`text`,text:Bt(t)?`Deleted stash entry "${t}".`:`Stash entry "${t}" not found.`}]};case`clear`:{let e=zt();return{content:[{type:`text`,text:`Cleared ${e} stash entr${e===1?`y`:`ies`}.`}]}}}}catch(e){return us.error(`Stash operation failed`,A(e)),{content:[{type:`text`,text:`Stash operation failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function ps(e){let t=L(`checkpoint`);e.registerTool(`checkpoint`,{title:t.title,description:`Save and restore lightweight session checkpoints in .aikit-state/checkpoints for cross-session continuity.`,inputSchema:{action:F.enum([`save`,`load`,`list`,`latest`]).describe(`Checkpoint action to perform`),label:F.string().optional().describe(`Checkpoint label for save, or checkpoint id for load`),data:F.string().max(5e5).optional().describe(`JSON object string for save actions`),notes:F.string().max(1e4).optional().describe(`Optional notes for save actions`)},annotations:t.annotations},async({action:e,label:t,data:n,notes:r})=>{try{switch(e){case`save`:if(!t)throw Error(`label required for save`);return{content:[{type:`text`,text:gs(Ee(t,vs(n),{notes:r}))}]};case`load`:{if(!t)throw Error(`label required for load`);let e=Te(t);return{content:[{type:`text`,text:e?gs(e):`Checkpoint "${t}" not found.`}]}}case`list`:{let e=we();return{content:[{type:`text`,text:e.length===0?`No checkpoints saved.`:e.map(e=>`- ${e.id} — ${e.label} (${e.createdAt})`).join(`
614
+ `)}]}}case`latest`:{let e=Ce();return{content:[{type:`text`,text:e?gs(e):`No checkpoints saved.`}]}}}}catch(e){return us.error(`Checkpoint failed`,A(e)),{content:[{type:`text`,text:`Checkpoint failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function ms(e){let t=L(`lane`);e.registerTool(`lane`,{title:t.title,description:`Manage verified lanes — isolated file copies for parallel exploration. Create a lane, make changes, diff, merge back, or discard.`,inputSchema:{action:F.enum([`create`,`list`,`status`,`diff`,`merge`,`discard`]).describe(`Lane action to perform`),name:F.string().optional().describe(`Lane name (required for create/status/diff/merge/discard)`),files:F.array(F.string()).optional().describe(`File paths to copy into the lane (required for create)`)},annotations:t.annotations},async({action:e,name:t,files:n})=>{try{switch(e){case`create`:{if(!t)throw Error(`name is required for create`);if(!n||n.length===0)throw Error(`files are required for create`);let e=et(t,n);return{content:[{type:`text`,text:JSON.stringify(e)}]}}case`list`:return{content:[{type:`text`,text:JSON.stringify(rt())}]};case`status`:if(!t)throw Error(`name is required for status`);return{content:[{type:`text`,text:JSON.stringify(at(t))}]};case`diff`:if(!t)throw Error(`name is required for diff`);return{content:[{type:`text`,text:JSON.stringify(tt(t))}]};case`merge`:if(!t)throw Error(`name is required for merge`);return{content:[{type:`text`,text:JSON.stringify(it(t))}]};case`discard`:if(!t)throw Error(`name is required for discard`);return{content:[{type:`text`,text:JSON.stringify({discarded:nt(t)})}]}}}catch(e){return us.error(`Lane action failed`,A(e)),{content:[{type:`text`,text:`Lane action failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function hs(e){let t=L(`queue`);e.registerTool(`queue`,{title:t.title,description:`Manage task queues for sequential agent operations. Push items, take next, mark done/failed, list queues.`,inputSchema:{action:F.enum([`create`,`push`,`next`,`done`,`fail`,`get`,`list`,`clear`,`delete`]).describe(`Queue action`),name:F.string().optional().describe(`Queue name (required for most actions)`),title:F.string().optional().describe(`Item title (required for push)`),id:F.string().optional().describe(`Item ID (required for done/fail)`),data:F.unknown().optional().describe(`Arbitrary data to attach to a queue item`),error:F.string().optional().describe(`Error message (required for fail)`)},annotations:t.annotations},async({action:e,name:t,title:n,id:r,data:i,error:a})=>{try{switch(e){case`create`:if(!t)throw Error(`name is required for create`);return{content:[{type:`text`,text:JSON.stringify(_t(t))}]};case`push`:if(!t)throw Error(`name is required for push`);if(!n)throw Error(`title is required for push`);return{content:[{type:`text`,text:JSON.stringify(wt(t,n,i))}]};case`next`:{if(!t)throw Error(`name is required for next`);let e=Ct(t);return{content:[{type:`text`,text:JSON.stringify(e)}]}}case`done`:if(!t)throw Error(`name is required for done`);if(!r)throw Error(`id is required for done`);return{content:[{type:`text`,text:JSON.stringify(yt(t,r))}]};case`fail`:if(!t)throw Error(`name is required for fail`);if(!r)throw Error(`id is required for fail`);if(!a)throw Error(`error is required for fail`);return{content:[{type:`text`,text:JSON.stringify(bt(t,r,a))}]};case`get`:if(!t)throw Error(`name is required for get`);return{content:[{type:`text`,text:JSON.stringify(xt(t))}]};case`list`:return{content:[{type:`text`,text:JSON.stringify(St())}]};case`clear`:if(!t)throw Error(`name is required for clear`);return{content:[{type:`text`,text:JSON.stringify({cleared:gt(t)})}]};case`delete`:if(!t)throw Error(`name is required for delete`);return{content:[{type:`text`,text:JSON.stringify({deleted:vt(t)})}]}}}catch(e){return us.error(`Queue action failed`,A(e)),{content:[{type:`text`,text:`Queue action failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function gs(e){let t=[e.id,`Label: ${e.label}`,`Created: ${e.createdAt}`];if(e.notes&&t.push(`Notes: ${e.notes}`),e.files?.length){t.push(`Files: ${e.files.length}`);for(let n of e.files)t.push(` - ${n}`)}return t.push(``,`Data:`,JSON.stringify(e.data)),t.join(`
615
+ `)}function _s(e){let t=e.trim();if(!t)return``;try{return JSON.parse(t)}catch{return e}}function vs(e){let t=e?.trim();if(!t)return{};let n;try{n=JSON.parse(t)}catch{throw Error(`data must be a valid JSON object string`)}if(!n||typeof n!=`object`||Array.isArray(n))throw Error(`data must be a JSON object string`);return n}const ys=E(`tools`);function bs(e){let t=[`## Rule: ${e.id}`,``,`- **Status**: ${e.enabled?`enabled`:`disabled`}`,`- **Description**: ${e.description??`—`}`,`- **Category**: ${e.category??`—`}`,`- **Push weight**: ${e.pushWeight??`—`}`];return e.patterns?.length&&t.push(`- **Patterns**: ${e.patterns.join(`, `)}`),e.examples?.length&&t.push(`- **Examples**: ${e.examples.join(`, `)}`),t.join(`
616
+ `)}function xs(e,t){let n=L(`er_update_policy`);e.registerTool(`er_update_policy`,{title:n.title,description:`Manage ER push classification rules. Supports listing, updating, creating, and deleting rules that determine when knowledge should be pushed to Enterprise RAG.`,inputSchema:{action:F.enum([`list`,`get`,`update`,`create`,`delete`]).describe(`Action to perform on classification rules`),rule_id:F.string().optional().describe(`Rule ID (required for get, update, delete)`),changes:F.object({patterns:F.array(F.string()).optional(),category:F.string().optional(),pushWeight:F.number().min(0).max(1).optional(),description:F.string().optional(),examples:F.array(F.string()).optional(),enabled:F.boolean().optional()}).optional().describe(`Changes to apply (for update action)`),new_rule:F.object({id:F.string().regex(/^[a-z][a-z0-9-]*$/),patterns:F.array(F.string()).min(1),category:F.string(),pushWeight:F.number().min(0).max(1),description:F.string(),examples:F.array(F.string()).default([]),enabled:F.boolean().default(!0)}).optional().describe(`New rule definition (for create action)`)},annotations:n.annotations},async({action:e,rule_id:n,changes:r,new_rule:i})=>{try{if(e===`list`){let e=t.getRules();return{content:[{type:`text`,text:`## Classification Rules\n\n${e.map(e=>`- **${e.id}** (${e.enabled?`enabled`:`disabled`}) — ${e.description}\n Category: ${e.category} | Weight: ${e.pushWeight} | Patterns: ${e.patterns.join(`, `)}`).join(`
617
+ `)}\n\n---\n_${e.length} rules total. Use \`action: "update"\` to modify a rule._`}]}}if(e===`get`){if(!n)return{content:[{type:`text`,text:'`rule_id` is required for "get" action.'}],isError:!0};let e=t.getRule(n);return e?{content:[{type:`text`,text:bs(e)}]}:{content:[{type:`text`,text:`Rule "${n}" not found.`}],isError:!0}}if(e===`update`){if(!n||!r)return{content:[{type:`text`,text:'`rule_id` and `changes` are required for "update" action.'}],isError:!0};let e=t.updateRule(n,r);return e?{content:[{type:`text`,text:`${bs(e)}\n\n---\n_Updated. Next: Use \`action: "list"\` to verify._`}]}:{content:[{type:`text`,text:`Rule "${n}" not found.`}],isError:!0}}return e===`create`?i?{content:[{type:`text`,text:`${bs(t.addRule(i))}\n\n---\n_Created. Next: Test classification with \`remember\`._`}]}:{content:[{type:`text`,text:'`new_rule` is required for "create" action.'}],isError:!0}:e===`delete`?n?t.deleteRule(n)?{content:[{type:`text`,text:`Deleted rule **${n}**.\n\n---\n_Next: Use \`action: "list"\` to verify._`}]}:{content:[{type:`text`,text:`Rule "${n}" not found.`}],isError:!0}:{content:[{type:`text`,text:'`rule_id` is required for "delete" action.'}],isError:!0}:{content:[{type:`text`,text:`Unknown action: ${e}`}],isError:!0}}catch(e){return ys.error(`Policy update failed`,A(e)),{content:[{type:`text`,text:`Policy update failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function Ss(){return`
618
618
  /* ── Reset ────────────────────────────────────────────────────────── */
619
619
  *{box-sizing:border-box;margin:0;padding:0}
620
620
 
@@ -1009,52 +1009,52 @@ li{margin:4px 0}
1009
1009
  ::-webkit-scrollbar-track{background:var(--card)}
1010
1010
  ::-webkit-scrollbar-thumb{background:var(--border);border-radius:3px}
1011
1011
  ::-webkit-scrollbar-thumb:hover{background:var(--muted-foreground)}
1012
- `}const q=B;function Ss(e){let t=e;return!t?.items||!Array.isArray(t.items)?``:`<div class="timeline">${t.items.map(e=>{let t=e.status??`pending`,n=e.phase?`<div class="timeline-phase">${q(e.phase)}</div>`:``,r=e.description?`<div class="timeline-desc">${q(e.description)}</div>`:``;return`<div class="timeline-item">
1012
+ `}const K=B;function Cs(e){let t=e;return!t?.items||!Array.isArray(t.items)?``:`<div class="timeline">${t.items.map(e=>{let t=e.status??`pending`,n=e.phase?`<div class="timeline-phase">${K(e.phase)}</div>`:``,r=e.description?`<div class="timeline-desc">${K(e.description)}</div>`:``;return`<div class="timeline-item">
1013
1013
  <div class="timeline-dot ${t}"></div>
1014
1014
  ${n}
1015
- <div class="timeline-title">${q(e.title)}</div>
1015
+ <div class="timeline-title">${K(e.title)}</div>
1016
1016
  ${r}
1017
- </div>`}).join(``)}</div>`}function Cs(e){let t=e;return!t?.items||!Array.isArray(t.items)?``:`<div class="checklist">${t.items.map(e=>{let t=e.checked?`checked`:``,n=e.checked?`✓`:``,r=e.note?`<div class="checklist-note">${q(e.note)}</div>`:``;return`<div class="checklist-item ${t}">
1017
+ </div>`}).join(``)}</div>`}function ws(e){let t=e;return!t?.items||!Array.isArray(t.items)?``:`<div class="checklist">${t.items.map(e=>{let t=e.checked?`checked`:``,n=e.checked?`✓`:``,r=e.note?`<div class="checklist-note">${K(e.note)}</div>`:``;return`<div class="checklist-item ${t}">
1018
1018
  <div class="checklist-check ${t}">${n}</div>
1019
1019
  <div>
1020
- <div class="checklist-label">${q(e.label)}</div>
1020
+ <div class="checklist-label">${K(e.label)}</div>
1021
1021
  ${r}
1022
1022
  </div>
1023
- </div>`}).join(``)}</div>`}function ws(e){let t=e;if(t?.left&&t?.right)return ws({columns:[{title:t.left.label??`Left`,items:t.left.items??[]},{title:t.right.label??`Right`,items:t.right.items??[]}]});if(!t?.columns||!Array.isArray(t.columns)||t.columns.length===0)return``;let n=t.columns.length,r=Math.max(...t.columns.map(e=>e.items?.length??0));return`<div class="comparison-grid" style="grid-template-columns:repeat(${n},1fr)">${t.columns.map(e=>{let t=`<div class="comparison-header">${q(e.title)}</div>`,n=[];for(let t=0;t<r;t++){let r=e.items?.[t]??``;n.push(`<div class="comparison-item">${q(r)}</div>`)}return`<div class="comparison-col">${t}${n.join(``)}</div>`}).join(``)}</div>`}function Ts(e){let t=e;return!t?.items||!Array.isArray(t.items)?``:`<div class="status-board">${t.items.map(e=>{let t=e.detail?`<span class="status-detail">${q(e.detail)}</span>`:``;return`<div class="status-row">
1023
+ </div>`}).join(``)}</div>`}function Ts(e){let t=e;if(t?.left&&t?.right)return Ts({columns:[{title:t.left.label??`Left`,items:t.left.items??[]},{title:t.right.label??`Right`,items:t.right.items??[]}]});if(!t?.columns||!Array.isArray(t.columns)||t.columns.length===0)return``;let n=t.columns.length,r=Math.max(...t.columns.map(e=>e.items?.length??0));return`<div class="comparison-grid" style="grid-template-columns:repeat(${n},1fr)">${t.columns.map(e=>{let t=`<div class="comparison-header">${K(e.title)}</div>`,n=[];for(let t=0;t<r;t++){let r=e.items?.[t]??``;n.push(`<div class="comparison-item">${K(r)}</div>`)}return`<div class="comparison-col">${t}${n.join(``)}</div>`}).join(``)}</div>`}function Es(e){let t=e;return!t?.items||!Array.isArray(t.items)?``:`<div class="status-board">${t.items.map(e=>{let t=e.detail?`<span class="status-detail">${K(e.detail)}</span>`:``;return`<div class="status-row">
1024
1024
  <div class="status-indicator ${e.status??`pending`}"></div>
1025
- <span class="status-label">${q(e.label)}</span>
1025
+ <span class="status-label">${K(e.label)}</span>
1026
1026
  ${t}
1027
- </div>`}).join(``)}</div>`}function Es(e){let t=e;if(!t?.question)return``;let n=t.context?`<div class="prompt-context">${q(t.context)}</div>`:``,r=t.placeholder?`<div class="prompt-placeholder">${q(t.placeholder)}</div>`:``;return`<div class="prompt-block">
1028
- <div class="prompt-question">${q(t.question)}</div>
1027
+ </div>`}).join(``)}</div>`}function Ds(e){let t=e;if(!t?.question)return``;let n=t.context?`<div class="prompt-context">${K(t.context)}</div>`:``,r=t.placeholder?`<div class="prompt-placeholder">${K(t.placeholder)}</div>`:``;return`<div class="prompt-block">
1028
+ <div class="prompt-question">${K(t.question)}</div>
1029
1029
  ${n}${r}
1030
- </div>`}function Ds(e){let t=e;if(!t?.items||!Array.isArray(t.items))return``;let n=e=>e>=100?`var(--success)`:e>=60?`var(--primary)`:e>=30?`var(--warning)`:`var(--error)`;return`<div class="progress-list">${t.items.map(e=>{let t=e.max??100,r=t>0?Math.min(100,e.value/t*100):0,i=e.color??n(r);return`<div class="progress-item">
1030
+ </div>`}function Os(e){let t=e;if(!t?.items||!Array.isArray(t.items))return``;let n=e=>e>=100?`var(--success)`:e>=60?`var(--primary)`:e>=30?`var(--warning)`:`var(--error)`;return`<div class="progress-list">${t.items.map(e=>{let t=e.max??100,r=t>0?Math.min(100,e.value/t*100):0,i=e.color??n(r);return`<div class="progress-item">
1031
1031
  <div class="progress-header">
1032
- <span class="progress-label">${q(e.label)}</span>
1032
+ <span class="progress-label">${K(e.label)}</span>
1033
1033
  <span class="progress-value">${e.value}/${t}</span>
1034
1034
  </div>
1035
1035
  <div class="progress-track">
1036
1036
  <div class="progress-fill" style="width:${r.toFixed(1)}%;background:${i}"></div>
1037
1037
  </div>
1038
- </div>`}).join(``)}</div>`}const J=B;function Os(e){return Math.abs(e)>=1e6?`${(e/1e6).toFixed(1).replace(/\.0$/,``)}M`:Math.abs(e)>=1e3?`${(e/1e3).toFixed(1).replace(/\.0$/,``)}k`:Number.isInteger(e)?String(e):e.toFixed(1)}function ks(e){return`var(--chart-${e%12+1})`}let As=0;function js(e){let t=e.value;if(!t?.data?.length||!t.chartType)return`<pre>${J(JSON.stringify(e.value,null,2))}</pre>`;As++;let n=e.title||t.title?`<div class="chart-title">${J(String(e.title||t.title))}</div>`:``,r;switch(t.chartType){case`line`:r=zs(t,!1);break;case`area`:r=zs(t,!0);break;case`bar`:r=Bs(t,!1);break;case`horizontal-bar`:r=Bs(t,!0);break;case`pie`:r=Vs(t,!1);break;case`donut`:r=Vs(t,!0);break;case`sparkline`:r=Hs(t);break;case`heatmap`:r=Us(t);break;default:r=`<pre>${J(JSON.stringify(t,null,2))}</pre>`}let i=t.showLegend!==!1&&t.yKeys.length>1&&t.chartType!==`sparkline`?Ms(t.yKeys):``;return`<div class="chart-container">${n}${r}${i}</div>`}function Ms(e){return`<div class="chart-legend">${e.map((e,t)=>`<span class="chart-legend-item"><span class="chart-legend-swatch" style="background:${ks(t)}"></span>${J(e)}</span>`).join(``)}</div>`}const Y={top:20,right:20,bottom:35,left:55};function Ns(e,t){return e.map(e=>Number(e[t])||0)}function Ps(e,t){return e.map(e=>String(e[t]??``))}function Fs(e){let t=1/0,n=-1/0;for(let r of e)r<t&&(t=r),r>n&&(n=r);return t===n&&(t=t===0?0:t*.9,n=n===0?1:n*1.1),[t,n]}function Is(e){return e>=0?0:e}function Ls(e,t,n,r=5){let i=[];for(let a=0;a<=r;a++){let o=a/r,s=Y.top+n-o*n,c=e+o*(t-e);i.push(`<line class="chart-grid-line" x1="${Y.left}" x2="${600-Y.right}" y1="${s}" y2="${s}"/>`),i.push(`<text class="chart-axis-label" x="${Y.left-8}" y="${s+4}" text-anchor="end">${Os(c)}</text>`)}return i.join(``)}function Rs(e,t,n,r){let i=Math.floor(t/50),a=Math.max(1,Math.ceil(e.length/i));return e.map((e,t)=>t%a===0?`<text class="chart-axis-label" x="${Y.left+t*r+r/2}" y="${Y.top+n+18}" text-anchor="middle">${J(e.length>10?`${e.slice(0,9)}…`:e)}</text>`:``).join(``)}function zs(e,t){let n=(e.height??300)-Y.top-Y.bottom,r=600-Y.left-Y.right,i=Ps(e.data,e.xKey),a=e.data.length;if(a===0)return``;let o=r/Math.max(a-1,1),s=1/0,c=-1/0;for(let t of e.yKeys){let[n,r]=Fs(Ns(e.data,t));n<s&&(s=n),r>c&&(c=r)}s=Is(s);let l=c-s||1,u=e=>Y.top+n-(e-s)/l*n,d=e=>Y.left+e*o,f=``,p=[];for(let r=0;r<e.yKeys.length;r++){let i=Ns(e.data,e.yKeys[r]),o=ks(r),s=`M${i.map((e,t)=>`${d(t).toFixed(1)},${u(e).toFixed(1)}`).join(`L`)}`;if(t){let e=`ag${As}_${r}`;f+=`<linearGradient id="${e}" x1="0" y1="0" x2="0" y2="1">
1038
+ </div>`}).join(``)}</div>`}const q=B;function ks(e){return Math.abs(e)>=1e6?`${(e/1e6).toFixed(1).replace(/\.0$/,``)}M`:Math.abs(e)>=1e3?`${(e/1e3).toFixed(1).replace(/\.0$/,``)}k`:Number.isInteger(e)?String(e):e.toFixed(1)}function As(e){return`var(--chart-${e%12+1})`}let js=0;function Ms(e){let t=e.value;if(!t?.data?.length||!t.chartType)return`<pre>${q(JSON.stringify(e.value,null,2))}</pre>`;js++;let n=e.title||t.title?`<div class="chart-title">${q(String(e.title||t.title))}</div>`:``,r;switch(t.chartType){case`line`:r=Bs(t,!1);break;case`area`:r=Bs(t,!0);break;case`bar`:r=Vs(t,!1);break;case`horizontal-bar`:r=Vs(t,!0);break;case`pie`:r=Hs(t,!1);break;case`donut`:r=Hs(t,!0);break;case`sparkline`:r=Us(t);break;case`heatmap`:r=Ws(t);break;default:r=`<pre>${q(JSON.stringify(t,null,2))}</pre>`}let i=t.showLegend!==!1&&t.yKeys.length>1&&t.chartType!==`sparkline`?Ns(t.yKeys):``;return`<div class="chart-container">${n}${r}${i}</div>`}function Ns(e){return`<div class="chart-legend">${e.map((e,t)=>`<span class="chart-legend-item"><span class="chart-legend-swatch" style="background:${As(t)}"></span>${q(e)}</span>`).join(``)}</div>`}const J={top:20,right:20,bottom:35,left:55};function Ps(e,t){return e.map(e=>Number(e[t])||0)}function Fs(e,t){return e.map(e=>String(e[t]??``))}function Is(e){let t=1/0,n=-1/0;for(let r of e)r<t&&(t=r),r>n&&(n=r);return t===n&&(t=t===0?0:t*.9,n=n===0?1:n*1.1),[t,n]}function Ls(e){return e>=0?0:e}function Rs(e,t,n,r=5){let i=[];for(let a=0;a<=r;a++){let o=a/r,s=J.top+n-o*n,c=e+o*(t-e);i.push(`<line class="chart-grid-line" x1="${J.left}" x2="${600-J.right}" y1="${s}" y2="${s}"/>`),i.push(`<text class="chart-axis-label" x="${J.left-8}" y="${s+4}" text-anchor="end">${ks(c)}</text>`)}return i.join(``)}function zs(e,t,n,r){let i=Math.floor(t/50),a=Math.max(1,Math.ceil(e.length/i));return e.map((e,t)=>t%a===0?`<text class="chart-axis-label" x="${J.left+t*r+r/2}" y="${J.top+n+18}" text-anchor="middle">${q(e.length>10?`${e.slice(0,9)}…`:e)}</text>`:``).join(``)}function Bs(e,t){let n=(e.height??300)-J.top-J.bottom,r=600-J.left-J.right,i=Fs(e.data,e.xKey),a=e.data.length;if(a===0)return``;let o=r/Math.max(a-1,1),s=1/0,c=-1/0;for(let t of e.yKeys){let[n,r]=Is(Ps(e.data,t));n<s&&(s=n),r>c&&(c=r)}s=Ls(s);let l=c-s||1,u=e=>J.top+n-(e-s)/l*n,d=e=>J.left+e*o,f=``,p=[];for(let r=0;r<e.yKeys.length;r++){let i=Ps(e.data,e.yKeys[r]),o=As(r),s=`M${i.map((e,t)=>`${d(t).toFixed(1)},${u(e).toFixed(1)}`).join(`L`)}`;if(t){let e=`ag${js}_${r}`;f+=`<linearGradient id="${e}" x1="0" y1="0" x2="0" y2="1">
1039
1039
  <stop offset="0%" stop-color="${o}" stop-opacity="0.3"/>
1040
1040
  <stop offset="100%" stop-color="${o}" stop-opacity="0"/>
1041
- </linearGradient>`;let t=`${s}L${d(a-1).toFixed(1)},${(Y.top+n).toFixed(1)}L${d(0).toFixed(1)},${(Y.top+n).toFixed(1)}Z`;p.push(`<path d="${t}" fill="url(#${e})" stroke="none"/>`)}p.push(`<path d="${s}" fill="none" stroke="${o}" stroke-width="2" stroke-linejoin="round" stroke-linecap="round"/>`);for(let e=0;e<i.length;e++)p.push(`<circle cx="${d(e).toFixed(1)}" cy="${u(i[e]).toFixed(1)}" r="3" fill="${o}" stroke="var(--card)" stroke-width="1.5"/>`)}let m=e.height??300,h=e.showGrid===!1?``:Ls(s,c,n),g=Rs(i,r,n,a>1?o:r);return`<svg class="chart-svg" viewBox="0 0 600 ${m}" preserveAspectRatio="xMidYMid meet">
1041
+ </linearGradient>`;let t=`${s}L${d(a-1).toFixed(1)},${(J.top+n).toFixed(1)}L${d(0).toFixed(1)},${(J.top+n).toFixed(1)}Z`;p.push(`<path d="${t}" fill="url(#${e})" stroke="none"/>`)}p.push(`<path d="${s}" fill="none" stroke="${o}" stroke-width="2" stroke-linejoin="round" stroke-linecap="round"/>`);for(let e=0;e<i.length;e++)p.push(`<circle cx="${d(e).toFixed(1)}" cy="${u(i[e]).toFixed(1)}" r="3" fill="${o}" stroke="var(--card)" stroke-width="1.5"/>`)}let m=e.height??300,h=e.showGrid===!1?``:Rs(s,c,n),g=zs(i,r,n,a>1?o:r);return`<svg class="chart-svg" viewBox="0 0 600 ${m}" preserveAspectRatio="xMidYMid meet">
1042
1042
  ${f?`<defs>${f}</defs>`:``}
1043
1043
  ${h}${g}${p.join(``)}
1044
- </svg>`}function Bs(e,t){let n=(e.height??300)-Y.top-Y.bottom,r=600-Y.left-Y.right,i=Ps(e.data,e.xKey),a=e.data.length;if(a===0)return``;let o=e.yKeys.length,s=0;for(let t of e.yKeys)for(let n of Ns(e.data,t))n>s&&(s=n);s===0&&(s=1);let c=e.height??300,l=[];if(t){let t=Math.min(24,(n-(a-1)*4)/(a*o)),u=t*o+4,d=e.showGrid===!1?``:Ls(0,s,n),f=i.map((e,t)=>{let n=Y.top+t*u+u/2,r=e.length>15?`${e.slice(0,14)}…`:e;return`<text class="chart-axis-label" x="${Y.left-8}" y="${n+4}" text-anchor="end">${J(r)}</text>`}).join(``);for(let n=0;n<a;n++)for(let i=0;i<o;i++){let a=Number(e.data[n][e.yKeys[i]])||0,o=a/s*r,c=Y.top+n*u+i*t;l.push(`<rect x="${Y.left}" y="${c}" width="${o.toFixed(1)}" height="${t-2}" rx="3" fill="${ks(i)}" opacity="0.85">
1045
- <title>${J(e.yKeys[i])}: ${Os(a)}</title>
1046
- </rect>`)}return`<svg class="chart-svg" viewBox="0 0 600 ${Math.max(c,a*u+Y.top+Y.bottom)}" preserveAspectRatio="xMidYMid meet">
1044
+ </svg>`}function Vs(e,t){let n=(e.height??300)-J.top-J.bottom,r=600-J.left-J.right,i=Fs(e.data,e.xKey),a=e.data.length;if(a===0)return``;let o=e.yKeys.length,s=0;for(let t of e.yKeys)for(let n of Ps(e.data,t))n>s&&(s=n);s===0&&(s=1);let c=e.height??300,l=[];if(t){let t=Math.min(24,(n-(a-1)*4)/(a*o)),u=t*o+4,d=e.showGrid===!1?``:Rs(0,s,n),f=i.map((e,t)=>{let n=J.top+t*u+u/2,r=e.length>15?`${e.slice(0,14)}…`:e;return`<text class="chart-axis-label" x="${J.left-8}" y="${n+4}" text-anchor="end">${q(r)}</text>`}).join(``);for(let n=0;n<a;n++)for(let i=0;i<o;i++){let a=Number(e.data[n][e.yKeys[i]])||0,o=a/s*r,c=J.top+n*u+i*t;l.push(`<rect x="${J.left}" y="${c}" width="${o.toFixed(1)}" height="${t-2}" rx="3" fill="${As(i)}" opacity="0.85">
1045
+ <title>${q(e.yKeys[i])}: ${ks(a)}</title>
1046
+ </rect>`)}return`<svg class="chart-svg" viewBox="0 0 600 ${Math.max(c,a*u+J.top+J.bottom)}" preserveAspectRatio="xMidYMid meet">
1047
1047
  ${d}${f}${l.join(``)}
1048
- </svg>`}else{let t=r/a,u=Math.min(40,(t-8)/o),d=e.showGrid===!1?``:Ls(0,s,n),f=Rs(i,r,n,t);for(let r=0;r<a;r++)for(let i=0;i<o;i++){let a=Number(e.data[r][e.yKeys[i]])||0,c=a/s*n,d=Y.left+r*t+(t-u*o)/2+i*u,f=Y.top+n-c;l.push(`<rect x="${d.toFixed(1)}" y="${f.toFixed(1)}" width="${(u-2).toFixed(1)}" height="${c.toFixed(1)}" rx="3" fill="${ks(i)}" opacity="0.85">
1049
- <title>${J(e.yKeys[i])}: ${Os(a)}</title>
1048
+ </svg>`}else{let t=r/a,u=Math.min(40,(t-8)/o),d=e.showGrid===!1?``:Rs(0,s,n),f=zs(i,r,n,t);for(let r=0;r<a;r++)for(let i=0;i<o;i++){let a=Number(e.data[r][e.yKeys[i]])||0,c=a/s*n,d=J.left+r*t+(t-u*o)/2+i*u,f=J.top+n-c;l.push(`<rect x="${d.toFixed(1)}" y="${f.toFixed(1)}" width="${(u-2).toFixed(1)}" height="${c.toFixed(1)}" rx="3" fill="${As(i)}" opacity="0.85">
1049
+ <title>${q(e.yKeys[i])}: ${ks(a)}</title>
1050
1050
  </rect>`)}return`<svg class="chart-svg" viewBox="0 0 600 ${c}" preserveAspectRatio="xMidYMid meet">
1051
1051
  ${d}${f}${l.join(``)}
1052
- </svg>`}}function Vs(e,t){let n=e.height??300,r=n/2,i=n/2,a=n/2-10,o=t?a*.55:0,s=e.yKeys[0]||`value`,c=e.data.map(e=>Math.max(0,Number(e[s])||0)),l=Ps(e.data,e.xKey),u=c.reduce((e,t)=>e+t,0);if(u===0)return`<div style="color:var(--muted-foreground);text-align:center;padding:20px">No data</div>`;let d=[],f=-Math.PI/2;for(let e=0;e<c.length;e++){let t=c[e]/u;if(t===0)continue;let n=t*Math.PI*2,s=f,p=f+n,m=r+a*Math.cos(s),h=i+a*Math.sin(s),g=r+a*Math.cos(p),_=i+a*Math.sin(p),v=+(n>Math.PI),y;if(o>0){let e=r+o*Math.cos(s),t=i+o*Math.sin(s),n=r+o*Math.cos(p),c=i+o*Math.sin(p);y=`M${m.toFixed(2)},${h.toFixed(2)} A${a},${a} 0 ${v},1 ${g.toFixed(2)},${_.toFixed(2)} L${n.toFixed(2)},${c.toFixed(2)} A${o},${o} 0 ${v},0 ${e.toFixed(2)},${t.toFixed(2)}Z`}else y=`M${r},${i} L${m.toFixed(2)},${h.toFixed(2)} A${a},${a} 0 ${v},1 ${g.toFixed(2)},${_.toFixed(2)}Z`;d.push(`<path d="${y}" fill="${ks(e)}" stroke="var(--background)" stroke-width="2" opacity="0.9">
1053
- <title>${J(l[e]||`Item ${e+1}`)}: ${Os(c[e])} (${(t*100).toFixed(1)}%)</title>
1054
- </path>`),f=p}let p=t?`<text x="${r}" y="${i-6}" text-anchor="middle" fill="var(--foreground)" font-size="18" font-weight="700">${Os(u)}</text>
1055
- <text x="${r}" y="${i+12}" text-anchor="middle" fill="var(--muted-foreground)" font-size="11">Total</text>`:``,m=Ms(l.filter((e,t)=>c[t]>0));return`<svg class="chart-svg" viewBox="0 0 ${n} ${n}" preserveAspectRatio="xMidYMid meet">
1052
+ </svg>`}}function Hs(e,t){let n=e.height??300,r=n/2,i=n/2,a=n/2-10,o=t?a*.55:0,s=e.yKeys[0]||`value`,c=e.data.map(e=>Math.max(0,Number(e[s])||0)),l=Fs(e.data,e.xKey),u=c.reduce((e,t)=>e+t,0);if(u===0)return`<div style="color:var(--muted-foreground);text-align:center;padding:20px">No data</div>`;let d=[],f=-Math.PI/2;for(let e=0;e<c.length;e++){let t=c[e]/u;if(t===0)continue;let n=t*Math.PI*2,s=f,p=f+n,m=r+a*Math.cos(s),h=i+a*Math.sin(s),g=r+a*Math.cos(p),_=i+a*Math.sin(p),v=+(n>Math.PI),y;if(o>0){let e=r+o*Math.cos(s),t=i+o*Math.sin(s),n=r+o*Math.cos(p),c=i+o*Math.sin(p);y=`M${m.toFixed(2)},${h.toFixed(2)} A${a},${a} 0 ${v},1 ${g.toFixed(2)},${_.toFixed(2)} L${n.toFixed(2)},${c.toFixed(2)} A${o},${o} 0 ${v},0 ${e.toFixed(2)},${t.toFixed(2)}Z`}else y=`M${r},${i} L${m.toFixed(2)},${h.toFixed(2)} A${a},${a} 0 ${v},1 ${g.toFixed(2)},${_.toFixed(2)}Z`;d.push(`<path d="${y}" fill="${As(e)}" stroke="var(--background)" stroke-width="2" opacity="0.9">
1053
+ <title>${q(l[e]||`Item ${e+1}`)}: ${ks(c[e])} (${(t*100).toFixed(1)}%)</title>
1054
+ </path>`),f=p}let p=t?`<text x="${r}" y="${i-6}" text-anchor="middle" fill="var(--foreground)" font-size="18" font-weight="700">${ks(u)}</text>
1055
+ <text x="${r}" y="${i+12}" text-anchor="middle" fill="var(--muted-foreground)" font-size="11">Total</text>`:``,m=Ns(l.filter((e,t)=>c[t]>0));return`<svg class="chart-svg" viewBox="0 0 ${n} ${n}" preserveAspectRatio="xMidYMid meet">
1056
1056
  ${d.join(``)}${p}
1057
- </svg>${m}`}function Hs(e){let t=e.height??40,n=e.yKeys[0]||`value`,r=Ns(e.data,n),i=r.length;if(i===0)return``;let[a,o]=Fs(r),s=o-a||1,c=200/Math.max(i-1,1),l=r.map((e,n)=>`${(n*c).toFixed(1)},${(t-4-(e-a)/s*(t-8)).toFixed(1)}`),u=`spk${As}`,d=ks(0);return`<svg class="chart-svg" viewBox="0 0 200 ${t}" preserveAspectRatio="xMidYMid meet" style="max-width:200px;height:${t}px">
1057
+ </svg>${m}`}function Us(e){let t=e.height??40,n=e.yKeys[0]||`value`,r=Ps(e.data,n),i=r.length;if(i===0)return``;let[a,o]=Is(r),s=o-a||1,c=200/Math.max(i-1,1),l=r.map((e,n)=>`${(n*c).toFixed(1)},${(t-4-(e-a)/s*(t-8)).toFixed(1)}`),u=`spk${js}`,d=As(0);return`<svg class="chart-svg" viewBox="0 0 200 ${t}" preserveAspectRatio="xMidYMid meet" style="max-width:200px;height:${t}px">
1058
1058
  <defs>
1059
1059
  <linearGradient id="${u}" x1="0" y1="0" x2="0" y2="1">
1060
1060
  <stop offset="0%" stop-color="${d}" stop-opacity="0.2"/>
@@ -1064,16 +1064,16 @@ li{margin:4px 0}
1064
1064
  <path d="M${l.join(`L`)}L${((i-1)*c).toFixed(1)},${t}L0,${t}Z" fill="url(#${u})" stroke="none"/>
1065
1065
  <polyline points="${l.join(` `)}" fill="none" stroke="${d}" stroke-width="1.5" stroke-linejoin="round"/>
1066
1066
  <circle cx="${((i-1)*c).toFixed(1)}" cy="${l[i-1].split(`,`)[1]}" r="2.5" fill="${d}"/>
1067
- </svg>`}function Us(e){let t=Ps(e.data,e.xKey),n=e.data.length,r=e.yKeys.length;if(n===0||r===0)return``;let i=1/0,a=-1/0;for(let t of e.yKeys)for(let n of Ns(e.data,t))n<i&&(i=n),n>a&&(a=n);let o=a-i||1,s=Math.min(50,(600-Y.left-Y.right)/n),c=Math.min(30,200/r),l=Y.left+n*s+Y.right,u=Y.top+r*c+Y.bottom,d=[];for(let t=0;t<r;t++){let n=Y.top+t*c+c/2+4,r=e.yKeys[t].length>8?`${e.yKeys[t].slice(0,7)}…`:e.yKeys[t];d.push(`<text class="chart-axis-label" x="${Y.left-8}" y="${n}" text-anchor="end">${J(r)}</text>`)}let f=Math.floor((l-Y.left)/40),p=Math.max(1,Math.ceil(n/f));for(let e=0;e<n;e++){if(e%p!==0)continue;let n=Y.left+e*s+s/2,r=t[e].length>6?`${t[e].slice(0,5)}…`:t[e];d.push(`<text class="chart-axis-label" x="${n}" y="${u-8}" text-anchor="middle">${J(r)}</text>`)}for(let a=0;a<n;a++)for(let n=0;n<r;n++){let r=Number(e.data[a][e.yKeys[n]])||0,l=(r-i)/o,u=Y.left+a*s,f=Y.top+n*c;d.push(`<rect x="${u}" y="${f}" width="${s-1}" height="${c-1}" rx="2" fill="var(--primary)" opacity="${(.1+l*.8).toFixed(2)}">
1068
- <title>${J(t[a])} / ${J(e.yKeys[n])}: ${Os(r)}</title>
1067
+ </svg>`}function Ws(e){let t=Fs(e.data,e.xKey),n=e.data.length,r=e.yKeys.length;if(n===0||r===0)return``;let i=1/0,a=-1/0;for(let t of e.yKeys)for(let n of Ps(e.data,t))n<i&&(i=n),n>a&&(a=n);let o=a-i||1,s=Math.min(50,(600-J.left-J.right)/n),c=Math.min(30,200/r),l=J.left+n*s+J.right,u=J.top+r*c+J.bottom,d=[];for(let t=0;t<r;t++){let n=J.top+t*c+c/2+4,r=e.yKeys[t].length>8?`${e.yKeys[t].slice(0,7)}…`:e.yKeys[t];d.push(`<text class="chart-axis-label" x="${J.left-8}" y="${n}" text-anchor="end">${q(r)}</text>`)}let f=Math.floor((l-J.left)/40),p=Math.max(1,Math.ceil(n/f));for(let e=0;e<n;e++){if(e%p!==0)continue;let n=J.left+e*s+s/2,r=t[e].length>6?`${t[e].slice(0,5)}…`:t[e];d.push(`<text class="chart-axis-label" x="${n}" y="${u-8}" text-anchor="middle">${q(r)}</text>`)}for(let a=0;a<n;a++)for(let n=0;n<r;n++){let r=Number(e.data[a][e.yKeys[n]])||0,l=(r-i)/o,u=J.left+a*s,f=J.top+n*c;d.push(`<rect x="${u}" y="${f}" width="${s-1}" height="${c-1}" rx="2" fill="var(--primary)" opacity="${(.1+l*.8).toFixed(2)}">
1068
+ <title>${q(t[a])} / ${q(e.yKeys[n])}: ${ks(r)}</title>
1069
1069
  </rect>`)}return`<svg class="chart-svg" viewBox="0 0 ${l} ${u}" preserveAspectRatio="xMidYMid meet">
1070
1070
  ${d.join(``)}
1071
- </svg>`}function Ws(e){return e==null?`null`:Array.isArray(e)?`[${e.map(Ws).join(`, `)}]`:String(e)}function Gs(e){return e.replace(/[^a-zA-Z0-9_]/g,`_`)}function Ks(e){if(typeof e!=`object`||!e||!(`type`in e))return!1;let t=e,n=typeof t.type==`string`?t.type:``;return new Set([`separator`,`actions`]).has(n)?!0:`value`in t||typeof t.text==`string`||Array.isArray(t.headers)&&Array.isArray(t.rows)||typeof t.code==`string`||Array.isArray(t.items)||!!t.entries&&typeof t.entries==`object`&&!Array.isArray(t.entries)||!!t.columns&&typeof t.columns==`object`||`chartType`in t||Array.isArray(t.data)||typeof t.content==`string`||typeof t.markdown==`string`||typeof t.description==`string`||Array.isArray(t.metrics)||Array.isArray(t.cards)||Array.isArray(t.nodes)||typeof t.question==`string`}function qs(e){if(Array.isArray(e)){let t=e.filter(e=>typeof e==`object`&&!!e),n=t.map(e=>String(e.title??``)),r=Math.max(0,...t.map(e=>Array.isArray(e.items)?e.items.length:0));return{headers:n,rows:Array.from({length:r},(e,n)=>t.map(e=>Array.isArray(e.items)?e.items[n]??``:``))}}if(!e||typeof e!=`object`)return null;let t=e,n=Object.keys(t),r=Math.max(0,...n.map(e=>Array.isArray(t[e])?t[e].length:0));return{headers:n,rows:Array.from({length:r},(e,r)=>n.map(e=>Array.isArray(t[e])?t[e][r]??``:``))}}function Js(e){let t=e,n=e;if(`value`in n||(typeof t.text==`string`?n={...n,value:t.text}:typeof t.content==`string`?n={...n,value:t.content}:typeof t.markdown==`string`?n={...n,value:t.markdown}:typeof t.description==`string`?n={...n,value:t.description}:typeof t.code==`string`?n={...n,value:t.code}:Array.isArray(t.headers)&&Array.isArray(t.rows)?n={...n,value:{headers:t.headers,rows:t.rows}}:Array.isArray(t.items)?n={...n,value:{items:t.items}}:Array.isArray(t.metrics)?n={...n,value:t.metrics}:Array.isArray(t.cards)?n={...n,value:t.cards}:Array.isArray(t.nodes)&&Array.isArray(t.edges)?n={...n,value:{nodes:t.nodes,edges:t.edges}}:typeof t.question==`string`?n={...n,value:{question:t.question,context:t.context,placeholder:t.placeholder}}:(`chartType`in t||Array.isArray(t.data))&&(n={...n,value:{chartType:t.chartType,data:t.data,xKey:t.xKey??`label`,yKeys:t.yKeys??[`value`]}})),n.type===`chart`){let e=n.value;if(e&&typeof e==`object`&&!Array.isArray(e)){let t=e,r=t.data&&typeof t.data==`object`&&!Array.isArray(t.data)?t.data:null,i=Array.isArray(t.labels)?t.labels:Array.isArray(r?.labels)?r.labels:null,a=Array.isArray(t.datasets)?t.datasets:Array.isArray(r?.datasets)?r.datasets:null,o=typeof t.type==`string`?t.type:typeof t.chartType==`string`?t.chartType:null;if(o&&i&&a&&!Array.isArray(t.data)){let e=a.map((e,t)=>String(e.label??`series${t+1}`)),t=i.map((e,t)=>{let n={label:String(e)};for(let[e,r]of a.entries()){let i=r,a=String(i.label??`series${e+1}`);n[a]=i.data?.[t]??0}return n});n={...n,value:{chartType:String(o),data:t,xKey:`label`,yKeys:e}}}}}let r=n;if(n.type===`text`||n.type===`paragraph`)return{...n,type:`markdown`};if(n.type===`heading`)return{...n,type:`markdown`,value:`## ${String(r.value??``)}`};if(n.type===`kv`){let e=t.entries&&typeof t.entries==`object`&&!Array.isArray(t.entries)?t.entries:r.value&&typeof r.value==`object`&&!Array.isArray(r.value)?r.value:null;if(e)return{...n,type:`table`,value:{headers:[`Key`,`Value`],rows:Object.entries(e).map(([e,t])=>[e,t])}}}if(n.type===`comparison`){let e=qs(t.columns??(r.value&&typeof r.value==`object`?r.value.columns:void 0))??qs(r.value);if(e)return{...n,type:`table`,value:e};let i=r.value;if(i&&typeof i==`object`&&!Array.isArray(i)){let e=i;if(Array.isArray(e.headers)&&Array.isArray(e.rows))return{...n,type:`table`}}}if(n.type===`timeline`){let e=r.value;if(Array.isArray(e)){let t=e.map(e=>{if(e&&typeof e==`object`){let t=e;return[String(t.status??t.state??``),String(t.time??t.date??t.timestamp??``),String(t.label??t.description??t.title??t.text??``)]}return[``,``,String(e)]});return{...n,type:`table`,value:{headers:[`Status`,`Time`,`Description`],rows:t}}}}return n}function Ys(e,t){let n=e=>{if(e==null)return``;if(typeof e==`string`)return e;if(typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`)return String(e);if(typeof e==`object`)try{let t=JSON.stringify(e);return typeof t==`string`?t:String(e)}catch{return String(e)}return String(e)};if(e==null)return null;if(typeof e==`string`)return{type:`markdown`,title:t,value:e};if(typeof e==`number`||typeof e==`boolean`)return{type:`markdown`,title:t,value:String(e)};if(Array.isArray(e)){if(e.every(e=>typeof e==`string`||typeof e==`number`||typeof e==`boolean`))return{type:`markdown`,title:t,value:e.map(e=>`- ${String(e)}`).join(`
1071
+ </svg>`}function Gs(e){if(e==null)return`null`;if(Array.isArray(e))return`[${e.map(Gs).join(`, `)}]`;if(typeof e==`object`)try{return JSON.stringify(e)}catch{return String(e)}return String(e)}function Ks(e){return e.replace(/[^a-zA-Z0-9_]/g,`_`)}function qs(e){if(typeof e!=`object`||!e||!(`type`in e))return!1;let t=e,n=typeof t.type==`string`?t.type:``;return new Set([`separator`,`actions`]).has(n)?!0:`value`in t||typeof t.text==`string`||Array.isArray(t.headers)&&Array.isArray(t.rows)||typeof t.code==`string`||Array.isArray(t.items)||!!t.entries&&typeof t.entries==`object`&&!Array.isArray(t.entries)||!!t.columns&&typeof t.columns==`object`||`chartType`in t||Array.isArray(t.data)||typeof t.content==`string`||typeof t.markdown==`string`||typeof t.description==`string`||Array.isArray(t.metrics)||Array.isArray(t.cards)||Array.isArray(t.nodes)||typeof t.question==`string`}function Js(e){if(Array.isArray(e)){let t=e.filter(e=>typeof e==`object`&&!!e),n=t.map(e=>String(e.title??``)),r=Math.max(0,...t.map(e=>Array.isArray(e.items)?e.items.length:0));return{headers:n,rows:Array.from({length:r},(e,n)=>t.map(e=>Array.isArray(e.items)?e.items[n]??``:``))}}if(!e||typeof e!=`object`)return null;let t=e,n=Object.keys(t),r=Math.max(0,...n.map(e=>Array.isArray(t[e])?t[e].length:0));return{headers:n,rows:Array.from({length:r},(e,r)=>n.map(e=>Array.isArray(t[e])?t[e][r]??``:``))}}function Ys(e){let t=e,n=e;if(`value`in n||(typeof t.text==`string`?n={...n,value:t.text}:typeof t.content==`string`?n={...n,value:t.content}:typeof t.markdown==`string`?n={...n,value:t.markdown}:typeof t.description==`string`?n={...n,value:t.description}:typeof t.code==`string`?n={...n,value:t.code}:Array.isArray(t.headers)&&Array.isArray(t.rows)?n={...n,value:{headers:t.headers,rows:t.rows}}:Array.isArray(t.items)?n={...n,value:{items:t.items}}:Array.isArray(t.metrics)?n={...n,value:t.metrics}:Array.isArray(t.cards)?n={...n,value:t.cards}:Array.isArray(t.nodes)&&Array.isArray(t.edges)?n={...n,value:{nodes:t.nodes,edges:t.edges}}:typeof t.question==`string`?n={...n,value:{question:t.question,context:t.context,placeholder:t.placeholder}}:(`chartType`in t||Array.isArray(t.data))&&(n={...n,value:{chartType:t.chartType,data:t.data,xKey:t.xKey??`label`,yKeys:t.yKeys??[`value`]}})),n.type===`chart`){let e=n.value;if(e&&typeof e==`object`&&!Array.isArray(e)){let t=e,r=t.data&&typeof t.data==`object`&&!Array.isArray(t.data)?t.data:null,i=Array.isArray(t.labels)?t.labels:Array.isArray(r?.labels)?r.labels:null,a=Array.isArray(t.datasets)?t.datasets:Array.isArray(r?.datasets)?r.datasets:null,o=typeof t.type==`string`?t.type:typeof t.chartType==`string`?t.chartType:null;if(o&&i&&a&&!Array.isArray(t.data)){let e=a.map((e,t)=>String(e.label??`series${t+1}`)),t=i.map((e,t)=>{let n={label:String(e)};for(let[e,r]of a.entries()){let i=r,a=String(i.label??`series${e+1}`);n[a]=i.data?.[t]??0}return n});n={...n,value:{chartType:String(o),data:t,xKey:`label`,yKeys:e}}}}}let r=n;if(n.type===`text`||n.type===`paragraph`)return{...n,type:`markdown`};if(n.type===`heading`)return{...n,type:`markdown`,value:`## ${String(r.value??``)}`};if(n.type===`kv`){let e=t.entries&&typeof t.entries==`object`&&!Array.isArray(t.entries)?t.entries:r.value&&typeof r.value==`object`&&!Array.isArray(r.value)?r.value:null;if(e)return{...n,type:`table`,value:{headers:[`Key`,`Value`],rows:Object.entries(e).map(([e,t])=>[e,t])}}}if(n.type===`comparison`){let e=Js(t.columns??(r.value&&typeof r.value==`object`?r.value.columns:void 0))??Js(r.value);if(e)return{...n,type:`table`,value:e};let i=r.value;if(i&&typeof i==`object`&&!Array.isArray(i)){let e=i;if(Array.isArray(e.headers)&&Array.isArray(e.rows))return{...n,type:`table`}}}if(n.type===`timeline`){let e=r.value;if(Array.isArray(e)){let t=e.map(e=>{if(e&&typeof e==`object`){let t=e;return[String(t.status??t.state??``),String(t.time??t.date??t.timestamp??``),String(t.label??t.description??t.title??t.text??``)]}return[``,``,String(e)]});return{...n,type:`table`,value:{headers:[`Status`,`Time`,`Description`],rows:t}}}}return n}function Xs(e,t){let n=e=>{if(e==null)return``;if(typeof e==`string`)return e;if(typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`)return String(e);if(typeof e==`object`)try{let t=JSON.stringify(e);return typeof t==`string`?t:String(e)}catch{return String(e)}return String(e)};if(e==null)return null;if(typeof e==`string`)return{type:`markdown`,title:t,value:e};if(typeof e==`number`||typeof e==`boolean`)return{type:`markdown`,title:t,value:String(e)};if(Array.isArray(e)){if(e.every(e=>typeof e==`string`||typeof e==`number`||typeof e==`boolean`))return{type:`markdown`,title:t,value:e.map(e=>`- ${String(e)}`).join(`
1072
1072
  `)};let n=e.filter(e=>typeof e==`object`&&!!e);if(n.length===e.length){let e={success:`✅`,done:`✅`,warning:`⚠️`,"at-risk":`⚠️`,error:`❌`,info:`ℹ️`,pending:`⏳`};if(n.every(e=>typeof e.category==`string`&&Array.isArray(e.items))){let r=n.map(t=>{let n=typeof t.category==`string`?t.category:null,r=Array.isArray(t.items)?t.items:null;if(!n||!r)return null;let i=r.map(t=>{if(!t||typeof t!=`object`)return null;let n=t,r=n.label??n.title??n.name,i=typeof r==`string`||typeof r==`number`||typeof r==`boolean`?String(r):null;if(!i)return null;let a=typeof n.status==`string`?`${e[n.status.toLowerCase()]??`●`} `:``,o=n.detail??n.description;return`- ${a}${i}${typeof o==`string`&&o.length>0?` — ${o}`:typeof o==`number`||typeof o==`boolean`?` — ${String(o)}`:``}`}).filter(e=>typeof e==`string`);return i.length===0?null:`### ${n}\n${i.join(`
1073
1073
  `)}`}).filter(e=>typeof e==`string`);if(r.length>0)return{type:`markdown`,title:t,value:r.join(`
1074
1074
 
1075
- `)}}let r=new Set;for(let e of n)for(let t of Object.keys(e))r.add(t);let i=Array.from(r);return{type:`table`,title:t,value:{headers:i,rows:n.map(e=>i.map(t=>{if(!(t in e)||e[t]===void 0||e[t]===null)return``;let n=e[t];if(typeof n==`object`)try{let e=JSON.stringify(n);return typeof e==`string`?e:``}catch{return String(n)}return String(n)}))}}}}if(typeof e==`object`){let r=e;if(Array.isArray(r.items))return Ys(r.items,t);let i=Object.entries(r).map(([e,t])=>`**${e}**: ${n(t)}`);return i.length>0?{type:`markdown`,title:t,value:i.join(`
1076
- `)}:null}return null}function Xs(e){let t=e.value;if(e.type===`separator`)return{type:`markdown`,title:e.title,value:`---`};if(e.type===`checklist`){let n=Array.isArray(t)?t:t&&typeof t==`object`&&Array.isArray(t.items)?t.items:null;if(!n)return e;let r=n.map(e=>{if(!e||typeof e!=`object`)return null;let t=e;if(typeof t.label!=`string`)return null;let n=t.checked===!0?`x`:` `,r=typeof t.note==`string`&&t.note.length>0?` — ${t.note}`:``;return`- [${n}] ${t.label}${r}`}).filter(e=>typeof e==`string`);return r.length>0?{type:`markdown`,title:e.title,value:r.join(`
1075
+ `)}}let r=new Set;for(let e of n)for(let t of Object.keys(e))r.add(t);let i=Array.from(r);return{type:`table`,title:t,value:{headers:i,rows:n.map(e=>i.map(t=>{if(!(t in e)||e[t]===void 0||e[t]===null)return``;let n=e[t];if(typeof n==`object`)try{let e=JSON.stringify(n);return typeof e==`string`?e:``}catch{return String(n)}return String(n)}))}}}}if(typeof e==`object`){let r=e;if(Array.isArray(r.items))return Xs(r.items,t);let i=Object.entries(r).map(([e,t])=>`**${e}**: ${n(t)}`);return i.length>0?{type:`markdown`,title:t,value:i.join(`
1076
+ `)}:null}return null}function Zs(e){let t=e.value;if(e.type===`separator`)return{type:`markdown`,title:e.title,value:`---`};if(e.type===`checklist`){let n=Array.isArray(t)?t:t&&typeof t==`object`&&Array.isArray(t.items)?t.items:null;if(!n)return e;let r=n.map(e=>{if(!e||typeof e!=`object`)return null;let t=e;if(typeof t.label!=`string`)return null;let n=t.checked===!0?`x`:` `,r=typeof t.note==`string`&&t.note.length>0?` — ${t.note}`:``;return`- [${n}] ${t.label}${r}`}).filter(e=>typeof e==`string`);return r.length>0?{type:`markdown`,title:e.title,value:r.join(`
1077
1077
  `)}:e}if(e.type===`status-board`){let n={success:`✅`,done:`✅`,warning:`⚠️`,"at-risk":`⚠️`,error:`❌`,info:`ℹ️`,pending:`⏳`},r=Array.isArray(t)?t:t&&typeof t==`object`&&Array.isArray(t.items)?t.items:null;if(r&&r.length>0){let t=r[0];if(t&&typeof t==`object`&&`category`in t){let t=r.map(e=>{if(!e||typeof e!=`object`)return null;let t=e;if(typeof t.category!=`string`||!Array.isArray(t.items))return null;let r=t.items.map(e=>{if(!e||typeof e!=`object`)return null;let t=e;if(typeof t.label!=`string`)return null;let r=typeof t.status==`string`?`${n[t.status.toLowerCase()]??`●`} `:``,i=typeof t.detail==`string`&&t.detail.length>0?` — ${t.detail}`:``;return`- ${r}${t.label}${i}`}).filter(Boolean);return`### ${t.category}\n${r.join(`
1078
1078
  `)}`}).filter(Boolean);if(t.length>0)return{type:`markdown`,title:e.title,value:t.join(`
1079
1079
 
@@ -1083,18 +1083,18 @@ li{margin:4px 0}
1083
1083
  `)}`}).filter(Boolean);if(r.length>0)return{type:`markdown`,title:e.title,value:r.join(`
1084
1084
 
1085
1085
  `)}}let i=n.map(e=>{if(!e||typeof e!=`object`)return null;let n=e,r=typeof n.label==`string`?n.label:typeof n.title==`string`?n.title:null;return r?`- ${typeof n.status==`string`?`${t[n.status.toLowerCase()]??`●`} `:``}${r}${typeof n.description==`string`&&n.description.length>0?` — ${n.description}`:``}`:null}).filter(Boolean);if(i.length>0)return{type:`markdown`,title:e.title,value:i.join(`
1086
- `)}}}return e.type===`table`&&typeof t==`string`?{type:`markdown`,title:e.title,value:t}:new Set([`markdown`,`table`,`code`,`chart`,`metrics`,`tree`,`graph`,`mermaid`]).has(e.type)?e:Ys(e.value,e.title)||{type:`code`,title:e.title,value:typeof e.value==`string`?e.value:JSON.stringify(e.value,null,2)}}function Zs(e){return Array.isArray(e)?e.map(e=>Ks(e)?Xs(Js(e)):e):e}Cn.setOptions({async:!1,gfm:!0,breaks:!0}),Cn.use({renderer:{html(e){return B(e.text)}}});function Qs(e){return e.replace(/<table\b/g,`<div class="table-wrap"><table`).replace(/<\/table>/g,`</table></div>`)}function $s(e){if(typeof e!=`object`||!e)return`<p>${B(String(e))}</p>`;let t=e;return typeof t.type==`string`?tc(Js(t)):`<pre>${B(JSON.stringify(e,null,2))}</pre>`}function ec(e,t){let n=[];if(e&&n.push(`<h1>${B(e)}</h1>`),typeof t==`string`)n.push(`<div class="md-content">${Qs(Cn.parse(t))}</div>`);else if(Array.isArray(t))if(t.length===0)n.push(`<p><em>empty</em></p>`);else if(Ks(t[0]))for(let e of t)n.push($s(e));else typeof t[0]==`object`&&t[0]!==null?n.push(nc(t)):n.push(`<ul>${t.map(e=>`<li>${B(String(e))}</li>`).join(``)}</ul>`);else if(typeof t==`object`&&t){let e=t;if(Array.isArray(e.blocks)&&e.blocks.length>0)for(let t of e.blocks)n.push($s(t));else Array.isArray(e.metrics)?n.push(rc(e.metrics)):Array.isArray(e.nodes)&&Array.isArray(e.edges)?(n.push(`<pre class="mermaid">${B(sc(e))}</pre>`),n.push(`<script src="https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.min.js"><\/script>`),n.push(`<script>mermaid.run();<\/script>`)):n.push(ac(e))}else n.push(`<p>${B(String(t))}</p>`);return n.join(`
1087
- `)}function tc(e){let t=[];switch(e.title&&t.push(`<h2>${B(e.title)}</h2>`),e.type){case`markdown`:t.push(`<div class="md-content">${Qs(Cn.parse(String(e.value??``)))}</div>`);break;case`code`:t.push(`<pre><code>${B(String(e.value??``))}</code></pre>`);break;case`mermaid`:t.push(`<pre class="mermaid">${B(String(e.value??``))}</pre>`);break;case`table`:if(Array.isArray(e.value)){let n=e.value;if(n.length>0&&Array.isArray(n[0])){let e=n,r=e[0].map(String),i=e.slice(1).map(e=>Object.fromEntries(r.map((t,n)=>[t,e[n]])));t.push(nc(i))}else t.push(nc(n))}else if(e.value&&typeof e.value==`object`&&`headers`in e.value&&`rows`in e.value){let{headers:n,rows:r}=e.value,i=r.map(e=>Object.fromEntries(n.map((t,n)=>[t,e[n]])));t.push(nc(i))}break;case`metrics`:{let n;Array.isArray(e.value)?n=e.value:e.value&&typeof e.value==`object`&&(n=Object.entries(e.value).map(([e,t])=>({label:e,value:String(t)}))),n&&t.push(rc(n));break}case`cards`:Array.isArray(e.value)&&t.push(ic(e.value));break;case`tree`:e.value&&typeof e.value==`object`&&t.push(ac(e.value));break;case`graph`:e.value&&typeof e.value==`object`&&t.push(`<pre class="mermaid">${B(sc(e.value))}</pre>`);break;case`chart`:t.push(js(e));break;case`timeline`:{let n=e.value;Array.isArray(n)&&(n={items:n.map(e=>({title:String(e.event??e.title??``),phase:e.date==null?e.phase==null?void 0:String(e.phase):String(e.date),description:e.description==null?void 0:String(e.description),status:e.status??`done`}))}),n&&t.push(Ss(n));break}case`checklist`:e.value&&t.push(Cs(e.value));break;case`comparison`:e.value&&t.push(ws(e.value));break;case`status-board`:e.value&&t.push(Ts(e.value));break;case`prompt`:e.value&&t.push(Es(e.value));break;case`progress`:e.value&&t.push(Ds(e.value));break;case`text`:t.push(`<div class="md-content">${Cn.parse(String(e.value??``))}</div>`);break;case`heading`:{let n=Math.min(Math.max(Number(e.level)||2,1),6);t.push(`<h${n}>${B(String(e.value??``))}</h${n}>`);break}case`paragraph`:t.push(`<p>${B(String(e.value??``))}</p>`);break;case`separator`:t.push(`<hr class="separator">`);break;case`actions`:{let n=(Array.isArray(e.value)?e.value:[]).map(e=>{if(e.type===`select`){let t=Array.isArray(e.options)?e.options.map(e=>`<option value="${B(String(e.value??e.label??``))}">${B(String(e.label??e.value??``))}</option>`).join(``):``;return`<select class="action-select"><option value="">${B(String(e.label??`Select...`))}</option>${t}</select>`}return`<button class="action-btn action-${String(e.variant??`secondary`)}">${B(String(e.label??``))}</button>`}).join(``);t.push(`<div class="action-bar">${n}</div>`);break}default:t.push(`<pre>${B(JSON.stringify(e.value,null,2))}</pre>`)}return t.join(`
1088
- `)}function nc(e){if(e.length===0)return`<p><em>empty table</em></p>`;let t=Object.keys(e[0]);return`<div class="table-wrap"><table><thead><tr>${t.map(e=>`<th>${B(e)}</th>`).join(``)}</tr></thead><tbody>${e.map(e=>`<tr>${t.map(t=>`<td>${B(String(e[t]??``))}</td>`).join(``)}</tr>`).join(`
1089
- `)}</tbody></table></div>`}function rc(e){return`<div class="metric-grid">${e.map(e=>`<div class="metric"><div class="metric-value">${B(String(e.value))}</div><div class="metric-label">${B(e.label)}</div></div>`).join(``)}</div>`}function ic(e){return`<div class="card-grid">${e.map(e=>{let t=[`<div class="card">`];return e.title&&t.push(`<div class="card-title">${B(String(e.title))}</div>`),(e.body||e.description)&&t.push(`<div class="card-body">${B(String(e.body??e.description))}</div>`),(e.badge||e.status)&&t.push(`<span class="badge">${B(String(e.badge??e.status))}</span>`),t.push(`</div>`),t.join(``)}).join(``)}</div>`}function ac(e){if(`name`in e&&`children`in e&&Array.isArray(e.children))return oc(e);if(`name`in e&&!(`children`in e))return`<div class="tree-node"><span class="tree-key">${B(String(e.name))}</span></div>`;let t=[];for(let[n,r]of Object.entries(e))typeof r==`object`&&r&&!Array.isArray(r)?t.push(`<div class="tree-node"><span class="tree-key">${B(n)}:</span><div class="tree-children">${ac(r)}</div></div>`):t.push(`<div class="tree-node"><span class="tree-key">${B(n)}:</span> ${B(Ws(r))}</div>`);return t.join(``)}function oc(e){let t=B(String(e.name));return!e.children||e.children.length===0?`<div class="tree-node"><span class="tree-key">${t}</span></div>`:`<div class="tree-node"><span class="tree-key">${t}</span><div class="tree-children">${e.children.map(e=>typeof e==`object`&&e?oc(e):`<div class="tree-node"><span class="tree-key">${B(String(e))}</span></div>`).join(``)}</div></div>`}function sc(e){let t=[`graph LR`];for(let n of e.nodes){let e=Gs(String(n.id??n.name??``)),r=String(n.label??n.name??e);t.push(` ${e}["${r}"]`)}for(let n of e.edges){let e=Gs(String(n.source??n.from??``)),r=Gs(String(n.target??n.to??``)),i=n.label?`|${String(n.label)}|`:``;t.push(` ${e} -->${i} ${r}`)}return t.join(`
1090
- `)}function cc(e,t,n,r){let i=r&&r!==`auto`?ma(r,t):ec(e,t);return`<!DOCTYPE html>
1086
+ `)}}}return e.type===`table`&&typeof t==`string`?{type:`markdown`,title:e.title,value:t}:new Set([`markdown`,`table`,`code`,`chart`,`metrics`,`tree`,`graph`,`mermaid`]).has(e.type)?e:Xs(e.value,e.title)||{type:`code`,title:e.title,value:typeof e.value==`string`?e.value:JSON.stringify(e.value,null,2)}}function Qs(e){if(!Array.isArray(e)&&typeof e==`object`&&e){let t=e;return Array.isArray(t.blocks)&&t.blocks.length>0?Qs(t.blocks):e}return Array.isArray(e)?e.map(e=>qs(e)?Zs(Ys(e)):e):e}Cn.setOptions({async:!1,gfm:!0,breaks:!0}),Cn.use({renderer:{html(e){return B(e.text)}}});function $s(e){return e.replace(/<table\b/g,`<div class="table-wrap"><table`).replace(/<\/table>/g,`</table></div>`)}function ec(e){if(typeof e!=`object`||!e)return`<p>${B(String(e))}</p>`;let t=e;return typeof t.type==`string`?nc(Ys(t)):`<pre>${B(JSON.stringify(e,null,2))}</pre>`}function tc(e,t){let n=[];if(e&&n.push(`<h1>${B(e)}</h1>`),typeof t==`string`)n.push(`<div class="md-content">${$s(Cn.parse(t))}</div>`);else if(Array.isArray(t))if(t.length===0)n.push(`<p><em>empty</em></p>`);else if(qs(t[0]))for(let e of t)n.push(ec(e));else typeof t[0]==`object`&&t[0]!==null?n.push(rc(t)):n.push(`<ul>${t.map(e=>`<li>${B(String(e))}</li>`).join(``)}</ul>`);else if(typeof t==`object`&&t){let e=t;if(Array.isArray(e.blocks)&&e.blocks.length>0)for(let t of e.blocks)n.push(ec(t));else Array.isArray(e.metrics)?n.push(ic(e.metrics)):Array.isArray(e.nodes)&&Array.isArray(e.edges)?(n.push(`<pre class="mermaid">${B(cc(e))}</pre>`),n.push(`<script src="https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.min.js"><\/script>`),n.push(`<script>mermaid.run();<\/script>`)):n.push(oc(e))}else n.push(`<p>${B(String(t))}</p>`);return n.join(`
1087
+ `)}function nc(e){let t=[];switch(e.title&&t.push(`<h2>${B(e.title)}</h2>`),e.type){case`markdown`:t.push(`<div class="md-content">${$s(Cn.parse(String(e.value??``)))}</div>`);break;case`code`:t.push(`<pre><code>${B(String(e.value??``))}</code></pre>`);break;case`mermaid`:t.push(`<pre class="mermaid">${B(String(e.value??``))}</pre>`);break;case`table`:if(Array.isArray(e.value)){let n=e.value;if(n.length>0&&Array.isArray(n[0])){let e=n,r=e[0].map(String),i=e.slice(1).map(e=>Object.fromEntries(r.map((t,n)=>[t,e[n]])));t.push(rc(i))}else t.push(rc(n))}else if(e.value&&typeof e.value==`object`&&`headers`in e.value&&`rows`in e.value){let{headers:n,rows:r}=e.value,i=r.map(e=>Object.fromEntries(n.map((t,n)=>[t,e[n]])));t.push(rc(i))}break;case`metrics`:{let n;Array.isArray(e.value)?n=e.value:e.value&&typeof e.value==`object`&&(n=Object.entries(e.value).map(([e,t])=>({label:e,value:String(t)}))),n&&t.push(ic(n));break}case`cards`:Array.isArray(e.value)&&t.push(ac(e.value));break;case`tree`:e.value&&typeof e.value==`object`&&t.push(oc(e.value));break;case`graph`:e.value&&typeof e.value==`object`&&t.push(`<pre class="mermaid">${B(cc(e.value))}</pre>`);break;case`chart`:t.push(Ms(e));break;case`timeline`:{let n=e.value;Array.isArray(n)&&(n={items:n.map(e=>({title:String(e.event??e.title??``),phase:e.date==null?e.phase==null?void 0:String(e.phase):String(e.date),description:e.description==null?void 0:String(e.description),status:e.status??`done`}))}),n&&t.push(Cs(n));break}case`checklist`:e.value&&t.push(ws(e.value));break;case`comparison`:e.value&&t.push(Ts(e.value));break;case`status-board`:e.value&&t.push(Es(e.value));break;case`prompt`:e.value&&t.push(Ds(e.value));break;case`progress`:e.value&&t.push(Os(e.value));break;case`text`:t.push(`<div class="md-content">${Cn.parse(String(e.value??``))}</div>`);break;case`heading`:{let n=Math.min(Math.max(Number(e.level)||2,1),6);t.push(`<h${n}>${B(String(e.value??``))}</h${n}>`);break}case`paragraph`:t.push(`<p>${B(String(e.value??``))}</p>`);break;case`separator`:t.push(`<hr class="separator">`);break;case`actions`:{let n=(Array.isArray(e.value)?e.value:[]).map(e=>{if(e.type===`select`){let t=Array.isArray(e.options)?e.options.map(e=>`<option value="${B(String(e.value??e.label??``))}">${B(String(e.label??e.value??``))}</option>`).join(``):``;return`<select class="action-select"><option value="">${B(String(e.label??`Select...`))}</option>${t}</select>`}return`<button class="action-btn action-${String(e.variant??`secondary`)}">${B(String(e.label??``))}</button>`}).join(``);t.push(`<div class="action-bar">${n}</div>`);break}default:t.push(`<pre>${B(JSON.stringify(e.value,null,2))}</pre>`)}return t.join(`
1088
+ `)}function rc(e){if(e.length===0)return`<p><em>empty table</em></p>`;let t=Object.keys(e[0]);return`<div class="table-wrap"><table><thead><tr>${t.map(e=>`<th>${B(e)}</th>`).join(``)}</tr></thead><tbody>${e.map(e=>`<tr>${t.map(t=>`<td>${B(String(e[t]??``))}</td>`).join(``)}</tr>`).join(`
1089
+ `)}</tbody></table></div>`}function ic(e){return`<div class="metric-grid">${e.map(e=>`<div class="metric"><div class="metric-value">${B(String(e.value))}</div><div class="metric-label">${B(e.label)}</div></div>`).join(``)}</div>`}function ac(e){return`<div class="card-grid">${e.map(e=>{let t=[`<div class="card">`];return e.title&&t.push(`<div class="card-title">${B(String(e.title))}</div>`),(e.body||e.description)&&t.push(`<div class="card-body">${B(String(e.body??e.description))}</div>`),(e.badge||e.status)&&t.push(`<span class="badge">${B(String(e.badge??e.status))}</span>`),t.push(`</div>`),t.join(``)}).join(``)}</div>`}function oc(e){if(`name`in e&&`children`in e&&Array.isArray(e.children))return sc(e);if(`name`in e&&!(`children`in e))return`<div class="tree-node"><span class="tree-key">${B(String(e.name))}</span></div>`;let t=[];for(let[n,r]of Object.entries(e))typeof r==`object`&&r&&!Array.isArray(r)?t.push(`<div class="tree-node"><span class="tree-key">${B(n)}:</span><div class="tree-children">${oc(r)}</div></div>`):t.push(`<div class="tree-node"><span class="tree-key">${B(n)}:</span> ${B(Gs(r))}</div>`);return t.join(``)}function sc(e){let t=B(String(e.name));return!e.children||e.children.length===0?`<div class="tree-node"><span class="tree-key">${t}</span></div>`:`<div class="tree-node"><span class="tree-key">${t}</span><div class="tree-children">${e.children.map(e=>typeof e==`object`&&e?sc(e):`<div class="tree-node"><span class="tree-key">${B(String(e))}</span></div>`).join(``)}</div></div>`}function cc(e){let t=[`graph LR`];for(let n of e.nodes){let e=Ks(String(n.id??n.name??``)),r=String(n.label??n.name??e);t.push(` ${e}["${r}"]`)}for(let n of e.edges){let e=Ks(String(n.source??n.from??``)),r=Ks(String(n.target??n.to??``)),i=n.label?`|${String(n.label)}|`:``;t.push(` ${e} -->${i} ${r}`)}return t.join(`
1090
+ `)}function lc(e,t,n,r){let i=r&&r!==`auto`?ma(r,t):tc(e,t);return`<!DOCTYPE html>
1091
1091
  <html lang="en">
1092
1092
  <head>
1093
1093
  <meta charset="UTF-8">
1094
1094
  <meta name="viewport" content="width=device-width,initial-scale=1.0">
1095
1095
  <title>${B(e??`AI Kit Dashboard`)}</title>
1096
1096
  <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet">
1097
- <style>${xs()}</style>
1097
+ <style>${Ss()}</style>
1098
1098
  </head>
1099
1099
  <body>
1100
1100
  <div class="dashboard">
@@ -1179,17 +1179,17 @@ document.querySelectorAll('.table-wrap').forEach(wrap=>{
1179
1179
  });
1180
1180
  <\/script>
1181
1181
  </body>
1182
- </html>`}function lc(e,t,n){let r=[];if(e&&r.push(`# ${e}\n`),typeof t==`string`)r.push(t);else if(Array.isArray(t))if(t.length===0)r.push(`*(empty)*`);else if(Ks(t[0]))for(let e of t)r.push(uc(Js(e),n));else if(typeof t[0]==`object`&&t[0]!==null)n?.compactTables?r.push(fc(t)):r.push(dc(t));else for(let e of t)r.push(`- ${String(e)}`);else if(typeof t==`object`&&t){let e=t;if(Array.isArray(e.blocks)&&e.blocks.length>0)for(let t of e.blocks)Ks(t)?r.push(uc(Js(t),n)):r.push(String(t));else Array.isArray(e.nodes)&&Array.isArray(e.edges)?r.push(hc(e)):Array.isArray(e.metrics)?r.push(mc(e.metrics)):r.push(gc(e))}else r.push(String(t));return r.join(`
1183
- `)}function uc(e,t){let n=[];switch(e.title&&n.push(`## ${e.title}\n`),e.type){case`markdown`:n.push(String(e.value??``));break;case`code`:n.push(`\`\`\`${e.language??``}\n${String(e.value??``)}\n\`\`\``);break;case`mermaid`:n.push(`\`\`\`mermaid\n${String(e.value??``)}\n\`\`\``);break;case`table`:{let r=e.value;if(Array.isArray(r)&&r.length>0)t?.compactTables?n.push(fc(r,e.title)):n.push(dc(r));else if(r&&typeof r==`object`&&!Array.isArray(r)&&`headers`in r&&`rows`in r){let{headers:i,rows:a}=r;if(t?.compactTables){let t=[];e.title&&t.push(`**${e.title}**\n`);for(let e=0;e<a.length;e++){let n=i.map((t,n)=>`**${t}**: ${String(a[e]?.[n]??``)}`).join(` · `);t.push(`${e+1}. ${n}`)}n.push(t.join(`
1184
- `))}else{n.push(`| ${i.join(` | `)} |`),n.push(`| ${i.map(()=>`---`).join(` | `)} |`);for(let e of a)n.push(`| ${e.map(e=>String(e??``)).join(` | `)} |`)}}else n.push(`*(empty table)*`);break}case`metrics`:Array.isArray(e.value)&&n.push(mc(e.value));break;case`graph`:e.value&&typeof e.value==`object`&&n.push(hc(e.value));break;case`cards`:if(Array.isArray(e.value))for(let t of e.value)n.push(`### ${t.title??`Card`}`),(t.body||t.description)&&n.push(String(t.body??t.description)),(t.badge||t.status)&&n.push(`> **${t.badge??t.status}**`),n.push(``);break;case`tree`:e.value&&typeof e.value==`object`&&n.push(gc(e.value));break;case`chart`:{let t=e.value;t?.data&&Array.isArray(t.data)&&n.push(`*${String(t.chartType??`chart`)} chart — ${t.data.length} data points*`);break}case`timeline`:{let t=e.value;if(t?.items)for(let e of t.items){let t=e.status===`done`?`✅`:e.status===`active`?`🔄`:e.status===`error`?`❌`:`⬜`;n.push(`${t} **${e.title}**${e.description?` — ${e.description}`:``}`)}break}case`checklist`:{let t=e.value;if(t?.items)for(let e of t.items)n.push(`- [${e.checked?`x`:` `}] ${e.label}${e.note?` — ${e.note}`:``}`);break}case`comparison`:{let r=e.value;if(r?.columns&&r.columns.length>0)if(t?.compactTables)n.push(pc(r.columns,e.title));else{let e=Math.max(...r.columns.map(e=>e.items?.length??0)),t=r.columns.map(e=>e.title);n.push(`| ${t.join(` | `)} |`),n.push(`| ${t.map(()=>`---`).join(` | `)} |`);for(let t=0;t<e;t++)n.push(`| ${r.columns.map(e=>e.items?.[t]??``).join(` | `)} |`)}break}case`status-board`:{let t=e.value;if(t?.items)for(let e of t.items){let t=e.status===`success`?`🟢`:e.status===`warning`?`🟡`:e.status===`error`?`🔴`:e.status===`info`?`🔵`:`⚪`;n.push(`${t} **${e.label}**${e.detail?` — ${e.detail}`:``}`)}break}case`prompt`:{let t=e.value;t?.question&&(n.push(`> **${t.question}**`),t.context&&n.push(`> ${t.context}`));break}case`progress`:{let t=e.value;if(t?.items)for(let e of t.items){let t=e.max??100,r=t>0?Math.round(e.value/t*100):0,i=Math.round(r/5),a=`█`.repeat(i)+`░`.repeat(20-i);n.push(`${e.label}: ${a} ${r}%`)}break}case`text`:n.push(String(e.value??``));break;case`heading`:{let t=Math.min(Math.max(Number(e.level)||2,1),6);n.push(`${`#`.repeat(t)} ${String(e.value??``)}\n`);break}case`paragraph`:n.push(String(e.value??``));break;case`separator`:n.push(`---
1182
+ </html>`}function uc(e,t,n){let r=[];if(e&&r.push(`# ${e}\n`),typeof t==`string`)r.push(t);else if(Array.isArray(t))if(t.length===0)r.push(`*(empty)*`);else if(qs(t[0])||typeof t[0]==`object`&&t[0]!==null&&typeof t[0].type==`string`)for(let e of t)r.push(dc(Ys(e),n));else if(typeof t[0]==`object`&&t[0]!==null)n?.compactTables?r.push(pc(t)):r.push(fc(t));else for(let e of t)r.push(`- ${String(e)}`);else if(typeof t==`object`&&t){let e=t;if(Array.isArray(e.blocks)&&e.blocks.length>0)for(let t of e.blocks)qs(t)||typeof t==`object`&&t&&typeof t.type==`string`?r.push(dc(Ys(t),n)):typeof t==`object`&&t?r.push(_c(t)):r.push(String(t));else Array.isArray(e.nodes)&&Array.isArray(e.edges)?r.push(gc(e)):Array.isArray(e.metrics)?r.push(hc(e.metrics)):r.push(_c(e))}else r.push(String(t));return r.join(`
1183
+ `)}function dc(e,t){let n=[];switch(e.title&&n.push(`## ${e.title}\n`),e.type){case`markdown`:n.push(String(e.value??``));break;case`code`:n.push(`\`\`\`${e.language??``}\n${String(e.value??``)}\n\`\`\``);break;case`mermaid`:n.push(`\`\`\`mermaid\n${String(e.value??``)}\n\`\`\``);break;case`table`:{let r=e.value;if(Array.isArray(r)&&r.length>0)t?.compactTables?n.push(pc(r,e.title)):n.push(fc(r));else if(r&&typeof r==`object`&&!Array.isArray(r)&&`headers`in r&&`rows`in r){let{headers:i,rows:a}=r;if(t?.compactTables){let t=[];e.title&&t.push(`**${e.title}**\n`);for(let e=0;e<a.length;e++){let n=i.map((t,n)=>`**${t}**: ${String(a[e]?.[n]??``)}`).join(` · `);t.push(`${e+1}. ${n}`)}n.push(t.join(`
1184
+ `))}else{n.push(`| ${i.join(` | `)} |`),n.push(`| ${i.map(()=>`---`).join(` | `)} |`);for(let e of a)n.push(`| ${e.map(e=>String(e??``)).join(` | `)} |`)}}else n.push(`*(empty table)*`);break}case`metrics`:Array.isArray(e.value)&&n.push(hc(e.value));break;case`graph`:e.value&&typeof e.value==`object`&&n.push(gc(e.value));break;case`cards`:if(Array.isArray(e.value))for(let t of e.value)n.push(`### ${t.title??`Card`}`),(t.body||t.description)&&n.push(String(t.body??t.description)),(t.badge||t.status)&&n.push(`> **${t.badge??t.status}**`),n.push(``);break;case`tree`:e.value&&typeof e.value==`object`&&n.push(_c(e.value));break;case`chart`:{let t=e.value;t?.data&&Array.isArray(t.data)&&n.push(`*${String(t.chartType??`chart`)} chart — ${t.data.length} data points*`);break}case`timeline`:{let t=e.value;if(t?.items)for(let e of t.items){let t=e.status===`done`?`✅`:e.status===`active`?`🔄`:e.status===`error`?`❌`:`⬜`;n.push(`${t} **${e.title}**${e.description?` — ${e.description}`:``}`)}break}case`checklist`:{let t=e.value;if(t?.items)for(let e of t.items)n.push(`- [${e.checked?`x`:` `}] ${e.label}${e.note?` — ${e.note}`:``}`);break}case`comparison`:{let r=e.value;if(r?.columns&&r.columns.length>0)if(t?.compactTables)n.push(mc(r.columns,e.title));else{let e=Math.max(...r.columns.map(e=>e.items?.length??0)),t=r.columns.map(e=>e.title);n.push(`| ${t.join(` | `)} |`),n.push(`| ${t.map(()=>`---`).join(` | `)} |`);for(let t=0;t<e;t++)n.push(`| ${r.columns.map(e=>e.items?.[t]??``).join(` | `)} |`)}break}case`status-board`:{let t=e.value;if(t?.items)for(let e of t.items){let t=e.status===`success`?`🟢`:e.status===`warning`?`🟡`:e.status===`error`?`🔴`:e.status===`info`?`🔵`:`⚪`;n.push(`${t} **${e.label}**${e.detail?` — ${e.detail}`:``}`)}break}case`prompt`:{let t=e.value;t?.question&&(n.push(`> **${t.question}**`),t.context&&n.push(`> ${t.context}`));break}case`progress`:{let t=e.value;if(t?.items)for(let e of t.items){let t=e.max??100,r=t>0?Math.round(e.value/t*100):0,i=Math.round(r/5),a=`█`.repeat(i)+`░`.repeat(20-i);n.push(`${e.label}: ${a} ${r}%`)}break}case`text`:n.push(String(e.value??``));break;case`heading`:{let t=Math.min(Math.max(Number(e.level)||2,1),6);n.push(`${`#`.repeat(t)} ${String(e.value??``)}\n`);break}case`paragraph`:n.push(String(e.value??``));break;case`separator`:n.push(`---
1185
1185
  `);break;default:n.push(JSON.stringify(e.value,null,2))}return n.push(``),n.join(`
1186
- `)}function dc(e){if(e.length===0)return`*(empty table)*`;let t=Object.keys(e[0]),n=[];n.push(`| ${t.join(` | `)} |`),n.push(`| ${t.map(()=>`---`).join(` | `)} |`);for(let r of e)n.push(`| ${t.map(e=>String(r[e]??``)).join(` | `)} |`);return n.join(`
1187
- `)}function fc(e,t){if(e.length===0)return`*(empty table)*`;let n=Object.keys(e[0]),r=[];t&&r.push(`**${t}**\n`);for(let t=0;t<e.length;t++){let i=e[t],a=String(i[n[0]]??``);if(n.length===1)r.push(`${t+1}. **${a}**`);else{let e=n.slice(1).map(e=>`${e}: ${String(i[e]??``)}`).join(` · `);r.push(`${t+1}. **${a}** — ${e}`)}}return r.join(`
1188
- `)}function pc(e,t){let n=[];t&&n.push(`**${t}**\n`);for(let t of e){if(n.push(`**${t.title}**`),t.items&&t.items.length>0)for(let e of t.items)n.push(`- ${e}`);else n.push(`- *(none)*`);n.push(``)}return n.join(`
1189
- `)}function mc(e){return e.map(e=>`- **${e.label}**: ${e.value}`).join(`
1190
- `)}function hc(e){let t=["```mermaid",`graph LR`];for(let n of e.nodes){let e=Gs(String(n.id??n.name??``)),r=String(n.label??n.name??e);t.push(` ${e}["${r}"]`)}for(let n of e.edges){let e=Gs(String(n.source??n.from??``)),r=Gs(String(n.target??n.to??``)),i=n.label?`|${String(n.label)}|`:``;t.push(` ${e} -->${i} ${r}`)}return t.push("```"),t.join(`
1191
- `)}function gc(e,t=0){let n=` `.repeat(t),r=[];for(let[i,a]of Object.entries(e))typeof a==`object`&&a&&!Array.isArray(a)?(r.push(`${n}- **${i}**:`),r.push(gc(a,t+1))):r.push(`${n}- **${i}**: ${Ws(a)}`);return r.join(`
1192
- `)}const _c=import.meta.dirname??m(v(import.meta.url));function vc(e){let t=e;for(let e=0;e<10;e++){try{let e=g(t,`package.json`);if(a(e)&&JSON.parse(s(e,`utf8`)).name===`@vpxa/aikit`)return t}catch{}let e=m(t);if(e===t)break;t=e}return _(e,`..`,`..`,`..`)}const yc=`ui://aikit/present.html`,bc=F.object({type:F.enum([`button`,`select`]).describe(`Action type`),id:F.string().describe(`Unique action identifier`),label:F.string().describe(`Display label`),variant:F.enum([`primary`,`danger`,`default`]).optional().describe(`Button style variant`),options:F.array(F.union([F.string(),F.object({label:F.string(),value:F.string()})])).optional().describe(`Select options (for type=select)`)}),xc={format:F.enum([`html`,`browser`]).default(`html`).describe(`Output format.
1186
+ `)}function fc(e){if(e.length===0)return`*(empty table)*`;let t=Object.keys(e[0]),n=[];n.push(`| ${t.join(` | `)} |`),n.push(`| ${t.map(()=>`---`).join(` | `)} |`);for(let r of e)n.push(`| ${t.map(e=>String(r[e]??``)).join(` | `)} |`);return n.join(`
1187
+ `)}function pc(e,t){if(e.length===0)return`*(empty table)*`;let n=Object.keys(e[0]),r=[];t&&r.push(`**${t}**\n`);for(let t=0;t<e.length;t++){let i=e[t],a=String(i[n[0]]??``);if(n.length===1)r.push(`${t+1}. **${a}**`);else{let e=n.slice(1).map(e=>`${e}: ${String(i[e]??``)}`).join(` · `);r.push(`${t+1}. **${a}** — ${e}`)}}return r.join(`
1188
+ `)}function mc(e,t){let n=[];t&&n.push(`**${t}**\n`);for(let t of e){if(n.push(`**${t.title}**`),t.items&&t.items.length>0)for(let e of t.items)n.push(`- ${e}`);else n.push(`- *(none)*`);n.push(``)}return n.join(`
1189
+ `)}function hc(e){return e.map(e=>`- **${e.label}**: ${e.value}`).join(`
1190
+ `)}function gc(e){let t=["```mermaid",`graph LR`];for(let n of e.nodes){let e=Ks(String(n.id??n.name??``)),r=String(n.label??n.name??e);t.push(` ${e}["${r}"]`)}for(let n of e.edges){let e=Ks(String(n.source??n.from??``)),r=Ks(String(n.target??n.to??``)),i=n.label?`|${String(n.label)}|`:``;t.push(` ${e} -->${i} ${r}`)}return t.push("```"),t.join(`
1191
+ `)}function _c(e,t=0){let n=` `.repeat(t),r=[];for(let[i,a]of Object.entries(e))typeof a==`object`&&a&&!Array.isArray(a)?(r.push(`${n}- **${i}**:`),r.push(_c(a,t+1))):r.push(`${n}- **${i}**: ${Gs(a)}`);return r.join(`
1192
+ `)}const vc=import.meta.dirname??m(v(import.meta.url));function yc(e){let t=e;for(let e=0;e<10;e++){try{let e=g(t,`package.json`);if(a(e)&&JSON.parse(s(e,`utf8`)).name===`@vpxa/aikit`)return t}catch{}let e=m(t);if(e===t)break;t=e}return _(e,`..`,`..`,`..`)}const bc=`ui://aikit/present.html`,xc=F.object({type:F.enum([`button`,`select`]).describe(`Action type`),id:F.string().describe(`Unique action identifier`),label:F.string().describe(`Display label`),variant:F.enum([`primary`,`danger`,`default`]).optional().describe(`Button style variant`),options:F.array(F.union([F.string(),F.object({label:F.string(),value:F.string()})])).optional().describe(`Select options (for type=select)`)}),Sc={format:F.enum([`html`,`browser`]).default(`html`).describe(`Output format.
1193
1193
  - "html" (default): Rich markdown in chat + embedded UIResource for MCP-UI hosts. Actions shown as numbered choices.
1194
1194
  - "browser": Rich markdown in chat + opens beautiful themed dashboard in the browser. When actions are provided, the browser shows interactive buttons and the tool blocks until user clicks, returning their selection.`),title:F.string().optional().describe(`Optional heading`),content:F.any().describe(`Content to present. Accepts these shapes:
1195
1195
  • markdown string — rendered as rich text
@@ -1211,7 +1211,7 @@ document.querySelectorAll('.table-wrap').forEach(wrap=>{
1211
1211
  - type:"comparison" → value: [{title,items:string[]}] (columns)
1212
1212
  - type:"progress" → value: {label,value:number,max?:number}
1213
1213
  • any JSON — rendered as collapsible tree
1214
- IMPORTANT: For charts, use the ChartValue format above. Do NOT use Chart.js format ({labels, datasets}) — it will be auto-converted but the native format is preferred.`),actions:F.array(bc).optional().describe(`Interactive actions (buttons/selects). In html mode, shown as numbered choices. In browser mode, rendered as clickable buttons and the tool blocks until user clicks.`),template:F.enum([`auto`,`list-sort`,`data-table`,`picker`,`flame-graph`,`form`,`timeline`,`kanban`,`tree`,`diff-view`,`dashboard`]).optional().describe(`UI template for interactive display in MCP Apps hosts.
1214
+ IMPORTANT: For charts, use the ChartValue format above. Do NOT use Chart.js format ({labels, datasets}) — it will be auto-converted but the native format is preferred.`),actions:F.array(xc).optional().describe(`Interactive actions (buttons/selects). In html mode, shown as numbered choices. In browser mode, rendered as clickable buttons and the tool blocks until user clicks.`),template:F.enum([`auto`,`list-sort`,`data-table`,`picker`,`flame-graph`,`form`,`timeline`,`kanban`,`tree`,`diff-view`,`dashboard`]).optional().describe(`UI template for interactive display in MCP Apps hosts.
1215
1215
  - auto (default): detect from content shape
1216
1216
  - list-sort: drag-drop reorderable list — content: { items: [{id, label}] }
1217
1217
  - data-table: filterable sortable table — content: { columns: [{key, label}], rows: [{...}], stats?: [{label, value}] }
@@ -1222,16 +1222,16 @@ IMPORTANT: For charts, use the ChartValue format above. Do NOT use Chart.js form
1222
1222
  - kanban: drag-drop board — content: { columns: [{id, label, color?}], cards: [{id, title, column, tags?[], priority?}] }
1223
1223
  - tree: collapsible tree view — content: { root: {label, children?:[...]} | [...] }
1224
1224
  - diff-view: side-by-side diff — content: { files: [{path, status, additions, deletions, hunks:[{header, changes:[{type, content}]}]}] }
1225
- - dashboard: metric cards grid — content: { metrics: [{label, value, trend?, status?, type?}] }`)};let Sc,Cc=!1,wc=null;process.on(`exit`,()=>{if(wc){try{wc.close()}catch{}wc=null}});function Tc(){return g(vc(_c),`packages`,`present`,`dist`,`index.html`)}function Ec(){if(!Sc)try{Sc=s(Tc(),`utf-8`)}catch{Sc=``}return Sc}function Dc(e,t){let n=L(`present`),r=Ec(),i=`Present content to the user in the best format. Two modes:
1225
+ - dashboard: metric cards grid — content: { metrics: [{label, value, trend?, status?, type?}] }`)};let Cc,wc=!1,Y=null;process.on(`exit`,()=>{if(Y){try{Y.close()}catch{}Y=null}});function Tc(){return g(yc(vc),`packages`,`present`,`dist`,`index.html`)}function Ec(){if(!Cc)try{Cc=s(Tc(),`utf-8`)}catch{Cc=``}return Cc}function Dc(e,t){let n=L(`present`),r=Ec(),i=`Present content to the user in the best format. Two modes:
1226
1226
  - "html" (default): Rich markdown in chat + embedded UIResource. Use for display-only content (tables, charts, reports, status boards) where no user interaction is needed.
1227
1227
  - "browser": Serves a themed dashboard on a local URL. Use ONLY when you need user interaction back (confirmations, selections, form input). The tool blocks until user clicks an action button, then returns their selection.
1228
1228
  FORMAT RULE: If no user interaction is needed → use "html". If you need user input back → use "browser".
1229
1229
  CONTENT GUIDE: Pass typed blocks [{ type, title?, value }] for structured content. See the \`content\` parameter description for all supported block types and their value shapes. For charts: use {chartType, data:Record[], xKey, yKeys} — NOT Chart.js format.
1230
- BROWSER WORKFLOW: After calling present with format "browser", you MUST extract the URL from the response and call openBrowserPage({ url }) tool - PlayWright MCP to open it in VS Code Simple Browser. A system browser fallback also opens automatically, but always call openBrowserPage tool - PlayWright MCP yourself.`,a=async({format:e,title:n,content:r,actions:i,template:a})=>(e??`html`)===`browser`||Array.isArray(i)&&i.length>0?await Oc(n,r,i,t,a):kc(n,r,i,a);if(r){Cc||=(_n(e,`AI Kit Present App`,yc,{description:`Rich interactive content viewer for AI Kit tools`},async()=>({contents:[{uri:yc,mimeType:gn,text:r}]})),!0),vn(e,`present`,{title:n.title,description:i,annotations:n.annotations,inputSchema:xc,_meta:{ui:{resourceUri:yc}}},a);return}e.tool(`present`,i,xc,n.annotations,a)}async function Oc(e,t,n,r,i){let a=lc(e,t,{compactTables:!0}),o=cc(e,t,n,i),s=Sn({uri:`ui://aikit/present-browser.html`,content:{type:`rawHtml`,htmlString:o},encoding:`text`,adapters:{mcpApps:{enabled:!0}}}),c,l,u=Array.isArray(n)?n:[],d=``,f;try{wc&&=(wc.close(),null),u.length>0&&(c=new Promise(e=>{l=e}));let e=!1;d=await new Promise((t,n)=>{let r=xn((t,n)=>{if(e||(e=!0,f&&clearTimeout(f)),t.method===`POST`&&t.url===`/callback`){let e=``;t.on(`data`,t=>{e+=t.toString()}),t.on(`end`,()=>{n.writeHead(200,{"Content-Type":`application/json`,"Access-Control-Allow-Origin":`*`}),n.end(`{"ok":true}`);try{let t=JSON.parse(e);l?.(t)}catch{}});return}if(t.method===`OPTIONS`){n.writeHead(204,{"Access-Control-Allow-Origin":`*`,"Access-Control-Allow-Methods":`POST`,"Access-Control-Allow-Headers":`Content-Type`}),n.end();return}n.writeHead(200,{"Content-Type":`text/html; charset=utf-8`}),n.end(o)});r.listen(0,`127.0.0.1`,()=>{let i=r.address();if(typeof i==`object`&&i){wc=r;let n=`http://127.0.0.1:${i.port}`;f=setTimeout(()=>{if(!e)try{yn(process.platform===`win32`?`start "" "${n}"`:process.platform===`darwin`?`open "${n}"`:`xdg-open "${n}"`)}catch{}},8e3),f.unref(),t(n)}else n(Error(`Failed to start present server`))}),setTimeout(()=>{r.close(),wc===r&&(wc=null)},300*1e3).unref()})}catch{}let p=d?`${a}\n\n---\n🌐 **Dashboard opened in browser:** ${d}\n\n**IMPORTANT:** You MUST now open this URL using the \`openBrowserPage\` tool - PlayWright MCP. If that tool is unavailable, open the URL in the system browser as a fallback. If neither works, ask the user to open the URL manually.`:a;if(u.length>0&&r?.available&&c)try{let e=await Promise.race([c,new Promise((e,t)=>setTimeout(()=>t(Error(`timeout`)),300*1e3))]);return{content:[{type:`text`,text:`${p}\n\n✅ **Selected:** ${e.actionId} = \`${e.value}\``},s]}}catch{return{content:[{type:`text`,text:`${p}\n\n⚠️ *No selection received (timed out).*`},s]}}return{content:[{type:`text`,text:p},s]}}function kc(e,t,n,r){let i=Array.isArray(n)?n:[],a=lc(e,t,{compactTables:!0}),o=Sn({uri:`ui://aikit/present-static.html`,content:{type:`rawHtml`,htmlString:cc(e,t,n,r)},encoding:`text`,adapters:{mcpApps:{enabled:!0}}});return{content:[{type:`text`,text:a},o],structuredContent:{title:e,content:Zs(t),actions:i}}}const Ac=E(`tools`);function jc(e,t){let n=new fn({structure:new mn,dependencies:new ln,symbols:new hn,patterns:new pn,entryPoints:new dn,diagrams:new un}),r=L(`produce_knowledge`);e.registerTool(`produce_knowledge`,{title:r.title,description:`Run automated codebase analysis and produce synthesis instructions. Executes Tier 1 deterministic analyzers, then returns structured baselines and instructions for you to synthesize knowledge using remember.`,inputSchema:{scope:F.string().optional().describe(`Root path to analyze (defaults to workspace root)`),aspects:F.array(F.enum([`all`,`structure`,`dependencies`,`symbols`,`patterns`,`entry-points`,`diagrams`])).default([`all`]).describe(`Which analysis aspects to run`)},annotations:r.annotations},async({scope:e,aspects:r})=>{try{let i=e??`.`;Ac.info(`Running knowledge production`,{rootPath:i,aspects:r});let a=await n.runExtraction(i,r);try{let e=t?.onboardDir??g(i,`.ai`,`context`);o(e,{recursive:!0});let n=`<!-- Generated by produce_knowledge at ${new Date().toISOString()} -->\n\n`;for(let[t,r]of Object.entries(a))r&&typeof r==`string`&&f(g(e,`${t}.md`),n+r,`utf-8`);Ac.info(`Knowledge persisted to .ai/context/`,{files:Object.keys(a).length})}catch(e){Ac.warn(`Failed to persist knowledge to .ai/context/`,{error:A(e)})}return{content:[{type:`text`,text:n.buildSynthesisInstructions(a,r)+`
1230
+ BROWSER WORKFLOW: After calling present with format "browser", you MUST extract the URL from the response and call openBrowserPage({ url }) tool - PlayWright MCP to open it in VS Code Simple Browser. A system browser fallback also opens automatically, but always call openBrowserPage tool - PlayWright MCP yourself.`,a=async({format:e,title:n,content:r,actions:i,template:a})=>(e??`html`)===`browser`||Array.isArray(i)&&i.length>0?await Oc(n,r,i,t,a):kc(n,r,i,a);if(r){wc||=(_n(e,`AI Kit Present App`,bc,{description:`Rich interactive content viewer for AI Kit tools`},async()=>({contents:[{uri:bc,mimeType:gn,text:r}]})),!0),vn(e,`present`,{title:n.title,description:i,annotations:n.annotations,inputSchema:Sc,_meta:{ui:{resourceUri:bc}}},a);return}e.tool(`present`,i,Sc,n.annotations,a)}async function Oc(e,t,n,r,i){let a=uc(e,t,{compactTables:!0}),o=lc(e,t,n,i),s=Sn({uri:`ui://aikit/present-browser.html`,content:{type:`rawHtml`,htmlString:o},encoding:`text`,adapters:{mcpApps:{enabled:!0}}}),c,l,u=Array.isArray(n)?n:[],d=``,f;try{Y&&=(Y.close(),null),u.length>0&&(c=new Promise(e=>{l=e}));let e=!1;d=await new Promise((t,n)=>{let r=xn((t,n)=>{if(e||(e=!0,f&&clearTimeout(f)),t.method===`POST`&&t.url===`/callback`){let e=``;t.on(`data`,t=>{e+=t.toString()}),t.on(`end`,()=>{n.writeHead(200,{"Content-Type":`application/json`,"Access-Control-Allow-Origin":`*`}),n.end(`{"ok":true}`);try{let t=JSON.parse(e);l?.(t)}catch{}});return}if(t.method===`OPTIONS`){n.writeHead(204,{"Access-Control-Allow-Origin":`*`,"Access-Control-Allow-Methods":`POST`,"Access-Control-Allow-Headers":`Content-Type`}),n.end();return}n.writeHead(200,{"Content-Type":`text/html; charset=utf-8`}),n.end(o)});r.listen(0,`127.0.0.1`,()=>{let i=r.address();if(typeof i==`object`&&i){Y=r;let n=`http://127.0.0.1:${i.port}`;f=setTimeout(()=>{if(!e)try{yn(process.platform===`win32`?`start "" "${n}"`:process.platform===`darwin`?`open "${n}"`:`xdg-open "${n}"`)}catch{}},8e3),f.unref(),t(n)}else n(Error(`Failed to start present server`))}),setTimeout(()=>{r.close(),Y===r&&(Y=null)},300*1e3).unref()})}catch{}let p=d?`${a}\n\n---\n🌐 **Dashboard opened in browser:** ${d}\n\n**IMPORTANT:** You MUST now open this URL using the \`openBrowserPage\` tool - PlayWright MCP. If that tool is unavailable, open the URL in the system browser as a fallback. If neither works, ask the user to open the URL manually.`:a;if(u.length>0&&r?.available&&c)try{let e=await Promise.race([c,new Promise((e,t)=>setTimeout(()=>t(Error(`timeout`)),300*1e3))]);return{content:[{type:`text`,text:`${p}\n\n✅ **Selected:** ${e.actionId} = \`${e.value}\``},s]}}catch{return{content:[{type:`text`,text:`${p}\n\n⚠️ *No selection received (timed out).*`},s]}}return{content:[{type:`text`,text:p},s]}}function kc(e,t,n,r){let i=Array.isArray(n)?n:[],a=uc(e,t,{compactTables:!0}),o=Sn({uri:`ui://aikit/present-static.html`,content:{type:`rawHtml`,htmlString:lc(e,t,n,r)},encoding:`text`,adapters:{mcpApps:{enabled:!0}}});return{content:[{type:`text`,text:a},o],structuredContent:{title:e,content:Qs(t),actions:i}}}const Ac=E(`tools`);function jc(e,t){let n=new fn({structure:new mn,dependencies:new ln,symbols:new hn,patterns:new pn,entryPoints:new dn,diagrams:new un}),r=L(`produce_knowledge`);e.registerTool(`produce_knowledge`,{title:r.title,description:`Run automated codebase analysis and produce synthesis instructions. Executes Tier 1 deterministic analyzers, then returns structured baselines and instructions for you to synthesize knowledge using remember.`,inputSchema:{scope:F.string().optional().describe(`Root path to analyze (defaults to workspace root)`),aspects:F.array(F.enum([`all`,`structure`,`dependencies`,`symbols`,`patterns`,`entry-points`,`diagrams`])).default([`all`]).describe(`Which analysis aspects to run`)},annotations:r.annotations},async({scope:e,aspects:r})=>{try{let i=e??`.`;Ac.info(`Running knowledge production`,{rootPath:i,aspects:r});let a=await n.runExtraction(i,r);try{let e=t?.onboardDir??g(i,`.ai`,`context`);o(e,{recursive:!0});let n=`<!-- Generated by produce_knowledge at ${new Date().toISOString()} -->\n\n`;for(let[t,r]of Object.entries(a))r&&typeof r==`string`&&f(g(e,`${t}.md`),n+r,`utf-8`);Ac.info(`Knowledge persisted to .ai/context/`,{files:Object.keys(a).length})}catch(e){Ac.warn(`Failed to persist knowledge to .ai/context/`,{error:A(e)})}return{content:[{type:`text`,text:n.buildSynthesisInstructions(a,r)+`
1231
1231
 
1232
1232
  ---
1233
1233
  _Next: Review the baselines above and use \`remember\` to store synthesized knowledge entries._`}]}}catch(e){return Ac.error(`Knowledge production failed`,A(e)),{content:[{type:`text`,text:`Knowledge production failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}const Mc=E(`tools`);function Nc(e,t){let n=L(`read`);e.registerTool(`read`,{title:n.title,description:`Read the full content of a specific curated knowledge entry by its path. Use list first to discover available entries.`,inputSchema:{path:F.string().describe(`Relative path within .ai/curated/ (e.g., "decisions/use-lancedb.md")`)},annotations:n.annotations},async({path:e})=>{try{let n=await t.read(e),r=[`## ${n.title}`,`- **Path**: .ai/curated/${e}`,`- **Category**: ${n.category}`,n.tags.length?`- **Tags**: ${n.tags.join(`, `)}`:null,`- **Version**: ${n.version}`,`- **Created**: ${n.created}`,n.updated===n.created?null:`- **Updated**: ${n.updated}`,``].filter(e=>e!==null).join(`
1234
- `),i=Vo(e,n.title,`[${n.category}]`);return{content:[{type:`text`,text:`${r}\n${n.content}\n\n---\n_Next: Use \`update\` to modify this entry, or \`search\` to find related entries._`},...i?[i]:[]]}}catch(e){return Mc.error(`Read failed`,A(e)),{content:[{type:`text`,text:`Read failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}const X=E(`tools`);function Pc(e,t,n,r,i,a,o){let s=L(`reindex`);e.registerTool(`reindex`,{title:s.title,description:`Trigger re-indexing of the AI Kit index. Can do incremental (only changed files) or full re-index. When smart indexing is active, use force: true to override the automatic trickle indexer.`,inputSchema:{full:F.boolean().default(!1).describe(`If true, force full re-index ignoring file hashes`),force:F.boolean().default(!1).describe(`If true, override smart indexing guard and run reindex anyway`)},annotations:s.annotations},async({full:e,force:s},c)=>{try{if(t.isIndexing)return{content:[{type:`text`,text:`## Reindex Already in Progress
1234
+ `),i=Ho(e,n.title,`[${n.category}]`);return{content:[{type:`text`,text:`${r}\n${n.content}\n\n---\n_Next: Use \`update\` to modify this entry, or \`search\` to find related entries._`},...i?[i]:[]]}}catch(e){return Mc.error(`Read failed`,A(e)),{content:[{type:`text`,text:`Read failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}const X=E(`tools`);function Pc(e,t,n,r,i,a,o){let s=L(`reindex`);e.registerTool(`reindex`,{title:s.title,description:`Trigger re-indexing of the AI Kit index. Can do incremental (only changed files) or full re-index. When smart indexing is active, use force: true to override the automatic trickle indexer.`,inputSchema:{full:F.boolean().default(!1).describe(`If true, force full re-index ignoring file hashes`),force:F.boolean().default(!1).describe(`If true, override smart indexing guard and run reindex anyway`)},annotations:s.annotations},async({full:e,force:s},c)=>{try{if(t.isIndexing)return{content:[{type:`text`,text:`## Reindex Already in Progress
1235
1235
 
1236
1236
  A reindex operation is currently running. Search and other tools continue to work with existing data. Use \`status({})\` to check when it completes.`}]};if(o===`smart`&&!s)return{content:[{type:`text`,text:`## Smart Indexing Active
1237
1237
 
@@ -1242,7 +1242,7 @@ Smart indexing (trickle mode) is enabled — files are automatically indexed as
1242
1242
  Use \`status({})\` to check smart indexing queue status.`}]};let l=na(c).createTask(`Reindex`,1);l.progress(0,`Starting ${e?`full`:`incremental`} reindex`),X.info(`Starting background re-index`,{mode:e?`full`:`incremental`});let u=e=>t=>{t.phase===`chunking`&&t.currentFile&&X.debug(`Re-index progress`,{prefix:e,current:t.filesProcessed+1,total:t.filesTotal,file:t.currentFile})};return(e?t.reindexAll(n,u(`Reindex`)):t.index(n,u(`Index`))).then(async e=>{if(X.info(`Background re-index complete`,{filesProcessed:e.filesProcessed,chunksCreated:e.chunksCreated,durationMs:e.durationMs}),l.complete(`Reindex complete: ${e.filesProcessed} files, ${e.chunksCreated} chunks in ${e.durationMs}ms`),i)try{await i.createFtsIndex(),X.info(`FTS index rebuilt after reindex`)}catch(e){X.warn(`FTS index rebuild failed`,A(e))}try{let e=await r.reindexAll();X.info(`Curated re-index complete`,{indexed:e.indexed})}catch(e){X.warn(`Curated re-index failed`,A(e))}if(a)try{await a.notifyAfterReindex()}catch(e){X.warn(`Post-reindex resource notification failed`,A(e))}}).catch(e=>{l.fail(`Reindex failed: ${e instanceof Error?e.message:String(e)}`),X.error(`Background reindex failed`,A(e))}),{content:[{type:`text`,text:`## Reindex Started (Background)\n\n- **Mode**: ${e?`Full`:`Incremental`}\n- Search and other tools continue to work with existing data during reindex.\n- Completion will be logged. Use \`status({})\` to check index stats afterward.\n\n---\n_Next: Continue working — the reindex runs in the background._`}]}}catch(e){return X.error(`Reindex failed`,A(e)),{content:[{type:`text`,text:`Reindex failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}const Fc=E(`tools`);function Ic(e,t,n,r,i){let a=L(`remember`);e.registerTool(`remember`,{title:a.title,description:`Store a new piece of curated knowledge. Use this to persist decisions, patterns, conventions, or any insight worth remembering across sessions.`,inputSchema:{title:F.string().min(3).max(120).describe(`Short descriptive title for the knowledge entry`),content:F.string().min(10).max(1e5).describe(`The markdown content to store`),category:F.string().regex(/^[a-z][a-z0-9-]*$/).describe(`Category slug (e.g., "decisions", "patterns", "conventions", "api-contracts")`),tags:F.array(F.string()).default([]).describe(`Optional tags for filtering`)},annotations:a.annotations},async({title:e,content:a,category:o,tags:s})=>{try{let c=await t.remember(e,a,o,s),l=``;if(n){let t=n.classify(e,a,s);r&&r.recordClassification(e,t.matchingRules.map(e=>e.ruleId),t.pushRecommended),t.matchingRules.length>0&&(l=`\n\n### Classification Signals\n${t.matchingRules.map(e=>` - **${e.ruleId}** (${e.category}, weight: ${e.pushWeight}) — matched: ${e.matchedPatterns.join(`, `)}`).join(`
1243
1243
  `)}\n- **Push recommended**: ${t.pushRecommended?`yes`:`no`} (max weight: ${t.maxPushWeight})`,t.pushRecommended&&(l+=`
1244
1244
 
1245
- > 💡 This entry matches push rules. Consider \`er_push\` to share with Enterprise RAG.`))}i&&i.notifyAfterCuratedWrite(c.path).catch(()=>{});let u=Vo(c.path,e,`[${o}]`);return{content:[{type:`text`,text:`Remembered: **${e}**\n\nStored at \`.ai/curated/${c.path}\` and indexed for semantic search.${l}\n\n---\n_Next: Use \`search\` to verify the entry is findable, or \`list\` to see all curated entries._`},...u?[u]:[]]}}catch(e){return Fc.error(`Remember failed`,A(e)),{content:[{type:`text`,text:`Remember failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}const Lc=E(`tools`);function Rc(e){let t=L(`replay`);e.registerTool(`replay`,{title:t.title,description:`View or clear the audit trail of recent MCP tool and CLI invocations. Shows tool name, duration, status, and input/output summaries.`,inputSchema:{action:F.enum([`list`,`clear`]).default(`list`).describe(`Action: "list" (default) to view entries, "clear" to wipe the log`),last:F.number().optional().describe(`Number of entries to return (default: 20, list only)`),tool:F.string().optional().describe(`Filter by tool name (list only)`),source:F.enum([`mcp`,`cli`]).optional().describe(`Filter by source: "mcp" or "cli" (list only)`),since:F.string().optional().describe(`ISO timestamp — only show entries after this time (list only)`)},annotations:t.annotations},async({action:e,last:t,tool:n,source:r,since:i})=>{try{if(e===`clear`)return kt(),{content:[{type:`text`,text:`Replay log cleared.`}]};let a=At({last:t,tool:n,source:r,since:i});if(a.length===0)return{content:[{type:`text`,text:`No replay entries found. Activity is logged when tools are invoked via MCP or CLI.`}]};let o=a.map(e=>`${e.ts.split(`T`)[1]?.split(`.`)[0]??e.ts} ${e.status===`ok`?`✓`:`✗`} ${e.tool} (${e.durationMs}ms) [${e.source}]\n in: ${e.input}\n out: ${e.output}`);return jt().catch(()=>{}),{content:[{type:`text`,text:`**Replay Log** (${a.length} entries)\n\n${o.join(`
1245
+ > 💡 This entry matches push rules. Consider \`er_push\` to share with Enterprise RAG.`))}i&&i.notifyAfterCuratedWrite(c.path).catch(()=>{});let u=Ho(c.path,e,`[${o}]`);return{content:[{type:`text`,text:`Remembered: **${e}**\n\nStored at \`.ai/curated/${c.path}\` and indexed for semantic search.${l}\n\n---\n_Next: Use \`search\` to verify the entry is findable, or \`list\` to see all curated entries._`},...u?[u]:[]]}}catch(e){return Fc.error(`Remember failed`,A(e)),{content:[{type:`text`,text:`Remember failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}const Lc=E(`tools`);function Rc(e){let t=L(`replay`);e.registerTool(`replay`,{title:t.title,description:`View or clear the audit trail of recent MCP tool and CLI invocations. Shows tool name, duration, status, and input/output summaries.`,inputSchema:{action:F.enum([`list`,`clear`]).default(`list`).describe(`Action: "list" (default) to view entries, "clear" to wipe the log`),last:F.number().optional().describe(`Number of entries to return (default: 20, list only)`),tool:F.string().optional().describe(`Filter by tool name (list only)`),source:F.enum([`mcp`,`cli`]).optional().describe(`Filter by source: "mcp" or "cli" (list only)`),since:F.string().optional().describe(`ISO timestamp — only show entries after this time (list only)`)},annotations:t.annotations},async({action:e,last:t,tool:n,source:r,since:i})=>{try{if(e===`clear`)return kt(),{content:[{type:`text`,text:`Replay log cleared.`}]};let a=At({last:t,tool:n,source:r,since:i});if(a.length===0)return{content:[{type:`text`,text:`No replay entries found. Activity is logged when tools are invoked via MCP or CLI.`}]};let o=a.map(e=>`${e.ts.split(`T`)[1]?.split(`.`)[0]??e.ts} ${e.status===`ok`?`✓`:`✗`} ${e.tool} (${e.durationMs}ms) [${e.source}]\n in: ${e.input}\n out: ${e.output}`);return jt().catch(()=>{}),{content:[{type:`text`,text:`**Replay Log** (${a.length} entries)\n\n${o.join(`
1246
1246
 
1247
1247
  `)}`}]}}catch(e){return Lc.error(`Replay failed`,A(e)),{content:[{type:`text`,text:`Replay failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}const zc=E(`tools`);function Bc(e){let t=L(`restore`);e.registerTool(`restore`,{title:t.title,description:`List and restore file snapshots taken before destructive operations (codemod, rename, forget). Use action=list to see available restore points, action=restore with an id to undo.`,inputSchema:{action:F.enum([`list`,`restore`]).describe(`list: show restore points, restore: apply a restore point`),id:F.string().optional().describe(`Restore point ID (required for action=restore)`),limit:F.number().min(1).max(50).default(10).describe(`Max restore points to list`)},annotations:t.annotations},async({action:e,id:t,limit:n})=>{try{if(e===`list`){let e=ot().slice(0,n);return e.length===0?{content:[{type:`text`,text:`No restore points found.`}]}:{content:[{type:`text`,text:`## Restore Points\n\n${e.map(e=>`- **${e.id}** (${e.timestamp}) — ${e.operation}: ${e.description} (${e.files.length} files)`).join(`
1248
1248
  `)}`}]}}if(!t)throw Error(`id is required for restore action`);let r=await Mt(t);return{content:[{type:`text`,text:`Restored ${r.length} files:\n${r.map(e=>`- \`${e}\``).join(`
@@ -1255,7 +1255,7 @@ Use \`status({})\` to check smart indexing queue status.`}]};let l=na(c).createT
1255
1255
 
1256
1256
  ---
1257
1257
 
1258
- `),j=(c===`hybrid`?`hybrid (vector + keyword RRF)`:c===`keyword`?`keyword (FTS)`:`semantic (vector)`)+E,M=Yc(b,e),te=M.length>0?`\n_Distinctive terms: ${M.map(e=>`\`${e}\``).join(`, `)}_`:``,ne=await Zc(n,b),N=[];if(b.length===0)N.push("`reindex` — no results found, index may be stale"),N.push("`find` — try federated search with glob/regex");else{let e=b[0]?.record.sourcePath;e&&N.push(`\`lookup\` — see all chunks from \`${e}\``),N.push("`symbol` — resolve a specific symbol from the results"),N.push("`compact` — compress a result file for focused reading")}let re=[O?`${O}\n\n`:``,ne?`${ne}\n\n`:``,ee,`\n\n---\n_Search mode: ${j} | ${b.length} results_${te}`,`\n_Next: ${N.join(` | `)}_`],ie=C+re.join(``);g&&(ie=Xt(ie,g));let ae=new Set,oe=[];for(let e of b){if(e.record.origin!==`curated`||e.record.sourcePath.startsWith(`[`))continue;let t=Uo(e.record.sourcePath);if(!t)continue;let n=Vo(t,e.record.headingPath??t);n&&!ae.has(n.uri)&&(ae.add(n.uri),oe.push(n))}return{content:[{type:`text`,text:ie},...oe],structuredContent:{results:b.map(e=>({sourcePath:e.record.sourcePath,contentType:e.record.contentType,score:e.score,...e.record.headingPath?{headingPath:e.record.headingPath}:{},...e.record.startLine?{startLine:e.record.startLine}:{},...e.record.endLine?{endLine:e.record.endLine}:{},...e.record.origin===`indexed`?{}:{origin:e.record.origin},...e.record.category?{category:e.record.category}:{},...e.record.tags?.length?{tags:e.record.tags}:{}})),totalResults:b.length,searchMode:c,query:e}}}catch(e){return Wc.error(`Search failed`,A(e)),{content:[{type:`text`,text:`Search failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}const $c=E(`tools`);function el(e,t){let n=L(`session_digest`);e.registerTool(`session_digest`,{title:n.title,description:`Compress the current session's tool trajectory into a focused digest. Aggregates replay log, stash state, and checkpoints. Supports deterministic and LLM-assisted (sampling) modes with configurable token budget.`,inputSchema:{scope:F.enum([`tools`,`stash`,`all`]).default(`all`).describe(`What to include: tools (replay only), stash (stash + checkpoints only), or all`),since:F.string().optional().describe(`ISO timestamp — only include activity after this time`),last:F.number().min(1).max(500).optional().describe(`Max replay entries to consider (default: 50)`),focus:F.string().optional().describe(`Focus query — prioritize entries matching this topic`),mode:F.enum([`deterministic`,`sampling`]).default(`deterministic`).describe(`Summary mode: deterministic (fast, template-based) or sampling (LLM-assisted, richer)`),token_budget:F.number().min(100).max(8e3).default(2e3).describe(`Target token budget for the digest output`),persist:F.boolean().default(!0).describe(`Auto-save digest to stash for crash recovery`)},annotations:n.annotations},async({scope:e,since:n,last:r,focus:i,mode:a,token_budget:o,persist:s})=>{try{let c={scope:e,since:n,last:r,focus:i,mode:a,tokenBudget:o,persist:s};return{content:[{type:`text`,text:(a===`sampling`&&t?.available?await Lt(c,async(e,n,r)=>(await t.createMessage({prompt:e,systemPrompt:n,maxTokens:r})).text):It(c)).digest}]}}catch(e){return $c.error(`Session digest failed`,A(e)),{content:[{type:`text`,text:`Session digest failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}const tl=E(`tools`);function nl(e,t,n,r=15e3){let i,a=new Promise(e=>{i=setTimeout(()=>{tl.warn(`Status sub-operation "${n}" timed out after ${r}ms`),e({value:t,timedOut:!0})},r)});return Promise.race([e.then(e=>(clearTimeout(i),{value:e,timedOut:!1}),e=>(clearTimeout(i),tl.warn(`Status sub-operation "${n}" failed: ${e instanceof Error?e.message:String(e)}`),{value:t,timedOut:!1})),a])}const rl=5*6e4;let il=null,al=null;function ol(e,t,n,r){let i=Math.min(e/2e4,1),a=Math.min((t+n)/5e4,1),o=Math.min(r/200,1);return Math.round(i*40+a*35+o*25)}function sl(){let e=Date.now();if(il&&e-il.ts<rl)return il.value;try{let t=_(N(),`.copilot`,`.aikit-scaffold.json`);if(!a(t))return il={value:null,ts:e},null;let n=JSON.parse(s(t,`utf-8`)).version??null;return il={value:n,ts:e},n}catch{return il={value:null,ts:e},null}}function cl(){let e=Date.now();if(al&&e-al.ts<rl)return al.value;try{let t=_(process.cwd(),`.github`,`.aikit-scaffold.json`);if(!a(t))return al={value:null,ts:e},null;let n=JSON.parse(s(t,`utf-8`)).version??null;return al={value:n,ts:e},n}catch{return al={value:null,ts:e},null}}function ll(e){let t=L(`status`);e.registerTool(`status`,{title:t.title,description:`Get the current status and statistics of the AI Kit index.`,outputSchema:fi,annotations:t.annotations},async()=>{let e=r(),t=sl(),a=cl(),o=t!=null&&t!==e,s=a!=null&&a!==e,c=[`## AI Kit Status`,``,`⏳ **AI Kit is initializing** — index stats will be available shortly.`,``,`### Runtime`,`- **Tree-sitter (WASM)**: ${re.get()?`✅ Available (AST analysis)`:`⚠ Unavailable (regex fallback)`}`,``,`### Version`,`- **Server**: ${e}`,`- **Scaffold (user)**: ${t??`not installed`}`,`- **Scaffold (workspace)**: ${a??`not installed`}`];if(o||s){let r=i(),l=[];o&&l.push(`user scaffold v${t}`),s&&l.push(`workspace scaffold v${a}`);let u=l.join(`, `);r.state===`success`?c.push(``,`### ✅ Upgrade Applied`,`- Server v${e} — ${u} auto-upgraded successfully.`,`- _Restart the MCP server to use the updated version._`):r.state===`pending`?c.push(``,`### ⏳ Upgrade In Progress`,`- Server v${e} ≠ ${u}`,`- Auto-upgrade is running in the background…`):r.state===`failed`?(n(),c.push(``,`### ⬆ Upgrade Available (auto-upgrade failed, retrying)`,`- Server v${e} ≠ ${u}`,`- Error: ${r.error??`unknown`}`)):(n(),c.push(``,`### ⬆ Upgrade Available`,`- Server v${e} ≠ ${u}`,`- Auto-upgrade triggered — check again shortly.`))}let l={totalRecords:0,totalFiles:0,lastIndexedAt:null,onboarded:!1,onboardDir:``,contentTypes:{},wasmAvailable:!!re.get(),graphStats:null,curatedCount:0,serverVersion:e,scaffoldVersion:t??null,workspaceScaffoldVersion:a??null,upgradeAvailable:o||s,contextPressure:0};return{content:[{type:`text`,text:c.join(`
1258
+ `),j=(c===`hybrid`?`hybrid (vector + keyword RRF)`:c===`keyword`?`keyword (FTS)`:`semantic (vector)`)+E,M=Yc(b,e),te=M.length>0?`\n_Distinctive terms: ${M.map(e=>`\`${e}\``).join(`, `)}_`:``,ne=await Zc(n,b),N=[];if(b.length===0)N.push("`reindex` — no results found, index may be stale"),N.push("`find` — try federated search with glob/regex");else{let e=b[0]?.record.sourcePath;e&&N.push(`\`lookup\` — see all chunks from \`${e}\``),N.push("`symbol` — resolve a specific symbol from the results"),N.push("`compact` — compress a result file for focused reading")}let re=[O?`${O}\n\n`:``,ne?`${ne}\n\n`:``,ee,`\n\n---\n_Search mode: ${j} | ${b.length} results_${te}`,`\n_Next: ${N.join(` | `)}_`],ie=C+re.join(``);g&&(ie=Xt(ie,g));let ae=new Set,oe=[];for(let e of b){if(e.record.origin!==`curated`||e.record.sourcePath.startsWith(`[`))continue;let t=Wo(e.record.sourcePath);if(!t)continue;let n=Ho(t,e.record.headingPath??t);n&&!ae.has(n.uri)&&(ae.add(n.uri),oe.push(n))}return{content:[{type:`text`,text:ie},...oe],structuredContent:{results:b.map(e=>({sourcePath:e.record.sourcePath,contentType:e.record.contentType,score:e.score,...e.record.headingPath?{headingPath:e.record.headingPath}:{},...e.record.startLine?{startLine:e.record.startLine}:{},...e.record.endLine?{endLine:e.record.endLine}:{},...e.record.origin===`indexed`?{}:{origin:e.record.origin},...e.record.category?{category:e.record.category}:{},...e.record.tags?.length?{tags:e.record.tags}:{}})),totalResults:b.length,searchMode:c,query:e}}}catch(e){return Wc.error(`Search failed`,A(e)),{content:[{type:`text`,text:`Search failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}const $c=E(`tools`);function el(e,t){let n=L(`session_digest`);e.registerTool(`session_digest`,{title:n.title,description:`Compress the current session's tool trajectory into a focused digest. Aggregates replay log, stash state, and checkpoints. Supports deterministic and LLM-assisted (sampling) modes with configurable token budget.`,inputSchema:{scope:F.enum([`tools`,`stash`,`all`]).default(`all`).describe(`What to include: tools (replay only), stash (stash + checkpoints only), or all`),since:F.string().optional().describe(`ISO timestamp — only include activity after this time`),last:F.number().min(1).max(500).optional().describe(`Max replay entries to consider (default: 50)`),focus:F.string().optional().describe(`Focus query — prioritize entries matching this topic`),mode:F.enum([`deterministic`,`sampling`]).default(`deterministic`).describe(`Summary mode: deterministic (fast, template-based) or sampling (LLM-assisted, richer)`),token_budget:F.number().min(100).max(8e3).default(2e3).describe(`Target token budget for the digest output`),persist:F.boolean().default(!0).describe(`Auto-save digest to stash for crash recovery`)},annotations:n.annotations},async({scope:e,since:n,last:r,focus:i,mode:a,token_budget:o,persist:s})=>{try{let c={scope:e,since:n,last:r,focus:i,mode:a,tokenBudget:o,persist:s};return{content:[{type:`text`,text:(a===`sampling`&&t?.available?await Lt(c,async(e,n,r)=>(await t.createMessage({prompt:e,systemPrompt:n,maxTokens:r})).text):It(c)).digest}]}}catch(e){return $c.error(`Session digest failed`,A(e)),{content:[{type:`text`,text:`Session digest failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}const tl=E(`tools`);function nl(e,t,n,r=15e3){let i,a=new Promise(e=>{i=setTimeout(()=>{tl.warn(`Status sub-operation "${n}" timed out after ${r}ms`),e({value:t,timedOut:!0})},r)});return Promise.race([e.then(e=>(clearTimeout(i),{value:e,timedOut:!1}),e=>(clearTimeout(i),tl.warn(`Status sub-operation "${n}" failed: ${e instanceof Error?e.message:String(e)}`),{value:t,timedOut:!1})),a])}const rl=5*6e4;let il=null,al=null;function ol(e,t,n,r){let i=Math.min(e/2e4,1),a=Math.min((t+n)/5e4,1),o=Math.min(r/200,1);return Math.round(i*40+a*35+o*25)}function sl(){let e=Date.now();if(il&&e-il.ts<rl)return il.value;try{let t=_(N(),`.copilot`,`.aikit-scaffold.json`);if(!a(t))return il={value:null,ts:e},null;let n=JSON.parse(s(t,`utf-8`)).version??null;return il={value:n,ts:e},n}catch{return il={value:null,ts:e},null}}function cl(){let e=Date.now();if(al&&e-al.ts<rl)return al.value;try{let t=_(process.cwd(),`.github`,`.aikit-scaffold.json`);if(!a(t))return al={value:null,ts:e},null;let n=JSON.parse(s(t,`utf-8`)).version??null;return al={value:n,ts:e},n}catch{return al={value:null,ts:e},null}}function ll(e){let t=L(`status`);e.registerTool(`status`,{title:t.title,description:`Get the current status and statistics of the AI Kit index.`,outputSchema:fi,annotations:t.annotations},async()=>{let e=r(),t=sl(),a=cl(),o=t!=null&&t!==e,s=a!=null&&a!==e,c=[`## AI Kit Status`,``,`⏳ **AI Kit is initializing** — index stats will be available shortly.`,``,`### Runtime`,`- **Tree-sitter (WASM)**: ${re.get()?`✅ Available (AST analysis)`:`⚠ Unavailable (regex fallback)`}`,``,`### Version`,`- **Server**: ${e}`,`- **Scaffold (user)**: ${t??`not installed`}`,`- **Scaffold (workspace)**: ${a??`not installed`}`];if(o||s){let r=i(),l=[];o&&l.push(`user scaffold v${t}`),s&&l.push(`workspace scaffold v${a}`);let u=l.join(`, `);r.state===`success`?c.push(``,`### ✅ Upgrade Applied`,`- Server v${e} — ${u} auto-upgraded successfully.`,`- _Restart the MCP server to use the updated version._`):r.state===`pending`?c.push(``,`### ⏳ Upgrade In Progress`,`- Server v${e} ≠ ${u}`,`- Auto-upgrade is running in the background…`):r.state===`failed`?(n(),c.push(``,`### ⬆ Upgrade Available (auto-upgrade failed, retrying)`,`- Server v${e} ≠ ${u}`,`- Error: ${r.error??`unknown`}`)):(n(),c.push(``,`### ⬆ Upgrade Available`,`- Server v${e} ≠ ${u}`,`- Auto-upgrade triggered — check again shortly.`))}let l={totalRecords:0,totalFiles:0,lastIndexedAt:null,onboarded:!1,onboardDir:``,contentTypes:{},wasmAvailable:!!re.get(),graphStats:null,curatedCount:0,serverVersion:e,scaffoldVersion:t??null,workspaceScaffoldVersion:a??null,upgradeAvailable:o||s,contextPressure:0};return{content:[{type:`text`,text:c.join(`
1259
1259
  `)}],structuredContent:l}})}function ul(e,t,o,s,c,l,u,f){let p=L(`status`);e.registerTool(`status`,{title:p.title,description:`Get the current status and statistics of the AI Kit index.`,outputSchema:fi,annotations:p.annotations},async()=>{let e=[];try{let[p,m]=await Promise.all([nl(t.getStats(),{totalRecords:0,totalFiles:0,lastIndexedAt:null,contentTypeBreakdown:{}},`store.getStats`),nl(t.listSourcePaths(),[],`store.listSourcePaths`)]),h=p.value;p.timedOut&&e.push(`⚠ Index stats timed out — values may be incomplete`);let g=m.value;m.timedOut&&e.push(`⚠ File listing timed out`);let v=null,b=0,x=[`## AI Kit Status`,``,`- **Total Records**: ${h.totalRecords}`,`- **Total Files**: ${h.totalFiles}`,`- **Last Indexed**: ${h.lastIndexedAt??`Never`}`,``,`### Content Types`,...Object.entries(h.contentTypeBreakdown).map(([e,t])=>`- ${e}: ${t}`),``,`### Indexed Files`,...g.slice(0,50).map(e=>`- ${e}`),g.length>50?`\n... and ${g.length-50} more files`:``];if(o)try{let t=await nl(o.getStats(),{nodeCount:0,edgeCount:0,nodeTypes:{},edgeTypes:{}},`graphStore.getStats`);if(t.timedOut)e.push(`⚠ Graph stats timed out`),x.push(``,`### Knowledge Graph`,`- Graph stats timed out`);else{let e=t.value;v={nodes:e.nodeCount,edges:e.edgeCount},x.push(``,`### Knowledge Graph`,`- **Nodes**: ${e.nodeCount}`,`- **Edges**: ${e.edgeCount}`,...Object.entries(e.nodeTypes).map(([e,t])=>` - ${e}: ${t}`));try{let e=await nl(o.validate(),{valid:!0,danglingEdges:[],orphanNodes:[],stats:{nodeCount:0,edgeCount:0,nodeTypes:{},edgeTypes:{}}},`graphStore.validate`);if(!e.timedOut){let t=e.value;t.valid||x.push(`- **⚠ Integrity Issues**: ${t.danglingEdges.length} dangling edges`),t.orphanNodes.length>0&&x.push(`- **Orphan nodes**: ${t.orphanNodes.length}`)}}catch{}}}catch{x.push(``,`### Knowledge Graph`,`- Graph store unavailable`)}let S=l?.onboardDir??_(process.cwd(),y.aiContext),C=a(S),w=c?.onboardComplete||C;if(x.push(``,`### Onboard Status`,w?`- ✅ Complete${c?.onboardTimestamp?` (last: ${c.onboardTimestamp})`:``}`:'- ❌ Not run — call `onboard({ path: "." })` to analyze the codebase',`- **Onboard Directory**: \`${S}\``),s)try{let t=await nl(s.list(),[],`curated.list`);if(t.timedOut)e.push(`⚠ Curated knowledge listing timed out`),x.push(``,`### Curated Knowledge`,`- Listing timed out`);else{let e=t.value;b=e.length,x.push(``,`### Curated Knowledge`,e.length>0?`- ${e.length} entries`:"- Empty — use `remember()` to persist decisions")}}catch{x.push(``,`### Curated Knowledge`,`- Unable to read curated entries`)}let T=ol(h.totalRecords,v?.nodes??0,v?.edges??0,b);x.push(``),x.push(`## 📊 Context Pressure: ${T}/100`),T>=80?x.push(`⚠️ High pressure — consider pruning stale entries or compacting context.`):T>=50?x.push(`ℹ️ Moderate pressure — knowledge base is well-populated.`):x.push(`✅ Low pressure — plenty of headroom for more content.`);let E=0;if(h.lastIndexedAt){E=new Date(h.lastIndexedAt).getTime();let e=(Date.now()-E)/(1e3*60*60);x.push(``,`### Index Freshness`,e>24?u===`smart`?`- ⚠ Last indexed ${Math.floor(e)}h ago — smart indexing will refresh automatically`:`- ⚠ Last indexed ${Math.floor(e)}h ago — may be stale. Run \`reindex({})\``:`- ✅ Last indexed ${e<1?`less than 1h`:`${Math.floor(e)}h`} ago`)}if(u===`smart`)if(x.push(``,`### Smart Indexing`),f){let e=f();e?x.push(`- **Mode**: Smart (trickle)`,`- **Status**: ${e.running?`✅ Running`:`⏸ Stopped`}`,`- **Queue**: ${e.queueSize} files pending`,`- **Changed files**: ${e.changedFilesSize} detected`,`- **Interval**: ${Math.round(e.intervalMs/1e3)}s per batch of ${e.batchSize}`):x.push(`- **Mode**: Smart (trickle)`,`- **Status**: scheduler state unavailable (init may have failed)`)}else x.push(`- **Mode**: Smart (trickle) — scheduler state unavailable`);{try{let e=_(process.cwd(),y.data,`stash`);if(a(e)){let t=d(e).mtimeMs;t>E&&(E=t)}}catch{}let e=[];if(s)try{let t=b>0?await s.list():[];for(let e of t){let t=new Date(e.updated||e.created).getTime();t>E&&(E=t)}e.push(...t.sort((e,t)=>new Date(t.updated).getTime()-new Date(e.updated).getTime()).slice(0,5))}catch{}let t=E>0?Date.now()-E:0;if(t>=144e5){let n=Math.floor(t/36e5);if(x.push(``,`### 🌅 Session Briefing`,`_${n}+ hours since last activity — here's what to pick up:_`,``),e.length>0){x.push(`**Recent decisions/notes:**`);for(let t of e)x.push(`- **${t.title}** (${t.category??`note`}) — ${(t.contentPreview??``).slice(0,80)}…`)}x.push(``,`**Suggested next steps:**`,'- `search({ query: "SESSION CHECKPOINT", origin: "curated" })` — find your last checkpoint',"- `restore({})` — resume from a saved checkpoint","- `list()` — browse all stored knowledge")}}x.push(``,`### Runtime`,`- **Tree-sitter (WASM)**: ${re.get()?`✅ Available (AST analysis)`:`⚠ Unavailable (regex fallback)`}`);let D=sl(),O=cl(),k=r(),ee=D!=null&&D!==k,A=O!=null&&O!==k;if(ee||A){let e=i(),t=[];ee&&t.push(`user scaffold v${D}`),A&&t.push(`workspace scaffold v${O}`);let r=t.join(`, `);e.state===`success`?x.push(``,`### ✅ Upgrade Applied`,`- Server v${k} — ${r} auto-upgraded successfully.`,`- _Restart the MCP server to use the updated version._`):e.state===`pending`?x.push(``,`### ⏳ Upgrade In Progress`,`- Server v${k} ≠ ${r}`,`- Auto-upgrade is running in the background…`):e.state===`failed`?(n(),x.push(``,`### ⬆ Upgrade Available (auto-upgrade failed, retrying)`,`- Server v${k} ≠ ${r}`,`- Error: ${e.error??`unknown`}`)):(n(),x.push(``,`### ⬆ Upgrade Available`,`- Server v${k} ≠ ${r}`,`- Auto-upgrade triggered — check again shortly.`))}e.length>0&&x.push(``,`### ⚠ Warnings`,...e.map(e=>`- ${e}`));let j=Br();if(j.length>0){let e=j.sort((e,t)=>t.callCount-e.callCount);x.push(``,`### Tool Usage This Session`,``),x.push(`| Tool | Calls | Tokens In | Tokens Out | Errors | Avg Latency |`),x.push(`|------|-------|-----------|------------|--------|-------------|`);for(let t of e.slice(0,15)){let e=Math.round(t.totalInputChars/4),n=Math.round(t.totalOutputChars/4),r=Math.round(t.totalDurationMs/t.callCount);x.push(`| ${t.tool} | ${t.callCount} | ${e.toLocaleString()} | ${n.toLocaleString()} | ${t.errorCount} | ${r}ms |`)}}let M=Nr();if(M.bufferSize>=10){let e=M.state===`healthy`?`🟢`:M.state===`degraded`?`🔴`:`🟡`;x.push(``,`### Auto-GC: ${e} ${M.state}`),x.push(`- p95 latency: ${M.p95}ms | buffer: ${M.bufferSize} samples`),M.gcCount>0&&x.push(`- GC cycles triggered: ${M.gcCount}`)}let te=x.join(`
1260
1260
  `),ne={totalRecords:h.totalRecords,totalFiles:h.totalFiles,lastIndexedAt:h.lastIndexedAt??null,onboarded:w,onboardDir:S,contentTypes:h.contentTypeBreakdown,wasmAvailable:!!re.get(),graphStats:v,curatedCount:b,serverVersion:k,scaffoldVersion:D??null,workspaceScaffoldVersion:O??null,upgradeAvailable:ee||A,contextPressure:T};return{content:[{type:`text`,text:te+(u===`smart`?"\n\n---\n_Next: Use `search` to query indexed content or `graph({action:'find_nodes', name_pattern:'<top-level-module>'})` → then `graph({action:'neighbors', node_id})` for relationships. Smart indexing handles updates automatically._":"\n\n---\n_Next: Use `search` to query indexed content, `graph({action:'find_nodes', name_pattern:'<top-level-module>'})` → then `graph({action:'neighbors', node_id})` for relationships, or `reindex` to refresh the index._")}],structuredContent:ne}}catch(e){return tl.error(`Status failed`,A(e)),{content:[{type:`text`,text:`Status check failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}const dl=E(`tools`);function fl(e,t,n){let r=L(`update`);e.registerTool(`update`,{title:r.title,description:`Update an existing curated knowledge entry. Increments version and records the reason in the changelog.`,inputSchema:{path:F.string().describe(`Relative path within .ai/curated/ (e.g., "decisions/use-lancedb.md")`),content:F.string().min(10).max(1e5).describe(`New markdown content to replace existing content`),reason:F.string().min(3).max(1e3).describe(`Why this update is being made (recorded in changelog)`)},annotations:r.annotations},async({path:e,content:r,reason:i})=>{try{let a=await t.update(e,r,i);return n&&n.notifyAfterCuratedWrite(e).catch(()=>{}),{content:[{type:`text`,text:`Updated: \`.ai/curated/${a.path}\` → version ${a.version}\n\nReason: ${i}\n\n---\n_Next: Use \`read\` to verify the updated content, or \`search\` to test searchability._`}]}}catch(e){return dl.error(`Update failed`,A(e)),{content:[{type:`text`,text:`Update failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}const Z=E(`tools`);function pl(e){let t=L(`web_search`);e.registerTool(`web_search`,{title:t.title,description:`PREFERRED web search — search the web via DuckDuckGo (no API key). Pass one query or multiple for parallel searching. Returns structured results with title, URL, and snippet.`,inputSchema:{queries:F.array(F.string().max(2e3)).min(1).max(5).describe('Search queries (1–5). Single: `["react hooks"]`. Multiple searched in parallel.'),limit:F.number().min(1).max(20).default(5).describe(`Max results per query`),site:F.string().optional().describe(`Restrict to domain (e.g., "docs.aws.amazon.com")`)},annotations:t.annotations},async({queries:e,limit:t,site:n})=>{let r=e,i=async e=>{let r=await tn({query:e,limit:t,site:n}),i=[`## Search: ${r.query}`,``];if(r.results.length===0)i.push(`No results found.`);else for(let e of r.results)i.push(`### [${e.title}](${e.url})`,e.snippet,``);return i.join(`
1261
1261
  `)};if(r.length===1)try{return{content:[{type:`text`,text:`${await i(r[0])}\n---\n_Next: Use \`web_fetch\` to read any of these pages in full._`}]}}catch(e){return Z.error(`Web search failed`,A(e)),{content:[{type:`text`,text:`Web search failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}let a=await Promise.allSettled(r.map(e=>i(e))),o=[],s=0;for(let e=0;e<a.length;e++){let t=a[e];if(t.status===`fulfilled`)o.push(t.value);else{s++;let n=t.reason instanceof Error?t.reason.message:String(t.reason);Z.error(`Web search failed`,{query:r[e],error:n}),o.push(`## ❌ Search failed: ${r[e]}\n\n${n}`)}}let c=`_Searched ${a.length-s}/${a.length} queries successfully._`;return o.push(``,`---`,c,"_Next: Use `web_fetch` to read any of these pages in full._"),{content:[{type:`text`,text:o.join(`
@@ -1269,6 +1269,6 @@ Data matches the schema.`}]};let r=[`## Validation: FAILED`,``,`**${n.errors.len
1269
1269
  `)}]}}catch(e){return Z.error(`Schema validation failed`,A(e)),{content:[{type:`text`,text:`Schema validation failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function bl(e){let t=L(`snippet`);e.registerTool(`snippet`,{title:t.title,description:`Save, retrieve, search, and manage persistent code snippets/templates.`,inputSchema:{action:F.enum([`save`,`get`,`list`,`search`,`delete`]).describe(`Operation to perform`),name:F.string().optional().describe(`Snippet name (required for save/get/delete)`),language:F.string().optional().describe(`Language tag (for save)`),code:F.string().max(1e5).optional().describe(`Code content (for save)`),tags:F.array(F.string()).optional().describe(`Tags for categorization (for save)`),query:F.string().optional().describe(`Search query (for search)`)},annotations:t.annotations},async({action:e,name:t,language:n,code:r,tags:i,query:a})=>{try{let o=Rt({action:e,name:t,language:n,code:r,tags:i,query:a});if(`deleted`in o)return{content:[{type:`text`,text:o.deleted?`Snippet "${t}" deleted.`:`Snippet "${t}" not found.`}]};if(`snippets`in o){if(o.snippets.length===0)return{content:[{type:`text`,text:`No snippets found.`}]};let e=[`## Snippets`,``];for(let t of o.snippets){let n=t.tags.length>0?` [${t.tags.join(`, `)}]`:``;e.push(`- **${t.name}** (${t.language})${n}`)}return{content:[{type:`text`,text:e.join(`
1270
1270
  `)}]}}let s=o,c=s.tags.length>0?`\nTags: ${s.tags.join(`, `)}`:``;return{content:[{type:`text`,text:`## ${s.name} (${s.language})${c}\n\n\`\`\`${s.language}\n${s.code}\n\`\`\``}]}}catch(e){return Z.error(`Snippet failed`,A(e)),{content:[{type:`text`,text:`Snippet failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function xl(e){let t=L(`env`);e.registerTool(`env`,{title:t.title,description:`Get system and runtime environment info. Sensitive env vars are redacted by default.`,outputSchema:gi,inputSchema:{include_env:F.boolean().default(!1).describe(`Include environment variables`),filter_env:F.string().optional().describe(`Filter env vars by name substring`),show_sensitive:F.boolean().default(!1).describe(`Show sensitive values (keys, tokens, etc.) — redacted by default`)},annotations:t.annotations},async({include_env:e,filter_env:t,show_sensitive:n})=>{let r=Re({includeEnv:e,filterEnv:t,showSensitive:n}),i=[`## Environment`,``,`**Platform:** ${r.system.platform} ${r.system.arch}`,`**OS:** ${r.system.type} ${r.system.release}`,`**Host:** ${r.system.hostname}`,`**CPUs:** ${r.system.cpus}`,`**Memory:** ${r.system.memoryFreeGb}GB free / ${r.system.memoryTotalGb}GB total`,``,`**Node:** ${r.runtime.node}`,`**V8:** ${r.runtime.v8}`,`**CWD:** ${r.cwd}`];if(r.env){i.push(``,`### Environment Variables`,``);for(let[e,t]of Object.entries(r.env))i.push(`- \`${e}\`: ${t}`)}let a={platform:r.system.platform,arch:r.system.arch,nodeVersion:r.runtime.node,cwd:r.cwd,cpus:r.system.cpus,memoryFreeGb:r.system.memoryFreeGb,memoryTotalGb:r.system.memoryTotalGb};return{content:[{type:`text`,text:i.join(`
1271
1271
  `)}],structuredContent:a}})}function Sl(e){let t=L(`time`);e.registerTool(`time`,{title:t.title,description:`Parse dates, convert timezones, calculate durations, add time. Supports ISO 8601, unix timestamps, and human-readable formats.`,outputSchema:_i,inputSchema:{operation:F.enum([`now`,`parse`,`convert`,`diff`,`add`]).describe(`now: current time | parse: parse a date string | convert: timezone conversion | diff: duration between two dates | add: add duration to date`),input:F.string().optional().describe(`Date input (ISO, unix timestamp, or parseable string). For diff: two comma-separated dates`),timezone:F.string().optional().describe(`Target timezone (e.g., "America/New_York", "Asia/Tokyo")`),duration:F.string().optional().describe(`Duration to add (e.g., "2h30m", "1d", "30s") — for add operation`)},annotations:t.annotations},async({operation:e,input:t,timezone:n,duration:r})=>{try{let i=Jt({operation:e,input:t,timezone:n,duration:r}),a=[`**${i.output}**`,``,`ISO: ${i.iso}`,`Unix: ${i.unix}`];i.details&&a.push(``,"```json",JSON.stringify(i.details),"```");let o={iso:i.iso,unix:i.unix,timezone:n??Intl.DateTimeFormat().resolvedOptions().timeZone,formatted:i.output};return{content:[{type:`text`,text:a.join(`
1272
- `)}],structuredContent:o}}catch(e){return Z.error(`Time failed`,A(e)),{content:[{type:`text`,text:`Time failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}const Q=E(`server`);function Cl(e){let t=e.toLowerCase();return[`protobuf`,`invalid model`,`invalid onnx`,`unexpected end`,`unexpected token`,`failed to load`,`failed to initialize embedding`,`checksum`,`corrupt`,`malformed`,`could not load`,`onnx`,`database disk image is malformed`,`file is not a database`,`lance`].some(e=>t.includes(e))}async function wl(e,t){let n=t.toLowerCase(),r;try{({rm:r}=await import(`node:fs/promises`))}catch{return}if(n.includes(`embedding`)||n.includes(`onnx`)||n.includes(`protobuf`)||n.includes(`model`)){let t=e.embedding?.model??x.model,n=g(N(),`.cache`,`huggingface`,`transformers-js`,t);try{await r(n,{recursive:!0,force:!0}),Q.info(`Auto-heal: cleared embedding model cache`,{path:n})}catch{}}if(n.includes(`lance`)||n.includes(`database`)||n.includes(`store`)){let t=g(e.store.path,`lance`);try{await r(t,{recursive:!0,force:!0}),Q.info(`Auto-heal: cleared LanceDB store`,{path:t})}catch{}}if(n.includes(`sqlite`)||n.includes(`database disk image`)||n.includes(`graph`)){let t=g(e.store.path,`graph.db`);try{await r(t,{force:!0}),Q.info(`Auto-heal: cleared graph database`,{path:t})}catch{}}}async function Tl(n){Q.info(`Initializing AI Kit components`);let[r,i,o,s]=await Promise.all([(async()=>{let e=new ae({model:n.embedding.model,dimensions:n.embedding.dimensions});return await e.initialize(),Q.info(`Embedder loaded`,{modelId:e.modelId,dimensions:e.dimensions}),e})(),(async()=>{let e=await he({backend:n.store.backend,path:n.store.path});return await e.initialize(),Q.info(`Store initialized`),e})(),(async()=>{let e=new me({path:n.store.path});return await e.initialize(),Q.info(`Graph store initialized`),e})(),(async()=>{let e=await ie();return e?Q.info(`WASM tree-sitter enabled for AST analysis`):Q.warn(`WASM tree-sitter not available; analyzers will use regex fallback`),e})()]),c=new pe(r,i),l=new fe(n.store.path);l.load(),c.setHashCache(l);let u=n.curated.path,f=new e(u);await f.initialize();let p=new t(u,i,r,f);c.setGraphStore(o);let m=ua(n.er),h=m?new le(n.curated.path):void 0;h&&Q.info(`Policy store initialized`,{ruleCount:h.getRules().length});let g=m?new ce:void 0,v=_(n.sources[0]?.path??process.cwd(),y.aiContext),b=a(v),x=n.onboardDir?a(n.onboardDir):!1,S=b||x,C,w=b?v:n.onboardDir;if(S&&w)try{C=d(w).mtime.toISOString()}catch{}return Q.info(`Onboard state detected`,{onboardComplete:S,onboardTimestamp:C,aiKbExists:b,onboardDirExists:x}),{embedder:r,store:i,indexer:c,curated:p,graphStore:o,fileCache:new ge,bridge:m,policyStore:h,evolutionCollector:g,onboardComplete:S,onboardTimestamp:C}}function El(e,t){let n=new nn({name:t.serverName??`aikit`,version:r()},{capabilities:{logging:{},completions:{},prompts:{}}});return Cr(n),Ml(n,e,t,vr(n),new Wr(n),Xr(n)),Er(n,{curated:e.curated,store:e.store,graphStore:e.graphStore},t.indexMode),n}function Dl(e){return e.toolProfiles}const Ol=[`flow_list`,`flow_info`,`flow_start`,`flow_step`,`flow_status`,`flow_reset`,`flow_runs`,`flow_read_instruction`,`flow_add`,`flow_remove`,`flow_update`],kl=[`er_push`,`er_pull`,`er_sync_status`],Al=[...kl,`er_update_policy`,`er_evolve_review`],jl=new Set(Al);function Ml(e,t,n,r,i,a,o,s){let c=new lr,l=new Vn;l.register(Rn),l.register(Pn),l.register(Fn),l.register(jn),l.register(Dn),l.register(On),l.register(Bn);let u=new Kn(l,t.curated);c.use(Wn(u),{order:5,name:`auto-knowledge`}),c.use(Hr(),{order:10,name:`replay`}),c.use(Zr(),{order:50,name:`structured-content-guard`}),c.use(_r(),{order:90,name:`compression`}),mr(e,c,n.toolPrefix??``);let d=oi(process.env.AIKIT_TOOLSET||n.toolProfile||`full`,[...$,...Al],ur,Dl(n)),f=e=>d.has(e),p=[...d].filter(e=>jl.has(e)?kl.includes(e)?!!t.bridge:e===`er_update_policy`?!!t.policyStore:e===`er_evolve_review`?!!t.evolutionCollector:!1:!0);f(`search`)&&Qc(e,t.embedder,t.store,t.graphStore,t.bridge,t.evolutionCollector,a),f(`lookup`)&&qo(e,t.store);let m={onboardComplete:t.onboardComplete,onboardTimestamp:t.onboardTimestamp};f(`status`)&&ul(e,t.store,t.graphStore,t.curated,m,n,o,s),f(`config`)&&Va(e,n),f(`reindex`)&&Pc(e,t.indexer,n,t.curated,t.store,i,o),f(`remember`)&&Ic(e,t.curated,t.policyStore,t.evolutionCollector,i),f(`update`)&&fl(e,t.curated,i),f(`forget`)&&jo(e,t.curated,i),f(`read`)&&Nc(e,t.curated),f(`list`)&&Go(e,t.curated),f(`analyze_structure`)&&qi(e,t.store,t.embedder),f(`analyze_dependencies`)&&Ji(e,t.store,t.embedder),f(`analyze_symbols`)&&Yi(e,t.store,t.embedder),f(`analyze_patterns`)&&Xi(e,t.store,t.embedder),f(`analyze_entry_points`)&&Zi(e,t.store,t.embedder),f(`analyze_diagram`)&&Qi(e,t.store,t.embedder),f(`blast_radius`)&&$i(e,t.store,t.embedder,t.graphStore),f(`produce_knowledge`)&&jc(e,n),f(`onboard`)&&cs(e,t.store,t.embedder,n,m),f(`graph`)&&Fo(e,t.graphStore),f(`audit`)&&ia(e,t.store,t.embedder);let h=n.sources[0]?.path??process.cwd();f(`compact`)&&Ja(e,t.embedder,t.fileCache,h),f(`scope_map`)&&Ya(e,t.embedder,t.store),f(`find`)&&Xa(e,t.embedder,t.store),f(`parse_output`)&&fo(e),f(`workset`)&&us(e),f(`check`)&&so(e),f(`batch`)&&co(e,t.embedder,t.store),f(`symbol`)&&Za(e,t.embedder,t.store,t.graphStore),f(`eval`)&&lo(e),f(`test_run`)&&uo(e),f(`stash`)&&ds(e),f(`git_context`)&&Yo(e),f(`diff_parse`)&&Xo(e),f(`rename`)&&Zo(e),f(`codemod`)&&Qo(e),f(`restore`)&&Bc(e),f(`file_summary`)&&Qa(e,t.fileCache,h),f(`checkpoint`)&&fs(e),f(`data_transform`)&&$o(e),f(`trace`)&&$a(e,t.embedder,t.store,t.graphStore),f(`process`)&&Io(e),f(`watch`)&&Lo(e),f(`dead_symbols`)&&eo(e,t.embedder,t.store),f(`delegate`)&&po(e,a),f(`health`)&&Ro(e),f(`lane`)&&ps(e),f(`queue`)&&ms(e),f(`web_fetch`)&&zo(e),f(`guide`)&&Bo(e,o),ns.some(e=>f(e))&&rs(e,n,p),f(`evidence_map`)&&To(e),f(`digest`)&&Eo(e,t.embedder),f(`forge_classify`)&&Do(e),f(`stratum_card`)&&Oo(e,t.embedder,t.fileCache),f(`forge_ground`)&&ko(e,t.embedder,t.store),f(`present`)&&Dc(e,r),r&&f(`brainstorm`)&&oa(e,r),f(`web_search`)&&pl(e),f(`http`)&&ml(e),f(`regex_test`)&&hl(e),f(`encode`)&&gl(e),f(`measure`)&&_l(e),f(`changelog`)&&vl(e),f(`schema_validate`)&&yl(e),f(`snippet`)&&bl(e),f(`env`)&&xl(e),f(`time`)&&Sl(e),Ol.some(e=>f(e))&&Co(e,n),t.bridge&&kl.some(e=>f(e))&&(da(e,t.bridge,t.evolutionCollector),fa(e,t.bridge),pa(e,t.bridge)),t.policyStore&&f(`er_update_policy`)&&bs(e,t.policyStore),t.evolutionCollector&&f(`er_evolve_review`)&&ao(e,t.evolutionCollector),Kr(e,t.store,t.curated),Rc(e),f(`session_digest`)&&el(e,a)}async function Nl(e){let t=await Tl(e),n=El(t,e);Q.info(`MCP server configured`,{toolCount:$.length,resourceCount:2});let r=async()=>{try{let n=e.sources.map(e=>e.path).join(`, `);Q.info(`Running initial index`,{sourcePaths:n});let r=await t.indexer.index(e,e=>{e.phase===`crawling`||e.phase===`done`||(e.phase===`chunking`&&e.currentFile&&Q.debug(`Indexing file`,{current:e.filesProcessed+1,total:e.filesTotal,file:e.currentFile}),e.phase===`cleanup`&&Q.debug(`Index cleanup`,{staleEntries:e.filesTotal-e.filesProcessed}))});Q.info(`Initial index complete`,{filesProcessed:r.filesProcessed,filesSkipped:r.filesSkipped,chunksCreated:r.chunksCreated,durationMs:r.durationMs});try{await t.store.createFtsIndex()}catch(e){Q.warn(`FTS index creation failed`,A(e))}try{let e=await t.curated.reindexAll();Q.info(`Curated re-index complete`,{indexed:e.indexed})}catch(e){Q.error(`Curated re-index failed`,A(e))}}catch(e){Q.error(`Initial index failed; will retry on aikit_reindex`,A(e))}},i=async()=>{Q.info(`Shutting down`),await Promise.all([t.embedder.shutdown().catch(()=>{}),t.graphStore.close().catch(()=>{}),t.store.close().catch(()=>{})]),process.exit(0)};process.on(`SIGINT`,i),process.on(`SIGTERM`,i);let a=process.ppid,o=setInterval(()=>{try{process.kill(a,0)}catch{Q.info(`Parent process died; shutting down`,{parentPid:a}),clearInterval(o),i()}},5e3);return o.unref(),{server:n,runInitialIndex:r,shutdown:i}}const Pl=new Set(`batch.brainstorm.changelog.check.checkpoint.codemod.compact.config.data_transform.delegate.diff_parse.digest.encode.env.eval.evidence_map.file_summary.forge_classify.git_context.graph.guide.health.http.lane.measure.onboard.parse_output.present.process.produce_knowledge.queue.read.regex_test.reindex.remember.rename.replay.restore.schema_validate.session_digest.scope_map.snippet.stash.status.stratum_card.test_run.time.update.forget.list.watch.web_fetch.web_search.workset`.split(`.`)),Fl=5e3,Il=new Set(`brainstorm.changelog.check.checkpoint.codemod.data_transform.delegate.diff_parse.encode.env.eval.evidence_map.flow_info.flow_list.flow_reset.flow_runs.flow_start.flow_status.flow_step.flow_add.flow_update.flow_remove.flow_read_instruction.describe_tool.list_tools.search_tools.forge_classify.git_context.guide.present.health.http.lane.measure.parse_output.process.produce_knowledge.queue.regex_test.rename.replay.restore.schema_validate.session_digest.snippet.stash.status.test_run.time.watch.web_fetch.web_search.workset`.split(`.`));function Ll(e,t,n){let r=e=>!n||n.has(e);r(`check`)&&so(e),r(`eval`)&&lo(e),r(`test_run`)&&uo(e),r(`parse_output`)&&fo(e),r(`delegate`)&&po(e),r(`git_context`)&&Yo(e),r(`diff_parse`)&&Xo(e),r(`rename`)&&Zo(e),r(`codemod`)&&Qo(e),r(`data_transform`)&&$o(e),r(`workset`)&&us(e),r(`stash`)&&ds(e),r(`checkpoint`)&&fs(e),r(`restore`)&&Bc(e),r(`lane`)&&ps(e),r(`queue`)&&ms(e),r(`session_digest`)&&el(e),r(`health`)&&Ro(e),r(`process`)&&Io(e),r(`watch`)&&Lo(e),r(`web_fetch`)&&zo(e),r(`guide`)&&Bo(e),ns.some(e=>r(e))&&rs(e,t,[...n??new Set($)]),r(`evidence_map`)&&To(e),r(`forge_classify`)&&Do(e),r(`present`)&&Dc(e),r(`brainstorm`)&&oa(e,yr),r(`produce_knowledge`)&&jc(e),r(`replay`)&&Rc(e),r(`status`)&&ll(e),Ol.some(e=>r(e))&&Co(e,t),r(`web_search`)&&pl(e),r(`http`)&&ml(e),r(`regex_test`)&&hl(e),r(`encode`)&&gl(e),r(`measure`)&&_l(e),r(`changelog`)&&vl(e),r(`schema_validate`)&&yl(e),r(`snippet`)&&bl(e),r(`env`)&&xl(e),r(`time`)&&Sl(e)}const $=`analyze_dependencies.analyze_diagram.analyze_entry_points.analyze_patterns.analyze_structure.analyze_symbols.audit.batch.blast_radius.brainstorm.changelog.check.checkpoint.codemod.compact.config.data_transform.dead_symbols.delegate.diff_parse.digest.encode.env.eval.evidence_map.file_summary.find.flow_info.flow_list.flow_reset.flow_runs.flow_start.flow_status.flow_step.flow_add.flow_update.flow_remove.flow_read_instruction.forge_classify.forge_ground.forget.git_context.graph.guide.health.http.lane.describe_tool.list_tools.list.lookup.measure.onboard.parse_output.present.process.produce_knowledge.queue.read.regex_test.reindex.remember.rename.replay.restore.schema_validate.scope_map.search.search_tools.session_digest.snippet.stash.status.stratum_card.symbol.test_run.time.trace.update.watch.web_fetch.web_search.workset`.split(`.`);function Rl(e,t){let n=new nn({name:e.serverName??`aikit`,version:r()},{capabilities:{logging:{},completions:{},prompts:{}}}),i=`initializing`,a=``,o=!1,s=null,c=oi(process.env.AIKIT_TOOLSET||e.toolProfile||`full`,$,ur,Dl(e)),l=null,u=null;function d(e){if(!e||typeof e!=`object`)return[];let t=e,n=[];for(let e of[`path`,`file`,`source_path`,`sourcePath`,`filePath`]){let r=t[e];typeof r==`string`&&r&&n.push(r)}for(let e of[`changed_files`,`paths`,`files`]){let r=t[e];if(Array.isArray(r))for(let e of r){if(typeof e==`string`){n.push(e);continue}e&&typeof e==`object`&&typeof e.path==`string`&&n.push(e.path)}}if(Array.isArray(t.sources))for(let e of t.sources)e&&typeof e==`object`&&typeof e.path==`string`&&n.push(e.path);return n}let f=()=>i===`failed`?[`❌ AI Kit initialization failed — this tool is unavailable.`,``,a?`Error: ${a}`:``,``,`**${Il.size} tools are still available** and fully functional:`,`check, eval, test_run, git_context, health, measure, web_fetch, web_search,`,`flow_list, flow_status, flow_start, flow_read_instruction, regex_test, encode,`,`stash, checkpoint, lane, process, time, env, and more.`,``,`To fix embedding errors, try deleting the cached model:`,` rm -rf ~/.cache/huggingface/transformers-js/mixedbread-ai/`,`Then restart the server to re-download a fresh copy.`,``,`Try restarting the MCP server to retry initialization.`].filter(Boolean).join(`
1272
+ `)}],structuredContent:o}}catch(e){return Z.error(`Time failed`,A(e)),{content:[{type:`text`,text:`Time failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}const Q=E(`server`);function Cl(e){let t=e.toLowerCase();return[`protobuf`,`invalid model`,`invalid onnx`,`unexpected end`,`unexpected token`,`failed to load`,`failed to initialize embedding`,`checksum`,`corrupt`,`malformed`,`could not load`,`onnx`,`database disk image is malformed`,`file is not a database`,`lance`].some(e=>t.includes(e))}async function wl(e,t){let n=t.toLowerCase(),r;try{({rm:r}=await import(`node:fs/promises`))}catch{return}if(n.includes(`embedding`)||n.includes(`onnx`)||n.includes(`protobuf`)||n.includes(`model`)){let t=e.embedding?.model??x.model,n=g(N(),`.cache`,`huggingface`,`transformers-js`,t);try{await r(n,{recursive:!0,force:!0}),Q.info(`Auto-heal: cleared embedding model cache`,{path:n})}catch{}}if(n.includes(`lance`)||n.includes(`database`)||n.includes(`store`)){let t=g(e.store.path,`lance`);try{await r(t,{recursive:!0,force:!0}),Q.info(`Auto-heal: cleared LanceDB store`,{path:t})}catch{}}if(n.includes(`sqlite`)||n.includes(`database disk image`)||n.includes(`graph`)){let t=g(e.store.path,`graph.db`);try{await r(t,{force:!0}),Q.info(`Auto-heal: cleared graph database`,{path:t})}catch{}}}async function Tl(n){Q.info(`Initializing AI Kit components`);let[r,i,o,s]=await Promise.all([(async()=>{let e=new ae({model:n.embedding.model,dimensions:n.embedding.dimensions});return await e.initialize(),Q.info(`Embedder loaded`,{modelId:e.modelId,dimensions:e.dimensions}),e})(),(async()=>{let e=await he({backend:n.store.backend,path:n.store.path});return await e.initialize(),Q.info(`Store initialized`),e})(),(async()=>{let e=new me({path:n.store.path});return await e.initialize(),Q.info(`Graph store initialized`),e})(),(async()=>{let e=await ie();return e?Q.info(`WASM tree-sitter enabled for AST analysis`):Q.warn(`WASM tree-sitter not available; analyzers will use regex fallback`),e})()]),c=new pe(r,i),l=new fe(n.store.path);l.load(),c.setHashCache(l);let u=n.curated.path,f=new e(u);await f.initialize();let p=new t(u,i,r,f);c.setGraphStore(o);let m=ua(n.er),h=m?new le(n.curated.path):void 0;h&&Q.info(`Policy store initialized`,{ruleCount:h.getRules().length});let g=m?new ce:void 0,v=_(n.sources[0]?.path??process.cwd(),y.aiContext),b=a(v),x=n.onboardDir?a(n.onboardDir):!1,S=b||x,C,w=b?v:n.onboardDir;if(S&&w)try{C=d(w).mtime.toISOString()}catch{}return Q.info(`Onboard state detected`,{onboardComplete:S,onboardTimestamp:C,aiKbExists:b,onboardDirExists:x}),{embedder:r,store:i,indexer:c,curated:p,graphStore:o,fileCache:new ge,bridge:m,policyStore:h,evolutionCollector:g,onboardComplete:S,onboardTimestamp:C}}function El(e,t){let n=new nn({name:t.serverName??`aikit`,version:r()},{capabilities:{logging:{},completions:{},prompts:{}}});return Cr(n),Ml(n,e,t,vr(n),new Wr(n),Xr(n)),Er(n,{curated:e.curated,store:e.store,graphStore:e.graphStore},t.indexMode),n}function Dl(e){return e.toolProfiles}const Ol=[`flow_list`,`flow_info`,`flow_start`,`flow_step`,`flow_status`,`flow_reset`,`flow_runs`,`flow_read_instruction`,`flow_add`,`flow_remove`,`flow_update`],kl=[`er_push`,`er_pull`,`er_sync_status`],Al=[...kl,`er_update_policy`,`er_evolve_review`],jl=new Set(Al);function Ml(e,t,n,r,i,a,o,s){let c=new lr,l=new Vn;l.register(Rn),l.register(Pn),l.register(Fn),l.register(jn),l.register(Dn),l.register(On),l.register(Bn);let u=new Kn(l,t.curated);c.use(Wn(u),{order:5,name:`auto-knowledge`}),c.use(Hr(),{order:10,name:`replay`}),c.use(Zr(),{order:50,name:`structured-content-guard`}),c.use(_r(),{order:90,name:`compression`}),mr(e,c,n.toolPrefix??``);let d=oi(process.env.AIKIT_TOOLSET||n.toolProfile||`full`,[...$,...Al],ur,Dl(n)),f=e=>d.has(e),p=[...d].filter(e=>jl.has(e)?kl.includes(e)?!!t.bridge:e===`er_update_policy`?!!t.policyStore:e===`er_evolve_review`?!!t.evolutionCollector:!1:!0);f(`search`)&&Qc(e,t.embedder,t.store,t.graphStore,t.bridge,t.evolutionCollector,a),f(`lookup`)&&Jo(e,t.store);let m={onboardComplete:t.onboardComplete,onboardTimestamp:t.onboardTimestamp};f(`status`)&&ul(e,t.store,t.graphStore,t.curated,m,n,o,s),f(`config`)&&Va(e,n),f(`reindex`)&&Pc(e,t.indexer,n,t.curated,t.store,i,o),f(`remember`)&&Ic(e,t.curated,t.policyStore,t.evolutionCollector,i),f(`update`)&&fl(e,t.curated,i),f(`forget`)&&jo(e,t.curated,i),f(`read`)&&Nc(e,t.curated),f(`list`)&&Ko(e,t.curated),f(`analyze_structure`)&&qi(e,t.store,t.embedder),f(`analyze_dependencies`)&&Ji(e,t.store,t.embedder),f(`analyze_symbols`)&&Yi(e,t.store,t.embedder),f(`analyze_patterns`)&&Xi(e,t.store,t.embedder),f(`analyze_entry_points`)&&Zi(e,t.store,t.embedder),f(`analyze_diagram`)&&Qi(e,t.store,t.embedder),f(`blast_radius`)&&$i(e,t.store,t.embedder,t.graphStore),f(`produce_knowledge`)&&jc(e,n),f(`onboard`)&&ls(e,t.store,t.embedder,n,m),f(`graph`)&&Fo(e,t.graphStore),f(`audit`)&&ia(e,t.store,t.embedder);let h=n.sources[0]?.path??process.cwd();f(`compact`)&&Ja(e,t.embedder,t.fileCache,h),f(`scope_map`)&&Ya(e,t.embedder,t.store),f(`find`)&&Xa(e,t.embedder,t.store),f(`parse_output`)&&fo(e),f(`workset`)&&ds(e),f(`check`)&&so(e),f(`batch`)&&co(e,t.embedder,t.store),f(`symbol`)&&Za(e,t.embedder,t.store,t.graphStore),f(`eval`)&&lo(e),f(`test_run`)&&uo(e),f(`stash`)&&fs(e),f(`git_context`)&&Xo(e),f(`diff_parse`)&&Zo(e),f(`rename`)&&Qo(e),f(`codemod`)&&$o(e),f(`restore`)&&Bc(e),f(`file_summary`)&&Qa(e,t.fileCache,h),f(`checkpoint`)&&ps(e),f(`data_transform`)&&es(e),f(`trace`)&&$a(e,t.embedder,t.store,t.graphStore),f(`process`)&&Lo(e),f(`watch`)&&Ro(e),f(`dead_symbols`)&&eo(e,t.embedder,t.store),f(`delegate`)&&po(e,a),f(`health`)&&zo(e),f(`lane`)&&ms(e),f(`queue`)&&hs(e),f(`web_fetch`)&&Bo(e),f(`guide`)&&Vo(e,o),rs.some(e=>f(e))&&is(e,n,p),f(`evidence_map`)&&To(e),f(`digest`)&&Eo(e,t.embedder),f(`forge_classify`)&&Do(e),f(`stratum_card`)&&Oo(e,t.embedder,t.fileCache),f(`forge_ground`)&&ko(e,t.embedder,t.store),f(`present`)&&Dc(e,r),r&&f(`brainstorm`)&&oa(e,r),f(`web_search`)&&pl(e),f(`http`)&&ml(e),f(`regex_test`)&&hl(e),f(`encode`)&&gl(e),f(`measure`)&&_l(e),f(`changelog`)&&vl(e),f(`schema_validate`)&&yl(e),f(`snippet`)&&bl(e),f(`env`)&&xl(e),f(`time`)&&Sl(e),Ol.some(e=>f(e))&&Co(e,n),t.bridge&&kl.some(e=>f(e))&&(da(e,t.bridge,t.evolutionCollector),fa(e,t.bridge),pa(e,t.bridge)),t.policyStore&&f(`er_update_policy`)&&xs(e,t.policyStore),t.evolutionCollector&&f(`er_evolve_review`)&&ao(e,t.evolutionCollector),Kr(e,t.store,t.curated),Rc(e),f(`session_digest`)&&el(e,a)}async function Nl(e){let t=await Tl(e),n=El(t,e);Q.info(`MCP server configured`,{toolCount:$.length,resourceCount:2});let r=async()=>{try{let n=e.sources.map(e=>e.path).join(`, `);Q.info(`Running initial index`,{sourcePaths:n});let r=await t.indexer.index(e,e=>{e.phase===`crawling`||e.phase===`done`||(e.phase===`chunking`&&e.currentFile&&Q.debug(`Indexing file`,{current:e.filesProcessed+1,total:e.filesTotal,file:e.currentFile}),e.phase===`cleanup`&&Q.debug(`Index cleanup`,{staleEntries:e.filesTotal-e.filesProcessed}))});Q.info(`Initial index complete`,{filesProcessed:r.filesProcessed,filesSkipped:r.filesSkipped,chunksCreated:r.chunksCreated,durationMs:r.durationMs});try{await t.store.createFtsIndex()}catch(e){Q.warn(`FTS index creation failed`,A(e))}try{let e=await t.curated.reindexAll();Q.info(`Curated re-index complete`,{indexed:e.indexed})}catch(e){Q.error(`Curated re-index failed`,A(e))}}catch(e){Q.error(`Initial index failed; will retry on aikit_reindex`,A(e))}},i=async()=>{Q.info(`Shutting down`),await Promise.all([t.embedder.shutdown().catch(()=>{}),t.graphStore.close().catch(()=>{}),t.store.close().catch(()=>{})]),process.exit(0)};process.on(`SIGINT`,i),process.on(`SIGTERM`,i);let a=process.ppid,o=setInterval(()=>{try{process.kill(a,0)}catch{Q.info(`Parent process died; shutting down`,{parentPid:a}),clearInterval(o),i()}},5e3);return o.unref(),{server:n,runInitialIndex:r,shutdown:i}}const Pl=new Set(`batch.brainstorm.changelog.check.checkpoint.codemod.compact.config.data_transform.delegate.diff_parse.digest.encode.env.eval.evidence_map.file_summary.forge_classify.git_context.graph.guide.health.http.lane.measure.onboard.parse_output.present.process.produce_knowledge.queue.read.regex_test.reindex.remember.rename.replay.restore.schema_validate.session_digest.scope_map.snippet.stash.status.stratum_card.test_run.time.update.forget.list.watch.web_fetch.web_search.workset`.split(`.`)),Fl=5e3,Il=new Set(`brainstorm.changelog.check.checkpoint.codemod.data_transform.delegate.diff_parse.encode.env.eval.evidence_map.flow_info.flow_list.flow_reset.flow_runs.flow_start.flow_status.flow_step.flow_add.flow_update.flow_remove.flow_read_instruction.describe_tool.list_tools.search_tools.forge_classify.git_context.guide.present.health.http.lane.measure.parse_output.process.produce_knowledge.queue.regex_test.rename.replay.restore.schema_validate.session_digest.snippet.stash.status.test_run.time.watch.web_fetch.web_search.workset`.split(`.`));function Ll(e,t,n){let r=e=>!n||n.has(e);r(`check`)&&so(e),r(`eval`)&&lo(e),r(`test_run`)&&uo(e),r(`parse_output`)&&fo(e),r(`delegate`)&&po(e),r(`git_context`)&&Xo(e),r(`diff_parse`)&&Zo(e),r(`rename`)&&Qo(e),r(`codemod`)&&$o(e),r(`data_transform`)&&es(e),r(`workset`)&&ds(e),r(`stash`)&&fs(e),r(`checkpoint`)&&ps(e),r(`restore`)&&Bc(e),r(`lane`)&&ms(e),r(`queue`)&&hs(e),r(`session_digest`)&&el(e),r(`health`)&&zo(e),r(`process`)&&Lo(e),r(`watch`)&&Ro(e),r(`web_fetch`)&&Bo(e),r(`guide`)&&Vo(e),rs.some(e=>r(e))&&is(e,t,[...n??new Set($)]),r(`evidence_map`)&&To(e),r(`forge_classify`)&&Do(e),r(`present`)&&Dc(e),r(`brainstorm`)&&oa(e,yr),r(`produce_knowledge`)&&jc(e),r(`replay`)&&Rc(e),r(`status`)&&ll(e),Ol.some(e=>r(e))&&Co(e,t),r(`web_search`)&&pl(e),r(`http`)&&ml(e),r(`regex_test`)&&hl(e),r(`encode`)&&gl(e),r(`measure`)&&_l(e),r(`changelog`)&&vl(e),r(`schema_validate`)&&yl(e),r(`snippet`)&&bl(e),r(`env`)&&xl(e),r(`time`)&&Sl(e)}const $=`analyze_dependencies.analyze_diagram.analyze_entry_points.analyze_patterns.analyze_structure.analyze_symbols.audit.batch.blast_radius.brainstorm.changelog.check.checkpoint.codemod.compact.config.data_transform.dead_symbols.delegate.diff_parse.digest.encode.env.eval.evidence_map.file_summary.find.flow_info.flow_list.flow_reset.flow_runs.flow_start.flow_status.flow_step.flow_add.flow_update.flow_remove.flow_read_instruction.forge_classify.forge_ground.forget.git_context.graph.guide.health.http.lane.describe_tool.list_tools.list.lookup.measure.onboard.parse_output.present.process.produce_knowledge.queue.read.regex_test.reindex.remember.rename.replay.restore.schema_validate.scope_map.search.search_tools.session_digest.snippet.stash.status.stratum_card.symbol.test_run.time.trace.update.watch.web_fetch.web_search.workset`.split(`.`);function Rl(e,t){let n=new nn({name:e.serverName??`aikit`,version:r()},{capabilities:{logging:{},completions:{},prompts:{}}}),i=`initializing`,a=``,o=!1,s=null,c=oi(process.env.AIKIT_TOOLSET||e.toolProfile||`full`,$,ur,Dl(e)),l=null,u=null;function d(e){if(!e||typeof e!=`object`)return[];let t=e,n=[];for(let e of[`path`,`file`,`source_path`,`sourcePath`,`filePath`]){let r=t[e];typeof r==`string`&&r&&n.push(r)}for(let e of[`changed_files`,`paths`,`files`]){let r=t[e];if(Array.isArray(r))for(let e of r){if(typeof e==`string`){n.push(e);continue}e&&typeof e==`object`&&typeof e.path==`string`&&n.push(e.path)}}if(Array.isArray(t.sources))for(let e of t.sources)e&&typeof e==`object`&&typeof e.path==`string`&&n.push(e.path);return n}let f=()=>i===`failed`?[`❌ AI Kit initialization failed — this tool is unavailable.`,``,a?`Error: ${a}`:``,``,`**${Il.size} tools are still available** and fully functional:`,`check, eval, test_run, git_context, health, measure, web_fetch, web_search,`,`flow_list, flow_status, flow_start, flow_read_instruction, regex_test, encode,`,`stash, checkpoint, lane, process, time, env, and more.`,``,`To fix embedding errors, try deleting the cached model:`,` rm -rf ~/.cache/huggingface/transformers-js/mixedbread-ai/`,`Then restart the server to re-download a fresh copy.`,``,`Try restarting the MCP server to retry initialization.`].filter(Boolean).join(`
1273
1273
  `):[`AI Kit is still initializing (loading embeddings model & store).`,``,`**${Il.size} tools are already available** while initialization completes — including:`,`check, eval, test_run, git_context, health, measure, web_fetch, web_search,`,`flow_list, flow_status, flow_start, flow_read_instruction, regex_test, encode,`,`stash, checkpoint, lane, process, time, env, and more.`,``,`This tool requires the AI Kit index. Please retry in a few seconds,`,`or use one of the available tools above in the meantime.`].join(`
1274
1274
  `);Cr(n),hr(n,e.toolPrefix??``);let p=n.sendToolListChanged.bind(n);n.sendToolListChanged=()=>{};let m=[];for(let e of $){if(!c.has(e))continue;let t=L(e),r=n.registerTool(e,{title:t.title,description:`${t.title} — initializing, available shortly`,inputSchema:{},annotations:t.annotations},async()=>({content:[{type:`text`,text:f()}]}));Il.has(e)?r.remove():m.push(r)}Ll(n,e,c),n.sendToolListChanged=p;let h=n.registerResource(`aikit-status`,`aikit://status`,{description:`AI Kit status (initializing...)`,mimeType:`text/plain`},async()=>({contents:[{uri:`aikit://status`,text:`AI Kit is initializing...`,mimeType:`text/plain`}]})),g=n.registerPrompt(`_init`,{description:`Initializing AI Kit…`,argsSchema:{_dummy:P(F.string(),()=>[])}},async()=>({messages:[]})),_,v=new Promise(e=>{_=e}),y,b=new Promise(e=>{y=e}),x=()=>y?.(),S=(async()=>{await b;let r;try{r=await Tl(e)}catch(t){let n=t instanceof Error?t.message:String(t);if(Cl(n)){Q.warn(`AI Kit initialization failed with recoverable error — attempting auto-heal retry`,{error:n}),await wl(e,n);try{r=await Tl(e),Q.info(`AI Kit auto-heal successful — initialization recovered after retry`)}catch(e){i=`failed`,a=e instanceof Error?e.message:String(e),Q.error(`AI Kit initialization failed after auto-heal attempt — server continuing with zero-dep tools only`,{error:a,originalError:n});return}}else{i=`failed`,a=n,Q.error(`AI Kit initialization failed — server continuing with zero-dep tools only`,{error:a});return}}let c=n.sendToolListChanged.bind(n);n.sendToolListChanged=()=>{};let f=n.sendPromptListChanged.bind(n);n.sendPromptListChanged=()=>{};let p=n.sendResourceListChanged.bind(n);n.sendResourceListChanged=()=>{};for(let e of m)e.remove();h.remove(),g.remove();let v=n._registeredTools??{};for(let e of Il)v[e]?.remove();let y=new Wr(n),x=Xr(n);Ml(n,r,e,vr(n),y,x,t,t===`smart`?(()=>{let e=u;return e?.getState?e.getState():null}):null),Er(n,{curated:r.curated,store:r.store,graphStore:r.graphStore},t),n.sendToolListChanged=c,n.sendPromptListChanged=f,n.sendResourceListChanged=p,Promise.resolve(n.sendToolListChanged()).catch(()=>{}),Promise.resolve(n.sendPromptListChanged()).catch(()=>{}),Promise.resolve(n.sendResourceListChanged()).catch(()=>{});let S=n._registeredTools??{};for(let[e,t]of Object.entries(S)){if(Pl.has(e))continue;let n=t.handler;t.handler=async(...t)=>{if(!r.indexer.isIndexing)return n(...t);let i=o?`re-indexing`:`running initial index`,a=new Promise(t=>setTimeout(()=>t({content:[{type:`text`,text:`⏳ AI Kit is ${i}. The tool "${e}" timed out waiting for index data (${Fl/1e3}s).\n\nThe existing index may be temporarily locked. Please retry shortly — indexing will complete automatically.`}]}),Fl));return Promise.race([n(...t),a])}}for(let[e,t]of Object.entries(S)){let n=t.handler,r=ui(e);t.handler=async(...t)=>{try{return await di(()=>n(...t),r,e)}catch(t){if(t instanceof li)return{content:[{type:`text`,text:`⏳ Tool "${e}" timed out after ${r/1e3}s. This may indicate a long-running operation. Please retry or break the task into smaller steps.`}]};throw t}}}let C=Object.keys(S).length;C<$.length&&Q.warn(`ALL_TOOL_NAMES count mismatch`,{expectedToolCount:$.length,registeredToolCount:C}),Q.info(`MCP server configured`,{toolCount:$.length,resourceCount:4});let T=new Tr;T.onPressure((e,t)=>{e===`warning`&&Qn(),e===`critical`&&(Q.warn(`Memory pressure critical — consider restarting`,{rssMB:Math.round(t/1024/1024)}),Qn())}),T.start();let E=new xr;l=E,E.onIdle(async()=>{if(w.isRunning||r.indexer.isIndexing){Q.info(`Idle cleanup deferred — background tasks still running`),E.touch();return}Q.info(`Idle cleanup: closing store and graph connections`);try{await Promise.all([r.store.close().catch(()=>{}),r.graphStore.close().catch(()=>{})])}catch{}}),E.touch();for(let e of Object.values(S)){let t=e.handler;e.handler=async(...e)=>{if(E.touch(),u){let t=d(e[0]);t.length>0&&u.prioritize(...t)}return t(...e)}}s=r,_?.(r)})(),C=async()=>{let t=await v;l?.setBusy(!0);try{let n=e.sources.map(e=>e.path).join(`, `);Q.info(`Running initial index`,{sourcePaths:n});let r=await t.indexer.index(e,e=>{e.phase===`crawling`||e.phase===`done`||(e.phase===`chunking`&&e.currentFile&&Q.debug(`Indexing file`,{current:e.filesProcessed+1,total:e.filesTotal,file:e.currentFile}),e.phase===`cleanup`&&Q.debug(`Index cleanup`,{staleEntries:e.filesTotal-e.filesProcessed}))});o=!0,Q.info(`Initial index complete`,{filesProcessed:r.filesProcessed,filesSkipped:r.filesSkipped,chunksCreated:r.chunksCreated,durationMs:r.durationMs});try{await t.store.createFtsIndex()}catch(e){Q.warn(`FTS index creation failed`,A(e))}try{let e=await t.curated.reindexAll();Q.info(`Curated re-index complete`,{indexed:e.indexed})}catch(e){Q.error(`Curated re-index failed`,A(e))}}catch(e){Q.error(`Initial index failed; will retry on aikit_reindex`,A(e))}finally{l?.setBusy(!1)}},w=new Jn,T=()=>w.schedule({name:`initial-index`,fn:C}),E=process.ppid,D=setInterval(()=>{try{process.kill(E,0)}catch{Q.info(`Parent process died; shutting down`,{parentPid:E}),clearInterval(D),v.then(async e=>{await Promise.all([e.embedder.shutdown().catch(()=>{}),e.graphStore.close().catch(()=>{}),e.store.close().catch(()=>{})])}).catch(()=>{}).finally(()=>process.exit(0))}},5e3);return D.unref(),{server:n,startInit:x,ready:S,runInitialIndex:T,get kb(){return s},scheduler:w,setSmartScheduler(e){u=e}}}export{$ as ALL_TOOL_NAMES,Rl as createLazyServer,El as createMcpServer,Nl as createServer,Tl as initializeKnowledgeBase,Ml as registerMcpTools};
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __createRequire } from 'node:module'; const require = __createRequire(import.meta.url);
2
- import{r as e}from"./chunk-DqSKhezp.js";import{t}from"./react-CKRDn6y3.js";import{a as n,i as r,n as i,t as a}from"./jsx-runtime-CI8Ofr1S.js";import{t as o}from"./useKBClient-BACLDL_U.js";import{t as s}from"./StatusPanel-yRieSRc3.js";import{t as c}from"./SearchPanel-CDSGcT7M.js";import{t as l}from"./CuratedPanel-DGFKz-fJ.js";import{t as u}from"./LogPanel-DGeptKim.js";var d=e(t()),f=a();const p=[`status`,`search`,`curated`,`log`];function m({client:e}){let[t,a]=(0,d.useState)(`status`);return i((e,n)=>{n.tab&&a(p[(p.indexOf(t)+1)%p.length]),e===`1`&&a(`status`),e===`2`&&a(`search`),e===`3`&&a(`curated`),e===`4`&&a(`log`)}),(0,f.jsx)(o,{value:e,children:(0,f.jsxs)(n,{flexDirection:`column`,width:`100%`,children:[(0,f.jsxs)(n,{borderStyle:`single`,paddingX:1,children:[(0,f.jsx)(r,{bold:!0,color:`cyan`,children:`AI Kit Dashboard`}),(0,f.jsx)(r,{children:` │ `}),p.map(e=>(0,f.jsxs)(d.Fragment,{children:[(0,f.jsxs)(r,{color:e===t?`green`:`gray`,bold:e===t,children:[`[`,p.indexOf(e)+1,`] `,e]}),(0,f.jsx)(r,{children:` `})]},e)),(0,f.jsx)(r,{color:`gray`,children:` │ Tab: switch │ Ctrl+C: quit`})]}),(0,f.jsxs)(n,{flexGrow:1,minHeight:10,children:[t===`status`&&(0,f.jsx)(s,{}),t===`search`&&(0,f.jsx)(c,{}),t===`curated`&&(0,f.jsx)(l,{}),t===`log`&&(0,f.jsx)(u,{})]})]})})}export{m as t};
2
+ import{r as e}from"./chunk-DqSKhezp.js";import{t}from"./react-CKRDn6y3.js";import{a as n,i as r,n as i,t as a}from"./jsx-runtime-CI8Ofr1S.js";import{t as o}from"./useKBClient-BACLDL_U.js";import{t as s}from"./StatusPanel-yRieSRc3.js";import{t as c}from"./SearchPanel-CDSGcT7M.js";import{t as l}from"./CuratedPanel-DGFKz-fJ.js";import{t as u}from"./LogPanel-BrBa5xIT.js";var d=e(t()),f=a();const p=[`status`,`search`,`curated`,`log`];function m({client:e}){let[t,a]=(0,d.useState)(`status`);return i((e,n)=>{n.tab&&a(p[(p.indexOf(t)+1)%p.length]),e===`1`&&a(`status`),e===`2`&&a(`search`),e===`3`&&a(`curated`),e===`4`&&a(`log`)}),(0,f.jsx)(o,{value:e,children:(0,f.jsxs)(n,{flexDirection:`column`,width:`100%`,children:[(0,f.jsxs)(n,{borderStyle:`single`,paddingX:1,children:[(0,f.jsx)(r,{bold:!0,color:`cyan`,children:`AI Kit Dashboard`}),(0,f.jsx)(r,{children:` │ `}),p.map(e=>(0,f.jsxs)(d.Fragment,{children:[(0,f.jsxs)(r,{color:e===t?`green`:`gray`,bold:e===t,children:[`[`,p.indexOf(e)+1,`] `,e]}),(0,f.jsx)(r,{children:` `})]},e)),(0,f.jsx)(r,{color:`gray`,children:` │ Tab: switch │ Ctrl+C: quit`})]}),(0,f.jsxs)(n,{flexGrow:1,minHeight:10,children:[t===`status`&&(0,f.jsx)(s,{}),t===`search`&&(0,f.jsx)(c,{}),t===`curated`&&(0,f.jsx)(l,{}),t===`log`&&(0,f.jsx)(u,{})]})]})})}export{m as t};
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __createRequire } from 'node:module'; const require = __createRequire(import.meta.url);
2
- import{t as e}from"./App-DobfqTPH.js";export{e as App};
2
+ import{t as e}from"./App-Bkz0lpCn.js";export{e as App};
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __createRequire } from 'node:module'; const require = __createRequire(import.meta.url);
2
- import{r as e}from"./chunk-DqSKhezp.js";import{t}from"./react-CKRDn6y3.js";import{a as n,i as r,t as i}from"./jsx-runtime-CI8Ofr1S.js";import{homedir as a}from"node:os";import{exec as o,execFile as s}from"node:child_process";import{appendFileSync as c,closeSync as l,constants as u,existsSync as d,mkdirSync as f,openSync as ee,readFileSync as p,readdirSync as m,renameSync as h,statSync as g,unlinkSync as _,writeFileSync as v}from"node:fs";import{basename as te,dirname as y,join as b,resolve as x}from"node:path";import{createHash as S}from"node:crypto";import{fileURLToPath as C}from"node:url";import{promisify as w}from"node:util";import"diff";import{LRUCache as ne}from"lru-cache";import"gpt-tokenizer/model/gpt-4o";import"turndown";var T=e(t());const E={ai:`.ai`,aiContext:`.ai/context`,aiCurated:`.ai/curated`,restorePoints:`.ai/restore-points`,data:`.aikit-data`,state:`.aikit-state`,logs:`.aikit-state/logs`,brainstorm:`.brainstorm`,handoffs:`.handoffs`},D={root:`.aikit-data`,registry:`registry.json`};E.data;function O(){return process.env.AIKIT_GLOBAL_DATA_DIR??x(a(),D.root)}function k(e){let t=x(e);return`${te(t).toLowerCase().replace(/[^a-z0-9-]/g,`-`)||`workspace`}-${S(`sha256`).update(t).digest(`hex`).slice(0,8)}`}function A(){let e=x(O(),D.registry);if(!d(e))return{version:1,workspaces:{}};let t=p(e,`utf-8`);try{return JSON.parse(t)}catch{return{version:1,workspaces:{}}}}function re(e,t=5e3){let n=`${e}.lock`,r=Date.now()+t,i=10;for(;Date.now()<r;)try{let e=ee(n,u.O_CREAT|u.O_EXCL|u.O_WRONLY);return v(e,`${process.pid}\n`),l(e),n}catch(e){if(e.code!==`EEXIST`)throw e;try{let{mtimeMs:e}=g(n);if(Date.now()-e>3e4){_(n);continue}}catch{}let t=new SharedArrayBuffer(4);Atomics.wait(new Int32Array(t),0,0,i),i=Math.min(i*2,200)}throw Error(`Failed to acquire registry lock after ${t}ms`)}function ie(e){try{_(e)}catch{}}function ae(e){let t=O();f(t,{recursive:!0});let n=x(t,D.registry),r=re(n);try{let t=`${n}.tmp`;v(t,JSON.stringify(e,null,2),`utf-8`),h(t,n)}finally{ie(r)}}function oe(e){let t=A(),n=k(e),r=new Date().toISOString();return t.workspaces[n]?t.workspaces[n].lastAccessedAt=r:t.workspaces[n]={partition:n,workspacePath:x(e),registeredAt:r,lastAccessedAt:r},f(j(n),{recursive:!0}),ae(t),t.workspaces[n]}function j(e){return x(O(),e)}function M(){return d(x(O(),D.registry))}function N(e){return M()?x(j(oe(e).partition),`state`):x(e,E.state)}const P={debug:0,info:1,warn:2,error:3},F=[];let I=process.env.AIKIT_LOG_LEVEL??`info`,L=process.env.AIKIT_LOG_FILE_SINK===`true`||process.env.AIKIT_LOG_FILE_SINK!==`false`&&!process.env.VITEST&&process.env.NODE_ENV!==`test`;function R(){return L?process.env.VITEST||process.env.NODE_ENV===`test`?process.env.AIKIT_LOG_FILE_SINK===`true`:!0:!1}let z;function B(){return z||=b(N(process.cwd()),`logs`),z}function V(e){let t=e.toISOString().slice(0,10);return b(B(),`${t}.jsonl`)}let H=0;function U(){let e=Date.now();if(!(e-H<36e5)){H=e;try{let t=B(),n=new Date(e-30*864e5).toISOString().slice(0,10);for(let e of m(t))if(e.endsWith(`.jsonl`)&&e.slice(0,10)<n)try{_(b(t,e))}catch{}}catch{}}}function W(e,t){try{f(B(),{recursive:!0}),c(V(t),`${e}\n`),U()}catch{}}function G(e){function t(t,n,r){if(P[t]<P[I])return;let i=new Date,a={ts:i.toISOString(),level:t,component:e,msg:n,...r},o=JSON.stringify(a);console.error(o);for(let i of F)try{i({level:t,component:e,message:n,data:r})}catch{}R()&&(t===`warn`||t===`error`)&&W(o,i)}return{debug:(e,n)=>t(`debug`,e,n),info:(e,n)=>t(`info`,e,n),warn:(e,n)=>t(`warn`,e,n),error:(e,n)=>t(`error`,e,n)}}b(y(C(import.meta.url)),`..`,`..`,`wasm`),new Set(Object.keys({".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`}));const K=G(`query-executor`),q=y(C(import.meta.url));function se(){let e=b(q,`..`,`queries`);if(d(e))return e;let t=b(q,`..`,`..`,`src`,`queries`);return d(t)?t:e}const J=se(),ce={".ts":`typescript`,".tsx":`typescript`,".mts":`typescript`,".cts":`typescript`,".js":`javascript`,".jsx":`javascript`,".mjs":`javascript`,".cjs":`javascript`,".py":`python`,".go":`go`,".rs":`rust`,".java":`java`};var Y=class{queryCache=new Map;scmCache=new Map;execute(e,t,n,r){let i=this.getOrCompile(t,n,r);return i?i.matches(e).map(e=>X(e)):[]}executeCaptures(e,t,n,r){let i=this.getOrCompile(t,n,r);return i?i.captures(e).map(e=>Z(e)):[]}executeRaw(e,t,n){return t.query(n).matches(e).map(e=>X(e))}getOrCompile(e,t,n){let r=ce[t];if(!r)return null;let i=`${r}:${n}`,a=this.queryCache.get(i);if(a)return a;let o=this.loadScm(r,n);if(!o)return null;try{let t=e.query(o);return this.queryCache.set(i,t),t}catch(e){throw K.warn(`Failed to compile query`,{langDir:r,queryType:n,error:String(e)}),Error(`Failed to compile ${r}/${n}.scm: ${String(e)}`)}}loadScm(e,t){let n=`${e}:${t}`,r=this.scmCache.get(n);if(r!==void 0)return r;let i=b(J,e,`${t}.scm`);try{let e=p(i,`utf-8`);return this.scmCache.set(n,e),e}catch{return K.info(`Query file not found (graceful skip)`,{langDir:e,queryType:t}),null}}dispose(){this.queryCache.clear(),this.scmCache.clear()}static resolveQueryDir(e){return b(J,e)}};function X(e){let t=new Map;for(let n of e.captures)t.set(n.name,Z(n));return{pattern:e.pattern,captures:t}}function Z(e){let{node:t}=e;return{name:e.name,text:t.text,nodeType:t.type,startLine:t.startPosition.row,endLine:t.endPosition.row,startColumn:t.startPosition.column,endColumn:t.endPosition.column,node:t}}new Y,new Y,new Y,new Y,new Y,new Set(`.ts,.tsx,.js,.jsx,.mjs,.cjs,.java,.kt,.kts,.scala,.py,.go,.rs,.rb,.php,.swift,.cs,.c,.cpp,.h,.hpp,.sh,.bash,.ps1,.sql,.graphql,.gql,.proto,.json,.yaml,.yml,.toml,.env,.ini,.cfg,.xml,.pom,.gradle,.tf,.hcl,.lock,.mjs`.split(`,`)),w(o),new Set([`node_modules`,`.git`,`dist`,`build`,`coverage`,`.turbo`,`.cache`,`cdk.out`,E.state]),E.restorePoints,new ne({max:200,ttl:1e3*60*30});const Q=[];function le(e){Q.push(e),Q.sort((e,t)=>t.priority-e.priority)}function ue(e){for(let t of e)le(t)}ue([{name:`git`,toolPatterns:[`git`,`git-status`],priority:10,match(e){return e.tool===`git`||e.tool===`git-status`},compress(e){let t=e.text.split(`
2
+ import{r as e}from"./chunk-DqSKhezp.js";import{t}from"./react-CKRDn6y3.js";import{a as n,i as r,t as i}from"./jsx-runtime-CI8Ofr1S.js";import{homedir as a}from"node:os";import{exec as o,execFile as s}from"node:child_process";import{appendFileSync as c,closeSync as l,constants as u,existsSync as d,mkdirSync as f,openSync as ee,readFileSync as p,readdirSync as m,renameSync as h,statSync as g,unlinkSync as _,writeFileSync as v}from"node:fs";import{basename as te,dirname as y,join as b,resolve as x}from"node:path";import{createHash as S}from"node:crypto";import{fileURLToPath as C}from"node:url";import{promisify as w}from"node:util";import"diff";import{LRUCache as ne}from"lru-cache";import"gpt-tokenizer/model/gpt-4o";import"turndown";var T=e(t());const E={ai:`.ai`,aiContext:`.ai/context`,aiCurated:`.ai/curated`,restorePoints:`.ai/restore-points`,data:`.aikit-data`,state:`.aikit-state`,logs:`.aikit-state/logs`,brainstorm:`.brainstorm`,handoffs:`.handoffs`},D={root:`.aikit-data`,registry:`registry.json`};E.data;function O(){return process.env.AIKIT_GLOBAL_DATA_DIR??x(a(),D.root)}function k(e){let t=x(e);return`${te(t).toLowerCase().replace(/[^a-z0-9-]/g,`-`)||`workspace`}-${S(`sha256`).update(t).digest(`hex`).slice(0,8)}`}function A(){let e=x(O(),D.registry);if(!d(e))return{version:1,workspaces:{}};let t=p(e,`utf-8`);try{return JSON.parse(t)}catch{return{version:1,workspaces:{}}}}function re(e,t=5e3){let n=`${e}.lock`,r=Date.now()+t,i=10;for(;Date.now()<r;)try{let e=ee(n,u.O_CREAT|u.O_EXCL|u.O_WRONLY);return v(e,`${process.pid}\n`),l(e),n}catch(e){if(e.code!==`EEXIST`)throw e;try{let{mtimeMs:e}=g(n);if(Date.now()-e>3e4){_(n);continue}}catch{}let t=new SharedArrayBuffer(4);Atomics.wait(new Int32Array(t),0,0,i),i=Math.min(i*2,200)}throw Error(`Failed to acquire registry lock after ${t}ms`)}function ie(e){try{_(e)}catch{}}function ae(e){let t=O();f(t,{recursive:!0});let n=x(t,D.registry),r=re(n);try{let t=`${n}.tmp`;v(t,JSON.stringify(e,null,2),`utf-8`),h(t,n)}finally{ie(r)}}function oe(e){let t=A(),n=k(e),r=new Date().toISOString();return t.workspaces[n]?t.workspaces[n].lastAccessedAt=r:t.workspaces[n]={partition:n,workspacePath:x(e),registeredAt:r,lastAccessedAt:r},f(j(n),{recursive:!0}),ae(t),t.workspaces[n]}function j(e){return x(O(),e)}function se(){return d(x(O(),D.registry))}function M(e){return se()?x(j(oe(e).partition),`state`):x(e,E.state)}const N={debug:0,info:1,warn:2,error:3},P=[];let F=process.env.AIKIT_LOG_LEVEL??`info`,I=process.env.AIKIT_LOG_FILE_SINK===`true`||process.env.AIKIT_LOG_FILE_SINK!==`false`&&!process.env.VITEST&&process.env.NODE_ENV!==`test`;function L(){return I?process.env.VITEST||process.env.NODE_ENV===`test`?process.env.AIKIT_LOG_FILE_SINK===`true`:!0:!1}let R;function z(){return R||=b(M(process.cwd()),`logs`),R}function B(e){let t=e.toISOString().slice(0,10);return b(z(),`${t}.jsonl`)}let V=0;function H(){let e=Date.now();if(!(e-V<36e5)){V=e;try{let t=z(),n=new Date(e-30*864e5).toISOString().slice(0,10);for(let e of m(t))if(e.endsWith(`.jsonl`)&&e.slice(0,10)<n)try{_(b(t,e))}catch{}}catch{}}}function U(e,t){try{f(z(),{recursive:!0}),c(B(t),`${e}\n`),H()}catch{}}function W(e){function t(t,n,r){if(N[t]<N[F])return;let i=new Date,a={ts:i.toISOString(),level:t,component:e,msg:n,...r},o=JSON.stringify(a);console.error(o);for(let i of P)try{i({level:t,component:e,message:n,data:r})}catch{}L()&&(t===`warn`||t===`error`)&&U(o,i)}return{debug:(e,n)=>t(`debug`,e,n),info:(e,n)=>t(`info`,e,n),warn:(e,n)=>t(`warn`,e,n),error:(e,n)=>t(`error`,e,n)}}const G=y(C(import.meta.url));function ce(){let e=[b(G,`..`,`..`,`wasm`),b(G,`..`,`wasm`)];for(let t of e)if(d(b(t,`tree-sitter.wasm`)))return t;return e[0]}ce(),new Set(Object.keys({".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`}));const K=W(`query-executor`),q=y(C(import.meta.url));function le(){let e=b(q,`..`,`queries`);if(d(e))return e;let t=b(q,`..`,`..`,`src`,`queries`);return d(t)?t:e}const J=le(),ue={".ts":`typescript`,".tsx":`typescript`,".mts":`typescript`,".cts":`typescript`,".js":`javascript`,".jsx":`javascript`,".mjs":`javascript`,".cjs":`javascript`,".py":`python`,".go":`go`,".rs":`rust`,".java":`java`};var Y=class{queryCache=new Map;scmCache=new Map;execute(e,t,n,r){let i=this.getOrCompile(t,n,r);return i?i.matches(e).map(e=>X(e)):[]}executeCaptures(e,t,n,r){let i=this.getOrCompile(t,n,r);return i?i.captures(e).map(e=>Z(e)):[]}executeRaw(e,t,n){return t.query(n).matches(e).map(e=>X(e))}getOrCompile(e,t,n){let r=ue[t];if(!r)return null;let i=`${r}:${n}`,a=this.queryCache.get(i);if(a)return a;let o=this.loadScm(r,n);if(!o)return null;try{let t=e.query(o);return this.queryCache.set(i,t),t}catch(e){throw K.warn(`Failed to compile query`,{langDir:r,queryType:n,error:String(e)}),Error(`Failed to compile ${r}/${n}.scm: ${String(e)}`)}}loadScm(e,t){let n=`${e}:${t}`,r=this.scmCache.get(n);if(r!==void 0)return r;let i=b(J,e,`${t}.scm`);try{let e=p(i,`utf-8`);return this.scmCache.set(n,e),e}catch{return K.info(`Query file not found (graceful skip)`,{langDir:e,queryType:t}),null}}dispose(){this.queryCache.clear(),this.scmCache.clear()}static resolveQueryDir(e){return b(J,e)}};function X(e){let t=new Map;for(let n of e.captures)t.set(n.name,Z(n));return{pattern:e.pattern,captures:t}}function Z(e){let{node:t}=e;return{name:e.name,text:t.text,nodeType:t.type,startLine:t.startPosition.row,endLine:t.endPosition.row,startColumn:t.startPosition.column,endColumn:t.endPosition.column,node:t}}new Y,new Y,new Y,new Y,new Y,new Set(`.ts,.tsx,.js,.jsx,.mjs,.cjs,.java,.kt,.kts,.scala,.py,.go,.rs,.rb,.php,.swift,.cs,.c,.cpp,.h,.hpp,.sh,.bash,.ps1,.sql,.graphql,.gql,.proto,.json,.yaml,.yml,.toml,.env,.ini,.cfg,.xml,.pom,.gradle,.tf,.hcl,.lock,.mjs`.split(`,`)),w(o),new Set([`node_modules`,`.git`,`dist`,`build`,`coverage`,`.turbo`,`.cache`,`cdk.out`,E.state]),E.restorePoints,new ne({max:200,ttl:1e3*60*30});const Q=[];function de(e){Q.push(e),Q.sort((e,t)=>t.priority-e.priority)}function fe(e){for(let t of e)de(t)}fe([{name:`git`,toolPatterns:[`git`,`git-status`],priority:10,match(e){return e.tool===`git`||e.tool===`git-status`},compress(e){let t=e.text.split(`
3
3
  `),n=[],r=!1,i=0,a=0,o=``;for(let s of t){if(s.startsWith(`diff --git`)||s.startsWith(`---`)||s.startsWith(`+++`)){r&&(i>0||a>0)&&n.push(` [${i}+ ${a}- lines in ${o}]`),r=!1,i=0,a=0,n.push(s),s.startsWith(`diff --git`)&&(o=s.replace(/^diff --git a\/\S+ b\//,``));continue}if(s.startsWith(`@@`)){r&&(i>0||a>0)&&n.push(` [${i}+ ${a}- lines]`),r=!0,i=0,a=0,n.push(s);continue}if(e.tool===`git-status`){n.push(s);continue}if(r){s.startsWith(`+`)?i++:s.startsWith(`-`)&&a++;continue}if(s.startsWith(`commit `)||s.startsWith(`Author:`)||s.startsWith(`Date:`)||s.startsWith(`On branch`)||s.match(/^\s*\d+ file/)||s.match(/insertion|deletion/)){n.push(s);continue}if(s.startsWith(`error:`)||s.startsWith(`fatal:`)||s.startsWith(`warning:`)){n.push(s);continue}/^\s{4}\S/.test(s)&&n.push(s)}return r&&(i>0||a>0)&&n.push(` [${i}+ ${a}- lines in ${o}]`),n.join(`
4
4
  `)}},{name:`npm`,toolPatterns:[`npm`,`pnpm`,`yarn`],priority:10,match(e){return e.tool===`npm`||e.tool===`pnpm`},compress(e){let t=e.text.split(`
5
5
  `),n=[],r=0,i=0,a=[];for(let e of t){if(e.includes(`ERR!`)||e.startsWith(`npm error`)||e.includes(`ERESOLVE`)){a.push(e);continue}if(e.includes(`npm warn`)||e.includes(`WARN`)){r++,r<=3&&n.push(e);continue}if(e.includes(`notice`)){i++;continue}if(!(e.includes(`timing`)||e.includes(`http fetch`)||/^\s*$/.test(e))){if(e.match(/^(added|removed|changed|up to date|audited|found \d+)/)){n.push(e);continue}if(e.match(/^(Packages:|Progress:|Done in|dependencies:)/)){n.push(e);continue}e.match(/^(>|\$)\s/)&&n.push(e)}}return r>3&&n.push(`[${r-3} more warnings]`),i>0&&n.push(`[${i} notices]`),a.length>0&&(n.unshift(`=== ERRORS ===`),n.splice(1,0,...a)),n.join(`
@@ -13,5 +13,5 @@ import{r as e}from"./chunk-DqSKhezp.js";import{t}from"./react-CKRDn6y3.js";impor
13
13
  `),n=[],r=0;for(let e of t){if(e.match(/^(NAME|NAMESPACE|LAST SEEN|TYPE)\s+/)){n.push(e);continue}if(e.match(/\b(Warning|Error|Failed|CrashLoopBackOff|OOMKilled|Evicted|Pending)\b/i)){n.push(e);continue}if(e.match(/^\S+\s+\d+\/\d+\s+(Running|Error|CrashLoop|Pending|Completed|Terminating)/)){n.push(e);continue}if(e.match(/^\d+[smhd]\s+.*Normal\s/)){r++;continue}e.match(/^\S+\s+/)&&e.trim().length>0&&n.push(e)}return r>0&&n.push(`[${r} normal events]`),n.join(`
14
14
  `)}},{name:`generic`,toolPatterns:[/.*/],priority:0,match(e){return e.tool===`unknown`||!e.tool},compress(e){let t=e.text.split(`
15
15
  `),n=[],r=``,i=0,a=0;for(let e of t){let t=e.trim();if(t===``){a++,a<=1&&n.push(``);continue}if(a=0,t===r.trim()){i++;continue}i>0&&(n.push(` [repeated ${i} more times]`),i=0),r=e,n.push(e)}return i>0&&n.push(` [repeated ${i} more times]`),n.join(`
16
- `)}}]),new Set([`.git`,E.data,E.state,`.turbo`,`.yarn`,`build`,`coverage`,`dist`,`node_modules`]),w(s),new Set(`if_statement.for_statement.for_in_statement.while_statement.do_statement.switch_case.catch_clause.ternary_expression.if_statement.for_statement.while_statement.except_clause.list_comprehension.if_statement.for_statement.enhanced_for_statement.while_statement.catch_clause.ternary_expression.if_statement.for_statement.select_statement.if_expression.for_expression.while_expression.match_arm`.split(`.`));function de(){return x(N(process.cwd()),`replay.jsonl`)}function fe(e={}){let t=de(),n;try{n=p(t,`utf-8`)}catch{return[]}let r=n.trim().split(`
17
- `).filter(Boolean),i=[];for(let e of r)try{i.push(JSON.parse(e))}catch{}if(e.tool&&(i=i.filter(t=>t.tool===e.tool)),e.source&&(i=i.filter(t=>t.source===e.source)),e.since){let t=e.since;i=i.filter(e=>e.ts>=t)}let a=e.last??20;return i.slice(-a)}w(o),E.data,`script,style,noscript,iframe,svg,nav,footer,header,aside,form,button,input,select,textarea,[role="navigation"],[role="banner"],[role="contentinfo"],[aria-hidden="true"],.sidebar,.nav,.menu,.footer,.header,.ad,.advertisement,.cookie-banner,.popup,.modal`.split(`,`);var $=i();function pe(){let[e,t]=(0,T.useState)([]);return(0,T.useEffect)(()=>{let e=()=>{t(fe({last:30}))};e();let n=setInterval(e,2e3);return()=>clearInterval(n)},[]),(0,$.jsxs)(n,{flexDirection:`column`,borderStyle:`round`,paddingX:1,children:[(0,$.jsx)(r,{bold:!0,color:`cyan`,children:`Activity Log`}),(0,$.jsx)(r,{children:` `}),e.length===0&&(0,$.jsx)(r,{color:`gray`,children:`No activity recorded yet`}),e.slice().reverse().map((e,t)=>{let n=e.ts.split(`T`)[1]?.split(`.`)[0]??e.ts,i=e.status===`ok`?`green`:`red`;return(0,$.jsxs)(r,{children:[(0,$.jsx)(r,{color:`gray`,children:n}),` `,(0,$.jsx)(r,{color:i,children:e.status===`ok`?`✓`:`✗`}),` `,(0,$.jsx)(r,{bold:!0,children:e.tool}),` `,(0,$.jsxs)(r,{color:`gray`,children:[`(`,e.durationMs,`ms)`]})]},`${e.ts}-${t}`)}),(0,$.jsx)(r,{children:` `}),(0,$.jsx)(r,{color:`gray`,children:`Refreshes every 2s │ Showing last 30`})]})}export{pe as t};
16
+ `)}}]),new Set([`.git`,E.data,E.state,`.turbo`,`.yarn`,`build`,`coverage`,`dist`,`node_modules`]),w(s),new Set(`if_statement.for_statement.for_in_statement.while_statement.do_statement.switch_case.catch_clause.ternary_expression.if_statement.for_statement.while_statement.except_clause.list_comprehension.if_statement.for_statement.enhanced_for_statement.while_statement.catch_clause.ternary_expression.if_statement.for_statement.select_statement.if_expression.for_expression.while_expression.match_arm`.split(`.`));function pe(){return x(M(process.cwd()),`replay.jsonl`)}function me(e={}){let t=pe(),n;try{n=p(t,`utf-8`)}catch{return[]}let r=n.trim().split(`
17
+ `).filter(Boolean),i=[];for(let e of r)try{i.push(JSON.parse(e))}catch{}if(e.tool&&(i=i.filter(t=>t.tool===e.tool)),e.source&&(i=i.filter(t=>t.source===e.source)),e.since){let t=e.since;i=i.filter(e=>e.ts>=t)}let a=e.last??20;return i.slice(-a)}w(o),E.data,`script,style,noscript,iframe,svg,nav,footer,header,aside,form,button,input,select,textarea,[role="navigation"],[role="banner"],[role="contentinfo"],[aria-hidden="true"],.sidebar,.nav,.menu,.footer,.header,.ad,.advertisement,.cookie-banner,.popup,.modal`.split(`,`);var $=i();function he(){let[e,t]=(0,T.useState)([]);return(0,T.useEffect)(()=>{let e=()=>{t(me({last:30}))};e();let n=setInterval(e,2e3);return()=>clearInterval(n)},[]),(0,$.jsxs)(n,{flexDirection:`column`,borderStyle:`round`,paddingX:1,children:[(0,$.jsx)(r,{bold:!0,color:`cyan`,children:`Activity Log`}),(0,$.jsx)(r,{children:` `}),e.length===0&&(0,$.jsx)(r,{color:`gray`,children:`No activity recorded yet`}),e.slice().reverse().map((e,t)=>{let n=e.ts.split(`T`)[1]?.split(`.`)[0]??e.ts,i=e.status===`ok`?`green`:`red`;return(0,$.jsxs)(r,{children:[(0,$.jsx)(r,{color:`gray`,children:n}),` `,(0,$.jsx)(r,{color:i,children:e.status===`ok`?`✓`:`✗`}),` `,(0,$.jsx)(r,{bold:!0,children:e.tool}),` `,(0,$.jsxs)(r,{color:`gray`,children:[`(`,e.durationMs,`ms)`]})]},`${e.ts}-${t}`)}),(0,$.jsx)(r,{children:` `}),(0,$.jsx)(r,{color:`gray`,children:`Refreshes every 2s │ Showing last 30`})]})}export{he as t};
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __createRequire } from 'node:module'; const require = __createRequire(import.meta.url);
2
- import{r as e}from"./chunk-DqSKhezp.js";import{t}from"./react-CKRDn6y3.js";import{r as n}from"./jsx-runtime-CI8Ofr1S.js";import{t as r}from"./App-DobfqTPH.js";var i=e(t());function a(e){n(i.createElement(r,{client:e}))}export{a as launch};
2
+ import{r as e}from"./chunk-DqSKhezp.js";import{t}from"./react-CKRDn6y3.js";import{r as n}from"./jsx-runtime-CI8Ofr1S.js";import{t as r}from"./App-Bkz0lpCn.js";var i=e(t());function a(e){n(i.createElement(r,{client:e}))}export{a as launch};
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __createRequire } from 'node:module'; const require = __createRequire(import.meta.url);
2
- import{t as e}from"../LogPanel-DGeptKim.js";export{e as LogPanel};
2
+ import{t as e}from"../LogPanel-BrBa5xIT.js";export{e as LogPanel};