@vpxa/aikit 0.1.317 → 0.1.318

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.
@@ -2681,7 +2681,8 @@ None.`:`### Stale Lessons\n${u.map(e=>`- **${e.title}** (\`${e.path}\`) — effe
2681
2681
  }
2682
2682
  mermaid.initialize({ startOnLoad: false, theme: theme });
2683
2683
  mermaid.run();
2684
- };`,onload:`window.__aikit_initMermaid&&window.__aikit_initMermaid()`,local:{route:`/vendor/mermaid.min.js`,getSource:_h()}},yh=new Map([[`mermaid`,vh]]);function bh(e,t){if(!e?.length)return;let n=[];for(let r of e){let e=yh.get(r);if(e){if(t===`browser`){n.push({inlineSource:e.inlineSource,onload:e.onload});continue}if(t===`mcp-app`){n.push({inlineSource:e.inlineSource,onload:e.onload});continue}n.push({src:e.cdn,initScript:e.initScript,onload:e.onload})}}return n.length>0?n:void 0}function xh(){let e=[];for(let t of yh.values())t.local&&e.push({route:t.local.route,getSource:t.local.getSource,cdn:t.cdn});return e}const Sh=300*1e3,Ch=15*1e3,wh=`/@aikit/blocks-interactive/dist/`;var Th=class{maxTokens;refillPerSecond;tokens;lastRefill;constructor(e,t){this.maxTokens=e,this.refillPerSecond=t,this.tokens=e,this.lastRefill=Date.now()}tryConsume(){return this.#e(),this.tokens>=1?(--this.tokens,!0):!1}#e(){let e=Date.now(),t=(e-this.lastRefill)/1e3;this.tokens=Math.min(this.maxTokens,this.tokens+t*this.refillPerSecond),this.lastRefill=e}};let Eh=null,Dh=null;const Oh=new Map,kh=new Th(10,10),Ah=new Th(50,50);function jh(){return Eh||(Eh={manager:new hh,server:null,port:0},process.on(`exit`,()=>{Eh?.manager.shutdown()})),Eh.manager}async function Mh(){if(!Eh)throw Error(`Browser server state not initialized`);let e=Eh;if(e.server)return e.port;if(Dh)return Dh;let t=Rr((e,t)=>{Lh(e,t)});return e.server=t,Dh=new Promise((n,r)=>{t.listen(0,`127.0.0.1`,()=>{let i=t.address();typeof i==`object`&&i?(e.port=i.port,n(i.port)):r(Error(`Failed to resolve local browser address`))}),t.on(`error`,r)}),Dh}let Nh;function Ph(){return Nh===void 0&&(Nh=w(`blocks-interactive`)),Nh}function Fh(e){if(!e.startsWith(wh))return null;let t=Ph();if(!t)return null;let n=L(I(t,`dist`,e.slice(32))),r=L(I(t,`dist`)),i=process.platform===`win32`?`\\`:`/`;return!n.startsWith(r+i)&&n!==r?null:n}function Ih(e){return`script-src 'nonce-${e}' 'strict-dynamic'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self'; frame-ancestors 'self'`}function Lh(e,t){let n=Eh;if(!n){qh(t);return}try{let r=new URL(e.url??`/`,`http://${e.headers.host??`127.0.0.1`}`).pathname;if((e.method??`GET`)===`OPTIONS`){t.writeHead(204,{"Access-Control-Allow-Origin":`*`,"Access-Control-Allow-Methods":`POST, GET, OPTIONS`,"Access-Control-Allow-Headers":`Content-Type`}),t.end();return}if(r.startsWith(`/__aikit_screenshot.png`)){let r=e.headers.referer;Yh(t,typeof r==`string`&&r.length>0?r:`http://127.0.0.1:${n.port}`);return}let i=r.match(/^\/present\/([^/]+)(?:\/(.*))?$/);if(i){let r=i[1],a=i[2]??``,o=Oh.get(r);if(!o){Rh(t,404,X.SESSION_NOT_FOUND,`Session ${r} not found`);return}if(o.hasClientConnected=!0,n.manager.transitionSession(r,`connected`,`client-connect`),a===``||a===`/`){t.writeHead(200,{"Content-Type":`text/html; charset=utf-8`,"Content-Security-Policy":Ih(o.callbackSession.nonce)}),t.end(o.html);return}if(a===`viewer`){if(!o.viewerHtml){t.writeHead(404,{"Content-Type":`text/plain`}),t.end(`Not Found`);return}t.writeHead(200,{"Content-Type":`text/html; charset=utf-8`}),t.end(o.viewerHtml);return}if(a===`callback`){if(!kh.tryConsume()){Rh(t,429,X.RATE_LIMITED,`Too many requests`);return}o.callbackSession.handle(e,t,`http://127.0.0.1:${n.port}`).catch(()=>{qh(t)});return}t.writeHead(404,{"Content-Type":`text/plain`}),t.end(`Not Found`);return}let a=xh().find(t=>e.url===t.route);if(a){let e=a.getSource();if(e){t.writeHead(200,{"Content-Type":`application/javascript; charset=utf-8`,"Cache-Control":`public, max-age=86400`}),t.end(e);return}t.writeHead(302,{Location:a.cdn}),t.end();return}if(r.startsWith(wh)){if(!Ah.tryConsume()){Rh(t,429,X.RATE_LIMITED,`Too many requests`);return}let e=Fh(r);if(e)try{let n=F(e,`utf8`);t.writeHead(200,{"Content-Type":`application/javascript; charset=utf-8`}),t.end(n);return}catch{}}t.writeHead(404,{"Content-Type":`text/plain`}),t.end(`Not Found`)}catch{qh(t)}}function Rh(e,t,n,r){if(!e.headersSent)try{e.writeHead(t,{"Content-Type":`application/json; charset=utf-8`}),e.end(JSON.stringify({error:n,message:r}))}catch{try{e.end()}catch{}}}function zh(e){return e.length===0?``:e.map(e=>{let t=Y(e.id),n=Y(e.label);if(e.type===`select`||e.type===`multi-select`)return`<label class="present-action-field"><span>${n}</span><select data-action-id="${t}"${e.type===`multi-select`?` multiple`:``}>${(e.options??[]).map(e=>`<option value="${Y(e.value)}">${Y(e.label)}</option>`).join(``)}</select></label>`;if(e.type===`text-submit`)return`<label class="present-action-field"><span>${n}</span><div class="present-text-submit"><input type="text" class="present-text-input" data-action-id="${t}" data-action-label="${n}" placeholder="${n}" /><button type="button" class="present-action-btn present-action-primary present-submit-btn" data-submit-for="${t}">Send</button></div></label>`;if(e.type===`form-submit`){let r=e.schema;if(r)return`<form class="present-form" data-action-id="${t}" data-action-label="${n}">${Object.entries(r).map(([e,t])=>{let n=Y(t.description??e);return`<label class="present-action-field"><span>${n}</span><input type="${t.type===`number`?`number`:t.type===`boolean`?`checkbox`:`text`}" class="present-text-input" name="${Y(e)}" placeholder="${n}" /></label>`}).join(``)}<button type="submit" class="present-action-btn present-action-primary">${n}</button></form>`}return`<button type="button" class="present-action-btn present-action-${Y(e.variant??`default`)}" data-action-id="${t}" data-action-label="${n}">${n}</button>`}).join(``)}function Bh(e,t){if(e.length===0)return``;let n=JSON.stringify(t);return`<style>
2684
+ };`,onload:`window.__aikit_initMermaid&&window.__aikit_initMermaid()`,local:{route:`/vendor/mermaid.min.js`,getSource:_h()}},yh=new Map([[`mermaid`,vh]]);function bh(e,t){if(!e?.length)return;let n=[];for(let r of e){let e=yh.get(r);if(e){if(t===`browser`){n.push({inlineSource:e.inlineSource,onload:e.onload});continue}if(t===`mcp-app`){n.push({inlineSource:e.inlineSource,onload:e.onload});continue}n.push({src:e.cdn,initScript:e.initScript,onload:e.onload})}}return n.length>0?n:void 0}function xh(){let e=[];for(let t of yh.values())t.local&&e.push({route:t.local.route,getSource:t.local.getSource,cdn:t.cdn});return e}const Sh=300*1e3,Ch=15*1e3,wh=`/@aikit/blocks-interactive/dist/`;var Th=class{maxTokens;refillPerSecond;tokens;lastRefill;constructor(e,t){this.maxTokens=e,this.refillPerSecond=t,this.tokens=e,this.lastRefill=Date.now()}tryConsume(){return this.#e(),this.tokens>=1?(--this.tokens,!0):!1}#e(){let e=Date.now(),t=(e-this.lastRefill)/1e3;this.tokens=Math.min(this.maxTokens,this.tokens+t*this.refillPerSecond),this.lastRefill=e}};let Eh=null,Dh=null;const Oh=new Map,kh=new Th(10,10),Ah=new Th(50,50);function jh(){return Eh||(Eh={manager:new hh,server:null,port:0},process.on(`exit`,()=>{Eh?.manager.shutdown()})),Eh.manager}async function Mh(){if(!Eh)throw Error(`Browser server state not initialized`);let e=Eh;if(e.server)return e.port;if(Dh)return Dh;let t=Rr((e,t)=>{Lh(e,t)});return e.server=t,Dh=new Promise((n,r)=>{t.listen(0,`127.0.0.1`,()=>{let i=t.address();typeof i==`object`&&i?(e.port=i.port,n(i.port)):r(Error(`Failed to resolve local browser address`))}),t.on(`error`,r)}),Dh}let Nh;function Ph(){return Nh===void 0&&(Nh=w(`blocks-interactive`)),Nh}function Fh(e){if(!e.startsWith(wh))return null;let t=Ph();if(!t)return null;let n=L(I(t,`dist`,e.slice(32))),r=L(I(t,`dist`)),i=process.platform===`win32`?`\\`:`/`;return!n.startsWith(r+i)&&n!==r?null:n}function Ih(e){return`script-src 'nonce-${e}' 'strict-dynamic'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self'; frame-ancestors 'self'`}function Lh(e,t){let n=Eh;if(!n){Jh(t);return}try{let r=new URL(e.url??`/`,`http://${e.headers.host??`127.0.0.1`}`).pathname;if((e.method??`GET`)===`OPTIONS`){t.writeHead(204,{"Access-Control-Allow-Origin":`*`,"Access-Control-Allow-Methods":`POST, GET, OPTIONS`,"Access-Control-Allow-Headers":`Content-Type`}),t.end();return}if(r.startsWith(`/__aikit_screenshot.png`)){let r=e.headers.referer;Xh(t,typeof r==`string`&&r.length>0?r:`http://127.0.0.1:${n.port}`);return}let i=r.match(/^\/present\/([^/]+)(?:\/(.*))?$/);if(i){let r=i[1],a=i[2]??``,o=Oh.get(r);if(!o){Rh(t,404,X.SESSION_NOT_FOUND,`Session ${r} not found`);return}if(o.hasClientConnected=!0,n.manager.transitionSession(r,`connected`,`client-connect`),a===``||a===`/`){t.writeHead(200,{"Content-Type":`text/html; charset=utf-8`,"Content-Security-Policy":Ih(o.callbackSession.nonce)}),t.end(o.html);return}if(a===`viewer`){if(!o.viewerHtml){t.writeHead(404,{"Content-Type":`text/plain`}),t.end(`Not Found`);return}t.writeHead(200,{"Content-Type":`text/html; charset=utf-8`}),t.end(o.viewerHtml);return}if(a===`callback`){if(!kh.tryConsume()){Rh(t,429,X.RATE_LIMITED,`Too many requests`);return}o.callbackSession.handle(e,t,`http://127.0.0.1:${n.port}`).catch(()=>{Jh(t)});return}t.writeHead(404,{"Content-Type":`text/plain`}),t.end(`Not Found`);return}let a=xh().find(t=>e.url===t.route);if(a){let e=a.getSource();if(e){t.writeHead(200,{"Content-Type":`application/javascript; charset=utf-8`,"Cache-Control":`public, max-age=86400`}),t.end(e);return}t.writeHead(302,{Location:a.cdn}),t.end();return}if(r.startsWith(wh)){if(!Ah.tryConsume()){Rh(t,429,X.RATE_LIMITED,`Too many requests`);return}let e=Fh(r);if(e)try{let n=F(e,`utf8`);t.writeHead(200,{"Content-Type":`application/javascript; charset=utf-8`}),t.end(n);return}catch{}}t.writeHead(404,{"Content-Type":`text/plain`}),t.end(`Not Found`)}catch{Jh(t)}}function Rh(e,t,n,r){if(!e.headersSent)try{e.writeHead(t,{"Content-Type":`application/json; charset=utf-8`}),e.end(JSON.stringify({error:n,message:r}))}catch{try{e.end()}catch{}}}function zh(e){let t=Y(e.id),n=Y(e.label);if(e.type===`select`||e.type===`multi-select`)return`<label class="present-action-field"><span>${n}</span><select data-action-id="${t}"${e.type===`multi-select`?` multiple`:``}>${(e.options??[]).map(e=>`<option value="${Y(e.value)}">${Y(e.label)}</option>`).join(``)}</select></label>`;if(e.type===`text-submit`)return`<label class="present-action-field"><span>${n}</span><div class="present-text-submit"><input type="text" class="present-text-input" data-action-id="${t}" data-action-label="${n}" placeholder="${n}" /><button type="button" class="present-action-btn present-action-primary present-submit-btn" data-submit-for="${t}">Send</button></div></label>`;if(e.type===`form-submit`){let r=e.schema;if(r)return`<form class="present-form" data-action-id="${t}" data-action-label="${n}">${Object.entries(r).map(([e,t])=>{let n=Y(t.description??e);return`<label class="present-action-field"><span>${n}</span><input type="${t.type===`number`?`number`:t.type===`boolean`?`checkbox`:`text`}" class="present-text-input" name="${Y(e)}" placeholder="${n}" /></label>`}).join(``)}<button type="submit" class="present-action-btn present-action-primary">${n}</button></form>`}return`<button type="button" class="present-action-btn present-action-${Y(e.variant??`default`)}" data-action-id="${t}" data-action-label="${n}">${n}</button>`}function Bh(e){if(e.length===0)return``;let t=e.filter(e=>e.type===`button`||e.type===`select`||e.type===`multi-select`||e.type===`custom`),n=e.filter(e=>e.type===`text-submit`||e.type===`form-submit`),r=[];return t.length>0&&r.push(`<div class="bk-actions">${t.map(zh).join(``)}</div>`),n.length>0&&r.push(n.map(zh).join(``)),r.join(`
2685
+ `)}function Vh(e,t){if(e.length===0)return``;let n=JSON.stringify(t);return`<style>
2685
2686
  .present-surface-title { margin: 0 0 0.75rem; font-size: 1.875rem; }
2686
2687
  .present-surface-description { margin: 0; color: var(--muted-foreground, #6b7280); }
2687
2688
  .present-actions-list { display: flex; flex-wrap: wrap; gap: 0.75rem; align-items: flex-end; }
@@ -2903,8 +2904,8 @@ None.`:`### Stale Lessons\n${u.map(e=>`- **${e.title}** (\`${e.path}\`) — effe
2903
2904
  navigator.sendBeacon('/callback', new Blob([body], { type: 'application/json' }));
2904
2905
  });
2905
2906
  })();
2906
- <\/script>`}function Vh(e){try{if(process.platform===`win32`){Hn(`cmd`,[`/c`,`start`,``,e],{windowsHide:!0});return}if(process.platform===`darwin`){Hn(`open`,[e]);return}Hn(`xdg-open`,[e])}catch{}}async function Hh(e){try{let t=$n();return await t.launch(`ui`),t.resetIdleTimer(),await(await t.getContext().newPage()).goto(e,{waitUntil:`domcontentloaded`}),!0}catch{return Vh(e),!1}}function Uh(e,t,n){let r=[e.title];return e.description&&r.push(e.description),r.push(``,`Opened in browser at ${t}`,n),r.join(`
2907
- `)}function Wh(e){return e.some(e=>e.id!==`__dismiss`)}function Gh(e){return`<script nonce="${Y(e)}">
2907
+ <\/script>`}function Hh(e){try{if(process.platform===`win32`){Hn(`cmd`,[`/c`,`start`,``,e],{windowsHide:!0});return}if(process.platform===`darwin`){Hn(`open`,[e]);return}Hn(`xdg-open`,[e])}catch{}}async function Uh(e){try{let t=$n();return await t.launch(`ui`),t.resetIdleTimer(),await t.open(e),!0}catch{return Hh(e),!1}}function Wh(e,t,n){let r=[e.title];return e.description&&r.push(e.description),r.push(``,`Opened in browser at ${t}`,n),r.join(`
2908
+ `)}function Gh(e){return e.some(e=>e.id!==`__dismiss`)}function Kh(e){return`<script nonce="${Y(e)}">
2908
2909
  (function() {
2909
2910
  const iframe = document.querySelector('.present-viewer-iframe');
2910
2911
  if (!iframe) return;
@@ -2918,7 +2919,7 @@ None.`:`### Stale Lessons\n${u.map(e=>`- **${e.title}** (\`${e.path}\`) — effe
2918
2919
  observer.observe(document.documentElement, { attributes: true, attributeFilter: ['data-theme'] });
2919
2920
  iframe.addEventListener('load', sendTheme);
2920
2921
  })();
2921
- <\/script>`}function Kh(e){return e.replace(`</head>`,`<style>
2922
+ <\/script>`}function qh(e){return e.replace(`</head>`,`<style>
2922
2923
  .toolbar, .badge, body > header, body > footer { display: none !important; }
2923
2924
  body { padding-top: 0 !important; margin-top: 0 !important; }
2924
2925
  </style>
@@ -2929,11 +2930,11 @@ window.addEventListener('message', function(e) {
2929
2930
  }
2930
2931
  });
2931
2932
  <\/script>
2932
- </body>`)}function qh(e){if(!e.headersSent)try{e.writeHead(500,{"Content-Type":`text/plain`}),e.end(`Internal Server Error`)}catch{try{e.end()}catch{}}}async function Jh(e){let t=$n();t.isLaunched()||await t.launch(`headless`),t.resetIdleTimer();let n=await t.getContext().newPage();try{return await n.goto(e,{waitUntil:`domcontentloaded`}),await n.waitForLoadState(`networkidle`,{timeout:2e3}).catch(()=>{}),await n.screenshot({fullPage:!0,type:`png`})}finally{await n.close().catch(()=>{})}}async function Yh(e,t){if(!t){e.writeHead(503,{"Content-Type":`text/plain; charset=utf-8`}),e.end(`Screenshot target is not ready.`);return}try{let n=await Jh(t);e.writeHead(200,{"Content-Type":`image/png`,"Cache-Control":`no-store`}),e.end(n)}catch{qh(e)}}function Xh(e,t){return e.replace(/'\/callback'/g,`'/present/${t}/callback'`).replace(/"\/callback"/g,`"/present/${t}/callback"`)}function Zh(e,t){return e.replace(/src="\/viewer"/g,`src="/present/${t}/viewer"`)}async function Qh(e,t){if(Tg(`<html><body style="font-family:system-ui;padding:2rem;color:#888;text-align:center"><p>Content opened in browser window.</p></body></html>`),e.data!=null&&t.inputSchema){let n=fn({data:e.data,schema:t.inputSchema});if(!n.valid){let e=n.errors.map(e=>` ${e.path}: ${e.message}${e.expected?` (expected: ${e.expected}, got: ${e.received})`:``}`).join(`
2933
- `);return{content:[{type:`text`,text:`[ERROR:VALIDATION] Template "${t.id}" data validation failed:\n${e}\n\nExpected schema: ${JSON.stringify(t.inputSchema,null,2)}`}],structuredContent:{kind:`error`,error:{code:`VIEWER_DATA_INVALID`,message:`Template "${t.id}" data validation failed:\n${e}\n\nExpected schema: ${JSON.stringify(t.inputSchema,null,2)}`}},isError:!0}}}let n=Kh(bm(t.resolveHtml(),e.data??null,t.injectId,t.transformData)),r=jh(),i=Ie(16).toString(`hex`),a=r.createSession({surfaceId:`viewer`,transport:`viewer`,nonce:i});if(!a.ok)return{content:[{type:`text`,text:`${e.title}\n\nUnable to start local browser transport.`}],structuredContent:{kind:`error`,error:{code:`BROWSER_START_FAILED`,message:a.error.message}},isError:!0};let o=a.session.id,s=fh(`viewer`,e.actions??[],r,o,i),c=Zh(kr({title:e.title,subtitle:e.description,html:[`<div class="present-viewer-container">`,` <iframe class="present-viewer-iframe" src="/viewer" sandbox="allow-scripts allow-same-origin"></iframe>`,` ${Gh(i)}`,`</div>`].join(`
2933
+ </body>`)}function Jh(e){if(!e.headersSent)try{e.writeHead(500,{"Content-Type":`text/plain`}),e.end(`Internal Server Error`)}catch{try{e.end()}catch{}}}async function Yh(e){let t=$n();t.isLaunched()||await t.launch(`headless`),t.resetIdleTimer();let n=await t.open(e);try{let{base64:e}=await t.screenshot(n,{fullPage:!0});return Buffer.from(e,`base64`)}finally{await t.tabExec(n,`close`).catch(()=>{})}}async function Xh(e,t){if(!t){e.writeHead(503,{"Content-Type":`text/plain; charset=utf-8`}),e.end(`Screenshot target is not ready.`);return}try{let n=await Yh(t);e.writeHead(200,{"Content-Type":`image/png`,"Cache-Control":`no-store`}),e.end(n)}catch{Jh(e)}}function Zh(e,t){return e.replace(/'\/callback'/g,`'/present/${t}/callback'`).replace(/"\/callback"/g,`"/present/${t}/callback"`)}function Qh(e,t){return e.replace(/src="\/viewer"/g,`src="/present/${t}/viewer"`)}async function $h(e,t){if(Eg(`<html><body style="font-family:system-ui;padding:2rem;color:#888;text-align:center"><p>Content opened in browser window.</p></body></html>`),e.data!=null&&t.inputSchema){let n=fn({data:e.data,schema:t.inputSchema});if(!n.valid){let e=n.errors.map(e=>` ${e.path}: ${e.message}${e.expected?` (expected: ${e.expected}, got: ${e.received})`:``}`).join(`
2934
+ `);return{content:[{type:`text`,text:`[ERROR:VALIDATION] Template "${t.id}" data validation failed:\n${e}\n\nExpected schema: ${JSON.stringify(t.inputSchema,null,2)}`}],structuredContent:{kind:`error`,error:{code:`VIEWER_DATA_INVALID`,message:`Template "${t.id}" data validation failed:\n${e}\n\nExpected schema: ${JSON.stringify(t.inputSchema,null,2)}`}},isError:!0}}}let n=qh(bm(t.resolveHtml(),e.data??null,t.injectId,t.transformData)),r=jh(),i=Ie(16).toString(`hex`),a=r.createSession({surfaceId:`viewer`,transport:`viewer`,nonce:i});if(!a.ok)return{content:[{type:`text`,text:`${e.title}\n\nUnable to start local browser transport.`}],structuredContent:{kind:`error`,error:{code:`BROWSER_START_FAILED`,message:a.error.message}},isError:!0};let o=a.session.id,s=fh(`viewer`,e.actions??[],r,o,i),c=Qh(kr({title:e.title,subtitle:e.description,html:[`<div class="present-viewer-container">`,` <iframe class="present-viewer-iframe" src="/viewer" sandbox="allow-scripts allow-same-origin"></iframe>`,` ${Kh(i)}`,`</div>`].join(`
2934
2935
  `),css:[[`.present-viewer-container {`,` flex: 1;`,` min-height: calc(100vh - 12rem);`,` position: relative;`,` border-radius: 0.75rem;`,` overflow: hidden;`,` border: none;`,`}`,`.present-viewer-iframe {`,` border: none;`,` width: 100%;`,` height: 100%;`,` position: absolute;`,` inset: 0;`,` border-radius: inherit;`,`}`].join(`
