@vpxa/aikit 0.1.130 → 0.1.131

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vpxa/aikit",
3
- "version": "0.1.130",
3
+ "version": "0.1.131",
4
4
  "type": "module",
5
5
  "description": "Local-first AI developer toolkit — knowledge base, code analysis, context management, and developer tools for LLM agents",
6
6
  "license": "MIT",
@@ -1 +1 @@
1
- import{t as e}from"./curated-manager-BkSgtNC2.js";import{readFileSync as t}from"node:fs";import{dirname as n,resolve as r}from"node:path";import{fileURLToPath as i,pathToFileURL as a}from"node:url";import{parseArgs as o}from"node:util";import{createLogger as s,serializeError as c}from"../../core/dist/index.js";const l=n(i(import.meta.url)),u=(()=>{try{let e=r(l,`..`,`..`,`..`,`package.json`);return JSON.parse(t(e,`utf-8`)).version??`0.0.0`}catch{return`0.0.0`}})(),d=s(`server`);function f(){return process.env.AIKIT_TRANSPORT?process.env.AIKIT_TRANSPORT:process.stdin.isTTY?`http`:`stdio`}const{values:p}=(()=>{let e=process.argv[1];if(!e)return!1;try{return import.meta.url===a(e).href}catch{return!1}})()?o({allowPositionals:!0,options:{transport:{type:`string`,default:f()},port:{type:`string`,default:process.env.AIKIT_PORT??`3210`}}}):{values:{transport:f(),port:process.env.AIKIT_PORT??`3210`}};async function m(){if(process.on(`unhandledRejection`,e=>{d.error(`Unhandled rejection`,c(e))}),d.info(`Starting MCP AI Kit server`,{version:u}),p.transport===`http`){let[{default:e},{loadConfig:t,resolveIndexMode:n},{registerDashboardRoutes:r,resolveDashboardDir:i},{registerSettingsRoutes:a,resolveSettingsDir:o},{createSettingsRouter:s}]=await Promise.all([import(`express`),import(`./config-D4z6-EcI.js`),import(`./dashboard-static-BfIe0Si1.js`),import(`./settings-static-BosGZSPf.js`),import(`./routes-OaSHcA6x.js`)]),l=t();d.info(`Config loaded`,{sourceCount:l.sources.length,storePath:l.store.path});let u=e();u.use(e.json());let f=Number(p.port);u.use((e,t,n)=>{if(t.setHeader(`Access-Control-Allow-Origin`,process.env.AIKIT_CORS_ORIGIN??`http://localhost:${f}`),t.setHeader(`Access-Control-Allow-Methods`,`GET, POST, PUT, PATCH, DELETE, OPTIONS`),t.setHeader(`Access-Control-Allow-Headers`,`Content-Type, Authorization`),e.method===`OPTIONS`){t.status(204).end();return}n()}),r(u,i(),d);let m=new Date().toISOString();u.use(`/settings/api`,s({log:d,mcpInfo:()=>({transport:`http`,port:f,pid:process.pid,startedAt:m})})),a(u,o(),d),u.get(`/health`,(e,t)=>{t.json({status:`ok`})});let h=!1,g=null,_=null,v=null,y=Promise.resolve();u.post(`/mcp`,async(e,t)=>{if(!h||!_||!v){t.status(503).json({jsonrpc:`2.0`,error:{code:-32603,message:`Server initializing — please retry in a few seconds`},id:null});return}let n=y,r;y=new Promise(e=>{r=e}),await n;try{let n=new v({sessionIdGenerator:void 0});await _.connect(n),await n.handleRequest(e,t,e.body),n.close()}catch(e){if(d.error(`MCP handler error`,c(e)),!t.headersSent){let n=e instanceof Error?e.message:String(e),r=n.includes(`Not Acceptable`);t.status(r?406:500).json({jsonrpc:`2.0`,error:{code:r?-32e3:-32603,message:r?n:`Internal server error`},id:null})}}finally{r()}}),u.get(`/mcp`,(e,t)=>{t.writeHead(405).end(JSON.stringify({jsonrpc:`2.0`,error:{code:-32e3,message:`Method not allowed.`},id:null}))}),u.delete(`/mcp`,(e,t)=>{t.writeHead(405).end(JSON.stringify({jsonrpc:`2.0`,error:{code:-32e3,message:`Method not allowed.`},id:null}))});let b=u.listen(f,`127.0.0.1`,()=>{d.info(`MCP server listening`,{url:`http://127.0.0.1:${f}/mcp`,port:f}),setTimeout(async()=>{try{let[{createLazyServer:e,ALL_TOOL_NAMES:t},{StreamableHTTPServerTransport:r},{checkForUpdates:i,autoUpgradeScaffold:a}]=await Promise.all([import(`./server-nizfrMPw.js`),import(`@modelcontextprotocol/sdk/server/streamableHttp.js`),import(`./version-check-Bj07vc5x.js`)]);i(),a();let o=n(l),s=e(l,o);_=s.server,v=r,h=!0,d.info(`MCP server configured (lazy — AI Kit initializing in background)`,{toolCount:t.length,resourceCount:2}),s.startInit(),o===`auto`?s.ready.then(async()=>{try{let e=l.sources.map(e=>e.path).join(`, `);d.info(`Running initial index`,{sourcePaths:e}),await s.runInitialIndex(),d.info(`Initial index complete`)}catch(e){d.error(`Initial index failed; will retry on aikit_reindex`,c(e))}}).catch(e=>d.error(`AI Kit init or indexing failed`,c(e))):o===`smart`?s.ready.then(async()=>{try{if(!s.aikit)throw Error(`AI Kit components are not available after initialization`);let{SmartIndexScheduler:e}=await import(`../../indexer/dist/index.js`),t=new e(s.aikit.indexer,l,s.aikit.store),n=s.aikit.store;g=t,t.start(),n.onBeforeClose&&n.onBeforeClose(()=>t.stop()),s.setSmartScheduler(t),d.info(`Smart index scheduler started (HTTP mode)`)}catch(e){d.error(`Failed to start smart index scheduler`,c(e))}}).catch(e=>d.error(`AI Kit initialization failed`,c(e))):(s.ready.catch(e=>d.error(`AI Kit initialization failed`,c(e))),d.info(`Initial full indexing skipped in HTTP mode`,{indexMode:o}))}catch(e){d.error(`Failed to load server modules`,c(e))}},100)}),x=async e=>{d.info(`Shutdown signal received`,{signal:e}),g?.stop(),b.close(),_&&await _.close(),process.exit(0)};process.on(`SIGINT`,()=>x(`SIGINT`)),process.on(`SIGTERM`,()=>x(`SIGTERM`))}else{let[{loadConfig:e,reconfigureForWorkspace:t,resolveIndexMode:n},{createLazyServer:r},{checkForUpdates:a,autoUpgradeScaffold:o},{RootsListChangedNotificationSchema:s}]=await Promise.all([import(`./config-D4z6-EcI.js`),import(`./server-nizfrMPw.js`),import(`./version-check-Bj07vc5x.js`),import(`@modelcontextprotocol/sdk/types.js`)]),l=e();d.info(`Config loaded`,{sourceCount:l.sources.length,storePath:l.store.path}),a(),o();let u=n(l),f=r(l,u),{server:p,startInit:m,ready:h,runInitialIndex:g}=f,{StdioServerTransport:_}=await import(`@modelcontextprotocol/sdk/server/stdio.js`),v=new _;await p.connect(v),d.info(`MCP server started`,{transport:`stdio`});let y=e=>{if(e.length===0)return!1;let n=e[0].uri,r=n.startsWith(`file://`)?i(n):n;return d.info(`MCP roots resolved`,{rootUri:n,rootPath:r,rootCount:e.length}),t(l,r),l.allRoots=e.map(e=>{let t=e.uri;return t.startsWith(`file://`)?i(t):t}),!0},b=!1;try{b=y((await p.server.listRoots()).roots),b||d.info(`No MCP roots yet; waiting for roots/list_changed notification`)}catch(e){d.warn(`MCP roots/list not supported by client; using cwd fallback`,{cwd:process.cwd(),...c(e)}),b=!0}b||=await new Promise(e=>{let t=setTimeout(()=>{d.warn(`Timed out waiting for MCP roots/list_changed; using cwd fallback`,{cwd:process.cwd()}),e(!1)},5e3);p.server.setNotificationHandler(s,async()=>{clearTimeout(t);try{e(y((await p.server.listRoots()).roots))}catch(t){d.warn(`roots/list retry failed after notification`,c(t)),e(!1)}})}),m();let x=null,S=()=>{x&&clearTimeout(x),x=setTimeout(()=>{d.info(`Auto-shutdown: no activity for 30 minutes — exiting`),process.exit(0)},18e5),x.unref&&x.unref()};S(),process.stdin.on(`data`,()=>S()),h.catch(e=>{d.error(`Initialization failed — server will continue with limited tools`,c(e))}),u===`auto`?g().catch(e=>d.error(`Initial index failed`,c(e))):u===`smart`?h.then(async()=>{try{if(!f.aikit)throw Error(`AI Kit components are not available after initialization`);let{SmartIndexScheduler:e}=await import(`../../indexer/dist/index.js`),t=new e(f.aikit.indexer,l,f.aikit.store),n=f.aikit.store;t.start(),n.onBeforeClose&&n.onBeforeClose(()=>t.stop()),f.setSmartScheduler(t),d.info(`Smart index scheduler started (stdio mode)`)}catch(e){d.error(`Failed to start smart index scheduler`,c(e))}}).catch(e=>d.error(`AI Kit init failed for smart scheduler`,c(e))):d.warn(`Initial full indexing skipped; use aikit_reindex to index manually`,{indexMode:u})}}m().catch(e=>{d.error(`Fatal error`,c(e)),process.exit(1)});export{e as CuratedKnowledgeManager};
1
+ import{t as e}from"./curated-manager-BkSgtNC2.js";import{readFileSync as t}from"node:fs";import{dirname as n,resolve as r}from"node:path";import{fileURLToPath as i,pathToFileURL as a}from"node:url";import{parseArgs as o}from"node:util";import{createLogger as s,serializeError as c}from"../../core/dist/index.js";const l=n(i(import.meta.url)),u=(()=>{try{let e=r(l,`..`,`..`,`..`,`package.json`);return JSON.parse(t(e,`utf-8`)).version??`0.0.0`}catch{return`0.0.0`}})(),d=s(`server`);function f(){return process.env.AIKIT_TRANSPORT?process.env.AIKIT_TRANSPORT:process.stdin.isTTY?`http`:`stdio`}const{values:p}=(()=>{let e=process.argv[1];if(!e)return!1;try{return import.meta.url===a(e).href}catch{return!1}})()?o({allowPositionals:!0,options:{transport:{type:`string`,default:f()},port:{type:`string`,default:process.env.AIKIT_PORT??`3210`}}}):{values:{transport:f(),port:process.env.AIKIT_PORT??`3210`}};async function m(){if(process.on(`unhandledRejection`,e=>{d.error(`Unhandled rejection`,c(e))}),d.info(`Starting MCP AI Kit server`,{version:u}),p.transport===`http`){let[{default:e},{loadConfig:t,resolveIndexMode:n},{registerDashboardRoutes:r,resolveDashboardDir:i},{registerSettingsRoutes:a,resolveSettingsDir:o},{createSettingsRouter:s}]=await Promise.all([import(`express`),import(`./config-D4z6-EcI.js`),import(`./dashboard-static-BfIe0Si1.js`),import(`./settings-static-BosGZSPf.js`),import(`./routes-OaSHcA6x.js`)]),l=t();d.info(`Config loaded`,{sourceCount:l.sources.length,storePath:l.store.path});let u=e();u.use(e.json());let f=Number(p.port);u.use((e,t,n)=>{if(t.setHeader(`Access-Control-Allow-Origin`,process.env.AIKIT_CORS_ORIGIN??`http://localhost:${f}`),t.setHeader(`Access-Control-Allow-Methods`,`GET, POST, PUT, PATCH, DELETE, OPTIONS`),t.setHeader(`Access-Control-Allow-Headers`,`Content-Type, Authorization`),e.method===`OPTIONS`){t.status(204).end();return}n()}),r(u,i(),d);let m=new Date().toISOString();u.use(`/settings/api`,s({log:d,mcpInfo:()=>({transport:`http`,port:f,pid:process.pid,startedAt:m})})),a(u,o(),d),u.get(`/health`,(e,t)=>{t.json({status:`ok`})});let h=!1,g=null,_=null,v=null,y=Promise.resolve();u.post(`/mcp`,async(e,t)=>{if(!h||!_||!v){t.status(503).json({jsonrpc:`2.0`,error:{code:-32603,message:`Server initializing — please retry in a few seconds`},id:null});return}let n=y,r;y=new Promise(e=>{r=e}),await n;try{let n=new v({sessionIdGenerator:void 0});await _.connect(n),await n.handleRequest(e,t,e.body),n.close()}catch(e){if(d.error(`MCP handler error`,c(e)),!t.headersSent){let n=e instanceof Error?e.message:String(e),r=n.includes(`Not Acceptable`);t.status(r?406:500).json({jsonrpc:`2.0`,error:{code:r?-32e3:-32603,message:r?n:`Internal server error`},id:null})}}finally{r()}}),u.get(`/mcp`,(e,t)=>{t.writeHead(405).end(JSON.stringify({jsonrpc:`2.0`,error:{code:-32e3,message:`Method not allowed.`},id:null}))}),u.delete(`/mcp`,(e,t)=>{t.writeHead(405).end(JSON.stringify({jsonrpc:`2.0`,error:{code:-32e3,message:`Method not allowed.`},id:null}))});let b=u.listen(f,`127.0.0.1`,()=>{d.info(`MCP server listening`,{url:`http://127.0.0.1:${f}/mcp`,port:f}),setTimeout(async()=>{try{let[{createLazyServer:e,ALL_TOOL_NAMES:t},{StreamableHTTPServerTransport:r},{checkForUpdates:i,autoUpgradeScaffold:a}]=await Promise.all([import(`./server-ESbYgRg0.js`),import(`@modelcontextprotocol/sdk/server/streamableHttp.js`),import(`./version-check-Bj07vc5x.js`)]);i(),a();let o=n(l),s=e(l,o);_=s.server,v=r,h=!0,d.info(`MCP server configured (lazy — AI Kit initializing in background)`,{toolCount:t.length,resourceCount:2}),s.startInit(),o===`auto`?s.ready.then(async()=>{try{let e=l.sources.map(e=>e.path).join(`, `);d.info(`Running initial index`,{sourcePaths:e}),await s.runInitialIndex(),d.info(`Initial index complete`)}catch(e){d.error(`Initial index failed; will retry on aikit_reindex`,c(e))}}).catch(e=>d.error(`AI Kit init or indexing failed`,c(e))):o===`smart`?s.ready.then(async()=>{try{if(!s.aikit)throw Error(`AI Kit components are not available after initialization`);let{SmartIndexScheduler:e}=await import(`../../indexer/dist/index.js`),t=new e(s.aikit.indexer,l,s.aikit.store),n=s.aikit.store;g=t,t.start(),n.onBeforeClose&&n.onBeforeClose(()=>t.stop()),s.setSmartScheduler(t),d.info(`Smart index scheduler started (HTTP mode)`)}catch(e){d.error(`Failed to start smart index scheduler`,c(e))}}).catch(e=>d.error(`AI Kit initialization failed`,c(e))):(s.ready.catch(e=>d.error(`AI Kit initialization failed`,c(e))),d.info(`Initial full indexing skipped in HTTP mode`,{indexMode:o}))}catch(e){d.error(`Failed to load server modules`,c(e))}},100)}),x=async e=>{d.info(`Shutdown signal received`,{signal:e}),g?.stop(),b.close(),_&&await _.close(),process.exit(0)};process.on(`SIGINT`,()=>x(`SIGINT`)),process.on(`SIGTERM`,()=>x(`SIGTERM`))}else{let[{loadConfig:e,reconfigureForWorkspace:t,resolveIndexMode:n},{createLazyServer:r},{checkForUpdates:a,autoUpgradeScaffold:o},{RootsListChangedNotificationSchema:s}]=await Promise.all([import(`./config-D4z6-EcI.js`),import(`./server-ESbYgRg0.js`),import(`./version-check-Bj07vc5x.js`),import(`@modelcontextprotocol/sdk/types.js`)]),l=e();d.info(`Config loaded`,{sourceCount:l.sources.length,storePath:l.store.path}),a(),o();let u=n(l),f=r(l,u),{server:p,startInit:m,ready:h,runInitialIndex:g}=f,{StdioServerTransport:_}=await import(`@modelcontextprotocol/sdk/server/stdio.js`),v=new _;await p.connect(v),d.info(`MCP server started`,{transport:`stdio`});let y=e=>{if(e.length===0)return!1;let n=e[0].uri,r=n.startsWith(`file://`)?i(n):n;return d.info(`MCP roots resolved`,{rootUri:n,rootPath:r,rootCount:e.length}),t(l,r),l.allRoots=e.map(e=>{let t=e.uri;return t.startsWith(`file://`)?i(t):t}),!0},b=!1;try{b=y((await p.server.listRoots()).roots),b||d.info(`No MCP roots yet; waiting for roots/list_changed notification`)}catch(e){d.warn(`MCP roots/list not supported by client; using cwd fallback`,{cwd:process.cwd(),...c(e)}),b=!0}b||=await new Promise(e=>{let t=setTimeout(()=>{d.warn(`Timed out waiting for MCP roots/list_changed; using cwd fallback`,{cwd:process.cwd()}),e(!1)},5e3);p.server.setNotificationHandler(s,async()=>{clearTimeout(t);try{e(y((await p.server.listRoots()).roots))}catch(t){d.warn(`roots/list retry failed after notification`,c(t)),e(!1)}})}),m();let x=null,S=()=>{x&&clearTimeout(x),x=setTimeout(()=>{d.info(`Auto-shutdown: no activity for 30 minutes — exiting`),process.exit(0)},18e5),x.unref&&x.unref()};S(),process.stdin.on(`data`,()=>S()),h.catch(e=>{d.error(`Initialization failed — server will continue with limited tools`,c(e))}),u===`auto`?g().catch(e=>d.error(`Initial index failed`,c(e))):u===`smart`?h.then(async()=>{try{if(!f.aikit)throw Error(`AI Kit components are not available after initialization`);let{SmartIndexScheduler:e}=await import(`../../indexer/dist/index.js`),t=new e(f.aikit.indexer,l,f.aikit.store),n=f.aikit.store;t.start(),n.onBeforeClose&&n.onBeforeClose(()=>t.stop()),f.setSmartScheduler(t),d.info(`Smart index scheduler started (stdio mode)`)}catch(e){d.error(`Failed to start smart index scheduler`,c(e))}}).catch(e=>d.error(`AI Kit init failed for smart scheduler`,c(e))):d.warn(`Initial full indexing skipped; use aikit_reindex to index manually`,{indexMode:u})}}m().catch(e=>{d.error(`Fatal error`,c(e)),process.exit(1)});export{e as CuratedKnowledgeManager};
@@ -262,7 +262,7 @@ Complements: \`symbol\` (single lookup), \`trace\` (call-chain AST), \`blast_rad
262
262
  `)}}let i=n.map(e=>{if(!e||typeof e!=`object`)return null;let t=e;return typeof t.label!=`string`||typeof t.status!=`string`?null:[Lc[t.status.toLowerCase()]??`●`,t.label,typeof t.detail==`string`?t.detail:``]}).filter(e=>Array.isArray(e));return i.length>0?{type:`table`,title:e.title,value:{headers:[`Status`,`Service`,`Detail`],rows:i}}:null}const zc={done:`✅`,active:`🔵`,pending:`⏳`,error:`❌`};function Bc(e,t){if(!Array.isArray(t))return null;let n=t.map(e=>{if(e&&typeof e==`object`){let t=e;return[String(t.status??t.state??``),String(t.time??t.date??t.timestamp??``),String(t.label??t.description??t.title??t.text??``)]}return[``,``,String(e)]});return{...e,type:`table`,value:{headers:[`Status`,`Time`,`Description`],rows:n}}}function Vc(e){if(e.type!==`timeline`||!e.value||typeof e.value!=`object`||!Array.isArray(e.value.items))return null;let t=e.value.items.map(e=>{if(!e||typeof e!=`object`)return null;let t=e;return typeof t.title==`string`?[zc[typeof t.status==`string`?t.status.toLowerCase():``]??`●`,typeof t.phase==`string`&&t.phase.length>0?t.phase:t.title,typeof t.description==`string`?t.description:``]:null}).filter(e=>Array.isArray(e));return t.length>0?{type:`table`,title:e.title,value:{headers:[`Status`,`Phase`,`Description`],rows:t}}:null}function Hc(e){let t=e;if(e.type===`text`||e.type===`paragraph`)return{...e,type:`markdown`};if(e.type===`heading`)return{...e,type:`markdown`,value:`## ${String(t.value??``)}`};if(e.type===`header`){let n=Math.min(Math.max(Number(e.level)||2,1),6);return{...e,type:`markdown`,value:`${`#`.repeat(n)} ${String(t.value??``)}`}}if(e.type===`section`)return{...e,type:`markdown`};if(e.type===`list`||e.type===`bullet`||e.type===`bullets`){let n=Array.isArray(t.value)?t.value:t.value&&typeof t.value==`object`&&Array.isArray(t.value.items)?t.value.items:void 0;return Array.isArray(n)?{...e,type:`markdown`,value:n.map(e=>`- ${String(e)}`).join(`
263
263
  `)}:{...e,type:`markdown`}}if(e.type===`note`||e.type===`info`||e.type===`warning`||e.type===`alert`||e.type===`callout`){let n=e.type===`warning`?`⚠️`:e.type===`alert`?`🚨`:`ℹ️`;return{...e,type:`markdown`,value:`> ${n} ${String(t.value??``)}`}}if(e.type===`quote`||e.type===`blockquote`){let n=String(t.value??``).split(`
264
264
  `);return{...e,type:`markdown`,value:n.map(e=>`> ${e}`).join(`
265
- `)}}if(e.type===`divider`||e.type===`hr`)return{...e,type:`separator`};if(e.type===`image`||e.type===`img`){let t=e,n=String(t.src??t.url??t.value??``),r=String(t.alt??t.label??t.title??`image`);return{...e,type:`markdown`,value:`![${r}](${n})`}}if(e.type===`link`||e.type===`url`){let t=e,n=String(t.href??t.url??t.value??``),r=String(t.label??t.text??t.title??n);return{...e,type:`markdown`,value:`[${r}](${n})`}}return e}function Uc(e){let t=e;return`value`in t?e:typeof t.text==`string`?{...e,value:t.text}:typeof t.content==`string`?{...e,value:t.content}:typeof t.markdown==`string`?{...e,value:t.markdown}:typeof t.description==`string`?{...e,value:t.description}:typeof t.code==`string`?{...e,value:t.code}:Array.isArray(t.headers)&&Array.isArray(t.rows)?{...e,value:{headers:t.headers,rows:t.rows}}:Array.isArray(t.items)?{...e,value:{items:t.items}}:Array.isArray(t.metrics)?{...e,value:t.metrics}:Array.isArray(t.cards)?{...e,value:t.cards}:Array.isArray(t.nodes)&&Array.isArray(t.edges)?{...e,value:{nodes:t.nodes,edges:t.edges}}:typeof t.question==`string`?{...e,value:{question:t.question,context:t.context,placeholder:t.placeholder}}:`chartType`in t||Array.isArray(t.data)?{...e,value:{chartType:t.chartType,data:t.data,xKey:t.xKey??`label`,yKeys:t.yKeys??[`value`]}}:e}function Wc(e){if(e.type!==`chart`)return e;let t=e.value;if(!t||typeof t!=`object`||Array.isArray(t))return e;let n=t,r=n.data&&typeof n.data==`object`&&!Array.isArray(n.data)?n.data:null,i=Array.isArray(n.labels)?n.labels:Array.isArray(r?.labels)?r.labels:null,a=Array.isArray(n.datasets)?n.datasets:Array.isArray(r?.datasets)?r.datasets:null,o=typeof n.type==`string`?n.type:typeof n.chartType==`string`?n.chartType:null;if(!o||!i||!a||Array.isArray(n.data))return e;let s=a.map((e,t)=>String(e.label??`series${t+1}`)),c=i.map((e,t)=>{let n={label:String(e)};for(let[e,r]of a.entries()){let i=r,a=String(i.label??`series${e+1}`);n[a]=i.data?.[t]??0}return n});return{...e,value:{chartType:String(o),data:c,xKey:`label`,yKeys:s}}}function Gc(e){if(Array.isArray(e)){let t=e.filter(e=>typeof e==`object`&&!!e),n=t.map(e=>String(e.title??``)),r=Math.max(0,...t.map(e=>Array.isArray(e.items)?e.items.length:0));return{headers:n,rows:Array.from({length:r},(e,n)=>t.map(e=>Array.isArray(e.items)?e.items[n]??``:``))}}if(!e||typeof e!=`object`)return null;let t=e,n=Object.keys(t),r=Math.max(0,...n.map(e=>Array.isArray(t[e])?t[e].length:0));return{headers:n,rows:Array.from({length:r},(e,r)=>n.map(e=>Array.isArray(t[e])?t[e][r]??``:``))}}function Kc(e,t,n){let r=Gc(t)??Gc(n);if(r)return{...e,type:`table`,value:r};if(n&&typeof n==`object`&&!Array.isArray(n)){let t=n;if(Array.isArray(t.headers)&&Array.isArray(t.rows))return{...e,type:`table`}}return null}function qc(e,t,n){let r=t&&typeof t==`object`&&!Array.isArray(t)?t:n&&typeof n==`object`&&!Array.isArray(n)?n:null;return r?{...e,type:`table`,value:{headers:[`Key`,`Value`],rows:Object.entries(r).map(([e,t])=>[e,t])}}:null}function Jc(e){let t=e,n=Uc(e);if(n=Wc(n),n.type===`kv`)return qc(n,t.entries,n.value)??n;if(n.type===`comparison`){let e=n,r=t.columns??(e.value&&typeof e.value==`object`?e.value.columns:void 0);return Kc(n,r,e.value)??n}return n=Hc(n),n.type===`timeline`?Bc(n,n.value)??n:n}const Yc=new Set([`separator`,`actions`]);function Xc(e){if(typeof e!=`object`||!e||!(`type`in e))return!1;let t=e,n=typeof t.type==`string`?t.type:``;return Yc.has(n)?!0:`value`in t||typeof t.text==`string`||Array.isArray(t.headers)&&Array.isArray(t.rows)||typeof t.code==`string`||Array.isArray(t.items)||!!t.entries&&typeof t.entries==`object`&&!Array.isArray(t.entries)||!!t.columns&&typeof t.columns==`object`||`chartType`in t||Array.isArray(t.data)||typeof t.content==`string`||typeof t.markdown==`string`||typeof t.description==`string`||Array.isArray(t.metrics)||Array.isArray(t.cards)||Array.isArray(t.nodes)||typeof t.question==`string`}function Zc(e){return Ic(e)??kc(e)??Rc(e)??Fc(e)??Pc(e)??Vc(e)??Oc(e)??Nc(e)??e}function Qc(e){if(!Array.isArray(e)&&typeof e==`object`&&e){let t=e;return Array.isArray(t.blocks)&&t.blocks.length>0?Qc(t.blocks):e}return Array.isArray(e)?e.map(e=>Xc(e)?Zc(Jc(e)):e):e}const $c=g(b(import.meta.url)),el=m.resolve($c,`..`,`..`,`..`,`..`,`present`,`dist`,`index.html`);let tl;function nl(){if(tl!==void 0)return tl??void 0;if(!a.existsSync(el)){tl=null;return}return tl=a.readFileSync(el,`utf8`),tl??void 0}function rl(e){return JSON.stringify(e).replace(/</g,`\\u003c`).replace(/>/g,`\\u003e`).replace(/&/g,`\\u0026`).replace(/\u2028/g,`\\u2028`).replace(/\u2029/g,`\\u2029`)}function il(e,t){return`<!DOCTYPE html>
265
+ `)}}if(e.type===`divider`||e.type===`hr`)return{...e,type:`separator`};if(e.type===`image`||e.type===`img`){let t=e,n=String(t.src??t.url??t.value??``),r=String(t.alt??t.label??t.title??`image`);return{...e,type:`markdown`,value:`![${r}](${n})`}}if(e.type===`link`||e.type===`url`){let t=e,n=String(t.href??t.url??t.value??``),r=String(t.label??t.text??t.title??n);return{...e,type:`markdown`,value:`[${r}](${n})`}}return e}function Uc(e){let t=e;return`value`in t?e:typeof t.text==`string`?{...e,value:t.text}:typeof t.content==`string`?{...e,value:t.content}:typeof t.markdown==`string`?{...e,value:t.markdown}:typeof t.description==`string`?{...e,value:t.description}:typeof t.code==`string`?{...e,value:t.code}:Array.isArray(t.headers)&&Array.isArray(t.rows)?{...e,value:{headers:t.headers,rows:t.rows}}:Array.isArray(t.items)?{...e,value:{items:t.items}}:Array.isArray(t.metrics)?{...e,value:t.metrics}:Array.isArray(t.cards)?{...e,value:t.cards}:Array.isArray(t.nodes)&&Array.isArray(t.edges)?{...e,value:{nodes:t.nodes,edges:t.edges}}:typeof t.question==`string`?{...e,value:{question:t.question,context:t.context,placeholder:t.placeholder}}:`chartType`in t||Array.isArray(t.data)?{...e,value:{chartType:t.chartType,data:t.data,xKey:t.xKey??`label`,yKeys:t.yKeys??[`value`]}}:e}function Wc(e){if(e.type!==`chart`)return e;let t=e.value;if(!t||typeof t!=`object`||Array.isArray(t))return e;let n=t,r=n.data&&typeof n.data==`object`&&!Array.isArray(n.data)?n.data:null,i=Array.isArray(n.labels)?n.labels:Array.isArray(r?.labels)?r.labels:null,a=Array.isArray(n.datasets)?n.datasets:Array.isArray(r?.datasets)?r.datasets:null,o=typeof n.type==`string`?n.type:typeof n.chartType==`string`?n.chartType:null;if(!o||!i||!a||Array.isArray(n.data))return e;let s=a.map((e,t)=>String(e.label??`series${t+1}`)),c=i.map((e,t)=>{let n={label:String(e)};for(let[e,r]of a.entries()){let i=r,a=String(i.label??`series${e+1}`);n[a]=i.data?.[t]??0}return n});return{...e,value:{chartType:String(o),data:c,xKey:`label`,yKeys:s}}}function Gc(e){if(Array.isArray(e)){let t=e.filter(e=>typeof e==`object`&&!!e),n=t.map(e=>String(e.title??``)),r=Math.max(0,...t.map(e=>Array.isArray(e.items)?e.items.length:0));return{headers:n,rows:Array.from({length:r},(e,n)=>t.map(e=>Array.isArray(e.items)?e.items[n]??``:``))}}if(!e||typeof e!=`object`)return null;let t=e,n=Object.keys(t),r=Math.max(0,...n.map(e=>Array.isArray(t[e])?t[e].length:0));return{headers:n,rows:Array.from({length:r},(e,r)=>n.map(e=>Array.isArray(t[e])?t[e][r]??``:``))}}function Kc(e,t,n){let r=Gc(t)??Gc(n);if(r)return{...e,type:`table`,value:r};if(n&&typeof n==`object`&&!Array.isArray(n)){let t=n;if(Array.isArray(t.headers)&&Array.isArray(t.rows))return{...e,type:`table`}}return null}function qc(e,t,n){let r=t&&typeof t==`object`&&!Array.isArray(t)?t:n&&typeof n==`object`&&!Array.isArray(n)?n:null;return r?{...e,type:`table`,value:{headers:[`Key`,`Value`],rows:Object.entries(r).map(([e,t])=>[e,t])}}:null}function Jc(e){let t=e,n=Uc(e);if(n=Wc(n),n.type===`kv`)return qc(n,t.entries,n.value)??n;if(n.type===`comparison`){let e=n,r=t.columns??(e.value&&typeof e.value==`object`?e.value.columns:void 0);return Kc(n,r,e.value)??n}return n=Hc(n),n.type===`timeline`?Bc(n,n.value)??n:n}const Yc=new Set([`separator`,`actions`]);function Xc(e){if(typeof e!=`object`||!e||!(`type`in e))return!1;let t=e,n=typeof t.type==`string`?t.type:``;return Yc.has(n)?!0:`value`in t||typeof t.text==`string`||Array.isArray(t.headers)&&Array.isArray(t.rows)||typeof t.code==`string`||Array.isArray(t.items)||!!t.entries&&typeof t.entries==`object`&&!Array.isArray(t.entries)||!!t.columns&&typeof t.columns==`object`||`chartType`in t||Array.isArray(t.data)||typeof t.content==`string`||typeof t.markdown==`string`||typeof t.description==`string`||Array.isArray(t.metrics)||Array.isArray(t.cards)||Array.isArray(t.nodes)||typeof t.question==`string`}function Zc(e){return Ic(e)??kc(e)??Rc(e)??Fc(e)??Pc(e)??Vc(e)??Oc(e)??Nc(e)??e}function Qc(e){if(!Array.isArray(e)&&typeof e==`object`&&e){let t=e;return Array.isArray(t.blocks)&&t.blocks.length>0?Qc(t.blocks):e}return Array.isArray(e)?e.map(e=>Xc(e)?Zc(Jc(e)):e):e}function $c(e){let t=e;for(let e=0;e<10;e++){if(a.existsSync(m.join(t,`package.json`)))return t;let e=m.dirname(t);if(e===t)break;t=e}return e}function el(){let e=$c(m.dirname(b(import.meta.url))),t=m.join(e,`packages`,`present`,`dist`,`index.html`);if(a.existsSync(t))return t;let n=m.join(e,`node_modules`,`@aikit`,`present`,`dist`,`index.html`);return a.existsSync(n)?n:t}const tl=el();let nl;function rl(){if(nl!==void 0)return nl??void 0;if(!a.existsSync(tl)){nl=null;return}return nl=a.readFileSync(tl,`utf8`),nl??void 0}function il(e){return JSON.stringify(e).replace(/</g,`\\u003c`).replace(/>/g,`\\u003e`).replace(/&/g,`\\u0026`).replace(/\u2028/g,`\\u2028`).replace(/\u2029/g,`\\u2029`)}function al(e,t){return`<!DOCTYPE html>
266
266
  <html>
267
267
  <head>
268
268
  <meta charset="utf-8">
@@ -282,37 +282,37 @@ Complements: \`symbol\` (single lookup), \`trace\` (call-chain AST), \`blast_rad
282
282
  </div>
283
283
  ${t}
284
284
  </body>
285
- </html>`}function al(e,t,n,r){let i={title:e,content:Qc(t)};r!==void 0&&(i.template=r),Array.isArray(n)&&n.length>0&&(i.actions=n);let a=`<script type="application/json" id="present-data">${rl(i)}<\/script>`,o=U(e??`AI Kit Dashboard`),s=nl();return s?s.replace(/<title>[\s\S]*?<\/title>/i,`<title>${o}</title>`).replace(`</head>`,` ${a}\n</head>`):il(o,a)}An.setOptions({async:!1,gfm:!0,breaks:!0}),An.use({renderer:{html(e){return U(e.text)},link(e){let t=e.href??``,n=t.replace(/\s/g,``).toLowerCase();if(n.startsWith(`javascript:`)||n.startsWith(`vbscript:`)||n.startsWith(`data:`))return this.parser.parseInline(e.tokens);let r=e.title?` title="${U(e.title)}"`:``,i=this.parser.parseInline(e.tokens);return`<a href="${U(t)}"${r}>${i}</a>`}}});function ol(e,t,n){let r=[];if(e&&r.push(`# ${e}\n`),typeof t==`string`)r.push(t);else if(Array.isArray(t))if(t.length===0)r.push(`*(empty)*`);else if(Xc(t[0])||typeof t[0]==`object`&&t[0]!==null&&typeof t[0].type==`string`)for(let e of t)r.push(sl(Jc(e),n));else if(typeof t[0]==`object`&&t[0]!==null)n?.compactTables?r.push(ll(t)):r.push(cl(t));else for(let e of t)r.push(`- ${String(e)}`);else if(typeof t==`object`&&t){let e=t;if(Array.isArray(e.blocks)&&e.blocks.length>0)for(let t of e.blocks)Xc(t)||typeof t==`object`&&t&&typeof t.type==`string`?r.push(sl(Jc(t),n)):typeof t==`object`&&t?r.push(pl(t)):r.push(String(t));else Array.isArray(e.nodes)&&Array.isArray(e.edges)?r.push(fl(e)):Array.isArray(e.metrics)?r.push(dl(e.metrics)):r.push(pl(e))}else r.push(String(t));return r.join(`
286
- `)}function sl(e,t){let n=[];switch(e.title&&n.push(`## ${e.title}\n`),e.type){case`markdown`:{let t=String(e.value??``);t=t.replace(/(^|\n)((?!\|)[^\n]+)\n(\|)/g,`$1$2
285
+ </html>`}function ol(e,t,n,r){let i={title:e,content:Qc(t)};r!==void 0&&(i.template=r),Array.isArray(n)&&n.length>0&&(i.actions=n);let a=`<script type="application/json" id="present-data">${il(i)}<\/script>`,o=U(e??`AI Kit Dashboard`),s=rl();return s?s.replace(/<title>[\s\S]*?<\/title>/i,`<title>${o}</title>`).replace(`</head>`,` ${a}\n</head>`):al(o,a)}An.setOptions({async:!1,gfm:!0,breaks:!0}),An.use({renderer:{html(e){return U(e.text)},link(e){let t=e.href??``,n=t.replace(/\s/g,``).toLowerCase();if(n.startsWith(`javascript:`)||n.startsWith(`vbscript:`)||n.startsWith(`data:`))return this.parser.parseInline(e.tokens);let r=e.title?` title="${U(e.title)}"`:``,i=this.parser.parseInline(e.tokens);return`<a href="${U(t)}"${r}>${i}</a>`}}});function sl(e,t,n){let r=[];if(e&&r.push(`# ${e}\n`),typeof t==`string`)r.push(t);else if(Array.isArray(t))if(t.length===0)r.push(`*(empty)*`);else if(Xc(t[0])||typeof t[0]==`object`&&t[0]!==null&&typeof t[0].type==`string`)for(let e of t)r.push(cl(Jc(e),n));else if(typeof t[0]==`object`&&t[0]!==null)n?.compactTables?r.push(ul(t)):r.push(ll(t));else for(let e of t)r.push(`- ${String(e)}`);else if(typeof t==`object`&&t){let e=t;if(Array.isArray(e.blocks)&&e.blocks.length>0)for(let t of e.blocks)Xc(t)||typeof t==`object`&&t&&typeof t.type==`string`?r.push(cl(Jc(t),n)):typeof t==`object`&&t?r.push(ml(t)):r.push(String(t));else Array.isArray(e.nodes)&&Array.isArray(e.edges)?r.push(pl(e)):Array.isArray(e.metrics)?r.push(fl(e.metrics)):r.push(ml(e))}else r.push(String(t));return r.join(`
286
+ `)}function cl(e,t){let n=[];switch(e.title&&n.push(`## ${e.title}\n`),e.type){case`markdown`:{let t=String(e.value??``);t=t.replace(/(^|\n)((?!\|)[^\n]+)\n(\|)/g,`$1$2
287
287
 
288
- $3`),n.push(t);break}case`code`:n.push(`\`\`\`${e.language??``}\n${String(e.value??``)}\n\`\`\``);break;case`mermaid`:n.push(`\`\`\`mermaid\n${String(e.value??``)}\n\`\`\``);break;case`table`:{let r=e.value;if(Array.isArray(r)&&r.length>0)t?.compactTables?n.push(ll(r,e.title)):n.push(cl(r));else if(r&&typeof r==`object`&&!Array.isArray(r)&&`headers`in r&&`rows`in r){let{headers:i,rows:a}=r;if(t?.compactTables){let t=[];e.title&&t.push(`**${e.title}**\n`);for(let e=0;e<a.length;e++){let n=i.map((t,n)=>`**${t}**: ${String(a[e]?.[n]??``)}`).join(` · `);t.push(`${e+1}. ${n}`)}n.push(t.join(`
289
- `))}else{n.push(`| ${i.join(` | `)} |`),n.push(`| ${i.map(()=>`---`).join(` | `)} |`);for(let e of a)n.push(`| ${e.map(e=>String(e??``)).join(` | `)} |`)}}else n.push(`*(empty table)*`);break}case`metrics`:Array.isArray(e.value)&&n.push(dl(e.value));break;case`graph`:e.value&&typeof e.value==`object`&&n.push(fl(e.value));break;case`cards`:if(Array.isArray(e.value))for(let t of e.value)n.push(`### ${t.title??`Card`}`),(t.body||t.description)&&n.push(String(t.body??t.description)),(t.badge||t.status)&&n.push(`> **${t.badge??t.status}**`),n.push(``);break;case`tree`:e.value&&typeof e.value==`object`&&n.push(pl(e.value));break;case`chart`:{let t=e.value;t?.data&&Array.isArray(t.data)&&n.push(`*${String(t.chartType??`chart`)} chart — ${t.data.length} data points*`);break}case`timeline`:{let t=e.value;if(t?.items)for(let e of t.items){let t=e.status===`done`?`✅`:e.status===`active`?`🔄`:e.status===`error`?`❌`:`⬜`;n.push(`${t} **${e.title}**${e.description?` — ${e.description}`:``}`)}break}case`checklist`:{let t=e.value;if(t?.items)for(let e of t.items)n.push(`- [${e.checked?`x`:` `}] ${e.label}${e.note?` — ${e.note}`:``}`);break}case`comparison`:{let r=e.value;if(r?.columns&&r.columns.length>0)if(t?.compactTables)n.push(ul(r.columns,e.title));else{let e=Math.max(...r.columns.map(e=>e.items?.length??0)),t=r.columns.map(e=>e.title);n.push(`| ${t.join(` | `)} |`),n.push(`| ${t.map(()=>`---`).join(` | `)} |`);for(let t=0;t<e;t++)n.push(`| ${r.columns.map(e=>e.items?.[t]??``).join(` | `)} |`)}break}case`status-board`:{let t=e.value;if(t?.items)for(let e of t.items){let t=e.status===`success`?`🟢`:e.status===`warning`?`🟡`:e.status===`error`?`🔴`:e.status===`info`?`🔵`:`⚪`;n.push(`${t} **${e.label}**${e.detail?` — ${e.detail}`:``}`)}break}case`prompt`:{let t=e.value;t?.question&&(n.push(`> **${t.question}**`),t.context&&n.push(`> ${t.context}`));break}case`progress`:{let t=e.value;if(t?.items)for(let e of t.items){let t=e.max??100,r=t>0?Math.round(e.value/t*100):0,i=Math.round(r/5),a=`█`.repeat(i)+`░`.repeat(20-i);n.push(`${e.label}: ${a} ${r}%`)}break}case`docs-browser`:{let t=e.value,r={current:`✅`,stale:`⚠️`,missing:`❌`};t?.title?.trim()&&n.push(`## ${t.title.trim()}`);let i=Array.isArray(t?.files)?t.files:[];if(i.length===0){n.push(`*(No content available)*`);break}i.forEach((e,t)=>{let a=e?.path?.trim()||`document-${t+1}`,o=e?.title?.trim()||a.split(/[\\/]/).pop()||a,s=e?.status&&r[e.status]?r[e.status]:`📄`;n.push(`${s} **${o}** (\`${a}\`)`),n.push(``),typeof e?.content==`string`&&e.content.trim().length>0?n.push(e.content.trim()):n.push(`*(No content available)*`),t<i.length-1&&(n.push(``),n.push(`---`),n.push(``))});break}case`viewer-link`:{let t=e.value,r=t?.label?.trim()||t?.viewerType?.trim()||`Viewer`,i=t?.icon?.trim()||`🔗`;n.push(`${i} **${r}**`),t?.description?.trim()&&n.push(t.description.trim()),t?.url?.trim()&&n.push(`[Open](${t.url.trim()})`);break}case`text`:n.push(String(e.value??``));break;case`heading`:{let t=Math.min(Math.max(Number(e.level)||2,1),6);n.push(`${`#`.repeat(t)} ${String(e.value??``)}\n`);break}case`paragraph`:n.push(String(e.value??``));break;case`separator`:n.push(`---
288
+ $3`),n.push(t);break}case`code`:n.push(`\`\`\`${e.language??``}\n${String(e.value??``)}\n\`\`\``);break;case`mermaid`:n.push(`\`\`\`mermaid\n${String(e.value??``)}\n\`\`\``);break;case`table`:{let r=e.value;if(Array.isArray(r)&&r.length>0)t?.compactTables?n.push(ul(r,e.title)):n.push(ll(r));else if(r&&typeof r==`object`&&!Array.isArray(r)&&`headers`in r&&`rows`in r){let{headers:i,rows:a}=r;if(t?.compactTables){let t=[];e.title&&t.push(`**${e.title}**\n`);for(let e=0;e<a.length;e++){let n=i.map((t,n)=>`**${t}**: ${String(a[e]?.[n]??``)}`).join(` · `);t.push(`${e+1}. ${n}`)}n.push(t.join(`
289
+ `))}else{n.push(`| ${i.join(` | `)} |`),n.push(`| ${i.map(()=>`---`).join(` | `)} |`);for(let e of a)n.push(`| ${e.map(e=>String(e??``)).join(` | `)} |`)}}else n.push(`*(empty table)*`);break}case`metrics`:Array.isArray(e.value)&&n.push(fl(e.value));break;case`graph`:e.value&&typeof e.value==`object`&&n.push(pl(e.value));break;case`cards`:if(Array.isArray(e.value))for(let t of e.value)n.push(`### ${t.title??`Card`}`),(t.body||t.description)&&n.push(String(t.body??t.description)),(t.badge||t.status)&&n.push(`> **${t.badge??t.status}**`),n.push(``);break;case`tree`:e.value&&typeof e.value==`object`&&n.push(ml(e.value));break;case`chart`:{let t=e.value;t?.data&&Array.isArray(t.data)&&n.push(`*${String(t.chartType??`chart`)} chart — ${t.data.length} data points*`);break}case`timeline`:{let t=e.value;if(t?.items)for(let e of t.items){let t=e.status===`done`?`✅`:e.status===`active`?`🔄`:e.status===`error`?`❌`:`⬜`;n.push(`${t} **${e.title}**${e.description?` — ${e.description}`:``}`)}break}case`checklist`:{let t=e.value;if(t?.items)for(let e of t.items)n.push(`- [${e.checked?`x`:` `}] ${e.label}${e.note?` — ${e.note}`:``}`);break}case`comparison`:{let r=e.value;if(r?.columns&&r.columns.length>0)if(t?.compactTables)n.push(dl(r.columns,e.title));else{let e=Math.max(...r.columns.map(e=>e.items?.length??0)),t=r.columns.map(e=>e.title);n.push(`| ${t.join(` | `)} |`),n.push(`| ${t.map(()=>`---`).join(` | `)} |`);for(let t=0;t<e;t++)n.push(`| ${r.columns.map(e=>e.items?.[t]??``).join(` | `)} |`)}break}case`status-board`:{let t=e.value;if(t?.items)for(let e of t.items){let t=e.status===`success`?`🟢`:e.status===`warning`?`🟡`:e.status===`error`?`🔴`:e.status===`info`?`🔵`:`⚪`;n.push(`${t} **${e.label}**${e.detail?` — ${e.detail}`:``}`)}break}case`prompt`:{let t=e.value;t?.question&&(n.push(`> **${t.question}**`),t.context&&n.push(`> ${t.context}`));break}case`progress`:{let t=e.value;if(t?.items)for(let e of t.items){let t=e.max??100,r=t>0?Math.round(e.value/t*100):0,i=Math.round(r/5),a=`█`.repeat(i)+`░`.repeat(20-i);n.push(`${e.label}: ${a} ${r}%`)}break}case`docs-browser`:{let t=e.value,r={current:`✅`,stale:`⚠️`,missing:`❌`};t?.title?.trim()&&n.push(`## ${t.title.trim()}`);let i=Array.isArray(t?.files)?t.files:[];if(i.length===0){n.push(`*(No content available)*`);break}i.forEach((e,t)=>{let a=e?.path?.trim()||`document-${t+1}`,o=e?.title?.trim()||a.split(/[\\/]/).pop()||a,s=e?.status&&r[e.status]?r[e.status]:`📄`;n.push(`${s} **${o}** (\`${a}\`)`),n.push(``),typeof e?.content==`string`&&e.content.trim().length>0?n.push(e.content.trim()):n.push(`*(No content available)*`),t<i.length-1&&(n.push(``),n.push(`---`),n.push(``))});break}case`viewer-link`:{let t=e.value,r=t?.label?.trim()||t?.viewerType?.trim()||`Viewer`,i=t?.icon?.trim()||`🔗`;n.push(`${i} **${r}**`),t?.description?.trim()&&n.push(t.description.trim()),t?.url?.trim()&&n.push(`[Open](${t.url.trim()})`);break}case`text`:n.push(String(e.value??``));break;case`heading`:{let t=Math.min(Math.max(Number(e.level)||2,1),6);n.push(`${`#`.repeat(t)} ${String(e.value??``)}\n`);break}case`paragraph`:n.push(String(e.value??``));break;case`separator`:n.push(`---
290
290
  `);break;default:n.push(JSON.stringify(e.value,null,2))}return n.push(``),n.join(`
291
- `)}function cl(e){if(e.length===0)return`*(empty table)*`;let t=Object.keys(e[0]),n=[];n.push(`| ${t.join(` | `)} |`),n.push(`| ${t.map(()=>`---`).join(` | `)} |`);for(let r of e)n.push(`| ${t.map(e=>String(r[e]??``)).join(` | `)} |`);return n.join(`
292
- `)}function ll(e,t){if(e.length===0)return`*(empty table)*`;let n=Object.keys(e[0]),r=[];t&&r.push(`**${t}**\n`);for(let t=0;t<e.length;t++){let i=e[t],a=String(i[n[0]]??``);if(n.length===1)r.push(`${t+1}. **${a}**`);else{let e=n.slice(1).map(e=>`${e}: ${String(i[e]??``)}`).join(` · `);r.push(`${t+1}. **${a}** — ${e}`)}}return r.join(`
293
- `)}function ul(e,t){let n=[];t&&n.push(`**${t}**\n`);for(let t of e){if(n.push(`**${t.title}**`),t.items&&t.items.length>0)for(let e of t.items)n.push(`- ${e}`);else n.push(`- *(none)*`);n.push(``)}return n.join(`
294
- `)}function dl(e){return e.map(e=>`- **${e.label}**: ${e.value}`).join(`
295
- `)}function fl(e){let t=["```mermaid",`graph LR`];for(let n of e.nodes){let e=Ia(String(n.id??n.name??``)),r=String(n.label??n.name??e);t.push(` ${e}["${r}"]`)}for(let n of e.edges){let e=Ia(String(n.source??n.from??``)),r=Ia(String(n.target??n.to??``)),i=n.label?`|${String(n.label)}|`:``;t.push(` ${e} -->${i} ${r}`)}return t.push("```"),t.join(`
296
- `)}function pl(e,t=0){let n=` `.repeat(t),r=[];for(let[i,a]of Object.entries(e))typeof a==`object`&&a&&!Array.isArray(a)?(r.push(`${n}- **${i}**:`),r.push(pl(a,t+1))):r.push(`${n}- **${i}**: ${Fa(a)}`);return r.join(`
297
- `)}const q=U;function ml(e){if(!e)return!1;let t=e.trim().toLowerCase();return t.startsWith(`http://`)||t.startsWith(`https://`)||t.startsWith(`/`)||t.startsWith(`./`)||t.startsWith(`../`)?!0:!t.includes(`:`)}function hl(e){return e?/^(#[\da-f]{3,8}|rgba?\([^)]+\)|hsla?\([^)]+\)|var\(--[\w-]+\)|[a-z]{1,20})$/i.test(e.trim()):!1}function gl(e){let t=e;return!t?.items||!Array.isArray(t.items)?``:`<div class="timeline">${t.items.map(e=>{let t=e.status??`pending`,n=e.phase?`<div class="timeline-phase">${q(e.phase)}</div>`:``,r=e.description?`<div class="timeline-desc">${q(e.description)}</div>`:``;return`<div class="timeline-item">
291
+ `)}function ll(e){if(e.length===0)return`*(empty table)*`;let t=Object.keys(e[0]),n=[];n.push(`| ${t.join(` | `)} |`),n.push(`| ${t.map(()=>`---`).join(` | `)} |`);for(let r of e)n.push(`| ${t.map(e=>String(r[e]??``)).join(` | `)} |`);return n.join(`
292
+ `)}function ul(e,t){if(e.length===0)return`*(empty table)*`;let n=Object.keys(e[0]),r=[];t&&r.push(`**${t}**\n`);for(let t=0;t<e.length;t++){let i=e[t],a=String(i[n[0]]??``);if(n.length===1)r.push(`${t+1}. **${a}**`);else{let e=n.slice(1).map(e=>`${e}: ${String(i[e]??``)}`).join(` · `);r.push(`${t+1}. **${a}** — ${e}`)}}return r.join(`
293
+ `)}function dl(e,t){let n=[];t&&n.push(`**${t}**\n`);for(let t of e){if(n.push(`**${t.title}**`),t.items&&t.items.length>0)for(let e of t.items)n.push(`- ${e}`);else n.push(`- *(none)*`);n.push(``)}return n.join(`
294
+ `)}function fl(e){return e.map(e=>`- **${e.label}**: ${e.value}`).join(`
295
+ `)}function pl(e){let t=["```mermaid",`graph LR`];for(let n of e.nodes){let e=Ia(String(n.id??n.name??``)),r=String(n.label??n.name??e);t.push(` ${e}["${r}"]`)}for(let n of e.edges){let e=Ia(String(n.source??n.from??``)),r=Ia(String(n.target??n.to??``)),i=n.label?`|${String(n.label)}|`:``;t.push(` ${e} -->${i} ${r}`)}return t.push("```"),t.join(`
296
+ `)}function ml(e,t=0){let n=` `.repeat(t),r=[];for(let[i,a]of Object.entries(e))typeof a==`object`&&a&&!Array.isArray(a)?(r.push(`${n}- **${i}**:`),r.push(ml(a,t+1))):r.push(`${n}- **${i}**: ${Fa(a)}`);return r.join(`
297
+ `)}const q=U;function hl(e){if(!e)return!1;let t=e.trim().toLowerCase();return t.startsWith(`http://`)||t.startsWith(`https://`)||t.startsWith(`/`)||t.startsWith(`./`)||t.startsWith(`../`)?!0:!t.includes(`:`)}function gl(e){return e?/^(#[\da-f]{3,8}|rgba?\([^)]+\)|hsla?\([^)]+\)|var\(--[\w-]+\)|[a-z]{1,20})$/i.test(e.trim()):!1}function _l(e){let t=e;return!t?.items||!Array.isArray(t.items)?``:`<div class="timeline">${t.items.map(e=>{let t=e.status??`pending`,n=e.phase?`<div class="timeline-phase">${q(e.phase)}</div>`:``,r=e.description?`<div class="timeline-desc">${q(e.description)}</div>`:``;return`<div class="timeline-item">
298
298
  <div class="timeline-dot ${t}"></div>
299
299
  ${n}
300
300
  <div class="timeline-title">${q(e.title)}</div>
301
301
  ${r}
302
- </div>`}).join(``)}</div>`}function _l(e){let t=e;return!t?.items||!Array.isArray(t.items)?``:`<div class="checklist">${t.items.map(e=>{let t=e.checked?`checked`:``,n=e.checked?`✓`:``,r=e.note?`<div class="checklist-note">${q(e.note)}</div>`:``;return`<div class="checklist-item ${t}">
302
+ </div>`}).join(``)}</div>`}function vl(e){let t=e;return!t?.items||!Array.isArray(t.items)?``:`<div class="checklist">${t.items.map(e=>{let t=e.checked?`checked`:``,n=e.checked?`✓`:``,r=e.note?`<div class="checklist-note">${q(e.note)}</div>`:``;return`<div class="checklist-item ${t}">
303
303
  <div class="checklist-check ${t}">${n}</div>
304
304
  <div>
305
305
  <div class="checklist-label">${q(e.label)}</div>
306
306
  ${r}
307
307
  </div>
308
- </div>`}).join(``)}</div>`}function vl(e){let t=e;if(t?.left&&t?.right)return vl({columns:[{title:t.left.label??`Left`,items:t.left.items??[]},{title:t.right.label??`Right`,items:t.right.items??[]}]});if(!t?.columns||!Array.isArray(t.columns)||t.columns.length===0)return``;let n=t.columns.length,r=Math.max(...t.columns.map(e=>e.items?.length??0));return`<div class="comparison-grid" style="grid-template-columns:repeat(${n},1fr)">${t.columns.map(e=>{let t=`<div class="comparison-header">${q(e.title)}</div>`,n=[];for(let t=0;t<r;t++){let r=e.items?.[t]??``;n.push(`<div class="comparison-item">${q(r)}</div>`)}return`<div class="comparison-col">${t}${n.join(``)}</div>`}).join(``)}</div>`}function yl(e){let t=e;return!t?.items||!Array.isArray(t.items)?``:`<div class="status-board">${t.items.flatMap(e=>{let t=e;if(Array.isArray(t.items)){let e=t.category?.trim();return t.items.map(t=>({...t,label:e?`${e}: ${t.label}`:t.label}))}return[e]}).map(e=>{let t=e.detail?`<span class="status-detail">${q(e.detail)}</span>`:``;return`<div class="status-row">
308
+ </div>`}).join(``)}</div>`}function yl(e){let t=e;if(t?.left&&t?.right)return yl({columns:[{title:t.left.label??`Left`,items:t.left.items??[]},{title:t.right.label??`Right`,items:t.right.items??[]}]});if(!t?.columns||!Array.isArray(t.columns)||t.columns.length===0)return``;let n=t.columns.length,r=Math.max(...t.columns.map(e=>e.items?.length??0));return`<div class="comparison-grid" style="grid-template-columns:repeat(${n},1fr)">${t.columns.map(e=>{let t=`<div class="comparison-header">${q(e.title)}</div>`,n=[];for(let t=0;t<r;t++){let r=e.items?.[t]??``;n.push(`<div class="comparison-item">${q(r)}</div>`)}return`<div class="comparison-col">${t}${n.join(``)}</div>`}).join(``)}</div>`}function bl(e){let t=e;return!t?.items||!Array.isArray(t.items)?``:`<div class="status-board">${t.items.flatMap(e=>{let t=e;if(Array.isArray(t.items)){let e=t.category?.trim();return t.items.map(t=>({...t,label:e?`${e}: ${t.label}`:t.label}))}return[e]}).map(e=>{let t=e.detail?`<span class="status-detail">${q(e.detail)}</span>`:``;return`<div class="status-row">
309
309
  <div class="status-indicator ${e.status??`pending`}"></div>
310
310
  <span class="status-label">${q(e.label)}</span>
311
311
  ${t}
312
- </div>`}).join(``)}</div>`}function bl(e){let t=e;if(!t?.question)return``;let n=t.context?`<div class="prompt-context">${q(t.context)}</div>`:``,r=t.placeholder?`<div class="prompt-placeholder">${q(t.placeholder)}</div>`:``;return`<div class="prompt-block">
312
+ </div>`}).join(``)}</div>`}function xl(e){let t=e;if(!t?.question)return``;let n=t.context?`<div class="prompt-context">${q(t.context)}</div>`:``,r=t.placeholder?`<div class="prompt-placeholder">${q(t.placeholder)}</div>`:``;return`<div class="prompt-block">
313
313
  <div class="prompt-question">${q(t.question)}</div>
314
314
  ${n}${r}
315
- </div>`}function xl(e){let t=e;if(!t?.items||!Array.isArray(t.items))return``;let n=e=>e>=100?`var(--success)`:e>=60?`var(--primary)`:e>=30?`var(--warning)`:`var(--error)`;return`<div class="progress-list">${t.items.map(e=>{let t=e.max??100,r=t>0?Math.min(100,e.value/t*100):0,i=hl(e.color??``)?e.color?.trim()??n(r):n(r);return`<div class="progress-item">
315
+ </div>`}function Sl(e){let t=e;if(!t?.items||!Array.isArray(t.items))return``;let n=e=>e>=100?`var(--success)`:e>=60?`var(--primary)`:e>=30?`var(--warning)`:`var(--error)`;return`<div class="progress-list">${t.items.map(e=>{let t=e.max??100,r=t>0?Math.min(100,e.value/t*100):0,i=gl(e.color??``)?e.color?.trim()??n(r):n(r);return`<div class="progress-item">
316
316
  <div class="progress-header">
317
317
  <span class="progress-label">${q(e.label)}</span>
318
318
  <span class="progress-value">${e.value}/${t}</span>
@@ -320,10 +320,10 @@ $3`),n.push(t);break}case`code`:n.push(`\`\`\`${e.language??``}\n${String(e.valu
320
320
  <div class="progress-track">
321
321
  <div class="progress-fill" style="width:${r.toFixed(1)}%;background:${i}"></div>
322
322
  </div>
323
- </div>`}).join(``)}</div>`}function Sl(e){let t=e,n=t?.label?.trim()||t?.viewerType?.trim()||`Open viewer`,r=t?.description?.trim(),i=t?.icon?.trim()||`🔗`,a=`<div style="border-left:4px solid var(--color-primary, #818cf8); padding:12px 16px; margin:8px 0; border-radius:8px; background:var(--color-card, #1e293b);">
323
+ </div>`}).join(``)}</div>`}function Cl(e){let t=e,n=t?.label?.trim()||t?.viewerType?.trim()||`Open viewer`,r=t?.description?.trim(),i=t?.icon?.trim()||`🔗`,a=`<div style="border-left:4px solid var(--color-primary, #818cf8); padding:12px 16px; margin:8px 0; border-radius:8px; background:var(--color-card, #1e293b);">
324
324
  <div style="font-weight:600; font-size:1rem; margin-bottom:${r?`4px`:`0`};">${q(i)} ${q(n)}</div>
325
325
  ${r?`<div style="font-size:0.85rem; color:var(--color-muted, #94a3b8);">${q(r)}</div>`:``}
326
- </div>`;return t?.url?`<a href="${ml(t.url)?q(t.url):`#`}" style="display:block; color:inherit; text-decoration:none;">${a}</a>`:a}function Cl(e){let t=e,n=Array.isArray(t?.files)?t.files:[],r={current:`background:#14532d; color:#bbf7d0; border:1px solid #166534;`,stale:`background:#713f12; color:#fde68a; border:1px solid #a16207;`,missing:`background:#7f1d1d; color:#fecaca; border:1px solid #b91c1c;`};return`<div class="docs-browser" style="border:1px solid var(--color-border, #334155); border-radius:8px; overflow:hidden; background:var(--color-surface, transparent);">${t?.title?.trim()?`<div style="padding:12px 12px 0; font-weight:600; color:var(--color-text, #e2e8f0);">${q(t.title)}</div>`:``}${n.length?n.map((e,t)=>{let n=e?.path?.trim()||`document-${t+1}`,i=e?.title?.trim()||n.split(/[\\/]/).pop()||n,a=e?.status&&r[e.status]?`<span style="display:inline-flex; align-items:center; padding:2px 8px; border-radius:999px; font-size:0.75rem; text-transform:uppercase; letter-spacing:0.04em; ${r[e.status]}">${q(e.status)}</span>`:``,o=typeof e?.content==`string`&&e.content.trim().length>0?`<div class="md-content">${An.parse(e.content)}</div>`:`<div style="font-size:0.85rem; color:var(--color-muted, #94a3b8);">No content available.</div>`;return`<details${t===0?` open`:``}>
326
+ </div>`;return t?.url?`<a href="${hl(t.url)?q(t.url):`#`}" style="display:block; color:inherit; text-decoration:none;">${a}</a>`:a}function wl(e){let t=e,n=Array.isArray(t?.files)?t.files:[],r={current:`background:#14532d; color:#bbf7d0; border:1px solid #166534;`,stale:`background:#713f12; color:#fde68a; border:1px solid #a16207;`,missing:`background:#7f1d1d; color:#fecaca; border:1px solid #b91c1c;`};return`<div class="docs-browser" style="border:1px solid var(--color-border, #334155); border-radius:8px; overflow:hidden; background:var(--color-surface, transparent);">${t?.title?.trim()?`<div style="padding:12px 12px 0; font-weight:600; color:var(--color-text, #e2e8f0);">${q(t.title)}</div>`:``}${n.length?n.map((e,t)=>{let n=e?.path?.trim()||`document-${t+1}`,i=e?.title?.trim()||n.split(/[\\/]/).pop()||n,a=e?.status&&r[e.status]?`<span style="display:inline-flex; align-items:center; padding:2px 8px; border-radius:999px; font-size:0.75rem; text-transform:uppercase; letter-spacing:0.04em; ${r[e.status]}">${q(e.status)}</span>`:``,o=typeof e?.content==`string`&&e.content.trim().length>0?`<div class="md-content">${An.parse(e.content)}</div>`:`<div style="font-size:0.85rem; color:var(--color-muted, #94a3b8);">No content available.</div>`;return`<details${t===0?` open`:``}>
327
327
  <summary style="padding:8px 12px; cursor:pointer; background:var(--color-card, #1e293b); display:flex; align-items:center; justify-content:space-between; gap:12px;">
328
328
  <div style="display:flex; flex-direction:column; gap:2px; min-width:0;">
329
329
  <span style="font-family:monospace; font-size:0.85rem; color:var(--color-muted, #94a3b8); word-break:break-all;">${q(n)}</span>
@@ -332,26 +332,26 @@ $3`),n.push(t);break}case`code`:n.push(`\`\`\`${e.language??``}\n${String(e.valu
332
332
  ${a}
333
333
  </summary>
334
334
  <div style="padding:12px; border-top:1px solid var(--color-border, #334155);">${o}</div>
335
- </details>`}).join(``):`<div style="padding:12px; color:var(--color-muted, #94a3b8);">No documentation files.</div>`}</div>`}const J=U;function wl(e){return Math.abs(e)>=1e6?`${(e/1e6).toFixed(1).replace(/\.0$/,``)}M`:Math.abs(e)>=1e3?`${(e/1e3).toFixed(1).replace(/\.0$/,``)}k`:Number.isInteger(e)?String(e):e.toFixed(1)}function Tl(e){return`var(--chart-${e%12+1})`}let El=0;function Dl(e){let t=e.value;if(!t?.data?.length||!t.chartType)return`<pre>${J(JSON.stringify(e.value,null,2))}</pre>`;El++;let n=e.title||t.title?`<div class="chart-title">${J(String(e.title||t.title))}</div>`:``,r;switch(t.chartType){case`line`:r=Fl(t,!1);break;case`area`:r=Fl(t,!0);break;case`bar`:r=Il(t,!1);break;case`horizontal-bar`:r=Il(t,!0);break;case`pie`:r=Ll(t,!1);break;case`donut`:r=Ll(t,!0);break;case`sparkline`:r=Rl(t);break;case`heatmap`:r=zl(t);break;default:r=`<pre>${J(JSON.stringify(t,null,2))}</pre>`}let i=t.showLegend!==!1&&t.yKeys.length>1&&t.chartType!==`sparkline`?Ol(t.yKeys):``;return`<div class="chart-container">${n}${r}${i}</div>`}function Ol(e){return`<div class="chart-legend">${e.map((e,t)=>`<span class="chart-legend-item"><span class="chart-legend-swatch" style="background:${Tl(t)}"></span>${J(e)}</span>`).join(``)}</div>`}const Y={top:20,right:20,bottom:35,left:55};function kl(e,t){return e.map(e=>Number(e[t])||0)}function Al(e,t){return e.map(e=>String(e[t]??``))}function jl(e){let t=1/0,n=-1/0;for(let r of e)r<t&&(t=r),r>n&&(n=r);return t===n&&(t=t===0?0:t*.9,n=n===0?1:n*1.1),[t,n]}function Ml(e){return e>=0?0:e}function Nl(e,t,n,r=5){let i=[];for(let a=0;a<=r;a++){let o=a/r,s=Y.top+n-o*n,c=e+o*(t-e);i.push(`<line class="chart-grid-line" x1="${Y.left}" x2="${600-Y.right}" y1="${s}" y2="${s}"/>`),i.push(`<text class="chart-axis-label" x="${Y.left-8}" y="${s+4}" text-anchor="end">${wl(c)}</text>`)}return i.join(``)}function Pl(e,t,n,r){let i=Math.floor(t/50),a=Math.max(1,Math.ceil(e.length/i));return e.map((e,t)=>t%a===0?`<text class="chart-axis-label" x="${Y.left+t*r+r/2}" y="${Y.top+n+18}" text-anchor="middle">${J(e.length>10?`${e.slice(0,9)}…`:e)}</text>`:``).join(``)}function Fl(e,t){let n=(e.height??300)-Y.top-Y.bottom,r=600-Y.left-Y.right,i=Al(e.data,e.xKey),a=e.data.length;if(a===0)return``;let o=r/Math.max(a-1,1),s=1/0,c=-1/0;for(let t of e.yKeys){let[n,r]=jl(kl(e.data,t));n<s&&(s=n),r>c&&(c=r)}s=Ml(s);let l=c-s||1,u=e=>Y.top+n-(e-s)/l*n,d=e=>Y.left+e*o,f=``,p=[];for(let r=0;r<e.yKeys.length;r++){let i=kl(e.data,e.yKeys[r]),o=Tl(r),s=`M${i.map((e,t)=>`${d(t).toFixed(1)},${u(e).toFixed(1)}`).join(`L`)}`;if(t){let e=`ag${El}_${r}`;f+=`<linearGradient id="${e}" x1="0" y1="0" x2="0" y2="1">
335
+ </details>`}).join(``):`<div style="padding:12px; color:var(--color-muted, #94a3b8);">No documentation files.</div>`}</div>`}const J=U;function Tl(e){return Math.abs(e)>=1e6?`${(e/1e6).toFixed(1).replace(/\.0$/,``)}M`:Math.abs(e)>=1e3?`${(e/1e3).toFixed(1).replace(/\.0$/,``)}k`:Number.isInteger(e)?String(e):e.toFixed(1)}function El(e){return`var(--chart-${e%12+1})`}let Dl=0;function Ol(e){let t=e.value;if(!t?.data?.length||!t.chartType)return`<pre>${J(JSON.stringify(e.value,null,2))}</pre>`;Dl++;let n=e.title||t.title?`<div class="chart-title">${J(String(e.title||t.title))}</div>`:``,r;switch(t.chartType){case`line`:r=Il(t,!1);break;case`area`:r=Il(t,!0);break;case`bar`:r=Ll(t,!1);break;case`horizontal-bar`:r=Ll(t,!0);break;case`pie`:r=Rl(t,!1);break;case`donut`:r=Rl(t,!0);break;case`sparkline`:r=zl(t);break;case`heatmap`:r=Bl(t);break;default:r=`<pre>${J(JSON.stringify(t,null,2))}</pre>`}let i=t.showLegend!==!1&&t.yKeys.length>1&&t.chartType!==`sparkline`?kl(t.yKeys):``;return`<div class="chart-container">${n}${r}${i}</div>`}function kl(e){return`<div class="chart-legend">${e.map((e,t)=>`<span class="chart-legend-item"><span class="chart-legend-swatch" style="background:${El(t)}"></span>${J(e)}</span>`).join(``)}</div>`}const Y={top:20,right:20,bottom:35,left:55};function Al(e,t){return e.map(e=>Number(e[t])||0)}function jl(e,t){return e.map(e=>String(e[t]??``))}function Ml(e){let t=1/0,n=-1/0;for(let r of e)r<t&&(t=r),r>n&&(n=r);return t===n&&(t=t===0?0:t*.9,n=n===0?1:n*1.1),[t,n]}function Nl(e){return e>=0?0:e}function Pl(e,t,n,r=5){let i=[];for(let a=0;a<=r;a++){let o=a/r,s=Y.top+n-o*n,c=e+o*(t-e);i.push(`<line class="chart-grid-line" x1="${Y.left}" x2="${600-Y.right}" y1="${s}" y2="${s}"/>`),i.push(`<text class="chart-axis-label" x="${Y.left-8}" y="${s+4}" text-anchor="end">${Tl(c)}</text>`)}return i.join(``)}function Fl(e,t,n,r){let i=Math.floor(t/50),a=Math.max(1,Math.ceil(e.length/i));return e.map((e,t)=>t%a===0?`<text class="chart-axis-label" x="${Y.left+t*r+r/2}" y="${Y.top+n+18}" text-anchor="middle">${J(e.length>10?`${e.slice(0,9)}…`:e)}</text>`:``).join(``)}function Il(e,t){let n=(e.height??300)-Y.top-Y.bottom,r=600-Y.left-Y.right,i=jl(e.data,e.xKey),a=e.data.length;if(a===0)return``;let o=r/Math.max(a-1,1),s=1/0,c=-1/0;for(let t of e.yKeys){let[n,r]=Ml(Al(e.data,t));n<s&&(s=n),r>c&&(c=r)}s=Nl(s);let l=c-s||1,u=e=>Y.top+n-(e-s)/l*n,d=e=>Y.left+e*o,f=``,p=[];for(let r=0;r<e.yKeys.length;r++){let i=Al(e.data,e.yKeys[r]),o=El(r),s=`M${i.map((e,t)=>`${d(t).toFixed(1)},${u(e).toFixed(1)}`).join(`L`)}`;if(t){let e=`ag${Dl}_${r}`;f+=`<linearGradient id="${e}" x1="0" y1="0" x2="0" y2="1">
336
336
  <stop offset="0%" stop-color="${o}" stop-opacity="0.3"/>
337
337
  <stop offset="100%" stop-color="${o}" stop-opacity="0"/>
338
- </linearGradient>`;let t=`${s}L${d(a-1).toFixed(1)},${(Y.top+n).toFixed(1)}L${d(0).toFixed(1)},${(Y.top+n).toFixed(1)}Z`;p.push(`<path d="${t}" fill="url(#${e})" stroke="none"/>`)}p.push(`<path d="${s}" fill="none" stroke="${o}" stroke-width="2" stroke-linejoin="round" stroke-linecap="round"/>`);for(let e=0;e<i.length;e++)p.push(`<circle cx="${d(e).toFixed(1)}" cy="${u(i[e]).toFixed(1)}" r="3" fill="${o}" stroke="var(--card)" stroke-width="1.5"/>`)}let m=e.height??300,h=e.showGrid===!1?``:Nl(s,c,n),g=Pl(i,r,n,a>1?o:r);return`<svg class="chart-svg" viewBox="0 0 600 ${m}" preserveAspectRatio="xMidYMid meet">
338
+ </linearGradient>`;let t=`${s}L${d(a-1).toFixed(1)},${(Y.top+n).toFixed(1)}L${d(0).toFixed(1)},${(Y.top+n).toFixed(1)}Z`;p.push(`<path d="${t}" fill="url(#${e})" stroke="none"/>`)}p.push(`<path d="${s}" fill="none" stroke="${o}" stroke-width="2" stroke-linejoin="round" stroke-linecap="round"/>`);for(let e=0;e<i.length;e++)p.push(`<circle cx="${d(e).toFixed(1)}" cy="${u(i[e]).toFixed(1)}" r="3" fill="${o}" stroke="var(--card)" stroke-width="1.5"/>`)}let m=e.height??300,h=e.showGrid===!1?``:Pl(s,c,n),g=Fl(i,r,n,a>1?o:r);return`<svg class="chart-svg" viewBox="0 0 600 ${m}" preserveAspectRatio="xMidYMid meet">
339
339
  ${f?`<defs>${f}</defs>`:``}
340
340
  ${h}${g}${p.join(``)}
341
- </svg>`}function Il(e,t){let n=(e.height??300)-Y.top-Y.bottom,r=600-Y.left-Y.right,i=Al(e.data,e.xKey),a=e.data.length;if(a===0)return``;let o=e.yKeys.length,s=0;for(let t of e.yKeys)for(let n of kl(e.data,t))n>s&&(s=n);s===0&&(s=1);let c=e.height??300,l=[];if(t){let t=Math.min(24,(n-(a-1)*4)/(a*o)),u=t*o+4,d=e.showGrid===!1?``:Nl(0,s,n),f=i.map((e,t)=>{let n=Y.top+t*u+u/2,r=e.length>15?`${e.slice(0,14)}…`:e;return`<text class="chart-axis-label" x="${Y.left-8}" y="${n+4}" text-anchor="end">${J(r)}</text>`}).join(``);for(let n=0;n<a;n++)for(let i=0;i<o;i++){let a=Number(e.data[n][e.yKeys[i]])||0,o=a/s*r,c=Y.top+n*u+i*t;l.push(`<rect x="${Y.left}" y="${c}" width="${o.toFixed(1)}" height="${t-2}" rx="3" fill="${Tl(i)}" opacity="0.85">
342
- <title>${J(e.yKeys[i])}: ${wl(a)}</title>
341
+ </svg>`}function Ll(e,t){let n=(e.height??300)-Y.top-Y.bottom,r=600-Y.left-Y.right,i=jl(e.data,e.xKey),a=e.data.length;if(a===0)return``;let o=e.yKeys.length,s=0;for(let t of e.yKeys)for(let n of Al(e.data,t))n>s&&(s=n);s===0&&(s=1);let c=e.height??300,l=[];if(t){let t=Math.min(24,(n-(a-1)*4)/(a*o)),u=t*o+4,d=e.showGrid===!1?``:Pl(0,s,n),f=i.map((e,t)=>{let n=Y.top+t*u+u/2,r=e.length>15?`${e.slice(0,14)}…`:e;return`<text class="chart-axis-label" x="${Y.left-8}" y="${n+4}" text-anchor="end">${J(r)}</text>`}).join(``);for(let n=0;n<a;n++)for(let i=0;i<o;i++){let a=Number(e.data[n][e.yKeys[i]])||0,o=a/s*r,c=Y.top+n*u+i*t;l.push(`<rect x="${Y.left}" y="${c}" width="${o.toFixed(1)}" height="${t-2}" rx="3" fill="${El(i)}" opacity="0.85">
342
+ <title>${J(e.yKeys[i])}: ${Tl(a)}</title>
343
343
  </rect>`)}return`<svg class="chart-svg" viewBox="0 0 600 ${Math.max(c,a*u+Y.top+Y.bottom)}" preserveAspectRatio="xMidYMid meet">
344
344
  ${d}${f}${l.join(``)}
345
- </svg>`}else{let t=r/a,u=Math.min(40,(t-8)/o),d=e.showGrid===!1?``:Nl(0,s,n),f=Pl(i,r,n,t);for(let r=0;r<a;r++)for(let i=0;i<o;i++){let a=Number(e.data[r][e.yKeys[i]])||0,c=a/s*n,d=Y.left+r*t+(t-u*o)/2+i*u,f=Y.top+n-c;l.push(`<rect x="${d.toFixed(1)}" y="${f.toFixed(1)}" width="${(u-2).toFixed(1)}" height="${c.toFixed(1)}" rx="3" fill="${Tl(i)}" opacity="0.85">
346
- <title>${J(e.yKeys[i])}: ${wl(a)}</title>
345
+ </svg>`}else{let t=r/a,u=Math.min(40,(t-8)/o),d=e.showGrid===!1?``:Pl(0,s,n),f=Fl(i,r,n,t);for(let r=0;r<a;r++)for(let i=0;i<o;i++){let a=Number(e.data[r][e.yKeys[i]])||0,c=a/s*n,d=Y.left+r*t+(t-u*o)/2+i*u,f=Y.top+n-c;l.push(`<rect x="${d.toFixed(1)}" y="${f.toFixed(1)}" width="${(u-2).toFixed(1)}" height="${c.toFixed(1)}" rx="3" fill="${El(i)}" opacity="0.85">
346
+ <title>${J(e.yKeys[i])}: ${Tl(a)}</title>
347
347
  </rect>`)}return`<svg class="chart-svg" viewBox="0 0 600 ${c}" preserveAspectRatio="xMidYMid meet">
348
348
  ${d}${f}${l.join(``)}
349
- </svg>`}}function Ll(e,t){let n=e.height??300,r=n/2,i=n/2,a=n/2-10,o=t?a*.55:0,s=e.yKeys[0]||`value`,c=e.data.map(e=>Math.max(0,Number(e[s])||0)),l=Al(e.data,e.xKey),u=c.reduce((e,t)=>e+t,0);if(u===0)return`<div style="color:var(--muted-foreground);text-align:center;padding:20px">No data</div>`;let d=[],f=-Math.PI/2;for(let e=0;e<c.length;e++){let t=c[e]/u;if(t===0)continue;let n=t*Math.PI*2,s=f,p=f+n,m=r+a*Math.cos(s),h=i+a*Math.sin(s),g=r+a*Math.cos(p),_=i+a*Math.sin(p),v=+(n>Math.PI),y;if(o>0){let e=r+o*Math.cos(s),t=i+o*Math.sin(s),n=r+o*Math.cos(p),c=i+o*Math.sin(p);y=`M${m.toFixed(2)},${h.toFixed(2)} A${a},${a} 0 ${v},1 ${g.toFixed(2)},${_.toFixed(2)} L${n.toFixed(2)},${c.toFixed(2)} A${o},${o} 0 ${v},0 ${e.toFixed(2)},${t.toFixed(2)}Z`}else y=`M${r},${i} L${m.toFixed(2)},${h.toFixed(2)} A${a},${a} 0 ${v},1 ${g.toFixed(2)},${_.toFixed(2)}Z`;d.push(`<path d="${y}" fill="${Tl(e)}" stroke="var(--background)" stroke-width="2" opacity="0.9">
350
- <title>${J(l[e]||`Item ${e+1}`)}: ${wl(c[e])} (${(t*100).toFixed(1)}%)</title>
351
- </path>`),f=p}let p=t?`<text x="${r}" y="${i-6}" text-anchor="middle" fill="var(--foreground)" font-size="18" font-weight="700">${wl(u)}</text>
352
- <text x="${r}" y="${i+12}" text-anchor="middle" fill="var(--muted-foreground)" font-size="11">Total</text>`:``,m=Ol(l.filter((e,t)=>c[t]>0));return`<svg class="chart-svg" viewBox="0 0 ${n} ${n}" preserveAspectRatio="xMidYMid meet">
349
+ </svg>`}}function Rl(e,t){let n=e.height??300,r=n/2,i=n/2,a=n/2-10,o=t?a*.55:0,s=e.yKeys[0]||`value`,c=e.data.map(e=>Math.max(0,Number(e[s])||0)),l=jl(e.data,e.xKey),u=c.reduce((e,t)=>e+t,0);if(u===0)return`<div style="color:var(--muted-foreground);text-align:center;padding:20px">No data</div>`;let d=[],f=-Math.PI/2;for(let e=0;e<c.length;e++){let t=c[e]/u;if(t===0)continue;let n=t*Math.PI*2,s=f,p=f+n,m=r+a*Math.cos(s),h=i+a*Math.sin(s),g=r+a*Math.cos(p),_=i+a*Math.sin(p),v=+(n>Math.PI),y;if(o>0){let e=r+o*Math.cos(s),t=i+o*Math.sin(s),n=r+o*Math.cos(p),c=i+o*Math.sin(p);y=`M${m.toFixed(2)},${h.toFixed(2)} A${a},${a} 0 ${v},1 ${g.toFixed(2)},${_.toFixed(2)} L${n.toFixed(2)},${c.toFixed(2)} A${o},${o} 0 ${v},0 ${e.toFixed(2)},${t.toFixed(2)}Z`}else y=`M${r},${i} L${m.toFixed(2)},${h.toFixed(2)} A${a},${a} 0 ${v},1 ${g.toFixed(2)},${_.toFixed(2)}Z`;d.push(`<path d="${y}" fill="${El(e)}" stroke="var(--background)" stroke-width="2" opacity="0.9">
350
+ <title>${J(l[e]||`Item ${e+1}`)}: ${Tl(c[e])} (${(t*100).toFixed(1)}%)</title>
351
+ </path>`),f=p}let p=t?`<text x="${r}" y="${i-6}" text-anchor="middle" fill="var(--foreground)" font-size="18" font-weight="700">${Tl(u)}</text>
352
+ <text x="${r}" y="${i+12}" text-anchor="middle" fill="var(--muted-foreground)" font-size="11">Total</text>`:``,m=kl(l.filter((e,t)=>c[t]>0));return`<svg class="chart-svg" viewBox="0 0 ${n} ${n}" preserveAspectRatio="xMidYMid meet">
353
353
  ${d.join(``)}${p}
354
- </svg>${m}`}function Rl(e){let t=e.height??40,n=e.yKeys[0]||`value`,r=kl(e.data,n),i=r.length;if(i===0)return``;let[a,o]=jl(r),s=o-a||1,c=200/Math.max(i-1,1),l=r.map((e,n)=>`${(n*c).toFixed(1)},${(t-4-(e-a)/s*(t-8)).toFixed(1)}`),u=`spk${El}`,d=Tl(0);return`<svg class="chart-svg" viewBox="0 0 200 ${t}" preserveAspectRatio="xMidYMid meet" style="max-width:200px;height:${t}px">
354
+ </svg>${m}`}function zl(e){let t=e.height??40,n=e.yKeys[0]||`value`,r=Al(e.data,n),i=r.length;if(i===0)return``;let[a,o]=Ml(r),s=o-a||1,c=200/Math.max(i-1,1),l=r.map((e,n)=>`${(n*c).toFixed(1)},${(t-4-(e-a)/s*(t-8)).toFixed(1)}`),u=`spk${Dl}`,d=El(0);return`<svg class="chart-svg" viewBox="0 0 200 ${t}" preserveAspectRatio="xMidYMid meet" style="max-width:200px;height:${t}px">
355
355
  <defs>
356
356
  <linearGradient id="${u}" x1="0" y1="0" x2="0" y2="1">
357
357
  <stop offset="0%" stop-color="${d}" stop-opacity="0.2"/>
@@ -361,15 +361,15 @@ $3`),n.push(t);break}case`code`:n.push(`\`\`\`${e.language??``}\n${String(e.valu
361
361
  <path d="M${l.join(`L`)}L${((i-1)*c).toFixed(1)},${t}L0,${t}Z" fill="url(#${u})" stroke="none"/>
362
362
  <polyline points="${l.join(` `)}" fill="none" stroke="${d}" stroke-width="1.5" stroke-linejoin="round"/>
363
363
  <circle cx="${((i-1)*c).toFixed(1)}" cy="${l[i-1].split(`,`)[1]}" r="2.5" fill="${d}"/>
364
- </svg>`}function zl(e){let t=Al(e.data,e.xKey),n=e.data.length,r=e.yKeys.length;if(n===0||r===0)return``;let i=1/0,a=-1/0;for(let t of e.yKeys)for(let n of kl(e.data,t))n<i&&(i=n),n>a&&(a=n);let o=a-i||1,s=Math.min(50,(600-Y.left-Y.right)/n),c=Math.min(30,200/r),l=Y.left+n*s+Y.right,u=Y.top+r*c+Y.bottom,d=[];for(let t=0;t<r;t++){let n=Y.top+t*c+c/2+4,r=e.yKeys[t].length>8?`${e.yKeys[t].slice(0,7)}…`:e.yKeys[t];d.push(`<text class="chart-axis-label" x="${Y.left-8}" y="${n}" text-anchor="end">${J(r)}</text>`)}let f=Math.floor((l-Y.left)/40),p=Math.max(1,Math.ceil(n/f));for(let e=0;e<n;e++){if(e%p!==0)continue;let n=Y.left+e*s+s/2,r=t[e].length>6?`${t[e].slice(0,5)}…`:t[e];d.push(`<text class="chart-axis-label" x="${n}" y="${u-8}" text-anchor="middle">${J(r)}</text>`)}for(let a=0;a<n;a++)for(let n=0;n<r;n++){let r=Number(e.data[a][e.yKeys[n]])||0,l=(r-i)/o,u=Y.left+a*s,f=Y.top+n*c;d.push(`<rect x="${u}" y="${f}" width="${s-1}" height="${c-1}" rx="2" fill="var(--primary)" opacity="${(.1+l*.8).toFixed(2)}">
365
- <title>${J(t[a])} / ${J(e.yKeys[n])}: ${wl(r)}</title>
364
+ </svg>`}function Bl(e){let t=jl(e.data,e.xKey),n=e.data.length,r=e.yKeys.length;if(n===0||r===0)return``;let i=1/0,a=-1/0;for(let t of e.yKeys)for(let n of Al(e.data,t))n<i&&(i=n),n>a&&(a=n);let o=a-i||1,s=Math.min(50,(600-Y.left-Y.right)/n),c=Math.min(30,200/r),l=Y.left+n*s+Y.right,u=Y.top+r*c+Y.bottom,d=[];for(let t=0;t<r;t++){let n=Y.top+t*c+c/2+4,r=e.yKeys[t].length>8?`${e.yKeys[t].slice(0,7)}…`:e.yKeys[t];d.push(`<text class="chart-axis-label" x="${Y.left-8}" y="${n}" text-anchor="end">${J(r)}</text>`)}let f=Math.floor((l-Y.left)/40),p=Math.max(1,Math.ceil(n/f));for(let e=0;e<n;e++){if(e%p!==0)continue;let n=Y.left+e*s+s/2,r=t[e].length>6?`${t[e].slice(0,5)}…`:t[e];d.push(`<text class="chart-axis-label" x="${n}" y="${u-8}" text-anchor="middle">${J(r)}</text>`)}for(let a=0;a<n;a++)for(let n=0;n<r;n++){let r=Number(e.data[a][e.yKeys[n]])||0,l=(r-i)/o,u=Y.left+a*s,f=Y.top+n*c;d.push(`<rect x="${u}" y="${f}" width="${s-1}" height="${c-1}" rx="2" fill="var(--primary)" opacity="${(.1+l*.8).toFixed(2)}">
365
+ <title>${J(t[a])} / ${J(e.yKeys[n])}: ${Tl(r)}</title>
366
366
  </rect>`)}return`<svg class="chart-svg" viewBox="0 0 ${l} ${u}" preserveAspectRatio="xMidYMid meet">
367
367
  ${d.join(``)}
368
- </svg>`}function Bl(e){if(e.length===0)return`<p><em>empty table</em></p>`;let t=Object.keys(e[0]);return`<div class="table-wrap"><table><thead><tr>${t.map(e=>`<th>${U(e)}</th>`).join(``)}</tr></thead><tbody>${e.map(e=>`<tr>${t.map(t=>`<td>${U(String(e[t]??``))}</td>`).join(``)}</tr>`).join(`
369
- `)}</tbody></table></div>`}function Vl(e){return`<div class="metric-grid">${e.map(e=>`<div class="metric"><div class="metric-value">${U(String(e.value))}</div><div class="metric-label">${U(e.label)}</div></div>`).join(``)}</div>`}function Hl(e){return`<div class="card-grid">${e.map(e=>{let t=[`<div class="card">`];return e.title&&t.push(`<div class="card-title">${U(String(e.title))}</div>`),(e.body||e.description)&&t.push(`<div class="card-body">${U(String(e.body??e.description))}</div>`),(e.badge||e.status)&&t.push(`<span class="badge">${U(String(e.badge??e.status))}</span>`),t.push(`</div>`),t.join(``)}).join(``)}</div>`}function Ul(e){if(`name`in e&&`children`in e&&Array.isArray(e.children))return Wl(e);if(`name`in e&&!(`children`in e))return`<div class="tree-node"><span class="tree-key">${U(String(e.name))}</span></div>`;let t=[];for(let[n,r]of Object.entries(e))typeof r==`object`&&r&&!Array.isArray(r)?t.push(`<div class="tree-node"><span class="tree-key">${U(n)}:</span><div class="tree-children">${Ul(r)}</div></div>`):t.push(`<div class="tree-node"><span class="tree-key">${U(n)}:</span> ${U(Fa(r))}</div>`);return t.join(``)}function Wl(e){let t=U(String(e.name));return!e.children||e.children.length===0?`<div class="tree-node"><span class="tree-key">${t}</span></div>`:`<div class="tree-node"><span class="tree-key">${t}</span><div class="tree-children">${e.children.map(e=>typeof e==`object`&&e?Wl(e):`<div class="tree-node"><span class="tree-key">${U(String(e))}</span></div>`).join(``)}</div></div>`}function Gl(e){let t=[`graph LR`];for(let n of e.nodes){let e=Ia(String(n.id??n.name??``)),r=String(n.label??n.name??e);t.push(` ${e}["${r}"]`)}for(let n of e.edges){let e=Ia(String(n.source??n.from??``)),r=Ia(String(n.target??n.to??``)),i=n.label?`|${String(n.label)}|`:``;t.push(` ${e} -->${i} ${r}`)}return t.join(`
370
- `)}function Kl(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ql(e){return e.replace(/<table\b/g,`<div class="table-wrap"><table`).replace(/<\/table>/g,`</table></div>`)}function Jl(e,t){if(typeof e!=`object`||!e)return`<p>${U(String(e))}</p>`;let n=e;return typeof n.type==`string`?hu(Jc(n),t):`<pre>${U(JSON.stringify(e,null,2))}</pre>`}function Yl(e,t,n=`inline`){let r=[];if(e&&r.push(`<h1>${U(e)}</h1>`),typeof t==`string`)r.push(`<div class="md-content">${ql(An.parse(t))}</div>`);else if(Array.isArray(t))if(t.length===0)r.push(`<p><em>empty</em></p>`);else if(Xc(t[0]))for(let e of t)r.push(Jl(e,n));else typeof t[0]==`object`&&t[0]!==null?r.push(Bl(t)):r.push(`<ul>${t.map(e=>`<li>${U(String(e))}</li>`).join(``)}</ul>`);else if(typeof t==`object`&&t){let e=t;if(Array.isArray(e.blocks)&&e.blocks.length>0)for(let t of e.blocks)r.push(Jl(t,n));else Array.isArray(e.metrics)?r.push(Vl(e.metrics)):Array.isArray(e.nodes)&&Array.isArray(e.edges)?(r.push(`<pre class="mermaid">${U(Gl(e))}</pre>`),r.push(`<script src="https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.min.js"><\/script>`),r.push(`<script>mermaid.run();<\/script>`)):r.push(Ul(e))}else r.push(`<p>${U(String(t))}</p>`);return r.join(`
371
- `)}function Xl(e){return`<div class="md-content">${ql(An.parse(String(e.value??``)))}</div>`}function Zl(e){return`<pre><code>${U(String(e.value??``))}</code></pre>`}function Ql(e){return`<pre class="mermaid">${U(String(e.value??``))}</pre>`}function $l(e){if(Array.isArray(e.value)){let t=e.value;if(t.length>0&&Array.isArray(t[0])){let e=t,n=e[0].map(String);return Bl(e.slice(1).map(e=>Object.fromEntries(n.map((t,n)=>[t,e[n]]))))}return Bl(t)}if(e.value&&typeof e.value==`object`&&`headers`in e.value&&`rows`in e.value){let{headers:t,rows:n}=e.value;return Bl(n.map(e=>Object.fromEntries(t.map((t,n)=>[t,e[n]]))))}return``}function eu(e){let t;return Array.isArray(e.value)?t=e.value:e.value&&typeof e.value==`object`&&(t=Object.entries(e.value).map(([e,t])=>({label:e,value:String(t)}))),t?Vl(t):``}function tu(e){return Array.isArray(e.value)?Hl(e.value):``}function nu(e){return e.value&&typeof e.value==`object`?Ul(e.value):``}function ru(e,t){return!e.value||typeof e.value!=`object`?``:`<pre class="mermaid">${U(Gl(e.value))}</pre>`}function iu(e){let t=e.value;return Array.isArray(t)&&(t={items:t.map(e=>({title:String(e.event??e.title??``),phase:e.date==null?e.phase==null?void 0:String(e.phase):String(e.date),description:e.description==null?void 0:String(e.description),status:e.status??`done`}))}),t?gl(t):``}function au(e){return e.value?_l(Array.isArray(e.value)?{items:e.value}:e.value):``}function ou(e){return e.value?vl(Array.isArray(e.value)?{columns:e.value}:e.value):``}function su(e){return e.value?yl(Array.isArray(e.value)?{items:e.value}:e.value):``}function cu(e){if(!e.value)return``;let t=e.value;return Array.isArray(t)?t={items:t}:Kl(t)&&!(`items`in t)&&`label`in t&&`value`in t&&(t={items:[t]}),xl(t)}function lu(e){return`<div class="md-content">${An.parse(String(e.value??``))}</div>`}function uu(e){let t=Math.min(Math.max(Number(e.level)||2,1),6);return`<h${t}>${U(String(e.value??``))}</h${t}>`}function du(e){return`<p>${U(String(e.value??``))}</p>`}function fu(e){return`<div class="action-bar">${(Array.isArray(e.value)?e.value:[]).map(e=>{if(e.type===`select`){let t=Array.isArray(e.options)?e.options.map(e=>`<option value="${U(String(e.value??e.label??``))}">${U(String(e.label??e.value??``))}</option>`).join(``):``;return`<select class="action-select"><option value="">${U(String(e.label??`Select...`))}</option>${t}</select>`}return`<button class="action-btn action-${String(e.variant??`secondary`)}">${U(String(e.label??``))}</button>`}).join(``)}</div>`}function pu(e){return`<pre>${U(JSON.stringify(e.value,null,2))}</pre>`}const mu=new Map([[`markdown`,e=>Xl(e)],[`code`,e=>Zl(e)],[`mermaid`,e=>Ql(e)],[`table`,e=>$l(e)],[`metrics`,e=>eu(e)],[`cards`,e=>tu(e)],[`tree`,e=>nu(e)],[`graph`,(e,t)=>ru(e,t)],[`chart`,e=>Dl(e)],[`timeline`,e=>iu(e)],[`checklist`,e=>au(e)],[`comparison`,e=>ou(e)],[`status-board`,e=>su(e)],[`prompt`,e=>e.value?bl(e.value):``],[`progress`,e=>cu(e)],[`viewer-link`,e=>e.value?Sl(e.value):``],[`docs-browser`,e=>e.value?Cl(e.value):``],[`text`,e=>lu(e)],[`heading`,e=>uu(e)],[`paragraph`,e=>du(e)],[`separator`,()=>`<hr class="separator">`],[`actions`,e=>fu(e)]]);function hu(e,t=`inline`){let n=[];e.title&&n.push(`<h2>${U(e.title)}</h2>`);let r=mu.get(e.type);return n.push(r?r(e,t):pu(e)),n.join(`
372
- `)}const gu=import.meta.dirname??g(b(import.meta.url));function _u(e){let t=e;for(let e=0;e<10;e++){try{let e=v(t,`package.json`);if(o(e)&&JSON.parse(c(e,`utf8`)).name===`@vpxa/aikit`)return t}catch{}let e=g(t);if(e===t)break;t=e}return y(e,`..`,`..`,`..`)}const vu=`ui://aikit/present.html`;function yu(e){return Array.isArray(e)?e:[]}function bu(e){return e.length===0?``:`<section class="present-inline-actions"><div class="action-bar">${e.map(e=>{let t=U(String(e.id??``)),n=U(String(e.label??`Action`));return e.type===`select`?`<label class="action-select-wrap"><span>${n}</span><select class="action-select" data-present-action="select" data-action-id="${t}"><option value="">${n}</option>${Array.isArray(e.options)?e.options.map(e=>{if(typeof e==`string`){let t=U(e);return`<option value="${t}">${t}</option>`}return`<option value="${U(String(e.value??e.label??``))}">${U(String(e.label??e.value??``))}</option>`}).join(``):``}</select></label>`:`<button type="button" class="action-btn action-${U(String(e.variant??`default`))}" data-present-action="button" data-action-id="${t}" data-action-value="clicked">${n}</button>`}).join(``)}</div><div id="action-feedback" class="action-feedback" aria-live="polite"></div></section>`}function xu(e,t,n){return`<!DOCTYPE html>
368
+ </svg>`}function Vl(e){if(e.length===0)return`<p><em>empty table</em></p>`;let t=Object.keys(e[0]);return`<div class="table-wrap"><table><thead><tr>${t.map(e=>`<th>${U(e)}</th>`).join(``)}</tr></thead><tbody>${e.map(e=>`<tr>${t.map(t=>`<td>${U(String(e[t]??``))}</td>`).join(``)}</tr>`).join(`
369
+ `)}</tbody></table></div>`}function Hl(e){return`<div class="metric-grid">${e.map(e=>`<div class="metric"><div class="metric-value">${U(String(e.value))}</div><div class="metric-label">${U(e.label)}</div></div>`).join(``)}</div>`}function Ul(e){return`<div class="card-grid">${e.map(e=>{let t=[`<div class="card">`];return e.title&&t.push(`<div class="card-title">${U(String(e.title))}</div>`),(e.body||e.description)&&t.push(`<div class="card-body">${U(String(e.body??e.description))}</div>`),(e.badge||e.status)&&t.push(`<span class="badge">${U(String(e.badge??e.status))}</span>`),t.push(`</div>`),t.join(``)}).join(``)}</div>`}function Wl(e){if(`name`in e&&`children`in e&&Array.isArray(e.children))return Gl(e);if(`name`in e&&!(`children`in e))return`<div class="tree-node"><span class="tree-key">${U(String(e.name))}</span></div>`;let t=[];for(let[n,r]of Object.entries(e))typeof r==`object`&&r&&!Array.isArray(r)?t.push(`<div class="tree-node"><span class="tree-key">${U(n)}:</span><div class="tree-children">${Wl(r)}</div></div>`):t.push(`<div class="tree-node"><span class="tree-key">${U(n)}:</span> ${U(Fa(r))}</div>`);return t.join(``)}function Gl(e){let t=U(String(e.name));return!e.children||e.children.length===0?`<div class="tree-node"><span class="tree-key">${t}</span></div>`:`<div class="tree-node"><span class="tree-key">${t}</span><div class="tree-children">${e.children.map(e=>typeof e==`object`&&e?Gl(e):`<div class="tree-node"><span class="tree-key">${U(String(e))}</span></div>`).join(``)}</div></div>`}function Kl(e){let t=[`graph LR`];for(let n of e.nodes){let e=Ia(String(n.id??n.name??``)),r=String(n.label??n.name??e);t.push(` ${e}["${r}"]`)}for(let n of e.edges){let e=Ia(String(n.source??n.from??``)),r=Ia(String(n.target??n.to??``)),i=n.label?`|${String(n.label)}|`:``;t.push(` ${e} -->${i} ${r}`)}return t.join(`
370
+ `)}function ql(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Jl(e){return e.replace(/<table\b/g,`<div class="table-wrap"><table`).replace(/<\/table>/g,`</table></div>`)}function Yl(e,t){if(typeof e!=`object`||!e)return`<p>${U(String(e))}</p>`;let n=e;return typeof n.type==`string`?gu(Jc(n),t):`<pre>${U(JSON.stringify(e,null,2))}</pre>`}function Xl(e,t,n=`inline`){let r=[];if(e&&r.push(`<h1>${U(e)}</h1>`),typeof t==`string`)r.push(`<div class="md-content">${Jl(An.parse(t))}</div>`);else if(Array.isArray(t))if(t.length===0)r.push(`<p><em>empty</em></p>`);else if(Xc(t[0]))for(let e of t)r.push(Yl(e,n));else typeof t[0]==`object`&&t[0]!==null?r.push(Vl(t)):r.push(`<ul>${t.map(e=>`<li>${U(String(e))}</li>`).join(``)}</ul>`);else if(typeof t==`object`&&t){let e=t;if(Array.isArray(e.blocks)&&e.blocks.length>0)for(let t of e.blocks)r.push(Yl(t,n));else Array.isArray(e.metrics)?r.push(Hl(e.metrics)):Array.isArray(e.nodes)&&Array.isArray(e.edges)?(r.push(`<pre class="mermaid">${U(Kl(e))}</pre>`),r.push(`<script src="https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.min.js"><\/script>`),r.push(`<script>mermaid.run();<\/script>`)):r.push(Wl(e))}else r.push(`<p>${U(String(t))}</p>`);return r.join(`
371
+ `)}function Zl(e){return`<div class="md-content">${Jl(An.parse(String(e.value??``)))}</div>`}function Ql(e){return`<pre><code>${U(String(e.value??``))}</code></pre>`}function $l(e){return`<pre class="mermaid">${U(String(e.value??``))}</pre>`}function eu(e){if(Array.isArray(e.value)){let t=e.value;if(t.length>0&&Array.isArray(t[0])){let e=t,n=e[0].map(String);return Vl(e.slice(1).map(e=>Object.fromEntries(n.map((t,n)=>[t,e[n]]))))}return Vl(t)}if(e.value&&typeof e.value==`object`&&`headers`in e.value&&`rows`in e.value){let{headers:t,rows:n}=e.value;return Vl(n.map(e=>Object.fromEntries(t.map((t,n)=>[t,e[n]]))))}return``}function tu(e){let t;return Array.isArray(e.value)?t=e.value:e.value&&typeof e.value==`object`&&(t=Object.entries(e.value).map(([e,t])=>({label:e,value:String(t)}))),t?Hl(t):``}function nu(e){return Array.isArray(e.value)?Ul(e.value):``}function ru(e){return e.value&&typeof e.value==`object`?Wl(e.value):``}function iu(e,t){return!e.value||typeof e.value!=`object`?``:`<pre class="mermaid">${U(Kl(e.value))}</pre>`}function au(e){let t=e.value;return Array.isArray(t)&&(t={items:t.map(e=>({title:String(e.event??e.title??``),phase:e.date==null?e.phase==null?void 0:String(e.phase):String(e.date),description:e.description==null?void 0:String(e.description),status:e.status??`done`}))}),t?_l(t):``}function ou(e){return e.value?vl(Array.isArray(e.value)?{items:e.value}:e.value):``}function su(e){return e.value?yl(Array.isArray(e.value)?{columns:e.value}:e.value):``}function cu(e){return e.value?bl(Array.isArray(e.value)?{items:e.value}:e.value):``}function lu(e){if(!e.value)return``;let t=e.value;return Array.isArray(t)?t={items:t}:ql(t)&&!(`items`in t)&&`label`in t&&`value`in t&&(t={items:[t]}),Sl(t)}function uu(e){return`<div class="md-content">${An.parse(String(e.value??``))}</div>`}function du(e){let t=Math.min(Math.max(Number(e.level)||2,1),6);return`<h${t}>${U(String(e.value??``))}</h${t}>`}function fu(e){return`<p>${U(String(e.value??``))}</p>`}function pu(e){return`<div class="action-bar">${(Array.isArray(e.value)?e.value:[]).map(e=>{if(e.type===`select`){let t=Array.isArray(e.options)?e.options.map(e=>`<option value="${U(String(e.value??e.label??``))}">${U(String(e.label??e.value??``))}</option>`).join(``):``;return`<select class="action-select"><option value="">${U(String(e.label??`Select...`))}</option>${t}</select>`}return`<button class="action-btn action-${String(e.variant??`secondary`)}">${U(String(e.label??``))}</button>`}).join(``)}</div>`}function mu(e){return`<pre>${U(JSON.stringify(e.value,null,2))}</pre>`}const hu=new Map([[`markdown`,e=>Zl(e)],[`code`,e=>Ql(e)],[`mermaid`,e=>$l(e)],[`table`,e=>eu(e)],[`metrics`,e=>tu(e)],[`cards`,e=>nu(e)],[`tree`,e=>ru(e)],[`graph`,(e,t)=>iu(e,t)],[`chart`,e=>Ol(e)],[`timeline`,e=>au(e)],[`checklist`,e=>ou(e)],[`comparison`,e=>su(e)],[`status-board`,e=>cu(e)],[`prompt`,e=>e.value?xl(e.value):``],[`progress`,e=>lu(e)],[`viewer-link`,e=>e.value?Cl(e.value):``],[`docs-browser`,e=>e.value?wl(e.value):``],[`text`,e=>uu(e)],[`heading`,e=>du(e)],[`paragraph`,e=>fu(e)],[`separator`,()=>`<hr class="separator">`],[`actions`,e=>pu(e)]]);function gu(e,t=`inline`){let n=[];e.title&&n.push(`<h2>${U(e.title)}</h2>`);let r=hu.get(e.type);return n.push(r?r(e,t):mu(e)),n.join(`
372
+ `)}const _u=import.meta.dirname??g(b(import.meta.url));function vu(e){let t=e;for(let e=0;e<10;e++){try{let e=v(t,`package.json`);if(o(e)&&JSON.parse(c(e,`utf8`)).name===`@vpxa/aikit`)return t}catch{}let e=g(t);if(e===t)break;t=e}return y(e,`..`,`..`,`..`)}const yu=`ui://aikit/present.html`;function bu(e){return Array.isArray(e)?e:[]}function xu(e){return e.length===0?``:`<section class="present-inline-actions"><div class="action-bar">${e.map(e=>{let t=U(String(e.id??``)),n=U(String(e.label??`Action`));return e.type===`select`?`<label class="action-select-wrap"><span>${n}</span><select class="action-select" data-present-action="select" data-action-id="${t}"><option value="">${n}</option>${Array.isArray(e.options)?e.options.map(e=>{if(typeof e==`string`){let t=U(e);return`<option value="${t}">${t}</option>`}return`<option value="${U(String(e.value??e.label??``))}">${U(String(e.label??e.value??``))}</option>`}).join(``):``}</select></label>`:`<button type="button" class="action-btn action-${U(String(e.variant??`default`))}" data-present-action="button" data-action-id="${t}" data-action-value="clicked">${n}</button>`}).join(``)}</div><div id="action-feedback" class="action-feedback" aria-live="polite"></div></section>`}function Su(e,t,n){return`<!DOCTYPE html>
373
373
  <html lang="en">
374
374
  <head>
375
375
  <meta charset="utf-8">
@@ -447,8 +447,8 @@ $3`),n.push(t);break}case`code`:n.push(`\`\`\`${e.language??``}\n${String(e.valu
447
447
  </head>
448
448
  <body>
449
449
  <div class="present-inline-root">
450
- ${Yl(e,t,`inline`)}
451
- ${bu(n)}
450
+ ${Xl(e,t,`inline`)}
451
+ ${xu(n)}
452
452
  </div>
453
453
  <script>
454
454
  function sendCallback(actionId, value) {
@@ -483,7 +483,7 @@ $3`),n.push(t);break}case`code`:n.push(`\`\`\`${e.language??``}\n${String(e.valu
483
483
  });
484
484
  <\/script>
485
485
  </body>
486
- </html>`}const Su=F.object({type:F.enum([`button`,`select`]).describe(`Action type`),id:F.string().describe(`Unique action identifier`),label:F.string().describe(`Display label`),variant:F.enum([`primary`,`danger`,`default`]).optional().describe(`Button style variant`),options:F.array(F.union([F.string(),F.object({label:F.string(),value:F.string()})])).optional().describe(`Select options (for type=select)`)}),Cu={format:F.enum([`html`,`browser`]).default(`html`).describe(`Output format.
486
+ </html>`}const Cu=F.object({type:F.enum([`button`,`select`]).describe(`Action type`),id:F.string().describe(`Unique action identifier`),label:F.string().describe(`Display label`),variant:F.enum([`primary`,`danger`,`default`]).optional().describe(`Button style variant`),options:F.array(F.union([F.string(),F.object({label:F.string(),value:F.string()})])).optional().describe(`Select options (for type=select)`)}),wu={format:F.enum([`html`,`browser`]).default(`html`).describe(`Output format.
487
487
  - "html" (default): Rich markdown in chat + embedded UIResource for MCP-UI hosts. Actions shown as numbered choices.
488
488
  - "browser": Rich markdown in chat + opens beautiful themed dashboard in the browser. When actions are provided, the browser shows interactive buttons and the tool blocks until user clicks, returning their selection.`),title:F.string().optional().describe(`Optional heading`),content:F.any().describe(`Content to present. Accepts these shapes:
489
489
  • markdown string — rendered as rich text
@@ -491,7 +491,7 @@ $3`),n.push(t);break}case`code`:n.push(`\`\`\`${e.language??``}\n${String(e.valu
491
491
  • { nodes, edges } — rendered as mermaid graph
492
492
  • typed blocks array [{ type, title?, value }] — the primary format:
493
493
  ${Ec()}\n• any JSON — rendered as collapsible tree
494
- IMPORTANT: For charts, use the ChartValue format above. Do NOT use Chart.js format ({labels, datasets}) — it will be auto-converted but the native format is preferred.`),actions:F.array(Su).optional().describe(`Interactive actions (buttons/selects). In html mode, shown as numbered choices. In browser mode, rendered as clickable buttons and the tool blocks until user clicks.`),template:F.enum([`auto`,`list-sort`,`data-table`,`picker`,`flame-graph`,`form`,`timeline`,`kanban`,`tree`,`diff-view`,`dashboard`]).optional().describe(`UI template for interactive display in MCP Apps hosts.
494
+ IMPORTANT: For charts, use the ChartValue format above. Do NOT use Chart.js format ({labels, datasets}) — it will be auto-converted but the native format is preferred.`),actions:F.array(Cu).optional().describe(`Interactive actions (buttons/selects). In html mode, shown as numbered choices. In browser mode, rendered as clickable buttons and the tool blocks until user clicks.`),template:F.enum([`auto`,`list-sort`,`data-table`,`picker`,`flame-graph`,`form`,`timeline`,`kanban`,`tree`,`diff-view`,`dashboard`]).optional().describe(`UI template for interactive display in MCP Apps hosts.
495
495
  - auto (default): detect from content shape
496
496
  - list-sort: drag-drop reorderable list — content: { items: [{id, label}] }
497
497
  - data-table: filterable sortable table — content: { columns: [{key, label}], rows: [{...}], stats?: [{label, value}] }
@@ -502,15 +502,15 @@ IMPORTANT: For charts, use the ChartValue format above. Do NOT use Chart.js form
502
502
  - kanban: drag-drop board — content: { columns: [{id, label, color?}], cards: [{id, title, column, tags?[], priority?}] }
503
503
  - tree: collapsible tree view — content: { root: {label, children?:[...]} | [...] }
504
504
  - diff-view: side-by-side diff — content: { files: [{path, status, additions, deletions, hunks:[{header, changes:[{type, content}]}]}] }
505
- - dashboard: metric cards grid — content: { metrics: [{label, value, trend?, status?, type?}] }`)};let wu,Tu=!1,Eu=null;process.on(`exit`,()=>{if(Eu){try{Eu.close()}catch{}Eu=null}});function Du(){let e=_u(gu),t=v(e,`packages`,`present`,`dist`,`index.html`);return o(t)?t:v(e,`packages`,`present`,`index.html`)}function Ou(){if(!wu)try{wu=c(Du(),`utf-8`)}catch{wu=``}return wu}function ku(e,t){let n=z(`present`),r=Ou(),i=`Present content to the user in the best format. Two modes:
505
+ - dashboard: metric cards grid — content: { metrics: [{label, value, trend?, status?, type?}] }`)};let Tu,Eu=!1,Du=null;process.on(`exit`,()=>{if(Du){try{Du.close()}catch{}Du=null}});function Ou(){let e=vu(_u),t=v(e,`packages`,`present`,`dist`,`index.html`);return o(t)?t:v(e,`packages`,`present`,`index.html`)}function ku(){if(!Tu)try{Tu=c(Ou(),`utf-8`)}catch{Tu=``}return Tu}function Au(e,t){let n=z(`present`),r=ku(),i=`Present content to the user in the best format. Two modes:
506
506
  - "html" (default): Rich markdown in chat + embedded UIResource. Use for display-only content (tables, charts, reports, status boards) where no user interaction is needed.
507
507
  - "browser": Serves a themed dashboard on a local URL. Use ONLY when you need user interaction back (confirmations, selections, form input). The tool blocks until user clicks an action button, then returns their selection.
508
508
  FORMAT RULE: If no user interaction is needed → use "html". If you need user input back → use "browser".
509
509
  CONTENT GUIDE: Pass typed blocks [{ type, title?, value }] for structured content. See the \`content\` parameter description for all supported block types and their value shapes. For charts: use {chartType, data:Record[], xKey, yKeys} — NOT Chart.js format.
510
- BROWSER WORKFLOW: After calling present with format "browser", you MUST extract the URL from the response and call openBrowserPage({ url }) tool - PlayWright MCP to open it in VS Code Simple Browser. A system browser fallback also opens automatically, but always call openBrowserPage tool - PlayWright MCP yourself.`,a=async({format:e,title:n,content:r,actions:i,template:a})=>{let o=La(r);return(e??`html`)===`browser`||Array.isArray(i)&&i.length>0?await Au(n,o,i,t,a):ju(n,o,i,a)};if(r){Tu||=(bn(e,`AI Kit Present App`,vu,{description:`Rich interactive content viewer for AI Kit tools`},async()=>({contents:[{uri:vu,mimeType:yn,text:r}]})),!0),xn(e,`present`,{title:n.title,description:i,annotations:n.annotations,inputSchema:Cu,_meta:{ui:{resourceUri:vu}}},a);return}e.tool(`present`,i,Cu,n.annotations,a)}async function Au(e,t,n,r,i){let a=ol(e,t,{compactTables:!0}),o=yu(n),s=xu(e,t,o),c=al(e,t,n,i),l=kn({uri:`ui://aikit/present-browser.html`,content:{type:`rawHtml`,htmlString:s},encoding:`text`,adapters:{mcpApps:{enabled:!0}}}),u,d,f=``,p;try{Eu&&=(Eu.close(),null),o.length>0&&(u=new Promise(e=>{d=e}));let e=!1;f=await new Promise((t,n)=>{let r=On((t,n)=>{if(e||(e=!0,p&&clearTimeout(p)),t.method===`POST`&&t.url===`/callback`){let e=``;t.on(`data`,t=>{e+=t.toString()}),t.on(`end`,()=>{n.writeHead(200,{"Content-Type":`application/json`,"Access-Control-Allow-Origin":`*`}),n.end(`{"ok":true}`);try{let t=JSON.parse(e);d?.(t)}catch{}});return}if(t.method===`OPTIONS`){n.writeHead(204,{"Access-Control-Allow-Origin":`*`,"Access-Control-Allow-Methods":`POST`,"Access-Control-Allow-Headers":`Content-Type`}),n.end();return}n.writeHead(200,{"Content-Type":`text/html; charset=utf-8`}),n.end(c)});r.listen(0,`127.0.0.1`,()=>{let i=r.address();if(typeof i==`object`&&i){Eu=r;let n=`http://127.0.0.1:${i.port}`;p=setTimeout(()=>{if(!e)try{Tn(process.platform===`win32`?`start "" "${n}"`:process.platform===`darwin`?`open "${n}"`:`xdg-open "${n}"`)}catch{}},8e3),p.unref(),t(n)}else n(Error(`Failed to start present server`))}),setTimeout(()=>{r.close(),Eu===r&&(Eu=null)},300*1e3).unref()})}catch{}let m=f?`${a}\n\n---\n🌐 **Dashboard opened in browser:** ${f}\n\n**IMPORTANT:** You MUST now open this URL using the \`openBrowserPage\` tool - PlayWright MCP. If that tool is unavailable, open the URL in the system browser as a fallback. If neither works, ask the user to open the URL manually.`:a;if(o.length>0&&r?.available&&u)try{let e=await Promise.race([u,new Promise((e,t)=>setTimeout(()=>t(Error(`timeout`)),300*1e3))]);return{content:[{type:`text`,text:`${m}\n\n✅ **Selected:** ${e.actionId} = \`${e.value}\``},l]}}catch{return{content:[{type:`text`,text:`${m}\n\n⚠️ *No selection received (timed out).*`},l]}}return{content:[{type:`text`,text:m},l]}}function ju(e,t,n,r){let i=yu(n),a=ol(e,t,{compactTables:!0}),o=kn({uri:vu,content:{type:`rawHtml`,htmlString:al(e,t,n,r)},encoding:`text`,adapters:{mcpApps:{enabled:!0}}});return{content:[{type:`text`,text:a},o],structuredContent:{title:e,content:Qc(t),actions:i}}}const Mu=k(`tools`);function Nu(e,t){let n=new on({structure:new cn,dependencies:new nn,symbols:new ln,patterns:new sn,entryPoints:new an,diagrams:new rn}),r=z(`produce_knowledge`);e.registerTool(`produce_knowledge`,{title:r.title,description:`Run automated codebase analysis and produce synthesis instructions. Executes Tier 1 deterministic analyzers, then returns structured baselines and instructions for you to synthesize knowledge using remember.`,inputSchema:{scope:F.string().optional().describe(`Root path to analyze (defaults to workspace root)`),aspects:F.array(F.enum([`all`,`structure`,`dependencies`,`symbols`,`patterns`,`entry-points`,`diagrams`])).default([`all`]).describe(`Which analysis aspects to run`)},annotations:r.annotations},async({scope:e,aspects:r})=>{try{let i=e??`.`;Mu.info(`Running knowledge production`,{rootPath:i,aspects:r});let a=await n.runExtraction(i,r);try{let e=t?.onboardDir??v(i,`.ai`,`context`);s(e,{recursive:!0});let n=`<!-- Generated by produce_knowledge at ${new Date().toISOString()} -->\n\n`;for(let[t,r]of Object.entries(a))r&&typeof r==`string`&&p(v(e,`${t}.md`),n+r,`utf-8`);Mu.info(`Knowledge persisted to .ai/context/`,{files:Object.keys(a).length})}catch(e){Mu.warn(`Failed to persist knowledge to .ai/context/`,{error:j(e)})}return{content:[{type:`text`,text:n.buildSynthesisInstructions(a,r)+`
510
+ BROWSER WORKFLOW: After calling present with format "browser", you MUST extract the URL from the response and call openBrowserPage({ url }) tool - PlayWright MCP to open it in VS Code Simple Browser. A system browser fallback also opens automatically, but always call openBrowserPage tool - PlayWright MCP yourself.`,a=async({format:e,title:n,content:r,actions:i,template:a})=>{let o=La(r);return(e??`html`)===`browser`||Array.isArray(i)&&i.length>0?await ju(n,o,i,t,a):Mu(n,o,i)};if(r){Eu||=(bn(e,`AI Kit Present App`,yu,{description:`Rich interactive content viewer for AI Kit tools`},async()=>({contents:[{uri:yu,mimeType:yn,text:r}]})),!0),xn(e,`present`,{title:n.title,description:i,annotations:n.annotations,inputSchema:wu,_meta:{ui:{resourceUri:yu}}},a);return}e.tool(`present`,i,wu,n.annotations,a)}async function ju(e,t,n,r,i){let a=sl(e,t,{compactTables:!0}),o=bu(n),s=Su(e,t,o),c=ol(e,t,n,i),l=kn({uri:`ui://aikit/present-browser.html`,content:{type:`rawHtml`,htmlString:s},encoding:`text`,adapters:{mcpApps:{enabled:!0}}}),u,d,f=``,p;try{Du&&=(Du.close(),null),o.length>0&&(u=new Promise(e=>{d=e}));let e=!1;f=await new Promise((t,n)=>{let r=On((t,n)=>{if(e||(e=!0,p&&clearTimeout(p)),t.method===`POST`&&t.url===`/callback`){let e=``;t.on(`data`,t=>{e+=t.toString()}),t.on(`end`,()=>{n.writeHead(200,{"Content-Type":`application/json`,"Access-Control-Allow-Origin":`*`}),n.end(`{"ok":true}`);try{let t=JSON.parse(e);d?.(t)}catch{}});return}if(t.method===`OPTIONS`){n.writeHead(204,{"Access-Control-Allow-Origin":`*`,"Access-Control-Allow-Methods":`POST`,"Access-Control-Allow-Headers":`Content-Type`}),n.end();return}n.writeHead(200,{"Content-Type":`text/html; charset=utf-8`}),n.end(c)});r.listen(0,`127.0.0.1`,()=>{let i=r.address();if(typeof i==`object`&&i){Du=r;let n=`http://127.0.0.1:${i.port}`;p=setTimeout(()=>{if(!e)try{Tn(process.platform===`win32`?`start "" "${n}"`:process.platform===`darwin`?`open "${n}"`:`xdg-open "${n}"`)}catch{}},8e3),p.unref(),t(n)}else n(Error(`Failed to start present server`))}),setTimeout(()=>{r.close(),Du===r&&(Du=null)},300*1e3).unref()})}catch{}let m=f?`${a}\n\n---\n🌐 **Dashboard opened in browser:** ${f}\n\n**IMPORTANT:** You MUST now open this URL using the \`openBrowserPage\` tool - PlayWright MCP. If that tool is unavailable, open the URL in the system browser as a fallback. If neither works, ask the user to open the URL manually.`:a;if(o.length>0&&r?.available&&u)try{let e=await Promise.race([u,new Promise((e,t)=>setTimeout(()=>t(Error(`timeout`)),300*1e3))]);return{content:[{type:`text`,text:`${m}\n\n✅ **Selected:** ${e.actionId} = \`${e.value}\``},l]}}catch{return{content:[{type:`text`,text:`${m}\n\n⚠️ *No selection received (timed out).*`},l]}}return{content:[{type:`text`,text:m},l]}}function Mu(e,t,n){let r=bu(n),i=sl(e,t,{compactTables:!0}),a=kn({uri:yu,content:{type:`rawHtml`,htmlString:Xl(e,t)},encoding:`text`,adapters:{mcpApps:{enabled:!0}}});return{content:[{type:`text`,text:i},a],structuredContent:{title:e,content:Qc(t),actions:r}}}const Nu=k(`tools`);function Pu(e,t){let n=new on({structure:new cn,dependencies:new nn,symbols:new ln,patterns:new sn,entryPoints:new an,diagrams:new rn}),r=z(`produce_knowledge`);e.registerTool(`produce_knowledge`,{title:r.title,description:`Run automated codebase analysis and produce synthesis instructions. Executes Tier 1 deterministic analyzers, then returns structured baselines and instructions for you to synthesize knowledge using remember.`,inputSchema:{scope:F.string().optional().describe(`Root path to analyze (defaults to workspace root)`),aspects:F.array(F.enum([`all`,`structure`,`dependencies`,`symbols`,`patterns`,`entry-points`,`diagrams`])).default([`all`]).describe(`Which analysis aspects to run`)},annotations:r.annotations},async({scope:e,aspects:r})=>{try{let i=e??`.`;Nu.info(`Running knowledge production`,{rootPath:i,aspects:r});let a=await n.runExtraction(i,r);try{let e=t?.onboardDir??v(i,`.ai`,`context`);s(e,{recursive:!0});let n=`<!-- Generated by produce_knowledge at ${new Date().toISOString()} -->\n\n`;for(let[t,r]of Object.entries(a))r&&typeof r==`string`&&p(v(e,`${t}.md`),n+r,`utf-8`);Nu.info(`Knowledge persisted to .ai/context/`,{files:Object.keys(a).length})}catch(e){Nu.warn(`Failed to persist knowledge to .ai/context/`,{error:j(e)})}return{content:[{type:`text`,text:n.buildSynthesisInstructions(a,r)+`
511
511
 
512
512
  ---
513
- _Next: Review the baselines above and use \`remember\` to store synthesized knowledge entries._`}]}}catch(e){return Mu.error(`Knowledge production failed`,j(e)),H(`INTERNAL`,`Knowledge production failed: ${e instanceof Error?e.message:String(e)}`)}})}const X=k(`tools`);function Pu(e,t,n,r,i,a,o){let s=z(`reindex`);e.registerTool(`reindex`,{title:s.title,description:`Trigger re-indexing of the AI Kit index. Can do incremental (only changed files) or full re-index. When smart indexing is active, use force: true to override the automatic trickle indexer.`,inputSchema:{full:F.boolean().default(!1).describe(`If true, force full re-index ignoring file hashes`),force:F.boolean().default(!1).describe(`If true, override smart indexing guard and run reindex anyway`)},annotations:s.annotations},async({full:e,force:s},c)=>{try{if(t.isIndexing)return{content:[{type:`text`,text:`## Reindex Already in Progress
513
+ _Next: Review the baselines above and use \`remember\` to store synthesized knowledge entries._`}]}}catch(e){return Nu.error(`Knowledge production failed`,j(e)),H(`INTERNAL`,`Knowledge production failed: ${e instanceof Error?e.message:String(e)}`)}})}const X=k(`tools`);function Fu(e,t,n,r,i,a,o){let s=z(`reindex`);e.registerTool(`reindex`,{title:s.title,description:`Trigger re-indexing of the AI Kit index. Can do incremental (only changed files) or full re-index. When smart indexing is active, use force: true to override the automatic trickle indexer.`,inputSchema:{full:F.boolean().default(!1).describe(`If true, force full re-index ignoring file hashes`),force:F.boolean().default(!1).describe(`If true, override smart indexing guard and run reindex anyway`)},annotations:s.annotations},async({full:e,force:s},c)=>{try{if(t.isIndexing)return{content:[{type:`text`,text:`## Reindex Already in Progress
514
514
 
515
515
  A reindex operation is currently running. Search and other tools continue to work with existing data. Use \`status({})\` to check when it completes.`}]};if(o===`smart`&&!s)return{content:[{type:`text`,text:`## Smart Indexing Active
516
516
 
@@ -518,38 +518,38 @@ Smart indexing (trickle mode) is enabled — files are automatically indexed as
518
518
 
519
519
  **If the index is severely outdated**, use \`reindex({ force: true })\` to override.
520
520
 
521
- Use \`status({})\` to check smart indexing queue status.`}]};let l=Ea(c).createTask(`Reindex`,1);l.progress(0,`Starting ${e?`full`:`incremental`} reindex`),X.info(`Starting background re-index`,{mode:e?`full`:`incremental`});let u=e=>t=>{t.phase===`chunking`&&t.currentFile&&X.debug(`Re-index progress`,{prefix:e,current:t.filesProcessed+1,total:t.filesTotal,file:t.currentFile})};return(e?t.reindexAll(n,u(`Reindex`)):t.index(n,u(`Index`))).then(async e=>{if(X.info(`Background re-index complete`,{filesProcessed:e.filesProcessed,chunksCreated:e.chunksCreated,durationMs:e.durationMs}),l.complete(`Reindex complete: ${e.filesProcessed} files, ${e.chunksCreated} chunks in ${e.durationMs}ms`),i)try{await i.createFtsIndex(),X.info(`FTS index rebuilt after reindex`)}catch(e){X.warn(`FTS index rebuild failed`,j(e))}try{let e=await r.reindexAll();X.info(`Curated re-index complete`,{indexed:e.indexed})}catch(e){X.warn(`Curated re-index failed`,j(e))}if(a)try{await a.notifyAfterReindex()}catch(e){X.warn(`Post-reindex resource notification failed`,j(e))}}).catch(e=>{l.fail(`Reindex failed: ${e instanceof Error?e.message:String(e)}`),X.error(`Background reindex failed`,j(e))}),{content:[{type:`text`,text:`## Reindex Started (Background)\n\n- **Mode**: ${e?`Full`:`Incremental`}\n- Search and other tools continue to work with existing data during reindex.\n- Completion will be logged. Use \`status({})\` to check index stats afterward.\n\n---\n_Next: Continue working — the reindex runs in the background._`}]}}catch(e){return X.error(`Reindex failed`,j(e)),H(`INTERNAL`,`Reindex failed: ${e instanceof Error?e.message:String(e)}`)}})}const Fu=k(`tools`);function Iu(e){let t=z(`replay`);e.registerTool(`replay`,{title:t.title,description:`View or clear the audit trail of recent MCP tool and CLI invocations. Shows tool name, duration, status, and input/output summaries.`,inputSchema:{action:F.enum([`list`,`clear`]).default(`list`).describe(`Action: "list" (default) to view entries, "clear" to wipe the log`),last:F.number().optional().describe(`Number of entries to return (default: 20, list only)`),tool:F.string().optional().describe(`Filter by tool name (list only)`),source:F.enum([`mcp`,`cli`]).optional().describe(`Filter by source: "mcp" or "cli" (list only)`),since:F.string().optional().describe(`ISO timestamp — only show entries after this time (list only)`)},annotations:t.annotations},async({action:e,last:t,tool:n,source:r,since:i})=>{try{if(e===`clear`)return St(),{content:[{type:`text`,text:`Replay log cleared.`}]};let a=Ct({last:t,tool:n,source:r,since:i});if(a.length===0)return{content:[{type:`text`,text:`No replay entries found. Activity is logged when tools are invoked via MCP or CLI.`}]};let o=a.map(e=>`${e.ts.split(`T`)[1]?.split(`.`)[0]??e.ts} ${e.status===`ok`?`✓`:`✗`} ${e.tool} (${e.durationMs}ms) [${e.source}]\n in: ${e.input}\n out: ${e.output}`);return wt().catch(()=>{}),{content:[{type:`text`,text:`**Replay Log** (${a.length} entries)\n\n${o.join(`
521
+ Use \`status({})\` to check smart indexing queue status.`}]};let l=Ea(c).createTask(`Reindex`,1);l.progress(0,`Starting ${e?`full`:`incremental`} reindex`),X.info(`Starting background re-index`,{mode:e?`full`:`incremental`});let u=e=>t=>{t.phase===`chunking`&&t.currentFile&&X.debug(`Re-index progress`,{prefix:e,current:t.filesProcessed+1,total:t.filesTotal,file:t.currentFile})};return(e?t.reindexAll(n,u(`Reindex`)):t.index(n,u(`Index`))).then(async e=>{if(X.info(`Background re-index complete`,{filesProcessed:e.filesProcessed,chunksCreated:e.chunksCreated,durationMs:e.durationMs}),l.complete(`Reindex complete: ${e.filesProcessed} files, ${e.chunksCreated} chunks in ${e.durationMs}ms`),i)try{await i.createFtsIndex(),X.info(`FTS index rebuilt after reindex`)}catch(e){X.warn(`FTS index rebuild failed`,j(e))}try{let e=await r.reindexAll();X.info(`Curated re-index complete`,{indexed:e.indexed})}catch(e){X.warn(`Curated re-index failed`,j(e))}if(a)try{await a.notifyAfterReindex()}catch(e){X.warn(`Post-reindex resource notification failed`,j(e))}}).catch(e=>{l.fail(`Reindex failed: ${e instanceof Error?e.message:String(e)}`),X.error(`Background reindex failed`,j(e))}),{content:[{type:`text`,text:`## Reindex Started (Background)\n\n- **Mode**: ${e?`Full`:`Incremental`}\n- Search and other tools continue to work with existing data during reindex.\n- Completion will be logged. Use \`status({})\` to check index stats afterward.\n\n---\n_Next: Continue working — the reindex runs in the background._`}]}}catch(e){return X.error(`Reindex failed`,j(e)),H(`INTERNAL`,`Reindex failed: ${e instanceof Error?e.message:String(e)}`)}})}const Iu=k(`tools`);function Lu(e){let t=z(`replay`);e.registerTool(`replay`,{title:t.title,description:`View or clear the audit trail of recent MCP tool and CLI invocations. Shows tool name, duration, status, and input/output summaries.`,inputSchema:{action:F.enum([`list`,`clear`]).default(`list`).describe(`Action: "list" (default) to view entries, "clear" to wipe the log`),last:F.number().optional().describe(`Number of entries to return (default: 20, list only)`),tool:F.string().optional().describe(`Filter by tool name (list only)`),source:F.enum([`mcp`,`cli`]).optional().describe(`Filter by source: "mcp" or "cli" (list only)`),since:F.string().optional().describe(`ISO timestamp — only show entries after this time (list only)`)},annotations:t.annotations},async({action:e,last:t,tool:n,source:r,since:i})=>{try{if(e===`clear`)return St(),{content:[{type:`text`,text:`Replay log cleared.`}]};let a=Ct({last:t,tool:n,source:r,since:i});if(a.length===0)return{content:[{type:`text`,text:`No replay entries found. Activity is logged when tools are invoked via MCP or CLI.`}]};let o=a.map(e=>`${e.ts.split(`T`)[1]?.split(`.`)[0]??e.ts} ${e.status===`ok`?`✓`:`✗`} ${e.tool} (${e.durationMs}ms) [${e.source}]\n in: ${e.input}\n out: ${e.output}`);return wt().catch(()=>{}),{content:[{type:`text`,text:`**Replay Log** (${a.length} entries)\n\n${o.join(`
522
522
 
523
- `)}`}]}}catch(e){return Fu.error(`Replay failed`,j(e)),H(`INTERNAL`,`Replay failed: ${e instanceof Error?e.message:String(e)}`)}})}const Lu=k(`tools`);function Ru(e){let t=z(`restore`);e.registerTool(`restore`,{title:t.title,description:`List and restore file snapshots taken before destructive operations (codemod, rename, forget). Use action=list to see available restore points, action=restore with an id to undo.`,inputSchema:{action:F.enum([`list`,`restore`]).describe(`list: show restore points, restore: apply a restore point`),id:F.string().optional().describe(`Restore point ID (required for action=restore)`),limit:F.number().min(1).max(50).default(10).describe(`Max restore points to list`)},annotations:t.annotations},async({action:e,id:t,limit:n})=>{try{if(e===`list`){let e=Ze().slice(0,n);return e.length===0?{content:[{type:`text`,text:`No restore points found.`}]}:{content:[{type:`text`,text:`## Restore Points\n\n${e.map(e=>`- **${e.id}** (${e.timestamp}) — ${e.operation}: ${e.description} (${e.files.length} files)`).join(`
523
+ `)}`}]}}catch(e){return Iu.error(`Replay failed`,j(e)),H(`INTERNAL`,`Replay failed: ${e instanceof Error?e.message:String(e)}`)}})}const Ru=k(`tools`);function zu(e){let t=z(`restore`);e.registerTool(`restore`,{title:t.title,description:`List and restore file snapshots taken before destructive operations (codemod, rename, forget). Use action=list to see available restore points, action=restore with an id to undo.`,inputSchema:{action:F.enum([`list`,`restore`]).describe(`list: show restore points, restore: apply a restore point`),id:F.string().optional().describe(`Restore point ID (required for action=restore)`),limit:F.number().min(1).max(50).default(10).describe(`Max restore points to list`)},annotations:t.annotations},async({action:e,id:t,limit:n})=>{try{if(e===`list`){let e=Ze().slice(0,n);return e.length===0?{content:[{type:`text`,text:`No restore points found.`}]}:{content:[{type:`text`,text:`## Restore Points\n\n${e.map(e=>`- **${e.id}** (${e.timestamp}) — ${e.operation}: ${e.description} (${e.files.length} files)`).join(`
524
524
  `)}`}]}}if(!t)throw Error(`id is required for restore action`);let r=await Tt(t);return{content:[{type:`text`,text:`Restored ${r.length} files:\n${r.map(e=>`- \`${e}\``).join(`
525
- `)}`}]}}catch(e){return Lu.error(`Restore failed`,j(e)),H(`INTERNAL`,`Restore failed: ${e instanceof Error?e.message:String(e)}`)}})}const zu=/<\/?curated-context>/gi;function Bu(e){return e.replace(zu,``)}function Vu(e){return`<curated-context>\n${Bu(e)}\n</curated-context>`}const Hu=k(`tools`);function Uu(e){let t=[],n=h(process.cwd());n&&t.push(`[project: ${n}]`);let r=Nt(`__context_boost`);return r&&t.push(`[focus: ${r.value}]`),t.length===0?e:`${t.join(` `)} ${e}`}async function Wu(e,t,n,r,i){if(!e||t>=e.config.fallbackThreshold&&n.length>0)return{results:n,triggered:!1,cacheHit:!1};let a=!1;try{let t=e.cache.get(r);return t?a=!0:(t=await e.client.search(r,i),t.length>0&&e.cache.set(r,t)),t.length>0?{results:vn(n,t,i).map(e=>({record:{id:`er:${e.sourcePath}`,content:e.content,sourcePath:e.source===`er`?`[ER] ${e.sourcePath}`:e.sourcePath,startLine:e.startLine??0,endLine:e.endLine??0,contentType:e.contentType??`documentation`,headingPath:e.headingPath,origin:e.source===`er`?`curated`:e.origin??`indexed`,category:e.category,tags:e.tags??[],chunkIndex:0,totalChunks:1,fileHash:``,indexedAt:new Date().toISOString(),version:1},score:e.score})),triggered:!0,cacheHit:a}:{results:n,triggered:!0,cacheHit:a}}catch(e){return Hu.warn(`ER fallback failed`,j(e)),{results:n,triggered:!0,cacheHit:a}}}function Gu(e,t,n=60){let r=new Map,i=e[0]?.score||1,a=t[0]?.score||1;for(let t=0;t<e.length;t++){let a=e[t],o=a.score/i;r.set(a.record.id,{record:a.record,score:1/(n+t+1)*o})}for(let e=0;e<t.length;e++){let i=t[e],o=i.score/a,s=r.get(i.record.id);s?s.score+=1/(n+e+1)*o:r.set(i.record.id,{record:i.record,score:1/(n+e+1)*o})}return[...r.values()].sort((e,t)=>t.score-e.score).map(({record:e,score:t})=>({record:e,score:t}))}function Ku(e,t){let n=t.toLowerCase().split(/\s+/).filter(e=>e.length>=2);return n.length<2?e:e.map(e=>{let t=e.record.content.toLowerCase();if(t.length>5e3)return e;let r=n.map(e=>{let n=[],r=t.indexOf(e);for(;r!==-1&&n.length<10;)n.push(r),r=t.indexOf(e,r+1);return n});if(r.some(e=>e.length===0))return e;let i=t.length;for(let e of r[0]){let t=e,a=e+n[0].length;for(let i=1;i<r.length;i++){let o=r[i][0],s=Math.abs(o-e);for(let t=1;t<r[i].length;t++){let n=Math.abs(r[i][t]-e);n<s&&(s=n,o=r[i][t])}t=Math.min(t,o),a=Math.max(a,o+n[i].length)}i=Math.min(i,a-t)}let a=1+.25/(1+i/200);return{record:e.record,score:e.score*a}}).sort((e,t)=>t.score-e.score)}function qu(e){if(e.length<=1)return e;let t=new Set;return e.filter(e=>{let n=e.record.contentHash;return n?t.has(n)?!1:(t.add(n),!0):!0})}function Ju(e,t,n=8){let r=new Set(t.toLowerCase().split(/\s+/).filter(e=>e.length>=2)),i=new Map,a=e.length;for(let t of e){let e=t.record.content.split(/[^a-zA-Z0-9_]+/).filter(e=>e.length>=3&&!Yu.has(e.toLowerCase())),n=new Set;for(let t of e){let e=t.toLowerCase();/[_A-Z]/.test(t)&&i.set(`__id__${e}`,1),n.has(e)||(n.add(e),i.set(e,(i.get(e)??0)+1))}}let o=[];for(let[e,t]of i){if(e.startsWith(`__id__`)||r.has(e)||t>a*.8)continue;let n=Math.log(a/t),s=+!!i.has(`__id__${e}`),c=e.length>8?.5:0;o.push({term:e,score:n+s+c})}return o.sort((e,t)=>t.score-e.score).slice(0,n).map(e=>e.term)}const Yu=new Set(`the.and.for.are.but.not.you.all.can.had.her.was.one.our.out.has.have.from.this.that.with.they.been.said.each.which.their.will.other.about.many.then.them.these.some.would.make.like.into.could.time.very.when.come.just.know.take.people.also.back.after.only.more.than.over.such.import.export.const.function.return.true.false.null.undefined.string.number.boolean.void.type.interface`.split(`.`));async function Xu(e,t){try{let n=await e.getStats();if(!n.lastIndexedAt)return;let r=new Date(n.lastIndexedAt).getTime(),i=Date.now(),a=[...new Set(t.map(e=>e.record.sourcePath))].filter(e=>!e.startsWith(`[ER]`)).slice(0,5);if(a.length===0)return;let o=0;for(let e of a)try{(await Yt(e)).mtimeMs>r&&o++}catch{o++}if(o>0){let e=i-r,t=Math.floor(e/6e4),n=t<1?`<1 min`:`${t} min`;return`> ⚠️ **Index may be stale** — ${o} file(s) modified since last index (${n} ago). Use \`reindex\` to refresh.`}}catch{}}function Zu(e,t,n,r,i,a,o){let s=z(`search`);e.registerTool(`search`,{title:s.title,description:`Search AI Kit for code, docs, and prior decisions. Default choice for discovery. Modes: hybrid (default), semantic, keyword. For multi-strategy precision queries use find; for a known file path use lookup.`,outputSchema:Ei,inputSchema:{query:F.string().max(5e3).describe(`Natural language search query`),limit:F.number().min(1).max(20).default(5).describe(`Maximum results to return`),search_mode:F.enum([`hybrid`,`semantic`,`keyword`]).default(`hybrid`).describe(`Search strategy: hybrid (vector + FTS + RRF fusion, default), semantic (vector only), keyword (FTS only)`),content_type:F.enum(S).optional().describe(`Filter by content type`),source_type:F.enum(T).optional().describe(`Coarse filter: "source" (code only), "documentation" (md, curated), "test", "config". Overrides content_type if both set.`),origin:F.enum(w).optional().describe(`Filter by knowledge origin`),category:F.string().optional().describe(`Filter by category (e.g., decisions, patterns, conventions)`),tags:F.array(F.string()).optional().describe(`Filter by tags (returns results matching ANY of the specified tags)`),min_score:F.number().min(0).max(1).default(.25).describe(`Minimum similarity score`),graph_hops:F.number().min(0).max(3).default(1).describe(`Number of graph hops to augment results with connected entities (0 = disabled, 1 = direct connections, 2-3 = deeper traversal). Default 1 provides module/symbol context automatically.`),max_tokens:F.number().min(100).max(5e4).optional().describe(`Maximum token budget for the response. When set, output is truncated to fit.`),dedup:F.enum([`file`,`chunk`]).default(`chunk`).describe(`Deduplication mode: "chunk" (default, show all matching chunks) or "file" (collapse chunks from same file into single result with merged line ranges)`),workspaces:F.array(F.string()).optional().describe(`Cross-workspace search: partition names or folder basenames to include. Use ["*"] for all registered workspaces. Only works in user-level install mode.`)},annotations:s.annotations},async({query:e,limit:s,search_mode:c,content_type:l,source_type:u,origin:d,category:f,tags:p,min_score:m,graph_hops:h,max_tokens:g,dedup:_,workspaces:v})=>{try{let y={limit:s,minScore:m,contentType:l,sourceType:u,origin:d,category:f,tags:p},b,x=!1,S=!1,C=``,w=Uu(e);if(c===`keyword`)b=await n.ftsSearch(e,y),b=b.slice(0,s);else if(c===`semantic`){let r=await t.embedQuery(w);b=await n.search(r,y);let a=await Wu(i,b[0]?.score??0,b,e,s);b=a.results,x=a.triggered,S=a.cacheHit}else{let r=await t.embedQuery(w),a=n.coarseSearch,o=a?a.bind(n):n.search.bind(n),[c,l]=await Promise.all([o(r,{...y,limit:s*2}),n.ftsSearch(e,{...y,limit:s*2}).catch(()=>[])]);c.length===0&&l.length>0?(b=l.slice(0,s),C=` (FTS-only: vector index rebuilding)`):b=l.length===0&&c.length>0?c.slice(0,s):Gu(c,l).slice(0,s);let u=await Wu(i,c[0]?.score??0,b,e,s);b=u.results,x=u.triggered,S=u.cacheHit}a&&a.recordSearch(e,x,S),b.length>1&&(b=Ku(b,e)),b=qu(b);let T=``;if(v&&v.length>0){let n=io(v,O(process.cwd()));if(n.length>0){let{stores:r,closeAll:i}=await ao(n);try{let i;i=c===`keyword`?await so(r,e,{...y,limit:s}):await oo(r,await t.embedQuery(e),{...y,limit:s});for(let e of i)b.push({record:{...e.record,sourcePath:`[${e.workspace}] ${e.record.sourcePath}`},score:e.score});b=b.sort((e,t)=>t.score-e.score).slice(0,s),T=` + ${n.length} workspace(s)`}finally{await i()}}}if(_===`file`&&b.length>1){let e=new Map;for(let t of b){let n=t.record.sourcePath,r=e.get(n);r?(t.score>r.best.score&&(r.best=t),r.ranges.push({start:t.record.startLine,end:t.record.endLine})):e.set(n,{best:t,ranges:[{start:t.record.startLine,end:t.record.endLine}]})}b=[...e.values()].sort((e,t)=>t.best.score-e.best.score).map(({best:e,ranges:t})=>({record:{...e.record,content:t.length>1?`${e.record.content}\n\n_Matched ${t.length} sections: ${t.sort((e,t)=>e.start-t.start).map(e=>`L${e.start}-${e.end}`).join(`, `)}_`:e.record.content},score:e.score}))}if(b.length>1){let e=b[0].score,t=Math.max(e*.4,.1);b=b.filter(e=>e.score>=t)}if(b.length===0){if(o?.available)try{let r=(await o.createMessage({prompt:`The search query "${e}" returned 0 results in AI Kit code search. Suggest ONE alternative search query that might find relevant results. Reply with ONLY the alternative query, nothing else.`,systemPrompt:`You are a search query optimizer for AI Kit code search. Generate a single alternative query.`,maxTokens:100})).text.trim().split(`
526
- `)[0].slice(0,500);if(r&&r!==e){let i=await t.embedQuery(r),a=await n.search(i,y);a.length>0&&(b=a,C=`> _Original query "${e}" returned 0 results. Auto-reformulated to "${r}"._\n\n`,Hu.info(`Smart search fallback succeeded`,{originalQuery:e,altQuery:r,resultCount:a.length}))}}catch(e){Hu.debug(`Smart search fallback failed`,{error:String(e)})}if(b.length===0)return{content:[{type:`text`,text:`No results found for the given query.`}],structuredContent:{results:[],totalResults:0,searchMode:c,query:e}}}let E,D;if(h>0&&!r&&(D="> **Note:** `graph_hops` was set but no graph store is available. Graph augmentation skipped."),h>0&&r)try{let e=await ze(r,b.map(e=>({recordId:e.record.id,score:e.score,sourcePath:e.record.sourcePath})),{hops:h,maxPerHit:5});E=new Map;for(let t of e)if(t.graphContext.nodes.length>0){let e=t.graphContext.nodes.slice(0,5).map(e=>` - **${e.name}** (${e.type})`).join(`
525
+ `)}`}]}}catch(e){return Ru.error(`Restore failed`,j(e)),H(`INTERNAL`,`Restore failed: ${e instanceof Error?e.message:String(e)}`)}})}const Bu=/<\/?curated-context>/gi;function Vu(e){return e.replace(Bu,``)}function Hu(e){return`<curated-context>\n${Vu(e)}\n</curated-context>`}const Uu=k(`tools`);function Wu(e){let t=[],n=h(process.cwd());n&&t.push(`[project: ${n}]`);let r=Nt(`__context_boost`);return r&&t.push(`[focus: ${r.value}]`),t.length===0?e:`${t.join(` `)} ${e}`}async function Gu(e,t,n,r,i){if(!e||t>=e.config.fallbackThreshold&&n.length>0)return{results:n,triggered:!1,cacheHit:!1};let a=!1;try{let t=e.cache.get(r);return t?a=!0:(t=await e.client.search(r,i),t.length>0&&e.cache.set(r,t)),t.length>0?{results:vn(n,t,i).map(e=>({record:{id:`er:${e.sourcePath}`,content:e.content,sourcePath:e.source===`er`?`[ER] ${e.sourcePath}`:e.sourcePath,startLine:e.startLine??0,endLine:e.endLine??0,contentType:e.contentType??`documentation`,headingPath:e.headingPath,origin:e.source===`er`?`curated`:e.origin??`indexed`,category:e.category,tags:e.tags??[],chunkIndex:0,totalChunks:1,fileHash:``,indexedAt:new Date().toISOString(),version:1},score:e.score})),triggered:!0,cacheHit:a}:{results:n,triggered:!0,cacheHit:a}}catch(e){return Uu.warn(`ER fallback failed`,j(e)),{results:n,triggered:!0,cacheHit:a}}}function Ku(e,t,n=60){let r=new Map,i=e[0]?.score||1,a=t[0]?.score||1;for(let t=0;t<e.length;t++){let a=e[t],o=a.score/i;r.set(a.record.id,{record:a.record,score:1/(n+t+1)*o})}for(let e=0;e<t.length;e++){let i=t[e],o=i.score/a,s=r.get(i.record.id);s?s.score+=1/(n+e+1)*o:r.set(i.record.id,{record:i.record,score:1/(n+e+1)*o})}return[...r.values()].sort((e,t)=>t.score-e.score).map(({record:e,score:t})=>({record:e,score:t}))}function qu(e,t){let n=t.toLowerCase().split(/\s+/).filter(e=>e.length>=2);return n.length<2?e:e.map(e=>{let t=e.record.content.toLowerCase();if(t.length>5e3)return e;let r=n.map(e=>{let n=[],r=t.indexOf(e);for(;r!==-1&&n.length<10;)n.push(r),r=t.indexOf(e,r+1);return n});if(r.some(e=>e.length===0))return e;let i=t.length;for(let e of r[0]){let t=e,a=e+n[0].length;for(let i=1;i<r.length;i++){let o=r[i][0],s=Math.abs(o-e);for(let t=1;t<r[i].length;t++){let n=Math.abs(r[i][t]-e);n<s&&(s=n,o=r[i][t])}t=Math.min(t,o),a=Math.max(a,o+n[i].length)}i=Math.min(i,a-t)}let a=1+.25/(1+i/200);return{record:e.record,score:e.score*a}}).sort((e,t)=>t.score-e.score)}function Ju(e){if(e.length<=1)return e;let t=new Set;return e.filter(e=>{let n=e.record.contentHash;return n?t.has(n)?!1:(t.add(n),!0):!0})}function Yu(e,t,n=8){let r=new Set(t.toLowerCase().split(/\s+/).filter(e=>e.length>=2)),i=new Map,a=e.length;for(let t of e){let e=t.record.content.split(/[^a-zA-Z0-9_]+/).filter(e=>e.length>=3&&!Xu.has(e.toLowerCase())),n=new Set;for(let t of e){let e=t.toLowerCase();/[_A-Z]/.test(t)&&i.set(`__id__${e}`,1),n.has(e)||(n.add(e),i.set(e,(i.get(e)??0)+1))}}let o=[];for(let[e,t]of i){if(e.startsWith(`__id__`)||r.has(e)||t>a*.8)continue;let n=Math.log(a/t),s=+!!i.has(`__id__${e}`),c=e.length>8?.5:0;o.push({term:e,score:n+s+c})}return o.sort((e,t)=>t.score-e.score).slice(0,n).map(e=>e.term)}const Xu=new Set(`the.and.for.are.but.not.you.all.can.had.her.was.one.our.out.has.have.from.this.that.with.they.been.said.each.which.their.will.other.about.many.then.them.these.some.would.make.like.into.could.time.very.when.come.just.know.take.people.also.back.after.only.more.than.over.such.import.export.const.function.return.true.false.null.undefined.string.number.boolean.void.type.interface`.split(`.`));async function Zu(e,t){try{let n=await e.getStats();if(!n.lastIndexedAt)return;let r=new Date(n.lastIndexedAt).getTime(),i=Date.now(),a=[...new Set(t.map(e=>e.record.sourcePath))].filter(e=>!e.startsWith(`[ER]`)).slice(0,5);if(a.length===0)return;let o=0;for(let e of a)try{(await Yt(e)).mtimeMs>r&&o++}catch{o++}if(o>0){let e=i-r,t=Math.floor(e/6e4),n=t<1?`<1 min`:`${t} min`;return`> ⚠️ **Index may be stale** — ${o} file(s) modified since last index (${n} ago). Use \`reindex\` to refresh.`}}catch{}}function Qu(e,t,n,r,i,a,o){let s=z(`search`);e.registerTool(`search`,{title:s.title,description:`Search AI Kit for code, docs, and prior decisions. Default choice for discovery. Modes: hybrid (default), semantic, keyword. For multi-strategy precision queries use find; for a known file path use lookup.`,outputSchema:Ei,inputSchema:{query:F.string().max(5e3).describe(`Natural language search query`),limit:F.number().min(1).max(20).default(5).describe(`Maximum results to return`),search_mode:F.enum([`hybrid`,`semantic`,`keyword`]).default(`hybrid`).describe(`Search strategy: hybrid (vector + FTS + RRF fusion, default), semantic (vector only), keyword (FTS only)`),content_type:F.enum(S).optional().describe(`Filter by content type`),source_type:F.enum(T).optional().describe(`Coarse filter: "source" (code only), "documentation" (md, curated), "test", "config". Overrides content_type if both set.`),origin:F.enum(w).optional().describe(`Filter by knowledge origin`),category:F.string().optional().describe(`Filter by category (e.g., decisions, patterns, conventions)`),tags:F.array(F.string()).optional().describe(`Filter by tags (returns results matching ANY of the specified tags)`),min_score:F.number().min(0).max(1).default(.25).describe(`Minimum similarity score`),graph_hops:F.number().min(0).max(3).default(1).describe(`Number of graph hops to augment results with connected entities (0 = disabled, 1 = direct connections, 2-3 = deeper traversal). Default 1 provides module/symbol context automatically.`),max_tokens:F.number().min(100).max(5e4).optional().describe(`Maximum token budget for the response. When set, output is truncated to fit.`),dedup:F.enum([`file`,`chunk`]).default(`chunk`).describe(`Deduplication mode: "chunk" (default, show all matching chunks) or "file" (collapse chunks from same file into single result with merged line ranges)`),workspaces:F.array(F.string()).optional().describe(`Cross-workspace search: partition names or folder basenames to include. Use ["*"] for all registered workspaces. Only works in user-level install mode.`)},annotations:s.annotations},async({query:e,limit:s,search_mode:c,content_type:l,source_type:u,origin:d,category:f,tags:p,min_score:m,graph_hops:h,max_tokens:g,dedup:_,workspaces:v})=>{try{let y={limit:s,minScore:m,contentType:l,sourceType:u,origin:d,category:f,tags:p},b,x=!1,S=!1,C=``,w=Wu(e);if(c===`keyword`)b=await n.ftsSearch(e,y),b=b.slice(0,s);else if(c===`semantic`){let r=await t.embedQuery(w);b=await n.search(r,y);let a=await Gu(i,b[0]?.score??0,b,e,s);b=a.results,x=a.triggered,S=a.cacheHit}else{let r=await t.embedQuery(w),a=n.coarseSearch,o=a?a.bind(n):n.search.bind(n),[c,l]=await Promise.all([o(r,{...y,limit:s*2}),n.ftsSearch(e,{...y,limit:s*2}).catch(()=>[])]);c.length===0&&l.length>0?(b=l.slice(0,s),C=` (FTS-only: vector index rebuilding)`):b=l.length===0&&c.length>0?c.slice(0,s):Ku(c,l).slice(0,s);let u=await Gu(i,c[0]?.score??0,b,e,s);b=u.results,x=u.triggered,S=u.cacheHit}a&&a.recordSearch(e,x,S),b.length>1&&(b=qu(b,e)),b=Ju(b);let T=``;if(v&&v.length>0){let n=io(v,O(process.cwd()));if(n.length>0){let{stores:r,closeAll:i}=await ao(n);try{let i;i=c===`keyword`?await so(r,e,{...y,limit:s}):await oo(r,await t.embedQuery(e),{...y,limit:s});for(let e of i)b.push({record:{...e.record,sourcePath:`[${e.workspace}] ${e.record.sourcePath}`},score:e.score});b=b.sort((e,t)=>t.score-e.score).slice(0,s),T=` + ${n.length} workspace(s)`}finally{await i()}}}if(_===`file`&&b.length>1){let e=new Map;for(let t of b){let n=t.record.sourcePath,r=e.get(n);r?(t.score>r.best.score&&(r.best=t),r.ranges.push({start:t.record.startLine,end:t.record.endLine})):e.set(n,{best:t,ranges:[{start:t.record.startLine,end:t.record.endLine}]})}b=[...e.values()].sort((e,t)=>t.best.score-e.best.score).map(({best:e,ranges:t})=>({record:{...e.record,content:t.length>1?`${e.record.content}\n\n_Matched ${t.length} sections: ${t.sort((e,t)=>e.start-t.start).map(e=>`L${e.start}-${e.end}`).join(`, `)}_`:e.record.content},score:e.score}))}if(b.length>1){let e=b[0].score,t=Math.max(e*.4,.1);b=b.filter(e=>e.score>=t)}if(b.length===0){if(o?.available)try{let r=(await o.createMessage({prompt:`The search query "${e}" returned 0 results in AI Kit code search. Suggest ONE alternative search query that might find relevant results. Reply with ONLY the alternative query, nothing else.`,systemPrompt:`You are a search query optimizer for AI Kit code search. Generate a single alternative query.`,maxTokens:100})).text.trim().split(`
526
+ `)[0].slice(0,500);if(r&&r!==e){let i=await t.embedQuery(r),a=await n.search(i,y);a.length>0&&(b=a,C=`> _Original query "${e}" returned 0 results. Auto-reformulated to "${r}"._\n\n`,Uu.info(`Smart search fallback succeeded`,{originalQuery:e,altQuery:r,resultCount:a.length}))}}catch(e){Uu.debug(`Smart search fallback failed`,{error:String(e)})}if(b.length===0)return{content:[{type:`text`,text:`No results found for the given query.`}],structuredContent:{results:[],totalResults:0,searchMode:c,query:e}}}let E,D;if(h>0&&!r&&(D="> **Note:** `graph_hops` was set but no graph store is available. Graph augmentation skipped."),h>0&&r)try{let e=await ze(r,b.map(e=>({recordId:e.record.id,score:e.score,sourcePath:e.record.sourcePath})),{hops:h,maxPerHit:5});E=new Map;for(let t of e)if(t.graphContext.nodes.length>0){let e=t.graphContext.nodes.slice(0,5).map(e=>` - **${e.name}** (${e.type})`).join(`
527
527
  `),n=t.graphContext.edges.slice(0,5).map(e=>` - ${e.fromId} —[${e.type}]→ ${e.toId}`).join(`
528
528
  `),r=[`- **Graph Context** (${h} hop${h>1?`s`:``}):`];e&&r.push(` Entities:\n${e}`),n&&r.push(` Relationships:\n${n}`),E.set(t.recordId,r.join(`
529
- `))}}catch(e){Hu.warn(`Graph augmentation failed`,j(e)),D=`> **Note:** Graph augmentation failed. Results shown without graph context.`}let k=Date.now();for(let e of b)if(e.record.origin===`curated`&&e.record.indexedAt){let t=k-new Date(e.record.indexedAt).getTime(),n=Math.max(0,t/864e5);e.score*=.95**n}b.sort((e,t)=>t.score-e.score),b=se(b);let ee=b.map((e,t)=>{let n=e.record;return`${`### Result ${t+1} (score: ${e.score.toFixed(3)})`}\n${[`- **Source**: ${n.sourcePath}`,n.headingPath?`- **Section**: ${n.headingPath}`:null,`- **Type**: ${n.contentType}`,n.startLine?`- **Lines**: ${n.startLine}-${n.endLine}`:null,n.origin===`indexed`?null:`- **Origin**: ${n.origin}`,n.category?`- **Category**: ${n.category}`:null,n.tags?.length?`- **Tags**: ${n.tags.join(`, `)}`:null,E?.get(n.id)??null].filter(Boolean).join(`
530
- `)}\n\n${n.origin===`curated`?Vu(n.content):n.content}`}).join(`
529
+ `))}}catch(e){Uu.warn(`Graph augmentation failed`,j(e)),D=`> **Note:** Graph augmentation failed. Results shown without graph context.`}let k=Date.now();for(let e of b)if(e.record.origin===`curated`&&e.record.indexedAt){let t=k-new Date(e.record.indexedAt).getTime(),n=Math.max(0,t/864e5);e.score*=.95**n}b.sort((e,t)=>t.score-e.score),b=se(b);let ee=b.map((e,t)=>{let n=e.record;return`${`### Result ${t+1} (score: ${e.score.toFixed(3)})`}\n${[`- **Source**: ${n.sourcePath}`,n.headingPath?`- **Section**: ${n.headingPath}`:null,`- **Type**: ${n.contentType}`,n.startLine?`- **Lines**: ${n.startLine}-${n.endLine}`:null,n.origin===`indexed`?null:`- **Origin**: ${n.origin}`,n.category?`- **Category**: ${n.category}`:null,n.tags?.length?`- **Tags**: ${n.tags.join(`, `)}`:null,E?.get(n.id)??null].filter(Boolean).join(`
530
+ `)}\n\n${n.origin===`curated`?Hu(n.content):n.content}`}).join(`
531
531
 
532
532
  ---
533
533
 
534
- `),A=(c===`hybrid`?`hybrid (vector + keyword RRF)`:c===`keyword`?`keyword (FTS)`:`semantic (vector)`)+T,te=Ju(b,e),ne=te.length>0?`\n_Distinctive terms: ${te.map(e=>`\`${e}\``).join(`, `)}_`:``,M=await Xu(n,b),N=[];if(b.length===0)N.push("`reindex` — no results found, index may be stale"),N.push("`find` — try federated search with glob/regex");else{let e=b[0]?.record.sourcePath;e&&N.push(`\`lookup\` — see all chunks from \`${e}\``),N.push("`symbol` — resolve a specific symbol from the results"),N.push("`compact` — compress a result file for focused reading")}let re=[D?`${D}\n\n`:``,M?`${M}\n\n`:``,ee,`\n\n---\n_Search mode: ${A} | ${b.length} results_${ne}`,`\n_Next: ${N.join(` | `)}_`],ie=C+re.join(``);g&&(ie=Ht(ie,g));let ae=new Set,oe=[];for(let e of b){if(e.record.origin!==`curated`||e.record.sourcePath.startsWith(`[`))continue;let t=Cs(e.record.sourcePath);if(!t)continue;let n=xs(t,e.record.headingPath??t);n&&!ae.has(n.uri)&&(ae.add(n.uri),oe.push(n))}return{content:[{type:`text`,text:ie},...oe],structuredContent:{results:b.map(e=>({sourcePath:e.record.sourcePath,contentType:e.record.contentType,score:e.score,...e.record.headingPath?{headingPath:e.record.headingPath}:{},...e.record.startLine?{startLine:e.record.startLine}:{},...e.record.endLine?{endLine:e.record.endLine}:{},...e.record.origin===`indexed`?{}:{origin:e.record.origin},...e.record.category?{category:e.record.category}:{},...e.record.tags?.length?{tags:e.record.tags}:{}})),totalResults:b.length,searchMode:c,query:e}}}catch(e){return Hu.error(`Search failed`,j(e)),H(`INTERNAL`,`Search failed: ${e instanceof Error?e.message:String(e)}`)}})}const Qu=k(`tools`);function $u(e,t){let n=z(`session_digest`);e.registerTool(`session_digest`,{title:n.title,description:`Compress the current session's tool trajectory into a focused digest. Aggregates replay log, stash state, and checkpoints. Supports deterministic and LLM-assisted (sampling) modes with configurable token budget.`,inputSchema:{scope:F.enum([`tools`,`stash`,`all`]).default(`all`).describe(`What to include: tools (replay only), stash (stash + checkpoints only), or all`),since:F.string().optional().describe(`ISO timestamp — only include activity after this time`),last:F.number().min(1).max(500).optional().describe(`Max replay entries to consider (default: 50)`),focus:F.string().optional().describe(`Focus query — prioritize entries matching this topic`),mode:F.enum([`deterministic`,`sampling`]).default(`deterministic`).describe(`Summary mode: deterministic (fast, template-based) or sampling (LLM-assisted, richer)`),token_budget:F.number().min(100).max(8e3).default(2e3).describe(`Target token budget for the digest output`),persist:F.boolean().default(!0).describe(`Auto-save digest to stash for crash recovery`)},annotations:n.annotations},async({scope:e,since:n,last:r,focus:i,mode:a,token_budget:o,persist:s})=>{try{let c={scope:e,since:n,last:r,focus:i,mode:a,tokenBudget:o,persist:s};return{content:[{type:`text`,text:(a===`sampling`&&t?.available?await At(c,async(e,n,r)=>(await t.createMessage({prompt:e,systemPrompt:n,maxTokens:r})).text):kt(c)).digest}]}}catch(e){return Qu.error(`Session digest failed`,j(e)),H(`INTERNAL`,`Session digest failed: ${e instanceof Error?e.message:String(e)}`)}})}const ed=k(`tools`);function td(e,t,n,r=15e3){let i,a=new Promise(e=>{i=setTimeout(()=>{ed.warn(`Status sub-operation "${n}" timed out after ${r}ms`),e({value:t,timedOut:!0})},r)});return Promise.race([e.then(e=>(clearTimeout(i),{value:e,timedOut:!1}),e=>(clearTimeout(i),ed.warn(`Status sub-operation "${n}" failed: ${e instanceof Error?e.message:String(e)}`),{value:t,timedOut:!1})),a])}function nd(){let e=dn.get(),t=un.get();if(e)return`- **Tree-sitter (WASM)**: ✅ Available (${t.grammarCount} grammars, dir: ${t.wasmDir})`;let n=t.pathsChecked.length?t.pathsChecked.map(e=>` ${e.exists?`✓`:`✗`} ${e.path}`).join(`
534
+ `),A=(c===`hybrid`?`hybrid (vector + keyword RRF)`:c===`keyword`?`keyword (FTS)`:`semantic (vector)`)+T,te=Yu(b,e),ne=te.length>0?`\n_Distinctive terms: ${te.map(e=>`\`${e}\``).join(`, `)}_`:``,M=await Zu(n,b),N=[];if(b.length===0)N.push("`reindex` — no results found, index may be stale"),N.push("`find` — try federated search with glob/regex");else{let e=b[0]?.record.sourcePath;e&&N.push(`\`lookup\` — see all chunks from \`${e}\``),N.push("`symbol` — resolve a specific symbol from the results"),N.push("`compact` — compress a result file for focused reading")}let re=[D?`${D}\n\n`:``,M?`${M}\n\n`:``,ee,`\n\n---\n_Search mode: ${A} | ${b.length} results_${ne}`,`\n_Next: ${N.join(` | `)}_`],ie=C+re.join(``);g&&(ie=Ht(ie,g));let ae=new Set,oe=[];for(let e of b){if(e.record.origin!==`curated`||e.record.sourcePath.startsWith(`[`))continue;let t=Cs(e.record.sourcePath);if(!t)continue;let n=xs(t,e.record.headingPath??t);n&&!ae.has(n.uri)&&(ae.add(n.uri),oe.push(n))}return{content:[{type:`text`,text:ie},...oe],structuredContent:{results:b.map(e=>({sourcePath:e.record.sourcePath,contentType:e.record.contentType,score:e.score,...e.record.headingPath?{headingPath:e.record.headingPath}:{},...e.record.startLine?{startLine:e.record.startLine}:{},...e.record.endLine?{endLine:e.record.endLine}:{},...e.record.origin===`indexed`?{}:{origin:e.record.origin},...e.record.category?{category:e.record.category}:{},...e.record.tags?.length?{tags:e.record.tags}:{}})),totalResults:b.length,searchMode:c,query:e}}}catch(e){return Uu.error(`Search failed`,j(e)),H(`INTERNAL`,`Search failed: ${e instanceof Error?e.message:String(e)}`)}})}const $u=k(`tools`);function ed(e,t){let n=z(`session_digest`);e.registerTool(`session_digest`,{title:n.title,description:`Compress the current session's tool trajectory into a focused digest. Aggregates replay log, stash state, and checkpoints. Supports deterministic and LLM-assisted (sampling) modes with configurable token budget.`,inputSchema:{scope:F.enum([`tools`,`stash`,`all`]).default(`all`).describe(`What to include: tools (replay only), stash (stash + checkpoints only), or all`),since:F.string().optional().describe(`ISO timestamp — only include activity after this time`),last:F.number().min(1).max(500).optional().describe(`Max replay entries to consider (default: 50)`),focus:F.string().optional().describe(`Focus query — prioritize entries matching this topic`),mode:F.enum([`deterministic`,`sampling`]).default(`deterministic`).describe(`Summary mode: deterministic (fast, template-based) or sampling (LLM-assisted, richer)`),token_budget:F.number().min(100).max(8e3).default(2e3).describe(`Target token budget for the digest output`),persist:F.boolean().default(!0).describe(`Auto-save digest to stash for crash recovery`)},annotations:n.annotations},async({scope:e,since:n,last:r,focus:i,mode:a,token_budget:o,persist:s})=>{try{let c={scope:e,since:n,last:r,focus:i,mode:a,tokenBudget:o,persist:s};return{content:[{type:`text`,text:(a===`sampling`&&t?.available?await At(c,async(e,n,r)=>(await t.createMessage({prompt:e,systemPrompt:n,maxTokens:r})).text):kt(c)).digest}]}}catch(e){return $u.error(`Session digest failed`,j(e)),H(`INTERNAL`,`Session digest failed: ${e instanceof Error?e.message:String(e)}`)}})}const td=k(`tools`);function nd(e,t,n,r=15e3){let i,a=new Promise(e=>{i=setTimeout(()=>{td.warn(`Status sub-operation "${n}" timed out after ${r}ms`),e({value:t,timedOut:!0})},r)});return Promise.race([e.then(e=>(clearTimeout(i),{value:e,timedOut:!1}),e=>(clearTimeout(i),td.warn(`Status sub-operation "${n}" failed: ${e instanceof Error?e.message:String(e)}`),{value:t,timedOut:!1})),a])}function rd(){let e=dn.get(),t=un.get();if(e)return`- **Tree-sitter (WASM)**: ✅ Available (${t.grammarCount} grammars, dir: ${t.wasmDir})`;let n=t.pathsChecked.length?t.pathsChecked.map(e=>` ${e.exists?`✓`:`✗`} ${e.path}`).join(`
535
535
  `):` 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(`
536
- `)}const rd=5*6e4;let id=null,ad=null;function od(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 sd(){let e=Date.now();if(id&&e-id.ts<rd)return id.value;try{let t=y(Dn(),`.copilot`,`.aikit-scaffold.json`);if(!o(t))return id={value:null,ts:e},null;let n=JSON.parse(c(t,`utf-8`)).version??null;return id={value:n,ts:e},n}catch{return id={value:null,ts:e},null}}function cd(){let e=Date.now();if(ad&&e-ad.ts<rd)return ad.value;try{let t=y(process.cwd(),`.github`,`.aikit-scaffold.json`);if(!o(t))return ad={value:null,ts:e},null;let n=JSON.parse(c(t,`utf-8`)).version??null;return ad={value:n,ts:e},n}catch{return ad={value:null,ts:e},null}}function ld(e){let t=z(`status`);e.registerTool(`status`,{title:t.title,description:`Get the current status and statistics of the AI Kit index.`,outputSchema:_i,annotations:t.annotations},async()=>{let e=r(),t=sd(),a=cd(),o=t!=null&&t!==e,s=a!=null&&a!==e,c=[`## AI Kit Status`,``,`⏳ **AI Kit is initializing** — index stats will be available shortly.`,``,`### Runtime`,`- **Tree-sitter (WASM)**: ${dn.get()?`✅ Available (AST analysis)`:`⚠ Unavailable (regex fallback)`}`,``,`### Version`,`- **Server**: ${e}`,`- **Scaffold (user)**: ${t??`not installed`}`,`- **Scaffold (workspace)**: ${a??`not installed`}`];if(o||s){let r=i(),l=[];o&&l.push(`user scaffold v${t}`),s&&l.push(`workspace scaffold v${a}`);let u=l.join(`, `);r.state===`success`?c.push(``,`### ✅ Upgrade Applied`,`- Server v${e} — ${u} auto-upgraded successfully.`,`- _Restart the MCP server to use the updated version._`):r.state===`pending`?c.push(``,`### ⏳ Upgrade In Progress`,`- Server v${e} ≠ ${u}`,`- Auto-upgrade is running in the background…`):r.state===`failed`?(n(),c.push(``,`### ⬆ Upgrade Available (auto-upgrade failed, retrying)`,`- Server v${e} ≠ ${u}`,`- Error: ${r.error??`unknown`}`)):(n(),c.push(``,`### ⬆ Upgrade Available`,`- Server v${e} ≠ ${u}`,`- Auto-upgrade triggered — check again shortly.`))}let l={totalRecords:0,totalFiles:0,lastIndexedAt:null,onboarded:!1,onboardDir:``,contentTypes:{},wasmAvailable:!!dn.get(),graphStats:null,curatedCount:0,serverVersion:e,scaffoldVersion:t??null,workspaceScaffoldVersion:a??null,upgradeAvailable:o||s,contextPressure:0};return{content:[{type:`text`,text:c.join(`
537
- `)}],structuredContent:l}})}function ud(e,t,a,s,c,l,u,d){let p=z(`status`);e.registerTool(`status`,{title:p.title,description:`Get the current status and statistics of the AI Kit index.`,outputSchema:_i,annotations:p.annotations},async()=>{let e=[];try{let[p,m]=await Promise.all([td(t.getStats(),{totalRecords:0,totalFiles:0,lastIndexedAt:null,contentTypeBreakdown:{}},`store.getStats`),td(t.listSourcePaths(),[],`store.listSourcePaths`)]),h=p.value;p.timedOut&&e.push(`⚠ Index stats timed out — values may be incomplete`);let g=m.value;m.timedOut&&e.push(`⚠ File listing timed out`);let _=null,v=0,b=[`## AI Kit Status`,``,`- **Total Records**: ${h.totalRecords}`,`- **Total Files**: ${h.totalFiles}`,`- **Last Indexed**: ${h.lastIndexedAt??`Never`}`,``,`### Content Types`,...Object.entries(h.contentTypeBreakdown).map(([e,t])=>`- ${e}: ${t}`),``,`### Indexed Files`,...g.slice(0,50).map(e=>`- ${e}`),g.length>50?`\n... and ${g.length-50} more files`:``];if(a)try{let t=await td(a.getStats(),{nodeCount:0,edgeCount:0,nodeTypes:{},edgeTypes:{}},`graphStore.getStats`);if(t.timedOut)e.push(`⚠ Graph stats timed out`),b.push(``,`### Knowledge Graph`,`- Graph stats timed out`);else{let e=t.value;_={nodes:e.nodeCount,edges:e.edgeCount},b.push(``,`### Knowledge Graph`,`- **Nodes**: ${e.nodeCount}`,`- **Edges**: ${e.edgeCount}`,...Object.entries(e.nodeTypes).map(([e,t])=>` - ${e}: ${t}`));try{let e=await td(a.validate(),{valid:!0,danglingEdges:[],orphanNodes:[],stats:{nodeCount:0,edgeCount:0,nodeTypes:{},edgeTypes:{}}},`graphStore.validate`);if(!e.timedOut){let t=e.value;t.valid||b.push(`- **⚠ Integrity Issues**: ${t.danglingEdges.length} dangling edges`),t.orphanNodes.length>0&&b.push(`- **Orphan nodes**: ${t.orphanNodes.length}`)}}catch{}}}catch{b.push(``,`### Knowledge Graph`,`- Graph store unavailable`)}let S=l?.onboardDir??y(process.cwd(),x.aiContext),C=o(S),w=c?.onboardComplete||C;if(b.push(``,`### Onboard Status`,w?`- ✅ Complete${c?.onboardTimestamp?` (last: ${c.onboardTimestamp})`:``}`:'- ❌ Not run — call `onboard({ path: "." })` to analyze the codebase',`- **Onboard Directory**: \`${S}\``),s)try{let t=await td(s.list(),[],`curated.list`);if(t.timedOut)e.push(`⚠ Curated knowledge listing timed out`),b.push(``,`### Curated Knowledge`,`- Listing timed out`);else{let e=t.value;v=e.length,b.push(``,`### Curated Knowledge`,e.length>0?`- ${e.length} entries`:'- Empty — use `knowledge({ action: "remember", ... })` to persist decisions')}}catch{b.push(``,`### Curated Knowledge`,`- Unable to read curated entries`)}let T=od(h.totalRecords,_?.nodes??0,_?.edges??0,v);b.push(``),b.push(`## 📊 Context Pressure: ${T}/100`),T>=80?b.push(`⚠️ High pressure — consider pruning stale entries or compacting context.`):T>=50?b.push(`ℹ️ Moderate pressure — AI Kit memory is well-populated.`):b.push(`✅ Low pressure — plenty of headroom for more content.`);let E=0;if(h.lastIndexedAt){E=new Date(h.lastIndexedAt).getTime();let e=(Date.now()-E)/(1e3*60*60);b.push(``,`### Index Freshness`,e>24?u===`smart`?`- ⚠ Last indexed ${Math.floor(e)}h ago — smart indexing will refresh automatically`:`- ⚠ Last indexed ${Math.floor(e)}h ago — may be stale. Run \`reindex({})\``:`- ✅ Last indexed ${e<1?`less than 1h`:`${Math.floor(e)}h`} ago`)}let D=null,O=t;if(typeof O.getDiagnostics==`function`)try{D=O.getDiagnostics(),b.push(``,`### Storage`,`- **Backend**: ${l?.store?.backend??`unknown`}`,`- **Adapter**: ${D.adapterType}`,`- **Vector search**: ${D.vectorSearchEnabled?`✅ enabled`:`⚠ disabled (FTS-only fallback)`}`,D.dbPath?`- **DB**: ${D.dbPath}`:``,D.dbSizeBytes==null?``:`- **DB size**: ${(D.dbSizeBytes/1024/1024).toFixed(2)} MB`,`- **Embedding dim**: ${D.embeddingDim}`,`- **Vector dtype**: ${D.vectorDtype}`)}catch{}if(u===`smart`)if(b.push(``,`### Smart Indexing`),d){let e=d();e?b.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}`):b.push(`- **Mode**: Smart (trickle)`,`- **Status**: scheduler state unavailable (init may have failed)`)}else b.push(`- **Mode**: Smart (trickle) — scheduler state unavailable`);{try{let e=y(process.cwd(),x.data,`stash`);if(o(e)){let t=f(e).mtimeMs;t>E&&(E=t)}}catch{}let e=[];if(s)try{let t=v>0?await s.list():[];for(let e of t){let t=new Date(e.updated||e.created).getTime();t>E&&(E=t)}e.push(...t.sort((e,t)=>new Date(t.updated).getTime()-new Date(e.updated).getTime()).slice(0,5))}catch{}let t=E>0?Date.now()-E:0;if(t>=144e5){let n=Math.floor(t/36e5);if(b.push(``,`### 🌅 Session Briefing`,`_${n}+ hours since last activity — here's what to pick up:_`,``),e.length>0){b.push(`**Recent decisions/notes:**`);for(let t of e)b.push(`- **${t.title}** (${t.category??`note`}) — ${(t.contentPreview??``).slice(0,80)}…`)}b.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')}}b.push(``,`### Runtime`,nd());let k=sd(),ee=cd(),A=r(),te=k!=null&&k!==A,ne=ee!=null&&ee!==A;if(te||ne){let e=i(),t=[];te&&t.push(`user scaffold v${k}`),ne&&t.push(`workspace scaffold v${ee}`);let r=t.join(`, `);e.state===`success`?b.push(``,`### ✅ Upgrade Applied`,`- Server v${A} — ${r} auto-upgraded successfully.`,`- _Restart the MCP server to use the updated version._`):e.state===`pending`?b.push(``,`### ⏳ Upgrade In Progress`,`- Server v${A} ≠ ${r}`,`- Auto-upgrade is running in the background…`):e.state===`failed`?(n(),b.push(``,`### ⬆ Upgrade Available (auto-upgrade failed, retrying)`,`- Server v${A} ≠ ${r}`,`- Error: ${e.error??`unknown`}`)):(n(),b.push(``,`### ⬆ Upgrade Available`,`- Server v${A} ≠ ${r}`,`- Auto-upgrade triggered — check again shortly.`))}e.length>0&&b.push(``,`### ⚠ Warnings`,...e.map(e=>`- ${e}`));let j=Rr();if(j.length>0){let e=j.sort((e,t)=>t.callCount-e.callCount);b.push(``,`### Tool Usage This Session`,``),b.push(`| Tool | Calls | Tokens In | Tokens Out | Errors | Avg Latency |`),b.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);b.push(`| ${t.tool} | ${t.callCount} | ${e.toLocaleString()} | ${n.toLocaleString()} | ${t.errorCount} | ${r}ms |`)}}let M=jr();if(M.bufferSize>=10){let e=M.state===`healthy`?`🟢`:M.state===`degraded`?`🔴`:`🟡`;b.push(``,`### Auto-GC: ${e} ${M.state}`),b.push(`- p95 latency: ${M.p95}ms | buffer: ${M.bufferSize} samples`),M.gcCount>0&&b.push(`- GC cycles triggered: ${M.gcCount}`)}let N=b.join(`
538
- `),re={totalRecords:h.totalRecords,totalFiles:h.totalFiles,lastIndexedAt:h.lastIndexedAt??null,onboarded:w,onboardDir:S,contentTypes:h.contentTypeBreakdown,wasmAvailable:!!dn.get(),wasmDiagnostics:un.get(),graphStats:_,curatedCount:v,serverVersion:A,scaffoldVersion:k??null,workspaceScaffoldVersion:ee??null,upgradeAvailable:te||ne,storeBackend:l?.store?.backend,storeDiagnostics:D??null,contextPressure:T};return{content:[{type:`text`,text:N+(u===`smart`?"\n\n---\n_Next: Use `search` to query indexed content or `graph({action:'find_nodes', name_pattern:'<top-level-module>'})` → then `graph({action:'neighbors', node_id})` for relationships. Smart indexing handles updates automatically._":"\n\n---\n_Next: Use `search` to query indexed content, `graph({action:'find_nodes', name_pattern:'<top-level-module>'})` → then `graph({action:'neighbors', node_id})` for relationships, or `reindex` to refresh the index._")}],structuredContent:re}}catch(e){return ed.error(`Status failed`,j(e)),H(`INTERNAL`,`Status check failed: ${e instanceof Error?e.message:String(e)}`)}})}const dd=k(`tools`);function fd(e){let t=z(`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:F.array(F.string().max(2e3)).min(1).max(5).describe('Search queries (1–5). Single: `["react hooks"]`. Multiple searched in parallel.'),limit:F.number().min(1).max(20).default(5).describe(`Max results per query`),site:F.string().optional().describe(`Restrict to domain (e.g., "docs.aws.amazon.com")`),provider:F.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},async({queries:e,limit:t,site:n,provider:r})=>{let i=e,a=async e=>{let i=await qt({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(`
539
- `)};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 dd.error(`Web search failed`,j(e)),H(`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);dd.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(`
536
+ `)}const id=5*6e4;let ad=null,od=null;function sd(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 cd(){let e=Date.now();if(ad&&e-ad.ts<id)return ad.value;try{let t=y(Dn(),`.copilot`,`.aikit-scaffold.json`);if(!o(t))return ad={value:null,ts:e},null;let n=JSON.parse(c(t,`utf-8`)).version??null;return ad={value:n,ts:e},n}catch{return ad={value:null,ts:e},null}}function ld(){let e=Date.now();if(od&&e-od.ts<id)return od.value;try{let t=y(process.cwd(),`.github`,`.aikit-scaffold.json`);if(!o(t))return od={value:null,ts:e},null;let n=JSON.parse(c(t,`utf-8`)).version??null;return od={value:n,ts:e},n}catch{return od={value:null,ts:e},null}}function ud(e){let t=z(`status`);e.registerTool(`status`,{title:t.title,description:`Get the current status and statistics of the AI Kit index.`,outputSchema:_i,annotations:t.annotations},async()=>{let e=r(),t=cd(),a=ld(),o=t!=null&&t!==e,s=a!=null&&a!==e,c=[`## AI Kit Status`,``,`⏳ **AI Kit is initializing** — index stats will be available shortly.`,``,`### Runtime`,`- **Tree-sitter (WASM)**: ${dn.get()?`✅ Available (AST analysis)`:`⚠ Unavailable (regex fallback)`}`,``,`### Version`,`- **Server**: ${e}`,`- **Scaffold (user)**: ${t??`not installed`}`,`- **Scaffold (workspace)**: ${a??`not installed`}`];if(o||s){let r=i(),l=[];o&&l.push(`user scaffold v${t}`),s&&l.push(`workspace scaffold v${a}`);let u=l.join(`, `);r.state===`success`?c.push(``,`### ✅ Upgrade Applied`,`- Server v${e} — ${u} auto-upgraded successfully.`,`- _Restart the MCP server to use the updated version._`):r.state===`pending`?c.push(``,`### ⏳ Upgrade In Progress`,`- Server v${e} ≠ ${u}`,`- Auto-upgrade is running in the background…`):r.state===`failed`?(n(),c.push(``,`### ⬆ Upgrade Available (auto-upgrade failed, retrying)`,`- Server v${e} ≠ ${u}`,`- Error: ${r.error??`unknown`}`)):(n(),c.push(``,`### ⬆ Upgrade Available`,`- Server v${e} ≠ ${u}`,`- Auto-upgrade triggered — check again shortly.`))}let l={totalRecords:0,totalFiles:0,lastIndexedAt:null,onboarded:!1,onboardDir:``,contentTypes:{},wasmAvailable:!!dn.get(),graphStats:null,curatedCount:0,serverVersion:e,scaffoldVersion:t??null,workspaceScaffoldVersion:a??null,upgradeAvailable:o||s,contextPressure:0};return{content:[{type:`text`,text:c.join(`
537
+ `)}],structuredContent:l}})}function dd(e,t,a,s,c,l,u,d){let p=z(`status`);e.registerTool(`status`,{title:p.title,description:`Get the current status and statistics of the AI Kit index.`,outputSchema:_i,annotations:p.annotations},async()=>{let e=[];try{let[p,m]=await Promise.all([nd(t.getStats(),{totalRecords:0,totalFiles:0,lastIndexedAt:null,contentTypeBreakdown:{}},`store.getStats`),nd(t.listSourcePaths(),[],`store.listSourcePaths`)]),h=p.value;p.timedOut&&e.push(`⚠ Index stats timed out — values may be incomplete`);let g=m.value;m.timedOut&&e.push(`⚠ File listing timed out`);let _=null,v=0,b=[`## AI Kit Status`,``,`- **Total Records**: ${h.totalRecords}`,`- **Total Files**: ${h.totalFiles}`,`- **Last Indexed**: ${h.lastIndexedAt??`Never`}`,``,`### Content Types`,...Object.entries(h.contentTypeBreakdown).map(([e,t])=>`- ${e}: ${t}`),``,`### Indexed Files`,...g.slice(0,50).map(e=>`- ${e}`),g.length>50?`\n... and ${g.length-50} more files`:``];if(a)try{let t=await nd(a.getStats(),{nodeCount:0,edgeCount:0,nodeTypes:{},edgeTypes:{}},`graphStore.getStats`);if(t.timedOut)e.push(`⚠ Graph stats timed out`),b.push(``,`### Knowledge Graph`,`- Graph stats timed out`);else{let e=t.value;_={nodes:e.nodeCount,edges:e.edgeCount},b.push(``,`### Knowledge Graph`,`- **Nodes**: ${e.nodeCount}`,`- **Edges**: ${e.edgeCount}`,...Object.entries(e.nodeTypes).map(([e,t])=>` - ${e}: ${t}`));try{let e=await nd(a.validate(),{valid:!0,danglingEdges:[],orphanNodes:[],stats:{nodeCount:0,edgeCount:0,nodeTypes:{},edgeTypes:{}}},`graphStore.validate`);if(!e.timedOut){let t=e.value;t.valid||b.push(`- **⚠ Integrity Issues**: ${t.danglingEdges.length} dangling edges`),t.orphanNodes.length>0&&b.push(`- **Orphan nodes**: ${t.orphanNodes.length}`)}}catch{}}}catch{b.push(``,`### Knowledge Graph`,`- Graph store unavailable`)}let S=l?.onboardDir??y(process.cwd(),x.aiContext),C=o(S),w=c?.onboardComplete||C;if(b.push(``,`### Onboard Status`,w?`- ✅ Complete${c?.onboardTimestamp?` (last: ${c.onboardTimestamp})`:``}`:'- ❌ Not run — call `onboard({ path: "." })` to analyze the codebase',`- **Onboard Directory**: \`${S}\``),s)try{let t=await nd(s.list(),[],`curated.list`);if(t.timedOut)e.push(`⚠ Curated knowledge listing timed out`),b.push(``,`### Curated Knowledge`,`- Listing timed out`);else{let e=t.value;v=e.length,b.push(``,`### Curated Knowledge`,e.length>0?`- ${e.length} entries`:'- Empty — use `knowledge({ action: "remember", ... })` to persist decisions')}}catch{b.push(``,`### Curated Knowledge`,`- Unable to read curated entries`)}let T=sd(h.totalRecords,_?.nodes??0,_?.edges??0,v);b.push(``),b.push(`## 📊 Context Pressure: ${T}/100`),T>=80?b.push(`⚠️ High pressure — consider pruning stale entries or compacting context.`):T>=50?b.push(`ℹ️ Moderate pressure — AI Kit memory is well-populated.`):b.push(`✅ Low pressure — plenty of headroom for more content.`);let E=0;if(h.lastIndexedAt){E=new Date(h.lastIndexedAt).getTime();let e=(Date.now()-E)/(1e3*60*60);b.push(``,`### Index Freshness`,e>24?u===`smart`?`- ⚠ Last indexed ${Math.floor(e)}h ago — smart indexing will refresh automatically`:`- ⚠ Last indexed ${Math.floor(e)}h ago — may be stale. Run \`reindex({})\``:`- ✅ Last indexed ${e<1?`less than 1h`:`${Math.floor(e)}h`} ago`)}let D=null,O=t;if(typeof O.getDiagnostics==`function`)try{D=O.getDiagnostics(),b.push(``,`### Storage`,`- **Backend**: ${l?.store?.backend??`unknown`}`,`- **Adapter**: ${D.adapterType}`,`- **Vector search**: ${D.vectorSearchEnabled?`✅ enabled`:`⚠ disabled (FTS-only fallback)`}`,D.dbPath?`- **DB**: ${D.dbPath}`:``,D.dbSizeBytes==null?``:`- **DB size**: ${(D.dbSizeBytes/1024/1024).toFixed(2)} MB`,`- **Embedding dim**: ${D.embeddingDim}`,`- **Vector dtype**: ${D.vectorDtype}`)}catch{}if(u===`smart`)if(b.push(``,`### Smart Indexing`),d){let e=d();e?b.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}`):b.push(`- **Mode**: Smart (trickle)`,`- **Status**: scheduler state unavailable (init may have failed)`)}else b.push(`- **Mode**: Smart (trickle) — scheduler state unavailable`);{try{let e=y(process.cwd(),x.data,`stash`);if(o(e)){let t=f(e).mtimeMs;t>E&&(E=t)}}catch{}let e=[];if(s)try{let t=v>0?await s.list():[];for(let e of t){let t=new Date(e.updated||e.created).getTime();t>E&&(E=t)}e.push(...t.sort((e,t)=>new Date(t.updated).getTime()-new Date(e.updated).getTime()).slice(0,5))}catch{}let t=E>0?Date.now()-E:0;if(t>=144e5){let n=Math.floor(t/36e5);if(b.push(``,`### 🌅 Session Briefing`,`_${n}+ hours since last activity — here's what to pick up:_`,``),e.length>0){b.push(`**Recent decisions/notes:**`);for(let t of e)b.push(`- **${t.title}** (${t.category??`note`}) — ${(t.contentPreview??``).slice(0,80)}…`)}b.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')}}b.push(``,`### Runtime`,rd());let k=cd(),ee=ld(),A=r(),te=k!=null&&k!==A,ne=ee!=null&&ee!==A;if(te||ne){let e=i(),t=[];te&&t.push(`user scaffold v${k}`),ne&&t.push(`workspace scaffold v${ee}`);let r=t.join(`, `);e.state===`success`?b.push(``,`### ✅ Upgrade Applied`,`- Server v${A} — ${r} auto-upgraded successfully.`,`- _Restart the MCP server to use the updated version._`):e.state===`pending`?b.push(``,`### ⏳ Upgrade In Progress`,`- Server v${A} ≠ ${r}`,`- Auto-upgrade is running in the background…`):e.state===`failed`?(n(),b.push(``,`### ⬆ Upgrade Available (auto-upgrade failed, retrying)`,`- Server v${A} ≠ ${r}`,`- Error: ${e.error??`unknown`}`)):(n(),b.push(``,`### ⬆ Upgrade Available`,`- Server v${A} ≠ ${r}`,`- Auto-upgrade triggered — check again shortly.`))}e.length>0&&b.push(``,`### ⚠ Warnings`,...e.map(e=>`- ${e}`));let j=Rr();if(j.length>0){let e=j.sort((e,t)=>t.callCount-e.callCount);b.push(``,`### Tool Usage This Session`,``),b.push(`| Tool | Calls | Tokens In | Tokens Out | Errors | Avg Latency |`),b.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);b.push(`| ${t.tool} | ${t.callCount} | ${e.toLocaleString()} | ${n.toLocaleString()} | ${t.errorCount} | ${r}ms |`)}}let M=jr();if(M.bufferSize>=10){let e=M.state===`healthy`?`🟢`:M.state===`degraded`?`🔴`:`🟡`;b.push(``,`### Auto-GC: ${e} ${M.state}`),b.push(`- p95 latency: ${M.p95}ms | buffer: ${M.bufferSize} samples`),M.gcCount>0&&b.push(`- GC cycles triggered: ${M.gcCount}`)}let N=b.join(`
538
+ `),re={totalRecords:h.totalRecords,totalFiles:h.totalFiles,lastIndexedAt:h.lastIndexedAt??null,onboarded:w,onboardDir:S,contentTypes:h.contentTypeBreakdown,wasmAvailable:!!dn.get(),wasmDiagnostics:un.get(),graphStats:_,curatedCount:v,serverVersion:A,scaffoldVersion:k??null,workspaceScaffoldVersion:ee??null,upgradeAvailable:te||ne,storeBackend:l?.store?.backend,storeDiagnostics:D??null,contextPressure:T};return{content:[{type:`text`,text:N+(u===`smart`?"\n\n---\n_Next: Use `search` to query indexed content or `graph({action:'find_nodes', name_pattern:'<top-level-module>'})` → then `graph({action:'neighbors', node_id})` for relationships. Smart indexing handles updates automatically._":"\n\n---\n_Next: Use `search` to query indexed content, `graph({action:'find_nodes', name_pattern:'<top-level-module>'})` → then `graph({action:'neighbors', node_id})` for relationships, or `reindex` to refresh the index._")}],structuredContent:re}}catch(e){return td.error(`Status failed`,j(e)),H(`INTERNAL`,`Status check failed: ${e instanceof Error?e.message:String(e)}`)}})}const fd=k(`tools`);function pd(e){let t=z(`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:F.array(F.string().max(2e3)).min(1).max(5).describe('Search queries (1–5). Single: `["react hooks"]`. Multiple searched in parallel.'),limit:F.number().min(1).max(20).default(5).describe(`Max results per query`),site:F.string().optional().describe(`Restrict to domain (e.g., "docs.aws.amazon.com")`),provider:F.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},async({queries:e,limit:t,site:n,provider:r})=>{let i=e,a=async e=>{let i=await qt({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(`
539
+ `)};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 fd.error(`Web search failed`,j(e)),H(`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);fd.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(`
540
540
 
541
- `);return c===o.length?H(`INTERNAL`,u):{content:[{type:`text`,text:u}]}})}function pd(e){let t=z(`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:F.string().url().describe(`Request URL (http/https only)`),method:F.enum([`GET`,`POST`,`PUT`,`PATCH`,`DELETE`,`HEAD`]).default(`GET`).describe(`HTTP method`),headers:F.record(F.string(),F.string()).optional().describe(`Request headers as key-value pairs`),body:F.string().optional().describe(`Request body (for POST/PUT/PATCH)`),timeout:F.number().min(1e3).max(6e4).default(15e3).describe(`Timeout in milliseconds`)},annotations:t.annotations},async({url:e,method:t,headers:n,body:r,timeout:i})=>{try{let a=await Ue({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(`
542
- `)}]}}catch(e){return dd.error(`HTTP request failed`,j(e)),H(`INTERNAL`,`HTTP request failed: ${e instanceof Error?e.message:String(e)}`)}})}function md(e){let t=z(`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:F.string().max(500).describe(`Regex pattern (without delimiters)`),flags:F.string().max(10).regex(/^[gimsuy]*$/).default(``).describe(`Regex flags (g, i, m, s, etc.)`),test_strings:F.array(F.string().max(1e4)).max(50).describe(`Strings to test the pattern against`),mode:F.enum([`match`,`replace`,`split`]).default(`match`).describe(`Test mode`),replacement:F.string().optional().describe(`Replacement string (for replace mode)`)},annotations:t.annotations},async({pattern:e,flags:t,test_strings:n,mode:r,replacement:i})=>{let a=_t({pattern:e,flags:t,testStrings:n,mode:r,replacement:i});if(!a.valid)return H(`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(`
543
- `)}]}})}function hd(e){let t=z(`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:F.enum([`base64_encode`,`base64_decode`,`url_encode`,`url_decode`,`sha256`,`md5`,`jwt_decode`,`hex_encode`,`hex_decode`]).describe(`Operation to perform`),input:F.string().max(1e6).describe(`Input text`)},annotations:t.annotations},async({operation:e,input:t})=>{try{let n=De({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 dd.error(`Encode failed`,j(e)),H(`INTERNAL`,`Encode failed: ${e instanceof Error?e.message:String(e)}`)}})}function gd(e){let t=z(`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:yi,inputSchema:{path:F.string().describe(`File or directory path to measure`),extensions:F.array(F.string()).optional().describe(`File extensions to include (default: .ts,.tsx,.js,.jsx)`)},annotations:t.annotations},async({path:e,extensions:t})=>{try{let n=await $e({path:e,extensions:t}),r=[`## Code Metrics`,``,`**Files:** ${n.summary.totalFiles}`,`**Total lines:** ${n.summary.totalLines} (${n.summary.totalCodeLines} code)`,`**Functions:** ${n.summary.totalFunctions}`,`**Avg complexity:** ${n.summary.avgComplexity}`,`**Max complexity:** ${n.summary.maxComplexity.value} (${n.summary.maxComplexity.file})`,``,`### Top files by complexity`,``,`| File | Lines | Code | Complexity | Cognitive | Functions | Imports |`,`|------|-------|------|------------|-----------|-----------|---------|`];for(let e of n.files.slice(0,20)){let t=e.cognitiveComplexity===void 0?`—`:String(e.cognitiveComplexity);r.push(`| ${e.path} | ${e.lines.total} | ${e.lines.code} | ${e.complexity} | ${t} | ${e.functions} | ${e.imports} |`)}n.files.length>20&&r.push(``,`_...and ${n.files.length-20} more files_`);let i={summary:{totalFiles:n.summary.totalFiles,totalLines:n.summary.totalLines,totalCodeLines:n.summary.totalCodeLines,totalFunctions:n.summary.totalFunctions,avgComplexity:n.summary.avgComplexity,maxComplexity:{value:n.summary.maxComplexity.value,file:n.summary.maxComplexity.file}},files:n.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.join(`
544
- `)}],structuredContent:i}}catch(e){return dd.error(`Measure failed`,j(e)),H(`INTERNAL`,`Measure failed: ${e instanceof Error?e.message:String(e)}`)}})}function _d(e){let t=z(`changelog`);e.registerTool(`changelog`,{title:t.title,description:`Generate a changelog from git history between two refs. Groups by conventional commit type.`,inputSchema:{from:F.string().max(200).describe(`Start ref (tag, SHA, HEAD~N)`),to:F.string().max(200).default(`HEAD`).describe(`End ref (default: HEAD)`),format:F.enum([`grouped`,`chronological`,`per-scope`]).default(`grouped`).describe(`Output format`),include_breaking:F.boolean().default(!0).describe(`Highlight breaking changes`),cwd:F.string().optional().describe(`Repository root or working directory`)},annotations:t.annotations},async({from:e,to:t,format:n,include_breaking:r,cwd:i})=>{try{let a=ce({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 dd.error(`Changelog failed`,j(e)),H(`INTERNAL`,`Changelog failed: ${e instanceof Error?e.message:String(e)}`)}})}function vd(e){let t=z(`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:F.string().max(5e5).describe(`JSON data to validate (as string)`),schema:F.string().max(5e5).describe(`JSON Schema to validate against (as string)`)},annotations:t.annotations},async({data:e,schema:t})=>{try{let n=Dt({data:JSON.parse(e),schema:JSON.parse(t)});if(n.valid)return{content:[{type:`text`,text:`## Validation: PASSED
541
+ `);return c===o.length?H(`INTERNAL`,u):{content:[{type:`text`,text:u}]}})}function md(e){let t=z(`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:F.string().url().describe(`Request URL (http/https only)`),method:F.enum([`GET`,`POST`,`PUT`,`PATCH`,`DELETE`,`HEAD`]).default(`GET`).describe(`HTTP method`),headers:F.record(F.string(),F.string()).optional().describe(`Request headers as key-value pairs`),body:F.string().optional().describe(`Request body (for POST/PUT/PATCH)`),timeout:F.number().min(1e3).max(6e4).default(15e3).describe(`Timeout in milliseconds`)},annotations:t.annotations},async({url:e,method:t,headers:n,body:r,timeout:i})=>{try{let a=await Ue({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(`
542
+ `)}]}}catch(e){return fd.error(`HTTP request failed`,j(e)),H(`INTERNAL`,`HTTP request failed: ${e instanceof Error?e.message:String(e)}`)}})}function hd(e){let t=z(`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:F.string().max(500).describe(`Regex pattern (without delimiters)`),flags:F.string().max(10).regex(/^[gimsuy]*$/).default(``).describe(`Regex flags (g, i, m, s, etc.)`),test_strings:F.array(F.string().max(1e4)).max(50).describe(`Strings to test the pattern against`),mode:F.enum([`match`,`replace`,`split`]).default(`match`).describe(`Test mode`),replacement:F.string().optional().describe(`Replacement string (for replace mode)`)},annotations:t.annotations},async({pattern:e,flags:t,test_strings:n,mode:r,replacement:i})=>{let a=_t({pattern:e,flags:t,testStrings:n,mode:r,replacement:i});if(!a.valid)return H(`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(`
543
+ `)}]}})}function gd(e){let t=z(`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:F.enum([`base64_encode`,`base64_decode`,`url_encode`,`url_decode`,`sha256`,`md5`,`jwt_decode`,`hex_encode`,`hex_decode`]).describe(`Operation to perform`),input:F.string().max(1e6).describe(`Input text`)},annotations:t.annotations},async({operation:e,input:t})=>{try{let n=De({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 fd.error(`Encode failed`,j(e)),H(`INTERNAL`,`Encode failed: ${e instanceof Error?e.message:String(e)}`)}})}function _d(e){let t=z(`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:yi,inputSchema:{path:F.string().describe(`File or directory path to measure`),extensions:F.array(F.string()).optional().describe(`File extensions to include (default: .ts,.tsx,.js,.jsx)`)},annotations:t.annotations},async({path:e,extensions:t})=>{try{let n=await $e({path:e,extensions:t}),r=[`## Code Metrics`,``,`**Files:** ${n.summary.totalFiles}`,`**Total lines:** ${n.summary.totalLines} (${n.summary.totalCodeLines} code)`,`**Functions:** ${n.summary.totalFunctions}`,`**Avg complexity:** ${n.summary.avgComplexity}`,`**Max complexity:** ${n.summary.maxComplexity.value} (${n.summary.maxComplexity.file})`,``,`### Top files by complexity`,``,`| File | Lines | Code | Complexity | Cognitive | Functions | Imports |`,`|------|-------|------|------------|-----------|-----------|---------|`];for(let e of n.files.slice(0,20)){let t=e.cognitiveComplexity===void 0?`—`:String(e.cognitiveComplexity);r.push(`| ${e.path} | ${e.lines.total} | ${e.lines.code} | ${e.complexity} | ${t} | ${e.functions} | ${e.imports} |`)}n.files.length>20&&r.push(``,`_...and ${n.files.length-20} more files_`);let i={summary:{totalFiles:n.summary.totalFiles,totalLines:n.summary.totalLines,totalCodeLines:n.summary.totalCodeLines,totalFunctions:n.summary.totalFunctions,avgComplexity:n.summary.avgComplexity,maxComplexity:{value:n.summary.maxComplexity.value,file:n.summary.maxComplexity.file}},files:n.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.join(`
544
+ `)}],structuredContent:i}}catch(e){return fd.error(`Measure failed`,j(e)),H(`INTERNAL`,`Measure failed: ${e instanceof Error?e.message:String(e)}`)}})}function vd(e){let t=z(`changelog`);e.registerTool(`changelog`,{title:t.title,description:`Generate a changelog from git history between two refs. Groups by conventional commit type.`,inputSchema:{from:F.string().max(200).describe(`Start ref (tag, SHA, HEAD~N)`),to:F.string().max(200).default(`HEAD`).describe(`End ref (default: HEAD)`),format:F.enum([`grouped`,`chronological`,`per-scope`]).default(`grouped`).describe(`Output format`),include_breaking:F.boolean().default(!0).describe(`Highlight breaking changes`),cwd:F.string().optional().describe(`Repository root or working directory`)},annotations:t.annotations},async({from:e,to:t,format:n,include_breaking:r,cwd:i})=>{try{let a=ce({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 fd.error(`Changelog failed`,j(e)),H(`INTERNAL`,`Changelog failed: ${e instanceof Error?e.message:String(e)}`)}})}function yd(e){let t=z(`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:F.string().max(5e5).describe(`JSON data to validate (as string)`),schema:F.string().max(5e5).describe(`JSON Schema to validate against (as string)`)},annotations:t.annotations},async({data:e,schema:t})=>{try{let n=Dt({data:JSON.parse(e),schema:JSON.parse(t)});if(n.valid)return{content:[{type:`text`,text:`## Validation: PASSED
545
545
 
546
546
  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(`
547
- `)}]}}catch(e){return dd.error(`Schema validation failed`,j(e)),H(`INTERNAL`,`Schema validation failed: ${e instanceof Error?e.message:String(e)}`)}})}function yd(e){let t=z(`env`);e.registerTool(`env`,{title:t.title,description:`Get system and runtime environment info. Sensitive env vars are redacted by default.`,outputSchema:bi,inputSchema:{include_env:F.boolean().default(!1).describe(`Include environment variables`),filter_env:F.string().optional().describe(`Filter env vars by name substring`),show_sensitive:F.boolean().default(!1).describe(`Show sensitive values (keys, tokens, etc.) — redacted by default`)},annotations:t.annotations},async({include_env:e,filter_env:t,show_sensitive:n})=>{let r=Oe({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(`
548
- `)}],structuredContent:a}})}function bd(e){let t=z(`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:xi,inputSchema:{operation:F.enum([`now`,`parse`,`convert`,`diff`,`add`]).describe(`now: current time | parse: parse a date string | convert: timezone conversion | diff: duration between two dates | add: add duration to date`),input:F.string().optional().describe(`Date input (ISO, unix timestamp, or parseable string). For diff: two comma-separated dates`),timezone:F.string().optional().describe(`Target timezone (e.g., "America/New_York", "Asia/Tokyo")`),duration:F.string().optional().describe(`Duration to add (e.g., "2h30m", "1d", "30s") — for add operation`)},annotations:t.annotations},async({operation:e,input:t,timezone:n,duration:r})=>{try{let i=Bt({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(`
549
- `)}],structuredContent:o}}catch(e){return dd.error(`Time failed`,j(e)),H(`INTERNAL`,`Time failed: ${e instanceof Error?e.message:String(e)}`)}})}function xd(e,t,n,r,i,a,o,s,c){let l=new wr,u=new dr;u.register(cr),u.register(ir),u.register(ar),u.register(tr),u.register(Zn),u.register(Qn),u.register(ur);let d=new gr(u,t.curated);l.use(mr(d),{order:5,name:`auto-knowledge`}),l.use(Br(),{order:10,name:`replay`}),l.use(Xr(),{order:50,name:`structured-content-guard`}),l.use(yr(vr(n.tokenBudget)),{order:90,name:`compression`}),ti(e,l,n.toolPrefix??``);let f=c??hi(n,[...L,...Wr],R,Kr(n)),p=e=>f.has(e),m=[...f].filter(e=>Gr.has(e)?Ur.includes(e)?!!t.bridge:e===`er_update_policy`?!!t.policyStore:e===`er_evolve_review`?!!t.evolutionCollector:!1:!0);p(`search`)&&Zu(e,t.embedder,t.store,t.graphStore,t.bridge,t.evolutionCollector,a);let h={store:t.store,graphStore:t.graphStore,embedder:t.embedder};p(`lookup`)&&Zs(e,t.store,h);let g={onboardComplete:t.onboardComplete,onboardTimestamp:t.onboardTimestamp};p(`status`)&&ud(e,t.store,t.graphStore,t.curated,g,n,o,s),p(`config`)&&no(e,n),p(`reindex`)&&Pu(e,t.indexer,n,t.curated,t.store,i,o),p(`knowledge`)&&Ys(e,t.curated,t.policyStore,t.evolutionCollector,i),p(`analyze`)&&Sa(e,t.store,t.embedder,h),p(`blast_radius`)&&Ca(e,t.store,t.embedder,t.graphStore,h),p(`produce_knowledge`)&&Nu(e,n),p(`onboard`)&&fc(e,t.store,t.embedder,n,g,h),p(`graph`)&&hs(e,t.graphStore),p(`audit`)&&Oa(e,t.store,t.embedder,n.tokenBudget);let _=n.sources[0]?.path??process.cwd();p(`compact`)&&uo(e,t.embedder,t.fileCache,_,n.allRoots,h),p(`scope_map`)&&fo(e,t.embedder,t.store,h),p(`find`)&&po(e,t.embedder,t.store,_,h),p(`parse_output`)&&Do(e),p(`workset`)&&mc(e),p(`check`)&&wo(e,h,n.tokenBudget),p(`symbol`)&&mo(e,t.embedder,t.store,t.graphStore),p(`eval`)&&To(e),p(`test_run`)&&Eo(e,h),p(`stash`)&&hc(e),p(`git_context`)&&$s(e),p(`diff_parse`)&&ec(e),p(`rename`)&&tc(e),p(`codemod`)&&nc(e),p(`restore`)&&Ru(e),p(`file_summary`)&&ho(e,t.fileCache,_,n.allRoots,h),p(`checkpoint`)&&gc(e),p(`data_transform`)&&rc(e),p(`trace`)&&go(e,t.embedder,t.store,t.graphStore),p(`process`)&&gs(e),p(`watch`)&&_s(e),p(`dead_symbols`)&&_o(e,t.embedder,t.store,_,n.allRoots,h),p(`delegate`)&&Oo(e,a),p(`health`)&&vs(e),p(`lane`)&&_c(e),p(`queue`)&&vc(e),p(`web_fetch`)&&ys(e),p(`guide`)&&bs(e,o),oc.some(e=>p(e))&&sc(e,n,m),p(`evidence_map`)&&ss(e),p(`digest`)&&cs(e,t.embedder),p(`forge_classify`)&&ls(e),p(`stratum_card`)&&us(e,t.embedder,t.fileCache),p(`forge_ground`)&&ds(e,t.embedder,t.store),p(`present`)&&ku(e,r),p(`web_search`)&&fd(e),p(`http`)&&pd(e),p(`regex_test`)&&md(e),p(`encode`)&&hd(e),p(`measure`)&&gd(e),p(`changelog`)&&_d(e),p(`schema_validate`)&&vd(e),p(`env`)&&yd(e),p(`time`)&&bd(e),p(`flow`)&&as(e,n),t.bridge&&Ur.some(e=>p(e))&&(Ma(e,t.bridge,t.evolutionCollector),Na(e,t.bridge),Pa(e,t.bridge)),t.policyStore&&p(`er_update_policy`)&&wc(e,t.policyStore),t.evolutionCollector&&p(`er_evolve_review`)&&So(e,t.evolutionCollector),Hr(e,t.store,t.curated),p(`replay`)&&Iu(e),p(`session_digest`)&&$u(e,a)}function Sd(e,t,n){let r=e=>!n||n.has(e);r(`check`)&&wo(e,void 0,t.tokenBudget),r(`eval`)&&To(e),r(`test_run`)&&Eo(e),r(`parse_output`)&&Do(e),r(`delegate`)&&Oo(e),r(`git_context`)&&$s(e),r(`diff_parse`)&&ec(e),r(`rename`)&&tc(e),r(`codemod`)&&nc(e),r(`data_transform`)&&rc(e),r(`workset`)&&mc(e),r(`stash`)&&hc(e),r(`checkpoint`)&&gc(e),r(`restore`)&&Ru(e),r(`lane`)&&_c(e),r(`queue`)&&vc(e),r(`session_digest`)&&$u(e),r(`health`)&&vs(e),r(`process`)&&gs(e),r(`watch`)&&_s(e),r(`web_fetch`)&&ys(e),r(`guide`)&&bs(e),oc.some(e=>r(e))&&sc(e,t,[...n??new Set(L)]),r(`evidence_map`)&&ss(e),r(`forge_classify`)&&ls(e),r(`present`)&&ku(e),r(`produce_knowledge`)&&Nu(e),r(`replay`)&&Iu(e),r(`status`)&&ld(e),r(`flow`)&&as(e,t),r(`web_search`)&&fd(e),r(`http`)&&pd(e),r(`regex_test`)&&md(e),r(`encode`)&&hd(e),r(`measure`)&&gd(e),r(`changelog`)&&_d(e),r(`schema_validate`)&&vd(e),r(`env`)&&yd(e),r(`time`)&&bd(e)}const Cd=k(`resource-notifier`);var wd=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){Cd.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){Cd.debug(`sendResourceUpdated failed`,{uri:e,error:String(t)})}}};const Z=k(`server`);async function Td(n){Z.info(`Initializing AI Kit components`);let r=n.store.backend,i=n.store.path,a=null;if(r===`sqlite-vec`){let e=v(i,`aikit.db`);a=await Cn(e),Z.info(`SQLite adapter ready`,{type:a.type,vectorCapable:a.vectorCapable,dbPath:e}),a.vectorCapable||Z.warn(`┌──────────────────────────────────────────────────────────────────┐
547
+ `)}]}}catch(e){return fd.error(`Schema validation failed`,j(e)),H(`INTERNAL`,`Schema validation failed: ${e instanceof Error?e.message:String(e)}`)}})}function bd(e){let t=z(`env`);e.registerTool(`env`,{title:t.title,description:`Get system and runtime environment info. Sensitive env vars are redacted by default.`,outputSchema:bi,inputSchema:{include_env:F.boolean().default(!1).describe(`Include environment variables`),filter_env:F.string().optional().describe(`Filter env vars by name substring`),show_sensitive:F.boolean().default(!1).describe(`Show sensitive values (keys, tokens, etc.) — redacted by default`)},annotations:t.annotations},async({include_env:e,filter_env:t,show_sensitive:n})=>{let r=Oe({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(`
548
+ `)}],structuredContent:a}})}function xd(e){let t=z(`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:xi,inputSchema:{operation:F.enum([`now`,`parse`,`convert`,`diff`,`add`]).describe(`now: current time | parse: parse a date string | convert: timezone conversion | diff: duration between two dates | add: add duration to date`),input:F.string().optional().describe(`Date input (ISO, unix timestamp, or parseable string). For diff: two comma-separated dates`),timezone:F.string().optional().describe(`Target timezone (e.g., "America/New_York", "Asia/Tokyo")`),duration:F.string().optional().describe(`Duration to add (e.g., "2h30m", "1d", "30s") — for add operation`)},annotations:t.annotations},async({operation:e,input:t,timezone:n,duration:r})=>{try{let i=Bt({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(`
549
+ `)}],structuredContent:o}}catch(e){return fd.error(`Time failed`,j(e)),H(`INTERNAL`,`Time failed: ${e instanceof Error?e.message:String(e)}`)}})}function Sd(e,t,n,r,i,a,o,s,c){let l=new wr,u=new dr;u.register(cr),u.register(ir),u.register(ar),u.register(tr),u.register(Zn),u.register(Qn),u.register(ur);let d=new gr(u,t.curated);l.use(mr(d),{order:5,name:`auto-knowledge`}),l.use(Br(),{order:10,name:`replay`}),l.use(Xr(),{order:50,name:`structured-content-guard`}),l.use(yr(vr(n.tokenBudget)),{order:90,name:`compression`}),ti(e,l,n.toolPrefix??``);let f=c??hi(n,[...L,...Wr],R,Kr(n)),p=e=>f.has(e),m=[...f].filter(e=>Gr.has(e)?Ur.includes(e)?!!t.bridge:e===`er_update_policy`?!!t.policyStore:e===`er_evolve_review`?!!t.evolutionCollector:!1:!0);p(`search`)&&Qu(e,t.embedder,t.store,t.graphStore,t.bridge,t.evolutionCollector,a);let h={store:t.store,graphStore:t.graphStore,embedder:t.embedder};p(`lookup`)&&Zs(e,t.store,h);let g={onboardComplete:t.onboardComplete,onboardTimestamp:t.onboardTimestamp};p(`status`)&&dd(e,t.store,t.graphStore,t.curated,g,n,o,s),p(`config`)&&no(e,n),p(`reindex`)&&Fu(e,t.indexer,n,t.curated,t.store,i,o),p(`knowledge`)&&Ys(e,t.curated,t.policyStore,t.evolutionCollector,i),p(`analyze`)&&Sa(e,t.store,t.embedder,h),p(`blast_radius`)&&Ca(e,t.store,t.embedder,t.graphStore,h),p(`produce_knowledge`)&&Pu(e,n),p(`onboard`)&&fc(e,t.store,t.embedder,n,g,h),p(`graph`)&&hs(e,t.graphStore),p(`audit`)&&Oa(e,t.store,t.embedder,n.tokenBudget);let _=n.sources[0]?.path??process.cwd();p(`compact`)&&uo(e,t.embedder,t.fileCache,_,n.allRoots,h),p(`scope_map`)&&fo(e,t.embedder,t.store,h),p(`find`)&&po(e,t.embedder,t.store,_,h),p(`parse_output`)&&Do(e),p(`workset`)&&mc(e),p(`check`)&&wo(e,h,n.tokenBudget),p(`symbol`)&&mo(e,t.embedder,t.store,t.graphStore),p(`eval`)&&To(e),p(`test_run`)&&Eo(e,h),p(`stash`)&&hc(e),p(`git_context`)&&$s(e),p(`diff_parse`)&&ec(e),p(`rename`)&&tc(e),p(`codemod`)&&nc(e),p(`restore`)&&zu(e),p(`file_summary`)&&ho(e,t.fileCache,_,n.allRoots,h),p(`checkpoint`)&&gc(e),p(`data_transform`)&&rc(e),p(`trace`)&&go(e,t.embedder,t.store,t.graphStore),p(`process`)&&gs(e),p(`watch`)&&_s(e),p(`dead_symbols`)&&_o(e,t.embedder,t.store,_,n.allRoots,h),p(`delegate`)&&Oo(e,a),p(`health`)&&vs(e),p(`lane`)&&_c(e),p(`queue`)&&vc(e),p(`web_fetch`)&&ys(e),p(`guide`)&&bs(e,o),oc.some(e=>p(e))&&sc(e,n,m),p(`evidence_map`)&&ss(e),p(`digest`)&&cs(e,t.embedder),p(`forge_classify`)&&ls(e),p(`stratum_card`)&&us(e,t.embedder,t.fileCache),p(`forge_ground`)&&ds(e,t.embedder,t.store),p(`present`)&&Au(e,r),p(`web_search`)&&pd(e),p(`http`)&&md(e),p(`regex_test`)&&hd(e),p(`encode`)&&gd(e),p(`measure`)&&_d(e),p(`changelog`)&&vd(e),p(`schema_validate`)&&yd(e),p(`env`)&&bd(e),p(`time`)&&xd(e),p(`flow`)&&as(e,n),t.bridge&&Ur.some(e=>p(e))&&(Ma(e,t.bridge,t.evolutionCollector),Na(e,t.bridge),Pa(e,t.bridge)),t.policyStore&&p(`er_update_policy`)&&wc(e,t.policyStore),t.evolutionCollector&&p(`er_evolve_review`)&&So(e,t.evolutionCollector),Hr(e,t.store,t.curated),p(`replay`)&&Lu(e),p(`session_digest`)&&ed(e,a)}function Cd(e,t,n){let r=e=>!n||n.has(e);r(`check`)&&wo(e,void 0,t.tokenBudget),r(`eval`)&&To(e),r(`test_run`)&&Eo(e),r(`parse_output`)&&Do(e),r(`delegate`)&&Oo(e),r(`git_context`)&&$s(e),r(`diff_parse`)&&ec(e),r(`rename`)&&tc(e),r(`codemod`)&&nc(e),r(`data_transform`)&&rc(e),r(`workset`)&&mc(e),r(`stash`)&&hc(e),r(`checkpoint`)&&gc(e),r(`restore`)&&zu(e),r(`lane`)&&_c(e),r(`queue`)&&vc(e),r(`session_digest`)&&ed(e),r(`health`)&&vs(e),r(`process`)&&gs(e),r(`watch`)&&_s(e),r(`web_fetch`)&&ys(e),r(`guide`)&&bs(e),oc.some(e=>r(e))&&sc(e,t,[...n??new Set(L)]),r(`evidence_map`)&&ss(e),r(`forge_classify`)&&ls(e),r(`present`)&&Au(e),r(`produce_knowledge`)&&Pu(e),r(`replay`)&&Lu(e),r(`status`)&&ud(e),r(`flow`)&&as(e,t),r(`web_search`)&&pd(e),r(`http`)&&md(e),r(`regex_test`)&&hd(e),r(`encode`)&&gd(e),r(`measure`)&&_d(e),r(`changelog`)&&vd(e),r(`schema_validate`)&&yd(e),r(`env`)&&bd(e),r(`time`)&&xd(e)}const wd=k(`resource-notifier`);var Td=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){wd.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){wd.debug(`sendResourceUpdated failed`,{uri:e,error:String(t)})}}};const Z=k(`server`);async function Ed(n){Z.info(`Initializing AI Kit components`);let r=n.store.backend,i=n.store.path,a=null;if(r===`sqlite-vec`){let e=v(i,`aikit.db`);a=await Cn(e),Z.info(`SQLite adapter ready`,{type:a.type,vectorCapable:a.vectorCapable,dbPath:e}),a.vectorCapable||Z.warn(`┌──────────────────────────────────────────────────────────────────┐
550
550
  │ ⚠ SQLite vector extension unavailable — DEGRADED MODE │
551
551
  │ Vector search is disabled. Hybrid search returns FTS only. │
552
552
  │ To enable: install/rebuild better-sqlite3 (native module). │
553
- └──────────────────────────────────────────────────────────────────┘`);let t=v(i,`lance`);o(t)&&Z.info(`Old LanceDB data found at ${t} — ignored. Safe to delete after verifying sqlite-vec works.`)}let[s,c,l,u]=await Promise.all([(async()=>{if(n.embedding.childProcess!==!1){let e=new jn({model:n.embedding.model,dimensions:n.embedding.dimensions,interOpNumThreads:n.embedding.interOpNumThreads,intraOpNumThreads:n.embedding.intraOpNumThreads,idleTimeoutMs:n.embedding.idleTimeoutMs});return await e.initialize(),Z.info(`Embedder loaded (child process)`,{modelId:e.modelId,dimensions:e.dimensions}),e}let{OnnxEmbedder:e}=await import(`../../embeddings/dist/index.js`),t=new e({model:n.embedding.model,dimensions:n.embedding.dimensions,interOpNumThreads:n.embedding.interOpNumThreads,intraOpNumThreads:n.embedding.intraOpNumThreads});return await t.initialize(),Z.info(`Embedder loaded (in-process)`,{modelId:t.modelId,dimensions:t.dimensions}),t})(),(async()=>{let e=await wn({backend:r,path:i,adapter:a??void 0,embeddingDim:n.embedding.dimensions});return await e.initialize(),Z.info(`Store initialized`,{backend:r}),e})(),(async()=>{let e=a?new Sn({adapter:a}):new Sn({path:i});return await e.initialize(),Z.info(`Graph store initialized`,{shared:!!a}),e})(),(async()=>{let e=await fn();if(e){let e=un.get();Z.info(`WASM tree-sitter enabled`,{grammars:e.grammarCount,dir:e.wasmDir})}else{let e=un.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})()]),d=new Nn(s,c),p=new Mn(n.store.path);p.load(),d.setHashCache(p);let m=n.curated.path,h=new e(m);await h.initialize();let g=new t(m,c,s,h);d.setGraphStore(l);let _=ja(n.er),b=_?new gn(n.curated.path):void 0;b&&Z.info(`Policy store initialized`,{ruleCount:b.getRules().length});let S=_?new hn:void 0,C=y(n.sources[0]?.path??process.cwd(),x.aiContext),w=o(C),T=n.onboardDir?o(n.onboardDir):!1,E=w||T,D,O=w?C:n.onboardDir;if(E&&O)try{D=f(O).mtime.toISOString()}catch{}return Z.info(`Onboard state detected`,{onboardComplete:E,onboardTimestamp:D,aiKbExists:w,onboardDirExists:T}),{embedder:s,store:c,indexer:d,curated:g,graphStore:l,fileCache:new re,bridge:_,policyStore:b,evolutionCollector:S,onboardComplete:E,onboardTimestamp:D}}function Ed(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(`, `)}.`];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(` `)}const Dd=k(`background-task`);var Od=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,Dd.info(`Background task started`,{task:e.name,pending:this.queue.length});let t=Date.now();try{await e.fn();let n=Date.now()-t;Dd.info(`Background task completed`,{task:e.name,durationMs:n}),e.resolve()}catch(n){let r=Date.now()-t;Dd.error(`Background task failed`,{task:e.name,durationMs:r,err:n}),e.reject(n instanceof Error?n:Error(String(n)))}}this.running=null}};const kd=k(`idle-timer`);var Ad=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){kd.info(`Idle timeout reached with no active session — skipping cleanup (waiting for first tool call)`);return}if(this._busy){kd.info(`Skipping idle cleanup — background work in progress`);return}kd.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`&&kd.warn(`Idle cleanup callback failed`,{error:String(t.reason)})}};const jd=k(`memory-monitor`);var Md=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(),jd.info(`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`?jd.warn(`Memory CRITICAL: ${n}MB RSS — consider restarting the server`):t===`warning`?jd.warn(`Memory WARNING: ${n}MB RSS`):this.lastLevel!==`normal`&&jd.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 Nd=k(`tool-timeout`),Pd=new Set([`onboard`,`reindex`,`produce_knowledge`,`analyze`,`codemod`,`audit`]);var Fd=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 Id(e){return Pd.has(e)?6e5:12e4}function Ld(e,t,n){return new Promise((r,i)=>{let a=!1,o=setTimeout(()=>{if(!a){a=!0;let e=new Fd(n,t);Nd.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=k(`server`);function Rd(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`,`module not found`].some(e=>t.includes(e))}async function zd(e,t){let n=t.toLowerCase(),r;try{({rm:r}=await import(`node:fs/promises`))}catch{return}if(n.includes(`embedding`)||n.includes(`onnx`)||n.includes(`protobuf`)||n.includes(`model`)){let t=e.embedding?.model??C.model,n=v(Dn(),`.cache`,`huggingface`,`transformers-js`,t);try{await r(n,{recursive:!0,force:!0}),Q.info(`Auto-heal: cleared embedding model cache`,{path:n})}catch{}}if(n.includes(`lance`)||n.includes(`database`)||n.includes(`store`)){let t=v(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=v(e.store.path,`graph.db`);try{await r(t,{force:!0}),Q.info(`Auto-heal: cleared graph database`,{path:t})}catch{}}}function Bd(e,t){let n=hi(e,L,R,Kr(e)),i=Ed(e,n,R),a=new Xt({name:e.serverName??`aikit`,version:r()},{capabilities:{logging:{},completions:{},prompts:{}},instructions:i}),o=`initializing`,s=``,c=!1,l=null,u=null,d=null;function f(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 p=()=>o===`failed`?[`❌ AI Kit initialization failed — this tool is unavailable.`,``,s?`Error: ${s}`:``,``,`**${Yr.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.`,``,`To fix embedding errors, try deleting the cached model:`,` rm -rf ~/.cache/huggingface/transformers-js/mixedbread-ai/`,`Then restart the server to re-download a fresh copy.`,``,`Try restarting the MCP server to retry initialization.`].filter(Boolean).join(`
553
+ └──────────────────────────────────────────────────────────────────┘`);let t=v(i,`lance`);o(t)&&Z.info(`Old LanceDB data found at ${t} — ignored. Safe to delete after verifying sqlite-vec works.`)}let[s,c,l,u]=await Promise.all([(async()=>{if(n.embedding.childProcess!==!1){let e=new jn({model:n.embedding.model,dimensions:n.embedding.dimensions,interOpNumThreads:n.embedding.interOpNumThreads,intraOpNumThreads:n.embedding.intraOpNumThreads,idleTimeoutMs:n.embedding.idleTimeoutMs});return await e.initialize(),Z.info(`Embedder loaded (child process)`,{modelId:e.modelId,dimensions:e.dimensions}),e}let{OnnxEmbedder:e}=await import(`../../embeddings/dist/index.js`),t=new e({model:n.embedding.model,dimensions:n.embedding.dimensions,interOpNumThreads:n.embedding.interOpNumThreads,intraOpNumThreads:n.embedding.intraOpNumThreads});return await t.initialize(),Z.info(`Embedder loaded (in-process)`,{modelId:t.modelId,dimensions:t.dimensions}),t})(),(async()=>{let e=await wn({backend:r,path:i,adapter:a??void 0,embeddingDim:n.embedding.dimensions});return await e.initialize(),Z.info(`Store initialized`,{backend:r}),e})(),(async()=>{let e=a?new Sn({adapter:a}):new Sn({path:i});return await e.initialize(),Z.info(`Graph store initialized`,{shared:!!a}),e})(),(async()=>{let e=await fn();if(e){let e=un.get();Z.info(`WASM tree-sitter enabled`,{grammars:e.grammarCount,dir:e.wasmDir})}else{let e=un.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})()]),d=new Nn(s,c),p=new Mn(n.store.path);p.load(),d.setHashCache(p);let m=n.curated.path,h=new e(m);await h.initialize();let g=new t(m,c,s,h);d.setGraphStore(l);let _=ja(n.er),b=_?new gn(n.curated.path):void 0;b&&Z.info(`Policy store initialized`,{ruleCount:b.getRules().length});let S=_?new hn:void 0,C=y(n.sources[0]?.path??process.cwd(),x.aiContext),w=o(C),T=n.onboardDir?o(n.onboardDir):!1,E=w||T,D,O=w?C:n.onboardDir;if(E&&O)try{D=f(O).mtime.toISOString()}catch{}return Z.info(`Onboard state detected`,{onboardComplete:E,onboardTimestamp:D,aiKbExists:w,onboardDirExists:T}),{embedder:s,store:c,indexer:d,curated:g,graphStore:l,fileCache:new re,bridge:_,policyStore:b,evolutionCollector:S,onboardComplete:E,onboardTimestamp:D}}function Dd(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(`, `)}.`];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(` `)}const Od=k(`background-task`);var kd=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,Od.info(`Background task started`,{task:e.name,pending:this.queue.length});let t=Date.now();try{await e.fn();let n=Date.now()-t;Od.info(`Background task completed`,{task:e.name,durationMs:n}),e.resolve()}catch(n){let r=Date.now()-t;Od.error(`Background task failed`,{task:e.name,durationMs:r,err:n}),e.reject(n instanceof Error?n:Error(String(n)))}}this.running=null}};const Ad=k(`idle-timer`);var jd=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){Ad.info(`Idle timeout reached with no active session — skipping cleanup (waiting for first tool call)`);return}if(this._busy){Ad.info(`Skipping idle cleanup — background work in progress`);return}Ad.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`&&Ad.warn(`Idle cleanup callback failed`,{error:String(t.reason)})}};const Md=k(`memory-monitor`);var Nd=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(),Md.info(`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`?Md.warn(`Memory CRITICAL: ${n}MB RSS — consider restarting the server`):t===`warning`?Md.warn(`Memory WARNING: ${n}MB RSS`):this.lastLevel!==`normal`&&Md.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 Pd=k(`tool-timeout`),Fd=new Set([`onboard`,`reindex`,`produce_knowledge`,`analyze`,`codemod`,`audit`]);var Id=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 Ld(e){return Fd.has(e)?6e5:12e4}function Rd(e,t,n){return new Promise((r,i)=>{let a=!1,o=setTimeout(()=>{if(!a){a=!0;let e=new Id(n,t);Pd.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=k(`server`);function zd(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`,`module not found`].some(e=>t.includes(e))}async function Bd(e,t){let n=t.toLowerCase(),r;try{({rm:r}=await import(`node:fs/promises`))}catch{return}if(n.includes(`embedding`)||n.includes(`onnx`)||n.includes(`protobuf`)||n.includes(`model`)){let t=e.embedding?.model??C.model,n=v(Dn(),`.cache`,`huggingface`,`transformers-js`,t);try{await r(n,{recursive:!0,force:!0}),Q.info(`Auto-heal: cleared embedding model cache`,{path:n})}catch{}}if(n.includes(`lance`)||n.includes(`database`)||n.includes(`store`)){let t=v(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=v(e.store.path,`graph.db`);try{await r(t,{force:!0}),Q.info(`Auto-heal: cleared graph database`,{path:t})}catch{}}}function Vd(e,t){let n=hi(e,L,R,Kr(e)),i=Dd(e,n,R),a=new Xt({name:e.serverName??`aikit`,version:r()},{capabilities:{logging:{},completions:{},prompts:{}},instructions:i}),o=`initializing`,s=``,c=!1,l=null,u=null,d=null;function f(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 p=()=>o===`failed`?[`❌ AI Kit initialization failed — this tool is unavailable.`,``,s?`Error: ${s}`:``,``,`**${Yr.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.`,``,`To fix embedding errors, try deleting the cached model:`,` rm -rf ~/.cache/huggingface/transformers-js/mixedbread-ai/`,`Then restart the server to re-download a fresh copy.`,``,`Try restarting the MCP server to retry initialization.`].filter(Boolean).join(`
554
554
  `):[`AI Kit is still initializing (loading embeddings model & store).`,``,`**${Yr.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(`
555
- `);In(a),ti(a,new wr,e.toolPrefix??``);let m=a.sendToolListChanged.bind(a);a.sendToolListChanged=()=>{};let h=[];for(let e of L){if(!n.has(e))continue;let t=z(e),r=a.registerTool(e,{title:t.title,description:`${t.title} — initializing, available shortly`,inputSchema:{},annotations:t.annotations},async()=>({content:[{type:`text`,text:p()}]}));Yr.has(e)?r.remove():h.push(r)}Sd(a,e,n),a.sendToolListChanged=m;let g=a.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`}]})),_=a.registerPrompt(`_init`,{description:`Initializing AI Kit…`,argsSchema:{_dummy:P(F.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}=await import(`node:fs`),{fileURLToPath:n}=await import(`node:url`),{resolve:r,dirname:i}=await import(`node:path`),a=e(import.meta.url),o=r(i(n(import.meta.url)),`..`,`package.json`),s=JSON.parse(t(o,`utf8`)),c=Object.keys(s.dependencies??{}),l=[];for(let e of c)try{a.resolve(e)}catch{l.push(e)}l.length>0&&Q.warn(`${l.length} dependencies not resolvable — init may fail`,{missing:l,hint:`Corrupted npx cache from interrupted downloads. Try: npx clear-npx-cache`})}catch{}let n;try{n=await Td(e)}catch(t){let r=t instanceof Error?t.message:String(t);if(Rd(r)){Q.warn(`AI Kit initialization failed with recoverable error — attempting auto-heal retry`,{error:r}),await zd(e,r);try{n=await Td(e),Q.info(`AI Kit auto-heal successful — initialization recovered after retry`)}catch(e){o=`failed`,s=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:s,originalError:r}),y?.(e instanceof Error?e:Error(s));return}}else{o=`failed`,s=r,Q.error(`AI Kit initialization failed — server continuing with zero-dep tools only`,{error:s}),y?.(t instanceof Error?t:Error(s));return}}let r=a.sendToolListChanged.bind(a);a.sendToolListChanged=()=>{};let i=a.sendPromptListChanged.bind(a);a.sendPromptListChanged=()=>{};let p=a.sendResourceListChanged.bind(a);a.sendResourceListChanged=()=>{};for(let e of h)e.remove();g.remove(),_.remove();let m=a._registeredTools??{};for(let e of Yr)m[e]?.remove();let b=new wd(a),x=No(a);xd(a,n,e,Pn(a),b,x,t,t===`smart`?(()=>{let e=d;return e?.getState?e.getState():null}):null),qn(a,{curated:n.curated,store:n.store,graphStore:n.graphStore},t),a.sendToolListChanged=r,a.sendPromptListChanged=i,a.sendResourceListChanged=p,Promise.resolve(a.sendToolListChanged()).catch(()=>{}),Promise.resolve(a.sendPromptListChanged()).catch(()=>{}),Promise.resolve(a.sendResourceListChanged()).catch(()=>{});let C=a._registeredTools??{};for(let[e,t]of Object.entries(C)){if(qr.has(e))continue;let r=t.handler;t.handler=async(...t)=>{if(!n.indexer.isIndexing)return r(...t);let i=c?`re-indexing`:`running initial index`,a=new Promise(t=>setTimeout(()=>t({content:[{type:`text`,text:`⏳ AI Kit is ${i}. The tool "${e}" timed out waiting for index data (${Jr/1e3}s).\n\nThe existing index may be temporarily locked. Please retry shortly — indexing will complete automatically.`}]}),Jr));return Promise.race([r(...t),a])}}for(let[e,t]of Object.entries(C)){let n=t.handler,r=Id(e);t.handler=async(...t)=>{try{return await Ld(()=>n(...t),r,e)}catch(t){if(t instanceof Fd)return{content:[{type:`text`,text:`⏳ Tool "${e}" timed out after ${r/1e3}s. This may indicate a long-running operation. Please retry or break the task into smaller steps.`}]};throw t}}}let w=Object.keys(C).length;w<L.length&&Q.warn(`ALL_TOOL_NAMES count mismatch`,{expectedToolCount:L.length,registeredToolCount:w}),Q.info(`MCP server configured`,{toolCount:L.length,resourceCount:4});let T=new Md;T.onPressure((e,t)=>{e===`warning`&&Bn(),e===`critical`&&(Q.warn(`Memory pressure critical — consider restarting`,{rssMB:Math.round(t/1024/1024)}),Bn())}),T.registerMemoryPressureCallback(()=>n.embedder.shutdown?.()),T.start();let D=new Ad;u=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(),d){let t=f(e[0]);t.length>0&&d.prioritize(...t)}return t(...e)}}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))),l=n,v?.(n)})(),T=async()=>{let t;try{t=await b}catch{Q.warn(`Skipping initial index — AI Kit initialization failed`);return}u?.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}))});c=!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`,j(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`,j(e))}}catch(e){Q.error(`Initial index failed; will retry on aikit_reindex`,j(e))}finally{u?.setBusy(!1)}},E=new Od,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),d?.stop&&d.stop(),b.then(async e=>{await Promise.all([e.embedder.shutdown?.().catch(()=>{})??Promise.resolve(),e.graphStore.close().catch(()=>{}),e.store.close().catch(()=>{})])}).catch(()=>{}).finally(()=>process.exit(0))}},5e3);return k.unref(),{server:a,startInit:C,ready:w,runInitialIndex:D,get aikit(){return l},scheduler:E,setSmartScheduler(e){d=e}}}const $=k(`server`);function Vd(e,t){let n=hi(t,[...L,...Wr],R,Kr(t)),i=Ed(t,n,R),a=new Xt({name:t.serverName??`aikit`,version:r()},{capabilities:{logging:{},completions:{},prompts:{}},instructions:i});return In(a),xd(a,e,t,Pn(a),new wd(a),No(a),void 0,null,n),qn(a,{curated:e.curated,store:e.store,graphStore:e.graphStore},t.indexMode),a}async function Hd(e){let t=await Td(e),n=Vd(t,e);$.info(`MCP server configured`,{toolCount:L.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`,j(e))}try{let e=await t.curated.reindexAll();$.info(`Curated re-index complete`,{indexed:e.indexed})}catch(e){$.error(`Curated re-index failed`,j(e))}}catch(e){$.error(`Initial index failed; will retry on aikit_reindex`,j(e))}},i=async()=>{$.info(`Shutting down`),await Promise.all([t.embedder.shutdown?.().catch(()=>{})??Promise.resolve(),t.graphStore.close().catch(()=>{}),t.store.close().catch(()=>{})]),process.exit(0)};process.on(`SIGINT`,i),process.on(`SIGTERM`,i);let a=process.ppid,o=setInterval(()=>{try{process.kill(a,0)}catch{$.info(`Parent process died; shutting down`,{parentPid:a}),clearInterval(o),i()}},5e3);return o.unref(),{server:n,runInitialIndex:r,shutdown:i}}export{L as ALL_TOOL_NAMES,Bd as createLazyServer,Vd as createMcpServer,Hd as createServer,Td as initializeAikit,xd as registerMcpTools};
555
+ `);In(a),ti(a,new wr,e.toolPrefix??``);let m=a.sendToolListChanged.bind(a);a.sendToolListChanged=()=>{};let h=[];for(let e of L){if(!n.has(e))continue;let t=z(e),r=a.registerTool(e,{title:t.title,description:`${t.title} — initializing, available shortly`,inputSchema:{},annotations:t.annotations},async()=>({content:[{type:`text`,text:p()}]}));Yr.has(e)?r.remove():h.push(r)}Cd(a,e,n),a.sendToolListChanged=m;let g=a.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`}]})),_=a.registerPrompt(`_init`,{description:`Initializing AI Kit…`,argsSchema:{_dummy:P(F.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}=await import(`node:fs`),{fileURLToPath:n}=await import(`node:url`),{resolve:r,dirname:i}=await import(`node:path`),a=e(import.meta.url),o=r(i(n(import.meta.url)),`..`,`package.json`),s=JSON.parse(t(o,`utf8`)),c=Object.keys(s.dependencies??{}),l=[];for(let e of c)try{a.resolve(e)}catch{l.push(e)}l.length>0&&Q.warn(`${l.length} dependencies not resolvable — init may fail`,{missing:l,hint:`Corrupted npx cache from interrupted downloads. Try: npx clear-npx-cache`})}catch{}let n;try{n=await Ed(e)}catch(t){let r=t instanceof Error?t.message:String(t);if(zd(r)){Q.warn(`AI Kit initialization failed with recoverable error — attempting auto-heal retry`,{error:r}),await Bd(e,r);try{n=await Ed(e),Q.info(`AI Kit auto-heal successful — initialization recovered after retry`)}catch(e){o=`failed`,s=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:s,originalError:r}),y?.(e instanceof Error?e:Error(s));return}}else{o=`failed`,s=r,Q.error(`AI Kit initialization failed — server continuing with zero-dep tools only`,{error:s}),y?.(t instanceof Error?t:Error(s));return}}let r=a.sendToolListChanged.bind(a);a.sendToolListChanged=()=>{};let i=a.sendPromptListChanged.bind(a);a.sendPromptListChanged=()=>{};let p=a.sendResourceListChanged.bind(a);a.sendResourceListChanged=()=>{};for(let e of h)e.remove();g.remove(),_.remove();let m=a._registeredTools??{};for(let e of Yr)m[e]?.remove();let b=new Td(a),x=No(a);Sd(a,n,e,Pn(a),b,x,t,t===`smart`?(()=>{let e=d;return e?.getState?e.getState():null}):null),qn(a,{curated:n.curated,store:n.store,graphStore:n.graphStore},t),a.sendToolListChanged=r,a.sendPromptListChanged=i,a.sendResourceListChanged=p,Promise.resolve(a.sendToolListChanged()).catch(()=>{}),Promise.resolve(a.sendPromptListChanged()).catch(()=>{}),Promise.resolve(a.sendResourceListChanged()).catch(()=>{});let C=a._registeredTools??{};for(let[e,t]of Object.entries(C)){if(qr.has(e))continue;let r=t.handler;t.handler=async(...t)=>{if(!n.indexer.isIndexing)return r(...t);let i=c?`re-indexing`:`running initial index`,a=new Promise(t=>setTimeout(()=>t({content:[{type:`text`,text:`⏳ AI Kit is ${i}. The tool "${e}" timed out waiting for index data (${Jr/1e3}s).\n\nThe existing index may be temporarily locked. Please retry shortly — indexing will complete automatically.`}]}),Jr));return Promise.race([r(...t),a])}}for(let[e,t]of Object.entries(C)){let n=t.handler,r=Ld(e);t.handler=async(...t)=>{try{return await Rd(()=>n(...t),r,e)}catch(t){if(t instanceof Id)return{content:[{type:`text`,text:`⏳ Tool "${e}" timed out after ${r/1e3}s. This may indicate a long-running operation. Please retry or break the task into smaller steps.`}]};throw t}}}let w=Object.keys(C).length;w<L.length&&Q.warn(`ALL_TOOL_NAMES count mismatch`,{expectedToolCount:L.length,registeredToolCount:w}),Q.info(`MCP server configured`,{toolCount:L.length,resourceCount:4});let T=new Nd;T.onPressure((e,t)=>{e===`warning`&&Bn(),e===`critical`&&(Q.warn(`Memory pressure critical — consider restarting`,{rssMB:Math.round(t/1024/1024)}),Bn())}),T.registerMemoryPressureCallback(()=>n.embedder.shutdown?.()),T.start();let D=new jd;u=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(),d){let t=f(e[0]);t.length>0&&d.prioritize(...t)}return t(...e)}}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))),l=n,v?.(n)})(),T=async()=>{let t;try{t=await b}catch{Q.warn(`Skipping initial index — AI Kit initialization failed`);return}u?.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}))});c=!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`,j(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`,j(e))}}catch(e){Q.error(`Initial index failed; will retry on aikit_reindex`,j(e))}finally{u?.setBusy(!1)}},E=new kd,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),d?.stop&&d.stop(),b.then(async e=>{await Promise.all([e.embedder.shutdown?.().catch(()=>{})??Promise.resolve(),e.graphStore.close().catch(()=>{}),e.store.close().catch(()=>{})])}).catch(()=>{}).finally(()=>process.exit(0))}},5e3);return k.unref(),{server:a,startInit:C,ready:w,runInitialIndex:D,get aikit(){return l},scheduler:E,setSmartScheduler(e){d=e}}}const $=k(`server`);function Hd(e,t){let n=hi(t,[...L,...Wr],R,Kr(t)),i=Dd(t,n,R),a=new Xt({name:t.serverName??`aikit`,version:r()},{capabilities:{logging:{},completions:{},prompts:{}},instructions:i});return In(a),Sd(a,e,t,Pn(a),new Td(a),No(a),void 0,null,n),qn(a,{curated:e.curated,store:e.store,graphStore:e.graphStore},t.indexMode),a}async function Ud(e){let t=await Ed(e),n=Hd(t,e);$.info(`MCP server configured`,{toolCount:L.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`,j(e))}try{let e=await t.curated.reindexAll();$.info(`Curated re-index complete`,{indexed:e.indexed})}catch(e){$.error(`Curated re-index failed`,j(e))}}catch(e){$.error(`Initial index failed; will retry on aikit_reindex`,j(e))}},i=async()=>{$.info(`Shutting down`),await Promise.all([t.embedder.shutdown?.().catch(()=>{})??Promise.resolve(),t.graphStore.close().catch(()=>{}),t.store.close().catch(()=>{})]),process.exit(0)};process.on(`SIGINT`,i),process.on(`SIGTERM`,i);let a=process.ppid,o=setInterval(()=>{try{process.kill(a,0)}catch{$.info(`Parent process died; shutting down`,{parentPid:a}),clearInterval(o),i()}},5e3);return o.unref(),{server:n,runInitialIndex:r,shutdown:i}}export{L as ALL_TOOL_NAMES,Vd as createLazyServer,Hd as createMcpServer,Ud as createServer,Ed as initializeAikit,Sd as registerMcpTools};
@@ -1,6 +1,6 @@
1
1
  // AUTO-GENERATED - do not edit manually.
