@vpxa/aikit 0.1.312 → 0.1.314

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.
@@ -2916,8 +2916,8 @@ window.addEventListener('message', function(e) {
2916
2916
  </body>`)}function Kh(e){if(!e.headersSent)try{e.writeHead(500,{"Content-Type":`text/plain`}),e.end(`Internal Server Error`)}catch{try{e.end()}catch{}}}async function qh(e){let t=Zn();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 Jh(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 qh(t);e.writeHead(200,{"Content-Type":`image/png`,"Cache-Control":`no-store`}),e.end(n)}catch{Kh(e)}}function Yh(e,t){return e.replace(/'\/callback'/g,`'/present/${t}/callback'`).replace(/"\/callback"/g,`"/present/${t}/callback"`)}function Xh(e,t){return e.replace(/src="\/viewer"/g,`src="/present/${t}/viewer"`)}async function Zh(e,t){if(wg(`<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(`
2917
2917
  `);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=Gh(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=Xh(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>`,` ${Wh(i)}`,`</div>`].join(`
2918
2918
  `),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(`
2919
- `)],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 Vh(l),setTimeout(()=>{Oh.delete(o),r.removeSession(o)},Sh),{content:[{type:`text`,text:Hh(e,l,`Rendered.`)}],structuredContent:{kind:`rendered`,reason:`no-response-required`}}}async function Qh(e){wg(`<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=Yh(kr({title:e.title,subtitle:e.description,html:[r.html,zh(r.actions,o.nonce)].filter(Boolean).join(`
2920
- `),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}),a);Oh.set(a,{callbackSession:o,html:c,hasClientConnected:!1,createdAt:Date.now()});let l=``;try{l=`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 u=await Vh(l);if(!Uh(r.actions))return setTimeout(()=>{Oh.delete(a);try{t.removeSession(a)}catch{}},Sh),{content:[{type:`text`,text:Hh(e,l,`Rendered.`)}],structuredContent:{kind:`rendered`,reason:`no-response-required`}};let d=await Promise.race([o.promise,new Promise(e=>{setTimeout(()=>{Oh.get(a)?.hasClientConnected||(Oh.delete(a),e(o.settleError(`BROWSER_CONNECT_TIMEOUT`,u?`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 f=d.kind===`result`?`Selected action: ${d.result.actionId}`:d.kind===`timeout`?`Timed out after ${d.waitedMs}ms.`:d.kind===`cancelled`?`Cancelled: ${d.reason}.`:d.kind===`error`?`Error: ${d.error.message}`:`Rendered.`;return{content:[{type:`text`,text:Hh(e,l,f)}],structuredContent:d,isError:d.kind===`error`}}const $h={id:`browser`,priority:20,canHandle(e,t){let n=Ug(e);return Gm(n)||!!t.preferBrowser&&!!Wg(n)},async render(e,t){return Qh(e)}},eg=`openai/outputTemplate`,tg=`ui/resourceUri`,ng={connectDomains:[],resourceDomains:[]},rg={connect_domains:[],resource_domains:[]};function ig(e){return{ui:{resourceUri:e,visibility:[`model`,`app`]},[tg]:e,[eg]:e,"openai/widgetAccessible":!0}}function ag(){return{ui:{prefersBorder:!1,csp:ng},"openai/widgetDescription":`AI Kit renders structured visual surfaces such as dashboards, charts, reports, and diagrams.`,"openai/widgetPrefersBorder":!1,"openai/widgetCSP":rg}}function og(e){return{ui:{resourceUri:e},[tg]:e,[eg]:e}}function sg(e){return{...e,schemaVersion:1}}function cg(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=qg(r);wg(a);let o=Gg(e,i,{includeSurfaceHeader:!1}),s=Sg(),c=Dg(s);return c&&Tg(c,a),{content:[{type:`text`,text:o}],structuredContent:sg(e),_meta:og(s),ui:{type:`resource`,uri:s}}}catch(t){return Yg(`RENDER_FAILED`,t instanceof Error?t.message:`Failed to render ChannelSurface`,void 0,e.title)}}const lg={id:`mcp-app`,priority:30,canHandle(e,t){return!0},async render(e,t){return cg(e)}};var ug=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 dg(e){return`<script nonce="${Y(e)}">
2919
+ `)],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 Vh(l),setTimeout(()=>{Oh.delete(o),r.removeSession(o)},Sh),{content:[{type:`text`,text:Hh(e,l,`Rendered.`)}],structuredContent:{kind:`rendered`,reason:`no-response-required`}}}async function Qh(e){wg(`<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=Yh(Xg(kr({title:e.title,subtitle:e.description,html:[r.html,zh(r.actions,o.nonce)].filter(Boolean).join(`
2920
+ `),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})),a);Oh.set(a,{callbackSession:o,html:c,hasClientConnected:!1,createdAt:Date.now()});let l=``;try{l=`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 u=await Vh(l);if(!Uh(r.actions))return setTimeout(()=>{Oh.delete(a);try{t.removeSession(a)}catch{}},Sh),{content:[{type:`text`,text:Hh(e,l,`Rendered.`)}],structuredContent:{kind:`rendered`,reason:`no-response-required`}};let d=await Promise.race([o.promise,new Promise(e=>{setTimeout(()=>{Oh.get(a)?.hasClientConnected||(Oh.delete(a),e(o.settleError(`BROWSER_CONNECT_TIMEOUT`,u?`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 f=d.kind===`result`?`Selected action: ${d.result.actionId}`:d.kind===`timeout`?`Timed out after ${d.waitedMs}ms.`:d.kind===`cancelled`?`Cancelled: ${d.reason}.`:d.kind===`error`?`Error: ${d.error.message}`:`Rendered.`;return{content:[{type:`text`,text:Hh(e,l,f)}],structuredContent:d,isError:d.kind===`error`}}const $h={id:`browser`,priority:20,canHandle(e,t){let n=Ug(e);return Gm(n)||!!t.preferBrowser&&!!Wg(n)},async render(e,t){return Qh(e)}},eg=`openai/outputTemplate`,tg=`ui/resourceUri`,ng={connectDomains:[],resourceDomains:[]},rg={connect_domains:[],resource_domains:[]};function ig(e){return{ui:{resourceUri:e,visibility:[`model`,`app`]},[tg]:e,[eg]:e,"openai/widgetAccessible":!0}}function ag(){return{ui:{prefersBorder:!1,csp:ng},"openai/widgetDescription":`AI Kit renders structured visual surfaces such as dashboards, charts, reports, and diagrams.`,"openai/widgetPrefersBorder":!1,"openai/widgetCSP":rg}}function og(e){return{ui:{resourceUri:e},[tg]:e,[eg]:e}}function sg(e){return{...e,schemaVersion:1}}function cg(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=Xg(qg(r));wg(a);let o=Gg(e,i,{includeSurfaceHeader:!1}),s=Sg(),c=Dg(s);return c&&Tg(c,a),{content:[{type:`text`,text:o}],structuredContent:sg(e),_meta:og(s),ui:{type:`resource`,uri:s}}}catch(t){return Qg(`RENDER_FAILED`,t instanceof Error?t.message:`Failed to render ChannelSurface`,void 0,e.title)}}const lg={id:`mcp-app`,priority:30,canHandle(e,t){return!0},async render(e,t){return cg(e)}};var ug=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 dg(e){return`<script nonce="${Y(e)}">
2921
2921
  (function() {
2922
2922
  const iframe = document.querySelector('.present-viewer-iframe');
2923
2923
  if (!iframe) return;
@@ -2940,8 +2940,8 @@ window.addEventListener('message', function(e) {
2940
2940
  });
2941
2941
  <\/script>`}async function pg(e,t){try{let n=Kg(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`};wg(qg(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>`,` ${dg(r)}`,` ${fg(r)}`,`</div>`].join(`
2942
2942
  `),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(`
2943
- `)],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=Gg(e,i,{includeSurfaceHeader:!1}),o=Sg();return{content:[{type:`text`,text:a}],structuredContent:sg(e),_meta:og(o),ui:{type:`resource`,uri:o}}}catch(t){return Yg(`VIEWER_RENDER_FAILED`,t instanceof Error?t.message:`Failed to render viewer template`,void 0,e.title)}}const mg={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 Yg(`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(`
2944
- `);return Yg(`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 Zh(e,n):i?pg(e,n):Yg(`VIEWER_TRANSPORT_UNSUPPORTED`,`Viewer template "${n.id}" does not support an available transport`,void 0,e.title)}},hg=`ui://aikit/present.html`,gg=`ui://aikit/present/{id}.html`,_g=M(`present`);let vg=0,yg=``;const bg=new Map,xg=new Map;function Sg(){return`ui://aikit/present/${`${Date.now().toString(36)}_${(++vg).toString(36)}`}.html`}function Cg(){return yg}function wg(e){yg=e}function Tg(e,t){let n=xg.get(e);n&&clearTimeout(n),bg.set(e,t),xg.set(e,setTimeout(()=>{bg.delete(e),xg.delete(e)},3e4))}function Eg(e){return bg.get(e)}function Dg(e){return e.match(/\/present\/(.+)\.html$/)?.[1]}const Og=new ug;Og.register(mg),Og.register($h),Og.register(lg);function kg(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const Ag=/\\u[0-9a-fA-F]{4}/,jg=/^\s*\|(?:[^|\r\n]+\|){2,}\s*$/,Mg=/^\s*\|?(?:\s*:?-{3,}:?\s*\|){2,}\s*$/,Ng=/\b(cli|terminal|tty|console|command(?:-|\s)?line)\b/i;function Pg(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 Fg(e){let t=e.split(/\r?\n/);for(let e=0;e<t.length-1;e+=1)if(jg.test(t[e])&&Mg.test(t[e+1]))return!0;return!1}function Ig(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 Lg(e,t){if(t<2)return!1;let n=e.trim();return n.startsWith(`|`)?Ig(n).length===t:!1}function Rg(e){let t=e.split(/\r?\n/),n=[],r=[],i=()=>{r.length!==0&&(n.push({type:`text`,content:r.join(`
2943
+ `)],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=Gg(e,i,{includeSurfaceHeader:!1}),o=Sg();return{content:[{type:`text`,text:a}],structuredContent:sg(e),_meta:og(o),ui:{type:`resource`,uri:o}}}catch(t){return Qg(`VIEWER_RENDER_FAILED`,t instanceof Error?t.message:`Failed to render viewer template`,void 0,e.title)}}const mg={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 Qg(`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(`
2944
+ `);return Qg(`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 Zh(e,n):i?pg(e,n):Qg(`VIEWER_TRANSPORT_UNSUPPORTED`,`Viewer template "${n.id}" does not support an available transport`,void 0,e.title)}},hg=`ui://aikit/present.html`,gg=`ui://aikit/present/{id}.html`,_g=M(`present`);let vg=0,yg=``;const bg=new Map,xg=new Map;function Sg(){return`ui://aikit/present/${`${Date.now().toString(36)}_${(++vg).toString(36)}`}.html`}function Cg(){return yg}function wg(e){yg=e}function Tg(e,t){let n=xg.get(e);n&&clearTimeout(n),bg.set(e,t),xg.set(e,setTimeout(()=>{bg.delete(e),xg.delete(e)},3e4))}function Eg(e){return bg.get(e)}function Dg(e){return e.match(/\/present\/(.+)\.html$/)?.[1]}const Og=new ug;Og.register(mg),Og.register($h),Og.register(lg);function kg(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const Ag=/\\u[0-9a-fA-F]{4}/,jg=/^\s*\|(?:[^|\r\n]+\|){2,}\s*$/,Mg=/^\s*\|?(?:\s*:?-{3,}:?\s*\|){2,}\s*$/,Ng=/\b(cli|terminal|tty|console|command(?:-|\s)?line)\b/i;function Pg(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 Fg(e){let t=e.split(/\r?\n/);for(let e=0;e<t.length-1;e+=1)if(jg.test(t[e])&&Mg.test(t[e+1]))return!0;return!1}function Ig(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 Lg(e,t){if(t<2)return!1;let n=e.trim();return n.startsWith(`|`)?Ig(n).length===t:!1}function Rg(e){let t=e.split(/\r?\n/),n=[],r=[],i=()=>{r.length!==0&&(n.push({type:`text`,content:r.join(`
2945
2945
  `)}),r.length=0)},a=0;for(;a<t.length;){let e=t[a],o=t[a+1];if(o!==void 0&&jg.test(e)&&Mg.test(o)){let r=Ig(e),o=[];i();let s=a+2;for(;s<t.length&&Lg(t[s],r.length);)o.push(Ig(t[s])),s+=1;n.push({type:`table`,headers:r,rows:o}),a=s;continue}r.push(e),a+=1}return i(),n}function zg(e){let t=Pg(e);return!t||!Fg(t)?[e]:Rg(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 Bg(e){if(typeof e==`string`)return Ng.test(e);if(Array.isArray(e))return e.some(e=>Bg(e));if(!kg(e))return!1;let t=[`client`,`clientInfo`,`host`,`source`,`mode`,`name`,`title`,`channel`];return Object.entries(e).some(([e,n])=>t.includes(e)?Bg(n):!1)}function Vg(e,t){return{preferBrowser:[t,e._meta,kg(e.metadata)?e.metadata.source:void 0].some(e=>Bg(e))}}const Hg={id:`__dismiss`,type:`button`,label:`Done`,variant:`default`};function Ug(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:[Hg]}:e}function Wg(e){if(!e.template)return!0;let t=_m(e.template);return t?t.supportedTransports.includes(`browser`):Wm(e)?.supportedTransports.includes(`browser`)??!1}function Gg(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(`
2946
2946
  `)}function Kg(e){let t=e.replace(`</head>`,`<style>
2947
2947
  .toolbar, .badge, body > header, body > footer { display: none !important; }
@@ -2977,12 +2977,26 @@ window.addEventListener('message', function(e) {
2977
2977
  if(typeof ResizeObserver!=="undefined"){new ResizeObserver(notify).observe(document.documentElement)}
2978
2978
  else{setInterval(notify,500)}
2979
2979
  })();
2980
- <\/script>`;return e.includes(`</body>`)?e.replace(`</body>`,`${t}</body>`):`${e}${t}`}function Jg(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(`
2981
- `)}function Yg(e,t,n,r){return wg(Jg(r??`Present`,t)),{content:[{type:`text`,text:`[ERROR:VALIDATION] ${t}`}],isError:!0}}function Xg(e,t){if(!kg(e)||!(`schemaVersion`in e))return{ok:!1,response:Yg(`INVALID_CHANNEL_SURFACE`,`present expects a ChannelSurface object with schemaVersion: 1`)};if(e.schemaVersion!==1)return{ok:!1,response:Yg(`UNSUPPORTED_SCHEMA_VERSION`,`Unsupported ChannelSurface schemaVersion: ${String(e.schemaVersion)}`)};if(typeof e.title==`string`&&Ag.test(e.title))return{ok:!1,response:Yg(`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(!kg(e)||e.type!==`markdown`)return[e];let t=Pg(e);return!t||!Fg(t)?[e]:zg(e)})}:e;return{ok:!0,surface:n,options:Vg(n,t)}}const Zg={id:`__feedback`,type:`text-submit`,label:`💬 Feedback`,variant:`default`};function Qg(e){return!e.actions||e.actions.length===0||e.actions.some(e=>e.id===`__feedback`)?e:{...e,actions:[...e.actions,Zg]}}function $g(e){return(e.actions?.length??0)>0||e.response?.required===!0?Og.getAll().some(e=>e.id===`browser`):!1}async function e_(e,t={}){let n=$g(e)?{...t,preferBrowser:!0}:t,r=Ug(e),i=Og.select(r,n),a=i?.id===`browser`?Qg(r):r,o;if(o=i?await i.render(a,n):cg(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 t_(e){return{type:`kv`,value:e}}function n_(e){if(Array.isArray(e))return e}const r_=[{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=n_(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(t_(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=n_(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=n_(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=n_(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=n_(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}}}],i_=new Map;for(let e of r_)i_.set(e.name,e);function a_(e,t){let n=i_.get(e);return n?n.expand(t):null}const o_={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`},s_=/^(#{1,6})\s/,c_=/^(`{3,}|~{3,})/,l_=/^\|.+\|.+\|/m;function u_(e){let t=e.trim(),n=t.match(s_);if(n)return{type:`heading`,value:t.slice(n[0].length)};if(c_.test(t)){let e=t.indexOf(`
2982
- `),n=t.lastIndexOf(t[0]);return{type:`code`,value:e>=0?t.slice(e+1,n).trimEnd():t}}return l_.test(t)?{type:`table`,value:t}:{type:`markdown`,value:t}}function d_(e,t){let n=o_[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 f_(e){if(typeof e==`string`){let t=u_(e);return{type:t.type,value:t.value}}if(Array.isArray(e)){let[t,n]=e;if(typeof t==`string`){let e=d_(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 p_(e){return{title:e.title??``,blocks:Array.isArray(e.blocks)?e.blocks.map(f_):[]}}function m_(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function h_(e){return m_(e)&&typeof e.schemaVersion==`number`&&e.schemaVersion===1}function g_(e){return m_(e)&&typeof e.schemaVersion==`number`&&e.schemaVersion!==1}function __(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 v_(e){try{let t=re(e);return m_(t)?(t.schemaVersion===void 0&&(t.schemaVersion=1),y_(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 y_(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(!m_(n))return{ok:!1,error:{code:`INVALID_PRESET_INPUT`,reason:`Preset data must be an object`}};let r=a_(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(g_(e))return{ok:!1,error:{code:`UNSUPPORTED_SCHEMA_VERSION`,reason:`Unsupported schemaVersion: ${String(e.schemaVersion)}`,hint:`Use schemaVersion: 1`}};if(h_(e))return __(e);if(typeof e==`string`){let t=p_({blocks:[e]});return{ok:!0,surface:{schemaVersion:1,title:t.title||`Present`,blocks:t.blocks}}}if(m_(e)){if(typeof e.raw==`string`)return v_(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=p_(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 b_=R.object({label:R.string(),value:R.string(),description:R.string().optional()}),x_=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(b_).optional(),schema:R.record(R.string(),R.unknown()).optional()}),S_=R.object({type:R.string(),title:R.string().optional(),value:R.unknown().optional(),language:R.string().optional()}).catchall(R.unknown()),C_={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(S_).optional().describe(`Typed block content for the surface.`),data:R.unknown().optional().describe(`Template data payload, if the template expands data.`),actions:R.array(x_).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 w_(e){let t=e.server?.getClientCapabilities?.();if(!t)return`unknown`;let n=_r(t);return!n||Array.isArray(n.mimeTypes)&&n.mimeTypes.length>0&&!n.mimeTypes.includes(gr)?`unsupported`:`supported`}const T_=[{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 E_(e,t){let n=W(`present`);yr(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:C_,annotations:n.annotations,_meta:ig(gg)},J(`present`,async(t,n)=>{let r=y_(t);if(!r.ok)return Yg(r.error.code,r.error.reason,void 0,`Present`);let i=Xg(r.surface,n);if(!i.ok)return i.response;let a=w_(e);return await e_(i.surface,{...i.options,preferBrowser:i.options.preferBrowser||a===`unsupported`})}));try{let t=new Gn(gg,{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?Eg(r):void 0;return{contents:[{uri:e.href,mimeType:gr,_meta:ag(),text:i??Cg()??`<html><body><p>No content generated yet. Call the present tool first.</p></body></html>`}]}})}catch{}try{e.registerResource(`Present App`,hg,{description:`AI Kit present app - entry point`},async()=>({contents:[{uri:hg,mimeType:gr,_meta:ag(),text:Cg()||`<html><body><p>No content generated yet. Call the present tool first.</p></body></html>`}]}))}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(T_,null,2)}]}))}catch{}}const D_=M(`tools`);function O_(e,t){let n=new rr({structure:new ar,dependencies:new er,symbols:new or,patterns:new ir,entryPoints:new nr,diagrams:new tr}),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??`.`;D_.info(`Running knowledge production`,{rootPath:o,aspects:r});let s=await n.runExtraction(o,r);try{let e=t?.onboardDir??``;if(!e)throw D_.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`);D_.info(`Knowledge persisted to .ai/context/`,{files:Object.keys(s).length})}catch(e){D_.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+`
2980
+ <\/script>`;return e.includes(`</body>`)?e.replace(`</body>`,`${t}</body>`):`${e}${t}`}let Jg=``;function Yg(e){Jg=e||``}function Xg(e){if(!Jg)return e;let t=`<script>${Jg}<\/script>
2981
+ <script>
2982
+ (function(){
2983
+ var readyState = document.readyState;
2984
+ var boot = function() {
2985
+ if (typeof AnnotationInit === 'undefined') return;
2986
+ AnnotationInit();
2987
+ };
2988
+ if (readyState === 'loading') {
2989
+ document.addEventListener('DOMContentLoaded', boot, { once: true });
2990
+ } else {
2991
+ boot();
2992
+ }
2993
+ })();
2994
+ <\/script>`;return e.includes(`</body>`)?e.replace(`</body>`,`${t}\n</body>`):`${e}${t}`}function Zg(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(`
2995
+ `)}function Qg(e,t,n,r){return wg(Zg(r??`Present`,t)),{content:[{type:`text`,text:`[ERROR:VALIDATION] ${t}`}],isError:!0}}function $g(e,t){if(!kg(e)||!(`schemaVersion`in e))return{ok:!1,response:Qg(`INVALID_CHANNEL_SURFACE`,`present expects a ChannelSurface object with schemaVersion: 1`)};if(e.schemaVersion!==1)return{ok:!1,response:Qg(`UNSUPPORTED_SCHEMA_VERSION`,`Unsupported ChannelSurface schemaVersion: ${String(e.schemaVersion)}`)};if(typeof e.title==`string`&&Ag.test(e.title))return{ok:!1,response:Qg(`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(!kg(e)||e.type!==`markdown`)return[e];let t=Pg(e);return!t||!Fg(t)?[e]:zg(e)})}:e;return{ok:!0,surface:n,options:Vg(n,t)}}const e_={id:`__feedback`,type:`text-submit`,label:`💬 Feedback`,variant:`default`};function t_(e){return!e.actions||e.actions.length===0||e.actions.some(e=>e.id===`__feedback`)?e:{...e,actions:[...e.actions,e_]}}function n_(e){return(e.actions?.length??0)>0||e.response?.required===!0?Og.getAll().some(e=>e.id===`browser`):!1}async function r_(e,t={}){let n=n_(e)?{...t,preferBrowser:!0}:t,r=Ug(e),i=Og.select(r,n),a=i?.id===`browser`?t_(r):r,o;if(o=i?await i.render(a,n):cg(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 i_(e){return{type:`kv`,value:e}}function a_(e){if(Array.isArray(e))return e}const o_=[{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=a_(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(i_(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=a_(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=a_(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=a_(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=a_(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}}}],s_=new Map;for(let e of o_)s_.set(e.name,e);function c_(e,t){let n=s_.get(e);return n?n.expand(t):null}const l_={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`},u_=/^(#{1,6})\s/,d_=/^(`{3,}|~{3,})/,f_=/^\|.+\|.+\|/m;function p_(e){let t=e.trim(),n=t.match(u_);if(n)return{type:`heading`,value:t.slice(n[0].length)};if(d_.test(t)){let e=t.indexOf(`
2996
+ `),n=t.lastIndexOf(t[0]);return{type:`code`,value:e>=0?t.slice(e+1,n).trimEnd():t}}return f_.test(t)?{type:`table`,value:t}:{type:`markdown`,value:t}}function m_(e,t){let n=l_[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 h_(e){if(typeof e==`string`){let t=p_(e);return{type:t.type,value:t.value}}if(Array.isArray(e)){let[t,n]=e;if(typeof t==`string`){let e=m_(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 g_(e){return{title:e.title??``,blocks:Array.isArray(e.blocks)?e.blocks.map(h_):[]}}function __(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function v_(e){return __(e)&&typeof e.schemaVersion==`number`&&e.schemaVersion===1}function y_(e){return __(e)&&typeof e.schemaVersion==`number`&&e.schemaVersion!==1}function b_(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 x_(e){try{let t=re(e);return __(t)?(t.schemaVersion===void 0&&(t.schemaVersion=1),S_(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 S_(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(!__(n))return{ok:!1,error:{code:`INVALID_PRESET_INPUT`,reason:`Preset data must be an object`}};let r=c_(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(y_(e))return{ok:!1,error:{code:`UNSUPPORTED_SCHEMA_VERSION`,reason:`Unsupported schemaVersion: ${String(e.schemaVersion)}`,hint:`Use schemaVersion: 1`}};if(v_(e))return b_(e);if(typeof e==`string`){let t=g_({blocks:[e]});return{ok:!0,surface:{schemaVersion:1,title:t.title||`Present`,blocks:t.blocks}}}if(__(e)){if(typeof e.raw==`string`)return x_(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=g_(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 C_=R.object({label:R.string(),value:R.string(),description:R.string().optional()}),w_=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(C_).optional(),schema:R.record(R.string(),R.unknown()).optional()}),T_=R.object({type:R.string(),title:R.string().optional(),value:R.unknown().optional(),language:R.string().optional()}).catchall(R.unknown()),E_={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(T_).optional().describe(`Typed block content for the surface.`),data:R.unknown().optional().describe(`Template data payload, if the template expands data.`),actions:R.array(w_).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 D_(e){let t=e.server?.getClientCapabilities?.();if(!t)return`unknown`;let n=_r(t);return!n||Array.isArray(n.mimeTypes)&&n.mimeTypes.length>0&&!n.mimeTypes.includes(gr)?`unsupported`:`supported`}const O_=[{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 k_(e,t){let n=W(`present`);try{let e=w(`present`);e&&Yg(F(L(e,`dist`,`annotation-layer.js`),`utf8`))}catch{}yr(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:E_,annotations:n.annotations,_meta:ig(gg)},J(`present`,async(t,n)=>{let r=S_(t);if(!r.ok)return Qg(r.error.code,r.error.reason,void 0,`Present`);let i=$g(r.surface,n);if(!i.ok)return i.response;let a=D_(e);return await r_(i.surface,{...i.options,preferBrowser:i.options.preferBrowser||a===`unsupported`})}));try{let t=new Gn(gg,{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?Eg(r):void 0;return{contents:[{uri:e.href,mimeType:gr,_meta:ag(),text:i??Cg()??`<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 Cg()||`<html><body><p>Loading...</p></body></html>`}try{e.registerResource(`Present App`,hg,{description:`AI Kit present app - entry point`},async()=>({contents:[{uri:hg,mimeType:gr,_meta:ag(),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(O_,null,2)}]}))}catch{}}const A_=M(`tools`);function j_(e,t){let n=new rr({structure:new ar,dependencies:new er,symbols:new or,patterns:new ir,entryPoints:new nr,diagrams:new tr}),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??`.`;A_.info(`Running knowledge production`,{rootPath:o,aspects:r});let s=await n.runExtraction(o,r);try{let e=t?.onboardDir??``;if(!e)throw A_.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`);A_.info(`Knowledge persisted to .ai/context/`,{files:Object.keys(s).length})}catch(e){A_.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+`
2983
2997
 
2984
2998
  ---
2985
- _Next: Review the baselines above and use \`remember\` to store synthesized knowledge entries._`}]}}catch(e){return a?.fail?.(`Production failed`),D_.error(`Knowledge production failed`,N(e)),q(`INTERNAL`,`Knowledge production failed: ${e instanceof Error?e.message:String(e)}`)}}))}const k_=M(`tools`);function A_(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
2999
+ _Next: Review the baselines above and use \`remember\` to store synthesized knowledge entries._`}]}}catch(e){return a?.fail?.(`Production failed`),A_.error(`Knowledge production failed`,N(e)),q(`INTERNAL`,`Knowledge production failed: ${e instanceof Error?e.message:String(e)}`)}}))}const M_=M(`tools`);function N_(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
2986
3000
 
2987
3001
  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
2988
3002
 
@@ -2990,47 +3004,47 @@ Smart indexing (trickle mode) is enabled — files are automatically indexed as
2990
3004
 
2991
3005
  **If the index is severely outdated**, use \`reindex({ force: true })\` to override.
2992
3006
 
2993
- Use \`status({})\` to check smart indexing queue status.`}]};let l=Qc(c).createTask(`Reindex`,1);l.progress(0,`Starting ${e?`full`:`incremental`} reindex`),k_.info(`Starting background re-index`,{mode:e?`full`:`incremental`});let u=e=>t=>{t.phase===`chunking`&&t.currentFile&&k_.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(k_.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(),k_.info(`FTS index rebuilt after reindex`)}catch(e){k_.warn(`FTS index rebuild failed`,N(e))}try{let e=await r.reindexAll();k_.info(`Curated re-index complete`,{indexed:e.indexed})}catch(e){k_.warn(`Curated re-index failed`,N(e))}if(a)try{await a.notifyAfterReindex()}catch(e){k_.warn(`Post-reindex resource notification failed`,N(e))}}).catch(e=>{l.fail(`Reindex failed: ${e instanceof Error?e.message:String(e)}`),k_.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 k_.error(`Reindex failed`,N(e)),q(`INTERNAL`,`Reindex failed: ${e instanceof Error?e.message:String(e)}`)}}))}const j_=M(`tools`);function M_(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(`
3007
+ Use \`status({})\` to check smart indexing queue status.`}]};let l=Qc(c).createTask(`Reindex`,1);l.progress(0,`Starting ${e?`full`:`incremental`} reindex`),M_.info(`Starting background re-index`,{mode:e?`full`:`incremental`});let u=e=>t=>{t.phase===`chunking`&&t.currentFile&&M_.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(M_.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(),M_.info(`FTS index rebuilt after reindex`)}catch(e){M_.warn(`FTS index rebuild failed`,N(e))}try{let e=await r.reindexAll();M_.info(`Curated re-index complete`,{indexed:e.indexed})}catch(e){M_.warn(`Curated re-index failed`,N(e))}if(a)try{await a.notifyAfterReindex()}catch(e){M_.warn(`Post-reindex resource notification failed`,N(e))}}).catch(e=>{l.fail(`Reindex failed: ${e instanceof Error?e.message:String(e)}`),M_.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 M_.error(`Reindex failed`,N(e)),q(`INTERNAL`,`Reindex failed: ${e instanceof Error?e.message:String(e)}`)}}))}const P_=M(`tools`);function F_(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(`
2994
3008
 
2995
- `)}`}]}}catch(e){return j_.error(`Replay failed`,N(e)),q(`INTERNAL`,`Replay failed: ${e instanceof Error?e.message:String(e)}`)}}))}const N_=M(`tools`);function P_(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(`
3009
+ `)}`}]}}catch(e){return P_.error(`Replay failed`,N(e)),q(`INTERNAL`,`Replay failed: ${e instanceof Error?e.message:String(e)}`)}}))}const I_=M(`tools`);function L_(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(`
2996
3010
  `)}`}]}}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(`
2997
- `)}`}]}}catch(e){return N_.error(`Restore failed`,N(e)),q(`INTERNAL`,`Restore failed: ${e instanceof Error?e.message:String(e)}`)}})}const F_=/<\/?curated-context>/gi;function I_(e){return e.replace(F_,``)}function L_(e){return`<curated-context>\n${I_(e)}\n</curated-context>`}const R_=M(`tools`);function z_(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 B_(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 V_(e,t,n){return n?e:t===`curated`?e*1.2:e}function H_(e,t){return t?e:e.map(e=>({record:e.record,score:V_(e.score,e.record.origin,t)})).sort((e,t)=>t.score-e.score)}function U_(e,t){let n=e?Math.floor(e/Math.max(1,t)):96;return Math.max(40,Math.min(160,n))}function W_(e,t){let n=e.origin===`curated`?L_(e.content):e.content,r=kn(n,t);return{body:r,truncated:r!==n}}async function G_(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:hr(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 R_.warn(`ER fallback failed`,N(e)),{results:n,triggered:!0,cacheHit:a}}}function K_(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 J_(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 Y_(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&&!X_.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 X_=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 Z_(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 Q_(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=B_(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 G_(i,T[0]?.score??0,T,e,d);T=a.results,E=a.triggered,D=a.cacheHit}catch(t){k=!1,R_.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._
3011
+ `)}`}]}}catch(e){return I_.error(`Restore failed`,N(e)),q(`INTERNAL`,`Restore failed: ${e instanceof Error?e.message:String(e)}`)}})}const R_=/<\/?curated-context>/gi;function z_(e){return e.replace(R_,``)}function B_(e){return`<curated-context>\n${z_(e)}\n</curated-context>`}const V_=M(`tools`);function H_(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 U_(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 W_(e,t,n){return n?e:t===`curated`?e*1.2:e}function G_(e,t){return t?e:e.map(e=>({record:e.record,score:W_(e.score,e.record.origin,t)})).sort((e,t)=>t.score-e.score)}function K_(e,t){let n=e?Math.floor(e/Math.max(1,t)):96;return Math.max(40,Math.min(160,n))}function q_(e,t){let n=e.origin===`curated`?B_(e.content):e.content,r=kn(n,t);return{body:r,truncated:r!==n}}async function J_(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:hr(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 V_.warn(`ER fallback failed`,N(e)),{results:n,triggered:!0,cacheHit:a}}}function Y_(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 X_(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 Z_(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 Q_(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&&!$_.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 $_=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 ev(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 tv(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=U_(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 J_(i,T[0]?.score??0,T,e,d);T=a.results,E=a.triggered,D=a.cacheHit}catch(t){k=!1,V_.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._
2998
3012
 
2999
- `}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,R_.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._
3013
+ `}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,V_.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._
3000
3014
 
3001
- `}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):K_(r,a).slice(0,d):T=a.slice(0,d),k){let t=await G_(i,r[0]?.score??0,T,e,d);T=t.results,E=t.triggered,D=t.cacheHit}}T=H_(T,h).slice(0,d),a&&a.recordSearch(e,E,D),T.length>1&&(T=q_(T,e)),T=J_(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(`
3002
- `)[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`,R_.debug(`Smart search fallback succeeded`,{originalQuery:e,altQuery:r,resultCount:i.length}))}}catch(e){R_.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(`
3015
+ `}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):Y_(r,a).slice(0,d):T=a.slice(0,d),k){let t=await J_(i,r[0]?.score??0,T,e,d);T=t.results,E=t.triggered,D=t.cacheHit}}T=G_(T,h).slice(0,d),a&&a.recordSearch(e,E,D),T.length>1&&(T=X_(T,e)),T=Z_(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(`
3016
+ `)[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`,V_.debug(`Smart search fallback succeeded`,{originalQuery:e,altQuery:r,resultCount:i.length}))}}catch(e){V_.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(`
3003
3017
  `),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(`
3004
3018
  `),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(`
3005
- `))}}catch(e){R_.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&&z_(s,t,c,l)}let ae=U_(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(`
3006
- `),{body:a,truncated:o}=W_(n,ae);return oe||=o,`${r}\n${i}\n\n${a}${o?`\n\n_Full content: use \`lookup\` on \`${n.sourcePath}\`._`:``}`}).join(`
3019
+ `))}}catch(e){V_.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&&H_(s,t,c,l)}let ae=K_(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(`
3020
+ `),{body:a,truncated:o}=q_(n,ae);return oe||=o,`${r}\n${i}\n\n${a}${o?`\n\n_Full content: use \`lookup\` on \`${n.sourcePath}\`._`:``}`}).join(`
3007
3021
 
3008
3022
  ---
3009
3023
 
3010
- `),ce=(f===`hybrid`?`hybrid (vector + keyword RRF)`:f===`keyword`?`keyword (FTS)`:`semantic (vector)`)+te,le=Y_(T,e),A=le.length>0?`\n_Distinctive terms: ${le.map(e=>`\`${e}\``).join(`, `)}_`:``,j=await Z_(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){R_.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 $_=M(`tools`);function ev(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 $_.error(`Session digest failed`,N(e)),q(`INTERNAL`,`Session digest failed: ${e instanceof Error?e.message:String(e)}`)}}))}const tv=1e4,nv={defaultTtlSeconds:300,defaultLeaseTtlMinutes:10,globalEnabled:!1};function rv(e){return e??nv}function iv(e,t){let n=e.trim();if(!n)throw Error(`${t} is required`);return n}function av(e,t,n){let r=iv(e,t);if(r.length>n)throw Error(`${t} exceeds max length of ${n}`);return r}function ov(e,t){if(!Number.isFinite(e)||e<=0)throw Error(`${t} must be greater than 0`);return Math.trunc(e)}function sv(e,t=!1,n){iv(e,`workspace`);let r=rv(n);if(!t)return e;if(!r.globalEnabled)throw Error(`Global signal scope is disabled`);return`__global__`}function cv(e,t,n){let r=rv(n),i=sv(t.workspace,t.global??!1,r),a=av(t.key,`key`,500),o=av(t.value,`value`,tv),s=t.agent?av(t.agent,`agent`,500):void 0,c=ov(t.ttlSeconds??r.defaultTtlSeconds,`ttlSeconds`);return e.signalPost(i,a,o,s,c)}function lv(e,t,n){let r=iv(t,`workspace`),i=av(n,`key`,500);return e.signalGet(r,i)}function uv(e,t){let n=iv(t,`workspace`);return e.signalList(n)}function dv(e,t,n){let r=iv(t,`workspace`),i=n===void 0?void 0:av(n,`key`,500);return e.signalClear(r,i)}function fv(e,t,n){let r=rv(n),i=av(t.resource,`resource`,500),a=av(t.holder,`holder`,500),o=iv(t.workspace,`workspace`),s=t.intent?av(t.intent,`intent`,tv):void 0,c=ov(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 pv(e,t,n,r){let i=iv(t,`workspace`),a=av(n,`resource`,500),o=av(r,`holder`,500);return e.leaseRelease(a,o,i)}function mv(e,t){let n=iv(t,`workspace`);return e.leaseList(n)}const hv=M(`tools:signal`);function gv(e){return JSON.stringify(e,null,2)}function _v(e,t,n){let r=W(`signal`),i={...nv,...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=cv(t,{workspace:n,key:r,value:a,agent:o,ttlSeconds:u,global:d},i);return{content:[{type:`text`,text:gv({id:e})}],structuredContent:{id:e}}}case`get`:{if(!r)throw Error(`key is required for get`);let e=lv(t,sv(n,d??!1,i),r);return{content:[{type:`text`,text:e.length===0?`[]`:gv(e)}],structuredContent:{signals:e}}}case`list`:{let e=uv(t,sv(n,d??!1,i));return{content:[{type:`text`,text:e.length===0?`[]`:gv(e)}],structuredContent:{signals:e}}}case`clear`:{let e=dv(t,sv(n,d??!1,i),r);return{content:[{type:`text`,text:gv({cleared:e})}],structuredContent:{cleared:e}}}case`lease`:{if(!s||!c)throw Error(`resource and holder are required for lease`);let e=fv(t,{resource:s,holder:c,workspace:n,intent:l,ttlMinutes:u},i);return{content:[{type:`text`,text:gv(e)}],structuredContent:e}}case`unlease`:{if(!s||!c)throw Error(`resource and holder are required for unlease`);let e=pv(t,n,s,c);return{content:[{type:`text`,text:gv({released:e})}],structuredContent:{released:e}}}case`leases`:{let e=mv(t,n);return{content:[{type:`text`,text:e.length===0?`[]`:gv(e)}],structuredContent:{leases:e}}}}}catch(e){return hv.error(`Signal operation failed`,N(e)),q(`INTERNAL`,`Signal operation failed: ${e instanceof Error?e.message:String(e)}`)}}))}function vv(e,t){return e.length<=t?e:e.slice(0,t)}function yv(e){if(!e)return 0;let t=Date.parse(e);return Number.isNaN(t)?0:t}async function bv(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:vv(r.insight??``,150),confidence:n}})),conventions:i.map(e=>({entry:e,lastAccessedAt:t.memoryMetaGet(e.path)?.lastAccessedAt??null})).sort((e,t)=>yv(t.lastAccessedAt)-yv(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)=>yv(t.lastAccessedAt)-yv(e.lastAccessedAt)).map(({entry:e})=>vv(e.contentPreview,200))[0]??null}}catch{return null}}const xv=M(`tools`),Sv=14400*1e3,Cv={includePrelude:R.boolean().default(!1).describe(`Include session prelude with top lessons, conventions, and last checkpoint`)};function wv(e,t,n,r=15e3){let i,a=new Promise(e=>{i=setTimeout(()=>{xv.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),xv.warn(`Status sub-operation "${n}" failed: ${e instanceof Error?e.message:String(e)}`),{value:t,timedOut:!1})),a])}function Tv(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 Ev(){let e=cr.get(),t=sr.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(`
3024
+ `),ce=(f===`hybrid`?`hybrid (vector + keyword RRF)`:f===`keyword`?`keyword (FTS)`:`semantic (vector)`)+te,le=Q_(T,e),A=le.length>0?`\n_Distinctive terms: ${le.map(e=>`\`${e}\``).join(`, `)}_`:``,j=await ev(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){V_.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 nv=M(`tools`);function rv(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 nv.error(`Session digest failed`,N(e)),q(`INTERNAL`,`Session digest failed: ${e instanceof Error?e.message:String(e)}`)}}))}const iv=1e4,av={defaultTtlSeconds:300,defaultLeaseTtlMinutes:10,globalEnabled:!1};function ov(e){return e??av}function sv(e,t){let n=e.trim();if(!n)throw Error(`${t} is required`);return n}function cv(e,t,n){let r=sv(e,t);if(r.length>n)throw Error(`${t} exceeds max length of ${n}`);return r}function lv(e,t){if(!Number.isFinite(e)||e<=0)throw Error(`${t} must be greater than 0`);return Math.trunc(e)}function uv(e,t=!1,n){sv(e,`workspace`);let r=ov(n);if(!t)return e;if(!r.globalEnabled)throw Error(`Global signal scope is disabled`);return`__global__`}function dv(e,t,n){let r=ov(n),i=uv(t.workspace,t.global??!1,r),a=cv(t.key,`key`,500),o=cv(t.value,`value`,iv),s=t.agent?cv(t.agent,`agent`,500):void 0,c=lv(t.ttlSeconds??r.defaultTtlSeconds,`ttlSeconds`);return e.signalPost(i,a,o,s,c)}function fv(e,t,n){let r=sv(t,`workspace`),i=cv(n,`key`,500);return e.signalGet(r,i)}function pv(e,t){let n=sv(t,`workspace`);return e.signalList(n)}function mv(e,t,n){let r=sv(t,`workspace`),i=n===void 0?void 0:cv(n,`key`,500);return e.signalClear(r,i)}function hv(e,t,n){let r=ov(n),i=cv(t.resource,`resource`,500),a=cv(t.holder,`holder`,500),o=sv(t.workspace,`workspace`),s=t.intent?cv(t.intent,`intent`,iv):void 0,c=lv(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 gv(e,t,n,r){let i=sv(t,`workspace`),a=cv(n,`resource`,500),o=cv(r,`holder`,500);return e.leaseRelease(a,o,i)}function _v(e,t){let n=sv(t,`workspace`);return e.leaseList(n)}const vv=M(`tools:signal`);function yv(e){return JSON.stringify(e,null,2)}function bv(e,t,n){let r=W(`signal`),i={...av,...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=dv(t,{workspace:n,key:r,value:a,agent:o,ttlSeconds:u,global:d},i);return{content:[{type:`text`,text:yv({id:e})}],structuredContent:{id:e}}}case`get`:{if(!r)throw Error(`key is required for get`);let e=fv(t,uv(n,d??!1,i),r);return{content:[{type:`text`,text:e.length===0?`[]`:yv(e)}],structuredContent:{signals:e}}}case`list`:{let e=pv(t,uv(n,d??!1,i));return{content:[{type:`text`,text:e.length===0?`[]`:yv(e)}],structuredContent:{signals:e}}}case`clear`:{let e=mv(t,uv(n,d??!1,i),r);return{content:[{type:`text`,text:yv({cleared:e})}],structuredContent:{cleared:e}}}case`lease`:{if(!s||!c)throw Error(`resource and holder are required for lease`);let e=hv(t,{resource:s,holder:c,workspace:n,intent:l,ttlMinutes:u},i);return{content:[{type:`text`,text:yv(e)}],structuredContent:e}}case`unlease`:{if(!s||!c)throw Error(`resource and holder are required for unlease`);let e=gv(t,n,s,c);return{content:[{type:`text`,text:yv({released:e})}],structuredContent:{released:e}}}case`leases`:{let e=_v(t,n);return{content:[{type:`text`,text:e.length===0?`[]`:yv(e)}],structuredContent:{leases:e}}}}}catch(e){return vv.error(`Signal operation failed`,N(e)),q(`INTERNAL`,`Signal operation failed: ${e instanceof Error?e.message:String(e)}`)}}))}function xv(e,t){return e.length<=t?e:e.slice(0,t)}function Sv(e){if(!e)return 0;let t=Date.parse(e);return Number.isNaN(t)?0:t}async function Cv(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:xv(r.insight??``,150),confidence:n}})),conventions:i.map(e=>({entry:e,lastAccessedAt:t.memoryMetaGet(e.path)?.lastAccessedAt??null})).sort((e,t)=>Sv(t.lastAccessedAt)-Sv(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)=>Sv(t.lastAccessedAt)-Sv(e.lastAccessedAt)).map(({entry:e})=>xv(e.contentPreview,200))[0]??null}}catch{return null}}const wv=M(`tools`),Tv=14400*1e3,Ev={includePrelude:R.boolean().default(!1).describe(`Include session prelude with top lessons, conventions, and last checkpoint`)};function Dv(e,t,n,r=15e3){let i,a=new Promise(e=>{i=setTimeout(()=>{wv.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),wv.warn(`Status sub-operation "${n}" failed: ${e instanceof Error?e.message:String(e)}`),{value:t,timedOut:!1})),a])}function Ov(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 kv(){let e=cr.get(),t=sr.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(`
3011
3025
  `):` 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(`
3012
- `)}const Dv=5*6e4;let Ov=null,kv=null;function Av(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 jv(){let e=Date.now();if(Ov&&e-Ov.ts<Dv)return Ov.value;try{let t=L(Hn(),`.copilot`,`.aikit-scaffold.json`);if(!P(t))return Ov={value:null,ts:e},null;let n=JSON.parse(F(t,`utf-8`)).version??null;return Ov={value:n,ts:e},n}catch{return Ov={value:null,ts:e},null}}function Mv(){let e=Date.now();if(kv&&e-kv.ts<Dv)return kv.value;try{let t=L(process.cwd(),`.github`,`.aikit-scaffold.json`);if(!P(t))return kv={value:null,ts:e},null;let n=JSON.parse(F(t,`utf-8`)).version??null;return kv={value:n,ts:e},n}catch{return kv={value:null,ts:e},null}}function Nv(e){let t=W(`status`);e.registerTool(`status`,{title:t.title,description:`Get the current status and statistics of the AI Kit index.`,inputSchema:Cv,annotations:t.annotations},J(`status`,async()=>{let e=ae(),t=jv(),n=Mv(),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)**: ${cr.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:!!cr.get(),wasmDiagnostics:sr.get(),graphStats:null,curatedCount:0,serverVersion:e,scaffoldVersion:t??null,workspaceScaffoldVersion:n??null,upgradeAvailable:r||i,contextPressure:0,nextAction:Tv({onboarded:!1,indexStale:!1,contextPressure:0})};return{content:[{type:`text`,text:a.join(`
3013
- `)}],structuredContent:o}}))}function Pv(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:Cv,annotations:l.annotations},J(`status`,async({includePrelude:e=!1})=>{let l=[];try{let[u,d]=await Promise.all([wv(t.getStats(),{totalRecords:0,totalFiles:0,lastIndexedAt:null,contentTypeBreakdown:{}},`store.getStats`),wv(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 wv(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 wv(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 wv(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=Av(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=Tv({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>=Sv){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`,Ev());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=jv(),ne=Mv(),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(`
3014
- `),pe=e||D>=Sv?await bv(r,c):void 0,me={totalRecords:f.totalRecords,totalFiles:f.totalFiles,lastIndexedAt:f.lastIndexedAt??null,onboarded:y,onboardDir:_,contentTypes:f.contentTypeBreakdown,wasmAvailable:!!cr.get(),wasmDiagnostics:sr.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 xv.error(`Status failed`,N(e)),q(`INTERNAL`,`Status check failed: ${e instanceof Error?e.message:String(e)}`)}}))}const Fv=M(`tools`);function Iv(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 Lv(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(`
3015
- `)};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 Fv.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);Fv.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(`
3016
-
3017
- `);return c===o.length?q(`INTERNAL`,u):{content:[{type:`text`,text:u}]}}))}function Rv(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(`
3018
- `)}]}}catch(e){return Fv.error(`HTTP request failed`,N(e)),q(`INTERNAL`,`HTTP request failed: ${e instanceof Error?e.message:String(e)}`)}}))}function zv(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(`
3019
- `)}]}}))}function Bv(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 Fv.error(`Encode failed`,N(e)),q(`INTERNAL`,`Encode failed: ${e instanceof Error?e.message:String(e)}`)}}))}function Vv(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(`
3026
+ `)}const Av=5*6e4;let jv=null,Mv=null;function Nv(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 Pv(){let e=Date.now();if(jv&&e-jv.ts<Av)return jv.value;try{let t=L(Hn(),`.copilot`,`.aikit-scaffold.json`);if(!P(t))return jv={value:null,ts:e},null;let n=JSON.parse(F(t,`utf-8`)).version??null;return jv={value:n,ts:e},n}catch{return jv={value:null,ts:e},null}}function Fv(){let e=Date.now();if(Mv&&e-Mv.ts<Av)return Mv.value;try{let t=L(process.cwd(),`.github`,`.aikit-scaffold.json`);if(!P(t))return Mv={value:null,ts:e},null;let n=JSON.parse(F(t,`utf-8`)).version??null;return Mv={value:n,ts:e},n}catch{return Mv={value:null,ts:e},null}}function Iv(e){let t=W(`status`);e.registerTool(`status`,{title:t.title,description:`Get the current status and statistics of the AI Kit index.`,inputSchema:Ev,annotations:t.annotations},J(`status`,async()=>{let e=ae(),t=Pv(),n=Fv(),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)**: ${cr.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:!!cr.get(),wasmDiagnostics:sr.get(),graphStats:null,curatedCount:0,serverVersion:e,scaffoldVersion:t??null,workspaceScaffoldVersion:n??null,upgradeAvailable:r||i,contextPressure:0,nextAction:Ov({onboarded:!1,indexStale:!1,contextPressure:0})};return{content:[{type:`text`,text:a.join(`
3027
+ `)}],structuredContent:o}}))}function Lv(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:Ev,annotations:l.annotations},J(`status`,async({includePrelude:e=!1})=>{let l=[];try{let[u,d]=await Promise.all([Dv(t.getStats(),{totalRecords:0,totalFiles:0,lastIndexedAt:null,contentTypeBreakdown:{}},`store.getStats`),Dv(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 Dv(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 Dv(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 Dv(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=Nv(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=Ov({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>=Tv){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`,kv());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=Pv(),ne=Fv(),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(`
3028
+ `),pe=e||D>=Tv?await Cv(r,c):void 0,me={totalRecords:f.totalRecords,totalFiles:f.totalFiles,lastIndexedAt:f.lastIndexedAt??null,onboarded:y,onboardDir:_,contentTypes:f.contentTypeBreakdown,wasmAvailable:!!cr.get(),wasmDiagnostics:sr.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 wv.error(`Status failed`,N(e)),q(`INTERNAL`,`Status check failed: ${e instanceof Error?e.message:String(e)}`)}}))}const Rv=M(`tools`);function zv(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 Bv(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(`
3029
+ `)};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 Rv.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);Rv.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(`
3030
+
3031
+ `);return c===o.length?q(`INTERNAL`,u):{content:[{type:`text`,text:u}]}}))}function Vv(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(`
3032
+ `)}]}}catch(e){return Rv.error(`HTTP request failed`,N(e)),q(`INTERNAL`,`HTTP request failed: ${e instanceof Error?e.message:String(e)}`)}}))}function Hv(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(`
3033
+ `)}]}}))}function Uv(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 Rv.error(`Encode failed`,N(e)),q(`INTERNAL`,`Encode failed: ${e instanceof Error?e.message:String(e)}`)}}))}function Wv(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(`
3020
3034
  `),r):a.join(`
3021
- `)}],structuredContent:o}}catch(e){return Iv(e)?(Fv.warn(`Measure failed`,{error:`File not found`}),q(`NOT_FOUND`,`File not found`)):(Fv.error(`Measure failed`,N(e)),q(`INTERNAL`,`Measure failed: ${e instanceof Error?e.message:String(e)}`))}}))}function Hv(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 Fv.error(`Changelog failed`,N(e)),q(`INTERNAL`,`Changelog failed: ${e instanceof Error?e.message:String(e)}`)}}))}function Uv(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
3035
+ `)}],structuredContent:o}}catch(e){return zv(e)?(Rv.warn(`Measure failed`,{error:`File not found`}),q(`NOT_FOUND`,`File not found`)):(Rv.error(`Measure failed`,N(e)),q(`INTERNAL`,`Measure failed: ${e instanceof Error?e.message:String(e)}`))}}))}function Gv(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 Rv.error(`Changelog failed`,N(e)),q(`INTERNAL`,`Changelog failed: ${e instanceof Error?e.message:String(e)}`)}}))}function Kv(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
3022
3036
 
3023
3037
  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(`
3024
- `)}]}}catch(e){return Fv.error(`Schema validation failed`,N(e)),q(`INTERNAL`,`Schema validation failed: ${e instanceof Error?e.message:String(e)}`)}}))}function Wv(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(`
3025
- `)}],structuredContent:a}}))}function Gv(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(`
3026
- `)}],structuredContent:o}}catch(e){return Fv.error(`Time failed`,N(e)),q(`INTERNAL`,`Time failed: ${e instanceof Error?e.message:String(e)}`)}}))}function Kv(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=Kv(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`)&&Q_(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`)&&Pv(t,n.store,n.graphStore,n.curated,T,r,s,c,n.stateStore),y(`config`)&&Al(t,r),y(`reindex`)&&A_(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`)&&O_(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`)&&_v(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`)&&P_(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`)&&E_(t,i),y(`browser`)&&Qn(t,r),y(`web_search`)&&Lv(t),y(`http`)&&Rv(t),y(`regex_test`)&&zv(t),y(`encode`)&&Bv(t),y(`measure`)&&Vv(t),y(`changelog`)&&Hv(t),y(`schema_validate`)&&Uv(t),y(`env`)&&Wv(t),y(`time`)&&Gv(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`)&&M_(t),y(`session_digest`)&&ev(t,n.stateStore,o)}function Jv(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`)&&P_(e),r(`lane`)&&am(e),r(`queue`)&&om(e),r(`session_digest`)&&ev(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`)&&E_(e),r(`browser`)&&Qn(e,t),r(`produce_knowledge`)&&O_(e),r(`compliance_score`)&&ll(e),r(`replay`)&&M_(e),r(`status`)&&Nv(e),r(`flow`)&&dd(e,t),r(`web_search`)&&Lv(e),r(`http`)&&Rv(e),r(`regex_test`)&&zv(e),r(`encode`)&&Bv(e),r(`measure`)&&Vv(e),r(`changelog`)&&Hv(e),r(`schema_validate`)&&Uv(e),r(`env`)&&Wv(e),r(`time`)&&Gv(e)}const Yv=M(`resource-notifier`);var Xv=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){Yv.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){Yv.debug(`sendResourceUpdated failed`,{uri:e,error:String(t)})}}};const Q=M(`server`);function Zv(e){let t=e?.trim().toLowerCase();return t===`1`||t===`true`||t===`yes`||t===`on`}async function Qv(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=Zv(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 Sr(e),Q.debug(`SQLite adapter ready`,{type:d.type,vectorCapable:d.vectorCapable,dbPath:e}),d.vectorCapable||Q.warn(`┌──────────────────────────────────────────────────────────────────┐
3038
+ `)}]}}catch(e){return Rv.error(`Schema validation failed`,N(e)),q(`INTERNAL`,`Schema validation failed: ${e instanceof Error?e.message:String(e)}`)}}))}function qv(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(`
3039
+ `)}],structuredContent:a}}))}function Jv(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(`
3040
+ `)}],structuredContent:o}}catch(e){return Rv.error(`Time failed`,N(e)),q(`INTERNAL`,`Time failed: ${e instanceof Error?e.message:String(e)}`)}}))}function Yv(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 Xv(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=Yv(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`)&&tv(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`)&&Lv(t,n.store,n.graphStore,n.curated,T,r,s,c,n.stateStore),y(`config`)&&Al(t,r),y(`reindex`)&&N_(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`)&&j_(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`)&&bv(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`)&&L_(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`)&&k_(t,i),y(`browser`)&&Qn(t,r),y(`web_search`)&&Bv(t),y(`http`)&&Vv(t),y(`regex_test`)&&Hv(t),y(`encode`)&&Uv(t),y(`measure`)&&Wv(t),y(`changelog`)&&Gv(t),y(`schema_validate`)&&Kv(t),y(`env`)&&qv(t),y(`time`)&&Jv(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`)&&F_(t),y(`session_digest`)&&rv(t,n.stateStore,o)}function Zv(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`)&&L_(e),r(`lane`)&&am(e),r(`queue`)&&om(e),r(`session_digest`)&&rv(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`)&&k_(e),r(`browser`)&&Qn(e,t),r(`produce_knowledge`)&&j_(e),r(`compliance_score`)&&ll(e),r(`replay`)&&F_(e),r(`status`)&&Iv(e),r(`flow`)&&dd(e,t),r(`web_search`)&&Bv(e),r(`http`)&&Vv(e),r(`regex_test`)&&Hv(e),r(`encode`)&&Uv(e),r(`measure`)&&Wv(e),r(`changelog`)&&Gv(e),r(`schema_validate`)&&Kv(e),r(`env`)&&qv(e),r(`time`)&&Jv(e)}const Qv=M(`resource-notifier`);var $v=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){Qv.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){Qv.debug(`sendResourceUpdated failed`,{uri:e,error:String(t)})}}};const Q=M(`server`);function ey(e){let t=e?.trim().toLowerCase();return t===`1`||t===`true`||t===`yes`||t===`on`}async function ty(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=ey(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 Sr(e),Q.debug(`SQLite adapter ready`,{type:d.type,vectorCapable:d.vectorCapable,dbPath:e}),d.vectorCapable||Q.warn(`┌──────────────────────────────────────────────────────────────────┐
3027
3041
  │ ⚠ SQLite vector extension unavailable — DEGRADED MODE │
3028
3042
  │ Vector search is disabled. Hybrid search returns FTS only. │
3029
3043
  │ To enable: install/rebuild better-sqlite3 (native module). │
3030
- └──────────────────────────────────────────────────────────────────┘`);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 Sr(u.controlDbPath),Tr(f,xr),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 Sr(e),Tr(f,xr),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 wr({backend:r,path:s,adapter:d??void 0,embeddingDim:o.dimensions,embeddingProfile:o,partition:u}):await wr({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 br({adapter:d}):new br({path:s});return await e.initialize(),Q.debug(`Graph store initialized`,{shared:!!d}),e})(),(async()=>{let e=await lr();if(e){let e=sr.get();Q.debug(`WASM tree-sitter enabled`,{grammars:e.grammarCount,dir:e.wasmDir})}else{let e=sr.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=Cr(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 pr(n.curated.path):void 0;w&&Q.debug(`Policy store initialized`,{ruleCount:w.getRules().length});let T=C?new fr: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 $v(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(`
3031
- `)}const ey=M(`background-task`);var ty=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,ey.info(`Background task started`,{task:e.name,pending:this.queue.length});let t=Date.now();try{await e.fn();let n=Date.now()-t;ey.info(`Background task completed`,{task:e.name,durationMs:n}),e.resolve()}catch(n){let r=Date.now()-t;ey.error(`Background task failed`,{task:e.name,durationMs:r,err:n}),e.reject(n instanceof Error?n:Error(String(n)))}}this.running=null}};const ny=M(`idle-timer`);var ry=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){ny.info(`Idle timeout reached with no active session — skipping cleanup (waiting for first tool call)`);return}if(this._busy){ny.info(`Skipping idle cleanup — background work in progress`);return}ny.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`&&ny.warn(`Idle cleanup callback failed`,{error:String(t.reason)})}};const iy=M(`memory-monitor`);var ay=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(),iy.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`?iy.warn(`Memory CRITICAL: ${n}MB RSS — consider restarting the server`):t===`warning`?iy.warn(`Memory WARNING: ${n}MB RSS`):this.lastLevel!==`normal`&&iy.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 oy=new Hr;function sy(e,t){return oy.run(e,async()=>{try{return await t()}finally{}})}M(`tool-timeout`);const cy=new Set([`onboard`,`reindex`,`produce_knowledge`,`analyze`,`codemod`,`audit`]);var ly=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 uy(e){return cy.has(e)?6e5:12e4}function dy(e,t,n){let r=new AbortController,i=r.signal;return new Promise((a,o)=>{let s=setTimeout(()=>{let e=new ly(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`),fy=new Set([`status`,`list_tools`,`describe_tool`,`config`,`env`,`present`]);function py(e,t=28){let n=e.replace(/\s+/g,` `).trim();return n.length<=t?n:`${n.slice(0,t-3)}...`}function my(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 hy(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=>`"${py(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`"${py(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 gy(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||fy.has(i))return o;try{r--;let e=a[0],i=await hy(t,n,my(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 _y(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 vy(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(`
3044
+ └──────────────────────────────────────────────────────────────────┘`);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 Sr(u.controlDbPath),Tr(f,xr),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 Sr(e),Tr(f,xr),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 wr({backend:r,path:s,adapter:d??void 0,embeddingDim:o.dimensions,embeddingProfile:o,partition:u}):await wr({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 br({adapter:d}):new br({path:s});return await e.initialize(),Q.debug(`Graph store initialized`,{shared:!!d}),e})(),(async()=>{let e=await lr();if(e){let e=sr.get();Q.debug(`WASM tree-sitter enabled`,{grammars:e.grammarCount,dir:e.wasmDir})}else{let e=sr.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=Cr(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 pr(n.curated.path):void 0;w&&Q.debug(`Policy store initialized`,{ruleCount:w.getRules().length});let T=C?new fr: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 ny(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(`
3045
+ `)}const ry=M(`background-task`);var iy=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,ry.info(`Background task started`,{task:e.name,pending:this.queue.length});let t=Date.now();try{await e.fn();let n=Date.now()-t;ry.info(`Background task completed`,{task:e.name,durationMs:n}),e.resolve()}catch(n){let r=Date.now()-t;ry.error(`Background task failed`,{task:e.name,durationMs:r,err:n}),e.reject(n instanceof Error?n:Error(String(n)))}}this.running=null}};const ay=M(`idle-timer`);var oy=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){ay.info(`Idle timeout reached with no active session — skipping cleanup (waiting for first tool call)`);return}if(this._busy){ay.info(`Skipping idle cleanup — background work in progress`);return}ay.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`&&ay.warn(`Idle cleanup callback failed`,{error:String(t.reason)})}};const sy=M(`memory-monitor`);var cy=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(),sy.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`?sy.warn(`Memory CRITICAL: ${n}MB RSS — consider restarting the server`):t===`warning`?sy.warn(`Memory WARNING: ${n}MB RSS`):this.lastLevel!==`normal`&&sy.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 ly=new Hr;function uy(e,t){return ly.run(e,async()=>{try{return await t()}finally{}})}M(`tool-timeout`);const dy=new Set([`onboard`,`reindex`,`produce_knowledge`,`analyze`,`codemod`,`audit`]);var fy=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 py(e){return dy.has(e)?6e5:12e4}function my(e,t,n){let r=new AbortController,i=r.signal;return new Promise((a,o)=>{let s=setTimeout(()=>{let e=new fy(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`),hy=new Set([`status`,`list_tools`,`describe_tool`,`config`,`env`,`present`]);function gy(e,t=28){let n=e.replace(/\s+/g,` `).trim();return n.length<=t?n:`${n.slice(0,t-3)}...`}function _y(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 vy(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=>`"${gy(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`"${gy(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 yy(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||hy.has(i))return o;try{r--;let e=a[0],i=await vy(t,n,_y(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 by(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 xy(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(`
3032
3046
  `):[`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(`
3033
- `)}async function yy(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(`
3034
- `),`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(Hn(),`.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 by(e,t){let n=Ns(e,Ba,U,is(e)),r=$v(e,n,U),i=new Wn({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.`,``,vy(o),``,`Try restarting the MCP server to retry initialization.`].filter(Boolean).join(`
3047
+ `)}async function Sy(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(`
3048
+ `),`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(Hn(),`.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 Cy(e,t){let n=Ns(e,Ba,U,is(e)),r=ny(e,n,U),i=new Wn({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.`,``,xy(o),``,`Try restarting the MCP server to retry initialization.`].filter(Boolean).join(`
3035
3049
  `):[`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(`
3036
- `);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)}Jv(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:Xn(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 Qv(e)}catch(t){let r=t instanceof Error?t.message:String(t);if(_y(r)){$.warn(`AI Kit initialization failed with recoverable error — attempting auto-heal retry`,{error:r}),await yy(e,r);try{n=await Qv(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 Xv(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=uy(e);t.handler=async(...i)=>{try{return await dy(e=>sy(e,()=>n(...i)),r,e)}catch(n){if(n instanceof ly)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 ay;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 ry;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)}}gy(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 ty,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 xy=M(`server`);function Sy(e,t){let n=Ns(t,[...Ba,...ns],U,is(t)),r=$v(t,n,U),i=new Wn({name:t.serverName??`aikit`,version:ae()},{capabilities:{logging:{},completions:{},prompts:{},extensions:{roots:{}}},instructions:r}),a=i;return a.setNotificationHandler(Kn,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)),xy.info(`Workspace root updated (HTTP mode)`,{rootPath:n,sourceCount:t.sources.length})):(x(t,n),xy.info(`Workspace root updated (stdio mode)`,{rootPath:n}))}}catch(e){xy.debug(`MCP roots/list not available`,{error:N(e)})}}),Gr(i),qv({server:i,aikit:e,config:t,elicitor:Ur(i),resourceNotifier:new Xv(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 Cy(e){let t=await Qv(e),n=Sy(t,e);xy.debug(`MCP server configured`,{toolCount:Ba.length,resourceCount:2});let r=async()=>{try{let n=e.sources.map(e=>e.path).join(`, `);xy.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&&xy.debug(`Indexing file`,{current:e.filesProcessed+1,total:e.filesTotal,file:e.currentFile}),e.phase===`cleanup`&&xy.debug(`Index cleanup`,{staleEntries:e.filesTotal-e.filesProcessed}))});xy.info(`Initial index complete`,{filesProcessed:r.filesProcessed,filesSkipped:r.filesSkipped,chunksCreated:r.chunksCreated,durationMs:r.durationMs});try{await t.store.createFtsIndex()}catch(e){xy.warn(`FTS index creation failed`,N(e))}try{let e=await t.curated.reindexAll();xy.info(`Curated re-index complete`,{indexed:e.indexed})}catch(e){xy.error(`Curated re-index failed`,N(e))}}catch(e){xy.error(`Initial index failed; will retry on aikit_reindex`,N(e))}},i=async()=>{xy.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{xy.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,by as createLazyServer,Sy as createMcpServer,Cy as createServer,Qv as initializeAikit,qv as registerMcpTools};
3050
+ `);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)}Zv(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:Xn(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 ty(e)}catch(t){let r=t instanceof Error?t.message:String(t);if(by(r)){$.warn(`AI Kit initialization failed with recoverable error — attempting auto-heal retry`,{error:r}),await Sy(e,r);try{n=await ty(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 $v(i),x=gu(i);Xv({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=py(e);t.handler=async(...i)=>{try{return await my(e=>uy(e,()=>n(...i)),r,e)}catch(n){if(n instanceof fy)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 cy;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 oy;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)}}yy(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 iy,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 wy=M(`server`);function Ty(e,t){let n=Ns(t,[...Ba,...ns],U,is(t)),r=ny(t,n,U),i=new Wn({name:t.serverName??`aikit`,version:ae()},{capabilities:{logging:{},completions:{},prompts:{},extensions:{roots:{}}},instructions:r}),a=i;return a.setNotificationHandler(Kn,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)),wy.info(`Workspace root updated (HTTP mode)`,{rootPath:n,sourceCount:t.sources.length})):(x(t,n),wy.info(`Workspace root updated (stdio mode)`,{rootPath:n}))}}catch(e){wy.debug(`MCP roots/list not available`,{error:N(e)})}}),Gr(i),Xv({server:i,aikit:e,config:t,elicitor:Ur(i),resourceNotifier:new $v(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 Ey(e){let t=await ty(e),n=Ty(t,e);wy.debug(`MCP server configured`,{toolCount:Ba.length,resourceCount:2});let r=async()=>{try{let n=e.sources.map(e=>e.path).join(`, `);wy.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&&wy.debug(`Indexing file`,{current:e.filesProcessed+1,total:e.filesTotal,file:e.currentFile}),e.phase===`cleanup`&&wy.debug(`Index cleanup`,{staleEntries:e.filesTotal-e.filesProcessed}))});wy.info(`Initial index complete`,{filesProcessed:r.filesProcessed,filesSkipped:r.filesSkipped,chunksCreated:r.chunksCreated,durationMs:r.durationMs});try{await t.store.createFtsIndex()}catch(e){wy.warn(`FTS index creation failed`,N(e))}try{let e=await t.curated.reindexAll();wy.info(`Curated re-index complete`,{indexed:e.indexed})}catch(e){wy.error(`Curated re-index failed`,N(e))}}catch(e){wy.error(`Initial index failed; will retry on aikit_reindex`,N(e))}},i=async()=>{wy.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{wy.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,Cy as createLazyServer,Ty as createMcpServer,Ey as createServer,ty as initializeAikit,Xv as registerMcpTools};