@vpxa/aikit 0.1.70 → 0.1.72

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.
@@ -1068,12 +1068,15 @@ li{margin:4px 0}
1068
1068
  <title>${J(t[a])} / ${J(e.yKeys[n])}: ${Os(r)}</title>
1069
1069
  </rect>`)}return`<svg class="chart-svg" viewBox="0 0 ${l} ${u}" preserveAspectRatio="xMidYMid meet">
1070
1070
  ${d.join(``)}
1071
- </svg>`}function Ws(e){return e==null?`null`:Array.isArray(e)?`[${e.map(Ws).join(`, `)}]`:String(e)}function Gs(e){return e.replace(/[^a-zA-Z0-9_]/g,`_`)}function Ks(e){if(typeof e!=`object`||!e||!(`type`in e))return!1;let t=e,n=typeof t.type==`string`?t.type:``;return new Set([`separator`,`actions`]).has(n)?!0:`value`in t||typeof t.text==`string`||Array.isArray(t.headers)&&Array.isArray(t.rows)||typeof t.code==`string`||Array.isArray(t.items)||!!t.entries&&typeof t.entries==`object`&&!Array.isArray(t.entries)||!!t.columns&&typeof t.columns==`object`||`chartType`in t||Array.isArray(t.data)||typeof t.content==`string`||typeof t.markdown==`string`||typeof t.description==`string`||Array.isArray(t.metrics)||Array.isArray(t.cards)||Array.isArray(t.nodes)||typeof t.question==`string`}function qs(e){if(Array.isArray(e)){let t=e.filter(e=>typeof e==`object`&&!!e),n=t.map(e=>String(e.title??``)),r=Math.max(0,...t.map(e=>Array.isArray(e.items)?e.items.length:0));return{headers:n,rows:Array.from({length:r},(e,n)=>t.map(e=>Array.isArray(e.items)?e.items[n]??``:``))}}if(!e||typeof e!=`object`)return null;let t=e,n=Object.keys(t),r=Math.max(0,...n.map(e=>Array.isArray(t[e])?t[e].length:0));return{headers:n,rows:Array.from({length:r},(e,r)=>n.map(e=>Array.isArray(t[e])?t[e][r]??``:``))}}function Js(e){let t=e,n=e;if(`value`in n||(typeof t.text==`string`?n={...n,value:t.text}:typeof t.content==`string`?n={...n,value:t.content}:typeof t.markdown==`string`?n={...n,value:t.markdown}:typeof t.description==`string`?n={...n,value:t.description}:typeof t.code==`string`?n={...n,value:t.code}:Array.isArray(t.headers)&&Array.isArray(t.rows)?n={...n,value:{headers:t.headers,rows:t.rows}}:Array.isArray(t.items)?n={...n,value:{items:t.items}}:Array.isArray(t.metrics)?n={...n,value:t.metrics}:Array.isArray(t.cards)?n={...n,value:t.cards}:Array.isArray(t.nodes)&&Array.isArray(t.edges)?n={...n,value:{nodes:t.nodes,edges:t.edges}}:typeof t.question==`string`?n={...n,value:{question:t.question,context:t.context,placeholder:t.placeholder}}:(`chartType`in t||Array.isArray(t.data))&&(n={...n,value:{chartType:t.chartType,data:t.data,xKey:t.xKey??`label`,yKeys:t.yKeys??[`value`]}})),n.type===`chart`){let e=n.value;if(e&&typeof e==`object`&&!Array.isArray(e)){let t=e,r=t.data&&typeof t.data==`object`&&!Array.isArray(t.data)?t.data:null,i=Array.isArray(t.labels)?t.labels:Array.isArray(r?.labels)?r.labels:null,a=Array.isArray(t.datasets)?t.datasets:Array.isArray(r?.datasets)?r.datasets:null,o=typeof t.type==`string`?t.type:typeof t.chartType==`string`?t.chartType:null;if(o&&i&&a&&!Array.isArray(t.data)){let e=a.map((e,t)=>String(e.label??`series${t+1}`)),t=i.map((e,t)=>{let n={label:String(e)};for(let[e,r]of a.entries()){let i=r,a=String(i.label??`series${e+1}`);n[a]=i.data?.[t]??0}return n});n={...n,value:{chartType:String(o),data:t,xKey:`label`,yKeys:e}}}}}let r=n;if(n.type===`text`||n.type===`paragraph`)return{...n,type:`markdown`};if(n.type===`heading`)return{...n,type:`markdown`,value:`## ${String(r.value??``)}`};if(n.type===`kv`){let e=t.entries&&typeof t.entries==`object`&&!Array.isArray(t.entries)?t.entries:r.value&&typeof r.value==`object`&&!Array.isArray(r.value)?r.value:null;if(e)return{...n,type:`table`,value:{headers:[`Key`,`Value`],rows:Object.entries(e).map(([e,t])=>[e,t])}}}if(n.type===`comparison`){let e=qs(t.columns??(r.value&&typeof r.value==`object`?r.value.columns:void 0))??qs(r.value);if(e)return{...n,type:`table`,value:e};let i=r.value;if(i&&typeof i==`object`&&!Array.isArray(i)){let e=i;if(Array.isArray(e.headers)&&Array.isArray(e.rows))return{...n,type:`table`}}}if(n.type===`timeline`){let e=r.value;if(Array.isArray(e)){let t=e.map(e=>{if(e&&typeof e==`object`){let t=e;return[String(t.status??t.state??``),String(t.time??t.date??t.timestamp??``),String(t.label??t.description??t.title??t.text??``)]}return[``,``,String(e)]});return{...n,type:`table`,value:{headers:[`Status`,`Time`,`Description`],rows:t}}}}return n}function Ys(e,t){let n=e=>{if(e==null)return``;if(typeof e==`string`)return e;if(typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`)return String(e);if(typeof e==`object`)try{let t=JSON.stringify(e);return typeof t==`string`?t:String(e)}catch{return String(e)}return String(e)};if(e==null)return null;if(typeof e==`string`)return{type:`markdown`,title:t,value:e};if(typeof e==`number`||typeof e==`boolean`)return{type:`markdown`,title:t,value:String(e)};if(Array.isArray(e)){if(e.every(e=>typeof e==`string`||typeof e==`number`||typeof e==`boolean`))return{type:`markdown`,title:t,value:e.map(e=>`- ${String(e)}`).join(`
1071
+ </svg>`}function Ws(e){if(e==null)return`null`;if(Array.isArray(e))return`[${e.map(Ws).join(`, `)}]`;if(typeof e==`object`)try{return JSON.stringify(e)}catch{return String(e)}return String(e)}function Gs(e){return e.replace(/[^a-zA-Z0-9_]/g,`_`)}function Ks(e){if(typeof e!=`string`)return e;let t=e.trim();if(t.startsWith(`[`)&&t.endsWith(`]`)||t.startsWith(`{`)&&t.endsWith(`}`))try{return JSON.parse(t)}catch{return e}return e}function qs(e){if(typeof e!=`object`||!e||!(`type`in e))return!1;let t=e,n=typeof t.type==`string`?t.type:``;return new Set([`separator`,`actions`]).has(n)?!0:`value`in t||typeof t.text==`string`||Array.isArray(t.headers)&&Array.isArray(t.rows)||typeof t.code==`string`||Array.isArray(t.items)||!!t.entries&&typeof t.entries==`object`&&!Array.isArray(t.entries)||!!t.columns&&typeof t.columns==`object`||`chartType`in t||Array.isArray(t.data)||typeof t.content==`string`||typeof t.markdown==`string`||typeof t.description==`string`||Array.isArray(t.metrics)||Array.isArray(t.cards)||Array.isArray(t.nodes)||typeof t.question==`string`}function Js(e){if(Array.isArray(e)){let t=e.filter(e=>typeof e==`object`&&!!e),n=t.map(e=>String(e.title??``)),r=Math.max(0,...t.map(e=>Array.isArray(e.items)?e.items.length:0));return{headers:n,rows:Array.from({length:r},(e,n)=>t.map(e=>Array.isArray(e.items)?e.items[n]??``:``))}}if(!e||typeof e!=`object`)return null;let t=e,n=Object.keys(t),r=Math.max(0,...n.map(e=>Array.isArray(t[e])?t[e].length:0));return{headers:n,rows:Array.from({length:r},(e,r)=>n.map(e=>Array.isArray(t[e])?t[e][r]??``:``))}}function Ys(e){let t=e,n=e;if(`value`in n||(typeof t.text==`string`?n={...n,value:t.text}:typeof t.content==`string`?n={...n,value:t.content}:typeof t.markdown==`string`?n={...n,value:t.markdown}:typeof t.description==`string`?n={...n,value:t.description}:typeof t.code==`string`?n={...n,value:t.code}:Array.isArray(t.headers)&&Array.isArray(t.rows)?n={...n,value:{headers:t.headers,rows:t.rows}}:Array.isArray(t.items)?n={...n,value:{items:t.items}}:Array.isArray(t.metrics)?n={...n,value:t.metrics}:Array.isArray(t.cards)?n={...n,value:t.cards}:Array.isArray(t.nodes)&&Array.isArray(t.edges)?n={...n,value:{nodes:t.nodes,edges:t.edges}}:typeof t.question==`string`?n={...n,value:{question:t.question,context:t.context,placeholder:t.placeholder}}:(`chartType`in t||Array.isArray(t.data))&&(n={...n,value:{chartType:t.chartType,data:t.data,xKey:t.xKey??`label`,yKeys:t.yKeys??[`value`]}})),n.type===`chart`){let e=n.value;if(e&&typeof e==`object`&&!Array.isArray(e)){let t=e,r=t.data&&typeof t.data==`object`&&!Array.isArray(t.data)?t.data:null,i=Array.isArray(t.labels)?t.labels:Array.isArray(r?.labels)?r.labels:null,a=Array.isArray(t.datasets)?t.datasets:Array.isArray(r?.datasets)?r.datasets:null,o=typeof t.type==`string`?t.type:typeof t.chartType==`string`?t.chartType:null;if(o&&i&&a&&!Array.isArray(t.data)){let e=a.map((e,t)=>String(e.label??`series${t+1}`)),t=i.map((e,t)=>{let n={label:String(e)};for(let[e,r]of a.entries()){let i=r,a=String(i.label??`series${e+1}`);n[a]=i.data?.[t]??0}return n});n={...n,value:{chartType:String(o),data:t,xKey:`label`,yKeys:e}}}}}let r=n;if(n.type===`text`||n.type===`paragraph`)return{...n,type:`markdown`};if(n.type===`heading`)return{...n,type:`markdown`,value:`## ${String(r.value??``)}`};if(n.type===`header`){let e=Math.min(Math.max(Number(n.level)||2,1),6);return{...n,type:`markdown`,value:`${`#`.repeat(e)} ${String(r.value??``)}`}}if(n.type===`section`)return{...n,type:`markdown`};if(n.type===`list`||n.type===`bullet`||n.type===`bullets`){let e=Array.isArray(r.value)?r.value:r.value&&typeof r.value==`object`&&Array.isArray(r.value.items)?r.value.items:void 0;return Array.isArray(e)?{...n,type:`markdown`,value:e.map(e=>`- ${String(e)}`).join(`
1072
+ `)}:{...n,type:`markdown`}}if(n.type===`note`||n.type===`info`||n.type===`warning`||n.type===`alert`||n.type===`callout`){let e=n.type===`warning`?`⚠️`:n.type===`alert`?`🚨`:`ℹ️`;return{...n,type:`markdown`,value:`> ${e} ${String(r.value??``)}`}}if(n.type===`quote`||n.type===`blockquote`){let e=String(r.value??``).split(`
1073
+ `);return{...n,type:`markdown`,value:e.map(e=>`> ${e}`).join(`
1074
+ `)}}if(n.type===`divider`||n.type===`hr`)return{...n,type:`separator`};if(n.type===`image`||n.type===`img`){let e=n,t=String(e.src??e.url??e.value??``),r=String(e.alt??e.label??e.title??`image`);return{...n,type:`markdown`,value:`![${r}](${t})`}}if(n.type===`link`||n.type===`url`){let e=n,t=String(e.href??e.url??e.value??``),r=String(e.label??e.text??e.title??t);return{...n,type:`markdown`,value:`[${r}](${t})`}}if(n.type===`kv`){let e=t.entries&&typeof t.entries==`object`&&!Array.isArray(t.entries)?t.entries:r.value&&typeof r.value==`object`&&!Array.isArray(r.value)?r.value:null;if(e)return{...n,type:`table`,value:{headers:[`Key`,`Value`],rows:Object.entries(e).map(([e,t])=>[e,t])}}}if(n.type===`comparison`){let e=Js(t.columns??(r.value&&typeof r.value==`object`?r.value.columns:void 0))??Js(r.value);if(e)return{...n,type:`table`,value:e};let i=r.value;if(i&&typeof i==`object`&&!Array.isArray(i)){let e=i;if(Array.isArray(e.headers)&&Array.isArray(e.rows))return{...n,type:`table`}}}if(n.type===`timeline`){let e=r.value;if(Array.isArray(e)){let t=e.map(e=>{if(e&&typeof e==`object`){let t=e;return[String(t.status??t.state??``),String(t.time??t.date??t.timestamp??``),String(t.label??t.description??t.title??t.text??``)]}return[``,``,String(e)]});return{...n,type:`table`,value:{headers:[`Status`,`Time`,`Description`],rows:t}}}}return n}function Xs(e,t){let n=e=>{if(e==null)return``;if(typeof e==`string`)return e;if(typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`)return String(e);if(typeof e==`object`)try{let t=JSON.stringify(e);return typeof t==`string`?t:String(e)}catch{return String(e)}return String(e)};if(e==null)return null;if(typeof e==`string`)return{type:`markdown`,title:t,value:e};if(typeof e==`number`||typeof e==`boolean`)return{type:`markdown`,title:t,value:String(e)};if(Array.isArray(e)){if(e.every(e=>typeof e==`string`||typeof e==`number`||typeof e==`boolean`))return{type:`markdown`,title:t,value:e.map(e=>`- ${String(e)}`).join(`
1072
1075
  `)};let n=e.filter(e=>typeof e==`object`&&!!e);if(n.length===e.length){let e={success:`✅`,done:`✅`,warning:`⚠️`,"at-risk":`⚠️`,error:`❌`,info:`ℹ️`,pending:`⏳`};if(n.every(e=>typeof e.category==`string`&&Array.isArray(e.items))){let r=n.map(t=>{let n=typeof t.category==`string`?t.category:null,r=Array.isArray(t.items)?t.items:null;if(!n||!r)return null;let i=r.map(t=>{if(!t||typeof t!=`object`)return null;let n=t,r=n.label??n.title??n.name,i=typeof r==`string`||typeof r==`number`||typeof r==`boolean`?String(r):null;if(!i)return null;let a=typeof n.status==`string`?`${e[n.status.toLowerCase()]??`●`} `:``,o=n.detail??n.description;return`- ${a}${i}${typeof o==`string`&&o.length>0?` — ${o}`:typeof o==`number`||typeof o==`boolean`?` — ${String(o)}`:``}`}).filter(e=>typeof e==`string`);return i.length===0?null:`### ${n}\n${i.join(`
1073
1076
  `)}`}).filter(e=>typeof e==`string`);if(r.length>0)return{type:`markdown`,title:t,value:r.join(`
1074
1077
 
1075
- `)}}let r=new Set;for(let e of n)for(let t of Object.keys(e))r.add(t);let i=Array.from(r);return{type:`table`,title:t,value:{headers:i,rows:n.map(e=>i.map(t=>{if(!(t in e)||e[t]===void 0||e[t]===null)return``;let n=e[t];if(typeof n==`object`)try{let e=JSON.stringify(n);return typeof e==`string`?e:``}catch{return String(n)}return String(n)}))}}}}if(typeof e==`object`){let r=e;if(Array.isArray(r.items))return Ys(r.items,t);let i=Object.entries(r).map(([e,t])=>`**${e}**: ${n(t)}`);return i.length>0?{type:`markdown`,title:t,value:i.join(`
1076
- `)}:null}return null}function Xs(e){let t=e.value;if(e.type===`separator`)return{type:`markdown`,title:e.title,value:`---`};if(e.type===`checklist`){let n=Array.isArray(t)?t:t&&typeof t==`object`&&Array.isArray(t.items)?t.items:null;if(!n)return e;let r=n.map(e=>{if(!e||typeof e!=`object`)return null;let t=e;if(typeof t.label!=`string`)return null;let n=t.checked===!0?`x`:` `,r=typeof t.note==`string`&&t.note.length>0?` — ${t.note}`:``;return`- [${n}] ${t.label}${r}`}).filter(e=>typeof e==`string`);return r.length>0?{type:`markdown`,title:e.title,value:r.join(`
1078
+ `)}}let r=new Set;for(let e of n)for(let t of Object.keys(e))r.add(t);let i=Array.from(r);return{type:`table`,title:t,value:{headers:i,rows:n.map(e=>i.map(t=>{if(!(t in e)||e[t]===void 0||e[t]===null)return``;let n=e[t];if(typeof n==`object`)try{let e=JSON.stringify(n);return typeof e==`string`?e:``}catch{return String(n)}return String(n)}))}}}}if(typeof e==`object`){let r=e;if(Array.isArray(r.items))return Xs(r.items,t);let i=Object.entries(r).map(([e,t])=>`**${e}**: ${n(t)}`);return i.length>0?{type:`markdown`,title:t,value:i.join(`
1079
+ `)}:null}return null}function Zs(e){let t=e.value;if(e.type===`separator`)return{type:`markdown`,title:e.title,value:`---`};if(e.type===`checklist`){let n=Array.isArray(t)?t:t&&typeof t==`object`&&Array.isArray(t.items)?t.items:null;if(!n)return e;let r=n.map(e=>{if(!e||typeof e!=`object`)return null;let t=e;if(typeof t.label!=`string`)return null;let n=t.checked===!0?`x`:` `,r=typeof t.note==`string`&&t.note.length>0?` — ${t.note}`:``;return`- [${n}] ${t.label}${r}`}).filter(e=>typeof e==`string`);return r.length>0?{type:`markdown`,title:e.title,value:r.join(`
1077
1080
  `)}:e}if(e.type===`status-board`){let n={success:`✅`,done:`✅`,warning:`⚠️`,"at-risk":`⚠️`,error:`❌`,info:`ℹ️`,pending:`⏳`},r=Array.isArray(t)?t:t&&typeof t==`object`&&Array.isArray(t.items)?t.items:null;if(r&&r.length>0){let t=r[0];if(t&&typeof t==`object`&&`category`in t){let t=r.map(e=>{if(!e||typeof e!=`object`)return null;let t=e;if(typeof t.category!=`string`||!Array.isArray(t.items))return null;let r=t.items.map(e=>{if(!e||typeof e!=`object`)return null;let t=e;if(typeof t.label!=`string`)return null;let r=typeof t.status==`string`?`${n[t.status.toLowerCase()]??`●`} `:``,i=typeof t.detail==`string`&&t.detail.length>0?` — ${t.detail}`:``;return`- ${r}${t.label}${i}`}).filter(Boolean);return`### ${t.category}\n${r.join(`
1078
1081
  `)}`}).filter(Boolean);if(t.length>0)return{type:`markdown`,title:e.title,value:t.join(`
1079
1082
 
@@ -1083,11 +1086,11 @@ li{margin:4px 0}
1083
1086
  `)}`}).filter(Boolean);if(r.length>0)return{type:`markdown`,title:e.title,value:r.join(`
1084
1087
 
1085
1088
  `)}}let i=n.map(e=>{if(!e||typeof e!=`object`)return null;let n=e,r=typeof n.label==`string`?n.label:typeof n.title==`string`?n.title:null;return r?`- ${typeof n.status==`string`?`${t[n.status.toLowerCase()]??`●`} `:``}${r}${typeof n.description==`string`&&n.description.length>0?` — ${n.description}`:``}`:null}).filter(Boolean);if(i.length>0)return{type:`markdown`,title:e.title,value:i.join(`
1086
- `)}}}return e.type===`table`&&typeof t==`string`?{type:`markdown`,title:e.title,value:t}:new Set([`markdown`,`table`,`code`,`chart`,`metrics`,`tree`,`graph`,`mermaid`]).has(e.type)?e:Ys(e.value,e.title)||{type:`code`,title:e.title,value:typeof e.value==`string`?e.value:JSON.stringify(e.value,null,2)}}function Zs(e){return Array.isArray(e)?e.map(e=>Ks(e)?Xs(Js(e)):e):e}Cn.setOptions({async:!1,gfm:!0,breaks:!0}),Cn.use({renderer:{html(e){return B(e.text)}}});function Qs(e){return e.replace(/<table\b/g,`<div class="table-wrap"><table`).replace(/<\/table>/g,`</table></div>`)}function $s(e){if(typeof e!=`object`||!e)return`<p>${B(String(e))}</p>`;let t=e;return typeof t.type==`string`?tc(Js(t)):`<pre>${B(JSON.stringify(e,null,2))}</pre>`}function ec(e,t){let n=[];if(e&&n.push(`<h1>${B(e)}</h1>`),typeof t==`string`)n.push(`<div class="md-content">${Qs(Cn.parse(t))}</div>`);else if(Array.isArray(t))if(t.length===0)n.push(`<p><em>empty</em></p>`);else if(Ks(t[0]))for(let e of t)n.push($s(e));else typeof t[0]==`object`&&t[0]!==null?n.push(nc(t)):n.push(`<ul>${t.map(e=>`<li>${B(String(e))}</li>`).join(``)}</ul>`);else if(typeof t==`object`&&t){let e=t;if(Array.isArray(e.blocks)&&e.blocks.length>0)for(let t of e.blocks)n.push($s(t));else Array.isArray(e.metrics)?n.push(rc(e.metrics)):Array.isArray(e.nodes)&&Array.isArray(e.edges)?(n.push(`<pre class="mermaid">${B(sc(e))}</pre>`),n.push(`<script src="https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.min.js"><\/script>`),n.push(`<script>mermaid.run();<\/script>`)):n.push(ac(e))}else n.push(`<p>${B(String(t))}</p>`);return n.join(`
1087
- `)}function tc(e){let t=[];switch(e.title&&t.push(`<h2>${B(e.title)}</h2>`),e.type){case`markdown`:t.push(`<div class="md-content">${Qs(Cn.parse(String(e.value??``)))}</div>`);break;case`code`:t.push(`<pre><code>${B(String(e.value??``))}</code></pre>`);break;case`mermaid`:t.push(`<pre class="mermaid">${B(String(e.value??``))}</pre>`);break;case`table`:if(Array.isArray(e.value)){let n=e.value;if(n.length>0&&Array.isArray(n[0])){let e=n,r=e[0].map(String),i=e.slice(1).map(e=>Object.fromEntries(r.map((t,n)=>[t,e[n]])));t.push(nc(i))}else t.push(nc(n))}else if(e.value&&typeof e.value==`object`&&`headers`in e.value&&`rows`in e.value){let{headers:n,rows:r}=e.value,i=r.map(e=>Object.fromEntries(n.map((t,n)=>[t,e[n]])));t.push(nc(i))}break;case`metrics`:{let n;Array.isArray(e.value)?n=e.value:e.value&&typeof e.value==`object`&&(n=Object.entries(e.value).map(([e,t])=>({label:e,value:String(t)}))),n&&t.push(rc(n));break}case`cards`:Array.isArray(e.value)&&t.push(ic(e.value));break;case`tree`:e.value&&typeof e.value==`object`&&t.push(ac(e.value));break;case`graph`:e.value&&typeof e.value==`object`&&t.push(`<pre class="mermaid">${B(sc(e.value))}</pre>`);break;case`chart`:t.push(js(e));break;case`timeline`:{let n=e.value;Array.isArray(n)&&(n={items:n.map(e=>({title:String(e.event??e.title??``),phase:e.date==null?e.phase==null?void 0:String(e.phase):String(e.date),description:e.description==null?void 0:String(e.description),status:e.status??`done`}))}),n&&t.push(Ss(n));break}case`checklist`:e.value&&t.push(Cs(e.value));break;case`comparison`:e.value&&t.push(ws(e.value));break;case`status-board`:e.value&&t.push(Ts(e.value));break;case`prompt`:e.value&&t.push(Es(e.value));break;case`progress`:e.value&&t.push(Ds(e.value));break;case`text`:t.push(`<div class="md-content">${Cn.parse(String(e.value??``))}</div>`);break;case`heading`:{let n=Math.min(Math.max(Number(e.level)||2,1),6);t.push(`<h${n}>${B(String(e.value??``))}</h${n}>`);break}case`paragraph`:t.push(`<p>${B(String(e.value??``))}</p>`);break;case`separator`:t.push(`<hr class="separator">`);break;case`actions`:{let n=(Array.isArray(e.value)?e.value:[]).map(e=>{if(e.type===`select`){let t=Array.isArray(e.options)?e.options.map(e=>`<option value="${B(String(e.value??e.label??``))}">${B(String(e.label??e.value??``))}</option>`).join(``):``;return`<select class="action-select"><option value="">${B(String(e.label??`Select...`))}</option>${t}</select>`}return`<button class="action-btn action-${String(e.variant??`secondary`)}">${B(String(e.label??``))}</button>`}).join(``);t.push(`<div class="action-bar">${n}</div>`);break}default:t.push(`<pre>${B(JSON.stringify(e.value,null,2))}</pre>`)}return t.join(`
1088
- `)}function nc(e){if(e.length===0)return`<p><em>empty table</em></p>`;let t=Object.keys(e[0]);return`<div class="table-wrap"><table><thead><tr>${t.map(e=>`<th>${B(e)}</th>`).join(``)}</tr></thead><tbody>${e.map(e=>`<tr>${t.map(t=>`<td>${B(String(e[t]??``))}</td>`).join(``)}</tr>`).join(`
1089
- `)}</tbody></table></div>`}function rc(e){return`<div class="metric-grid">${e.map(e=>`<div class="metric"><div class="metric-value">${B(String(e.value))}</div><div class="metric-label">${B(e.label)}</div></div>`).join(``)}</div>`}function ic(e){return`<div class="card-grid">${e.map(e=>{let t=[`<div class="card">`];return e.title&&t.push(`<div class="card-title">${B(String(e.title))}</div>`),(e.body||e.description)&&t.push(`<div class="card-body">${B(String(e.body??e.description))}</div>`),(e.badge||e.status)&&t.push(`<span class="badge">${B(String(e.badge??e.status))}</span>`),t.push(`</div>`),t.join(``)}).join(``)}</div>`}function ac(e){if(`name`in e&&`children`in e&&Array.isArray(e.children))return oc(e);if(`name`in e&&!(`children`in e))return`<div class="tree-node"><span class="tree-key">${B(String(e.name))}</span></div>`;let t=[];for(let[n,r]of Object.entries(e))typeof r==`object`&&r&&!Array.isArray(r)?t.push(`<div class="tree-node"><span class="tree-key">${B(n)}:</span><div class="tree-children">${ac(r)}</div></div>`):t.push(`<div class="tree-node"><span class="tree-key">${B(n)}:</span> ${B(Ws(r))}</div>`);return t.join(``)}function oc(e){let t=B(String(e.name));return!e.children||e.children.length===0?`<div class="tree-node"><span class="tree-key">${t}</span></div>`:`<div class="tree-node"><span class="tree-key">${t}</span><div class="tree-children">${e.children.map(e=>typeof e==`object`&&e?oc(e):`<div class="tree-node"><span class="tree-key">${B(String(e))}</span></div>`).join(``)}</div></div>`}function sc(e){let t=[`graph LR`];for(let n of e.nodes){let e=Gs(String(n.id??n.name??``)),r=String(n.label??n.name??e);t.push(` ${e}["${r}"]`)}for(let n of e.edges){let e=Gs(String(n.source??n.from??``)),r=Gs(String(n.target??n.to??``)),i=n.label?`|${String(n.label)}|`:``;t.push(` ${e} -->${i} ${r}`)}return t.join(`
1090
- `)}function cc(e,t,n,r){let i=r&&r!==`auto`?ma(r,t):ec(e,t);return`<!DOCTYPE html>
1089
+ `)}}}return e.type===`table`&&typeof t==`string`?{type:`markdown`,title:e.title,value:t}:new Set([`markdown`,`table`,`code`,`chart`,`metrics`,`tree`,`graph`,`mermaid`]).has(e.type)?e:Xs(e.value,e.title)||{type:`code`,title:e.title,value:typeof e.value==`string`?e.value:JSON.stringify(e.value,null,2)}}function Qs(e){if(!Array.isArray(e)&&typeof e==`object`&&e){let t=e;return Array.isArray(t.blocks)&&t.blocks.length>0?Qs(t.blocks):e}return Array.isArray(e)?e.map(e=>qs(e)?Zs(Ys(e)):e):e}Cn.setOptions({async:!1,gfm:!0,breaks:!0}),Cn.use({renderer:{html(e){return B(e.text)}}});function $s(e){return e.replace(/<table\b/g,`<div class="table-wrap"><table`).replace(/<\/table>/g,`</table></div>`)}function ec(e){if(typeof e!=`object`||!e)return`<p>${B(String(e))}</p>`;let t=e;return typeof t.type==`string`?nc(Ys(t)):`<pre>${B(JSON.stringify(e,null,2))}</pre>`}function tc(e,t){let n=[];if(e&&n.push(`<h1>${B(e)}</h1>`),typeof t==`string`)n.push(`<div class="md-content">${$s(Cn.parse(t))}</div>`);else if(Array.isArray(t))if(t.length===0)n.push(`<p><em>empty</em></p>`);else if(qs(t[0]))for(let e of t)n.push(ec(e));else typeof t[0]==`object`&&t[0]!==null?n.push(rc(t)):n.push(`<ul>${t.map(e=>`<li>${B(String(e))}</li>`).join(``)}</ul>`);else if(typeof t==`object`&&t){let e=t;if(Array.isArray(e.blocks)&&e.blocks.length>0)for(let t of e.blocks)n.push(ec(t));else Array.isArray(e.metrics)?n.push(ic(e.metrics)):Array.isArray(e.nodes)&&Array.isArray(e.edges)?(n.push(`<pre class="mermaid">${B(cc(e))}</pre>`),n.push(`<script src="https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.min.js"><\/script>`),n.push(`<script>mermaid.run();<\/script>`)):n.push(oc(e))}else n.push(`<p>${B(String(t))}</p>`);return n.join(`
1090
+ `)}function nc(e){let t=[];switch(e.title&&t.push(`<h2>${B(e.title)}</h2>`),e.type){case`markdown`:t.push(`<div class="md-content">${$s(Cn.parse(String(e.value??``)))}</div>`);break;case`code`:t.push(`<pre><code>${B(String(e.value??``))}</code></pre>`);break;case`mermaid`:t.push(`<pre class="mermaid">${B(String(e.value??``))}</pre>`);break;case`table`:if(Array.isArray(e.value)){let n=e.value;if(n.length>0&&Array.isArray(n[0])){let e=n,r=e[0].map(String),i=e.slice(1).map(e=>Object.fromEntries(r.map((t,n)=>[t,e[n]])));t.push(rc(i))}else t.push(rc(n))}else if(e.value&&typeof e.value==`object`&&`headers`in e.value&&`rows`in e.value){let{headers:n,rows:r}=e.value,i=r.map(e=>Object.fromEntries(n.map((t,n)=>[t,e[n]])));t.push(rc(i))}break;case`metrics`:{let n;Array.isArray(e.value)?n=e.value:e.value&&typeof e.value==`object`&&(n=Object.entries(e.value).map(([e,t])=>({label:e,value:String(t)}))),n&&t.push(ic(n));break}case`cards`:Array.isArray(e.value)&&t.push(ac(e.value));break;case`tree`:e.value&&typeof e.value==`object`&&t.push(oc(e.value));break;case`graph`:e.value&&typeof e.value==`object`&&t.push(`<pre class="mermaid">${B(cc(e.value))}</pre>`);break;case`chart`:t.push(js(e));break;case`timeline`:{let n=e.value;Array.isArray(n)&&(n={items:n.map(e=>({title:String(e.event??e.title??``),phase:e.date==null?e.phase==null?void 0:String(e.phase):String(e.date),description:e.description==null?void 0:String(e.description),status:e.status??`done`}))}),n&&t.push(Ss(n));break}case`checklist`:e.value&&t.push(Cs(e.value));break;case`comparison`:e.value&&t.push(ws(e.value));break;case`status-board`:e.value&&t.push(Ts(e.value));break;case`prompt`:e.value&&t.push(Es(e.value));break;case`progress`:e.value&&t.push(Ds(e.value));break;case`text`:t.push(`<div class="md-content">${Cn.parse(String(e.value??``))}</div>`);break;case`heading`:{let n=Math.min(Math.max(Number(e.level)||2,1),6);t.push(`<h${n}>${B(String(e.value??``))}</h${n}>`);break}case`paragraph`:t.push(`<p>${B(String(e.value??``))}</p>`);break;case`separator`:t.push(`<hr class="separator">`);break;case`actions`:{let n=(Array.isArray(e.value)?e.value:[]).map(e=>{if(e.type===`select`){let t=Array.isArray(e.options)?e.options.map(e=>`<option value="${B(String(e.value??e.label??``))}">${B(String(e.label??e.value??``))}</option>`).join(``):``;return`<select class="action-select"><option value="">${B(String(e.label??`Select...`))}</option>${t}</select>`}return`<button class="action-btn action-${String(e.variant??`secondary`)}">${B(String(e.label??``))}</button>`}).join(``);t.push(`<div class="action-bar">${n}</div>`);break}default:t.push(`<pre>${B(JSON.stringify(e.value,null,2))}</pre>`)}return t.join(`
1091
+ `)}function rc(e){if(e.length===0)return`<p><em>empty table</em></p>`;let t=Object.keys(e[0]);return`<div class="table-wrap"><table><thead><tr>${t.map(e=>`<th>${B(e)}</th>`).join(``)}</tr></thead><tbody>${e.map(e=>`<tr>${t.map(t=>`<td>${B(String(e[t]??``))}</td>`).join(``)}</tr>`).join(`
1092
+ `)}</tbody></table></div>`}function ic(e){return`<div class="metric-grid">${e.map(e=>`<div class="metric"><div class="metric-value">${B(String(e.value))}</div><div class="metric-label">${B(e.label)}</div></div>`).join(``)}</div>`}function ac(e){return`<div class="card-grid">${e.map(e=>{let t=[`<div class="card">`];return e.title&&t.push(`<div class="card-title">${B(String(e.title))}</div>`),(e.body||e.description)&&t.push(`<div class="card-body">${B(String(e.body??e.description))}</div>`),(e.badge||e.status)&&t.push(`<span class="badge">${B(String(e.badge??e.status))}</span>`),t.push(`</div>`),t.join(``)}).join(``)}</div>`}function oc(e){if(`name`in e&&`children`in e&&Array.isArray(e.children))return sc(e);if(`name`in e&&!(`children`in e))return`<div class="tree-node"><span class="tree-key">${B(String(e.name))}</span></div>`;let t=[];for(let[n,r]of Object.entries(e))typeof r==`object`&&r&&!Array.isArray(r)?t.push(`<div class="tree-node"><span class="tree-key">${B(n)}:</span><div class="tree-children">${oc(r)}</div></div>`):t.push(`<div class="tree-node"><span class="tree-key">${B(n)}:</span> ${B(Ws(r))}</div>`);return t.join(``)}function sc(e){let t=B(String(e.name));return!e.children||e.children.length===0?`<div class="tree-node"><span class="tree-key">${t}</span></div>`:`<div class="tree-node"><span class="tree-key">${t}</span><div class="tree-children">${e.children.map(e=>typeof e==`object`&&e?sc(e):`<div class="tree-node"><span class="tree-key">${B(String(e))}</span></div>`).join(``)}</div></div>`}function cc(e){let t=[`graph LR`];for(let n of e.nodes){let e=Gs(String(n.id??n.name??``)),r=String(n.label??n.name??e);t.push(` ${e}["${r}"]`)}for(let n of e.edges){let e=Gs(String(n.source??n.from??``)),r=Gs(String(n.target??n.to??``)),i=n.label?`|${String(n.label)}|`:``;t.push(` ${e} -->${i} ${r}`)}return t.join(`
1093
+ `)}function lc(e,t,n,r){let i=r&&r!==`auto`?ma(r,t):tc(e,t);return`<!DOCTYPE html>
1091
1094
  <html lang="en">
1092
1095
  <head>
1093
1096
  <meta charset="UTF-8">
@@ -1179,17 +1182,17 @@ document.querySelectorAll('.table-wrap').forEach(wrap=>{
1179
1182
  });
1180
1183
  <\/script>
1181
1184
  </body>
1182
- </html>`}function lc(e,t,n){let r=[];if(e&&r.push(`# ${e}\n`),typeof t==`string`)r.push(t);else if(Array.isArray(t))if(t.length===0)r.push(`*(empty)*`);else if(Ks(t[0]))for(let e of t)r.push(uc(Js(e),n));else if(typeof t[0]==`object`&&t[0]!==null)n?.compactTables?r.push(fc(t)):r.push(dc(t));else for(let e of t)r.push(`- ${String(e)}`);else if(typeof t==`object`&&t){let e=t;if(Array.isArray(e.blocks)&&e.blocks.length>0)for(let t of e.blocks)Ks(t)?r.push(uc(Js(t),n)):r.push(String(t));else Array.isArray(e.nodes)&&Array.isArray(e.edges)?r.push(hc(e)):Array.isArray(e.metrics)?r.push(mc(e.metrics)):r.push(gc(e))}else r.push(String(t));return r.join(`
1183
- `)}function uc(e,t){let n=[];switch(e.title&&n.push(`## ${e.title}\n`),e.type){case`markdown`:n.push(String(e.value??``));break;case`code`:n.push(`\`\`\`${e.language??``}\n${String(e.value??``)}\n\`\`\``);break;case`mermaid`:n.push(`\`\`\`mermaid\n${String(e.value??``)}\n\`\`\``);break;case`table`:{let r=e.value;if(Array.isArray(r)&&r.length>0)t?.compactTables?n.push(fc(r,e.title)):n.push(dc(r));else if(r&&typeof r==`object`&&!Array.isArray(r)&&`headers`in r&&`rows`in r){let{headers:i,rows:a}=r;if(t?.compactTables){let t=[];e.title&&t.push(`**${e.title}**\n`);for(let e=0;e<a.length;e++){let n=i.map((t,n)=>`**${t}**: ${String(a[e]?.[n]??``)}`).join(` · `);t.push(`${e+1}. ${n}`)}n.push(t.join(`
1184
- `))}else{n.push(`| ${i.join(` | `)} |`),n.push(`| ${i.map(()=>`---`).join(` | `)} |`);for(let e of a)n.push(`| ${e.map(e=>String(e??``)).join(` | `)} |`)}}else n.push(`*(empty table)*`);break}case`metrics`:Array.isArray(e.value)&&n.push(mc(e.value));break;case`graph`:e.value&&typeof e.value==`object`&&n.push(hc(e.value));break;case`cards`:if(Array.isArray(e.value))for(let t of e.value)n.push(`### ${t.title??`Card`}`),(t.body||t.description)&&n.push(String(t.body??t.description)),(t.badge||t.status)&&n.push(`> **${t.badge??t.status}**`),n.push(``);break;case`tree`:e.value&&typeof e.value==`object`&&n.push(gc(e.value));break;case`chart`:{let t=e.value;t?.data&&Array.isArray(t.data)&&n.push(`*${String(t.chartType??`chart`)} chart — ${t.data.length} data points*`);break}case`timeline`:{let t=e.value;if(t?.items)for(let e of t.items){let t=e.status===`done`?`✅`:e.status===`active`?`🔄`:e.status===`error`?`❌`:`⬜`;n.push(`${t} **${e.title}**${e.description?` — ${e.description}`:``}`)}break}case`checklist`:{let t=e.value;if(t?.items)for(let e of t.items)n.push(`- [${e.checked?`x`:` `}] ${e.label}${e.note?` — ${e.note}`:``}`);break}case`comparison`:{let r=e.value;if(r?.columns&&r.columns.length>0)if(t?.compactTables)n.push(pc(r.columns,e.title));else{let e=Math.max(...r.columns.map(e=>e.items?.length??0)),t=r.columns.map(e=>e.title);n.push(`| ${t.join(` | `)} |`),n.push(`| ${t.map(()=>`---`).join(` | `)} |`);for(let t=0;t<e;t++)n.push(`| ${r.columns.map(e=>e.items?.[t]??``).join(` | `)} |`)}break}case`status-board`:{let t=e.value;if(t?.items)for(let e of t.items){let t=e.status===`success`?`🟢`:e.status===`warning`?`🟡`:e.status===`error`?`🔴`:e.status===`info`?`🔵`:`⚪`;n.push(`${t} **${e.label}**${e.detail?` — ${e.detail}`:``}`)}break}case`prompt`:{let t=e.value;t?.question&&(n.push(`> **${t.question}**`),t.context&&n.push(`> ${t.context}`));break}case`progress`:{let t=e.value;if(t?.items)for(let e of t.items){let t=e.max??100,r=t>0?Math.round(e.value/t*100):0,i=Math.round(r/5),a=`█`.repeat(i)+`░`.repeat(20-i);n.push(`${e.label}: ${a} ${r}%`)}break}case`text`:n.push(String(e.value??``));break;case`heading`:{let t=Math.min(Math.max(Number(e.level)||2,1),6);n.push(`${`#`.repeat(t)} ${String(e.value??``)}\n`);break}case`paragraph`:n.push(String(e.value??``));break;case`separator`:n.push(`---
1185
+ </html>`}function uc(e,t,n){let r=[];if(e&&r.push(`# ${e}\n`),typeof t==`string`)r.push(t);else if(Array.isArray(t))if(t.length===0)r.push(`*(empty)*`);else if(qs(t[0])||typeof t[0]==`object`&&t[0]!==null&&typeof t[0].type==`string`)for(let e of t)r.push(dc(Ys(e),n));else if(typeof t[0]==`object`&&t[0]!==null)n?.compactTables?r.push(pc(t)):r.push(fc(t));else for(let e of t)r.push(`- ${String(e)}`);else if(typeof t==`object`&&t){let e=t;if(Array.isArray(e.blocks)&&e.blocks.length>0)for(let t of e.blocks)qs(t)||typeof t==`object`&&t&&typeof t.type==`string`?r.push(dc(Ys(t),n)):typeof t==`object`&&t?r.push(_c(t)):r.push(String(t));else Array.isArray(e.nodes)&&Array.isArray(e.edges)?r.push(gc(e)):Array.isArray(e.metrics)?r.push(hc(e.metrics)):r.push(_c(e))}else r.push(String(t));return r.join(`
1186
+ `)}function dc(e,t){let n=[];switch(e.title&&n.push(`## ${e.title}\n`),e.type){case`markdown`:n.push(String(e.value??``));break;case`code`:n.push(`\`\`\`${e.language??``}\n${String(e.value??``)}\n\`\`\``);break;case`mermaid`:n.push(`\`\`\`mermaid\n${String(e.value??``)}\n\`\`\``);break;case`table`:{let r=e.value;if(Array.isArray(r)&&r.length>0)t?.compactTables?n.push(pc(r,e.title)):n.push(fc(r));else if(r&&typeof r==`object`&&!Array.isArray(r)&&`headers`in r&&`rows`in r){let{headers:i,rows:a}=r;if(t?.compactTables){let t=[];e.title&&t.push(`**${e.title}**\n`);for(let e=0;e<a.length;e++){let n=i.map((t,n)=>`**${t}**: ${String(a[e]?.[n]??``)}`).join(` · `);t.push(`${e+1}. ${n}`)}n.push(t.join(`
1187
+ `))}else{n.push(`| ${i.join(` | `)} |`),n.push(`| ${i.map(()=>`---`).join(` | `)} |`);for(let e of a)n.push(`| ${e.map(e=>String(e??``)).join(` | `)} |`)}}else n.push(`*(empty table)*`);break}case`metrics`:Array.isArray(e.value)&&n.push(hc(e.value));break;case`graph`:e.value&&typeof e.value==`object`&&n.push(gc(e.value));break;case`cards`:if(Array.isArray(e.value))for(let t of e.value)n.push(`### ${t.title??`Card`}`),(t.body||t.description)&&n.push(String(t.body??t.description)),(t.badge||t.status)&&n.push(`> **${t.badge??t.status}**`),n.push(``);break;case`tree`:e.value&&typeof e.value==`object`&&n.push(_c(e.value));break;case`chart`:{let t=e.value;t?.data&&Array.isArray(t.data)&&n.push(`*${String(t.chartType??`chart`)} chart — ${t.data.length} data points*`);break}case`timeline`:{let t=e.value;if(t?.items)for(let e of t.items){let t=e.status===`done`?`✅`:e.status===`active`?`🔄`:e.status===`error`?`❌`:`⬜`;n.push(`${t} **${e.title}**${e.description?` — ${e.description}`:``}`)}break}case`checklist`:{let t=e.value;if(t?.items)for(let e of t.items)n.push(`- [${e.checked?`x`:` `}] ${e.label}${e.note?` — ${e.note}`:``}`);break}case`comparison`:{let r=e.value;if(r?.columns&&r.columns.length>0)if(t?.compactTables)n.push(mc(r.columns,e.title));else{let e=Math.max(...r.columns.map(e=>e.items?.length??0)),t=r.columns.map(e=>e.title);n.push(`| ${t.join(` | `)} |`),n.push(`| ${t.map(()=>`---`).join(` | `)} |`);for(let t=0;t<e;t++)n.push(`| ${r.columns.map(e=>e.items?.[t]??``).join(` | `)} |`)}break}case`status-board`:{let t=e.value;if(t?.items)for(let e of t.items){let t=e.status===`success`?`🟢`:e.status===`warning`?`🟡`:e.status===`error`?`🔴`:e.status===`info`?`🔵`:`⚪`;n.push(`${t} **${e.label}**${e.detail?` — ${e.detail}`:``}`)}break}case`prompt`:{let t=e.value;t?.question&&(n.push(`> **${t.question}**`),t.context&&n.push(`> ${t.context}`));break}case`progress`:{let t=e.value;if(t?.items)for(let e of t.items){let t=e.max??100,r=t>0?Math.round(e.value/t*100):0,i=Math.round(r/5),a=`█`.repeat(i)+`░`.repeat(20-i);n.push(`${e.label}: ${a} ${r}%`)}break}case`text`:n.push(String(e.value??``));break;case`heading`:{let t=Math.min(Math.max(Number(e.level)||2,1),6);n.push(`${`#`.repeat(t)} ${String(e.value??``)}\n`);break}case`paragraph`:n.push(String(e.value??``));break;case`separator`:n.push(`---
1185
1188
  `);break;default:n.push(JSON.stringify(e.value,null,2))}return n.push(``),n.join(`
1186
- `)}function dc(e){if(e.length===0)return`*(empty table)*`;let t=Object.keys(e[0]),n=[];n.push(`| ${t.join(` | `)} |`),n.push(`| ${t.map(()=>`---`).join(` | `)} |`);for(let r of e)n.push(`| ${t.map(e=>String(r[e]??``)).join(` | `)} |`);return n.join(`
1187
- `)}function fc(e,t){if(e.length===0)return`*(empty table)*`;let n=Object.keys(e[0]),r=[];t&&r.push(`**${t}**\n`);for(let t=0;t<e.length;t++){let i=e[t],a=String(i[n[0]]??``);if(n.length===1)r.push(`${t+1}. **${a}**`);else{let e=n.slice(1).map(e=>`${e}: ${String(i[e]??``)}`).join(` · `);r.push(`${t+1}. **${a}** — ${e}`)}}return r.join(`
1188
- `)}function pc(e,t){let n=[];t&&n.push(`**${t}**\n`);for(let t of e){if(n.push(`**${t.title}**`),t.items&&t.items.length>0)for(let e of t.items)n.push(`- ${e}`);else n.push(`- *(none)*`);n.push(``)}return n.join(`
1189
- `)}function mc(e){return e.map(e=>`- **${e.label}**: ${e.value}`).join(`
1190
- `)}function hc(e){let t=["```mermaid",`graph LR`];for(let n of e.nodes){let e=Gs(String(n.id??n.name??``)),r=String(n.label??n.name??e);t.push(` ${e}["${r}"]`)}for(let n of e.edges){let e=Gs(String(n.source??n.from??``)),r=Gs(String(n.target??n.to??``)),i=n.label?`|${String(n.label)}|`:``;t.push(` ${e} -->${i} ${r}`)}return t.push("```"),t.join(`
1191
- `)}function gc(e,t=0){let n=` `.repeat(t),r=[];for(let[i,a]of Object.entries(e))typeof a==`object`&&a&&!Array.isArray(a)?(r.push(`${n}- **${i}**:`),r.push(gc(a,t+1))):r.push(`${n}- **${i}**: ${Ws(a)}`);return r.join(`
1192
- `)}const _c=import.meta.dirname??m(v(import.meta.url));function vc(e){let t=e;for(let e=0;e<10;e++){try{let e=g(t,`package.json`);if(a(e)&&JSON.parse(s(e,`utf8`)).name===`@vpxa/aikit`)return t}catch{}let e=m(t);if(e===t)break;t=e}return _(e,`..`,`..`,`..`)}const yc=`ui://aikit/present.html`,bc=F.object({type:F.enum([`button`,`select`]).describe(`Action type`),id:F.string().describe(`Unique action identifier`),label:F.string().describe(`Display label`),variant:F.enum([`primary`,`danger`,`default`]).optional().describe(`Button style variant`),options:F.array(F.union([F.string(),F.object({label:F.string(),value:F.string()})])).optional().describe(`Select options (for type=select)`)}),xc={format:F.enum([`html`,`browser`]).default(`html`).describe(`Output format.
1189
+ `)}function fc(e){if(e.length===0)return`*(empty table)*`;let t=Object.keys(e[0]),n=[];n.push(`| ${t.join(` | `)} |`),n.push(`| ${t.map(()=>`---`).join(` | `)} |`);for(let r of e)n.push(`| ${t.map(e=>String(r[e]??``)).join(` | `)} |`);return n.join(`
1190
+ `)}function pc(e,t){if(e.length===0)return`*(empty table)*`;let n=Object.keys(e[0]),r=[];t&&r.push(`**${t}**\n`);for(let t=0;t<e.length;t++){let i=e[t],a=String(i[n[0]]??``);if(n.length===1)r.push(`${t+1}. **${a}**`);else{let e=n.slice(1).map(e=>`${e}: ${String(i[e]??``)}`).join(` · `);r.push(`${t+1}. **${a}** — ${e}`)}}return r.join(`
1191
+ `)}function mc(e,t){let n=[];t&&n.push(`**${t}**\n`);for(let t of e){if(n.push(`**${t.title}**`),t.items&&t.items.length>0)for(let e of t.items)n.push(`- ${e}`);else n.push(`- *(none)*`);n.push(``)}return n.join(`
1192
+ `)}function hc(e){return e.map(e=>`- **${e.label}**: ${e.value}`).join(`
1193
+ `)}function gc(e){let t=["```mermaid",`graph LR`];for(let n of e.nodes){let e=Gs(String(n.id??n.name??``)),r=String(n.label??n.name??e);t.push(` ${e}["${r}"]`)}for(let n of e.edges){let e=Gs(String(n.source??n.from??``)),r=Gs(String(n.target??n.to??``)),i=n.label?`|${String(n.label)}|`:``;t.push(` ${e} -->${i} ${r}`)}return t.push("```"),t.join(`
1194
+ `)}function _c(e,t=0){let n=` `.repeat(t),r=[];for(let[i,a]of Object.entries(e))typeof a==`object`&&a&&!Array.isArray(a)?(r.push(`${n}- **${i}**:`),r.push(_c(a,t+1))):r.push(`${n}- **${i}**: ${Ws(a)}`);return r.join(`
1195
+ `)}const vc=import.meta.dirname??m(v(import.meta.url));function yc(e){let t=e;for(let e=0;e<10;e++){try{let e=g(t,`package.json`);if(a(e)&&JSON.parse(s(e,`utf8`)).name===`@vpxa/aikit`)return t}catch{}let e=m(t);if(e===t)break;t=e}return _(e,`..`,`..`,`..`)}const bc=`ui://aikit/present.html`,xc=F.object({type:F.enum([`button`,`select`]).describe(`Action type`),id:F.string().describe(`Unique action identifier`),label:F.string().describe(`Display label`),variant:F.enum([`primary`,`danger`,`default`]).optional().describe(`Button style variant`),options:F.array(F.union([F.string(),F.object({label:F.string(),value:F.string()})])).optional().describe(`Select options (for type=select)`)}),Sc={format:F.enum([`html`,`browser`]).default(`html`).describe(`Output format.
1193
1196
  - "html" (default): Rich markdown in chat + embedded UIResource for MCP-UI hosts. Actions shown as numbered choices.
1194
1197
  - "browser": Rich markdown in chat + opens beautiful themed dashboard in the browser. When actions are provided, the browser shows interactive buttons and the tool blocks until user clicks, returning their selection.`),title:F.string().optional().describe(`Optional heading`),content:F.any().describe(`Content to present. Accepts these shapes:
1195
1198
  • markdown string — rendered as rich text
@@ -1211,7 +1214,7 @@ document.querySelectorAll('.table-wrap').forEach(wrap=>{
1211
1214
  - type:"comparison" → value: [{title,items:string[]}] (columns)
1212
1215
  - type:"progress" → value: {label,value:number,max?:number}
1213
1216
  • any JSON — rendered as collapsible tree
1214
- IMPORTANT: For charts, use the ChartValue format above. Do NOT use Chart.js format ({labels, datasets}) — it will be auto-converted but the native format is preferred.`),actions:F.array(bc).optional().describe(`Interactive actions (buttons/selects). In html mode, shown as numbered choices. In browser mode, rendered as clickable buttons and the tool blocks until user clicks.`),template:F.enum([`auto`,`list-sort`,`data-table`,`picker`,`flame-graph`,`form`,`timeline`,`kanban`,`tree`,`diff-view`,`dashboard`]).optional().describe(`UI template for interactive display in MCP Apps hosts.
1217
+ IMPORTANT: For charts, use the ChartValue format above. Do NOT use Chart.js format ({labels, datasets}) — it will be auto-converted but the native format is preferred.`),actions:F.array(xc).optional().describe(`Interactive actions (buttons/selects). In html mode, shown as numbered choices. In browser mode, rendered as clickable buttons and the tool blocks until user clicks.`),template:F.enum([`auto`,`list-sort`,`data-table`,`picker`,`flame-graph`,`form`,`timeline`,`kanban`,`tree`,`diff-view`,`dashboard`]).optional().describe(`UI template for interactive display in MCP Apps hosts.
1215
1218
  - auto (default): detect from content shape
1216
1219
  - list-sort: drag-drop reorderable list — content: { items: [{id, label}] }
1217
1220
  - data-table: filterable sortable table — content: { columns: [{key, label}], rows: [{...}], stats?: [{label, value}] }
@@ -1222,16 +1225,16 @@ IMPORTANT: For charts, use the ChartValue format above. Do NOT use Chart.js form
1222
1225
  - kanban: drag-drop board — content: { columns: [{id, label, color?}], cards: [{id, title, column, tags?[], priority?}] }
1223
1226
  - tree: collapsible tree view — content: { root: {label, children?:[...]} | [...] }
1224
1227
  - diff-view: side-by-side diff — content: { files: [{path, status, additions, deletions, hunks:[{header, changes:[{type, content}]}]}] }
1225
- - dashboard: metric cards grid — content: { metrics: [{label, value, trend?, status?, type?}] }`)};let Sc,Cc=!1,wc=null;process.on(`exit`,()=>{if(wc){try{wc.close()}catch{}wc=null}});function Tc(){return g(vc(_c),`packages`,`present`,`dist`,`index.html`)}function Ec(){if(!Sc)try{Sc=s(Tc(),`utf-8`)}catch{Sc=``}return Sc}function Dc(e,t){let n=L(`present`),r=Ec(),i=`Present content to the user in the best format. Two modes:
1228
+ - dashboard: metric cards grid — content: { metrics: [{label, value, trend?, status?, type?}] }`)};let Cc,wc=!1,Tc=null;process.on(`exit`,()=>{if(Tc){try{Tc.close()}catch{}Tc=null}});function Ec(){return g(yc(vc),`packages`,`present`,`dist`,`index.html`)}function Dc(){if(!Cc)try{Cc=s(Ec(),`utf-8`)}catch{Cc=``}return Cc}function Oc(e,t){let n=L(`present`),r=Dc(),i=`Present content to the user in the best format. Two modes:
1226
1229
  - "html" (default): Rich markdown in chat + embedded UIResource. Use for display-only content (tables, charts, reports, status boards) where no user interaction is needed.
1227
1230
  - "browser": Serves a themed dashboard on a local URL. Use ONLY when you need user interaction back (confirmations, selections, form input). The tool blocks until user clicks an action button, then returns their selection.
1228
1231
  FORMAT RULE: If no user interaction is needed → use "html". If you need user input back → use "browser".
1229
1232
  CONTENT GUIDE: Pass typed blocks [{ type, title?, value }] for structured content. See the \`content\` parameter description for all supported block types and their value shapes. For charts: use {chartType, data:Record[], xKey, yKeys} — NOT Chart.js format.
1230
- BROWSER WORKFLOW: After calling present with format "browser", you MUST extract the URL from the response and call openBrowserPage({ url }) tool - PlayWright MCP to open it in VS Code Simple Browser. A system browser fallback also opens automatically, but always call openBrowserPage tool - PlayWright MCP yourself.`,a=async({format:e,title:n,content:r,actions:i,template:a})=>(e??`html`)===`browser`||Array.isArray(i)&&i.length>0?await Oc(n,r,i,t,a):kc(n,r,i,a);if(r){Cc||=(_n(e,`AI Kit Present App`,yc,{description:`Rich interactive content viewer for AI Kit tools`},async()=>({contents:[{uri:yc,mimeType:gn,text:r}]})),!0),vn(e,`present`,{title:n.title,description:i,annotations:n.annotations,inputSchema:xc,_meta:{ui:{resourceUri:yc}}},a);return}e.tool(`present`,i,xc,n.annotations,a)}async function Oc(e,t,n,r,i){let a=lc(e,t,{compactTables:!0}),o=cc(e,t,n,i),s=Sn({uri:`ui://aikit/present-browser.html`,content:{type:`rawHtml`,htmlString:o},encoding:`text`,adapters:{mcpApps:{enabled:!0}}}),c,l,u=Array.isArray(n)?n:[],d=``,f;try{wc&&=(wc.close(),null),u.length>0&&(c=new Promise(e=>{l=e}));let e=!1;d=await new Promise((t,n)=>{let r=xn((t,n)=>{if(e||(e=!0,f&&clearTimeout(f)),t.method===`POST`&&t.url===`/callback`){let e=``;t.on(`data`,t=>{e+=t.toString()}),t.on(`end`,()=>{n.writeHead(200,{"Content-Type":`application/json`,"Access-Control-Allow-Origin":`*`}),n.end(`{"ok":true}`);try{let t=JSON.parse(e);l?.(t)}catch{}});return}if(t.method===`OPTIONS`){n.writeHead(204,{"Access-Control-Allow-Origin":`*`,"Access-Control-Allow-Methods":`POST`,"Access-Control-Allow-Headers":`Content-Type`}),n.end();return}n.writeHead(200,{"Content-Type":`text/html; charset=utf-8`}),n.end(o)});r.listen(0,`127.0.0.1`,()=>{let i=r.address();if(typeof i==`object`&&i){wc=r;let n=`http://127.0.0.1:${i.port}`;f=setTimeout(()=>{if(!e)try{yn(process.platform===`win32`?`start "" "${n}"`:process.platform===`darwin`?`open "${n}"`:`xdg-open "${n}"`)}catch{}},8e3),f.unref(),t(n)}else n(Error(`Failed to start present server`))}),setTimeout(()=>{r.close(),wc===r&&(wc=null)},300*1e3).unref()})}catch{}let p=d?`${a}\n\n---\n🌐 **Dashboard opened in browser:** ${d}\n\n**IMPORTANT:** You MUST now open this URL using the \`openBrowserPage\` tool - PlayWright MCP. If that tool is unavailable, open the URL in the system browser as a fallback. If neither works, ask the user to open the URL manually.`:a;if(u.length>0&&r?.available&&c)try{let e=await Promise.race([c,new Promise((e,t)=>setTimeout(()=>t(Error(`timeout`)),300*1e3))]);return{content:[{type:`text`,text:`${p}\n\n✅ **Selected:** ${e.actionId} = \`${e.value}\``},s]}}catch{return{content:[{type:`text`,text:`${p}\n\n⚠️ *No selection received (timed out).*`},s]}}return{content:[{type:`text`,text:p},s]}}function kc(e,t,n,r){let i=Array.isArray(n)?n:[],a=lc(e,t,{compactTables:!0}),o=Sn({uri:`ui://aikit/present-static.html`,content:{type:`rawHtml`,htmlString:cc(e,t,n,r)},encoding:`text`,adapters:{mcpApps:{enabled:!0}}});return{content:[{type:`text`,text:a},o],structuredContent:{title:e,content:Zs(t),actions:i}}}const Ac=E(`tools`);function jc(e,t){let n=new fn({structure:new mn,dependencies:new ln,symbols:new hn,patterns:new pn,entryPoints:new dn,diagrams:new un}),r=L(`produce_knowledge`);e.registerTool(`produce_knowledge`,{title:r.title,description:`Run automated codebase analysis and produce synthesis instructions. Executes Tier 1 deterministic analyzers, then returns structured baselines and instructions for you to synthesize knowledge using remember.`,inputSchema:{scope:F.string().optional().describe(`Root path to analyze (defaults to workspace root)`),aspects:F.array(F.enum([`all`,`structure`,`dependencies`,`symbols`,`patterns`,`entry-points`,`diagrams`])).default([`all`]).describe(`Which analysis aspects to run`)},annotations:r.annotations},async({scope:e,aspects:r})=>{try{let i=e??`.`;Ac.info(`Running knowledge production`,{rootPath:i,aspects:r});let a=await n.runExtraction(i,r);try{let e=t?.onboardDir??g(i,`.ai`,`context`);o(e,{recursive:!0});let n=`<!-- Generated by produce_knowledge at ${new Date().toISOString()} -->\n\n`;for(let[t,r]of Object.entries(a))r&&typeof r==`string`&&f(g(e,`${t}.md`),n+r,`utf-8`);Ac.info(`Knowledge persisted to .ai/context/`,{files:Object.keys(a).length})}catch(e){Ac.warn(`Failed to persist knowledge to .ai/context/`,{error:A(e)})}return{content:[{type:`text`,text:n.buildSynthesisInstructions(a,r)+`
1233
+ 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=Ks(r);return(e??`html`)===`browser`||Array.isArray(i)&&i.length>0?await kc(n,o,i,t,a):Ac(n,o,i,a)};if(r){wc||=(_n(e,`AI Kit Present App`,bc,{description:`Rich interactive content viewer for AI Kit tools`},async()=>({contents:[{uri:bc,mimeType:gn,text:r}]})),!0),vn(e,`present`,{title:n.title,description:i,annotations:n.annotations,inputSchema:Sc,_meta:{ui:{resourceUri:bc}}},a);return}e.tool(`present`,i,Sc,n.annotations,a)}async function kc(e,t,n,r,i){let a=uc(e,t,{compactTables:!0}),o=lc(e,t,n,i),s=Sn({uri:`ui://aikit/present-browser.html`,content:{type:`rawHtml`,htmlString:o},encoding:`text`,adapters:{mcpApps:{enabled:!0}}}),c,l,u=Array.isArray(n)?n:[],d=``,f;try{Tc&&=(Tc.close(),null),u.length>0&&(c=new Promise(e=>{l=e}));let e=!1;d=await new Promise((t,n)=>{let r=xn((t,n)=>{if(e||(e=!0,f&&clearTimeout(f)),t.method===`POST`&&t.url===`/callback`){let e=``;t.on(`data`,t=>{e+=t.toString()}),t.on(`end`,()=>{n.writeHead(200,{"Content-Type":`application/json`,"Access-Control-Allow-Origin":`*`}),n.end(`{"ok":true}`);try{let t=JSON.parse(e);l?.(t)}catch{}});return}if(t.method===`OPTIONS`){n.writeHead(204,{"Access-Control-Allow-Origin":`*`,"Access-Control-Allow-Methods":`POST`,"Access-Control-Allow-Headers":`Content-Type`}),n.end();return}n.writeHead(200,{"Content-Type":`text/html; charset=utf-8`}),n.end(o)});r.listen(0,`127.0.0.1`,()=>{let i=r.address();if(typeof i==`object`&&i){Tc=r;let n=`http://127.0.0.1:${i.port}`;f=setTimeout(()=>{if(!e)try{yn(process.platform===`win32`?`start "" "${n}"`:process.platform===`darwin`?`open "${n}"`:`xdg-open "${n}"`)}catch{}},8e3),f.unref(),t(n)}else n(Error(`Failed to start present server`))}),setTimeout(()=>{r.close(),Tc===r&&(Tc=null)},300*1e3).unref()})}catch{}let p=d?`${a}\n\n---\n🌐 **Dashboard opened in browser:** ${d}\n\n**IMPORTANT:** You MUST now open this URL using the \`openBrowserPage\` tool - PlayWright MCP. If that tool is unavailable, open the URL in the system browser as a fallback. If neither works, ask the user to open the URL manually.`:a;if(u.length>0&&r?.available&&c)try{let e=await Promise.race([c,new Promise((e,t)=>setTimeout(()=>t(Error(`timeout`)),300*1e3))]);return{content:[{type:`text`,text:`${p}\n\n✅ **Selected:** ${e.actionId} = \`${e.value}\``},s]}}catch{return{content:[{type:`text`,text:`${p}\n\n⚠️ *No selection received (timed out).*`},s]}}return{content:[{type:`text`,text:p},s]}}function Ac(e,t,n,r){let i=Array.isArray(n)?n:[],a=uc(e,t,{compactTables:!0}),o=Sn({uri:`ui://aikit/present-static.html`,content:{type:`rawHtml`,htmlString:lc(e,t,n,r)},encoding:`text`,adapters:{mcpApps:{enabled:!0}}});return{content:[{type:`text`,text:a},o],structuredContent:{title:e,content:Qs(t),actions:i}}}const jc=E(`tools`);function Mc(e,t){let n=new fn({structure:new mn,dependencies:new ln,symbols:new hn,patterns:new pn,entryPoints:new dn,diagrams:new un}),r=L(`produce_knowledge`);e.registerTool(`produce_knowledge`,{title:r.title,description:`Run automated codebase analysis and produce synthesis instructions. Executes Tier 1 deterministic analyzers, then returns structured baselines and instructions for you to synthesize knowledge using remember.`,inputSchema:{scope:F.string().optional().describe(`Root path to analyze (defaults to workspace root)`),aspects:F.array(F.enum([`all`,`structure`,`dependencies`,`symbols`,`patterns`,`entry-points`,`diagrams`])).default([`all`]).describe(`Which analysis aspects to run`)},annotations:r.annotations},async({scope:e,aspects:r})=>{try{let i=e??`.`;jc.info(`Running knowledge production`,{rootPath:i,aspects:r});let a=await n.runExtraction(i,r);try{let e=t?.onboardDir??g(i,`.ai`,`context`);o(e,{recursive:!0});let n=`<!-- Generated by produce_knowledge at ${new Date().toISOString()} -->\n\n`;for(let[t,r]of Object.entries(a))r&&typeof r==`string`&&f(g(e,`${t}.md`),n+r,`utf-8`);jc.info(`Knowledge persisted to .ai/context/`,{files:Object.keys(a).length})}catch(e){jc.warn(`Failed to persist knowledge to .ai/context/`,{error:A(e)})}return{content:[{type:`text`,text:n.buildSynthesisInstructions(a,r)+`
1231
1234
 
1232
1235
  ---
1233
- _Next: Review the baselines above and use \`remember\` to store synthesized knowledge entries._`}]}}catch(e){return Ac.error(`Knowledge production failed`,A(e)),{content:[{type:`text`,text:`Knowledge production failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}const Mc=E(`tools`);function Nc(e,t){let n=L(`read`);e.registerTool(`read`,{title:n.title,description:`Read the full content of a specific curated knowledge entry by its path. Use list first to discover available entries.`,inputSchema:{path:F.string().describe(`Relative path within .ai/curated/ (e.g., "decisions/use-lancedb.md")`)},annotations:n.annotations},async({path:e})=>{try{let n=await t.read(e),r=[`## ${n.title}`,`- **Path**: .ai/curated/${e}`,`- **Category**: ${n.category}`,n.tags.length?`- **Tags**: ${n.tags.join(`, `)}`:null,`- **Version**: ${n.version}`,`- **Created**: ${n.created}`,n.updated===n.created?null:`- **Updated**: ${n.updated}`,``].filter(e=>e!==null).join(`
1234
- `),i=Vo(e,n.title,`[${n.category}]`);return{content:[{type:`text`,text:`${r}\n${n.content}\n\n---\n_Next: Use \`update\` to modify this entry, or \`search\` to find related entries._`},...i?[i]:[]]}}catch(e){return Mc.error(`Read failed`,A(e)),{content:[{type:`text`,text:`Read failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}const X=E(`tools`);function Pc(e,t,n,r,i,a,o){let s=L(`reindex`);e.registerTool(`reindex`,{title:s.title,description:`Trigger re-indexing of the AI Kit index. Can do incremental (only changed files) or full re-index. When smart indexing is active, use force: true to override the automatic trickle indexer.`,inputSchema:{full:F.boolean().default(!1).describe(`If true, force full re-index ignoring file hashes`),force:F.boolean().default(!1).describe(`If true, override smart indexing guard and run reindex anyway`)},annotations:s.annotations},async({full:e,force:s},c)=>{try{if(t.isIndexing)return{content:[{type:`text`,text:`## Reindex Already in Progress
1236
+ _Next: Review the baselines above and use \`remember\` to store synthesized knowledge entries._`}]}}catch(e){return jc.error(`Knowledge production failed`,A(e)),{content:[{type:`text`,text:`Knowledge production failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}const Nc=E(`tools`);function Pc(e,t){let n=L(`read`);e.registerTool(`read`,{title:n.title,description:`Read the full content of a specific curated knowledge entry by its path. Use list first to discover available entries.`,inputSchema:{path:F.string().describe(`Relative path within .ai/curated/ (e.g., "decisions/use-lancedb.md")`)},annotations:n.annotations},async({path:e})=>{try{let n=await t.read(e),r=[`## ${n.title}`,`- **Path**: .ai/curated/${e}`,`- **Category**: ${n.category}`,n.tags.length?`- **Tags**: ${n.tags.join(`, `)}`:null,`- **Version**: ${n.version}`,`- **Created**: ${n.created}`,n.updated===n.created?null:`- **Updated**: ${n.updated}`,``].filter(e=>e!==null).join(`
1237
+ `),i=Vo(e,n.title,`[${n.category}]`);return{content:[{type:`text`,text:`${r}\n${n.content}\n\n---\n_Next: Use \`update\` to modify this entry, or \`search\` to find related entries._`},...i?[i]:[]]}}catch(e){return Nc.error(`Read failed`,A(e)),{content:[{type:`text`,text:`Read failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}const X=E(`tools`);function Fc(e,t,n,r,i,a,o){let s=L(`reindex`);e.registerTool(`reindex`,{title:s.title,description:`Trigger re-indexing of the AI Kit index. Can do incremental (only changed files) or full re-index. When smart indexing is active, use force: true to override the automatic trickle indexer.`,inputSchema:{full:F.boolean().default(!1).describe(`If true, force full re-index ignoring file hashes`),force:F.boolean().default(!1).describe(`If true, override smart indexing guard and run reindex anyway`)},annotations:s.annotations},async({full:e,force:s},c)=>{try{if(t.isIndexing)return{content:[{type:`text`,text:`## Reindex Already in Progress
1235
1238
 
1236
1239
  A reindex operation is currently running. Search and other tools continue to work with existing data. Use \`status({})\` to check when it completes.`}]};if(o===`smart`&&!s)return{content:[{type:`text`,text:`## Smart Indexing Active
1237
1240
 
@@ -1239,36 +1242,36 @@ Smart indexing (trickle mode) is enabled — files are automatically indexed as
1239
1242
 
1240
1243
  **If the index is severely outdated**, use \`reindex({ force: true })\` to override.
1241
1244
 
1242
- Use \`status({})\` to check smart indexing queue status.`}]};let l=na(c).createTask(`Reindex`,1);l.progress(0,`Starting ${e?`full`:`incremental`} reindex`),X.info(`Starting background re-index`,{mode:e?`full`:`incremental`});let u=e=>t=>{t.phase===`chunking`&&t.currentFile&&X.debug(`Re-index progress`,{prefix:e,current:t.filesProcessed+1,total:t.filesTotal,file:t.currentFile})};return(e?t.reindexAll(n,u(`Reindex`)):t.index(n,u(`Index`))).then(async e=>{if(X.info(`Background re-index complete`,{filesProcessed:e.filesProcessed,chunksCreated:e.chunksCreated,durationMs:e.durationMs}),l.complete(`Reindex complete: ${e.filesProcessed} files, ${e.chunksCreated} chunks in ${e.durationMs}ms`),i)try{await i.createFtsIndex(),X.info(`FTS index rebuilt after reindex`)}catch(e){X.warn(`FTS index rebuild failed`,A(e))}try{let e=await r.reindexAll();X.info(`Curated re-index complete`,{indexed:e.indexed})}catch(e){X.warn(`Curated re-index failed`,A(e))}if(a)try{await a.notifyAfterReindex()}catch(e){X.warn(`Post-reindex resource notification failed`,A(e))}}).catch(e=>{l.fail(`Reindex failed: ${e instanceof Error?e.message:String(e)}`),X.error(`Background reindex failed`,A(e))}),{content:[{type:`text`,text:`## Reindex Started (Background)\n\n- **Mode**: ${e?`Full`:`Incremental`}\n- Search and other tools continue to work with existing data during reindex.\n- Completion will be logged. Use \`status({})\` to check index stats afterward.\n\n---\n_Next: Continue working — the reindex runs in the background._`}]}}catch(e){return X.error(`Reindex failed`,A(e)),{content:[{type:`text`,text:`Reindex failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}const Fc=E(`tools`);function Ic(e,t,n,r,i){let a=L(`remember`);e.registerTool(`remember`,{title:a.title,description:`Store a new piece of curated knowledge. Use this to persist decisions, patterns, conventions, or any insight worth remembering across sessions.`,inputSchema:{title:F.string().min(3).max(120).describe(`Short descriptive title for the knowledge entry`),content:F.string().min(10).max(1e5).describe(`The markdown content to store`),category:F.string().regex(/^[a-z][a-z0-9-]*$/).describe(`Category slug (e.g., "decisions", "patterns", "conventions", "api-contracts")`),tags:F.array(F.string()).default([]).describe(`Optional tags for filtering`)},annotations:a.annotations},async({title:e,content:a,category:o,tags:s})=>{try{let c=await t.remember(e,a,o,s),l=``;if(n){let t=n.classify(e,a,s);r&&r.recordClassification(e,t.matchingRules.map(e=>e.ruleId),t.pushRecommended),t.matchingRules.length>0&&(l=`\n\n### Classification Signals\n${t.matchingRules.map(e=>` - **${e.ruleId}** (${e.category}, weight: ${e.pushWeight}) — matched: ${e.matchedPatterns.join(`, `)}`).join(`
1245
+ Use \`status({})\` to check smart indexing queue status.`}]};let l=na(c).createTask(`Reindex`,1);l.progress(0,`Starting ${e?`full`:`incremental`} reindex`),X.info(`Starting background re-index`,{mode:e?`full`:`incremental`});let u=e=>t=>{t.phase===`chunking`&&t.currentFile&&X.debug(`Re-index progress`,{prefix:e,current:t.filesProcessed+1,total:t.filesTotal,file:t.currentFile})};return(e?t.reindexAll(n,u(`Reindex`)):t.index(n,u(`Index`))).then(async e=>{if(X.info(`Background re-index complete`,{filesProcessed:e.filesProcessed,chunksCreated:e.chunksCreated,durationMs:e.durationMs}),l.complete(`Reindex complete: ${e.filesProcessed} files, ${e.chunksCreated} chunks in ${e.durationMs}ms`),i)try{await i.createFtsIndex(),X.info(`FTS index rebuilt after reindex`)}catch(e){X.warn(`FTS index rebuild failed`,A(e))}try{let e=await r.reindexAll();X.info(`Curated re-index complete`,{indexed:e.indexed})}catch(e){X.warn(`Curated re-index failed`,A(e))}if(a)try{await a.notifyAfterReindex()}catch(e){X.warn(`Post-reindex resource notification failed`,A(e))}}).catch(e=>{l.fail(`Reindex failed: ${e instanceof Error?e.message:String(e)}`),X.error(`Background reindex failed`,A(e))}),{content:[{type:`text`,text:`## Reindex Started (Background)\n\n- **Mode**: ${e?`Full`:`Incremental`}\n- Search and other tools continue to work with existing data during reindex.\n- Completion will be logged. Use \`status({})\` to check index stats afterward.\n\n---\n_Next: Continue working — the reindex runs in the background._`}]}}catch(e){return X.error(`Reindex failed`,A(e)),{content:[{type:`text`,text:`Reindex failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}const Ic=E(`tools`);function Lc(e,t,n,r,i){let a=L(`remember`);e.registerTool(`remember`,{title:a.title,description:`Store a new piece of curated knowledge. Use this to persist decisions, patterns, conventions, or any insight worth remembering across sessions.`,inputSchema:{title:F.string().min(3).max(120).describe(`Short descriptive title for the knowledge entry`),content:F.string().min(10).max(1e5).describe(`The markdown content to store`),category:F.string().regex(/^[a-z][a-z0-9-]*$/).describe(`Category slug (e.g., "decisions", "patterns", "conventions", "api-contracts")`),tags:F.array(F.string()).default([]).describe(`Optional tags for filtering`)},annotations:a.annotations},async({title:e,content:a,category:o,tags:s})=>{try{let c=await t.remember(e,a,o,s),l=``;if(n){let t=n.classify(e,a,s);r&&r.recordClassification(e,t.matchingRules.map(e=>e.ruleId),t.pushRecommended),t.matchingRules.length>0&&(l=`\n\n### Classification Signals\n${t.matchingRules.map(e=>` - **${e.ruleId}** (${e.category}, weight: ${e.pushWeight}) — matched: ${e.matchedPatterns.join(`, `)}`).join(`
1243
1246
  `)}\n- **Push recommended**: ${t.pushRecommended?`yes`:`no`} (max weight: ${t.maxPushWeight})`,t.pushRecommended&&(l+=`
1244
1247
 
1245
- > 💡 This entry matches push rules. Consider \`er_push\` to share with Enterprise RAG.`))}i&&i.notifyAfterCuratedWrite(c.path).catch(()=>{});let u=Vo(c.path,e,`[${o}]`);return{content:[{type:`text`,text:`Remembered: **${e}**\n\nStored at \`.ai/curated/${c.path}\` and indexed for semantic search.${l}\n\n---\n_Next: Use \`search\` to verify the entry is findable, or \`list\` to see all curated entries._`},...u?[u]:[]]}}catch(e){return Fc.error(`Remember failed`,A(e)),{content:[{type:`text`,text:`Remember failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}const Lc=E(`tools`);function Rc(e){let t=L(`replay`);e.registerTool(`replay`,{title:t.title,description:`View or clear the audit trail of recent MCP tool and CLI invocations. Shows tool name, duration, status, and input/output summaries.`,inputSchema:{action:F.enum([`list`,`clear`]).default(`list`).describe(`Action: "list" (default) to view entries, "clear" to wipe the log`),last:F.number().optional().describe(`Number of entries to return (default: 20, list only)`),tool:F.string().optional().describe(`Filter by tool name (list only)`),source:F.enum([`mcp`,`cli`]).optional().describe(`Filter by source: "mcp" or "cli" (list only)`),since:F.string().optional().describe(`ISO timestamp — only show entries after this time (list only)`)},annotations:t.annotations},async({action:e,last:t,tool:n,source:r,since:i})=>{try{if(e===`clear`)return kt(),{content:[{type:`text`,text:`Replay log cleared.`}]};let a=At({last:t,tool:n,source:r,since:i});if(a.length===0)return{content:[{type:`text`,text:`No replay entries found. Activity is logged when tools are invoked via MCP or CLI.`}]};let o=a.map(e=>`${e.ts.split(`T`)[1]?.split(`.`)[0]??e.ts} ${e.status===`ok`?`✓`:`✗`} ${e.tool} (${e.durationMs}ms) [${e.source}]\n in: ${e.input}\n out: ${e.output}`);return jt().catch(()=>{}),{content:[{type:`text`,text:`**Replay Log** (${a.length} entries)\n\n${o.join(`
1248
+ > 💡 This entry matches push rules. Consider \`er_push\` to share with Enterprise RAG.`))}i&&i.notifyAfterCuratedWrite(c.path).catch(()=>{});let u=Vo(c.path,e,`[${o}]`);return{content:[{type:`text`,text:`Remembered: **${e}**\n\nStored at \`.ai/curated/${c.path}\` and indexed for semantic search.${l}\n\n---\n_Next: Use \`search\` to verify the entry is findable, or \`list\` to see all curated entries._`},...u?[u]:[]]}}catch(e){return Ic.error(`Remember failed`,A(e)),{content:[{type:`text`,text:`Remember failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}const Rc=E(`tools`);function zc(e){let t=L(`replay`);e.registerTool(`replay`,{title:t.title,description:`View or clear the audit trail of recent MCP tool and CLI invocations. Shows tool name, duration, status, and input/output summaries.`,inputSchema:{action:F.enum([`list`,`clear`]).default(`list`).describe(`Action: "list" (default) to view entries, "clear" to wipe the log`),last:F.number().optional().describe(`Number of entries to return (default: 20, list only)`),tool:F.string().optional().describe(`Filter by tool name (list only)`),source:F.enum([`mcp`,`cli`]).optional().describe(`Filter by source: "mcp" or "cli" (list only)`),since:F.string().optional().describe(`ISO timestamp — only show entries after this time (list only)`)},annotations:t.annotations},async({action:e,last:t,tool:n,source:r,since:i})=>{try{if(e===`clear`)return kt(),{content:[{type:`text`,text:`Replay log cleared.`}]};let a=At({last:t,tool:n,source:r,since:i});if(a.length===0)return{content:[{type:`text`,text:`No replay entries found. Activity is logged when tools are invoked via MCP or CLI.`}]};let o=a.map(e=>`${e.ts.split(`T`)[1]?.split(`.`)[0]??e.ts} ${e.status===`ok`?`✓`:`✗`} ${e.tool} (${e.durationMs}ms) [${e.source}]\n in: ${e.input}\n out: ${e.output}`);return jt().catch(()=>{}),{content:[{type:`text`,text:`**Replay Log** (${a.length} entries)\n\n${o.join(`
1246
1249
 
1247
- `)}`}]}}catch(e){return Lc.error(`Replay failed`,A(e)),{content:[{type:`text`,text:`Replay failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}const zc=E(`tools`);function Bc(e){let t=L(`restore`);e.registerTool(`restore`,{title:t.title,description:`List and restore file snapshots taken before destructive operations (codemod, rename, forget). Use action=list to see available restore points, action=restore with an id to undo.`,inputSchema:{action:F.enum([`list`,`restore`]).describe(`list: show restore points, restore: apply a restore point`),id:F.string().optional().describe(`Restore point ID (required for action=restore)`),limit:F.number().min(1).max(50).default(10).describe(`Max restore points to list`)},annotations:t.annotations},async({action:e,id:t,limit:n})=>{try{if(e===`list`){let e=ot().slice(0,n);return e.length===0?{content:[{type:`text`,text:`No restore points found.`}]}:{content:[{type:`text`,text:`## Restore Points\n\n${e.map(e=>`- **${e.id}** (${e.timestamp}) — ${e.operation}: ${e.description} (${e.files.length} files)`).join(`
1250
+ `)}`}]}}catch(e){return Rc.error(`Replay failed`,A(e)),{content:[{type:`text`,text:`Replay failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}const Bc=E(`tools`);function Vc(e){let t=L(`restore`);e.registerTool(`restore`,{title:t.title,description:`List and restore file snapshots taken before destructive operations (codemod, rename, forget). Use action=list to see available restore points, action=restore with an id to undo.`,inputSchema:{action:F.enum([`list`,`restore`]).describe(`list: show restore points, restore: apply a restore point`),id:F.string().optional().describe(`Restore point ID (required for action=restore)`),limit:F.number().min(1).max(50).default(10).describe(`Max restore points to list`)},annotations:t.annotations},async({action:e,id:t,limit:n})=>{try{if(e===`list`){let e=ot().slice(0,n);return e.length===0?{content:[{type:`text`,text:`No restore points found.`}]}:{content:[{type:`text`,text:`## Restore Points\n\n${e.map(e=>`- **${e.id}** (${e.timestamp}) — ${e.operation}: ${e.description} (${e.files.length} files)`).join(`
1248
1251
  `)}`}]}}if(!t)throw Error(`id is required for restore action`);let r=await Mt(t);return{content:[{type:`text`,text:`Restored ${r.length} files:\n${r.map(e=>`- \`${e}\``).join(`
1249
- `)}`}]}}catch(e){return zc.error(`Restore failed`,A(e)),{content:[{type:`text`,text:`Restore failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}const Vc=/<\/?curated-context>/gi;function Hc(e){return e.replace(Vc,``)}function Uc(e){return`<curated-context>\n${Hc(e)}\n</curated-context>`}const Wc=E(`tools`);function Gc(e){let t=[],n=p(process.cwd());n&&t.push(`[project: ${n}]`);let r=Vt(`__context_boost`);return r&&t.push(`[focus: ${r.value}]`),t.length===0?e:`${t.join(` `)} ${e}`}async function Kc(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:de(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 Wc.warn(`ER fallback failed`,A(e)),{results:n,triggered:!0,cacheHit:a}}}function qc(e,t,n=60){let r=new Map;for(let t=0;t<e.length;t++){let i=e[t];r.set(i.record.id,{record:i.record,score:1/(n+t+1)})}for(let e=0;e<t.length;e++){let i=t[e],a=r.get(i.record.id);a?a.score+=1/(n+e+1):r.set(i.record.id,{record:i.record,score:1/(n+e+1)})}return[...r.values()].sort((e,t)=>t.score-e.score).map(({record:e,score:t})=>({record:e,score:t}))}function Jc(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 Yc(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&&!Xc.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 Xc=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 Zc(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 ne(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 Qc(e,t,n,r,i,a,o){let s=L(`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:Si,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(b).optional().describe(`Filter by content type`),source_type:F.enum(C).optional().describe(`Coarse filter: "source" (code only), "documentation" (md, curated), "test", "config". Overrides content_type if both set.`),origin:F.enum(S).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=Gc(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 Kc(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,o]=await Promise.all([n.search(r,{...y,limit:s*2}),n.ftsSearch(e,{...y,limit:s*2}).catch(()=>[])]);b=qc(a,o).slice(0,s);let c=await Kc(i,a[0]?.score??0,b,e,s);b=c.results,x=c.triggered,S=c.cacheHit}a&&a.recordSearch(e,x,S),b.length>1&&(b=Jc(b,e));let E=``;if(v&&v.length>0){let n=Ua(v,T(process.cwd()));if(n.length>0){let{stores:r,closeAll:i}=await Wa(n);try{let i;i=c===`keyword`?await Ka(r,e,{...y,limit:s}):await Ga(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),E=` + ${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===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(`
1250
- `)[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`,Wc.info(`Smart search fallback succeeded`,{originalQuery:e,altQuery:r,resultCount:a.length}))}}catch(e){Wc.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 D,O;if(h>0&&!r&&(O="> **Note:** `graph_hops` was set but no graph store is available. Graph augmentation skipped."),h>0&&r)try{let e=await Ye(r,b.map(e=>({recordId:e.record.id,score:e.score,sourcePath:e.record.sourcePath})),{hops:h,maxPerHit:5});D=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(`
1252
+ `)}`}]}}catch(e){return Bc.error(`Restore failed`,A(e)),{content:[{type:`text`,text:`Restore failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}const Hc=/<\/?curated-context>/gi;function Uc(e){return e.replace(Hc,``)}function Wc(e){return`<curated-context>\n${Uc(e)}\n</curated-context>`}const Gc=E(`tools`);function Kc(e){let t=[],n=p(process.cwd());n&&t.push(`[project: ${n}]`);let r=Vt(`__context_boost`);return r&&t.push(`[focus: ${r.value}]`),t.length===0?e:`${t.join(` `)} ${e}`}async function qc(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:de(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 Gc.warn(`ER fallback failed`,A(e)),{results:n,triggered:!0,cacheHit:a}}}function Jc(e,t,n=60){let r=new Map;for(let t=0;t<e.length;t++){let i=e[t];r.set(i.record.id,{record:i.record,score:1/(n+t+1)})}for(let e=0;e<t.length;e++){let i=t[e],a=r.get(i.record.id);a?a.score+=1/(n+e+1):r.set(i.record.id,{record:i.record,score:1/(n+e+1)})}return[...r.values()].sort((e,t)=>t.score-e.score).map(({record:e,score:t})=>({record:e,score:t}))}function Yc(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 Xc(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&&!Zc.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 Zc=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 Qc(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 ne(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 $c(e,t,n,r,i,a,o){let s=L(`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:Si,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(b).optional().describe(`Filter by content type`),source_type:F.enum(C).optional().describe(`Coarse filter: "source" (code only), "documentation" (md, curated), "test", "config". Overrides content_type if both set.`),origin:F.enum(S).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=Kc(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 qc(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,o]=await Promise.all([n.search(r,{...y,limit:s*2}),n.ftsSearch(e,{...y,limit:s*2}).catch(()=>[])]);b=Jc(a,o).slice(0,s);let c=await qc(i,a[0]?.score??0,b,e,s);b=c.results,x=c.triggered,S=c.cacheHit}a&&a.recordSearch(e,x,S),b.length>1&&(b=Yc(b,e));let E=``;if(v&&v.length>0){let n=Ua(v,T(process.cwd()));if(n.length>0){let{stores:r,closeAll:i}=await Wa(n);try{let i;i=c===`keyword`?await Ka(r,e,{...y,limit:s}):await Ga(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),E=` + ${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===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(`
1253
+ `)[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`,Gc.info(`Smart search fallback succeeded`,{originalQuery:e,altQuery:r,resultCount:a.length}))}}catch(e){Gc.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 D,O;if(h>0&&!r&&(O="> **Note:** `graph_hops` was set but no graph store is available. Graph augmentation skipped."),h>0&&r)try{let e=await Ye(r,b.map(e=>({recordId:e.record.id,score:e.score,sourcePath:e.record.sourcePath})),{hops:h,maxPerHit:5});D=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(`
1251
1254
  `),n=t.graphContext.edges.slice(0,5).map(e=>` - ${e.fromId} —[${e.type}]→ ${e.toId}`).join(`
1252
1255
  `),r=[`- **Graph Context** (${h} hop${h>1?`s`:``}):`];e&&r.push(` Entities:\n${e}`),n&&r.push(` Relationships:\n${n}`),D.set(t.recordId,r.join(`
1253
- `))}}catch(e){Wc.warn(`Graph augmentation failed`,A(e)),O=`> **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=be(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,D?.get(n.id)??null].filter(Boolean).join(`
1254
- `)}\n\n${n.origin===`curated`?Uc(n.content):n.content}`}).join(`
1256
+ `))}}catch(e){Gc.warn(`Graph augmentation failed`,A(e)),O=`> **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=be(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,D?.get(n.id)??null].filter(Boolean).join(`
1257
+ `)}\n\n${n.origin===`curated`?Wc(n.content):n.content}`}).join(`
1255
1258
 
1256
1259
  ---
1257
1260
 
1258
- `),j=(c===`hybrid`?`hybrid (vector + keyword RRF)`:c===`keyword`?`keyword (FTS)`:`semantic (vector)`)+E,M=Yc(b,e),te=M.length>0?`\n_Distinctive terms: ${M.map(e=>`\`${e}\``).join(`, `)}_`:``,ne=await Zc(n,b),N=[];if(b.length===0)N.push("`reindex` — no results found, index may be stale"),N.push("`find` — try federated search with glob/regex");else{let e=b[0]?.record.sourcePath;e&&N.push(`\`lookup\` — see all chunks from \`${e}\``),N.push("`symbol` — resolve a specific symbol from the results"),N.push("`compact` — compress a result file for focused reading")}let re=[O?`${O}\n\n`:``,ne?`${ne}\n\n`:``,ee,`\n\n---\n_Search mode: ${j} | ${b.length} results_${te}`,`\n_Next: ${N.join(` | `)}_`],ie=C+re.join(``);g&&(ie=Xt(ie,g));let ae=new Set,oe=[];for(let e of b){if(e.record.origin!==`curated`||e.record.sourcePath.startsWith(`[`))continue;let t=Uo(e.record.sourcePath);if(!t)continue;let n=Vo(t,e.record.headingPath??t);n&&!ae.has(n.uri)&&(ae.add(n.uri),oe.push(n))}return{content:[{type:`text`,text:ie},...oe],structuredContent:{results:b.map(e=>({sourcePath:e.record.sourcePath,contentType:e.record.contentType,score:e.score,...e.record.headingPath?{headingPath:e.record.headingPath}:{},...e.record.startLine?{startLine:e.record.startLine}:{},...e.record.endLine?{endLine:e.record.endLine}:{},...e.record.origin===`indexed`?{}:{origin:e.record.origin},...e.record.category?{category:e.record.category}:{},...e.record.tags?.length?{tags:e.record.tags}:{}})),totalResults:b.length,searchMode:c,query:e}}}catch(e){return Wc.error(`Search failed`,A(e)),{content:[{type:`text`,text:`Search failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}const $c=E(`tools`);function el(e,t){let n=L(`session_digest`);e.registerTool(`session_digest`,{title:n.title,description:`Compress the current session's tool trajectory into a focused digest. Aggregates replay log, stash state, and checkpoints. Supports deterministic and LLM-assisted (sampling) modes with configurable token budget.`,inputSchema:{scope:F.enum([`tools`,`stash`,`all`]).default(`all`).describe(`What to include: tools (replay only), stash (stash + checkpoints only), or all`),since:F.string().optional().describe(`ISO timestamp — only include activity after this time`),last:F.number().min(1).max(500).optional().describe(`Max replay entries to consider (default: 50)`),focus:F.string().optional().describe(`Focus query — prioritize entries matching this topic`),mode:F.enum([`deterministic`,`sampling`]).default(`deterministic`).describe(`Summary mode: deterministic (fast, template-based) or sampling (LLM-assisted, richer)`),token_budget:F.number().min(100).max(8e3).default(2e3).describe(`Target token budget for the digest output`),persist:F.boolean().default(!0).describe(`Auto-save digest to stash for crash recovery`)},annotations:n.annotations},async({scope:e,since:n,last:r,focus:i,mode:a,token_budget:o,persist:s})=>{try{let c={scope:e,since:n,last:r,focus:i,mode:a,tokenBudget:o,persist:s};return{content:[{type:`text`,text:(a===`sampling`&&t?.available?await Lt(c,async(e,n,r)=>(await t.createMessage({prompt:e,systemPrompt:n,maxTokens:r})).text):It(c)).digest}]}}catch(e){return $c.error(`Session digest failed`,A(e)),{content:[{type:`text`,text:`Session digest failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}const tl=E(`tools`);function nl(e,t,n,r=15e3){let i,a=new Promise(e=>{i=setTimeout(()=>{tl.warn(`Status sub-operation "${n}" timed out after ${r}ms`),e({value:t,timedOut:!0})},r)});return Promise.race([e.then(e=>(clearTimeout(i),{value:e,timedOut:!1}),e=>(clearTimeout(i),tl.warn(`Status sub-operation "${n}" failed: ${e instanceof Error?e.message:String(e)}`),{value:t,timedOut:!1})),a])}const rl=5*6e4;let il=null,al=null;function ol(e,t,n,r){let i=Math.min(e/2e4,1),a=Math.min((t+n)/5e4,1),o=Math.min(r/200,1);return Math.round(i*40+a*35+o*25)}function sl(){let e=Date.now();if(il&&e-il.ts<rl)return il.value;try{let t=_(N(),`.copilot`,`.aikit-scaffold.json`);if(!a(t))return il={value:null,ts:e},null;let n=JSON.parse(s(t,`utf-8`)).version??null;return il={value:n,ts:e},n}catch{return il={value:null,ts:e},null}}function cl(){let e=Date.now();if(al&&e-al.ts<rl)return al.value;try{let t=_(process.cwd(),`.github`,`.aikit-scaffold.json`);if(!a(t))return al={value:null,ts:e},null;let n=JSON.parse(s(t,`utf-8`)).version??null;return al={value:n,ts:e},n}catch{return al={value:null,ts:e},null}}function ll(e){let t=L(`status`);e.registerTool(`status`,{title:t.title,description:`Get the current status and statistics of the AI Kit index.`,outputSchema:fi,annotations:t.annotations},async()=>{let e=r(),t=sl(),a=cl(),o=t!=null&&t!==e,s=a!=null&&a!==e,c=[`## AI Kit Status`,``,`⏳ **AI Kit is initializing** — index stats will be available shortly.`,``,`### Runtime`,`- **Tree-sitter (WASM)**: ${re.get()?`✅ Available (AST analysis)`:`⚠ Unavailable (regex fallback)`}`,``,`### Version`,`- **Server**: ${e}`,`- **Scaffold (user)**: ${t??`not installed`}`,`- **Scaffold (workspace)**: ${a??`not installed`}`];if(o||s){let r=i(),l=[];o&&l.push(`user scaffold v${t}`),s&&l.push(`workspace scaffold v${a}`);let u=l.join(`, `);r.state===`success`?c.push(``,`### ✅ Upgrade Applied`,`- Server v${e} — ${u} auto-upgraded successfully.`,`- _Restart the MCP server to use the updated version._`):r.state===`pending`?c.push(``,`### ⏳ Upgrade In Progress`,`- Server v${e} ≠ ${u}`,`- Auto-upgrade is running in the background…`):r.state===`failed`?(n(),c.push(``,`### ⬆ Upgrade Available (auto-upgrade failed, retrying)`,`- Server v${e} ≠ ${u}`,`- Error: ${r.error??`unknown`}`)):(n(),c.push(``,`### ⬆ Upgrade Available`,`- Server v${e} ≠ ${u}`,`- Auto-upgrade triggered — check again shortly.`))}let l={totalRecords:0,totalFiles:0,lastIndexedAt:null,onboarded:!1,onboardDir:``,contentTypes:{},wasmAvailable:!!re.get(),graphStats:null,curatedCount:0,serverVersion:e,scaffoldVersion:t??null,workspaceScaffoldVersion:a??null,upgradeAvailable:o||s,contextPressure:0};return{content:[{type:`text`,text:c.join(`
1259
- `)}],structuredContent:l}})}function ul(e,t,o,s,c,l,u,f){let p=L(`status`);e.registerTool(`status`,{title:p.title,description:`Get the current status and statistics of the AI Kit index.`,outputSchema:fi,annotations:p.annotations},async()=>{let e=[];try{let[p,m]=await Promise.all([nl(t.getStats(),{totalRecords:0,totalFiles:0,lastIndexedAt:null,contentTypeBreakdown:{}},`store.getStats`),nl(t.listSourcePaths(),[],`store.listSourcePaths`)]),h=p.value;p.timedOut&&e.push(`⚠ Index stats timed out — values may be incomplete`);let g=m.value;m.timedOut&&e.push(`⚠ File listing timed out`);let v=null,b=0,x=[`## AI Kit Status`,``,`- **Total Records**: ${h.totalRecords}`,`- **Total Files**: ${h.totalFiles}`,`- **Last Indexed**: ${h.lastIndexedAt??`Never`}`,``,`### Content Types`,...Object.entries(h.contentTypeBreakdown).map(([e,t])=>`- ${e}: ${t}`),``,`### Indexed Files`,...g.slice(0,50).map(e=>`- ${e}`),g.length>50?`\n... and ${g.length-50} more files`:``];if(o)try{let t=await nl(o.getStats(),{nodeCount:0,edgeCount:0,nodeTypes:{},edgeTypes:{}},`graphStore.getStats`);if(t.timedOut)e.push(`⚠ Graph stats timed out`),x.push(``,`### Knowledge Graph`,`- Graph stats timed out`);else{let e=t.value;v={nodes:e.nodeCount,edges:e.edgeCount},x.push(``,`### Knowledge Graph`,`- **Nodes**: ${e.nodeCount}`,`- **Edges**: ${e.edgeCount}`,...Object.entries(e.nodeTypes).map(([e,t])=>` - ${e}: ${t}`));try{let e=await nl(o.validate(),{valid:!0,danglingEdges:[],orphanNodes:[],stats:{nodeCount:0,edgeCount:0,nodeTypes:{},edgeTypes:{}}},`graphStore.validate`);if(!e.timedOut){let t=e.value;t.valid||x.push(`- **⚠ Integrity Issues**: ${t.danglingEdges.length} dangling edges`),t.orphanNodes.length>0&&x.push(`- **Orphan nodes**: ${t.orphanNodes.length}`)}}catch{}}}catch{x.push(``,`### Knowledge Graph`,`- Graph store unavailable`)}let S=l?.onboardDir??_(process.cwd(),y.aiContext),C=a(S),w=c?.onboardComplete||C;if(x.push(``,`### Onboard Status`,w?`- ✅ Complete${c?.onboardTimestamp?` (last: ${c.onboardTimestamp})`:``}`:'- ❌ Not run — call `onboard({ path: "." })` to analyze the codebase',`- **Onboard Directory**: \`${S}\``),s)try{let t=await nl(s.list(),[],`curated.list`);if(t.timedOut)e.push(`⚠ Curated knowledge listing timed out`),x.push(``,`### Curated Knowledge`,`- Listing timed out`);else{let e=t.value;b=e.length,x.push(``,`### Curated Knowledge`,e.length>0?`- ${e.length} entries`:"- Empty — use `remember()` to persist decisions")}}catch{x.push(``,`### Curated Knowledge`,`- Unable to read curated entries`)}let T=ol(h.totalRecords,v?.nodes??0,v?.edges??0,b);x.push(``),x.push(`## 📊 Context Pressure: ${T}/100`),T>=80?x.push(`⚠️ High pressure — consider pruning stale entries or compacting context.`):T>=50?x.push(`ℹ️ Moderate pressure — knowledge base is well-populated.`):x.push(`✅ Low pressure — plenty of headroom for more content.`);let E=0;if(h.lastIndexedAt){E=new Date(h.lastIndexedAt).getTime();let e=(Date.now()-E)/(1e3*60*60);x.push(``,`### Index Freshness`,e>24?u===`smart`?`- ⚠ Last indexed ${Math.floor(e)}h ago — smart indexing will refresh automatically`:`- ⚠ Last indexed ${Math.floor(e)}h ago — may be stale. Run \`reindex({})\``:`- ✅ Last indexed ${e<1?`less than 1h`:`${Math.floor(e)}h`} ago`)}if(u===`smart`)if(x.push(``,`### Smart Indexing`),f){let e=f();e?x.push(`- **Mode**: Smart (trickle)`,`- **Status**: ${e.running?`✅ Running`:`⏸ Stopped`}`,`- **Queue**: ${e.queueSize} files pending`,`- **Changed files**: ${e.changedFilesSize} detected`,`- **Interval**: ${Math.round(e.intervalMs/1e3)}s per batch of ${e.batchSize}`):x.push(`- **Mode**: Smart (trickle)`,`- **Status**: scheduler state unavailable (init may have failed)`)}else x.push(`- **Mode**: Smart (trickle) — scheduler state unavailable`);{try{let e=_(process.cwd(),y.data,`stash`);if(a(e)){let t=d(e).mtimeMs;t>E&&(E=t)}}catch{}let e=[];if(s)try{let t=b>0?await s.list():[];for(let e of t){let t=new Date(e.updated||e.created).getTime();t>E&&(E=t)}e.push(...t.sort((e,t)=>new Date(t.updated).getTime()-new Date(e.updated).getTime()).slice(0,5))}catch{}let t=E>0?Date.now()-E:0;if(t>=144e5){let n=Math.floor(t/36e5);if(x.push(``,`### 🌅 Session Briefing`,`_${n}+ hours since last activity — here's what to pick up:_`,``),e.length>0){x.push(`**Recent decisions/notes:**`);for(let t of e)x.push(`- **${t.title}** (${t.category??`note`}) — ${(t.contentPreview??``).slice(0,80)}…`)}x.push(``,`**Suggested next steps:**`,'- `search({ query: "SESSION CHECKPOINT", origin: "curated" })` — find your last checkpoint',"- `restore({})` — resume from a saved checkpoint","- `list()` — browse all stored knowledge")}}x.push(``,`### Runtime`,`- **Tree-sitter (WASM)**: ${re.get()?`✅ Available (AST analysis)`:`⚠ Unavailable (regex fallback)`}`);let D=sl(),O=cl(),k=r(),ee=D!=null&&D!==k,A=O!=null&&O!==k;if(ee||A){let e=i(),t=[];ee&&t.push(`user scaffold v${D}`),A&&t.push(`workspace scaffold v${O}`);let r=t.join(`, `);e.state===`success`?x.push(``,`### ✅ Upgrade Applied`,`- Server v${k} — ${r} auto-upgraded successfully.`,`- _Restart the MCP server to use the updated version._`):e.state===`pending`?x.push(``,`### ⏳ Upgrade In Progress`,`- Server v${k} ≠ ${r}`,`- Auto-upgrade is running in the background…`):e.state===`failed`?(n(),x.push(``,`### ⬆ Upgrade Available (auto-upgrade failed, retrying)`,`- Server v${k} ≠ ${r}`,`- Error: ${e.error??`unknown`}`)):(n(),x.push(``,`### ⬆ Upgrade Available`,`- Server v${k} ≠ ${r}`,`- Auto-upgrade triggered — check again shortly.`))}e.length>0&&x.push(``,`### ⚠ Warnings`,...e.map(e=>`- ${e}`));let j=Br();if(j.length>0){let e=j.sort((e,t)=>t.callCount-e.callCount);x.push(``,`### Tool Usage This Session`,``),x.push(`| Tool | Calls | Tokens In | Tokens Out | Errors | Avg Latency |`),x.push(`|------|-------|-----------|------------|--------|-------------|`);for(let t of e.slice(0,15)){let e=Math.round(t.totalInputChars/4),n=Math.round(t.totalOutputChars/4),r=Math.round(t.totalDurationMs/t.callCount);x.push(`| ${t.tool} | ${t.callCount} | ${e.toLocaleString()} | ${n.toLocaleString()} | ${t.errorCount} | ${r}ms |`)}}let M=Nr();if(M.bufferSize>=10){let e=M.state===`healthy`?`🟢`:M.state===`degraded`?`🔴`:`🟡`;x.push(``,`### Auto-GC: ${e} ${M.state}`),x.push(`- p95 latency: ${M.p95}ms | buffer: ${M.bufferSize} samples`),M.gcCount>0&&x.push(`- GC cycles triggered: ${M.gcCount}`)}let te=x.join(`
1260
- `),ne={totalRecords:h.totalRecords,totalFiles:h.totalFiles,lastIndexedAt:h.lastIndexedAt??null,onboarded:w,onboardDir:S,contentTypes:h.contentTypeBreakdown,wasmAvailable:!!re.get(),graphStats:v,curatedCount:b,serverVersion:k,scaffoldVersion:D??null,workspaceScaffoldVersion:O??null,upgradeAvailable:ee||A,contextPressure:T};return{content:[{type:`text`,text:te+(u===`smart`?"\n\n---\n_Next: Use `search` to query indexed content or `graph({action:'find_nodes', name_pattern:'<top-level-module>'})` → then `graph({action:'neighbors', node_id})` for relationships. Smart indexing handles updates automatically._":"\n\n---\n_Next: Use `search` to query indexed content, `graph({action:'find_nodes', name_pattern:'<top-level-module>'})` → then `graph({action:'neighbors', node_id})` for relationships, or `reindex` to refresh the index._")}],structuredContent:ne}}catch(e){return tl.error(`Status failed`,A(e)),{content:[{type:`text`,text:`Status check failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}const dl=E(`tools`);function fl(e,t,n){let r=L(`update`);e.registerTool(`update`,{title:r.title,description:`Update an existing curated knowledge entry. Increments version and records the reason in the changelog.`,inputSchema:{path:F.string().describe(`Relative path within .ai/curated/ (e.g., "decisions/use-lancedb.md")`),content:F.string().min(10).max(1e5).describe(`New markdown content to replace existing content`),reason:F.string().min(3).max(1e3).describe(`Why this update is being made (recorded in changelog)`)},annotations:r.annotations},async({path:e,content:r,reason:i})=>{try{let a=await t.update(e,r,i);return n&&n.notifyAfterCuratedWrite(e).catch(()=>{}),{content:[{type:`text`,text:`Updated: \`.ai/curated/${a.path}\` → version ${a.version}\n\nReason: ${i}\n\n---\n_Next: Use \`read\` to verify the updated content, or \`search\` to test searchability._`}]}}catch(e){return dl.error(`Update failed`,A(e)),{content:[{type:`text`,text:`Update failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}const Z=E(`tools`);function pl(e){let t=L(`web_search`);e.registerTool(`web_search`,{title:t.title,description:`PREFERRED web search — search the web via DuckDuckGo (no API key). Pass one query or multiple for parallel searching. Returns structured results with title, URL, and snippet.`,inputSchema:{queries:F.array(F.string().max(2e3)).min(1).max(5).describe('Search queries (1–5). Single: `["react hooks"]`. Multiple searched in parallel.'),limit:F.number().min(1).max(20).default(5).describe(`Max results per query`),site:F.string().optional().describe(`Restrict to domain (e.g., "docs.aws.amazon.com")`)},annotations:t.annotations},async({queries:e,limit:t,site:n})=>{let r=e,i=async e=>{let r=await tn({query:e,limit:t,site:n}),i=[`## Search: ${r.query}`,``];if(r.results.length===0)i.push(`No results found.`);else for(let e of r.results)i.push(`### [${e.title}](${e.url})`,e.snippet,``);return i.join(`
1261
+ `),j=(c===`hybrid`?`hybrid (vector + keyword RRF)`:c===`keyword`?`keyword (FTS)`:`semantic (vector)`)+E,M=Xc(b,e),te=M.length>0?`\n_Distinctive terms: ${M.map(e=>`\`${e}\``).join(`, `)}_`:``,ne=await Qc(n,b),N=[];if(b.length===0)N.push("`reindex` — no results found, index may be stale"),N.push("`find` — try federated search with glob/regex");else{let e=b[0]?.record.sourcePath;e&&N.push(`\`lookup\` — see all chunks from \`${e}\``),N.push("`symbol` — resolve a specific symbol from the results"),N.push("`compact` — compress a result file for focused reading")}let re=[O?`${O}\n\n`:``,ne?`${ne}\n\n`:``,ee,`\n\n---\n_Search mode: ${j} | ${b.length} results_${te}`,`\n_Next: ${N.join(` | `)}_`],ie=C+re.join(``);g&&(ie=Xt(ie,g));let ae=new Set,oe=[];for(let e of b){if(e.record.origin!==`curated`||e.record.sourcePath.startsWith(`[`))continue;let t=Uo(e.record.sourcePath);if(!t)continue;let n=Vo(t,e.record.headingPath??t);n&&!ae.has(n.uri)&&(ae.add(n.uri),oe.push(n))}return{content:[{type:`text`,text:ie},...oe],structuredContent:{results:b.map(e=>({sourcePath:e.record.sourcePath,contentType:e.record.contentType,score:e.score,...e.record.headingPath?{headingPath:e.record.headingPath}:{},...e.record.startLine?{startLine:e.record.startLine}:{},...e.record.endLine?{endLine:e.record.endLine}:{},...e.record.origin===`indexed`?{}:{origin:e.record.origin},...e.record.category?{category:e.record.category}:{},...e.record.tags?.length?{tags:e.record.tags}:{}})),totalResults:b.length,searchMode:c,query:e}}}catch(e){return Gc.error(`Search failed`,A(e)),{content:[{type:`text`,text:`Search failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}const el=E(`tools`);function tl(e,t){let n=L(`session_digest`);e.registerTool(`session_digest`,{title:n.title,description:`Compress the current session's tool trajectory into a focused digest. Aggregates replay log, stash state, and checkpoints. Supports deterministic and LLM-assisted (sampling) modes with configurable token budget.`,inputSchema:{scope:F.enum([`tools`,`stash`,`all`]).default(`all`).describe(`What to include: tools (replay only), stash (stash + checkpoints only), or all`),since:F.string().optional().describe(`ISO timestamp — only include activity after this time`),last:F.number().min(1).max(500).optional().describe(`Max replay entries to consider (default: 50)`),focus:F.string().optional().describe(`Focus query — prioritize entries matching this topic`),mode:F.enum([`deterministic`,`sampling`]).default(`deterministic`).describe(`Summary mode: deterministic (fast, template-based) or sampling (LLM-assisted, richer)`),token_budget:F.number().min(100).max(8e3).default(2e3).describe(`Target token budget for the digest output`),persist:F.boolean().default(!0).describe(`Auto-save digest to stash for crash recovery`)},annotations:n.annotations},async({scope:e,since:n,last:r,focus:i,mode:a,token_budget:o,persist:s})=>{try{let c={scope:e,since:n,last:r,focus:i,mode:a,tokenBudget:o,persist:s};return{content:[{type:`text`,text:(a===`sampling`&&t?.available?await Lt(c,async(e,n,r)=>(await t.createMessage({prompt:e,systemPrompt:n,maxTokens:r})).text):It(c)).digest}]}}catch(e){return el.error(`Session digest failed`,A(e)),{content:[{type:`text`,text:`Session digest failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}const nl=E(`tools`);function rl(e,t,n,r=15e3){let i,a=new Promise(e=>{i=setTimeout(()=>{nl.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),nl.warn(`Status sub-operation "${n}" failed: ${e instanceof Error?e.message:String(e)}`),{value:t,timedOut:!1})),a])}const il=5*6e4;let al=null,ol=null;function sl(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 cl(){let e=Date.now();if(al&&e-al.ts<il)return al.value;try{let t=_(N(),`.copilot`,`.aikit-scaffold.json`);if(!a(t))return al={value:null,ts:e},null;let n=JSON.parse(s(t,`utf-8`)).version??null;return al={value:n,ts:e},n}catch{return al={value:null,ts:e},null}}function ll(){let e=Date.now();if(ol&&e-ol.ts<il)return ol.value;try{let t=_(process.cwd(),`.github`,`.aikit-scaffold.json`);if(!a(t))return ol={value:null,ts:e},null;let n=JSON.parse(s(t,`utf-8`)).version??null;return ol={value:n,ts:e},n}catch{return ol={value:null,ts:e},null}}function ul(e){let t=L(`status`);e.registerTool(`status`,{title:t.title,description:`Get the current status and statistics of the AI Kit index.`,outputSchema:fi,annotations:t.annotations},async()=>{let e=r(),t=cl(),a=ll(),o=t!=null&&t!==e,s=a!=null&&a!==e,c=[`## AI Kit Status`,``,`⏳ **AI Kit is initializing** — index stats will be available shortly.`,``,`### Runtime`,`- **Tree-sitter (WASM)**: ${re.get()?`✅ Available (AST analysis)`:`⚠ Unavailable (regex fallback)`}`,``,`### Version`,`- **Server**: ${e}`,`- **Scaffold (user)**: ${t??`not installed`}`,`- **Scaffold (workspace)**: ${a??`not installed`}`];if(o||s){let r=i(),l=[];o&&l.push(`user scaffold v${t}`),s&&l.push(`workspace scaffold v${a}`);let u=l.join(`, `);r.state===`success`?c.push(``,`### ✅ Upgrade Applied`,`- Server v${e} — ${u} auto-upgraded successfully.`,`- _Restart the MCP server to use the updated version._`):r.state===`pending`?c.push(``,`### ⏳ Upgrade In Progress`,`- Server v${e} ≠ ${u}`,`- Auto-upgrade is running in the background…`):r.state===`failed`?(n(),c.push(``,`### ⬆ Upgrade Available (auto-upgrade failed, retrying)`,`- Server v${e} ≠ ${u}`,`- Error: ${r.error??`unknown`}`)):(n(),c.push(``,`### ⬆ Upgrade Available`,`- Server v${e} ≠ ${u}`,`- Auto-upgrade triggered — check again shortly.`))}let l={totalRecords:0,totalFiles:0,lastIndexedAt:null,onboarded:!1,onboardDir:``,contentTypes:{},wasmAvailable:!!re.get(),graphStats:null,curatedCount:0,serverVersion:e,scaffoldVersion:t??null,workspaceScaffoldVersion:a??null,upgradeAvailable:o||s,contextPressure:0};return{content:[{type:`text`,text:c.join(`
1262
+ `)}],structuredContent:l}})}function dl(e,t,o,s,c,l,u,f){let p=L(`status`);e.registerTool(`status`,{title:p.title,description:`Get the current status and statistics of the AI Kit index.`,outputSchema:fi,annotations:p.annotations},async()=>{let e=[];try{let[p,m]=await Promise.all([rl(t.getStats(),{totalRecords:0,totalFiles:0,lastIndexedAt:null,contentTypeBreakdown:{}},`store.getStats`),rl(t.listSourcePaths(),[],`store.listSourcePaths`)]),h=p.value;p.timedOut&&e.push(`⚠ Index stats timed out — values may be incomplete`);let g=m.value;m.timedOut&&e.push(`⚠ File listing timed out`);let v=null,b=0,x=[`## AI Kit Status`,``,`- **Total Records**: ${h.totalRecords}`,`- **Total Files**: ${h.totalFiles}`,`- **Last Indexed**: ${h.lastIndexedAt??`Never`}`,``,`### Content Types`,...Object.entries(h.contentTypeBreakdown).map(([e,t])=>`- ${e}: ${t}`),``,`### Indexed Files`,...g.slice(0,50).map(e=>`- ${e}`),g.length>50?`\n... and ${g.length-50} more files`:``];if(o)try{let t=await rl(o.getStats(),{nodeCount:0,edgeCount:0,nodeTypes:{},edgeTypes:{}},`graphStore.getStats`);if(t.timedOut)e.push(`⚠ Graph stats timed out`),x.push(``,`### Knowledge Graph`,`- Graph stats timed out`);else{let e=t.value;v={nodes:e.nodeCount,edges:e.edgeCount},x.push(``,`### Knowledge Graph`,`- **Nodes**: ${e.nodeCount}`,`- **Edges**: ${e.edgeCount}`,...Object.entries(e.nodeTypes).map(([e,t])=>` - ${e}: ${t}`));try{let e=await rl(o.validate(),{valid:!0,danglingEdges:[],orphanNodes:[],stats:{nodeCount:0,edgeCount:0,nodeTypes:{},edgeTypes:{}}},`graphStore.validate`);if(!e.timedOut){let t=e.value;t.valid||x.push(`- **⚠ Integrity Issues**: ${t.danglingEdges.length} dangling edges`),t.orphanNodes.length>0&&x.push(`- **Orphan nodes**: ${t.orphanNodes.length}`)}}catch{}}}catch{x.push(``,`### Knowledge Graph`,`- Graph store unavailable`)}let S=l?.onboardDir??_(process.cwd(),y.aiContext),C=a(S),w=c?.onboardComplete||C;if(x.push(``,`### Onboard Status`,w?`- ✅ Complete${c?.onboardTimestamp?` (last: ${c.onboardTimestamp})`:``}`:'- ❌ Not run — call `onboard({ path: "." })` to analyze the codebase',`- **Onboard Directory**: \`${S}\``),s)try{let t=await rl(s.list(),[],`curated.list`);if(t.timedOut)e.push(`⚠ Curated knowledge listing timed out`),x.push(``,`### Curated Knowledge`,`- Listing timed out`);else{let e=t.value;b=e.length,x.push(``,`### Curated Knowledge`,e.length>0?`- ${e.length} entries`:"- Empty — use `remember()` to persist decisions")}}catch{x.push(``,`### Curated Knowledge`,`- Unable to read curated entries`)}let T=sl(h.totalRecords,v?.nodes??0,v?.edges??0,b);x.push(``),x.push(`## 📊 Context Pressure: ${T}/100`),T>=80?x.push(`⚠️ High pressure — consider pruning stale entries or compacting context.`):T>=50?x.push(`ℹ️ Moderate pressure — knowledge base is well-populated.`):x.push(`✅ Low pressure — plenty of headroom for more content.`);let E=0;if(h.lastIndexedAt){E=new Date(h.lastIndexedAt).getTime();let e=(Date.now()-E)/(1e3*60*60);x.push(``,`### Index Freshness`,e>24?u===`smart`?`- ⚠ Last indexed ${Math.floor(e)}h ago — smart indexing will refresh automatically`:`- ⚠ Last indexed ${Math.floor(e)}h ago — may be stale. Run \`reindex({})\``:`- ✅ Last indexed ${e<1?`less than 1h`:`${Math.floor(e)}h`} ago`)}if(u===`smart`)if(x.push(``,`### Smart Indexing`),f){let e=f();e?x.push(`- **Mode**: Smart (trickle)`,`- **Status**: ${e.running?`✅ Running`:`⏸ Stopped`}`,`- **Queue**: ${e.queueSize} files pending`,`- **Changed files**: ${e.changedFilesSize} detected`,`- **Interval**: ${Math.round(e.intervalMs/1e3)}s per batch of ${e.batchSize}`):x.push(`- **Mode**: Smart (trickle)`,`- **Status**: scheduler state unavailable (init may have failed)`)}else x.push(`- **Mode**: Smart (trickle) — scheduler state unavailable`);{try{let e=_(process.cwd(),y.data,`stash`);if(a(e)){let t=d(e).mtimeMs;t>E&&(E=t)}}catch{}let e=[];if(s)try{let t=b>0?await s.list():[];for(let e of t){let t=new Date(e.updated||e.created).getTime();t>E&&(E=t)}e.push(...t.sort((e,t)=>new Date(t.updated).getTime()-new Date(e.updated).getTime()).slice(0,5))}catch{}let t=E>0?Date.now()-E:0;if(t>=144e5){let n=Math.floor(t/36e5);if(x.push(``,`### 🌅 Session Briefing`,`_${n}+ hours since last activity — here's what to pick up:_`,``),e.length>0){x.push(`**Recent decisions/notes:**`);for(let t of e)x.push(`- **${t.title}** (${t.category??`note`}) — ${(t.contentPreview??``).slice(0,80)}…`)}x.push(``,`**Suggested next steps:**`,'- `search({ query: "SESSION CHECKPOINT", origin: "curated" })` — find your last checkpoint',"- `restore({})` — resume from a saved checkpoint","- `list()` — browse all stored knowledge")}}x.push(``,`### Runtime`,`- **Tree-sitter (WASM)**: ${re.get()?`✅ Available (AST analysis)`:`⚠ Unavailable (regex fallback)`}`);let D=cl(),O=ll(),k=r(),ee=D!=null&&D!==k,A=O!=null&&O!==k;if(ee||A){let e=i(),t=[];ee&&t.push(`user scaffold v${D}`),A&&t.push(`workspace scaffold v${O}`);let r=t.join(`, `);e.state===`success`?x.push(``,`### ✅ Upgrade Applied`,`- Server v${k} — ${r} auto-upgraded successfully.`,`- _Restart the MCP server to use the updated version._`):e.state===`pending`?x.push(``,`### ⏳ Upgrade In Progress`,`- Server v${k} ≠ ${r}`,`- Auto-upgrade is running in the background…`):e.state===`failed`?(n(),x.push(``,`### ⬆ Upgrade Available (auto-upgrade failed, retrying)`,`- Server v${k} ≠ ${r}`,`- Error: ${e.error??`unknown`}`)):(n(),x.push(``,`### ⬆ Upgrade Available`,`- Server v${k} ≠ ${r}`,`- Auto-upgrade triggered — check again shortly.`))}e.length>0&&x.push(``,`### ⚠ Warnings`,...e.map(e=>`- ${e}`));let j=Br();if(j.length>0){let e=j.sort((e,t)=>t.callCount-e.callCount);x.push(``,`### Tool Usage This Session`,``),x.push(`| Tool | Calls | Tokens In | Tokens Out | Errors | Avg Latency |`),x.push(`|------|-------|-----------|------------|--------|-------------|`);for(let t of e.slice(0,15)){let e=Math.round(t.totalInputChars/4),n=Math.round(t.totalOutputChars/4),r=Math.round(t.totalDurationMs/t.callCount);x.push(`| ${t.tool} | ${t.callCount} | ${e.toLocaleString()} | ${n.toLocaleString()} | ${t.errorCount} | ${r}ms |`)}}let M=Nr();if(M.bufferSize>=10){let e=M.state===`healthy`?`🟢`:M.state===`degraded`?`🔴`:`🟡`;x.push(``,`### Auto-GC: ${e} ${M.state}`),x.push(`- p95 latency: ${M.p95}ms | buffer: ${M.bufferSize} samples`),M.gcCount>0&&x.push(`- GC cycles triggered: ${M.gcCount}`)}let te=x.join(`
1263
+ `),ne={totalRecords:h.totalRecords,totalFiles:h.totalFiles,lastIndexedAt:h.lastIndexedAt??null,onboarded:w,onboardDir:S,contentTypes:h.contentTypeBreakdown,wasmAvailable:!!re.get(),graphStats:v,curatedCount:b,serverVersion:k,scaffoldVersion:D??null,workspaceScaffoldVersion:O??null,upgradeAvailable:ee||A,contextPressure:T};return{content:[{type:`text`,text:te+(u===`smart`?"\n\n---\n_Next: Use `search` to query indexed content or `graph({action:'find_nodes', name_pattern:'<top-level-module>'})` → then `graph({action:'neighbors', node_id})` for relationships. Smart indexing handles updates automatically._":"\n\n---\n_Next: Use `search` to query indexed content, `graph({action:'find_nodes', name_pattern:'<top-level-module>'})` → then `graph({action:'neighbors', node_id})` for relationships, or `reindex` to refresh the index._")}],structuredContent:ne}}catch(e){return nl.error(`Status failed`,A(e)),{content:[{type:`text`,text:`Status check failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}const fl=E(`tools`);function pl(e,t,n){let r=L(`update`);e.registerTool(`update`,{title:r.title,description:`Update an existing curated knowledge entry. Increments version and records the reason in the changelog.`,inputSchema:{path:F.string().describe(`Relative path within .ai/curated/ (e.g., "decisions/use-lancedb.md")`),content:F.string().min(10).max(1e5).describe(`New markdown content to replace existing content`),reason:F.string().min(3).max(1e3).describe(`Why this update is being made (recorded in changelog)`)},annotations:r.annotations},async({path:e,content:r,reason:i})=>{try{let a=await t.update(e,r,i);return n&&n.notifyAfterCuratedWrite(e).catch(()=>{}),{content:[{type:`text`,text:`Updated: \`.ai/curated/${a.path}\` → version ${a.version}\n\nReason: ${i}\n\n---\n_Next: Use \`read\` to verify the updated content, or \`search\` to test searchability._`}]}}catch(e){return fl.error(`Update failed`,A(e)),{content:[{type:`text`,text:`Update failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}const Z=E(`tools`);function ml(e){let t=L(`web_search`);e.registerTool(`web_search`,{title:t.title,description:`PREFERRED web search — search the web via DuckDuckGo (no API key). Pass one query or multiple for parallel searching. Returns structured results with title, URL, and snippet.`,inputSchema:{queries:F.array(F.string().max(2e3)).min(1).max(5).describe('Search queries (1–5). Single: `["react hooks"]`. Multiple searched in parallel.'),limit:F.number().min(1).max(20).default(5).describe(`Max results per query`),site:F.string().optional().describe(`Restrict to domain (e.g., "docs.aws.amazon.com")`)},annotations:t.annotations},async({queries:e,limit:t,site:n})=>{let r=e,i=async e=>{let r=await tn({query:e,limit:t,site:n}),i=[`## Search: ${r.query}`,``];if(r.results.length===0)i.push(`No results found.`);else for(let e of r.results)i.push(`### [${e.title}](${e.url})`,e.snippet,``);return i.join(`
1261
1264
  `)};if(r.length===1)try{return{content:[{type:`text`,text:`${await i(r[0])}\n---\n_Next: Use \`web_fetch\` to read any of these pages in full._`}]}}catch(e){return Z.error(`Web search failed`,A(e)),{content:[{type:`text`,text:`Web search failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}let a=await Promise.allSettled(r.map(e=>i(e))),o=[],s=0;for(let e=0;e<a.length;e++){let t=a[e];if(t.status===`fulfilled`)o.push(t.value);else{s++;let n=t.reason instanceof Error?t.reason.message:String(t.reason);Z.error(`Web search failed`,{query:r[e],error:n}),o.push(`## ❌ Search failed: ${r[e]}\n\n${n}`)}}let c=`_Searched ${a.length-s}/${a.length} queries successfully._`;return o.push(``,`---`,c,"_Next: Use `web_fetch` to read any of these pages in full._"),{content:[{type:`text`,text:o.join(`
1262
1265
 
1263
- `)}],...s===a.length?{isError:!0}:{}}})}function ml(e){let t=L(`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 $e({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(`
1264
- `)}]}}catch(e){return Z.error(`HTTP request failed`,A(e)),{content:[{type:`text`,text:`HTTP request failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function hl(e){let t=L(`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=Tt({pattern:e,flags:t,testStrings:n,mode:r,replacement:i});if(!a.valid)return{content:[{type:`text`,text:`Invalid regex: ${a.error}`}],isError:!0};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(`
1265
- `)}]}})}function gl(e){let t=L(`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=Le({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 Z.error(`Encode failed`,A(e)),{content:[{type:`text`,text:`Encode failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function _l(e){let t=L(`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:hi,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 ct({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(`
1266
- `)}],structuredContent:i}}catch(e){return Z.error(`Measure failed`,A(e)),{content:[{type:`text`,text:`Measure failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function vl(e){let t=L(`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=xe({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 Z.error(`Changelog failed`,A(e)),{content:[{type:`text`,text:`Changelog failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function yl(e){let t=L(`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=Pt({data:JSON.parse(e),schema:JSON.parse(t)});if(n.valid)return{content:[{type:`text`,text:`## Validation: PASSED
1266
+ `)}],...s===a.length?{isError:!0}:{}}})}function hl(e){let t=L(`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 $e({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(`
1267
+ `)}]}}catch(e){return Z.error(`HTTP request failed`,A(e)),{content:[{type:`text`,text:`HTTP request failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function gl(e){let t=L(`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=Tt({pattern:e,flags:t,testStrings:n,mode:r,replacement:i});if(!a.valid)return{content:[{type:`text`,text:`Invalid regex: ${a.error}`}],isError:!0};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(`
1268
+ `)}]}})}function _l(e){let t=L(`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=Le({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 Z.error(`Encode failed`,A(e)),{content:[{type:`text`,text:`Encode failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function vl(e){let t=L(`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:hi,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 ct({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(`
1269
+ `)}],structuredContent:i}}catch(e){return Z.error(`Measure failed`,A(e)),{content:[{type:`text`,text:`Measure failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function yl(e){let t=L(`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=xe({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 Z.error(`Changelog failed`,A(e)),{content:[{type:`text`,text:`Changelog failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function bl(e){let t=L(`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=Pt({data:JSON.parse(e),schema:JSON.parse(t)});if(n.valid)return{content:[{type:`text`,text:`## Validation: PASSED
1267
1270
 
1268
1271
  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(`
1269
- `)}]}}catch(e){return Z.error(`Schema validation failed`,A(e)),{content:[{type:`text`,text:`Schema validation failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function bl(e){let t=L(`snippet`);e.registerTool(`snippet`,{title:t.title,description:`Save, retrieve, search, and manage persistent code snippets/templates.`,inputSchema:{action:F.enum([`save`,`get`,`list`,`search`,`delete`]).describe(`Operation to perform`),name:F.string().optional().describe(`Snippet name (required for save/get/delete)`),language:F.string().optional().describe(`Language tag (for save)`),code:F.string().max(1e5).optional().describe(`Code content (for save)`),tags:F.array(F.string()).optional().describe(`Tags for categorization (for save)`),query:F.string().optional().describe(`Search query (for search)`)},annotations:t.annotations},async({action:e,name:t,language:n,code:r,tags:i,query:a})=>{try{let o=Rt({action:e,name:t,language:n,code:r,tags:i,query:a});if(`deleted`in o)return{content:[{type:`text`,text:o.deleted?`Snippet "${t}" deleted.`:`Snippet "${t}" not found.`}]};if(`snippets`in o){if(o.snippets.length===0)return{content:[{type:`text`,text:`No snippets found.`}]};let e=[`## Snippets`,``];for(let t of o.snippets){let n=t.tags.length>0?` [${t.tags.join(`, `)}]`:``;e.push(`- **${t.name}** (${t.language})${n}`)}return{content:[{type:`text`,text:e.join(`
1270
- `)}]}}let s=o,c=s.tags.length>0?`\nTags: ${s.tags.join(`, `)}`:``;return{content:[{type:`text`,text:`## ${s.name} (${s.language})${c}\n\n\`\`\`${s.language}\n${s.code}\n\`\`\``}]}}catch(e){return Z.error(`Snippet failed`,A(e)),{content:[{type:`text`,text:`Snippet failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function xl(e){let t=L(`env`);e.registerTool(`env`,{title:t.title,description:`Get system and runtime environment info. Sensitive env vars are redacted by default.`,outputSchema:gi,inputSchema:{include_env:F.boolean().default(!1).describe(`Include environment variables`),filter_env:F.string().optional().describe(`Filter env vars by name substring`),show_sensitive:F.boolean().default(!1).describe(`Show sensitive values (keys, tokens, etc.) — redacted by default`)},annotations:t.annotations},async({include_env:e,filter_env:t,show_sensitive:n})=>{let r=Re({includeEnv:e,filterEnv:t,showSensitive:n}),i=[`## Environment`,``,`**Platform:** ${r.system.platform} ${r.system.arch}`,`**OS:** ${r.system.type} ${r.system.release}`,`**Host:** ${r.system.hostname}`,`**CPUs:** ${r.system.cpus}`,`**Memory:** ${r.system.memoryFreeGb}GB free / ${r.system.memoryTotalGb}GB total`,``,`**Node:** ${r.runtime.node}`,`**V8:** ${r.runtime.v8}`,`**CWD:** ${r.cwd}`];if(r.env){i.push(``,`### Environment Variables`,``);for(let[e,t]of Object.entries(r.env))i.push(`- \`${e}\`: ${t}`)}let a={platform:r.system.platform,arch:r.system.arch,nodeVersion:r.runtime.node,cwd:r.cwd,cpus:r.system.cpus,memoryFreeGb:r.system.memoryFreeGb,memoryTotalGb:r.system.memoryTotalGb};return{content:[{type:`text`,text:i.join(`
1271
- `)}],structuredContent:a}})}function Sl(e){let t=L(`time`);e.registerTool(`time`,{title:t.title,description:`Parse dates, convert timezones, calculate durations, add time. Supports ISO 8601, unix timestamps, and human-readable formats.`,outputSchema:_i,inputSchema:{operation:F.enum([`now`,`parse`,`convert`,`diff`,`add`]).describe(`now: current time | parse: parse a date string | convert: timezone conversion | diff: duration between two dates | add: add duration to date`),input:F.string().optional().describe(`Date input (ISO, unix timestamp, or parseable string). For diff: two comma-separated dates`),timezone:F.string().optional().describe(`Target timezone (e.g., "America/New_York", "Asia/Tokyo")`),duration:F.string().optional().describe(`Duration to add (e.g., "2h30m", "1d", "30s") — for add operation`)},annotations:t.annotations},async({operation:e,input:t,timezone:n,duration:r})=>{try{let i=Jt({operation:e,input:t,timezone:n,duration:r}),a=[`**${i.output}**`,``,`ISO: ${i.iso}`,`Unix: ${i.unix}`];i.details&&a.push(``,"```json",JSON.stringify(i.details),"```");let o={iso:i.iso,unix:i.unix,timezone:n??Intl.DateTimeFormat().resolvedOptions().timeZone,formatted:i.output};return{content:[{type:`text`,text:a.join(`
1272
- `)}],structuredContent:o}}catch(e){return Z.error(`Time failed`,A(e)),{content:[{type:`text`,text:`Time failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}const Q=E(`server`);function Cl(e){let t=e.toLowerCase();return[`protobuf`,`invalid model`,`invalid onnx`,`unexpected end`,`unexpected token`,`failed to load`,`failed to initialize embedding`,`checksum`,`corrupt`,`malformed`,`could not load`,`onnx`,`database disk image is malformed`,`file is not a database`,`lance`].some(e=>t.includes(e))}async function wl(e,t){let n=t.toLowerCase(),r;try{({rm:r}=await import(`node:fs/promises`))}catch{return}if(n.includes(`embedding`)||n.includes(`onnx`)||n.includes(`protobuf`)||n.includes(`model`)){let t=e.embedding?.model??x.model,n=g(N(),`.cache`,`huggingface`,`transformers-js`,t);try{await r(n,{recursive:!0,force:!0}),Q.info(`Auto-heal: cleared embedding model cache`,{path:n})}catch{}}if(n.includes(`lance`)||n.includes(`database`)||n.includes(`store`)){let t=g(e.store.path,`lance`);try{await r(t,{recursive:!0,force:!0}),Q.info(`Auto-heal: cleared LanceDB store`,{path:t})}catch{}}if(n.includes(`sqlite`)||n.includes(`database disk image`)||n.includes(`graph`)){let t=g(e.store.path,`graph.db`);try{await r(t,{force:!0}),Q.info(`Auto-heal: cleared graph database`,{path:t})}catch{}}}async function Tl(n){Q.info(`Initializing AI Kit components`);let[r,i,o,s]=await Promise.all([(async()=>{let e=new ae({model:n.embedding.model,dimensions:n.embedding.dimensions});return await e.initialize(),Q.info(`Embedder loaded`,{modelId:e.modelId,dimensions:e.dimensions}),e})(),(async()=>{let e=await he({backend:n.store.backend,path:n.store.path});return await e.initialize(),Q.info(`Store initialized`),e})(),(async()=>{let e=new me({path:n.store.path});return await e.initialize(),Q.info(`Graph store initialized`),e})(),(async()=>{let e=await ie();return e?Q.info(`WASM tree-sitter enabled for AST analysis`):Q.warn(`WASM tree-sitter not available; analyzers will use regex fallback`),e})()]),c=new pe(r,i),l=new fe(n.store.path);l.load(),c.setHashCache(l);let u=n.curated.path,f=new e(u);await f.initialize();let p=new t(u,i,r,f);c.setGraphStore(o);let m=ua(n.er),h=m?new le(n.curated.path):void 0;h&&Q.info(`Policy store initialized`,{ruleCount:h.getRules().length});let g=m?new ce:void 0,v=_(n.sources[0]?.path??process.cwd(),y.aiContext),b=a(v),x=n.onboardDir?a(n.onboardDir):!1,S=b||x,C,w=b?v:n.onboardDir;if(S&&w)try{C=d(w).mtime.toISOString()}catch{}return Q.info(`Onboard state detected`,{onboardComplete:S,onboardTimestamp:C,aiKbExists:b,onboardDirExists:x}),{embedder:r,store:i,indexer:c,curated:p,graphStore:o,fileCache:new ge,bridge:m,policyStore:h,evolutionCollector:g,onboardComplete:S,onboardTimestamp:C}}function El(e,t){let n=new nn({name:t.serverName??`aikit`,version:r()},{capabilities:{logging:{},completions:{},prompts:{}}});return Cr(n),Ml(n,e,t,vr(n),new Wr(n),Xr(n)),Er(n,{curated:e.curated,store:e.store,graphStore:e.graphStore},t.indexMode),n}function Dl(e){return e.toolProfiles}const Ol=[`flow_list`,`flow_info`,`flow_start`,`flow_step`,`flow_status`,`flow_reset`,`flow_runs`,`flow_read_instruction`,`flow_add`,`flow_remove`,`flow_update`],kl=[`er_push`,`er_pull`,`er_sync_status`],Al=[...kl,`er_update_policy`,`er_evolve_review`],jl=new Set(Al);function Ml(e,t,n,r,i,a,o,s){let c=new lr,l=new Vn;l.register(Rn),l.register(Pn),l.register(Fn),l.register(jn),l.register(Dn),l.register(On),l.register(Bn);let u=new Kn(l,t.curated);c.use(Wn(u),{order:5,name:`auto-knowledge`}),c.use(Hr(),{order:10,name:`replay`}),c.use(Zr(),{order:50,name:`structured-content-guard`}),c.use(_r(),{order:90,name:`compression`}),mr(e,c,n.toolPrefix??``);let d=oi(process.env.AIKIT_TOOLSET||n.toolProfile||`full`,[...$,...Al],ur,Dl(n)),f=e=>d.has(e),p=[...d].filter(e=>jl.has(e)?kl.includes(e)?!!t.bridge:e===`er_update_policy`?!!t.policyStore:e===`er_evolve_review`?!!t.evolutionCollector:!1:!0);f(`search`)&&Qc(e,t.embedder,t.store,t.graphStore,t.bridge,t.evolutionCollector,a),f(`lookup`)&&qo(e,t.store);let m={onboardComplete:t.onboardComplete,onboardTimestamp:t.onboardTimestamp};f(`status`)&&ul(e,t.store,t.graphStore,t.curated,m,n,o,s),f(`config`)&&Va(e,n),f(`reindex`)&&Pc(e,t.indexer,n,t.curated,t.store,i,o),f(`remember`)&&Ic(e,t.curated,t.policyStore,t.evolutionCollector,i),f(`update`)&&fl(e,t.curated,i),f(`forget`)&&jo(e,t.curated,i),f(`read`)&&Nc(e,t.curated),f(`list`)&&Go(e,t.curated),f(`analyze_structure`)&&qi(e,t.store,t.embedder),f(`analyze_dependencies`)&&Ji(e,t.store,t.embedder),f(`analyze_symbols`)&&Yi(e,t.store,t.embedder),f(`analyze_patterns`)&&Xi(e,t.store,t.embedder),f(`analyze_entry_points`)&&Zi(e,t.store,t.embedder),f(`analyze_diagram`)&&Qi(e,t.store,t.embedder),f(`blast_radius`)&&$i(e,t.store,t.embedder,t.graphStore),f(`produce_knowledge`)&&jc(e,n),f(`onboard`)&&cs(e,t.store,t.embedder,n,m),f(`graph`)&&Fo(e,t.graphStore),f(`audit`)&&ia(e,t.store,t.embedder);let h=n.sources[0]?.path??process.cwd();f(`compact`)&&Ja(e,t.embedder,t.fileCache,h),f(`scope_map`)&&Ya(e,t.embedder,t.store),f(`find`)&&Xa(e,t.embedder,t.store),f(`parse_output`)&&fo(e),f(`workset`)&&us(e),f(`check`)&&so(e),f(`batch`)&&co(e,t.embedder,t.store),f(`symbol`)&&Za(e,t.embedder,t.store,t.graphStore),f(`eval`)&&lo(e),f(`test_run`)&&uo(e),f(`stash`)&&ds(e),f(`git_context`)&&Yo(e),f(`diff_parse`)&&Xo(e),f(`rename`)&&Zo(e),f(`codemod`)&&Qo(e),f(`restore`)&&Bc(e),f(`file_summary`)&&Qa(e,t.fileCache,h),f(`checkpoint`)&&fs(e),f(`data_transform`)&&$o(e),f(`trace`)&&$a(e,t.embedder,t.store,t.graphStore),f(`process`)&&Io(e),f(`watch`)&&Lo(e),f(`dead_symbols`)&&eo(e,t.embedder,t.store),f(`delegate`)&&po(e,a),f(`health`)&&Ro(e),f(`lane`)&&ps(e),f(`queue`)&&ms(e),f(`web_fetch`)&&zo(e),f(`guide`)&&Bo(e,o),ns.some(e=>f(e))&&rs(e,n,p),f(`evidence_map`)&&To(e),f(`digest`)&&Eo(e,t.embedder),f(`forge_classify`)&&Do(e),f(`stratum_card`)&&Oo(e,t.embedder,t.fileCache),f(`forge_ground`)&&ko(e,t.embedder,t.store),f(`present`)&&Dc(e,r),r&&f(`brainstorm`)&&oa(e,r),f(`web_search`)&&pl(e),f(`http`)&&ml(e),f(`regex_test`)&&hl(e),f(`encode`)&&gl(e),f(`measure`)&&_l(e),f(`changelog`)&&vl(e),f(`schema_validate`)&&yl(e),f(`snippet`)&&bl(e),f(`env`)&&xl(e),f(`time`)&&Sl(e),Ol.some(e=>f(e))&&Co(e,n),t.bridge&&kl.some(e=>f(e))&&(da(e,t.bridge,t.evolutionCollector),fa(e,t.bridge),pa(e,t.bridge)),t.policyStore&&f(`er_update_policy`)&&bs(e,t.policyStore),t.evolutionCollector&&f(`er_evolve_review`)&&ao(e,t.evolutionCollector),Kr(e,t.store,t.curated),Rc(e),f(`session_digest`)&&el(e,a)}async function Nl(e){let t=await Tl(e),n=El(t,e);Q.info(`MCP server configured`,{toolCount:$.length,resourceCount:2});let r=async()=>{try{let n=e.sources.map(e=>e.path).join(`, `);Q.info(`Running initial index`,{sourcePaths:n});let r=await t.indexer.index(e,e=>{e.phase===`crawling`||e.phase===`done`||(e.phase===`chunking`&&e.currentFile&&Q.debug(`Indexing file`,{current:e.filesProcessed+1,total:e.filesTotal,file:e.currentFile}),e.phase===`cleanup`&&Q.debug(`Index cleanup`,{staleEntries:e.filesTotal-e.filesProcessed}))});Q.info(`Initial index complete`,{filesProcessed:r.filesProcessed,filesSkipped:r.filesSkipped,chunksCreated:r.chunksCreated,durationMs:r.durationMs});try{await t.store.createFtsIndex()}catch(e){Q.warn(`FTS index creation failed`,A(e))}try{let e=await t.curated.reindexAll();Q.info(`Curated re-index complete`,{indexed:e.indexed})}catch(e){Q.error(`Curated re-index failed`,A(e))}}catch(e){Q.error(`Initial index failed; will retry on aikit_reindex`,A(e))}},i=async()=>{Q.info(`Shutting down`),await Promise.all([t.embedder.shutdown().catch(()=>{}),t.graphStore.close().catch(()=>{}),t.store.close().catch(()=>{})]),process.exit(0)};process.on(`SIGINT`,i),process.on(`SIGTERM`,i);let a=process.ppid,o=setInterval(()=>{try{process.kill(a,0)}catch{Q.info(`Parent process died; shutting down`,{parentPid:a}),clearInterval(o),i()}},5e3);return o.unref(),{server:n,runInitialIndex:r,shutdown:i}}const Pl=new Set(`batch.brainstorm.changelog.check.checkpoint.codemod.compact.config.data_transform.delegate.diff_parse.digest.encode.env.eval.evidence_map.file_summary.forge_classify.git_context.graph.guide.health.http.lane.measure.onboard.parse_output.present.process.produce_knowledge.queue.read.regex_test.reindex.remember.rename.replay.restore.schema_validate.session_digest.scope_map.snippet.stash.status.stratum_card.test_run.time.update.forget.list.watch.web_fetch.web_search.workset`.split(`.`)),Fl=5e3,Il=new Set(`brainstorm.changelog.check.checkpoint.codemod.data_transform.delegate.diff_parse.encode.env.eval.evidence_map.flow_info.flow_list.flow_reset.flow_runs.flow_start.flow_status.flow_step.flow_add.flow_update.flow_remove.flow_read_instruction.describe_tool.list_tools.search_tools.forge_classify.git_context.guide.present.health.http.lane.measure.parse_output.process.produce_knowledge.queue.regex_test.rename.replay.restore.schema_validate.session_digest.snippet.stash.status.test_run.time.watch.web_fetch.web_search.workset`.split(`.`));function Ll(e,t,n){let r=e=>!n||n.has(e);r(`check`)&&so(e),r(`eval`)&&lo(e),r(`test_run`)&&uo(e),r(`parse_output`)&&fo(e),r(`delegate`)&&po(e),r(`git_context`)&&Yo(e),r(`diff_parse`)&&Xo(e),r(`rename`)&&Zo(e),r(`codemod`)&&Qo(e),r(`data_transform`)&&$o(e),r(`workset`)&&us(e),r(`stash`)&&ds(e),r(`checkpoint`)&&fs(e),r(`restore`)&&Bc(e),r(`lane`)&&ps(e),r(`queue`)&&ms(e),r(`session_digest`)&&el(e),r(`health`)&&Ro(e),r(`process`)&&Io(e),r(`watch`)&&Lo(e),r(`web_fetch`)&&zo(e),r(`guide`)&&Bo(e),ns.some(e=>r(e))&&rs(e,t,[...n??new Set($)]),r(`evidence_map`)&&To(e),r(`forge_classify`)&&Do(e),r(`present`)&&Dc(e),r(`brainstorm`)&&oa(e,yr),r(`produce_knowledge`)&&jc(e),r(`replay`)&&Rc(e),r(`status`)&&ll(e),Ol.some(e=>r(e))&&Co(e,t),r(`web_search`)&&pl(e),r(`http`)&&ml(e),r(`regex_test`)&&hl(e),r(`encode`)&&gl(e),r(`measure`)&&_l(e),r(`changelog`)&&vl(e),r(`schema_validate`)&&yl(e),r(`snippet`)&&bl(e),r(`env`)&&xl(e),r(`time`)&&Sl(e)}const $=`analyze_dependencies.analyze_diagram.analyze_entry_points.analyze_patterns.analyze_structure.analyze_symbols.audit.batch.blast_radius.brainstorm.changelog.check.checkpoint.codemod.compact.config.data_transform.dead_symbols.delegate.diff_parse.digest.encode.env.eval.evidence_map.file_summary.find.flow_info.flow_list.flow_reset.flow_runs.flow_start.flow_status.flow_step.flow_add.flow_update.flow_remove.flow_read_instruction.forge_classify.forge_ground.forget.git_context.graph.guide.health.http.lane.describe_tool.list_tools.list.lookup.measure.onboard.parse_output.present.process.produce_knowledge.queue.read.regex_test.reindex.remember.rename.replay.restore.schema_validate.scope_map.search.search_tools.session_digest.snippet.stash.status.stratum_card.symbol.test_run.time.trace.update.watch.web_fetch.web_search.workset`.split(`.`);function Rl(e,t){let n=new nn({name:e.serverName??`aikit`,version:r()},{capabilities:{logging:{},completions:{},prompts:{}}}),i=`initializing`,a=``,o=!1,s=null,c=oi(process.env.AIKIT_TOOLSET||e.toolProfile||`full`,$,ur,Dl(e)),l=null,u=null;function d(e){if(!e||typeof e!=`object`)return[];let t=e,n=[];for(let e of[`path`,`file`,`source_path`,`sourcePath`,`filePath`]){let r=t[e];typeof r==`string`&&r&&n.push(r)}for(let e of[`changed_files`,`paths`,`files`]){let r=t[e];if(Array.isArray(r))for(let e of r){if(typeof e==`string`){n.push(e);continue}e&&typeof e==`object`&&typeof e.path==`string`&&n.push(e.path)}}if(Array.isArray(t.sources))for(let e of t.sources)e&&typeof e==`object`&&typeof e.path==`string`&&n.push(e.path);return n}let f=()=>i===`failed`?[`❌ AI Kit initialization failed — this tool is unavailable.`,``,a?`Error: ${a}`:``,``,`**${Il.size} tools are still available** and fully functional:`,`check, eval, test_run, git_context, health, measure, web_fetch, web_search,`,`flow_list, flow_status, flow_start, flow_read_instruction, regex_test, encode,`,`stash, checkpoint, lane, process, time, env, and more.`,``,`To fix embedding errors, try deleting the cached model:`,` rm -rf ~/.cache/huggingface/transformers-js/mixedbread-ai/`,`Then restart the server to re-download a fresh copy.`,``,`Try restarting the MCP server to retry initialization.`].filter(Boolean).join(`
1273
- `):[`AI Kit is still initializing (loading embeddings model & store).`,``,`**${Il.size} tools are already available** while initialization completes — including:`,`check, eval, test_run, git_context, health, measure, web_fetch, web_search,`,`flow_list, flow_status, flow_start, flow_read_instruction, regex_test, encode,`,`stash, checkpoint, lane, process, time, env, and more.`,``,`This tool requires the AI Kit index. Please retry in a few seconds,`,`or use one of the available tools above in the meantime.`].join(`
1274
- `);Cr(n),hr(n,e.toolPrefix??``);let p=n.sendToolListChanged.bind(n);n.sendToolListChanged=()=>{};let m=[];for(let e of $){if(!c.has(e))continue;let t=L(e),r=n.registerTool(e,{title:t.title,description:`${t.title} — initializing, available shortly`,inputSchema:{},annotations:t.annotations},async()=>({content:[{type:`text`,text:f()}]}));Il.has(e)?r.remove():m.push(r)}Ll(n,e,c),n.sendToolListChanged=p;let h=n.registerResource(`aikit-status`,`aikit://status`,{description:`AI Kit status (initializing...)`,mimeType:`text/plain`},async()=>({contents:[{uri:`aikit://status`,text:`AI Kit is initializing...`,mimeType:`text/plain`}]})),g=n.registerPrompt(`_init`,{description:`Initializing AI Kit…`,argsSchema:{_dummy:P(F.string(),()=>[])}},async()=>({messages:[]})),_,v=new Promise(e=>{_=e}),y,b=new Promise(e=>{y=e}),x=()=>y?.(),S=(async()=>{await b;let r;try{r=await Tl(e)}catch(t){let n=t instanceof Error?t.message:String(t);if(Cl(n)){Q.warn(`AI Kit initialization failed with recoverable error — attempting auto-heal retry`,{error:n}),await wl(e,n);try{r=await Tl(e),Q.info(`AI Kit auto-heal successful — initialization recovered after retry`)}catch(e){i=`failed`,a=e instanceof Error?e.message:String(e),Q.error(`AI Kit initialization failed after auto-heal attempt — server continuing with zero-dep tools only`,{error:a,originalError:n});return}}else{i=`failed`,a=n,Q.error(`AI Kit initialization failed — server continuing with zero-dep tools only`,{error:a});return}}let c=n.sendToolListChanged.bind(n);n.sendToolListChanged=()=>{};let f=n.sendPromptListChanged.bind(n);n.sendPromptListChanged=()=>{};let p=n.sendResourceListChanged.bind(n);n.sendResourceListChanged=()=>{};for(let e of m)e.remove();h.remove(),g.remove();let v=n._registeredTools??{};for(let e of Il)v[e]?.remove();let y=new Wr(n),x=Xr(n);Ml(n,r,e,vr(n),y,x,t,t===`smart`?(()=>{let e=u;return e?.getState?e.getState():null}):null),Er(n,{curated:r.curated,store:r.store,graphStore:r.graphStore},t),n.sendToolListChanged=c,n.sendPromptListChanged=f,n.sendResourceListChanged=p,Promise.resolve(n.sendToolListChanged()).catch(()=>{}),Promise.resolve(n.sendPromptListChanged()).catch(()=>{}),Promise.resolve(n.sendResourceListChanged()).catch(()=>{});let S=n._registeredTools??{};for(let[e,t]of Object.entries(S)){if(Pl.has(e))continue;let n=t.handler;t.handler=async(...t)=>{if(!r.indexer.isIndexing)return n(...t);let i=o?`re-indexing`:`running initial index`,a=new Promise(t=>setTimeout(()=>t({content:[{type:`text`,text:`⏳ AI Kit is ${i}. The tool "${e}" timed out waiting for index data (${Fl/1e3}s).\n\nThe existing index may be temporarily locked. Please retry shortly — indexing will complete automatically.`}]}),Fl));return Promise.race([n(...t),a])}}for(let[e,t]of Object.entries(S)){let n=t.handler,r=ui(e);t.handler=async(...t)=>{try{return await di(()=>n(...t),r,e)}catch(t){if(t instanceof li)return{content:[{type:`text`,text:`⏳ Tool "${e}" timed out after ${r/1e3}s. This may indicate a long-running operation. Please retry or break the task into smaller steps.`}]};throw t}}}let C=Object.keys(S).length;C<$.length&&Q.warn(`ALL_TOOL_NAMES count mismatch`,{expectedToolCount:$.length,registeredToolCount:C}),Q.info(`MCP server configured`,{toolCount:$.length,resourceCount:4});let T=new Tr;T.onPressure((e,t)=>{e===`warning`&&Qn(),e===`critical`&&(Q.warn(`Memory pressure critical — consider restarting`,{rssMB:Math.round(t/1024/1024)}),Qn())}),T.start();let E=new xr;l=E,E.onIdle(async()=>{if(w.isRunning||r.indexer.isIndexing){Q.info(`Idle cleanup deferred — background tasks still running`),E.touch();return}Q.info(`Idle cleanup: closing store and graph connections`);try{await Promise.all([r.store.close().catch(()=>{}),r.graphStore.close().catch(()=>{})])}catch{}}),E.touch();for(let e of Object.values(S)){let t=e.handler;e.handler=async(...e)=>{if(E.touch(),u){let t=d(e[0]);t.length>0&&u.prioritize(...t)}return t(...e)}}s=r,_?.(r)})(),C=async()=>{let t=await v;l?.setBusy(!0);try{let n=e.sources.map(e=>e.path).join(`, `);Q.info(`Running initial index`,{sourcePaths:n});let r=await t.indexer.index(e,e=>{e.phase===`crawling`||e.phase===`done`||(e.phase===`chunking`&&e.currentFile&&Q.debug(`Indexing file`,{current:e.filesProcessed+1,total:e.filesTotal,file:e.currentFile}),e.phase===`cleanup`&&Q.debug(`Index cleanup`,{staleEntries:e.filesTotal-e.filesProcessed}))});o=!0,Q.info(`Initial index complete`,{filesProcessed:r.filesProcessed,filesSkipped:r.filesSkipped,chunksCreated:r.chunksCreated,durationMs:r.durationMs});try{await t.store.createFtsIndex()}catch(e){Q.warn(`FTS index creation failed`,A(e))}try{let e=await t.curated.reindexAll();Q.info(`Curated re-index complete`,{indexed:e.indexed})}catch(e){Q.error(`Curated re-index failed`,A(e))}}catch(e){Q.error(`Initial index failed; will retry on aikit_reindex`,A(e))}finally{l?.setBusy(!1)}},w=new Jn,T=()=>w.schedule({name:`initial-index`,fn:C}),E=process.ppid,D=setInterval(()=>{try{process.kill(E,0)}catch{Q.info(`Parent process died; shutting down`,{parentPid:E}),clearInterval(D),v.then(async e=>{await Promise.all([e.embedder.shutdown().catch(()=>{}),e.graphStore.close().catch(()=>{}),e.store.close().catch(()=>{})])}).catch(()=>{}).finally(()=>process.exit(0))}},5e3);return D.unref(),{server:n,startInit:x,ready:S,runInitialIndex:T,get kb(){return s},scheduler:w,setSmartScheduler(e){u=e}}}export{$ as ALL_TOOL_NAMES,Rl as createLazyServer,El as createMcpServer,Nl as createServer,Tl as initializeKnowledgeBase,Ml as registerMcpTools};
1272
+ `)}]}}catch(e){return Z.error(`Schema validation failed`,A(e)),{content:[{type:`text`,text:`Schema validation failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function xl(e){let t=L(`snippet`);e.registerTool(`snippet`,{title:t.title,description:`Save, retrieve, search, and manage persistent code snippets/templates.`,inputSchema:{action:F.enum([`save`,`get`,`list`,`search`,`delete`]).describe(`Operation to perform`),name:F.string().optional().describe(`Snippet name (required for save/get/delete)`),language:F.string().optional().describe(`Language tag (for save)`),code:F.string().max(1e5).optional().describe(`Code content (for save)`),tags:F.array(F.string()).optional().describe(`Tags for categorization (for save)`),query:F.string().optional().describe(`Search query (for search)`)},annotations:t.annotations},async({action:e,name:t,language:n,code:r,tags:i,query:a})=>{try{let o=Rt({action:e,name:t,language:n,code:r,tags:i,query:a});if(`deleted`in o)return{content:[{type:`text`,text:o.deleted?`Snippet "${t}" deleted.`:`Snippet "${t}" not found.`}]};if(`snippets`in o){if(o.snippets.length===0)return{content:[{type:`text`,text:`No snippets found.`}]};let e=[`## Snippets`,``];for(let t of o.snippets){let n=t.tags.length>0?` [${t.tags.join(`, `)}]`:``;e.push(`- **${t.name}** (${t.language})${n}`)}return{content:[{type:`text`,text:e.join(`
1273
+ `)}]}}let s=o,c=s.tags.length>0?`\nTags: ${s.tags.join(`, `)}`:``;return{content:[{type:`text`,text:`## ${s.name} (${s.language})${c}\n\n\`\`\`${s.language}\n${s.code}\n\`\`\``}]}}catch(e){return Z.error(`Snippet failed`,A(e)),{content:[{type:`text`,text:`Snippet failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function Sl(e){let t=L(`env`);e.registerTool(`env`,{title:t.title,description:`Get system and runtime environment info. Sensitive env vars are redacted by default.`,outputSchema:gi,inputSchema:{include_env:F.boolean().default(!1).describe(`Include environment variables`),filter_env:F.string().optional().describe(`Filter env vars by name substring`),show_sensitive:F.boolean().default(!1).describe(`Show sensitive values (keys, tokens, etc.) — redacted by default`)},annotations:t.annotations},async({include_env:e,filter_env:t,show_sensitive:n})=>{let r=Re({includeEnv:e,filterEnv:t,showSensitive:n}),i=[`## Environment`,``,`**Platform:** ${r.system.platform} ${r.system.arch}`,`**OS:** ${r.system.type} ${r.system.release}`,`**Host:** ${r.system.hostname}`,`**CPUs:** ${r.system.cpus}`,`**Memory:** ${r.system.memoryFreeGb}GB free / ${r.system.memoryTotalGb}GB total`,``,`**Node:** ${r.runtime.node}`,`**V8:** ${r.runtime.v8}`,`**CWD:** ${r.cwd}`];if(r.env){i.push(``,`### Environment Variables`,``);for(let[e,t]of Object.entries(r.env))i.push(`- \`${e}\`: ${t}`)}let a={platform:r.system.platform,arch:r.system.arch,nodeVersion:r.runtime.node,cwd:r.cwd,cpus:r.system.cpus,memoryFreeGb:r.system.memoryFreeGb,memoryTotalGb:r.system.memoryTotalGb};return{content:[{type:`text`,text:i.join(`
1274
+ `)}],structuredContent:a}})}function Cl(e){let t=L(`time`);e.registerTool(`time`,{title:t.title,description:`Parse dates, convert timezones, calculate durations, add time. Supports ISO 8601, unix timestamps, and human-readable formats.`,outputSchema:_i,inputSchema:{operation:F.enum([`now`,`parse`,`convert`,`diff`,`add`]).describe(`now: current time | parse: parse a date string | convert: timezone conversion | diff: duration between two dates | add: add duration to date`),input:F.string().optional().describe(`Date input (ISO, unix timestamp, or parseable string). For diff: two comma-separated dates`),timezone:F.string().optional().describe(`Target timezone (e.g., "America/New_York", "Asia/Tokyo")`),duration:F.string().optional().describe(`Duration to add (e.g., "2h30m", "1d", "30s") — for add operation`)},annotations:t.annotations},async({operation:e,input:t,timezone:n,duration:r})=>{try{let i=Jt({operation:e,input:t,timezone:n,duration:r}),a=[`**${i.output}**`,``,`ISO: ${i.iso}`,`Unix: ${i.unix}`];i.details&&a.push(``,"```json",JSON.stringify(i.details),"```");let o={iso:i.iso,unix:i.unix,timezone:n??Intl.DateTimeFormat().resolvedOptions().timeZone,formatted:i.output};return{content:[{type:`text`,text:a.join(`
1275
+ `)}],structuredContent:o}}catch(e){return Z.error(`Time failed`,A(e)),{content:[{type:`text`,text:`Time failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}const Q=E(`server`);function wl(e){let t=e.toLowerCase();return[`protobuf`,`invalid model`,`invalid onnx`,`unexpected end`,`unexpected token`,`failed to load`,`failed to initialize embedding`,`checksum`,`corrupt`,`malformed`,`could not load`,`onnx`,`database disk image is malformed`,`file is not a database`,`lance`].some(e=>t.includes(e))}async function Tl(e,t){let n=t.toLowerCase(),r;try{({rm:r}=await import(`node:fs/promises`))}catch{return}if(n.includes(`embedding`)||n.includes(`onnx`)||n.includes(`protobuf`)||n.includes(`model`)){let t=e.embedding?.model??x.model,n=g(N(),`.cache`,`huggingface`,`transformers-js`,t);try{await r(n,{recursive:!0,force:!0}),Q.info(`Auto-heal: cleared embedding model cache`,{path:n})}catch{}}if(n.includes(`lance`)||n.includes(`database`)||n.includes(`store`)){let t=g(e.store.path,`lance`);try{await r(t,{recursive:!0,force:!0}),Q.info(`Auto-heal: cleared LanceDB store`,{path:t})}catch{}}if(n.includes(`sqlite`)||n.includes(`database disk image`)||n.includes(`graph`)){let t=g(e.store.path,`graph.db`);try{await r(t,{force:!0}),Q.info(`Auto-heal: cleared graph database`,{path:t})}catch{}}}async function El(n){Q.info(`Initializing AI Kit components`);let[r,i,o,s]=await Promise.all([(async()=>{let e=new ae({model:n.embedding.model,dimensions:n.embedding.dimensions});return await e.initialize(),Q.info(`Embedder loaded`,{modelId:e.modelId,dimensions:e.dimensions}),e})(),(async()=>{let e=await he({backend:n.store.backend,path:n.store.path});return await e.initialize(),Q.info(`Store initialized`),e})(),(async()=>{let e=new me({path:n.store.path});return await e.initialize(),Q.info(`Graph store initialized`),e})(),(async()=>{let e=await ie();return e?Q.info(`WASM tree-sitter enabled for AST analysis`):Q.warn(`WASM tree-sitter not available; analyzers will use regex fallback`),e})()]),c=new pe(r,i),l=new fe(n.store.path);l.load(),c.setHashCache(l);let u=n.curated.path,f=new e(u);await f.initialize();let p=new t(u,i,r,f);c.setGraphStore(o);let m=ua(n.er),h=m?new le(n.curated.path):void 0;h&&Q.info(`Policy store initialized`,{ruleCount:h.getRules().length});let g=m?new ce:void 0,v=_(n.sources[0]?.path??process.cwd(),y.aiContext),b=a(v),x=n.onboardDir?a(n.onboardDir):!1,S=b||x,C,w=b?v:n.onboardDir;if(S&&w)try{C=d(w).mtime.toISOString()}catch{}return Q.info(`Onboard state detected`,{onboardComplete:S,onboardTimestamp:C,aiKbExists:b,onboardDirExists:x}),{embedder:r,store:i,indexer:c,curated:p,graphStore:o,fileCache:new ge,bridge:m,policyStore:h,evolutionCollector:g,onboardComplete:S,onboardTimestamp:C}}function Dl(e,t){let n=new nn({name:t.serverName??`aikit`,version:r()},{capabilities:{logging:{},completions:{},prompts:{}}});return Cr(n),Nl(n,e,t,vr(n),new Wr(n),Xr(n)),Er(n,{curated:e.curated,store:e.store,graphStore:e.graphStore},t.indexMode),n}function Ol(e){return e.toolProfiles}const kl=[`flow_list`,`flow_info`,`flow_start`,`flow_step`,`flow_status`,`flow_reset`,`flow_runs`,`flow_read_instruction`,`flow_add`,`flow_remove`,`flow_update`],Al=[`er_push`,`er_pull`,`er_sync_status`],jl=[...Al,`er_update_policy`,`er_evolve_review`],Ml=new Set(jl);function Nl(e,t,n,r,i,a,o,s){let c=new lr,l=new Vn;l.register(Rn),l.register(Pn),l.register(Fn),l.register(jn),l.register(Dn),l.register(On),l.register(Bn);let u=new Kn(l,t.curated);c.use(Wn(u),{order:5,name:`auto-knowledge`}),c.use(Hr(),{order:10,name:`replay`}),c.use(Zr(),{order:50,name:`structured-content-guard`}),c.use(_r(),{order:90,name:`compression`}),mr(e,c,n.toolPrefix??``);let d=oi(process.env.AIKIT_TOOLSET||n.toolProfile||`full`,[...$,...jl],ur,Ol(n)),f=e=>d.has(e),p=[...d].filter(e=>Ml.has(e)?Al.includes(e)?!!t.bridge:e===`er_update_policy`?!!t.policyStore:e===`er_evolve_review`?!!t.evolutionCollector:!1:!0);f(`search`)&&$c(e,t.embedder,t.store,t.graphStore,t.bridge,t.evolutionCollector,a),f(`lookup`)&&qo(e,t.store);let m={onboardComplete:t.onboardComplete,onboardTimestamp:t.onboardTimestamp};f(`status`)&&dl(e,t.store,t.graphStore,t.curated,m,n,o,s),f(`config`)&&Va(e,n),f(`reindex`)&&Fc(e,t.indexer,n,t.curated,t.store,i,o),f(`remember`)&&Lc(e,t.curated,t.policyStore,t.evolutionCollector,i),f(`update`)&&pl(e,t.curated,i),f(`forget`)&&jo(e,t.curated,i),f(`read`)&&Pc(e,t.curated),f(`list`)&&Go(e,t.curated),f(`analyze_structure`)&&qi(e,t.store,t.embedder),f(`analyze_dependencies`)&&Ji(e,t.store,t.embedder),f(`analyze_symbols`)&&Yi(e,t.store,t.embedder),f(`analyze_patterns`)&&Xi(e,t.store,t.embedder),f(`analyze_entry_points`)&&Zi(e,t.store,t.embedder),f(`analyze_diagram`)&&Qi(e,t.store,t.embedder),f(`blast_radius`)&&$i(e,t.store,t.embedder,t.graphStore),f(`produce_knowledge`)&&Mc(e,n),f(`onboard`)&&cs(e,t.store,t.embedder,n,m),f(`graph`)&&Fo(e,t.graphStore),f(`audit`)&&ia(e,t.store,t.embedder);let h=n.sources[0]?.path??process.cwd();f(`compact`)&&Ja(e,t.embedder,t.fileCache,h),f(`scope_map`)&&Ya(e,t.embedder,t.store),f(`find`)&&Xa(e,t.embedder,t.store),f(`parse_output`)&&fo(e),f(`workset`)&&us(e),f(`check`)&&so(e),f(`batch`)&&co(e,t.embedder,t.store),f(`symbol`)&&Za(e,t.embedder,t.store,t.graphStore),f(`eval`)&&lo(e),f(`test_run`)&&uo(e),f(`stash`)&&ds(e),f(`git_context`)&&Yo(e),f(`diff_parse`)&&Xo(e),f(`rename`)&&Zo(e),f(`codemod`)&&Qo(e),f(`restore`)&&Vc(e),f(`file_summary`)&&Qa(e,t.fileCache,h),f(`checkpoint`)&&fs(e),f(`data_transform`)&&$o(e),f(`trace`)&&$a(e,t.embedder,t.store,t.graphStore),f(`process`)&&Io(e),f(`watch`)&&Lo(e),f(`dead_symbols`)&&eo(e,t.embedder,t.store),f(`delegate`)&&po(e,a),f(`health`)&&Ro(e),f(`lane`)&&ps(e),f(`queue`)&&ms(e),f(`web_fetch`)&&zo(e),f(`guide`)&&Bo(e,o),ns.some(e=>f(e))&&rs(e,n,p),f(`evidence_map`)&&To(e),f(`digest`)&&Eo(e,t.embedder),f(`forge_classify`)&&Do(e),f(`stratum_card`)&&Oo(e,t.embedder,t.fileCache),f(`forge_ground`)&&ko(e,t.embedder,t.store),f(`present`)&&Oc(e,r),r&&f(`brainstorm`)&&oa(e,r),f(`web_search`)&&ml(e),f(`http`)&&hl(e),f(`regex_test`)&&gl(e),f(`encode`)&&_l(e),f(`measure`)&&vl(e),f(`changelog`)&&yl(e),f(`schema_validate`)&&bl(e),f(`snippet`)&&xl(e),f(`env`)&&Sl(e),f(`time`)&&Cl(e),kl.some(e=>f(e))&&Co(e,n),t.bridge&&Al.some(e=>f(e))&&(da(e,t.bridge,t.evolutionCollector),fa(e,t.bridge),pa(e,t.bridge)),t.policyStore&&f(`er_update_policy`)&&bs(e,t.policyStore),t.evolutionCollector&&f(`er_evolve_review`)&&ao(e,t.evolutionCollector),Kr(e,t.store,t.curated),zc(e),f(`session_digest`)&&tl(e,a)}async function Pl(e){let t=await El(e),n=Dl(t,e);Q.info(`MCP server configured`,{toolCount:$.length,resourceCount:2});let r=async()=>{try{let n=e.sources.map(e=>e.path).join(`, `);Q.info(`Running initial index`,{sourcePaths:n});let r=await t.indexer.index(e,e=>{e.phase===`crawling`||e.phase===`done`||(e.phase===`chunking`&&e.currentFile&&Q.debug(`Indexing file`,{current:e.filesProcessed+1,total:e.filesTotal,file:e.currentFile}),e.phase===`cleanup`&&Q.debug(`Index cleanup`,{staleEntries:e.filesTotal-e.filesProcessed}))});Q.info(`Initial index complete`,{filesProcessed:r.filesProcessed,filesSkipped:r.filesSkipped,chunksCreated:r.chunksCreated,durationMs:r.durationMs});try{await t.store.createFtsIndex()}catch(e){Q.warn(`FTS index creation failed`,A(e))}try{let e=await t.curated.reindexAll();Q.info(`Curated re-index complete`,{indexed:e.indexed})}catch(e){Q.error(`Curated re-index failed`,A(e))}}catch(e){Q.error(`Initial index failed; will retry on aikit_reindex`,A(e))}},i=async()=>{Q.info(`Shutting down`),await Promise.all([t.embedder.shutdown().catch(()=>{}),t.graphStore.close().catch(()=>{}),t.store.close().catch(()=>{})]),process.exit(0)};process.on(`SIGINT`,i),process.on(`SIGTERM`,i);let a=process.ppid,o=setInterval(()=>{try{process.kill(a,0)}catch{Q.info(`Parent process died; shutting down`,{parentPid:a}),clearInterval(o),i()}},5e3);return o.unref(),{server:n,runInitialIndex:r,shutdown:i}}const Fl=new Set(`batch.brainstorm.changelog.check.checkpoint.codemod.compact.config.data_transform.delegate.diff_parse.digest.encode.env.eval.evidence_map.file_summary.forge_classify.git_context.graph.guide.health.http.lane.measure.onboard.parse_output.present.process.produce_knowledge.queue.read.regex_test.reindex.remember.rename.replay.restore.schema_validate.session_digest.scope_map.snippet.stash.status.stratum_card.test_run.time.update.forget.list.watch.web_fetch.web_search.workset`.split(`.`)),Il=5e3,Ll=new Set(`brainstorm.changelog.check.checkpoint.codemod.data_transform.delegate.diff_parse.encode.env.eval.evidence_map.flow_info.flow_list.flow_reset.flow_runs.flow_start.flow_status.flow_step.flow_add.flow_update.flow_remove.flow_read_instruction.describe_tool.list_tools.search_tools.forge_classify.git_context.guide.present.health.http.lane.measure.parse_output.process.produce_knowledge.queue.regex_test.rename.replay.restore.schema_validate.session_digest.snippet.stash.status.test_run.time.watch.web_fetch.web_search.workset`.split(`.`));function Rl(e,t,n){let r=e=>!n||n.has(e);r(`check`)&&so(e),r(`eval`)&&lo(e),r(`test_run`)&&uo(e),r(`parse_output`)&&fo(e),r(`delegate`)&&po(e),r(`git_context`)&&Yo(e),r(`diff_parse`)&&Xo(e),r(`rename`)&&Zo(e),r(`codemod`)&&Qo(e),r(`data_transform`)&&$o(e),r(`workset`)&&us(e),r(`stash`)&&ds(e),r(`checkpoint`)&&fs(e),r(`restore`)&&Vc(e),r(`lane`)&&ps(e),r(`queue`)&&ms(e),r(`session_digest`)&&tl(e),r(`health`)&&Ro(e),r(`process`)&&Io(e),r(`watch`)&&Lo(e),r(`web_fetch`)&&zo(e),r(`guide`)&&Bo(e),ns.some(e=>r(e))&&rs(e,t,[...n??new Set($)]),r(`evidence_map`)&&To(e),r(`forge_classify`)&&Do(e),r(`present`)&&Oc(e),r(`brainstorm`)&&oa(e,yr),r(`produce_knowledge`)&&Mc(e),r(`replay`)&&zc(e),r(`status`)&&ul(e),kl.some(e=>r(e))&&Co(e,t),r(`web_search`)&&ml(e),r(`http`)&&hl(e),r(`regex_test`)&&gl(e),r(`encode`)&&_l(e),r(`measure`)&&vl(e),r(`changelog`)&&yl(e),r(`schema_validate`)&&bl(e),r(`snippet`)&&xl(e),r(`env`)&&Sl(e),r(`time`)&&Cl(e)}const $=`analyze_dependencies.analyze_diagram.analyze_entry_points.analyze_patterns.analyze_structure.analyze_symbols.audit.batch.blast_radius.brainstorm.changelog.check.checkpoint.codemod.compact.config.data_transform.dead_symbols.delegate.diff_parse.digest.encode.env.eval.evidence_map.file_summary.find.flow_info.flow_list.flow_reset.flow_runs.flow_start.flow_status.flow_step.flow_add.flow_update.flow_remove.flow_read_instruction.forge_classify.forge_ground.forget.git_context.graph.guide.health.http.lane.describe_tool.list_tools.list.lookup.measure.onboard.parse_output.present.process.produce_knowledge.queue.read.regex_test.reindex.remember.rename.replay.restore.schema_validate.scope_map.search.search_tools.session_digest.snippet.stash.status.stratum_card.symbol.test_run.time.trace.update.watch.web_fetch.web_search.workset`.split(`.`);function zl(e,t){let n=new nn({name:e.serverName??`aikit`,version:r()},{capabilities:{logging:{},completions:{},prompts:{}}}),i=`initializing`,a=``,o=!1,s=null,c=oi(process.env.AIKIT_TOOLSET||e.toolProfile||`full`,$,ur,Ol(e)),l=null,u=null;function d(e){if(!e||typeof e!=`object`)return[];let t=e,n=[];for(let e of[`path`,`file`,`source_path`,`sourcePath`,`filePath`]){let r=t[e];typeof r==`string`&&r&&n.push(r)}for(let e of[`changed_files`,`paths`,`files`]){let r=t[e];if(Array.isArray(r))for(let e of r){if(typeof e==`string`){n.push(e);continue}e&&typeof e==`object`&&typeof e.path==`string`&&n.push(e.path)}}if(Array.isArray(t.sources))for(let e of t.sources)e&&typeof e==`object`&&typeof e.path==`string`&&n.push(e.path);return n}let f=()=>i===`failed`?[`❌ AI Kit initialization failed — this tool is unavailable.`,``,a?`Error: ${a}`:``,``,`**${Ll.size} tools are still available** and fully functional:`,`check, eval, test_run, git_context, health, measure, web_fetch, web_search,`,`flow_list, flow_status, flow_start, flow_read_instruction, regex_test, encode,`,`stash, checkpoint, lane, process, time, env, and more.`,``,`To fix embedding errors, try deleting the cached model:`,` rm -rf ~/.cache/huggingface/transformers-js/mixedbread-ai/`,`Then restart the server to re-download a fresh copy.`,``,`Try restarting the MCP server to retry initialization.`].filter(Boolean).join(`
1276
+ `):[`AI Kit is still initializing (loading embeddings model & store).`,``,`**${Ll.size} tools are already available** while initialization completes — including:`,`check, eval, test_run, git_context, health, measure, web_fetch, web_search,`,`flow_list, flow_status, flow_start, flow_read_instruction, regex_test, encode,`,`stash, checkpoint, lane, process, time, env, and more.`,``,`This tool requires the AI Kit index. Please retry in a few seconds,`,`or use one of the available tools above in the meantime.`].join(`
1277
+ `);Cr(n),hr(n,e.toolPrefix??``);let p=n.sendToolListChanged.bind(n);n.sendToolListChanged=()=>{};let m=[];for(let e of $){if(!c.has(e))continue;let t=L(e),r=n.registerTool(e,{title:t.title,description:`${t.title} — initializing, available shortly`,inputSchema:{},annotations:t.annotations},async()=>({content:[{type:`text`,text:f()}]}));Ll.has(e)?r.remove():m.push(r)}Rl(n,e,c),n.sendToolListChanged=p;let h=n.registerResource(`aikit-status`,`aikit://status`,{description:`AI Kit status (initializing...)`,mimeType:`text/plain`},async()=>({contents:[{uri:`aikit://status`,text:`AI Kit is initializing...`,mimeType:`text/plain`}]})),g=n.registerPrompt(`_init`,{description:`Initializing AI Kit…`,argsSchema:{_dummy:P(F.string(),()=>[])}},async()=>({messages:[]})),_,v=new Promise(e=>{_=e}),y,b=new Promise(e=>{y=e}),x=()=>y?.(),S=(async()=>{await b;let r;try{r=await El(e)}catch(t){let n=t instanceof Error?t.message:String(t);if(wl(n)){Q.warn(`AI Kit initialization failed with recoverable error — attempting auto-heal retry`,{error:n}),await Tl(e,n);try{r=await El(e),Q.info(`AI Kit auto-heal successful — initialization recovered after retry`)}catch(e){i=`failed`,a=e instanceof Error?e.message:String(e),Q.error(`AI Kit initialization failed after auto-heal attempt — server continuing with zero-dep tools only`,{error:a,originalError:n});return}}else{i=`failed`,a=n,Q.error(`AI Kit initialization failed — server continuing with zero-dep tools only`,{error:a});return}}let c=n.sendToolListChanged.bind(n);n.sendToolListChanged=()=>{};let f=n.sendPromptListChanged.bind(n);n.sendPromptListChanged=()=>{};let p=n.sendResourceListChanged.bind(n);n.sendResourceListChanged=()=>{};for(let e of m)e.remove();h.remove(),g.remove();let v=n._registeredTools??{};for(let e of Ll)v[e]?.remove();let y=new Wr(n),x=Xr(n);Nl(n,r,e,vr(n),y,x,t,t===`smart`?(()=>{let e=u;return e?.getState?e.getState():null}):null),Er(n,{curated:r.curated,store:r.store,graphStore:r.graphStore},t),n.sendToolListChanged=c,n.sendPromptListChanged=f,n.sendResourceListChanged=p,Promise.resolve(n.sendToolListChanged()).catch(()=>{}),Promise.resolve(n.sendPromptListChanged()).catch(()=>{}),Promise.resolve(n.sendResourceListChanged()).catch(()=>{});let S=n._registeredTools??{};for(let[e,t]of Object.entries(S)){if(Fl.has(e))continue;let n=t.handler;t.handler=async(...t)=>{if(!r.indexer.isIndexing)return n(...t);let i=o?`re-indexing`:`running initial index`,a=new Promise(t=>setTimeout(()=>t({content:[{type:`text`,text:`⏳ AI Kit is ${i}. The tool "${e}" timed out waiting for index data (${Il/1e3}s).\n\nThe existing index may be temporarily locked. Please retry shortly — indexing will complete automatically.`}]}),Il));return Promise.race([n(...t),a])}}for(let[e,t]of Object.entries(S)){let n=t.handler,r=ui(e);t.handler=async(...t)=>{try{return await di(()=>n(...t),r,e)}catch(t){if(t instanceof li)return{content:[{type:`text`,text:`⏳ Tool "${e}" timed out after ${r/1e3}s. This may indicate a long-running operation. Please retry or break the task into smaller steps.`}]};throw t}}}let C=Object.keys(S).length;C<$.length&&Q.warn(`ALL_TOOL_NAMES count mismatch`,{expectedToolCount:$.length,registeredToolCount:C}),Q.info(`MCP server configured`,{toolCount:$.length,resourceCount:4});let T=new Tr;T.onPressure((e,t)=>{e===`warning`&&Qn(),e===`critical`&&(Q.warn(`Memory pressure critical — consider restarting`,{rssMB:Math.round(t/1024/1024)}),Qn())}),T.start();let E=new xr;l=E,E.onIdle(async()=>{if(w.isRunning||r.indexer.isIndexing){Q.info(`Idle cleanup deferred — background tasks still running`),E.touch();return}Q.info(`Idle cleanup: closing store and graph connections`);try{await Promise.all([r.store.close().catch(()=>{}),r.graphStore.close().catch(()=>{})])}catch{}}),E.touch();for(let e of Object.values(S)){let t=e.handler;e.handler=async(...e)=>{if(E.touch(),u){let t=d(e[0]);t.length>0&&u.prioritize(...t)}return t(...e)}}s=r,_?.(r)})(),C=async()=>{let t=await v;l?.setBusy(!0);try{let n=e.sources.map(e=>e.path).join(`, `);Q.info(`Running initial index`,{sourcePaths:n});let r=await t.indexer.index(e,e=>{e.phase===`crawling`||e.phase===`done`||(e.phase===`chunking`&&e.currentFile&&Q.debug(`Indexing file`,{current:e.filesProcessed+1,total:e.filesTotal,file:e.currentFile}),e.phase===`cleanup`&&Q.debug(`Index cleanup`,{staleEntries:e.filesTotal-e.filesProcessed}))});o=!0,Q.info(`Initial index complete`,{filesProcessed:r.filesProcessed,filesSkipped:r.filesSkipped,chunksCreated:r.chunksCreated,durationMs:r.durationMs});try{await t.store.createFtsIndex()}catch(e){Q.warn(`FTS index creation failed`,A(e))}try{let e=await t.curated.reindexAll();Q.info(`Curated re-index complete`,{indexed:e.indexed})}catch(e){Q.error(`Curated re-index failed`,A(e))}}catch(e){Q.error(`Initial index failed; will retry on aikit_reindex`,A(e))}finally{l?.setBusy(!1)}},w=new Jn,T=()=>w.schedule({name:`initial-index`,fn:C}),E=process.ppid,D=setInterval(()=>{try{process.kill(E,0)}catch{Q.info(`Parent process died; shutting down`,{parentPid:E}),clearInterval(D),v.then(async e=>{await Promise.all([e.embedder.shutdown().catch(()=>{}),e.graphStore.close().catch(()=>{}),e.store.close().catch(()=>{})])}).catch(()=>{}).finally(()=>process.exit(0))}},5e3);return D.unref(),{server:n,startInit:x,ready:S,runInitialIndex:T,get kb(){return s},scheduler:w,setSmartScheduler(e){u=e}}}export{$ as ALL_TOOL_NAMES,zl as createLazyServer,Dl as createMcpServer,Pl as createServer,El as initializeKnowledgeBase,Nl as registerMcpTools};
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __createRequire } from 'node:module'; const require = __createRequire(import.meta.url);
2
- import{r as e}from"./chunk-DqSKhezp.js";import{t}from"./react-CKRDn6y3.js";import{a as n,i as r,n as i,t as a}from"./jsx-runtime-CI8Ofr1S.js";import{t as o}from"./useKBClient-BACLDL_U.js";import{t as s}from"./StatusPanel-yRieSRc3.js";import{t as c}from"./SearchPanel-CDSGcT7M.js";import{t as l}from"./CuratedPanel-DGFKz-fJ.js";import{t as u}from"./LogPanel-DGeptKim.js";var d=e(t()),f=a();const p=[`status`,`search`,`curated`,`log`];function m({client:e}){let[t,a]=(0,d.useState)(`status`);return i((e,n)=>{n.tab&&a(p[(p.indexOf(t)+1)%p.length]),e===`1`&&a(`status`),e===`2`&&a(`search`),e===`3`&&a(`curated`),e===`4`&&a(`log`)}),(0,f.jsx)(o,{value:e,children:(0,f.jsxs)(n,{flexDirection:`column`,width:`100%`,children:[(0,f.jsxs)(n,{borderStyle:`single`,paddingX:1,children:[(0,f.jsx)(r,{bold:!0,color:`cyan`,children:`AI Kit Dashboard`}),(0,f.jsx)(r,{children:` │ `}),p.map(e=>(0,f.jsxs)(d.Fragment,{children:[(0,f.jsxs)(r,{color:e===t?`green`:`gray`,bold:e===t,children:[`[`,p.indexOf(e)+1,`] `,e]}),(0,f.jsx)(r,{children:` `})]},e)),(0,f.jsx)(r,{color:`gray`,children:` │ Tab: switch │ Ctrl+C: quit`})]}),(0,f.jsxs)(n,{flexGrow:1,minHeight:10,children:[t===`status`&&(0,f.jsx)(s,{}),t===`search`&&(0,f.jsx)(c,{}),t===`curated`&&(0,f.jsx)(l,{}),t===`log`&&(0,f.jsx)(u,{})]})]})})}export{m as t};
2
+ import{r as e}from"./chunk-DqSKhezp.js";import{t}from"./react-CKRDn6y3.js";import{a as n,i as r,n as i,t as a}from"./jsx-runtime-CI8Ofr1S.js";import{t as o}from"./useKBClient-BACLDL_U.js";import{t as s}from"./StatusPanel-yRieSRc3.js";import{t as c}from"./SearchPanel-CDSGcT7M.js";import{t as l}from"./CuratedPanel-DGFKz-fJ.js";import{t as u}from"./LogPanel-BrBa5xIT.js";var d=e(t()),f=a();const p=[`status`,`search`,`curated`,`log`];function m({client:e}){let[t,a]=(0,d.useState)(`status`);return i((e,n)=>{n.tab&&a(p[(p.indexOf(t)+1)%p.length]),e===`1`&&a(`status`),e===`2`&&a(`search`),e===`3`&&a(`curated`),e===`4`&&a(`log`)}),(0,f.jsx)(o,{value:e,children:(0,f.jsxs)(n,{flexDirection:`column`,width:`100%`,children:[(0,f.jsxs)(n,{borderStyle:`single`,paddingX:1,children:[(0,f.jsx)(r,{bold:!0,color:`cyan`,children:`AI Kit Dashboard`}),(0,f.jsx)(r,{children:` │ `}),p.map(e=>(0,f.jsxs)(d.Fragment,{children:[(0,f.jsxs)(r,{color:e===t?`green`:`gray`,bold:e===t,children:[`[`,p.indexOf(e)+1,`] `,e]}),(0,f.jsx)(r,{children:` `})]},e)),(0,f.jsx)(r,{color:`gray`,children:` │ Tab: switch │ Ctrl+C: quit`})]}),(0,f.jsxs)(n,{flexGrow:1,minHeight:10,children:[t===`status`&&(0,f.jsx)(s,{}),t===`search`&&(0,f.jsx)(c,{}),t===`curated`&&(0,f.jsx)(l,{}),t===`log`&&(0,f.jsx)(u,{})]})]})})}export{m as t};
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __createRequire } from 'node:module'; const require = __createRequire(import.meta.url);
2
- import{t as e}from"./App-DobfqTPH.js";export{e as App};
2
+ import{t as e}from"./App-Bkz0lpCn.js";export{e as App};