@vpxa/aikit 0.1.267 → 0.1.269

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.
@@ -142,7 +142,7 @@ Changed values:
142
142
  ${o.length>0?o.join(`
143
143
  `):`- No effective changes; requested values already matched the file.`}
144
144
 
145
- These changes take effect on the next server restart.`;return r(`Configuration`,pl(t)),{content:[{type:`text`,text:s}],ui:{type:`resource`,uri:$c}}}catch(e){return Qc.error(`Failed to update config`,{configPath:a,error:e instanceof Error?e.message:String(e)}),{content:[{type:`text`,text:`Failed to update configuration in ${a}: ${e instanceof Error?e.message:String(e)}`}]}}})),r(`Configuration`,pl(t))}const vl=I(`cross-workspace`);function yl(e,t){if(!Pe())return[];let n=Fe();if(n.length===0)return[];if(e.includes(`*`))return t?n.filter(e=>e.partition!==t):n;let r=[];for(let i of e){let e=n.find(e=>e.partition===i);if(e){e.partition!==t&&r.push(e);continue}let a=n.filter(e=>e.partition!==t&&e.partition.replace(/-[a-f0-9]{8}$/,``)===i.toLowerCase());r.push(...a)}let i=new Set;return r.filter(e=>i.has(e.partition)?!1:(i.add(e.partition),!0))}async function bl(e){let t=new Map;for(let n of e){let e=Ne(n.partition),r=P(e,`aikit.db`);try{let e=await xr({backend:`sqlite-vec`,path:r});await e.initialize(),t.set(n.partition,e)}catch(t){vl.warn(`Failed to open workspace store`,{partition:n.partition,partitionDir:e,storePath:r,error:L(t)})}}return{stores:t,closeAll:async()=>{for(let[,e]of t)try{await e.close()}catch{}}}}async function xl(e,t,n){let r=[...e.entries()].map(async([e,r])=>{try{return(await r.search(t,n)).map(t=>({...t,workspace:e}))}catch(t){return vl.warn(`Cross-workspace search failed for partition`,{partition:e,err:t}),[]}});return(await Promise.all(r)).flat().sort((e,t)=>t.score-e.score).slice(0,n.limit)}async function Sl(e,t,n){let r=[...e.entries()].map(async([e,r])=>{try{return(await r.ftsSearch(t,n)).map(t=>({...t,workspace:e}))}catch(t){return vl.warn(`Cross-workspace FTS search failed for partition`,{partition:e,err:t}),[]}});return(await Promise.all(r)).flat().sort((e,t)=>t.score-e.score).slice(0,n.limit)}function Cl(e){return e.toLowerCase().replace(/[-_]/g,``)}function wl(e){let t=ge(e),n=Cl(he(e));try{let e=le(t);for(let r of e)if(Cl(r)===n){let e=F(t,r);if(j(e))return e}}catch{}}function Tl(e,t,n){if(_e(e))return j(e)?e:wl(e)||e;let r=F(t,e);if(j(r))return r;let i=wl(r);if(i)return i;if(n)for(let r of n){if(r===t)continue;let n=F(r,e);if(j(n))return n;let i=wl(n);if(i)return i}try{let n=le(t,{withFileTypes:!0});for(let r of n){if(!r.isDirectory()||r.name.startsWith(`.`)||r.name===`node_modules`)continue;let n=F(t,r.name,e);if(j(n))return n;let i=wl(n);if(i)return i}}catch{}return r}function El(e){if(e.length!==0)return yn({kind:`compact`,text:e,originalChars:e.length,compressedChars:e.length})?.ref??void 0}function Dl(e,t){return t?`${e}\n\nRef: ${t}`:e}const Ol=I(`tools:context`),kl=/^ctx[cd]_[a-z0-9]+$/;function Al(e){return e instanceof Error&&`code`in e&&e.code===`ENOENT`}function jl(e,t){return Al(t)?(Ol.warn(`${e} failed`,{error:`File not found`}),q(`NOT_FOUND`,`File not found`)):(Ol.error(`${e} failed`,L(t)),q(`INTERNAL`,`${e} failed: ${t instanceof Error?t.message:String(t)}`))}function Ml(e){return kl.test(e)}function Nl({text:e,path:t,ref:n,query:r}){let i=typeof e==`string`&&e.length>0,a=typeof t==`string`&&t.length>0,o=typeof n==`string`&&n.length>0,s=typeof r==`string`&&r.trim().length>0;if(!o&&a&&Ml(t))return`Cached reversible refs must be passed as "ref", not "path".`;if(o&&(i||a))return`Provide "ref" by itself, not together with "text" or "path".`;if(!o&&!i&&!a)return`Either "text", "path", or "ref" must be provided.`;if(!o&&!s)return`A focus query is required unless you are restoring a cached ref.`}function Pl(e,t,n,r){if(!r||!e)return;let i=e.replace(/\\/g,`/`);if(![t,...n??[]].map(e=>e.replace(/\\/g,`/`)).some(e=>{let t=e.endsWith(`/`)?e.slice(0,-1):e;return i===t||i.startsWith(`${t}/`)}))try{r(e)}catch{}}function Fl(e,t,n,r,i,a,o){let s=W(`compact`);e.registerTool(`compact`,{title:s.title,description:"Compress text to relevant sections using embedding similarity (no LLM). Provide `text`, `path`, or a cached `ref` from compact/digest/search/find/knowledge. Segments by paragraph/sentence/line.",outputSchema:Zs,inputSchema:{text:z.string().optional().describe(`The text to compress (provide this OR path, not both)`),path:z.string().optional().describe("File path to read server-side — avoids read_file round-trip + token doubling. Use `ref` for cached ctxc_/ctxd_ reads."),ref:z.string().optional().describe(`Reusable cached string ref from compact/digest/search/find/knowledge output`),query:z.string().optional().describe("Focus query — required with `text` or `path`, optional when restoring from `ref`."),max_chars:z.number().min(100).max(5e4).default(3e3).describe(`Target output size in characters`),segmentation:z.enum([`paragraph`,`sentence`,`line`]).default(`paragraph`).describe(`How to split the text for scoring`),token_budget:z.number().min(50).max(12500).optional().describe(`Token budget — overrides max_chars (approx 4 chars per token). Use to fit output into a specific context window.`),enrich:z.boolean().default(!1).describe(`Append curated knowledge and graph context to output. Adds ~150-250 tokens. Default false — set true when you need stored decisions, conventions, or relationship context for the file/query.`)},annotations:s.annotations},J(`compact`,async({text:e,path:s,ref:c,query:l,max_chars:u,segmentation:d,token_budget:f,enrich:p})=>{try{let m=Nl({text:e,path:s,ref:c,query:l});if(m)return q(`VALIDATION`,m);let h=s?Tl(s,r,i):void 0,g=typeof l==`string`&&l.trim().length>0,_=c?await Ze(t,{ref:c,query:l,maxChars:u,tokenBudget:f,segmentation:d,cache:n}):h?await Ze(t,{path:h,query:l??``,maxChars:u,tokenBudget:f,segmentation:d,cache:n}):await Ze(t,{text:e??``,query:l??``,maxChars:u,tokenBudget:f,segmentation:d,cache:n});Pl(h,r,i,o);let v=!!(c&&!g),y=[v?`Retrieved cached ref ${_.ref??c} (${_.compressedChars} chars)`:`Compressed ${_.originalChars} → ${_.compressedChars} chars (${(_.ratio*100).toFixed(0)}%)`,v?void 0:`Kept ${_.segmentsKept}/${_.segmentsTotal} segments`,_.ref?`Ref: ${_.ref}`:void 0,``,_.text].filter(e=>typeof e==`string`).join(`
145
+ These changes take effect on the next server restart.`;return r(`Configuration`,pl(t)),{content:[{type:`text`,text:s}],ui:{type:`resource`,uri:$c}}}catch(e){return Qc.error(`Failed to update config`,{configPath:a,error:e instanceof Error?e.message:String(e)}),{content:[{type:`text`,text:`Failed to update configuration in ${a}: ${e instanceof Error?e.message:String(e)}`}]}}})),r(`Configuration`,pl(t))}const vl=I(`cross-workspace`);function yl(e,t){if(!Pe())return[];let n=Fe();if(n.length===0)return[];if(e.includes(`*`))return t?n.filter(e=>e.partition!==t):n;let r=[];for(let i of e){let e=n.find(e=>e.partition===i);if(e){e.partition!==t&&r.push(e);continue}let a=n.filter(e=>e.partition!==t&&e.partition.replace(/-[a-f0-9]{8}$/,``)===i.toLowerCase());r.push(...a)}let i=new Set;return r.filter(e=>i.has(e.partition)?!1:(i.add(e.partition),!0))}async function bl(e){let t=new Map;for(let n of e){let e=Ne(n.partition),r=P(e,`aikit.db`);try{let e=await xr({backend:`sqlite-vec`,path:r});await e.initialize(),t.set(n.partition,e)}catch(t){vl.warn(`Failed to open workspace store`,{partition:n.partition,partitionDir:e,storePath:r,error:L(t)})}}return{stores:t,closeAll:async()=>{for(let[,e]of t)try{await e.close()}catch{}}}}async function xl(e,t,n){let r=[...e.entries()].map(async([e,r])=>{try{return(await r.search(t,n)).map(t=>({...t,workspace:e}))}catch(t){return vl.warn(`Cross-workspace search failed for partition`,{partition:e,err:t}),[]}});return(await Promise.all(r)).flat().sort((e,t)=>t.score-e.score).slice(0,n.limit)}async function Sl(e,t,n){let r=[...e.entries()].map(async([e,r])=>{try{return(await r.ftsSearch(t,n)).map(t=>({...t,workspace:e}))}catch(t){return vl.warn(`Cross-workspace FTS search failed for partition`,{partition:e,err:t}),[]}});return(await Promise.all(r)).flat().sort((e,t)=>t.score-e.score).slice(0,n.limit)}function Cl(e){return e.toLowerCase().replace(/[-_]/g,``)}function wl(e){let t=ge(e),n=Cl(he(e));try{let e=le(t);for(let r of e)if(Cl(r)===n){let e=F(t,r);if(j(e))return e}}catch{}}function Tl(e,t,n){if(_e(e))return j(e)?e:wl(e)||e;let r=F(t,e);if(j(r))return r;let i=wl(r);if(i)return i;if(n)for(let r of n){if(r===t)continue;let n=F(r,e);if(j(n))return n;let i=wl(n);if(i)return i}try{let n=le(t,{withFileTypes:!0});for(let r of n){if(!r.isDirectory()||r.name.startsWith(`.`)||r.name===`node_modules`)continue;let n=F(t,r.name,e);if(j(n))return n;let i=wl(n);if(i)return i}}catch{}return r}function El(e){if(e.length!==0)return yn({kind:`compact`,text:e,originalChars:e.length,compressedChars:e.length})?.ref??void 0}function Dl(e,t){return t?`${e}\n\nRef: ${t}`:e}const Ol=I(`tools:context`),kl=/^ctx[cd]_[a-z0-9]+$/;function Al(e){return e instanceof Error?(`code`in e?e.code:void 0)===`ENOENT`||e.message.startsWith(`File not found:`)||e.message.startsWith(`Path not found:`):!1}function jl(e,t){return Al(t)?(Ol.warn(`${e} failed`,{error:`File not found`}),q(`NOT_FOUND`,`File not found`)):(Ol.error(`${e} failed`,L(t)),q(`INTERNAL`,`${e} failed: ${t instanceof Error?t.message:String(t)}`))}function Ml(e){return kl.test(e)}function Nl({text:e,path:t,ref:n,query:r}){let i=typeof e==`string`&&e.length>0,a=typeof t==`string`&&t.length>0,o=typeof n==`string`&&n.length>0,s=typeof r==`string`&&r.trim().length>0;if(!o&&a&&Ml(t))return`Cached reversible refs must be passed as "ref", not "path".`;if(o&&(i||a))return`Provide "ref" by itself, not together with "text" or "path".`;if(!o&&!i&&!a)return`Either "text", "path", or "ref" must be provided.`;if(!o&&!s)return`A focus query is required unless you are restoring a cached ref.`}function Pl(e,t,n,r){if(!r||!e)return;let i=e.replace(/\\/g,`/`);if(![t,...n??[]].map(e=>e.replace(/\\/g,`/`)).some(e=>{let t=e.endsWith(`/`)?e.slice(0,-1):e;return i===t||i.startsWith(`${t}/`)}))try{r(e)}catch{}}function Fl(e,t,n,r,i,a,o){let s=W(`compact`);e.registerTool(`compact`,{title:s.title,description:"Compress text to relevant sections using embedding similarity (no LLM). Provide `text`, `path`, or a cached `ref` from compact/digest/search/find/knowledge. Segments by paragraph/sentence/line.",outputSchema:Zs,inputSchema:{text:z.string().optional().describe(`The text to compress (provide this OR path, not both)`),path:z.string().optional().describe("File path to read server-side — avoids read_file round-trip + token doubling. Use `ref` for cached ctxc_/ctxd_ reads."),ref:z.string().optional().describe(`Reusable cached string ref from compact/digest/search/find/knowledge output`),query:z.string().optional().describe("Focus query — required with `text` or `path`, optional when restoring from `ref`."),max_chars:z.number().min(100).max(5e4).default(3e3).describe(`Target output size in characters`),segmentation:z.enum([`paragraph`,`sentence`,`line`]).default(`paragraph`).describe(`How to split the text for scoring`),token_budget:z.number().min(50).max(12500).optional().describe(`Token budget — overrides max_chars (approx 4 chars per token). Use to fit output into a specific context window.`),enrich:z.boolean().default(!1).describe(`Append curated knowledge and graph context to output. Adds ~150-250 tokens. Default false — set true when you need stored decisions, conventions, or relationship context for the file/query.`)},annotations:s.annotations},J(`compact`,async({text:e,path:s,ref:c,query:l,max_chars:u,segmentation:d,token_budget:f,enrich:p})=>{try{let m=Nl({text:e,path:s,ref:c,query:l});if(m)return q(`VALIDATION`,m);let h=s?Tl(s,r,i):void 0,g=typeof l==`string`&&l.trim().length>0,_=c?await Ze(t,{ref:c,query:l,maxChars:u,tokenBudget:f,segmentation:d,cache:n}):h?await Ze(t,{path:h,query:l??``,maxChars:u,tokenBudget:f,segmentation:d,cache:n}):await Ze(t,{text:e??``,query:l??``,maxChars:u,tokenBudget:f,segmentation:d,cache:n});Pl(h,r,i,o);let v=!!(c&&!g),y=[v?`Retrieved cached ref ${_.ref??c} (${_.compressedChars} chars)`:`Compressed ${_.originalChars} → ${_.compressedChars} chars (${(_.ratio*100).toFixed(0)}%)`,v?void 0:`Kept ${_.segmentsKept}/${_.segmentsTotal} segments`,_.ref?`Ref: ${_.ref}`:void 0,``,_.text].filter(e=>typeof e==`string`).join(`
146
146
  `);if(p&&a){let e=await G(a,{query:l,filePath:h});y+=K(e)}return{content:[{type:`text`,text:y}],structuredContent:{text:y,ref:_.ref,originalChars:_.originalChars,compressedChars:_.compressedChars,ratio:_.ratio,segmentsKept:_.segmentsKept,segmentsTotal:_.segmentsTotal}}}catch(e){return{...jl(`Compact`,e),structuredContent:{text:``,originalChars:0,compressedChars:0,ratio:0,segmentsKept:0,segmentsTotal:0}}}}))}function Il(e,t,n,r){let i=W(`scope_map`);e.registerTool(`scope_map`,{title:i.title,description:`Generate a task-scoped reading plan. Given a task description, identifies which files and sections are relevant, with estimated token counts and suggested reading order.`,outputSchema:Bs,inputSchema:{task:z.string().describe(`Description of the task to scope`),max_files:z.number().min(1).max(50).default(15).describe(`Maximum files to include`),content_type:z.enum(Ce).optional().describe(`Filter by content type`),max_tokens:z.number().min(100).max(5e4).optional().describe(`Maximum token budget for the response. When set, output is truncated to fit.`),enrich:z.boolean().default(!0).describe(`Append curated knowledge and graph context to output. Adds ~150-250 tokens. Default true for planning tools — set false to save tokens when enrichment is not needed.`)},annotations:i.annotations},J(`scope_map`,async({task:e,max_files:i,content_type:a,max_tokens:o,enrich:s})=>{try{let c=await un(t,n,{task:e,maxFiles:i,contentType:a}),l=[`## Scope Map: ${e}`,`Total estimated tokens: ~${c.totalEstimatedTokens}`,``,`### Files (by relevance)`,...c.files.map((e,t)=>`${t+1}. **${e.path}** (~${e.estimatedTokens} tokens, ${(e.relevance*100).toFixed(0)}% relevant)\n ${e.reason}\n Focus: ${e.focusRanges.map(e=>`L${e.start}-${e.end}`).join(`, `)}`),``,`### Suggested Reading Order`,...c.readingOrder.map((e,t)=>`${t+1}. ${e}`),``,`### Suggested Compact Calls`,`_Estimated compressed total: ~${Math.ceil(c.totalEstimatedTokens/5)} tokens_`,...c.compactCommands.map((e,t)=>`${t+1}. ${e}`)].join(`