2935
- `)],islands:[],payload:void 0,nonce:i,generatedAt:new Date().toISOString(),colorScheme:e.colorScheme,lang:e.lang,dir:e.dir,transport:`browser`,exportPolicy:`local-interactive`,footerContentHtml:ph}),o);Oh.set(o,{callbackSession:s,html:c,viewerHtml:n,hasClientConnected:!1,createdAt:Date.now()});let l=``;try{l=`http://127.0.0.1:${await Mh()}/present/${o}`}catch(t){return Oh.delete(o),r.removeSession(o),{content:[{type:`text`,text:`${e.title}\n\nUnable to start local browser transport.`}],structuredContent:{kind:`error`,error:{code:`BROWSER_START_FAILED`,message:t instanceof Error?t.message:`Unable to start browser transport`}},isError:!0}}return await Hh(l),setTimeout(()=>{Oh.delete(o),r.removeSession(o)},Sh),{content:[{type:`text`,text:Uh(e,l,`Rendered.`)}],structuredContent:{kind:`rendered`,reason:`no-response-required`}}}async function $h(e){Tg(`<html><body style="font-family:system-ui;padding:2rem;color:#888;text-align:center"><p>Content opened in browser window.</p></body></html>`);let t=jh(),n=Ie(16).toString(`hex`),r=Lr(e,{transport:`browser`,registry:Um,blockVendorScripts:qm(),nonce:n}),i=t.createSession({surfaceId:r.surfaceId,transport:`browser`,nonce:n});if(!i.ok)return{content:[{type:`text`,text:`${e.title}\n\nUnable to start local browser transport.`}],structuredContent:{kind:`error`,error:{code:`BROWSER_START_FAILED`,message:i.error.message}},isError:!0};let a=i.session.id,o=fh(r.surfaceId,r.actions,t,a,n),s=bh(r.vendorScripts,`browser`);xh();let c=r.actions.length>0?`<div class="bk-actions">${zh(r.actions)}</div>`:``,l=r.actions.length>0?Bh(r.actions,o.nonce):``,u=Xh(Qg(kr({title:e.title,subtitle:e.description,html:[r.html,c,l].filter(Boolean).join(`
2936
- `),css:r.css,islands:r.islands,payload:r.payload,nonce:r.nonce,generatedAt:new Date().toISOString(),colorScheme:e.colorScheme,lang:e.lang,dir:e.dir,transport:`browser`,exportPolicy:r.exportPolicy,footerContentHtml:ph,headScripts:s}),r.nonce),a);Oh.set(a,{callbackSession:o,html:u,hasClientConnected:!1,createdAt:Date.now()});let d=``;try{d=`http://127.0.0.1:${await Mh()}/present/${a}`;let e=Oh.get(a);e&&e.hasClientConnected}catch(n){return Oh.delete(a),t.removeSession(a),t.shutdown(),{content:[{type:`text`,text:`${e.title}\n\nUnable to start local browser transport.`}],structuredContent:o.settleError(`BROWSER_START_FAILED`,n instanceof Error?n.message:`Unable to start browser transport`),isError:!0}}let f=await Hh(d);if(!Wh(r.actions))return setTimeout(()=>{Oh.delete(a);try{t.removeSession(a)}catch{}},Sh),{content:[{type:`text`,text:Uh(e,d,`Rendered.`)}],structuredContent:{kind:`rendered`,reason:`no-response-required`}};let p=await Promise.race([o.promise,new Promise(e=>{setTimeout(()=>{Oh.get(a)?.hasClientConnected||(Oh.delete(a),e(o.settleError(`BROWSER_CONNECT_TIMEOUT`,f?`No browser client connected within ${Ch}ms.`:`Fell back to system browser, but no browser client connected within ${Ch}ms.`)))},Ch)}),new Promise(e=>{setTimeout(()=>e(o.settleTimeout(Sh)),Sh)})]);setTimeout(()=>{Oh.delete(a);try{t.removeSession(a)}catch{}},Sh);let m=p.kind===`result`?`Selected action: ${p.result.actionId}`:p.kind===`timeout`?`Timed out after ${p.waitedMs}ms.`:p.kind===`cancelled`?`Cancelled: ${p.reason}.`:p.kind===`error`?`Error: ${p.error.message}`:`Rendered.`;return{content:[{type:`text`,text:Uh(e,d,m)}],structuredContent:p,isError:p.kind===`error`}}const eg={id:`browser`,priority:20,canHandle(e,t){let n=Wg(e);return Gm(n)||!!t.preferBrowser&&!!Gg(n)},async render(e,t){return $h(e)}},tg=`openai/outputTemplate`,ng=`ui/resourceUri`,rg={connectDomains:[],resourceDomains:[]},ig={connect_domains:[],resource_domains:[]};function ag(e){return{ui:{resourceUri:e,visibility:[`model`,`app`]},[ng]:e,[tg]:e,"openai/widgetAccessible":!0}}function og(){return{ui:{prefersBorder:!1,csp:rg},"openai/widgetDescription":`AI Kit renders structured visual surfaces such as dashboards, charts, reports, and diagrams.`,"openai/widgetPrefersBorder":!1,"openai/widgetCSP":ig}}function sg(e){return{ui:{resourceUri:e},[ng]:e,[tg]:e}}function cg(e){return{...e,schemaVersion:1}}function lg(e){try{let t=Lr(e,{transport:`mcp-app`,registry:Um,blockVendorScripts:qm()}),n=bh(t.vendorScripts,`mcp-app`),r=kr({title:e.title,subtitle:e.description,html:t.html,css:t.css,islands:t.islands,payload:t.payload,nonce:t.nonce,colorScheme:e.colorScheme,lang:e.lang,dir:e.dir,transport:`mcp-app`,exportPolicy:t.exportPolicy,showToolbox:t.exportPolicy!==`static-only`,showInstallGuide:!1,footerContentHtml:ph,headScripts:n}),i={kind:`rendered`,reason:`no-response-required`},a=Jg(r);Tg(a);let o=Kg(e,i,{includeSurfaceHeader:!1}),s=Cg(),c=Og(s);return c&&Eg(c,a),{content:[{type:`text`,text:o}],structuredContent:cg(e),_meta:sg(s),ui:{type:`resource`,uri:s}}}catch(t){return e_(`RENDER_FAILED`,t instanceof Error?t.message:`Failed to render ChannelSurface`,void 0,e.title)}}const ug={id:`mcp-app`,priority:30,canHandle(e,t){return!0},async render(e,t){return lg(e)}};var dg=class{handlers=[];register(e){let t=this.handlers.findIndex(t=>t.id===e.id);t===-1?this.handlers.push(e):this.handlers[t]=e}unregister(e){let t=this.handlers.findIndex(t=>t.id===e);t!==-1&&this.handlers.splice(t,1)}select(e,t){return[...this.handlers].sort((e,t)=>(e.priority??99)-(t.priority??99)).find(n=>n.canHandle(e,t))??null}getAll(){return[...this.handlers]}};function fg(e){return`<script nonce="${Y(e)}">
2936
+ `)],islands:[],payload:void 0,nonce:i,generatedAt:new Date().toISOString(),colorScheme:e.colorScheme,lang:e.lang,dir:e.dir,transport:`browser`,exportPolicy:`local-interactive`,footerContentHtml:ph}),o);Oh.set(o,{callbackSession:s,html:c,viewerHtml:n,hasClientConnected:!1,createdAt:Date.now()});let l=``;try{l=`http://127.0.0.1:${await Mh()}/present/${o}`}catch(t){return Oh.delete(o),r.removeSession(o),{content:[{type:`text`,text:`${e.title}\n\nUnable to start local browser transport.`}],structuredContent:{kind:`error`,error:{code:`BROWSER_START_FAILED`,message:t instanceof Error?t.message:`Unable to start browser transport`}},isError:!0}}return await Uh(l),setTimeout(()=>{Oh.delete(o),r.removeSession(o)},Sh),{content:[{type:`text`,text:Wh(e,l,`Rendered.`)}],structuredContent:{kind:`rendered`,reason:`no-response-required`}}}async function eg(e){Eg(`<html><body style="font-family:system-ui;padding:2rem;color:#888;text-align:center"><p>Content opened in browser window.</p></body></html>`);let t=jh(),n=Ie(16).toString(`hex`),r=Lr(e,{transport:`browser`,registry:Um,blockVendorScripts:qm(),nonce:n}),i=t.createSession({surfaceId:r.surfaceId,transport:`browser`,nonce:n});if(!i.ok)return{content:[{type:`text`,text:`${e.title}\n\nUnable to start local browser transport.`}],structuredContent:{kind:`error`,error:{code:`BROWSER_START_FAILED`,message:i.error.message}},isError:!0};let a=i.session.id,o=fh(r.surfaceId,r.actions,t,a,n),s=bh(r.vendorScripts,`browser`);xh();let c=r.actions.length>0?Bh(r.actions):``,l=r.actions.length>0?Vh(r.actions,o.nonce):``,u=Zh($g(kr({title:e.title,subtitle:e.description,html:[r.html,c,l].filter(Boolean).join(`
2937
+ `),css:r.css,islands:r.islands,payload:r.payload,nonce:r.nonce,generatedAt:new Date().toISOString(),colorScheme:e.colorScheme,lang:e.lang,dir:e.dir,transport:`browser`,exportPolicy:r.exportPolicy,footerContentHtml:ph,headScripts:s}),r.nonce),a);Oh.set(a,{callbackSession:o,html:u,hasClientConnected:!1,createdAt:Date.now()});let d=``;try{d=`http://127.0.0.1:${await Mh()}/present/${a}`;let e=Oh.get(a);e&&e.hasClientConnected}catch(n){return Oh.delete(a),t.removeSession(a),t.shutdown(),{content:[{type:`text`,text:`${e.title}\n\nUnable to start local browser transport.`}],structuredContent:o.settleError(`BROWSER_START_FAILED`,n instanceof Error?n.message:`Unable to start browser transport`),isError:!0}}let f=await Uh(d);if(!Gh(r.actions))return setTimeout(()=>{Oh.delete(a);try{t.removeSession(a)}catch{}},Sh),{content:[{type:`text`,text:Wh(e,d,`Rendered.`)}],structuredContent:{kind:`rendered`,reason:`no-response-required`}};let p=await Promise.race([o.promise,new Promise(e=>{setTimeout(()=>{Oh.get(a)?.hasClientConnected||(Oh.delete(a),e(o.settleError(`BROWSER_CONNECT_TIMEOUT`,f?`No browser client connected within ${Ch}ms.`:`Fell back to system browser, but no browser client connected within ${Ch}ms.`)))},Ch)}),new Promise(e=>{setTimeout(()=>e(o.settleTimeout(Sh)),Sh)})]);setTimeout(()=>{Oh.delete(a);try{t.removeSession(a)}catch{}},Sh);let m=p.kind===`result`?`Selected action: ${p.result.actionId}`:p.kind===`timeout`?`Timed out after ${p.waitedMs}ms.`:p.kind===`cancelled`?`Cancelled: ${p.reason}.`:p.kind===`error`?`Error: ${p.error.message}`:`Rendered.`;return{content:[{type:`text`,text:Wh(e,d,m)}],structuredContent:p,isError:p.kind===`error`}}const tg={id:`browser`,priority:20,canHandle(e,t){let n=Gg(e);return Gm(n)||!!t.preferBrowser&&!!Kg(n)},async render(e,t){return eg(e)}},ng=`openai/outputTemplate`,rg=`ui/resourceUri`,ig={connectDomains:[],resourceDomains:[]},ag={connect_domains:[],resource_domains:[]};function og(e){return{ui:{resourceUri:e,visibility:[`model`,`app`]},[rg]:e,[ng]:e,"openai/widgetAccessible":!0}}function sg(){return{ui:{prefersBorder:!1,csp:ig},"openai/widgetDescription":`AI Kit renders structured visual surfaces such as dashboards, charts, reports, and diagrams.`,"openai/widgetPrefersBorder":!1,"openai/widgetCSP":ag}}function cg(e){return{ui:{resourceUri:e},[rg]:e,[ng]:e}}function lg(e){return{...e,schemaVersion:1}}function ug(e){try{let t=Lr(e,{transport:`mcp-app`,registry:Um,blockVendorScripts:qm()}),n=bh(t.vendorScripts,`mcp-app`),r=kr({title:e.title,subtitle:e.description,html:t.html,css:t.css,islands:t.islands,payload:t.payload,nonce:t.nonce,colorScheme:e.colorScheme,lang:e.lang,dir:e.dir,transport:`mcp-app`,exportPolicy:t.exportPolicy,showToolbox:t.exportPolicy!==`static-only`,showInstallGuide:!1,footerContentHtml:ph,headScripts:n}),i={kind:`rendered`,reason:`no-response-required`},a=Yg(r);Eg(a);let o=qg(e,i,{includeSurfaceHeader:!1}),s=wg(),c=kg(s);return c&&Dg(c,a),{content:[{type:`text`,text:o}],structuredContent:lg(e),_meta:cg(s),ui:{type:`resource`,uri:s}}}catch(t){return t_(`RENDER_FAILED`,t instanceof Error?t.message:`Failed to render ChannelSurface`,void 0,e.title)}}const dg={id:`mcp-app`,priority:30,canHandle(e,t){return!0},async render(e,t){return ug(e)}};var fg=class{handlers=[];register(e){let t=this.handlers.findIndex(t=>t.id===e.id);t===-1?this.handlers.push(e):this.handlers[t]=e}unregister(e){let t=this.handlers.findIndex(t=>t.id===e);t!==-1&&this.handlers.splice(t,1)}select(e,t){return[...this.handlers].sort((e,t)=>(e.priority??99)-(t.priority??99)).find(n=>n.canHandle(e,t))??null}getAll(){return[...this.handlers]}};function pg(e){return`<script nonce="${Y(e)}">
2937
2938
  (function() {
2938
2939
  const iframe = document.querySelector('.present-viewer-iframe');
2939
2940
  if (!iframe) return;
@@ -2947,23 +2948,23 @@ window.addEventListener('message', function(e) {
2947
2948
  observer.observe(document.documentElement, { attributes: true, attributeFilter: ['data-theme'] });
2948
2949
  iframe.addEventListener('load', sendTheme);
2949
2950
  })();
2950
- <\/script>`}function pg(e){return`<script nonce="${Y(e)}">
2951
+ <\/script>`}function mg(e){return`<script nonce="${Y(e)}">
2951
2952
  window.addEventListener('message', function(e) {
2952
2953
  if (e.data && e.data.type === 'aikit-viewer-height') {
2953
2954
  var container = document.querySelector('.present-viewer-container');
2954
2955
  if (container) { container.style.height = e.data.height + 'px'; }
2955
2956
  }
2956
2957
  });
2957
- <\/script>`}async function mg(e,t){try{let n=qg(bm(t.resolveHtml(),e.data??null,t.injectId,t.transformData)).replace(/&/g,`&amp;`).replace(/"/g,`&quot;`),r=Ie(16).toString(`hex`),i={kind:`rendered`,reason:`no-response-required`};Tg(Jg(kr({title:e.title,subtitle:e.description,html:[`<div class="present-viewer-container">`,` <iframe class="present-viewer-iframe" srcdoc="${n}" sandbox="allow-scripts allow-same-origin"></iframe>`,` ${fg(r)}`,` ${pg(r)}`,`</div>`].join(`
2958
+ <\/script>`}async function hg(e,t){try{let n=Jg(bm(t.resolveHtml(),e.data??null,t.injectId,t.transformData)).replace(/&/g,`&amp;`).replace(/"/g,`&quot;`),r=Ie(16).toString(`hex`),i={kind:`rendered`,reason:`no-response-required`};Eg(Yg(kr({title:e.title,subtitle:e.description,html:[`<div class="present-viewer-container">`,` <iframe class="present-viewer-iframe" srcdoc="${n}" sandbox="allow-scripts allow-same-origin"></iframe>`,` ${pg(r)}`,` ${mg(r)}`,`</div>`].join(`
2958
2959
  `),css:[[`.present-viewer-container {`,` flex: 1;`,` min-height: 640px;`,` position: relative;`,` border-radius: 0.75rem;`,` overflow: hidden;`,` border: none;`,`}`,`.present-viewer-iframe {`,` border: none;`,` width: 100%;`,` height: 100%;`,` position: absolute;`,` inset: 0;`,` border-radius: inherit;`,`}`].join(`
2959
- `)],islands:[],payload:void 0,nonce:r,generatedAt:new Date().toISOString(),footerContentHtml:ph,colorScheme:e.colorScheme,lang:e.lang,dir:e.dir,transport:`mcp-app`,exportPolicy:`local-interactive`})));let a=Kg(e,i,{includeSurfaceHeader:!1}),o=Cg();return{content:[{type:`text`,text:a}],structuredContent:cg(e),_meta:sg(o),ui:{type:`resource`,uri:o}}}catch(t){return e_(`VIEWER_RENDER_FAILED`,t instanceof Error?t.message:`Failed to render viewer template`,void 0,e.title)}}const hg={id:`viewer`,priority:10,canHandle(e,t){return e.template?_m(e.template)!=null:!1},async render(e,t){let n=_m(e.template??``);if(!n)return e_(`VIEWER_NOT_FOUND`,`Viewer template "${e.template}" not found`,void 0,e.title);if(e.data!=null&&n.inputSchema){let t=fn({data:e.data,schema:n.inputSchema});if(!t.valid){let r=t.errors.map(e=>` ${e.path}: ${e.message}${e.expected?` (expected: ${e.expected}, got: ${e.received})`:``}`).join(`
2960
- `);return e_(`VIEWER_DATA_INVALID`,`Template "${n.id}" data validation failed:\n${r}\n\nExpected schema: ${JSON.stringify(n.inputSchema,null,2)}`,void 0,e.title)}}let r=n.supportedTransports.includes(`browser`),i=n.supportedTransports.includes(`mcp-app`);return t.preferBrowser&&r||r&&!i?await Qh(e,n):i?mg(e,n):e_(`VIEWER_TRANSPORT_UNSUPPORTED`,`Viewer template "${n.id}" does not support an available transport`,void 0,e.title)}},gg=`ui://aikit/present.html`,_g=`ui://aikit/present/{id}.html`,vg=M(`present`);let yg=0,bg=``;const xg=new Map,Sg=new Map;function Cg(){return`ui://aikit/present/${`${Date.now().toString(36)}_${(++yg).toString(36)}`}.html`}function wg(){return bg}function Tg(e){bg=e}function Eg(e,t){let n=Sg.get(e);n&&clearTimeout(n),xg.set(e,t),Sg.set(e,setTimeout(()=>{xg.delete(e),Sg.delete(e)},3e4))}function Dg(e){return xg.get(e)}function Og(e){return e.match(/\/present\/(.+)\.html$/)?.[1]}const kg=new dg;kg.register(hg),kg.register(eg),kg.register(ug);function Ag(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const jg=/\\u[0-9a-fA-F]{4}/,Mg=/^\s*\|(?:[^|\r\n]+\|){2,}\s*$/,Ng=/^\s*\|?(?:\s*:?-{3,}:?\s*\|){2,}\s*$/,Pg=/\b(cli|terminal|tty|console|command(?:-|\s)?line)\b/i;function Fg(e){let t=[e.value,e.markdown,e.text,e.content];for(let e of t)if(typeof e==`string`&&e.trim().length>0)return e}function Ig(e){let t=e.split(/\r?\n/);for(let e=0;e<t.length-1;e+=1)if(Mg.test(t[e])&&Ng.test(t[e+1]))return!0;return!1}function Lg(e){let t=e.trim().split(`|`),n=+(t[0]?.trim()===``),r=t.at(-1)?.trim()===``?t.length-1:t.length;return t.slice(n,r).map(e=>e.trim())}function Rg(e,t){if(t<2)return!1;let n=e.trim();return n.startsWith(`|`)?Lg(n).length===t:!1}function zg(e){let t=e.split(/\r?\n/),n=[],r=[],i=()=>{r.length!==0&&(n.push({type:`text`,content:r.join(`
2961
- `)}),r.length=0)},a=0;for(;a<t.length;){let e=t[a],o=t[a+1];if(o!==void 0&&Mg.test(e)&&Ng.test(o)){let r=Lg(e),o=[];i();let s=a+2;for(;s<t.length&&Rg(t[s],r.length);)o.push(Lg(t[s])),s+=1;n.push({type:`table`,headers:r,rows:o}),a=s;continue}r.push(e),a+=1}return i(),n}function Bg(e){let t=Fg(e);return!t||!Ig(t)?[e]:zg(t).flatMap(e=>{if(e.type===`text`){let t=e.content.trim();return t.length>0?[{type:`markdown`,value:t}]:[]}return[{type:`table`,value:{headers:e.headers,rows:e.rows}}]})}function Vg(e){if(typeof e==`string`)return Pg.test(e);if(Array.isArray(e))return e.some(e=>Vg(e));if(!Ag(e))return!1;let t=[`client`,`clientInfo`,`host`,`source`,`mode`,`name`,`title`,`channel`];return Object.entries(e).some(([e,n])=>t.includes(e)?Vg(n):!1)}function Hg(e,t){return{preferBrowser:[t,e._meta,Ag(e.metadata)?e.metadata.source:void 0].some(e=>Vg(e))}}const Ug={id:`__dismiss`,type:`button`,label:`Done`,variant:`default`};function Wg(e){if((e.actions?.length??0)>0||!e.template)return e;let t=Wm(e);return t?.supportedTransports.includes(`browser`)===!0&&!t.supportedTransports.includes(`mcp-app`)?{...e,actions:[Ug]}:e}function Gg(e){if(!e.template)return!0;let t=_m(e.template);return t?t.supportedTransports.includes(`browser`):Wm(e)?.supportedTransports.includes(`browser`)??!1}function Kg(e,t,n={}){let r=n.includeSurfaceHeader??!0,i=r?[e.title]:[];return r&&e.description&&i.push(e.description),Pr(t)?i.push(``,`Selected action: ${t.result.actionId}`):Nr(t)?i.push(``,`Error: ${t.error.message}`):t.kind===`timeout`?i.push(``,`Timed out after ${t.waitedMs}ms.`):t.kind===`cancelled`?i.push(``,`Cancelled: ${t.reason}.`):r||i.push(`Rendered inline.`),i.join(`
2962
- `)}function qg(e){let t=e.replace(`</head>`,`<style>
2960
+ `)],islands:[],payload:void 0,nonce:r,generatedAt:new Date().toISOString(),footerContentHtml:ph,colorScheme:e.colorScheme,lang:e.lang,dir:e.dir,transport:`mcp-app`,exportPolicy:`local-interactive`})));let a=qg(e,i,{includeSurfaceHeader:!1}),o=wg();return{content:[{type:`text`,text:a}],structuredContent:lg(e),_meta:cg(o),ui:{type:`resource`,uri:o}}}catch(t){return t_(`VIEWER_RENDER_FAILED`,t instanceof Error?t.message:`Failed to render viewer template`,void 0,e.title)}}const gg={id:`viewer`,priority:10,canHandle(e,t){return e.template?_m(e.template)!=null:!1},async render(e,t){let n=_m(e.template??``);if(!n)return t_(`VIEWER_NOT_FOUND`,`Viewer template "${e.template}" not found`,void 0,e.title);if(e.data!=null&&n.inputSchema){let t=fn({data:e.data,schema:n.inputSchema});if(!t.valid){let r=t.errors.map(e=>` ${e.path}: ${e.message}${e.expected?` (expected: ${e.expected}, got: ${e.received})`:``}`).join(`
2961
+ `);return t_(`VIEWER_DATA_INVALID`,`Template "${n.id}" data validation failed:\n${r}\n\nExpected schema: ${JSON.stringify(n.inputSchema,null,2)}`,void 0,e.title)}}let r=n.supportedTransports.includes(`browser`),i=n.supportedTransports.includes(`mcp-app`);return t.preferBrowser&&r||r&&!i?await $h(e,n):i?hg(e,n):t_(`VIEWER_TRANSPORT_UNSUPPORTED`,`Viewer template "${n.id}" does not support an available transport`,void 0,e.title)}},_g=`ui://aikit/present.html`,vg=`ui://aikit/present/{id}.html`,yg=M(`present`);let bg=0,xg=``;const Sg=new Map,Cg=new Map;function wg(){return`ui://aikit/present/${`${Date.now().toString(36)}_${(++bg).toString(36)}`}.html`}function Tg(){return xg}function Eg(e){xg=e}function Dg(e,t){let n=Cg.get(e);n&&clearTimeout(n),Sg.set(e,t),Cg.set(e,setTimeout(()=>{Sg.delete(e),Cg.delete(e)},3e4))}function Og(e){return Sg.get(e)}function kg(e){return e.match(/\/present\/(.+)\.html$/)?.[1]}const Ag=new fg;Ag.register(gg),Ag.register(tg),Ag.register(dg);function jg(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const Mg=/\\u[0-9a-fA-F]{4}/,Ng=/^\s*\|(?:[^|\r\n]+\|){2,}\s*$/,Pg=/^\s*\|?(?:\s*:?-{3,}:?\s*\|){2,}\s*$/,Fg=/\b(cli|terminal|tty|console|command(?:-|\s)?line)\b/i;function Ig(e){let t=[e.value,e.markdown,e.text,e.content];for(let e of t)if(typeof e==`string`&&e.trim().length>0)return e}function Lg(e){let t=e.split(/\r?\n/);for(let e=0;e<t.length-1;e+=1)if(Ng.test(t[e])&&Pg.test(t[e+1]))return!0;return!1}function Rg(e){let t=e.trim().split(`|`),n=+(t[0]?.trim()===``),r=t.at(-1)?.trim()===``?t.length-1:t.length;return t.slice(n,r).map(e=>e.trim())}function zg(e,t){if(t<2)return!1;let n=e.trim();return n.startsWith(`|`)?Rg(n).length===t:!1}function Bg(e){let t=e.split(/\r?\n/),n=[],r=[],i=()=>{r.length!==0&&(n.push({type:`text`,content:r.join(`
2962
+ `)}),r.length=0)},a=0;for(;a<t.length;){let e=t[a],o=t[a+1];if(o!==void 0&&Ng.test(e)&&Pg.test(o)){let r=Rg(e),o=[];i();let s=a+2;for(;s<t.length&&zg(t[s],r.length);)o.push(Rg(t[s])),s+=1;n.push({type:`table`,headers:r,rows:o}),a=s;continue}r.push(e),a+=1}return i(),n}function Vg(e){let t=Ig(e);return!t||!Lg(t)?[e]:Bg(t).flatMap(e=>{if(e.type===`text`){let t=e.content.trim();return t.length>0?[{type:`markdown`,value:t}]:[]}return[{type:`table`,value:{headers:e.headers,rows:e.rows}}]})}function Hg(e){if(typeof e==`string`)return Fg.test(e);if(Array.isArray(e))return e.some(e=>Hg(e));if(!jg(e))return!1;let t=[`client`,`clientInfo`,`host`,`source`,`mode`,`name`,`title`,`channel`];return Object.entries(e).some(([e,n])=>t.includes(e)?Hg(n):!1)}function Ug(e,t){return{preferBrowser:[t,e._meta,jg(e.metadata)?e.metadata.source:void 0].some(e=>Hg(e))}}const Wg={id:`__dismiss`,type:`button`,label:`Done`,variant:`default`};function Gg(e){if((e.actions?.length??0)>0||!e.template)return e;let t=Wm(e);return t?.supportedTransports.includes(`browser`)===!0&&!t.supportedTransports.includes(`mcp-app`)?{...e,actions:[Wg]}:e}function Kg(e){if(!e.template)return!0;let t=_m(e.template);return t?t.supportedTransports.includes(`browser`):Wm(e)?.supportedTransports.includes(`browser`)??!1}function qg(e,t,n={}){let r=n.includeSurfaceHeader??!0,i=r?[e.title]:[];return r&&e.description&&i.push(e.description),Pr(t)?i.push(``,`Selected action: ${t.result.actionId}`):Nr(t)?i.push(``,`Error: ${t.error.message}`):t.kind===`timeout`?i.push(``,`Timed out after ${t.waitedMs}ms.`):t.kind===`cancelled`?i.push(``,`Cancelled: ${t.reason}.`):r||i.push(`Rendered inline.`),i.join(`
2963
+ `)}function Jg(e){let t=e.replace(`</head>`,`<style>
2963
2964
  .toolbar, .badge, body > header, body > footer { display: none !important; }
2964
2965
  body { padding-top: 0 !important; margin-top: 0 !important; }
2965
2966
  </style>
2966
- </head>`);t===e&&vg.warn(`injectEmbeddedViewerRuntime: </head> not found — viewer style not injected`);let n=t.replace(`</body>`,`<script>
2967
+ </head>`);t===e&&yg.warn(`injectEmbeddedViewerRuntime: </head> not found — viewer style not injected`);let n=t.replace(`</body>`,`<script>
2967
2968
  (function() {
2968
2969
  function report() {
2969
2970
  var h = document.documentElement.scrollHeight;
@@ -2982,7 +2983,7 @@ window.addEventListener('message', function(e) {
2982
2983
  }
2983
2984
  });
2984
2985
  <\/script>
2985
- </body>`);return n===t&&vg.warn(`injectEmbeddedViewerRuntime: </body> not found — runtime scripts not injected`),n}function Jg(e){let t=`<script>
2986
+ </body>`);return n===t&&yg.warn(`injectEmbeddedViewerRuntime: </body> not found — runtime scripts not injected`),n}function Yg(e){let t=`<script>
2986
2987
  (function(){
2987
2988
  var last=0;
2988
2989
  function notify(){
@@ -2993,7 +2994,7 @@ window.addEventListener('message', function(e) {
2993
2994
  if(typeof ResizeObserver!=="undefined"){new ResizeObserver(notify).observe(document.documentElement)}
2994
2995
  else{setInterval(notify,500)}
2995
2996
  })();
2996
- <\/script>`;return e.includes(`</body>`)?e.replace(`</body>`,`${t}</body>`):`${e}${t}`}let Yg=``;function Xg(e){return`<script${e?` nonce="${Y(e)}"`:``}>
2997
+ <\/script>`;return e.includes(`</body>`)?e.replace(`</body>`,`${t}</body>`):`${e}${t}`}let Xg=``;function Zg(e){return`<script${e?` nonce="${Y(e)}"`:``}>
2997
2998
  (function(){
2998
2999
  var readyState = document.readyState;
2999
3000
  var boot = function() {
@@ -3006,12 +3007,12 @@ window.addEventListener('message', function(e) {
3006
3007
  boot();
3007
3008
  }
3008
3009
  })();
3009
- <\/script>`}function Zg(e){Yg=e||``}function Qg(e,t){if(!Yg)return e;let n=`${`<script${t?` nonce="${Y(t)}"`:``}>${Yg}<\/script>`}\n${Xg(t||``)}`;return e.includes(`</body>`)?e.replace(`</body>`,`${n}\n</body>`):`${e}${n}`}function $g(e,t){return[`<!DOCTYPE html>`,`<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">`,`<title>Error — ${Y(e)}</title>`,`<style>`,` * { box-sizing: border-box; margin: 0; padding: 0; }`,` body { font-family: system-ui, -apple-system, sans-serif; min-height: 100vh; display: flex; align-items: center; justify-content: center; padding: 2rem; background: #fafafa; color: #333; }`,` .error-card { max-width: 560px; width: 100%; padding: 2.5rem; border-radius: 1rem; background: #fff; border: 1px solid #e5e7eb; box-shadow: 0 1px 3px rgba(0,0,0,0.06); }`,` .error-badge { display: inline-block; font-size: 0.75rem; font-weight: 600; text-transform: uppercase; letter-spacing: 0.05em; color: #dc2626; background: #fef2f2; border: 1px solid #fecaca; border-radius: 0.375rem; padding: 0.25rem 0.625rem; margin-bottom: 1rem; }`,` .error-title { font-size: 1.25rem; font-weight: 600; margin-bottom: 0.75rem; color: #111; }`,` .error-message { font-size: 0.875rem; line-height: 1.6; color: #6b7280; white-space: pre-wrap; word-break: break-word; }`,`</style></head><body>`,`<div class="error-card">`,` <span class="error-badge">Render Error</span>`,` <h1 class="error-title">${Y(e)}</h1>`,` <p class="error-message">${Y(t)}</p>`,`</div>`,`</body></html>`].join(`
3010
- `)}function e_(e,t,n,r){return Tg($g(r??`Present`,t)),{content:[{type:`text`,text:`[ERROR:VALIDATION] ${t}`}],isError:!0}}function t_(e,t){if(!Ag(e)||!(`schemaVersion`in e))return{ok:!1,response:e_(`INVALID_CHANNEL_SURFACE`,`present expects a ChannelSurface object with schemaVersion: 1`)};if(e.schemaVersion!==1)return{ok:!1,response:e_(`UNSUPPORTED_SCHEMA_VERSION`,`Unsupported ChannelSurface schemaVersion: ${String(e.schemaVersion)}`)};if(typeof e.title==`string`&&jg.test(e.title))return{ok:!1,response:e_(`TITLE_UNICODE_ESCAPE_NOT_ALLOWED`,`Use actual Unicode characters in title, not escape sequences.`)};let n=Array.isArray(e.blocks)?{...e,blocks:e.blocks.flatMap(e=>{if(!Ag(e)||e.type!==`markdown`)return[e];let t=Fg(e);return!t||!Ig(t)?[e]:Bg(e)})}:e;return{ok:!0,surface:n,options:Hg(n,t)}}const n_={id:`__feedback`,type:`text-submit`,label:`💬 Feedback`,variant:`default`};function r_(e){return!e.actions||e.actions.length===0||e.actions.some(e=>e.id===`__feedback`)?e:{...e,actions:[...e.actions,n_]}}function i_(e){return(e.actions?.length??0)>0||e.response?.required===!0?kg.getAll().some(e=>e.id===`browser`):!1}async function a_(e,t={}){let n=i_(e)?{...t,preferBrowser:!0}:t,r=Wg(e),i=kg.select(r,n),a=i?.id===`browser`?r_(r):r,o;if(o=i?await i.render(a,n):lg(a),t.compact){let{structuredContent:e,...t}=o;return t}return o}function Z(e,t=``){return typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`?String(e):t}function o_(e){return{type:`kv`,value:e}}function s_(e){if(Array.isArray(e))return e}const c_=[{name:`summary`,description:`Title + markdown summary + optional metrics (pass/fail counts)`,expand(e){let t=Z(e.title,`Summary`),n=[{type:`heading`,value:t}],r=Z(e.summary);r&&n.push({type:`markdown`,value:r});let i=Number(e.passed)||0,a=Number(e.failed)||0;if(i>0||a>0){let e=[];i>0&&e.push({label:`Passed`,value:i,status:`success`}),a>0&&e.push({label:`Failed`,value:a,status:`error`}),n.push({type:`metrics`,value:e})}return{title:t,blocks:n}}},{name:`plan`,description:`Title + heading per step + checklist items`,expand(e){let t=Z(e.title,`Plan`),n=[{type:`heading`,value:t}],r=s_(e.steps);return r&&n.push({type:`checklist`,value:{items:r}}),{title:t,blocks:n}}},{name:`understanding`,description:`Title + markdown explanation + kv pairs`,expand(e){let t=Z(e.title,`Understanding`),n=[{type:`heading`,value:t}],r=Z(e.explanation);return r&&n.push({type:`markdown`,value:r}),e.details&&typeof e.details==`object`&&!Array.isArray(e.details)&&n.push(o_(e.details)),{title:t,blocks:n}}},{name:`bug-analyze`,description:`Title + heading + severity/status kv + code block + markdown`,expand(e){let t=Z(e.title,`Bug Analysis`),n=[{type:`heading`,value:t}],r={};e.severity&&(r.Severity=e.severity),e.status&&(r.Status=e.status),Object.keys(r).length>0&&n.push({type:`kv`,value:r});let i=Z(e.code);i&&n.push({type:`code`,value:i});let a=Z(e.analysis);return a&&n.push({type:`markdown`,value:a}),{title:t,blocks:n}}},{name:`task-done`,description:`Title + checklist of completed items + optional metrics`,expand(e){let t=Z(e.title,`Task Complete`),n=[{type:`heading`,value:t}],r=s_(e.items);r&&n.push({type:`checklist`,value:{items:r}});let i=e.completed,a=e.total;if(i!==void 0||a!==void 0){let e=[];i!==void 0&&e.push({label:`Completed`,value:Number(i)||i,status:`success`}),a!==void 0&&e.push({label:`Total`,value:Number(a)||a}),n.push({type:`metrics`,value:e})}return{title:t,blocks:n}}},{name:`review`,description:`Title + criteria checklist + annotation items + approval controls`,expand(e){let t=Z(e.title,`Review`),n=[{type:`heading`,value:t}],r=s_(e.criteria);r&&n.push({type:`checklist`,value:{items:r}});let i=e.annotations;Array.isArray(i)&&i.length>0&&n.push({type:`annotation`,value:i});let a=e.approval;return a&&typeof a==`object`?n.push({type:`approval`,value:a}):n.push({type:`actions`,value:[{type:`button`,id:`approve`,label:`Approve`,variant:`primary`},{type:`button`,id:`reject`,label:`Reject`,variant:`danger`}]}),{title:t,blocks:n}}},{name:`explore`,description:`Title + heading per finding + code blocks`,expand(e){let t=Z(e.title,`Exploration`),n=[{type:`heading`,value:t}],r=s_(e.findings);if(r)for(let e of r)n.push({type:`heading`,value:Z(e.heading,`Finding`)}),e.code&&n.push({type:`code`,value:e.code});return{title:t,blocks:n}}},{name:`decision`,description:`Title + kv for recommendation + comparison blocks per option`,expand(e){let t=Z(e.title,`Decision`),n=[{type:`heading`,value:t}];e.recommendation&&n.push({type:`kv`,value:{Recommendation:e.recommendation}});let r=s_(e.options);return r&&r.length>0&&n.push({type:`comparison`,value:r.map(e=>({title:Z(e.title,`Option`),items:Array.isArray(e.items)?e.items:[]}))}),{title:t,blocks:n}}}],l_=new Map;for(let e of c_)l_.set(e.name,e);function u_(e,t){let n=l_.get(e);return n?n.expand(t):null}const d_={h:`heading`,m:`markdown`,t:`table`,p:`paragraph`,c:`code`,s:`separator`,M:`metrics`,C:`chart`,T:`timeline`,g:`graph`,tr:`tree`,tl:`timeline`,cl:`checklist`,pr:`progress`,sb:`status-board`,kv:`kv`,ac:`actions`,di:`mermaid`},f_=/^(#{1,6})\s/,p_=/^(`{3,}|~{3,})/,m_=/^\|.+\|.+\|/m;function h_(e){let t=e.trim(),n=t.match(f_);if(n)return{type:`heading`,value:t.slice(n[0].length)};if(p_.test(t)){let e=t.indexOf(`
3011
- `),n=t.lastIndexOf(t[0]);return{type:`code`,value:e>=0?t.slice(e+1,n).trimEnd():t}}return m_.test(t)?{type:`table`,value:t}:{type:`markdown`,value:t}}function g_(e,t){let n=d_[e];if(!n)return null;switch(e){case`M`:return{type:`metrics`,value:t};case`C`:return{type:`chart`,value:t};case`T`:case`tl`:return{type:`timeline`,value:t};case`g`:return{type:`graph`,value:t};case`tr`:return{type:`tree`,value:t};case`cl`:return{type:`checklist`,value:t};case`pr`:return{type:`progress`,value:t};case`sb`:return{type:`status-board`,value:t};case`kv`:return{type:`kv`,value:t};case`ac`:return{type:`actions`,value:t};case`di`:return{type:`mermaid`,value:t};case`s`:return{type:`separator`,value:t||!0};default:return{type:n,value:typeof t==`string`?t:String(t??``)}}}function __(e){if(typeof e==`string`){let t=h_(e);return{type:t.type,value:t.value}}if(Array.isArray(e)){let[t,n]=e;if(typeof t==`string`){let e=g_(t,n);if(e)return e}return{type:`markdown`,value:String(t??``)}}if(typeof e==`object`&&e){let{blockId:t,...n}=e;return n}return{type:`markdown`,value:String(e??``)}}function v_(e){return{title:e.title??``,blocks:Array.isArray(e.blocks)?e.blocks.map(__):[]}}function y_(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function b_(e){return y_(e)&&typeof e.schemaVersion==`number`&&e.schemaVersion===1}function x_(e){return y_(e)&&typeof e.schemaVersion==`number`&&e.schemaVersion!==1}function S_(e){return e.schemaVersion===1?typeof e.title!=`string`||e.title.length===0?{ok:!1,error:{code:`MISSING_TITLE`,reason:`ChannelSurface requires a non-empty title`}}:e.blocks!==void 0&&!Array.isArray(e.blocks)?{ok:!1,error:{code:`INVALID_BLOCKS`,reason:`blocks must be an array of TypedBlock objects`}}:{ok:!0,surface:e}:{ok:!1,error:{code:`UNSUPPORTED_SCHEMA_VERSION`,reason:`Unsupported schemaVersion: ${String(e.schemaVersion)}`}}}function C_(e){try{let t=re(e);return y_(t)?(t.schemaVersion===void 0&&(t.schemaVersion=1),w_(t)):{ok:!1,error:{code:`INVALID_RAW_INPUT`,reason:`raw field must contain a JSON object (ChannelSurface)`}}}catch(e){return{ok:!1,error:{code:`INVALID_RAW_JSON`,reason:`Failed to parse raw field: ${e.message}`,hint:`JSON repair attempted. Ensure the raw string contains a valid ChannelSurface object. Common LLM errors (newlines in strings, trailing commas) are auto-repaired.`}}}}function w_(e){if(Array.isArray(e)){if(e.length!==2)return{ok:!1,error:{code:`INVALID_PRESET_INPUT`,reason:`Preset input must be a [name, data] tuple`,hint:`Use [presetName, { title, ...fields }]`}};let[t,n]=e;if(typeof t!=`string`)return{ok:!1,error:{code:`INVALID_PRESET_INPUT`,reason:`Preset name must be a string`}};if(!y_(n))return{ok:!1,error:{code:`INVALID_PRESET_INPUT`,reason:`Preset data must be an object`}};let r=u_(t,n);return r?{ok:!0,surface:{schemaVersion:1,title:r.title,blocks:r.blocks}}:{ok:!1,error:{code:`UNKNOWN_PRESET`,reason:`Unknown preset: ${t}`,hint:`Available presets: summary, plan, understanding, bug-analyze, task-done, review, explore, decision`}}}if(x_(e))return{ok:!1,error:{code:`UNSUPPORTED_SCHEMA_VERSION`,reason:`Unsupported schemaVersion: ${String(e.schemaVersion)}`,hint:`Use schemaVersion: 1`}};if(b_(e))return S_(e);if(typeof e==`string`){let t=v_({blocks:[e]});return{ok:!0,surface:{schemaVersion:1,title:t.title||`Present`,blocks:t.blocks}}}if(y_(e)){if(typeof e.raw==`string`)return C_(e.raw);if(!(`blocks`in e)&&!(`title`in e))return{ok:!1,error:{code:`INVALID_INPUT`,reason:`Expected a ChannelSurface object, preset tuple, or shorthand input`}};let t=v_(e);return{ok:!0,surface:{schemaVersion:1,title:t.title||`Present`,blocks:t.blocks}}}return{ok:!1,error:{code:`INVALID_INPUT`,reason:`Expected a ChannelSurface object, preset tuple, or shorthand input`}}}const T_=R.object({label:R.string(),value:R.string(),description:R.string().optional()}),E_=R.object({id:R.string().describe(`Unique action identifier`),type:R.enum([`button`,`select`,`multi-select`,`form-submit`,`text-submit`,`confirm`,`custom`]).describe(`Interactive action type`),label:R.string().describe(`Visible action label`),variant:R.enum([`primary`,`danger`,`default`]).optional(),options:R.array(T_).optional(),schema:R.record(R.string(),R.unknown()).optional()}),D_=R.object({type:R.string(),title:R.string().optional(),value:R.unknown().optional(),language:R.string().optional()}).catchall(R.unknown()),O_={schemaVersion:R.literal(1).describe(`ChannelSurface schema version. Must be 1.`),title:R.string().describe(`Surface title shown to the user.`),description:R.string().optional().describe(`Optional supporting copy for the surface.`),template:R.string().optional().describe(`Optional template id such as report@1.`),layout:R.object({maxWidth:R.string().optional(),padding:R.string().optional(),columns:R.number().optional()}).optional(),blocks:R.array(D_).optional().describe(`Typed block content for the surface.`),data:R.unknown().optional().describe(`Template data payload, if the template expands data.`),actions:R.array(E_).optional().describe(`Interactive actions. Presence triggers browser transport.`),response:R.object({timeout:R.number().optional(),required:R.boolean().optional()}).optional(),metadata:R.object({surfaceId:R.string().optional(),createdAt:R.string().optional(),source:R.string().optional()}).optional(),colorScheme:R.enum([`light`,`dark`,`auto`]).optional(),lang:R.string().optional(),dir:R.enum([`ltr`,`rtl`,`auto`]).optional(),raw:R.string().optional().describe(`Raw JSON string with auto-repair. Accepts common LLM JSON errors (unescaped newlines in strings, trailing commas). Use for complex payloads with mermaid/code/markdown blocks.`)};R.object({surfaceId:R.string(),actionId:R.string(),actionType:R.enum([`button`,`select`,`multi-select`,`form-submit`,`text-submit`,`confirm`,`custom`]),value:R.unknown().optional(),formData:R.record(R.string(),R.unknown()).optional(),selection:R.union([R.string(),R.array(R.string())]).optional(),label:R.string().optional(),timestamp:R.string(),sourceTransport:R.enum([`mcp-app`,`browser`,`export`])});function k_(e){let t=e.server?.getClientCapabilities?.();if(!t)return`unknown`;let n=yr(t);return!n||Array.isArray(n.mimeTypes)&&n.mimeTypes.length>0&&!n.mimeTypes.includes(vr)?`unsupported`:`supported`}const A_=[{name:`summary`,description:`Title + markdown summary + optional metrics (pass/fail counts)`,inputSchema:{type:`object`,properties:{title:{type:`string`,description:`Section heading`},summary:{type:`string`,description:`Free-form markdown summary`},passed:{type:`number`,description:`Pass count for metrics`},failed:{type:`number`,description:`Fail count for metrics`}},required:[`title`]},example:JSON.stringify({title:`Build Summary`,summary:`All tests passed.`,passed:42,failed:0}),expandsTo:`blocks: [heading, markdown, metrics]`},{name:`plan`,description:`Title + heading per step + checklist items`,inputSchema:{type:`object`,properties:{title:{type:`string`},steps:{type:`array`,items:{type:`object`,properties:{label:{type:`string`},checked:{type:`boolean`}}}}},required:[`title`]},example:JSON.stringify({title:`Sprint Plan`,steps:[{label:`Write tests`,checked:!1},{label:`Deploy`,checked:!1}]}),expandsTo:`blocks: [heading, checklist]`},{name:`understanding`,description:`Title + markdown explanation + kv pairs`,inputSchema:{type:`object`,properties:{title:{type:`string`},explanation:{type:`string`},details:{type:`object`,additionalProperties:{type:`string`}}},required:[`title`,`explanation`]},example:JSON.stringify({title:`Architecture Overview`,explanation:`The system uses microservices.`,details:{Language:`TypeScript`,Runtime:`Node`}}),expandsTo:`blocks: [heading, markdown, kv]`},{name:`bug-analyze`,description:`Title + heading + severity/status kv + code block + markdown`,inputSchema:{type:`object`,properties:{title:{type:`string`},severity:{type:`string`},status:{type:`string`},code:{type:`string`},analysis:{type:`string`}},required:[`title`,`severity`,`status`]},example:JSON.stringify({title:`Null pointer in auth`,severity:`high`,status:`open`,code:`const x = obj.prop;`,analysis:`obj may be null when token missing.`}),expandsTo:`blocks: [heading, kv, code, markdown]`},{name:`task-done`,description:`Title + checklist of completed items + optional metrics`,inputSchema:{type:`object`,properties:{title:{type:`string`},items:{type:`array`,items:{type:`object`,properties:{label:{type:`string`},checked:{type:`boolean`}}}},completed:{type:`number`},total:{type:`number`}},required:[`title`,`items`]},example:JSON.stringify({title:`PR #42 Done`,items:[{label:`Lint pass`,checked:!0},{label:`Tests pass`,checked:!0}],completed:2,total:2}),expandsTo:`blocks: [heading, checklist, metrics]`},{name:`review`,description:`Title + criteria checklist + approval actions`,inputSchema:{type:`object`,properties:{title:{type:`string`,description:`Review title`},criteria:{type:`array`,description:`Checklist criteria items`,items:{type:`object`,properties:{label:{type:`string`},checked:{type:`boolean`}}}},annotations:{type:`array`,description:`Optional annotation items`,items:{type:`object`,properties:{label:{type:`string`},description:{type:`string`},severity:{type:`string`}}}},approval:{type:`object`,description:`Optional approval config`,properties:{prompt:{type:`string`},options:{type:`array`,items:{type:`object`,properties:{label:{type:`string`},value:{type:`string`}}}}}}},required:[`title`,`criteria`]},example:JSON.stringify({title:`Code Review`,criteria:[{label:`Tests included`,checked:!0},{label:`No regressions`,checked:!1}]}),expandsTo:`blocks: [heading, checklist] + actions: [approve, reject]`},{name:`explore`,description:`Title + heading per finding + code blocks`,inputSchema:{type:`object`,properties:{title:{type:`string`},findings:{type:`array`,items:{type:`object`,properties:{heading:{type:`string`},code:{type:`string`}}}}},required:[`title`,`findings`]},example:JSON.stringify({title:`Codebase Exploration`,findings:[{heading:`Auth flow`,code:`function login()`},{heading:`API routes`,code:`router.get("/api")`}]}),expandsTo:`blocks: [heading, code] per finding`},{name:`decision`,description:`Title + kv for recommendation + comparison blocks per option`,inputSchema:{type:`object`,properties:{title:{type:`string`},recommendation:{type:`string`},options:{type:`array`,items:{type:`object`,properties:{title:{type:`string`},items:{type:`array`,items:{type:`string`}}}}}},required:[`title`,`recommendation`]},example:JSON.stringify({title:`DB Choice`,recommendation:`PostgreSQL`,options:[{title:`Postgres`,items:[`ACID`,`Rich types`]},{title:`Mongo`,items:[`Schema-less`,`Horizontal`]}]}),expandsTo:`blocks: [heading, kv, comparison]`}];function j_(e,t){let n=W(`present`);try{let e=w(`present`);e&&Zg(F(L(e,`dist`,`annotation-layer.js`),`utf8`))}catch{}xr(e,`present`,{title:n.title,description:"Render a ChannelSurface. Required: schemaVersion: 1, title. Supports blocks, template+data, named presets, and raw JSON string with auto-repair. Use `raw` for complex payloads (mermaid, code, many blocks) — common LLM JSON errors are auto-fixed. Actions use browser transport. Resources: aikit://schemas/channel-surface (schema+blocks), aikit://present/presets (presets), aikit://present/templates (viewers).",inputSchema:O_,annotations:n.annotations,_meta:ag(_g)},J(`present`,async(t,n)=>{let r=w_(t);if(!r.ok)return e_(r.error.code,r.error.reason,void 0,`Present`);let i=t_(r.surface,n);if(!i.ok)return i.response;let a=k_(e);return await a_(i.surface,{...i.options,preferBrowser:i.options.preferBrowser||a===`unsupported`})}));try{let t=new qn(_g,{list:void 0});e.registerResource(`Present View`,t,{description:`AI Kit present tool viewer`},async(e,t,n)=>{let r=Array.isArray(t.id)?t.id[0]:t.id,i=r?Dg(r):void 0;return{contents:[{uri:e.href,mimeType:vr,_meta:og(),text:i??wg()??`<html><body><p>No content generated yet. Call the present tool first.</p></body></html>`}]}})}catch{}function r(){try{let e=w(`present`);if(e)return F(L(e,`dist`,`index.html`),`utf8`)}catch{}return wg()||`<html><body><p>Loading...</p></body></html>`}try{e.registerResource(`Present App`,gg,{description:`AI Kit present app - entry point`},async()=>({contents:[{uri:gg,mimeType:vr,_meta:og(),text:r()}]}))}catch{}try{e.registerResource(`present-templates`,`aikit://present/templates`,{description:`List all registered present viewer templates with their input schemas`},async()=>{let e=ym().map(e=>({id:e.id,label:e.label,description:e.description,transports:e.supportedTransports,inputSchema:e.inputSchema}));return{contents:[{uri:`aikit://present/templates`,mimeType:`application/json`,text:JSON.stringify(e,null,2)}]}})}catch{}try{e.registerResource(`present-presets`,`aikit://present/presets`,{description:`List all registered present presets with input schemas and examples`},async()=>({contents:[{uri:`aikit://present/presets`,mimeType:`application/json`,text:JSON.stringify(A_,null,2)}]}))}catch{}}const M_=M(`tools`);function N_(e,t){let n=new ar({structure:new sr,dependencies:new nr,symbols:new cr,patterns:new or,entryPoints:new ir,diagrams:new rr}),r=W(`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:R.string().optional().describe(`Root path to analyze (defaults to workspace root)`),aspects:R.array(R.enum([`all`,`structure`,`dependencies`,`symbols`,`patterns`,`entry-points`,`diagrams`])).default([`all`]).describe(`Which analysis aspects to run`)},annotations:r.annotations},J(`produce_knowledge`,async({scope:e,aspects:r},i)=>{let a;try{a=Qc(i).createTask(`Produce Knowledge`,3),a.progress(0,`Running analyzers`);let o=e??`.`;M_.info(`Running knowledge production`,{rootPath:o,aspects:r});let s=await n.runExtraction(o,r);try{let e=t?.onboardDir??``;if(!e)throw M_.warn(`onboardDir not configured — skipping artifact persistence.`),Error(`skip`);Ce(e,{recursive:!0});let n=`<!-- Generated by produce_knowledge at ${new Date().toISOString()} -->\n\n`;for(let[t,r]of Object.entries(s))r&&typeof r==`string`&&ke(I(e,`${t}.md`),n+r,`utf-8`);M_.info(`Knowledge persisted to .ai/context/`,{files:Object.keys(s).length})}catch(e){M_.warn(`Failed to persist knowledge to .ai/context/`,{error:N(e)})}a.progress(1,`Synthesizing results`);let c=n.buildSynthesisInstructions(s,r);return a.complete(`Knowledge production complete`),{content:[{type:`text`,text:c+`
3010
+ <\/script>`}function Qg(e){Xg=e||``}function $g(e,t){if(!Xg)return e;let n=`${`<script${t?` nonce="${Y(t)}"`:``}>${Xg}<\/script>`}\n${Zg(t||``)}`;return e.includes(`</body>`)?e.replace(`</body>`,`${n}\n</body>`):`${e}${n}`}function e_(e,t){return[`<!DOCTYPE html>`,`<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">`,`<title>Error — ${Y(e)}</title>`,`<style>`,` * { box-sizing: border-box; margin: 0; padding: 0; }`,` body { font-family: system-ui, -apple-system, sans-serif; min-height: 100vh; display: flex; align-items: center; justify-content: center; padding: 2rem; background: #fafafa; color: #333; }`,` .error-card { max-width: 560px; width: 100%; padding: 2.5rem; border-radius: 1rem; background: #fff; border: 1px solid #e5e7eb; box-shadow: 0 1px 3px rgba(0,0,0,0.06); }`,` .error-badge { display: inline-block; font-size: 0.75rem; font-weight: 600; text-transform: uppercase; letter-spacing: 0.05em; color: #dc2626; background: #fef2f2; border: 1px solid #fecaca; border-radius: 0.375rem; padding: 0.25rem 0.625rem; margin-bottom: 1rem; }`,` .error-title { font-size: 1.25rem; font-weight: 600; margin-bottom: 0.75rem; color: #111; }`,` .error-message { font-size: 0.875rem; line-height: 1.6; color: #6b7280; white-space: pre-wrap; word-break: break-word; }`,`</style></head><body>`,`<div class="error-card">`,` <span class="error-badge">Render Error</span>`,` <h1 class="error-title">${Y(e)}</h1>`,` <p class="error-message">${Y(t)}</p>`,`</div>`,`</body></html>`].join(`
3011
+ `)}function t_(e,t,n,r){return Eg(e_(r??`Present`,t)),{content:[{type:`text`,text:`[ERROR:VALIDATION] ${t}`}],isError:!0}}function n_(e,t){if(!jg(e)||!(`schemaVersion`in e))return{ok:!1,response:t_(`INVALID_CHANNEL_SURFACE`,`present expects a ChannelSurface object with schemaVersion: 1`)};if(e.schemaVersion!==1)return{ok:!1,response:t_(`UNSUPPORTED_SCHEMA_VERSION`,`Unsupported ChannelSurface schemaVersion: ${String(e.schemaVersion)}`)};if(typeof e.title==`string`&&Mg.test(e.title))return{ok:!1,response:t_(`TITLE_UNICODE_ESCAPE_NOT_ALLOWED`,`Use actual Unicode characters in title, not escape sequences.`)};let n=Array.isArray(e.blocks)?{...e,blocks:e.blocks.flatMap(e=>{if(!jg(e)||e.type!==`markdown`)return[e];let t=Ig(e);return!t||!Lg(t)?[e]:Vg(e)})}:e;return{ok:!0,surface:n,options:Ug(n,t)}}const r_={id:`__feedback`,type:`text-submit`,label:`💬 Feedback`,variant:`default`};function i_(e){return!e.actions||e.actions.length===0||e.actions.some(e=>e.id===`__feedback`)?e:{...e,actions:[...e.actions,r_]}}function a_(e){return(e.actions?.length??0)>0||e.response?.required===!0?Ag.getAll().some(e=>e.id===`browser`):!1}async function o_(e,t={}){let n=a_(e)?{...t,preferBrowser:!0}:t,r=Gg(e),i=Ag.select(r,n),a=i?.id===`browser`?i_(r):r,o;if(o=i?await i.render(a,n):ug(a),t.compact){let{structuredContent:e,...t}=o;return t}return o}function Z(e,t=``){return typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`?String(e):t}function s_(e){return{type:`kv`,value:e}}function c_(e){if(Array.isArray(e))return e}const l_=[{name:`summary`,description:`Title + markdown summary + optional metrics (pass/fail counts)`,expand(e){let t=Z(e.title,`Summary`),n=[{type:`heading`,value:t}],r=Z(e.summary);r&&n.push({type:`markdown`,value:r});let i=Number(e.passed)||0,a=Number(e.failed)||0;if(i>0||a>0){let e=[];i>0&&e.push({label:`Passed`,value:i,status:`success`}),a>0&&e.push({label:`Failed`,value:a,status:`error`}),n.push({type:`metrics`,value:e})}return{title:t,blocks:n}}},{name:`plan`,description:`Title + heading per step + checklist items`,expand(e){let t=Z(e.title,`Plan`),n=[{type:`heading`,value:t}],r=c_(e.steps);return r&&n.push({type:`checklist`,value:{items:r}}),{title:t,blocks:n}}},{name:`understanding`,description:`Title + markdown explanation + kv pairs`,expand(e){let t=Z(e.title,`Understanding`),n=[{type:`heading`,value:t}],r=Z(e.explanation);return r&&n.push({type:`markdown`,value:r}),e.details&&typeof e.details==`object`&&!Array.isArray(e.details)&&n.push(s_(e.details)),{title:t,blocks:n}}},{name:`bug-analyze`,description:`Title + heading + severity/status kv + code block + markdown`,expand(e){let t=Z(e.title,`Bug Analysis`),n=[{type:`heading`,value:t}],r={};e.severity&&(r.Severity=e.severity),e.status&&(r.Status=e.status),Object.keys(r).length>0&&n.push({type:`kv`,value:r});let i=Z(e.code);i&&n.push({type:`code`,value:i});let a=Z(e.analysis);return a&&n.push({type:`markdown`,value:a}),{title:t,blocks:n}}},{name:`task-done`,description:`Title + checklist of completed items + optional metrics`,expand(e){let t=Z(e.title,`Task Complete`),n=[{type:`heading`,value:t}],r=c_(e.items);r&&n.push({type:`checklist`,value:{items:r}});let i=e.completed,a=e.total;if(i!==void 0||a!==void 0){let e=[];i!==void 0&&e.push({label:`Completed`,value:Number(i)||i,status:`success`}),a!==void 0&&e.push({label:`Total`,value:Number(a)||a}),n.push({type:`metrics`,value:e})}return{title:t,blocks:n}}},{name:`review`,description:`Title + criteria checklist + annotation items + approval controls`,expand(e){let t=Z(e.title,`Review`),n=[{type:`heading`,value:t}],r=c_(e.criteria);r&&n.push({type:`checklist`,value:{items:r}});let i=e.annotations;Array.isArray(i)&&i.length>0&&n.push({type:`annotation`,value:i});let a=e.approval;return a&&typeof a==`object`?n.push({type:`approval`,value:a}):n.push({type:`actions`,value:[{type:`button`,id:`approve`,label:`Approve`,variant:`primary`},{type:`button`,id:`reject`,label:`Reject`,variant:`danger`}]}),{title:t,blocks:n}}},{name:`explore`,description:`Title + heading per finding + code blocks`,expand(e){let t=Z(e.title,`Exploration`),n=[{type:`heading`,value:t}],r=c_(e.findings);if(r)for(let e of r)n.push({type:`heading`,value:Z(e.heading,`Finding`)}),e.code&&n.push({type:`code`,value:e.code});return{title:t,blocks:n}}},{name:`decision`,description:`Title + kv for recommendation + comparison blocks per option`,expand(e){let t=Z(e.title,`Decision`),n=[{type:`heading`,value:t}];e.recommendation&&n.push({type:`kv`,value:{Recommendation:e.recommendation}});let r=c_(e.options);return r&&r.length>0&&n.push({type:`comparison`,value:r.map(e=>({title:Z(e.title,`Option`),items:Array.isArray(e.items)?e.items:[]}))}),{title:t,blocks:n}}}],u_=new Map;for(let e of l_)u_.set(e.name,e);function d_(e,t){let n=u_.get(e);return n?n.expand(t):null}const f_={h:`heading`,m:`markdown`,t:`table`,p:`paragraph`,c:`code`,s:`separator`,M:`metrics`,C:`chart`,T:`timeline`,g:`graph`,tr:`tree`,tl:`timeline`,cl:`checklist`,pr:`progress`,sb:`status-board`,kv:`kv`,ac:`actions`,di:`mermaid`},p_=/^(#{1,6})\s/,m_=/^(`{3,}|~{3,})/,h_=/^\|.+\|.+\|/m;function g_(e){let t=e.trim(),n=t.match(p_);if(n)return{type:`heading`,value:t.slice(n[0].length)};if(m_.test(t)){let e=t.indexOf(`
3012
+ `),n=t.lastIndexOf(t[0]);return{type:`code`,value:e>=0?t.slice(e+1,n).trimEnd():t}}return h_.test(t)?{type:`table`,value:t}:{type:`markdown`,value:t}}function __(e,t){let n=f_[e];if(!n)return null;switch(e){case`M`:return{type:`metrics`,value:t};case`C`:return{type:`chart`,value:t};case`T`:case`tl`:return{type:`timeline`,value:t};case`g`:return{type:`graph`,value:t};case`tr`:return{type:`tree`,value:t};case`cl`:return{type:`checklist`,value:t};case`pr`:return{type:`progress`,value:t};case`sb`:return{type:`status-board`,value:t};case`kv`:return{type:`kv`,value:t};case`ac`:return{type:`actions`,value:t};case`di`:return{type:`mermaid`,value:t};case`s`:return{type:`separator`,value:t||!0};default:return{type:n,value:typeof t==`string`?t:String(t??``)}}}function v_(e){if(typeof e==`string`){let t=g_(e);return{type:t.type,value:t.value}}if(Array.isArray(e)){let[t,n]=e;if(typeof t==`string`){let e=__(t,n);if(e)return e}return{type:`markdown`,value:String(t??``)}}if(typeof e==`object`&&e){let{blockId:t,...n}=e;return n}return{type:`markdown`,value:String(e??``)}}function y_(e){return{title:e.title??``,blocks:Array.isArray(e.blocks)?e.blocks.map(v_):[]}}function b_(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function x_(e){return b_(e)&&typeof e.schemaVersion==`number`&&e.schemaVersion===1}function S_(e){return b_(e)&&typeof e.schemaVersion==`number`&&e.schemaVersion!==1}function C_(e){return e.schemaVersion===1?typeof e.title!=`string`||e.title.length===0?{ok:!1,error:{code:`MISSING_TITLE`,reason:`ChannelSurface requires a non-empty title`}}:e.blocks!==void 0&&!Array.isArray(e.blocks)?{ok:!1,error:{code:`INVALID_BLOCKS`,reason:`blocks must be an array of TypedBlock objects`}}:{ok:!0,surface:e}:{ok:!1,error:{code:`UNSUPPORTED_SCHEMA_VERSION`,reason:`Unsupported schemaVersion: ${String(e.schemaVersion)}`}}}function w_(e){try{let t=re(e);return b_(t)?(t.schemaVersion===void 0&&(t.schemaVersion=1),T_(t)):{ok:!1,error:{code:`INVALID_RAW_INPUT`,reason:`raw field must contain a JSON object (ChannelSurface)`}}}catch(e){return{ok:!1,error:{code:`INVALID_RAW_JSON`,reason:`Failed to parse raw field: ${e.message}`,hint:`JSON repair attempted. Ensure the raw string contains a valid ChannelSurface object. Common LLM errors (newlines in strings, trailing commas) are auto-repaired.`}}}}function T_(e){if(Array.isArray(e)){if(e.length!==2)return{ok:!1,error:{code:`INVALID_PRESET_INPUT`,reason:`Preset input must be a [name, data] tuple`,hint:`Use [presetName, { title, ...fields }]`}};let[t,n]=e;if(typeof t!=`string`)return{ok:!1,error:{code:`INVALID_PRESET_INPUT`,reason:`Preset name must be a string`}};if(!b_(n))return{ok:!1,error:{code:`INVALID_PRESET_INPUT`,reason:`Preset data must be an object`}};let r=d_(t,n);return r?{ok:!0,surface:{schemaVersion:1,title:r.title,blocks:r.blocks}}:{ok:!1,error:{code:`UNKNOWN_PRESET`,reason:`Unknown preset: ${t}`,hint:`Available presets: summary, plan, understanding, bug-analyze, task-done, review, explore, decision`}}}if(S_(e))return{ok:!1,error:{code:`UNSUPPORTED_SCHEMA_VERSION`,reason:`Unsupported schemaVersion: ${String(e.schemaVersion)}`,hint:`Use schemaVersion: 1`}};if(x_(e))return C_(e);if(typeof e==`string`){let t=y_({blocks:[e]});return{ok:!0,surface:{schemaVersion:1,title:t.title||`Present`,blocks:t.blocks}}}if(b_(e)){if(typeof e.raw==`string`)return w_(e.raw);if(!(`blocks`in e)&&!(`title`in e))return{ok:!1,error:{code:`INVALID_INPUT`,reason:`Expected a ChannelSurface object, preset tuple, or shorthand input`}};let t=y_(e);return{ok:!0,surface:{schemaVersion:1,title:t.title||`Present`,blocks:t.blocks}}}return{ok:!1,error:{code:`INVALID_INPUT`,reason:`Expected a ChannelSurface object, preset tuple, or shorthand input`}}}const E_=R.object({label:R.string(),value:R.string(),description:R.string().optional()}),D_=R.object({id:R.string().describe(`Unique action identifier`),type:R.enum([`button`,`select`,`multi-select`,`form-submit`,`text-submit`,`confirm`,`custom`]).describe(`Interactive action type`),label:R.string().describe(`Visible action label`),variant:R.enum([`primary`,`danger`,`default`]).optional(),options:R.array(E_).optional(),schema:R.record(R.string(),R.unknown()).optional()}),O_=R.object({type:R.string(),title:R.string().optional(),value:R.unknown().optional(),language:R.string().optional()}).catchall(R.unknown()),k_={schemaVersion:R.literal(1).describe(`ChannelSurface schema version. Must be 1.`),title:R.string().describe(`Surface title shown to the user.`),description:R.string().optional().describe(`Optional supporting copy for the surface.`),template:R.string().optional().describe(`Optional template id such as report@1.`),layout:R.object({maxWidth:R.string().optional(),padding:R.string().optional(),columns:R.number().optional()}).optional(),blocks:R.array(O_).optional().describe(`Typed block content for the surface.`),data:R.unknown().optional().describe(`Template data payload, if the template expands data.`),actions:R.array(D_).optional().describe(`Interactive actions. Presence triggers browser transport.`),response:R.object({timeout:R.number().optional(),required:R.boolean().optional()}).optional(),metadata:R.object({surfaceId:R.string().optional(),createdAt:R.string().optional(),source:R.string().optional()}).optional(),colorScheme:R.enum([`light`,`dark`,`auto`]).optional(),lang:R.string().optional(),dir:R.enum([`ltr`,`rtl`,`auto`]).optional(),raw:R.string().optional().describe(`Raw JSON string with auto-repair. Accepts common LLM JSON errors (unescaped newlines in strings, trailing commas). Use for complex payloads with mermaid/code/markdown blocks.`)};R.object({surfaceId:R.string(),actionId:R.string(),actionType:R.enum([`button`,`select`,`multi-select`,`form-submit`,`text-submit`,`confirm`,`custom`]),value:R.unknown().optional(),formData:R.record(R.string(),R.unknown()).optional(),selection:R.union([R.string(),R.array(R.string())]).optional(),label:R.string().optional(),timestamp:R.string(),sourceTransport:R.enum([`mcp-app`,`browser`,`export`])});function A_(e){let t=e.server?.getClientCapabilities?.();if(!t)return`unknown`;let n=yr(t);return!n||Array.isArray(n.mimeTypes)&&n.mimeTypes.length>0&&!n.mimeTypes.includes(vr)?`unsupported`:`supported`}const j_=[{name:`summary`,description:`Title + markdown summary + optional metrics (pass/fail counts)`,inputSchema:{type:`object`,properties:{title:{type:`string`,description:`Section heading`},summary:{type:`string`,description:`Free-form markdown summary`},passed:{type:`number`,description:`Pass count for metrics`},failed:{type:`number`,description:`Fail count for metrics`}},required:[`title`]},example:JSON.stringify({title:`Build Summary`,summary:`All tests passed.`,passed:42,failed:0}),expandsTo:`blocks: [heading, markdown, metrics]`},{name:`plan`,description:`Title + heading per step + checklist items`,inputSchema:{type:`object`,properties:{title:{type:`string`},steps:{type:`array`,items:{type:`object`,properties:{label:{type:`string`},checked:{type:`boolean`}}}}},required:[`title`]},example:JSON.stringify({title:`Sprint Plan`,steps:[{label:`Write tests`,checked:!1},{label:`Deploy`,checked:!1}]}),expandsTo:`blocks: [heading, checklist]`},{name:`understanding`,description:`Title + markdown explanation + kv pairs`,inputSchema:{type:`object`,properties:{title:{type:`string`},explanation:{type:`string`},details:{type:`object`,additionalProperties:{type:`string`}}},required:[`title`,`explanation`]},example:JSON.stringify({title:`Architecture Overview`,explanation:`The system uses microservices.`,details:{Language:`TypeScript`,Runtime:`Node`}}),expandsTo:`blocks: [heading, markdown, kv]`},{name:`bug-analyze`,description:`Title + heading + severity/status kv + code block + markdown`,inputSchema:{type:`object`,properties:{title:{type:`string`},severity:{type:`string`},status:{type:`string`},code:{type:`string`},analysis:{type:`string`}},required:[`title`,`severity`,`status`]},example:JSON.stringify({title:`Null pointer in auth`,severity:`high`,status:`open`,code:`const x = obj.prop;`,analysis:`obj may be null when token missing.`}),expandsTo:`blocks: [heading, kv, code, markdown]`},{name:`task-done`,description:`Title + checklist of completed items + optional metrics`,inputSchema:{type:`object`,properties:{title:{type:`string`},items:{type:`array`,items:{type:`object`,properties:{label:{type:`string`},checked:{type:`boolean`}}}},completed:{type:`number`},total:{type:`number`}},required:[`title`,`items`]},example:JSON.stringify({title:`PR #42 Done`,items:[{label:`Lint pass`,checked:!0},{label:`Tests pass`,checked:!0}],completed:2,total:2}),expandsTo:`blocks: [heading, checklist, metrics]`},{name:`review`,description:`Title + criteria checklist + approval actions`,inputSchema:{type:`object`,properties:{title:{type:`string`,description:`Review title`},criteria:{type:`array`,description:`Checklist criteria items`,items:{type:`object`,properties:{label:{type:`string`},checked:{type:`boolean`}}}},annotations:{type:`array`,description:`Optional annotation items`,items:{type:`object`,properties:{label:{type:`string`},description:{type:`string`},severity:{type:`string`}}}},approval:{type:`object`,description:`Optional approval config`,properties:{prompt:{type:`string`},options:{type:`array`,items:{type:`object`,properties:{label:{type:`string`},value:{type:`string`}}}}}}},required:[`title`,`criteria`]},example:JSON.stringify({title:`Code Review`,criteria:[{label:`Tests included`,checked:!0},{label:`No regressions`,checked:!1}]}),expandsTo:`blocks: [heading, checklist] + actions: [approve, reject]`},{name:`explore`,description:`Title + heading per finding + code blocks`,inputSchema:{type:`object`,properties:{title:{type:`string`},findings:{type:`array`,items:{type:`object`,properties:{heading:{type:`string`},code:{type:`string`}}}}},required:[`title`,`findings`]},example:JSON.stringify({title:`Codebase Exploration`,findings:[{heading:`Auth flow`,code:`function login()`},{heading:`API routes`,code:`router.get("/api")`}]}),expandsTo:`blocks: [heading, code] per finding`},{name:`decision`,description:`Title + kv for recommendation + comparison blocks per option`,inputSchema:{type:`object`,properties:{title:{type:`string`},recommendation:{type:`string`},options:{type:`array`,items:{type:`object`,properties:{title:{type:`string`},items:{type:`array`,items:{type:`string`}}}}}},required:[`title`,`recommendation`]},example:JSON.stringify({title:`DB Choice`,recommendation:`PostgreSQL`,options:[{title:`Postgres`,items:[`ACID`,`Rich types`]},{title:`Mongo`,items:[`Schema-less`,`Horizontal`]}]}),expandsTo:`blocks: [heading, kv, comparison]`}];function M_(e,t){let n=W(`present`);try{let e=w(`present`);e&&Qg(F(L(e,`dist`,`annotation-layer.js`),`utf8`))}catch{}xr(e,`present`,{title:n.title,description:"Render a ChannelSurface. Required: schemaVersion: 1, title. Supports blocks, template+data, named presets, and raw JSON string with auto-repair. Use `raw` for complex payloads (mermaid, code, many blocks) — common LLM JSON errors are auto-fixed. Actions use browser transport. Resources: aikit://schemas/channel-surface (schema+blocks), aikit://present/presets (presets), aikit://present/templates (viewers).",inputSchema:k_,annotations:n.annotations,_meta:og(vg)},J(`present`,async(t,n)=>{let r=T_(t);if(!r.ok)return t_(r.error.code,r.error.reason,void 0,`Present`);let i=n_(r.surface,n);if(!i.ok)return i.response;let a=A_(e);return await o_(i.surface,{...i.options,preferBrowser:i.options.preferBrowser||a===`unsupported`})}));try{let t=new qn(vg,{list:void 0});e.registerResource(`Present View`,t,{description:`AI Kit present tool viewer`},async(e,t,n)=>{let r=Array.isArray(t.id)?t.id[0]:t.id,i=r?Og(r):void 0;return{contents:[{uri:e.href,mimeType:vr,_meta:sg(),text:i??Tg()??`<html><body><p>No content generated yet. Call the present tool first.</p></body></html>`}]}})}catch{}function r(){try{let e=w(`present`);if(e)return F(L(e,`dist`,`index.html`),`utf8`)}catch{}return Tg()||`<html><body><p>Loading...</p></body></html>`}try{e.registerResource(`Present App`,_g,{description:`AI Kit present app - entry point`},async()=>({contents:[{uri:_g,mimeType:vr,_meta:sg(),text:r()}]}))}catch{}try{e.registerResource(`present-templates`,`aikit://present/templates`,{description:`List all registered present viewer templates with their input schemas`},async()=>{let e=ym().map(e=>({id:e.id,label:e.label,description:e.description,transports:e.supportedTransports,inputSchema:e.inputSchema}));return{contents:[{uri:`aikit://present/templates`,mimeType:`application/json`,text:JSON.stringify(e,null,2)}]}})}catch{}try{e.registerResource(`present-presets`,`aikit://present/presets`,{description:`List all registered present presets with input schemas and examples`},async()=>({contents:[{uri:`aikit://present/presets`,mimeType:`application/json`,text:JSON.stringify(j_,null,2)}]}))}catch{}}const N_=M(`tools`);function P_(e,t){let n=new ar({structure:new sr,dependencies:new nr,symbols:new cr,patterns:new or,entryPoints:new ir,diagrams:new rr}),r=W(`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:R.string().optional().describe(`Root path to analyze (defaults to workspace root)`),aspects:R.array(R.enum([`all`,`structure`,`dependencies`,`symbols`,`patterns`,`entry-points`,`diagrams`])).default([`all`]).describe(`Which analysis aspects to run`)},annotations:r.annotations},J(`produce_knowledge`,async({scope:e,aspects:r},i)=>{let a;try{a=Qc(i).createTask(`Produce Knowledge`,3),a.progress(0,`Running analyzers`);let o=e??`.`;N_.info(`Running knowledge production`,{rootPath:o,aspects:r});let s=await n.runExtraction(o,r);try{let e=t?.onboardDir??``;if(!e)throw N_.warn(`onboardDir not configured — skipping artifact persistence.`),Error(`skip`);Ce(e,{recursive:!0});let n=`<!-- Generated by produce_knowledge at ${new Date().toISOString()} -->\n\n`;for(let[t,r]of Object.entries(s))r&&typeof r==`string`&&ke(I(e,`${t}.md`),n+r,`utf-8`);N_.info(`Knowledge persisted to .ai/context/`,{files:Object.keys(s).length})}catch(e){N_.warn(`Failed to persist knowledge to .ai/context/`,{error:N(e)})}a.progress(1,`Synthesizing results`);let c=n.buildSynthesisInstructions(s,r);return a.complete(`Knowledge production complete`),{content:[{type:`text`,text:c+`
3012
3013
 
3013
3014
  ---
3014
- _Next: Review the baselines above and use \`remember\` to store synthesized knowledge entries._`}]}}catch(e){return a?.fail?.(`Production failed`),M_.error(`Knowledge production failed`,N(e)),q(`INTERNAL`,`Knowledge production failed: ${e instanceof Error?e.message:String(e)}`)}}))}const P_=M(`tools`);function F_(e,t,n,r,i,a,o){let s=W(`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:R.boolean().default(!1).describe(`If true, force full re-index ignoring file hashes`),force:R.boolean().default(!1).describe(`If true, override smart indexing guard and run reindex anyway`)},annotations:s.annotations},J(`reindex`,async({full:e,force:s},c)=>{try{if(t.isIndexing)return{content:[{type:`text`,text:`## Reindex Already in Progress
3015
+ _Next: Review the baselines above and use \`remember\` to store synthesized knowledge entries._`}]}}catch(e){return a?.fail?.(`Production failed`),N_.error(`Knowledge production failed`,N(e)),q(`INTERNAL`,`Knowledge production failed: ${e instanceof Error?e.message:String(e)}`)}}))}const F_=M(`tools`);function I_(e,t,n,r,i,a,o){let s=W(`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:R.boolean().default(!1).describe(`If true, force full re-index ignoring file hashes`),force:R.boolean().default(!1).describe(`If true, override smart indexing guard and run reindex anyway`)},annotations:s.annotations},J(`reindex`,async({full:e,force:s},c)=>{try{if(t.isIndexing)return{content:[{type:`text`,text:`## Reindex Already in Progress
3015
3016
 
3016
3017
  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
3017
3018
 
@@ -3019,47 +3020,47 @@ Smart indexing (trickle mode) is enabled — files are automatically indexed as
3019
3020
 
3020
3021
  **If the index is severely outdated**, use \`reindex({ force: true })\` to override.
3021
3022
 
3022
- Use \`status({})\` to check smart indexing queue status.`}]};let l=Qc(c).createTask(`Reindex`,1);l.progress(0,`Starting ${e?`full`:`incremental`} reindex`),P_.info(`Starting background re-index`,{mode:e?`full`:`incremental`});let u=e=>t=>{t.phase===`chunking`&&t.currentFile&&P_.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(P_.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(),P_.info(`FTS index rebuilt after reindex`)}catch(e){P_.warn(`FTS index rebuild failed`,N(e))}try{let e=await r.reindexAll();P_.info(`Curated re-index complete`,{indexed:e.indexed})}catch(e){P_.warn(`Curated re-index failed`,N(e))}if(a)try{await a.notifyAfterReindex()}catch(e){P_.warn(`Post-reindex resource notification failed`,N(e))}}).catch(e=>{l.fail(`Reindex failed: ${e instanceof Error?e.message:String(e)}`),P_.error(`Background reindex failed`,N(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 P_.error(`Reindex failed`,N(e)),q(`INTERNAL`,`Reindex failed: ${e instanceof Error?e.message:String(e)}`)}}))}const I_=M(`tools`);function L_(e){let t=W(`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:R.enum([`list`,`clear`]).default(`list`).describe(`Action: "list" (default) to view entries, "clear" to wipe the log`),last:R.number().optional().describe(`Number of entries to return (default: 20, list only)`),tool:R.string().optional().describe(`Filter by tool name (list only)`),source:R.enum([`mcp`,`cli`]).optional().describe(`Filter by source: "mcp" or "cli" (list only)`),since:R.string().optional().describe(`ISO timestamp — only show entries after this time (list only)`)},annotations:t.annotations},J(`replay`,async({action:e,last:t,tool:n,source:r,since:i})=>{try{if(e===`clear`)return sn(),{content:[{type:`text`,text:`Replay log cleared.`}]};let a=cn({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 ln().catch(()=>{}),{content:[{type:`text`,text:`**Replay Log** (${a.length} entries)\n\n${o.join(`
3023
+ Use \`status({})\` to check smart indexing queue status.`}]};let l=Qc(c).createTask(`Reindex`,1);l.progress(0,`Starting ${e?`full`:`incremental`} reindex`),F_.info(`Starting background re-index`,{mode:e?`full`:`incremental`});let u=e=>t=>{t.phase===`chunking`&&t.currentFile&&F_.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(F_.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(),F_.info(`FTS index rebuilt after reindex`)}catch(e){F_.warn(`FTS index rebuild failed`,N(e))}try{let e=await r.reindexAll();F_.info(`Curated re-index complete`,{indexed:e.indexed})}catch(e){F_.warn(`Curated re-index failed`,N(e))}if(a)try{await a.notifyAfterReindex()}catch(e){F_.warn(`Post-reindex resource notification failed`,N(e))}}).catch(e=>{l.fail(`Reindex failed: ${e instanceof Error?e.message:String(e)}`),F_.error(`Background reindex failed`,N(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 F_.error(`Reindex failed`,N(e)),q(`INTERNAL`,`Reindex failed: ${e instanceof Error?e.message:String(e)}`)}}))}const L_=M(`tools`);function R_(e){let t=W(`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:R.enum([`list`,`clear`]).default(`list`).describe(`Action: "list" (default) to view entries, "clear" to wipe the log`),last:R.number().optional().describe(`Number of entries to return (default: 20, list only)`),tool:R.string().optional().describe(`Filter by tool name (list only)`),source:R.enum([`mcp`,`cli`]).optional().describe(`Filter by source: "mcp" or "cli" (list only)`),since:R.string().optional().describe(`ISO timestamp — only show entries after this time (list only)`)},annotations:t.annotations},J(`replay`,async({action:e,last:t,tool:n,source:r,since:i})=>{try{if(e===`clear`)return sn(),{content:[{type:`text`,text:`Replay log cleared.`}]};let a=cn({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 ln().catch(()=>{}),{content:[{type:`text`,text:`**Replay Log** (${a.length} entries)\n\n${o.join(`
3023
3024
 
3024
- `)}`}]}}catch(e){return I_.error(`Replay failed`,N(e)),q(`INTERNAL`,`Replay failed: ${e instanceof Error?e.message:String(e)}`)}}))}const R_=M(`tools`);function z_(e){let t=W(`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:R.enum([`list`,`restore`]).describe(`list: show restore points, restore: apply a restore point`),id:R.string().optional().describe(`Restore point ID (required for action=restore)`),limit:R.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=Ft().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(`
3025
+ `)}`}]}}catch(e){return L_.error(`Replay failed`,N(e)),q(`INTERNAL`,`Replay failed: ${e instanceof Error?e.message:String(e)}`)}}))}const z_=M(`tools`);function B_(e){let t=W(`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:R.enum([`list`,`restore`]).describe(`list: show restore points, restore: apply a restore point`),id:R.string().optional().describe(`Restore point ID (required for action=restore)`),limit:R.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=Ft().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(`
3025
3026
  `)}`}]}}if(!t)throw Error(`id is required for restore action`);let r=await un(t);return{content:[{type:`text`,text:`Restored ${r.length} files:\n${r.map(e=>`- \`${e}\``).join(`
3026
- `)}`}]}}catch(e){return R_.error(`Restore failed`,N(e)),q(`INTERNAL`,`Restore failed: ${e instanceof Error?e.message:String(e)}`)}})}const B_=/<\/?curated-context>/gi;function V_(e){return e.replace(B_,``)}function H_(e){return`<curated-context>\n${V_(e)}\n</curated-context>`}const U_=M(`tools`);function W_(e,t,n,r){b(e,t,n);let i=e.memoryMetaGet(t);if(!i)return;let a=g(i,{..._,...r});a&&(y(e,t,a),v(e,t,n))}function G_(e,t){let n=[],r=Ae(process.cwd());r&&n.push(`[project: ${r}]`);let i=t?yn(t,`__context_boost`):void 0;return i&&n.push(`[focus: ${i.value}]`),n.length===0?e:`${n.join(` `)} ${e}`}function K_(e,t,n){return n?e:t===`curated`?e*1.2:e}function q_(e,t){return t?e:e.map(e=>({record:e.record,score:K_(e.score,e.record.origin,t)})).sort((e,t)=>t.score-e.score)}function J_(e,t){let n=e?Math.floor(e/Math.max(1,t)):96;return Math.max(40,Math.min(160,n))}function Y_(e,t){let n=e.origin===`curated`?H_(e.content):e.content,r=kn(n,t);return{body:r,truncated:r!==n}}async function X_(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:_r(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 U_.warn(`ER fallback failed`,N(e)),{results:n,triggered:!0,cacheHit:a}}}function Z_(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*(n+1)}))}function Q_(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 $_(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 ev(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&&!tv.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 tv=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 nv(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 zn(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 rv(e,t,n,r,i,a,o,s,c,l,u){let d=W(`search`);e.registerTool(`search`,{title:d.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:Ks,inputSchema:{query:R.string().max(5e3).describe(`Natural language search query`),limit:R.number().min(1).max(20).default(5).describe(`Maximum results to return`),search_mode:R.enum([`hybrid`,`semantic`,`keyword`]).default(`hybrid`).describe(`Search strategy: hybrid (vector + FTS + RRF fusion, default), semantic (vector only), keyword (FTS only)`),content_type:R.enum(j).optional().describe(`Filter by content type`),source_type:R.enum(he).optional().describe(`Coarse filter: "source" (code only), "documentation" (md, curated), "test", "config". Overrides content_type if both set.`),origin:R.enum(pe).optional().describe(`Filter by knowledge origin`),category:R.string().optional().describe(`Filter by category (e.g., decisions, patterns, conventions)`),tags:R.array(R.string()).optional().describe(`Filter by exact tag membership (any supplied tag may match)`),min_score:R.number().min(0).max(1).default(.25).describe(`Minimum similarity score`),graph_hops:R.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:R.number().min(100).max(5e4).optional().describe(`Maximum token budget for the response. When set, output is truncated to fit.`),dedup:R.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:R.array(R.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:d.annotations},async({query:e,limit:d,search_mode:f,content_type:p,source_type:m,origin:h,category:g,tags:_,min_score:v,graph_hops:y,max_tokens:b,dedup:x,workspaces:S})=>{let C=Date.now();try{let w={limit:d,minScore:v,contentType:p,sourceType:m,origin:h,category:g,tags:_},T,E=!1,D=!1,O=``,k=f!==`keyword`,ee=G_(e,s);if(f===`keyword`)T=await n.ftsSearch(e,w),T=T.slice(0,d);else if(f===`semantic`)try{let r=await t.embedQuery(ee);T=await n.search(r,w);let a=await X_(i,T[0]?.score??0,T,e,d);T=a.results,E=a.triggered,D=a.cacheHit}catch(t){k=!1,U_.warn(`Embedder unavailable in semantic mode, falling back to FTS`,N(t)),T=await n.ftsSearch(e,{...w,limit:d}),O=`> _⚠️ Semantic search unavailable (embedder recovering). Showing keyword results instead._
3027
+ `)}`}]}}catch(e){return z_.error(`Restore failed`,N(e)),q(`INTERNAL`,`Restore failed: ${e instanceof Error?e.message:String(e)}`)}})}const V_=/<\/?curated-context>/gi;function H_(e){return e.replace(V_,``)}function U_(e){return`<curated-context>\n${H_(e)}\n</curated-context>`}const W_=M(`tools`);function G_(e,t,n,r){b(e,t,n);let i=e.memoryMetaGet(t);if(!i)return;let a=g(i,{..._,...r});a&&(y(e,t,a),v(e,t,n))}function K_(e,t){let n=[],r=Ae(process.cwd());r&&n.push(`[project: ${r}]`);let i=t?yn(t,`__context_boost`):void 0;return i&&n.push(`[focus: ${i.value}]`),n.length===0?e:`${n.join(` `)} ${e}`}function q_(e,t,n){return n?e:t===`curated`?e*1.2:e}function J_(e,t){return t?e:e.map(e=>({record:e.record,score:q_(e.score,e.record.origin,t)})).sort((e,t)=>t.score-e.score)}function Y_(e,t){let n=e?Math.floor(e/Math.max(1,t)):96;return Math.max(40,Math.min(160,n))}function X_(e,t){let n=e.origin===`curated`?U_(e.content):e.content,r=kn(n,t);return{body:r,truncated:r!==n}}async function Z_(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:_r(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 W_.warn(`ER fallback failed`,N(e)),{results:n,triggered:!0,cacheHit:a}}}function Q_(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*(n+1)}))}function $_(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 ev(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 tv(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&&!nv.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 nv=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 rv(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 zn(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 iv(e,t,n,r,i,a,o,s,c,l,u){let d=W(`search`);e.registerTool(`search`,{title:d.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:Ks,inputSchema:{query:R.string().max(5e3).describe(`Natural language search query`),limit:R.number().min(1).max(20).default(5).describe(`Maximum results to return`),search_mode:R.enum([`hybrid`,`semantic`,`keyword`]).default(`hybrid`).describe(`Search strategy: hybrid (vector + FTS + RRF fusion, default), semantic (vector only), keyword (FTS only)`),content_type:R.enum(j).optional().describe(`Filter by content type`),source_type:R.enum(he).optional().describe(`Coarse filter: "source" (code only), "documentation" (md, curated), "test", "config". Overrides content_type if both set.`),origin:R.enum(pe).optional().describe(`Filter by knowledge origin`),category:R.string().optional().describe(`Filter by category (e.g., decisions, patterns, conventions)`),tags:R.array(R.string()).optional().describe(`Filter by exact tag membership (any supplied tag may match)`),min_score:R.number().min(0).max(1).default(.25).describe(`Minimum similarity score`),graph_hops:R.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:R.number().min(100).max(5e4).optional().describe(`Maximum token budget for the response. When set, output is truncated to fit.`),dedup:R.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:R.array(R.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:d.annotations},async({query:e,limit:d,search_mode:f,content_type:p,source_type:m,origin:h,category:g,tags:_,min_score:v,graph_hops:y,max_tokens:b,dedup:x,workspaces:S})=>{let C=Date.now();try{let w={limit:d,minScore:v,contentType:p,sourceType:m,origin:h,category:g,tags:_},T,E=!1,D=!1,O=``,k=f!==`keyword`,ee=K_(e,s);if(f===`keyword`)T=await n.ftsSearch(e,w),T=T.slice(0,d);else if(f===`semantic`)try{let r=await t.embedQuery(ee);T=await n.search(r,w);let a=await Z_(i,T[0]?.score??0,T,e,d);T=a.results,E=a.triggered,D=a.cacheHit}catch(t){k=!1,W_.warn(`Embedder unavailable in semantic mode, falling back to FTS`,N(t)),T=await n.ftsSearch(e,{...w,limit:d}),O=`> _⚠️ Semantic search unavailable (embedder recovering). Showing keyword results instead._
3027
3028
 
3028
- `}else{let r=[],a=[];try{let i=await t.embedQuery(ee),o=n.coarseSearch,s=o?o.bind(n):n.search.bind(n);[r,a]=await Promise.all([s(i,{...w,limit:d*2}),n.ftsSearch(e,{...w,limit:d*2}).catch(()=>[])])}catch(t){k=!1,U_.warn(`Embedder unavailable, falling back to FTS-only`,N(t)),a=await n.ftsSearch(e,{...w,limit:d*2}),O=`> _⚠️ Vector search unavailable (embedder recovering). Results from keyword search only._
3029
+ `}else{let r=[],a=[];try{let i=await t.embedQuery(ee),o=n.coarseSearch,s=o?o.bind(n):n.search.bind(n);[r,a]=await Promise.all([s(i,{...w,limit:d*2}),n.ftsSearch(e,{...w,limit:d*2}).catch(()=>[])])}catch(t){k=!1,W_.warn(`Embedder unavailable, falling back to FTS-only`,N(t)),a=await n.ftsSearch(e,{...w,limit:d*2}),O=`> _⚠️ Vector search unavailable (embedder recovering). Results from keyword search only._
3029
3030
 
3030
- `}if(k?r.length===0&&a.length>0?(T=a.slice(0,d),O=` (FTS-only: vector index rebuilding)`):T=a.length===0&&r.length>0?r.slice(0,d):Z_(r,a).slice(0,d):T=a.slice(0,d),k){let t=await X_(i,r[0]?.score??0,T,e,d);T=t.results,E=t.triggered,D=t.cacheHit}}T=q_(T,h).slice(0,d),a&&a.recordSearch(e,E,D),T.length>1&&(T=Q_(T,e)),T=$_(T);let te=``;if(S&&S.length>0){let n=Ml(S,u);if(n.length>0){let{stores:r,closeAll:i}=await Nl(n);try{let i;i=f===`keyword`||!k?await Fl(r,e,{...w,limit:d}):await Pl(r,await t.embedQuery(e),{...w,limit:d});for(let e of i)T.push({record:{...e.record,sourcePath:`[${e.workspace}] ${e.record.sourcePath}`},score:e.score});T=T.sort((e,t)=>t.score-e.score).slice(0,d),te=` + ${n.length} workspace(s)`}finally{await i()}}}if(x===`file`&&T.length>1){let e=new Map;for(let t of T){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}]})}T=[...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(T.length>1){let e=T[0].score,t=Math.max(e*.4,.1);T=T.filter(e=>e.score>=t)}if(T.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,timeoutMs:1e4})).text.trim().split(`
3031
- `)[0].slice(0,500);if(r&&r!==e){let i=f===`keyword`||!k?await n.ftsSearch(r,w):await n.search(await t.embedQuery(r),w);i.length>0&&(T=i,O=`> _Original query "${e}" returned 0 results. Auto-reformulated to "${r}"._\n\n`,U_.debug(`Smart search fallback succeeded`,{originalQuery:e,altQuery:r,resultCount:i.length}))}}catch(e){U_.debug(`Smart search fallback failed`,{error:String(e)})}if(T.length===0){let t=rt({text:`No results found for the given query.`,query:e,searchMode:f,limit:d,results:[],durationMs:Date.now()-C}),n=zl(t.summary);return{content:[{type:`text`,text:Bl(t.summary,n)}],isError:!t.ok,structuredContent:{...t.data??{results:[],totalResults:0,searchMode:f,query:e},ref:n}}}}let ne,re;if(y>0&&!r&&(re="> **Note:** `graph_hops` was set but no graph store is available. Graph augmentation skipped."),y>0&&r)try{let e=await Ct(r,T.map(e=>({recordId:e.record.id,score:e.score,sourcePath:e.record.sourcePath})),{hops:y,maxPerHit:5});ne=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(`
3031
+ `}if(k?r.length===0&&a.length>0?(T=a.slice(0,d),O=` (FTS-only: vector index rebuilding)`):T=a.length===0&&r.length>0?r.slice(0,d):Q_(r,a).slice(0,d):T=a.slice(0,d),k){let t=await Z_(i,r[0]?.score??0,T,e,d);T=t.results,E=t.triggered,D=t.cacheHit}}T=J_(T,h).slice(0,d),a&&a.recordSearch(e,E,D),T.length>1&&(T=$_(T,e)),T=ev(T);let te=``;if(S&&S.length>0){let n=Ml(S,u);if(n.length>0){let{stores:r,closeAll:i}=await Nl(n);try{let i;i=f===`keyword`||!k?await Fl(r,e,{...w,limit:d}):await Pl(r,await t.embedQuery(e),{...w,limit:d});for(let e of i)T.push({record:{...e.record,sourcePath:`[${e.workspace}] ${e.record.sourcePath}`},score:e.score});T=T.sort((e,t)=>t.score-e.score).slice(0,d),te=` + ${n.length} workspace(s)`}finally{await i()}}}if(x===`file`&&T.length>1){let e=new Map;for(let t of T){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}]})}T=[...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(T.length>1){let e=T[0].score,t=Math.max(e*.4,.1);T=T.filter(e=>e.score>=t)}if(T.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,timeoutMs:1e4})).text.trim().split(`
3032
+ `)[0].slice(0,500);if(r&&r!==e){let i=f===`keyword`||!k?await n.ftsSearch(r,w):await n.search(await t.embedQuery(r),w);i.length>0&&(T=i,O=`> _Original query "${e}" returned 0 results. Auto-reformulated to "${r}"._\n\n`,W_.debug(`Smart search fallback succeeded`,{originalQuery:e,altQuery:r,resultCount:i.length}))}}catch(e){W_.debug(`Smart search fallback failed`,{error:String(e)})}if(T.length===0){let t=rt({text:`No results found for the given query.`,query:e,searchMode:f,limit:d,results:[],durationMs:Date.now()-C}),n=zl(t.summary);return{content:[{type:`text`,text:Bl(t.summary,n)}],isError:!t.ok,structuredContent:{...t.data??{results:[],totalResults:0,searchMode:f,query:e},ref:n}}}}let ne,re;if(y>0&&!r&&(re="> **Note:** `graph_hops` was set but no graph store is available. Graph augmentation skipped."),y>0&&r)try{let e=await Ct(r,T.map(e=>({recordId:e.record.id,score:e.score,sourcePath:e.record.sourcePath})),{hops:y,maxPerHit:5});ne=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(`
3032
3033
  `),n=new Map;for(let e of t.graphContext.nodes)n.set(e.id,e.name);let r=t.graphContext.edges.slice(0,5).map(e=>` - ${n.get(e.fromId)??e.fromId} —[${e.type}]→ ${n.get(e.toId)??e.toId}`).join(`
3033
3034
  `),i=[`- **Graph Context** (${y} hop${y>1?`s`:``}):`];e&&i.push(` Entities:\n${e}`),r&&i.push(` Relationships:\n${r}`),ne.set(t.recordId,i.join(`
3034
- `))}}catch(e){U_.warn(`Graph augmentation failed`,N(e)),re=`> **Note:** Graph augmentation failed. Results shown without graph context.`}let ie=Date.now();for(let e of T)if(e.record.origin===`curated`&&e.record.indexedAt){let t=ie-new Date(e.record.indexedAt).getTime(),n=Math.max(0,t/864e5);e.score*=.95**n}if(T.sort((e,t)=>t.score-e.score),T=Ue(T),s)for(let e of T){if(e.record.origin!==`curated`)continue;let t=Ad(e.record.sourcePath);t&&W_(s,t,c,l)}let ae=J_(b,T.length),oe=!1,se=T.map((e,t)=>{let n=e.record,r=`### Result ${t+1} (score: ${e.score.toFixed(3)})`,i=[`- **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,ne?.get(n.id)??null].filter(Boolean).join(`
3035
- `),{body:a,truncated:o}=Y_(n,ae);return oe||=o,`${r}\n${i}\n\n${a}${o?`\n\n_Full content: use \`lookup\` on \`${n.sourcePath}\`._`:``}`}).join(`
3035
+ `))}}catch(e){W_.warn(`Graph augmentation failed`,N(e)),re=`> **Note:** Graph augmentation failed. Results shown without graph context.`}let ie=Date.now();for(let e of T)if(e.record.origin===`curated`&&e.record.indexedAt){let t=ie-new Date(e.record.indexedAt).getTime(),n=Math.max(0,t/864e5);e.score*=.95**n}if(T.sort((e,t)=>t.score-e.score),T=Ue(T),s)for(let e of T){if(e.record.origin!==`curated`)continue;let t=Ad(e.record.sourcePath);t&&G_(s,t,c,l)}let ae=Y_(b,T.length),oe=!1,se=T.map((e,t)=>{let n=e.record,r=`### Result ${t+1} (score: ${e.score.toFixed(3)})`,i=[`- **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,ne?.get(n.id)??null].filter(Boolean).join(`
3036
+ `),{body:a,truncated:o}=X_(n,ae);return oe||=o,`${r}\n${i}\n\n${a}${o?`\n\n_Full content: use \`lookup\` on \`${n.sourcePath}\`._`:``}`}).join(`
3036
3037
 
3037
3038
  ---
3038
3039
 
3039
- `),ce=(f===`hybrid`?`hybrid (vector + keyword RRF)`:f===`keyword`?`keyword (FTS)`:`semantic (vector)`)+te,le=ev(T,e),A=le.length>0?`\n_Distinctive terms: ${le.map(e=>`\`${e}\``).join(`, `)}_`:``,j=await nv(n,T),ue=[];if(T.length===0)ue.push("`reindex` — no results found, index may be stale"),ue.push("`find` — try federated search with glob/regex");else{let e=T[0]?.record.sourcePath;e&&ue.push(`\`lookup\` — see all chunks from \`${e}\``),ue.push("`symbol` — resolve a specific symbol from the results"),ue.push("`compact` — compress a result file for focused reading")}let de=[re?`${re}\n\n`:``,j?`${j}\n\n`:``,se,`\n\n---\n_Search mode: ${ce} | ${T.length} results_${A}`,`\n_Next: ${ue.join(` | `)}_`],fe=O+de.join(``),pe=!1;if(b){let e=kn(fe,b);pe=e!==fe,fe=e}pe||=oe;let me=T.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}:{}})),he=[re,j].filter(e=>!!e),ge=rt({text:fe,query:e,searchMode:f,limit:d,results:me,durationMs:Date.now()-C,truncated:pe,caveats:he}),_e=zl(ge.summary),ve=new Set,M=[];for(let e of T){if(e.record.origin!==`curated`||e.record.sourcePath.startsWith(`[`))continue;let t=Ad(e.record.sourcePath);if(!t)continue;let n=Od(t,e.record.headingPath??t);n&&!ve.has(n.uri)&&(ve.add(n.uri),M.push(n))}return{content:[{type:`text`,text:Bl(ge.summary,_e)},...M],isError:!ge.ok,structuredContent:{...ge.data??{results:[],totalResults:0,searchMode:f,query:e},ref:_e}}}catch(t){U_.error(`Search failed`,N(t));let n=rt({text:`Search failed: ${t instanceof Error?t.message:String(t)}`,query:e??``,searchMode:f??`hybrid`,limit:d,results:[],durationMs:Date.now()-C}),r=zl(n.summary);return{content:[{type:`text`,text:Bl(n.summary,r)}],structuredContent:{...n.data??{results:[],totalResults:0,searchMode:f??`hybrid`,query:e??``},ref:r}}}})}const iv=M(`tools`);function av(e,t,n){let r=W(`session_digest`);e.registerTool(`session_digest`,{title:r.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:R.enum([`tools`,`stash`,`all`]).default(`all`).describe(`What to include: tools (replay only), stash (stash + checkpoints only), or all`),since:R.string().optional().describe(`ISO timestamp — only include activity after this time`),last:R.number().min(1).max(500).optional().describe(`Max replay entries to consider (default: 50)`),focus:R.string().optional().describe(`Focus query — prioritize entries matching this topic`),mode:R.enum([`deterministic`,`sampling`]).default(`deterministic`).describe(`Summary mode: deterministic (fast, template-based) or sampling (LLM-assisted, richer)`),token_budget:R.number().min(100).max(8e3).default(2e3).describe(`Target token budget for the digest output`),persist:R.boolean().default(!0).describe(`Auto-save digest to stash for crash recovery`)},annotations:r.annotations},J(`session_digest`,async({scope:e,since:r,last:i,focus:a,mode:o,token_budget:s,persist:c})=>{try{let l={scope:e,since:r,last:i,focus:a,mode:o,tokenBudget:s,persist:c},u=t?{stateStore:t}:void 0;return{content:[{type:`text`,text:(o===`sampling`&&n?.available?await gn(l,async(e,t,r)=>(await n.createMessage({prompt:e,systemPrompt:t,maxTokens:r})).text,u):hn(l,u)).digest}]}}catch(e){return iv.error(`Session digest failed`,N(e)),q(`INTERNAL`,`Session digest failed: ${e instanceof Error?e.message:String(e)}`)}}))}const ov=1e4,sv={defaultTtlSeconds:300,defaultLeaseTtlMinutes:10,globalEnabled:!1};function cv(e){return e??sv}function lv(e,t){let n=e.trim();if(!n)throw Error(`${t} is required`);return n}function uv(e,t,n){let r=lv(e,t);if(r.length>n)throw Error(`${t} exceeds max length of ${n}`);return r}function dv(e,t){if(!Number.isFinite(e)||e<=0)throw Error(`${t} must be greater than 0`);return Math.trunc(e)}function fv(e,t=!1,n){lv(e,`workspace`);let r=cv(n);if(!t)return e;if(!r.globalEnabled)throw Error(`Global signal scope is disabled`);return`__global__`}function pv(e,t,n){let r=cv(n),i=fv(t.workspace,t.global??!1,r),a=uv(t.key,`key`,500),o=uv(t.value,`value`,ov),s=t.agent?uv(t.agent,`agent`,500):void 0,c=dv(t.ttlSeconds??r.defaultTtlSeconds,`ttlSeconds`);return e.signalPost(i,a,o,s,c)}function mv(e,t,n){let r=lv(t,`workspace`),i=uv(n,`key`,500);return e.signalGet(r,i)}function hv(e,t){let n=lv(t,`workspace`);return e.signalList(n)}function gv(e,t,n){let r=lv(t,`workspace`),i=n===void 0?void 0:uv(n,`key`,500);return e.signalClear(r,i)}function _v(e,t,n){let r=cv(n),i=uv(t.resource,`resource`,500),a=uv(t.holder,`holder`,500),o=lv(t.workspace,`workspace`),s=t.intent?uv(t.intent,`intent`,ov):void 0,c=dv(t.ttlMinutes??r.defaultLeaseTtlMinutes,`ttlMinutes`);if(c>60)throw Error(`ttlMinutes exceeds max of 60`);let l=e.leaseAcquire(i,a,o,s,c),u=e.leaseGet(i,o);return u?{acquired:l,holder:u.holder,expiresAt:u.expiresAt}:{acquired:l}}function vv(e,t,n,r){let i=lv(t,`workspace`),a=uv(n,`resource`,500),o=uv(r,`holder`,500);return e.leaseRelease(a,o,i)}function yv(e,t){let n=lv(t,`workspace`);return e.leaseList(n)}const bv=M(`tools:signal`);function xv(e){return JSON.stringify(e,null,2)}function Sv(e,t,n){let r=W(`signal`),i={...sv,...n};e.registerTool(`signal`,{title:r.title,description:`Inter-agent signaling and lease coordination`,inputSchema:{action:R.enum([`post`,`get`,`list`,`clear`,`lease`,`unlease`,`leases`]).describe(`Signal action to perform`),workspace:R.string().describe(`Workspace identifier (required)`),key:R.string().optional().describe(`Signal key (for post/get/clear)`),value:R.string().optional().describe(`Signal value (for post)`),agent:R.string().optional().describe(`Agent identifier`),resource:R.string().optional().describe(`Resource path (for lease/unlease)`),holder:R.string().optional().describe(`Lease holder ID (for lease/unlease)`),intent:R.string().optional().describe(`What the holder plans to do`),ttl:R.number().optional().describe(`TTL (seconds for signals, minutes for leases)`),global:R.boolean().optional().describe(`Use global scope (default: false)`)},annotations:r.annotations},J(`signal`,async({action:e,workspace:n,key:r,value:a,agent:o,resource:s,holder:c,intent:l,ttl:u,global:d})=>{try{switch(e){case`post`:{if(!r||a===void 0)throw Error(`key and value are required for post`);let e=pv(t,{workspace:n,key:r,value:a,agent:o,ttlSeconds:u,global:d},i);return{content:[{type:`text`,text:xv({id:e})}],structuredContent:{id:e}}}case`get`:{if(!r)throw Error(`key is required for get`);let e=mv(t,fv(n,d??!1,i),r);return{content:[{type:`text`,text:e.length===0?`[]`:xv(e)}],structuredContent:{signals:e}}}case`list`:{let e=hv(t,fv(n,d??!1,i));return{content:[{type:`text`,text:e.length===0?`[]`:xv(e)}],structuredContent:{signals:e}}}case`clear`:{let e=gv(t,fv(n,d??!1,i),r);return{content:[{type:`text`,text:xv({cleared:e})}],structuredContent:{cleared:e}}}case`lease`:{if(!s||!c)throw Error(`resource and holder are required for lease`);let e=_v(t,{resource:s,holder:c,workspace:n,intent:l,ttlMinutes:u},i);return{content:[{type:`text`,text:xv(e)}],structuredContent:e}}case`unlease`:{if(!s||!c)throw Error(`resource and holder are required for unlease`);let e=vv(t,n,s,c);return{content:[{type:`text`,text:xv({released:e})}],structuredContent:{released:e}}}case`leases`:{let e=yv(t,n);return{content:[{type:`text`,text:e.length===0?`[]`:xv(e)}],structuredContent:{leases:e}}}}}catch(e){return bv.error(`Signal operation failed`,N(e)),q(`INTERNAL`,`Signal operation failed: ${e instanceof Error?e.message:String(e)}`)}}))}function Cv(e,t){return e.length<=t?e:e.slice(0,t)}function wv(e){if(!e)return 0;let t=Date.parse(e);return Number.isNaN(t)?0:t}async function Tv(e,t,n=d){if(!e||!t)return null;try{let[r,i,o]=await Promise.all([e.list({category:`lessons`,limit:200,orderBy:`updated`,order:`desc`}),e.list({category:`conventions`,limit:200,orderBy:`updated`,order:`desc`}),e.list({category:`session`,limit:200,orderBy:`updated`,order:`desc`})]),s=r.filter(e=>e.tags.includes(`lesson`)).map(e=>{let r=t.memoryMetaGet(e.path);return!r||r.supersededBy!=null?null:{entry:e,confidence:c(r.confidence,r.lastAccessedAt,r.createdAt,n)}}).filter(e=>e!==null).sort((e,t)=>t.confidence-e.confidence).slice(0,3);return{lessons:await Promise.all(s.map(async({entry:t,confidence:n})=>{let r=a((await e.read(t.path)).content);return{title:t.title,insight:Cv(r.insight??``,150),confidence:n}})),conventions:i.map(e=>({entry:e,lastAccessedAt:t.memoryMetaGet(e.path)?.lastAccessedAt??null})).sort((e,t)=>wv(t.lastAccessedAt)-wv(e.lastAccessedAt)).slice(0,2).map(({entry:e})=>({title:e.title,preview:e.contentPreview})),checkpoint:o.map(e=>({entry:e,lastAccessedAt:t.memoryMetaGet(e.path)?.lastAccessedAt??null})).sort((e,t)=>wv(t.lastAccessedAt)-wv(e.lastAccessedAt)).map(({entry:e})=>Cv(e.contentPreview,200))[0]??null}}catch{return null}}const Ev=M(`tools`),Dv=14400*1e3,Ov={includePrelude:R.boolean().default(!1).describe(`Include session prelude with top lessons, conventions, and last checkpoint`)};function kv(e,t,n,r=15e3){let i,a=new Promise(e=>{i=setTimeout(()=>{Ev.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),Ev.warn(`Status sub-operation "${n}" failed: ${e instanceof Error?e.message:String(e)}`),{value:t,timedOut:!1})),a])}function Av(e){return e.onboarded?e.indexStale?{kind:`reindex`,reason:`Index stale. Run reindex() to update.`}:e.contextPressure>70?{kind:`handoff`,reason:`Context pressure high. Consider session handoff.`}:{kind:`proceed`,reason:`Ready to work.`}:{kind:`onboard`,reason:`Index not initialized. Run onboard({ path: "." }) first.`}}function jv(){let e=ur.get(),t=lr.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(`
3040
+ `),ce=(f===`hybrid`?`hybrid (vector + keyword RRF)`:f===`keyword`?`keyword (FTS)`:`semantic (vector)`)+te,le=tv(T,e),A=le.length>0?`\n_Distinctive terms: ${le.map(e=>`\`${e}\``).join(`, `)}_`:``,j=await rv(n,T),ue=[];if(T.length===0)ue.push("`reindex` — no results found, index may be stale"),ue.push("`find` — try federated search with glob/regex");else{let e=T[0]?.record.sourcePath;e&&ue.push(`\`lookup\` — see all chunks from \`${e}\``),ue.push("`symbol` — resolve a specific symbol from the results"),ue.push("`compact` — compress a result file for focused reading")}let de=[re?`${re}\n\n`:``,j?`${j}\n\n`:``,se,`\n\n---\n_Search mode: ${ce} | ${T.length} results_${A}`,`\n_Next: ${ue.join(` | `)}_`],fe=O+de.join(``),pe=!1;if(b){let e=kn(fe,b);pe=e!==fe,fe=e}pe||=oe;let me=T.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}:{}})),he=[re,j].filter(e=>!!e),ge=rt({text:fe,query:e,searchMode:f,limit:d,results:me,durationMs:Date.now()-C,truncated:pe,caveats:he}),_e=zl(ge.summary),ve=new Set,M=[];for(let e of T){if(e.record.origin!==`curated`||e.record.sourcePath.startsWith(`[`))continue;let t=Ad(e.record.sourcePath);if(!t)continue;let n=Od(t,e.record.headingPath??t);n&&!ve.has(n.uri)&&(ve.add(n.uri),M.push(n))}return{content:[{type:`text`,text:Bl(ge.summary,_e)},...M],isError:!ge.ok,structuredContent:{...ge.data??{results:[],totalResults:0,searchMode:f,query:e},ref:_e}}}catch(t){W_.error(`Search failed`,N(t));let n=rt({text:`Search failed: ${t instanceof Error?t.message:String(t)}`,query:e??``,searchMode:f??`hybrid`,limit:d,results:[],durationMs:Date.now()-C}),r=zl(n.summary);return{content:[{type:`text`,text:Bl(n.summary,r)}],structuredContent:{...n.data??{results:[],totalResults:0,searchMode:f??`hybrid`,query:e??``},ref:r}}}})}const av=M(`tools`);function ov(e,t,n){let r=W(`session_digest`);e.registerTool(`session_digest`,{title:r.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:R.enum([`tools`,`stash`,`all`]).default(`all`).describe(`What to include: tools (replay only), stash (stash + checkpoints only), or all`),since:R.string().optional().describe(`ISO timestamp — only include activity after this time`),last:R.number().min(1).max(500).optional().describe(`Max replay entries to consider (default: 50)`),focus:R.string().optional().describe(`Focus query — prioritize entries matching this topic`),mode:R.enum([`deterministic`,`sampling`]).default(`deterministic`).describe(`Summary mode: deterministic (fast, template-based) or sampling (LLM-assisted, richer)`),token_budget:R.number().min(100).max(8e3).default(2e3).describe(`Target token budget for the digest output`),persist:R.boolean().default(!0).describe(`Auto-save digest to stash for crash recovery`)},annotations:r.annotations},J(`session_digest`,async({scope:e,since:r,last:i,focus:a,mode:o,token_budget:s,persist:c})=>{try{let l={scope:e,since:r,last:i,focus:a,mode:o,tokenBudget:s,persist:c},u=t?{stateStore:t}:void 0;return{content:[{type:`text`,text:(o===`sampling`&&n?.available?await gn(l,async(e,t,r)=>(await n.createMessage({prompt:e,systemPrompt:t,maxTokens:r})).text,u):hn(l,u)).digest}]}}catch(e){return av.error(`Session digest failed`,N(e)),q(`INTERNAL`,`Session digest failed: ${e instanceof Error?e.message:String(e)}`)}}))}const sv=1e4,cv={defaultTtlSeconds:300,defaultLeaseTtlMinutes:10,globalEnabled:!1};function lv(e){return e??cv}function uv(e,t){let n=e.trim();if(!n)throw Error(`${t} is required`);return n}function dv(e,t,n){let r=uv(e,t);if(r.length>n)throw Error(`${t} exceeds max length of ${n}`);return r}function fv(e,t){if(!Number.isFinite(e)||e<=0)throw Error(`${t} must be greater than 0`);return Math.trunc(e)}function pv(e,t=!1,n){uv(e,`workspace`);let r=lv(n);if(!t)return e;if(!r.globalEnabled)throw Error(`Global signal scope is disabled`);return`__global__`}function mv(e,t,n){let r=lv(n),i=pv(t.workspace,t.global??!1,r),a=dv(t.key,`key`,500),o=dv(t.value,`value`,sv),s=t.agent?dv(t.agent,`agent`,500):void 0,c=fv(t.ttlSeconds??r.defaultTtlSeconds,`ttlSeconds`);return e.signalPost(i,a,o,s,c)}function hv(e,t,n){let r=uv(t,`workspace`),i=dv(n,`key`,500);return e.signalGet(r,i)}function gv(e,t){let n=uv(t,`workspace`);return e.signalList(n)}function _v(e,t,n){let r=uv(t,`workspace`),i=n===void 0?void 0:dv(n,`key`,500);return e.signalClear(r,i)}function vv(e,t,n){let r=lv(n),i=dv(t.resource,`resource`,500),a=dv(t.holder,`holder`,500),o=uv(t.workspace,`workspace`),s=t.intent?dv(t.intent,`intent`,sv):void 0,c=fv(t.ttlMinutes??r.defaultLeaseTtlMinutes,`ttlMinutes`);if(c>60)throw Error(`ttlMinutes exceeds max of 60`);let l=e.leaseAcquire(i,a,o,s,c),u=e.leaseGet(i,o);return u?{acquired:l,holder:u.holder,expiresAt:u.expiresAt}:{acquired:l}}function yv(e,t,n,r){let i=uv(t,`workspace`),a=dv(n,`resource`,500),o=dv(r,`holder`,500);return e.leaseRelease(a,o,i)}function bv(e,t){let n=uv(t,`workspace`);return e.leaseList(n)}const xv=M(`tools:signal`);function Sv(e){return JSON.stringify(e,null,2)}function Cv(e,t,n){let r=W(`signal`),i={...cv,...n};e.registerTool(`signal`,{title:r.title,description:`Inter-agent signaling and lease coordination`,inputSchema:{action:R.enum([`post`,`get`,`list`,`clear`,`lease`,`unlease`,`leases`]).describe(`Signal action to perform`),workspace:R.string().describe(`Workspace identifier (required)`),key:R.string().optional().describe(`Signal key (for post/get/clear)`),value:R.string().optional().describe(`Signal value (for post)`),agent:R.string().optional().describe(`Agent identifier`),resource:R.string().optional().describe(`Resource path (for lease/unlease)`),holder:R.string().optional().describe(`Lease holder ID (for lease/unlease)`),intent:R.string().optional().describe(`What the holder plans to do`),ttl:R.number().optional().describe(`TTL (seconds for signals, minutes for leases)`),global:R.boolean().optional().describe(`Use global scope (default: false)`)},annotations:r.annotations},J(`signal`,async({action:e,workspace:n,key:r,value:a,agent:o,resource:s,holder:c,intent:l,ttl:u,global:d})=>{try{switch(e){case`post`:{if(!r||a===void 0)throw Error(`key and value are required for post`);let e=mv(t,{workspace:n,key:r,value:a,agent:o,ttlSeconds:u,global:d},i);return{content:[{type:`text`,text:Sv({id:e})}],structuredContent:{id:e}}}case`get`:{if(!r)throw Error(`key is required for get`);let e=hv(t,pv(n,d??!1,i),r);return{content:[{type:`text`,text:e.length===0?`[]`:Sv(e)}],structuredContent:{signals:e}}}case`list`:{let e=gv(t,pv(n,d??!1,i));return{content:[{type:`text`,text:e.length===0?`[]`:Sv(e)}],structuredContent:{signals:e}}}case`clear`:{let e=_v(t,pv(n,d??!1,i),r);return{content:[{type:`text`,text:Sv({cleared:e})}],structuredContent:{cleared:e}}}case`lease`:{if(!s||!c)throw Error(`resource and holder are required for lease`);let e=vv(t,{resource:s,holder:c,workspace:n,intent:l,ttlMinutes:u},i);return{content:[{type:`text`,text:Sv(e)}],structuredContent:e}}case`unlease`:{if(!s||!c)throw Error(`resource and holder are required for unlease`);let e=yv(t,n,s,c);return{content:[{type:`text`,text:Sv({released:e})}],structuredContent:{released:e}}}case`leases`:{let e=bv(t,n);return{content:[{type:`text`,text:e.length===0?`[]`:Sv(e)}],structuredContent:{leases:e}}}}}catch(e){return xv.error(`Signal operation failed`,N(e)),q(`INTERNAL`,`Signal operation failed: ${e instanceof Error?e.message:String(e)}`)}}))}function wv(e,t){return e.length<=t?e:e.slice(0,t)}function Tv(e){if(!e)return 0;let t=Date.parse(e);return Number.isNaN(t)?0:t}async function Ev(e,t,n=d){if(!e||!t)return null;try{let[r,i,o]=await Promise.all([e.list({category:`lessons`,limit:200,orderBy:`updated`,order:`desc`}),e.list({category:`conventions`,limit:200,orderBy:`updated`,order:`desc`}),e.list({category:`session`,limit:200,orderBy:`updated`,order:`desc`})]),s=r.filter(e=>e.tags.includes(`lesson`)).map(e=>{let r=t.memoryMetaGet(e.path);return!r||r.supersededBy!=null?null:{entry:e,confidence:c(r.confidence,r.lastAccessedAt,r.createdAt,n)}}).filter(e=>e!==null).sort((e,t)=>t.confidence-e.confidence).slice(0,3);return{lessons:await Promise.all(s.map(async({entry:t,confidence:n})=>{let r=a((await e.read(t.path)).content);return{title:t.title,insight:wv(r.insight??``,150),confidence:n}})),conventions:i.map(e=>({entry:e,lastAccessedAt:t.memoryMetaGet(e.path)?.lastAccessedAt??null})).sort((e,t)=>Tv(t.lastAccessedAt)-Tv(e.lastAccessedAt)).slice(0,2).map(({entry:e})=>({title:e.title,preview:e.contentPreview})),checkpoint:o.map(e=>({entry:e,lastAccessedAt:t.memoryMetaGet(e.path)?.lastAccessedAt??null})).sort((e,t)=>Tv(t.lastAccessedAt)-Tv(e.lastAccessedAt)).map(({entry:e})=>wv(e.contentPreview,200))[0]??null}}catch{return null}}const Dv=M(`tools`),Ov=14400*1e3,kv={includePrelude:R.boolean().default(!1).describe(`Include session prelude with top lessons, conventions, and last checkpoint`)};function Av(e,t,n,r=15e3){let i,a=new Promise(e=>{i=setTimeout(()=>{Dv.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),Dv.warn(`Status sub-operation "${n}" failed: ${e instanceof Error?e.message:String(e)}`),{value:t,timedOut:!1})),a])}function jv(e){return e.onboarded?e.indexStale?{kind:`reindex`,reason:`Index stale. Run reindex() to update.`}:e.contextPressure>70?{kind:`handoff`,reason:`Context pressure high. Consider session handoff.`}:{kind:`proceed`,reason:`Ready to work.`}:{kind:`onboard`,reason:`Index not initialized. Run onboard({ path: "." }) first.`}}function Mv(){let e=ur.get(),t=lr.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(`
3040
3041
  `):` 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(`
3041
- `)}const Mv=5*6e4;let Nv=null,Pv=null;function Fv(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 Iv(){let e=Date.now();if(Nv&&e-Nv.ts<Mv)return Nv.value;try{let t=L(Wn(),`.copilot`,`.aikit-scaffold.json`);if(!P(t))return Nv={value:null,ts:e},null;let n=JSON.parse(F(t,`utf-8`)).version??null;return Nv={value:n,ts:e},n}catch{return Nv={value:null,ts:e},null}}function Lv(){let e=Date.now();if(Pv&&e-Pv.ts<Mv)return Pv.value;try{let t=L(process.cwd(),`.github`,`.aikit-scaffold.json`);if(!P(t))return Pv={value:null,ts:e},null;let n=JSON.parse(F(t,`utf-8`)).version??null;return Pv={value:n,ts:e},n}catch{return Pv={value:null,ts:e},null}}function Rv(e){let t=W(`status`);e.registerTool(`status`,{title:t.title,description:`Get the current status and statistics of the AI Kit index.`,inputSchema:Ov,annotations:t.annotations},J(`status`,async()=>{let e=ae(),t=Iv(),n=Lv(),r=t!=null&&t!==e,i=n!=null&&n!==e,a=[`## AI Kit Status`,``,`⏳ **AI Kit is initializing** — index stats will be available shortly.`,``,`### Runtime`,`- **Tree-sitter (WASM)**: ${ur.get()?`✅ Available (AST analysis)`:`⚠ Unavailable (regex fallback)`}`,``,`### Version`,`- **Server**: ${e}`,`- **Scaffold (user)**: ${t??`not installed`}`,`- **Scaffold (workspace)**: ${n??`not installed`}`];if(r||i){let o=oe(),s=[];r&&s.push(`user scaffold v${t}`),i&&s.push(`workspace scaffold v${n}`);let c=s.join(`, `);o.state===`success`?a.push(``,`### ✅ Upgrade Applied`,`- Server v${e} — ${c} auto-upgraded successfully.`,`- _Restart the MCP server to use the updated version._`):o.state===`pending`?a.push(``,`### ⏳ Upgrade In Progress`,`- Server v${e} ≠ ${c}`,`- Auto-upgrade is running in the background…`):o.state===`failed`?(ie(),a.push(``,`### ⬆ Upgrade Available (auto-upgrade failed, retrying)`,`- Server v${e} ≠ ${c}`,`- Error: ${o.error??`unknown`}`)):(ie(),a.push(``,`### ⬆ Upgrade Available`,`- Server v${e} ≠ ${c}`,`- Auto-upgrade triggered — check again shortly.`))}let o={totalRecords:0,totalFiles:0,lastIndexedAt:null,onboarded:!1,onboardDir:``,contentTypes:{},wasmAvailable:!!ur.get(),wasmDiagnostics:lr.get(),graphStats:null,curatedCount:0,serverVersion:e,scaffoldVersion:t??null,workspaceScaffoldVersion:n??null,upgradeAvailable:r||i,contextPressure:0,nextAction:Av({onboarded:!1,indexStale:!1,contextPressure:0})};return{content:[{type:`text`,text:a.join(`
3042
- `)}],structuredContent:o}}))}function zv(e,t,n,r,i,a,o,s,c){let l=W(`status`);e.registerTool(`status`,{title:l.title,description:`Get the current status and statistics of the AI Kit index.`,inputSchema:Ov,annotations:l.annotations},J(`status`,async({includePrelude:e=!1})=>{let l=[];try{let[u,d]=await Promise.all([kv(t.getStats(),{totalRecords:0,totalFiles:0,lastIndexedAt:null,contentTypeBreakdown:{}},`store.getStats`),kv(t.listSourcePaths(),[],`store.listSourcePaths`)]),f=u.value;u.timedOut&&l.push(`⚠ Index stats timed out — values may be incomplete`);let p=d.value;d.timedOut&&l.push(`⚠ File listing timed out`);let m=null,h=0,g=[`## AI Kit Status`,``,`- **Total Records**: ${f.totalRecords}`,`- **Total Files**: ${f.totalFiles}`,`- **Last Indexed**: ${f.lastIndexedAt??`Never`}`,``,`### Content Types`,...Object.entries(f.contentTypeBreakdown).map(([e,t])=>`- ${e}: ${t}`),``,`### Indexed Files`,...p.slice(0,50).map(e=>`- ${e}`),p.length>50?`\n... and ${p.length-50} more files`:``];if(n)try{let e=await kv(n.getStats(),{nodeCount:0,edgeCount:0,nodeTypes:{},edgeTypes:{}},`graphStore.getStats`);if(e.timedOut)l.push(`⚠ Graph stats timed out`),g.push(``,`### Knowledge Graph`,`- Graph stats timed out`);else{let t=e.value;m={nodes:t.nodeCount,edges:t.edgeCount},g.push(``,`### Knowledge Graph`,`- **Nodes**: ${t.nodeCount}`,`- **Edges**: ${t.edgeCount}`,...Object.entries(t.nodeTypes).map(([e,t])=>` - ${e}: ${t}`));try{let e=await kv(n.validate(),{valid:!0,danglingEdges:[],orphanNodes:[],stats:{nodeCount:0,edgeCount:0,nodeTypes:{},edgeTypes:{}}},`graphStore.validate`);if(!e.timedOut){let t=e.value;t.valid||g.push(`- **⚠ Integrity Issues**: ${t.danglingEdges.length} dangling edges`),t.orphanNodes.length>0&&g.push(`- **Orphan nodes**: ${t.orphanNodes.length}`)}}catch{}}}catch{g.push(``,`### Knowledge Graph`,`- Graph store unavailable`)}let _=a?.onboardDir??``,v=P(_),y=i?.onboardComplete||v;if(g.push(``,`### Onboard Status`,y?`- ✅ Complete${i?.onboardTimestamp?` (last: ${i.onboardTimestamp})`:``}`:'- ❌ Not run — call `onboard({ path: "." })` to analyze the codebase',`- **Onboard Directory**: \`${_}\``),r)try{let e=await kv(r.count(),0,`curated.count`);e.timedOut?(l.push(`⚠ Curated knowledge count timed out`),g.push(``,`### Curated Knowledge`,`- Listing timed out`)):(h=e.value,g.push(``,`### Curated Knowledge`,h>0?`- ${h} entries`:'- Empty — use `knowledge({ action: "remember", ... })` to persist decisions'))}catch{g.push(``,`### Curated Knowledge`,`- Unable to read curated entries`)}let b=Fv(f.totalRecords,m?.nodes??0,m?.edges??0,h),x=f.lastIndexedAt?new Date(f.lastIndexedAt).getTime():0,S=x>0?Date.now()-x:1/0,C=Av({onboarded:y,indexStale:y&&S>1440*60*1e3,contextPressure:b});g.push(``),g.push(`## 📊 Context Pressure: ${b}/100`),b>=80?g.push(`⚠️ High pressure — consider pruning stale entries or compacting context.`):b>=50?g.push(`ℹ️ Moderate pressure — AI Kit memory is well-populated.`):g.push(`✅ Low pressure — plenty of headroom for more content.`);let w=0;if(f.lastIndexedAt){w=new Date(f.lastIndexedAt).getTime();let e=(Date.now()-w)/(1e3*60*60);g.push(``,`### Index Freshness`,e>24?o===`smart`?`- ⚠ Last indexed ${Math.floor(e)}h ago — smart indexing will refresh automatically`:`- ⚠ Last indexed ${Math.floor(e)}h ago — may be stale. Run \`reindex({})\``:`- ✅ Last indexed ${e<1?`less than 1h`:`${Math.floor(e)}h`} ago`)}g.push(``,`### Next Action`,`- **${C.kind}**: ${C.reason}`);let T=null,E=t;if(typeof E.getDiagnostics==`function`)try{let e=E.getDiagnostics();T={adapterType:e.adapterType,vectorSearchEnabled:e.vectorSearchEnabled,ftsEnabled:e.ftsEnabled,degradedMode:e.degradedMode,dbPath:e.dbPath,dbSizeBytes:e.dbSizeBytes,embeddingDim:e.embeddingDim,vectorDtype:e.vectorDtype},g.push(``,`### Storage`,`- **Backend**: ${a?.store?.backend??`unknown`}`,`- **Adapter**: ${T.adapterType}`,`- **Vector search**: ${T.vectorSearchEnabled?`✅ enabled`:`⚠ disabled (FTS-only fallback)`}`,T.dbPath?`- **DB**: ${T.dbPath}`:``,T.dbSizeBytes==null?``:`- **DB size**: ${(T.dbSizeBytes/1024/1024).toFixed(2)} MB`,`- **Embedding dim**: ${T.embeddingDim}`,`- **Vector dtype**: ${T.vectorDtype}`)}catch{}if(o===`smart`)if(g.push(``,`### Smart Indexing`),s){let e=s();e?g.push(`- **Mode**: Smart (trickle)`,`- **Status**: ${e.running?`✅ Running`:`⏸ Stopped`}`,`- **Queue**: ${e.queueSize} files pending`,`- **Changed files**: ${e.changedFilesSize} detected`,`- **Interval**: ${Math.round(e.intervalMs/1e3)}s per batch of ${e.batchSize}`):g.push(`- **Mode**: Smart (trickle)`,`- **Status**: scheduler state unavailable (init may have failed)`)}else g.push(`- **Mode**: Smart (trickle) — scheduler state unavailable`);let D=0;{try{let e=a?.stateDir?I(a.stateDir,`stash`):null;if(e&&P(e)){let t=De(e).mtimeMs;t>w&&(w=t)}}catch{}let e=[];if(r)try{let t=h>0?await r.list({limit:5,orderBy:`updated`,order:`desc`}):[];for(let e of t){let t=new Date(e.updated||e.created).getTime();t>w&&(w=t)}e.push(...t)}catch{}if(D=w>0?Date.now()-w:0,D>=Dv){let t=Math.floor(D/36e5);if(g.push(``,`### 🌅 Session Briefing`,`_${t}+ hours since last activity — here's what to pick up:_`,``),e.length>0){g.push(`**Recent decisions/notes:**`);for(let t of e)g.push(`- **${t.title}** (${t.category??`note`}) — ${(t.contentPreview??``).slice(0,80)}…`)}g.push(``,`**Suggested next steps:**`,'- `search({ query: "SESSION CHECKPOINT", origin: "curated" })` — find your last checkpoint',"- `restore({})` — resume from a saved checkpoint",'- `knowledge({ action: "list" })` — browse all stored knowledge')}}g.push(``,`### Runtime`,jv());let O=fe.instance().getAll(),k=O.filter(e=>e.status!==`healthy`);if(k.length>0){g.push(``,`### ⚠️ Subsystem Health`);for(let e of k){let t=Math.round((Date.now()-e.since)/1e3);g.push(`- **${e.name}**: ${e.status} (${t}s ago${e.reason?` — ${e.reason}`:``})`)}}else O.length>0&&g.push(``,`### ✅ Subsystem Health`,`- All ${O.length} subsystems healthy`);let ee=ue.getAll();if(ee.size>0){g.push(``,`### 🔌 Circuit Breakers`);for(let[e,t]of ee){let n=t.getState(),r=`- **${e}**: ${n===`closed`?`🟢`:n===`open`?`🔴`:`🟡`} ${n}`;if(n===`open`){let e=t.remainingCooldownMs();r+=` (recovery in ${Math.ceil(e/1e3)}s)`}g.push(r)}}let te=Iv(),ne=Lv(),re=ae(),se=te!=null&&te!==re,ce=ne!=null&&ne!==re;if(se||ce){let e=oe(),t=[];se&&t.push(`user scaffold v${te}`),ce&&t.push(`workspace scaffold v${ne}`);let n=t.join(`, `);e.state===`success`?g.push(``,`### ✅ Upgrade Applied`,`- Server v${re} — ${n} auto-upgraded successfully.`,`- _Restart the MCP server to use the updated version._`):e.state===`pending`?g.push(``,`### ⏳ Upgrade In Progress`,`- Server v${re} ≠ ${n}`,`- Auto-upgrade is running in the background…`):e.state===`failed`?(ie(),g.push(``,`### ⬆ Upgrade Available (auto-upgrade failed, retrying)`,`- Server v${re} ≠ ${n}`,`- Error: ${e.error??`unknown`}`)):(ie(),g.push(``,`### ⬆ Upgrade Available`,`- Server v${re} ≠ ${n}`,`- Auto-upgrade triggered — check again shortly.`))}l.length>0&&g.push(``,`### ⚠ Warnings`,...l.map(e=>`- ${e}`));let le=Wo();if(le.length>0){let e=le.sort((e,t)=>t.callCount-e.callCount);g.push(``,`### Tool Usage This Session`,``),g.push(`| Tool | Calls | Tokens In | Tokens Out | Errors | Avg Latency |`),g.push(`|------|-------|-----------|------------|--------|-------------|`);for(let t of e.slice(0,15)){let e=Math.round(t.totalInputChars/4),n=Math.round(t.totalOutputChars/4),r=Math.round(t.totalDurationMs/t.callCount);g.push(`| ${t.tool} | ${t.callCount} | ${e.toLocaleString()} | ${n.toLocaleString()} | ${t.errorCount} | ${r}ms |`)}}let A=Bo();A.callCount>0&&(g.push(``),g.push(`### Session Token Usage`),g.push(`- Tool calls: ${A.callCount}`),g.push(`- Input chars: ${A.totalInputChars.toLocaleString()}`),g.push(`- Output chars: ${A.totalOutputChars.toLocaleString()}`),g.push(`- Est. input tokens: ${Math.round(A.totalInputChars/4).toLocaleString()}`),g.push(`- Est. total tokens: ${Math.round((A.totalInputChars+A.totalOutputChars)/4).toLocaleString()}`));let j=No();if(j.bufferSize>=10){let e=j.state===`healthy`?`🟢`:j.state===`degraded`?`🔴`:`🟡`;g.push(``,`### Auto-GC: ${e} ${j.state}`),g.push(`- p95 latency: ${j.p95}ms | buffer: ${j.bufferSize} samples`),j.gcCount>0&&g.push(`- GC cycles triggered: ${j.gcCount}`)}let de=g.join(`
3043
- `),pe=e||D>=Dv?await Tv(r,c):void 0,me={totalRecords:f.totalRecords,totalFiles:f.totalFiles,lastIndexedAt:f.lastIndexedAt??null,onboarded:y,onboardDir:_,contentTypes:f.contentTypeBreakdown,wasmAvailable:!!ur.get(),wasmDiagnostics:lr.get(),graphStats:m,curatedCount:h,serverVersion:re,scaffoldVersion:te??null,workspaceScaffoldVersion:ne??null,upgradeAvailable:se||ce,storeBackend:a?.store?.backend,storeDiagnostics:T??null,contextPressure:b,nextAction:C,sessionTokens:{callCount:A.callCount,totalInputChars:A.totalInputChars,totalOutputChars:A.totalOutputChars,estInputTokens:Math.round(A.totalInputChars/4),estTotalTokens:Math.round((A.totalInputChars+A.totalOutputChars)/4),startTime:A.startTime},...pe===void 0?{}:{prelude:pe}};return{content:[{type:`text`,text:de+(o===`smart`?"\n\n---\n_Next: Use `search` to query indexed content or `graph({action:'find_nodes', name_pattern:'<top-level-module>'})` → then `graph({action:'neighbors', node_id})` for relationships. Smart indexing handles updates automatically._":"\n\n---\n_Next: Use `search` to query indexed content, `graph({action:'find_nodes', name_pattern:'<top-level-module>'})` → then `graph({action:'neighbors', node_id})` for relationships, or `reindex` to refresh the index._")}],structuredContent:me}}catch(e){return Ev.error(`Status failed`,N(e)),q(`INTERNAL`,`Status check failed: ${e instanceof Error?e.message:String(e)}`)}}))}const Bv=M(`tools`);function Vv(e){return e instanceof Error?(`code`in e?e.code:void 0)===`ENOENT`||e.message.startsWith(`File not found:`)||e.message.startsWith(`Path not found:`):!1}function Hv(e){let t=W(`web_search`);e.registerTool(`web_search`,{title:t.title,description:`PREFERRED web search — fans out to multiple keyless providers (DuckDuckGo + Bing-HTML + Mojeek) by default, returning a deduplicated, consensus-ranked union within a 10s deadline. Optional providers (SearXNG, Google, Brave, Bing API) join the fan-out automatically when their env vars are set. Pass one query or multiple for parallel searching.`,inputSchema:{queries:R.array(R.string().max(2e3)).min(1).max(5).describe('Search queries (1–5). Single: `["react hooks"]`. Multiple searched in parallel.'),limit:R.number().min(1).max(20).default(5).describe(`Max results per query`),site:R.string().optional().describe(`Restrict to domain (e.g., "docs.aws.amazon.com")`),provider:R.enum([`multi`,`duckduckgo`,`bing-html`,`mojeek`,`searxng`,`google`,`brave`,`bing`]).optional().describe("Search provider. Defaults to env AIKIT_SEARCH_PROVIDER, then `multi` (fan-out). Single keyless: `duckduckgo`, `bing-html`, `mojeek`. Self-hosted: `searxng` (requires SEARXNG_URL). Keyed APIs: `google` (GOOGLE_API_KEY+GOOGLE_CSE_ID), `brave` (BRAVE_API_KEY), `bing` (BING_API_KEY). Missing keys auto-fall back to duckduckgo.")},annotations:t.annotations},J(`web_search`,async({queries:e,limit:t,site:n,provider:r})=>{let i=e,a=async e=>{let i=await Pn({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(`
3044
- `)};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 Bv.error(`Web search failed`,N(e)),q(`INTERNAL`,`Web search failed: ${e instanceof Error?e.message:String(e)}`)}let o=await Promise.allSettled(i.map(e=>a(e))),s=[],c=0;for(let e=0;e<o.length;e++){let t=o[e];if(t.status===`fulfilled`)s.push(t.value);else{c++;let n=t.reason instanceof Error?t.reason.message:String(t.reason);Bv.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(`
3045
-
3046
- `);return c===o.length?q(`INTERNAL`,u):{content:[{type:`text`,text:u}]}}))}function Uv(e){let t=W(`http`);e.registerTool(`http`,{title:t.title,description:`Make HTTP requests (GET/POST/PUT/PATCH/DELETE/HEAD) for API testing. Returns status, headers, and formatted body with timing info.`,inputSchema:{url:R.string().url().describe(`Request URL (http/https only)`),method:R.enum([`GET`,`POST`,`PUT`,`PATCH`,`DELETE`,`HEAD`]).default(`GET`).describe(`HTTP method`),headers:R.record(R.string(),R.string()).optional().describe(`Request headers as key-value pairs`),body:R.string().optional().describe(`Request body (for POST/PUT/PATCH)`),timeout:R.number().min(1e3).max(6e4).default(15e3).describe(`Timeout in milliseconds`)},annotations:t.annotations},J(`http`,async({url:e,method:t,headers:n,body:r,timeout:i})=>{try{let a=await Dt({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(`
3047
- `)}]}}catch(e){return Bv.error(`HTTP request failed`,N(e)),q(`INTERNAL`,`HTTP request failed: ${e instanceof Error?e.message:String(e)}`)}}))}function Wv(e){let t=W(`regex_test`);e.registerTool(`regex_test`,{title:t.title,description:`Test a regex pattern against sample strings. Supports match, replace, and split modes.`,inputSchema:{pattern:R.string().max(500).describe(`Regex pattern (without delimiters)`),flags:R.string().max(10).regex(/^[gimsuy]*$/).default(``).describe(`Regex flags (g, i, m, s, etc.)`),test_strings:R.array(R.string().max(1e4)).max(50).describe(`Strings to test the pattern against`),mode:R.enum([`match`,`replace`,`split`]).default(`match`).describe(`Test mode`),replacement:R.string().optional().describe(`Replacement string (for replace mode)`)},annotations:t.annotations},J(`regex_test`,async({pattern:e,flags:t,test_strings:n,mode:r,replacement:i})=>{let a=tn({pattern:e,flags:t,testStrings:n,mode:r,replacement:i});if(!a.valid)return q(`VALIDATION`,`Invalid regex: ${a.error}`);let o=[`## Regex: \`/${a.pattern}/${a.flags}\``,``,`Mode: ${r}`,``];for(let e of a.results){if(o.push(`**Input:** \`${e.input}\``),o.push(`**Matched:** ${e.matched}`),e.matches)for(let t of e.matches){let e=t.groups.length>0?` groups: [${t.groups.join(`, `)}]`:``;o.push(` - "${t.full}" at index ${t.index}${e}`)}e.replaced!==void 0&&o.push(`**Result:** \`${e.replaced}\``),e.split&&o.push(`**Split:** ${JSON.stringify(e.split)}`),o.push(``)}return{content:[{type:`text`,text:o.join(`
3048
- `)}]}}))}function Gv(e){let t=W(`encode`);e.registerTool(`encode`,{title:t.title,description:`Encode, decode, or hash text. Supports base64, URL encoding, SHA-256, MD5, JWT decode, hex.`,inputSchema:{operation:R.enum([`base64_encode`,`base64_decode`,`url_encode`,`url_decode`,`sha256`,`md5`,`jwt_decode`,`hex_encode`,`hex_decode`]).describe(`Operation to perform`),input:R.string().max(1e6).describe(`Input text`)},annotations:t.annotations},J(`encode`,async({operation:e,input:t})=>{try{let n=ut({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 Bv.error(`Encode failed`,N(e)),q(`INTERNAL`,`Encode failed: ${e instanceof Error?e.message:String(e)}`)}}))}function Kv(e){let t=W(`measure`);e.registerTool(`measure`,{title:t.title,description:`Measure code complexity, line counts, and function counts for a file or directory. Returns per-file metrics sorted by complexity.`,outputSchema:zs,inputSchema:{path:R.string().describe(`File or directory path to measure`),extensions:R.array(R.string()).optional().describe(`File extensions to include (default: .ts,.tsx,.js,.jsx)`),include_hidden:R.boolean().optional().describe(`Include hidden trees such as .generated and .cache. Default false.`),max_tokens:R.number().min(100).max(5e4).optional().describe(`Maximum token budget for the response. When set, output is truncated to fit.`)},annotations:t.annotations},J(`measure`,async({path:e,extensions:t,include_hidden:n,max_tokens:r})=>{try{let i=await Lt({path:e,extensions:t,includeHidden:n}),a=[`## Code Metrics`,``,`**Files:** ${i.summary.totalFiles}`,`**Total lines:** ${i.summary.totalLines} (${i.summary.totalCodeLines} code)`,`**Functions:** ${i.summary.totalFunctions}`,`**Avg complexity:** ${i.summary.avgComplexity}`,`**Max complexity:** ${i.summary.maxComplexity.value} (${i.summary.maxComplexity.file})`,``,`### Top files by complexity`,``,`| File | Lines | Code | Complexity | Cognitive | Functions | Imports |`,`|------|-------|------|------------|-----------|-----------|---------|`];for(let e of i.files.slice(0,20)){let t=e.cognitiveComplexity===void 0?`—`:String(e.cognitiveComplexity);a.push(`| ${e.path} | ${e.lines.total} | ${e.lines.code} | ${e.complexity} | ${t} | ${e.functions} | ${e.imports} |`)}i.files.length>20&&a.push(``,`_...and ${i.files.length-20} more files_`);let o={summary:{totalFiles:i.summary.totalFiles,totalLines:i.summary.totalLines,totalCodeLines:i.summary.totalCodeLines,totalFunctions:i.summary.totalFunctions,avgComplexity:i.summary.avgComplexity,maxComplexity:{value:i.summary.maxComplexity.value,file:i.summary.maxComplexity.file}},files:i.files.map(e=>({path:e.path,lines:e.lines.total,code:e.lines.code,complexity:e.complexity,functions:e.functions}))};return{content:[{type:`text`,text:r?kn(a.join(`
3042
+ `)}const Nv=5*6e4;let Pv=null,Fv=null;function Iv(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 Lv(){let e=Date.now();if(Pv&&e-Pv.ts<Nv)return Pv.value;try{let t=L(Wn(),`.copilot`,`.aikit-scaffold.json`);if(!P(t))return Pv={value:null,ts:e},null;let n=JSON.parse(F(t,`utf-8`)).version??null;return Pv={value:n,ts:e},n}catch{return Pv={value:null,ts:e},null}}function Rv(){let e=Date.now();if(Fv&&e-Fv.ts<Nv)return Fv.value;try{let t=L(process.cwd(),`.github`,`.aikit-scaffold.json`);if(!P(t))return Fv={value:null,ts:e},null;let n=JSON.parse(F(t,`utf-8`)).version??null;return Fv={value:n,ts:e},n}catch{return Fv={value:null,ts:e},null}}function zv(e){let t=W(`status`);e.registerTool(`status`,{title:t.title,description:`Get the current status and statistics of the AI Kit index.`,inputSchema:kv,annotations:t.annotations},J(`status`,async()=>{let e=ae(),t=Lv(),n=Rv(),r=t!=null&&t!==e,i=n!=null&&n!==e,a=[`## AI Kit Status`,``,`⏳ **AI Kit is initializing** — index stats will be available shortly.`,``,`### Runtime`,`- **Tree-sitter (WASM)**: ${ur.get()?`✅ Available (AST analysis)`:`⚠ Unavailable (regex fallback)`}`,``,`### Version`,`- **Server**: ${e}`,`- **Scaffold (user)**: ${t??`not installed`}`,`- **Scaffold (workspace)**: ${n??`not installed`}`];if(r||i){let o=oe(),s=[];r&&s.push(`user scaffold v${t}`),i&&s.push(`workspace scaffold v${n}`);let c=s.join(`, `);o.state===`success`?a.push(``,`### ✅ Upgrade Applied`,`- Server v${e} — ${c} auto-upgraded successfully.`,`- _Restart the MCP server to use the updated version._`):o.state===`pending`?a.push(``,`### ⏳ Upgrade In Progress`,`- Server v${e} ≠ ${c}`,`- Auto-upgrade is running in the background…`):o.state===`failed`?(ie(),a.push(``,`### ⬆ Upgrade Available (auto-upgrade failed, retrying)`,`- Server v${e} ≠ ${c}`,`- Error: ${o.error??`unknown`}`)):(ie(),a.push(``,`### ⬆ Upgrade Available`,`- Server v${e} ≠ ${c}`,`- Auto-upgrade triggered — check again shortly.`))}let o={totalRecords:0,totalFiles:0,lastIndexedAt:null,onboarded:!1,onboardDir:``,contentTypes:{},wasmAvailable:!!ur.get(),wasmDiagnostics:lr.get(),graphStats:null,curatedCount:0,serverVersion:e,scaffoldVersion:t??null,workspaceScaffoldVersion:n??null,upgradeAvailable:r||i,contextPressure:0,nextAction:jv({onboarded:!1,indexStale:!1,contextPressure:0})};return{content:[{type:`text`,text:a.join(`
3043
+ `)}],structuredContent:o}}))}function Bv(e,t,n,r,i,a,o,s,c){let l=W(`status`);e.registerTool(`status`,{title:l.title,description:`Get the current status and statistics of the AI Kit index.`,inputSchema:kv,annotations:l.annotations},J(`status`,async({includePrelude:e=!1})=>{let l=[];try{let[u,d]=await Promise.all([Av(t.getStats(),{totalRecords:0,totalFiles:0,lastIndexedAt:null,contentTypeBreakdown:{}},`store.getStats`),Av(t.listSourcePaths(),[],`store.listSourcePaths`)]),f=u.value;u.timedOut&&l.push(`⚠ Index stats timed out — values may be incomplete`);let p=d.value;d.timedOut&&l.push(`⚠ File listing timed out`);let m=null,h=0,g=[`## AI Kit Status`,``,`- **Total Records**: ${f.totalRecords}`,`- **Total Files**: ${f.totalFiles}`,`- **Last Indexed**: ${f.lastIndexedAt??`Never`}`,``,`### Content Types`,...Object.entries(f.contentTypeBreakdown).map(([e,t])=>`- ${e}: ${t}`),``,`### Indexed Files`,...p.slice(0,50).map(e=>`- ${e}`),p.length>50?`\n... and ${p.length-50} more files`:``];if(n)try{let e=await Av(n.getStats(),{nodeCount:0,edgeCount:0,nodeTypes:{},edgeTypes:{}},`graphStore.getStats`);if(e.timedOut)l.push(`⚠ Graph stats timed out`),g.push(``,`### Knowledge Graph`,`- Graph stats timed out`);else{let t=e.value;m={nodes:t.nodeCount,edges:t.edgeCount},g.push(``,`### Knowledge Graph`,`- **Nodes**: ${t.nodeCount}`,`- **Edges**: ${t.edgeCount}`,...Object.entries(t.nodeTypes).map(([e,t])=>` - ${e}: ${t}`));try{let e=await Av(n.validate(),{valid:!0,danglingEdges:[],orphanNodes:[],stats:{nodeCount:0,edgeCount:0,nodeTypes:{},edgeTypes:{}}},`graphStore.validate`);if(!e.timedOut){let t=e.value;t.valid||g.push(`- **⚠ Integrity Issues**: ${t.danglingEdges.length} dangling edges`),t.orphanNodes.length>0&&g.push(`- **Orphan nodes**: ${t.orphanNodes.length}`)}}catch{}}}catch{g.push(``,`### Knowledge Graph`,`- Graph store unavailable`)}let _=a?.onboardDir??``,v=P(_),y=i?.onboardComplete||v;if(g.push(``,`### Onboard Status`,y?`- ✅ Complete${i?.onboardTimestamp?` (last: ${i.onboardTimestamp})`:``}`:'- ❌ Not run — call `onboard({ path: "." })` to analyze the codebase',`- **Onboard Directory**: \`${_}\``),r)try{let e=await Av(r.count(),0,`curated.count`);e.timedOut?(l.push(`⚠ Curated knowledge count timed out`),g.push(``,`### Curated Knowledge`,`- Listing timed out`)):(h=e.value,g.push(``,`### Curated Knowledge`,h>0?`- ${h} entries`:'- Empty — use `knowledge({ action: "remember", ... })` to persist decisions'))}catch{g.push(``,`### Curated Knowledge`,`- Unable to read curated entries`)}let b=Iv(f.totalRecords,m?.nodes??0,m?.edges??0,h),x=f.lastIndexedAt?new Date(f.lastIndexedAt).getTime():0,S=x>0?Date.now()-x:1/0,C=jv({onboarded:y,indexStale:y&&S>1440*60*1e3,contextPressure:b});g.push(``),g.push(`## 📊 Context Pressure: ${b}/100`),b>=80?g.push(`⚠️ High pressure — consider pruning stale entries or compacting context.`):b>=50?g.push(`ℹ️ Moderate pressure — AI Kit memory is well-populated.`):g.push(`✅ Low pressure — plenty of headroom for more content.`);let w=0;if(f.lastIndexedAt){w=new Date(f.lastIndexedAt).getTime();let e=(Date.now()-w)/(1e3*60*60);g.push(``,`### Index Freshness`,e>24?o===`smart`?`- ⚠ Last indexed ${Math.floor(e)}h ago — smart indexing will refresh automatically`:`- ⚠ Last indexed ${Math.floor(e)}h ago — may be stale. Run \`reindex({})\``:`- ✅ Last indexed ${e<1?`less than 1h`:`${Math.floor(e)}h`} ago`)}g.push(``,`### Next Action`,`- **${C.kind}**: ${C.reason}`);let T=null,E=t;if(typeof E.getDiagnostics==`function`)try{let e=E.getDiagnostics();T={adapterType:e.adapterType,vectorSearchEnabled:e.vectorSearchEnabled,ftsEnabled:e.ftsEnabled,degradedMode:e.degradedMode,dbPath:e.dbPath,dbSizeBytes:e.dbSizeBytes,embeddingDim:e.embeddingDim,vectorDtype:e.vectorDtype},g.push(``,`### Storage`,`- **Backend**: ${a?.store?.backend??`unknown`}`,`- **Adapter**: ${T.adapterType}`,`- **Vector search**: ${T.vectorSearchEnabled?`✅ enabled`:`⚠ disabled (FTS-only fallback)`}`,T.dbPath?`- **DB**: ${T.dbPath}`:``,T.dbSizeBytes==null?``:`- **DB size**: ${(T.dbSizeBytes/1024/1024).toFixed(2)} MB`,`- **Embedding dim**: ${T.embeddingDim}`,`- **Vector dtype**: ${T.vectorDtype}`)}catch{}if(o===`smart`)if(g.push(``,`### Smart Indexing`),s){let e=s();e?g.push(`- **Mode**: Smart (trickle)`,`- **Status**: ${e.running?`✅ Running`:`⏸ Stopped`}`,`- **Queue**: ${e.queueSize} files pending`,`- **Changed files**: ${e.changedFilesSize} detected`,`- **Interval**: ${Math.round(e.intervalMs/1e3)}s per batch of ${e.batchSize}`):g.push(`- **Mode**: Smart (trickle)`,`- **Status**: scheduler state unavailable (init may have failed)`)}else g.push(`- **Mode**: Smart (trickle) — scheduler state unavailable`);let D=0;{try{let e=a?.stateDir?I(a.stateDir,`stash`):null;if(e&&P(e)){let t=De(e).mtimeMs;t>w&&(w=t)}}catch{}let e=[];if(r)try{let t=h>0?await r.list({limit:5,orderBy:`updated`,order:`desc`}):[];for(let e of t){let t=new Date(e.updated||e.created).getTime();t>w&&(w=t)}e.push(...t)}catch{}if(D=w>0?Date.now()-w:0,D>=Ov){let t=Math.floor(D/36e5);if(g.push(``,`### 🌅 Session Briefing`,`_${t}+ hours since last activity — here's what to pick up:_`,``),e.length>0){g.push(`**Recent decisions/notes:**`);for(let t of e)g.push(`- **${t.title}** (${t.category??`note`}) — ${(t.contentPreview??``).slice(0,80)}…`)}g.push(``,`**Suggested next steps:**`,'- `search({ query: "SESSION CHECKPOINT", origin: "curated" })` — find your last checkpoint',"- `restore({})` — resume from a saved checkpoint",'- `knowledge({ action: "list" })` — browse all stored knowledge')}}g.push(``,`### Runtime`,Mv());let O=fe.instance().getAll(),k=O.filter(e=>e.status!==`healthy`);if(k.length>0){g.push(``,`### ⚠️ Subsystem Health`);for(let e of k){let t=Math.round((Date.now()-e.since)/1e3);g.push(`- **${e.name}**: ${e.status} (${t}s ago${e.reason?` — ${e.reason}`:``})`)}}else O.length>0&&g.push(``,`### ✅ Subsystem Health`,`- All ${O.length} subsystems healthy`);let ee=ue.getAll();if(ee.size>0){g.push(``,`### 🔌 Circuit Breakers`);for(let[e,t]of ee){let n=t.getState(),r=`- **${e}**: ${n===`closed`?`🟢`:n===`open`?`🔴`:`🟡`} ${n}`;if(n===`open`){let e=t.remainingCooldownMs();r+=` (recovery in ${Math.ceil(e/1e3)}s)`}g.push(r)}}let te=Lv(),ne=Rv(),re=ae(),se=te!=null&&te!==re,ce=ne!=null&&ne!==re;if(se||ce){let e=oe(),t=[];se&&t.push(`user scaffold v${te}`),ce&&t.push(`workspace scaffold v${ne}`);let n=t.join(`, `);e.state===`success`?g.push(``,`### ✅ Upgrade Applied`,`- Server v${re} — ${n} auto-upgraded successfully.`,`- _Restart the MCP server to use the updated version._`):e.state===`pending`?g.push(``,`### ⏳ Upgrade In Progress`,`- Server v${re} ≠ ${n}`,`- Auto-upgrade is running in the background…`):e.state===`failed`?(ie(),g.push(``,`### ⬆ Upgrade Available (auto-upgrade failed, retrying)`,`- Server v${re} ≠ ${n}`,`- Error: ${e.error??`unknown`}`)):(ie(),g.push(``,`### ⬆ Upgrade Available`,`- Server v${re} ≠ ${n}`,`- Auto-upgrade triggered — check again shortly.`))}l.length>0&&g.push(``,`### ⚠ Warnings`,...l.map(e=>`- ${e}`));let le=Wo();if(le.length>0){let e=le.sort((e,t)=>t.callCount-e.callCount);g.push(``,`### Tool Usage This Session`,``),g.push(`| Tool | Calls | Tokens In | Tokens Out | Errors | Avg Latency |`),g.push(`|------|-------|-----------|------------|--------|-------------|`);for(let t of e.slice(0,15)){let e=Math.round(t.totalInputChars/4),n=Math.round(t.totalOutputChars/4),r=Math.round(t.totalDurationMs/t.callCount);g.push(`| ${t.tool} | ${t.callCount} | ${e.toLocaleString()} | ${n.toLocaleString()} | ${t.errorCount} | ${r}ms |`)}}let A=Bo();A.callCount>0&&(g.push(``),g.push(`### Session Token Usage`),g.push(`- Tool calls: ${A.callCount}`),g.push(`- Input chars: ${A.totalInputChars.toLocaleString()}`),g.push(`- Output chars: ${A.totalOutputChars.toLocaleString()}`),g.push(`- Est. input tokens: ${Math.round(A.totalInputChars/4).toLocaleString()}`),g.push(`- Est. total tokens: ${Math.round((A.totalInputChars+A.totalOutputChars)/4).toLocaleString()}`));let j=No();if(j.bufferSize>=10){let e=j.state===`healthy`?`🟢`:j.state===`degraded`?`🔴`:`🟡`;g.push(``,`### Auto-GC: ${e} ${j.state}`),g.push(`- p95 latency: ${j.p95}ms | buffer: ${j.bufferSize} samples`),j.gcCount>0&&g.push(`- GC cycles triggered: ${j.gcCount}`)}let de=g.join(`
3044
+ `),pe=e||D>=Ov?await Ev(r,c):void 0,me={totalRecords:f.totalRecords,totalFiles:f.totalFiles,lastIndexedAt:f.lastIndexedAt??null,onboarded:y,onboardDir:_,contentTypes:f.contentTypeBreakdown,wasmAvailable:!!ur.get(),wasmDiagnostics:lr.get(),graphStats:m,curatedCount:h,serverVersion:re,scaffoldVersion:te??null,workspaceScaffoldVersion:ne??null,upgradeAvailable:se||ce,storeBackend:a?.store?.backend,storeDiagnostics:T??null,contextPressure:b,nextAction:C,sessionTokens:{callCount:A.callCount,totalInputChars:A.totalInputChars,totalOutputChars:A.totalOutputChars,estInputTokens:Math.round(A.totalInputChars/4),estTotalTokens:Math.round((A.totalInputChars+A.totalOutputChars)/4),startTime:A.startTime},...pe===void 0?{}:{prelude:pe}};return{content:[{type:`text`,text:de+(o===`smart`?"\n\n---\n_Next: Use `search` to query indexed content or `graph({action:'find_nodes', name_pattern:'<top-level-module>'})` → then `graph({action:'neighbors', node_id})` for relationships. Smart indexing handles updates automatically._":"\n\n---\n_Next: Use `search` to query indexed content, `graph({action:'find_nodes', name_pattern:'<top-level-module>'})` → then `graph({action:'neighbors', node_id})` for relationships, or `reindex` to refresh the index._")}],structuredContent:me}}catch(e){return Dv.error(`Status failed`,N(e)),q(`INTERNAL`,`Status check failed: ${e instanceof Error?e.message:String(e)}`)}}))}const Vv=M(`tools`);function Hv(e){return e instanceof Error?(`code`in e?e.code:void 0)===`ENOENT`||e.message.startsWith(`File not found:`)||e.message.startsWith(`Path not found:`):!1}function Uv(e){let t=W(`web_search`);e.registerTool(`web_search`,{title:t.title,description:`PREFERRED web search — fans out to multiple keyless providers (DuckDuckGo + Bing-HTML + Mojeek) by default, returning a deduplicated, consensus-ranked union within a 10s deadline. Optional providers (SearXNG, Google, Brave, Bing API) join the fan-out automatically when their env vars are set. Pass one query or multiple for parallel searching.`,inputSchema:{queries:R.array(R.string().max(2e3)).min(1).max(5).describe('Search queries (1–5). Single: `["react hooks"]`. Multiple searched in parallel.'),limit:R.number().min(1).max(20).default(5).describe(`Max results per query`),site:R.string().optional().describe(`Restrict to domain (e.g., "docs.aws.amazon.com")`),provider:R.enum([`multi`,`duckduckgo`,`bing-html`,`mojeek`,`searxng`,`google`,`brave`,`bing`]).optional().describe("Search provider. Defaults to env AIKIT_SEARCH_PROVIDER, then `multi` (fan-out). Single keyless: `duckduckgo`, `bing-html`, `mojeek`. Self-hosted: `searxng` (requires SEARXNG_URL). Keyed APIs: `google` (GOOGLE_API_KEY+GOOGLE_CSE_ID), `brave` (BRAVE_API_KEY), `bing` (BING_API_KEY). Missing keys auto-fall back to duckduckgo.")},annotations:t.annotations},J(`web_search`,async({queries:e,limit:t,site:n,provider:r})=>{let i=e,a=async e=>{let i=await Pn({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(`
3045
+ `)};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 Vv.error(`Web search failed`,N(e)),q(`INTERNAL`,`Web search failed: ${e instanceof Error?e.message:String(e)}`)}let o=await Promise.allSettled(i.map(e=>a(e))),s=[],c=0;for(let e=0;e<o.length;e++){let t=o[e];if(t.status===`fulfilled`)s.push(t.value);else{c++;let n=t.reason instanceof Error?t.reason.message:String(t.reason);Vv.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(`
3046
+
3047
+ `);return c===o.length?q(`INTERNAL`,u):{content:[{type:`text`,text:u}]}}))}function Wv(e){let t=W(`http`);e.registerTool(`http`,{title:t.title,description:`Make HTTP requests (GET/POST/PUT/PATCH/DELETE/HEAD) for API testing. Returns status, headers, and formatted body with timing info.`,inputSchema:{url:R.string().url().describe(`Request URL (http/https only)`),method:R.enum([`GET`,`POST`,`PUT`,`PATCH`,`DELETE`,`HEAD`]).default(`GET`).describe(`HTTP method`),headers:R.record(R.string(),R.string()).optional().describe(`Request headers as key-value pairs`),body:R.string().optional().describe(`Request body (for POST/PUT/PATCH)`),timeout:R.number().min(1e3).max(6e4).default(15e3).describe(`Timeout in milliseconds`)},annotations:t.annotations},J(`http`,async({url:e,method:t,headers:n,body:r,timeout:i})=>{try{let a=await Dt({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(`
3048
+ `)}]}}catch(e){return Vv.error(`HTTP request failed`,N(e)),q(`INTERNAL`,`HTTP request failed: ${e instanceof Error?e.message:String(e)}`)}}))}function Gv(e){let t=W(`regex_test`);e.registerTool(`regex_test`,{title:t.title,description:`Test a regex pattern against sample strings. Supports match, replace, and split modes.`,inputSchema:{pattern:R.string().max(500).describe(`Regex pattern (without delimiters)`),flags:R.string().max(10).regex(/^[gimsuy]*$/).default(``).describe(`Regex flags (g, i, m, s, etc.)`),test_strings:R.array(R.string().max(1e4)).max(50).describe(`Strings to test the pattern against`),mode:R.enum([`match`,`replace`,`split`]).default(`match`).describe(`Test mode`),replacement:R.string().optional().describe(`Replacement string (for replace mode)`)},annotations:t.annotations},J(`regex_test`,async({pattern:e,flags:t,test_strings:n,mode:r,replacement:i})=>{let a=tn({pattern:e,flags:t,testStrings:n,mode:r,replacement:i});if(!a.valid)return q(`VALIDATION`,`Invalid regex: ${a.error}`);let o=[`## Regex: \`/${a.pattern}/${a.flags}\``,``,`Mode: ${r}`,``];for(let e of a.results){if(o.push(`**Input:** \`${e.input}\``),o.push(`**Matched:** ${e.matched}`),e.matches)for(let t of e.matches){let e=t.groups.length>0?` groups: [${t.groups.join(`, `)}]`:``;o.push(` - "${t.full}" at index ${t.index}${e}`)}e.replaced!==void 0&&o.push(`**Result:** \`${e.replaced}\``),e.split&&o.push(`**Split:** ${JSON.stringify(e.split)}`),o.push(``)}return{content:[{type:`text`,text:o.join(`
3049
+ `)}]}}))}function Kv(e){let t=W(`encode`);e.registerTool(`encode`,{title:t.title,description:`Encode, decode, or hash text. Supports base64, URL encoding, SHA-256, MD5, JWT decode, hex.`,inputSchema:{operation:R.enum([`base64_encode`,`base64_decode`,`url_encode`,`url_decode`,`sha256`,`md5`,`jwt_decode`,`hex_encode`,`hex_decode`]).describe(`Operation to perform`),input:R.string().max(1e6).describe(`Input text`)},annotations:t.annotations},J(`encode`,async({operation:e,input:t})=>{try{let n=ut({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 Vv.error(`Encode failed`,N(e)),q(`INTERNAL`,`Encode failed: ${e instanceof Error?e.message:String(e)}`)}}))}function qv(e){let t=W(`measure`);e.registerTool(`measure`,{title:t.title,description:`Measure code complexity, line counts, and function counts for a file or directory. Returns per-file metrics sorted by complexity.`,outputSchema:zs,inputSchema:{path:R.string().describe(`File or directory path to measure`),extensions:R.array(R.string()).optional().describe(`File extensions to include (default: .ts,.tsx,.js,.jsx)`),include_hidden:R.boolean().optional().describe(`Include hidden trees such as .generated and .cache. Default false.`),max_tokens:R.number().min(100).max(5e4).optional().describe(`Maximum token budget for the response. When set, output is truncated to fit.`)},annotations:t.annotations},J(`measure`,async({path:e,extensions:t,include_hidden:n,max_tokens:r})=>{try{let i=await Lt({path:e,extensions:t,includeHidden:n}),a=[`## Code Metrics`,``,`**Files:** ${i.summary.totalFiles}`,`**Total lines:** ${i.summary.totalLines} (${i.summary.totalCodeLines} code)`,`**Functions:** ${i.summary.totalFunctions}`,`**Avg complexity:** ${i.summary.avgComplexity}`,`**Max complexity:** ${i.summary.maxComplexity.value} (${i.summary.maxComplexity.file})`,``,`### Top files by complexity`,``,`| File | Lines | Code | Complexity | Cognitive | Functions | Imports |`,`|------|-------|------|------------|-----------|-----------|---------|`];for(let e of i.files.slice(0,20)){let t=e.cognitiveComplexity===void 0?`—`:String(e.cognitiveComplexity);a.push(`| ${e.path} | ${e.lines.total} | ${e.lines.code} | ${e.complexity} | ${t} | ${e.functions} | ${e.imports} |`)}i.files.length>20&&a.push(``,`_...and ${i.files.length-20} more files_`);let o={summary:{totalFiles:i.summary.totalFiles,totalLines:i.summary.totalLines,totalCodeLines:i.summary.totalCodeLines,totalFunctions:i.summary.totalFunctions,avgComplexity:i.summary.avgComplexity,maxComplexity:{value:i.summary.maxComplexity.value,file:i.summary.maxComplexity.file}},files:i.files.map(e=>({path:e.path,lines:e.lines.total,code:e.lines.code,complexity:e.complexity,functions:e.functions}))};return{content:[{type:`text`,text:r?kn(a.join(`
3049
3050
  `),r):a.join(`
3050
- `)}],structuredContent:o}}catch(e){return Vv(e)?(Bv.warn(`Measure failed`,{error:`File not found`}),q(`NOT_FOUND`,`File not found`)):(Bv.error(`Measure failed`,N(e)),q(`INTERNAL`,`Measure failed: ${e instanceof Error?e.message:String(e)}`))}}))}function qv(e){let t=W(`changelog`);e.registerTool(`changelog`,{title:t.title,description:`Generate a changelog from git history between two refs. Groups by conventional commit type.`,inputSchema:{from:R.string().max(200).describe(`Start ref (tag, SHA, HEAD~N)`),to:R.string().max(200).default(`HEAD`).describe(`End ref (default: HEAD)`),format:R.enum([`grouped`,`chronological`,`per-scope`]).default(`grouped`).describe(`Output format`),include_breaking:R.boolean().default(!0).describe(`Highlight breaking changes`),cwd:R.string().optional().describe(`Repository root or working directory`)},annotations:t.annotations},J(`changelog`,async({from:e,to:t,format:n,include_breaking:r,cwd:i})=>{try{let a=We({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 Bv.error(`Changelog failed`,N(e)),q(`INTERNAL`,`Changelog failed: ${e instanceof Error?e.message:String(e)}`)}}))}function Jv(e){let t=W(`schema_validate`);e.registerTool(`schema_validate`,{title:t.title,description:`Validate JSON data against a JSON Schema. Supports type, required, properties, items, enum, pattern, min/max.`,inputSchema:{data:R.string().max(5e5).describe(`JSON data to validate (as string)`),schema:R.string().max(5e5).describe(`JSON Schema to validate against (as string)`)},annotations:t.annotations},J(`schema_validate`,async({data:e,schema:t})=>{try{let n=fn({data:JSON.parse(e),schema:JSON.parse(t)});if(n.valid)return{content:[{type:`text`,text:`## Validation: PASSED
3051
+ `)}],structuredContent:o}}catch(e){return Hv(e)?(Vv.warn(`Measure failed`,{error:`File not found`}),q(`NOT_FOUND`,`File not found`)):(Vv.error(`Measure failed`,N(e)),q(`INTERNAL`,`Measure failed: ${e instanceof Error?e.message:String(e)}`))}}))}function Jv(e){let t=W(`changelog`);e.registerTool(`changelog`,{title:t.title,description:`Generate a changelog from git history between two refs. Groups by conventional commit type.`,inputSchema:{from:R.string().max(200).describe(`Start ref (tag, SHA, HEAD~N)`),to:R.string().max(200).default(`HEAD`).describe(`End ref (default: HEAD)`),format:R.enum([`grouped`,`chronological`,`per-scope`]).default(`grouped`).describe(`Output format`),include_breaking:R.boolean().default(!0).describe(`Highlight breaking changes`),cwd:R.string().optional().describe(`Repository root or working directory`)},annotations:t.annotations},J(`changelog`,async({from:e,to:t,format:n,include_breaking:r,cwd:i})=>{try{let a=We({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 Vv.error(`Changelog failed`,N(e)),q(`INTERNAL`,`Changelog failed: ${e instanceof Error?e.message:String(e)}`)}}))}function Yv(e){let t=W(`schema_validate`);e.registerTool(`schema_validate`,{title:t.title,description:`Validate JSON data against a JSON Schema. Supports type, required, properties, items, enum, pattern, min/max.`,inputSchema:{data:R.string().max(5e5).describe(`JSON data to validate (as string)`),schema:R.string().max(5e5).describe(`JSON Schema to validate against (as string)`)},annotations:t.annotations},J(`schema_validate`,async({data:e,schema:t})=>{try{let n=fn({data:JSON.parse(e),schema:JSON.parse(t)});if(n.valid)return{content:[{type:`text`,text:`## Validation: PASSED
3051
3052
 
3052
3053
  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(`
3053
- `)}]}}catch(e){return Bv.error(`Schema validation failed`,N(e)),q(`INTERNAL`,`Schema validation failed: ${e instanceof Error?e.message:String(e)}`)}}))}function Yv(e){let t=W(`env`);e.registerTool(`env`,{title:t.title,description:`Get system and runtime environment info. Sensitive env vars are redacted by default.`,outputSchema:Bs,inputSchema:{include_env:R.boolean().default(!1).describe(`Include environment variables`),filter_env:R.string().optional().describe(`Filter env vars by name substring`),show_sensitive:R.boolean().default(!1).describe(`Show sensitive values (keys, tokens, etc.) — redacted by default`)},annotations:t.annotations},J(`env`,async({include_env:e,filter_env:t,show_sensitive:n})=>{let r=ft({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(`
3054
- `)}],structuredContent:a}}))}function Xv(e){let t=W(`time`);e.registerTool(`time`,{title:t.title,description:`Parse dates, convert timezones, calculate durations, add time. Supports ISO 8601, unix timestamps, and human-readable formats.`,outputSchema:Vs,inputSchema:{operation:R.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:R.string().optional().describe(`Date input (ISO, unix timestamp, or parseable string). For diff: two comma-separated dates`),timezone:R.string().optional().describe(`Target timezone (e.g., "America/New_York", "Asia/Tokyo")`),duration:R.string().optional().describe(`Duration to add (e.g., "2h30m", "1d", "30s") — for add operation`)},annotations:t.annotations},J(`time`,async({operation:e,input:t,timezone:n,duration:r})=>{try{let i=Dn({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(`
3055
- `)}],structuredContent:o}}catch(e){return Bv.error(`Time failed`,N(e)),q(`INTERNAL`,`Time failed: ${e instanceof Error?e.message:String(e)}`)}}))}function Zv(e){try{let t=I(e,`.flows`);if(!P(t))return null;let n=we(t,{withFileTypes:!0});for(let e of n){if(!e.isDirectory())continue;let n=I(t,e.name,`meta.json`);if(P(n)&&JSON.parse(F(n,`utf-8`)).status===`active`)return e.name}}catch{return null}return null}function Qv(e){let{server:t,aikit:n,config:r,elicitor:i,resourceNotifier:a,samplingClient:o,indexMode:s,getSmartState:c,getSmartScheduler:l,precomputedActiveTools:u}=e,d=new Eo,f=r.sources[0]?.path??process.cwd(),p=ve(f),m={activeSlug:null};m.activeSlug=Zv(f);let h=new Ga(I(r.stateDir??``,`flow-context`),()=>m.activeSlug),g=new Oa;g.register(Ni()),g.register(Ta),g.register(Ui),g.register(ma),g.register(Bi),g.register(Pi),g.register(Fi),g.register(Sa),g.register(Li),g.register(Da),g.register(pa(()=>m.activeSlug?{active:!0,slug:m.activeSlug}:null));let _=new Na(g,n.curated,{},h),v=u??Ns(r,[...Ba,...ns],U,is(r)),y=e=>v.has(e),b=new Set([...v].filter(e=>!Mp.includes(e)&&!fo.has(e))),x=new go;d.use(ja(_),{order:5,name:`auto-knowledge`}),d.use(Ko(),{order:10,name:`replay`}),d.use(yo(x,{stateStore:n.stateStore,curatedStore:n.curated},{trackedTools:b}),{order:94,name:`procedural-memory`}),d.use(so(new ao(n.stateStore,n.curated)),{order:95,name:`observation-capture`}),d.use(ss(),{order:1,name:`structured-content-guard`}),d.use(Wa(Ua(r.tokenBudget)),{order:90,name:`compression`}),vs(t,d,r.toolPrefix??``);let S=[...v].filter(e=>rs.has(e)?ts.includes(e)?!!n.bridge:e===`er_update_policy`?!!n.policyStore:e===`er_evolve_review`?!!n.evolutionCollector:!1:!0);y(`search`)&&rv(t,n.embedder,n.store,n.graphStore,n.bridge,n.evolutionCollector,o,n.stateStore,r.memory?.retention,r.memory?.consolidation,p);let C={store:n.store,graphStore:n.graphStore,embedder:n.embedder},w=l?e=>{l()?.prioritize(e)}:void 0;y(`lookup`)&&gp(t,n.store,C);let T={onboardComplete:n.onboardComplete,onboardTimestamp:n.onboardTimestamp};y(`status`)&&zv(t,n.store,n.graphStore,n.curated,T,r,s,c,n.stateStore),y(`config`)&&Al(t,r),y(`reindex`)&&F_(t,n.indexer,r,n.curated,n.store,a,s),y(`knowledge`)&&mp(t,n.curated,n.policyStore,n.evolutionCollector,a,h,n.stateStore,r.memory?.retention,r.memory?.supersession,r.memory?.consolidation,r.memory?.lessons,C),y(`memory_explain`)&&jp(t,n.embedder,n.store),y(`analyze`)&&Jc(t,n.store,n.embedder,C),y(`blast_radius`)&&Yc(t,n.store,n.embedder,n.graphStore,C),y(`produce_knowledge`)&&N_(t,r),y(`onboard`)&&em(t,n.store,n.embedder,r,T,C),y(`graph`)&&xd(t,n.graphStore,C),y(`audit`)&&el(t,n.store,n.embedder,r.tokenBudget),y(`compact`)&&Jl(t,n.embedder,n.fileCache,f,r.allRoots,C,w),y(`scope_map`)&&Yl(t,n.embedder,n.store,C),y(`find`)&&Xl(t,n.embedder,n.store,f,C,p),y(`parse_output`)&&uu(t),y(`workset`)&&nm(t),y(`check`)&&su(t,C,r.tokenBudget),y(`symbol`)&&Zl(t,n.embedder,n.store,n.graphStore,C),y(`eval`)&&cu(t),y(`test_run`)&&lu(t,C),y(`stash`)&&rm(t,n.stateStore),y(`signal`)&&Sv(t,n.stateStore),y(`git_context`)&&bp(t),y(`diff_parse`)&&xp(t),y(`rename`)&&Sp(t,r),y(`codemod`)&&Cp(t,r),y(`restore`)&&z_(t),y(`file_summary`)&&Ql(t,n.fileCache,f,r.allRoots,C,w),y(`checkpoint`)&&im(t,n.stateStore),y(`data_transform`)&&wp(t),y(`trace`)&&$l(t,n.embedder,n.store,n.graphStore,C),y(`process`)&&Cd(t),y(`watch`)&&wd(t),y(`dead_symbols`)&&eu(t,n.embedder,n.store,f,r.allRoots,C),y(`delegate`)&&du(t,o),y(`health`)&&Td(t),y(`lane`)&&am(t),y(`queue`)&&om(t),y(`web_fetch`)&&Ed(t),y(`guide`)&&Dd(t,s),Mp.some(e=>y(e))&&Np(t,r,S),y(`evidence_map`)&&pd(t),y(`digest`)&&md(t,n.embedder),y(`forge_classify`)&&hd(t,C),y(`stratum_card`)&&gd(t,n.embedder,n.fileCache),y(`forge_ground`)&&_d(t,n.embedder,n.store),y(`present`)&&j_(t,i),y(`browser`)&&er(t,r),y(`web_search`)&&Hv(t),y(`http`)&&Uv(t),y(`regex_test`)&&Wv(t),y(`encode`)&&Gv(t),y(`measure`)&&Kv(t),y(`changelog`)&&qv(t),y(`schema_validate`)&&Jv(t),y(`env`)&&Yv(t),y(`time`)&&Xv(t),y(`flow`)&&dd(t,r,{store:n.store?{search:async(e,t)=>(await n.store.ftsSearch(e,t)).map(e=>({content:e.record.content}))}:null,graphStore:n.graphStore,embedder:n.embedder},e=>{m.activeSlug=e}),n.bridge&&ts.some(e=>y(e))&&(il(t,n.bridge,n.evolutionCollector),al(t,n.bridge),ol(t,n.bridge)),n.policyStore&&y(`er_update_policy`)&&fm(t,n.policyStore),n.evolutionCollector&&y(`er_evolve_review`)&&au(t,n.evolutionCollector),es(t,n.store,n.curated),y(`compliance_score`)&&ll(t),y(`replay`)&&L_(t),y(`session_digest`)&&av(t,n.stateStore,o)}function $v(e,t,n){let r=e=>!n||n.has(e);r(`check`)&&su(e,void 0,t.tokenBudget),r(`eval`)&&cu(e),r(`test_run`)&&lu(e),r(`parse_output`)&&uu(e),r(`delegate`)&&du(e),r(`git_context`)&&bp(e),r(`diff_parse`)&&xp(e),r(`rename`)&&Sp(e,t),r(`codemod`)&&Cp(e,t),r(`data_transform`)&&wp(e),r(`workset`)&&nm(e),r(`restore`)&&z_(e),r(`lane`)&&am(e),r(`queue`)&&om(e),r(`session_digest`)&&av(e),r(`health`)&&Td(e),r(`process`)&&Cd(e),r(`watch`)&&wd(e),r(`web_fetch`)&&Ed(e),r(`guide`)&&Dd(e),Mp.some(e=>r(e))&&Np(e,t,[...n??new Set(Ba)]),r(`evidence_map`)&&pd(e),r(`forge_classify`)&&hd(e),r(`present`)&&j_(e),r(`browser`)&&er(e,t),r(`produce_knowledge`)&&N_(e),r(`compliance_score`)&&ll(e),r(`replay`)&&L_(e),r(`status`)&&Rv(e),r(`flow`)&&dd(e,t),r(`web_search`)&&Hv(e),r(`http`)&&Uv(e),r(`regex_test`)&&Wv(e),r(`encode`)&&Gv(e),r(`measure`)&&Kv(e),r(`changelog`)&&qv(e),r(`schema_validate`)&&Jv(e),r(`env`)&&Yv(e),r(`time`)&&Xv(e)}const ey=M(`resource-notifier`);var ty=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){ey.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){ey.debug(`sendResourceUpdated failed`,{uri:e,error:String(t)})}}};const Q=M(`server`);function ny(e){let t=e?.trim().toLowerCase();return t===`1`||t===`true`||t===`yes`||t===`on`}async function ry(n){Q.info(`Initializing AI Kit components`);let r=n.store.backend,i=n.embedding,a=me[i.model],o={model:i.model,nativeDim:i.nativeDim??a?.nativeDim??de.nativeDim,dimensions:i.dimensions??a?.dimensions??de.dimensions,queryPrefix:i.queryPrefix??a?.queryPrefix??de.queryPrefix,pooling:i.pooling??a?.pooling??`mean`},s=n.store.path,c=ny(process.env.AIKIT_SPLIT_STATE),l=I(s,`aikit.db`),u={splitEnabled:c,contentDbPath:l,controlDbPath:c?I(s,`aikit-control.db`):l},d=null;if(r===`sqlite-vec`){let e=u.contentDbPath;P(s)||Ce(s,{recursive:!0}),d=await wr(e),Q.debug(`SQLite adapter ready`,{type:d.type,vectorCapable:d.vectorCapable,dbPath:e}),d.vectorCapable||Q.warn(`┌──────────────────────────────────────────────────────────────────┐
3054
+ `)}]}}catch(e){return Vv.error(`Schema validation failed`,N(e)),q(`INTERNAL`,`Schema validation failed: ${e instanceof Error?e.message:String(e)}`)}}))}function Xv(e){let t=W(`env`);e.registerTool(`env`,{title:t.title,description:`Get system and runtime environment info. Sensitive env vars are redacted by default.`,outputSchema:Bs,inputSchema:{include_env:R.boolean().default(!1).describe(`Include environment variables`),filter_env:R.string().optional().describe(`Filter env vars by name substring`),show_sensitive:R.boolean().default(!1).describe(`Show sensitive values (keys, tokens, etc.) — redacted by default`)},annotations:t.annotations},J(`env`,async({include_env:e,filter_env:t,show_sensitive:n})=>{let r=ft({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(`
3055
+ `)}],structuredContent:a}}))}function Zv(e){let t=W(`time`);e.registerTool(`time`,{title:t.title,description:`Parse dates, convert timezones, calculate durations, add time. Supports ISO 8601, unix timestamps, and human-readable formats.`,outputSchema:Vs,inputSchema:{operation:R.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:R.string().optional().describe(`Date input (ISO, unix timestamp, or parseable string). For diff: two comma-separated dates`),timezone:R.string().optional().describe(`Target timezone (e.g., "America/New_York", "Asia/Tokyo")`),duration:R.string().optional().describe(`Duration to add (e.g., "2h30m", "1d", "30s") — for add operation`)},annotations:t.annotations},J(`time`,async({operation:e,input:t,timezone:n,duration:r})=>{try{let i=Dn({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(`
3056
+ `)}],structuredContent:o}}catch(e){return Vv.error(`Time failed`,N(e)),q(`INTERNAL`,`Time failed: ${e instanceof Error?e.message:String(e)}`)}}))}function Qv(e){try{let t=I(e,`.flows`);if(!P(t))return null;let n=we(t,{withFileTypes:!0});for(let e of n){if(!e.isDirectory())continue;let n=I(t,e.name,`meta.json`);if(P(n)&&JSON.parse(F(n,`utf-8`)).status===`active`)return e.name}}catch{return null}return null}function $v(e){let{server:t,aikit:n,config:r,elicitor:i,resourceNotifier:a,samplingClient:o,indexMode:s,getSmartState:c,getSmartScheduler:l,precomputedActiveTools:u}=e,d=new Eo,f=r.sources[0]?.path??process.cwd(),p=ve(f),m={activeSlug:null};m.activeSlug=Qv(f);let h=new Ga(I(r.stateDir??``,`flow-context`),()=>m.activeSlug),g=new Oa;g.register(Ni()),g.register(Ta),g.register(Ui),g.register(ma),g.register(Bi),g.register(Pi),g.register(Fi),g.register(Sa),g.register(Li),g.register(Da),g.register(pa(()=>m.activeSlug?{active:!0,slug:m.activeSlug}:null));let _=new Na(g,n.curated,{},h),v=u??Ns(r,[...Ba,...ns],U,is(r)),y=e=>v.has(e),b=new Set([...v].filter(e=>!Mp.includes(e)&&!fo.has(e))),x=new go;d.use(ja(_),{order:5,name:`auto-knowledge`}),d.use(Ko(),{order:10,name:`replay`}),d.use(yo(x,{stateStore:n.stateStore,curatedStore:n.curated},{trackedTools:b}),{order:94,name:`procedural-memory`}),d.use(so(new ao(n.stateStore,n.curated)),{order:95,name:`observation-capture`}),d.use(ss(),{order:1,name:`structured-content-guard`}),d.use(Wa(Ua(r.tokenBudget)),{order:90,name:`compression`}),vs(t,d,r.toolPrefix??``);let S=[...v].filter(e=>rs.has(e)?ts.includes(e)?!!n.bridge:e===`er_update_policy`?!!n.policyStore:e===`er_evolve_review`?!!n.evolutionCollector:!1:!0);y(`search`)&&iv(t,n.embedder,n.store,n.graphStore,n.bridge,n.evolutionCollector,o,n.stateStore,r.memory?.retention,r.memory?.consolidation,p);let C={store:n.store,graphStore:n.graphStore,embedder:n.embedder},w=l?e=>{l()?.prioritize(e)}:void 0;y(`lookup`)&&gp(t,n.store,C);let T={onboardComplete:n.onboardComplete,onboardTimestamp:n.onboardTimestamp};y(`status`)&&Bv(t,n.store,n.graphStore,n.curated,T,r,s,c,n.stateStore),y(`config`)&&Al(t,r),y(`reindex`)&&I_(t,n.indexer,r,n.curated,n.store,a,s),y(`knowledge`)&&mp(t,n.curated,n.policyStore,n.evolutionCollector,a,h,n.stateStore,r.memory?.retention,r.memory?.supersession,r.memory?.consolidation,r.memory?.lessons,C),y(`memory_explain`)&&jp(t,n.embedder,n.store),y(`analyze`)&&Jc(t,n.store,n.embedder,C),y(`blast_radius`)&&Yc(t,n.store,n.embedder,n.graphStore,C),y(`produce_knowledge`)&&P_(t,r),y(`onboard`)&&em(t,n.store,n.embedder,r,T,C),y(`graph`)&&xd(t,n.graphStore,C),y(`audit`)&&el(t,n.store,n.embedder,r.tokenBudget),y(`compact`)&&Jl(t,n.embedder,n.fileCache,f,r.allRoots,C,w),y(`scope_map`)&&Yl(t,n.embedder,n.store,C),y(`find`)&&Xl(t,n.embedder,n.store,f,C,p),y(`parse_output`)&&uu(t),y(`workset`)&&nm(t),y(`check`)&&su(t,C,r.tokenBudget),y(`symbol`)&&Zl(t,n.embedder,n.store,n.graphStore,C),y(`eval`)&&cu(t),y(`test_run`)&&lu(t,C),y(`stash`)&&rm(t,n.stateStore),y(`signal`)&&Cv(t,n.stateStore),y(`git_context`)&&bp(t),y(`diff_parse`)&&xp(t),y(`rename`)&&Sp(t,r),y(`codemod`)&&Cp(t,r),y(`restore`)&&B_(t),y(`file_summary`)&&Ql(t,n.fileCache,f,r.allRoots,C,w),y(`checkpoint`)&&im(t,n.stateStore),y(`data_transform`)&&wp(t),y(`trace`)&&$l(t,n.embedder,n.store,n.graphStore,C),y(`process`)&&Cd(t),y(`watch`)&&wd(t),y(`dead_symbols`)&&eu(t,n.embedder,n.store,f,r.allRoots,C),y(`delegate`)&&du(t,o),y(`health`)&&Td(t),y(`lane`)&&am(t),y(`queue`)&&om(t),y(`web_fetch`)&&Ed(t),y(`guide`)&&Dd(t,s),Mp.some(e=>y(e))&&Np(t,r,S),y(`evidence_map`)&&pd(t),y(`digest`)&&md(t,n.embedder),y(`forge_classify`)&&hd(t,C),y(`stratum_card`)&&gd(t,n.embedder,n.fileCache),y(`forge_ground`)&&_d(t,n.embedder,n.store),y(`present`)&&M_(t,i),y(`browser`)&&er(t,r),y(`web_search`)&&Uv(t),y(`http`)&&Wv(t),y(`regex_test`)&&Gv(t),y(`encode`)&&Kv(t),y(`measure`)&&qv(t),y(`changelog`)&&Jv(t),y(`schema_validate`)&&Yv(t),y(`env`)&&Xv(t),y(`time`)&&Zv(t),y(`flow`)&&dd(t,r,{store:n.store?{search:async(e,t)=>(await n.store.ftsSearch(e,t)).map(e=>({content:e.record.content}))}:null,graphStore:n.graphStore,embedder:n.embedder},e=>{m.activeSlug=e}),n.bridge&&ts.some(e=>y(e))&&(il(t,n.bridge,n.evolutionCollector),al(t,n.bridge),ol(t,n.bridge)),n.policyStore&&y(`er_update_policy`)&&fm(t,n.policyStore),n.evolutionCollector&&y(`er_evolve_review`)&&au(t,n.evolutionCollector),es(t,n.store,n.curated),y(`compliance_score`)&&ll(t),y(`replay`)&&R_(t),y(`session_digest`)&&ov(t,n.stateStore,o)}function ey(e,t,n){let r=e=>!n||n.has(e);r(`check`)&&su(e,void 0,t.tokenBudget),r(`eval`)&&cu(e),r(`test_run`)&&lu(e),r(`parse_output`)&&uu(e),r(`delegate`)&&du(e),r(`git_context`)&&bp(e),r(`diff_parse`)&&xp(e),r(`rename`)&&Sp(e,t),r(`codemod`)&&Cp(e,t),r(`data_transform`)&&wp(e),r(`workset`)&&nm(e),r(`restore`)&&B_(e),r(`lane`)&&am(e),r(`queue`)&&om(e),r(`session_digest`)&&ov(e),r(`health`)&&Td(e),r(`process`)&&Cd(e),r(`watch`)&&wd(e),r(`web_fetch`)&&Ed(e),r(`guide`)&&Dd(e),Mp.some(e=>r(e))&&Np(e,t,[...n??new Set(Ba)]),r(`evidence_map`)&&pd(e),r(`forge_classify`)&&hd(e),r(`present`)&&M_(e),r(`browser`)&&er(e,t),r(`produce_knowledge`)&&P_(e),r(`compliance_score`)&&ll(e),r(`replay`)&&R_(e),r(`status`)&&zv(e),r(`flow`)&&dd(e,t),r(`web_search`)&&Uv(e),r(`http`)&&Wv(e),r(`regex_test`)&&Gv(e),r(`encode`)&&Kv(e),r(`measure`)&&qv(e),r(`changelog`)&&Jv(e),r(`schema_validate`)&&Yv(e),r(`env`)&&Xv(e),r(`time`)&&Zv(e)}const ty=M(`resource-notifier`);var ny=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){ty.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){ty.debug(`sendResourceUpdated failed`,{uri:e,error:String(t)})}}};const Q=M(`server`);function ry(e){let t=e?.trim().toLowerCase();return t===`1`||t===`true`||t===`yes`||t===`on`}async function iy(n){Q.info(`Initializing AI Kit components`);let r=n.store.backend,i=n.embedding,a=me[i.model],o={model:i.model,nativeDim:i.nativeDim??a?.nativeDim??de.nativeDim,dimensions:i.dimensions??a?.dimensions??de.dimensions,queryPrefix:i.queryPrefix??a?.queryPrefix??de.queryPrefix,pooling:i.pooling??a?.pooling??`mean`},s=n.store.path,c=ry(process.env.AIKIT_SPLIT_STATE),l=I(s,`aikit.db`),u={splitEnabled:c,contentDbPath:l,controlDbPath:c?I(s,`aikit-control.db`):l},d=null;if(r===`sqlite-vec`){let e=u.contentDbPath;P(s)||Ce(s,{recursive:!0}),d=await wr(e),Q.debug(`SQLite adapter ready`,{type:d.type,vectorCapable:d.vectorCapable,dbPath:e}),d.vectorCapable||Q.warn(`┌──────────────────────────────────────────────────────────────────┐
3056
3057
  │ ⚠ SQLite vector extension unavailable — DEGRADED MODE │
3057
3058
  │ Vector search is disabled. Hybrid search returns FTS only. │
3058
3059
  │ To enable: install/rebuild better-sqlite3 (native module). │
3059
- └──────────────────────────────────────────────────────────────────┘`);let t=I(s,`lance`);P(t)&&Q.info(`Old LanceDB data found at ${t} — ignored. Safe to delete after verifying sqlite-vec works.`)}let f;if(d)if(u.splitEnabled&&u.controlDbPath!==u.contentDbPath){let{migrateToSplitState:e}=await import(`../../store/dist/index.js`);await e(u),f=await wr(u.controlDbPath),Dr(f,Cr),Q.info(`State store adapter ready`,{type:f.type,dbPath:u.controlDbPath,splitEnabled:!0})}else f=d;else{let e=I(s,`aikit-state.db`);P(s)||Ce(s,{recursive:!0}),f=await wr(e),Dr(f,Cr),Q.info(`State store adapter ready`,{type:f.type,dbPath:e})}let[p,m,h,g]=await Promise.all([(async()=>{if(n.embedding.childProcess!==!1){let e=new zr({model:o.model,dimensions:o.dimensions,nativeDim:o.nativeDim,queryPrefix:o.queryPrefix,pooling:o.pooling,interOpNumThreads:i.interOpNumThreads,intraOpNumThreads:i.intraOpNumThreads,idleTimeoutMs:i.idleTimeoutMs});return await e.initialize(),Q.debug(`Embedder loaded (child process)`,{modelId:e.modelId,dimensions:e.dimensions}),e}let{OnnxEmbedder:e}=await import(`../../embeddings/dist/index.js`),t=new e({model:o.model,dimensions:o.dimensions,nativeDim:o.nativeDim,queryPrefix:o.queryPrefix,pooling:o.pooling,interOpNumThreads:i.interOpNumThreads,intraOpNumThreads:i.intraOpNumThreads});return await t.initialize(),Q.debug(`Embedder loaded (in-process)`,{modelId:t.modelId,dimensions:t.dimensions}),t})(),(async()=>{let e=r===`sqlite-vec`?await Er({backend:r,path:s,adapter:d??void 0,embeddingDim:o.dimensions,embeddingProfile:o,partition:u}):await Er({backend:r,path:s,adapter:d??void 0,embeddingDim:o.dimensions,partition:void 0});return await e.initialize(),Q.debug(`Store initialized`,{backend:r}),e})(),(async()=>{let e=d?new Sr({adapter:d}):new Sr({path:s});return await e.initialize(),Q.debug(`Graph store initialized`,{shared:!!d}),e})(),(async()=>{let e=await dr();if(e){let e=lr.get();Q.debug(`WASM tree-sitter enabled`,{grammars:e.grammarCount,dir:e.wasmDir})}else{let e=lr.get();Q.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})()]),_=new Vr(p,m),v=Tr(f),y=new Br(n.store.path);y.load(),_.setHashCache(y);let b=n.curated.path,x=new e(b);await x.initialize();let S=new t(b,m,p,x);_.setGraphStore(h);let C=rl(n.er),w=C?new hr(n.curated.path):void 0;w&&Q.debug(`Policy store initialized`,{ruleCount:w.getRules().length});let T=C?new mr:void 0,E=L(n.sources[0]?.path??process.cwd(),A.aiContext),D=P(E),O=n.onboardDir?P(n.onboardDir):!1,k=D||O,ee,te=D?E:n.onboardDir;if(k&&te)try{ee=De(te).mtime.toISOString()}catch{}return Q.debug(`Onboard state detected`,{onboardComplete:k,onboardTimestamp:ee,aiKbExists:D,onboardDirExists:O}),{embedder:p,store:m,stateStore:v,closeStateStore:f===d?void 0:async()=>f.close(),indexer:_,curated:S,graphStore:h,fileCache:new ze,bridge:C,policyStore:w,evolutionCollector:T,onboardComplete:k,onboardTimestamp:ee}}function iy(e,t,n){if(e.serverInstructions)return e.serverInstructions;let r=new Set;for(let e of t){let t=n[e];if(t?.category)for(let e of t.category)r.add(e)}let i=[`This server provides ${t.size} tools across ${r.size} categories: ${[...r].sort().join(`, `)}.`,`TOOL ROUTING:`,`- Understand a file -> file_summary (structure) or compact (extract section)`,`- Find code/symbols -> search (hybrid) or symbol (definition + refs)`,`- Validate changes -> check (typecheck+lint) or test_run (tests)`,`- Read file for editing -> read_file (only for exact lines before edits)`,`FORBIDDEN: DO NOT USE native equivalents when AI Kit provides same:`,`- grep/find -> search or find tool`,`- cat/read_file (for understanding) -> file_summary or compact`,`- terminal tsc/lint -> check tool`,`- terminal test -> test_run tool`];return e.readOnly&&i.push(`Server is in read-only mode. Mutating operations are disabled.`),e.features?.length&&i.push(`Active feature groups: ${e.features.join(`, `)}.`),i.join(`
3060
- `)}const ay=M(`background-task`);var oy=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,ay.info(`Background task started`,{task:e.name,pending:this.queue.length});let t=Date.now();try{await e.fn();let n=Date.now()-t;ay.info(`Background task completed`,{task:e.name,durationMs:n}),e.resolve()}catch(n){let r=Date.now()-t;ay.error(`Background task failed`,{task:e.name,durationMs:r,err:n}),e.reject(n instanceof Error?n:Error(String(n)))}}this.running=null}};const sy=M(`idle-timer`);var cy=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){sy.info(`Idle timeout reached with no active session — skipping cleanup (waiting for first tool call)`);return}if(this._busy){sy.info(`Skipping idle cleanup — background work in progress`);return}sy.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`&&sy.warn(`Idle cleanup callback failed`,{error:String(t.reason)})}};const ly=M(`memory-monitor`);var uy=class{timer=null;warningBytes;criticalBytes;intervalMs;pressureFns=[];memoryPressureFns=[];lastLevel=`normal`;constructor(e){this.warningBytes=e?.warningBytes??3221225472,this.criticalBytes=e?.criticalBytes??6442450944,this.intervalMs=e?.intervalMs??3e4}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(),ly.debug(`Memory monitor started`,{warningMB:Math.round(this.warningBytes/1024/1024),criticalMB:Math.round(this.criticalBytes/1024/1024),intervalSec:Math.round(this.intervalMs/1e3)}))}stop(){this.timer&&=(clearInterval(this.timer),null)}getRssBytes(){return process.memoryUsage.rss()}check(){let e=this.getRssBytes(),t=`normal`;if(e>=this.criticalBytes?t=`critical`:e>=this.warningBytes&&(t=`warning`),t!==this.lastLevel||t===`critical`){let n=Math.round(e/1024/1024);t===`critical`?ly.warn(`Memory CRITICAL: ${n}MB RSS — consider restarting the server`):t===`warning`?ly.warn(`Memory WARNING: ${n}MB RSS`):this.lastLevel!==`normal`&&ly.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 dy=new Hr;function fy(e,t){return dy.run(e,async()=>{try{return await t()}finally{}})}M(`tool-timeout`);const py=new Set([`onboard`,`reindex`,`produce_knowledge`,`analyze`,`codemod`,`audit`]);var my=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 hy(e){return py.has(e)?6e5:12e4}function gy(e,t,n){let r=new AbortController,i=r.signal;return new Promise((a,o)=>{let s=setTimeout(()=>{let e=new my(n,t);i.aborted||r.abort(e),o(e)},t);s.unref();try{e(i).then(a,o).finally(()=>clearTimeout(s))}catch(e){clearTimeout(s),o(e instanceof Error?e:Error(String(e)))}})}const $=M(`server`),_y=new Set([`status`,`list_tools`,`describe_tool`,`config`,`env`,`present`]);function vy(e,t=28){let n=e.replace(/\s+/g,` `).trim();return n.length<=t?n:`${n.slice(0,t-3)}...`}function yy(e){let t=[`query`,`path`,`task`,`name`,`start`,`symbol`,`file`,`pattern`],n=[];for(let r of t){let t=e[r];typeof t==`string`&&t.length>0&&t.length<200&&n.push(t)}return n.join(` `).slice(0,200)}async function by(e,t,n){let r=[];try{t.statePath&&dt(e.stateStore,{stateDir:t.statePath});let i=e.stateStore.stashList().map(e=>e.key);if(i.length>0){let e=n.toLowerCase().split(/\s+/).filter(e=>e.length>2);if(e.length===0)r.push(`stash: ${i.length} entries available`);else{let t=i.filter(t=>e.some(e=>t.toLowerCase().includes(e))).slice(0,3);t.length>0?r.push(`stash: ${t.map(e=>`"${vy(e)}"`).join(`, `)}${i.length>t.length?` (${i.length} total)`:``}`):r.push(`stash: ${i.length} entries available`)}}}catch{}try{if(n){let t=await Promise.race([e.store.ftsSearch(n,{limit:3}),new Promise(e=>{let t=setTimeout(()=>e(null),1e3);t.unref&&t.unref()})]);if(Array.isArray(t)&&t.length>0){let e=t.filter(e=>e&&typeof e==`object`&&`record`in e&&(e.record.origin===`produced`||e.record.origin===`curated`));if(e.length>0){let t=e.slice(0,2).map(e=>{let t=e.record;return`"${vy(t.headingPath||t.sourcePath||`knowledge`)}"`});r.push(`knowledge: ${t.join(`, `)}`)}}}}catch{}return r.length===0?null:`\n---\nContext available: ${r.join(` | `)}\nPull with: stash({action:'get', key:'...'}) or search({query:'...', origin:'produced'})\n---`}function xy(e,t,n){let r=3;for(let[i,a]of Object.entries(e)){let e=a.handler;a.handler=async(...a)=>{let o=await e(...a);if(!o||typeof o!=`object`||r<=0||o.isError||_y.has(i))return o;try{r--;let e=a[0],i=await by(t,n,yy(e&&typeof e==`object`?e:{}));i&&(o.content=Array.isArray(o.content)?o.content:[],o.content.push({type:`text`,text:i}))}catch{}return o}}}function Sy(e){let t=e.toLowerCase();return[`protobuf`,`invalid model`,`invalid onnx`,`unexpected end`,`unexpected token`,`failed to load`,`failed to initialize embedding`,`checksum`,`corrupt`,`malformed`,`could not load`,`onnx`,`database disk image is malformed`,`file is not a database`,`lance`,`cannot find module`,`cannot find package`,`module not found`].some(e=>t.includes(e))}function Cy(e){return Wp(e)?[`Auto-heal tried to repair missing runtime dependency files in the npx install.`,`If this persists, clear the broken npx cache and restart:`,` npm cache clean --force`,` npx -y @vpxa/aikit@latest serve`].join(`
3060
+ └──────────────────────────────────────────────────────────────────┘`);let t=I(s,`lance`);P(t)&&Q.info(`Old LanceDB data found at ${t} — ignored. Safe to delete after verifying sqlite-vec works.`)}let f;if(d)if(u.splitEnabled&&u.controlDbPath!==u.contentDbPath){let{migrateToSplitState:e}=await import(`../../store/dist/index.js`);await e(u),f=await wr(u.controlDbPath),Dr(f,Cr),Q.info(`State store adapter ready`,{type:f.type,dbPath:u.controlDbPath,splitEnabled:!0})}else f=d;else{let e=I(s,`aikit-state.db`);P(s)||Ce(s,{recursive:!0}),f=await wr(e),Dr(f,Cr),Q.info(`State store adapter ready`,{type:f.type,dbPath:e})}let[p,m,h,g]=await Promise.all([(async()=>{if(n.embedding.childProcess!==!1){let e=new zr({model:o.model,dimensions:o.dimensions,nativeDim:o.nativeDim,queryPrefix:o.queryPrefix,pooling:o.pooling,interOpNumThreads:i.interOpNumThreads,intraOpNumThreads:i.intraOpNumThreads,idleTimeoutMs:i.idleTimeoutMs});return await e.initialize(),Q.debug(`Embedder loaded (child process)`,{modelId:e.modelId,dimensions:e.dimensions}),e}let{OnnxEmbedder:e}=await import(`../../embeddings/dist/index.js`),t=new e({model:o.model,dimensions:o.dimensions,nativeDim:o.nativeDim,queryPrefix:o.queryPrefix,pooling:o.pooling,interOpNumThreads:i.interOpNumThreads,intraOpNumThreads:i.intraOpNumThreads});return await t.initialize(),Q.debug(`Embedder loaded (in-process)`,{modelId:t.modelId,dimensions:t.dimensions}),t})(),(async()=>{let e=r===`sqlite-vec`?await Er({backend:r,path:s,adapter:d??void 0,embeddingDim:o.dimensions,embeddingProfile:o,partition:u}):await Er({backend:r,path:s,adapter:d??void 0,embeddingDim:o.dimensions,partition:void 0});return await e.initialize(),Q.debug(`Store initialized`,{backend:r}),e})(),(async()=>{let e=d?new Sr({adapter:d}):new Sr({path:s});return await e.initialize(),Q.debug(`Graph store initialized`,{shared:!!d}),e})(),(async()=>{let e=await dr();if(e){let e=lr.get();Q.debug(`WASM tree-sitter enabled`,{grammars:e.grammarCount,dir:e.wasmDir})}else{let e=lr.get();Q.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})()]),_=new Vr(p,m),v=Tr(f),y=new Br(n.store.path);y.load(),_.setHashCache(y);let b=n.curated.path,x=new e(b);await x.initialize();let S=new t(b,m,p,x);_.setGraphStore(h);let C=rl(n.er),w=C?new hr(n.curated.path):void 0;w&&Q.debug(`Policy store initialized`,{ruleCount:w.getRules().length});let T=C?new mr:void 0,E=L(n.sources[0]?.path??process.cwd(),A.aiContext),D=P(E),O=n.onboardDir?P(n.onboardDir):!1,k=D||O,ee,te=D?E:n.onboardDir;if(k&&te)try{ee=De(te).mtime.toISOString()}catch{}return Q.debug(`Onboard state detected`,{onboardComplete:k,onboardTimestamp:ee,aiKbExists:D,onboardDirExists:O}),{embedder:p,store:m,stateStore:v,closeStateStore:f===d?void 0:async()=>f.close(),indexer:_,curated:S,graphStore:h,fileCache:new ze,bridge:C,policyStore:w,evolutionCollector:T,onboardComplete:k,onboardTimestamp:ee}}function ay(e,t,n){if(e.serverInstructions)return e.serverInstructions;let r=new Set;for(let e of t){let t=n[e];if(t?.category)for(let e of t.category)r.add(e)}let i=[`This server provides ${t.size} tools across ${r.size} categories: ${[...r].sort().join(`, `)}.`,`TOOL ROUTING:`,`- Understand a file -> file_summary (structure) or compact (extract section)`,`- Find code/symbols -> search (hybrid) or symbol (definition + refs)`,`- Validate changes -> check (typecheck+lint) or test_run (tests)`,`- Read file for editing -> read_file (only for exact lines before edits)`,`FORBIDDEN: DO NOT USE native equivalents when AI Kit provides same:`,`- grep/find -> search or find tool`,`- cat/read_file (for understanding) -> file_summary or compact`,`- terminal tsc/lint -> check tool`,`- terminal test -> test_run tool`];return e.readOnly&&i.push(`Server is in read-only mode. Mutating operations are disabled.`),e.features?.length&&i.push(`Active feature groups: ${e.features.join(`, `)}.`),i.join(`
3061
+ `)}const oy=M(`background-task`);var sy=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,oy.info(`Background task started`,{task:e.name,pending:this.queue.length});let t=Date.now();try{await e.fn();let n=Date.now()-t;oy.info(`Background task completed`,{task:e.name,durationMs:n}),e.resolve()}catch(n){let r=Date.now()-t;oy.error(`Background task failed`,{task:e.name,durationMs:r,err:n}),e.reject(n instanceof Error?n:Error(String(n)))}}this.running=null}};const cy=M(`idle-timer`);var ly=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){cy.info(`Idle timeout reached with no active session — skipping cleanup (waiting for first tool call)`);return}if(this._busy){cy.info(`Skipping idle cleanup — background work in progress`);return}cy.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`&&cy.warn(`Idle cleanup callback failed`,{error:String(t.reason)})}};const uy=M(`memory-monitor`);var dy=class{timer=null;warningBytes;criticalBytes;intervalMs;pressureFns=[];memoryPressureFns=[];lastLevel=`normal`;constructor(e){this.warningBytes=e?.warningBytes??3221225472,this.criticalBytes=e?.criticalBytes??6442450944,this.intervalMs=e?.intervalMs??3e4}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(),uy.debug(`Memory monitor started`,{warningMB:Math.round(this.warningBytes/1024/1024),criticalMB:Math.round(this.criticalBytes/1024/1024),intervalSec:Math.round(this.intervalMs/1e3)}))}stop(){this.timer&&=(clearInterval(this.timer),null)}getRssBytes(){return process.memoryUsage.rss()}check(){let e=this.getRssBytes(),t=`normal`;if(e>=this.criticalBytes?t=`critical`:e>=this.warningBytes&&(t=`warning`),t!==this.lastLevel||t===`critical`){let n=Math.round(e/1024/1024);t===`critical`?uy.warn(`Memory CRITICAL: ${n}MB RSS — consider restarting the server`):t===`warning`?uy.warn(`Memory WARNING: ${n}MB RSS`):this.lastLevel!==`normal`&&uy.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 fy=new Hr;function py(e,t){return fy.run(e,async()=>{try{return await t()}finally{}})}M(`tool-timeout`);const my=new Set([`onboard`,`reindex`,`produce_knowledge`,`analyze`,`codemod`,`audit`]);var hy=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 gy(e){return my.has(e)?6e5:12e4}function _y(e,t,n){let r=new AbortController,i=r.signal;return new Promise((a,o)=>{let s=setTimeout(()=>{let e=new hy(n,t);i.aborted||r.abort(e),o(e)},t);s.unref();try{e(i).then(a,o).finally(()=>clearTimeout(s))}catch(e){clearTimeout(s),o(e instanceof Error?e:Error(String(e)))}})}const $=M(`server`),vy=new Set([`status`,`list_tools`,`describe_tool`,`config`,`env`,`present`]);function yy(e,t=28){let n=e.replace(/\s+/g,` `).trim();return n.length<=t?n:`${n.slice(0,t-3)}...`}function by(e){let t=[`query`,`path`,`task`,`name`,`start`,`symbol`,`file`,`pattern`],n=[];for(let r of t){let t=e[r];typeof t==`string`&&t.length>0&&t.length<200&&n.push(t)}return n.join(` `).slice(0,200)}async function xy(e,t,n){let r=[];try{t.statePath&&dt(e.stateStore,{stateDir:t.statePath});let i=e.stateStore.stashList().map(e=>e.key);if(i.length>0){let e=n.toLowerCase().split(/\s+/).filter(e=>e.length>2);if(e.length===0)r.push(`stash: ${i.length} entries available`);else{let t=i.filter(t=>e.some(e=>t.toLowerCase().includes(e))).slice(0,3);t.length>0?r.push(`stash: ${t.map(e=>`"${yy(e)}"`).join(`, `)}${i.length>t.length?` (${i.length} total)`:``}`):r.push(`stash: ${i.length} entries available`)}}}catch{}try{if(n){let t=await Promise.race([e.store.ftsSearch(n,{limit:3}),new Promise(e=>{let t=setTimeout(()=>e(null),1e3);t.unref&&t.unref()})]);if(Array.isArray(t)&&t.length>0){let e=t.filter(e=>e&&typeof e==`object`&&`record`in e&&(e.record.origin===`produced`||e.record.origin===`curated`));if(e.length>0){let t=e.slice(0,2).map(e=>{let t=e.record;return`"${yy(t.headingPath||t.sourcePath||`knowledge`)}"`});r.push(`knowledge: ${t.join(`, `)}`)}}}}catch{}return r.length===0?null:`\n---\nContext available: ${r.join(` | `)}\nPull with: stash({action:'get', key:'...'}) or search({query:'...', origin:'produced'})\n---`}function Sy(e,t,n){let r=3;for(let[i,a]of Object.entries(e)){let e=a.handler;a.handler=async(...a)=>{let o=await e(...a);if(!o||typeof o!=`object`||r<=0||o.isError||vy.has(i))return o;try{r--;let e=a[0],i=await xy(t,n,by(e&&typeof e==`object`?e:{}));i&&(o.content=Array.isArray(o.content)?o.content:[],o.content.push({type:`text`,text:i}))}catch{}return o}}}function Cy(e){let t=e.toLowerCase();return[`protobuf`,`invalid model`,`invalid onnx`,`unexpected end`,`unexpected token`,`failed to load`,`failed to initialize embedding`,`checksum`,`corrupt`,`malformed`,`could not load`,`onnx`,`database disk image is malformed`,`file is not a database`,`lance`,`cannot find module`,`cannot find package`,`module not found`].some(e=>t.includes(e))}function wy(e){return Wp(e)?[`Auto-heal tried to repair missing runtime dependency files in the npx install.`,`If this persists, clear the broken npx cache and restart:`,` npm cache clean --force`,` npx -y @vpxa/aikit@latest serve`].join(`
3061
3062
  `):[`To fix embedding errors, try deleting the cached model:`,` rm -rf ~/.cache/huggingface/transformers-js/mixedbread-ai/`,`Then restart the server to re-download a fresh copy.`].join(`
3062
- `)}async function wy(e,t){let n=t.toLowerCase(),r;try{({rm:r}=await import(`node:fs/promises`))}catch{return}if(n.includes(`transformers.node.mjs`)&&n.includes(`cannot find module`)){let e=t.match(/Cannot find module '([^']+transformers\.node\.mjs)'/);if(e){let t=e[1],n=t.replace(/\.mjs$/,`.cjs`);try{let{existsSync:e,writeFileSync:r}=await import(`node:fs`);e(n)&&!e(t)&&(r(t,[`// Auto-generated ESM shim — published package missing this file`,`import { createRequire } from 'node:module';`,`const require = createRequire(import.meta.url);`,`const mod = require('./transformers.node.cjs');`,`export default mod;`,``].join(`
3063
- `),`utf8`),$.info(`Auto-heal: created ESM shim for @huggingface/transformers (.mjs wrapper → .cjs)`,{path:t}))}catch(e){$.warn(`Auto-heal: failed to create ESM shim`,{error:e instanceof Error?e.message:String(e),path:t})}}}if(n.includes(`embedding`)||n.includes(`onnx`)||n.includes(`protobuf`)||n.includes(`model`)){let t=e.embedding?.model;if(t){let e=I(Wn(),`.cache`,`huggingface`,`transformers-js`,t);try{await r(e,{recursive:!0,force:!0}),$.info(`Auto-heal: cleared embedding model cache`,{path:e})}catch{}}}if(n.includes(`lance`)||n.includes(`database`)||n.includes(`store`)){let t=I(e.store.path,`lance`);try{await r(t,{recursive:!0,force:!0}),$.info(`Auto-heal: cleared LanceDB store`,{path:t})}catch{}}if(n.includes(`sqlite`)||n.includes(`database disk image`)||n.includes(`graph`)){let t=I(e.store.path,`graph.db`);try{await r(t,{force:!0}),$.info(`Auto-heal: cleared graph database`,{path:t})}catch{}let n=I(e.store.path,`aikit.db`);try{await r(n,{force:!0}),await r(`${n}-wal`,{force:!0}).catch(()=>{}),await r(`${n}-shm`,{force:!0}).catch(()=>{}),$.info(`Auto-heal: cleared corrupted aikit database`,{path:n})}catch{}}if(Wp(t)){let e=await qp(t);e.repaired||$.warn(`Auto-heal: missing runtime dependency repair did not complete`,{packages:e.packages,reason:e.reason,error:e.error,hint:`Run: npm cache clean --force && npx -y @vpxa/aikit@latest serve`})}else n.includes(`cannot find module`)&&!n.includes(`.cache`)&&$.warn(`Auto-heal: missing module detected during initialization cleanup`,{hint:`Run: npm cache clean --force && npx -y @vpxa/aikit@latest serve`})}function Ty(e,t){let n=Ns(e,Ba,U,is(e)),r=iy(e,n,U),i=new Kn({name:e.serverName??`aikit`,version:ae()},{capabilities:{logging:{},completions:{},prompts:{}},instructions:r}),a=`initializing`,o=``,s=!1,c=null,l=null,u=null;function d(e){if(!e||typeof e!=`object`)return[];let t=e,n=[];for(let e of[`path`,`file`,`source_path`,`sourcePath`,`filePath`]){let r=t[e];typeof r==`string`&&r&&n.push(r)}for(let e of[`changed_files`,`paths`,`files`]){let r=t[e];if(Array.isArray(r))for(let e of r){if(typeof e==`string`){n.push(e);continue}e&&typeof e==`object`&&typeof e.path==`string`&&n.push(e.path)}}if(Array.isArray(t.sources))for(let e of t.sources)e&&typeof e==`object`&&typeof e.path==`string`&&n.push(e.path);return n}let f=()=>a===`failed`?[`❌ AI Kit initialization failed — this tool is unavailable.`,``,o?`Error: ${o}`:``,``,`**${Va.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.`,``,Cy(o),``,`Try restarting the MCP server to retry initialization.`].filter(Boolean).join(`
3063
+ `)}async function Ty(e,t){let n=t.toLowerCase(),r;try{({rm:r}=await import(`node:fs/promises`))}catch{return}if(n.includes(`transformers.node.mjs`)&&n.includes(`cannot find module`)){let e=t.match(/Cannot find module '([^']+transformers\.node\.mjs)'/);if(e){let t=e[1],n=t.replace(/\.mjs$/,`.cjs`);try{let{existsSync:e,writeFileSync:r}=await import(`node:fs`);e(n)&&!e(t)&&(r(t,[`// Auto-generated ESM shim — published package missing this file`,`import { createRequire } from 'node:module';`,`const require = createRequire(import.meta.url);`,`const mod = require('./transformers.node.cjs');`,`export default mod;`,``].join(`
3064
+ `),`utf8`),$.info(`Auto-heal: created ESM shim for @huggingface/transformers (.mjs wrapper → .cjs)`,{path:t}))}catch(e){$.warn(`Auto-heal: failed to create ESM shim`,{error:e instanceof Error?e.message:String(e),path:t})}}}if(n.includes(`embedding`)||n.includes(`onnx`)||n.includes(`protobuf`)||n.includes(`model`)){let t=e.embedding?.model;if(t){let e=I(Wn(),`.cache`,`huggingface`,`transformers-js`,t);try{await r(e,{recursive:!0,force:!0}),$.info(`Auto-heal: cleared embedding model cache`,{path:e})}catch{}}}if(n.includes(`lance`)||n.includes(`database`)||n.includes(`store`)){let t=I(e.store.path,`lance`);try{await r(t,{recursive:!0,force:!0}),$.info(`Auto-heal: cleared LanceDB store`,{path:t})}catch{}}if(n.includes(`sqlite`)||n.includes(`database disk image`)||n.includes(`graph`)){let t=I(e.store.path,`graph.db`);try{await r(t,{force:!0}),$.info(`Auto-heal: cleared graph database`,{path:t})}catch{}let n=I(e.store.path,`aikit.db`);try{await r(n,{force:!0}),await r(`${n}-wal`,{force:!0}).catch(()=>{}),await r(`${n}-shm`,{force:!0}).catch(()=>{}),$.info(`Auto-heal: cleared corrupted aikit database`,{path:n})}catch{}}if(Wp(t)){let e=await qp(t);e.repaired||$.warn(`Auto-heal: missing runtime dependency repair did not complete`,{packages:e.packages,reason:e.reason,error:e.error,hint:`Run: npm cache clean --force && npx -y @vpxa/aikit@latest serve`})}else n.includes(`cannot find module`)&&!n.includes(`.cache`)&&$.warn(`Auto-heal: missing module detected during initialization cleanup`,{hint:`Run: npm cache clean --force && npx -y @vpxa/aikit@latest serve`})}function Ey(e,t){let n=Ns(e,Ba,U,is(e)),r=ay(e,n,U),i=new Kn({name:e.serverName??`aikit`,version:ae()},{capabilities:{logging:{},completions:{},prompts:{}},instructions:r}),a=`initializing`,o=``,s=!1,c=null,l=null,u=null;function d(e){if(!e||typeof e!=`object`)return[];let t=e,n=[];for(let e of[`path`,`file`,`source_path`,`sourcePath`,`filePath`]){let r=t[e];typeof r==`string`&&r&&n.push(r)}for(let e of[`changed_files`,`paths`,`files`]){let r=t[e];if(Array.isArray(r))for(let e of r){if(typeof e==`string`){n.push(e);continue}e&&typeof e==`object`&&typeof e.path==`string`&&n.push(e.path)}}if(Array.isArray(t.sources))for(let e of t.sources)e&&typeof e==`object`&&typeof e.path==`string`&&n.push(e.path);return n}let f=()=>a===`failed`?[`❌ AI Kit initialization failed — this tool is unavailable.`,``,o?`Error: ${o}`:``,``,`**${Va.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.`,``,wy(o),``,`Try restarting the MCP server to retry initialization.`].filter(Boolean).join(`
3064
3065
  `):[`AI Kit is still initializing (loading embeddings model & store).`,``,`**${Va.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(`
3065
- `);Gr(i);let p=new Eo;p.use(ss(),{order:1,name:`structured-content-guard`}),vs(i,p,e.toolPrefix??``);let m=i.sendToolListChanged.bind(i);i.sendToolListChanged=()=>{};let h=[];for(let e of Ba){if(!n.has(e))continue;let t=W(e),r=i.registerTool(e,{title:t.title,description:`${t.title} — initializing, available shortly`,inputSchema:{},annotations:t.annotations},async()=>({content:[{type:`text`,text:f()}]}));Va.has(e)?r.remove():h.push(r)}$v(i,e,n),i.sendToolListChanged=m;let g=i.registerResource(`aikit-status`,`aikit://status`,{description:`AI Kit status (initializing...)`,mimeType:`text/plain`},async()=>({contents:[{uri:`aikit://status`,text:`AI Kit is initializing...`,mimeType:`text/plain`}]})),_=i.registerPrompt(`_init`,{description:`Initializing AI Kit…`,argsSchema:{_dummy:Qn(R.string(),()=>[])}},async()=>({messages:[]})),v,y,b=new Promise((e,t)=>{v=e,y=t}),x,S=new Promise(e=>{x=e}),C=()=>x?.(),w=(async()=>{await S;try{let{createRequire:e}=await import(`node:module`),{readFileSync:t,existsSync:n}=await import(`node:fs`),{fileURLToPath:r}=await import(`node:url`),{resolve:i,dirname:a}=await import(`node:path`),o=e(import.meta.url),s=a(r(import.meta.url)),c=i(s,`..`,`package.json`),l=i(s,`..`,`..`),u=JSON.parse(t(c,`utf8`)),d=Object.keys(u.dependencies??{}),f=[`@mixmark-io/domino`],p=[...d,...f.filter(e=>!d.includes(e))],m=p.filter(e=>!e.startsWith(`@aikit/`)),h=p.filter(e=>e.startsWith(`@aikit/`)),g=[];for(let e of m)try{o.resolve(e)}catch{try{o.resolve(`${e}/package.json`)}catch{g.push(e)}}g.length>0&&$.warn(`Dependencies not resolvable — server may operate in degraded mode`,{missing:g,hint:`Run: npm cache clean --force && npx -y @vpxa/aikit@latest serve`});let _=[];if(h.length>0){for(let e of h)n(i(l,e.slice(7),`dist`))||_.push(e);_.length>0&&$.warn(`Workspace sibling packages missing dist — server may have degraded features`,{missing:_,hint:`Reinstall: npm cache clean --force && npx -y @vpxa/aikit@latest serve`})}}catch{}let n;try{n=await ry(e)}catch(t){let r=t instanceof Error?t.message:String(t);if(Sy(r)){$.warn(`AI Kit initialization failed with recoverable error — attempting auto-heal retry`,{error:r}),await wy(e,r);try{n=await ry(e),$.info(`AI Kit auto-heal successful — initialization recovered after retry`)}catch(e){a=`failed`,o=e instanceof Error?e.message:String(e),$.error(`AI Kit initialization failed after auto-heal attempt — server continuing with zero-dep tools only`,{error:o,originalError:r}),y?.(e instanceof Error?e:Error(o));return}}else{a=`failed`,o=r,$.error(`AI Kit initialization failed — server continuing with zero-dep tools only`,{error:o}),y?.(t instanceof Error?t:Error(o));return}}let r=i.sendToolListChanged.bind(i);i.sendToolListChanged=()=>{};let f=i.sendPromptListChanged.bind(i);i.sendPromptListChanged=()=>{};let p=i.sendResourceListChanged.bind(i);i.sendResourceListChanged=()=>{};for(let e of h)e.remove();g.remove(),_.remove();let m=i._registeredTools??{};for(let e of Va)m[e]?.remove();let b=new ty(i),x=gu(i);Qv({server:i,aikit:n,config:e,elicitor:Ur(i),resourceNotifier:b,samplingClient:x,indexMode:t,getSmartState:t===`smart`?(()=>{let e=u;return e?.getState?e.getState():null}):null,getSmartScheduler:t===`smart`?()=>{let e=u;return e?{prioritize:e.prioritize.bind(e)}:null}:null}),ni(i,{curated:n.curated,store:n.store,graphStore:n.graphStore,stateStore:n.stateStore},t),i.sendToolListChanged=r,i.sendPromptListChanged=f,i.sendResourceListChanged=p,Promise.resolve(i.sendToolListChanged()).catch(()=>{}),Promise.resolve(i.sendPromptListChanged()).catch(()=>{}),Promise.resolve(i.sendResourceListChanged()).catch(()=>{});let C=i._registeredTools??{};for(let[e,t]of Object.entries(C)){if(Ha.has(e))continue;let r=t.handler;t.handler=async(...i)=>{if(!n.indexer.isIndexing)return r(...i);let a=s?`re-indexing`:`running initial index`,o=new Promise(n=>setTimeout(()=>n({content:[{type:`text`,text:`⏳ AI Kit is ${a}. The tool "${e}" timed out waiting for index data (${as/1e3}s).\n\nThe existing index may be temporarily locked. Please retry shortly — indexing will complete automatically.`}],...t.config?.outputSchema?{structuredContent:ps(t.config.outputSchema)}:{}}),as));return Promise.race([r(...i),o])}}for(let[e,t]of Object.entries(C)){let n=t.handler,r=hy(e);t.handler=async(...i)=>{try{return await gy(e=>fy(e,()=>n(...i)),r,e)}catch(n){if(n instanceof my)return{content:[{type:`text`,text:`⏳ Tool "${e}" timed out after ${r/1e3}s. This may indicate a long-running operation. Please retry or break the task into smaller steps.`}],...t.config?.outputSchema?{structuredContent:ps(t.config.outputSchema)}:{}};throw n}}}let w=Object.keys(C).length;w<Ba.length&&$.warn(`ALL_TOOL_NAMES count mismatch`,{expectedToolCount:Ba.length,registeredToolCount:w}),$.debug(`MCP server configured`,{toolCount:Ba.length,resourceCount:4});let T=new uy;T.onPressure((e,t)=>{e===`warning`&&Yr(),e===`critical`&&($.warn(`Memory pressure critical — consider restarting`,{rssMB:Math.round(t/1024/1024)}),Yr())}),T.registerMemoryPressureCallback(()=>n.embedder.shutdown?.()),T.start();let D=new cy;l=D,D.onIdle(async()=>{if(E.isRunning||n.indexer.isIndexing){$.info(`Idle cleanup deferred — background tasks still running`),D.touch();return}$.info(`Idle cleanup: releasing cached memory (connections stay open)`);try{n.store.releaseMemory?.(),n.graphStore.releaseMemory?.()}catch{}}),D.touch();let O=!1;for(let e of Object.values(C)){let t=e.handler;e.handler=async(...e)=>{if(O||(O=!0,D.markSessionActive()),D.touch(),u){let t=d(e[0]);t.length>0&&u.prioritize(...t)}return t(...e)}}xy(C,n,{statePath:e.stateDir??``});for(let[,e]of Object.entries(C)){let t=e.config?.outputSchema;if(!t)continue;let n=e.handler;e.handler=async(...e)=>{let r=await n(...e);if(!r||typeof r!=`object`)return r;let i=r;return!(`content`in i)||i.isError||i.structuredContent!=null&&typeof i.structuredContent==`object`?r:(i.structuredContent=ps(t),i.structuredContent??={},r)}}process.stdin.on(`end`,()=>($.info(`stdin closed — MCP client disconnected. Shutting down.`),process.exit(0))),process.stdin.on(`error`,()=>($.info(`stdin error — MCP client disconnected. Shutting down.`),process.exit(0))),c=n,v?.(n)})(),T=async()=>{let t;try{t=await b}catch{$.warn(`Skipping initial index — AI Kit initialization failed`);return}l?.setBusy(!0);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}))});s=!0,$.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`,N(e))}try{let e=await t.curated.reindexAll();$.info(`Curated re-index complete`,{indexed:e.indexed})}catch(e){$.error(`Curated re-index failed`,N(e))}}catch(e){$.error(`Initial index failed; will retry on aikit_reindex`,N(e))}finally{l?.setBusy(!1)}},E=new oy,D=()=>E.schedule({name:`initial-index`,fn:T}),O=process.ppid,k=setInterval(()=>{try{process.kill(O,0)}catch{$.info(`Parent process died; shutting down`,{parentPid:O}),clearInterval(k),u?.stop&&u.stop(),import(`../../tools/dist/index.js`).then(({processStopAll:e})=>e()).catch(()=>{}),b.then(async e=>{await Promise.all([e.embedder.shutdown?.().catch(()=>{})??Promise.resolve(),e.graphStore.close().catch(()=>{}),e.closeStateStore?.().catch(()=>{})??Promise.resolve(),e.store.close().catch(()=>{})])}).catch(()=>{}).finally(()=>process.exit(0))}},5e3);return k.unref(),{server:i,startInit:C,ready:w,runInitialIndex:D,get aikit(){return c},scheduler:E,setSmartScheduler(e){u=e}}}const Ey=M(`server`);function Dy(e,t){let n=Ns(t,[...Ba,...ns],U,is(t)),r=iy(t,n,U),i=new Kn({name:t.serverName??`aikit`,version:ae()},{capabilities:{logging:{},completions:{},prompts:{},extensions:{roots:{}}},instructions:r}),a=i;return a.setNotificationHandler(Jn,async()=>{try{let{roots:e}=await a.listRoots();if(e&&e.length>0){let n=ce(e[0].uri);process.env.AIKIT_TRANSPORT===`http`?(t.sources[0]={path:n,excludePatterns:t.sources[0]?.excludePatterns??[]},t.allRoots=e.map(e=>ce(e.uri)),Ey.info(`Workspace root updated (HTTP mode)`,{rootPath:n,sourceCount:t.sources.length})):(x(t,n),Ey.info(`Workspace root updated (stdio mode)`,{rootPath:n}))}}catch(e){Ey.debug(`MCP roots/list not available`,{error:N(e)})}}),Gr(i),Qv({server:i,aikit:e,config:t,elicitor:Ur(i),resourceNotifier:new ty(i),samplingClient:gu(i),precomputedActiveTools:n}),ni(i,{curated:e.curated,store:e.store,graphStore:e.graphStore,stateStore:e.stateStore},t.indexMode),i}async function Oy(e){let t=await ry(e),n=Dy(t,e);Ey.debug(`MCP server configured`,{toolCount:Ba.length,resourceCount:2});let r=async()=>{try{let n=e.sources.map(e=>e.path).join(`, `);Ey.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&&Ey.debug(`Indexing file`,{current:e.filesProcessed+1,total:e.filesTotal,file:e.currentFile}),e.phase===`cleanup`&&Ey.debug(`Index cleanup`,{staleEntries:e.filesTotal-e.filesProcessed}))});Ey.info(`Initial index complete`,{filesProcessed:r.filesProcessed,filesSkipped:r.filesSkipped,chunksCreated:r.chunksCreated,durationMs:r.durationMs});try{await t.store.createFtsIndex()}catch(e){Ey.warn(`FTS index creation failed`,N(e))}try{let e=await t.curated.reindexAll();Ey.info(`Curated re-index complete`,{indexed:e.indexed})}catch(e){Ey.error(`Curated re-index failed`,N(e))}}catch(e){Ey.error(`Initial index failed; will retry on aikit_reindex`,N(e))}},i=async()=>{Ey.info(`Shutting down`),await import(`../../tools/dist/index.js`).then(({processStopAll:e})=>e()).catch(()=>{}),await Promise.all([t.embedder.shutdown?.().catch(()=>{})??Promise.resolve(),t.graphStore.close().catch(()=>{}),t.closeStateStore?.().catch(()=>{})??Promise.resolve(),t.store.close().catch(()=>{})]),process.exit(0)};process.on(`SIGINT`,i),process.on(`SIGTERM`,i);let a=process.ppid,o=setInterval(()=>{try{process.kill(a,0)}catch{Ey.info(`Parent process died; shutting down`,{parentPid:a}),clearInterval(o),i()}},5e3);return o.unref(),{server:n,runInitialIndex:r,shutdown:i}}export{Ba as ALL_TOOL_NAMES,Ty as createLazyServer,Dy as createMcpServer,Oy as createServer,ry as initializeAikit,Qv as registerMcpTools};
3066
+ `);Gr(i);let p=new Eo;p.use(ss(),{order:1,name:`structured-content-guard`}),vs(i,p,e.toolPrefix??``);let m=i.sendToolListChanged.bind(i);i.sendToolListChanged=()=>{};let h=[];for(let e of Ba){if(!n.has(e))continue;let t=W(e),r=i.registerTool(e,{title:t.title,description:`${t.title} — initializing, available shortly`,inputSchema:{},annotations:t.annotations},async()=>({content:[{type:`text`,text:f()}]}));Va.has(e)?r.remove():h.push(r)}ey(i,e,n),i.sendToolListChanged=m;let g=i.registerResource(`aikit-status`,`aikit://status`,{description:`AI Kit status (initializing...)`,mimeType:`text/plain`},async()=>({contents:[{uri:`aikit://status`,text:`AI Kit is initializing...`,mimeType:`text/plain`}]})),_=i.registerPrompt(`_init`,{description:`Initializing AI Kit…`,argsSchema:{_dummy:Qn(R.string(),()=>[])}},async()=>({messages:[]})),v,y,b=new Promise((e,t)=>{v=e,y=t}),x,S=new Promise(e=>{x=e}),C=()=>x?.(),w=(async()=>{await S;try{let{createRequire:e}=await import(`node:module`),{readFileSync:t,existsSync:n}=await import(`node:fs`),{fileURLToPath:r}=await import(`node:url`),{resolve:i,dirname:a}=await import(`node:path`),o=e(import.meta.url),s=a(r(import.meta.url)),c=i(s,`..`,`package.json`),l=i(s,`..`,`..`),u=JSON.parse(t(c,`utf8`)),d=Object.keys(u.dependencies??{}),f=[`@mixmark-io/domino`],p=[...d,...f.filter(e=>!d.includes(e))],m=p.filter(e=>!e.startsWith(`@aikit/`)),h=p.filter(e=>e.startsWith(`@aikit/`)),g=[];for(let e of m)try{o.resolve(e)}catch{try{o.resolve(`${e}/package.json`)}catch{g.push(e)}}g.length>0&&$.warn(`Dependencies not resolvable — server may operate in degraded mode`,{missing:g,hint:`Run: npm cache clean --force && npx -y @vpxa/aikit@latest serve`});let _=[];if(h.length>0){for(let e of h)n(i(l,e.slice(7),`dist`))||_.push(e);_.length>0&&$.warn(`Workspace sibling packages missing dist — server may have degraded features`,{missing:_,hint:`Reinstall: npm cache clean --force && npx -y @vpxa/aikit@latest serve`})}}catch{}let n;try{n=await iy(e)}catch(t){let r=t instanceof Error?t.message:String(t);if(Cy(r)){$.warn(`AI Kit initialization failed with recoverable error — attempting auto-heal retry`,{error:r}),await Ty(e,r);try{n=await iy(e),$.info(`AI Kit auto-heal successful — initialization recovered after retry`)}catch(e){a=`failed`,o=e instanceof Error?e.message:String(e),$.error(`AI Kit initialization failed after auto-heal attempt — server continuing with zero-dep tools only`,{error:o,originalError:r}),y?.(e instanceof Error?e:Error(o));return}}else{a=`failed`,o=r,$.error(`AI Kit initialization failed — server continuing with zero-dep tools only`,{error:o}),y?.(t instanceof Error?t:Error(o));return}}let r=i.sendToolListChanged.bind(i);i.sendToolListChanged=()=>{};let f=i.sendPromptListChanged.bind(i);i.sendPromptListChanged=()=>{};let p=i.sendResourceListChanged.bind(i);i.sendResourceListChanged=()=>{};for(let e of h)e.remove();g.remove(),_.remove();let m=i._registeredTools??{};for(let e of Va)m[e]?.remove();let b=new ny(i),x=gu(i);$v({server:i,aikit:n,config:e,elicitor:Ur(i),resourceNotifier:b,samplingClient:x,indexMode:t,getSmartState:t===`smart`?(()=>{let e=u;return e?.getState?e.getState():null}):null,getSmartScheduler:t===`smart`?()=>{let e=u;return e?{prioritize:e.prioritize.bind(e)}:null}:null}),ni(i,{curated:n.curated,store:n.store,graphStore:n.graphStore,stateStore:n.stateStore},t),i.sendToolListChanged=r,i.sendPromptListChanged=f,i.sendResourceListChanged=p,Promise.resolve(i.sendToolListChanged()).catch(()=>{}),Promise.resolve(i.sendPromptListChanged()).catch(()=>{}),Promise.resolve(i.sendResourceListChanged()).catch(()=>{});let C=i._registeredTools??{};for(let[e,t]of Object.entries(C)){if(Ha.has(e))continue;let r=t.handler;t.handler=async(...i)=>{if(!n.indexer.isIndexing)return r(...i);let a=s?`re-indexing`:`running initial index`,o=new Promise(n=>setTimeout(()=>n({content:[{type:`text`,text:`⏳ AI Kit is ${a}. The tool "${e}" timed out waiting for index data (${as/1e3}s).\n\nThe existing index may be temporarily locked. Please retry shortly — indexing will complete automatically.`}],...t.config?.outputSchema?{structuredContent:ps(t.config.outputSchema)}:{}}),as));return Promise.race([r(...i),o])}}for(let[e,t]of Object.entries(C)){let n=t.handler,r=gy(e);t.handler=async(...i)=>{try{return await _y(e=>py(e,()=>n(...i)),r,e)}catch(n){if(n instanceof hy)return{content:[{type:`text`,text:`⏳ Tool "${e}" timed out after ${r/1e3}s. This may indicate a long-running operation. Please retry or break the task into smaller steps.`}],...t.config?.outputSchema?{structuredContent:ps(t.config.outputSchema)}:{}};throw n}}}let w=Object.keys(C).length;w<Ba.length&&$.warn(`ALL_TOOL_NAMES count mismatch`,{expectedToolCount:Ba.length,registeredToolCount:w}),$.debug(`MCP server configured`,{toolCount:Ba.length,resourceCount:4});let T=new dy;T.onPressure((e,t)=>{e===`warning`&&Yr(),e===`critical`&&($.warn(`Memory pressure critical — consider restarting`,{rssMB:Math.round(t/1024/1024)}),Yr())}),T.registerMemoryPressureCallback(()=>n.embedder.shutdown?.()),T.start();let D=new ly;l=D,D.onIdle(async()=>{if(E.isRunning||n.indexer.isIndexing){$.info(`Idle cleanup deferred — background tasks still running`),D.touch();return}$.info(`Idle cleanup: releasing cached memory (connections stay open)`);try{n.store.releaseMemory?.(),n.graphStore.releaseMemory?.()}catch{}}),D.touch();let O=!1;for(let e of Object.values(C)){let t=e.handler;e.handler=async(...e)=>{if(O||(O=!0,D.markSessionActive()),D.touch(),u){let t=d(e[0]);t.length>0&&u.prioritize(...t)}return t(...e)}}Sy(C,n,{statePath:e.stateDir??``});for(let[,e]of Object.entries(C)){let t=e.config?.outputSchema;if(!t)continue;let n=e.handler;e.handler=async(...e)=>{let r=await n(...e);if(!r||typeof r!=`object`)return r;let i=r;return!(`content`in i)||i.isError||i.structuredContent!=null&&typeof i.structuredContent==`object`?r:(i.structuredContent=ps(t),i.structuredContent??={},r)}}process.stdin.on(`end`,()=>($.info(`stdin closed — MCP client disconnected. Shutting down.`),process.exit(0))),process.stdin.on(`error`,()=>($.info(`stdin error — MCP client disconnected. Shutting down.`),process.exit(0))),c=n,v?.(n)})(),T=async()=>{let t;try{t=await b}catch{$.warn(`Skipping initial index — AI Kit initialization failed`);return}l?.setBusy(!0);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}))});s=!0,$.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`,N(e))}try{let e=await t.curated.reindexAll();$.info(`Curated re-index complete`,{indexed:e.indexed})}catch(e){$.error(`Curated re-index failed`,N(e))}}catch(e){$.error(`Initial index failed; will retry on aikit_reindex`,N(e))}finally{l?.setBusy(!1)}},E=new sy,D=()=>E.schedule({name:`initial-index`,fn:T}),O=process.ppid,k=setInterval(()=>{try{process.kill(O,0)}catch{$.info(`Parent process died; shutting down`,{parentPid:O}),clearInterval(k),u?.stop&&u.stop(),import(`../../tools/dist/index.js`).then(({processStopAll:e})=>e()).catch(()=>{}),b.then(async e=>{await Promise.all([e.embedder.shutdown?.().catch(()=>{})??Promise.resolve(),e.graphStore.close().catch(()=>{}),e.closeStateStore?.().catch(()=>{})??Promise.resolve(),e.store.close().catch(()=>{})])}).catch(()=>{}).finally(()=>process.exit(0))}},5e3);return k.unref(),{server:i,startInit:C,ready:w,runInitialIndex:D,get aikit(){return c},scheduler:E,setSmartScheduler(e){u=e}}}const Dy=M(`server`);function Oy(e,t){let n=Ns(t,[...Ba,...ns],U,is(t)),r=ay(t,n,U),i=new Kn({name:t.serverName??`aikit`,version:ae()},{capabilities:{logging:{},completions:{},prompts:{},extensions:{roots:{}}},instructions:r}),a=i;return a.setNotificationHandler(Jn,async()=>{try{let{roots:e}=await a.listRoots();if(e&&e.length>0){let n=ce(e[0].uri);process.env.AIKIT_TRANSPORT===`http`?(t.sources[0]={path:n,excludePatterns:t.sources[0]?.excludePatterns??[]},t.allRoots=e.map(e=>ce(e.uri)),Dy.info(`Workspace root updated (HTTP mode)`,{rootPath:n,sourceCount:t.sources.length})):(x(t,n),Dy.info(`Workspace root updated (stdio mode)`,{rootPath:n}))}}catch(e){Dy.debug(`MCP roots/list not available`,{error:N(e)})}}),Gr(i),$v({server:i,aikit:e,config:t,elicitor:Ur(i),resourceNotifier:new ny(i),samplingClient:gu(i),precomputedActiveTools:n}),ni(i,{curated:e.curated,store:e.store,graphStore:e.graphStore,stateStore:e.stateStore},t.indexMode),i}async function ky(e){let t=await iy(e),n=Oy(t,e);Dy.debug(`MCP server configured`,{toolCount:Ba.length,resourceCount:2});let r=async()=>{try{let n=e.sources.map(e=>e.path).join(`, `);Dy.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&&Dy.debug(`Indexing file`,{current:e.filesProcessed+1,total:e.filesTotal,file:e.currentFile}),e.phase===`cleanup`&&Dy.debug(`Index cleanup`,{staleEntries:e.filesTotal-e.filesProcessed}))});Dy.info(`Initial index complete`,{filesProcessed:r.filesProcessed,filesSkipped:r.filesSkipped,chunksCreated:r.chunksCreated,durationMs:r.durationMs});try{await t.store.createFtsIndex()}catch(e){Dy.warn(`FTS index creation failed`,N(e))}try{let e=await t.curated.reindexAll();Dy.info(`Curated re-index complete`,{indexed:e.indexed})}catch(e){Dy.error(`Curated re-index failed`,N(e))}}catch(e){Dy.error(`Initial index failed; will retry on aikit_reindex`,N(e))}},i=async()=>{Dy.info(`Shutting down`),await import(`../../tools/dist/index.js`).then(({processStopAll:e})=>e()).catch(()=>{}),await Promise.all([t.embedder.shutdown?.().catch(()=>{})??Promise.resolve(),t.graphStore.close().catch(()=>{}),t.closeStateStore?.().catch(()=>{})??Promise.resolve(),t.store.close().catch(()=>{})]),process.exit(0)};process.on(`SIGINT`,i),process.on(`SIGTERM`,i);let a=process.ppid,o=setInterval(()=>{try{process.kill(a,0)}catch{Dy.info(`Parent process died; shutting down`,{parentPid:a}),clearInterval(o),i()}},5e3);return o.unref(),{server:n,runInitialIndex:r,shutdown:i}}export{Ba as ALL_TOOL_NAMES,Ey as createLazyServer,Oy as createMcpServer,ky as createServer,iy as initializeAikit,$v as registerMcpTools};