@vpxa/aikit 0.1.188 → 0.1.190
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +3 -2
- package/packages/blocks-core/dist/index.js +2 -2
- package/packages/present/dist/index.html +28 -14
- package/packages/server/dist/index.js +1 -1
- package/packages/server/dist/{server-BvVBHkFD.js → server-CHnF9LI9.js} +42 -42
- package/scaffold/dist/definitions/skills/c4-architecture.mjs +1 -1
- package/scaffold/dist/definitions/skills/docs.mjs +1 -1
|
@@ -2635,8 +2635,8 @@ Complements: \`symbol\` (single lookup), \`trace\` (call-chain AST), \`blast_rad
|
|
|
2635
2635
|
}
|
|
2636
2636
|
mermaid.initialize({ startOnLoad: false, theme: theme });
|
|
2637
2637
|
mermaid.run();
|
|
2638
|
-
};`,onload:`window.__aikit_initMermaid&&window.__aikit_initMermaid()`,local:{route:`/vendor/mermaid.min.js`,getSource:Kd()}},Jd=new Map([[`mermaid`,qd]]);function Yd(e,t){if(!e?.length)return;let n=[];for(let r of e){let e=Jd.get(r);if(e){if(t===`browser`){n.push({inlineSource:e.inlineSource,onload:e.onload});continue}if(t===`mcp-app`){n.push({inlineSource:e.inlineSource,onload:e.onload});continue}n.push({src:e.cdn,initScript:e.initScript,onload:e.onload})}}return n.length>0?n:void 0}function Xd(){let e=[];for(let t of Jd.values())t.local&&e.push({route:t.local.route,getSource:t.local.getSource,cdn:t.cdn});return e}const Zd=300*1e3;let X=null;process.on(`exit`,()=>{let e=X;if(e){try{e.close()}catch{}X=null}});function
|
|
2639
|
-
`)}function
|
|
2638
|
+
};`,onload:`window.__aikit_initMermaid&&window.__aikit_initMermaid()`,local:{route:`/vendor/mermaid.min.js`,getSource:Kd()}},Jd=new Map([[`mermaid`,qd]]);function Yd(e,t){if(!e?.length)return;let n=[];for(let r of e){let e=Jd.get(r);if(e){if(t===`browser`){n.push({inlineSource:e.inlineSource,onload:e.onload});continue}if(t===`mcp-app`){n.push({inlineSource:e.inlineSource,onload:e.onload});continue}n.push({src:e.cdn,initScript:e.initScript,onload:e.onload})}}return n.length>0?n:void 0}function Xd(){let e=[];for(let t of Jd.values())t.local&&e.push({route:t.local.route,getSource:t.local.getSource,cdn:t.cdn});return e}const Zd=300*1e3,Qd=S(import.meta.url);let X=null;process.on(`exit`,()=>{let e=X;if(e){try{e.close()}catch{}X=null}});function $d(e){let t=typeof e.description==`string`&&e.description.trim().length>0?`<p class="present-surface-description">${q(e.description)}</p>`:``;return[`<h1 class="present-surface-title">${q(e.title)}</h1>`,t].filter(Boolean).join(`
|
|
2639
|
+
`)}function ef(e,t){return e.length===0?``:`
|
|
2640
2640
|
<section class="present-surface-actions">
|
|
2641
2641
|
<div class="present-action-bar">${e.map(e=>{let t=q(e.id),n=q(e.label);return e.type===`select`||e.type===`multi-select`?`<label class="present-action-field"><span>${n}</span><select data-action-id="${t}"${e.type===`multi-select`?` multiple`:``}>${(e.options??[]).map(e=>`<option value="${q(e.value)}">${q(e.label)}</option>`).join(``)}</select></label>`:`<button type="button" class="present-action-btn present-action-${q(e.variant??`default`)}" data-action-id="${t}" data-action-label="${n}">${n}</button>`}).join(``)}</div>
|
|
2642
2642
|
<p id="present-action-status" class="present-action-status" aria-live="polite"></p>
|
|
@@ -2763,8 +2763,8 @@ Complements: \`symbol\` (single lookup), \`trace\` (call-chain AST), \`blast_rad
|
|
|
2763
2763
|
navigator.sendBeacon('/callback', new Blob([body], { type: 'application/json' }));
|
|
2764
2764
|
});
|
|
2765
2765
|
})();
|
|
2766
|
-
<\/script>`}function
|
|
2767
|
-
`)}function
|
|
2766
|
+
<\/script>`}function tf(e){try{bn(process.platform===`win32`?`start "" "${e}"`:process.platform===`darwin`?`open "${e}"`:`xdg-open "${e}"`)}catch{}}async function nf(e){try{let t=kn();await t.launch(`ui`),await(await t.getContext().newPage()).goto(e,{waitUntil:`domcontentloaded`})}catch{tf(e)}}function rf(e,t,n){let r=[e.title];return e.description&&r.push(e.description),r.push(``,`Opened in browser at ${t}`,n),r.join(`
|
|
2767
|
+
`)}function af(e){return e.some(e=>e.id!==`__dismiss`)}function of(e){let t=e?.split(`?`)[0];if(t?.startsWith(`/@aikit/blocks-interactive/dist/`))return N(M(Qd.resolve(`@aikit/blocks-interactive/package.json`)),`dist`,t.slice(32))}function sf(e){return e.replace(`</head>`,`<style>
|
|
2768
2768
|
.toolbar, .badge, body > header, body > footer { display: none !important; }
|
|
2769
2769
|
body { padding-top: 0 !important; margin-top: 0 !important; }
|
|
2770
2770
|
</style>
|
|
@@ -2775,8 +2775,8 @@ window.addEventListener('message', function(e) {
|
|
|
2775
2775
|
}
|
|
2776
2776
|
});
|
|
2777
2777
|
<\/script>
|
|
2778
|
-
</body>`)}function
|
|
2779
|
-
`);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=
|
|
2778
|
+
</body>`)}function cf(){let e=X;e&&(e.close(),X=null)}async function lf(e,t){if(mf(`<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=Gt({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(`
|
|
2779
|
+
`);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=sf(yd(t.resolveHtml(),e.data??null,t.injectId,t.transformData)),r=ir({title:e.title,html:[$d(e),`<div class="present-viewer-container">`,` <iframe class="present-viewer-iframe" src="/viewer" sandbox="allow-scripts allow-same-origin"></iframe>`,` <script>
|
|
2780
2780
|
(function() {
|
|
2781
2781
|
const iframe = document.querySelector('.present-viewer-iframe');
|
|
2782
2782
|
if (!iframe) return;
|
|
@@ -2792,11 +2792,11 @@ window.addEventListener('message', function(e) {
|
|
|
2792
2792
|
})();
|
|
2793
2793
|
<\/script>`,`</div>`].join(`
|
|
2794
2794
|
`),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(`
|
|
2795
|
-
`)],islands:[],payload:void 0,nonce:``,generatedAt:new Date().toISOString(),colorScheme:e.colorScheme,lang:e.lang,dir:e.dir,transport:`browser`,exportPolicy:`local-interactive`}),i=``;try{
|
|
2796
|
-
`),css:t.css,islands:t.islands,payload:t.payload,nonce:t.nonce,generatedAt:new Date().toISOString(),colorScheme:e.colorScheme,lang:e.lang,dir:e.dir,transport:`browser`,exportPolicy:t.exportPolicy,headScripts:r}),o=``,s=``;try{let e=X;e&&(e.close(),X=null),o=await new Promise((e,t)=>{let r=pr((e,t)=>{if(e.method===`OPTIONS`){t.writeHead(204,{"Access-Control-Allow-Origin":s||`*`,"Access-Control-Allow-Methods":`POST`,"Access-Control-Allow-Headers":`Content-Type`}),t.end();return}if(e.method===`POST`&&e.url===`/callback`){n.handle(e,t,s);return}let r=i.find(t=>e.url===t.route);if(r){let e=r.getSource();if(e){t.writeHead(200,{"Content-Type":`application/javascript; charset=utf-8`,"Cache-Control":`public, max-age=86400`}),t.end(e);return}t.writeHead(302,{Location:r.cdn}),t.end();return}t.writeHead(200,{"Content-Type":`text/html; charset=utf-8`}),t.end(a)});r.listen(0,`127.0.0.1`,()=>{let n=r.address();if(typeof n!=`object`||!n){t(Error(`Failed to resolve local browser address`));return}X=r,s=`http://127.0.0.1:${n.port}`,e(s)})})}catch(t){return{content:[{type:`text`,text:`${e.title}\n\nUnable to start local browser transport.`}],structuredContent:n.settleError(`BROWSER_START_FAILED`,t instanceof Error?t.message:`Unable to start browser transport`),isError:!0}}if(
|
|
2797
|
-
`)}),r.length=0)},a=0;for(;a<t.length;){let e=t[a],o=t[a+1];if(o!==void 0&&
|
|
2798
|
-
`)}function
|
|
2799
|
-
`)}const
|
|
2795
|
+
`)],islands:[],payload:void 0,nonce:``,generatedAt:new Date().toISOString(),colorScheme:e.colorScheme,lang:e.lang,dir:e.dir,transport:`browser`,exportPolicy:`local-interactive`}),i=``;try{cf(),i=await new Promise((e,t)=>{let i=pr((e,t)=>{if(e.url===`/viewer`){t.writeHead(200,{"Content-Type":`text/html; charset=utf-8`}),t.end(n);return}t.writeHead(200,{"Content-Type":`text/html; charset=utf-8`}),t.end(r)});i.listen(0,`127.0.0.1`,()=>{let n=i.address();if(typeof n!=`object`||!n){t(Error(`Failed to resolve local browser address`));return}X=i,e(`http://127.0.0.1:${n.port}`)})})}catch(t){return{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 nf(i),{content:[{type:`text`,text:rf(e,i,`Rendered.`)}],structuredContent:{kind:`rendered`,reason:`no-response-required`}}}async function uf(e){mf(`<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=fr(e,{transport:`browser`,registry:Hd,blockVendorScripts:$u()}),n=dd(t.surfaceId,t.actions),r=Yd(t.vendorScripts,`browser`),i=Xd(),a=ir({title:e.title,html:[$d(e),t.html,ef(t.actions,n.nonce)].filter(Boolean).join(`
|
|
2796
|
+
`),css:t.css,islands:t.islands,payload:t.payload,nonce:t.nonce,generatedAt:new Date().toISOString(),colorScheme:e.colorScheme,lang:e.lang,dir:e.dir,transport:`browser`,exportPolicy:t.exportPolicy,headScripts:r}),o=``,s=``;try{let e=X;e&&(e.close(),X=null),o=await new Promise((e,t)=>{let r=pr((e,t)=>{if(e.method===`OPTIONS`){t.writeHead(204,{"Access-Control-Allow-Origin":s||`*`,"Access-Control-Allow-Methods":`POST`,"Access-Control-Allow-Headers":`Content-Type`}),t.end();return}if(e.method===`POST`&&e.url===`/callback`){n.handle(e,t,s);return}let r=i.find(t=>e.url===t.route);if(r){let e=r.getSource();if(e){t.writeHead(200,{"Content-Type":`application/javascript; charset=utf-8`,"Cache-Control":`public, max-age=86400`}),t.end(e);return}t.writeHead(302,{Location:r.cdn}),t.end();return}let o=of(e.url);if(o)try{let e=k(o,`utf8`);t.writeHead(200,{"Content-Type":`application/javascript; charset=utf-8`}),t.end(e);return}catch{}t.writeHead(200,{"Content-Type":`text/html; charset=utf-8`}),t.end(a)});r.listen(0,`127.0.0.1`,()=>{let n=r.address();if(typeof n!=`object`||!n){t(Error(`Failed to resolve local browser address`));return}X=r,s=`http://127.0.0.1:${n.port}`,e(s)})})}catch(t){return{content:[{type:`text`,text:`${e.title}\n\nUnable to start local browser transport.`}],structuredContent:n.settleError(`BROWSER_START_FAILED`,t instanceof Error?t.message:`Unable to start browser transport`),isError:!0}}if(nf(o),!af(t.actions)){let t=X;return t&&(n.promise.finally(()=>{X===t&&(t.close(),X=null)}),setTimeout(()=>{X===t&&(t.close(),X=null)},Zd)),{content:[{type:`text`,text:rf(e,o,`Rendered.`)}],structuredContent:{kind:`rendered`,reason:`no-response-required`}}}let c=await Promise.race([n.promise,new Promise(e=>{setTimeout(()=>e(n.settleTimeout(Zd)),Zd)})]),l=X;l&&(l.close(),X=null);let u=c.kind===`result`?`Selected action: ${c.result.actionId}`:c.kind===`timeout`?`Timed out after ${c.waitedMs}ms.`:c.kind===`cancelled`?`Cancelled: ${c.reason}.`:c.kind===`error`?`Error: ${c.error.message}`:`Rendered.`;return{content:[{type:`text`,text:rf(e,o,u)}],structuredContent:c,isError:c.kind===`error`}}const df=`ui://aikit/present.html`;let ff=``;function pf(){return ff}function mf(e){ff=e}function hf(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const gf=/\\u[0-9a-fA-F]{4}/,_f=/^\s*\|(?:[^|\r\n]+\|){2,}\s*$/,vf=/^\s*\|?(?:\s*:?-{3,}:?\s*\|){2,}\s*$/,yf=/\b(cli|terminal|tty|console|command(?:-|\s)?line)\b/i;function bf(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 xf(e){let t=e.split(/\r?\n/);for(let e=0;e<t.length-1;e+=1)if(_f.test(t[e])&&vf.test(t[e+1]))return!0;return!1}function Sf(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 Cf(e,t){if(t<2)return!1;let n=e.trim();return n.startsWith(`|`)?Sf(n).length===t:!1}function wf(e){let t=e.split(/\r?\n/),n=[],r=[],i=()=>{r.length!==0&&(n.push({type:`text`,content:r.join(`
|
|
2797
|
+
`)}),r.length=0)},a=0;for(;a<t.length;){let e=t[a],o=t[a+1];if(o!==void 0&&_f.test(e)&&vf.test(o)){let r=Sf(e),o=[];i();let s=a+2;for(;s<t.length&&Cf(t[s],r.length);)o.push(Sf(t[s])),s+=1;n.push({type:`table`,headers:r,rows:o}),a=s;continue}r.push(e),a+=1}return i(),n}function Tf(e){let t=bf(e);return!t||!xf(t)?[e]:wf(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 Ef(e){if(typeof e==`string`)return yf.test(e);if(Array.isArray(e))return e.some(e=>Ef(e));if(!hf(e))return!1;let t=[`client`,`clientInfo`,`host`,`source`,`mode`,`name`,`title`,`channel`];return Object.entries(e).some(([e,n])=>t.includes(e)?Ef(n):!1)}function Df(e,t){return{preferBrowser:[t,e._meta,hf(e.metadata)?e.metadata.source:void 0].some(e=>Ef(e))}}function Of(e){if(!e.template)return!0;let t=gd(e.template);return t?t.supportedTransports.includes(`browser`):Ud(e)?.supportedTransports.includes(`browser`)??!1}function kf(e){let t=typeof e.description==`string`&&e.description.trim().length>0?`<p class="present-surface-description">${q(e.description)}</p>`:``;return[`<section class="present-surface-header">`,` <h1>${q(e.title)}</h1>`,t,`</section>`,`<style>`,` .present-surface-header { display: grid; gap: 0.75rem; margin-bottom: 1.5rem; }`,` .present-surface-header h1 { margin: 0; font-size: 1.875rem; }`,` .present-surface-description { margin: 0; color: var(--dt-text-secondary, #475467); }`,`</style>`].filter(Boolean).join(`
|
|
2798
|
+
`)}function Af(e,t){let n=[e.title];return e.description&&n.push(e.description),lr(t)?n.push(``,`Selected action: ${t.result.actionId}`):cr(t)?n.push(``,`Error: ${t.error.message}`):t.kind===`timeout`?n.push(``,`Timed out after ${t.waitedMs}ms.`):t.kind===`cancelled`&&n.push(``,`Cancelled: ${t.reason}.`),n.join(`
|
|
2799
|
+
`)}const jf={id:`__dismiss`,type:`button`,label:`Done`,variant:`default`};function Mf(e){if((e.actions?.length??0)>0||!e.template)return e;let t=Ud(e);return t?.supportedTransports.includes(`browser`)===!0&&!t.supportedTransports.includes(`mcp-app`)?{...e,actions:[jf]}:e}function Nf(e){return e.replace(`</head>`,`<style>
|
|
2800
2800
|
.toolbar, .badge, body > header, body > footer { display: none !important; }
|
|
2801
2801
|
body { padding-top: 0 !important; margin-top: 0 !important; }
|
|
2802
2802
|
</style>
|
|
@@ -2818,7 +2818,7 @@ window.addEventListener('message', function(e) {
|
|
|
2818
2818
|
}
|
|
2819
2819
|
});
|
|
2820
2820
|
<\/script>
|
|
2821
|
-
</body>`)}function
|
|
2821
|
+
</body>`)}function Pf(e){let t=`<script>
|
|
2822
2822
|
(function(){
|
|
2823
2823
|
var last=0;
|
|
2824
2824
|
function notify(){
|
|
@@ -2829,8 +2829,8 @@ window.addEventListener('message', function(e) {
|
|
|
2829
2829
|
if(typeof ResizeObserver!=="undefined"){new ResizeObserver(notify).observe(document.documentElement)}
|
|
2830
2830
|
else{setInterval(notify,500)}
|
|
2831
2831
|
})();
|
|
2832
|
-
<\/script>`;return e.includes(`</body>`)?e.replace(`</body>`,`${t}</body>`):`${e}${t}`}function
|
|
2833
|
-
`);return
|
|
2832
|
+
<\/script>`;return e.includes(`</body>`)?e.replace(`</body>`,`${t}</body>`):`${e}${t}`}function Ff(e,t,n){return{content:[{type:`text`,text:`[ERROR:VALIDATION] ${t}`}],isError:!0}}function If(e,t){if(!hf(e)||!(`schemaVersion`in e))return{ok:!1,response:Ff(`INVALID_CHANNEL_SURFACE`,`present expects a ChannelSurface object with schemaVersion: 1`)};if(e.schemaVersion!==1)return{ok:!1,response:Ff(`UNSUPPORTED_SCHEMA_VERSION`,`Unsupported ChannelSurface schemaVersion: ${String(e.schemaVersion)}`)};if(typeof e.title==`string`&&gf.test(e.title))return{ok:!1,response:Ff(`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(!hf(e)||e.type!==`markdown`)return[e];let t=bf(e);return!t||!xf(t)?[e]:Tf(e)})}:e;return{ok:!0,surface:n,options:Df(n,t)}}async function Lf(e,t={}){let n=Mf(e);if(e.template){let r=gd(e.template);if(r)return await Rf(n,r,t)}return Wd(n)||t.preferBrowser&&Of(n)?await uf(n):zf(n)}async function Rf(e,t,n={}){if(e.data!=null&&t.inputSchema){let n=Gt({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(`
|
|
2833
|
+
`);return Ff(`VIEWER_DATA_INVALID`,`Template "${t.id}" data validation failed:\n${e}\n\nExpected schema: ${JSON.stringify(t.inputSchema,null,2)}`)}}let r=t.supportedTransports.includes(`browser`),i=t.supportedTransports.includes(`mcp-app`);if(n.preferBrowser&&r||r&&!i)return await lf(e,t);if(!i)return Ff(`VIEWER_TRANSPORT_UNSUPPORTED`,`Viewer template "${t.id}" does not support an available transport`);try{let n=Nf(yd(t.resolveHtml(),e.data??null,t.injectId,t.transformData)).replace(/&/g,`&`).replace(/"/g,`"`);return mf(Pf(ir({title:e.title,html:[kf(e),`<div class="present-viewer-container">`,` <iframe class="present-viewer-iframe" srcdoc="${n}" sandbox="allow-scripts allow-same-origin"></iframe>`,` <script>
|
|
2834
2834
|
(function() {
|
|
2835
2835
|
const iframe = document.querySelector('.present-viewer-iframe');
|
|
2836
2836
|
if (!iframe) return;
|
|
@@ -2853,16 +2853,16 @@ window.addEventListener('message', function(e) {
|
|
|
2853
2853
|
});
|
|
2854
2854
|
<\/script>`,`</div>`].join(`
|
|
2855
2855
|
`),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(`
|
|
2856
|
-
`)],islands:[],payload:void 0,nonce:``,generatedAt:new Date().toISOString(),colorScheme:e.colorScheme,lang:e.lang,dir:e.dir,transport:`mcp-app`,exportPolicy:`local-interactive`}))),{content:[{type:`text`,text:[
|
|
2856
|
+
`)],islands:[],payload:void 0,nonce:``,generatedAt:new Date().toISOString(),colorScheme:e.colorScheme,lang:e.lang,dir:e.dir,transport:`mcp-app`,exportPolicy:`local-interactive`}))),{content:[{type:`text`,text:[Af(e,{kind:`rendered`,reason:`no-response-required`}),`If this content doesn't render inline, retry with format: 'browser'.`].join(`
|
|
2857
2857
|
|
|
2858
|
-
`)}],ui:{type:`resource`,uri:
|
|
2859
|
-
`),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,headScripts:n})),{content:[{type:`text`,text:[
|
|
2858
|
+
`)}],ui:{type:`resource`,uri:df}}}catch(e){return Ff(`VIEWER_RENDER_FAILED`,e instanceof Error?e.message:`Failed to render viewer template`)}}function zf(e){try{let t=fr(e,{transport:`mcp-app`,registry:Hd,blockVendorScripts:$u()}),n=Yd(t.vendorScripts,`mcp-app`);return ff=Pf(ir({title:e.title,html:[kf(e),t.html].filter(Boolean).join(`
|
|
2859
|
+
`),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,headScripts:n})),{content:[{type:`text`,text:[Af(e,{kind:`rendered`,reason:`no-response-required`}),`If this content doesn't render inline, retry with format: 'browser'.`].join(`
|
|
2860
2860
|
|
|
2861
|
-
`)}],ui:{type:`resource`,uri:
|
|
2862
|
-
`);Xn(e,`present`,{title:n.title,description:r,inputSchema:
|
|
2861
|
+
`)}],ui:{type:`resource`,uri:df}}}catch(e){return Ff(`RENDER_FAILED`,e instanceof Error?e.message:`Failed to render ChannelSurface`)}}const Bf=L.object({label:L.string(),value:L.string(),description:L.string().optional()}),Vf=L.object({id:L.string().describe(`Unique action identifier`),type:L.enum([`button`,`select`,`multi-select`,`form-submit`,`text-submit`,`confirm`,`custom`]).describe(`Interactive action type`),label:L.string().describe(`Visible action label`),variant:L.enum([`primary`,`danger`,`default`]).optional(),options:L.array(Bf).optional(),schema:L.record(L.string(),L.unknown()).optional()}),Hf=L.object({type:L.string(),title:L.string().optional(),value:L.unknown().optional(),language:L.string().optional()}).catchall(L.unknown()),Uf={schemaVersion:L.literal(1).describe(`ChannelSurface schema version. Must be 1.`),title:L.string().describe(`Surface title shown to the user.`),description:L.string().optional().describe(`Optional supporting copy for the surface.`),template:L.string().optional().describe(`Optional template id such as report@1.`),layout:L.object({maxWidth:L.string().optional(),padding:L.string().optional(),columns:L.number().optional()}).optional(),blocks:L.array(Hf).optional().describe(`Typed block content for the surface.`),data:L.unknown().optional().describe(`Template data payload, if the template expands data.`),actions:L.array(Vf).optional().describe(`Interactive actions. Presence triggers browser transport.`),response:L.object({timeout:L.number().optional(),required:L.boolean().optional()}).optional(),metadata:L.object({surfaceId:L.string().optional(),createdAt:L.string().optional(),source:L.string().optional()}).optional(),colorScheme:L.enum([`light`,`dark`,`auto`]).optional(),lang:L.string().optional(),dir:L.enum([`ltr`,`rtl`,`auto`]).optional()};L.object({surfaceId:L.string(),actionId:L.string(),actionType:L.enum([`button`,`select`,`multi-select`,`form-submit`,`text-submit`,`confirm`,`custom`]),value:L.unknown().optional(),formData:L.record(L.string(),L.unknown()).optional(),selection:L.union([L.string(),L.array(L.string())]).optional(),label:L.string().optional(),timestamp:L.string(),sourceTransport:L.enum([`mcp-app`,`browser`,`export`])});function Wf(e,t){let n=U(`present`),r=[`Render a ChannelSurface for the user.`,`Quick ref:`,`- Full schema: aikit://schemas/channel-surface`,`- Required: schemaVersion: 1, title`,`- Content: blocks[] for direct rendering, or template + data for registry-backed rendering`,`- Actions: actions[] of SurfaceAction; interactive surfaces use browser transport and return ChannelOutcome`,`- Optional fields: description, layout, response, metadata, colorScheme, lang, dir`,`- Transports: mcp-app, browser, export`,`- Use schema resource for block enums and action details.`].join(`
|
|
2862
|
+
`);Xn(e,`present`,{title:n.title,description:r,inputSchema:Uf,annotations:n.annotations,_meta:{ui:{resourceUri:df}}},async(e,t)=>{let n=If(e,t);return n.ok?await Lf(n.surface,n.options):n.response});try{Yn(e,`Present View`,df,{description:`AI Kit present tool viewer`},async()=>({contents:[{uri:df,mimeType:Jn,text:pf()||`<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=vd().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{}}const Gf=F(`tools`);function Kf(e,t){let n=new Fn({structure:new Ln,dependencies:new Mn,symbols:new Rn,patterns:new In,entryPoints:new Pn,diagrams:new Nn}),r=U(`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:L.string().optional().describe(`Root path to analyze (defaults to workspace root)`),aspects:L.array(L.enum([`all`,`structure`,`dependencies`,`symbols`,`patterns`,`entry-points`,`diagrams`])).default([`all`]).describe(`Which analysis aspects to run`)},annotations:r.annotations},async({scope:e,aspects:r})=>{try{let i=e??`.`;Gf.info(`Running knowledge production`,{rootPath:i,aspects:r});let a=await n.runExtraction(i,r);try{let e=t?.onboardDir??``;if(!e)throw Gf.warn(`onboardDir not configured — skipping artifact persistence.`),Error(`skip`);O(e,{recursive:!0});let n=`<!-- Generated by produce_knowledge at ${new Date().toISOString()} -->\n\n`;for(let[t,r]of Object.entries(a))r&&typeof r==`string`&&ne(N(e,`${t}.md`),n+r,`utf-8`);Gf.info(`Knowledge persisted to .ai/context/`,{files:Object.keys(a).length})}catch(e){Gf.warn(`Failed to persist knowledge to .ai/context/`,{error:I(e)})}return{content:[{type:`text`,text:n.buildSynthesisInstructions(a,r)+`
|
|
2863
2863
|
|
|
2864
2864
|
---
|
|
2865
|
-
_Next: Review the baselines above and use \`remember\` to store synthesized knowledge entries._`}]}}catch(e){return
|
|
2865
|
+
_Next: Review the baselines above and use \`remember\` to store synthesized knowledge entries._`}]}}catch(e){return Gf.error(`Knowledge production failed`,I(e)),K(`INTERNAL`,`Knowledge production failed: ${e instanceof Error?e.message:String(e)}`)}})}const qf=F(`tools`);function Jf(e,t,n,r,i,a,o){let s=U(`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:L.boolean().default(!1).describe(`If true, force full re-index ignoring file hashes`),force:L.boolean().default(!1).describe(`If true, override smart indexing guard and run reindex anyway`)},annotations:s.annotations},async({full:e,force:s},c)=>{try{if(t.isIndexing)return{content:[{type:`text`,text:`## Reindex Already in Progress
|
|
2866
2866
|
|
|
2867
2867
|
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
|
|
2868
2868
|
|
|
@@ -2870,40 +2870,40 @@ Smart indexing (trickle mode) is enabled — files are automatically indexed as
|
|
|
2870
2870
|
|
|
2871
2871
|
**If the index is severely outdated**, use \`reindex({ force: true })\` to override.
|
|
2872
2872
|
|
|
2873
|
-
Use \`status({})\` to check smart indexing queue status.`}]};let l=Ss(c).createTask(`Reindex`,1);l.progress(0,`Starting ${e?`full`:`incremental`} reindex`),
|
|
2873
|
+
Use \`status({})\` to check smart indexing queue status.`}]};let l=Ss(c).createTask(`Reindex`,1);l.progress(0,`Starting ${e?`full`:`incremental`} reindex`),qf.info(`Starting background re-index`,{mode:e?`full`:`incremental`});let u=e=>t=>{t.phase===`chunking`&&t.currentFile&&qf.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(qf.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(),qf.info(`FTS index rebuilt after reindex`)}catch(e){qf.warn(`FTS index rebuild failed`,I(e))}try{let e=await r.reindexAll();qf.info(`Curated re-index complete`,{indexed:e.indexed})}catch(e){qf.warn(`Curated re-index failed`,I(e))}if(a)try{await a.notifyAfterReindex()}catch(e){qf.warn(`Post-reindex resource notification failed`,I(e))}}).catch(e=>{l.fail(`Reindex failed: ${e instanceof Error?e.message:String(e)}`),qf.error(`Background reindex failed`,I(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 qf.error(`Reindex failed`,I(e)),K(`INTERNAL`,`Reindex failed: ${e instanceof Error?e.message:String(e)}`)}})}const Yf=F(`tools`);function Xf(e){let t=U(`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:L.enum([`list`,`clear`]).default(`list`).describe(`Action: "list" (default) to view entries, "clear" to wipe the log`),last:L.number().optional().describe(`Number of entries to return (default: 20, list only)`),tool:L.string().optional().describe(`Filter by tool name (list only)`),source:L.enum([`mcp`,`cli`]).optional().describe(`Filter by source: "mcp" or "cli" (list only)`),since:L.string().optional().describe(`ISO timestamp — only show entries after this time (list only)`)},annotations:t.annotations},async({action:e,last:t,tool:n,source:r,since:i})=>{try{if(e===`clear`)return Bt(),{content:[{type:`text`,text:`Replay log cleared.`}]};let a=Vt({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 Ht().catch(()=>{}),{content:[{type:`text`,text:`**Replay Log** (${a.length} entries)\n\n${o.join(`
|
|
2874
2874
|
|
|
2875
|
-
`)}`}]}}catch(e){return
|
|
2875
|
+
`)}`}]}}catch(e){return Yf.error(`Replay failed`,I(e)),K(`INTERNAL`,`Replay failed: ${e instanceof Error?e.message:String(e)}`)}})}const Zf=F(`tools`);function Qf(e){let t=U(`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:L.enum([`list`,`restore`]).describe(`list: show restore points, restore: apply a restore point`),id:L.string().optional().describe(`Restore point ID (required for action=restore)`),limit:L.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=ht().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(`
|
|
2876
2876
|
`)}`}]}}if(!t)throw Error(`id is required for restore action`);let r=await Ut(t);return{content:[{type:`text`,text:`Restored ${r.length} files:\n${r.map(e=>`- \`${e}\``).join(`
|
|
2877
|
-
`)}`}]}}catch(e){return
|
|
2878
|
-
`)[0].slice(0,500);if(r&&r!==e){let i=await t.embedQuery(r),a=await n.search(i,S);a.length>0&&(C=a,E=`> _Original query "${e}" returned 0 results. Auto-reformulated to "${r}"._\n\n`,
|
|
2877
|
+
`)}`}]}}catch(e){return Zf.error(`Restore failed`,I(e)),K(`INTERNAL`,`Restore failed: ${e instanceof Error?e.message:String(e)}`)}})}const $f=/<\/?curated-context>/gi;function ep(e){return e.replace($f,``)}function tp(e){return`<curated-context>\n${ep(e)}\n</curated-context>`}const np=F(`tools`);function rp(e,t,i,a){r(e,t,i);let o=e.memoryMetaGet(t);if(!o)return;let s=_(o,{...n,...a});s&&(v(e,t,s),h(e,t,i))}function ip(e,t){let n=[],r=re(process.cwd());r&&n.push(`[project: ${r}]`);let i=t?Zt(t,`__context_boost`):void 0;return i&&n.push(`[focus: ${i.value}]`),n.length===0?e:`${n.join(` `)} ${e}`}function ap(e,t,n){return n?e:t===`curated`?e*1.2:e}function op(e,t){return t?e:e.map(e=>({record:e.record,score:ap(e.score,e.record.origin,t)})).sort((e,t)=>t.score-e.score)}async function sp(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:qn(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 np.warn(`ER fallback failed`,I(e)),{results:n,triggered:!0,cacheHit:a}}}function cp(e,t,n=60){let r=new Map,i=e[0]?.score||1,a=t[0]?.score||1;for(let t=0;t<e.length;t++){let a=e[t],o=a.score/i;r.set(a.record.id,{record:a.record,score:1/(n+t+1)*o})}for(let e=0;e<t.length;e++){let i=t[e],o=i.score/a,s=r.get(i.record.id);s?s.score+=1/(n+e+1)*o:r.set(i.record.id,{record:i.record,score:1/(n+e+1)*o})}return[...r.values()].sort((e,t)=>t.score-e.score).map(({record:e,score:t})=>({record:e,score:t}))}function lp(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 up(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 dp(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&&!fp.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 fp=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 pp(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 _n(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 mp(e,t,n,r,i,a,o,s,c,l){let u=U(`search`);e.registerTool(`search`,{title:u.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:So,inputSchema:{query:L.string().max(5e3).describe(`Natural language search query`),limit:L.number().min(1).max(20).default(5).describe(`Maximum results to return`),search_mode:L.enum([`hybrid`,`semantic`,`keyword`]).default(`hybrid`).describe(`Search strategy: hybrid (vector + FTS + RRF fusion, default), semantic (vector only), keyword (FTS only)`),content_type:L.enum(le).optional().describe(`Filter by content type`),source_type:L.enum(fe).optional().describe(`Coarse filter: "source" (code only), "documentation" (md, curated), "test", "config". Overrides content_type if both set.`),origin:L.enum(de).optional().describe(`Filter by knowledge origin`),category:L.string().optional().describe(`Filter by category (e.g., decisions, patterns, conventions)`),tags:L.array(L.string()).optional().describe(`Filter by tags (returns results matching ANY of the specified tags)`),min_score:L.number().min(0).max(1).default(.25).describe(`Minimum similarity score`),graph_hops:L.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:L.number().min(100).max(5e4).optional().describe(`Maximum token budget for the response. When set, output is truncated to fit.`),dedup:L.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:L.array(L.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:u.annotations},async({query:e,limit:u,search_mode:d,content_type:f,source_type:p,origin:m,category:h,tags:g,min_score:_,graph_hops:v,max_tokens:y,dedup:b,workspaces:x})=>{try{let S={limit:u,minScore:_,contentType:f,sourceType:p,origin:m,category:h,tags:g},C,w=!1,T=!1,E=``,D=ip(e,s);if(d===`keyword`)C=await n.ftsSearch(e,S),C=C.slice(0,u);else if(d===`semantic`){let r=await t.embedQuery(D);C=await n.search(r,S);let a=await sp(i,C[0]?.score??0,C,e,u);C=a.results,w=a.triggered,T=a.cacheHit}else{let r=await t.embedQuery(D),a=n.coarseSearch,o=a?a.bind(n):n.search.bind(n),[s,c]=await Promise.all([o(r,{...S,limit:u*2}),n.ftsSearch(e,{...S,limit:u*2}).catch(()=>[])]);s.length===0&&c.length>0?(C=c.slice(0,u),E=` (FTS-only: vector index rebuilding)`):C=c.length===0&&s.length>0?s.slice(0,u):cp(s,c).slice(0,u);let l=await sp(i,s[0]?.score??0,C,e,u);C=l.results,w=l.triggered,T=l.cacheHit}C=op(C,m).slice(0,u),a&&a.recordSearch(e,w,T),C.length>1&&(C=lp(C,e)),C=up(C);let O=``;if(x&&x.length>0){let n=Qs(x,he(process.cwd()));if(n.length>0){let{stores:r,closeAll:i}=await $s(n);try{let i;i=d===`keyword`?await tc(r,e,{...S,limit:u}):await ec(r,await t.embedQuery(e),{...S,limit:u});for(let e of i)C.push({record:{...e.record,sourcePath:`[${e.workspace}] ${e.record.sourcePath}`},score:e.score});C=C.sort((e,t)=>t.score-e.score).slice(0,u),O=` + ${n.length} workspace(s)`}finally{await i()}}}if(b===`file`&&C.length>1){let e=new Map;for(let t of C){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}]})}C=[...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(C.length>1){let e=C[0].score,t=Math.max(e*.4,.1);C=C.filter(e=>e.score>=t)}if(C.length===0){if(o?.available)try{let r=(await o.createMessage({prompt:`The search query "${e}" returned 0 results in AI Kit code search. Suggest ONE alternative search query that might find relevant results. Reply with ONLY the alternative query, nothing else.`,systemPrompt:`You are a search query optimizer for AI Kit code search. Generate a single alternative query.`,maxTokens:100})).text.trim().split(`
|
|
2878
|
+
`)[0].slice(0,500);if(r&&r!==e){let i=await t.embedQuery(r),a=await n.search(i,S);a.length>0&&(C=a,E=`> _Original query "${e}" returned 0 results. Auto-reformulated to "${r}"._\n\n`,np.info(`Smart search fallback succeeded`,{originalQuery:e,altQuery:r,resultCount:a.length}))}}catch(e){np.debug(`Smart search fallback failed`,{error:String(e)})}if(C.length===0)return{content:[{type:`text`,text:`No results found for the given query.`}],structuredContent:{results:[],totalResults:0,searchMode:d,query:e}}}let k,A;if(v>0&&!r&&(A="> **Note:** `graph_hops` was set but no graph store is available. Graph augmentation skipped."),v>0&&r)try{let e=await rt(r,C.map(e=>({recordId:e.record.id,score:e.score,sourcePath:e.record.sourcePath})),{hops:v,maxPerHit:5});k=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(`
|
|
2879
2879
|
`),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(`
|
|
2880
2880
|
`),i=[`- **Graph Context** (${v} hop${v>1?`s`:``}):`];e&&i.push(` Entities:\n${e}`),r&&i.push(` Relationships:\n${r}`),k.set(t.recordId,i.join(`
|
|
2881
|
-
`))}}catch(e){
|
|
2882
|
-
`)}\n\n${n.origin===`curated
|
|
2881
|
+
`))}}catch(e){np.warn(`Graph augmentation failed`,I(e)),A=`> **Note:** Graph augmentation failed. Results shown without graph context.`}let j=Date.now();for(let e of C)if(e.record.origin===`curated`&&e.record.indexedAt){let t=j-new Date(e.record.indexedAt).getTime(),n=Math.max(0,t/864e5);e.score*=.95**n}if(C.sort((e,t)=>t.score-e.score),C=we(C),s)for(let e of C){if(e.record.origin!==`curated`)continue;let t=El(e.record.sourcePath);t&&rp(s,t,c,l)}let ee=C.map((e,t)=>{let n=e.record;return`${`### Result ${t+1} (score: ${e.score.toFixed(3)})`}\n${[`- **Source**: ${n.sourcePath}`,n.headingPath?`- **Section**: ${n.headingPath}`:null,`- **Type**: ${n.contentType}`,n.startLine?`- **Lines**: ${n.startLine}-${n.endLine}`:null,n.origin===`indexed`?null:`- **Origin**: ${n.origin}`,n.category?`- **Category**: ${n.category}`:null,n.tags?.length?`- **Tags**: ${n.tags.join(`, `)}`:null,k?.get(n.id)??null].filter(Boolean).join(`
|
|
2882
|
+
`)}\n\n${n.origin===`curated`?tp(n.content):n.content}`}).join(`
|
|
2883
2883
|
|
|
2884
2884
|
---
|
|
2885
2885
|
|
|
2886
|
-
`),te=(d===`hybrid`?`hybrid (vector + keyword RRF)`:d===`keyword`?`keyword (FTS)`:`semantic (vector)`)+O,ne=
|
|
2886
|
+
`),te=(d===`hybrid`?`hybrid (vector + keyword RRF)`:d===`keyword`?`keyword (FTS)`:`semantic (vector)`)+O,ne=dp(C,e),re=ne.length>0?`\n_Distinctive terms: ${ne.map(e=>`\`${e}\``).join(`, `)}_`:``,M=await pp(n,C),ie=[];if(C.length===0)ie.push("`reindex` — no results found, index may be stale"),ie.push("`find` — try federated search with glob/regex");else{let e=C[0]?.record.sourcePath;e&&ie.push(`\`lookup\` — see all chunks from \`${e}\``),ie.push("`symbol` — resolve a specific symbol from the results"),ie.push("`compact` — compress a result file for focused reading")}let N=[A?`${A}\n\n`:``,M?`${M}\n\n`:``,ee,`\n\n---\n_Search mode: ${te} | ${C.length} results_${re}`,`\n_Next: ${ie.join(` | `)}_`],ae=E+N.join(``);y&&(ae=sn(ae,y));let P=new Set,oe=[];for(let e of C){if(e.record.origin!==`curated`||e.record.sourcePath.startsWith(`[`))continue;let t=El(e.record.sourcePath);if(!t)continue;let n=wl(t,e.record.headingPath??t);n&&!P.has(n.uri)&&(P.add(n.uri),oe.push(n))}return{content:[{type:`text`,text:ae},...oe],structuredContent:{results:C.map(e=>({sourcePath:e.record.sourcePath,contentType:e.record.contentType,score:e.score,...e.record.headingPath?{headingPath:e.record.headingPath}:{},...e.record.startLine?{startLine:e.record.startLine}:{},...e.record.endLine?{endLine:e.record.endLine}:{},...e.record.origin===`indexed`?{}:{origin:e.record.origin},...e.record.category?{category:e.record.category}:{},...e.record.tags?.length?{tags:e.record.tags}:{}})),totalResults:C.length,searchMode:d,query:e}}}catch(e){return np.error(`Search failed`,I(e)),K(`INTERNAL`,`Search failed: ${e instanceof Error?e.message:String(e)}`)}})}const hp=F(`tools`);function gp(e,t,n){let r=U(`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:L.enum([`tools`,`stash`,`all`]).default(`all`).describe(`What to include: tools (replay only), stash (stash + checkpoints only), or all`),since:L.string().optional().describe(`ISO timestamp — only include activity after this time`),last:L.number().min(1).max(500).optional().describe(`Max replay entries to consider (default: 50)`),focus:L.string().optional().describe(`Focus query — prioritize entries matching this topic`),mode:L.enum([`deterministic`,`sampling`]).default(`deterministic`).describe(`Summary mode: deterministic (fast, template-based) or sampling (LLM-assisted, richer)`),token_budget:L.number().min(100).max(8e3).default(2e3).describe(`Target token budget for the digest output`),persist:L.boolean().default(!0).describe(`Auto-save digest to stash for crash recovery`)},annotations:r.annotations},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 Jt(l,async(e,t,r)=>(await n.createMessage({prompt:e,systemPrompt:t,maxTokens:r})).text,u):qt(l,u)).digest}]}}catch(e){return hp.error(`Session digest failed`,I(e)),K(`INTERNAL`,`Session digest failed: ${e instanceof Error?e.message:String(e)}`)}})}const _p=1e4,vp={defaultTtlSeconds:300,defaultLeaseTtlMinutes:10,globalEnabled:!1};function yp(e){return e??vp}function bp(e,t){let n=e.trim();if(!n)throw Error(`${t} is required`);return n}function xp(e,t,n){let r=bp(e,t);if(r.length>n)throw Error(`${t} exceeds max length of ${n}`);return r}function Sp(e,t){if(!Number.isFinite(e)||e<=0)throw Error(`${t} must be greater than 0`);return Math.trunc(e)}function Cp(e,t=!1,n){bp(e,`workspace`);let r=yp(n);if(!t)return e;if(!r.globalEnabled)throw Error(`Global signal scope is disabled`);return`__global__`}function wp(e,t,n){let r=yp(n),i=Cp(t.workspace,t.global??!1,r),a=xp(t.key,`key`,500),o=xp(t.value,`value`,_p),s=t.agent?xp(t.agent,`agent`,500):void 0,c=Sp(t.ttlSeconds??r.defaultTtlSeconds,`ttlSeconds`);return e.signalPost(i,a,o,s,c)}function Tp(e,t,n){let r=bp(t,`workspace`),i=xp(n,`key`,500);return e.signalGet(r,i)}function Ep(e,t){let n=bp(t,`workspace`);return e.signalList(n)}function Dp(e,t,n){let r=bp(t,`workspace`),i=n===void 0?void 0:xp(n,`key`,500);return e.signalClear(r,i)}function Op(e,t,n){let r=yp(n),i=xp(t.resource,`resource`,500),a=xp(t.holder,`holder`,500),o=bp(t.workspace,`workspace`),s=t.intent?xp(t.intent,`intent`,_p):void 0,c=Sp(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 kp(e,t,n,r){let i=bp(t,`workspace`),a=xp(n,`resource`,500),o=xp(r,`holder`,500);return e.leaseRelease(a,o,i)}function Ap(e,t){let n=bp(t,`workspace`);return e.leaseList(n)}const jp=F(`tools:signal`);function Mp(e){return JSON.stringify(e,null,2)}function Np(e,t,n){let r=U(`signal`),i={...vp,...n};e.registerTool(`signal`,{title:r.title,description:`Inter-agent signaling and lease coordination`,inputSchema:{action:L.enum([`post`,`get`,`list`,`clear`,`lease`,`unlease`,`leases`]).describe(`Signal action to perform`),workspace:L.string().describe(`Workspace identifier (required)`),key:L.string().optional().describe(`Signal key (for post/get/clear)`),value:L.string().optional().describe(`Signal value (for post)`),agent:L.string().optional().describe(`Agent identifier`),resource:L.string().optional().describe(`Resource path (for lease/unlease)`),holder:L.string().optional().describe(`Lease holder ID (for lease/unlease)`),intent:L.string().optional().describe(`What the holder plans to do`),ttl:L.number().optional().describe(`TTL (seconds for signals, minutes for leases)`),global:L.boolean().optional().describe(`Use global scope (default: false)`)},annotations:r.annotations},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=wp(t,{workspace:n,key:r,value:a,agent:o,ttlSeconds:u,global:d},i);return{content:[{type:`text`,text:Mp({id:e})}],structuredContent:{id:e}}}case`get`:{if(!r)throw Error(`key is required for get`);let e=Tp(t,Cp(n,d??!1,i),r);return{content:[{type:`text`,text:e.length===0?`[]`:Mp(e)}],structuredContent:{signals:e}}}case`list`:{let e=Ep(t,Cp(n,d??!1,i));return{content:[{type:`text`,text:e.length===0?`[]`:Mp(e)}],structuredContent:{signals:e}}}case`clear`:{let e=Dp(t,Cp(n,d??!1,i),r);return{content:[{type:`text`,text:Mp({cleared:e})}],structuredContent:{cleared:e}}}case`lease`:{if(!s||!c)throw Error(`resource and holder are required for lease`);let e=Op(t,{resource:s,holder:c,workspace:n,intent:l,ttlMinutes:u},i);return{content:[{type:`text`,text:Mp(e)}],structuredContent:e}}case`unlease`:{if(!s||!c)throw Error(`resource and holder are required for unlease`);let e=kp(t,n,s,c);return{content:[{type:`text`,text:Mp({released:e})}],structuredContent:{released:e}}}case`leases`:{let e=Ap(t,n);return{content:[{type:`text`,text:e.length===0?`[]`:Mp(e)}],structuredContent:{leases:e}}}}}catch(e){return jp.error(`Signal operation failed`,I(e)),K(`INTERNAL`,`Signal operation failed: ${e instanceof Error?e.message:String(e)}`)}})}const Pp=F(`tools`);function Fp(e,t,n,r=15e3){let i,a=new Promise(e=>{i=setTimeout(()=>{Pp.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),Pp.warn(`Status sub-operation "${n}" failed: ${e instanceof Error?e.message:String(e)}`),{value:t,timedOut:!1})),a])}function Ip(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 Lp(){let e=Bn.get(),t=zn.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(`
|
|
2887
2887
|
`):` 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(`
|
|
2888
|
-
`)}const
|
|
2889
|
-
`)}],structuredContent:o}})}function
|
|
2890
|
-
`),ae={totalRecords:u.totalRecords,totalFiles:u.totalFiles,lastIndexedAt:u.lastIndexedAt??null,onboarded:_,onboardDir:h,contentTypes:u.contentTypeBreakdown,wasmAvailable:!!Bn.get(),wasmDiagnostics:zn.get(),graphStats:f,curatedCount:p,serverVersion:j,scaffoldVersion:k??null,workspaceScaffoldVersion:A??null,upgradeAvailable:ee||ne,storeBackend:a?.store?.backend,storeDiagnostics:E??null,contextPressure:v,nextAction:w};return{content:[{type:`text`,text:ie+(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:ae}}catch(e){return
|
|
2891
|
-
`)};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
|
|
2888
|
+
`)}const Rp=5*6e4;let zp=null,Bp=null;function Vp(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 Hp(){let e=Date.now();if(zp&&e-zp.ts<Rp)return zp.value;try{let t=P(Sn(),`.copilot`,`.aikit-scaffold.json`);if(!D(t))return zp={value:null,ts:e},null;let n=JSON.parse(k(t,`utf-8`)).version??null;return zp={value:n,ts:e},n}catch{return zp={value:null,ts:e},null}}function Up(){let e=Date.now();if(Bp&&e-Bp.ts<Rp)return Bp.value;try{let t=P(process.cwd(),`.github`,`.aikit-scaffold.json`);if(!D(t))return Bp={value:null,ts:e},null;let n=JSON.parse(k(t,`utf-8`)).version??null;return Bp={value:n,ts:e},n}catch{return Bp={value:null,ts:e},null}}function Wp(e){let t=U(`status`);e.registerTool(`status`,{title:t.title,description:`Get the current status and statistics of the AI Kit index.`,outputSchema:po,annotations:t.annotations},async()=>{let e=b(),t=Hp(),n=Up(),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)**: ${Bn.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=x(),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`?(y(),a.push(``,`### ⬆ Upgrade Available (auto-upgrade failed, retrying)`,`- Server v${e} ≠ ${c}`,`- Error: ${o.error??`unknown`}`)):(y(),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:!!Bn.get(),wasmDiagnostics:zn.get(),graphStats:null,curatedCount:0,serverVersion:e,scaffoldVersion:t??null,workspaceScaffoldVersion:n??null,upgradeAvailable:r||i,contextPressure:0,nextAction:Ip({onboarded:!1,indexStale:!1,contextPressure:0})};return{content:[{type:`text`,text:a.join(`
|
|
2889
|
+
`)}],structuredContent:o}})}function Gp(e,t,n,r,i,a,o,s){let c=U(`status`);e.registerTool(`status`,{title:c.title,description:`Get the current status and statistics of the AI Kit index.`,outputSchema:po,annotations:c.annotations},async()=>{let e=[];try{let[c,l]=await Promise.all([Fp(t.getStats(),{totalRecords:0,totalFiles:0,lastIndexedAt:null,contentTypeBreakdown:{}},`store.getStats`),Fp(t.listSourcePaths(),[],`store.listSourcePaths`)]),u=c.value;c.timedOut&&e.push(`⚠ Index stats timed out — values may be incomplete`);let d=l.value;l.timedOut&&e.push(`⚠ File listing timed out`);let f=null,p=0,m=[`## AI Kit Status`,``,`- **Total Records**: ${u.totalRecords}`,`- **Total Files**: ${u.totalFiles}`,`- **Last Indexed**: ${u.lastIndexedAt??`Never`}`,``,`### Content Types`,...Object.entries(u.contentTypeBreakdown).map(([e,t])=>`- ${e}: ${t}`),``,`### Indexed Files`,...d.slice(0,50).map(e=>`- ${e}`),d.length>50?`\n... and ${d.length-50} more files`:``];if(n)try{let t=await Fp(n.getStats(),{nodeCount:0,edgeCount:0,nodeTypes:{},edgeTypes:{}},`graphStore.getStats`);if(t.timedOut)e.push(`⚠ Graph stats timed out`),m.push(``,`### Knowledge Graph`,`- Graph stats timed out`);else{let e=t.value;f={nodes:e.nodeCount,edges:e.edgeCount},m.push(``,`### Knowledge Graph`,`- **Nodes**: ${e.nodeCount}`,`- **Edges**: ${e.edgeCount}`,...Object.entries(e.nodeTypes).map(([e,t])=>` - ${e}: ${t}`));try{let e=await Fp(n.validate(),{valid:!0,danglingEdges:[],orphanNodes:[],stats:{nodeCount:0,edgeCount:0,nodeTypes:{},edgeTypes:{}}},`graphStore.validate`);if(!e.timedOut){let t=e.value;t.valid||m.push(`- **⚠ Integrity Issues**: ${t.danglingEdges.length} dangling edges`),t.orphanNodes.length>0&&m.push(`- **Orphan nodes**: ${t.orphanNodes.length}`)}}catch{}}}catch{m.push(``,`### Knowledge Graph`,`- Graph store unavailable`)}let h=a?.onboardDir??``,g=D(h),_=i?.onboardComplete||g;if(m.push(``,`### Onboard Status`,_?`- ✅ Complete${i?.onboardTimestamp?` (last: ${i.onboardTimestamp})`:``}`:'- ❌ Not run — call `onboard({ path: "." })` to analyze the codebase',`- **Onboard Directory**: \`${h}\``),r)try{let t=await Fp(r.list(),[],`curated.list`);if(t.timedOut)e.push(`⚠ Curated knowledge listing timed out`),m.push(``,`### Curated Knowledge`,`- Listing timed out`);else{let e=t.value;p=e.length,m.push(``,`### Curated Knowledge`,e.length>0?`- ${e.length} entries`:'- Empty — use `knowledge({ action: "remember", ... })` to persist decisions')}}catch{m.push(``,`### Curated Knowledge`,`- Unable to read curated entries`)}let v=Vp(u.totalRecords,f?.nodes??0,f?.edges??0,p),S=u.lastIndexedAt?new Date(u.lastIndexedAt).getTime():0,C=S>0?Date.now()-S:1/0,w=Ip({onboarded:_,indexStale:_&&C>1440*60*1e3,contextPressure:v});m.push(``),m.push(`## 📊 Context Pressure: ${v}/100`),v>=80?m.push(`⚠️ High pressure — consider pruning stale entries or compacting context.`):v>=50?m.push(`ℹ️ Moderate pressure — AI Kit memory is well-populated.`):m.push(`✅ Low pressure — plenty of headroom for more content.`);let T=0;if(u.lastIndexedAt){T=new Date(u.lastIndexedAt).getTime();let e=(Date.now()-T)/(1e3*60*60);m.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`)}m.push(``,`### Next Action`,`- **${w.kind}**: ${w.reason}`);let E=null,O=t;if(typeof O.getDiagnostics==`function`)try{E=O.getDiagnostics(),m.push(``,`### Storage`,`- **Backend**: ${a?.store?.backend??`unknown`}`,`- **Adapter**: ${E.adapterType}`,`- **Vector search**: ${E.vectorSearchEnabled?`✅ enabled`:`⚠ disabled (FTS-only fallback)`}`,E.dbPath?`- **DB**: ${E.dbPath}`:``,E.dbSizeBytes==null?``:`- **DB size**: ${(E.dbSizeBytes/1024/1024).toFixed(2)} MB`,`- **Embedding dim**: ${E.embeddingDim}`,`- **Vector dtype**: ${E.vectorDtype}`)}catch{}if(o===`smart`)if(m.push(``,`### Smart Indexing`),s){let e=s();e?m.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}`):m.push(`- **Mode**: Smart (trickle)`,`- **Status**: scheduler state unavailable (init may have failed)`)}else m.push(`- **Mode**: Smart (trickle) — scheduler state unavailable`);{try{let e=a?.stateDir?N(a.stateDir,`stash`):null;if(e&&D(e)){let t=te(e).mtimeMs;t>T&&(T=t)}}catch{}let e=[];if(r)try{let t=p>0?await r.list():[];for(let e of t){let t=new Date(e.updated||e.created).getTime();t>T&&(T=t)}e.push(...t.sort((e,t)=>new Date(t.updated).getTime()-new Date(e.updated).getTime()).slice(0,5))}catch{}let t=T>0?Date.now()-T:0;if(t>=144e5){let n=Math.floor(t/36e5);if(m.push(``,`### 🌅 Session Briefing`,`_${n}+ hours since last activity — here's what to pick up:_`,``),e.length>0){m.push(`**Recent decisions/notes:**`);for(let t of e)m.push(`- **${t.title}** (${t.category??`note`}) — ${(t.contentPreview??``).slice(0,80)}…`)}m.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')}}m.push(``,`### Runtime`,Lp());let k=Hp(),A=Up(),j=b(),ee=k!=null&&k!==j,ne=A!=null&&A!==j;if(ee||ne){let e=x(),t=[];ee&&t.push(`user scaffold v${k}`),ne&&t.push(`workspace scaffold v${A}`);let n=t.join(`, `);e.state===`success`?m.push(``,`### ✅ Upgrade Applied`,`- Server v${j} — ${n} auto-upgraded successfully.`,`- _Restart the MCP server to use the updated version._`):e.state===`pending`?m.push(``,`### ⏳ Upgrade In Progress`,`- Server v${j} ≠ ${n}`,`- Auto-upgrade is running in the background…`):e.state===`failed`?(y(),m.push(``,`### ⬆ Upgrade Available (auto-upgrade failed, retrying)`,`- Server v${j} ≠ ${n}`,`- Error: ${e.error??`unknown`}`)):(y(),m.push(``,`### ⬆ Upgrade Available`,`- Server v${j} ≠ ${n}`,`- Auto-upgrade triggered — check again shortly.`))}e.length>0&&m.push(``,`### ⚠ Warnings`,...e.map(e=>`- ${e}`));let re=xa();if(re.length>0){let e=re.sort((e,t)=>t.callCount-e.callCount);m.push(``,`### Tool Usage This Session`,``),m.push(`| Tool | Calls | Tokens In | Tokens Out | Errors | Avg Latency |`),m.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);m.push(`| ${t.tool} | ${t.callCount} | ${e.toLocaleString()} | ${n.toLocaleString()} | ${t.errorCount} | ${r}ms |`)}}let M=pa();if(M.bufferSize>=10){let e=M.state===`healthy`?`🟢`:M.state===`degraded`?`🔴`:`🟡`;m.push(``,`### Auto-GC: ${e} ${M.state}`),m.push(`- p95 latency: ${M.p95}ms | buffer: ${M.bufferSize} samples`),M.gcCount>0&&m.push(`- GC cycles triggered: ${M.gcCount}`)}let ie=m.join(`
|
|
2890
|
+
`),ae={totalRecords:u.totalRecords,totalFiles:u.totalFiles,lastIndexedAt:u.lastIndexedAt??null,onboarded:_,onboardDir:h,contentTypes:u.contentTypeBreakdown,wasmAvailable:!!Bn.get(),wasmDiagnostics:zn.get(),graphStats:f,curatedCount:p,serverVersion:j,scaffoldVersion:k??null,workspaceScaffoldVersion:A??null,upgradeAvailable:ee||ne,storeBackend:a?.store?.backend,storeDiagnostics:E??null,contextPressure:v,nextAction:w};return{content:[{type:`text`,text:ie+(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:ae}}catch(e){return Pp.error(`Status failed`,I(e)),K(`INTERNAL`,`Status check failed: ${e instanceof Error?e.message:String(e)}`)}})}const Kp=F(`tools`);function qp(e){let t=U(`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:L.array(L.string().max(2e3)).min(1).max(5).describe('Search queries (1–5). Single: `["react hooks"]`. Multiple searched in parallel.'),limit:L.number().min(1).max(20).default(5).describe(`Max results per query`),site:L.string().optional().describe(`Restrict to domain (e.g., "docs.aws.amazon.com")`),provider:L.enum([`multi`,`duckduckgo`,`bing-html`,`mojeek`,`searxng`,`google`,`brave`,`bing`]).optional().describe("Search provider. Defaults to env AIKIT_SEARCH_PROVIDER, then `multi` (fan-out). Single keyless: `duckduckgo`, `bing-html`, `mojeek`. Self-hosted: `searxng` (requires SEARXNG_URL). Keyed APIs: `google` (GOOGLE_API_KEY+GOOGLE_CSE_ID), `brave` (BRAVE_API_KEY), `bing` (BING_API_KEY). Missing keys auto-fall back to duckduckgo.")},annotations:t.annotations},async({queries:e,limit:t,site:n,provider:r})=>{let i=e,a=async e=>{let i=await fn({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(`
|
|
2891
|
+
`)};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 Kp.error(`Web search failed`,I(e)),K(`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);Kp.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(`
|
|
2892
2892
|
|
|
2893
|
-
`);return c===o.length?K(`INTERNAL`,u):{content:[{type:`text`,text:u}]}})}function
|
|
2894
|
-
`)}]}}catch(e){return
|
|
2895
|
-
`)}]}})}function
|
|
2896
|
-
`)}],structuredContent:i}}catch(e){return
|
|
2893
|
+
`);return c===o.length?K(`INTERNAL`,u):{content:[{type:`text`,text:u}]}})}function Jp(e){let t=U(`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:L.string().url().describe(`Request URL (http/https only)`),method:L.enum([`GET`,`POST`,`PUT`,`PATCH`,`DELETE`,`HEAD`]).default(`GET`).describe(`HTTP method`),headers:L.record(L.string(),L.string()).optional().describe(`Request headers as key-value pairs`),body:L.string().optional().describe(`Request body (for POST/PUT/PATCH)`),timeout:L.number().min(1e3).max(6e4).default(15e3).describe(`Timeout in milliseconds`)},annotations:t.annotations},async({url:e,method:t,headers:n,body:r,timeout:i})=>{try{let a=await st({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(`
|
|
2894
|
+
`)}]}}catch(e){return Kp.error(`HTTP request failed`,I(e)),K(`INTERNAL`,`HTTP request failed: ${e instanceof Error?e.message:String(e)}`)}})}function Yp(e){let t=U(`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:L.string().max(500).describe(`Regex pattern (without delimiters)`),flags:L.string().max(10).regex(/^[gimsuy]*$/).default(``).describe(`Regex flags (g, i, m, s, etc.)`),test_strings:L.array(L.string().max(1e4)).max(50).describe(`Strings to test the pattern against`),mode:L.enum([`match`,`replace`,`split`]).default(`match`).describe(`Test mode`),replacement:L.string().optional().describe(`Replacement string (for replace mode)`)},annotations:t.annotations},async({pattern:e,flags:t,test_strings:n,mode:r,replacement:i})=>{let a=Ft({pattern:e,flags:t,testStrings:n,mode:r,replacement:i});if(!a.valid)return K(`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(`
|
|
2895
|
+
`)}]}})}function Xp(e){let t=U(`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:L.enum([`base64_encode`,`base64_decode`,`url_encode`,`url_decode`,`sha256`,`md5`,`jwt_decode`,`hex_encode`,`hex_decode`]).describe(`Operation to perform`),input:L.string().max(1e6).describe(`Input text`)},annotations:t.annotations},async({operation:e,input:t})=>{try{let n=We({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 Kp.error(`Encode failed`,I(e)),K(`INTERNAL`,`Encode failed: ${e instanceof Error?e.message:String(e)}`)}})}function Zp(e){let t=U(`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:ho,inputSchema:{path:L.string().describe(`File or directory path to measure`),extensions:L.array(L.string()).optional().describe(`File extensions to include (default: .ts,.tsx,.js,.jsx)`)},annotations:t.annotations},async({path:e,extensions:t})=>{try{let n=await _t({path:e,extensions:t}),r=[`## Code Metrics`,``,`**Files:** ${n.summary.totalFiles}`,`**Total lines:** ${n.summary.totalLines} (${n.summary.totalCodeLines} code)`,`**Functions:** ${n.summary.totalFunctions}`,`**Avg complexity:** ${n.summary.avgComplexity}`,`**Max complexity:** ${n.summary.maxComplexity.value} (${n.summary.maxComplexity.file})`,``,`### Top files by complexity`,``,`| File | Lines | Code | Complexity | Cognitive | Functions | Imports |`,`|------|-------|------|------------|-----------|-----------|---------|`];for(let e of n.files.slice(0,20)){let t=e.cognitiveComplexity===void 0?`—`:String(e.cognitiveComplexity);r.push(`| ${e.path} | ${e.lines.total} | ${e.lines.code} | ${e.complexity} | ${t} | ${e.functions} | ${e.imports} |`)}n.files.length>20&&r.push(``,`_...and ${n.files.length-20} more files_`);let i={summary:{totalFiles:n.summary.totalFiles,totalLines:n.summary.totalLines,totalCodeLines:n.summary.totalCodeLines,totalFunctions:n.summary.totalFunctions,avgComplexity:n.summary.avgComplexity,maxComplexity:{value:n.summary.maxComplexity.value,file:n.summary.maxComplexity.file}},files:n.files.map(e=>({path:e.path,lines:e.lines.total,code:e.lines.code,complexity:e.complexity,functions:e.functions}))};return{content:[{type:`text`,text:r.join(`
|
|
2896
|
+
`)}],structuredContent:i}}catch(e){return Kp.error(`Measure failed`,I(e)),K(`INTERNAL`,`Measure failed: ${e instanceof Error?e.message:String(e)}`)}})}function Qp(e){let t=U(`changelog`);e.registerTool(`changelog`,{title:t.title,description:`Generate a changelog from git history between two refs. Groups by conventional commit type.`,inputSchema:{from:L.string().max(200).describe(`Start ref (tag, SHA, HEAD~N)`),to:L.string().max(200).default(`HEAD`).describe(`End ref (default: HEAD)`),format:L.enum([`grouped`,`chronological`,`per-scope`]).default(`grouped`).describe(`Output format`),include_breaking:L.boolean().default(!0).describe(`Highlight breaking changes`),cwd:L.string().optional().describe(`Repository root or working directory`)},annotations:t.annotations},async({from:e,to:t,format:n,include_breaking:r,cwd:i})=>{try{let a=Te({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 Kp.error(`Changelog failed`,I(e)),K(`INTERNAL`,`Changelog failed: ${e instanceof Error?e.message:String(e)}`)}})}function $p(e){let t=U(`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:L.string().max(5e5).describe(`JSON data to validate (as string)`),schema:L.string().max(5e5).describe(`JSON Schema to validate against (as string)`)},annotations:t.annotations},async({data:e,schema:t})=>{try{let n=Gt({data:JSON.parse(e),schema:JSON.parse(t)});if(n.valid)return{content:[{type:`text`,text:`## Validation: PASSED
|
|
2897
2897
|
|
|
2898
2898
|
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(`
|
|
2899
|
-
`)}]}}catch(e){return
|
|
2900
|
-
`)}],structuredContent:a}})}function
|
|
2901
|
-
`)}],structuredContent:o}}catch(e){return
|
|
2899
|
+
`)}]}}catch(e){return Kp.error(`Schema validation failed`,I(e)),K(`INTERNAL`,`Schema validation failed: ${e instanceof Error?e.message:String(e)}`)}})}function em(e){let t=U(`env`);e.registerTool(`env`,{title:t.title,description:`Get system and runtime environment info. Sensitive env vars are redacted by default.`,outputSchema:go,inputSchema:{include_env:L.boolean().default(!1).describe(`Include environment variables`),filter_env:L.string().optional().describe(`Filter env vars by name substring`),show_sensitive:L.boolean().default(!1).describe(`Show sensitive values (keys, tokens, etc.) — redacted by default`)},annotations:t.annotations},async({include_env:e,filter_env:t,show_sensitive:n})=>{let r=Ke({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(`
|
|
2900
|
+
`)}],structuredContent:a}})}function tm(e){let t=U(`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:_o,inputSchema:{operation:L.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:L.string().optional().describe(`Date input (ISO, unix timestamp, or parseable string). For diff: two comma-separated dates`),timezone:L.string().optional().describe(`Target timezone (e.g., "America/New_York", "Asia/Tokyo")`),duration:L.string().optional().describe(`Duration to add (e.g., "2h30m", "1d", "30s") — for add operation`)},annotations:t.annotations},async({operation:e,input:t,timezone:n,duration:r})=>{try{let i=an({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(`
|
|
2901
|
+
`)}],structuredContent:o}}catch(e){return Kp.error(`Time failed`,I(e)),K(`INTERNAL`,`Time failed: ${e instanceof Error?e.message:String(e)}`)}})}function nm(e){try{let t=N(e,`.flows`);if(!D(t))return null;let n=A(t,{withFileTypes:!0});for(let e of n){if(!e.isDirectory())continue;let n=N(t,e.name,`meta.json`);if(D(n)&&JSON.parse(k(n,`utf-8`)).status===`active`)return e.name}}catch{return null}return null}function rm(e,t,n,r,i,a,o,s,c,l){let u=new oa,d=n.sources[0]?.path??process.cwd(),f={activeSlug:null};f.activeSlug=nm(d);let p=new Ei(N(n.stateDir??``,`flow-context`),()=>f.activeSlug),m=new _i;m.register(mi),m.register(Vr),m.register(di),m.register(Rr),m.register(Pr),m.register(Fr),m.register(gi),m.register(ui(()=>f.activeSlug?{active:!0,slug:f.activeSlug}:null));let h=new Si(m,t.curated,{},p),g=l??lo(n,[...La,...ja],H,Na(n)),_=e=>g.has(e),v=new Set([...g].filter(e=>!Nu.includes(e)&&!Ki.has(e))),y=new Xi;u.use(bi(h),{order:5,name:`auto-knowledge`}),u.use(Ca(),{order:10,name:`replay`}),u.use($i(y,{stateStore:t.stateStore,curatedStore:t.curated},{trackedTools:v}),{order:94,name:`procedural-memory`}),u.use(Hi(new Bi(t.stateStore,t.curated)),{order:95,name:`observation-capture`}),u.use(za(),{order:1,name:`structured-content-guard`}),u.use(Ti(wi(n.tokenBudget)),{order:90,name:`compression`}),Ja(e,u,n.toolPrefix??``);let b=[...g].filter(e=>Ma.has(e)?Aa.includes(e)?!!t.bridge:e===`er_update_policy`?!!t.policyStore:e===`er_evolve_review`?!!t.evolutionCollector:!1:!0);_(`search`)&&mp(e,t.embedder,t.store,t.graphStore,t.bridge,t.evolutionCollector,a,t.stateStore,n.memory?.retention,n.memory?.consolidation);let x={store:t.store,graphStore:t.graphStore,embedder:t.embedder},S=c?e=>{c()?.prioritize(e)}:void 0;_(`lookup`)&&wu(e,t.store,x);let C={onboardComplete:t.onboardComplete,onboardTimestamp:t.onboardTimestamp};_(`status`)&&Gp(e,t.store,t.graphStore,t.curated,C,n,o,s),_(`config`)&&Xs(e,n),_(`reindex`)&&Jf(e,t.indexer,n,t.curated,t.store,i,o),_(`knowledge`)&&Su(e,t.curated,t.policyStore,t.evolutionCollector,i,p,t.stateStore,n.memory?.retention,n.memory?.supersession,n.memory?.consolidation,n.memory?.lessons),_(`analyze`)&&vs(e,t.store,t.embedder,x),_(`blast_radius`)&&ys(e,t.store,t.embedder,t.graphStore,x),_(`produce_knowledge`)&&Kf(e,n),_(`onboard`)&&zu(e,t.store,t.embedder,n,C,x),_(`graph`)&&pl(e,t.graphStore),_(`audit`)&&ws(e,t.store,t.embedder,n.tokenBudget),_(`compact`)&&sc(e,t.embedder,t.fileCache,d,n.allRoots,x,S),_(`scope_map`)&&cc(e,t.embedder,t.store,x),_(`find`)&&lc(e,t.embedder,t.store,d,x),_(`parse_output`)&&Cc(e),_(`workset`)&&Vu(e),_(`check`)&&bc(e,x,n.tokenBudget),_(`symbol`)&&uc(e,t.embedder,t.store,t.graphStore),_(`eval`)&&xc(e),_(`test_run`)&&Sc(e,x),_(`stash`)&&Hu(e,t.stateStore),_(`signal`)&&Np(e,t.stateStore),_(`git_context`)&&Eu(e),_(`diff_parse`)&&Du(e),_(`rename`)&&Ou(e),_(`codemod`)&&ku(e),_(`restore`)&&Qf(e),_(`file_summary`)&&dc(e,t.fileCache,d,n.allRoots,x,S),_(`checkpoint`)&&Uu(e,t.stateStore),_(`data_transform`)&&Au(e),_(`trace`)&&fc(e,t.embedder,t.store,t.graphStore),_(`process`)&&hl(e),_(`watch`)&&gl(e),_(`dead_symbols`)&&pc(e,t.embedder,t.store,d,n.allRoots,x),_(`delegate`)&&wc(e,a),_(`health`)&&_l(e),_(`lane`)&&Wu(e),_(`queue`)&&Gu(e),_(`web_fetch`)&&vl(e),_(`guide`)&&yl(e,o),Nu.some(e=>_(e))&&Pu(e,n,b),_(`evidence_map`)&&al(e),_(`digest`)&&ol(e,t.embedder),_(`forge_classify`)&&sl(e),_(`stratum_card`)&&cl(e,t.embedder,t.fileCache),_(`forge_ground`)&&ll(e,t.embedder,t.store),_(`present`)&&Wf(e,r),_(`browser`)&&An(e,n),_(`web_search`)&&qp(e),_(`http`)&&Jp(e),_(`regex_test`)&&Yp(e),_(`encode`)&&Xp(e),_(`measure`)&&Zp(e),_(`changelog`)&&Qp(e),_(`schema_validate`)&&$p(e),_(`env`)&&em(e),_(`time`)&&tm(e),_(`flow`)&&rl(e,n,e=>{f.activeSlug=e}),t.bridge&&Aa.some(e=>_(e))&&(Os(e,t.bridge,t.evolutionCollector),ks(e,t.bridge),As(e,t.bridge)),t.policyStore&&_(`er_update_policy`)&&Zu(e,t.policyStore),t.evolutionCollector&&_(`er_evolve_review`)&&vc(e,t.evolutionCollector),ka(e,t.store,t.curated),_(`replay`)&&Xf(e),_(`session_digest`)&&gp(e,t.stateStore,a)}function im(e,t,n){let r=e=>!n||n.has(e);r(`check`)&&bc(e,void 0,t.tokenBudget),r(`eval`)&&xc(e),r(`test_run`)&&Sc(e),r(`parse_output`)&&Cc(e),r(`delegate`)&&wc(e),r(`git_context`)&&Eu(e),r(`diff_parse`)&&Du(e),r(`rename`)&&Ou(e),r(`codemod`)&&ku(e),r(`data_transform`)&&Au(e),r(`workset`)&&Vu(e),r(`restore`)&&Qf(e),r(`lane`)&&Wu(e),r(`queue`)&&Gu(e),r(`session_digest`)&&gp(e),r(`health`)&&_l(e),r(`process`)&&hl(e),r(`watch`)&&gl(e),r(`web_fetch`)&&vl(e),r(`guide`)&&yl(e),Nu.some(e=>r(e))&&Pu(e,t,[...n??new Set(La)]),r(`evidence_map`)&&al(e),r(`forge_classify`)&&sl(e),r(`present`)&&Wf(e),r(`browser`)&&An(e,t),r(`produce_knowledge`)&&Kf(e),r(`replay`)&&Xf(e),r(`status`)&&Wp(e),r(`flow`)&&rl(e,t),r(`web_search`)&&qp(e),r(`http`)&&Jp(e),r(`regex_test`)&&Yp(e),r(`encode`)&&Xp(e),r(`measure`)&&Zp(e),r(`changelog`)&&Qp(e),r(`schema_validate`)&&$p(e),r(`env`)&&em(e),r(`time`)&&tm(e)}const am=F(`resource-notifier`);var om=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){am.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){am.debug(`sendResourceUpdated failed`,{uri:e,error:String(t)})}}};const Z=F(`server`);async function sm(n){Z.info(`Initializing AI Kit components`);let r=n.store.backend,i=n.store.path,a=null;if(r===`sqlite-vec`){let e=N(i,`aikit.db`);D(i)||O(i,{recursive:!0}),a=await $n(e),Z.info(`SQLite adapter ready`,{type:a.type,vectorCapable:a.vectorCapable,dbPath:e}),a.vectorCapable||Z.warn(`┌──────────────────────────────────────────────────────────────────┐
|
|
2902
2902
|
│ ⚠ SQLite vector extension unavailable — DEGRADED MODE │
|
|
2903
2903
|
│ Vector search is disabled. Hybrid search returns FTS only. │
|
|
2904
2904
|
│ To enable: install/rebuild better-sqlite3 (native module). │
|
|
2905
|
-
└──────────────────────────────────────────────────────────────────┘`);let t=N(i,`lance`);D(t)&&Z.info(`Old LanceDB data found at ${t} — ignored. Safe to delete after verifying sqlite-vec works.`)}let o;if(a)o=a;else{let e=N(i,`aikit-state.db`);D(i)||O(i,{recursive:!0}),o=await $n(e),nr(o,Qn),Z.info(`State store adapter ready`,{type:o.type,dbPath:e})}let[s,c,l,u]=await Promise.all([(async()=>{if(n.embedding.childProcess!==!1){let e=new mr({model:n.embedding.model,dimensions:n.embedding.dimensions,interOpNumThreads:n.embedding.interOpNumThreads,intraOpNumThreads:n.embedding.intraOpNumThreads,idleTimeoutMs:n.embedding.idleTimeoutMs});return await e.initialize(),Z.info(`Embedder loaded (child process)`,{modelId:e.modelId,dimensions:e.dimensions}),e}let{OnnxEmbedder:e}=await import(`../../embeddings/dist/index.js`),t=new e({model:n.embedding.model,dimensions:n.embedding.dimensions,interOpNumThreads:n.embedding.interOpNumThreads,intraOpNumThreads:n.embedding.intraOpNumThreads});return await t.initialize(),Z.info(`Embedder loaded (in-process)`,{modelId:t.modelId,dimensions:t.dimensions}),t})(),(async()=>{let e=await tr({backend:r,path:i,adapter:a??void 0,embeddingDim:n.embedding.dimensions});return await e.initialize(),Z.info(`Store initialized`,{backend:r}),e})(),(async()=>{let e=a?new Zn({adapter:a}):new Zn({path:i});return await e.initialize(),Z.info(`Graph store initialized`,{shared:!!a}),e})(),(async()=>{let e=await Vn();if(e){let e=zn.get();Z.info(`WASM tree-sitter enabled`,{grammars:e.grammarCount,dir:e.wasmDir})}else{let e=zn.get();Z.warn(`WASM tree-sitter not available; analyzers will use regex fallback`,{reason:e.reason,os:e.os,arch:e.arch,healAttempted:e.healAttempted,healSuccess:e.healSuccess,healError:e.healError,pathsChecked:e.pathsChecked.map(e=>`${e.path} (${e.exists?`found`:`missing`})`)})}return e})()]),d=new gr(s,c),f=er(o),p=new hr(n.store.path);p.load(),d.setHashCache(p);let m=n.curated.path,h=new e(m);await h.initialize();let g=new t(m,c,s,h);d.setGraphStore(l);let _=Ds(n.er),v=_?new Gn(n.curated.path):void 0;v&&Z.info(`Policy store initialized`,{ruleCount:v.getRules().length});let y=_?new Wn:void 0,b=P(n.sources[0]?.path??process.cwd(),ce.aiContext),x=D(b),S=n.onboardDir?D(n.onboardDir):!1,C=x||S,w,T=x?b:n.onboardDir;if(C&&T)try{w=te(T).mtime.toISOString()}catch{}return Z.info(`Onboard state detected`,{onboardComplete:C,onboardTimestamp:w,aiKbExists:x,onboardDirExists:S}),{embedder:s,store:c,stateStore:f,closeStateStore:o===a?void 0:async()=>o.close(),indexer:d,curated:g,graphStore:l,fileCache:new be,bridge:_,policyStore:v,evolutionCollector:y,onboardComplete:C,onboardTimestamp:w}}function
|
|
2906
|
-
`)}const
|
|
2907
|
-
`),`utf8`),Q.info(`Auto-heal: created ESM shim for @huggingface/transformers (.mjs wrapper → .cjs)`,{path:t}))}catch(e){Q.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??ue.model,n=N(Sn(),`.cache`,`huggingface`,`transformers-js`,t);try{await r(n,{recursive:!0,force:!0}),Q.info(`Auto-heal: cleared embedding model cache`,{path:n})}catch{}}if(n.includes(`lance`)||n.includes(`database`)||n.includes(`store`)){let t=N(e.store.path,`lance`);try{await r(t,{recursive:!0,force:!0}),Q.info(`Auto-heal: cleared LanceDB store`,{path:t})}catch{}}if(n.includes(`sqlite`)||n.includes(`database disk image`)||n.includes(`graph`)){let t=N(e.store.path,`graph.db`);try{await r(t,{force:!0}),Q.info(`Auto-heal: cleared graph database`,{path:t})}catch{}let n=N(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(()=>{}),Q.info(`Auto-heal: cleared corrupted aikit database`,{path:n})}catch{}}if(n.includes(`cannot find module`)&&!n.includes(`huggingface`)&&!n.includes(`.cache`)){let{fileURLToPath:e}=await import(`node:url`),t=e(import.meta.url);if(t.includes(`_npx`)||t.includes(`npm-cache`)){let e=
|
|
2905
|
+
└──────────────────────────────────────────────────────────────────┘`);let t=N(i,`lance`);D(t)&&Z.info(`Old LanceDB data found at ${t} — ignored. Safe to delete after verifying sqlite-vec works.`)}let o;if(a)o=a;else{let e=N(i,`aikit-state.db`);D(i)||O(i,{recursive:!0}),o=await $n(e),nr(o,Qn),Z.info(`State store adapter ready`,{type:o.type,dbPath:e})}let[s,c,l,u]=await Promise.all([(async()=>{if(n.embedding.childProcess!==!1){let e=new mr({model:n.embedding.model,dimensions:n.embedding.dimensions,interOpNumThreads:n.embedding.interOpNumThreads,intraOpNumThreads:n.embedding.intraOpNumThreads,idleTimeoutMs:n.embedding.idleTimeoutMs});return await e.initialize(),Z.info(`Embedder loaded (child process)`,{modelId:e.modelId,dimensions:e.dimensions}),e}let{OnnxEmbedder:e}=await import(`../../embeddings/dist/index.js`),t=new e({model:n.embedding.model,dimensions:n.embedding.dimensions,interOpNumThreads:n.embedding.interOpNumThreads,intraOpNumThreads:n.embedding.intraOpNumThreads});return await t.initialize(),Z.info(`Embedder loaded (in-process)`,{modelId:t.modelId,dimensions:t.dimensions}),t})(),(async()=>{let e=await tr({backend:r,path:i,adapter:a??void 0,embeddingDim:n.embedding.dimensions});return await e.initialize(),Z.info(`Store initialized`,{backend:r}),e})(),(async()=>{let e=a?new Zn({adapter:a}):new Zn({path:i});return await e.initialize(),Z.info(`Graph store initialized`,{shared:!!a}),e})(),(async()=>{let e=await Vn();if(e){let e=zn.get();Z.info(`WASM tree-sitter enabled`,{grammars:e.grammarCount,dir:e.wasmDir})}else{let e=zn.get();Z.warn(`WASM tree-sitter not available; analyzers will use regex fallback`,{reason:e.reason,os:e.os,arch:e.arch,healAttempted:e.healAttempted,healSuccess:e.healSuccess,healError:e.healError,pathsChecked:e.pathsChecked.map(e=>`${e.path} (${e.exists?`found`:`missing`})`)})}return e})()]),d=new gr(s,c),f=er(o),p=new hr(n.store.path);p.load(),d.setHashCache(p);let m=n.curated.path,h=new e(m);await h.initialize();let g=new t(m,c,s,h);d.setGraphStore(l);let _=Ds(n.er),v=_?new Gn(n.curated.path):void 0;v&&Z.info(`Policy store initialized`,{ruleCount:v.getRules().length});let y=_?new Wn:void 0,b=P(n.sources[0]?.path??process.cwd(),ce.aiContext),x=D(b),S=n.onboardDir?D(n.onboardDir):!1,C=x||S,w,T=x?b:n.onboardDir;if(C&&T)try{w=te(T).mtime.toISOString()}catch{}return Z.info(`Onboard state detected`,{onboardComplete:C,onboardTimestamp:w,aiKbExists:x,onboardDirExists:S}),{embedder:s,store:c,stateStore:f,closeStateStore:o===a?void 0:async()=>o.close(),indexer:d,curated:g,graphStore:l,fileCache:new be,bridge:_,policyStore:v,evolutionCollector:y,onboardComplete:C,onboardTimestamp:w}}function cm(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(`
|
|
2906
|
+
`)}const lm=F(`background-task`);var um=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,lm.info(`Background task started`,{task:e.name,pending:this.queue.length});let t=Date.now();try{await e.fn();let n=Date.now()-t;lm.info(`Background task completed`,{task:e.name,durationMs:n}),e.resolve()}catch(n){let r=Date.now()-t;lm.error(`Background task failed`,{task:e.name,durationMs:r,err:n}),e.reject(n instanceof Error?n:Error(String(n)))}}this.running=null}};const dm=F(`idle-timer`);var fm=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){dm.info(`Idle timeout reached with no active session — skipping cleanup (waiting for first tool call)`);return}if(this._busy){dm.info(`Skipping idle cleanup — background work in progress`);return}dm.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`&&dm.warn(`Idle cleanup callback failed`,{error:String(t.reason)})}};const pm=F(`memory-monitor`);var mm=class{timer=null;warningBytes;criticalBytes;intervalMs;pressureFns=[];memoryPressureFns=[];lastLevel=`normal`;constructor(e){this.warningBytes=e?.warningBytes??4294967296,this.criticalBytes=e?.criticalBytes??8589934592,this.intervalMs=e?.intervalMs??6e4}onPressure(e){this.pressureFns.push(e)}registerMemoryPressureCallback(e){this.memoryPressureFns.push(e)}start(){this.timer||(this.timer=setInterval(()=>this.check(),this.intervalMs),this.timer.unref&&this.timer.unref(),pm.info(`Memory monitor started`,{warningMB:Math.round(this.warningBytes/1024/1024),criticalMB:Math.round(this.criticalBytes/1024/1024),intervalSec:Math.round(this.intervalMs/1e3)}))}stop(){this.timer&&=(clearInterval(this.timer),null)}getRssBytes(){return process.memoryUsage.rss()}check(){let e=this.getRssBytes(),t=`normal`;if(e>=this.criticalBytes?t=`critical`:e>=this.warningBytes&&(t=`warning`),t!==this.lastLevel||t===`critical`){let n=Math.round(e/1024/1024);t===`critical`?pm.warn(`Memory CRITICAL: ${n}MB RSS — consider restarting the server`):t===`warning`?pm.warn(`Memory WARNING: ${n}MB RSS`):this.lastLevel!==`normal`&&pm.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 hm=F(`tool-timeout`),gm=new Set([`onboard`,`reindex`,`produce_knowledge`,`analyze`,`codemod`,`audit`]);var _m=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 vm(e){return gm.has(e)?6e5:12e4}function ym(e,t,n){return new Promise((r,i)=>{let a=!1,o=setTimeout(()=>{if(!a){a=!0;let e=new _m(n,t);hm.warn(e.message),i(e)}},t);o.unref&&o.unref(),e().then(e=>{a||(a=!0,clearTimeout(o),r(e))},e=>{a||(a=!0,clearTimeout(o),i(e))})})}const Q=F(`server`),bm=new Set([`status`,`list_tools`,`describe_tool`,`config`,`env`]);function xm(e,t=28){let n=e.replace(/\s+/g,` `).trim();return n.length<=t?n:`${n.slice(0,t-3)}...`}function Sm(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 Cm(e,t,n){let r=[];try{t.statePath&&Ge(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=>`"${xm(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=>setTimeout(()=>e(null),50))]);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`"${xm(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 wm(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||bm.has(i))return o;try{r--;let e=a[0],i=await Cm(t,n,Sm(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 Tm(e){let t=e.toLowerCase();return[`protobuf`,`invalid model`,`invalid onnx`,`unexpected end`,`unexpected token`,`failed to load`,`failed to initialize embedding`,`checksum`,`corrupt`,`malformed`,`could not load`,`onnx`,`database disk image is malformed`,`file is not a database`,`lance`,`cannot find module`,`module not found`].some(e=>t.includes(e))}function Em(e){let t=e.indexOf(`node_modules`);return t>0?e.substring(0,t-1):null}async function Dm(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(`
|
|
2907
|
+
`),`utf8`),Q.info(`Auto-heal: created ESM shim for @huggingface/transformers (.mjs wrapper → .cjs)`,{path:t}))}catch(e){Q.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??ue.model,n=N(Sn(),`.cache`,`huggingface`,`transformers-js`,t);try{await r(n,{recursive:!0,force:!0}),Q.info(`Auto-heal: cleared embedding model cache`,{path:n})}catch{}}if(n.includes(`lance`)||n.includes(`database`)||n.includes(`store`)){let t=N(e.store.path,`lance`);try{await r(t,{recursive:!0,force:!0}),Q.info(`Auto-heal: cleared LanceDB store`,{path:t})}catch{}}if(n.includes(`sqlite`)||n.includes(`database disk image`)||n.includes(`graph`)){let t=N(e.store.path,`graph.db`);try{await r(t,{force:!0}),Q.info(`Auto-heal: cleared graph database`,{path:t})}catch{}let n=N(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(()=>{}),Q.info(`Auto-heal: cleared corrupted aikit database`,{path:n})}catch{}}if(n.includes(`cannot find module`)&&!n.includes(`huggingface`)&&!n.includes(`.cache`)){let{fileURLToPath:e}=await import(`node:url`),t=e(import.meta.url);if(t.includes(`_npx`)||t.includes(`npm-cache`)){let e=Em(t);if(e)try{let{execSync:t}=await import(`node:child_process`);t(`npm install --prefer-offline --no-audit --no-fund`,{cwd:e,stdio:`ignore`,timeout:6e4}),Q.info(`Auto-heal: re-ran npm install to restore missing module`,{path:e})}catch{Q.warn(`Auto-heal: npm install failed during module restoration`,{hint:`Run: npm cache clean --force && npx -y @vpxa/aikit serve`})}}}}function Om(e,t){let n=lo(e,La,H,Na(e)),r=cm(e,n,H),i=new Cn({name:e.serverName??`aikit`,version:b()},{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}`:``,``,`**${Ia.size} tools are still available** and fully functional:`,`check, eval, test_run, git_context, health, measure, web_fetch, web_search,`,`flow, regex_test, encode,`,`stash, checkpoint, lane, process, time, env, and more.`,``,`To fix embedding errors, try deleting the cached model:`,` rm -rf ~/.cache/huggingface/transformers-js/mixedbread-ai/`,`Then restart the server to re-download a fresh copy.`,``,`Try restarting the MCP server to retry initialization.`].filter(Boolean).join(`
|
|
2908
2908
|
`):[`AI Kit is still initializing (loading embeddings model & store).`,``,`**${Ia.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(`
|
|
2909
|
-
`);yr(i);let p=new oa;p.use(za(),{order:1,name:`structured-content-guard`}),Ja(i,p,e.toolPrefix??``);let m=i.sendToolListChanged.bind(i);i.sendToolListChanged=()=>{};let h=[];for(let e of La){if(!n.has(e))continue;let t=U(e),r=i.registerTool(e,{title:t.title,description:`${t.title} — initializing, available shortly`,inputSchema:{},annotations:t.annotations},async()=>({content:[{type:`text`,text:f()}]}));Ia.has(e)?r.remove():h.push(r)}
|
|
2909
|
+
`);yr(i);let p=new oa;p.use(za(),{order:1,name:`structured-content-guard`}),Ja(i,p,e.toolPrefix??``);let m=i.sendToolListChanged.bind(i);i.sendToolListChanged=()=>{};let h=[];for(let e of La){if(!n.has(e))continue;let t=U(e),r=i.registerTool(e,{title:t.title,description:`${t.title} — initializing, available shortly`,inputSchema:{},annotations:t.annotations},async()=>({content:[{type:`text`,text:f()}]}));Ia.has(e)?r.remove():h.push(r)}im(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:On(L.string(),()=>[])}},async()=>({messages:[]})),v,y,x=new Promise((e,t)=>{v=e,y=t}),S,C=new Promise(e=>{S=e}),w=()=>S?.(),T=(async()=>{await C;let n=[];try{let{createRequire:e}=await import(`node:module`),{readFileSync:t}=await import(`node:fs`),{fileURLToPath:r}=await import(`node:url`),{resolve:i,dirname:a}=await import(`node:path`),o=e(import.meta.url),s=i(a(r(import.meta.url)),`..`,`package.json`),c=JSON.parse(t(s,`utf8`)),l=Object.keys(c.dependencies??{}),u=[`@mixmark-io/domino`],d=[...l,...u.filter(e=>!l.includes(e))];for(let e of d)try{o.resolve(e)}catch{n.push(e)}if(n.length>0){Q.warn(`${n.length} dependencies not resolvable — attempting auto-repair`,{missing:n});let e=r(import.meta.url);if(e.includes(`_npx`)||e.includes(`npm-cache`))try{let{execSync:t}=await import(`node:child_process`),r=Em(e);if(r){Q.info(`Auto-heal: running npm install in npx cache to restore missing deps`,{path:r,missing:n}),t(`npm install --prefer-offline --no-audit --no-fund`,{cwd:r,stdio:`ignore`,timeout:6e4});let e=[];for(let t of n)try{o.resolve(t)}catch{e.push(t)}e.length===0?(Q.info(`Auto-heal: all missing dependencies restored successfully`),n=[]):(Q.warn(`Auto-heal: some deps still missing after npm install`,{stillMissing:e,hint:`Run: npm cache clean --force && npx -y @vpxa/aikit serve`}),n=e)}}catch(e){Q.warn(`Auto-heal: npm install failed — server may operate in degraded mode`,{error:e instanceof Error?e.message:String(e),hint:`Run: npm cache clean --force && npx -y @vpxa/aikit serve`})}else Q.warn(`Missing dependencies detected in non-npx environment`,{missing:n,hint:`Run: npm install (or pnpm install) to restore missing packages`})}}catch{}let r;try{r=await sm(e)}catch(t){let n=t instanceof Error?t.message:String(t);if(Tm(n)){Q.warn(`AI Kit initialization failed with recoverable error — attempting auto-heal retry`,{error:n}),await Dm(e,n);try{r=await sm(e),Q.info(`AI Kit auto-heal successful — initialization recovered after retry`)}catch(e){a=`failed`,o=e instanceof Error?e.message:String(e),Q.error(`AI Kit initialization failed after auto-heal attempt — server continuing with zero-dep tools only`,{error:o,originalError:n}),y?.(e instanceof Error?e:Error(o));return}}else{a=`failed`,o=n,Q.error(`AI Kit initialization failed — server continuing with zero-dep tools only`,{error:o}),y?.(t instanceof Error?t:Error(o));return}}let f=i.sendToolListChanged.bind(i);i.sendToolListChanged=()=>{};let p=i.sendPromptListChanged.bind(i);i.sendPromptListChanged=()=>{};let m=i.sendResourceListChanged.bind(i);i.sendResourceListChanged=()=>{};for(let e of h)e.remove();g.remove(),_.remove();let b=i._registeredTools??{};for(let e of Ia)b[e]?.remove();let x=new om(i),S=kc(i);rm(i,r,e,_r(i),x,S,t,t===`smart`?(()=>{let e=u;return e?.getState?e.getState():null}):null,t===`smart`?()=>{let e=u;return e?{prioritize:e.prioritize.bind(e)}:null}:null),Ar(i,{curated:r.curated,store:r.store,graphStore:r.graphStore,stateStore:r.stateStore},t),i.sendToolListChanged=f,i.sendPromptListChanged=p,i.sendResourceListChanged=m,Promise.resolve(i.sendToolListChanged()).catch(()=>{}),Promise.resolve(i.sendPromptListChanged()).catch(()=>{}),Promise.resolve(i.sendResourceListChanged()).catch(()=>{});let w=i._registeredTools??{};for(let[e,t]of Object.entries(w)){if(Pa.has(e))continue;let n=t.handler;t.handler=async(...i)=>{if(!r.indexer.isIndexing)return n(...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 (${Fa/1e3}s).\n\nThe existing index may be temporarily locked. Please retry shortly — indexing will complete automatically.`}],...t.config?.outputSchema?{structuredContent:Wa(t.config.outputSchema)}:{}}),Fa));return Promise.race([n(...i),o])}}for(let[e,t]of Object.entries(w)){let n=t.handler,r=vm(e);t.handler=async(...i)=>{try{return await ym(()=>n(...i),r,e)}catch(n){if(n instanceof _m)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:Wa(t.config.outputSchema)}:{}};throw n}}}let T=Object.keys(w).length;T<La.length&&Q.warn(`ALL_TOOL_NAMES count mismatch`,{expectedToolCount:La.length,registeredToolCount:T}),Q.info(`MCP server configured`,{toolCount:La.length,resourceCount:4});let E=new mm;E.onPressure((e,t)=>{e===`warning`&&Cr(),e===`critical`&&(Q.warn(`Memory pressure critical — consider restarting`,{rssMB:Math.round(t/1024/1024)}),Cr())}),E.registerMemoryPressureCallback(()=>r.embedder.shutdown?.()),E.start();let O=new fm;l=O,O.onIdle(async()=>{if(D.isRunning||r.indexer.isIndexing){Q.info(`Idle cleanup deferred — background tasks still running`),O.touch();return}Q.info(`Idle cleanup: releasing cached memory (connections stay open)`);try{r.store.releaseMemory?.(),r.graphStore.releaseMemory?.()}catch{}}),O.touch();let k=!1;for(let e of Object.values(w)){let t=e.handler;e.handler=async(...e)=>{if(k||(k=!0,O.markSessionActive()),O.touch(),u){let t=d(e[0]);t.length>0&&u.prioritize(...t)}return t(...e)}}wm(w,r,{statePath:e.stateDir??``}),process.stdin.on(`end`,()=>(Q.info(`stdin closed — MCP client disconnected. Shutting down.`),process.exit(0))),process.stdin.on(`error`,()=>(Q.info(`stdin error — MCP client disconnected. Shutting down.`),process.exit(0))),c=r,v?.(r)})(),E=async()=>{let t;try{t=await x}catch{Q.warn(`Skipping initial index — AI Kit initialization failed`);return}l?.setBusy(!0);try{let n=e.sources.map(e=>e.path).join(`, `);Q.info(`Running initial index`,{sourcePaths:n});let r=await t.indexer.index(e,e=>{e.phase===`crawling`||e.phase===`done`||(e.phase===`chunking`&&e.currentFile&&Q.debug(`Indexing file`,{current:e.filesProcessed+1,total:e.filesTotal,file:e.currentFile}),e.phase===`cleanup`&&Q.debug(`Index cleanup`,{staleEntries:e.filesTotal-e.filesProcessed}))});s=!0,Q.info(`Initial index complete`,{filesProcessed:r.filesProcessed,filesSkipped:r.filesSkipped,chunksCreated:r.chunksCreated,durationMs:r.durationMs});try{await t.store.createFtsIndex()}catch(e){Q.warn(`FTS index creation failed`,I(e))}try{let e=await t.curated.reindexAll();Q.info(`Curated re-index complete`,{indexed:e.indexed})}catch(e){Q.error(`Curated re-index failed`,I(e))}}catch(e){Q.error(`Initial index failed; will retry on aikit_reindex`,I(e))}finally{l?.setBusy(!1)}},D=new um,O=()=>D.schedule({name:`initial-index`,fn:E}),k=process.ppid,A=setInterval(()=>{try{process.kill(k,0)}catch{Q.info(`Parent process died; shutting down`,{parentPid:k}),clearInterval(A),u?.stop&&u.stop(),import(`../../tools/dist/index.js`).then(({processStopAll:e})=>e()).catch(()=>{}),x.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 A.unref(),{server:i,startInit:w,ready:T,runInitialIndex:O,get aikit(){return c},scheduler:D,setSmartScheduler(e){u=e}}}const $=F(`server`);function km(e,t){let n=lo(t,[...La,...ja],H,Na(t)),r=cm(t,n,H),i=new Cn({name:t.serverName??`aikit`,version:b()},{capabilities:{logging:{},completions:{},prompts:{}},instructions:r});return yr(i),rm(i,e,t,_r(i),new om(i),kc(i),void 0,null,null,n),Ar(i,{curated:e.curated,store:e.store,graphStore:e.graphStore,stateStore:e.stateStore},t.indexMode),i}async function Am(e){let t=await sm(e),n=km(t,e);$.info(`MCP server configured`,{toolCount:La.length,resourceCount:2});let r=async()=>{try{let n=e.sources.map(e=>e.path).join(`, `);$.info(`Running initial index`,{sourcePaths:n});let r=await t.indexer.index(e,e=>{e.phase===`crawling`||e.phase===`done`||(e.phase===`chunking`&&e.currentFile&&$.debug(`Indexing file`,{current:e.filesProcessed+1,total:e.filesTotal,file:e.currentFile}),e.phase===`cleanup`&&$.debug(`Index cleanup`,{staleEntries:e.filesTotal-e.filesProcessed}))});$.info(`Initial index complete`,{filesProcessed:r.filesProcessed,filesSkipped:r.filesSkipped,chunksCreated:r.chunksCreated,durationMs:r.durationMs});try{await t.store.createFtsIndex()}catch(e){$.warn(`FTS index creation failed`,I(e))}try{let e=await t.curated.reindexAll();$.info(`Curated re-index complete`,{indexed:e.indexed})}catch(e){$.error(`Curated re-index failed`,I(e))}}catch(e){$.error(`Initial index failed; will retry on aikit_reindex`,I(e))}},i=async()=>{$.info(`Shutting down`),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{$.info(`Parent process died; shutting down`,{parentPid:a}),clearInterval(o),i()}},5e3);return o.unref(),{server:n,runInitialIndex:r,shutdown:i}}export{La as ALL_TOOL_NAMES,Om as createLazyServer,km as createMcpServer,Am as createServer,sm as initializeAikit,rm as registerMcpTools};
|