147
147
  `)+"\n\n---\n_Next: Use `search` to dive into specific files, or `compact` to compress file contents for context._";if(s&&r){let t=await G(r,{query:e});l+=K(t)}return{content:[{type:`text`,text:o?R(l,o):l}],structuredContent:{files:c.files.map(e=>({path:e.path,relevance:e.relevance,estimatedTokens:e.estimatedTokens,...e.focusRanges.length>0?{focusLines:e.focusRanges.map(e=>`L${e.start}-${e.end}`)}:{}})),totalFiles:c.files.length,totalEstimatedTokens:c.totalEstimatedTokens,task:e}}}catch(e){return jl(`Scope map`,e)}}))}function Ll(e,t,n,r,i,a){let o=W(`find`);e.registerTool(`find`,{title:o.title,description:`Multi-strategy search combining vector, FTS, glob, and regex. Use for precise queries needing multiple strategies. mode=examples finds real usage of a symbol. For general discovery use search instead.`,outputSchema:Rs,inputSchema:{query:z.string().optional().describe(`Semantic/keyword search query (required for mode "examples")`),glob:z.string().optional().describe(`File glob pattern (search mode only)`),pattern:z.string().optional().describe(`Regex pattern to match in content (search mode only)`),limit:z.number().min(1).max(50).default(10).describe(`Max results`),content_type:z.enum(Ce).optional().describe(`Filter by content type`),mode:z.enum([`search`,`examples`]).default(`search`).describe(`Mode: "search" (default) for federated search, "examples" to find usage examples of a symbol/pattern`),max_tokens:z.number().min(100).max(5e4).optional().describe(`Maximum token budget for the response. When set, output is truncated to fit.`),workspaces:z.array(z.string()).optional().describe(`Cross-workspace search: partition names or folder basenames to include. Use ["*"] for all. User-level mode only.`),enrich:z.boolean().default(!1).describe(`Append curated knowledge and graph context to output. Adds ~150-250 tokens. Default false — set true when you need stored decisions, conventions, or relationship context for the file/query.`)},annotations:o.annotations},J(`find`,async({query:e,glob:o,pattern:s,limit:c,content_type:l,mode:u,max_tokens:d,workspaces:f,enrich:p})=>{try{if(u===`examples`){if(!e)return q(`VALIDATION`,`"query" is required for mode "examples".`);let r=await ht(t,n,{query:e,limit:c,contentType:l}),a=El(JSON.stringify(r)),o=JSON.stringify(a?{ref:a,...r}:r);if(p&&i){let t=await G(i,{query:e});o+=K(t)}return{content:[{type:`text`,text:d?R(o,d):o}]}}let m=await pt(t,n,{query:e,glob:o,pattern:s,limit:c,contentType:l,cwd:r}),h=``;if(f&&f.length>0&&e){let n=yl(f,a);if(n.length>0){let{stores:r,closeAll:i}=await bl(n);try{let i=await xl(r,await t.embedQuery(e),{limit:c,contentType:l});for(let e of i)m.results.push({path:`[${e.workspace}] ${e.record.sourcePath}`,score:e.score,source:`cross-workspace`,lineRange:e.record.startLine?{start:e.record.startLine,end:e.record.endLine}:void 0,preview:e.record.content.slice(0,200)});m.results.sort((e,t)=>t.score-e.score),m.results=m.results.slice(0,c),m.totalFound=m.results.length,h=` + ${n.length} workspace(s)`}finally{await i()}}}if(m.results.length===0){let t=`No results found.${m.failedStrategies?.length?`\nStrategies attempted: ${m.strategies.join(`, `)}\nFailed: ${m.failedStrategies.map(e=>`${e.strategy} (${e.reason})`).join(`, `)}`:m.strategies.length===0?`
148
148
  No search strategies were activated. Provide at least one of: query, glob, or pattern.`:``}`;if(p&&i){let n=await G(i,{query:e});t+=K(n)}let n=d?R(t,d):t,r=El(n);return{content:[{type:`text`,text:Dl(n,r)}],structuredContent:{matches:[],totalMatches:0,pattern:e??o??s??``,truncated:!1,ref:r}}}let g=[`Found ${m.totalFound} results via ${m.strategies.join(` + `)}${h}`,``,...m.results.map(e=>{let t=e.lineRange?`:${e.lineRange.start}-${e.lineRange.end}`:``,n=e.preview?`\n ${e.preview.slice(0,100)}...`:``;return`- [${e.source}] ${e.path}${t} (${(e.score*100).toFixed(0)}%)${n}`})].join(`
@@ -2998,26 +2998,26 @@ Use \`status({})\` to check smart indexing queue status.`}]};let l=zc(c).createT
2998
2998
  `):` none`,r=t.healAttempted?` Auto-heal: ${t.healSuccess?`✓ succeeded`:`✗ failed (${t.healError??`unknown`})`}`:` Auto-heal: not attempted`;return[`- **Tree-sitter (WASM)**: ⚠ Unavailable (regex fallback)`,` Reason: ${t.reason||`unknown`}`,` Paths checked:`,n,r,` OS: ${t.os} ${t.arch} | Node: ${t.nodeVersion}`,` Fix: Reinstall package or run vendor:wasm script`].join(`
2999
2999
  `)}const t_=5*6e4;let n_=null,r_=null;function i_(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 a_(){let e=Date.now();if(n_&&e-n_.ts<t_)return n_.value;try{let t=F(Bn(),`.copilot`,`.aikit-scaffold.json`);if(!j(t))return n_={value:null,ts:e},null;let n=JSON.parse(N(t,`utf-8`)).version??null;return n_={value:n,ts:e},n}catch{return n_={value:null,ts:e},null}}function o_(){let e=Date.now();if(r_&&e-r_.ts<t_)return r_.value;try{let t=F(process.cwd(),`.github`,`.aikit-scaffold.json`);if(!j(t))return r_={value:null,ts:e},null;let n=JSON.parse(N(t,`utf-8`)).version??null;return r_={value:n,ts:e},n}catch{return r_={value:null,ts:e},null}}function s_(e){let t=W(`status`);e.registerTool(`status`,{title:t.title,description:`Get the current status and statistics of the AI Kit index.`,inputSchema:Zg,outputSchema:Ds,annotations:t.annotations},J(`status`,async()=>{let e=re(),t=a_(),n=o_(),r=t!=null&&t!==e,i=n!=null&&n!==e,a=[`## AI Kit Status`,``,`⏳ **AI Kit is initializing** — index stats will be available shortly.`,``,`### Runtime`,`- **Tree-sitter (WASM)**: ${ar.get()?`✅ Available (AST analysis)`:`⚠ Unavailable (regex fallback)`}`,``,`### Version`,`- **Server**: ${e}`,`- **Scaffold (user)**: ${t??`not installed`}`,`- **Scaffold (workspace)**: ${n??`not installed`}`];if(r||i){let o=ie(),s=[];r&&s.push(`user scaffold v${t}`),i&&s.push(`workspace scaffold v${n}`);let c=s.join(`, `);o.state===`success`?a.push(``,`### ✅ Upgrade Applied`,`- Server v${e} — ${c} auto-upgraded successfully.`,`- _Restart the MCP server to use the updated version._`):o.state===`pending`?a.push(``,`### ⏳ Upgrade In Progress`,`- Server v${e} ≠ ${c}`,`- Auto-upgrade is running in the background…`):o.state===`failed`?(ne(),a.push(``,`### ⬆ Upgrade Available (auto-upgrade failed, retrying)`,`- Server v${e} ≠ ${c}`,`- Error: ${o.error??`unknown`}`)):(ne(),a.push(``,`### ⬆ Upgrade Available`,`- Server v${e} ≠ ${c}`,`- Auto-upgrade triggered — check again shortly.`))}let o={totalRecords:0,totalFiles:0,lastIndexedAt:null,onboarded:!1,onboardDir:``,contentTypes:{},wasmAvailable:!!ar.get(),wasmDiagnostics:ir.get(),graphStats:null,curatedCount:0,serverVersion:e,scaffoldVersion:t??null,workspaceScaffoldVersion:n??null,upgradeAvailable:r||i,contextPressure:0,nextAction:$g({onboarded:!1,indexStale:!1,contextPressure:0})};return{content:[{type:`text`,text:a.join(`
3000
3000
  `)}],structuredContent:o}}))}function c_(e,t,n,r,i,a,o,s,c){let l=W(`status`);e.registerTool(`status`,{title:l.title,description:`Get the current status and statistics of the AI Kit index.`,inputSchema:Zg,outputSchema:Ds,annotations:l.annotations},J(`status`,async({includePrelude:e=!1})=>{let l=[];try{let[u,d]=await Promise.all([Qg(t.getStats(),{totalRecords:0,totalFiles:0,lastIndexedAt:null,contentTypeBreakdown:{}},`store.getStats`),Qg(t.listSourcePaths(),[],`store.listSourcePaths`)]),f=u.value;u.timedOut&&l.push(`⚠ Index stats timed out — values may be incomplete`);let p=d.value;d.timedOut&&l.push(`⚠ File listing timed out`);let m=null,h=0,g=[`## AI Kit Status`,``,`- **Total Records**: ${f.totalRecords}`,`- **Total Files**: ${f.totalFiles}`,`- **Last Indexed**: ${f.lastIndexedAt??`Never`}`,``,`### Content Types`,...Object.entries(f.contentTypeBreakdown).map(([e,t])=>`- ${e}: ${t}`),``,`### Indexed Files`,...p.slice(0,50).map(e=>`- ${e}`),p.length>50?`\n... and ${p.length-50} more files`:``];if(n)try{let e=await Qg(n.getStats(),{nodeCount:0,edgeCount:0,nodeTypes:{},edgeTypes:{}},`graphStore.getStats`);if(e.timedOut)l.push(`⚠ Graph stats timed out`),g.push(``,`### Knowledge Graph`,`- Graph stats timed out`);else{let t=e.value;m={nodes:t.nodeCount,edges:t.edgeCount},g.push(``,`### Knowledge Graph`,`- **Nodes**: ${t.nodeCount}`,`- **Edges**: ${t.edgeCount}`,...Object.entries(t.nodeTypes).map(([e,t])=>` - ${e}: ${t}`));try{let e=await Qg(n.validate(),{valid:!0,danglingEdges:[],orphanNodes:[],stats:{nodeCount:0,edgeCount:0,nodeTypes:{},edgeTypes:{}}},`graphStore.validate`);if(!e.timedOut){let t=e.value;t.valid||g.push(`- **⚠ Integrity Issues**: ${t.danglingEdges.length} dangling edges`),t.orphanNodes.length>0&&g.push(`- **Orphan nodes**: ${t.orphanNodes.length}`)}}catch{}}}catch{g.push(``,`### Knowledge Graph`,`- Graph store unavailable`)}let _=a?.onboardDir??``,v=j(_),y=i?.onboardComplete||v;if(g.push(``,`### Onboard Status`,y?`- ✅ Complete${i?.onboardTimestamp?` (last: ${i.onboardTimestamp})`:``}`:'- ❌ Not run — call `onboard({ path: "." })` to analyze the codebase',`- **Onboard Directory**: \`${_}\``),r)try{let e=await Qg(r.list(),[],`curated.list`);if(e.timedOut)l.push(`⚠ Curated knowledge listing timed out`),g.push(``,`### Curated Knowledge`,`- Listing timed out`);else{let t=e.value;h=t.length,g.push(``,`### Curated Knowledge`,t.length>0?`- ${t.length} entries`:'- Empty — use `knowledge({ action: "remember", ... })` to persist decisions')}}catch{g.push(``,`### Curated Knowledge`,`- Unable to read curated entries`)}let b=i_(f.totalRecords,m?.nodes??0,m?.edges??0,h),x=f.lastIndexedAt?new Date(f.lastIndexedAt).getTime():0,S=x>0?Date.now()-x:1/0,C=$g({onboarded:y,indexStale:y&&S>1440*60*1e3,contextPressure:b});g.push(``),g.push(`## 📊 Context Pressure: ${b}/100`),b>=80?g.push(`⚠️ High pressure — consider pruning stale entries or compacting context.`):b>=50?g.push(`ℹ️ Moderate pressure — AI Kit memory is well-populated.`):g.push(`✅ Low pressure — plenty of headroom for more content.`);let w=0;if(f.lastIndexedAt){w=new Date(f.lastIndexedAt).getTime();let e=(Date.now()-w)/(1e3*60*60);g.push(``,`### Index Freshness`,e>24?o===`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`)}g.push(``,`### Next Action`,`- **${C.kind}**: ${C.reason}`);let T=null,E=t;if(typeof E.getDiagnostics==`function`)try{T=E.getDiagnostics(),g.push(``,`### Storage`,`- **Backend**: ${a?.store?.backend??`unknown`}`,`- **Adapter**: ${T.adapterType}`,`- **Vector search**: ${T.vectorSearchEnabled?`✅ enabled`:`⚠ disabled (FTS-only fallback)`}`,T.dbPath?`- **DB**: ${T.dbPath}`:``,T.dbSizeBytes==null?``:`- **DB size**: ${(T.dbSizeBytes/1024/1024).toFixed(2)} MB`,`- **Embedding dim**: ${T.embeddingDim}`,`- **Vector dtype**: ${T.vectorDtype}`)}catch{}if(o===`smart`)if(g.push(``,`### Smart Indexing`),s){let e=s();e?g.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}`):g.push(`- **Mode**: Smart (trickle)`,`- **Status**: scheduler state unavailable (init may have failed)`)}else g.push(`- **Mode**: Smart (trickle) — scheduler state unavailable`);let D=0;{try{let e=a?.stateDir?P(a.stateDir,`stash`):null;if(e&&j(e)){let t=fe(e).mtimeMs;t>w&&(w=t)}}catch{}let e=[];if(r)try{let t=h>0?await r.list():[];for(let e of t){let t=new Date(e.updated||e.created).getTime();t>w&&(w=t)}e.push(...t.sort((e,t)=>new Date(t.updated).getTime()-new Date(e.updated).getTime()).slice(0,5))}catch{}if(D=w>0?Date.now()-w:0,D>=Xg){let t=Math.floor(D/36e5);if(g.push(``,`### 🌅 Session Briefing`,`_${t}+ hours since last activity — here's what to pick up:_`,``),e.length>0){g.push(`**Recent decisions/notes:**`);for(let t of e)g.push(`- **${t.title}** (${t.category??`note`}) — ${(t.contentPreview??``).slice(0,80)}…`)}g.push(``,`**Suggested next steps:**`,'- `search({ query: "SESSION CHECKPOINT", origin: "curated" })` — find your last checkpoint',"- `restore({})` — resume from a saved checkpoint",'- `knowledge({ action: "list" })` — browse all stored knowledge')}}g.push(``,`### Runtime`,e_());let O=Ee.instance().getAll(),k=O.filter(e=>e.status!==`healthy`);if(k.length>0){g.push(``,`### ⚠️ Subsystem Health`);for(let e of k){let t=Math.round((Date.now()-e.since)/1e3);g.push(`- **${e.name}**: ${e.status} (${t}s ago${e.reason?` — ${e.reason}`:``})`)}}else O.length>0&&g.push(``,`### ✅ Subsystem Health`,`- All ${O.length} subsystems healthy`);let ee=we.getAll();if(ee.size>0){g.push(``,`### 🔌 Circuit Breakers`);for(let[e,t]of ee){let n=t.getState(),r=`- **${e}**: ${n===`closed`?`🟢`:n===`open`?`🔴`:`🟡`} ${n}`;if(n===`open`){let e=t.remainingCooldownMs();r+=` (recovery in ${Math.ceil(e/1e3)}s)`}g.push(r)}}let te=a_(),ae=o_(),A=re(),oe=te!=null&&te!==A,se=ae!=null&&ae!==A;if(oe||se){let e=ie(),t=[];oe&&t.push(`user scaffold v${te}`),se&&t.push(`workspace scaffold v${ae}`);let n=t.join(`, `);e.state===`success`?g.push(``,`### ✅ Upgrade Applied`,`- Server v${A} — ${n} auto-upgraded successfully.`,`- _Restart the MCP server to use the updated version._`):e.state===`pending`?g.push(``,`### ⏳ Upgrade In Progress`,`- Server v${A} ≠ ${n}`,`- Auto-upgrade is running in the background…`):e.state===`failed`?(ne(),g.push(``,`### ⬆ Upgrade Available (auto-upgrade failed, retrying)`,`- Server v${A} ≠ ${n}`,`- Error: ${e.error??`unknown`}`)):(ne(),g.push(``,`### ⬆ Upgrade Available`,`- Server v${A} ≠ ${n}`,`- Auto-upgrade triggered — check again shortly.`))}l.length>0&&g.push(``,`### ⚠ Warnings`,...l.map(e=>`- ${e}`));let ce=jo();if(ce.length>0){let e=ce.sort((e,t)=>t.callCount-e.callCount);g.push(``,`### Tool Usage This Session`,``),g.push(`| Tool | Calls | Tokens In | Tokens Out | Errors | Avg Latency |`),g.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);g.push(`| ${t.tool} | ${t.callCount} | ${e.toLocaleString()} | ${n.toLocaleString()} | ${t.errorCount} | ${r}ms |`)}}let M=Co();if(M.bufferSize>=10){let e=M.state===`healthy`?`🟢`:M.state===`degraded`?`🔴`:`🟡`;g.push(``,`### Auto-GC: ${e} ${M.state}`),g.push(`- p95 latency: ${M.p95}ms | buffer: ${M.bufferSize} samples`),M.gcCount>0&&g.push(`- GC cycles triggered: ${M.gcCount}`)}let N=g.join(`
