@vpxa/aikit 0.1.131 → 0.1.133
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json
CHANGED
|
@@ -3747,7 +3747,7 @@ ${e.themeCSS}`),e.fontFamily!==void 0&&(n+=`
|
|
|
3747
3747
|
:root { --mermaid-alt-font-family: ${e.altFontFamily}}`),t instanceof Map){let r=ov(e)?[`> *`,`span`]:[`rect`,`polygon`,`ellipse`,`circle`,`path`];t.forEach(e=>{UP(e.styles)||r.forEach(t=>{n+=D9(e.id,t,e.styles)}),UP(e.textStyles)||(n+=D9(e.id,`tspan`,(e?.textStyles||[]).map(e=>e.replace(`color`,`fill`))))})}return n},`createCssStyles`),ndt=V((e,t,n,r)=>ZW(KJe(`${r}{${Sde(t,tdt(e,n),{...e.themeVariables,theme:e.theme,look:e.look},r)}}`),QJe),`createUserStyles`),rdt=V((e=``,t,n)=>{let r=e;return!n&&!t&&(r=r.replace(/marker-end="url\([\d+./:=?A-Za-z-]*?#/g,`marker-end="url(#`)),r=bD(r),r=r.replace(/<br>/g,`<br/>`),r},`cleanUpSvgCode`),idt=V((e=``,t)=>`<iframe style="width:${qut};height:${t?.viewBox?.baseVal?.height?t.viewBox.baseVal.height+`px`:Jut};${Yut}" src="data:text/html;charset=UTF-8;base64,${Xlt(`<body style="${Xut}">${e}</body>`)}" sandbox="${Zut}">
|
|
3748
3748
|
${Qut}
|
|
3749
3749
|
</iframe>`,`putIntoIFrame`),O9=V((e,t,n,r,i)=>{let a=e.append(`div`);a.attr(`id`,n),r&&a.attr(`style`,r);let o=a.append(`svg`).attr(`id`,t).attr(`width`,`100%`).attr(`xmlns`,Wut);return i&&o.attr(`xmlns:xlink`,i),o.append(`g`),e},`appendDivSvgG`),V(W7,`sandboxedIframe`),adt=V((e,t,n,r)=>{e.getElementById(t)?.remove(),e.getElementById(n)?.remove(),e.getElementById(r)?.remove()},`removeExistingElements`),odt=V(async function(e,t,n){w9();let r=U7(t);t=r.code;let i=Z_();H.debug(i),t.length>(i?.maxTextSize??But)&&(t=Vut);let a=`#`+e,o=`i`+e,s=`#`+o,l=`d`+e,u=`#`+l,d=V(()=>{let e=Ny(p?s:u).node();e&&`remove`in e&&e.remove()},`removeTempElements`),f=Ny(`body`),p=i.securityLevel===Hut,m=i.securityLevel===Uut,h=i.fontFamily;n===void 0?(adt(document,e,l,o),p?(f=Ny(W7(Ny(`body`),o).nodes()[0].contentDocument.body),f.node().style.margin=0):f=Ny(`body`),O9(f,e,l)):(n&&(n.innerHTML=``),p?(f=Ny(W7(Ny(n),o).nodes()[0].contentDocument.body),f.node().style.margin=0):f=Ny(n),O9(f,e,l,`font-family: ${h}`,Gut));let g,_;try{g=await T9.fromText(t,{title:r.title})}catch(e){if(i.suppressErrorRendering)throw d(),e;g=await T9.fromText(`error`),_=e}let v=f.select(u).node(),y=g.type,b=v.firstChild,x=b.firstChild,S=g.renderer.getClasses?.(t,g),C=ndt(i,y,S,a),w=document.createElement(`style`);w.innerHTML=C,b.insertBefore(w,x);try{await g.renderer.draw(t,e,`11.14.0`,g)}catch(n){throw i.suppressErrorRendering?d():_ut.draw(t,e,`11.14.0`),n}let T=f.select(`${u} svg`),E=g.db.getAccTitle?.(),D=g.db.getAccDescription?.();$lt(y,T,E,D),f.select(`[id="${e}"]`).selectAll(`foreignobject > *`).attr(`xmlns`,Kut);let O=f.select(u).node().innerHTML;if(H.debug(`config.arrowMarkerAbsolute`,i.arrowMarkerAbsolute),O=rdt(O,p,B_(i.arrowMarkerAbsolute)),p){let e=f.select(u+` svg`).node();O=idt(O,e)}else m||(O=Ff.sanitize(O,{ADD_TAGS:$ut,ADD_ATTR:edt,HTML_INTEGRATION_POINTS:{foreignobject:!0}}));if(Fut(),_)throw _;return d(),{diagramType:y,svg:O,bindFunctions:g.db.bindFunctions}},`render`),V(Qlt,`initialize`),k9=V((e,t={})=>{let{code:n}=H7(e);return T9.fromText(n,t)},`getDiagramFromText`),V($lt,`addA11yInfo`),A9=Object.freeze({render:odt,parse:Zlt,getDiagramFromText:k9,initialize:Qlt,getConfig:Z_,setConfig:X_,getSiteConfig:Y_,updateSiteConfig:J_,reset:V(()=>{ev()},`reset`),globalReset:V(()=>{ev(z_)},`globalReset`),defaultConfig:z_}),xd(Z_().logLevel),ev(Z_()),sdt=V((e,t,n)=>{H.warn(e),oD(e)?(n&&n(e.str,e.hash),t.push({...e,message:e.str,error:e})):(n&&n(e),e instanceof Error&&t.push({str:e.message,message:e.message,hash:e.name,error:e}))},`handleError`),j9=V(async function(e={querySelector:`.mermaid`}){try{await cdt(e)}catch(t){if(oD(t)&&H.error(t.str),R9.parseError&&R9.parseError(t),!e.suppressErrors)throw H.error(`Use the suppressErrors option to suppress these errors`),t}},`run`),cdt=V(async function({postRenderCallback:e,querySelector:t,nodes:n}={querySelector:`.mermaid`}){let r=A9.getConfig();H.debug(`${e?``:`No `}Callback function found`);let i;if(n)i=n;else if(t)i=document.querySelectorAll(t);else throw Error(`Nodes and querySelector are both undefined`);H.debug(`Found ${i.length} diagrams`),r?.startOnLoad!==void 0&&(H.debug(`Start On Load: `+r?.startOnLoad),A9.updateSiteConfig({startOnLoad:r?.startOnLoad}));let a=new yD.InitIDGenerator(r.deterministicIds,r.deterministicIDSeed),o,s=[];for(let t of Array.from(i)){if(H.info(`Rendering diagram: `+t.id),t.getAttribute(`data-processed`))continue;t.setAttribute(`data-processed`,`true`);let n=`mermaid-${a.next()}`;o=t.innerHTML,o=EAe(yD.entityDecode(o)).trim().replace(/<br\s*\/?>/gi,`<br/>`);let r=yD.detectInit(o);r&&H.debug(`Detected early reinit: `,r);try{let{svg:r,bindFunctions:i}=await L9(n,o,t);t.innerHTML=r,e&&await e(n),i&&i(t)}catch(e){sdt(e,s,R9.parseError)}}if(s.length>0)throw s[0]},`runThrowsErrors`),M9=V(function(e){A9.initialize(e)},`initialize`),ldt=V(async function(e,t,n){H.warn(`mermaid.init is deprecated. Please use run instead.`),e&&M9(e);let r={postRenderCallback:n,querySelector:`.mermaid`};typeof t==`string`?r.querySelector=t:t&&(t instanceof HTMLElement?r.nodes=[t]:r.nodes=t),await j9(r)},`init`),udt=V(async(e,{lazyLoad:t=!0}={})=>{w9(),n_(...e),t===!1&&await Nut()},`registerExternalDiagrams`),N9=V(function(){if(R9.startOnLoad){let{startOnLoad:e}=A9.getConfig();e&&R9.run().catch(e=>H.error(`Mermaid failed to initialize`,e))}},`contentLoaded`),typeof document<`u`&&window.addEventListener(`load`,N9,!1),ddt=V(function(e){R9.parseError=e},`setParseErrorHandler`),P9=[],F9=!1,I9=V(async()=>{if(!F9){for(F9=!0;P9.length>0;){let e=P9.shift();if(e)try{await e()}catch(e){H.error(`Error executing queue`,e)}}F9=!1}},`executeQueue`),fdt=V(async(e,t)=>new Promise((n,r)=>{let i=V(()=>new Promise((i,a)=>{A9.parse(e,t).then(e=>{i(e),n(e)},e=>{H.error(`Error parsing`,e),R9.parseError?.(e),a(e),r(e)})}),`performCall`);P9.push(i),I9().catch(r)}),`parse`),L9=V((e,t,n)=>new Promise((r,i)=>{let a=V(()=>new Promise((a,o)=>{A9.render(e,t,n).then(e=>{a(e),r(e)},e=>{H.error(`Error parsing`,e),R9.parseError?.(e),o(e),i(e)})}),`performCall`);P9.push(a),I9().catch(i)}),`render`),R9={startOnLoad:!0,mermaidAPI:A9,parse:fdt,render:L9,init:ldt,run:j9,registerExternalDiagrams:udt,registerLayoutLoaders:xW,initialize:M9,parseError:void 0,contentLoaded:N9,setParseErrorHandler:ddt,detectType:t_,registerIconPacks:NO,getRegisteredDiagramsMetadata:V(()=>Object.keys(e_).map(e=>({id:e})),`getRegisteredDiagramsMetadata`)},pdt=R9}));ed();function z9(e){if(typeof e==`string`)return hdt(e);if(Array.isArray(e))return e.length===0?B9(`*Empty array*`):typeof e[0]==`object`&&e[0]!==null?H9(e):B9(e.map(e=>`- ${String(e)}`).join(`
|
|
3750
|
-
`));if(typeof e==`object`&&e){let t=e;return Array.isArray(t.nodes)&&Array.isArray(t.edges)?Edt(t):Array.isArray(t.metrics)?Tdt(t.metrics):U9(t)}return B9(String(e))}function hdt(e){let t=e.trim();if(/^(graph|flowchart|sequenceDiagram|classDiagram|stateDiagram|erDiagram|gantt|pie|gitGraph)\b/i.test(t))return V9(t);if(/^#{1,6}\s|^\s*[-*]\s|\*\*|__|\[.*\]\(|```/.test(t))return B9(t);if((t.startsWith(`{`)||t.startsWith(`[`))&&(t.endsWith(`}`)||t.endsWith(`]`)))try{return z9(JSON.parse(t))}catch{}return B9(t)}function gdt(e,t,n){let r=B(`div`,`comparison-side ${n}`),i=e&&typeof e==`object`&&!Array.isArray(e)?e:null,a=String(i?.label??i?.title??t),o=Array.isArray(i?.items)?i.items:Array.isArray(e)?e:e==null?[]:[e];r.appendChild(B(`div`,`comparison-label`,a));let s=B(`ul`,`comparison-items`);for(let e of o)s.appendChild(B(`li`,``,od(e)));return r.appendChild(s),r}function _dt(e){let t=B(`div`,`actions`);for(let n of e){if(n.type===`select`&&n.options){let e=document.createElement(`select`);e.className=`action-select`;let r=document.createElement(`option`);r.textContent=n.label,r.disabled=!0,r.selected=!0,e.appendChild(r);for(let t of n.options){let n=document.createElement(`option`);typeof t==`string`?(n.value=t,n.textContent=t):(n.value=t.value,n.textContent=t.label),e.appendChild(n)}t.appendChild(e);continue}let e=document.createElement(`button`);e.className=`action-btn ${n.variant??`default`}`,e.textContent=n.label,t.appendChild(e)}return t}function vdt(e,t){switch(e.type){case`markdown`:return B9(String(e.value??``));case`mermaid`:return V9(String(e.value??``));case`table`:{let t=e.value;if(Array.isArray(t)){if(t.length>0&&Array.isArray(t[0])){let e=t,n=e[0].map(String);return H9(e.slice(1).map(e=>Object.fromEntries(n.map((t,n)=>[t,e[n]]))))}return H9(t)}if(t&&typeof t==`object`&&`headers`in t&&`rows`in t){let{headers:e,rows:n}=t;return H9(n.map(t=>Object.fromEntries(e.map((e,n)=>[e,t[n]]))))}return H9([])}case`code`:return Cdt(String(e.value??``),e.language);case`tree`:return U9(e.value);case`cards`:return wdt(e.value);case`metrics`:return Tdt(e.value);case`graph`:return Edt(e.value);case`chart`:return xce(e);case`kv`:{let t=e.value;return t&&typeof t==`object`&&!Array.isArray(t)?H9(Object.entries(t).map(([e,t])=>({Key:e,Value:t}))):B9(JSON.stringify(t,null,2))}case`comparison`:{let t=e.value;if(t&&typeof t==`object`&&!Array.isArray(t)){let e=t;if(`left`in e||`right`in e){let t=B(`div`,`block block-comparison`);return t.appendChild(gdt(e.left,`Left`,`comparison-left`)),t.appendChild(gdt(e.right,`Right`,`comparison-right`)),t}if(Array.isArray(e.headers)&&Array.isArray(e.rows)){let t=e.headers;return H9(e.rows.map(e=>Object.fromEntries(t.map((t,n)=>[t,e[n]]))))}if(Array.isArray(e.columns)){let t=e.columns,n=Math.max(...t.map(e=>e.items?.length??0)),r=[];for(let e=0;e<n;e++){let n={};for(let r of t)n[r.name]=r.items?.[e]??``;r.push(n)}return H9(r)}}return B9(JSON.stringify(t,null,2))}case`actions`:{let n=Array.isArray(e.value)?e.value:[],r=t?Ddt(n,t):_dt(n);return r.classList.add(`block`,`block-actions`),r}case`timeline`:{let t=e.value;return Array.isArray(t)?H9(t.map(e=>{if(e&&typeof e==`object`){let t=e;return{Status:t.status??t.state??``,Time:t.time??t.date??t.timestamp??``,Description:t.label??t.description??t.title??t.text??``}}return{Status:``,Time:``,Description:String(e)}})):B9(JSON.stringify(t,null,2))}case`heading`:return B9(`## ${String(e.value??``)}`);case`checklist`:{let t=Array.isArray(e.value)?e.value:e.value?.items;if(!Array.isArray(t))return B9(JSON.stringify(e.value,null,2));let n=B(`div`,`block block-checklist`);for(let e of t){let t=B(`div`,`checklist-item ${e.checked?`checked`:``}`),r=B(`div`,`checklist-check ${e.checked?`checked`:``}`,e.checked?`✓`:``),i=B(`div`,``);i.appendChild(B(`div`,`checklist-label`,String(e.label??``))),e.note&&i.appendChild(B(`div`,`checklist-note`,String(e.note))),t.appendChild(r),t.appendChild(i),n.appendChild(t)}return n}case`status-board`:{let t=e.value,n=[];if(Array.isArray(t))for(let e of t)if(Array.isArray(e.items)){let t=e.category?.trim();for(let r of e.items)n.push({...r,label:t?`${t}: ${r.label}`:r.label})}else n.push(e);else t&&typeof t==`object`&&Array.isArray(t.items)&&n.push(...t.items);if(n.length===0)return B9(JSON.stringify(e.value,null,2));let r=B(`div`,`block block-status-board`);for(let e of n){let t=B(`div`,`status-row`);t.appendChild(B(`div`,`status-indicator ${e.status??`pending`}`,``)),t.appendChild(B(`span`,`status-label`,String(e.label??``))),e.detail&&t.appendChild(B(`span`,`status-detail`,String(e.detail))),r.appendChild(t)}return r}case`prompt`:{let t=e.value;if(!t?.question)return B9(JSON.stringify(e.value,null,2));let n=B(`div`,`block block-prompt prompt-block`);return n.appendChild(B(`div`,`prompt-question`,String(t.question))),t.context&&n.appendChild(B(`div`,`prompt-context`,String(t.context))),t.placeholder&&n.appendChild(B(`div`,`prompt-placeholder`,String(t.placeholder))),n}case`progress`:{let t;if(Array.isArray(e.value))t=e.value;else if(e.value&&typeof e.value==`object`){let n=e.value;t=Array.isArray(n.items)?n.items:[n]}else return B9(JSON.stringify(e.value,null,2));let n=B(`div`,`block block-progress progress-list`);for(let e of t){let t=typeof e.max==`number`?e.max:100,r=typeof e.value==`number`?e.value:0,i=t>0?Math.min(100,r/t*100):0,a=(typeof e.color==`string`?e.color:``)||(i>=100?`var(--success, #22c55e)`:i>=60?`var(--primary, #818cf8)`:i>=30?`var(--warning, #f59e0b)`:`var(--error, #ef4444)`),o=B(`div`,`progress-item`),s=B(`div`,`progress-header`);s.appendChild(B(`span`,`progress-label`,String(e.label??``))),s.appendChild(B(`span`,`progress-value`,`${r}/${t}`)),o.appendChild(s);let l=B(`div`,`progress-track`),u=B(`div`,`progress-fill`);u.style.width=`${i.toFixed(1)}%`,u.style.background=a,l.appendChild(u),o.appendChild(l),n.appendChild(o)}return n}case`viewer-link`:{let t=e.value,n=(typeof t.label==`string`?t.label.trim():``)||(typeof t.viewerType==`string`?t.viewerType.trim():``)||`Open viewer`,r=typeof t.description==`string`?t.description.trim():``,i=typeof t.icon==`string`&&t.icon.trim()||`🔗`,a=B(`div`,`block block-viewer-link`);a.style.borderLeft=`4px solid var(--color-primary, #818cf8)`,a.style.padding=`12px 16px`,a.style.borderRadius=`8px`,a.style.background=`var(--color-card, #1e293b)`;let o=B(`div`,``,`${i} ${n}`);if(o.style.fontWeight=`600`,a.appendChild(o),r){let e=B(`div`,``,r);e.style.fontSize=`0.85rem`,e.style.color=`var(--color-muted, #94a3b8)`,a.appendChild(e)}if(t?.url){let e=String(t.url).trim();if(/^https?:\/\//i.test(e)||/^file:\/\//i.test(e)){let t=document.createElement(`a`);return t.href=e,t.target=`_blank`,t.rel=`noopener noreferrer`,t.style.color=`inherit`,t.style.textDecoration=`none`,t.appendChild(a.cloneNode(!0)),t}}return a}case`docs-browser`:{let t=e.value,n=Array.isArray(t?.files)?t.files:[],r=B(`div`,`block block-docs-browser`);r.style.border=`1px solid var(--color-border, #334155)`,r.style.borderRadius=`8px`,r.style.overflow=`hidden`;let i=typeof t.title==`string`?t.title.trim():``;if(i){let e=B(`div`,``,i);e.style.padding=`12px`,e.style.fontWeight=`600`,r.appendChild(e)}if(n.length===0)return r.appendChild(B(`div`,``,`No documentation files.`)),r;for(let[e,t]of n.entries()){let n=document.createElement(`details`);e===0&&(n.open=!0);let i=document.createElement(`summary`);i.style.cssText=`padding:8px 12px; cursor:pointer; display:flex; align-items:center; justify-content:space-between; gap:12px;`;let a=t?.path?.trim()||`document-${e+1}`,o=t?.title?.trim()||a.split(/[\\/]/).pop()||a,s=B(`div`,``);s.appendChild(B(`span`,``,a));let l=s.firstElementChild;l instanceof HTMLElement&&(l.style.cssText=`font-family:monospace; font-size:0.85rem; color:var(--color-muted, #94a3b8);`);let u=B(`span`,``,o);if(u.style.fontWeight=`600`,s.appendChild(u),i.appendChild(s),t?.status){let e=B(`span`,``,t.status),n={current:`background:#14532d; color:#bbf7d0;`,stale:`background:#713f12; color:#fde68a;`,missing:`background:#7f1d1d; color:#fecaca;`};e.style.cssText=`padding:2px 8px; border-radius:999px; font-size:0.75rem; text-transform:uppercase; ${n[t.status]||``}`,i.appendChild(e)}n.appendChild(i);let d=B(`div`,``);d.style.cssText=`padding:12px; border-top:1px solid var(--color-border, #334155);`,t?.content?.trim()?d.appendChild(B9(t.content)):d.appendChild(B(`div`,``,`No content available.`)),n.appendChild(d),r.appendChild(n)}return r}case`text`:return B9(String(e.value??``));case`paragraph`:{let t=document.createElement(`p`);return t.textContent=String(e.value??``),t.classList.add(`block`,`block-paragraph`),t}case`separator`:{let e=document.createElement(`hr`);return e.classList.add(`block`,`block-separator`),e}default:return B9(JSON.stringify(e.value,null,2))}}function ydt(e,t){let n=vdt(e,t);return e.title&&n.insertBefore(B(`div`,`block-title`,e.title),n.firstChild),n}function B9(e){let t=B(`div`,`block block-markdown`);return t.innerHTML=uce(e),t}var bdt=null;function xdt(){return bdt||=$u(()=>Promise.resolve().then(()=>(mdt(),Klt)).then(e=>(e.default.initialize({startOnLoad:!1,theme:`default`}),e.default)),void 0,import.meta.url),bdt}var Sdt=0;function V9(e){let t=B(`div`,`block block-mermaid`),n=B(`pre`,`mermaid-source`,e);t.appendChild(n);let r=`mermaid-${++Sdt}`;return xdt().then(t=>t.render(r,e)).then(({svg:e})=>{t.innerHTML=e}).catch(()=>{n.classList.add(`mermaid-fallback`)}),t}function H9(e){let t=B(`div`,`block block-table`);if(e.length===0)return B9(`*Empty table*`);let n=Object.keys(e[0]),r=-1,i=!0,a=[...e],o=``,s=document.createElement(`input`);s.className=`table-filter`,s.placeholder=`Filter...`,s.addEventListener(`input`,()=>{o=s.value.toLowerCase(),p()}),t.appendChild(s);let l=document.createElement(`table`),u=document.createElement(`thead`),d=document.createElement(`tr`);n.forEach((e,t)=>{let n=document.createElement(`th`);n.textContent=e;let a=B(`span`,`sort-icon`,`⇅`);n.appendChild(a),n.addEventListener(`click`,()=>{r===t?i=!i:(r=t,i=!0),p()}),d.appendChild(n)}),u.appendChild(d),l.appendChild(u);let f=document.createElement(`tbody`);l.appendChild(f),t.appendChild(l);function p(){if(a=[...e],o&&(a=a.filter(e=>n.some(t=>String(e[t]??``).toLowerCase().includes(o)))),r>=0){let e=n[r];a.sort((t,n)=>{let r=String(t[e]??``),a=String(n[e]??``),o=r.localeCompare(a,void 0,{numeric:!0});return i?o:-o})}f.innerHTML=``;for(let e of a){let t=document.createElement(`tr`);for(let r of n){let n=document.createElement(`td`);n.textContent=String(e[r]??``),t.appendChild(n)}f.appendChild(t)}}return p(),t}function Cdt(e,t){let n=B(`div`,`block block-code`),r=B(`div`,`code-header`);r.appendChild(B(`span`,``,t??`code`));let i=document.createElement(`button`);i.className=`copy-btn`,i.textContent=`Copy`,i.addEventListener(`click`,()=>{navigator.clipboard.writeText(e).then(()=>{i.textContent=`Copied!`,setTimeout(()=>{i.textContent=`Copy`},1500)})}),r.appendChild(i),n.appendChild(r);let a=document.createElement(`pre`),o=document.createElement(`code`);return o.textContent=e,a.appendChild(o),n.appendChild(a),n}function U9(e,t=0){let n=B(`div`,t===0?`block block-tree`:``),r=typeof e.name==`string`?e.name:typeof e.label==`string`?e.label:null,i=Array.isArray(e.children)?e.children:null;if(r&&i){if(i.length===0)return B(`div`,`tree-leaf`,`📄 ${r}`);let a=B(`div`,`tree-node`),o=B(`span`,`tree-toggle`,`▼`),s=B(`div`,`tree-children`),l=!0;s.style.display=``,o.addEventListener(`click`,()=>{l=!l,o.textContent=l?`▼`:`▶`,s.style.display=l?``:`none`}),a.appendChild(o),a.appendChild(document.createTextNode(` ${r}`));for(let e of i)typeof e==`object`&&e&&!Array.isArray(e)?s.appendChild(U9(e,t+1)):s.appendChild(B(`div`,`tree-leaf`,`📄 ${od(e)}`));for(let[n,r]of Object.entries(e))if(!(n===`name`||n===`label`||n===`children`))if(typeof r==`object`&&r&&!Array.isArray(r))s.appendChild(U9({[n]:r},t+1));else{let e=B(`div`,`tree-leaf`);e.innerHTML=`<strong>${ad(n)}:</strong> ${ad(od(r))}`,s.appendChild(e)}return a.appendChild(s),n.appendChild(a),n}if(r)return n.appendChild(B(`div`,`tree-leaf`,`📄 ${r}`)),n;for(let[r,i]of Object.entries(e))if(typeof i==`object`&&i&&!Array.isArray(i)){let e=B(`div`,`tree-node`),a=B(`span`,`tree-toggle`,`▼`),o=U9(i,t+1);o.className=`tree-children`;let s=!0;a.addEventListener(`click`,()=>{s=!s,a.textContent=s?`▼`:`▶`,o.style.display=s?``:`none`}),e.appendChild(a),e.appendChild(document.createTextNode(` ${r}`)),e.appendChild(o),n.appendChild(e)}else{let e=B(`div`,`tree-leaf`);e.innerHTML=`<strong>${ad(r)}:</strong> ${ad(od(i))}`,n.appendChild(e)}return n}function wdt(e){let t=B(`div`,`block block-cards`);for(let n of e){let e=B(`div`,`card`);if(n.title&&e.appendChild(B(`div`,`card-title`,String(n.title))),(n.body||n.description)&&e.appendChild(B(`div`,`card-body`,String(n.body??n.description))),n.badge||n.status){let t=String(n.variant??n.status??`default`).toLowerCase(),r=[`success`,`warning`,`error`].includes(t)?t:``;e.appendChild(B(`span`,`card-badge ${r}`,String(n.badge??n.status)))}t.appendChild(e)}return t}function Tdt(e){let t=B(`div`,`block block-metrics`);for(let n of e){let e=B(`div`,`metric`);e.appendChild(B(`div`,`metric-value`,String(n.value))),e.appendChild(B(`div`,`metric-label`,n.label)),t.appendChild(e)}return t}function Edt(e){let t=[`graph LR`],n=new Map;for(let r of e.nodes){let e=String(r.id??r.name??``),i=String(r.label??r.name??e);n.set(e,i),t.push(` ${sd(e)}["${ad(i)}"]`)}for(let n of e.edges){let e=sd(String(n.source??n.from??``)),r=sd(String(n.target??n.to??``)),i=n.label?`|${ad(String(n.label))}|`:``;t.push(` ${e} -->${i} ${r}`)}return V9(t.join(`
|
|
3750
|
+
`));if(typeof e==`object`&&e){let t=e;return Array.isArray(t.nodes)&&Array.isArray(t.edges)?Edt(t):Array.isArray(t.metrics)?Tdt(t.metrics):U9(t)}return B9(String(e))}function hdt(e){let t=e.trim();if(/^(graph|flowchart|sequenceDiagram|classDiagram|stateDiagram|erDiagram|gantt|pie|gitGraph)\b/i.test(t))return V9(t);if(/^#{1,6}\s|^\s*[-*]\s|\*\*|__|\[.*\]\(|```/.test(t))return B9(t);if((t.startsWith(`{`)||t.startsWith(`[`))&&(t.endsWith(`}`)||t.endsWith(`]`)))try{return z9(JSON.parse(t))}catch{}return B9(t)}function gdt(e,t,n){let r=B(`div`,`comparison-side ${n}`),i=e&&typeof e==`object`&&!Array.isArray(e)?e:null,a=String(i?.label??i?.title??t),o=Array.isArray(i?.items)?i.items:Array.isArray(e)?e:e==null?[]:[e];r.appendChild(B(`div`,`comparison-label`,a));let s=B(`ul`,`comparison-items`);for(let e of o)s.appendChild(B(`li`,``,od(e)));return r.appendChild(s),r}function _dt(e){let t=B(`div`,`actions`);for(let n of e){if(n.type===`select`&&n.options){let e=document.createElement(`select`);e.className=`action-select`;let r=document.createElement(`option`);r.textContent=n.label,r.disabled=!0,r.selected=!0,e.appendChild(r);for(let t of n.options){let n=document.createElement(`option`);typeof t==`string`?(n.value=t,n.textContent=t):(n.value=t.value,n.textContent=t.label),e.appendChild(n)}t.appendChild(e);continue}let e=document.createElement(`button`);e.className=`action-btn ${n.variant??`default`}`,e.textContent=n.label,t.appendChild(e)}return t}function vdt(e,t){switch(e.type){case`markdown`:return B9(String(e.value??``));case`mermaid`:return V9(String(e.value??``));case`table`:{let t=e.value;if(Array.isArray(t)){if(t.length>0&&Array.isArray(t[0])){let e=t,n=e[0].map(String);return H9(e.slice(1).map(e=>Object.fromEntries(n.map((t,n)=>[t,e[n]]))))}return H9(t)}if(t&&typeof t==`object`&&`headers`in t&&`rows`in t){let{headers:e,rows:n}=t;return H9(n.map(t=>Object.fromEntries(e.map((e,n)=>[e,t[n]]))))}return H9([])}case`code`:return Cdt(String(e.value??``),e.language);case`tree`:return U9(e.value);case`cards`:return wdt(e.value);case`metrics`:return Tdt(e.value);case`graph`:return Edt(e.value);case`chart`:return xce(e);case`kv`:{let t=e.value;return t&&typeof t==`object`&&!Array.isArray(t)?H9(Object.entries(t).map(([e,t])=>({Key:e,Value:t}))):B9(JSON.stringify(t,null,2))}case`comparison`:{let t=e.value;if(t&&typeof t==`object`&&!Array.isArray(t)){let e=t;if(`left`in e||`right`in e){let t=B(`div`,`block block-comparison`);return t.appendChild(gdt(e.left,`Left`,`comparison-left`)),t.appendChild(gdt(e.right,`Right`,`comparison-right`)),t}if(Array.isArray(e.headers)&&Array.isArray(e.rows)){let t=e.headers;return H9(e.rows.map(e=>Object.fromEntries(t.map((t,n)=>[t,e[n]]))))}if(Array.isArray(e.columns)){let t=e.columns,n=Math.max(...t.map(e=>e.items?.length??0)),r=[];for(let e=0;e<n;e++){let n={};for(let r of t)n[r.name]=r.items?.[e]??``;r.push(n)}return H9(r)}}return B9(JSON.stringify(t,null,2))}case`actions`:{let n=Array.isArray(e.value)?e.value:[],r=t?Ddt(n,t):_dt(n);return r.classList.add(`block`,`block-actions`),r}case`timeline`:{let t=e.value;return Array.isArray(t)?H9(t.map(e=>{if(e&&typeof e==`object`){let t=e;return{Status:t.status??t.state??``,Time:t.time??t.date??t.timestamp??``,Description:t.label??t.description??t.title??t.text??``}}return{Status:``,Time:``,Description:String(e)}})):B9(JSON.stringify(t,null,2))}case`heading`:return B9(`## ${String(e.value??``)}`);case`checklist`:{let t=Array.isArray(e.value)?e.value:e.value?.items;if(!Array.isArray(t))return B9(JSON.stringify(e.value,null,2));let n=B(`div`,`block block-checklist`);for(let e of t){let t=B(`div`,`checklist-item ${e.checked?`checked`:``}`),r=B(`div`,`checklist-check ${e.checked?`checked`:``}`,e.checked?`✓`:``),i=B(`div`,``);i.appendChild(B(`div`,`checklist-label`,String(e.label??``))),e.note&&i.appendChild(B(`div`,`checklist-note`,String(e.note))),t.appendChild(r),t.appendChild(i),n.appendChild(t)}return n}case`status-board`:{let t=e.value,n=[];if(Array.isArray(t))for(let e of t)if(Array.isArray(e.items)){let t=e.category?.trim();for(let r of e.items)n.push({...r,label:t?`${t}: ${r.label}`:r.label})}else n.push(e);else t&&typeof t==`object`&&Array.isArray(t.items)&&n.push(...t.items);if(n.length===0)return B9(JSON.stringify(e.value,null,2));let r=B(`div`,`block block-status-board`);for(let e of n){let t=B(`div`,`status-row`);t.appendChild(B(`div`,`status-indicator ${e.status??`pending`}`,``)),t.appendChild(B(`span`,`status-label`,String(e.label??``))),e.detail&&t.appendChild(B(`span`,`status-detail`,String(e.detail))),r.appendChild(t)}return r}case`prompt`:{let t=e.value;if(!t?.question)return B9(JSON.stringify(e.value,null,2));let n=B(`div`,`block block-prompt prompt-block`);return n.appendChild(B(`div`,`prompt-question`,String(t.question))),t.context&&n.appendChild(B(`div`,`prompt-context`,String(t.context))),t.placeholder&&n.appendChild(B(`div`,`prompt-placeholder`,String(t.placeholder))),n}case`progress`:{let t;if(Array.isArray(e.value))t=e.value;else if(e.value&&typeof e.value==`object`){let n=e.value;t=Array.isArray(n.items)?n.items:[n]}else return B9(JSON.stringify(e.value,null,2));let n=B(`div`,`block block-progress progress-list`);for(let e of t){let t=typeof e.max==`number`?e.max:100,r=typeof e.value==`number`?e.value:0,i=t>0?Math.min(100,r/t*100):0,a=(typeof e.color==`string`?e.color:``)||(i>=100?`var(--success, #22c55e)`:i>=60?`var(--primary, #818cf8)`:i>=30?`var(--warning, #f59e0b)`:`var(--error, #ef4444)`),o=B(`div`,`progress-item`),s=B(`div`,`progress-header`);s.appendChild(B(`span`,`progress-label`,String(e.label??``))),s.appendChild(B(`span`,`progress-value`,`${r}/${t}`)),o.appendChild(s);let l=B(`div`,`progress-track`),u=B(`div`,`progress-fill`);u.style.width=`${i.toFixed(1)}%`,u.style.background=a,l.appendChild(u),o.appendChild(l),n.appendChild(o)}return n}case`docs-browser`:{let t=e.value,n=Array.isArray(t?.files)?t.files:[],r=B(`div`,`block block-docs-browser`);r.style.border=`1px solid var(--color-border, #334155)`,r.style.borderRadius=`8px`,r.style.overflow=`hidden`;let i=typeof t.title==`string`?t.title.trim():``;if(i){let e=B(`div`,``,i);e.style.padding=`12px`,e.style.fontWeight=`600`,r.appendChild(e)}if(n.length===0)return r.appendChild(B(`div`,``,`No documentation files.`)),r;for(let[e,t]of n.entries()){let n=document.createElement(`details`);e===0&&(n.open=!0);let i=document.createElement(`summary`);i.style.cssText=`padding:8px 12px; cursor:pointer; display:flex; align-items:center; justify-content:space-between; gap:12px;`;let a=t?.path?.trim()||`document-${e+1}`,o=t?.title?.trim()||a.split(/[\\/]/).pop()||a,s=B(`div`,``);s.appendChild(B(`span`,``,a));let l=s.firstElementChild;l instanceof HTMLElement&&(l.style.cssText=`font-family:monospace; font-size:0.85rem; color:var(--color-muted, #94a3b8);`);let u=B(`span`,``,o);if(u.style.fontWeight=`600`,s.appendChild(u),i.appendChild(s),t?.status){let e=B(`span`,``,t.status),n={current:`background:#14532d; color:#bbf7d0;`,stale:`background:#713f12; color:#fde68a;`,missing:`background:#7f1d1d; color:#fecaca;`};e.style.cssText=`padding:2px 8px; border-radius:999px; font-size:0.75rem; text-transform:uppercase; ${n[t.status]||``}`,i.appendChild(e)}n.appendChild(i);let d=B(`div`,``);d.style.cssText=`padding:12px; border-top:1px solid var(--color-border, #334155);`,t?.content?.trim()?d.appendChild(B9(t.content)):d.appendChild(B(`div`,``,`No content available.`)),n.appendChild(d),r.appendChild(n)}return r}case`text`:return B9(String(e.value??``));case`paragraph`:{let t=document.createElement(`p`);return t.textContent=String(e.value??``),t.classList.add(`block`,`block-paragraph`),t}case`separator`:{let e=document.createElement(`hr`);return e.classList.add(`block`,`block-separator`),e}default:return B9(JSON.stringify(e.value,null,2))}}function ydt(e,t){let n=vdt(e,t);return e.title&&n.insertBefore(B(`div`,`block-title`,e.title),n.firstChild),n}function B9(e){let t=B(`div`,`block block-markdown`);return t.innerHTML=uce(e),t}var bdt=null;function xdt(){return bdt||=$u(()=>Promise.resolve().then(()=>(mdt(),Klt)).then(e=>(e.default.initialize({startOnLoad:!1,theme:`default`}),e.default)),void 0,import.meta.url),bdt}var Sdt=0;function V9(e){let t=B(`div`,`block block-mermaid`),n=B(`pre`,`mermaid-source`,e);t.appendChild(n);let r=`mermaid-${++Sdt}`;return xdt().then(t=>t.render(r,e)).then(({svg:e})=>{t.innerHTML=e}).catch(()=>{n.classList.add(`mermaid-fallback`)}),t}function H9(e){let t=B(`div`,`block block-table`);if(e.length===0)return B9(`*Empty table*`);let n=Object.keys(e[0]),r=-1,i=!0,a=[...e],o=``,s=document.createElement(`input`);s.className=`table-filter`,s.placeholder=`Filter...`,s.addEventListener(`input`,()=>{o=s.value.toLowerCase(),p()}),t.appendChild(s);let l=document.createElement(`table`),u=document.createElement(`thead`),d=document.createElement(`tr`);n.forEach((e,t)=>{let n=document.createElement(`th`);n.textContent=e;let a=B(`span`,`sort-icon`,`⇅`);n.appendChild(a),n.addEventListener(`click`,()=>{r===t?i=!i:(r=t,i=!0),p()}),d.appendChild(n)}),u.appendChild(d),l.appendChild(u);let f=document.createElement(`tbody`);l.appendChild(f),t.appendChild(l);function p(){if(a=[...e],o&&(a=a.filter(e=>n.some(t=>String(e[t]??``).toLowerCase().includes(o)))),r>=0){let e=n[r];a.sort((t,n)=>{let r=String(t[e]??``),a=String(n[e]??``),o=r.localeCompare(a,void 0,{numeric:!0});return i?o:-o})}f.innerHTML=``;for(let e of a){let t=document.createElement(`tr`);for(let r of n){let n=document.createElement(`td`);n.textContent=String(e[r]??``),t.appendChild(n)}f.appendChild(t)}}return p(),t}function Cdt(e,t){let n=B(`div`,`block block-code`),r=B(`div`,`code-header`);r.appendChild(B(`span`,``,t??`code`));let i=document.createElement(`button`);i.className=`copy-btn`,i.textContent=`Copy`,i.addEventListener(`click`,()=>{navigator.clipboard.writeText(e).then(()=>{i.textContent=`Copied!`,setTimeout(()=>{i.textContent=`Copy`},1500)})}),r.appendChild(i),n.appendChild(r);let a=document.createElement(`pre`),o=document.createElement(`code`);return o.textContent=e,a.appendChild(o),n.appendChild(a),n}function U9(e,t=0){let n=B(`div`,t===0?`block block-tree`:``),r=typeof e.name==`string`?e.name:typeof e.label==`string`?e.label:null,i=Array.isArray(e.children)?e.children:null;if(r&&i){if(i.length===0)return B(`div`,`tree-leaf`,`📄 ${r}`);let a=B(`div`,`tree-node`),o=B(`span`,`tree-toggle`,`▼`),s=B(`div`,`tree-children`),l=!0;s.style.display=``,o.addEventListener(`click`,()=>{l=!l,o.textContent=l?`▼`:`▶`,s.style.display=l?``:`none`}),a.appendChild(o),a.appendChild(document.createTextNode(` ${r}`));for(let e of i)typeof e==`object`&&e&&!Array.isArray(e)?s.appendChild(U9(e,t+1)):s.appendChild(B(`div`,`tree-leaf`,`📄 ${od(e)}`));for(let[n,r]of Object.entries(e))if(!(n===`name`||n===`label`||n===`children`))if(typeof r==`object`&&r&&!Array.isArray(r))s.appendChild(U9({[n]:r},t+1));else{let e=B(`div`,`tree-leaf`);e.innerHTML=`<strong>${ad(n)}:</strong> ${ad(od(r))}`,s.appendChild(e)}return a.appendChild(s),n.appendChild(a),n}if(r)return n.appendChild(B(`div`,`tree-leaf`,`📄 ${r}`)),n;for(let[r,i]of Object.entries(e))if(typeof i==`object`&&i&&!Array.isArray(i)){let e=B(`div`,`tree-node`),a=B(`span`,`tree-toggle`,`▼`),o=U9(i,t+1);o.className=`tree-children`;let s=!0;a.addEventListener(`click`,()=>{s=!s,a.textContent=s?`▼`:`▶`,o.style.display=s?``:`none`}),e.appendChild(a),e.appendChild(document.createTextNode(` ${r}`)),e.appendChild(o),n.appendChild(e)}else{let e=B(`div`,`tree-leaf`);e.innerHTML=`<strong>${ad(r)}:</strong> ${ad(od(i))}`,n.appendChild(e)}return n}function wdt(e){let t=B(`div`,`block block-cards`);for(let n of e){let e=B(`div`,`card`);if(n.title&&e.appendChild(B(`div`,`card-title`,String(n.title))),(n.body||n.description)&&e.appendChild(B(`div`,`card-body`,String(n.body??n.description))),n.badge||n.status){let t=String(n.variant??n.status??`default`).toLowerCase(),r=[`success`,`warning`,`error`].includes(t)?t:``;e.appendChild(B(`span`,`card-badge ${r}`,String(n.badge??n.status)))}t.appendChild(e)}return t}function Tdt(e){let t=B(`div`,`block block-metrics`);for(let n of e){let e=B(`div`,`metric`);e.appendChild(B(`div`,`metric-value`,String(n.value))),e.appendChild(B(`div`,`metric-label`,n.label)),t.appendChild(e)}return t}function Edt(e){let t=[`graph LR`],n=new Map;for(let r of e.nodes){let e=String(r.id??r.name??``),i=String(r.label??r.name??e);n.set(e,i),t.push(` ${sd(e)}["${ad(i)}"]`)}for(let n of e.edges){let e=sd(String(n.source??n.from??``)),r=sd(String(n.target??n.to??``)),i=n.label?`|${ad(String(n.label))}|`:``;t.push(` ${e} -->${i} ${r}`)}return V9(t.join(`
|
|
3751
3751
|
`))}function Ddt(e,t){let n=B(`div`,`actions`);for(let r of e)if(r.type===`select`&&r.options){let e=document.createElement(`select`);e.className=`action-select`;let i=document.createElement(`option`);i.textContent=r.label,i.disabled=!0,i.selected=!0,e.appendChild(i);for(let t of r.options){let n=document.createElement(`option`);typeof t==`string`?(n.value=t,n.textContent=t):(n.value=t.value,n.textContent=t.label),e.appendChild(n)}e.addEventListener(`change`,()=>{t.emitAction(r,e.value)}),n.appendChild(e)}else{let e=document.createElement(`button`);e.className=`action-btn ${r.variant??`default`}`,e.textContent=r.label,e.addEventListener(`click`,()=>t.emitAction(r)),n.appendChild(e)}return n}function Odt(){if(typeof document<`u`){let e=document.createElement(`style`);e.textContent=`
|
|
3752
3752
|
.checklist-item { display: flex; align-items: flex-start; gap: 8px; padding: 6px 0; }
|
|
3753
3753
|
.checklist-check { width: 20px; height: 20px; border-radius: 4px; border: 2px solid var(--color-border, #334155); display: flex; align-items: center; justify-content: center; flex-shrink: 0; font-size: 0.75rem; }
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{t as e}from"./curated-manager-BkSgtNC2.js";import{readFileSync as t}from"node:fs";import{dirname as n,resolve as r}from"node:path";import{fileURLToPath as i,pathToFileURL as a}from"node:url";import{parseArgs as o}from"node:util";import{createLogger as s,serializeError as c}from"../../core/dist/index.js";const l=n(i(import.meta.url)),u=(()=>{try{let e=r(l,`..`,`..`,`..`,`package.json`);return JSON.parse(t(e,`utf-8`)).version??`0.0.0`}catch{return`0.0.0`}})(),d=s(`server`);function f(){return process.env.AIKIT_TRANSPORT?process.env.AIKIT_TRANSPORT:process.stdin.isTTY?`http`:`stdio`}const{values:p}=(()=>{let e=process.argv[1];if(!e)return!1;try{return import.meta.url===a(e).href}catch{return!1}})()?o({allowPositionals:!0,options:{transport:{type:`string`,default:f()},port:{type:`string`,default:process.env.AIKIT_PORT??`3210`}}}):{values:{transport:f(),port:process.env.AIKIT_PORT??`3210`}};async function m(){if(process.on(`unhandledRejection`,e=>{d.error(`Unhandled rejection`,c(e))}),d.info(`Starting MCP AI Kit server`,{version:u}),p.transport===`http`){let[{default:e},{loadConfig:t,resolveIndexMode:n},{registerDashboardRoutes:r,resolveDashboardDir:i},{registerSettingsRoutes:a,resolveSettingsDir:o},{createSettingsRouter:s}]=await Promise.all([import(`express`),import(`./config-D4z6-EcI.js`),import(`./dashboard-static-BfIe0Si1.js`),import(`./settings-static-BosGZSPf.js`),import(`./routes-OaSHcA6x.js`)]),l=t();d.info(`Config loaded`,{sourceCount:l.sources.length,storePath:l.store.path});let u=e();u.use(e.json());let f=Number(p.port);u.use((e,t,n)=>{if(t.setHeader(`Access-Control-Allow-Origin`,process.env.AIKIT_CORS_ORIGIN??`http://localhost:${f}`),t.setHeader(`Access-Control-Allow-Methods`,`GET, POST, PUT, PATCH, DELETE, OPTIONS`),t.setHeader(`Access-Control-Allow-Headers`,`Content-Type, Authorization`),e.method===`OPTIONS`){t.status(204).end();return}n()}),r(u,i(),d);let m=new Date().toISOString();u.use(`/settings/api`,s({log:d,mcpInfo:()=>({transport:`http`,port:f,pid:process.pid,startedAt:m})})),a(u,o(),d),u.get(`/health`,(e,t)=>{t.json({status:`ok`})});let h=!1,g=null,_=null,v=null,y=Promise.resolve();u.post(`/mcp`,async(e,t)=>{if(!h||!_||!v){t.status(503).json({jsonrpc:`2.0`,error:{code:-32603,message:`Server initializing — please retry in a few seconds`},id:null});return}let n=y,r;y=new Promise(e=>{r=e}),await n;try{let n=new v({sessionIdGenerator:void 0});await _.connect(n),await n.handleRequest(e,t,e.body),n.close()}catch(e){if(d.error(`MCP handler error`,c(e)),!t.headersSent){let n=e instanceof Error?e.message:String(e),r=n.includes(`Not Acceptable`);t.status(r?406:500).json({jsonrpc:`2.0`,error:{code:r?-32e3:-32603,message:r?n:`Internal server error`},id:null})}}finally{r()}}),u.get(`/mcp`,(e,t)=>{t.writeHead(405).end(JSON.stringify({jsonrpc:`2.0`,error:{code:-32e3,message:`Method not allowed.`},id:null}))}),u.delete(`/mcp`,(e,t)=>{t.writeHead(405).end(JSON.stringify({jsonrpc:`2.0`,error:{code:-32e3,message:`Method not allowed.`},id:null}))});let b=u.listen(f,`127.0.0.1`,()=>{d.info(`MCP server listening`,{url:`http://127.0.0.1:${f}/mcp`,port:f}),setTimeout(async()=>{try{let[{createLazyServer:e,ALL_TOOL_NAMES:t},{StreamableHTTPServerTransport:r},{checkForUpdates:i,autoUpgradeScaffold:a}]=await Promise.all([import(`./server-
|
|
1
|
+
import{t as e}from"./curated-manager-BkSgtNC2.js";import{readFileSync as t}from"node:fs";import{dirname as n,resolve as r}from"node:path";import{fileURLToPath as i,pathToFileURL as a}from"node:url";import{parseArgs as o}from"node:util";import{createLogger as s,serializeError as c}from"../../core/dist/index.js";const l=n(i(import.meta.url)),u=(()=>{try{let e=r(l,`..`,`..`,`..`,`package.json`);return JSON.parse(t(e,`utf-8`)).version??`0.0.0`}catch{return`0.0.0`}})(),d=s(`server`);function f(){return process.env.AIKIT_TRANSPORT?process.env.AIKIT_TRANSPORT:process.stdin.isTTY?`http`:`stdio`}const{values:p}=(()=>{let e=process.argv[1];if(!e)return!1;try{return import.meta.url===a(e).href}catch{return!1}})()?o({allowPositionals:!0,options:{transport:{type:`string`,default:f()},port:{type:`string`,default:process.env.AIKIT_PORT??`3210`}}}):{values:{transport:f(),port:process.env.AIKIT_PORT??`3210`}};async function m(){if(process.on(`unhandledRejection`,e=>{d.error(`Unhandled rejection`,c(e))}),d.info(`Starting MCP AI Kit server`,{version:u}),p.transport===`http`){let[{default:e},{loadConfig:t,resolveIndexMode:n},{registerDashboardRoutes:r,resolveDashboardDir:i},{registerSettingsRoutes:a,resolveSettingsDir:o},{createSettingsRouter:s}]=await Promise.all([import(`express`),import(`./config-D4z6-EcI.js`),import(`./dashboard-static-BfIe0Si1.js`),import(`./settings-static-BosGZSPf.js`),import(`./routes-OaSHcA6x.js`)]),l=t();d.info(`Config loaded`,{sourceCount:l.sources.length,storePath:l.store.path});let u=e();u.use(e.json());let f=Number(p.port);u.use((e,t,n)=>{if(t.setHeader(`Access-Control-Allow-Origin`,process.env.AIKIT_CORS_ORIGIN??`http://localhost:${f}`),t.setHeader(`Access-Control-Allow-Methods`,`GET, POST, PUT, PATCH, DELETE, OPTIONS`),t.setHeader(`Access-Control-Allow-Headers`,`Content-Type, Authorization`),e.method===`OPTIONS`){t.status(204).end();return}n()}),r(u,i(),d);let m=new Date().toISOString();u.use(`/settings/api`,s({log:d,mcpInfo:()=>({transport:`http`,port:f,pid:process.pid,startedAt:m})})),a(u,o(),d),u.get(`/health`,(e,t)=>{t.json({status:`ok`})});let h=!1,g=null,_=null,v=null,y=Promise.resolve();u.post(`/mcp`,async(e,t)=>{if(!h||!_||!v){t.status(503).json({jsonrpc:`2.0`,error:{code:-32603,message:`Server initializing — please retry in a few seconds`},id:null});return}let n=y,r;y=new Promise(e=>{r=e}),await n;try{let n=new v({sessionIdGenerator:void 0});await _.connect(n),await n.handleRequest(e,t,e.body),n.close()}catch(e){if(d.error(`MCP handler error`,c(e)),!t.headersSent){let n=e instanceof Error?e.message:String(e),r=n.includes(`Not Acceptable`);t.status(r?406:500).json({jsonrpc:`2.0`,error:{code:r?-32e3:-32603,message:r?n:`Internal server error`},id:null})}}finally{r()}}),u.get(`/mcp`,(e,t)=>{t.writeHead(405).end(JSON.stringify({jsonrpc:`2.0`,error:{code:-32e3,message:`Method not allowed.`},id:null}))}),u.delete(`/mcp`,(e,t)=>{t.writeHead(405).end(JSON.stringify({jsonrpc:`2.0`,error:{code:-32e3,message:`Method not allowed.`},id:null}))});let b=u.listen(f,`127.0.0.1`,()=>{d.info(`MCP server listening`,{url:`http://127.0.0.1:${f}/mcp`,port:f}),setTimeout(async()=>{try{let[{createLazyServer:e,ALL_TOOL_NAMES:t},{StreamableHTTPServerTransport:r},{checkForUpdates:i,autoUpgradeScaffold:a}]=await Promise.all([import(`./server-DaSl8hat.js`),import(`@modelcontextprotocol/sdk/server/streamableHttp.js`),import(`./version-check-Bj07vc5x.js`)]);i(),a();let o=n(l),s=e(l,o);_=s.server,v=r,h=!0,d.info(`MCP server configured (lazy — AI Kit initializing in background)`,{toolCount:t.length,resourceCount:2}),s.startInit(),o===`auto`?s.ready.then(async()=>{try{let e=l.sources.map(e=>e.path).join(`, `);d.info(`Running initial index`,{sourcePaths:e}),await s.runInitialIndex(),d.info(`Initial index complete`)}catch(e){d.error(`Initial index failed; will retry on aikit_reindex`,c(e))}}).catch(e=>d.error(`AI Kit init or indexing failed`,c(e))):o===`smart`?s.ready.then(async()=>{try{if(!s.aikit)throw Error(`AI Kit components are not available after initialization`);let{SmartIndexScheduler:e}=await import(`../../indexer/dist/index.js`),t=new e(s.aikit.indexer,l,s.aikit.store),n=s.aikit.store;g=t,t.start(),n.onBeforeClose&&n.onBeforeClose(()=>t.stop()),s.setSmartScheduler(t),d.info(`Smart index scheduler started (HTTP mode)`)}catch(e){d.error(`Failed to start smart index scheduler`,c(e))}}).catch(e=>d.error(`AI Kit initialization failed`,c(e))):(s.ready.catch(e=>d.error(`AI Kit initialization failed`,c(e))),d.info(`Initial full indexing skipped in HTTP mode`,{indexMode:o}))}catch(e){d.error(`Failed to load server modules`,c(e))}},100)}),x=async e=>{d.info(`Shutdown signal received`,{signal:e}),g?.stop(),b.close(),_&&await _.close(),process.exit(0)};process.on(`SIGINT`,()=>x(`SIGINT`)),process.on(`SIGTERM`,()=>x(`SIGTERM`))}else{let[{loadConfig:e,reconfigureForWorkspace:t,resolveIndexMode:n},{createLazyServer:r},{checkForUpdates:a,autoUpgradeScaffold:o},{RootsListChangedNotificationSchema:s}]=await Promise.all([import(`./config-D4z6-EcI.js`),import(`./server-DaSl8hat.js`),import(`./version-check-Bj07vc5x.js`),import(`@modelcontextprotocol/sdk/types.js`)]),l=e();d.info(`Config loaded`,{sourceCount:l.sources.length,storePath:l.store.path}),a(),o();let u=n(l),f=r(l,u),{server:p,startInit:m,ready:h,runInitialIndex:g}=f,{StdioServerTransport:_}=await import(`@modelcontextprotocol/sdk/server/stdio.js`),v=new _;await p.connect(v),d.info(`MCP server started`,{transport:`stdio`});let y=e=>{if(e.length===0)return!1;let n=e[0].uri,r=n.startsWith(`file://`)?i(n):n;return d.info(`MCP roots resolved`,{rootUri:n,rootPath:r,rootCount:e.length}),t(l,r),l.allRoots=e.map(e=>{let t=e.uri;return t.startsWith(`file://`)?i(t):t}),!0},b=!1;try{b=y((await p.server.listRoots()).roots),b||d.info(`No MCP roots yet; waiting for roots/list_changed notification`)}catch(e){d.warn(`MCP roots/list not supported by client; using cwd fallback`,{cwd:process.cwd(),...c(e)}),b=!0}b||=await new Promise(e=>{let t=setTimeout(()=>{d.warn(`Timed out waiting for MCP roots/list_changed; using cwd fallback`,{cwd:process.cwd()}),e(!1)},5e3);p.server.setNotificationHandler(s,async()=>{clearTimeout(t);try{e(y((await p.server.listRoots()).roots))}catch(t){d.warn(`roots/list retry failed after notification`,c(t)),e(!1)}})}),m();let x=null,S=()=>{x&&clearTimeout(x),x=setTimeout(()=>{d.info(`Auto-shutdown: no activity for 30 minutes — exiting`),process.exit(0)},18e5),x.unref&&x.unref()};S(),process.stdin.on(`data`,()=>S()),h.catch(e=>{d.error(`Initialization failed — server will continue with limited tools`,c(e))}),u===`auto`?g().catch(e=>d.error(`Initial index failed`,c(e))):u===`smart`?h.then(async()=>{try{if(!f.aikit)throw Error(`AI Kit components are not available after initialization`);let{SmartIndexScheduler:e}=await import(`../../indexer/dist/index.js`),t=new e(f.aikit.indexer,l,f.aikit.store),n=f.aikit.store;t.start(),n.onBeforeClose&&n.onBeforeClose(()=>t.stop()),f.setSmartScheduler(t),d.info(`Smart index scheduler started (stdio mode)`)}catch(e){d.error(`Failed to start smart index scheduler`,c(e))}}).catch(e=>d.error(`AI Kit init failed for smart scheduler`,c(e))):d.warn(`Initial full indexing skipped; use aikit_reindex to index manually`,{indexMode:u})}}m().catch(e=>{d.error(`Fatal error`,c(e)),process.exit(1)});export{e as CuratedKnowledgeManager};
|
|
@@ -226,15 +226,7 @@ Complements: \`symbol\` (single lookup), \`trace\` (call-chain AST), \`blast_rad
|
|
|
226
226
|
`)}]}}}}catch(e){return pc.error(`Checkpoint failed`,j(e)),H(`INTERNAL`,`Checkpoint failed: ${e instanceof Error?e.message:String(e)}`)}})}function _c(e){let t=z(`lane`);e.registerTool(`lane`,{title:t.title,description:`Manage verified lanes — isolated file copies for parallel exploration. Also provides advisory write-intent leases for multi-agent coordination.`,inputSchema:{action:F.enum([`create`,`list`,`status`,`diff`,`merge`,`discard`,`lease`,`unlease`,`leases`]).describe(`Lane action to perform`),name:F.string().optional().describe(`Lane name (required for create/status/diff/merge/discard)`),files:F.array(F.string()).optional().describe(`File paths to copy into the lane (required for create)`),agent:F.string().optional().describe(`Agent identifier (required for lease)`),intent:F.string().optional().describe(`What the agent plans to do (required for lease)`),id:F.string().optional().describe(`Lease ID (required for unlease)`),symbols:F.array(F.string()).optional().describe(`Symbol names within files (optional for lease)`),ttl_minutes:F.number().optional().describe(`Lease TTL in minutes (default 10, optional for lease)`)},annotations:t.annotations},async({action:e,name:t,files:n,agent:r,intent:i,id:a,symbols:o,ttl_minutes:s})=>{try{switch(e){case`create`:{if(!t)throw Error(`name is required for create`);if(!n||n.length===0)throw Error(`files are required for create`);let e=We(t,n);return{content:[{type:`text`,text:JSON.stringify(e)}]}}case`list`:return{content:[{type:`text`,text:JSON.stringify(qe())}]};case`status`:if(!t)throw Error(`name is required for status`);return{content:[{type:`text`,text:JSON.stringify(Ye(t))}]};case`diff`:if(!t)throw Error(`name is required for diff`);return{content:[{type:`text`,text:JSON.stringify(Ge(t))}]};case`merge`:if(!t)throw Error(`name is required for merge`);return{content:[{type:`text`,text:JSON.stringify(Je(t))}]};case`discard`:if(!t)throw Error(`name is required for discard`);return{content:[{type:`text`,text:JSON.stringify({discarded:Ke(t)})}]};case`lease`:{if(!r)throw Error(`agent is required for lease`);if(!n||n.length===0)throw Error(`files are required for lease`);if(!i)throw Error(`intent is required for lease`);let e=ie({agent:r,files:n,intent:i,symbols:o,ttl_minutes:s});return{content:[{type:`text`,text:JSON.stringify(e)}]}}case`unlease`:{if(!a)throw Error(`id is required for unlease`);let e=vt({id:a});return{content:[{type:`text`,text:JSON.stringify(e)}]}}case`leases`:{let e=Xe({agent:r});return{content:[{type:`text`,text:JSON.stringify(e)}]}}}}catch(e){return pc.error(`Lane action failed`,j(e)),H(`INTERNAL`,`Lane action failed: ${e instanceof Error?e.message:String(e)}`)}})}function vc(e){let t=z(`queue`);e.registerTool(`queue`,{title:t.title,description:`Manage task queues with optional DAG dependencies. Push items with dependsOn for wave-based execution. Take next, mark done/failed, list queues.`,inputSchema:{action:F.enum([`create`,`push`,`next`,`done`,`fail`,`get`,`list`,`clear`,`delete`,`dag`]).describe(`Queue action`),name:F.string().optional().describe(`Queue name (required for most actions)`),title:F.string().optional().describe(`Item title (required for push)`),id:F.string().optional().describe(`Item ID (required for done/fail)`),data:F.unknown().optional().describe(`Arbitrary data to attach to a queue item`),error:F.string().optional().describe(`Error message (required for fail)`),dependsOn:F.array(F.string()).optional().describe(`Item IDs this task depends on. Dependent items start as blocked until deps complete.`)},annotations:t.annotations},async({action:e,name:t,title:n,id:r,data:i,error:a,dependsOn:o})=>{try{switch(e){case`create`:if(!t)throw Error(`name is required for create`);return{content:[{type:`text`,text:JSON.stringify(ct(t))}]};case`push`:if(!t)throw Error(`name is required for push`);if(!n)throw Error(`title is required for push`);return{content:[{type:`text`,text:JSON.stringify(gt(t,n,i,void 0,o))}]};case`next`:{if(!t)throw Error(`name is required for next`);let e=ht(t);return{content:[{type:`text`,text:JSON.stringify(e)}]}}case`done`:if(!t)throw Error(`name is required for done`);if(!r)throw Error(`id is required for done`);return{content:[{type:`text`,text:JSON.stringify(dt(t,r))}]};case`fail`:if(!t)throw Error(`name is required for fail`);if(!r)throw Error(`id is required for fail`);if(!a)throw Error(`error is required for fail`);return{content:[{type:`text`,text:JSON.stringify(ft(t,r,a))}]};case`get`:if(!t)throw Error(`name is required for get`);return{content:[{type:`text`,text:JSON.stringify(pt(t))}]};case`list`:return{content:[{type:`text`,text:JSON.stringify(mt())}]};case`clear`:if(!t)throw Error(`name is required for clear`);return{content:[{type:`text`,text:JSON.stringify({cleared:st(t)})}]};case`delete`:if(!t)throw Error(`name is required for delete`);return{content:[{type:`text`,text:JSON.stringify({deleted:ut(t)})}]};case`dag`:if(!t)throw Error(`name is required for dag`);return{content:[{type:`text`,text:JSON.stringify(lt(t))}]}}}catch(e){return pc.error(`Queue action failed`,j(e)),H(`INTERNAL`,`Queue action failed: ${e instanceof Error?e.message:String(e)}`)}})}function yc(e){let t=[e.id,`Label: ${e.label}`,`Created: ${e.createdAt}`];if(e.notes&&t.push(`Notes: ${e.notes}`),e.files?.length){t.push(`Files: ${e.files.length}`);for(let n of e.files)t.push(` - ${n}`)}return t.push(``,`Data:`,JSON.stringify(e.data)),t.join(`
|
|
227
227
|
`)}function bc(e){let t=e.trim();if(!t)return``;try{return JSON.parse(t)}catch{return e}}function xc(e){let t=e?.trim();if(!t)return{};let n;try{n=JSON.parse(t)}catch{throw Error(`data must be a valid JSON object string`)}if(!n||typeof n!=`object`||Array.isArray(n))throw Error(`data must be a JSON object string`);return n}const Sc=k(`tools`);function Cc(e){let t=[`## Rule: ${e.id}`,``,`- **Status**: ${e.enabled?`enabled`:`disabled`}`,`- **Description**: ${e.description??`—`}`,`- **Category**: ${e.category??`—`}`,`- **Push weight**: ${e.pushWeight??`—`}`];return e.patterns?.length&&t.push(`- **Patterns**: ${e.patterns.join(`, `)}`),e.examples?.length&&t.push(`- **Examples**: ${e.examples.join(`, `)}`),t.join(`
|
|
228
228
|
`)}function wc(e,t){let n=z(`er_update_policy`);e.registerTool(`er_update_policy`,{title:n.title,description:`Manage ER push classification rules. Supports listing, updating, creating, and deleting rules that determine when knowledge should be pushed to Enterprise RAG.`,inputSchema:{action:F.enum([`list`,`get`,`update`,`create`,`delete`]).describe(`Action to perform on classification rules`),rule_id:F.string().optional().describe(`Rule ID (required for get, update, delete)`),changes:F.object({patterns:F.array(F.string()).optional(),category:F.string().optional(),pushWeight:F.number().min(0).max(1).optional(),description:F.string().optional(),examples:F.array(F.string()).optional(),enabled:F.boolean().optional()}).optional().describe(`Changes to apply (for update action)`),new_rule:F.object({id:F.string().regex(/^[a-z][a-z0-9-]*$/),patterns:F.array(F.string()).min(1),category:F.string(),pushWeight:F.number().min(0).max(1),description:F.string(),examples:F.array(F.string()).default([]),enabled:F.boolean().default(!0)}).optional().describe(`New rule definition (for create action)`)},annotations:n.annotations},async({action:e,rule_id:n,changes:r,new_rule:i})=>{try{if(e===`list`){let e=t.getRules();return{content:[{type:`text`,text:`## Classification Rules\n\n${e.map(e=>`- **${e.id}** (${e.enabled?`enabled`:`disabled`}) — ${e.description}\n Category: ${e.category} | Weight: ${e.pushWeight} | Patterns: ${e.patterns.join(`, `)}`).join(`
|
|
229
|
-
`)}\n\n---\n_${e.length} rules total. Use \`action: "update"\` to modify a rule._`}]}}if(e===`get`){if(!n)return H(`VALIDATION`,'`rule_id` is required for "get" action.');let e=t.getRule(n);return e?{content:[{type:`text`,text:Cc(e)}]}:H(`NOT_FOUND`,`Rule "${n}" not found.`)}if(e===`update`){if(!n||!r)return H(`VALIDATION`,'`rule_id` and `changes` are required for "update" action.');let e=t.updateRule(n,r);return e?{content:[{type:`text`,text:`${Cc(e)}\n\n---\n_Updated. Next: Use \`action: "list"\` to verify._`}]}:H(`NOT_FOUND`,`Rule "${n}" not found.`)}return e===`create`?i?{content:[{type:`text`,text:`${Cc(t.addRule(i))}\n\n---\n_Created. Next: Test classification with \`remember\`._`}]}:H(`VALIDATION`,'`new_rule` is required for "create" action.'):e===`delete`?n?t.deleteRule(n)?{content:[{type:`text`,text:`Deleted rule **${n}**.\n\n---\n_Next: Use \`action: "list"\` to verify._`}]}:H(`NOT_FOUND`,`Rule "${n}" not found.`):H(`VALIDATION`,'`rule_id` is required for "delete" action.'):H(`VALIDATION`,`Unknown action: ${e}`)}catch(e){return Sc.error(`Policy update failed`,j(e)),H(`INTERNAL`,`Policy update failed: ${e instanceof Error?e.message:String(e)}`)}})}const Tc=new Map([{type:`markdown`,category:`content`,description:`Markdown content rendered with the marked parser.`,valueShape:`string`,relevantSkills:[`present`,`docs`]},{type:`code`,category:`content`,description:`Formatted code block rendered inside pre/code tags.`,valueShape:`string`,relevantSkills:[`present`,`docs`]},{type:`mermaid`,category:`visualization`,description:`Mermaid diagram source rendered in a mermaid pre block.`,valueShape:`string`,relevantSkills:[`present`,`c4-architecture`,`docs`]},{type:`table`,category:`data`,description:`Tabular data rendered from records or explicit headers and rows.`,valueShape:`Record<string, unknown>[] | { headers: string[]; rows: unknown[][] }`,relevantSkills:[`present`,`docs`]},{type:`metrics`,category:`data`,description:`Metric cards showing label/value pairs with optional trend and status.`,valueShape:`Array<{ label: string; value: string | number; trend?: string | number; status?: string }>`,relevantSkills:[`present`]},{type:`cards`,category:`visualization`,description:`Card grid for titled items with optional body, badge, and status.`,valueShape:`Array<{ title: string; body?: string; badge?: string; status?: string; description?: string }>`,relevantSkills:[`present`,`docs`]},{type:`tree`,category:`visualization`,description:`Hierarchical object or name/children tree rendered recursively.`,valueShape:`{ name: string; children?: unknown[] } | Record<string, unknown>`,relevantSkills:[`present`]},{type:`graph`,category:`visualization`,description:`Node and edge graph rendered as a Mermaid flow graph in HTML mode.`,valueShape:`{ nodes: Array<{ id: string; label?: string }>; edges: Array<{ from: string; to: string; label?: string }> }`,relevantSkills:[`present`,`c4-architecture`]},{type:`chart`,category:`data`,description:`Structured chart definition rendered as SVG.`,valueShape:`{ chartType: string; data: Record<string, unknown>[]; xKey: string; yKeys: string[] }`,relevantSkills:[`present`]},{type:`timeline`,category:`interactive`,description:`Timeline entries rendered as a vertical sequence of events.`,valueShape:`Array<{ title: string; description?: string; timestamp?: string; status?: string }>`,relevantSkills:[`present`]},{type:`checklist`,category:`interactive`,description:`Checklist items with boolean checked state.`,valueShape:`Array<{label, checked}> | {items: Array<{label, checked}>}`,relevantSkills:[`present`]},{type:`comparison`,category:`interactive`,description:`Side-by-side comparison columns with titled item lists.`,valueShape:`Array<{title, items}> | {columns: Array<{title, items}>}`,relevantSkills:[`present`]},{type:`status-board`,category:`interactive`,description:`Status categories containing labeled status items.`,valueShape:`Array<{category, items}> | {items: Array<{category, items}>}`,relevantSkills:[`present`]},{type:`prompt`,category:`interactive`,description:`Prompt payload rendered through the prompt display helper.`,valueShape:`unknown`,relevantSkills:[`present`]},{type:`progress`,category:`interactive`,description:`Progress bar with current value and optional maximum.`,valueShape:`{label, value, max?} | {items: Array<{label, value, max?, color?}>}`,relevantSkills:[`present`]},{type:`
|
|
230
|
-
type: 'viewer-link',
|
|
231
|
-
value: {
|
|
232
|
-
viewerType: 'c4',
|
|
233
|
-
label: 'Open Interactive C4 Diagram',
|
|
234
|
-
description: 'Drag, zoom, and pan with ELK auto-layout',
|
|
235
|
-
icon: '🏗️',
|
|
236
|
-
},
|
|
237
|
-
}`},{type:`docs-browser`,category:`interactive`,description:`Collapsible file tree with markdown content for documentation browsing.`,valueShape:`{ files: Array<{ path: string; title?: string; content?: string; status?: "current" | "stale" | "missing" }>; title?: string }`,relevantSkills:[`present`,`docs`],usageExample:`{
|
|
229
|
+
`)}\n\n---\n_${e.length} rules total. Use \`action: "update"\` to modify a rule._`}]}}if(e===`get`){if(!n)return H(`VALIDATION`,'`rule_id` is required for "get" action.');let e=t.getRule(n);return e?{content:[{type:`text`,text:Cc(e)}]}:H(`NOT_FOUND`,`Rule "${n}" not found.`)}if(e===`update`){if(!n||!r)return H(`VALIDATION`,'`rule_id` and `changes` are required for "update" action.');let e=t.updateRule(n,r);return e?{content:[{type:`text`,text:`${Cc(e)}\n\n---\n_Updated. Next: Use \`action: "list"\` to verify._`}]}:H(`NOT_FOUND`,`Rule "${n}" not found.`)}return e===`create`?i?{content:[{type:`text`,text:`${Cc(t.addRule(i))}\n\n---\n_Created. Next: Test classification with \`remember\`._`}]}:H(`VALIDATION`,'`new_rule` is required for "create" action.'):e===`delete`?n?t.deleteRule(n)?{content:[{type:`text`,text:`Deleted rule **${n}**.\n\n---\n_Next: Use \`action: "list"\` to verify._`}]}:H(`NOT_FOUND`,`Rule "${n}" not found.`):H(`VALIDATION`,'`rule_id` is required for "delete" action.'):H(`VALIDATION`,`Unknown action: ${e}`)}catch(e){return Sc.error(`Policy update failed`,j(e)),H(`INTERNAL`,`Policy update failed: ${e instanceof Error?e.message:String(e)}`)}})}const Tc=new Map([{type:`markdown`,category:`content`,description:`Markdown content rendered with the marked parser.`,valueShape:`string`,relevantSkills:[`present`,`docs`]},{type:`code`,category:`content`,description:`Formatted code block rendered inside pre/code tags.`,valueShape:`string`,relevantSkills:[`present`,`docs`]},{type:`mermaid`,category:`visualization`,description:`Mermaid diagram source rendered in a mermaid pre block.`,valueShape:`string`,relevantSkills:[`present`,`c4-architecture`,`docs`]},{type:`table`,category:`data`,description:`Tabular data rendered from records or explicit headers and rows.`,valueShape:`Record<string, unknown>[] | { headers: string[]; rows: unknown[][] }`,relevantSkills:[`present`,`docs`]},{type:`metrics`,category:`data`,description:`Metric cards showing label/value pairs with optional trend and status.`,valueShape:`Array<{ label: string; value: string | number; trend?: string | number; status?: string }>`,relevantSkills:[`present`]},{type:`cards`,category:`visualization`,description:`Card grid for titled items with optional body, badge, and status.`,valueShape:`Array<{ title: string; body?: string; badge?: string; status?: string; description?: string }>`,relevantSkills:[`present`,`docs`]},{type:`tree`,category:`visualization`,description:`Hierarchical object or name/children tree rendered recursively.`,valueShape:`{ name: string; children?: unknown[] } | Record<string, unknown>`,relevantSkills:[`present`]},{type:`graph`,category:`visualization`,description:`Node and edge graph rendered as a Mermaid flow graph in HTML mode.`,valueShape:`{ nodes: Array<{ id: string; label?: string }>; edges: Array<{ from: string; to: string; label?: string }> }`,relevantSkills:[`present`,`c4-architecture`]},{type:`chart`,category:`data`,description:`Structured chart definition rendered as SVG.`,valueShape:`{ chartType: string; data: Record<string, unknown>[]; xKey: string; yKeys: string[] }`,relevantSkills:[`present`]},{type:`timeline`,category:`interactive`,description:`Timeline entries rendered as a vertical sequence of events.`,valueShape:`Array<{ title: string; description?: string; timestamp?: string; status?: string }>`,relevantSkills:[`present`]},{type:`checklist`,category:`interactive`,description:`Checklist items with boolean checked state.`,valueShape:`Array<{label, checked}> | {items: Array<{label, checked}>}`,relevantSkills:[`present`]},{type:`comparison`,category:`interactive`,description:`Side-by-side comparison columns with titled item lists.`,valueShape:`Array<{title, items}> | {columns: Array<{title, items}>}`,relevantSkills:[`present`]},{type:`status-board`,category:`interactive`,description:`Status categories containing labeled status items.`,valueShape:`Array<{category, items}> | {items: Array<{category, items}>}`,relevantSkills:[`present`]},{type:`prompt`,category:`interactive`,description:`Prompt payload rendered through the prompt display helper.`,valueShape:`unknown`,relevantSkills:[`present`]},{type:`progress`,category:`interactive`,description:`Progress bar with current value and optional maximum.`,valueShape:`{label, value, max?} | {items: Array<{label, value, max?, color?}>}`,relevantSkills:[`present`]},{type:`docs-browser`,category:`interactive`,description:`Documentation file list with inline content previews for chat-safe rendering.`,valueShape:`{ files: Array<{ path: string; title?: string; content?: string; status?: "current" | "stale" | "missing" }>; title?: string }`,relevantSkills:[`present`,`docs`],usageExample:`{
|
|
238
230
|
type: 'docs-browser',
|
|
239
231
|
value: {
|
|
240
232
|
title: 'Project Docs',
|
|
@@ -254,7 +246,7 @@ Complements: \`symbol\` (single lookup), \`trace\` (call-chain AST), \`blast_rad
|
|
|
254
246
|
`)}`}).filter(e=>typeof e==`string`);if(r.length>0)return{type:`markdown`,title:t,value:r.join(`
|
|
255
247
|
|
|
256
248
|
`)}}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 Ac(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(`
|
|
257
|
-
`)}:null}return null}function jc(e){return e.type!==`table`||typeof e.value!=`string`?null:{type:`markdown`,title:e.title,value:e.value}}const Mc=new Set([`markdown`,`table`,`code`,`chart`,`metrics`,`tree`,`graph`,`mermaid`]);function Nc(e){return jc(e)||(Mc.has(e.type)?null:Ac(e.value,e.title)||{type:`code`,title:e.title,value:typeof e.value==`string`?e.value:JSON.stringify(e.value,null,2)})}function Pc(e){if(e.type!==`progress`||!e.value||typeof e.value!=`object`||!Array.isArray(e.value.items))return null;let t=e.value.items.map(e=>{if(!e||typeof e!=`object`)return null;let t=e;if(typeof t.label!=`string`||typeof t.value!=`number`)return null;let n=typeof t.max==`number`?t.max:100,r=Number.isFinite(n)&&n>0?n:100,i=Math.round(t.value/r*100);return[t.label,`${i}%`,`${t.value} / ${r}`]}).filter(e=>Array.isArray(e));return t.length>0?{type:`table`,title:e.title,value:{headers:[`Item`,`Progress`,`Value`],rows:t}}:null}function Fc(e){if(e.type!==`prompt`||!e.value||typeof e.value!=`object`)return null;let t=e.value;if(typeof t.question!=`string`)return null;let n=[`**${t.question}**`];return typeof t.context==`string`&&t.context.length>0&&n.push(t.context),typeof t.placeholder==`string`&&t.placeholder.length>0&&n.push(`*${t.placeholder}*`),{type:`markdown`,title:e.title,value:n.join(`
|
|
249
|
+
`)}:null}return null}function jc(e){return e.type!==`table`||typeof e.value!=`string`?null:{type:`markdown`,title:e.title,value:e.value}}const Mc=new Set([`markdown`,`table`,`code`,`chart`,`metrics`,`tree`,`graph`,`mermaid`,`cards`,`timeline`,`checklist`,`comparison`,`status-board`,`prompt`,`progress`,`docs-browser`,`text`,`heading`,`paragraph`,`separator`,`actions`]);function Nc(e){return jc(e)||(Mc.has(e.type)?null:Ac(e.value,e.title)||{type:`code`,title:e.title,value:typeof e.value==`string`?e.value:JSON.stringify(e.value,null,2)})}function Pc(e){if(e.type!==`progress`||!e.value||typeof e.value!=`object`||!Array.isArray(e.value.items))return null;let t=e.value.items.map(e=>{if(!e||typeof e!=`object`)return null;let t=e;if(typeof t.label!=`string`||typeof t.value!=`number`)return null;let n=typeof t.max==`number`?t.max:100,r=Number.isFinite(n)&&n>0?n:100,i=Math.round(t.value/r*100);return[t.label,`${i}%`,`${t.value} / ${r}`]}).filter(e=>Array.isArray(e));return t.length>0?{type:`table`,title:e.title,value:{headers:[`Item`,`Progress`,`Value`],rows:t}}:null}function Fc(e){if(e.type!==`prompt`||!e.value||typeof e.value!=`object`)return null;let t=e.value;if(typeof t.question!=`string`)return null;let n=[`**${t.question}**`];return typeof t.context==`string`&&t.context.length>0&&n.push(t.context),typeof t.placeholder==`string`&&t.placeholder.length>0&&n.push(`*${t.placeholder}*`),{type:`markdown`,title:e.title,value:n.join(`
|
|
258
250
|
|
|
259
251
|
`)}}function Ic(e){return e.type===`separator`?{type:`markdown`,title:e.title,value:`---`}:null}const Lc={success:`✅`,done:`✅`,warning:`⚠️`,"at-risk":`⚠️`,error:`❌`,info:`ℹ️`,pending:`⏳`};function Rc(e){if(e.type!==`status-board`)return null;let t=e.value,n=Array.isArray(t)?t:t&&typeof t==`object`&&Array.isArray(t.items)?t.items:null;if(!n||n.length===0)return null;let r=n[0];if(r&&typeof r==`object`&&`category`in r){let t=n.map(e=>{if(!e||typeof e!=`object`)return null;let t=e;if(typeof t.category!=`string`||!Array.isArray(t.items))return null;let n=t.items.map(e=>{if(!e||typeof e!=`object`)return null;let t=e;if(typeof t.label!=`string`)return null;let n=typeof t.status==`string`?`${Lc[t.status.toLowerCase()]??`●`} `:``,r=typeof t.detail==`string`&&t.detail.length>0?` — ${t.detail}`:``;return`- ${n}${t.label}${r}`}).filter(e=>typeof e==`string`);return`### ${t.category}\n${n.join(`
|
|
260
252
|
`)}`}).filter(e=>typeof e==`string`);if(t.length>0)return{type:`markdown`,title:e.title,value:t.join(`
|
|
@@ -262,7 +254,7 @@ Complements: \`symbol\` (single lookup), \`trace\` (call-chain AST), \`blast_rad
|
|
|
262
254
|
`)}}let i=n.map(e=>{if(!e||typeof e!=`object`)return null;let t=e;return typeof t.label!=`string`||typeof t.status!=`string`?null:[Lc[t.status.toLowerCase()]??`●`,t.label,typeof t.detail==`string`?t.detail:``]}).filter(e=>Array.isArray(e));return i.length>0?{type:`table`,title:e.title,value:{headers:[`Status`,`Service`,`Detail`],rows:i}}:null}const zc={done:`✅`,active:`🔵`,pending:`⏳`,error:`❌`};function Bc(e,t){if(!Array.isArray(t))return null;let n=t.map(e=>{if(e&&typeof e==`object`){let t=e;return[String(t.status??t.state??``),String(t.time??t.date??t.timestamp??``),String(t.label??t.description??t.title??t.text??``)]}return[``,``,String(e)]});return{...e,type:`table`,value:{headers:[`Status`,`Time`,`Description`],rows:n}}}function Vc(e){if(e.type!==`timeline`||!e.value||typeof e.value!=`object`||!Array.isArray(e.value.items))return null;let t=e.value.items.map(e=>{if(!e||typeof e!=`object`)return null;let t=e;return typeof t.title==`string`?[zc[typeof t.status==`string`?t.status.toLowerCase():``]??`●`,typeof t.phase==`string`&&t.phase.length>0?t.phase:t.title,typeof t.description==`string`?t.description:``]:null}).filter(e=>Array.isArray(e));return t.length>0?{type:`table`,title:e.title,value:{headers:[`Status`,`Phase`,`Description`],rows:t}}:null}function Hc(e){let t=e;if(e.type===`text`||e.type===`paragraph`)return{...e,type:`markdown`};if(e.type===`heading`)return{...e,type:`markdown`,value:`## ${String(t.value??``)}`};if(e.type===`header`){let n=Math.min(Math.max(Number(e.level)||2,1),6);return{...e,type:`markdown`,value:`${`#`.repeat(n)} ${String(t.value??``)}`}}if(e.type===`section`)return{...e,type:`markdown`};if(e.type===`list`||e.type===`bullet`||e.type===`bullets`){let n=Array.isArray(t.value)?t.value:t.value&&typeof t.value==`object`&&Array.isArray(t.value.items)?t.value.items:void 0;return Array.isArray(n)?{...e,type:`markdown`,value:n.map(e=>`- ${String(e)}`).join(`
|
|
263
255
|
`)}:{...e,type:`markdown`}}if(e.type===`note`||e.type===`info`||e.type===`warning`||e.type===`alert`||e.type===`callout`){let n=e.type===`warning`?`⚠️`:e.type===`alert`?`🚨`:`ℹ️`;return{...e,type:`markdown`,value:`> ${n} ${String(t.value??``)}`}}if(e.type===`quote`||e.type===`blockquote`){let n=String(t.value??``).split(`
|
|
264
256
|
`);return{...e,type:`markdown`,value:n.map(e=>`> ${e}`).join(`
|
|
265
|
-
`)}}if(e.type===`divider`||e.type===`hr`)return{...e,type:`separator`};if(e.type===`image`||e.type===`img`){let t=e,n=String(t.src??t.url??t.value??``),r=String(t.alt??t.label??t.title??`image`);return{...e,type:`markdown`,value:``}}if(e.type===`link`||e.type===`url`){let t=e,n=String(t.href??t.url??t.value??``),r=String(t.label??t.text??t.title??n);return{...e,type:`markdown`,value:`[${r}](${n})`}}return e}function Uc(e){let t=e;return`value`in t?e:typeof t.text==`string`?{...e,value:t.text}:typeof t.content==`string`?{...e,value:t.content}:typeof t.markdown==`string`?{...e,value:t.markdown}:typeof t.description==`string`?{...e,value:t.description}:typeof t.code==`string`?{...e,value:t.code}:Array.isArray(t.headers)&&Array.isArray(t.rows)?{...e,value:{headers:t.headers,rows:t.rows}}:Array.isArray(t.items)?{...e,value:{items:t.items}}:Array.isArray(t.metrics)?{...e,value:t.metrics}:Array.isArray(t.cards)?{...e,value:t.cards}:Array.isArray(t.nodes)&&Array.isArray(t.edges)?{...e,value:{nodes:t.nodes,edges:t.edges}}:typeof t.question==`string`?{...e,value:{question:t.question,context:t.context,placeholder:t.placeholder}}:`chartType`in t||Array.isArray(t.data)?{...e,value:{chartType:t.chartType,data:t.data,xKey:t.xKey??`label`,yKeys:t.yKeys??[`value`]}}:e}function Wc(e){if(e.type!==`chart`)return e;let t=e.value;if(!t||typeof t!=`object`||Array.isArray(t))return e;let n=t,r=n.data&&typeof n.data==`object`&&!Array.isArray(n.data)?n.data:null,i=Array.isArray(n.labels)?n.labels:Array.isArray(r?.labels)?r.labels:null,a=Array.isArray(n.datasets)?n.datasets:Array.isArray(r?.datasets)?r.datasets:null,o=typeof n.type==`string`?n.type:typeof n.chartType==`string`?n.chartType:null;if(!o||!i||!a||Array.isArray(n.data))return e;let s=a.map((e,t)=>String(e.label??`series${t+1}`)),c=i.map((e,t)=>{let n={label:String(e)};for(let[e,r]of a.entries()){let i=r,a=String(i.label??`series${e+1}`);n[a]=i.data?.[t]??0}return n});return{...e,value:{chartType:String(o),data:c,xKey:`label`,yKeys:s}}}function Gc(e){if(Array.isArray(e)){let t=e.filter(e=>typeof e==`object`&&!!e),n=t.map(e=>String(e.title??``)),r=Math.max(0,...t.map(e=>Array.isArray(e.items)?e.items.length:0));return{headers:n,rows:Array.from({length:r},(e,n)=>t.map(e=>Array.isArray(e.items)?e.items[n]??``:``))}}if(!e||typeof e!=`object`)return null;let t=e,n=Object.keys(t),r=Math.max(0,...n.map(e=>Array.isArray(t[e])?t[e].length:0));return{headers:n,rows:Array.from({length:r},(e,r)=>n.map(e=>Array.isArray(t[e])?t[e][r]??``:``))}}function Kc(e,t,n){let r=Gc(t)??Gc(n);if(r)return{...e,type:`table`,value:r};if(n&&typeof n==`object`&&!Array.isArray(n)){let t=n;if(Array.isArray(t.headers)&&Array.isArray(t.rows))return{...e,type:`table`}}return null}function qc(e,t,n){let r=t&&typeof t==`object`&&!Array.isArray(t)?t:n&&typeof n==`object`&&!Array.isArray(n)?n:null;return r?{...e,type:`table`,value:{headers:[`Key`,`Value`],rows:Object.entries(r).map(([e,t])=>[e,t])}}:null}function Jc(e){let t=e,n=Uc(e);if(n=Wc(n),n.type===`kv`)return qc(n,t.entries,n.value)??n;if(n.type===`comparison`){let e=n,r=t.columns??(e.value&&typeof e.value==`object`?e.value.columns:void 0);return Kc(n,r,e.value)??n}return n=Hc(n),n.type===`timeline`?Bc(n,n.value)??n:n}const Yc=new Set([`separator`,`actions`]);function Xc(e){if(typeof e!=`object`||!e||!(`type`in e))return!1;let t=e,n=typeof t.type==`string`?t.type:``;return Yc.has(n)?!0:`value`in t||typeof t.text==`string`||Array.isArray(t.headers)&&Array.isArray(t.rows)||typeof t.code==`string`||Array.isArray(t.items)||!!t.entries&&typeof t.entries==`object`&&!Array.isArray(t.entries)||!!t.columns&&typeof t.columns==`object`||`chartType`in t||Array.isArray(t.data)||typeof t.content==`string`||typeof t.markdown==`string`||typeof t.description==`string`||Array.isArray(t.metrics)||Array.isArray(t.cards)||Array.isArray(t.nodes)||typeof t.question==`string`}function Zc(e){return Ic(e)??kc(e)??Rc(e)??Fc(e)??Pc(e)??Vc(e)??Oc(e)??Nc(e)??e}function Qc(e){if(!Array.isArray(e)&&typeof e==`object`&&e){let t=e;return Array.isArray(t.blocks)&&t.blocks.length>0?Qc(t.blocks):e}return Array.isArray(e)?e.map(e=>Xc(e)?Zc(Jc(e)):e):e}function $c(e){let t=e;for(let e=0;e<10;e++){if(a.existsSync(m.join(t,`package.json`)))return t;let e=m.dirname(t);if(e===t)break;t=e}return e}function el(){let e=$c(m.dirname(b(import.meta.url))),t=m.join(e,`packages`,`present`,`dist`,`index.html`);if(a.existsSync(t))return t;let n=m.join(e,`node_modules`,`@aikit`,`present`,`dist`,`index.html`);return a.existsSync(n)?n:t}const tl=el();let nl;function
|
|
257
|
+
`)}}if(e.type===`divider`||e.type===`hr`)return{...e,type:`separator`};if(e.type===`image`||e.type===`img`){let t=e,n=String(t.src??t.url??t.value??``),r=String(t.alt??t.label??t.title??`image`);return{...e,type:`markdown`,value:``}}if(e.type===`link`||e.type===`url`){let t=e,n=String(t.href??t.url??t.value??``),r=String(t.label??t.text??t.title??n);return{...e,type:`markdown`,value:`[${r}](${n})`}}return e}function Uc(e){let t=e;return`value`in t?e:typeof t.text==`string`?{...e,value:t.text}:typeof t.content==`string`?{...e,value:t.content}:typeof t.markdown==`string`?{...e,value:t.markdown}:typeof t.description==`string`?{...e,value:t.description}:typeof t.code==`string`?{...e,value:t.code}:Array.isArray(t.headers)&&Array.isArray(t.rows)?{...e,value:{headers:t.headers,rows:t.rows}}:Array.isArray(t.items)?{...e,value:{items:t.items}}:Array.isArray(t.metrics)?{...e,value:t.metrics}:Array.isArray(t.cards)?{...e,value:t.cards}:Array.isArray(t.nodes)&&Array.isArray(t.edges)?{...e,value:{nodes:t.nodes,edges:t.edges}}:typeof t.question==`string`?{...e,value:{question:t.question,context:t.context,placeholder:t.placeholder}}:`chartType`in t||Array.isArray(t.data)?{...e,value:{chartType:t.chartType,data:t.data,xKey:t.xKey??`label`,yKeys:t.yKeys??[`value`]}}:e}function Wc(e){if(e.type!==`chart`)return e;let t=e.value;if(!t||typeof t!=`object`||Array.isArray(t))return e;let n=t,r=n.data&&typeof n.data==`object`&&!Array.isArray(n.data)?n.data:null,i=Array.isArray(n.labels)?n.labels:Array.isArray(r?.labels)?r.labels:null,a=Array.isArray(n.datasets)?n.datasets:Array.isArray(r?.datasets)?r.datasets:null,o=typeof n.type==`string`?n.type:typeof n.chartType==`string`?n.chartType:null;if(!o||!i||!a||Array.isArray(n.data))return e;let s=a.map((e,t)=>String(e.label??`series${t+1}`)),c=i.map((e,t)=>{let n={label:String(e)};for(let[e,r]of a.entries()){let i=r,a=String(i.label??`series${e+1}`);n[a]=i.data?.[t]??0}return n});return{...e,value:{chartType:String(o),data:c,xKey:`label`,yKeys:s}}}function Gc(e){if(Array.isArray(e)){let t=e.filter(e=>typeof e==`object`&&!!e),n=t.map(e=>String(e.title??``)),r=Math.max(0,...t.map(e=>Array.isArray(e.items)?e.items.length:0));return{headers:n,rows:Array.from({length:r},(e,n)=>t.map(e=>Array.isArray(e.items)?e.items[n]??``:``))}}if(!e||typeof e!=`object`)return null;let t=e,n=Object.keys(t),r=Math.max(0,...n.map(e=>Array.isArray(t[e])?t[e].length:0));return{headers:n,rows:Array.from({length:r},(e,r)=>n.map(e=>Array.isArray(t[e])?t[e][r]??``:``))}}function Kc(e,t,n){let r=Gc(t)??Gc(n);if(r)return{...e,type:`table`,value:r};if(n&&typeof n==`object`&&!Array.isArray(n)){let t=n;if(Array.isArray(t.headers)&&Array.isArray(t.rows))return{...e,type:`table`}}return null}function qc(e,t,n){let r=t&&typeof t==`object`&&!Array.isArray(t)?t:n&&typeof n==`object`&&!Array.isArray(n)?n:null;return r?{...e,type:`table`,value:{headers:[`Key`,`Value`],rows:Object.entries(r).map(([e,t])=>[e,t])}}:null}function Jc(e){let t=e,n=Uc(e);if(n=Wc(n),n.type===`kv`)return qc(n,t.entries,n.value)??n;if(n.type===`comparison`){let e=n,r=t.columns??(e.value&&typeof e.value==`object`?e.value.columns:void 0);return Kc(n,r,e.value)??n}return n=Hc(n),n.type===`timeline`?Bc(n,n.value)??n:n}const Yc=new Set([`separator`,`actions`]);function Xc(e){if(typeof e!=`object`||!e||!(`type`in e))return!1;let t=e,n=typeof t.type==`string`?t.type:``;return Yc.has(n)?!0:`value`in t||typeof t.text==`string`||Array.isArray(t.headers)&&Array.isArray(t.rows)||typeof t.code==`string`||Array.isArray(t.items)||!!t.entries&&typeof t.entries==`object`&&!Array.isArray(t.entries)||!!t.columns&&typeof t.columns==`object`||`chartType`in t||Array.isArray(t.data)||typeof t.content==`string`||typeof t.markdown==`string`||typeof t.description==`string`||Array.isArray(t.metrics)||Array.isArray(t.cards)||Array.isArray(t.nodes)||typeof t.question==`string`}function Zc(e){return Ic(e)??kc(e)??Rc(e)??Fc(e)??Pc(e)??Vc(e)??Oc(e)??Nc(e)??e}function Qc(e){if(!Array.isArray(e)&&typeof e==`object`&&e){let t=e;return Array.isArray(t.blocks)&&t.blocks.length>0?Qc(t.blocks):e}return Array.isArray(e)?e.map(e=>Xc(e)?Zc(Jc(e)):e):e}function $c(e){let t=e;for(let e=0;e<10;e++){if(a.existsSync(m.join(t,`package.json`)))return t;let e=m.dirname(t);if(e===t)break;t=e}return e}function el(){let e=$c(m.dirname(b(import.meta.url))),t=m.join(e,`packages`,`present`,`dist`,`index.html`);if(a.existsSync(t))return t;let n=m.join(e,`node_modules`,`@aikit`,`present`,`dist`,`index.html`);return a.existsSync(n)?n:t}const tl=el();let nl,rl;function il(){if(nl!==void 0)return nl??void 0;if(!a.existsSync(tl)){nl=null;return}return nl=a.readFileSync(tl,`utf8`),nl??void 0}function al(e){return new Map(Array.from(e.entries(),([e,t])=>[e,{...t}]))}function ol(e){let t=new Map,n=0;return{shell:e.replace(/<script(?![^>]*\btype\s*=\s*["']application\/json["'])([^>]*)>([\s\S]*?)<\/script>/gi,(e,r,i)=>{if(/\bsrc\s*=/i.test(r))return e;let a=i.trim();if(!a)return e;let o=`app-${n++}.js`;return t.set(`/assets/${o}`,{content:a,contentType:`application/javascript`}),`<script src="/assets/${o}"${r}><\/script>`}),assets:t}}function sl(){if(rl!==void 0)return rl?{shell:rl.shell,assets:al(rl.assets)}:void 0;let e=il();if(!e){rl=null;return}return rl=ol(e),{shell:rl.shell,assets:al(rl.assets)}}function cl(e){return JSON.stringify(e).replace(/</g,`\\u003c`).replace(/>/g,`\\u003e`).replace(/&/g,`\\u0026`).replace(/\u2028/g,`\\u2028`).replace(/\u2029/g,`\\u2029`)}function ll(e,t){return`<!DOCTYPE html>
|
|
266
258
|
<html>
|
|
267
259
|
<head>
|
|
268
260
|
<meta charset="utf-8">
|
|
@@ -282,37 +274,25 @@ Complements: \`symbol\` (single lookup), \`trace\` (call-chain AST), \`blast_rad
|
|
|
282
274
|
</div>
|
|
283
275
|
${t}
|
|
284
276
|
</body>
|
|
285
|
-
</html>`}function
|
|
286
|
-
`)}function cl(e,t){let n=[];switch(e.title&&n.push(`## ${e.title}\n`),e.type){case`markdown`:{let t=String(e.value??``);t=t.replace(/(^|\n)((?!\|)[^\n]+)\n(\|)/g,`$1$2
|
|
287
|
-
|
|
288
|
-
$3`),n.push(t);break}case`code`:n.push(`\`\`\`${e.language??``}\n${String(e.value??``)}\n\`\`\``);break;case`mermaid`:n.push(`\`\`\`mermaid\n${String(e.value??``)}\n\`\`\``);break;case`table`:{let r=e.value;if(Array.isArray(r)&&r.length>0)t?.compactTables?n.push(ul(r,e.title)):n.push(ll(r));else if(r&&typeof r==`object`&&!Array.isArray(r)&&`headers`in r&&`rows`in r){let{headers:i,rows:a}=r;if(t?.compactTables){let t=[];e.title&&t.push(`**${e.title}**\n`);for(let e=0;e<a.length;e++){let n=i.map((t,n)=>`**${t}**: ${String(a[e]?.[n]??``)}`).join(` · `);t.push(`${e+1}. ${n}`)}n.push(t.join(`
|
|
289
|
-
`))}else{n.push(`| ${i.join(` | `)} |`),n.push(`| ${i.map(()=>`---`).join(` | `)} |`);for(let e of a)n.push(`| ${e.map(e=>String(e??``)).join(` | `)} |`)}}else n.push(`*(empty table)*`);break}case`metrics`:Array.isArray(e.value)&&n.push(fl(e.value));break;case`graph`:e.value&&typeof e.value==`object`&&n.push(pl(e.value));break;case`cards`:if(Array.isArray(e.value))for(let t of e.value)n.push(`### ${t.title??`Card`}`),(t.body||t.description)&&n.push(String(t.body??t.description)),(t.badge||t.status)&&n.push(`> **${t.badge??t.status}**`),n.push(``);break;case`tree`:e.value&&typeof e.value==`object`&&n.push(ml(e.value));break;case`chart`:{let t=e.value;t?.data&&Array.isArray(t.data)&&n.push(`*${String(t.chartType??`chart`)} chart — ${t.data.length} data points*`);break}case`timeline`:{let t=e.value;if(t?.items)for(let e of t.items){let t=e.status===`done`?`✅`:e.status===`active`?`🔄`:e.status===`error`?`❌`:`⬜`;n.push(`${t} **${e.title}**${e.description?` — ${e.description}`:``}`)}break}case`checklist`:{let t=e.value;if(t?.items)for(let e of t.items)n.push(`- [${e.checked?`x`:` `}] ${e.label}${e.note?` — ${e.note}`:``}`);break}case`comparison`:{let r=e.value;if(r?.columns&&r.columns.length>0)if(t?.compactTables)n.push(dl(r.columns,e.title));else{let e=Math.max(...r.columns.map(e=>e.items?.length??0)),t=r.columns.map(e=>e.title);n.push(`| ${t.join(` | `)} |`),n.push(`| ${t.map(()=>`---`).join(` | `)} |`);for(let t=0;t<e;t++)n.push(`| ${r.columns.map(e=>e.items?.[t]??``).join(` | `)} |`)}break}case`status-board`:{let t=e.value;if(t?.items)for(let e of t.items){let t=e.status===`success`?`🟢`:e.status===`warning`?`🟡`:e.status===`error`?`🔴`:e.status===`info`?`🔵`:`⚪`;n.push(`${t} **${e.label}**${e.detail?` — ${e.detail}`:``}`)}break}case`prompt`:{let t=e.value;t?.question&&(n.push(`> **${t.question}**`),t.context&&n.push(`> ${t.context}`));break}case`progress`:{let t=e.value;if(t?.items)for(let e of t.items){let t=e.max??100,r=t>0?Math.round(e.value/t*100):0,i=Math.round(r/5),a=`█`.repeat(i)+`░`.repeat(20-i);n.push(`${e.label}: ${a} ${r}%`)}break}case`docs-browser`:{let t=e.value,r={current:`✅`,stale:`⚠️`,missing:`❌`};t?.title?.trim()&&n.push(`## ${t.title.trim()}`);let i=Array.isArray(t?.files)?t.files:[];if(i.length===0){n.push(`*(No content available)*`);break}i.forEach((e,t)=>{let a=e?.path?.trim()||`document-${t+1}`,o=e?.title?.trim()||a.split(/[\\/]/).pop()||a,s=e?.status&&r[e.status]?r[e.status]:`📄`;n.push(`${s} **${o}** (\`${a}\`)`),n.push(``),typeof e?.content==`string`&&e.content.trim().length>0?n.push(e.content.trim()):n.push(`*(No content available)*`),t<i.length-1&&(n.push(``),n.push(`---`),n.push(``))});break}case`viewer-link`:{let t=e.value,r=t?.label?.trim()||t?.viewerType?.trim()||`Viewer`,i=t?.icon?.trim()||`🔗`;n.push(`${i} **${r}**`),t?.description?.trim()&&n.push(t.description.trim()),t?.url?.trim()&&n.push(`[Open](${t.url.trim()})`);break}case`text`:n.push(String(e.value??``));break;case`heading`:{let t=Math.min(Math.max(Number(e.level)||2,1),6);n.push(`${`#`.repeat(t)} ${String(e.value??``)}\n`);break}case`paragraph`:n.push(String(e.value??``));break;case`separator`:n.push(`---
|
|
290
|
-
`);break;default:n.push(JSON.stringify(e.value,null,2))}return n.push(``),n.join(`
|
|
291
|
-
`)}function ll(e){if(e.length===0)return`*(empty table)*`;let t=Object.keys(e[0]),n=[];n.push(`| ${t.join(` | `)} |`),n.push(`| ${t.map(()=>`---`).join(` | `)} |`);for(let r of e)n.push(`| ${t.map(e=>String(r[e]??``)).join(` | `)} |`);return n.join(`
|
|
292
|
-
`)}function ul(e,t){if(e.length===0)return`*(empty table)*`;let n=Object.keys(e[0]),r=[];t&&r.push(`**${t}**\n`);for(let t=0;t<e.length;t++){let i=e[t],a=String(i[n[0]]??``);if(n.length===1)r.push(`${t+1}. **${a}**`);else{let e=n.slice(1).map(e=>`${e}: ${String(i[e]??``)}`).join(` · `);r.push(`${t+1}. **${a}** — ${e}`)}}return r.join(`
|
|
293
|
-
`)}function dl(e,t){let n=[];t&&n.push(`**${t}**\n`);for(let t of e){if(n.push(`**${t.title}**`),t.items&&t.items.length>0)for(let e of t.items)n.push(`- ${e}`);else n.push(`- *(none)*`);n.push(``)}return n.join(`
|
|
294
|
-
`)}function fl(e){return e.map(e=>`- **${e.label}**: ${e.value}`).join(`
|
|
295
|
-
`)}function pl(e){let t=["```mermaid",`graph LR`];for(let n of e.nodes){let e=Ia(String(n.id??n.name??``)),r=String(n.label??n.name??e);t.push(` ${e}["${r}"]`)}for(let n of e.edges){let e=Ia(String(n.source??n.from??``)),r=Ia(String(n.target??n.to??``)),i=n.label?`|${String(n.label)}|`:``;t.push(` ${e} -->${i} ${r}`)}return t.push("```"),t.join(`
|
|
296
|
-
`)}function ml(e,t=0){let n=` `.repeat(t),r=[];for(let[i,a]of Object.entries(e))typeof a==`object`&&a&&!Array.isArray(a)?(r.push(`${n}- **${i}**:`),r.push(ml(a,t+1))):r.push(`${n}- **${i}**: ${Fa(a)}`);return r.join(`
|
|
297
|
-
`)}const q=U;function hl(e){if(!e)return!1;let t=e.trim().toLowerCase();return t.startsWith(`http://`)||t.startsWith(`https://`)||t.startsWith(`/`)||t.startsWith(`./`)||t.startsWith(`../`)?!0:!t.includes(`:`)}function gl(e){return e?/^(#[\da-f]{3,8}|rgba?\([^)]+\)|hsla?\([^)]+\)|var\(--[\w-]+\)|[a-z]{1,20})$/i.test(e.trim()):!1}function _l(e){let t=e;return!t?.items||!Array.isArray(t.items)?``:`<div class="timeline">${t.items.map(e=>{let t=e.status??`pending`,n=e.phase?`<div class="timeline-phase">${q(e.phase)}</div>`:``,r=e.description?`<div class="timeline-desc">${q(e.description)}</div>`:``;return`<div class="timeline-item">
|
|
277
|
+
</html>`}function ul(e,t,n,r){let i={title:e,content:Qc(t)};r!==void 0&&(i.template=r),Array.isArray(n)&&n.length>0&&(i.actions=n);let a=`<script type="application/json" id="present-data">${cl(i)}<\/script>`,o=U(e??`AI Kit Dashboard`),s=sl();return s?{html:s.shell.replace(/<title>[\s\S]*?<\/title>/i,`<title>${o}</title>`).replace(`</head>`,` ${a}\n</head>`),assets:s.assets}:{html:ll(o,a),assets:new Map}}const q=U;function dl(e){return e?/^(#[\da-f]{3,8}|rgba?\([^)]+\)|hsla?\([^)]+\)|var\(--[\w-]+\)|[a-z]{1,20})$/i.test(e.trim()):!1}function fl(e){let t=e;return!t?.items||!Array.isArray(t.items)?``:`<div class="timeline">${t.items.map(e=>{let t=e.status??`pending`,n=e.phase?`<div class="timeline-phase">${q(e.phase)}</div>`:``,r=e.description?`<div class="timeline-desc">${q(e.description)}</div>`:``;return`<div class="timeline-item">
|
|
298
278
|
<div class="timeline-dot ${t}"></div>
|
|
299
279
|
${n}
|
|
300
280
|
<div class="timeline-title">${q(e.title)}</div>
|
|
301
281
|
${r}
|
|
302
|
-
</div>`}).join(``)}</div>`}function
|
|
282
|
+
</div>`}).join(``)}</div>`}function pl(e){let t=e;return!t?.items||!Array.isArray(t.items)?``:`<div class="checklist">${t.items.map(e=>{let t=e.checked?`checked`:``,n=e.checked?`✓`:``,r=e.note?`<div class="checklist-note">${q(e.note)}</div>`:``;return`<div class="checklist-item ${t}">
|
|
303
283
|
<div class="checklist-check ${t}">${n}</div>
|
|
304
284
|
<div>
|
|
305
285
|
<div class="checklist-label">${q(e.label)}</div>
|
|
306
286
|
${r}
|
|
307
287
|
</div>
|
|
308
|
-
</div>`}).join(``)}</div>`}function
|
|
288
|
+
</div>`}).join(``)}</div>`}function ml(e){let t=e;if(t?.left&&t?.right)return ml({columns:[{title:t.left.label??`Left`,items:t.left.items??[]},{title:t.right.label??`Right`,items:t.right.items??[]}]});if(!t?.columns||!Array.isArray(t.columns)||t.columns.length===0)return``;let n=t.columns.length,r=Math.max(...t.columns.map(e=>e.items?.length??0));return`<div class="comparison-grid" style="grid-template-columns:repeat(${n},1fr)">${t.columns.map(e=>{let t=`<div class="comparison-header">${q(e.title)}</div>`,n=[];for(let t=0;t<r;t++){let r=e.items?.[t]??``;n.push(`<div class="comparison-item">${q(r)}</div>`)}return`<div class="comparison-col">${t}${n.join(``)}</div>`}).join(``)}</div>`}function hl(e){let t=e;return!t?.items||!Array.isArray(t.items)?``:`<div class="status-board">${t.items.flatMap(e=>{let t=e;if(Array.isArray(t.items)){let e=t.category?.trim();return t.items.map(t=>({...t,label:e?`${e}: ${t.label}`:t.label}))}return[e]}).map(e=>{let t=e.detail?`<span class="status-detail">${q(e.detail)}</span>`:``;return`<div class="status-row">
|
|
309
289
|
<div class="status-indicator ${e.status??`pending`}"></div>
|
|
310
290
|
<span class="status-label">${q(e.label)}</span>
|
|
311
291
|
${t}
|
|
312
|
-
</div>`}).join(``)}</div>`}function
|
|
292
|
+
</div>`}).join(``)}</div>`}function gl(e){let t=e;if(!t?.question)return``;let n=t.context?`<div class="prompt-context">${q(t.context)}</div>`:``,r=t.placeholder?`<div class="prompt-placeholder">${q(t.placeholder)}</div>`:``;return`<div class="prompt-block">
|
|
313
293
|
<div class="prompt-question">${q(t.question)}</div>
|
|
314
294
|
${n}${r}
|
|
315
|
-
</div>`}function
|
|
295
|
+
</div>`}function _l(e){let t=e;if(!t?.items||!Array.isArray(t.items))return``;let n=e=>e>=100?`var(--success)`:e>=60?`var(--primary)`:e>=30?`var(--warning)`:`var(--error)`;return`<div class="progress-list">${t.items.map(e=>{let t=e.max??100,r=t>0?Math.min(100,e.value/t*100):0,i=dl(e.color??``)?e.color?.trim()??n(r):n(r);return`<div class="progress-item">
|
|
316
296
|
<div class="progress-header">
|
|
317
297
|
<span class="progress-label">${q(e.label)}</span>
|
|
318
298
|
<span class="progress-value">${e.value}/${t}</span>
|
|
@@ -320,38 +300,26 @@ $3`),n.push(t);break}case`code`:n.push(`\`\`\`${e.language??``}\n${String(e.valu
|
|
|
320
300
|
<div class="progress-track">
|
|
321
301
|
<div class="progress-fill" style="width:${r.toFixed(1)}%;background:${i}"></div>
|
|
322
302
|
</div>
|
|
323
|
-
</div>`}).join(``)}</div>`}function
|
|
324
|
-
<div style="font-weight:600; font-size:1rem; margin-bottom:${r?`4px`:`0`};">${q(i)} ${q(n)}</div>
|
|
325
|
-
${r?`<div style="font-size:0.85rem; color:var(--color-muted, #94a3b8);">${q(r)}</div>`:``}
|
|
326
|
-
</div>`;return t?.url?`<a href="${hl(t.url)?q(t.url):`#`}" style="display:block; color:inherit; text-decoration:none;">${a}</a>`:a}function wl(e){let t=e,n=Array.isArray(t?.files)?t.files:[],r={current:`background:#14532d; color:#bbf7d0; border:1px solid #166534;`,stale:`background:#713f12; color:#fde68a; border:1px solid #a16207;`,missing:`background:#7f1d1d; color:#fecaca; border:1px solid #b91c1c;`};return`<div class="docs-browser" style="border:1px solid var(--color-border, #334155); border-radius:8px; overflow:hidden; background:var(--color-surface, transparent);">${t?.title?.trim()?`<div style="padding:12px 12px 0; font-weight:600; color:var(--color-text, #e2e8f0);">${q(t.title)}</div>`:``}${n.length?n.map((e,t)=>{let n=e?.path?.trim()||`document-${t+1}`,i=e?.title?.trim()||n.split(/[\\/]/).pop()||n,a=e?.status&&r[e.status]?`<span style="display:inline-flex; align-items:center; padding:2px 8px; border-radius:999px; font-size:0.75rem; text-transform:uppercase; letter-spacing:0.04em; ${r[e.status]}">${q(e.status)}</span>`:``,o=typeof e?.content==`string`&&e.content.trim().length>0?`<div class="md-content">${An.parse(e.content)}</div>`:`<div style="font-size:0.85rem; color:var(--color-muted, #94a3b8);">No content available.</div>`;return`<details${t===0?` open`:``}>
|
|
327
|
-
<summary style="padding:8px 12px; cursor:pointer; background:var(--color-card, #1e293b); display:flex; align-items:center; justify-content:space-between; gap:12px;">
|
|
328
|
-
<div style="display:flex; flex-direction:column; gap:2px; min-width:0;">
|
|
329
|
-
<span style="font-family:monospace; font-size:0.85rem; color:var(--color-muted, #94a3b8); word-break:break-all;">${q(n)}</span>
|
|
330
|
-
<span style="font-weight:600; color:var(--color-text, #e2e8f0);">${q(i)}</span>
|
|
331
|
-
</div>
|
|
332
|
-
${a}
|
|
333
|
-
</summary>
|
|
334
|
-
<div style="padding:12px; border-top:1px solid var(--color-border, #334155);">${o}</div>
|
|
335
|
-
</details>`}).join(``):`<div style="padding:12px; color:var(--color-muted, #94a3b8);">No documentation files.</div>`}</div>`}const J=U;function Tl(e){return Math.abs(e)>=1e6?`${(e/1e6).toFixed(1).replace(/\.0$/,``)}M`:Math.abs(e)>=1e3?`${(e/1e3).toFixed(1).replace(/\.0$/,``)}k`:Number.isInteger(e)?String(e):e.toFixed(1)}function El(e){return`var(--chart-${e%12+1})`}let Dl=0;function Ol(e){let t=e.value;if(!t?.data?.length||!t.chartType)return`<pre>${J(JSON.stringify(e.value,null,2))}</pre>`;Dl++;let n=e.title||t.title?`<div class="chart-title">${J(String(e.title||t.title))}</div>`:``,r;switch(t.chartType){case`line`:r=Il(t,!1);break;case`area`:r=Il(t,!0);break;case`bar`:r=Ll(t,!1);break;case`horizontal-bar`:r=Ll(t,!0);break;case`pie`:r=Rl(t,!1);break;case`donut`:r=Rl(t,!0);break;case`sparkline`:r=zl(t);break;case`heatmap`:r=Bl(t);break;default:r=`<pre>${J(JSON.stringify(t,null,2))}</pre>`}let i=t.showLegend!==!1&&t.yKeys.length>1&&t.chartType!==`sparkline`?kl(t.yKeys):``;return`<div class="chart-container">${n}${r}${i}</div>`}function kl(e){return`<div class="chart-legend">${e.map((e,t)=>`<span class="chart-legend-item"><span class="chart-legend-swatch" style="background:${El(t)}"></span>${J(e)}</span>`).join(``)}</div>`}const Y={top:20,right:20,bottom:35,left:55};function Al(e,t){return e.map(e=>Number(e[t])||0)}function jl(e,t){return e.map(e=>String(e[t]??``))}function Ml(e){let t=1/0,n=-1/0;for(let r of e)r<t&&(t=r),r>n&&(n=r);return t===n&&(t=t===0?0:t*.9,n=n===0?1:n*1.1),[t,n]}function Nl(e){return e>=0?0:e}function Pl(e,t,n,r=5){let i=[];for(let a=0;a<=r;a++){let o=a/r,s=Y.top+n-o*n,c=e+o*(t-e);i.push(`<line class="chart-grid-line" x1="${Y.left}" x2="${600-Y.right}" y1="${s}" y2="${s}"/>`),i.push(`<text class="chart-axis-label" x="${Y.left-8}" y="${s+4}" text-anchor="end">${Tl(c)}</text>`)}return i.join(``)}function Fl(e,t,n,r){let i=Math.floor(t/50),a=Math.max(1,Math.ceil(e.length/i));return e.map((e,t)=>t%a===0?`<text class="chart-axis-label" x="${Y.left+t*r+r/2}" y="${Y.top+n+18}" text-anchor="middle">${J(e.length>10?`${e.slice(0,9)}…`:e)}</text>`:``).join(``)}function Il(e,t){let n=(e.height??300)-Y.top-Y.bottom,r=600-Y.left-Y.right,i=jl(e.data,e.xKey),a=e.data.length;if(a===0)return``;let o=r/Math.max(a-1,1),s=1/0,c=-1/0;for(let t of e.yKeys){let[n,r]=Ml(Al(e.data,t));n<s&&(s=n),r>c&&(c=r)}s=Nl(s);let l=c-s||1,u=e=>Y.top+n-(e-s)/l*n,d=e=>Y.left+e*o,f=``,p=[];for(let r=0;r<e.yKeys.length;r++){let i=Al(e.data,e.yKeys[r]),o=El(r),s=`M${i.map((e,t)=>`${d(t).toFixed(1)},${u(e).toFixed(1)}`).join(`L`)}`;if(t){let e=`ag${Dl}_${r}`;f+=`<linearGradient id="${e}" x1="0" y1="0" x2="0" y2="1">
|
|
303
|
+
</div>`}).join(``)}</div>`}function vl(e){let t=e,n=Array.isArray(t?.files)?t.files:[],r={current:`✅`,stale:`⚠️`,missing:`❌`};return`<div class="docs-browser" style="border:1px solid var(--color-border, #334155); border-radius:8px; overflow:hidden;">${t?.title?.trim()?`<div style="padding:12px 12px 4px; font-weight:700; font-size:1.1rem; color:var(--color-text, #e2e8f0);">${q(t.title)}</div>`:``}${n.length?n.map(e=>{let t=e?.path?.trim()||`untitled`,n=e?.title?.trim()||t.split(/[\\/]/).pop()||t,i=e?.status&&r[e.status]||``,a=e?.status?` (${e.status})`:``,o=typeof e?.content==`string`&&e.content.trim().length>0?e.content.trim():``,s=`<div style="border-bottom:1px solid var(--color-border, #334155); padding:12px;">`;return s+=`<div><strong>${q(`${i}${i?` `:``}${n}`)}</strong>${q(a)}</div>`,s+=`<div style="font-family:monospace; font-size:0.85rem; color:var(--color-muted, #94a3b8);">${q(t)}</div>`,o&&(s+=`<div style="margin-top:8px; font-size:0.9rem;">${q(o)}</div>`),s+=`</div>`,s}).join(``):`<div style="padding:12px; color:var(--color-muted, #94a3b8);">No documentation files.</div>`}</div>`}const J=U;function yl(e){return Math.abs(e)>=1e6?`${(e/1e6).toFixed(1).replace(/\.0$/,``)}M`:Math.abs(e)>=1e3?`${(e/1e3).toFixed(1).replace(/\.0$/,``)}k`:Number.isInteger(e)?String(e):e.toFixed(1)}function bl(e){return`var(--chart-${e%12+1})`}let xl=0;function Sl(e){let t=e.value;if(!t?.data?.length||!t.chartType)return`<pre>${J(JSON.stringify(e.value,null,2))}</pre>`;xl++;let n=e.title||t.title?`<div class="chart-title">${J(String(e.title||t.title))}</div>`:``,r;switch(t.chartType){case`line`:r=Al(t,!1);break;case`area`:r=Al(t,!0);break;case`bar`:r=jl(t,!1);break;case`horizontal-bar`:r=jl(t,!0);break;case`pie`:r=Ml(t,!1);break;case`donut`:r=Ml(t,!0);break;case`sparkline`:r=Nl(t);break;case`heatmap`:r=Pl(t);break;default:r=`<pre>${J(JSON.stringify(t,null,2))}</pre>`}let i=t.showLegend!==!1&&t.yKeys.length>1&&t.chartType!==`sparkline`?Cl(t.yKeys):``;return`<div class="chart-container">${n}${r}${i}</div>`}function Cl(e){return`<div class="chart-legend">${e.map((e,t)=>`<span class="chart-legend-item"><span class="chart-legend-swatch" style="background:${bl(t)}"></span>${J(e)}</span>`).join(``)}</div>`}const Y={top:20,right:20,bottom:35,left:55};function wl(e,t){return e.map(e=>Number(e[t])||0)}function Tl(e,t){return e.map(e=>String(e[t]??``))}function El(e){let t=1/0,n=-1/0;for(let r of e)r<t&&(t=r),r>n&&(n=r);return t===n&&(t=t===0?0:t*.9,n=n===0?1:n*1.1),[t,n]}function Dl(e){return e>=0?0:e}function Ol(e,t,n,r=5){let i=[];for(let a=0;a<=r;a++){let o=a/r,s=Y.top+n-o*n,c=e+o*(t-e);i.push(`<line class="chart-grid-line" x1="${Y.left}" x2="${600-Y.right}" y1="${s}" y2="${s}"/>`),i.push(`<text class="chart-axis-label" x="${Y.left-8}" y="${s+4}" text-anchor="end">${yl(c)}</text>`)}return i.join(``)}function kl(e,t,n,r){let i=Math.floor(t/50),a=Math.max(1,Math.ceil(e.length/i));return e.map((e,t)=>t%a===0?`<text class="chart-axis-label" x="${Y.left+t*r+r/2}" y="${Y.top+n+18}" text-anchor="middle">${J(e.length>10?`${e.slice(0,9)}…`:e)}</text>`:``).join(``)}function Al(e,t){let n=(e.height??300)-Y.top-Y.bottom,r=600-Y.left-Y.right,i=Tl(e.data,e.xKey),a=e.data.length;if(a===0)return``;let o=r/Math.max(a-1,1),s=1/0,c=-1/0;for(let t of e.yKeys){let[n,r]=El(wl(e.data,t));n<s&&(s=n),r>c&&(c=r)}s=Dl(s);let l=c-s||1,u=e=>Y.top+n-(e-s)/l*n,d=e=>Y.left+e*o,f=``,p=[];for(let r=0;r<e.yKeys.length;r++){let i=wl(e.data,e.yKeys[r]),o=bl(r),s=`M${i.map((e,t)=>`${d(t).toFixed(1)},${u(e).toFixed(1)}`).join(`L`)}`;if(t){let e=`ag${xl}_${r}`;f+=`<linearGradient id="${e}" x1="0" y1="0" x2="0" y2="1">
|
|
336
304
|
<stop offset="0%" stop-color="${o}" stop-opacity="0.3"/>
|
|
337
305
|
<stop offset="100%" stop-color="${o}" stop-opacity="0"/>
|
|
338
|
-
</linearGradient>`;let t=`${s}L${d(a-1).toFixed(1)},${(Y.top+n).toFixed(1)}L${d(0).toFixed(1)},${(Y.top+n).toFixed(1)}Z`;p.push(`<path d="${t}" fill="url(#${e})" stroke="none"/>`)}p.push(`<path d="${s}" fill="none" stroke="${o}" stroke-width="2" stroke-linejoin="round" stroke-linecap="round"/>`);for(let e=0;e<i.length;e++)p.push(`<circle cx="${d(e).toFixed(1)}" cy="${u(i[e]).toFixed(1)}" r="3" fill="${o}" stroke="var(--card)" stroke-width="1.5"/>`)}let m=e.height??300,h=e.showGrid===!1?``:
|
|
306
|
+
</linearGradient>`;let t=`${s}L${d(a-1).toFixed(1)},${(Y.top+n).toFixed(1)}L${d(0).toFixed(1)},${(Y.top+n).toFixed(1)}Z`;p.push(`<path d="${t}" fill="url(#${e})" stroke="none"/>`)}p.push(`<path d="${s}" fill="none" stroke="${o}" stroke-width="2" stroke-linejoin="round" stroke-linecap="round"/>`);for(let e=0;e<i.length;e++)p.push(`<circle cx="${d(e).toFixed(1)}" cy="${u(i[e]).toFixed(1)}" r="3" fill="${o}" stroke="var(--card)" stroke-width="1.5"/>`)}let m=e.height??300,h=e.showGrid===!1?``:Ol(s,c,n),g=kl(i,r,n,a>1?o:r);return`<svg class="chart-svg" viewBox="0 0 600 ${m}" preserveAspectRatio="xMidYMid meet">
|
|
339
307
|
${f?`<defs>${f}</defs>`:``}
|
|
340
308
|
${h}${g}${p.join(``)}
|
|
341
|
-
</svg>`}function
|
|
342
|
-
<title>${J(e.yKeys[i])}: ${
|
|
309
|
+
</svg>`}function jl(e,t){let n=(e.height??300)-Y.top-Y.bottom,r=600-Y.left-Y.right,i=Tl(e.data,e.xKey),a=e.data.length;if(a===0)return``;let o=e.yKeys.length,s=0;for(let t of e.yKeys)for(let n of wl(e.data,t))n>s&&(s=n);s===0&&(s=1);let c=e.height??300,l=[];if(t){let t=Math.min(24,(n-(a-1)*4)/(a*o)),u=t*o+4,d=e.showGrid===!1?``:Ol(0,s,n),f=i.map((e,t)=>{let n=Y.top+t*u+u/2,r=e.length>15?`${e.slice(0,14)}…`:e;return`<text class="chart-axis-label" x="${Y.left-8}" y="${n+4}" text-anchor="end">${J(r)}</text>`}).join(``);for(let n=0;n<a;n++)for(let i=0;i<o;i++){let a=Number(e.data[n][e.yKeys[i]])||0,o=a/s*r,c=Y.top+n*u+i*t;l.push(`<rect x="${Y.left}" y="${c}" width="${o.toFixed(1)}" height="${t-2}" rx="3" fill="${bl(i)}" opacity="0.85">
|
|
310
|
+
<title>${J(e.yKeys[i])}: ${yl(a)}</title>
|
|
343
311
|
</rect>`)}return`<svg class="chart-svg" viewBox="0 0 600 ${Math.max(c,a*u+Y.top+Y.bottom)}" preserveAspectRatio="xMidYMid meet">
|
|
344
312
|
${d}${f}${l.join(``)}
|
|
345
|
-
</svg>`}else{let t=r/a,u=Math.min(40,(t-8)/o),d=e.showGrid===!1?``:
|
|
346
|
-
<title>${J(e.yKeys[i])}: ${
|
|
313
|
+
</svg>`}else{let t=r/a,u=Math.min(40,(t-8)/o),d=e.showGrid===!1?``:Ol(0,s,n),f=kl(i,r,n,t);for(let r=0;r<a;r++)for(let i=0;i<o;i++){let a=Number(e.data[r][e.yKeys[i]])||0,c=a/s*n,d=Y.left+r*t+(t-u*o)/2+i*u,f=Y.top+n-c;l.push(`<rect x="${d.toFixed(1)}" y="${f.toFixed(1)}" width="${(u-2).toFixed(1)}" height="${c.toFixed(1)}" rx="3" fill="${bl(i)}" opacity="0.85">
|
|
314
|
+
<title>${J(e.yKeys[i])}: ${yl(a)}</title>
|
|
347
315
|
</rect>`)}return`<svg class="chart-svg" viewBox="0 0 600 ${c}" preserveAspectRatio="xMidYMid meet">
|
|
348
316
|
${d}${f}${l.join(``)}
|
|
349
|
-
</svg>`}}function
|
|
350
|
-
<title>${J(l[e]||`Item ${e+1}`)}: ${
|
|
351
|
-
</path>`),f=p}let p=t?`<text x="${r}" y="${i-6}" text-anchor="middle" fill="var(--foreground)" font-size="18" font-weight="700">${
|
|
352
|
-
<text x="${r}" y="${i+12}" text-anchor="middle" fill="var(--muted-foreground)" font-size="11">Total</text>`:``,m=
|
|
317
|
+
</svg>`}}function Ml(e,t){let n=e.height??300,r=n/2,i=n/2,a=n/2-10,o=t?a*.55:0,s=e.yKeys[0]||`value`,c=e.data.map(e=>Math.max(0,Number(e[s])||0)),l=Tl(e.data,e.xKey),u=c.reduce((e,t)=>e+t,0);if(u===0)return`<div style="color:var(--muted-foreground);text-align:center;padding:20px">No data</div>`;let d=[],f=-Math.PI/2;for(let e=0;e<c.length;e++){let t=c[e]/u;if(t===0)continue;let n=t*Math.PI*2,s=f,p=f+n,m=r+a*Math.cos(s),h=i+a*Math.sin(s),g=r+a*Math.cos(p),_=i+a*Math.sin(p),v=+(n>Math.PI),y;if(o>0){let e=r+o*Math.cos(s),t=i+o*Math.sin(s),n=r+o*Math.cos(p),c=i+o*Math.sin(p);y=`M${m.toFixed(2)},${h.toFixed(2)} A${a},${a} 0 ${v},1 ${g.toFixed(2)},${_.toFixed(2)} L${n.toFixed(2)},${c.toFixed(2)} A${o},${o} 0 ${v},0 ${e.toFixed(2)},${t.toFixed(2)}Z`}else y=`M${r},${i} L${m.toFixed(2)},${h.toFixed(2)} A${a},${a} 0 ${v},1 ${g.toFixed(2)},${_.toFixed(2)}Z`;d.push(`<path d="${y}" fill="${bl(e)}" stroke="var(--background)" stroke-width="2" opacity="0.9">
|
|
318
|
+
<title>${J(l[e]||`Item ${e+1}`)}: ${yl(c[e])} (${(t*100).toFixed(1)}%)</title>
|
|
319
|
+
</path>`),f=p}let p=t?`<text x="${r}" y="${i-6}" text-anchor="middle" fill="var(--foreground)" font-size="18" font-weight="700">${yl(u)}</text>
|
|
320
|
+
<text x="${r}" y="${i+12}" text-anchor="middle" fill="var(--muted-foreground)" font-size="11">Total</text>`:``,m=Cl(l.filter((e,t)=>c[t]>0));return`<svg class="chart-svg" viewBox="0 0 ${n} ${n}" preserveAspectRatio="xMidYMid meet">
|
|
353
321
|
${d.join(``)}${p}
|
|
354
|
-
</svg>${m}`}function
|
|
322
|
+
</svg>${m}`}function Nl(e){let t=e.height??40,n=e.yKeys[0]||`value`,r=wl(e.data,n),i=r.length;if(i===0)return``;let[a,o]=El(r),s=o-a||1,c=200/Math.max(i-1,1),l=r.map((e,n)=>`${(n*c).toFixed(1)},${(t-4-(e-a)/s*(t-8)).toFixed(1)}`),u=`spk${xl}`,d=bl(0);return`<svg class="chart-svg" viewBox="0 0 200 ${t}" preserveAspectRatio="xMidYMid meet" style="max-width:200px;height:${t}px">
|
|
355
323
|
<defs>
|
|
356
324
|
<linearGradient id="${u}" x1="0" y1="0" x2="0" y2="1">
|
|
357
325
|
<stop offset="0%" stop-color="${d}" stop-opacity="0.2"/>
|
|
@@ -361,15 +329,27 @@ $3`),n.push(t);break}case`code`:n.push(`\`\`\`${e.language??``}\n${String(e.valu
|
|
|
361
329
|
<path d="M${l.join(`L`)}L${((i-1)*c).toFixed(1)},${t}L0,${t}Z" fill="url(#${u})" stroke="none"/>
|
|
362
330
|
<polyline points="${l.join(` `)}" fill="none" stroke="${d}" stroke-width="1.5" stroke-linejoin="round"/>
|
|
363
331
|
<circle cx="${((i-1)*c).toFixed(1)}" cy="${l[i-1].split(`,`)[1]}" r="2.5" fill="${d}"/>
|
|
364
|
-
</svg>`}function
|
|
365
|
-
<title>${J(t[a])} / ${J(e.yKeys[n])}: ${
|
|
332
|
+
</svg>`}function Pl(e){let t=Tl(e.data,e.xKey),n=e.data.length,r=e.yKeys.length;if(n===0||r===0)return``;let i=1/0,a=-1/0;for(let t of e.yKeys)for(let n of wl(e.data,t))n<i&&(i=n),n>a&&(a=n);let o=a-i||1,s=Math.min(50,(600-Y.left-Y.right)/n),c=Math.min(30,200/r),l=Y.left+n*s+Y.right,u=Y.top+r*c+Y.bottom,d=[];for(let t=0;t<r;t++){let n=Y.top+t*c+c/2+4,r=e.yKeys[t].length>8?`${e.yKeys[t].slice(0,7)}…`:e.yKeys[t];d.push(`<text class="chart-axis-label" x="${Y.left-8}" y="${n}" text-anchor="end">${J(r)}</text>`)}let f=Math.floor((l-Y.left)/40),p=Math.max(1,Math.ceil(n/f));for(let e=0;e<n;e++){if(e%p!==0)continue;let n=Y.left+e*s+s/2,r=t[e].length>6?`${t[e].slice(0,5)}…`:t[e];d.push(`<text class="chart-axis-label" x="${n}" y="${u-8}" text-anchor="middle">${J(r)}</text>`)}for(let a=0;a<n;a++)for(let n=0;n<r;n++){let r=Number(e.data[a][e.yKeys[n]])||0,l=(r-i)/o,u=Y.left+a*s,f=Y.top+n*c;d.push(`<rect x="${u}" y="${f}" width="${s-1}" height="${c-1}" rx="2" fill="var(--primary)" opacity="${(.1+l*.8).toFixed(2)}">
|
|
333
|
+
<title>${J(t[a])} / ${J(e.yKeys[n])}: ${yl(r)}</title>
|
|
366
334
|
</rect>`)}return`<svg class="chart-svg" viewBox="0 0 ${l} ${u}" preserveAspectRatio="xMidYMid meet">
|
|
367
335
|
${d.join(``)}
|
|
368
|
-
</svg>`}function
|
|
369
|
-
`)}</tbody></table></div>`}function
|
|
370
|
-
`)}
|
|
371
|
-
`)}function
|
|
372
|
-
|
|
336
|
+
</svg>`}function Fl(e){if(e.length===0)return`<p><em>empty table</em></p>`;let t=Object.keys(e[0]);return`<div class="table-wrap"><table><thead><tr>${t.map(e=>`<th>${U(e)}</th>`).join(``)}</tr></thead><tbody>${e.map(e=>`<tr>${t.map(t=>`<td>${U(String(e[t]??``))}</td>`).join(``)}</tr>`).join(`
|
|
337
|
+
`)}</tbody></table></div>`}function Il(e){return`<div class="metric-grid">${e.map(e=>`<div class="metric"><div class="metric-value">${U(String(e.value))}</div><div class="metric-label">${U(e.label)}</div></div>`).join(``)}</div>`}function Ll(e){return`<div class="card-grid">${e.map(e=>{let t=[`<div class="card">`];return e.title&&t.push(`<div class="card-title">${U(String(e.title))}</div>`),(e.body||e.description)&&t.push(`<div class="card-body">${U(String(e.body??e.description))}</div>`),(e.badge||e.status)&&t.push(`<span class="badge">${U(String(e.badge??e.status))}</span>`),t.push(`</div>`),t.join(``)}).join(``)}</div>`}function Rl(e){if(`name`in e&&`children`in e&&Array.isArray(e.children))return zl(e);if(`name`in e&&!(`children`in e))return`<div class="tree-node"><span class="tree-key">${U(String(e.name))}</span></div>`;let t=[];for(let[n,r]of Object.entries(e))typeof r==`object`&&r&&!Array.isArray(r)?t.push(`<div class="tree-node"><span class="tree-key">${U(n)}:</span><div class="tree-children">${Rl(r)}</div></div>`):t.push(`<div class="tree-node"><span class="tree-key">${U(n)}:</span> ${U(Fa(r))}</div>`);return t.join(``)}function zl(e){let t=U(String(e.name));return!e.children||e.children.length===0?`<div class="tree-node"><span class="tree-key">${t}</span></div>`:`<div class="tree-node"><span class="tree-key">${t}</span><div class="tree-children">${e.children.map(e=>typeof e==`object`&&e?zl(e):`<div class="tree-node"><span class="tree-key">${U(String(e))}</span></div>`).join(``)}</div></div>`}function Bl(e){let t=[`graph LR`];for(let n of e.nodes){let e=Ia(String(n.id??n.name??``)),r=String(n.label??n.name??e);t.push(` ${e}["${r}"]`)}for(let n of e.edges){let e=Ia(String(n.source??n.from??``)),r=Ia(String(n.target??n.to??``)),i=n.label?`|${String(n.label)}|`:``;t.push(` ${e} -->${i} ${r}`)}return t.join(`
|
|
338
|
+
`)}An.setOptions({async:!1,gfm:!0,breaks:!0}),An.use({renderer:{html(e){return U(e.text)},link(e){let t=e.href??``,n=t.replace(/\s/g,``).toLowerCase();if(n.startsWith(`javascript:`)||n.startsWith(`vbscript:`)||n.startsWith(`data:`))return this.parser.parseInline(e.tokens);let r=e.title?` title="${U(e.title)}"`:``,i=this.parser.parseInline(e.tokens);return`<a href="${U(t)}"${r}>${i}</a>`}}});function Vl(e,t,n){let r=[];if(e&&r.push(`# ${e}\n`),typeof t==`string`)r.push(t);else if(Array.isArray(t))if(t.length===0)r.push(`*(empty)*`);else if(Xc(t[0])||typeof t[0]==`object`&&t[0]!==null&&typeof t[0].type==`string`)for(let e of t)r.push(Hl(Jc(e),n));else if(typeof t[0]==`object`&&t[0]!==null)n?.compactTables?r.push(Wl(t)):r.push(Ul(t));else for(let e of t)r.push(`- ${String(e)}`);else if(typeof t==`object`&&t){let e=t;if(Array.isArray(e.blocks)&&e.blocks.length>0)for(let t of e.blocks)Xc(t)||typeof t==`object`&&t&&typeof t.type==`string`?r.push(Hl(Jc(t),n)):typeof t==`object`&&t?r.push(Jl(t)):r.push(String(t));else Array.isArray(e.nodes)&&Array.isArray(e.edges)?r.push(ql(e)):Array.isArray(e.metrics)?r.push(Kl(e.metrics)):r.push(Jl(e))}else r.push(String(t));return r.join(`
|
|
339
|
+
`)}function Hl(e,t){let n=[];switch(e.title&&n.push(`## ${e.title}\n`),e.type){case`markdown`:{let t=String(e.value??``);t=t.replace(/(^|\n)((?!\|)[^\n]+)\n(\|)/g,`$1$2
|
|
340
|
+
|
|
341
|
+
$3`),n.push(t);break}case`code`:n.push(`\`\`\`${e.language??``}\n${String(e.value??``)}\n\`\`\``);break;case`mermaid`:n.push(`\`\`\`mermaid\n${String(e.value??``)}\n\`\`\``);break;case`table`:{let r=e.value;if(Array.isArray(r)&&r.length>0)t?.compactTables?n.push(Wl(r,e.title)):n.push(Ul(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(`
|
|
342
|
+
`))}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(Kl(e.value));break;case`graph`:e.value&&typeof e.value==`object`&&n.push(ql(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(Jl(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(Gl(r.columns,e.title));else{let e=Math.max(...r.columns.map(e=>e.items?.length??0)),t=r.columns.map(e=>e.title);n.push(`| ${t.join(` | `)} |`),n.push(`| ${t.map(()=>`---`).join(` | `)} |`);for(let t=0;t<e;t++)n.push(`| ${r.columns.map(e=>e.items?.[t]??``).join(` | `)} |`)}break}case`status-board`:{let t=e.value;if(t?.items)for(let e of t.items){let t=e.status===`success`?`🟢`:e.status===`warning`?`🟡`:e.status===`error`?`🔴`:e.status===`info`?`🔵`:`⚪`;n.push(`${t} **${e.label}**${e.detail?` — ${e.detail}`:``}`)}break}case`prompt`:{let t=e.value;t?.question&&(n.push(`> **${t.question}**`),t.context&&n.push(`> ${t.context}`));break}case`progress`:{let t=e.value;if(t?.items)for(let e of t.items){let t=e.max??100,r=t>0?Math.round(e.value/t*100):0,i=Math.round(r/5),a=`█`.repeat(i)+`░`.repeat(20-i);n.push(`${e.label}: ${a} ${r}%`)}break}case`docs-browser`:{let t=e.value,r={current:`✅`,stale:`⚠️`,missing:`❌`};t?.title?.trim()&&n.push(`## ${t.title.trim()}`);let i=Array.isArray(t?.files)?t.files:[];if(i.length===0){n.push(`*(No content available)*`);break}i.forEach((e,t)=>{let a=e?.path?.trim()||`document-${t+1}`,o=e?.title?.trim()||a.split(/[\\/]/).pop()||a,s=e?.status&&r[e.status]?r[e.status]:`📄`;n.push(`${s} **${o}** (\`${a}\`)`),n.push(``),typeof e?.content==`string`&&e.content.trim().length>0?n.push(e.content.trim()):n.push(`*(No content available)*`),t<i.length-1&&(n.push(``),n.push(`---`),n.push(``))});break}case`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(`---
|
|
343
|
+
`);break;default:n.push(JSON.stringify(e.value,null,2))}return n.push(``),n.join(`
|
|
344
|
+
`)}function Ul(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(`
|
|
345
|
+
`)}function Wl(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(`
|
|
346
|
+
`)}function Gl(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(`
|
|
347
|
+
`)}function Kl(e){return e.map(e=>`- **${e.label}**: ${e.value}`).join(`
|
|
348
|
+
`)}function ql(e){let t=["```mermaid",`graph LR`];for(let n of e.nodes){let e=Ia(String(n.id??n.name??``)),r=String(n.label??n.name??e);t.push(` ${e}["${r}"]`)}for(let n of e.edges){let e=Ia(String(n.source??n.from??``)),r=Ia(String(n.target??n.to??``)),i=n.label?`|${String(n.label)}|`:``;t.push(` ${e} -->${i} ${r}`)}return t.push("```"),t.join(`
|
|
349
|
+
`)}function Jl(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(Jl(a,t+1))):r.push(`${n}- **${i}**: ${Fa(a)}`);return r.join(`
|
|
350
|
+
`)}function Yl(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Xl(e){return e.replace(/<table\b/g,`<div class="table-wrap"><table`).replace(/<\/table>/g,`</table></div>`)}function Zl(e){let t=encodeURIComponent(e).replace(/%([0-9A-F]{2})/g,(e,t)=>String.fromCharCode(Number.parseInt(t,16))),n=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,r=``;for(let e=0;e<t.length;e+=3){let i=t.charCodeAt(e)<<16|(t.charCodeAt(e+1)||0)<<8|(t.charCodeAt(e+2)||0);r+=n[i>>18&63],r+=n[i>>12&63],r+=e+1<t.length?n[i>>6&63]:`=`,r+=e+2<t.length?n[i&63]:`=`}return r}function Ql(e,t){if(typeof e!=`object`||!e)return`<p>${U(String(e))}</p>`;let n=e;return typeof n.type==`string`?yu(Jc(n),t):`<pre>${U(JSON.stringify(e,null,2))}</pre>`}function $l(e,t,n=`inline`){let r=[];if(e&&r.push(`<h1>${U(e)}</h1>`),typeof t==`string`)r.push(`<div class="md-content">${Xl(An.parse(t))}</div>`);else if(Array.isArray(t))if(t.length===0)r.push(`<p><em>empty</em></p>`);else if(Xc(t[0]))for(let e of t)r.push(Ql(e,n));else typeof t[0]==`object`&&t[0]!==null?r.push(Fl(t)):r.push(`<ul>${t.map(e=>`<li>${U(String(e))}</li>`).join(``)}</ul>`);else if(typeof t==`object`&&t){let e=t;if(Array.isArray(e.blocks)&&e.blocks.length>0)for(let t of e.blocks)r.push(Ql(t,n));else Array.isArray(e.metrics)?r.push(Il(e.metrics)):Array.isArray(e.nodes)&&Array.isArray(e.edges)?r.push(`<pre class="mermaid">${U(Bl(e))}</pre>`):r.push(Rl(e))}else r.push(`<p>${U(String(t))}</p>`);let i=r.join(`
|
|
351
|
+
`);return i.includes(`class="mermaid"`)&&!i.includes(`mermaid.min.js`)?`${i}\n<script src="https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.min.js"><\/script>\n<script>mermaid.run();<\/script>`:i}function eu(e){let t=String(e.value??``);return/^\s*<svg[\s>]/i.test(t)?`<div class="md-content"><img src="data:image/svg+xml;base64,${Zl(t)}" alt="SVG diagram" style="max-width:100%;" /></div>`:/^\s*</.test(t)?`<div class="md-content">${t}</div>`:`<div class="md-content">${Xl(An.parse(t))}</div>`}function tu(e){return`<pre><code>${U(String(e.value??``))}</code></pre>`}function nu(e){return`<pre class="mermaid">${U(String(e.value??``))}</pre>`}function ru(e){if(Array.isArray(e.value)){let t=e.value;if(t.length>0&&Array.isArray(t[0])){let e=t,n=e[0].map(String);return Fl(e.slice(1).map(e=>Object.fromEntries(n.map((t,n)=>[t,e[n]]))))}return Fl(t)}if(e.value&&typeof e.value==`object`&&`headers`in e.value&&`rows`in e.value){let{headers:t,rows:n}=e.value;return Fl(n.map(e=>Object.fromEntries(t.map((t,n)=>[t,e[n]]))))}return``}function iu(e){let t;return Array.isArray(e.value)?t=e.value:e.value&&typeof e.value==`object`&&(t=Object.entries(e.value).map(([e,t])=>({label:e,value:String(t)}))),t?Il(t):``}function au(e){return Array.isArray(e.value)?Ll(e.value):``}function ou(e){return e.value&&typeof e.value==`object`?Rl(e.value):``}function su(e,t){return!e.value||typeof e.value!=`object`?``:`<pre class="mermaid">${U(Bl(e.value))}</pre>`}function cu(e){let t=e.value;return Array.isArray(t)&&(t={items:t.map(e=>({title:String(e.event??e.title??``),phase:e.date==null?e.phase==null?void 0:String(e.phase):String(e.date),description:e.description==null?void 0:String(e.description),status:e.status??`done`}))}),t?fl(t):``}function lu(e){return e.value?pl(Array.isArray(e.value)?{items:e.value}:e.value):``}function uu(e){return e.value?ml(Array.isArray(e.value)?{columns:e.value}:e.value):``}function du(e){return e.value?hl(Array.isArray(e.value)?{items:e.value}:e.value):``}function fu(e){if(!e.value)return``;let t=e.value;return Array.isArray(t)?t={items:t}:Yl(t)&&!(`items`in t)&&`label`in t&&`value`in t&&(t={items:[t]}),_l(t)}function pu(e){return`<div class="md-content">${An.parse(String(e.value??``))}</div>`}function mu(e){let t=Math.min(Math.max(Number(e.level)||2,1),6);return`<h${t}>${U(String(e.value??``))}</h${t}>`}function hu(e){return`<p>${U(String(e.value??``))}</p>`}function gu(e){return`<div class="action-bar">${(Array.isArray(e.value)?e.value:[]).map(e=>{if(e.type===`select`){let t=Array.isArray(e.options)?e.options.map(e=>`<option value="${U(String(e.value??e.label??``))}">${U(String(e.label??e.value??``))}</option>`).join(``):``;return`<select class="action-select"><option value="">${U(String(e.label??`Select...`))}</option>${t}</select>`}return`<button class="action-btn action-${String(e.variant??`secondary`)}">${U(String(e.label??``))}</button>`}).join(``)}</div>`}function _u(e){return`<pre>${U(JSON.stringify(e.value,null,2))}</pre>`}const vu=new Map([[`markdown`,e=>eu(e)],[`code`,e=>tu(e)],[`mermaid`,e=>nu(e)],[`table`,e=>ru(e)],[`metrics`,e=>iu(e)],[`cards`,e=>au(e)],[`tree`,e=>ou(e)],[`graph`,(e,t)=>su(e,t)],[`chart`,e=>Sl(e)],[`timeline`,e=>cu(e)],[`checklist`,e=>lu(e)],[`comparison`,e=>uu(e)],[`status-board`,e=>du(e)],[`prompt`,e=>e.value?gl(e.value):``],[`progress`,e=>fu(e)],[`docs-browser`,e=>e.value?vl(e.value):``],[`text`,e=>pu(e)],[`heading`,e=>mu(e)],[`paragraph`,e=>hu(e)],[`separator`,()=>`<hr class="separator">`],[`actions`,e=>gu(e)]]);function yu(e,t=`inline`){let n=[];e.title&&n.push(`<h2>${U(e.title)}</h2>`);let r=vu.get(e.type);return n.push(r?r(e,t):_u(e)),n.join(`
|
|
352
|
+
`)}const bu=import.meta.dirname??g(b(import.meta.url));function xu(e){let t=e;for(let e=0;e<10;e++){try{let e=v(t,`package.json`);if(o(e)&&JSON.parse(c(e,`utf8`)).name===`@vpxa/aikit`)return t}catch{}let e=g(t);if(e===t)break;t=e}return y(e,`..`,`..`,`..`)}const Su=`ui://aikit/present.html`;function Cu(e){return Array.isArray(e)?e:[]}function wu(e){return e.length===0?``:`<section class="present-inline-actions"><div class="action-bar">${e.map(e=>{let t=U(String(e.id??``)),n=U(String(e.label??`Action`));return e.type===`select`?`<label class="action-select-wrap"><span>${n}</span><select class="action-select" data-present-action="select" data-action-id="${t}"><option value="">${n}</option>${Array.isArray(e.options)?e.options.map(e=>{if(typeof e==`string`){let t=U(e);return`<option value="${t}">${t}</option>`}return`<option value="${U(String(e.value??e.label??``))}">${U(String(e.label??e.value??``))}</option>`}).join(``):``}</select></label>`:`<button type="button" class="action-btn action-${U(String(e.variant??`default`))}" data-present-action="button" data-action-id="${t}" data-action-value="clicked">${n}</button>`}).join(``)}</div><div id="action-feedback" class="action-feedback" aria-live="polite"></div></section>`}function Tu(e,t,n){return`<!DOCTYPE html>
|
|
373
353
|
<html lang="en">
|
|
374
354
|
<head>
|
|
375
355
|
<meta charset="utf-8">
|
|
@@ -447,8 +427,8 @@ $3`),n.push(t);break}case`code`:n.push(`\`\`\`${e.language??``}\n${String(e.valu
|
|
|
447
427
|
</head>
|
|
448
428
|
<body>
|
|
449
429
|
<div class="present-inline-root">
|
|
450
|
-
${
|
|
451
|
-
${
|
|
430
|
+
${$l(e,t,`inline`)}
|
|
431
|
+
${wu(n)}
|
|
452
432
|
</div>
|
|
453
433
|
<script>
|
|
454
434
|
function sendCallback(actionId, value) {
|
|
@@ -483,7 +463,7 @@ $3`),n.push(t);break}case`code`:n.push(`\`\`\`${e.language??``}\n${String(e.valu
|
|
|
483
463
|
});
|
|
484
464
|
<\/script>
|
|
485
465
|
</body>
|
|
486
|
-
</html>`}const
|
|
466
|
+
</html>`}const Eu=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)`)}),Du={format:F.enum([`html`,`browser`]).default(`html`).describe(`Output format.
|
|
487
467
|
- "html" (default): Rich markdown in chat + embedded UIResource for MCP-UI hosts. Actions shown as numbered choices.
|
|
488
468
|
- "browser": Rich markdown in chat + opens beautiful themed dashboard in the browser. When actions are provided, the browser shows interactive buttons and the tool blocks until user clicks, returning their selection.`),title:F.string().optional().describe(`Optional heading`),content:F.any().describe(`Content to present. Accepts these shapes:
|
|
489
469
|
• markdown string — rendered as rich text
|
|
@@ -491,7 +471,7 @@ $3`),n.push(t);break}case`code`:n.push(`\`\`\`${e.language??``}\n${String(e.valu
|
|
|
491
471
|
• { nodes, edges } — rendered as mermaid graph
|
|
492
472
|
• typed blocks array [{ type, title?, value }] — the primary format:
|
|
493
473
|
${Ec()}\n• any JSON — rendered as collapsible tree
|
|
494
|
-
IMPORTANT: For charts, use the ChartValue format above. Do NOT use Chart.js format ({labels, datasets}) — it will be auto-converted but the native format is preferred.`),actions:F.array(
|
|
474
|
+
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(Eu).optional().describe(`Interactive actions (buttons/selects). In html mode, shown as numbered choices. In browser mode, rendered as clickable buttons and the tool blocks until user clicks.`),template:F.enum([`auto`,`list-sort`,`data-table`,`picker`,`flame-graph`,`form`,`timeline`,`kanban`,`tree`,`diff-view`,`dashboard`]).optional().describe(`UI template for interactive display in MCP Apps hosts.
|
|
495
475
|
- auto (default): detect from content shape
|
|
496
476
|
- list-sort: drag-drop reorderable list — content: { items: [{id, label}] }
|
|
497
477
|
- data-table: filterable sortable table — content: { columns: [{key, label}], rows: [{...}], stats?: [{label, value}] }
|
|
@@ -502,15 +482,15 @@ IMPORTANT: For charts, use the ChartValue format above. Do NOT use Chart.js form
|
|
|
502
482
|
- kanban: drag-drop board — content: { columns: [{id, label, color?}], cards: [{id, title, column, tags?[], priority?}] }
|
|
503
483
|
- tree: collapsible tree view — content: { root: {label, children?:[...]} | [...] }
|
|
504
484
|
- diff-view: side-by-side diff — content: { files: [{path, status, additions, deletions, hunks:[{header, changes:[{type, content}]}]}] }
|
|
505
|
-
- dashboard: metric cards grid — content: { metrics: [{label, value, trend?, status?, type?}] }`)};let
|
|
485
|
+
- dashboard: metric cards grid — content: { metrics: [{label, value, trend?, status?, type?}] }`)};let Ou,ku=!1,Au=null;process.on(`exit`,()=>{if(Au){try{Au.close()}catch{}Au=null}});function ju(){let e=xu(bu),t=v(e,`packages`,`present`,`dist`,`index.html`);return o(t)?t:v(e,`packages`,`present`,`index.html`)}function Mu(){if(!Ou)try{Ou=c(ju(),`utf-8`)}catch{Ou=``}return Ou}function Nu(e,t){let n=z(`present`),r=Mu(),i=`Present content to the user in the best format. Two modes:
|
|
506
486
|
- "html" (default): Rich markdown in chat + embedded UIResource. Use for display-only content (tables, charts, reports, status boards) where no user interaction is needed.
|
|
507
487
|
- "browser": Serves a themed dashboard on a local URL. Use ONLY when you need user interaction back (confirmations, selections, form input). The tool blocks until user clicks an action button, then returns their selection.
|
|
508
488
|
FORMAT RULE: If no user interaction is needed → use "html". If you need user input back → use "browser".
|
|
509
489
|
CONTENT GUIDE: Pass typed blocks [{ type, title?, value }] for structured content. See the \`content\` parameter description for all supported block types and their value shapes. For charts: use {chartType, data:Record[], xKey, yKeys} — NOT Chart.js format.
|
|
510
|
-
BROWSER WORKFLOW: After calling present with format "browser", you MUST extract the URL from the response and call openBrowserPage({ url }) tool - PlayWright MCP to open it in VS Code Simple Browser. A system browser fallback also opens automatically, but always call openBrowserPage tool - PlayWright MCP yourself.`,a=async({format:e,title:n,content:r,actions:i,template:a})=>{let o=La(r);return(e??`html`)===`browser`||Array.isArray(i)&&i.length>0?await
|
|
490
|
+
BROWSER WORKFLOW: After calling present with format "browser", you MUST extract the URL from the response and call openBrowserPage({ url }) tool - PlayWright MCP to open it in VS Code Simple Browser. A system browser fallback also opens automatically, but always call openBrowserPage tool - PlayWright MCP yourself.`,a=async({format:e,title:n,content:r,actions:i,template:a})=>{let o=La(r);return(e??`html`)===`browser`||Array.isArray(i)&&i.length>0?await Pu(n,o,i,t,a):Fu(n,o,i)};if(r){ku||=(bn(e,`AI Kit Present App`,Su,{description:`Rich interactive content viewer for AI Kit tools`},async()=>({contents:[{uri:Su,mimeType:yn,text:r}]})),!0),xn(e,`present`,{title:n.title,description:i,annotations:n.annotations,inputSchema:Du,_meta:{ui:{resourceUri:Su}}},a);return}e.tool(`present`,i,Du,n.annotations,a)}async function Pu(e,t,n,r,i){let a=Vl(e,t,{compactTables:!0}),o=Cu(n),s=Tu(e,t,o),{html:c,assets:l}=ul(e,t,n,i),u=kn({uri:`ui://aikit/present-browser.html`,content:{type:`rawHtml`,htmlString:s},encoding:`text`,adapters:{mcpApps:{enabled:!0}}}),d,f,p=``,m;try{Au&&=(Au.close(),null),o.length>0&&(d=new Promise(e=>{f=e}));let e=!1;p=await new Promise((t,n)=>{let r=On((t,n)=>{if(e||(e=!0,m&&clearTimeout(m)),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);f?.(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}let r=l.get(t.url??``);if(r){n.writeHead(200,{"Content-Type":r.contentType,"Cache-Control":`no-cache`}),n.end(r.content);return}n.writeHead(200,{"Content-Type":`text/html; charset=utf-8`}),n.end(c)});r.listen(0,`127.0.0.1`,()=>{let i=r.address();if(typeof i==`object`&&i){Au=r;let n=`http://127.0.0.1:${i.port}`;m=setTimeout(()=>{if(!e)try{Tn(process.platform===`win32`?`start "" "${n}"`:process.platform===`darwin`?`open "${n}"`:`xdg-open "${n}"`)}catch{}},8e3),m.unref(),t(n)}else n(Error(`Failed to start present server`))}),setTimeout(()=>{r.close(),Au===r&&(Au=null)},300*1e3).unref()})}catch{}let h=p?`${a}\n\n---\n🌐 **Dashboard opened in browser:** ${p}\n\n**IMPORTANT:** You MUST now open this URL using the \`openBrowserPage\` tool - PlayWright MCP. If that tool is unavailable, open the URL in the system browser as a fallback. If neither works, ask the user to open the URL manually.`:a;if(o.length>0&&r?.available&&d)try{let e=await Promise.race([d,new Promise((e,t)=>setTimeout(()=>t(Error(`timeout`)),300*1e3))]);return{content:[{type:`text`,text:`${h}\n\n✅ **Selected:** ${e.actionId} = \`${e.value}\``},u]}}catch{return{content:[{type:`text`,text:`${h}\n\n⚠️ *No selection received (timed out).*`},u]}}return{content:[{type:`text`,text:h},u]}}function Fu(e,t,n){let r=Cu(n),i=Vl(e,t,{compactTables:!0}),a=kn({uri:Su,content:{type:`rawHtml`,htmlString:$l(e,t)},encoding:`text`,adapters:{mcpApps:{enabled:!0}}});return{content:[{type:`text`,text:i},a],structuredContent:{title:e,content:Qc(t),actions:r}}}const Iu=k(`tools`);function Lu(e,t){let n=new on({structure:new cn,dependencies:new nn,symbols:new ln,patterns:new sn,entryPoints:new an,diagrams:new rn}),r=z(`produce_knowledge`);e.registerTool(`produce_knowledge`,{title:r.title,description:`Run automated codebase analysis and produce synthesis instructions. Executes Tier 1 deterministic analyzers, then returns structured baselines and instructions for you to synthesize knowledge using remember.`,inputSchema:{scope:F.string().optional().describe(`Root path to analyze (defaults to workspace root)`),aspects:F.array(F.enum([`all`,`structure`,`dependencies`,`symbols`,`patterns`,`entry-points`,`diagrams`])).default([`all`]).describe(`Which analysis aspects to run`)},annotations:r.annotations},async({scope:e,aspects:r})=>{try{let i=e??`.`;Iu.info(`Running knowledge production`,{rootPath:i,aspects:r});let a=await n.runExtraction(i,r);try{let e=t?.onboardDir??v(i,`.ai`,`context`);s(e,{recursive:!0});let n=`<!-- Generated by produce_knowledge at ${new Date().toISOString()} -->\n\n`;for(let[t,r]of Object.entries(a))r&&typeof r==`string`&&p(v(e,`${t}.md`),n+r,`utf-8`);Iu.info(`Knowledge persisted to .ai/context/`,{files:Object.keys(a).length})}catch(e){Iu.warn(`Failed to persist knowledge to .ai/context/`,{error:j(e)})}return{content:[{type:`text`,text:n.buildSynthesisInstructions(a,r)+`
|
|
511
491
|
|
|
512
492
|
---
|
|
513
|
-
_Next: Review the baselines above and use \`remember\` to store synthesized knowledge entries._`}]}}catch(e){return
|
|
493
|
+
_Next: Review the baselines above and use \`remember\` to store synthesized knowledge entries._`}]}}catch(e){return Iu.error(`Knowledge production failed`,j(e)),H(`INTERNAL`,`Knowledge production failed: ${e instanceof Error?e.message:String(e)}`)}})}const X=k(`tools`);function Ru(e,t,n,r,i,a,o){let s=z(`reindex`);e.registerTool(`reindex`,{title:s.title,description:`Trigger re-indexing of the AI Kit index. Can do incremental (only changed files) or full re-index. When smart indexing is active, use force: true to override the automatic trickle indexer.`,inputSchema:{full:F.boolean().default(!1).describe(`If true, force full re-index ignoring file hashes`),force:F.boolean().default(!1).describe(`If true, override smart indexing guard and run reindex anyway`)},annotations:s.annotations},async({full:e,force:s},c)=>{try{if(t.isIndexing)return{content:[{type:`text`,text:`## Reindex Already in Progress
|
|
514
494
|
|
|
515
495
|
A reindex operation is currently running. Search and other tools continue to work with existing data. Use \`status({})\` to check when it completes.`}]};if(o===`smart`&&!s)return{content:[{type:`text`,text:`## Smart Indexing Active
|
|
516
496
|
|
|
@@ -518,38 +498,38 @@ Smart indexing (trickle mode) is enabled — files are automatically indexed as
|
|
|
518
498
|
|
|
519
499
|
**If the index is severely outdated**, use \`reindex({ force: true })\` to override.
|
|
520
500
|
|
|
521
|
-
Use \`status({})\` to check smart indexing queue status.`}]};let l=Ea(c).createTask(`Reindex`,1);l.progress(0,`Starting ${e?`full`:`incremental`} reindex`),X.info(`Starting background re-index`,{mode:e?`full`:`incremental`});let u=e=>t=>{t.phase===`chunking`&&t.currentFile&&X.debug(`Re-index progress`,{prefix:e,current:t.filesProcessed+1,total:t.filesTotal,file:t.currentFile})};return(e?t.reindexAll(n,u(`Reindex`)):t.index(n,u(`Index`))).then(async e=>{if(X.info(`Background re-index complete`,{filesProcessed:e.filesProcessed,chunksCreated:e.chunksCreated,durationMs:e.durationMs}),l.complete(`Reindex complete: ${e.filesProcessed} files, ${e.chunksCreated} chunks in ${e.durationMs}ms`),i)try{await i.createFtsIndex(),X.info(`FTS index rebuilt after reindex`)}catch(e){X.warn(`FTS index rebuild failed`,j(e))}try{let e=await r.reindexAll();X.info(`Curated re-index complete`,{indexed:e.indexed})}catch(e){X.warn(`Curated re-index failed`,j(e))}if(a)try{await a.notifyAfterReindex()}catch(e){X.warn(`Post-reindex resource notification failed`,j(e))}}).catch(e=>{l.fail(`Reindex failed: ${e instanceof Error?e.message:String(e)}`),X.error(`Background reindex failed`,j(e))}),{content:[{type:`text`,text:`## Reindex Started (Background)\n\n- **Mode**: ${e?`Full`:`Incremental`}\n- Search and other tools continue to work with existing data during reindex.\n- Completion will be logged. Use \`status({})\` to check index stats afterward.\n\n---\n_Next: Continue working — the reindex runs in the background._`}]}}catch(e){return X.error(`Reindex failed`,j(e)),H(`INTERNAL`,`Reindex failed: ${e instanceof Error?e.message:String(e)}`)}})}const
|
|
501
|
+
Use \`status({})\` to check smart indexing queue status.`}]};let l=Ea(c).createTask(`Reindex`,1);l.progress(0,`Starting ${e?`full`:`incremental`} reindex`),X.info(`Starting background re-index`,{mode:e?`full`:`incremental`});let u=e=>t=>{t.phase===`chunking`&&t.currentFile&&X.debug(`Re-index progress`,{prefix:e,current:t.filesProcessed+1,total:t.filesTotal,file:t.currentFile})};return(e?t.reindexAll(n,u(`Reindex`)):t.index(n,u(`Index`))).then(async e=>{if(X.info(`Background re-index complete`,{filesProcessed:e.filesProcessed,chunksCreated:e.chunksCreated,durationMs:e.durationMs}),l.complete(`Reindex complete: ${e.filesProcessed} files, ${e.chunksCreated} chunks in ${e.durationMs}ms`),i)try{await i.createFtsIndex(),X.info(`FTS index rebuilt after reindex`)}catch(e){X.warn(`FTS index rebuild failed`,j(e))}try{let e=await r.reindexAll();X.info(`Curated re-index complete`,{indexed:e.indexed})}catch(e){X.warn(`Curated re-index failed`,j(e))}if(a)try{await a.notifyAfterReindex()}catch(e){X.warn(`Post-reindex resource notification failed`,j(e))}}).catch(e=>{l.fail(`Reindex failed: ${e instanceof Error?e.message:String(e)}`),X.error(`Background reindex failed`,j(e))}),{content:[{type:`text`,text:`## Reindex Started (Background)\n\n- **Mode**: ${e?`Full`:`Incremental`}\n- Search and other tools continue to work with existing data during reindex.\n- Completion will be logged. Use \`status({})\` to check index stats afterward.\n\n---\n_Next: Continue working — the reindex runs in the background._`}]}}catch(e){return X.error(`Reindex failed`,j(e)),H(`INTERNAL`,`Reindex failed: ${e instanceof Error?e.message:String(e)}`)}})}const zu=k(`tools`);function Bu(e){let t=z(`replay`);e.registerTool(`replay`,{title:t.title,description:`View or clear the audit trail of recent MCP tool and CLI invocations. Shows tool name, duration, status, and input/output summaries.`,inputSchema:{action:F.enum([`list`,`clear`]).default(`list`).describe(`Action: "list" (default) to view entries, "clear" to wipe the log`),last:F.number().optional().describe(`Number of entries to return (default: 20, list only)`),tool:F.string().optional().describe(`Filter by tool name (list only)`),source:F.enum([`mcp`,`cli`]).optional().describe(`Filter by source: "mcp" or "cli" (list only)`),since:F.string().optional().describe(`ISO timestamp — only show entries after this time (list only)`)},annotations:t.annotations},async({action:e,last:t,tool:n,source:r,since:i})=>{try{if(e===`clear`)return St(),{content:[{type:`text`,text:`Replay log cleared.`}]};let a=Ct({last:t,tool:n,source:r,since:i});if(a.length===0)return{content:[{type:`text`,text:`No replay entries found. Activity is logged when tools are invoked via MCP or CLI.`}]};let o=a.map(e=>`${e.ts.split(`T`)[1]?.split(`.`)[0]??e.ts} ${e.status===`ok`?`✓`:`✗`} ${e.tool} (${e.durationMs}ms) [${e.source}]\n in: ${e.input}\n out: ${e.output}`);return wt().catch(()=>{}),{content:[{type:`text`,text:`**Replay Log** (${a.length} entries)\n\n${o.join(`
|
|
522
502
|
|
|
523
|
-
`)}`}]}}catch(e){return
|
|
503
|
+
`)}`}]}}catch(e){return zu.error(`Replay failed`,j(e)),H(`INTERNAL`,`Replay failed: ${e instanceof Error?e.message:String(e)}`)}})}const Vu=k(`tools`);function Hu(e){let t=z(`restore`);e.registerTool(`restore`,{title:t.title,description:`List and restore file snapshots taken before destructive operations (codemod, rename, forget). Use action=list to see available restore points, action=restore with an id to undo.`,inputSchema:{action:F.enum([`list`,`restore`]).describe(`list: show restore points, restore: apply a restore point`),id:F.string().optional().describe(`Restore point ID (required for action=restore)`),limit:F.number().min(1).max(50).default(10).describe(`Max restore points to list`)},annotations:t.annotations},async({action:e,id:t,limit:n})=>{try{if(e===`list`){let e=Ze().slice(0,n);return e.length===0?{content:[{type:`text`,text:`No restore points found.`}]}:{content:[{type:`text`,text:`## Restore Points\n\n${e.map(e=>`- **${e.id}** (${e.timestamp}) — ${e.operation}: ${e.description} (${e.files.length} files)`).join(`
|
|
524
504
|
`)}`}]}}if(!t)throw Error(`id is required for restore action`);let r=await Tt(t);return{content:[{type:`text`,text:`Restored ${r.length} files:\n${r.map(e=>`- \`${e}\``).join(`
|
|
525
|
-
`)}`}]}}catch(e){return
|
|
526
|
-
`)[0].slice(0,500);if(r&&r!==e){let i=await t.embedQuery(r),a=await n.search(i,y);a.length>0&&(b=a,C=`> _Original query "${e}" returned 0 results. Auto-reformulated to "${r}"._\n\n`,
|
|
505
|
+
`)}`}]}}catch(e){return Vu.error(`Restore failed`,j(e)),H(`INTERNAL`,`Restore failed: ${e instanceof Error?e.message:String(e)}`)}})}const Uu=/<\/?curated-context>/gi;function Wu(e){return e.replace(Uu,``)}function Gu(e){return`<curated-context>\n${Wu(e)}\n</curated-context>`}const Ku=k(`tools`);function qu(e){let t=[],n=h(process.cwd());n&&t.push(`[project: ${n}]`);let r=Nt(`__context_boost`);return r&&t.push(`[focus: ${r.value}]`),t.length===0?e:`${t.join(` `)} ${e}`}async function Ju(e,t,n,r,i){if(!e||t>=e.config.fallbackThreshold&&n.length>0)return{results:n,triggered:!1,cacheHit:!1};let a=!1;try{let t=e.cache.get(r);return t?a=!0:(t=await e.client.search(r,i),t.length>0&&e.cache.set(r,t)),t.length>0?{results:vn(n,t,i).map(e=>({record:{id:`er:${e.sourcePath}`,content:e.content,sourcePath:e.source===`er`?`[ER] ${e.sourcePath}`:e.sourcePath,startLine:e.startLine??0,endLine:e.endLine??0,contentType:e.contentType??`documentation`,headingPath:e.headingPath,origin:e.source===`er`?`curated`:e.origin??`indexed`,category:e.category,tags:e.tags??[],chunkIndex:0,totalChunks:1,fileHash:``,indexedAt:new Date().toISOString(),version:1},score:e.score})),triggered:!0,cacheHit:a}:{results:n,triggered:!0,cacheHit:a}}catch(e){return Ku.warn(`ER fallback failed`,j(e)),{results:n,triggered:!0,cacheHit:a}}}function Yu(e,t,n=60){let r=new Map,i=e[0]?.score||1,a=t[0]?.score||1;for(let t=0;t<e.length;t++){let a=e[t],o=a.score/i;r.set(a.record.id,{record:a.record,score:1/(n+t+1)*o})}for(let e=0;e<t.length;e++){let i=t[e],o=i.score/a,s=r.get(i.record.id);s?s.score+=1/(n+e+1)*o:r.set(i.record.id,{record:i.record,score:1/(n+e+1)*o})}return[...r.values()].sort((e,t)=>t.score-e.score).map(({record:e,score:t})=>({record:e,score:t}))}function Xu(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 Zu(e){if(e.length<=1)return e;let t=new Set;return e.filter(e=>{let n=e.record.contentHash;return n?t.has(n)?!1:(t.add(n),!0):!0})}function Qu(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&&!$u.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 $u=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 ed(e,t){try{let n=await e.getStats();if(!n.lastIndexedAt)return;let r=new Date(n.lastIndexedAt).getTime(),i=Date.now(),a=[...new Set(t.map(e=>e.record.sourcePath))].filter(e=>!e.startsWith(`[ER]`)).slice(0,5);if(a.length===0)return;let o=0;for(let e of a)try{(await Yt(e)).mtimeMs>r&&o++}catch{o++}if(o>0){let e=i-r,t=Math.floor(e/6e4),n=t<1?`<1 min`:`${t} min`;return`> ⚠️ **Index may be stale** — ${o} file(s) modified since last index (${n} ago). Use \`reindex\` to refresh.`}}catch{}}function td(e,t,n,r,i,a,o){let s=z(`search`);e.registerTool(`search`,{title:s.title,description:`Search AI Kit for code, docs, and prior decisions. Default choice for discovery. Modes: hybrid (default), semantic, keyword. For multi-strategy precision queries use find; for a known file path use lookup.`,outputSchema:Ei,inputSchema:{query:F.string().max(5e3).describe(`Natural language search query`),limit:F.number().min(1).max(20).default(5).describe(`Maximum results to return`),search_mode:F.enum([`hybrid`,`semantic`,`keyword`]).default(`hybrid`).describe(`Search strategy: hybrid (vector + FTS + RRF fusion, default), semantic (vector only), keyword (FTS only)`),content_type:F.enum(S).optional().describe(`Filter by content type`),source_type:F.enum(T).optional().describe(`Coarse filter: "source" (code only), "documentation" (md, curated), "test", "config". Overrides content_type if both set.`),origin:F.enum(w).optional().describe(`Filter by knowledge origin`),category:F.string().optional().describe(`Filter by category (e.g., decisions, patterns, conventions)`),tags:F.array(F.string()).optional().describe(`Filter by tags (returns results matching ANY of the specified tags)`),min_score:F.number().min(0).max(1).default(.25).describe(`Minimum similarity score`),graph_hops:F.number().min(0).max(3).default(1).describe(`Number of graph hops to augment results with connected entities (0 = disabled, 1 = direct connections, 2-3 = deeper traversal). Default 1 provides module/symbol context automatically.`),max_tokens:F.number().min(100).max(5e4).optional().describe(`Maximum token budget for the response. When set, output is truncated to fit.`),dedup:F.enum([`file`,`chunk`]).default(`chunk`).describe(`Deduplication mode: "chunk" (default, show all matching chunks) or "file" (collapse chunks from same file into single result with merged line ranges)`),workspaces:F.array(F.string()).optional().describe(`Cross-workspace search: partition names or folder basenames to include. Use ["*"] for all registered workspaces. Only works in user-level install mode.`)},annotations:s.annotations},async({query:e,limit:s,search_mode:c,content_type:l,source_type:u,origin:d,category:f,tags:p,min_score:m,graph_hops:h,max_tokens:g,dedup:_,workspaces:v})=>{try{let y={limit:s,minScore:m,contentType:l,sourceType:u,origin:d,category:f,tags:p},b,x=!1,S=!1,C=``,w=qu(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 Ju(i,b[0]?.score??0,b,e,s);b=a.results,x=a.triggered,S=a.cacheHit}else{let r=await t.embedQuery(w),a=n.coarseSearch,o=a?a.bind(n):n.search.bind(n),[c,l]=await Promise.all([o(r,{...y,limit:s*2}),n.ftsSearch(e,{...y,limit:s*2}).catch(()=>[])]);c.length===0&&l.length>0?(b=l.slice(0,s),C=` (FTS-only: vector index rebuilding)`):b=l.length===0&&c.length>0?c.slice(0,s):Yu(c,l).slice(0,s);let u=await Ju(i,c[0]?.score??0,b,e,s);b=u.results,x=u.triggered,S=u.cacheHit}a&&a.recordSearch(e,x,S),b.length>1&&(b=Xu(b,e)),b=Zu(b);let T=``;if(v&&v.length>0){let n=io(v,O(process.cwd()));if(n.length>0){let{stores:r,closeAll:i}=await ao(n);try{let i;i=c===`keyword`?await so(r,e,{...y,limit:s}):await oo(r,await t.embedQuery(e),{...y,limit:s});for(let e of i)b.push({record:{...e.record,sourcePath:`[${e.workspace}] ${e.record.sourcePath}`},score:e.score});b=b.sort((e,t)=>t.score-e.score).slice(0,s),T=` + ${n.length} workspace(s)`}finally{await i()}}}if(_===`file`&&b.length>1){let e=new Map;for(let t of b){let n=t.record.sourcePath,r=e.get(n);r?(t.score>r.best.score&&(r.best=t),r.ranges.push({start:t.record.startLine,end:t.record.endLine})):e.set(n,{best:t,ranges:[{start:t.record.startLine,end:t.record.endLine}]})}b=[...e.values()].sort((e,t)=>t.best.score-e.best.score).map(({best:e,ranges:t})=>({record:{...e.record,content:t.length>1?`${e.record.content}\n\n_Matched ${t.length} sections: ${t.sort((e,t)=>e.start-t.start).map(e=>`L${e.start}-${e.end}`).join(`, `)}_`:e.record.content},score:e.score}))}if(b.length>1){let e=b[0].score,t=Math.max(e*.4,.1);b=b.filter(e=>e.score>=t)}if(b.length===0){if(o?.available)try{let r=(await o.createMessage({prompt:`The search query "${e}" returned 0 results in AI Kit code search. Suggest ONE alternative search query that might find relevant results. Reply with ONLY the alternative query, nothing else.`,systemPrompt:`You are a search query optimizer for AI Kit code search. Generate a single alternative query.`,maxTokens:100})).text.trim().split(`
|
|
506
|
+
`)[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`,Ku.info(`Smart search fallback succeeded`,{originalQuery:e,altQuery:r,resultCount:a.length}))}}catch(e){Ku.debug(`Smart search fallback failed`,{error:String(e)})}if(b.length===0)return{content:[{type:`text`,text:`No results found for the given query.`}],structuredContent:{results:[],totalResults:0,searchMode:c,query:e}}}let E,D;if(h>0&&!r&&(D="> **Note:** `graph_hops` was set but no graph store is available. Graph augmentation skipped."),h>0&&r)try{let e=await ze(r,b.map(e=>({recordId:e.record.id,score:e.score,sourcePath:e.record.sourcePath})),{hops:h,maxPerHit:5});E=new Map;for(let t of e)if(t.graphContext.nodes.length>0){let e=t.graphContext.nodes.slice(0,5).map(e=>` - **${e.name}** (${e.type})`).join(`
|
|
527
507
|
`),n=t.graphContext.edges.slice(0,5).map(e=>` - ${e.fromId} —[${e.type}]→ ${e.toId}`).join(`
|
|
528
508
|
`),r=[`- **Graph Context** (${h} hop${h>1?`s`:``}):`];e&&r.push(` Entities:\n${e}`),n&&r.push(` Relationships:\n${n}`),E.set(t.recordId,r.join(`
|
|
529
|
-
`))}}catch(e){
|
|
530
|
-
`)}\n\n${n.origin===`curated`?
|
|
509
|
+
`))}}catch(e){Ku.warn(`Graph augmentation failed`,j(e)),D=`> **Note:** Graph augmentation failed. Results shown without graph context.`}let k=Date.now();for(let e of b)if(e.record.origin===`curated`&&e.record.indexedAt){let t=k-new Date(e.record.indexedAt).getTime(),n=Math.max(0,t/864e5);e.score*=.95**n}b.sort((e,t)=>t.score-e.score),b=se(b);let ee=b.map((e,t)=>{let n=e.record;return`${`### Result ${t+1} (score: ${e.score.toFixed(3)})`}\n${[`- **Source**: ${n.sourcePath}`,n.headingPath?`- **Section**: ${n.headingPath}`:null,`- **Type**: ${n.contentType}`,n.startLine?`- **Lines**: ${n.startLine}-${n.endLine}`:null,n.origin===`indexed`?null:`- **Origin**: ${n.origin}`,n.category?`- **Category**: ${n.category}`:null,n.tags?.length?`- **Tags**: ${n.tags.join(`, `)}`:null,E?.get(n.id)??null].filter(Boolean).join(`
|
|
510
|
+
`)}\n\n${n.origin===`curated`?Gu(n.content):n.content}`}).join(`
|
|
531
511
|
|
|
532
512
|
---
|
|
533
513
|
|
|
534
|
-
`),A=(c===`hybrid`?`hybrid (vector + keyword RRF)`:c===`keyword`?`keyword (FTS)`:`semantic (vector)`)+T,te=
|
|
514
|
+
`),A=(c===`hybrid`?`hybrid (vector + keyword RRF)`:c===`keyword`?`keyword (FTS)`:`semantic (vector)`)+T,te=Qu(b,e),ne=te.length>0?`\n_Distinctive terms: ${te.map(e=>`\`${e}\``).join(`, `)}_`:``,M=await ed(n,b),N=[];if(b.length===0)N.push("`reindex` — no results found, index may be stale"),N.push("`find` — try federated search with glob/regex");else{let e=b[0]?.record.sourcePath;e&&N.push(`\`lookup\` — see all chunks from \`${e}\``),N.push("`symbol` — resolve a specific symbol from the results"),N.push("`compact` — compress a result file for focused reading")}let re=[D?`${D}\n\n`:``,M?`${M}\n\n`:``,ee,`\n\n---\n_Search mode: ${A} | ${b.length} results_${ne}`,`\n_Next: ${N.join(` | `)}_`],ie=C+re.join(``);g&&(ie=Ht(ie,g));let ae=new Set,oe=[];for(let e of b){if(e.record.origin!==`curated`||e.record.sourcePath.startsWith(`[`))continue;let t=Cs(e.record.sourcePath);if(!t)continue;let n=xs(t,e.record.headingPath??t);n&&!ae.has(n.uri)&&(ae.add(n.uri),oe.push(n))}return{content:[{type:`text`,text:ie},...oe],structuredContent:{results:b.map(e=>({sourcePath:e.record.sourcePath,contentType:e.record.contentType,score:e.score,...e.record.headingPath?{headingPath:e.record.headingPath}:{},...e.record.startLine?{startLine:e.record.startLine}:{},...e.record.endLine?{endLine:e.record.endLine}:{},...e.record.origin===`indexed`?{}:{origin:e.record.origin},...e.record.category?{category:e.record.category}:{},...e.record.tags?.length?{tags:e.record.tags}:{}})),totalResults:b.length,searchMode:c,query:e}}}catch(e){return Ku.error(`Search failed`,j(e)),H(`INTERNAL`,`Search failed: ${e instanceof Error?e.message:String(e)}`)}})}const nd=k(`tools`);function rd(e,t){let n=z(`session_digest`);e.registerTool(`session_digest`,{title:n.title,description:`Compress the current session's tool trajectory into a focused digest. Aggregates replay log, stash state, and checkpoints. Supports deterministic and LLM-assisted (sampling) modes with configurable token budget.`,inputSchema:{scope:F.enum([`tools`,`stash`,`all`]).default(`all`).describe(`What to include: tools (replay only), stash (stash + checkpoints only), or all`),since:F.string().optional().describe(`ISO timestamp — only include activity after this time`),last:F.number().min(1).max(500).optional().describe(`Max replay entries to consider (default: 50)`),focus:F.string().optional().describe(`Focus query — prioritize entries matching this topic`),mode:F.enum([`deterministic`,`sampling`]).default(`deterministic`).describe(`Summary mode: deterministic (fast, template-based) or sampling (LLM-assisted, richer)`),token_budget:F.number().min(100).max(8e3).default(2e3).describe(`Target token budget for the digest output`),persist:F.boolean().default(!0).describe(`Auto-save digest to stash for crash recovery`)},annotations:n.annotations},async({scope:e,since:n,last:r,focus:i,mode:a,token_budget:o,persist:s})=>{try{let c={scope:e,since:n,last:r,focus:i,mode:a,tokenBudget:o,persist:s};return{content:[{type:`text`,text:(a===`sampling`&&t?.available?await At(c,async(e,n,r)=>(await t.createMessage({prompt:e,systemPrompt:n,maxTokens:r})).text):kt(c)).digest}]}}catch(e){return nd.error(`Session digest failed`,j(e)),H(`INTERNAL`,`Session digest failed: ${e instanceof Error?e.message:String(e)}`)}})}const id=k(`tools`);function ad(e,t,n,r=15e3){let i,a=new Promise(e=>{i=setTimeout(()=>{id.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),id.warn(`Status sub-operation "${n}" failed: ${e instanceof Error?e.message:String(e)}`),{value:t,timedOut:!1})),a])}function od(){let e=dn.get(),t=un.get();if(e)return`- **Tree-sitter (WASM)**: ✅ Available (${t.grammarCount} grammars, dir: ${t.wasmDir})`;let n=t.pathsChecked.length?t.pathsChecked.map(e=>` ${e.exists?`✓`:`✗`} ${e.path}`).join(`
|
|
535
515
|
`):` none`,r=t.healAttempted?` Auto-heal: ${t.healSuccess?`✓ succeeded`:`✗ failed (${t.healError??`unknown`})`}`:` Auto-heal: not attempted`;return[`- **Tree-sitter (WASM)**: ⚠ Unavailable (regex fallback)`,` Reason: ${t.reason||`unknown`}`,` Paths checked:`,n,r,` OS: ${t.os} ${t.arch} | Node: ${t.nodeVersion}`,` Fix: Reinstall package or run vendor:wasm script`].join(`
|
|
536
|
-
`)}const
|
|
537
|
-
`)}],structuredContent:l}})}function
|
|
538
|
-
`),re={totalRecords:h.totalRecords,totalFiles:h.totalFiles,lastIndexedAt:h.lastIndexedAt??null,onboarded:w,onboardDir:S,contentTypes:h.contentTypeBreakdown,wasmAvailable:!!dn.get(),wasmDiagnostics:un.get(),graphStats:_,curatedCount:v,serverVersion:A,scaffoldVersion:k??null,workspaceScaffoldVersion:ee??null,upgradeAvailable:te||ne,storeBackend:l?.store?.backend,storeDiagnostics:D??null,contextPressure:T};return{content:[{type:`text`,text:N+(u===`smart`?"\n\n---\n_Next: Use `search` to query indexed content or `graph({action:'find_nodes', name_pattern:'<top-level-module>'})` → then `graph({action:'neighbors', node_id})` for relationships. Smart indexing handles updates automatically._":"\n\n---\n_Next: Use `search` to query indexed content, `graph({action:'find_nodes', name_pattern:'<top-level-module>'})` → then `graph({action:'neighbors', node_id})` for relationships, or `reindex` to refresh the index._")}],structuredContent:re}}catch(e){return
|
|
539
|
-
`)};if(i.length===1)try{return{content:[{type:`text`,text:`${await a(i[0])}\n---\n_Next: Use \`web_fetch\` to read any of these pages in full._`}]}}catch(e){return
|
|
516
|
+
`)}const sd=5*6e4;let cd=null,ld=null;function ud(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 dd(){let e=Date.now();if(cd&&e-cd.ts<sd)return cd.value;try{let t=y(Dn(),`.copilot`,`.aikit-scaffold.json`);if(!o(t))return cd={value:null,ts:e},null;let n=JSON.parse(c(t,`utf-8`)).version??null;return cd={value:n,ts:e},n}catch{return cd={value:null,ts:e},null}}function fd(){let e=Date.now();if(ld&&e-ld.ts<sd)return ld.value;try{let t=y(process.cwd(),`.github`,`.aikit-scaffold.json`);if(!o(t))return ld={value:null,ts:e},null;let n=JSON.parse(c(t,`utf-8`)).version??null;return ld={value:n,ts:e},n}catch{return ld={value:null,ts:e},null}}function pd(e){let t=z(`status`);e.registerTool(`status`,{title:t.title,description:`Get the current status and statistics of the AI Kit index.`,outputSchema:_i,annotations:t.annotations},async()=>{let e=r(),t=dd(),a=fd(),o=t!=null&&t!==e,s=a!=null&&a!==e,c=[`## AI Kit Status`,``,`⏳ **AI Kit is initializing** — index stats will be available shortly.`,``,`### Runtime`,`- **Tree-sitter (WASM)**: ${dn.get()?`✅ Available (AST analysis)`:`⚠ Unavailable (regex fallback)`}`,``,`### Version`,`- **Server**: ${e}`,`- **Scaffold (user)**: ${t??`not installed`}`,`- **Scaffold (workspace)**: ${a??`not installed`}`];if(o||s){let r=i(),l=[];o&&l.push(`user scaffold v${t}`),s&&l.push(`workspace scaffold v${a}`);let u=l.join(`, `);r.state===`success`?c.push(``,`### ✅ Upgrade Applied`,`- Server v${e} — ${u} auto-upgraded successfully.`,`- _Restart the MCP server to use the updated version._`):r.state===`pending`?c.push(``,`### ⏳ Upgrade In Progress`,`- Server v${e} ≠ ${u}`,`- Auto-upgrade is running in the background…`):r.state===`failed`?(n(),c.push(``,`### ⬆ Upgrade Available (auto-upgrade failed, retrying)`,`- Server v${e} ≠ ${u}`,`- Error: ${r.error??`unknown`}`)):(n(),c.push(``,`### ⬆ Upgrade Available`,`- Server v${e} ≠ ${u}`,`- Auto-upgrade triggered — check again shortly.`))}let l={totalRecords:0,totalFiles:0,lastIndexedAt:null,onboarded:!1,onboardDir:``,contentTypes:{},wasmAvailable:!!dn.get(),graphStats:null,curatedCount:0,serverVersion:e,scaffoldVersion:t??null,workspaceScaffoldVersion:a??null,upgradeAvailable:o||s,contextPressure:0};return{content:[{type:`text`,text:c.join(`
|
|
517
|
+
`)}],structuredContent:l}})}function md(e,t,a,s,c,l,u,d){let p=z(`status`);e.registerTool(`status`,{title:p.title,description:`Get the current status and statistics of the AI Kit index.`,outputSchema:_i,annotations:p.annotations},async()=>{let e=[];try{let[p,m]=await Promise.all([ad(t.getStats(),{totalRecords:0,totalFiles:0,lastIndexedAt:null,contentTypeBreakdown:{}},`store.getStats`),ad(t.listSourcePaths(),[],`store.listSourcePaths`)]),h=p.value;p.timedOut&&e.push(`⚠ Index stats timed out — values may be incomplete`);let g=m.value;m.timedOut&&e.push(`⚠ File listing timed out`);let _=null,v=0,b=[`## AI Kit Status`,``,`- **Total Records**: ${h.totalRecords}`,`- **Total Files**: ${h.totalFiles}`,`- **Last Indexed**: ${h.lastIndexedAt??`Never`}`,``,`### Content Types`,...Object.entries(h.contentTypeBreakdown).map(([e,t])=>`- ${e}: ${t}`),``,`### Indexed Files`,...g.slice(0,50).map(e=>`- ${e}`),g.length>50?`\n... and ${g.length-50} more files`:``];if(a)try{let t=await ad(a.getStats(),{nodeCount:0,edgeCount:0,nodeTypes:{},edgeTypes:{}},`graphStore.getStats`);if(t.timedOut)e.push(`⚠ Graph stats timed out`),b.push(``,`### Knowledge Graph`,`- Graph stats timed out`);else{let e=t.value;_={nodes:e.nodeCount,edges:e.edgeCount},b.push(``,`### Knowledge Graph`,`- **Nodes**: ${e.nodeCount}`,`- **Edges**: ${e.edgeCount}`,...Object.entries(e.nodeTypes).map(([e,t])=>` - ${e}: ${t}`));try{let e=await ad(a.validate(),{valid:!0,danglingEdges:[],orphanNodes:[],stats:{nodeCount:0,edgeCount:0,nodeTypes:{},edgeTypes:{}}},`graphStore.validate`);if(!e.timedOut){let t=e.value;t.valid||b.push(`- **⚠ Integrity Issues**: ${t.danglingEdges.length} dangling edges`),t.orphanNodes.length>0&&b.push(`- **Orphan nodes**: ${t.orphanNodes.length}`)}}catch{}}}catch{b.push(``,`### Knowledge Graph`,`- Graph store unavailable`)}let S=l?.onboardDir??y(process.cwd(),x.aiContext),C=o(S),w=c?.onboardComplete||C;if(b.push(``,`### Onboard Status`,w?`- ✅ Complete${c?.onboardTimestamp?` (last: ${c.onboardTimestamp})`:``}`:'- ❌ Not run — call `onboard({ path: "." })` to analyze the codebase',`- **Onboard Directory**: \`${S}\``),s)try{let t=await ad(s.list(),[],`curated.list`);if(t.timedOut)e.push(`⚠ Curated knowledge listing timed out`),b.push(``,`### Curated Knowledge`,`- Listing timed out`);else{let e=t.value;v=e.length,b.push(``,`### Curated Knowledge`,e.length>0?`- ${e.length} entries`:'- Empty — use `knowledge({ action: "remember", ... })` to persist decisions')}}catch{b.push(``,`### Curated Knowledge`,`- Unable to read curated entries`)}let T=ud(h.totalRecords,_?.nodes??0,_?.edges??0,v);b.push(``),b.push(`## 📊 Context Pressure: ${T}/100`),T>=80?b.push(`⚠️ High pressure — consider pruning stale entries or compacting context.`):T>=50?b.push(`ℹ️ Moderate pressure — AI Kit memory is well-populated.`):b.push(`✅ Low pressure — plenty of headroom for more content.`);let E=0;if(h.lastIndexedAt){E=new Date(h.lastIndexedAt).getTime();let e=(Date.now()-E)/(1e3*60*60);b.push(``,`### Index Freshness`,e>24?u===`smart`?`- ⚠ Last indexed ${Math.floor(e)}h ago — smart indexing will refresh automatically`:`- ⚠ Last indexed ${Math.floor(e)}h ago — may be stale. Run \`reindex({})\``:`- ✅ Last indexed ${e<1?`less than 1h`:`${Math.floor(e)}h`} ago`)}let D=null,O=t;if(typeof O.getDiagnostics==`function`)try{D=O.getDiagnostics(),b.push(``,`### Storage`,`- **Backend**: ${l?.store?.backend??`unknown`}`,`- **Adapter**: ${D.adapterType}`,`- **Vector search**: ${D.vectorSearchEnabled?`✅ enabled`:`⚠ disabled (FTS-only fallback)`}`,D.dbPath?`- **DB**: ${D.dbPath}`:``,D.dbSizeBytes==null?``:`- **DB size**: ${(D.dbSizeBytes/1024/1024).toFixed(2)} MB`,`- **Embedding dim**: ${D.embeddingDim}`,`- **Vector dtype**: ${D.vectorDtype}`)}catch{}if(u===`smart`)if(b.push(``,`### Smart Indexing`),d){let e=d();e?b.push(`- **Mode**: Smart (trickle)`,`- **Status**: ${e.running?`✅ Running`:`⏸ Stopped`}`,`- **Queue**: ${e.queueSize} files pending`,`- **Changed files**: ${e.changedFilesSize} detected`,`- **Interval**: ${Math.round(e.intervalMs/1e3)}s per batch of ${e.batchSize}`):b.push(`- **Mode**: Smart (trickle)`,`- **Status**: scheduler state unavailable (init may have failed)`)}else b.push(`- **Mode**: Smart (trickle) — scheduler state unavailable`);{try{let e=y(process.cwd(),x.data,`stash`);if(o(e)){let t=f(e).mtimeMs;t>E&&(E=t)}}catch{}let e=[];if(s)try{let t=v>0?await s.list():[];for(let e of t){let t=new Date(e.updated||e.created).getTime();t>E&&(E=t)}e.push(...t.sort((e,t)=>new Date(t.updated).getTime()-new Date(e.updated).getTime()).slice(0,5))}catch{}let t=E>0?Date.now()-E:0;if(t>=144e5){let n=Math.floor(t/36e5);if(b.push(``,`### 🌅 Session Briefing`,`_${n}+ hours since last activity — here's what to pick up:_`,``),e.length>0){b.push(`**Recent decisions/notes:**`);for(let t of e)b.push(`- **${t.title}** (${t.category??`note`}) — ${(t.contentPreview??``).slice(0,80)}…`)}b.push(``,`**Suggested next steps:**`,'- `search({ query: "SESSION CHECKPOINT", origin: "curated" })` — find your last checkpoint',"- `restore({})` — resume from a saved checkpoint",'- `knowledge({ action: "list" })` — browse all stored knowledge')}}b.push(``,`### Runtime`,od());let k=dd(),ee=fd(),A=r(),te=k!=null&&k!==A,ne=ee!=null&&ee!==A;if(te||ne){let e=i(),t=[];te&&t.push(`user scaffold v${k}`),ne&&t.push(`workspace scaffold v${ee}`);let r=t.join(`, `);e.state===`success`?b.push(``,`### ✅ Upgrade Applied`,`- Server v${A} — ${r} auto-upgraded successfully.`,`- _Restart the MCP server to use the updated version._`):e.state===`pending`?b.push(``,`### ⏳ Upgrade In Progress`,`- Server v${A} ≠ ${r}`,`- Auto-upgrade is running in the background…`):e.state===`failed`?(n(),b.push(``,`### ⬆ Upgrade Available (auto-upgrade failed, retrying)`,`- Server v${A} ≠ ${r}`,`- Error: ${e.error??`unknown`}`)):(n(),b.push(``,`### ⬆ Upgrade Available`,`- Server v${A} ≠ ${r}`,`- Auto-upgrade triggered — check again shortly.`))}e.length>0&&b.push(``,`### ⚠ Warnings`,...e.map(e=>`- ${e}`));let j=Rr();if(j.length>0){let e=j.sort((e,t)=>t.callCount-e.callCount);b.push(``,`### Tool Usage This Session`,``),b.push(`| Tool | Calls | Tokens In | Tokens Out | Errors | Avg Latency |`),b.push(`|------|-------|-----------|------------|--------|-------------|`);for(let t of e.slice(0,15)){let e=Math.round(t.totalInputChars/4),n=Math.round(t.totalOutputChars/4),r=Math.round(t.totalDurationMs/t.callCount);b.push(`| ${t.tool} | ${t.callCount} | ${e.toLocaleString()} | ${n.toLocaleString()} | ${t.errorCount} | ${r}ms |`)}}let M=jr();if(M.bufferSize>=10){let e=M.state===`healthy`?`🟢`:M.state===`degraded`?`🔴`:`🟡`;b.push(``,`### Auto-GC: ${e} ${M.state}`),b.push(`- p95 latency: ${M.p95}ms | buffer: ${M.bufferSize} samples`),M.gcCount>0&&b.push(`- GC cycles triggered: ${M.gcCount}`)}let N=b.join(`
|
|
518
|
+
`),re={totalRecords:h.totalRecords,totalFiles:h.totalFiles,lastIndexedAt:h.lastIndexedAt??null,onboarded:w,onboardDir:S,contentTypes:h.contentTypeBreakdown,wasmAvailable:!!dn.get(),wasmDiagnostics:un.get(),graphStats:_,curatedCount:v,serverVersion:A,scaffoldVersion:k??null,workspaceScaffoldVersion:ee??null,upgradeAvailable:te||ne,storeBackend:l?.store?.backend,storeDiagnostics:D??null,contextPressure:T};return{content:[{type:`text`,text:N+(u===`smart`?"\n\n---\n_Next: Use `search` to query indexed content or `graph({action:'find_nodes', name_pattern:'<top-level-module>'})` → then `graph({action:'neighbors', node_id})` for relationships. Smart indexing handles updates automatically._":"\n\n---\n_Next: Use `search` to query indexed content, `graph({action:'find_nodes', name_pattern:'<top-level-module>'})` → then `graph({action:'neighbors', node_id})` for relationships, or `reindex` to refresh the index._")}],structuredContent:re}}catch(e){return id.error(`Status failed`,j(e)),H(`INTERNAL`,`Status check failed: ${e instanceof Error?e.message:String(e)}`)}})}const hd=k(`tools`);function gd(e){let t=z(`web_search`);e.registerTool(`web_search`,{title:t.title,description:`PREFERRED web search — fans out to multiple keyless providers (DuckDuckGo + Bing-HTML + Mojeek) by default, returning a deduplicated, consensus-ranked union within a 10s deadline. Optional providers (SearXNG, Google, Brave, Bing API) join the fan-out automatically when their env vars are set. Pass one query or multiple for parallel searching.`,inputSchema:{queries:F.array(F.string().max(2e3)).min(1).max(5).describe('Search queries (1–5). Single: `["react hooks"]`. Multiple searched in parallel.'),limit:F.number().min(1).max(20).default(5).describe(`Max results per query`),site:F.string().optional().describe(`Restrict to domain (e.g., "docs.aws.amazon.com")`),provider:F.enum([`multi`,`duckduckgo`,`bing-html`,`mojeek`,`searxng`,`google`,`brave`,`bing`]).optional().describe("Search provider. Defaults to env AIKIT_SEARCH_PROVIDER, then `multi` (fan-out). Single keyless: `duckduckgo`, `bing-html`, `mojeek`. Self-hosted: `searxng` (requires SEARXNG_URL). Keyed APIs: `google` (GOOGLE_API_KEY+GOOGLE_CSE_ID), `brave` (BRAVE_API_KEY), `bing` (BING_API_KEY). Missing keys auto-fall back to duckduckgo.")},annotations:t.annotations},async({queries:e,limit:t,site:n,provider:r})=>{let i=e,a=async e=>{let i=await qt({query:e,limit:t,site:n,provider:r}),a=[`## Search: ${i.query} _(via ${i.provider})_`,``];if(i.results.length===0)a.push(`No results found.`);else for(let e of i.results)a.push(`### [${e.title}](${e.url})`,e.snippet,``);return a.join(`
|
|
519
|
+
`)};if(i.length===1)try{return{content:[{type:`text`,text:`${await a(i[0])}\n---\n_Next: Use \`web_fetch\` to read any of these pages in full._`}]}}catch(e){return hd.error(`Web search failed`,j(e)),H(`INTERNAL`,`Web search failed: ${e instanceof Error?e.message:String(e)}`)}let o=await Promise.allSettled(i.map(e=>a(e))),s=[],c=0;for(let e=0;e<o.length;e++){let t=o[e];if(t.status===`fulfilled`)s.push(t.value);else{c++;let n=t.reason instanceof Error?t.reason.message:String(t.reason);hd.error(`Web search failed`,{query:i[e],error:n}),s.push(`## ❌ Search failed: ${i[e]}\n\n${n}`)}}let l=`_Searched ${o.length-c}/${o.length} queries successfully._`;s.push(``,`---`,l,"_Next: Use `web_fetch` to read any of these pages in full._");let u=s.join(`
|
|
540
520
|
|
|
541
|
-
`);return c===o.length?H(`INTERNAL`,u):{content:[{type:`text`,text:u}]}})}function
|
|
542
|
-
`)}]}}catch(e){return
|
|
543
|
-
`)}]}})}function
|
|
544
|
-
`)}],structuredContent:i}}catch(e){return
|
|
521
|
+
`);return c===o.length?H(`INTERNAL`,u):{content:[{type:`text`,text:u}]}})}function _d(e){let t=z(`http`);e.registerTool(`http`,{title:t.title,description:`Make HTTP requests (GET/POST/PUT/PATCH/DELETE/HEAD) for API testing. Returns status, headers, and formatted body with timing info.`,inputSchema:{url:F.string().url().describe(`Request URL (http/https only)`),method:F.enum([`GET`,`POST`,`PUT`,`PATCH`,`DELETE`,`HEAD`]).default(`GET`).describe(`HTTP method`),headers:F.record(F.string(),F.string()).optional().describe(`Request headers as key-value pairs`),body:F.string().optional().describe(`Request body (for POST/PUT/PATCH)`),timeout:F.number().min(1e3).max(6e4).default(15e3).describe(`Timeout in milliseconds`)},annotations:t.annotations},async({url:e,method:t,headers:n,body:r,timeout:i})=>{try{let a=await Ue({url:e,method:t,headers:n,body:r,timeout:i}),o=[`## ${t} ${e}`,``,`**Status:** ${a.status} ${a.statusText}`,`**Time:** ${a.durationMs}ms`,`**Size:** ${a.sizeBytes} bytes`,`**Content-Type:** ${a.contentType}`,``,`### Headers`,"```json",JSON.stringify(a.headers),"```",``,`### Body`,a.contentType.includes(`json`)?"```json":"```",a.body,"```"];return a.truncated&&o.push(``,`_Response truncated — total size: ${a.sizeBytes} bytes_`),{content:[{type:`text`,text:o.join(`
|
|
522
|
+
`)}]}}catch(e){return hd.error(`HTTP request failed`,j(e)),H(`INTERNAL`,`HTTP request failed: ${e instanceof Error?e.message:String(e)}`)}})}function vd(e){let t=z(`regex_test`);e.registerTool(`regex_test`,{title:t.title,description:`Test a regex pattern against sample strings. Supports match, replace, and split modes.`,inputSchema:{pattern:F.string().max(500).describe(`Regex pattern (without delimiters)`),flags:F.string().max(10).regex(/^[gimsuy]*$/).default(``).describe(`Regex flags (g, i, m, s, etc.)`),test_strings:F.array(F.string().max(1e4)).max(50).describe(`Strings to test the pattern against`),mode:F.enum([`match`,`replace`,`split`]).default(`match`).describe(`Test mode`),replacement:F.string().optional().describe(`Replacement string (for replace mode)`)},annotations:t.annotations},async({pattern:e,flags:t,test_strings:n,mode:r,replacement:i})=>{let a=_t({pattern:e,flags:t,testStrings:n,mode:r,replacement:i});if(!a.valid)return H(`VALIDATION`,`Invalid regex: ${a.error}`);let o=[`## Regex: \`/${a.pattern}/${a.flags}\``,``,`Mode: ${r}`,``];for(let e of a.results){if(o.push(`**Input:** \`${e.input}\``),o.push(`**Matched:** ${e.matched}`),e.matches)for(let t of e.matches){let e=t.groups.length>0?` groups: [${t.groups.join(`, `)}]`:``;o.push(` - "${t.full}" at index ${t.index}${e}`)}e.replaced!==void 0&&o.push(`**Result:** \`${e.replaced}\``),e.split&&o.push(`**Split:** ${JSON.stringify(e.split)}`),o.push(``)}return{content:[{type:`text`,text:o.join(`
|
|
523
|
+
`)}]}})}function yd(e){let t=z(`encode`);e.registerTool(`encode`,{title:t.title,description:`Encode, decode, or hash text. Supports base64, URL encoding, SHA-256, MD5, JWT decode, hex.`,inputSchema:{operation:F.enum([`base64_encode`,`base64_decode`,`url_encode`,`url_decode`,`sha256`,`md5`,`jwt_decode`,`hex_encode`,`hex_decode`]).describe(`Operation to perform`),input:F.string().max(1e6).describe(`Input text`)},annotations:t.annotations},async({operation:e,input:t})=>{try{let n=De({operation:e,input:t});return{content:[{type:`text`,text:`## ${e}\n\n**Input:** \`${t.length>100?`${t.slice(0,100)}...`:t}\`\n**Output:**\n\`\`\`\n${n.output}\n\`\`\``}]}}catch(e){return hd.error(`Encode failed`,j(e)),H(`INTERNAL`,`Encode failed: ${e instanceof Error?e.message:String(e)}`)}})}function bd(e){let t=z(`measure`);e.registerTool(`measure`,{title:t.title,description:`Measure code complexity, line counts, and function counts for a file or directory. Returns per-file metrics sorted by complexity.`,outputSchema:yi,inputSchema:{path:F.string().describe(`File or directory path to measure`),extensions:F.array(F.string()).optional().describe(`File extensions to include (default: .ts,.tsx,.js,.jsx)`)},annotations:t.annotations},async({path:e,extensions:t})=>{try{let n=await $e({path:e,extensions:t}),r=[`## Code Metrics`,``,`**Files:** ${n.summary.totalFiles}`,`**Total lines:** ${n.summary.totalLines} (${n.summary.totalCodeLines} code)`,`**Functions:** ${n.summary.totalFunctions}`,`**Avg complexity:** ${n.summary.avgComplexity}`,`**Max complexity:** ${n.summary.maxComplexity.value} (${n.summary.maxComplexity.file})`,``,`### Top files by complexity`,``,`| File | Lines | Code | Complexity | Cognitive | Functions | Imports |`,`|------|-------|------|------------|-----------|-----------|---------|`];for(let e of n.files.slice(0,20)){let t=e.cognitiveComplexity===void 0?`—`:String(e.cognitiveComplexity);r.push(`| ${e.path} | ${e.lines.total} | ${e.lines.code} | ${e.complexity} | ${t} | ${e.functions} | ${e.imports} |`)}n.files.length>20&&r.push(``,`_...and ${n.files.length-20} more files_`);let i={summary:{totalFiles:n.summary.totalFiles,totalLines:n.summary.totalLines,totalCodeLines:n.summary.totalCodeLines,totalFunctions:n.summary.totalFunctions,avgComplexity:n.summary.avgComplexity,maxComplexity:{value:n.summary.maxComplexity.value,file:n.summary.maxComplexity.file}},files:n.files.map(e=>({path:e.path,lines:e.lines.total,code:e.lines.code,complexity:e.complexity,functions:e.functions}))};return{content:[{type:`text`,text:r.join(`
|
|
524
|
+
`)}],structuredContent:i}}catch(e){return hd.error(`Measure failed`,j(e)),H(`INTERNAL`,`Measure failed: ${e instanceof Error?e.message:String(e)}`)}})}function xd(e){let t=z(`changelog`);e.registerTool(`changelog`,{title:t.title,description:`Generate a changelog from git history between two refs. Groups by conventional commit type.`,inputSchema:{from:F.string().max(200).describe(`Start ref (tag, SHA, HEAD~N)`),to:F.string().max(200).default(`HEAD`).describe(`End ref (default: HEAD)`),format:F.enum([`grouped`,`chronological`,`per-scope`]).default(`grouped`).describe(`Output format`),include_breaking:F.boolean().default(!0).describe(`Highlight breaking changes`),cwd:F.string().optional().describe(`Repository root or working directory`)},annotations:t.annotations},async({from:e,to:t,format:n,include_breaking:r,cwd:i})=>{try{let a=ce({from:e,to:t,format:n,includeBreaking:r,cwd:i}),o=`${a.stats.total} commits (${Object.entries(a.stats.types).map(([e,t])=>`${t} ${e}`).join(`, `)})`;return{content:[{type:`text`,text:`${a.markdown}\n---\n_${o}_`}]}}catch(e){return hd.error(`Changelog failed`,j(e)),H(`INTERNAL`,`Changelog failed: ${e instanceof Error?e.message:String(e)}`)}})}function Sd(e){let t=z(`schema_validate`);e.registerTool(`schema_validate`,{title:t.title,description:`Validate JSON data against a JSON Schema. Supports type, required, properties, items, enum, pattern, min/max.`,inputSchema:{data:F.string().max(5e5).describe(`JSON data to validate (as string)`),schema:F.string().max(5e5).describe(`JSON Schema to validate against (as string)`)},annotations:t.annotations},async({data:e,schema:t})=>{try{let n=Dt({data:JSON.parse(e),schema:JSON.parse(t)});if(n.valid)return{content:[{type:`text`,text:`## Validation: PASSED
|
|
545
525
|
|
|
546
526
|
Data matches the schema.`}]};let r=[`## Validation: FAILED`,``,`**${n.errors.length} error(s):**`,``];for(let e of n.errors){let t=e.expected?` (expected: ${e.expected}, got: ${e.received})`:``;r.push(`- \`${e.path}\`: ${e.message}${t}`)}return{content:[{type:`text`,text:r.join(`
|
|
547
|
-
`)}]}}catch(e){return
|
|
548
|
-
`)}],structuredContent:a}})}function
|
|
549
|
-
`)}],structuredContent:o}}catch(e){return
|
|
527
|
+
`)}]}}catch(e){return hd.error(`Schema validation failed`,j(e)),H(`INTERNAL`,`Schema validation failed: ${e instanceof Error?e.message:String(e)}`)}})}function Cd(e){let t=z(`env`);e.registerTool(`env`,{title:t.title,description:`Get system and runtime environment info. Sensitive env vars are redacted by default.`,outputSchema:bi,inputSchema:{include_env:F.boolean().default(!1).describe(`Include environment variables`),filter_env:F.string().optional().describe(`Filter env vars by name substring`),show_sensitive:F.boolean().default(!1).describe(`Show sensitive values (keys, tokens, etc.) — redacted by default`)},annotations:t.annotations},async({include_env:e,filter_env:t,show_sensitive:n})=>{let r=Oe({includeEnv:e,filterEnv:t,showSensitive:n}),i=[`## Environment`,``,`**Platform:** ${r.system.platform} ${r.system.arch}`,`**OS:** ${r.system.type} ${r.system.release}`,`**Host:** ${r.system.hostname}`,`**CPUs:** ${r.system.cpus}`,`**Memory:** ${r.system.memoryFreeGb}GB free / ${r.system.memoryTotalGb}GB total`,``,`**Node:** ${r.runtime.node}`,`**V8:** ${r.runtime.v8}`,`**CWD:** ${r.cwd}`];if(r.env){i.push(``,`### Environment Variables`,``);for(let[e,t]of Object.entries(r.env))i.push(`- \`${e}\`: ${t}`)}let a={platform:r.system.platform,arch:r.system.arch,nodeVersion:r.runtime.node,cwd:r.cwd,cpus:r.system.cpus,memoryFreeGb:r.system.memoryFreeGb,memoryTotalGb:r.system.memoryTotalGb};return{content:[{type:`text`,text:i.join(`
|
|
528
|
+
`)}],structuredContent:a}})}function wd(e){let t=z(`time`);e.registerTool(`time`,{title:t.title,description:`Parse dates, convert timezones, calculate durations, add time. Supports ISO 8601, unix timestamps, and human-readable formats.`,outputSchema:xi,inputSchema:{operation:F.enum([`now`,`parse`,`convert`,`diff`,`add`]).describe(`now: current time | parse: parse a date string | convert: timezone conversion | diff: duration between two dates | add: add duration to date`),input:F.string().optional().describe(`Date input (ISO, unix timestamp, or parseable string). For diff: two comma-separated dates`),timezone:F.string().optional().describe(`Target timezone (e.g., "America/New_York", "Asia/Tokyo")`),duration:F.string().optional().describe(`Duration to add (e.g., "2h30m", "1d", "30s") — for add operation`)},annotations:t.annotations},async({operation:e,input:t,timezone:n,duration:r})=>{try{let i=Bt({operation:e,input:t,timezone:n,duration:r}),a=[`**${i.output}**`,``,`ISO: ${i.iso}`,`Unix: ${i.unix}`];i.details&&a.push(``,"```json",JSON.stringify(i.details),"```");let o={iso:i.iso,unix:i.unix,timezone:n??Intl.DateTimeFormat().resolvedOptions().timeZone,formatted:i.output};return{content:[{type:`text`,text:a.join(`
|
|
529
|
+
`)}],structuredContent:o}}catch(e){return hd.error(`Time failed`,j(e)),H(`INTERNAL`,`Time failed: ${e instanceof Error?e.message:String(e)}`)}})}function Td(e,t,n,r,i,a,o,s,c){let l=new wr,u=new dr;u.register(cr),u.register(ir),u.register(ar),u.register(tr),u.register(Zn),u.register(Qn),u.register(ur);let d=new gr(u,t.curated);l.use(mr(d),{order:5,name:`auto-knowledge`}),l.use(Br(),{order:10,name:`replay`}),l.use(Xr(),{order:50,name:`structured-content-guard`}),l.use(yr(vr(n.tokenBudget)),{order:90,name:`compression`}),ti(e,l,n.toolPrefix??``);let f=c??hi(n,[...L,...Wr],R,Kr(n)),p=e=>f.has(e),m=[...f].filter(e=>Gr.has(e)?Ur.includes(e)?!!t.bridge:e===`er_update_policy`?!!t.policyStore:e===`er_evolve_review`?!!t.evolutionCollector:!1:!0);p(`search`)&&td(e,t.embedder,t.store,t.graphStore,t.bridge,t.evolutionCollector,a);let h={store:t.store,graphStore:t.graphStore,embedder:t.embedder};p(`lookup`)&&Zs(e,t.store,h);let g={onboardComplete:t.onboardComplete,onboardTimestamp:t.onboardTimestamp};p(`status`)&&md(e,t.store,t.graphStore,t.curated,g,n,o,s),p(`config`)&&no(e,n),p(`reindex`)&&Ru(e,t.indexer,n,t.curated,t.store,i,o),p(`knowledge`)&&Ys(e,t.curated,t.policyStore,t.evolutionCollector,i),p(`analyze`)&&Sa(e,t.store,t.embedder,h),p(`blast_radius`)&&Ca(e,t.store,t.embedder,t.graphStore,h),p(`produce_knowledge`)&&Lu(e,n),p(`onboard`)&&fc(e,t.store,t.embedder,n,g,h),p(`graph`)&&hs(e,t.graphStore),p(`audit`)&&Oa(e,t.store,t.embedder,n.tokenBudget);let _=n.sources[0]?.path??process.cwd();p(`compact`)&&uo(e,t.embedder,t.fileCache,_,n.allRoots,h),p(`scope_map`)&&fo(e,t.embedder,t.store,h),p(`find`)&&po(e,t.embedder,t.store,_,h),p(`parse_output`)&&Do(e),p(`workset`)&&mc(e),p(`check`)&&wo(e,h,n.tokenBudget),p(`symbol`)&&mo(e,t.embedder,t.store,t.graphStore),p(`eval`)&&To(e),p(`test_run`)&&Eo(e,h),p(`stash`)&&hc(e),p(`git_context`)&&$s(e),p(`diff_parse`)&&ec(e),p(`rename`)&&tc(e),p(`codemod`)&&nc(e),p(`restore`)&&Hu(e),p(`file_summary`)&&ho(e,t.fileCache,_,n.allRoots,h),p(`checkpoint`)&&gc(e),p(`data_transform`)&&rc(e),p(`trace`)&&go(e,t.embedder,t.store,t.graphStore),p(`process`)&&gs(e),p(`watch`)&&_s(e),p(`dead_symbols`)&&_o(e,t.embedder,t.store,_,n.allRoots,h),p(`delegate`)&&Oo(e,a),p(`health`)&&vs(e),p(`lane`)&&_c(e),p(`queue`)&&vc(e),p(`web_fetch`)&&ys(e),p(`guide`)&&bs(e,o),oc.some(e=>p(e))&&sc(e,n,m),p(`evidence_map`)&&ss(e),p(`digest`)&&cs(e,t.embedder),p(`forge_classify`)&&ls(e),p(`stratum_card`)&&us(e,t.embedder,t.fileCache),p(`forge_ground`)&&ds(e,t.embedder,t.store),p(`present`)&&Nu(e,r),p(`web_search`)&&gd(e),p(`http`)&&_d(e),p(`regex_test`)&&vd(e),p(`encode`)&&yd(e),p(`measure`)&&bd(e),p(`changelog`)&&xd(e),p(`schema_validate`)&&Sd(e),p(`env`)&&Cd(e),p(`time`)&&wd(e),p(`flow`)&&as(e,n),t.bridge&&Ur.some(e=>p(e))&&(Ma(e,t.bridge,t.evolutionCollector),Na(e,t.bridge),Pa(e,t.bridge)),t.policyStore&&p(`er_update_policy`)&&wc(e,t.policyStore),t.evolutionCollector&&p(`er_evolve_review`)&&So(e,t.evolutionCollector),Hr(e,t.store,t.curated),p(`replay`)&&Bu(e),p(`session_digest`)&&rd(e,a)}function Ed(e,t,n){let r=e=>!n||n.has(e);r(`check`)&&wo(e,void 0,t.tokenBudget),r(`eval`)&&To(e),r(`test_run`)&&Eo(e),r(`parse_output`)&&Do(e),r(`delegate`)&&Oo(e),r(`git_context`)&&$s(e),r(`diff_parse`)&&ec(e),r(`rename`)&&tc(e),r(`codemod`)&&nc(e),r(`data_transform`)&&rc(e),r(`workset`)&&mc(e),r(`stash`)&&hc(e),r(`checkpoint`)&&gc(e),r(`restore`)&&Hu(e),r(`lane`)&&_c(e),r(`queue`)&&vc(e),r(`session_digest`)&&rd(e),r(`health`)&&vs(e),r(`process`)&&gs(e),r(`watch`)&&_s(e),r(`web_fetch`)&&ys(e),r(`guide`)&&bs(e),oc.some(e=>r(e))&&sc(e,t,[...n??new Set(L)]),r(`evidence_map`)&&ss(e),r(`forge_classify`)&&ls(e),r(`present`)&&Nu(e),r(`produce_knowledge`)&&Lu(e),r(`replay`)&&Bu(e),r(`status`)&&pd(e),r(`flow`)&&as(e,t),r(`web_search`)&&gd(e),r(`http`)&&_d(e),r(`regex_test`)&&vd(e),r(`encode`)&&yd(e),r(`measure`)&&bd(e),r(`changelog`)&&xd(e),r(`schema_validate`)&&Sd(e),r(`env`)&&Cd(e),r(`time`)&&wd(e)}const Dd=k(`resource-notifier`);var Od=class{mcpServer;constructor(e){this.mcpServer=e}async notifyStatusChanged(){await this.sendUpdate(`aikit://status`)}async notifyFileTreeChanged(){await this.sendUpdate(`aikit://file-tree`)}async notifyCuratedIndexChanged(){await this.sendUpdate(`aikit://curated`)}async notifyCuratedEntryChanged(e){await this.sendUpdate(`aikit://curated/${e}`)}async notifyResourceListChanged(){try{await this.mcpServer.server.sendResourceListChanged()}catch(e){Dd.debug(`sendResourceListChanged failed`,{error:String(e)})}}async notifyAfterReindex(){await Promise.allSettled([this.notifyStatusChanged(),this.notifyFileTreeChanged()])}async notifyAfterCuratedWrite(e){let t=[this.notifyStatusChanged(),this.notifyCuratedIndexChanged()];e&&t.push(this.notifyCuratedEntryChanged(e)),await Promise.allSettled(t)}async sendUpdate(e){try{await this.mcpServer.server.sendResourceUpdated({uri:e})}catch(t){Dd.debug(`sendResourceUpdated failed`,{uri:e,error:String(t)})}}};const Z=k(`server`);async function kd(n){Z.info(`Initializing AI Kit components`);let r=n.store.backend,i=n.store.path,a=null;if(r===`sqlite-vec`){let e=v(i,`aikit.db`);a=await Cn(e),Z.info(`SQLite adapter ready`,{type:a.type,vectorCapable:a.vectorCapable,dbPath:e}),a.vectorCapable||Z.warn(`┌──────────────────────────────────────────────────────────────────┐
|
|
550
530
|
│ ⚠ SQLite vector extension unavailable — DEGRADED MODE │
|
|
551
531
|
│ Vector search is disabled. Hybrid search returns FTS only. │
|
|
552
532
|
│ To enable: install/rebuild better-sqlite3 (native module). │
|
|
553
|
-
└──────────────────────────────────────────────────────────────────┘`);let t=v(i,`lance`);o(t)&&Z.info(`Old LanceDB data found at ${t} — ignored. Safe to delete after verifying sqlite-vec works.`)}let[s,c,l,u]=await Promise.all([(async()=>{if(n.embedding.childProcess!==!1){let e=new jn({model:n.embedding.model,dimensions:n.embedding.dimensions,interOpNumThreads:n.embedding.interOpNumThreads,intraOpNumThreads:n.embedding.intraOpNumThreads,idleTimeoutMs:n.embedding.idleTimeoutMs});return await e.initialize(),Z.info(`Embedder loaded (child process)`,{modelId:e.modelId,dimensions:e.dimensions}),e}let{OnnxEmbedder:e}=await import(`../../embeddings/dist/index.js`),t=new e({model:n.embedding.model,dimensions:n.embedding.dimensions,interOpNumThreads:n.embedding.interOpNumThreads,intraOpNumThreads:n.embedding.intraOpNumThreads});return await t.initialize(),Z.info(`Embedder loaded (in-process)`,{modelId:t.modelId,dimensions:t.dimensions}),t})(),(async()=>{let e=await wn({backend:r,path:i,adapter:a??void 0,embeddingDim:n.embedding.dimensions});return await e.initialize(),Z.info(`Store initialized`,{backend:r}),e})(),(async()=>{let e=a?new Sn({adapter:a}):new Sn({path:i});return await e.initialize(),Z.info(`Graph store initialized`,{shared:!!a}),e})(),(async()=>{let e=await fn();if(e){let e=un.get();Z.info(`WASM tree-sitter enabled`,{grammars:e.grammarCount,dir:e.wasmDir})}else{let e=un.get();Z.warn(`WASM tree-sitter not available; analyzers will use regex fallback`,{reason:e.reason,os:e.os,arch:e.arch,healAttempted:e.healAttempted,healSuccess:e.healSuccess,healError:e.healError,pathsChecked:e.pathsChecked.map(e=>`${e.path} (${e.exists?`found`:`missing`})`)})}return e})()]),d=new Nn(s,c),p=new Mn(n.store.path);p.load(),d.setHashCache(p);let m=n.curated.path,h=new e(m);await h.initialize();let g=new t(m,c,s,h);d.setGraphStore(l);let _=ja(n.er),b=_?new gn(n.curated.path):void 0;b&&Z.info(`Policy store initialized`,{ruleCount:b.getRules().length});let S=_?new hn:void 0,C=y(n.sources[0]?.path??process.cwd(),x.aiContext),w=o(C),T=n.onboardDir?o(n.onboardDir):!1,E=w||T,D,O=w?C:n.onboardDir;if(E&&O)try{D=f(O).mtime.toISOString()}catch{}return Z.info(`Onboard state detected`,{onboardComplete:E,onboardTimestamp:D,aiKbExists:w,onboardDirExists:T}),{embedder:s,store:c,indexer:d,curated:g,graphStore:l,fileCache:new re,bridge:_,policyStore:b,evolutionCollector:S,onboardComplete:E,onboardTimestamp:D}}function
|
|
533
|
+
└──────────────────────────────────────────────────────────────────┘`);let t=v(i,`lance`);o(t)&&Z.info(`Old LanceDB data found at ${t} — ignored. Safe to delete after verifying sqlite-vec works.`)}let[s,c,l,u]=await Promise.all([(async()=>{if(n.embedding.childProcess!==!1){let e=new jn({model:n.embedding.model,dimensions:n.embedding.dimensions,interOpNumThreads:n.embedding.interOpNumThreads,intraOpNumThreads:n.embedding.intraOpNumThreads,idleTimeoutMs:n.embedding.idleTimeoutMs});return await e.initialize(),Z.info(`Embedder loaded (child process)`,{modelId:e.modelId,dimensions:e.dimensions}),e}let{OnnxEmbedder:e}=await import(`../../embeddings/dist/index.js`),t=new e({model:n.embedding.model,dimensions:n.embedding.dimensions,interOpNumThreads:n.embedding.interOpNumThreads,intraOpNumThreads:n.embedding.intraOpNumThreads});return await t.initialize(),Z.info(`Embedder loaded (in-process)`,{modelId:t.modelId,dimensions:t.dimensions}),t})(),(async()=>{let e=await wn({backend:r,path:i,adapter:a??void 0,embeddingDim:n.embedding.dimensions});return await e.initialize(),Z.info(`Store initialized`,{backend:r}),e})(),(async()=>{let e=a?new Sn({adapter:a}):new Sn({path:i});return await e.initialize(),Z.info(`Graph store initialized`,{shared:!!a}),e})(),(async()=>{let e=await fn();if(e){let e=un.get();Z.info(`WASM tree-sitter enabled`,{grammars:e.grammarCount,dir:e.wasmDir})}else{let e=un.get();Z.warn(`WASM tree-sitter not available; analyzers will use regex fallback`,{reason:e.reason,os:e.os,arch:e.arch,healAttempted:e.healAttempted,healSuccess:e.healSuccess,healError:e.healError,pathsChecked:e.pathsChecked.map(e=>`${e.path} (${e.exists?`found`:`missing`})`)})}return e})()]),d=new Nn(s,c),p=new Mn(n.store.path);p.load(),d.setHashCache(p);let m=n.curated.path,h=new e(m);await h.initialize();let g=new t(m,c,s,h);d.setGraphStore(l);let _=ja(n.er),b=_?new gn(n.curated.path):void 0;b&&Z.info(`Policy store initialized`,{ruleCount:b.getRules().length});let S=_?new hn:void 0,C=y(n.sources[0]?.path??process.cwd(),x.aiContext),w=o(C),T=n.onboardDir?o(n.onboardDir):!1,E=w||T,D,O=w?C:n.onboardDir;if(E&&O)try{D=f(O).mtime.toISOString()}catch{}return Z.info(`Onboard state detected`,{onboardComplete:E,onboardTimestamp:D,aiKbExists:w,onboardDirExists:T}),{embedder:s,store:c,indexer:d,curated:g,graphStore:l,fileCache:new re,bridge:_,policyStore:b,evolutionCollector:S,onboardComplete:E,onboardTimestamp:D}}function Ad(e,t,n){if(e.serverInstructions)return e.serverInstructions;let r=new Set;for(let e of t){let t=n[e];if(t?.category)for(let e of t.category)r.add(e)}let i=[`This server provides ${t.size} tools across ${r.size} categories: ${[...r].sort().join(`, `)}.`];return e.readOnly&&i.push(`Server is in read-only mode. Mutating operations are disabled.`),e.features?.length&&i.push(`Active feature groups: ${e.features.join(`, `)}.`),i.join(` `)}const jd=k(`background-task`);var Md=class{queue=[];running=null;get isRunning(){return this.running!==null}get currentTask(){return this.running}get pendingCount(){return this.queue.length}schedule(e){return new Promise((t,n)=>{this.queue.push({...e,resolve:t,reject:n}),this.running||this.processQueue()})}async processQueue(){for(;this.queue.length>0;){let e=this.queue.shift();if(!e)break;this.running=e.name,jd.info(`Background task started`,{task:e.name,pending:this.queue.length});let t=Date.now();try{await e.fn();let n=Date.now()-t;jd.info(`Background task completed`,{task:e.name,durationMs:n}),e.resolve()}catch(n){let r=Date.now()-t;jd.error(`Background task failed`,{task:e.name,durationMs:r,err:n}),e.reject(n instanceof Error?n:Error(String(n)))}}this.running=null}};const Nd=k(`idle-timer`);var Pd=class{timer=null;cleanupFns=[];idleMs;disposed=!1;sessionActive=!1;_busy=!1;constructor(e){this.idleMs=e?.idleMs??3e5}setBusy(e){this._busy=e,e?this.cancel():this.touch()}onIdle(e){this.cleanupFns.push(e)}markSessionActive(){this.sessionActive=!0}touch(){this.disposed||this._busy||(this.cancel(),this.timer=setTimeout(()=>{this.runCleanup()},this.idleMs),this.timer.unref&&this.timer.unref())}cancel(){this.timer&&=(clearTimeout(this.timer),null)}dispose(){this.cancel(),this.cleanupFns.length=0,this.disposed=!0}async runCleanup(){if(!this.sessionActive){Nd.info(`Idle timeout reached with no active session — skipping cleanup (waiting for first tool call)`);return}if(this._busy){Nd.info(`Skipping idle cleanup — background work in progress`);return}Nd.info(`Idle for ${this.idleMs/1e3}s — running cleanup`);let e=await Promise.allSettled(this.cleanupFns.map(e=>e()));for(let t of e)t.status===`rejected`&&Nd.warn(`Idle cleanup callback failed`,{error:String(t.reason)})}};const Fd=k(`memory-monitor`);var Id=class{timer=null;warningBytes;criticalBytes;intervalMs;pressureFns=[];memoryPressureFns=[];lastLevel=`normal`;constructor(e){this.warningBytes=e?.warningBytes??4294967296,this.criticalBytes=e?.criticalBytes??8589934592,this.intervalMs=e?.intervalMs??6e4}onPressure(e){this.pressureFns.push(e)}registerMemoryPressureCallback(e){this.memoryPressureFns.push(e)}start(){this.timer||(this.timer=setInterval(()=>this.check(),this.intervalMs),this.timer.unref&&this.timer.unref(),Fd.info(`Memory monitor started`,{warningMB:Math.round(this.warningBytes/1024/1024),criticalMB:Math.round(this.criticalBytes/1024/1024),intervalSec:Math.round(this.intervalMs/1e3)}))}stop(){this.timer&&=(clearInterval(this.timer),null)}getRssBytes(){return process.memoryUsage.rss()}check(){let e=this.getRssBytes(),t=`normal`;if(e>=this.criticalBytes?t=`critical`:e>=this.warningBytes&&(t=`warning`),t!==this.lastLevel||t===`critical`){let n=Math.round(e/1024/1024);t===`critical`?Fd.warn(`Memory CRITICAL: ${n}MB RSS — consider restarting the server`):t===`warning`?Fd.warn(`Memory WARNING: ${n}MB RSS`):this.lastLevel!==`normal`&&Fd.info(`Memory returned to normal: ${n}MB RSS`),this.lastLevel=t}if(t!==`normal`)for(let n of this.pressureFns)try{n(t,e)}catch{}if(t===`critical`)for(let e of this.memoryPressureFns)try{let t=e();t&&typeof t.catch==`function`&&t.catch(()=>{})}catch{}return t===`critical`&&typeof globalThis.gc==`function`&&globalThis.gc(),t}};const Ld=k(`tool-timeout`),Rd=new Set([`onboard`,`reindex`,`produce_knowledge`,`analyze`,`codemod`,`audit`]);var zd=class extends Error{toolName;timeoutMs;constructor(e,t){super(`Tool "${e}" timed out after ${t}ms`),this.toolName=e,this.timeoutMs=t,this.name=`ToolTimeoutError`}};function Bd(e){return Rd.has(e)?6e5:12e4}function Vd(e,t,n){return new Promise((r,i)=>{let a=!1,o=setTimeout(()=>{if(!a){a=!0;let e=new zd(n,t);Ld.warn(e.message),i(e)}},t);o.unref&&o.unref(),e().then(e=>{a||(a=!0,clearTimeout(o),r(e))},e=>{a||(a=!0,clearTimeout(o),i(e))})})}const Q=k(`server`);function Hd(e){let t=e.toLowerCase();return[`protobuf`,`invalid model`,`invalid onnx`,`unexpected end`,`unexpected token`,`failed to load`,`failed to initialize embedding`,`checksum`,`corrupt`,`malformed`,`could not load`,`onnx`,`database disk image is malformed`,`file is not a database`,`lance`,`cannot find module`,`module not found`].some(e=>t.includes(e))}async function Ud(e,t){let n=t.toLowerCase(),r;try{({rm:r}=await import(`node:fs/promises`))}catch{return}if(n.includes(`embedding`)||n.includes(`onnx`)||n.includes(`protobuf`)||n.includes(`model`)){let t=e.embedding?.model??C.model,n=v(Dn(),`.cache`,`huggingface`,`transformers-js`,t);try{await r(n,{recursive:!0,force:!0}),Q.info(`Auto-heal: cleared embedding model cache`,{path:n})}catch{}}if(n.includes(`lance`)||n.includes(`database`)||n.includes(`store`)){let t=v(e.store.path,`lance`);try{await r(t,{recursive:!0,force:!0}),Q.info(`Auto-heal: cleared LanceDB store`,{path:t})}catch{}}if(n.includes(`sqlite`)||n.includes(`database disk image`)||n.includes(`graph`)){let t=v(e.store.path,`graph.db`);try{await r(t,{force:!0}),Q.info(`Auto-heal: cleared graph database`,{path:t})}catch{}}}function Wd(e,t){let n=hi(e,L,R,Kr(e)),i=Ad(e,n,R),a=new Xt({name:e.serverName??`aikit`,version:r()},{capabilities:{logging:{},completions:{},prompts:{}},instructions:i}),o=`initializing`,s=``,c=!1,l=null,u=null,d=null;function f(e){if(!e||typeof e!=`object`)return[];let t=e,n=[];for(let e of[`path`,`file`,`source_path`,`sourcePath`,`filePath`]){let r=t[e];typeof r==`string`&&r&&n.push(r)}for(let e of[`changed_files`,`paths`,`files`]){let r=t[e];if(Array.isArray(r))for(let e of r){if(typeof e==`string`){n.push(e);continue}e&&typeof e==`object`&&typeof e.path==`string`&&n.push(e.path)}}if(Array.isArray(t.sources))for(let e of t.sources)e&&typeof e==`object`&&typeof e.path==`string`&&n.push(e.path);return n}let p=()=>o===`failed`?[`❌ AI Kit initialization failed — this tool is unavailable.`,``,s?`Error: ${s}`:``,``,`**${Yr.size} tools are still available** and fully functional:`,`check, eval, test_run, git_context, health, measure, web_fetch, web_search,`,`flow, regex_test, encode,`,`stash, checkpoint, lane, process, time, env, and more.`,``,`To fix embedding errors, try deleting the cached model:`,` rm -rf ~/.cache/huggingface/transformers-js/mixedbread-ai/`,`Then restart the server to re-download a fresh copy.`,``,`Try restarting the MCP server to retry initialization.`].filter(Boolean).join(`
|
|
554
534
|
`):[`AI Kit is still initializing (loading embeddings model & store).`,``,`**${Yr.size} tools are already available** while initialization completes — including:`,`check, eval, test_run, git_context, health, measure, web_fetch, web_search,`,`flow, regex_test, encode,`,`stash, checkpoint, lane, process, time, env, and more.`,``,`This tool requires the AI Kit index. Please retry in a few seconds,`,`or use one of the available tools above in the meantime.`].join(`
|
|
555
|
-
`);In(a),ti(a,new wr,e.toolPrefix??``);let m=a.sendToolListChanged.bind(a);a.sendToolListChanged=()=>{};let h=[];for(let e of L){if(!n.has(e))continue;let t=z(e),r=a.registerTool(e,{title:t.title,description:`${t.title} — initializing, available shortly`,inputSchema:{},annotations:t.annotations},async()=>({content:[{type:`text`,text:p()}]}));Yr.has(e)?r.remove():h.push(r)}
|
|
535
|
+
`);In(a),ti(a,new wr,e.toolPrefix??``);let m=a.sendToolListChanged.bind(a);a.sendToolListChanged=()=>{};let h=[];for(let e of L){if(!n.has(e))continue;let t=z(e),r=a.registerTool(e,{title:t.title,description:`${t.title} — initializing, available shortly`,inputSchema:{},annotations:t.annotations},async()=>({content:[{type:`text`,text:p()}]}));Yr.has(e)?r.remove():h.push(r)}Ed(a,e,n),a.sendToolListChanged=m;let g=a.registerResource(`aikit-status`,`aikit://status`,{description:`AI Kit status (initializing...)`,mimeType:`text/plain`},async()=>({contents:[{uri:`aikit://status`,text:`AI Kit is initializing...`,mimeType:`text/plain`}]})),_=a.registerPrompt(`_init`,{description:`Initializing AI Kit…`,argsSchema:{_dummy:P(F.string(),()=>[])}},async()=>({messages:[]})),v,y,b=new Promise((e,t)=>{v=e,y=t}),x,S=new Promise(e=>{x=e}),C=()=>x?.(),w=(async()=>{await S;try{let{createRequire:e}=await import(`node:module`),{readFileSync:t}=await import(`node:fs`),{fileURLToPath:n}=await import(`node:url`),{resolve:r,dirname:i}=await import(`node:path`),a=e(import.meta.url),o=r(i(n(import.meta.url)),`..`,`package.json`),s=JSON.parse(t(o,`utf8`)),c=Object.keys(s.dependencies??{}),l=[];for(let e of c)try{a.resolve(e)}catch{l.push(e)}l.length>0&&Q.warn(`${l.length} dependencies not resolvable — init may fail`,{missing:l,hint:`Corrupted npx cache from interrupted downloads. Try: npx clear-npx-cache`})}catch{}let n;try{n=await kd(e)}catch(t){let r=t instanceof Error?t.message:String(t);if(Hd(r)){Q.warn(`AI Kit initialization failed with recoverable error — attempting auto-heal retry`,{error:r}),await Ud(e,r);try{n=await kd(e),Q.info(`AI Kit auto-heal successful — initialization recovered after retry`)}catch(e){o=`failed`,s=e instanceof Error?e.message:String(e),Q.error(`AI Kit initialization failed after auto-heal attempt — server continuing with zero-dep tools only`,{error:s,originalError:r}),y?.(e instanceof Error?e:Error(s));return}}else{o=`failed`,s=r,Q.error(`AI Kit initialization failed — server continuing with zero-dep tools only`,{error:s}),y?.(t instanceof Error?t:Error(s));return}}let r=a.sendToolListChanged.bind(a);a.sendToolListChanged=()=>{};let i=a.sendPromptListChanged.bind(a);a.sendPromptListChanged=()=>{};let p=a.sendResourceListChanged.bind(a);a.sendResourceListChanged=()=>{};for(let e of h)e.remove();g.remove(),_.remove();let m=a._registeredTools??{};for(let e of Yr)m[e]?.remove();let b=new Od(a),x=No(a);Td(a,n,e,Pn(a),b,x,t,t===`smart`?(()=>{let e=d;return e?.getState?e.getState():null}):null),qn(a,{curated:n.curated,store:n.store,graphStore:n.graphStore},t),a.sendToolListChanged=r,a.sendPromptListChanged=i,a.sendResourceListChanged=p,Promise.resolve(a.sendToolListChanged()).catch(()=>{}),Promise.resolve(a.sendPromptListChanged()).catch(()=>{}),Promise.resolve(a.sendResourceListChanged()).catch(()=>{});let C=a._registeredTools??{};for(let[e,t]of Object.entries(C)){if(qr.has(e))continue;let r=t.handler;t.handler=async(...t)=>{if(!n.indexer.isIndexing)return r(...t);let i=c?`re-indexing`:`running initial index`,a=new Promise(t=>setTimeout(()=>t({content:[{type:`text`,text:`⏳ AI Kit is ${i}. The tool "${e}" timed out waiting for index data (${Jr/1e3}s).\n\nThe existing index may be temporarily locked. Please retry shortly — indexing will complete automatically.`}]}),Jr));return Promise.race([r(...t),a])}}for(let[e,t]of Object.entries(C)){let n=t.handler,r=Bd(e);t.handler=async(...t)=>{try{return await Vd(()=>n(...t),r,e)}catch(t){if(t instanceof zd)return{content:[{type:`text`,text:`⏳ Tool "${e}" timed out after ${r/1e3}s. This may indicate a long-running operation. Please retry or break the task into smaller steps.`}]};throw t}}}let w=Object.keys(C).length;w<L.length&&Q.warn(`ALL_TOOL_NAMES count mismatch`,{expectedToolCount:L.length,registeredToolCount:w}),Q.info(`MCP server configured`,{toolCount:L.length,resourceCount:4});let T=new Id;T.onPressure((e,t)=>{e===`warning`&&Bn(),e===`critical`&&(Q.warn(`Memory pressure critical — consider restarting`,{rssMB:Math.round(t/1024/1024)}),Bn())}),T.registerMemoryPressureCallback(()=>n.embedder.shutdown?.()),T.start();let D=new Pd;u=D,D.onIdle(async()=>{if(E.isRunning||n.indexer.isIndexing){Q.info(`Idle cleanup deferred — background tasks still running`),D.touch();return}Q.info(`Idle cleanup: releasing cached memory (connections stay open)`);try{n.store.releaseMemory?.(),n.graphStore.releaseMemory?.()}catch{}}),D.touch();let O=!1;for(let e of Object.values(C)){let t=e.handler;e.handler=async(...e)=>{if(O||(O=!0,D.markSessionActive()),D.touch(),d){let t=f(e[0]);t.length>0&&d.prioritize(...t)}return t(...e)}}process.stdin.on(`end`,()=>(Q.info(`stdin closed — MCP client disconnected. Shutting down.`),process.exit(0))),process.stdin.on(`error`,()=>(Q.info(`stdin error — MCP client disconnected. Shutting down.`),process.exit(0))),l=n,v?.(n)})(),T=async()=>{let t;try{t=await b}catch{Q.warn(`Skipping initial index — AI Kit initialization failed`);return}u?.setBusy(!0);try{let n=e.sources.map(e=>e.path).join(`, `);Q.info(`Running initial index`,{sourcePaths:n});let r=await t.indexer.index(e,e=>{e.phase===`crawling`||e.phase===`done`||(e.phase===`chunking`&&e.currentFile&&Q.debug(`Indexing file`,{current:e.filesProcessed+1,total:e.filesTotal,file:e.currentFile}),e.phase===`cleanup`&&Q.debug(`Index cleanup`,{staleEntries:e.filesTotal-e.filesProcessed}))});c=!0,Q.info(`Initial index complete`,{filesProcessed:r.filesProcessed,filesSkipped:r.filesSkipped,chunksCreated:r.chunksCreated,durationMs:r.durationMs});try{await t.store.createFtsIndex()}catch(e){Q.warn(`FTS index creation failed`,j(e))}try{let e=await t.curated.reindexAll();Q.info(`Curated re-index complete`,{indexed:e.indexed})}catch(e){Q.error(`Curated re-index failed`,j(e))}}catch(e){Q.error(`Initial index failed; will retry on aikit_reindex`,j(e))}finally{u?.setBusy(!1)}},E=new Md,D=()=>E.schedule({name:`initial-index`,fn:T}),O=process.ppid,k=setInterval(()=>{try{process.kill(O,0)}catch{Q.info(`Parent process died; shutting down`,{parentPid:O}),clearInterval(k),d?.stop&&d.stop(),b.then(async e=>{await Promise.all([e.embedder.shutdown?.().catch(()=>{})??Promise.resolve(),e.graphStore.close().catch(()=>{}),e.store.close().catch(()=>{})])}).catch(()=>{}).finally(()=>process.exit(0))}},5e3);return k.unref(),{server:a,startInit:C,ready:w,runInitialIndex:D,get aikit(){return l},scheduler:E,setSmartScheduler(e){d=e}}}const $=k(`server`);function Gd(e,t){let n=hi(t,[...L,...Wr],R,Kr(t)),i=Ad(t,n,R),a=new Xt({name:t.serverName??`aikit`,version:r()},{capabilities:{logging:{},completions:{},prompts:{}},instructions:i});return In(a),Td(a,e,t,Pn(a),new Od(a),No(a),void 0,null,n),qn(a,{curated:e.curated,store:e.store,graphStore:e.graphStore},t.indexMode),a}async function Kd(e){let t=await kd(e),n=Gd(t,e);$.info(`MCP server configured`,{toolCount:L.length,resourceCount:2});let r=async()=>{try{let n=e.sources.map(e=>e.path).join(`, `);$.info(`Running initial index`,{sourcePaths:n});let r=await t.indexer.index(e,e=>{e.phase===`crawling`||e.phase===`done`||(e.phase===`chunking`&&e.currentFile&&$.debug(`Indexing file`,{current:e.filesProcessed+1,total:e.filesTotal,file:e.currentFile}),e.phase===`cleanup`&&$.debug(`Index cleanup`,{staleEntries:e.filesTotal-e.filesProcessed}))});$.info(`Initial index complete`,{filesProcessed:r.filesProcessed,filesSkipped:r.filesSkipped,chunksCreated:r.chunksCreated,durationMs:r.durationMs});try{await t.store.createFtsIndex()}catch(e){$.warn(`FTS index creation failed`,j(e))}try{let e=await t.curated.reindexAll();$.info(`Curated re-index complete`,{indexed:e.indexed})}catch(e){$.error(`Curated re-index failed`,j(e))}}catch(e){$.error(`Initial index failed; will retry on aikit_reindex`,j(e))}},i=async()=>{$.info(`Shutting down`),await Promise.all([t.embedder.shutdown?.().catch(()=>{})??Promise.resolve(),t.graphStore.close().catch(()=>{}),t.store.close().catch(()=>{})]),process.exit(0)};process.on(`SIGINT`,i),process.on(`SIGTERM`,i);let a=process.ppid,o=setInterval(()=>{try{process.kill(a,0)}catch{$.info(`Parent process died; shutting down`,{parentPid:a}),clearInterval(o),i()}},5e3);return o.unref(),{server:n,runInitialIndex:r,shutdown:i}}export{L as ALL_TOOL_NAMES,Wd as createLazyServer,Gd as createMcpServer,Kd as createServer,kd as initializeAikit,Td as registerMcpTools};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const e="| Type | Description | Value Shape |\n|------|-------------|-------------|\n| `markdown` | Markdown content rendered with the marked parser. | `string` |\n| `code` | Formatted code block rendered inside pre/code tags. | `string` |\n| `mermaid` | Mermaid diagram source rendered in a mermaid pre block. | `string` |\n| `table` | Tabular data rendered from records or explicit headers and rows. | `Record<string, unknown>[] | { headers: string[]; rows: unknown[][] }` |\n| `metrics` | Metric cards showing label/value pairs with optional trend and status. | `Array<{ label: string; value: string | number; trend?: string | number; status?: string }>` |\n| `cards` | Card grid for titled items with optional body, badge, and status. | `Array<{ title: string; body?: string; badge?: string; status?: string; description?: string }>` |\n| `tree` | Hierarchical object or name/children tree rendered recursively. | `{ name: string; children?: unknown[] } | Record<string, unknown>` |\n| `graph` | Node and edge graph rendered as a Mermaid flow graph in HTML mode. | `{ nodes: Array<{ id: string; label?: string }>; edges: Array<{ from: string; to: string; label?: string }> }` |\n| `chart` | Structured chart definition rendered as SVG. | `{ chartType: string; data: Record<string, unknown>[]; xKey: string; yKeys: string[] }` |\n| `timeline` | Timeline entries rendered as a vertical sequence of events. | `Array<{ title: string; description?: string; timestamp?: string; status?: string }>` |\n| `checklist` | Checklist items with boolean checked state. | `Array<{label, checked}> | {items: Array<{label, checked}>}` |\n| `comparison` | Side-by-side comparison columns with titled item lists. | `Array<{title, items}> | {columns: Array<{title, items}>}` |\n| `status-board` | Status categories containing labeled status items. | `Array<{category, items}> | {items: Array<{category, items}>}` |\n| `prompt` | Prompt payload rendered through the prompt display helper. | `unknown` |\n| `progress` | Progress bar with current value and optional maximum. | `{label, value, max?} | {items: Array<{label, value, max?, color?}>}` |\n| `
|
|
1
|
+
const e="| Type | Description | Value Shape |\n|------|-------------|-------------|\n| `markdown` | Markdown content rendered with the marked parser. | `string` |\n| `code` | Formatted code block rendered inside pre/code tags. | `string` |\n| `mermaid` | Mermaid diagram source rendered in a mermaid pre block. | `string` |\n| `table` | Tabular data rendered from records or explicit headers and rows. | `Record<string, unknown>[] | { headers: string[]; rows: unknown[][] }` |\n| `metrics` | Metric cards showing label/value pairs with optional trend and status. | `Array<{ label: string; value: string | number; trend?: string | number; status?: string }>` |\n| `cards` | Card grid for titled items with optional body, badge, and status. | `Array<{ title: string; body?: string; badge?: string; status?: string; description?: string }>` |\n| `tree` | Hierarchical object or name/children tree rendered recursively. | `{ name: string; children?: unknown[] } | Record<string, unknown>` |\n| `graph` | Node and edge graph rendered as a Mermaid flow graph in HTML mode. | `{ nodes: Array<{ id: string; label?: string }>; edges: Array<{ from: string; to: string; label?: string }> }` |\n| `chart` | Structured chart definition rendered as SVG. | `{ chartType: string; data: Record<string, unknown>[]; xKey: string; yKeys: string[] }` |\n| `timeline` | Timeline entries rendered as a vertical sequence of events. | `Array<{ title: string; description?: string; timestamp?: string; status?: string }>` |\n| `checklist` | Checklist items with boolean checked state. | `Array<{label, checked}> | {items: Array<{label, checked}>}` |\n| `comparison` | Side-by-side comparison columns with titled item lists. | `Array<{title, items}> | {columns: Array<{title, items}>}` |\n| `status-board` | Status categories containing labeled status items. | `Array<{category, items}> | {items: Array<{category, items}>}` |\n| `prompt` | Prompt payload rendered through the prompt display helper. | `unknown` |\n| `progress` | Progress bar with current value and optional maximum. | `{label, value, max?} | {items: Array<{label, value, max?, color?}>}` |\n| `docs-browser` | Documentation file list with inline content previews for chat-safe rendering. | `{ files: Array<{ path: string; title?: string; content?: string; status?: \"current\" | \"stale\" | \"missing\" }>; title?: string }` |\n| `text` | Plain text content rendered through the markdown parser. | `string` |\n| `heading` | Single heading with configurable level from h1 to h6. | `string` |\n| `paragraph` | Single paragraph rendered inside a p tag. | `string` |\n| `separator` | Horizontal rule used to separate adjacent blocks. | `undefined` |\n| `actions` | Action bar containing button and select action definitions. | `Array<{ type: string; id: string; label: string; variant?: string; options?: Array<string | { label: string; value: string }> }>` |\n\n### Usage Examples\n\n#### `docs-browser`\n\n```typescript\n{\n type: 'docs-browser',\n value: {\n title: 'Project Docs',\n files: [\n { path: 'docs/README.md', title: 'Overview', status: 'current' },\n { path: 'docs/api.md', title: 'API Reference', status: 'stale' },\n ],\n },\n}\n```",t=` - type:"markdown" → value: string
|
|
2
2
|
- type:"code" → value: string
|
|
3
3
|
- type:"mermaid" → value: string
|
|
4
4
|
- type:"table" → value: Record<string, unknown>[] | { headers: string[]; rows: unknown[][] }
|
|
@@ -13,69 +13,9 @@ const e="| Type | Description | Value Shape |\n|------|-------------|-----------
|
|
|
13
13
|
- type:"status-board" → value: Array<{category, items}> | {items: Array<{category, items}>}
|
|
14
14
|
- type:"prompt" → value: unknown
|
|
15
15
|
- type:"progress" → value: {label, value, max?} | {items: Array<{label, value, max?, color?}>}
|
|
16
|
-
- type:"viewer-link" → value: { viewerType: string; label: string; description?: string; url?: string; icon?: string }
|
|
17
16
|
- type:"docs-browser" → value: { files: Array<{ path: string; title?: string; content?: string; status?: "current" | "stale" | "missing" }>; title?: string }
|
|
18
17
|
- type:"text" → value: string
|
|
19
18
|
- type:"heading" → value: string
|
|
20
19
|
- type:"paragraph" → value: string
|
|
21
20
|
- type:"separator" → value: undefined
|
|
22
|
-
- type:"actions" → value: Array<{ type: string; id: string; label: string; variant?: string; options?: Array<string | { label: string; value: string }> }>`,n={present:"| Type | Description | Value Shape |\n|------|-------------|-------------|\n| `markdown` | Markdown content rendered with the marked parser. | `string` |\n| `code` | Formatted code block rendered inside pre/code tags. | `string` |\n| `mermaid` | Mermaid diagram source rendered in a mermaid pre block. | `string` |\n| `table` | Tabular data rendered from records or explicit headers and rows. | `Record<string, unknown>[] | { headers: string[]; rows: unknown[][] }` |\n| `metrics` | Metric cards showing label/value pairs with optional trend and status. | `Array<{ label: string; value: string | number; trend?: string | number; status?: string }>` |\n| `cards` | Card grid for titled items with optional body, badge, and status. | `Array<{ title: string; body?: string; badge?: string; status?: string; description?: string }>` |\n| `tree` | Hierarchical object or name/children tree rendered recursively. | `{ name: string; children?: unknown[] } | Record<string, unknown>` |\n| `graph` | Node and edge graph rendered as a Mermaid flow graph in HTML mode. | `{ nodes: Array<{ id: string; label?: string }>; edges: Array<{ from: string; to: string; label?: string }> }` |\n| `chart` | Structured chart definition rendered as SVG. | `{ chartType: string; data: Record<string, unknown>[]; xKey: string; yKeys: string[] }` |\n| `timeline` | Timeline entries rendered as a vertical sequence of events. | `Array<{ title: string; description?: string; timestamp?: string; status?: string }>` |\n| `checklist` | Checklist items with boolean checked state. | `Array<{label, checked}> | {items: Array<{label, checked}>}` |\n| `comparison` | Side-by-side comparison columns with titled item lists. | `Array<{title, items}> | {columns: Array<{title, items}>}` |\n| `status-board` | Status categories containing labeled status items. | `Array<{category, items}> | {items: Array<{category, items}>}` |\n| `prompt` | Prompt payload rendered through the prompt display helper. | `unknown` |\n| `progress` | Progress bar with current value and optional maximum. | `{label, value, max?} | {items: Array<{label, value, max?, color?}>}` |\n| `
|
|
23
|
-
|------|-------------|-------------|
|
|
24
|
-
| \`markdown\` | Markdown content rendered with the marked parser. | \`string\` |
|
|
25
|
-
| \`code\` | Formatted code block rendered inside pre/code tags. | \`string\` |
|
|
26
|
-
| \`mermaid\` | Mermaid diagram source rendered in a mermaid pre block. | \`string\` |
|
|
27
|
-
| \`table\` | Tabular data rendered from records or explicit headers and rows. | \`Record<string, unknown>[] | { headers: string[]; rows: unknown[][] }\` |
|
|
28
|
-
| \`cards\` | Card grid for titled items with optional body, badge, and status. | \`Array<{ title: string; body?: string; badge?: string; status?: string; description?: string }>\` |
|
|
29
|
-
| \`viewer-link\` | Styled card linking to a standalone interactive viewer. | \`{ viewerType: string; label: string; description?: string; url?: string; icon?: string }\` |
|
|
30
|
-
| \`docs-browser\` | Collapsible file tree with markdown content for documentation browsing. | \`{ files: Array<{ path: string; title?: string; content?: string; status?: "current" | "stale" | "missing" }>; title?: string }\` |
|
|
31
|
-
|
|
32
|
-
### Usage Examples
|
|
33
|
-
|
|
34
|
-
#### \`viewer-link\`
|
|
35
|
-
|
|
36
|
-
\`\`\`typescript
|
|
37
|
-
{
|
|
38
|
-
type: 'viewer-link',
|
|
39
|
-
value: {
|
|
40
|
-
viewerType: 'c4',
|
|
41
|
-
label: 'Open Interactive C4 Diagram',
|
|
42
|
-
description: 'Drag, zoom, and pan with ELK auto-layout',
|
|
43
|
-
icon: '🏗️',
|
|
44
|
-
},
|
|
45
|
-
}
|
|
46
|
-
\`\`\`
|
|
47
|
-
|
|
48
|
-
#### \`docs-browser\`
|
|
49
|
-
|
|
50
|
-
\`\`\`typescript
|
|
51
|
-
{
|
|
52
|
-
type: 'docs-browser',
|
|
53
|
-
value: {
|
|
54
|
-
title: 'Project Docs',
|
|
55
|
-
files: [
|
|
56
|
-
{ path: 'docs/README.md', title: 'Overview', status: 'current' },
|
|
57
|
-
{ path: 'docs/api.md', title: 'API Reference', status: 'stale' },
|
|
58
|
-
],
|
|
59
|
-
},
|
|
60
|
-
}
|
|
61
|
-
\`\`\``,"c4-architecture":`| Type | Description | Value Shape |
|
|
62
|
-
|------|-------------|-------------|
|
|
63
|
-
| \`mermaid\` | Mermaid diagram source rendered in a mermaid pre block. | \`string\` |
|
|
64
|
-
| \`graph\` | Node and edge graph rendered as a Mermaid flow graph in HTML mode. | \`{ nodes: Array<{ id: string; label?: string }>; edges: Array<{ from: string; to: string; label?: string }> }\` |
|
|
65
|
-
| \`viewer-link\` | Styled card linking to a standalone interactive viewer. | \`{ viewerType: string; label: string; description?: string; url?: string; icon?: string }\` |
|
|
66
|
-
|
|
67
|
-
### Usage Examples
|
|
68
|
-
|
|
69
|
-
#### \`viewer-link\`
|
|
70
|
-
|
|
71
|
-
\`\`\`typescript
|
|
72
|
-
{
|
|
73
|
-
type: 'viewer-link',
|
|
74
|
-
value: {
|
|
75
|
-
viewerType: 'c4',
|
|
76
|
-
label: 'Open Interactive C4 Diagram',
|
|
77
|
-
description: 'Drag, zoom, and pan with ELK auto-layout',
|
|
78
|
-
icon: '🏗️',
|
|
79
|
-
},
|
|
80
|
-
}
|
|
81
|
-
\`\`\``};export{e as ALL_BLOCK_DOCS,n as BLOCK_DOCS_BY_SKILL,t as BLOCK_TYPE_LIST};
|
|
21
|
+
- type:"actions" → value: Array<{ type: string; id: string; label: string; variant?: string; options?: Array<string | { label: string; value: string }> }>`,n={present:"| Type | Description | Value Shape |\n|------|-------------|-------------|\n| `markdown` | Markdown content rendered with the marked parser. | `string` |\n| `code` | Formatted code block rendered inside pre/code tags. | `string` |\n| `mermaid` | Mermaid diagram source rendered in a mermaid pre block. | `string` |\n| `table` | Tabular data rendered from records or explicit headers and rows. | `Record<string, unknown>[] | { headers: string[]; rows: unknown[][] }` |\n| `metrics` | Metric cards showing label/value pairs with optional trend and status. | `Array<{ label: string; value: string | number; trend?: string | number; status?: string }>` |\n| `cards` | Card grid for titled items with optional body, badge, and status. | `Array<{ title: string; body?: string; badge?: string; status?: string; description?: string }>` |\n| `tree` | Hierarchical object or name/children tree rendered recursively. | `{ name: string; children?: unknown[] } | Record<string, unknown>` |\n| `graph` | Node and edge graph rendered as a Mermaid flow graph in HTML mode. | `{ nodes: Array<{ id: string; label?: string }>; edges: Array<{ from: string; to: string; label?: string }> }` |\n| `chart` | Structured chart definition rendered as SVG. | `{ chartType: string; data: Record<string, unknown>[]; xKey: string; yKeys: string[] }` |\n| `timeline` | Timeline entries rendered as a vertical sequence of events. | `Array<{ title: string; description?: string; timestamp?: string; status?: string }>` |\n| `checklist` | Checklist items with boolean checked state. | `Array<{label, checked}> | {items: Array<{label, checked}>}` |\n| `comparison` | Side-by-side comparison columns with titled item lists. | `Array<{title, items}> | {columns: Array<{title, items}>}` |\n| `status-board` | Status categories containing labeled status items. | `Array<{category, items}> | {items: Array<{category, items}>}` |\n| `prompt` | Prompt payload rendered through the prompt display helper. | `unknown` |\n| `progress` | Progress bar with current value and optional maximum. | `{label, value, max?} | {items: Array<{label, value, max?, color?}>}` |\n| `docs-browser` | Documentation file list with inline content previews for chat-safe rendering. | `{ files: Array<{ path: string; title?: string; content?: string; status?: \"current\" | \"stale\" | \"missing\" }>; title?: string }` |\n\n### Usage Examples\n\n#### `docs-browser`\n\n```typescript\n{\n type: 'docs-browser',\n value: {\n title: 'Project Docs',\n files: [\n { path: 'docs/README.md', title: 'Overview', status: 'current' },\n { path: 'docs/api.md', title: 'API Reference', status: 'stale' },\n ],\n },\n}\n```",docs:"| Type | Description | Value Shape |\n|------|-------------|-------------|\n| `markdown` | Markdown content rendered with the marked parser. | `string` |\n| `code` | Formatted code block rendered inside pre/code tags. | `string` |\n| `mermaid` | Mermaid diagram source rendered in a mermaid pre block. | `string` |\n| `table` | Tabular data rendered from records or explicit headers and rows. | `Record<string, unknown>[] | { headers: string[]; rows: unknown[][] }` |\n| `cards` | Card grid for titled items with optional body, badge, and status. | `Array<{ title: string; body?: string; badge?: string; status?: string; description?: string }>` |\n| `docs-browser` | Documentation file list with inline content previews for chat-safe rendering. | `{ files: Array<{ path: string; title?: string; content?: string; status?: \"current\" | \"stale\" | \"missing\" }>; title?: string }` |\n\n### Usage Examples\n\n#### `docs-browser`\n\n```typescript\n{\n type: 'docs-browser',\n value: {\n title: 'Project Docs',\n files: [\n { path: 'docs/README.md', title: 'Overview', status: 'current' },\n { path: 'docs/api.md', title: 'API Reference', status: 'stale' },\n ],\n },\n}\n```","c4-architecture":"| Type | Description | Value Shape |\n|------|-------------|-------------|\n| `mermaid` | Mermaid diagram source rendered in a mermaid pre block. | `string` |\n| `graph` | Node and edge graph rendered as a Mermaid flow graph in HTML mode. | `{ nodes: Array<{ id: string; label?: string }>; edges: Array<{ from: string; to: string; label?: string }> }` |"};export{e as ALL_BLOCK_DOCS,n as BLOCK_DOCS_BY_SKILL,t as BLOCK_TYPE_LIST};
|
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
// AUTO-GENERATED - do not edit manually.
|
|
2
2
|
// Source: packages/server/src/tools/present/block-registry.ts
|
|
3
|
-
// Generated at: 2026-05-
|
|
3
|
+
// Generated at: 2026-05-10T14:06:21.809Z
|
|
4
4
|
|
|
5
|
-
export const ALL_BLOCK_DOCS = "| Type | Description | Value Shape |\n|------|-------------|-------------|\n| `markdown` | Markdown content rendered with the marked parser. | `string` |\n| `code` | Formatted code block rendered inside pre/code tags. | `string` |\n| `mermaid` | Mermaid diagram source rendered in a mermaid pre block. | `string` |\n| `table` | Tabular data rendered from records or explicit headers and rows. | `Record<string, unknown>[] | { headers: string[]; rows: unknown[][] }` |\n| `metrics` | Metric cards showing label/value pairs with optional trend and status. | `Array<{ label: string; value: string | number; trend?: string | number; status?: string }>` |\n| `cards` | Card grid for titled items with optional body, badge, and status. | `Array<{ title: string; body?: string; badge?: string; status?: string; description?: string }>` |\n| `tree` | Hierarchical object or name/children tree rendered recursively. | `{ name: string; children?: unknown[] } | Record<string, unknown>` |\n| `graph` | Node and edge graph rendered as a Mermaid flow graph in HTML mode. | `{ nodes: Array<{ id: string; label?: string }>; edges: Array<{ from: string; to: string; label?: string }> }` |\n| `chart` | Structured chart definition rendered as SVG. | `{ chartType: string; data: Record<string, unknown>[]; xKey: string; yKeys: string[] }` |\n| `timeline` | Timeline entries rendered as a vertical sequence of events. | `Array<{ title: string; description?: string; timestamp?: string; status?: string }>` |\n| `checklist` | Checklist items with boolean checked state. | `Array<{label, checked}> | {items: Array<{label, checked}>}` |\n| `comparison` | Side-by-side comparison columns with titled item lists. | `Array<{title, items}> | {columns: Array<{title, items}>}` |\n| `status-board` | Status categories containing labeled status items. | `Array<{category, items}> | {items: Array<{category, items}>}` |\n| `prompt` | Prompt payload rendered through the prompt display helper. | `unknown` |\n| `progress` | Progress bar with current value and optional maximum. | `{label, value, max?} | {items: Array<{label, value, max?, color?}>}` |\n| `
|
|
5
|
+
export const ALL_BLOCK_DOCS = "| Type | Description | Value Shape |\n|------|-------------|-------------|\n| `markdown` | Markdown content rendered with the marked parser. | `string` |\n| `code` | Formatted code block rendered inside pre/code tags. | `string` |\n| `mermaid` | Mermaid diagram source rendered in a mermaid pre block. | `string` |\n| `table` | Tabular data rendered from records or explicit headers and rows. | `Record<string, unknown>[] | { headers: string[]; rows: unknown[][] }` |\n| `metrics` | Metric cards showing label/value pairs with optional trend and status. | `Array<{ label: string; value: string | number; trend?: string | number; status?: string }>` |\n| `cards` | Card grid for titled items with optional body, badge, and status. | `Array<{ title: string; body?: string; badge?: string; status?: string; description?: string }>` |\n| `tree` | Hierarchical object or name/children tree rendered recursively. | `{ name: string; children?: unknown[] } | Record<string, unknown>` |\n| `graph` | Node and edge graph rendered as a Mermaid flow graph in HTML mode. | `{ nodes: Array<{ id: string; label?: string }>; edges: Array<{ from: string; to: string; label?: string }> }` |\n| `chart` | Structured chart definition rendered as SVG. | `{ chartType: string; data: Record<string, unknown>[]; xKey: string; yKeys: string[] }` |\n| `timeline` | Timeline entries rendered as a vertical sequence of events. | `Array<{ title: string; description?: string; timestamp?: string; status?: string }>` |\n| `checklist` | Checklist items with boolean checked state. | `Array<{label, checked}> | {items: Array<{label, checked}>}` |\n| `comparison` | Side-by-side comparison columns with titled item lists. | `Array<{title, items}> | {columns: Array<{title, items}>}` |\n| `status-board` | Status categories containing labeled status items. | `Array<{category, items}> | {items: Array<{category, items}>}` |\n| `prompt` | Prompt payload rendered through the prompt display helper. | `unknown` |\n| `progress` | Progress bar with current value and optional maximum. | `{label, value, max?} | {items: Array<{label, value, max?, color?}>}` |\n| `docs-browser` | Documentation file list with inline content previews for chat-safe rendering. | `{ files: Array<{ path: string; title?: string; content?: string; status?: \"current\" | \"stale\" | \"missing\" }>; title?: string }` |\n| `text` | Plain text content rendered through the markdown parser. | `string` |\n| `heading` | Single heading with configurable level from h1 to h6. | `string` |\n| `paragraph` | Single paragraph rendered inside a p tag. | `string` |\n| `separator` | Horizontal rule used to separate adjacent blocks. | `undefined` |\n| `actions` | Action bar containing button and select action definitions. | `Array<{ type: string; id: string; label: string; variant?: string; options?: Array<string | { label: string; value: string }> }>` |\n\n### Usage Examples\n\n#### `docs-browser`\n\n```typescript\n{\n type: 'docs-browser',\n value: {\n title: 'Project Docs',\n files: [\n { path: 'docs/README.md', title: 'Overview', status: 'current' },\n { path: 'docs/api.md', title: 'API Reference', status: 'stale' },\n ],\n },\n}\n```";
|
|
6
6
|
|
|
7
|
-
export const BLOCK_TYPE_LIST = " - type:\"markdown\" → value: string\n - type:\"code\" → value: string\n - type:\"mermaid\" → value: string\n - type:\"table\" → value: Record<string, unknown>[] | { headers: string[]; rows: unknown[][] }\n - type:\"metrics\" → value: Array<{ label: string; value: string | number; trend?: string | number; status?: string }>\n - type:\"cards\" → value: Array<{ title: string; body?: string; badge?: string; status?: string; description?: string }>\n - type:\"tree\" → value: { name: string; children?: unknown[] } | Record<string, unknown>\n - type:\"graph\" → value: { nodes: Array<{ id: string; label?: string }>; edges: Array<{ from: string; to: string; label?: string }> }\n - type:\"chart\" → value: { chartType: string; data: Record<string, unknown>[]; xKey: string; yKeys: string[] }\n - type:\"timeline\" → value: Array<{ title: string; description?: string; timestamp?: string; status?: string }>\n - type:\"checklist\" → value: Array<{label, checked}> | {items: Array<{label, checked}>}\n - type:\"comparison\" → value: Array<{title, items}> | {columns: Array<{title, items}>}\n - type:\"status-board\" → value: Array<{category, items}> | {items: Array<{category, items}>}\n - type:\"prompt\" → value: unknown\n - type:\"progress\" → value: {label, value, max?} | {items: Array<{label, value, max?, color?}>}\n - type:\"
|
|
7
|
+
export const BLOCK_TYPE_LIST = " - type:\"markdown\" → value: string\n - type:\"code\" → value: string\n - type:\"mermaid\" → value: string\n - type:\"table\" → value: Record<string, unknown>[] | { headers: string[]; rows: unknown[][] }\n - type:\"metrics\" → value: Array<{ label: string; value: string | number; trend?: string | number; status?: string }>\n - type:\"cards\" → value: Array<{ title: string; body?: string; badge?: string; status?: string; description?: string }>\n - type:\"tree\" → value: { name: string; children?: unknown[] } | Record<string, unknown>\n - type:\"graph\" → value: { nodes: Array<{ id: string; label?: string }>; edges: Array<{ from: string; to: string; label?: string }> }\n - type:\"chart\" → value: { chartType: string; data: Record<string, unknown>[]; xKey: string; yKeys: string[] }\n - type:\"timeline\" → value: Array<{ title: string; description?: string; timestamp?: string; status?: string }>\n - type:\"checklist\" → value: Array<{label, checked}> | {items: Array<{label, checked}>}\n - type:\"comparison\" → value: Array<{title, items}> | {columns: Array<{title, items}>}\n - type:\"status-board\" → value: Array<{category, items}> | {items: Array<{category, items}>}\n - type:\"prompt\" → value: unknown\n - type:\"progress\" → value: {label, value, max?} | {items: Array<{label, value, max?, color?}>}\n - type:\"docs-browser\" → value: { files: Array<{ path: string; title?: string; content?: string; status?: \"current\" | \"stale\" | \"missing\" }>; title?: string }\n - type:\"text\" → value: string\n - type:\"heading\" → value: string\n - type:\"paragraph\" → value: string\n - type:\"separator\" → value: undefined\n - type:\"actions\" → value: Array<{ type: string; id: string; label: string; variant?: string; options?: Array<string | { label: string; value: string }> }>";
|
|
8
8
|
|
|
9
9
|
export const BLOCK_DOCS_BY_SKILL = {
|
|
10
|
-
"present": "| Type | Description | Value Shape |\n|------|-------------|-------------|\n| `markdown` | Markdown content rendered with the marked parser. | `string` |\n| `code` | Formatted code block rendered inside pre/code tags. | `string` |\n| `mermaid` | Mermaid diagram source rendered in a mermaid pre block. | `string` |\n| `table` | Tabular data rendered from records or explicit headers and rows. | `Record<string, unknown>[] | { headers: string[]; rows: unknown[][] }` |\n| `metrics` | Metric cards showing label/value pairs with optional trend and status. | `Array<{ label: string; value: string | number; trend?: string | number; status?: string }>` |\n| `cards` | Card grid for titled items with optional body, badge, and status. | `Array<{ title: string; body?: string; badge?: string; status?: string; description?: string }>` |\n| `tree` | Hierarchical object or name/children tree rendered recursively. | `{ name: string; children?: unknown[] } | Record<string, unknown>` |\n| `graph` | Node and edge graph rendered as a Mermaid flow graph in HTML mode. | `{ nodes: Array<{ id: string; label?: string }>; edges: Array<{ from: string; to: string; label?: string }> }` |\n| `chart` | Structured chart definition rendered as SVG. | `{ chartType: string; data: Record<string, unknown>[]; xKey: string; yKeys: string[] }` |\n| `timeline` | Timeline entries rendered as a vertical sequence of events. | `Array<{ title: string; description?: string; timestamp?: string; status?: string }>` |\n| `checklist` | Checklist items with boolean checked state. | `Array<{label, checked}> | {items: Array<{label, checked}>}` |\n| `comparison` | Side-by-side comparison columns with titled item lists. | `Array<{title, items}> | {columns: Array<{title, items}>}` |\n| `status-board` | Status categories containing labeled status items. | `Array<{category, items}> | {items: Array<{category, items}>}` |\n| `prompt` | Prompt payload rendered through the prompt display helper. | `unknown` |\n| `progress` | Progress bar with current value and optional maximum. | `{label, value, max?} | {items: Array<{label, value, max?, color?}>}` |\n| `
|
|
11
|
-
"docs": "| Type | Description | Value Shape |\n|------|-------------|-------------|\n| `markdown` | Markdown content rendered with the marked parser. | `string` |\n| `code` | Formatted code block rendered inside pre/code tags. | `string` |\n| `mermaid` | Mermaid diagram source rendered in a mermaid pre block. | `string` |\n| `table` | Tabular data rendered from records or explicit headers and rows. | `Record<string, unknown>[] | { headers: string[]; rows: unknown[][] }` |\n| `cards` | Card grid for titled items with optional body, badge, and status. | `Array<{ title: string; body?: string; badge?: string; status?: string; description?: string }>` |\n| `
|
|
12
|
-
"c4-architecture": "| Type | Description | Value Shape |\n|------|-------------|-------------|\n| `mermaid` | Mermaid diagram source rendered in a mermaid pre block. | `string` |\n| `graph` | Node and edge graph rendered as a Mermaid flow graph in HTML mode. | `{ nodes: Array<{ id: string; label?: string }>; edges: Array<{ from: string; to: string; label?: string }> }`
|
|
10
|
+
"present": "| Type | Description | Value Shape |\n|------|-------------|-------------|\n| `markdown` | Markdown content rendered with the marked parser. | `string` |\n| `code` | Formatted code block rendered inside pre/code tags. | `string` |\n| `mermaid` | Mermaid diagram source rendered in a mermaid pre block. | `string` |\n| `table` | Tabular data rendered from records or explicit headers and rows. | `Record<string, unknown>[] | { headers: string[]; rows: unknown[][] }` |\n| `metrics` | Metric cards showing label/value pairs with optional trend and status. | `Array<{ label: string; value: string | number; trend?: string | number; status?: string }>` |\n| `cards` | Card grid for titled items with optional body, badge, and status. | `Array<{ title: string; body?: string; badge?: string; status?: string; description?: string }>` |\n| `tree` | Hierarchical object or name/children tree rendered recursively. | `{ name: string; children?: unknown[] } | Record<string, unknown>` |\n| `graph` | Node and edge graph rendered as a Mermaid flow graph in HTML mode. | `{ nodes: Array<{ id: string; label?: string }>; edges: Array<{ from: string; to: string; label?: string }> }` |\n| `chart` | Structured chart definition rendered as SVG. | `{ chartType: string; data: Record<string, unknown>[]; xKey: string; yKeys: string[] }` |\n| `timeline` | Timeline entries rendered as a vertical sequence of events. | `Array<{ title: string; description?: string; timestamp?: string; status?: string }>` |\n| `checklist` | Checklist items with boolean checked state. | `Array<{label, checked}> | {items: Array<{label, checked}>}` |\n| `comparison` | Side-by-side comparison columns with titled item lists. | `Array<{title, items}> | {columns: Array<{title, items}>}` |\n| `status-board` | Status categories containing labeled status items. | `Array<{category, items}> | {items: Array<{category, items}>}` |\n| `prompt` | Prompt payload rendered through the prompt display helper. | `unknown` |\n| `progress` | Progress bar with current value and optional maximum. | `{label, value, max?} | {items: Array<{label, value, max?, color?}>}` |\n| `docs-browser` | Documentation file list with inline content previews for chat-safe rendering. | `{ files: Array<{ path: string; title?: string; content?: string; status?: \"current\" | \"stale\" | \"missing\" }>; title?: string }` |\n\n### Usage Examples\n\n#### `docs-browser`\n\n```typescript\n{\n type: 'docs-browser',\n value: {\n title: 'Project Docs',\n files: [\n { path: 'docs/README.md', title: 'Overview', status: 'current' },\n { path: 'docs/api.md', title: 'API Reference', status: 'stale' },\n ],\n },\n}\n```",
|
|
11
|
+
"docs": "| Type | Description | Value Shape |\n|------|-------------|-------------|\n| `markdown` | Markdown content rendered with the marked parser. | `string` |\n| `code` | Formatted code block rendered inside pre/code tags. | `string` |\n| `mermaid` | Mermaid diagram source rendered in a mermaid pre block. | `string` |\n| `table` | Tabular data rendered from records or explicit headers and rows. | `Record<string, unknown>[] | { headers: string[]; rows: unknown[][] }` |\n| `cards` | Card grid for titled items with optional body, badge, and status. | `Array<{ title: string; body?: string; badge?: string; status?: string; description?: string }>` |\n| `docs-browser` | Documentation file list with inline content previews for chat-safe rendering. | `{ files: Array<{ path: string; title?: string; content?: string; status?: \"current\" | \"stale\" | \"missing\" }>; title?: string }` |\n\n### Usage Examples\n\n#### `docs-browser`\n\n```typescript\n{\n type: 'docs-browser',\n value: {\n title: 'Project Docs',\n files: [\n { path: 'docs/README.md', title: 'Overview', status: 'current' },\n { path: 'docs/api.md', title: 'API Reference', status: 'stale' },\n ],\n },\n}\n```",
|
|
12
|
+
"c4-architecture": "| Type | Description | Value Shape |\n|------|-------------|-------------|\n| `mermaid` | Mermaid diagram source rendered in a mermaid pre block. | `string` |\n| `graph` | Node and edge graph rendered as a Mermaid flow graph in HTML mode. | `{ nodes: Array<{ id: string; label?: string }>; edges: Array<{ from: string; to: string; label?: string }> }` |"
|
|
13
13
|
};
|