2
2
  // Source: packages/server/src/tools/present/block-registry.ts
3
- // Generated at: 2026-05-10T12:09:40.613Z
3
+ // Generated at: 2026-05-10T12:35:16.736Z
4
4
 
5
5
  export const ALL_BLOCK_DOCS = "| Type | Description | Value Shape |\n|------|-------------|-------------|\n| `markdown` | Markdown content rendered with the marked parser. | `string` |\n| `code` | Formatted code block rendered inside pre/code tags. | `string` |\n| `mermaid` | Mermaid diagram source rendered in a mermaid pre block. | `string` |\n| `table` | Tabular data rendered from records or explicit headers and rows. | `Record<string, unknown>[] | { headers: string[]; rows: unknown[][] }` |\n| `metrics` | Metric cards showing label/value pairs with optional trend and status. | `Array<{ label: string; value: string | number; trend?: string | number; status?: string }>` |\n| `cards` | Card grid for titled items with optional body, badge, and status. | `Array<{ title: string; body?: string; badge?: string; status?: string; description?: string }>` |\n| `tree` | Hierarchical object or name/children tree rendered recursively. | `{ name: string; children?: unknown[] } | Record<string, unknown>` |\n| `graph` | Node and edge graph rendered as a Mermaid flow graph in HTML mode. | `{ nodes: Array<{ id: string; label?: string }>; edges: Array<{ from: string; to: string; label?: string }> }` |\n| `chart` | Structured chart definition rendered as SVG. | `{ chartType: string; data: Record<string, unknown>[]; xKey: string; yKeys: string[] }` |\n| `timeline` | Timeline entries rendered as a vertical sequence of events. | `Array<{ title: string; description?: string; timestamp?: string; status?: string }>` |\n| `checklist` | Checklist items with boolean checked state. | `Array<{label, checked}> | {items: Array<{label, checked}>}` |\n| `comparison` | Side-by-side comparison columns with titled item lists. | `Array<{title, items}> | {columns: Array<{title, items}>}` |\n| `status-board` | Status categories containing labeled status items. | `Array<{category, items}> | {items: Array<{category, items}>}` |\n| `prompt` | Prompt payload rendered through the prompt display helper. | `unknown` |\n| `progress` | Progress bar with current value and optional maximum. | `{label, value, max?} | {items: Array<{label, value, max?, color?}>}` |\n| `viewer-link` | Styled card linking to a standalone interactive viewer. | `{ viewerType: string; label: string; description?: string; url?: string; icon?: string }` |\n| `docs-browser` | Collapsible file tree with markdown content for documentation browsing. | `{ files: Array<{ path: string; title?: string; content?: string; status?: \"current\" | \"stale\" | \"missing\" }>; title?: string }` |\n| `text` | Plain text content rendered through the markdown parser. | `string` |\n| `heading` | Single heading with configurable level from h1 to h6. | `string` |\n| `paragraph` | Single paragraph rendered inside a p tag. | `string` |\n| `separator` | Horizontal rule used to separate adjacent blocks. | `undefined` |\n| `actions` | Action bar containing button and select action definitions. | `Array<{ type: string; id: string; label: string; variant?: string; options?: Array<string | { label: string; value: string }> }>` |\n\n### Usage Examples\n\n#### `viewer-link`\n\n```typescript\n{\n type: 'viewer-link',\n value: {\n viewerType: 'c4',\n label: 'Open Interactive C4 Diagram',\n description: 'Drag, zoom, and pan with ELK auto-layout',\n icon: '🏗️',\n },\n}\n```\n\n#### `docs-browser`\n\n```typescript\n{\n type: 'docs-browser',\n value: {\n title: 'Project Docs',\n files: [\n { path: 'docs/README.md', title: 'Overview', status: 'current' },\n { path: 'docs/api.md', title: 'API Reference', status: 'stale' },\n ],\n },\n}\n```";
6
6