3001
- `),le=e||D>=Xg?await Jg(r,c):void 0,ue={totalRecords:f.totalRecords,totalFiles:f.totalFiles,lastIndexedAt:f.lastIndexedAt??null,onboarded:y,onboardDir:_,contentTypes:f.contentTypeBreakdown,wasmAvailable:!!ar.get(),wasmDiagnostics:ir.get(),graphStats:m,curatedCount:h,serverVersion:A,scaffoldVersion:te??null,workspaceScaffoldVersion:ae??null,upgradeAvailable:oe||se,storeBackend:a?.store?.backend,storeDiagnostics:T??null,contextPressure:b,nextAction:C,...le===void 0?{}:{prelude:le}};return{content:[{type:`text`,text:N+(o===`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:ue}}catch(e){return Yg.error(`Status failed`,L(e)),q(`INTERNAL`,`Status check failed: ${e instanceof Error?e.message:String(e)}`)}}))}const l_=I(`tools`);function u_(e){let t=W(`web_search`);e.registerTool(`web_search`,{title:t.title,description:`PREFERRED web search — fans out to multiple keyless providers (DuckDuckGo + Bing-HTML + Mojeek) by default, returning a deduplicated, consensus-ranked union within a 10s deadline. Optional providers (SearXNG, Google, Brave, Bing API) join the fan-out automatically when their env vars are set. Pass one query or multiple for parallel searching.`,inputSchema:{queries:z.array(z.string().max(2e3)).min(1).max(5).describe('Search queries (1–5). Single: `["react hooks"]`. Multiple searched in parallel.'),limit:z.number().min(1).max(20).default(5).describe(`Max results per query`),site:z.string().optional().describe(`Restrict to domain (e.g., "docs.aws.amazon.com")`),provider:z.enum([`multi`,`duckduckgo`,`bing-html`,`mojeek`,`searxng`,`google`,`brave`,`bing`]).optional().describe("Search provider. Defaults to env AIKIT_SEARCH_PROVIDER, then `multi` (fan-out). Single keyless: `duckduckgo`, `bing-html`, `mojeek`. Self-hosted: `searxng` (requires SEARXNG_URL). Keyed APIs: `google` (GOOGLE_API_KEY+GOOGLE_CSE_ID), `brave` (BRAVE_API_KEY), `bing` (BING_API_KEY). Missing keys auto-fall back to duckduckgo.")},annotations:t.annotations},J(`web_search`,async({queries:e,limit:t,site:n,provider:r})=>{let i=e,a=async e=>{let i=await An({query:e,limit:t,site:n,provider:r}),a=[`## Search: ${i.query} _(via ${i.provider})_`,``];if(i.results.length===0)a.push(`No results found.`);else for(let e of i.results)a.push(`### [${e.title}](${e.url})`,e.snippet,``);return a.join(`
3001
+ `),le=e||D>=Xg?await Jg(r,c):void 0,ue={totalRecords:f.totalRecords,totalFiles:f.totalFiles,lastIndexedAt:f.lastIndexedAt??null,onboarded:y,onboardDir:_,contentTypes:f.contentTypeBreakdown,wasmAvailable:!!ar.get(),wasmDiagnostics:ir.get(),graphStats:m,curatedCount:h,serverVersion:A,scaffoldVersion:te??null,workspaceScaffoldVersion:ae??null,upgradeAvailable:oe||se,storeBackend:a?.store?.backend,storeDiagnostics:T??null,contextPressure:b,nextAction:C,...le===void 0?{}:{prelude:le}};return{content:[{type:`text`,text:N+(o===`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:ue}}catch(e){return Yg.error(`Status failed`,L(e)),q(`INTERNAL`,`Status check failed: ${e instanceof Error?e.message:String(e)}`)}}))}const l_=I(`tools`);function u_(e){return e instanceof Error?(`code`in e?e.code:void 0)===`ENOENT`||e.message.startsWith(`File not found:`)||e.message.startsWith(`Path not found:`):!1}function d_(e){let t=W(`web_search`);e.registerTool(`web_search`,{title:t.title,description:`PREFERRED web search — fans out to multiple keyless providers (DuckDuckGo + Bing-HTML + Mojeek) by default, returning a deduplicated, consensus-ranked union within a 10s deadline. Optional providers (SearXNG, Google, Brave, Bing API) join the fan-out automatically when their env vars are set. Pass one query or multiple for parallel searching.`,inputSchema:{queries:z.array(z.string().max(2e3)).min(1).max(5).describe('Search queries (1–5). Single: `["react hooks"]`. Multiple searched in parallel.'),limit:z.number().min(1).max(20).default(5).describe(`Max results per query`),site:z.string().optional().describe(`Restrict to domain (e.g., "docs.aws.amazon.com")`),provider:z.enum([`multi`,`duckduckgo`,`bing-html`,`mojeek`,`searxng`,`google`,`brave`,`bing`]).optional().describe("Search provider. Defaults to env AIKIT_SEARCH_PROVIDER, then `multi` (fan-out). Single keyless: `duckduckgo`, `bing-html`, `mojeek`. Self-hosted: `searxng` (requires SEARXNG_URL). Keyed APIs: `google` (GOOGLE_API_KEY+GOOGLE_CSE_ID), `brave` (BRAVE_API_KEY), `bing` (BING_API_KEY). Missing keys auto-fall back to duckduckgo.")},annotations:t.annotations},J(`web_search`,async({queries:e,limit:t,site:n,provider:r})=>{let i=e,a=async e=>{let i=await An({query:e,limit:t,site:n,provider:r}),a=[`## Search: ${i.query} _(via ${i.provider})_`,``];if(i.results.length===0)a.push(`No results found.`);else for(let e of i.results)a.push(`### [${e.title}](${e.url})`,e.snippet,``);return a.join(`
3002
3002
  `)};if(i.length===1)try{return{content:[{type:`text`,text:`${await a(i[0])}\n---\n_Next: Use \`web_fetch\` to read any of these pages in full._`}]}}catch(e){return l_.error(`Web search failed`,L(e)),q(`INTERNAL`,`Web search failed: ${e instanceof Error?e.message:String(e)}`)}let o=await Promise.allSettled(i.map(e=>a(e))),s=[],c=0;for(let e=0;e<o.length;e++){let t=o[e];if(t.status===`fulfilled`)s.push(t.value);else{c++;let n=t.reason instanceof Error?t.reason.message:String(t.reason);l_.error(`Web search failed`,{query:i[e],error:n}),s.push(`## ❌ Search failed: ${i[e]}\n\n${n}`)}}let l=`_Searched ${o.length-c}/${o.length} queries successfully._`;s.push(``,`---`,l,"_Next: Use `web_fetch` to read any of these pages in full._");let u=s.join(`
3003
3003
 
3004
- `);return c===o.length?q(`INTERNAL`,u):{content:[{type:`text`,text:u}]}}))}function d_(e){let t=W(`http`);e.registerTool(`http`,{title:t.title,description:`Make HTTP requests (GET/POST/PUT/PATCH/DELETE/HEAD) for API testing. Returns status, headers, and formatted body with timing info.`,inputSchema:{url:z.string().url().describe(`Request URL (http/https only)`),method:z.enum([`GET`,`POST`,`PUT`,`PATCH`,`DELETE`,`HEAD`]).default(`GET`).describe(`HTTP method`),headers:z.record(z.string(),z.string()).optional().describe(`Request headers as key-value pairs`),body:z.string().optional().describe(`Request body (for POST/PUT/PATCH)`),timeout:z.number().min(1e3).max(6e4).default(15e3).describe(`Timeout in milliseconds`)},annotations:t.annotations},J(`http`,async({url:e,method:t,headers:n,body:r,timeout:i})=>{try{let a=await wt({url:e,method:t,headers:n,body:r,timeout:i}),o=[`## ${t} ${e}`,``,`**Status:** ${a.status} ${a.statusText}`,`**Time:** ${a.durationMs}ms`,`**Size:** ${a.sizeBytes} bytes`,`**Content-Type:** ${a.contentType}`,``,`### Headers`,"```json",JSON.stringify(a.headers),"```",``,`### Body`,a.contentType.includes(`json`)?"```json":"```",a.body,"```"];return a.truncated&&o.push(``,`_Response truncated — total size: ${a.sizeBytes} bytes_`),{content:[{type:`text`,text:o.join(`
3005
- `)}]}}catch(e){return l_.error(`HTTP request failed`,L(e)),q(`INTERNAL`,`HTTP request failed: ${e instanceof Error?e.message:String(e)}`)}}))}function f_(e){let t=W(`regex_test`);e.registerTool(`regex_test`,{title:t.title,description:`Test a regex pattern against sample strings. Supports match, replace, and split modes.`,inputSchema:{pattern:z.string().max(500).describe(`Regex pattern (without delimiters)`),flags:z.string().max(10).regex(/^[gimsuy]*$/).default(``).describe(`Regex flags (g, i, m, s, etc.)`),test_strings:z.array(z.string().max(1e4)).max(50).describe(`Strings to test the pattern against`),mode:z.enum([`match`,`replace`,`split`]).default(`match`).describe(`Test mode`),replacement:z.string().optional().describe(`Replacement string (for replace mode)`)},annotations:t.annotations},J(`regex_test`,async({pattern:e,flags:t,test_strings:n,mode:r,replacement:i})=>{let a=Qt({pattern:e,flags:t,testStrings:n,mode:r,replacement:i});if(!a.valid)return q(`VALIDATION`,`Invalid regex: ${a.error}`);let o=[`## Regex: \`/${a.pattern}/${a.flags}\``,``,`Mode: ${r}`,``];for(let e of a.results){if(o.push(`**Input:** \`${e.input}\``),o.push(`**Matched:** ${e.matched}`),e.matches)for(let t of e.matches){let e=t.groups.length>0?` groups: [${t.groups.join(`, `)}]`:``;o.push(` - "${t.full}" at index ${t.index}${e}`)}e.replaced!==void 0&&o.push(`**Result:** \`${e.replaced}\``),e.split&&o.push(`**Split:** ${JSON.stringify(e.split)}`),o.push(``)}return{content:[{type:`text`,text:o.join(`
3006
- `)}]}}))}function p_(e){let t=W(`encode`);e.registerTool(`encode`,{title:t.title,description:`Encode, decode, or hash text. Supports base64, URL encoding, SHA-256, MD5, JWT decode, hex.`,inputSchema:{operation:z.enum([`base64_encode`,`base64_decode`,`url_encode`,`url_decode`,`sha256`,`md5`,`jwt_decode`,`hex_encode`,`hex_decode`]).describe(`Operation to perform`),input:z.string().max(1e6).describe(`Input text`)},annotations:t.annotations},J(`encode`,async({operation:e,input:t})=>{try{let n=st({operation:e,input:t});return{content:[{type:`text`,text:`## ${e}\n\n**Input:** \`${t.length>100?`${t.slice(0,100)}...`:t}\`\n**Output:**\n\`\`\`\n${n.output}\n\`\`\``}]}}catch(e){return l_.error(`Encode failed`,L(e)),q(`INTERNAL`,`Encode failed: ${e instanceof Error?e.message:String(e)}`)}}))}function m_(e){let t=W(`measure`);e.registerTool(`measure`,{title:t.title,description:`Measure code complexity, line counts, and function counts for a file or directory. Returns per-file metrics sorted by complexity.`,outputSchema:ks,inputSchema:{path:z.string().describe(`File or directory path to measure`),extensions:z.array(z.string()).optional().describe(`File extensions to include (default: .ts,.tsx,.js,.jsx)`),include_hidden:z.boolean().optional().describe(`Include hidden trees such as .generated and .cache. Default false.`),max_tokens:z.number().min(100).max(5e4).optional().describe(`Maximum token budget for the response. When set, output is truncated to fit.`)},annotations:t.annotations},J(`measure`,async({path:e,extensions:t,include_hidden:n,max_tokens:r})=>{try{let i=await Pt({path:e,extensions:t,includeHidden:n}),a=[`## Code Metrics`,``,`**Files:** ${i.summary.totalFiles}`,`**Total lines:** ${i.summary.totalLines} (${i.summary.totalCodeLines} code)`,`**Functions:** ${i.summary.totalFunctions}`,`**Avg complexity:** ${i.summary.avgComplexity}`,`**Max complexity:** ${i.summary.maxComplexity.value} (${i.summary.maxComplexity.file})`,``,`### Top files by complexity`,``,`| File | Lines | Code | Complexity | Cognitive | Functions | Imports |`,`|------|-------|------|------------|-----------|-----------|---------|`];for(let e of i.files.slice(0,20)){let t=e.cognitiveComplexity===void 0?`—`:String(e.cognitiveComplexity);a.push(`| ${e.path} | ${e.lines.total} | ${e.lines.code} | ${e.complexity} | ${t} | ${e.functions} | ${e.imports} |`)}i.files.length>20&&a.push(``,`_...and ${i.files.length-20} more files_`);let o={summary:{totalFiles:i.summary.totalFiles,totalLines:i.summary.totalLines,totalCodeLines:i.summary.totalCodeLines,totalFunctions:i.summary.totalFunctions,avgComplexity:i.summary.avgComplexity,maxComplexity:{value:i.summary.maxComplexity.value,file:i.summary.maxComplexity.file}},files:i.files.map(e=>({path:e.path,lines:e.lines.total,code:e.lines.code,complexity:e.complexity,functions:e.functions}))};return{content:[{type:`text`,text:r?R(a.join(`
3004
+ `);return c===o.length?q(`INTERNAL`,u):{content:[{type:`text`,text:u}]}}))}function f_(e){let t=W(`http`);e.registerTool(`http`,{title:t.title,description:`Make HTTP requests (GET/POST/PUT/PATCH/DELETE/HEAD) for API testing. Returns status, headers, and formatted body with timing info.`,inputSchema:{url:z.string().url().describe(`Request URL (http/https only)`),method:z.enum([`GET`,`POST`,`PUT`,`PATCH`,`DELETE`,`HEAD`]).default(`GET`).describe(`HTTP method`),headers:z.record(z.string(),z.string()).optional().describe(`Request headers as key-value pairs`),body:z.string().optional().describe(`Request body (for POST/PUT/PATCH)`),timeout:z.number().min(1e3).max(6e4).default(15e3).describe(`Timeout in milliseconds`)},annotations:t.annotations},J(`http`,async({url:e,method:t,headers:n,body:r,timeout:i})=>{try{let a=await wt({url:e,method:t,headers:n,body:r,timeout:i}),o=[`## ${t} ${e}`,``,`**Status:** ${a.status} ${a.statusText}`,`**Time:** ${a.durationMs}ms`,`**Size:** ${a.sizeBytes} bytes`,`**Content-Type:** ${a.contentType}`,``,`### Headers`,"```json",JSON.stringify(a.headers),"```",``,`### Body`,a.contentType.includes(`json`)?"```json":"```",a.body,"```"];return a.truncated&&o.push(``,`_Response truncated — total size: ${a.sizeBytes} bytes_`),{content:[{type:`text`,text:o.join(`
3005
+ `)}]}}catch(e){return l_.error(`HTTP request failed`,L(e)),q(`INTERNAL`,`HTTP request failed: ${e instanceof Error?e.message:String(e)}`)}}))}function p_(e){let t=W(`regex_test`);e.registerTool(`regex_test`,{title:t.title,description:`Test a regex pattern against sample strings. Supports match, replace, and split modes.`,inputSchema:{pattern:z.string().max(500).describe(`Regex pattern (without delimiters)`),flags:z.string().max(10).regex(/^[gimsuy]*$/).default(``).describe(`Regex flags (g, i, m, s, etc.)`),test_strings:z.array(z.string().max(1e4)).max(50).describe(`Strings to test the pattern against`),mode:z.enum([`match`,`replace`,`split`]).default(`match`).describe(`Test mode`),replacement:z.string().optional().describe(`Replacement string (for replace mode)`)},annotations:t.annotations},J(`regex_test`,async({pattern:e,flags:t,test_strings:n,mode:r,replacement:i})=>{let a=Qt({pattern:e,flags:t,testStrings:n,mode:r,replacement:i});if(!a.valid)return q(`VALIDATION`,`Invalid regex: ${a.error}`);let o=[`## Regex: \`/${a.pattern}/${a.flags}\``,``,`Mode: ${r}`,``];for(let e of a.results){if(o.push(`**Input:** \`${e.input}\``),o.push(`**Matched:** ${e.matched}`),e.matches)for(let t of e.matches){let e=t.groups.length>0?` groups: [${t.groups.join(`, `)}]`:``;o.push(` - "${t.full}" at index ${t.index}${e}`)}e.replaced!==void 0&&o.push(`**Result:** \`${e.replaced}\``),e.split&&o.push(`**Split:** ${JSON.stringify(e.split)}`),o.push(``)}return{content:[{type:`text`,text:o.join(`
3006
+ `)}]}}))}function m_(e){let t=W(`encode`);e.registerTool(`encode`,{title:t.title,description:`Encode, decode, or hash text. Supports base64, URL encoding, SHA-256, MD5, JWT decode, hex.`,inputSchema:{operation:z.enum([`base64_encode`,`base64_decode`,`url_encode`,`url_decode`,`sha256`,`md5`,`jwt_decode`,`hex_encode`,`hex_decode`]).describe(`Operation to perform`),input:z.string().max(1e6).describe(`Input text`)},annotations:t.annotations},J(`encode`,async({operation:e,input:t})=>{try{let n=st({operation:e,input:t});return{content:[{type:`text`,text:`## ${e}\n\n**Input:** \`${t.length>100?`${t.slice(0,100)}...`:t}\`\n**Output:**\n\`\`\`\n${n.output}\n\`\`\``}]}}catch(e){return l_.error(`Encode failed`,L(e)),q(`INTERNAL`,`Encode failed: ${e instanceof Error?e.message:String(e)}`)}}))}function h_(e){let t=W(`measure`);e.registerTool(`measure`,{title:t.title,description:`Measure code complexity, line counts, and function counts for a file or directory. Returns per-file metrics sorted by complexity.`,outputSchema:ks,inputSchema:{path:z.string().describe(`File or directory path to measure`),extensions:z.array(z.string()).optional().describe(`File extensions to include (default: .ts,.tsx,.js,.jsx)`),include_hidden:z.boolean().optional().describe(`Include hidden trees such as .generated and .cache. Default false.`),max_tokens:z.number().min(100).max(5e4).optional().describe(`Maximum token budget for the response. When set, output is truncated to fit.`)},annotations:t.annotations},J(`measure`,async({path:e,extensions:t,include_hidden:n,max_tokens:r})=>{try{let i=await Pt({path:e,extensions:t,includeHidden:n}),a=[`## Code Metrics`,``,`**Files:** ${i.summary.totalFiles}`,`**Total lines:** ${i.summary.totalLines} (${i.summary.totalCodeLines} code)`,`**Functions:** ${i.summary.totalFunctions}`,`**Avg complexity:** ${i.summary.avgComplexity}`,`**Max complexity:** ${i.summary.maxComplexity.value} (${i.summary.maxComplexity.file})`,``,`### Top files by complexity`,``,`| File | Lines | Code | Complexity | Cognitive | Functions | Imports |`,`|------|-------|------|------------|-----------|-----------|---------|`];for(let e of i.files.slice(0,20)){let t=e.cognitiveComplexity===void 0?`—`:String(e.cognitiveComplexity);a.push(`| ${e.path} | ${e.lines.total} | ${e.lines.code} | ${e.complexity} | ${t} | ${e.functions} | ${e.imports} |`)}i.files.length>20&&a.push(``,`_...and ${i.files.length-20} more files_`);let o={summary:{totalFiles:i.summary.totalFiles,totalLines:i.summary.totalLines,totalCodeLines:i.summary.totalCodeLines,totalFunctions:i.summary.totalFunctions,avgComplexity:i.summary.avgComplexity,maxComplexity:{value:i.summary.maxComplexity.value,file:i.summary.maxComplexity.file}},files:i.files.map(e=>({path:e.path,lines:e.lines.total,code:e.lines.code,complexity:e.complexity,functions:e.functions}))};return{content:[{type:`text`,text:r?R(a.join(`
3007
3007
  `),r):a.join(`
3008
- `)}],structuredContent:o}}catch(e){return l_.error(`Measure failed`,L(e)),q(`INTERNAL`,`Measure failed: ${e instanceof Error?e.message:String(e)}`)}}))}function h_(e){let t=W(`changelog`);e.registerTool(`changelog`,{title:t.title,description:`Generate a changelog from git history between two refs. Groups by conventional commit type.`,inputSchema:{from:z.string().max(200).describe(`Start ref (tag, SHA, HEAD~N)`),to:z.string().max(200).default(`HEAD`).describe(`End ref (default: HEAD)`),format:z.enum([`grouped`,`chronological`,`per-scope`]).default(`grouped`).describe(`Output format`),include_breaking:z.boolean().default(!0).describe(`Highlight breaking changes`),cwd:z.string().optional().describe(`Repository root or working directory`)},annotations:t.annotations},J(`changelog`,async({from:e,to:t,format:n,include_breaking:r,cwd:i})=>{try{let a=Ve({from:e,to:t,format:n,includeBreaking:r,cwd:i}),o=`${a.stats.total} commits (${Object.entries(a.stats.types).map(([e,t])=>`${t} ${e}`).join(`, `)})`;return{content:[{type:`text`,text:`${a.markdown}\n---\n_${o}_`}]}}catch(e){return l_.error(`Changelog failed`,L(e)),q(`INTERNAL`,`Changelog failed: ${e instanceof Error?e.message:String(e)}`)}}))}function g_(e){let t=W(`schema_validate`);e.registerTool(`schema_validate`,{title:t.title,description:`Validate JSON data against a JSON Schema. Supports type, required, properties, items, enum, pattern, min/max.`,inputSchema:{data:z.string().max(5e5).describe(`JSON data to validate (as string)`),schema:z.string().max(5e5).describe(`JSON Schema to validate against (as string)`)},annotations:t.annotations},J(`schema_validate`,async({data:e,schema:t})=>{try{let n=ln({data:JSON.parse(e),schema:JSON.parse(t)});if(n.valid)return{content:[{type:`text`,text:`## Validation: PASSED
3008
+ `)}],structuredContent:o}}catch(e){return u_(e)?(l_.warn(`Measure failed`,{error:`File not found`}),q(`NOT_FOUND`,`File not found`)):(l_.error(`Measure failed`,L(e)),q(`INTERNAL`,`Measure failed: ${e instanceof Error?e.message:String(e)}`))}}))}function g_(e){let t=W(`changelog`);e.registerTool(`changelog`,{title:t.title,description:`Generate a changelog from git history between two refs. Groups by conventional commit type.`,inputSchema:{from:z.string().max(200).describe(`Start ref (tag, SHA, HEAD~N)`),to:z.string().max(200).default(`HEAD`).describe(`End ref (default: HEAD)`),format:z.enum([`grouped`,`chronological`,`per-scope`]).default(`grouped`).describe(`Output format`),include_breaking:z.boolean().default(!0).describe(`Highlight breaking changes`),cwd:z.string().optional().describe(`Repository root or working directory`)},annotations:t.annotations},J(`changelog`,async({from:e,to:t,format:n,include_breaking:r,cwd:i})=>{try{let a=Ve({from:e,to:t,format:n,includeBreaking:r,cwd:i}),o=`${a.stats.total} commits (${Object.entries(a.stats.types).map(([e,t])=>`${t} ${e}`).join(`, `)})`;return{content:[{type:`text`,text:`${a.markdown}\n---\n_${o}_`}]}}catch(e){return l_.error(`Changelog failed`,L(e)),q(`INTERNAL`,`Changelog failed: ${e instanceof Error?e.message:String(e)}`)}}))}function __(e){let t=W(`schema_validate`);e.registerTool(`schema_validate`,{title:t.title,description:`Validate JSON data against a JSON Schema. Supports type, required, properties, items, enum, pattern, min/max.`,inputSchema:{data:z.string().max(5e5).describe(`JSON data to validate (as string)`),schema:z.string().max(5e5).describe(`JSON Schema to validate against (as string)`)},annotations:t.annotations},J(`schema_validate`,async({data:e,schema:t})=>{try{let n=ln({data:JSON.parse(e),schema:JSON.parse(t)});if(n.valid)return{content:[{type:`text`,text:`## Validation: PASSED
3009
3009
 
3010
3010
  Data matches the schema.`}]};let r=[`## Validation: FAILED`,``,`**${n.errors.length} error(s):**`,``];for(let e of n.errors){let t=e.expected?` (expected: ${e.expected}, got: ${e.received})`:``;r.push(`- \`${e.path}\`: ${e.message}${t}`)}return{content:[{type:`text`,text:r.join(`
3011
- `)}]}}catch(e){return l_.error(`Schema validation failed`,L(e)),q(`INTERNAL`,`Schema validation failed: ${e instanceof Error?e.message:String(e)}`)}}))}function __(e){let t=W(`env`);e.registerTool(`env`,{title:t.title,description:`Get system and runtime environment info. Sensitive env vars are redacted by default.`,outputSchema:As,inputSchema:{include_env:z.boolean().default(!1).describe(`Include environment variables`),filter_env:z.string().optional().describe(`Filter env vars by name substring`),show_sensitive:z.boolean().default(!1).describe(`Show sensitive values (keys, tokens, etc.) — redacted by default`)},annotations:t.annotations},J(`env`,async({include_env:e,filter_env:t,show_sensitive:n})=>{let r=lt({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(`
3012
- `)}],structuredContent:a}}))}function v_(e){let t=W(`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:js,inputSchema:{operation:z.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:z.string().optional().describe(`Date input (ISO, unix timestamp, or parseable string). For diff: two comma-separated dates`),timezone:z.string().optional().describe(`Target timezone (e.g., "America/New_York", "Asia/Tokyo")`),duration:z.string().optional().describe(`Duration to add (e.g., "2h30m", "1d", "30s") — for add operation`)},annotations:t.annotations},J(`time`,async({operation:e,input:t,timezone:n,duration:r})=>{try{let i=wn({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(`
3013
- `)}],structuredContent:o}}catch(e){return l_.error(`Time failed`,L(e)),q(`INTERNAL`,`Time failed: ${e instanceof Error?e.message:String(e)}`)}}))}function y_(e){try{let t=P(e,`.flows`);if(!j(t))return null;let n=le(t,{withFileTypes:!0});for(let e of n){if(!e.isDirectory())continue;let n=P(t,e.name,`meta.json`);if(j(n)&&JSON.parse(N(n,`utf-8`)).status===`active`)return e.name}}catch{return null}return null}function b_(e,t,n,r,i,a,o,s,c,l){let u=new go,d=n.sources[0]?.path??process.cwd(),f=je(d),p={activeSlug:null};p.activeSlug=y_(d);let m=new Fa(P(n.stateDir??``,`flow-context`),()=>p.activeSlug),h=new xa;h.register(Di()),h.register(va),h.register(Li),h.register(sa),h.register(Pi),h.register(Oi),h.register(ki),h.register(ha),h.register(ji),h.register(ba),h.register(oa(()=>p.activeSlug?{active:!0,slug:p.activeSlug}:null));let g=new Ea(h,t.curated,{},m),_=l??Ss(n,[...qo,...Vo],ns,Uo(n)),v=e=>_.has(e),y=new Set([..._].filter(e=>!pp.includes(e)&&!to.has(e))),b=new ao;u.use(wa(g),{order:5,name:`auto-knowledge`}),u.use(No(),{order:10,name:`replay`}),u.use(co(b,{stateStore:t.stateStore,curatedStore:t.curated},{trackedTools:y}),{order:94,name:`procedural-memory`}),u.use(Za(new Ya(t.stateStore,t.curated)),{order:95,name:`observation-capture`}),u.use(Yo(),{order:1,name:`structured-content-guard`}),u.use(Pa(Na(n.tokenBudget)),{order:90,name:`compression`}),ss(e,u,n.toolPrefix??``);let x=[..._].filter(e=>Ho.has(e)?Bo.includes(e)?!!t.bridge:e===`er_update_policy`?!!t.policyStore:e===`er_evolve_review`?!!t.evolutionCollector:!1:!0);v(`search`)&&Eg(e,t.embedder,t.store,t.graphStore,t.bridge,t.evolutionCollector,a,t.stateStore,n.memory?.retention,n.memory?.consolidation,f);let S={store:t.store,graphStore:t.graphStore,embedder:t.embedder},C=c?e=>{c()?.prioritize(e)}:void 0;v(`lookup`)&&np(e,t.store,S);let w={onboardComplete:t.onboardComplete,onboardTimestamp:t.onboardTimestamp};v(`status`)&&c_(e,t.store,t.graphStore,t.curated,w,n,o,s,t.stateStore),v(`config`)&&_l(e,n),v(`reindex`)&&ig(e,t.indexer,n,t.curated,t.store,i,o),v(`knowledge`)&&ep(e,t.curated,t.policyStore,t.evolutionCollector,i,m,t.stateStore,n.memory?.retention,n.memory?.supersession,n.memory?.consolidation,n.memory?.lessons,S),v(`analyze`)&&Fc(e,t.store,t.embedder,S),v(`blast_radius`)&&Ic(e,t.store,t.embedder,t.graphStore,S),v(`produce_knowledge`)&&ng(e,n),v(`onboard`)&&Fp(e,t.store,t.embedder,n,w,S),v(`graph`)&&sd(e,t.graphStore,S),v(`audit`)&&Vc(e,t.store,t.embedder,n.tokenBudget),v(`compact`)&&Fl(e,t.embedder,t.fileCache,d,n.allRoots,S,C),v(`scope_map`)&&Il(e,t.embedder,t.store,S),v(`find`)&&Ll(e,t.embedder,t.store,d,S,f),v(`parse_output`)&&Zl(e),v(`workset`)&&Lp(e),v(`check`)&&Jl(e,S,n.tokenBudget),v(`symbol`)&&Rl(e,t.embedder,t.store,t.graphStore,S,f),v(`eval`)&&Yl(e),v(`test_run`)&&Xl(e,S),v(`stash`)&&Rp(e,t.stateStore),v(`signal`)&&Gg(e,t.stateStore),v(`git_context`)&&op(e),v(`diff_parse`)&&sp(e),v(`rename`)&&cp(e,n),v(`codemod`)&&lp(e,n),v(`restore`)&&cg(e),v(`file_summary`)&&zl(e,t.fileCache,d,n.allRoots,S,C),v(`checkpoint`)&&zp(e,t.stateStore),v(`data_transform`)&&up(e),v(`trace`)&&Bl(e,t.embedder,t.store,t.graphStore,S),v(`process`)&&ld(e),v(`watch`)&&ud(e),v(`dead_symbols`)&&Vl(e,t.embedder,t.store,d,n.allRoots,S),v(`delegate`)&&Ql(e,a),v(`health`)&&dd(e),v(`lane`)&&Bp(e),v(`queue`)&&Vp(e),v(`web_fetch`)&&fd(e),v(`guide`)&&pd(e,o),pp.some(e=>v(e))&&mp(e,n,x),v(`evidence_map`)&&$u(e),v(`digest`)&&ed(e,t.embedder),v(`forge_classify`)&&td(e,S),v(`stratum_card`)&&nd(e,t.embedder,t.fileCache),v(`forge_ground`)&&rd(e,t.embedder,t.store),v(`present`)&&eg(e,r),v(`browser`)&&Yn(e,n),v(`web_search`)&&u_(e),v(`http`)&&d_(e),v(`regex_test`)&&f_(e),v(`encode`)&&p_(e),v(`measure`)&&m_(e),v(`changelog`)&&h_(e),v(`schema_validate`)&&g_(e),v(`env`)&&__(e),v(`time`)&&v_(e),v(`flow`)&&Zu(e,n,{store:t.store?{search:async(e,n)=>(await t.store.ftsSearch(e,n)).map(e=>({content:e.record.content}))}:null,graphStore:t.graphStore,embedder:t.embedder},e=>{p.activeSlug=e}),t.bridge&&Bo.some(e=>v(e))&&(Gc(e,t.bridge,t.evolutionCollector),Kc(e,t.bridge),qc(e,t.bridge)),t.policyStore&&v(`er_update_policy`)&&qp(e,t.policyStore),t.evolutionCollector&&v(`er_evolve_review`)&&Kl(e,t.evolutionCollector),zo(e,t.store,t.curated),v(`compliance_score`)&&Xc(e),v(`replay`)&&og(e),v(`session_digest`)&&Og(e,t.stateStore,a)}function x_(e,t,n){let r=e=>!n||n.has(e);r(`check`)&&Jl(e,void 0,t.tokenBudget),r(`eval`)&&Yl(e),r(`test_run`)&&Xl(e),r(`parse_output`)&&Zl(e),r(`delegate`)&&Ql(e),r(`git_context`)&&op(e),r(`diff_parse`)&&sp(e),r(`rename`)&&cp(e,t),r(`codemod`)&&lp(e,t),r(`data_transform`)&&up(e),r(`workset`)&&Lp(e),r(`restore`)&&cg(e),r(`lane`)&&Bp(e),r(`queue`)&&Vp(e),r(`session_digest`)&&Og(e),r(`health`)&&dd(e),r(`process`)&&ld(e),r(`watch`)&&ud(e),r(`web_fetch`)&&fd(e),r(`guide`)&&pd(e),pp.some(e=>r(e))&&mp(e,t,[...n??new Set(qo)]),r(`evidence_map`)&&$u(e),r(`forge_classify`)&&td(e),r(`present`)&&eg(e),r(`browser`)&&Yn(e,t),r(`produce_knowledge`)&&ng(e),r(`compliance_score`)&&Xc(e),r(`replay`)&&og(e),r(`status`)&&s_(e),r(`flow`)&&Zu(e,t),r(`web_search`)&&u_(e),r(`http`)&&d_(e),r(`regex_test`)&&f_(e),r(`encode`)&&p_(e),r(`measure`)&&m_(e),r(`changelog`)&&h_(e),r(`schema_validate`)&&g_(e),r(`env`)&&__(e),r(`time`)&&v_(e)}const S_=I(`resource-notifier`);var C_=class{mcpServer;constructor(e){this.mcpServer=e}async notifyStatusChanged(){await this.sendUpdate(`aikit://status`)}async notifyFileTreeChanged(){await this.sendUpdate(`aikit://file-tree`)}async notifyCuratedIndexChanged(){await this.sendUpdate(`aikit://curated`)}async notifyCuratedEntryChanged(e){await this.sendUpdate(`aikit://curated/${e}`)}async notifyResourceListChanged(){try{await this.mcpServer.server.sendResourceListChanged()}catch(e){S_.debug(`sendResourceListChanged failed`,{error:String(e)})}}async notifyAfterReindex(){await Promise.allSettled([this.notifyStatusChanged(),this.notifyFileTreeChanged()])}async notifyAfterCuratedWrite(e){let t=[this.notifyStatusChanged(),this.notifyCuratedIndexChanged()];e&&t.push(this.notifyCuratedEntryChanged(e)),await Promise.allSettled(t)}async sendUpdate(e){try{await this.mcpServer.server.sendResourceUpdated({uri:e})}catch(t){S_.debug(`sendResourceUpdated failed`,{uri:e,error:String(t)})}}};const Z=I(`server`);function w_(e){let t=e?.trim().toLowerCase();return t===`1`||t===`true`||t===`yes`||t===`on`}async function T_(n){Z.info(`Initializing AI Kit components`);let r=n.store.backend,i=n.embedding,a={model:i.model,nativeDim:i.nativeDim??Te.nativeDim,dimensions:i.dimensions,queryPrefix:i.queryPrefix??Te.queryPrefix},o=n.store.path,s=w_(process.env.AIKIT_SPLIT_STATE),c=P(o,`aikit.db`),l={splitEnabled:s,contentDbPath:c,controlDbPath:s?P(o,`aikit-control.db`):c},u=null;if(r===`sqlite-vec`){let e=l.contentDbPath;j(o)||M(o,{recursive:!0}),u=await yr(e),Z.debug(`SQLite adapter ready`,{type:u.type,vectorCapable:u.vectorCapable,dbPath:e}),u.vectorCapable||Z.warn(`┌──────────────────────────────────────────────────────────────────┐
3011
+ `)}]}}catch(e){return l_.error(`Schema validation failed`,L(e)),q(`INTERNAL`,`Schema validation failed: ${e instanceof Error?e.message:String(e)}`)}}))}function v_(e){let t=W(`env`);e.registerTool(`env`,{title:t.title,description:`Get system and runtime environment info. Sensitive env vars are redacted by default.`,outputSchema:As,inputSchema:{include_env:z.boolean().default(!1).describe(`Include environment variables`),filter_env:z.string().optional().describe(`Filter env vars by name substring`),show_sensitive:z.boolean().default(!1).describe(`Show sensitive values (keys, tokens, etc.) — redacted by default`)},annotations:t.annotations},J(`env`,async({include_env:e,filter_env:t,show_sensitive:n})=>{let r=lt({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(`
3012
+ `)}],structuredContent:a}}))}function y_(e){let t=W(`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:js,inputSchema:{operation:z.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:z.string().optional().describe(`Date input (ISO, unix timestamp, or parseable string). For diff: two comma-separated dates`),timezone:z.string().optional().describe(`Target timezone (e.g., "America/New_York", "Asia/Tokyo")`),duration:z.string().optional().describe(`Duration to add (e.g., "2h30m", "1d", "30s") — for add operation`)},annotations:t.annotations},J(`time`,async({operation:e,input:t,timezone:n,duration:r})=>{try{let i=wn({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(`
3013
+ `)}],structuredContent:o}}catch(e){return l_.error(`Time failed`,L(e)),q(`INTERNAL`,`Time failed: ${e instanceof Error?e.message:String(e)}`)}}))}function b_(e){try{let t=P(e,`.flows`);if(!j(t))return null;let n=le(t,{withFileTypes:!0});for(let e of n){if(!e.isDirectory())continue;let n=P(t,e.name,`meta.json`);if(j(n)&&JSON.parse(N(n,`utf-8`)).status===`active`)return e.name}}catch{return null}return null}function x_(e,t,n,r,i,a,o,s,c,l){let u=new go,d=n.sources[0]?.path??process.cwd(),f=je(d),p={activeSlug:null};p.activeSlug=b_(d);let m=new Fa(P(n.stateDir??``,`flow-context`),()=>p.activeSlug),h=new xa;h.register(Di()),h.register(va),h.register(Li),h.register(sa),h.register(Pi),h.register(Oi),h.register(ki),h.register(ha),h.register(ji),h.register(ba),h.register(oa(()=>p.activeSlug?{active:!0,slug:p.activeSlug}:null));let g=new Ea(h,t.curated,{},m),_=l??Ss(n,[...qo,...Vo],ns,Uo(n)),v=e=>_.has(e),y=new Set([..._].filter(e=>!pp.includes(e)&&!to.has(e))),b=new ao;u.use(wa(g),{order:5,name:`auto-knowledge`}),u.use(No(),{order:10,name:`replay`}),u.use(co(b,{stateStore:t.stateStore,curatedStore:t.curated},{trackedTools:y}),{order:94,name:`procedural-memory`}),u.use(Za(new Ya(t.stateStore,t.curated)),{order:95,name:`observation-capture`}),u.use(Yo(),{order:1,name:`structured-content-guard`}),u.use(Pa(Na(n.tokenBudget)),{order:90,name:`compression`}),ss(e,u,n.toolPrefix??``);let x=[..._].filter(e=>Ho.has(e)?Bo.includes(e)?!!t.bridge:e===`er_update_policy`?!!t.policyStore:e===`er_evolve_review`?!!t.evolutionCollector:!1:!0);v(`search`)&&Eg(e,t.embedder,t.store,t.graphStore,t.bridge,t.evolutionCollector,a,t.stateStore,n.memory?.retention,n.memory?.consolidation,f);let S={store:t.store,graphStore:t.graphStore,embedder:t.embedder},C=c?e=>{c()?.prioritize(e)}:void 0;v(`lookup`)&&np(e,t.store,S);let w={onboardComplete:t.onboardComplete,onboardTimestamp:t.onboardTimestamp};v(`status`)&&c_(e,t.store,t.graphStore,t.curated,w,n,o,s,t.stateStore),v(`config`)&&_l(e,n),v(`reindex`)&&ig(e,t.indexer,n,t.curated,t.store,i,o),v(`knowledge`)&&ep(e,t.curated,t.policyStore,t.evolutionCollector,i,m,t.stateStore,n.memory?.retention,n.memory?.supersession,n.memory?.consolidation,n.memory?.lessons,S),v(`analyze`)&&Fc(e,t.store,t.embedder,S),v(`blast_radius`)&&Ic(e,t.store,t.embedder,t.graphStore,S),v(`produce_knowledge`)&&ng(e,n),v(`onboard`)&&Fp(e,t.store,t.embedder,n,w,S),v(`graph`)&&sd(e,t.graphStore,S),v(`audit`)&&Vc(e,t.store,t.embedder,n.tokenBudget),v(`compact`)&&Fl(e,t.embedder,t.fileCache,d,n.allRoots,S,C),v(`scope_map`)&&Il(e,t.embedder,t.store,S),v(`find`)&&Ll(e,t.embedder,t.store,d,S,f),v(`parse_output`)&&Zl(e),v(`workset`)&&Lp(e),v(`check`)&&Jl(e,S,n.tokenBudget),v(`symbol`)&&Rl(e,t.embedder,t.store,t.graphStore,S,f),v(`eval`)&&Yl(e),v(`test_run`)&&Xl(e,S),v(`stash`)&&Rp(e,t.stateStore),v(`signal`)&&Gg(e,t.stateStore),v(`git_context`)&&op(e),v(`diff_parse`)&&sp(e),v(`rename`)&&cp(e,n),v(`codemod`)&&lp(e,n),v(`restore`)&&cg(e),v(`file_summary`)&&zl(e,t.fileCache,d,n.allRoots,S,C),v(`checkpoint`)&&zp(e,t.stateStore),v(`data_transform`)&&up(e),v(`trace`)&&Bl(e,t.embedder,t.store,t.graphStore,S),v(`process`)&&ld(e),v(`watch`)&&ud(e),v(`dead_symbols`)&&Vl(e,t.embedder,t.store,d,n.allRoots,S),v(`delegate`)&&Ql(e,a),v(`health`)&&dd(e),v(`lane`)&&Bp(e),v(`queue`)&&Vp(e),v(`web_fetch`)&&fd(e),v(`guide`)&&pd(e,o),pp.some(e=>v(e))&&mp(e,n,x),v(`evidence_map`)&&$u(e),v(`digest`)&&ed(e,t.embedder),v(`forge_classify`)&&td(e,S),v(`stratum_card`)&&nd(e,t.embedder,t.fileCache),v(`forge_ground`)&&rd(e,t.embedder,t.store),v(`present`)&&eg(e,r),v(`browser`)&&Yn(e,n),v(`web_search`)&&d_(e),v(`http`)&&f_(e),v(`regex_test`)&&p_(e),v(`encode`)&&m_(e),v(`measure`)&&h_(e),v(`changelog`)&&g_(e),v(`schema_validate`)&&__(e),v(`env`)&&v_(e),v(`time`)&&y_(e),v(`flow`)&&Zu(e,n,{store:t.store?{search:async(e,n)=>(await t.store.ftsSearch(e,n)).map(e=>({content:e.record.content}))}:null,graphStore:t.graphStore,embedder:t.embedder},e=>{p.activeSlug=e}),t.bridge&&Bo.some(e=>v(e))&&(Gc(e,t.bridge,t.evolutionCollector),Kc(e,t.bridge),qc(e,t.bridge)),t.policyStore&&v(`er_update_policy`)&&qp(e,t.policyStore),t.evolutionCollector&&v(`er_evolve_review`)&&Kl(e,t.evolutionCollector),zo(e,t.store,t.curated),v(`compliance_score`)&&Xc(e),v(`replay`)&&og(e),v(`session_digest`)&&Og(e,t.stateStore,a)}function S_(e,t,n){let r=e=>!n||n.has(e);r(`check`)&&Jl(e,void 0,t.tokenBudget),r(`eval`)&&Yl(e),r(`test_run`)&&Xl(e),r(`parse_output`)&&Zl(e),r(`delegate`)&&Ql(e),r(`git_context`)&&op(e),r(`diff_parse`)&&sp(e),r(`rename`)&&cp(e,t),r(`codemod`)&&lp(e,t),r(`data_transform`)&&up(e),r(`workset`)&&Lp(e),r(`restore`)&&cg(e),r(`lane`)&&Bp(e),r(`queue`)&&Vp(e),r(`session_digest`)&&Og(e),r(`health`)&&dd(e),r(`process`)&&ld(e),r(`watch`)&&ud(e),r(`web_fetch`)&&fd(e),r(`guide`)&&pd(e),pp.some(e=>r(e))&&mp(e,t,[...n??new Set(qo)]),r(`evidence_map`)&&$u(e),r(`forge_classify`)&&td(e),r(`present`)&&eg(e),r(`browser`)&&Yn(e,t),r(`produce_knowledge`)&&ng(e),r(`compliance_score`)&&Xc(e),r(`replay`)&&og(e),r(`status`)&&s_(e),r(`flow`)&&Zu(e,t),r(`web_search`)&&d_(e),r(`http`)&&f_(e),r(`regex_test`)&&p_(e),r(`encode`)&&m_(e),r(`measure`)&&h_(e),r(`changelog`)&&g_(e),r(`schema_validate`)&&__(e),r(`env`)&&v_(e),r(`time`)&&y_(e)}const C_=I(`resource-notifier`);var w_=class{mcpServer;constructor(e){this.mcpServer=e}async notifyStatusChanged(){await this.sendUpdate(`aikit://status`)}async notifyFileTreeChanged(){await this.sendUpdate(`aikit://file-tree`)}async notifyCuratedIndexChanged(){await this.sendUpdate(`aikit://curated`)}async notifyCuratedEntryChanged(e){await this.sendUpdate(`aikit://curated/${e}`)}async notifyResourceListChanged(){try{await this.mcpServer.server.sendResourceListChanged()}catch(e){C_.debug(`sendResourceListChanged failed`,{error:String(e)})}}async notifyAfterReindex(){await Promise.allSettled([this.notifyStatusChanged(),this.notifyFileTreeChanged()])}async notifyAfterCuratedWrite(e){let t=[this.notifyStatusChanged(),this.notifyCuratedIndexChanged()];e&&t.push(this.notifyCuratedEntryChanged(e)),await Promise.allSettled(t)}async sendUpdate(e){try{await this.mcpServer.server.sendResourceUpdated({uri:e})}catch(t){C_.debug(`sendResourceUpdated failed`,{uri:e,error:String(t)})}}};const Z=I(`server`);function T_(e){let t=e?.trim().toLowerCase();return t===`1`||t===`true`||t===`yes`||t===`on`}async function E_(n){Z.info(`Initializing AI Kit components`);let r=n.store.backend,i=n.embedding,a={model:i.model,nativeDim:i.nativeDim??Te.nativeDim,dimensions:i.dimensions,queryPrefix:i.queryPrefix??Te.queryPrefix},o=n.store.path,s=T_(process.env.AIKIT_SPLIT_STATE),c=P(o,`aikit.db`),l={splitEnabled:s,contentDbPath:c,controlDbPath:s?P(o,`aikit-control.db`):c},u=null;if(r===`sqlite-vec`){let e=l.contentDbPath;j(o)||M(o,{recursive:!0}),u=await yr(e),Z.debug(`SQLite adapter ready`,{type:u.type,vectorCapable:u.vectorCapable,dbPath:e}),u.vectorCapable||Z.warn(`┌──────────────────────────────────────────────────────────────────┐
3014
3014
  │ ⚠ SQLite vector extension unavailable — DEGRADED MODE │
3015
3015
  │ Vector search is disabled. Hybrid search returns FTS only. │
3016
3016
  │ To enable: install/rebuild better-sqlite3 (native module). │
3017
- └──────────────────────────────────────────────────────────────────┘`);let t=P(o,`lance`);j(t)&&Z.info(`Old LanceDB data found at ${t} — ignored. Safe to delete after verifying sqlite-vec works.`)}let d;if(u)if(l.splitEnabled&&l.controlDbPath!==l.contentDbPath){let{migrateToSplitState:e}=await import(`../../store/dist/index.js`);await e(l),d=await yr(l.controlDbPath),Sr(d,vr),Z.info(`State store adapter ready`,{type:d.type,dbPath:l.controlDbPath,splitEnabled:!0})}else d=u;else{let e=P(o,`aikit-state.db`);j(o)||M(o,{recursive:!0}),d=await yr(e),Sr(d,vr),Z.info(`State store adapter ready`,{type:d.type,dbPath:e})}let[f,p,m,h]=await Promise.all([(async()=>{if(n.embedding.childProcess!==!1){let e=new Pr({model:a.model,dimensions:a.dimensions,nativeDim:a.nativeDim,queryPrefix:a.queryPrefix,interOpNumThreads:i.interOpNumThreads,intraOpNumThreads:i.intraOpNumThreads,idleTimeoutMs:i.idleTimeoutMs});return await e.initialize(),Z.debug(`Embedder loaded (child process)`,{modelId:e.modelId,dimensions:e.dimensions}),e}let{OnnxEmbedder:e}=await import(`../../embeddings/dist/index.js`),t=new e({model:a.model,dimensions:a.dimensions,nativeDim:a.nativeDim,queryPrefix:a.queryPrefix,interOpNumThreads:i.interOpNumThreads,intraOpNumThreads:i.intraOpNumThreads});return await t.initialize(),Z.debug(`Embedder loaded (in-process)`,{modelId:t.modelId,dimensions:t.dimensions}),t})(),(async()=>{let e=r===`sqlite-vec`?await xr({backend:r,path:o,adapter:u??void 0,embeddingDim:a.dimensions,embeddingProfile:a,partition:l}):await xr({backend:r,path:o,adapter:u??void 0,embeddingDim:a.dimensions,partition:void 0});return await e.initialize(),Z.debug(`Store initialized`,{backend:r}),e})(),(async()=>{let e=u?new _r({adapter:u}):new _r({path:o});return await e.initialize(),Z.debug(`Graph store initialized`,{shared:!!u}),e})(),(async()=>{let e=await or();if(e){let e=ir.get();Z.debug(`WASM tree-sitter enabled`,{grammars:e.grammarCount,dir:e.wasmDir})}else{let e=ir.get();Z.warn(`WASM tree-sitter not available; analyzers will use regex fallback`,{reason:e.reason,os:e.os,arch:e.arch,healAttempted:e.healAttempted,healSuccess:e.healSuccess,healError:e.healError,pathsChecked:e.pathsChecked.map(e=>`${e.path} (${e.exists?`found`:`missing`})`)})}return e})()]),g=new Ir(f,p),_=br(d),v=new Fr(n.store.path);v.load(),g.setHashCache(v);let y=n.curated.path,b=new e(y);await b.initialize();let x=new t(y,p,f,b);g.setGraphStore(m);let S=Wc(n.er),C=S?new ur(n.curated.path):void 0;C&&Z.debug(`Policy store initialized`,{ruleCount:C.getRules().length});let w=S?new lr:void 0,T=F(n.sources[0]?.path??process.cwd(),Se.aiContext),E=j(T),D=n.onboardDir?j(n.onboardDir):!1,O=E||D,k,ee=E?T:n.onboardDir;if(O&&ee)try{k=fe(ee).mtime.toISOString()}catch{}return Z.debug(`Onboard state detected`,{onboardComplete:O,onboardTimestamp:k,aiKbExists:E,onboardDirExists:D}),{embedder:f,store:p,stateStore:_,closeStateStore:d===u?void 0:async()=>d.close(),indexer:g,curated:x,graphStore:m,fileCache:new Ie,bridge:S,policyStore:C,evolutionCollector:w,onboardComplete:O,onboardTimestamp:k}}function E_(e,t,n){if(e.serverInstructions)return e.serverInstructions;let r=new Set;for(let e of t){let t=n[e];if(t?.category)for(let e of t.category)r.add(e)}let i=[`This server provides ${t.size} tools across ${r.size} categories: ${[...r].sort().join(`, `)}.`,`TOOL ROUTING:`,`- Understand a file -> file_summary (structure) or compact (extract section)`,`- Find code/symbols -> search (hybrid) or symbol (definition + refs)`,`- Validate changes -> check (typecheck+lint) or test_run (tests)`,`- Read file for editing -> read_file (only for exact lines before edits)`,`FORBIDDEN: DO NOT USE native equivalents when AI Kit provides same:`,`- grep/find -> search or find tool`,`- cat/read_file (for understanding) -> file_summary or compact`,`- terminal tsc/lint -> check tool`,`- terminal test -> test_run tool`];return e.readOnly&&i.push(`Server is in read-only mode. Mutating operations are disabled.`),e.features?.length&&i.push(`Active feature groups: ${e.features.join(`, `)}.`),i.join(`
3018
- `)}const D_=I(`background-task`);var O_=class{queue=[];running=null;get isRunning(){return this.running!==null}get currentTask(){return this.running}get pendingCount(){return this.queue.length}schedule(e){return new Promise((t,n)=>{this.queue.push({...e,resolve:t,reject:n}),this.running||this.processQueue()})}async processQueue(){for(;this.queue.length>0;){let e=this.queue.shift();if(!e)break;this.running=e.name,D_.info(`Background task started`,{task:e.name,pending:this.queue.length});let t=Date.now();try{await e.fn();let n=Date.now()-t;D_.info(`Background task completed`,{task:e.name,durationMs:n}),e.resolve()}catch(n){let r=Date.now()-t;D_.error(`Background task failed`,{task:e.name,durationMs:r,err:n}),e.reject(n instanceof Error?n:Error(String(n)))}}this.running=null}};const k_=I(`idle-timer`);var A_=class{timer=null;cleanupFns=[];idleMs;disposed=!1;sessionActive=!1;_busy=!1;constructor(e){this.idleMs=e?.idleMs??3e5}setBusy(e){this._busy=e,e?this.cancel():this.touch()}onIdle(e){this.cleanupFns.push(e)}markSessionActive(){this.sessionActive=!0}touch(){this.disposed||this._busy||(this.cancel(),this.timer=setTimeout(()=>{this.runCleanup()},this.idleMs),this.timer.unref&&this.timer.unref())}cancel(){this.timer&&=(clearTimeout(this.timer),null)}dispose(){this.cancel(),this.cleanupFns.length=0,this.disposed=!0}async runCleanup(){if(!this.sessionActive){k_.info(`Idle timeout reached with no active session — skipping cleanup (waiting for first tool call)`);return}if(this._busy){k_.info(`Skipping idle cleanup — background work in progress`);return}k_.info(`Idle for ${this.idleMs/1e3}s — running cleanup`);let e=await Promise.allSettled(this.cleanupFns.map(e=>e()));for(let t of e)t.status===`rejected`&&k_.warn(`Idle cleanup callback failed`,{error:String(t.reason)})}};const j_=I(`memory-monitor`);var M_=class{timer=null;warningBytes;criticalBytes;intervalMs;pressureFns=[];memoryPressureFns=[];lastLevel=`normal`;constructor(e){this.warningBytes=e?.warningBytes??4294967296,this.criticalBytes=e?.criticalBytes??8589934592,this.intervalMs=e?.intervalMs??6e4}onPressure(e){this.pressureFns.push(e)}registerMemoryPressureCallback(e){this.memoryPressureFns.push(e)}start(){this.timer||(this.timer=setInterval(()=>this.check(),this.intervalMs),this.timer.unref&&this.timer.unref(),j_.debug(`Memory monitor started`,{warningMB:Math.round(this.warningBytes/1024/1024),criticalMB:Math.round(this.criticalBytes/1024/1024),intervalSec:Math.round(this.intervalMs/1e3)}))}stop(){this.timer&&=(clearInterval(this.timer),null)}getRssBytes(){return process.memoryUsage.rss()}check(){let e=this.getRssBytes(),t=`normal`;if(e>=this.criticalBytes?t=`critical`:e>=this.warningBytes&&(t=`warning`),t!==this.lastLevel||t===`critical`){let n=Math.round(e/1024/1024);t===`critical`?j_.warn(`Memory CRITICAL: ${n}MB RSS — consider restarting the server`):t===`warning`?j_.warn(`Memory WARNING: ${n}MB RSS`):this.lastLevel!==`normal`&&j_.info(`Memory returned to normal: ${n}MB RSS`),this.lastLevel=t}if(t!==`normal`)for(let n of this.pressureFns)try{n(t,e)}catch{}if(t===`critical`)for(let e of this.memoryPressureFns)try{let t=e();t&&typeof t.catch==`function`&&t.catch(()=>{})}catch{}return t===`critical`&&typeof globalThis.gc==`function`&&globalThis.gc(),t}};const N_=I(`tool-timeout`),P_=new Set([`onboard`,`reindex`,`produce_knowledge`,`analyze`,`codemod`,`audit`]);var F_=class extends Error{toolName;timeoutMs;constructor(e,t){super(`Tool "${e}" timed out after ${t}ms`),this.toolName=e,this.timeoutMs=t,this.name=`ToolTimeoutError`}};function I_(e){return P_.has(e)?6e5:12e4}function L_(e,t,n){return new Promise((r,i)=>{let a=!1,o=setTimeout(()=>{if(!a){a=!0;let e=new F_(n,t);N_.warn(e.message),i(e)}},t);o.unref&&o.unref(),e().then(e=>{a||(a=!0,clearTimeout(o),r(e))},e=>{a||(a=!0,clearTimeout(o),i(e))})})}const Q=I(`server`),R_=new Set([`status`,`list_tools`,`describe_tool`,`config`,`env`,`present`]);function z_(e,t=28){let n=e.replace(/\s+/g,` `).trim();return n.length<=t?n:`${n.slice(0,t-3)}...`}function B_(e){let t=[`query`,`path`,`task`,`name`,`start`,`symbol`,`file`,`pattern`],n=[];for(let r of t){let t=e[r];typeof t==`string`&&t.length>0&&t.length<200&&n.push(t)}return n.join(` `).slice(0,200)}async function V_(e,t,n){let r=[];try{t.statePath&&ct(e.stateStore,{stateDir:t.statePath});let i=e.stateStore.stashList().map(e=>e.key);if(i.length>0){let e=n.toLowerCase().split(/\s+/).filter(e=>e.length>2);if(e.length===0)r.push(`stash: ${i.length} entries available`);else{let t=i.filter(t=>e.some(e=>t.toLowerCase().includes(e))).slice(0,3);t.length>0?r.push(`stash: ${t.map(e=>`"${z_(e)}"`).join(`, `)}${i.length>t.length?` (${i.length} total)`:``}`):r.push(`stash: ${i.length} entries available`)}}}catch{}try{if(n){let t=await Promise.race([e.store.ftsSearch(n,{limit:3}),new Promise(e=>setTimeout(()=>e(null),50))]);if(Array.isArray(t)&&t.length>0){let e=t.filter(e=>e&&typeof e==`object`&&`record`in e&&(e.record.origin===`produced`||e.record.origin===`curated`));if(e.length>0){let t=e.slice(0,2).map(e=>{let t=e.record;return`"${z_(t.headingPath||t.sourcePath||`knowledge`)}"`});r.push(`knowledge: ${t.join(`, `)}`)}}}}catch{}return r.length===0?null:`\n---\nContext available: ${r.join(` | `)}\nPull with: stash({action:'get', key:'...'}) or search({query:'...', origin:'produced'})\n---`}function H_(e,t,n){let r=3;for(let[i,a]of Object.entries(e)){let e=a.handler;a.handler=async(...a)=>{let o=await e(...a);if(!o||typeof o!=`object`||r<=0||o.isError||R_.has(i))return o;try{r--;let e=a[0],i=await V_(t,n,B_(e&&typeof e==`object`?e:{}));i&&(o.content=Array.isArray(o.content)?o.content:[],o.content.push({type:`text`,text:i}))}catch{}return o}}}function U_(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`,`cannot find module`,`cannot find package`,`module not found`].some(e=>t.includes(e))}function W_(e){return Tp(e)?[`Auto-heal tried to repair missing runtime dependency files in the npx install.`,`If this persists, clear the broken npx cache and restart:`,` npm cache clean --force`,` npx -y @vpxa/aikit@latest serve`].join(`
3017
+ └──────────────────────────────────────────────────────────────────┘`);let t=P(o,`lance`);j(t)&&Z.info(`Old LanceDB data found at ${t} — ignored. Safe to delete after verifying sqlite-vec works.`)}let d;if(u)if(l.splitEnabled&&l.controlDbPath!==l.contentDbPath){let{migrateToSplitState:e}=await import(`../../store/dist/index.js`);await e(l),d=await yr(l.controlDbPath),Sr(d,vr),Z.info(`State store adapter ready`,{type:d.type,dbPath:l.controlDbPath,splitEnabled:!0})}else d=u;else{let e=P(o,`aikit-state.db`);j(o)||M(o,{recursive:!0}),d=await yr(e),Sr(d,vr),Z.info(`State store adapter ready`,{type:d.type,dbPath:e})}let[f,p,m,h]=await Promise.all([(async()=>{if(n.embedding.childProcess!==!1){let e=new Pr({model:a.model,dimensions:a.dimensions,nativeDim:a.nativeDim,queryPrefix:a.queryPrefix,interOpNumThreads:i.interOpNumThreads,intraOpNumThreads:i.intraOpNumThreads,idleTimeoutMs:i.idleTimeoutMs});return await e.initialize(),Z.debug(`Embedder loaded (child process)`,{modelId:e.modelId,dimensions:e.dimensions}),e}let{OnnxEmbedder:e}=await import(`../../embeddings/dist/index.js`),t=new e({model:a.model,dimensions:a.dimensions,nativeDim:a.nativeDim,queryPrefix:a.queryPrefix,interOpNumThreads:i.interOpNumThreads,intraOpNumThreads:i.intraOpNumThreads});return await t.initialize(),Z.debug(`Embedder loaded (in-process)`,{modelId:t.modelId,dimensions:t.dimensions}),t})(),(async()=>{let e=r===`sqlite-vec`?await xr({backend:r,path:o,adapter:u??void 0,embeddingDim:a.dimensions,embeddingProfile:a,partition:l}):await xr({backend:r,path:o,adapter:u??void 0,embeddingDim:a.dimensions,partition:void 0});return await e.initialize(),Z.debug(`Store initialized`,{backend:r}),e})(),(async()=>{let e=u?new _r({adapter:u}):new _r({path:o});return await e.initialize(),Z.debug(`Graph store initialized`,{shared:!!u}),e})(),(async()=>{let e=await or();if(e){let e=ir.get();Z.debug(`WASM tree-sitter enabled`,{grammars:e.grammarCount,dir:e.wasmDir})}else{let e=ir.get();Z.warn(`WASM tree-sitter not available; analyzers will use regex fallback`,{reason:e.reason,os:e.os,arch:e.arch,healAttempted:e.healAttempted,healSuccess:e.healSuccess,healError:e.healError,pathsChecked:e.pathsChecked.map(e=>`${e.path} (${e.exists?`found`:`missing`})`)})}return e})()]),g=new Ir(f,p),_=br(d),v=new Fr(n.store.path);v.load(),g.setHashCache(v);let y=n.curated.path,b=new e(y);await b.initialize();let x=new t(y,p,f,b);g.setGraphStore(m);let S=Wc(n.er),C=S?new ur(n.curated.path):void 0;C&&Z.debug(`Policy store initialized`,{ruleCount:C.getRules().length});let w=S?new lr:void 0,T=F(n.sources[0]?.path??process.cwd(),Se.aiContext),E=j(T),D=n.onboardDir?j(n.onboardDir):!1,O=E||D,k,ee=E?T:n.onboardDir;if(O&&ee)try{k=fe(ee).mtime.toISOString()}catch{}return Z.debug(`Onboard state detected`,{onboardComplete:O,onboardTimestamp:k,aiKbExists:E,onboardDirExists:D}),{embedder:f,store:p,stateStore:_,closeStateStore:d===u?void 0:async()=>d.close(),indexer:g,curated:x,graphStore:m,fileCache:new Ie,bridge:S,policyStore:C,evolutionCollector:w,onboardComplete:O,onboardTimestamp:k}}function D_(e,t,n){if(e.serverInstructions)return e.serverInstructions;let r=new Set;for(let e of t){let t=n[e];if(t?.category)for(let e of t.category)r.add(e)}let i=[`This server provides ${t.size} tools across ${r.size} categories: ${[...r].sort().join(`, `)}.`,`TOOL ROUTING:`,`- Understand a file -> file_summary (structure) or compact (extract section)`,`- Find code/symbols -> search (hybrid) or symbol (definition + refs)`,`- Validate changes -> check (typecheck+lint) or test_run (tests)`,`- Read file for editing -> read_file (only for exact lines before edits)`,`FORBIDDEN: DO NOT USE native equivalents when AI Kit provides same:`,`- grep/find -> search or find tool`,`- cat/read_file (for understanding) -> file_summary or compact`,`- terminal tsc/lint -> check tool`,`- terminal test -> test_run tool`];return e.readOnly&&i.push(`Server is in read-only mode. Mutating operations are disabled.`),e.features?.length&&i.push(`Active feature groups: ${e.features.join(`, `)}.`),i.join(`
3018
+ `)}const O_=I(`background-task`);var k_=class{queue=[];running=null;get isRunning(){return this.running!==null}get currentTask(){return this.running}get pendingCount(){return this.queue.length}schedule(e){return new Promise((t,n)=>{this.queue.push({...e,resolve:t,reject:n}),this.running||this.processQueue()})}async processQueue(){for(;this.queue.length>0;){let e=this.queue.shift();if(!e)break;this.running=e.name,O_.info(`Background task started`,{task:e.name,pending:this.queue.length});let t=Date.now();try{await e.fn();let n=Date.now()-t;O_.info(`Background task completed`,{task:e.name,durationMs:n}),e.resolve()}catch(n){let r=Date.now()-t;O_.error(`Background task failed`,{task:e.name,durationMs:r,err:n}),e.reject(n instanceof Error?n:Error(String(n)))}}this.running=null}};const A_=I(`idle-timer`);var j_=class{timer=null;cleanupFns=[];idleMs;disposed=!1;sessionActive=!1;_busy=!1;constructor(e){this.idleMs=e?.idleMs??3e5}setBusy(e){this._busy=e,e?this.cancel():this.touch()}onIdle(e){this.cleanupFns.push(e)}markSessionActive(){this.sessionActive=!0}touch(){this.disposed||this._busy||(this.cancel(),this.timer=setTimeout(()=>{this.runCleanup()},this.idleMs),this.timer.unref&&this.timer.unref())}cancel(){this.timer&&=(clearTimeout(this.timer),null)}dispose(){this.cancel(),this.cleanupFns.length=0,this.disposed=!0}async runCleanup(){if(!this.sessionActive){A_.info(`Idle timeout reached with no active session — skipping cleanup (waiting for first tool call)`);return}if(this._busy){A_.info(`Skipping idle cleanup — background work in progress`);return}A_.info(`Idle for ${this.idleMs/1e3}s — running cleanup`);let e=await Promise.allSettled(this.cleanupFns.map(e=>e()));for(let t of e)t.status===`rejected`&&A_.warn(`Idle cleanup callback failed`,{error:String(t.reason)})}};const M_=I(`memory-monitor`);var N_=class{timer=null;warningBytes;criticalBytes;intervalMs;pressureFns=[];memoryPressureFns=[];lastLevel=`normal`;constructor(e){this.warningBytes=e?.warningBytes??4294967296,this.criticalBytes=e?.criticalBytes??8589934592,this.intervalMs=e?.intervalMs??6e4}onPressure(e){this.pressureFns.push(e)}registerMemoryPressureCallback(e){this.memoryPressureFns.push(e)}start(){this.timer||(this.timer=setInterval(()=>this.check(),this.intervalMs),this.timer.unref&&this.timer.unref(),M_.debug(`Memory monitor started`,{warningMB:Math.round(this.warningBytes/1024/1024),criticalMB:Math.round(this.criticalBytes/1024/1024),intervalSec:Math.round(this.intervalMs/1e3)}))}stop(){this.timer&&=(clearInterval(this.timer),null)}getRssBytes(){return process.memoryUsage.rss()}check(){let e=this.getRssBytes(),t=`normal`;if(e>=this.criticalBytes?t=`critical`:e>=this.warningBytes&&(t=`warning`),t!==this.lastLevel||t===`critical`){let n=Math.round(e/1024/1024);t===`critical`?M_.warn(`Memory CRITICAL: ${n}MB RSS — consider restarting the server`):t===`warning`?M_.warn(`Memory WARNING: ${n}MB RSS`):this.lastLevel!==`normal`&&M_.info(`Memory returned to normal: ${n}MB RSS`),this.lastLevel=t}if(t!==`normal`)for(let n of this.pressureFns)try{n(t,e)}catch{}if(t===`critical`)for(let e of this.memoryPressureFns)try{let t=e();t&&typeof t.catch==`function`&&t.catch(()=>{})}catch{}return t===`critical`&&typeof globalThis.gc==`function`&&globalThis.gc(),t}};const P_=I(`tool-timeout`),F_=new Set([`onboard`,`reindex`,`produce_knowledge`,`analyze`,`codemod`,`audit`]);var I_=class extends Error{toolName;timeoutMs;constructor(e,t){super(`Tool "${e}" timed out after ${t}ms`),this.toolName=e,this.timeoutMs=t,this.name=`ToolTimeoutError`}};function L_(e){return F_.has(e)?6e5:12e4}function R_(e,t,n){return new Promise((r,i)=>{let a=!1,o=setTimeout(()=>{if(!a){a=!0;let e=new I_(n,t);P_.warn(e.message),i(e)}},t);o.unref&&o.unref(),e().then(e=>{a||(a=!0,clearTimeout(o),r(e))},e=>{a||(a=!0,clearTimeout(o),i(e))})})}const Q=I(`server`),z_=new Set([`status`,`list_tools`,`describe_tool`,`config`,`env`,`present`]);function B_(e,t=28){let n=e.replace(/\s+/g,` `).trim();return n.length<=t?n:`${n.slice(0,t-3)}...`}function V_(e){let t=[`query`,`path`,`task`,`name`,`start`,`symbol`,`file`,`pattern`],n=[];for(let r of t){let t=e[r];typeof t==`string`&&t.length>0&&t.length<200&&n.push(t)}return n.join(` `).slice(0,200)}async function H_(e,t,n){let r=[];try{t.statePath&&ct(e.stateStore,{stateDir:t.statePath});let i=e.stateStore.stashList().map(e=>e.key);if(i.length>0){let e=n.toLowerCase().split(/\s+/).filter(e=>e.length>2);if(e.length===0)r.push(`stash: ${i.length} entries available`);else{let t=i.filter(t=>e.some(e=>t.toLowerCase().includes(e))).slice(0,3);t.length>0?r.push(`stash: ${t.map(e=>`"${B_(e)}"`).join(`, `)}${i.length>t.length?` (${i.length} total)`:``}`):r.push(`stash: ${i.length} entries available`)}}}catch{}try{if(n){let t=await Promise.race([e.store.ftsSearch(n,{limit:3}),new Promise(e=>setTimeout(()=>e(null),50))]);if(Array.isArray(t)&&t.length>0){let e=t.filter(e=>e&&typeof e==`object`&&`record`in e&&(e.record.origin===`produced`||e.record.origin===`curated`));if(e.length>0){let t=e.slice(0,2).map(e=>{let t=e.record;return`"${B_(t.headingPath||t.sourcePath||`knowledge`)}"`});r.push(`knowledge: ${t.join(`, `)}`)}}}}catch{}return r.length===0?null:`\n---\nContext available: ${r.join(` | `)}\nPull with: stash({action:'get', key:'...'}) or search({query:'...', origin:'produced'})\n---`}function U_(e,t,n){let r=3;for(let[i,a]of Object.entries(e)){let e=a.handler;a.handler=async(...a)=>{let o=await e(...a);if(!o||typeof o!=`object`||r<=0||o.isError||z_.has(i))return o;try{r--;let e=a[0],i=await H_(t,n,V_(e&&typeof e==`object`?e:{}));i&&(o.content=Array.isArray(o.content)?o.content:[],o.content.push({type:`text`,text:i}))}catch{}return o}}}function W_(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`,`cannot find module`,`cannot find package`,`module not found`].some(e=>t.includes(e))}function G_(e){return Tp(e)?[`Auto-heal tried to repair missing runtime dependency files in the npx install.`,`If this persists, clear the broken npx cache and restart:`,` npm cache clean --force`,` npx -y @vpxa/aikit@latest serve`].join(`
3019
3019
  `):[`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.`].join(`
3020
- `)}async function G_(e,t){let n=t.toLowerCase(),r;try{({rm:r}=await import(`node:fs/promises`))}catch{return}if(n.includes(`transformers.node.mjs`)&&n.includes(`cannot find module`)){let e=t.match(/Cannot find module '([^']+transformers\.node\.mjs)'/);if(e){let t=e[1],n=t.replace(/\.mjs$/,`.cjs`);try{let{existsSync:e,writeFileSync:r}=await import(`node:fs`);e(n)&&!e(t)&&(r(t,[`// Auto-generated ESM shim — published package missing this file`,`import { createRequire } from 'node:module';`,`const require = createRequire(import.meta.url);`,`const mod = require('./transformers.node.cjs');`,`export default mod;`,``].join(`
3021
- `),`utf8`),Q.info(`Auto-heal: created ESM shim for @huggingface/transformers (.mjs wrapper → .cjs)`,{path:t}))}catch(e){Q.warn(`Auto-heal: failed to create ESM shim`,{error:e instanceof Error?e.message:String(e),path:t})}}}if(n.includes(`embedding`)||n.includes(`onnx`)||n.includes(`protobuf`)||n.includes(`model`)){let t=e.embedding?.model;if(t){let e=P(Bn(),`.cache`,`huggingface`,`transformers-js`,t);try{await r(e,{recursive:!0,force:!0}),Q.info(`Auto-heal: cleared embedding model cache`,{path:e})}catch{}}}if(n.includes(`lance`)||n.includes(`database`)||n.includes(`store`)){let t=P(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=P(e.store.path,`graph.db`);try{await r(t,{force:!0}),Q.info(`Auto-heal: cleared graph database`,{path:t})}catch{}let n=P(e.store.path,`aikit.db`);try{await r(n,{force:!0}),await r(`${n}-wal`,{force:!0}).catch(()=>{}),await r(`${n}-shm`,{force:!0}).catch(()=>{}),Q.info(`Auto-heal: cleared corrupted aikit database`,{path:n})}catch{}}if(Tp(t)){let e=await Op(t);e.repaired||Q.warn(`Auto-heal: missing runtime dependency repair did not complete`,{packages:e.packages,reason:e.reason,error:e.error,hint:`Run: npm cache clean --force && npx -y @vpxa/aikit@latest serve`})}else n.includes(`cannot find module`)&&!n.includes(`.cache`)&&Q.warn(`Auto-heal: missing module detected during initialization cleanup`,{hint:`Run: npm cache clean --force && npx -y @vpxa/aikit@latest serve`})}function K_(e,t){let n=Ss(e,qo,ns,Uo(e)),r=E_(e,n,ns),i=new Hn({name:e.serverName??`aikit`,version:re()},{capabilities:{logging:{},completions:{},prompts:{}},instructions:r}),a=`initializing`,o=``,s=!1,c=null,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=()=>a===`failed`?[`❌ AI Kit initialization failed — this tool is unavailable.`,``,o?`Error: ${o}`:``,``,`**${Ko.size} tools are still available** and fully functional:`,`check, eval, test_run, git_context, health, measure, web_fetch, web_search,`,`flow, regex_test, encode,`,`stash, checkpoint, lane, process, time, env, and more.`,``,W_(o),``,`Try restarting the MCP server to retry initialization.`].filter(Boolean).join(`
3020
+ `)}async function K_(e,t){let n=t.toLowerCase(),r;try{({rm:r}=await import(`node:fs/promises`))}catch{return}if(n.includes(`transformers.node.mjs`)&&n.includes(`cannot find module`)){let e=t.match(/Cannot find module '([^']+transformers\.node\.mjs)'/);if(e){let t=e[1],n=t.replace(/\.mjs$/,`.cjs`);try{let{existsSync:e,writeFileSync:r}=await import(`node:fs`);e(n)&&!e(t)&&(r(t,[`// Auto-generated ESM shim — published package missing this file`,`import { createRequire } from 'node:module';`,`const require = createRequire(import.meta.url);`,`const mod = require('./transformers.node.cjs');`,`export default mod;`,``].join(`
3021
+ `),`utf8`),Q.info(`Auto-heal: created ESM shim for @huggingface/transformers (.mjs wrapper → .cjs)`,{path:t}))}catch(e){Q.warn(`Auto-heal: failed to create ESM shim`,{error:e instanceof Error?e.message:String(e),path:t})}}}if(n.includes(`embedding`)||n.includes(`onnx`)||n.includes(`protobuf`)||n.includes(`model`)){let t=e.embedding?.model;if(t){let e=P(Bn(),`.cache`,`huggingface`,`transformers-js`,t);try{await r(e,{recursive:!0,force:!0}),Q.info(`Auto-heal: cleared embedding model cache`,{path:e})}catch{}}}if(n.includes(`lance`)||n.includes(`database`)||n.includes(`store`)){let t=P(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=P(e.store.path,`graph.db`);try{await r(t,{force:!0}),Q.info(`Auto-heal: cleared graph database`,{path:t})}catch{}let n=P(e.store.path,`aikit.db`);try{await r(n,{force:!0}),await r(`${n}-wal`,{force:!0}).catch(()=>{}),await r(`${n}-shm`,{force:!0}).catch(()=>{}),Q.info(`Auto-heal: cleared corrupted aikit database`,{path:n})}catch{}}if(Tp(t)){let e=await Op(t);e.repaired||Q.warn(`Auto-heal: missing runtime dependency repair did not complete`,{packages:e.packages,reason:e.reason,error:e.error,hint:`Run: npm cache clean --force && npx -y @vpxa/aikit@latest serve`})}else n.includes(`cannot find module`)&&!n.includes(`.cache`)&&Q.warn(`Auto-heal: missing module detected during initialization cleanup`,{hint:`Run: npm cache clean --force && npx -y @vpxa/aikit@latest serve`})}function q_(e,t){let n=Ss(e,qo,ns,Uo(e)),r=D_(e,n,ns),i=new Hn({name:e.serverName??`aikit`,version:re()},{capabilities:{logging:{},completions:{},prompts:{}},instructions:r}),a=`initializing`,o=``,s=!1,c=null,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=()=>a===`failed`?[`❌ AI Kit initialization failed — this tool is unavailable.`,``,o?`Error: ${o}`:``,``,`**${Ko.size} tools are still available** and fully functional:`,`check, eval, test_run, git_context, health, measure, web_fetch, web_search,`,`flow, regex_test, encode,`,`stash, checkpoint, lane, process, time, env, and more.`,``,G_(o),``,`Try restarting the MCP server to retry initialization.`].filter(Boolean).join(`
3022
3022
  `):[`AI Kit is still initializing (loading embeddings model & store).`,``,`**${Ko.size} tools are already available** while initialization completes — including:`,`check, eval, test_run, git_context, health, measure, web_fetch, web_search,`,`flow, 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(`
3023
- `);zr(i);let p=new go;p.use(Yo(),{order:1,name:`structured-content-guard`}),ss(i,p,e.toolPrefix??``);let m=i.sendToolListChanged.bind(i);i.sendToolListChanged=()=>{};let h=[];for(let e of qo){if(!n.has(e))continue;let t=W(e),r=i.registerTool(e,{title:t.title,description:`${t.title} — initializing, available shortly`,inputSchema:{},annotations:t.annotations},async()=>({content:[{type:`text`,text:f()}]}));Ko.has(e)?r.remove():h.push(r)}x_(i,e,n),i.sendToolListChanged=m;let g=i.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`}]})),_=i.registerPrompt(`_init`,{description:`Initializing AI Kit…`,argsSchema:{_dummy:qn(z.string(),()=>[])}},async()=>({messages:[]})),v,y,b=new Promise((e,t)=>{v=e,y=t}),x,S=new Promise(e=>{x=e}),C=()=>x?.(),w=(async()=>{await S;try{let{createRequire:e}=await import(`node:module`),{readFileSync:t,existsSync:n}=await import(`node:fs`),{fileURLToPath:r}=await import(`node:url`),{resolve:i,dirname:a}=await import(`node:path`),o=e(import.meta.url),s=a(r(import.meta.url)),c=i(s,`..`,`package.json`),l=i(s,`..`,`..`),u=JSON.parse(t(c,`utf8`)),d=Object.keys(u.dependencies??{}),f=[`@mixmark-io/domino`],p=[...d,...f.filter(e=>!d.includes(e))],m=p.filter(e=>!e.startsWith(`@aikit/`)),h=p.filter(e=>e.startsWith(`@aikit/`)),g=[];for(let e of m)try{o.resolve(e)}catch{try{o.resolve(`${e}/package.json`)}catch{g.push(e)}}g.length>0&&Q.warn(`Dependencies not resolvable — server may operate in degraded mode`,{missing:g,hint:`Run: npm cache clean --force && npx -y @vpxa/aikit@latest serve`});let _=[];if(h.length>0){for(let e of h)n(i(l,e.slice(7),`dist`))||_.push(e);_.length>0&&Q.warn(`Workspace sibling packages missing dist — server may have degraded features`,{missing:_,hint:`Reinstall: npm cache clean --force && npx -y @vpxa/aikit@latest serve`})}}catch{}let n;try{n=await T_(e)}catch(t){let r=t instanceof Error?t.message:String(t);if(U_(r)){Q.warn(`AI Kit initialization failed with recoverable error — attempting auto-heal retry`,{error:r}),await G_(e,r);try{n=await T_(e),Q.info(`AI Kit auto-heal successful — initialization recovered after retry`)}catch(e){a=`failed`,o=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:o,originalError:r}),y?.(e instanceof Error?e:Error(o));return}}else{a=`failed`,o=r,Q.error(`AI Kit initialization failed — server continuing with zero-dep tools only`,{error:o}),y?.(t instanceof Error?t:Error(o));return}}let r=i.sendToolListChanged.bind(i);i.sendToolListChanged=()=>{};let f=i.sendPromptListChanged.bind(i);i.sendPromptListChanged=()=>{};let p=i.sendResourceListChanged.bind(i);i.sendResourceListChanged=()=>{};for(let e of h)e.remove();g.remove(),_.remove();let m=i._registeredTools??{};for(let e of Ko)m[e]?.remove();let b=new C_(i),x=ru(i);b_(i,n,e,Lr(i),b,x,t,t===`smart`?(()=>{let e=u;return e?.getState?e.getState():null}):null,t===`smart`?()=>{let e=u;return e?{prioritize:e.prioritize.bind(e)}:null}:null),Xr(i,{curated:n.curated,store:n.store,graphStore:n.graphStore,stateStore:n.stateStore},t),i.sendToolListChanged=r,i.sendPromptListChanged=f,i.sendResourceListChanged=p,Promise.resolve(i.sendToolListChanged()).catch(()=>{}),Promise.resolve(i.sendPromptListChanged()).catch(()=>{}),Promise.resolve(i.sendResourceListChanged()).catch(()=>{});let C=i._registeredTools??{};for(let[e,t]of Object.entries(C)){if(Wo.has(e))continue;let r=t.handler;t.handler=async(...i)=>{if(!n.indexer.isIndexing)return r(...i);let a=s?`re-indexing`:`running initial index`,o=new Promise(n=>setTimeout(()=>n({content:[{type:`text`,text:`⏳ AI Kit is ${a}. The tool "${e}" timed out waiting for index data (${Go/1e3}s).\n\nThe existing index may be temporarily locked. Please retry shortly — indexing will complete automatically.`}],...t.config?.outputSchema?{structuredContent:ts(t.config.outputSchema)}:{}}),Go));return Promise.race([r(...i),o])}}for(let[e,t]of Object.entries(C)){let n=t.handler,r=I_(e);t.handler=async(...i)=>{try{return await L_(()=>n(...i),r,e)}catch(n){if(n instanceof F_)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.`}],...t.config?.outputSchema?{structuredContent:ts(t.config.outputSchema)}:{}};throw n}}}let w=Object.keys(C).length;w<qo.length&&Q.warn(`ALL_TOOL_NAMES count mismatch`,{expectedToolCount:qo.length,registeredToolCount:w}),Q.debug(`MCP server configured`,{toolCount:qo.length,resourceCount:4});let T=new M_;T.onPressure((e,t)=>{e===`warning`&&Ur(),e===`critical`&&(Q.warn(`Memory pressure critical — consider restarting`,{rssMB:Math.round(t/1024/1024)}),Ur())}),T.registerMemoryPressureCallback(()=>n.embedder.shutdown?.()),T.start();let D=new A_;l=D,D.onIdle(async()=>{if(E.isRunning||n.indexer.isIndexing){Q.info(`Idle cleanup deferred — background tasks still running`),D.touch();return}Q.info(`Idle cleanup: releasing cached memory (connections stay open)`);try{n.store.releaseMemory?.(),n.graphStore.releaseMemory?.()}catch{}}),D.touch();let O=!1;for(let e of Object.values(C)){let t=e.handler;e.handler=async(...e)=>{if(O||(O=!0,D.markSessionActive()),D.touch(),u){let t=d(e[0]);t.length>0&&u.prioritize(...t)}return t(...e)}}H_(C,n,{statePath:e.stateDir??``});for(let[,e]of Object.entries(C)){let t=e.config?.outputSchema;if(!t)continue;let n=e.handler;e.handler=async(...e)=>{let r=await n(...e);if(!r||typeof r!=`object`)return r;let i=r;return!(`content`in i)||i.isError||i.structuredContent!=null&&typeof i.structuredContent==`object`?r:(i.structuredContent=ts(t),i.structuredContent??={},r)}}process.stdin.on(`end`,()=>(Q.info(`stdin closed — MCP client disconnected. Shutting down.`),process.exit(0))),process.stdin.on(`error`,()=>(Q.info(`stdin error — MCP client disconnected. Shutting down.`),process.exit(0))),c=n,v?.(n)})(),T=async()=>{let t;try{t=await b}catch{Q.warn(`Skipping initial index — AI Kit initialization failed`);return}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}))});s=!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`,L(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`,L(e))}}catch(e){Q.error(`Initial index failed; will retry on aikit_reindex`,L(e))}finally{l?.setBusy(!1)}},E=new O_,D=()=>E.schedule({name:`initial-index`,fn:T}),O=process.ppid,k=setInterval(()=>{try{process.kill(O,0)}catch{Q.info(`Parent process died; shutting down`,{parentPid:O}),clearInterval(k),u?.stop&&u.stop(),import(`../../tools/dist/index.js`).then(({processStopAll:e})=>e()).catch(()=>{}),b.then(async e=>{await Promise.all([e.embedder.shutdown?.().catch(()=>{})??Promise.resolve(),e.graphStore.close().catch(()=>{}),e.closeStateStore?.().catch(()=>{})??Promise.resolve(),e.store.close().catch(()=>{})])}).catch(()=>{}).finally(()=>process.exit(0))}},5e3);return k.unref(),{server:i,startInit:C,ready:w,runInitialIndex:D,get aikit(){return c},scheduler:E,setSmartScheduler(e){u=e}}}const $=I(`server`);function q_(e,t){let n=Ss(t,[...qo,...Vo],ns,Uo(t)),r=E_(t,n,ns),i=new Hn({name:t.serverName??`aikit`,version:re()},{capabilities:{logging:{},completions:{},prompts:{}},instructions:r});return zr(i),b_(i,e,t,Lr(i),new C_(i),ru(i),void 0,null,null,n),Xr(i,{curated:e.curated,store:e.store,graphStore:e.graphStore,stateStore:e.stateStore},t.indexMode),i}async function J_(e){let t=await T_(e),n=q_(t,e);$.debug(`MCP server configured`,{toolCount:qo.length,resourceCount:2});let r=async()=>{try{let n=e.sources.map(e=>e.path).join(`, `);$.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&&$.debug(`Indexing file`,{current:e.filesProcessed+1,total:e.filesTotal,file:e.currentFile}),e.phase===`cleanup`&&$.debug(`Index cleanup`,{staleEntries:e.filesTotal-e.filesProcessed}))});$.info(`Initial index complete`,{filesProcessed:r.filesProcessed,filesSkipped:r.filesSkipped,chunksCreated:r.chunksCreated,durationMs:r.durationMs});try{await t.store.createFtsIndex()}catch(e){$.warn(`FTS index creation failed`,L(e))}try{let e=await t.curated.reindexAll();$.info(`Curated re-index complete`,{indexed:e.indexed})}catch(e){$.error(`Curated re-index failed`,L(e))}}catch(e){$.error(`Initial index failed; will retry on aikit_reindex`,L(e))}},i=async()=>{$.info(`Shutting down`),await Promise.all([t.embedder.shutdown?.().catch(()=>{})??Promise.resolve(),t.graphStore.close().catch(()=>{}),t.closeStateStore?.().catch(()=>{})??Promise.resolve(),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{$.info(`Parent process died; shutting down`,{parentPid:a}),clearInterval(o),i()}},5e3);return o.unref(),{server:n,runInitialIndex:r,shutdown:i}}export{qo as ALL_TOOL_NAMES,K_ as createLazyServer,q_ as createMcpServer,J_ as createServer,T_ as initializeAikit,b_ as registerMcpTools};
3023
+ `);zr(i);let p=new go;p.use(Yo(),{order:1,name:`structured-content-guard`}),ss(i,p,e.toolPrefix??``);let m=i.sendToolListChanged.bind(i);i.sendToolListChanged=()=>{};let h=[];for(let e of qo){if(!n.has(e))continue;let t=W(e),r=i.registerTool(e,{title:t.title,description:`${t.title} — initializing, available shortly`,inputSchema:{},annotations:t.annotations},async()=>({content:[{type:`text`,text:f()}]}));Ko.has(e)?r.remove():h.push(r)}S_(i,e,n),i.sendToolListChanged=m;let g=i.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`}]})),_=i.registerPrompt(`_init`,{description:`Initializing AI Kit…`,argsSchema:{_dummy:qn(z.string(),()=>[])}},async()=>({messages:[]})),v,y,b=new Promise((e,t)=>{v=e,y=t}),x,S=new Promise(e=>{x=e}),C=()=>x?.(),w=(async()=>{await S;try{let{createRequire:e}=await import(`node:module`),{readFileSync:t,existsSync:n}=await import(`node:fs`),{fileURLToPath:r}=await import(`node:url`),{resolve:i,dirname:a}=await import(`node:path`),o=e(import.meta.url),s=a(r(import.meta.url)),c=i(s,`..`,`package.json`),l=i(s,`..`,`..`),u=JSON.parse(t(c,`utf8`)),d=Object.keys(u.dependencies??{}),f=[`@mixmark-io/domino`],p=[...d,...f.filter(e=>!d.includes(e))],m=p.filter(e=>!e.startsWith(`@aikit/`)),h=p.filter(e=>e.startsWith(`@aikit/`)),g=[];for(let e of m)try{o.resolve(e)}catch{try{o.resolve(`${e}/package.json`)}catch{g.push(e)}}g.length>0&&Q.warn(`Dependencies not resolvable — server may operate in degraded mode`,{missing:g,hint:`Run: npm cache clean --force && npx -y @vpxa/aikit@latest serve`});let _=[];if(h.length>0){for(let e of h)n(i(l,e.slice(7),`dist`))||_.push(e);_.length>0&&Q.warn(`Workspace sibling packages missing dist — server may have degraded features`,{missing:_,hint:`Reinstall: npm cache clean --force && npx -y @vpxa/aikit@latest serve`})}}catch{}let n;try{n=await E_(e)}catch(t){let r=t instanceof Error?t.message:String(t);if(W_(r)){Q.warn(`AI Kit initialization failed with recoverable error — attempting auto-heal retry`,{error:r}),await K_(e,r);try{n=await E_(e),Q.info(`AI Kit auto-heal successful — initialization recovered after retry`)}catch(e){a=`failed`,o=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:o,originalError:r}),y?.(e instanceof Error?e:Error(o));return}}else{a=`failed`,o=r,Q.error(`AI Kit initialization failed — server continuing with zero-dep tools only`,{error:o}),y?.(t instanceof Error?t:Error(o));return}}let r=i.sendToolListChanged.bind(i);i.sendToolListChanged=()=>{};let f=i.sendPromptListChanged.bind(i);i.sendPromptListChanged=()=>{};let p=i.sendResourceListChanged.bind(i);i.sendResourceListChanged=()=>{};for(let e of h)e.remove();g.remove(),_.remove();let m=i._registeredTools??{};for(let e of Ko)m[e]?.remove();let b=new w_(i),x=ru(i);x_(i,n,e,Lr(i),b,x,t,t===`smart`?(()=>{let e=u;return e?.getState?e.getState():null}):null,t===`smart`?()=>{let e=u;return e?{prioritize:e.prioritize.bind(e)}:null}:null),Xr(i,{curated:n.curated,store:n.store,graphStore:n.graphStore,stateStore:n.stateStore},t),i.sendToolListChanged=r,i.sendPromptListChanged=f,i.sendResourceListChanged=p,Promise.resolve(i.sendToolListChanged()).catch(()=>{}),Promise.resolve(i.sendPromptListChanged()).catch(()=>{}),Promise.resolve(i.sendResourceListChanged()).catch(()=>{});let C=i._registeredTools??{};for(let[e,t]of Object.entries(C)){if(Wo.has(e))continue;let r=t.handler;t.handler=async(...i)=>{if(!n.indexer.isIndexing)return r(...i);let a=s?`re-indexing`:`running initial index`,o=new Promise(n=>setTimeout(()=>n({content:[{type:`text`,text:`⏳ AI Kit is ${a}. The tool "${e}" timed out waiting for index data (${Go/1e3}s).\n\nThe existing index may be temporarily locked. Please retry shortly — indexing will complete automatically.`}],...t.config?.outputSchema?{structuredContent:ts(t.config.outputSchema)}:{}}),Go));return Promise.race([r(...i),o])}}for(let[e,t]of Object.entries(C)){let n=t.handler,r=L_(e);t.handler=async(...i)=>{try{return await R_(()=>n(...i),r,e)}catch(n){if(n instanceof I_)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.`}],...t.config?.outputSchema?{structuredContent:ts(t.config.outputSchema)}:{}};throw n}}}let w=Object.keys(C).length;w<qo.length&&Q.warn(`ALL_TOOL_NAMES count mismatch`,{expectedToolCount:qo.length,registeredToolCount:w}),Q.debug(`MCP server configured`,{toolCount:qo.length,resourceCount:4});let T=new N_;T.onPressure((e,t)=>{e===`warning`&&Ur(),e===`critical`&&(Q.warn(`Memory pressure critical — consider restarting`,{rssMB:Math.round(t/1024/1024)}),Ur())}),T.registerMemoryPressureCallback(()=>n.embedder.shutdown?.()),T.start();let D=new j_;l=D,D.onIdle(async()=>{if(E.isRunning||n.indexer.isIndexing){Q.info(`Idle cleanup deferred — background tasks still running`),D.touch();return}Q.info(`Idle cleanup: releasing cached memory (connections stay open)`);try{n.store.releaseMemory?.(),n.graphStore.releaseMemory?.()}catch{}}),D.touch();let O=!1;for(let e of Object.values(C)){let t=e.handler;e.handler=async(...e)=>{if(O||(O=!0,D.markSessionActive()),D.touch(),u){let t=d(e[0]);t.length>0&&u.prioritize(...t)}return t(...e)}}U_(C,n,{statePath:e.stateDir??``});for(let[,e]of Object.entries(C)){let t=e.config?.outputSchema;if(!t)continue;let n=e.handler;e.handler=async(...e)=>{let r=await n(...e);if(!r||typeof r!=`object`)return r;let i=r;return!(`content`in i)||i.isError||i.structuredContent!=null&&typeof i.structuredContent==`object`?r:(i.structuredContent=ts(t),i.structuredContent??={},r)}}process.stdin.on(`end`,()=>(Q.info(`stdin closed — MCP client disconnected. Shutting down.`),process.exit(0))),process.stdin.on(`error`,()=>(Q.info(`stdin error — MCP client disconnected. Shutting down.`),process.exit(0))),c=n,v?.(n)})(),T=async()=>{let t;try{t=await b}catch{Q.warn(`Skipping initial index — AI Kit initialization failed`);return}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}))});s=!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`,L(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`,L(e))}}catch(e){Q.error(`Initial index failed; will retry on aikit_reindex`,L(e))}finally{l?.setBusy(!1)}},E=new k_,D=()=>E.schedule({name:`initial-index`,fn:T}),O=process.ppid,k=setInterval(()=>{try{process.kill(O,0)}catch{Q.info(`Parent process died; shutting down`,{parentPid:O}),clearInterval(k),u?.stop&&u.stop(),import(`../../tools/dist/index.js`).then(({processStopAll:e})=>e()).catch(()=>{}),b.then(async e=>{await Promise.all([e.embedder.shutdown?.().catch(()=>{})??Promise.resolve(),e.graphStore.close().catch(()=>{}),e.closeStateStore?.().catch(()=>{})??Promise.resolve(),e.store.close().catch(()=>{})])}).catch(()=>{}).finally(()=>process.exit(0))}},5e3);return k.unref(),{server:i,startInit:C,ready:w,runInitialIndex:D,get aikit(){return c},scheduler:E,setSmartScheduler(e){u=e}}}const $=I(`server`);function J_(e,t){let n=Ss(t,[...qo,...Vo],ns,Uo(t)),r=D_(t,n,ns),i=new Hn({name:t.serverName??`aikit`,version:re()},{capabilities:{logging:{},completions:{},prompts:{}},instructions:r});return zr(i),x_(i,e,t,Lr(i),new w_(i),ru(i),void 0,null,null,n),Xr(i,{curated:e.curated,store:e.store,graphStore:e.graphStore,stateStore:e.stateStore},t.indexMode),i}async function Y_(e){let t=await E_(e),n=J_(t,e);$.debug(`MCP server configured`,{toolCount:qo.length,resourceCount:2});let r=async()=>{try{let n=e.sources.map(e=>e.path).join(`, `);$.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&&$.debug(`Indexing file`,{current:e.filesProcessed+1,total:e.filesTotal,file:e.currentFile}),e.phase===`cleanup`&&$.debug(`Index cleanup`,{staleEntries:e.filesTotal-e.filesProcessed}))});$.info(`Initial index complete`,{filesProcessed:r.filesProcessed,filesSkipped:r.filesSkipped,chunksCreated:r.chunksCreated,durationMs:r.durationMs});try{await t.store.createFtsIndex()}catch(e){$.warn(`FTS index creation failed`,L(e))}try{let e=await t.curated.reindexAll();$.info(`Curated re-index complete`,{indexed:e.indexed})}catch(e){$.error(`Curated re-index failed`,L(e))}}catch(e){$.error(`Initial index failed; will retry on aikit_reindex`,L(e))}},i=async()=>{$.info(`Shutting down`),await Promise.all([t.embedder.shutdown?.().catch(()=>{})??Promise.resolve(),t.graphStore.close().catch(()=>{}),t.closeStateStore?.().catch(()=>{})??Promise.resolve(),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{$.info(`Parent process died; shutting down`,{parentPid:a}),clearInterval(o),i()}},5e3);return o.unref(),{server:n,runInitialIndex:r,shutdown:i}}export{qo as ALL_TOOL_NAMES,q_ as createLazyServer,J_ as createMcpServer,Y_ as createServer,E_ as initializeAikit,x_ as registerMcpTools};