@vpxa/aikit 0.1.401 → 0.1.403

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.
@@ -2687,7 +2687,7 @@ None.`:`### Stale Lessons\n${l.map(e=>`- **${e.title}** (\`${e.path}\`) — effe
2687
2687
  }
2688
2688
  mermaid.initialize({ startOnLoad: false, theme: theme });
2689
2689
  mermaid.run();
2690
- };`,onload:`window.__aikit_initMermaid&&window.__aikit_initMermaid()`,local:{route:`/vendor/mermaid.min.js`,getSource:bm()}},Sm=new Map([[`mermaid`,xm]]);function Cm(e,t){if(!e?.length)return;let n=[];for(let r of e){let e=Sm.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 wm(){let e=[];for(let t of Sm.values())t.local&&e.push({route:t.local.route,getSource:t.local.getSource,cdn:t.cdn});return e}const Tm=300*1e3,Em=15*1e3,Dm=`/@aikit/blocks-interactive/dist/`;var Om=class{maxTokens;refillPerSecond;tokens;lastRefill;constructor(e,t){this.maxTokens=e,this.refillPerSecond=t,this.tokens=e,this.lastRefill=Date.now()}tryConsume(){return this.#e(),this.tokens>=1?(--this.tokens,!0):!1}#e(){let e=Date.now(),t=(e-this.lastRefill)/1e3;this.tokens=Math.min(this.maxTokens,this.tokens+t*this.refillPerSecond),this.lastRefill=e}};let km=null,Am=null;const Z=new Map,jm=new Om(10,10),Mm=new Om(50,50);function Nm(){return km||(km={manager:new vm,server:null,port:0},process.on(`exit`,()=>{Z.clear(),km?.manager.shutdown()})),km.manager}async function Pm(){if(!km)throw Error(`Browser server state not initialized`);let e=km;if(e.server)return e.port;if(Am)return Am;let t=Pr((e,t)=>{zm(e,t)});return e.server=t,Am=new Promise((n,r)=>{t.listen(0,`127.0.0.1`,()=>{let i=t.address();typeof i==`object`&&i?(e.port=i.port,n(i.port)):r(Error(`Failed to resolve local browser address`))}),t.on(`error`,r)}),Am}let Fm;function Im(){return Fm===void 0&&(Fm=r(`blocks-interactive`)),Fm}function Lm(e){if(!e.startsWith(Dm))return null;let t=Im();if(!t)return null;let n=I(F(t,`dist`,e.slice(32))),r=I(F(t,`dist`)),i=process.platform===`win32`?`\\`:`/`;return!n.startsWith(r+i)&&n!==r?null:n}function Rm(e){return`script-src 'nonce-${e}' 'strict-dynamic'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; connect-src 'self'; frame-ancestors 'self'; base-uri 'none'; object-src 'none'`}function zm(e,t){let n=km;if(!n){rh(t);return}try{let r=new URL(e.url??`/`,`http://${e.headers.host??`127.0.0.1`}`).pathname,i=e.method??`GET`;if(i===`OPTIONS`){t.writeHead(204,{"Access-Control-Allow-Origin":`*`,"Access-Control-Allow-Methods":`POST, GET, OPTIONS`,"Access-Control-Allow-Headers":`Content-Type`}),t.end();return}if(r.startsWith(`/__aikit_clipboard.png`)){if(i!==`POST`){Q(t,405,`METHOD_NOT_ALLOWED`,`Clipboard capture requires POST.`);return}sh(t,ih(e,n));return}if(r.startsWith(`/__aikit_screenshot.png`)){oh(t,ih(e,n));return}if(r.startsWith(`/__aikit_system_clipboard`)){if(i!==`POST`){Q(t,405,`METHOD_NOT_ALLOWED`,`System clipboard write requires POST.`);return}ch(e,t);return}let a=r.match(/^\/present\/([^/]+)(?:\/(.*))?$/);if(a){let r=a[1],o=a[2]??``,s=Z.get(r);if(!s){Q(t,404,X.SESSION_NOT_FOUND,`Session ${r} not found`);return}if(o===``||o===`/`){t.writeHead(200,{"Content-Type":`text/html; charset=utf-8`,"Content-Security-Policy":Rm(s.callbackSession.nonce)}),t.end(s.html);return}if(o===`viewer`){if(!s.viewerHtml){t.writeHead(404,{"Content-Type":`text/plain`}),t.end(`Not Found`);return}t.writeHead(200,{"Content-Type":`text/html; charset=utf-8`,"Content-Security-Policy":Rm(s.callbackSession.nonce)}),t.end(s.viewerHtml);return}if(o===`ready`){if(i!==`POST`){Q(t,405,`METHOD_NOT_ALLOWED`,`Ready requires POST.`);return}if(!jm.tryConsume()){Q(t,429,X.RATE_LIMITED,`Too many requests`);return}Bm(e,t,s,r,n).catch(()=>{rh(t)});return}if(o===`callback`){if(s.completed){Q(t,410,`SESSION_COMPLETED`,`Session already completed`);return}if(!s.ready){Q(t,403,`session_not_ready`,`Session not ready yet. POST /present/{id}/ready with the session nonce first.`);return}if(!jm.tryConsume()){Q(t,429,X.RATE_LIMITED,`Too many requests`);return}s.callbackSession.handle(e,t,`http://127.0.0.1:${n.port}`).catch(()=>{rh(t)});return}t.writeHead(404,{"Content-Type":`text/plain`}),t.end(`Not Found`);return}let o=wm().find(t=>e.url===t.route);if(o){let e=o.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:o.cdn}),t.end();return}if(r.startsWith(Dm)){if(!Mm.tryConsume()){Q(t,429,X.RATE_LIMITED,`Too many requests`);return}let e=Lm(r);if(e)try{let n=P(e,`utf8`);t.writeHead(200,{"Content-Type":`application/javascript; charset=utf-8`}),t.end(n);return}catch{}}t.writeHead(404,{"Content-Type":`text/plain`}),t.end(`Not Found`)}catch{rh(t)}}function Q(e,t,n,r){if(!e.headersSent)try{e.writeHead(t,{"Content-Type":`application/json; charset=utf-8`}),e.end(JSON.stringify({error:n,message:r}))}catch{try{e.end()}catch{}}}async function Bm(e,t,n,r,i){try{let a=[],o=0;for await(let n of e){let r=n;if(o+=r.length,o>4096){e.destroy(),Q(t,413,`PAYLOAD_TOO_LARGE`,`Request body too large`);return}a.push(r)}let s=Buffer.concat(a).toString(`utf8`),c;try{c=JSON.parse(s)}catch{Q(t,400,`INVALID_JSON`,`Request body must be valid JSON`);return}if(!cm(typeof c.nonce==`string`?c.nonce:``,n.callbackSession.nonce)){Q(t,403,X.INVALID_NONCE,`Nonce does not match`);return}n.ready=!0,i.manager.transitionSession(r,`connected`,`client-ready`),t.writeHead(200,{"Content-Type":`application/json`}),t.end(JSON.stringify({ok:!0}))}catch{rh(t)}}function Vm(e){let t=Y(e.id),n=Y(e.label);if(e.type===`select`||e.type===`multi-select`)return`<label class="present-action-field"><span>${n}</span><select data-action-id="${t}"${e.type===`multi-select`?` multiple`:``}>${(e.options??[]).map(e=>`<option value="${Y(e.value)}">${Y(e.label)}</option>`).join(``)}</select></label>`;if(e.type===`form-submit`){let r=e.schema;if(r)return`<form class="present-form" data-action-id="${t}" data-action-label="${n}">${Object.entries(r).map(([e,t])=>{let n=Y(t.description??e);return`<label class="present-action-field"><span>${n}</span><input type="${t.type===`number`?`number`:t.type===`boolean`?`checkbox`:`text`}" class="present-text-input" name="${Y(e)}" placeholder="${n}" /></label>`}).join(``)}<button type="submit" class="present-action-btn present-action-primary">${n}</button></form>`}return`<button type="button" class="present-action-btn present-action-${Y(e.variant??`default`)}" data-action-id="${t}" data-action-label="${n}">${n}</button>`}function Hm(e){return e.length===0?``:`<div class="bk-actions">${e.map(Vm).join(``)}</div>`}function Um(e,t){if(e.length===0)return``;let n=JSON.stringify(t);return`<style>
2690
+ };`,onload:`window.__aikit_initMermaid&&window.__aikit_initMermaid()`,local:{route:`/vendor/mermaid.min.js`,getSource:bm()}},Sm=new Map([[`mermaid`,xm]]);function Cm(e,t){if(!e?.length)return;let n=[];for(let r of e){let e=Sm.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 wm(){let e=[];for(let t of Sm.values())t.local&&e.push({route:t.local.route,getSource:t.local.getSource,cdn:t.cdn});return e}const Tm=300*1e3,Em=15*1e3,Dm=`/@aikit/blocks-interactive/dist/`;var Om=class{maxTokens;refillPerSecond;tokens;lastRefill;constructor(e,t){this.maxTokens=e,this.refillPerSecond=t,this.tokens=e,this.lastRefill=Date.now()}tryConsume(){return this.#e(),this.tokens>=1?(--this.tokens,!0):!1}#e(){let e=Date.now(),t=(e-this.lastRefill)/1e3;this.tokens=Math.min(this.maxTokens,this.tokens+t*this.refillPerSecond),this.lastRefill=e}};let km=null,Am=null;const Z=new Map,jm=new Om(10,10),Mm=new Om(50,50);function Nm(){return km||(km={manager:new vm,server:null,port:0},process.on(`exit`,()=>{Z.clear(),km?.manager.shutdown()})),km.manager}async function Pm(){if(!km)throw Error(`Browser server state not initialized`);let e=km;if(e.server)return e.port;if(Am)return Am;let t=Pr((e,t)=>{zm(e,t)});return e.server=t,Am=new Promise((n,r)=>{t.listen(0,`127.0.0.1`,()=>{let i=t.address();typeof i==`object`&&i?(e.port=i.port,n(i.port)):r(Error(`Failed to resolve local browser address`))}),t.on(`error`,r)}),Am}let Fm;function Im(){return Fm===void 0&&(Fm=r(`blocks-interactive`)),Fm}function Lm(e){if(!e.startsWith(Dm))return null;let t=Im();if(!t)return null;let n=I(F(t,`dist`,e.slice(32))),r=I(F(t,`dist`)),i=process.platform===`win32`?`\\`:`/`;return!n.startsWith(r+i)&&n!==r?null:n}function Rm(e){return`script-src 'nonce-${e}' 'strict-dynamic'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; connect-src 'self'; frame-ancestors 'self'; base-uri 'none'; object-src 'none'`}function zm(e,t){let n=km;if(!n){ih(t);return}try{let r=new URL(e.url??`/`,`http://${e.headers.host??`127.0.0.1`}`).pathname,i=e.method??`GET`;if(i===`OPTIONS`){t.writeHead(204,{"Access-Control-Allow-Origin":`*`,"Access-Control-Allow-Methods":`POST, GET, OPTIONS`,"Access-Control-Allow-Headers":`Content-Type`}),t.end();return}if(r.startsWith(`/__aikit_clipboard.png`)){if(i!==`POST`){Q(t,405,`METHOD_NOT_ALLOWED`,`Clipboard capture requires POST.`);return}ch(t,ah(e,n));return}if(r.startsWith(`/__aikit_screenshot.png`)){sh(t,ah(e,n));return}if(r.startsWith(`/__aikit_system_clipboard`)){if(i!==`POST`){Q(t,405,`METHOD_NOT_ALLOWED`,`System clipboard write requires POST.`);return}lh(e,t);return}let a=r.match(/^\/present\/([^/]+)(?:\/(.*))?$/);if(a){let r=a[1],o=a[2]??``,s=Z.get(r);if(!s){Q(t,404,X.SESSION_NOT_FOUND,`Session ${r} not found`);return}if(o===``||o===`/`){t.writeHead(200,{"Content-Type":`text/html; charset=utf-8`,"Content-Security-Policy":Rm(s.callbackSession.nonce)}),t.end(s.html);return}if(o===`viewer`){if(!s.viewerHtml){t.writeHead(404,{"Content-Type":`text/plain`}),t.end(`Not Found`);return}t.writeHead(200,{"Content-Type":`text/html; charset=utf-8`,"Content-Security-Policy":Rm(s.callbackSession.nonce)}),t.end(s.viewerHtml);return}if(o===`ready`){if(i!==`POST`){Q(t,405,`METHOD_NOT_ALLOWED`,`Ready requires POST.`);return}if(!jm.tryConsume()){Q(t,429,X.RATE_LIMITED,`Too many requests`);return}Bm(e,t,s,r,n).catch(()=>{ih(t)});return}if(o===`callback`){if(s.completed){Q(t,410,`SESSION_COMPLETED`,`Session already completed`);return}if(!s.ready){Q(t,403,`session_not_ready`,`Session not ready yet. POST /present/{id}/ready with the session nonce first.`);return}if(!jm.tryConsume()){Q(t,429,X.RATE_LIMITED,`Too many requests`);return}s.callbackSession.handle(e,t,`http://127.0.0.1:${n.port}`).catch(()=>{ih(t)});return}t.writeHead(404,{"Content-Type":`text/plain`}),t.end(`Not Found`);return}let o=wm().find(t=>e.url===t.route);if(o){let e=o.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:o.cdn}),t.end();return}if(r.startsWith(Dm)){if(!Mm.tryConsume()){Q(t,429,X.RATE_LIMITED,`Too many requests`);return}let e=Lm(r);if(e)try{let n=P(e,`utf8`);t.writeHead(200,{"Content-Type":`application/javascript; charset=utf-8`}),t.end(n);return}catch{}}t.writeHead(404,{"Content-Type":`text/plain`}),t.end(`Not Found`)}catch{ih(t)}}function Q(e,t,n,r){if(!e.headersSent)try{e.writeHead(t,{"Content-Type":`application/json; charset=utf-8`}),e.end(JSON.stringify({error:n,message:r}))}catch{try{e.end()}catch{}}}async function Bm(e,t,n,r,i){try{let a=[],o=0;for await(let n of e){let r=n;if(o+=r.length,o>4096){e.destroy(),Q(t,413,`PAYLOAD_TOO_LARGE`,`Request body too large`);return}a.push(r)}let s=Buffer.concat(a).toString(`utf8`),c;try{c=JSON.parse(s)}catch{Q(t,400,`INVALID_JSON`,`Request body must be valid JSON`);return}if(!cm(typeof c.nonce==`string`?c.nonce:``,n.callbackSession.nonce)){Q(t,403,X.INVALID_NONCE,`Nonce does not match`);return}n.ready=!0,i.manager.transitionSession(r,`connected`,`client-ready`),Zm({kind:`session_ready`,sessionId:r,detail:`client-nonce-ready`}),t.writeHead(200,{"Content-Type":`application/json`}),t.end(JSON.stringify({ok:!0}))}catch{Zm({kind:`session_ready_error`,sessionId:r,error:`internal error during ready handling`}),ih(t)}}function Vm(e){let t=Y(e.id),n=Y(e.label);if(e.type===`select`||e.type===`multi-select`)return`<label class="present-action-field"><span>${n}</span><select data-action-id="${t}"${e.type===`multi-select`?` multiple`:``}>${(e.options??[]).map(e=>`<option value="${Y(e.value)}">${Y(e.label)}</option>`).join(``)}</select></label>`;if(e.type===`form-submit`){let r=e.schema;if(r)return`<form class="present-form" data-action-id="${t}" data-action-label="${n}">${Object.entries(r).map(([e,t])=>{let n=Y(t.description??e);return`<label class="present-action-field"><span>${n}</span><input type="${t.type===`number`?`number`:t.type===`boolean`?`checkbox`:`text`}" class="present-text-input" name="${Y(e)}" placeholder="${n}" /></label>`}).join(``)}<button type="submit" class="present-action-btn present-action-primary">${n}</button></form>`}return`<button type="button" class="present-action-btn present-action-${Y(e.variant??`default`)}" data-action-id="${t}" data-action-label="${n}">${n}</button>`}function Hm(e){return e.length===0?``:`<div class="bk-actions">${e.map(Vm).join(``)}</div>`}function Um(e,t){if(e.length===0)return``;let n=JSON.stringify(t);return`<style>
2691
2691
  .present-surface-title { margin: 0 0 0.75rem; font-size: 1.875rem; }
2692
2692
  .present-surface-description { margin: 0; color: var(--muted-foreground, #6b7280); }
2693
2693
  .present-actions-list { display: flex; flex-wrap: wrap; gap: 0.75rem; align-items: flex-end; }
@@ -2920,27 +2920,27 @@ None.`:`### Stale Lessons\n${l.map(e=>`- **${e.title}** (\`${e.path}\`) — effe
2920
2920
  navigator.sendBeacon('/callback', new Blob([body], { type: 'application/json' }));
2921
2921
  });
2922
2922
  })();
2923
- <\/script>`}function Wm(e){try{if(process.platform===`win32`){let t=yr(`rundll32`,[`url.dll,FileProtocolHandler`,e],{detached:!0,stdio:`ignore`,windowsHide:!0});t.on(`error`,()=>{}),t.unref();return}if(process.platform===`darwin`){_r(`open`,[e]);return}_r(`xdg-open`,[e])}catch{}}function Gm(e){let t=e instanceof Error?e.message:String(e);return t.length>500?`${t.slice(0,497)}...`:t}function Km(e){let t=e.getLastExecDiagnostics;return typeof t==`function`?t.call(e):void 0}function qm(){return process.env.AIKIT_TMP_DIR||F(Kn(),`.aikit`,`tmp`)}function Jm(){return F(qm(),`present-browser-launch.jsonl`)}function Ym(e,t,n){return{traceId:Je(8).toString(`hex`),timestamp:new Date().toISOString(),url:e,platform:process.platform,agentBrowserArgsBefore:t,requiredAgentBrowserArgs:n,changedAgentBrowserArgs:!1,engineLaunch:{ok:!1,retried:!1},engineOpen:{ok:!1,retried:!1},viewport:{ok:!1}}}function Xm(e,t){if(!(process.env.VITEST||process.env.NODE_ENV===`test`))try{Oe(qm(),{recursive:!0}),Ee(Jm(),`${JSON.stringify({outcome:e.kind,pageId:e.kind===`opened_managed`?e.pageId:void 0,reason:e.kind===`failed`?e.reason:t.fallback?.reason,diagnostics:t})}\n`,`utf8`)}catch{}}function Zm(e,t){let n={...e,diagnostics:t};return Xm(n,t),n}function Qm(e){let t=e.diagnostics;return t?{presentBrowserLaunch:{outcome:e.kind,pageId:e.kind===`opened_managed`?e.pageId:void 0,reason:e.kind===`failed`?e.reason:t.fallback?.reason,logPath:Jm(),...t}}:{}}async function $m(e){let t=process.env.AGENT_BROWSER_ARGS??``,n=[`--start-maximized`,`--disable-infobars`,`--disable-popup-blocking`],r=Ym(e,t,n);try{let i=t?t.split(`,`):[],a=!1;for(let e of n)i.includes(e)||(i.push(e),a=!0);a&&(process.env.AGENT_BROWSER_ARGS=i.join(`,`)),r.changedAgentBrowserArgs=a,r.agentBrowserArgsAfter=process.env.AGENT_BROWSER_ARGS??``;let o=Jn();try{await o.launch(`ui`),r.engineLaunch.ok=!0,r.lastExecAfterLaunch=Km(o)}catch(e){r.engineLaunch.firstError=Gm(e),r.lastExecAfterLaunch=Km(o),r.engineLaunch.retried=!0,await o.close().catch(()=>{});try{await o.launch(`ui`),r.engineLaunch.ok=!0,r.lastExecAfterLaunch=Km(o)}catch(e){throw r.engineLaunch.retryError=Gm(e),r.lastExecAfterLaunch=Km(o),e}}o.resetIdleTimer();let s=`t0`;try{s=await o.open(e),r.engineOpen.ok=!0,r.engineOpen.pageId=s,r.lastExecAfterOpen=Km(o)}catch(t){r.engineOpen.firstError=Gm(t),r.lastExecAfterOpen=Km(o),r.engineOpen.retried=!0,await o.close().catch(()=>{}),await o.launch(`ui`),r.lastExecAfterLaunch=Km(o),o.resetIdleTimer();try{s=await o.open(e),r.engineOpen.ok=!0,r.engineOpen.pageId=s,r.lastExecAfterOpen=Km(o)}catch(e){throw r.engineOpen.retryError=Gm(e),r.lastExecAfterOpen=Km(o),e}}try{await o.exec(`set`,`viewport`,`1920`,`1080`),r.lastExecAfterViewport=Km(o),await o.exec(`eval`,`setTimeout(function(){window.focus()}, 300);`).catch(()=>{}),r.viewport.ok=!0}catch(e){r.viewport.error=Gm(e),r.lastExecAfterViewport=Km(o)}return Zm({kind:`opened_managed`,url:e,pageId:s},r)}catch(t){return r.fallback={used:!0,reason:Gm(t)},Wm(e),Zm({kind:`opened_system`,url:e},r)}}function eh(e,t,n,r){let i=[e.title];return e.description&&i.push(e.description),i.push(``),n.kind===`opened_managed`?i.push(`Opened in browser — ${t}`):n.kind===`opened_system`?i.push(`Opened in system browser — ${t}`):(i.push(`Failed to open browser: ${n.reason}`),i.push(`Manual URL: ${t}`)),i.push(r),i.join(`
2924
- `)}function th(e){return e.some(e=>e.id!==`__dismiss`)}function nh(e){return e.replace(`</head>`,`${og}\n</head>`).replace(`</body>`,`${sg}\n</body>`)}function rh(e){if(!e.headersSent)try{e.writeHead(500,{"Content-Type":`text/plain`}),e.end(`Internal Server Error`)}catch{try{e.end()}catch{}}}function ih(e,t){let n=e.headers.referer;return typeof n==`string`&&n.length>0?n:`http://127.0.0.1:${t.port}`}async function ah(e,t){let n=Jn();n.isLaunched()||await n.launch(`headless`);let{base64:r}=await n.screenshotActiveTab({fullPage:t?.fullPage!==!1,format:t?.format,quality:t?.quality,annotate:t?.annotate});return Buffer.from(r,`base64`)}async function oh(e,t){if(!t){e.writeHead(503,{"Content-Type":`text/plain; charset=utf-8`}),e.end(`Screenshot target is not ready.`);return}try{let n=await ah(t);e.writeHead(200,{"Content-Type":`image/png`,"Cache-Control":`no-store`}),e.end(n)}catch(t){let n=t instanceof Error?t.message:String(t);console.warn(`[present] Screenshot capture failed:`,n),rh(e)}}async function sh(e,t){if(!t){Q(e,503,`CLIPBOARD_CAPTURE_TARGET_MISSING`,`Clipboard target is not ready.`);return}try{let n=await ah(t);e.writeHead(200,{"Content-Type":`image/png`,"Cache-Control":`no-store`}),e.end(n)}catch(t){let n=t instanceof Error?t.message:String(t);console.warn(`[present] Clipboard capture failed:`,n),Q(e,500,`CLIPBOARD_CAPTURE_FAILED`,`Clipboard capture failed: ${n}`)}}async function ch(e,t){let n=[];e.on(`data`,e=>n.push(e)),e.on(`end`,async()=>{let e=Buffer.concat(n);if(e.length===0){Q(t,400,`EMPTY_BODY`,`No image data received.`);return}try{await lh(e),t.writeHead(200,{"Content-Type":`application/json`}),t.end(JSON.stringify({ok:!0}))}catch(e){let n=e instanceof Error?e.message:String(e);console.warn(`[present] System clipboard write failed:`,n),Q(t,500,`SYSTEM_CLIPBOARD_WRITE_FAILED`,`System clipboard write failed: ${n}`)}}),e.on(`error`,e=>{console.warn(`[present] System clipboard write request error:`,e.message),Q(t,500,`REQUEST_ERROR`,`Request stream error.`)})}async function lh(e){let t=F(qn(),`aikit-clipboard-${Date.now()}-${Je(4).toString(`hex`)}.png`);try{if(Pe(t,e),process.platform===`win32`){let e=[`Add-Type -AssemblyName System.Drawing;`,`Add-Type -AssemblyName System.Windows.Forms;`,`$path = '${t.replace(/'/g,`''`)}';`,`$img = [System.Drawing.Image]::FromFile($path);`,`$img2 = [System.Drawing.Bitmap]::FromImage($img);`,`$img.Dispose();`,`[System.Windows.Forms.Clipboard]::SetImage($img2);`,`Start-Sleep -Milliseconds 500;`,`$img2.Dispose();`].join(` `);await new Promise((t,n)=>{gr(`powershell.exe -NoProfile -STA -Command "${e.replace(/"/g,`\\"`)}"`,{timeout:15e3,windowsHide:!0},e=>{e?n(Error(`PowerShell clipboard write failed: ${e.message}`)):t()})})}else if(process.platform===`darwin`)await new Promise((e,n)=>{gr(`osascript -e 'set the clipboard to (read (POSIX file "${t}") as picture)'`,{timeout:15e3},t=>{t?n(Error(`macOS clipboard write failed: ${t.message}`)):e()})});else try{await new Promise((e,n)=>{gr(`wl-copy --type image/png < "${t}" 2>/dev/null`,{timeout:1e4},(t,r)=>{t?n(Error(`wl-copy failed: ${t.message}`)):e(r)})});return}catch{await new Promise((e,n)=>{gr(`xclip -selection clipboard -t image/png -i "${t}"`,{timeout:15e3},t=>{t?n(Error(`Linux clipboard write failed (tried wl-copy then xclip): ${t.message}. Install wl-clipboard (Wayland) or xclip (X11) for clipboard image support.`)):e()})})}}finally{try{Ne(t)}catch{}}}function uh(e,t){return e.replace(/'\/callback'/g,`'/present/${t}/callback'`).replace(/"\/callback"/g,`"/present/${t}/callback"`).replace(/'\/ready'/g,`'/present/${t}/ready'`).replace(/"\/ready"/g,`"/present/${t}/ready"`)}function dh(e,t){return e.replace(/src="\/viewer"/g,`src="/present/${t}/viewer"`)}async function fh(e,t,n){if(Rh(`<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=En({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(`
2925
- `);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 r=nh(Sp(t.resolveHtml(),e.data??null,t.injectId,t.transformData)),i=Nm(),a=Je(16).toString(`hex`),o=i.createSession({surfaceId:`viewer`,transport:`viewer`,nonce:a});if(!o.ok)return{content:[{type:`text`,text:`${e.title}\n\nUnable to start local browser transport.`}],structuredContent:{kind:`error`,error:{code:`BROWSER_START_FAILED`,message:o.error.message}},isError:!0};let s=o.session.id,c=hm(`viewer`,e.actions??[],i,s,a),l=dh(Tr({title:e.title,subtitle:e.description,html:[`<div class="present-viewer-container">`,` <iframe class="present-viewer-iframe" src="/viewer" sandbox="allow-scripts allow-same-origin"></iframe>`,` ${cg(a)}`,`</div>`].join(`
2923
+ <\/script>`}function Wm(e){try{if(process.platform===`win32`){let t=yr(`rundll32`,[`url.dll,FileProtocolHandler`,e],{detached:!0,stdio:`ignore`,windowsHide:!0});t.on(`error`,()=>{}),t.unref();return}if(process.platform===`darwin`){_r(`open`,[e]);return}_r(`xdg-open`,[e])}catch{}}function Gm(e){let t=e instanceof Error?e.message:String(e);return t.length>500?`${t.slice(0,497)}...`:t}function Km(e){let t=e.getLastExecDiagnostics;return typeof t==`function`?t.call(e):void 0}function qm(){return process.env.AIKIT_TMP_DIR||F(Kn(),`.aikit`,`tmp`)}function Jm(){return F(qm(),`present-browser-launch.jsonl`)}function Ym(e,t,n){return{traceId:Je(8).toString(`hex`),timestamp:new Date().toISOString(),url:e,platform:process.platform,agentBrowserArgsBefore:t,requiredAgentBrowserArgs:n,changedAgentBrowserArgs:!1,engineLaunch:{ok:!1,retried:!1},engineOpen:{ok:!1,retried:!1}}}function Xm(e,t){if(!(process.env.VITEST||process.env.NODE_ENV===`test`))try{Oe(qm(),{recursive:!0}),Ee(Jm(),`${JSON.stringify({event:`launch_outcome`,outcome:e.kind,pageId:e.kind===`opened_managed`?e.pageId:void 0,reason:e.kind===`failed`?e.reason:t.fallback?.reason,diagnostics:t})}\n`,`utf8`)}catch{}}function Zm(e){if(!(process.env.VITEST||process.env.NODE_ENV===`test`))try{Oe(qm(),{recursive:!0}),Ee(Jm(),`${JSON.stringify({event:`session`,kind:e.kind,sessionId:e.sessionId,surfaceId:e.surfaceId,detail:e.detail,timingMs:e.timingMs,error:e.error,timestamp:new Date().toISOString()})}\n`,`utf8`)}catch{}}function Qm(e,t){let n={...e,diagnostics:t};return Xm(n,t),n}function $m(e){let t=e.diagnostics;return t?{presentBrowserLaunch:{outcome:e.kind,pageId:e.kind===`opened_managed`?e.pageId:void 0,reason:e.kind===`failed`?e.reason:t.fallback?.reason,logPath:Jm(),...t}}:{}}async function eh(e){let t=process.env.AGENT_BROWSER_ARGS??``,n=[`--start-maximized`,`--disable-infobars`,`--disable-popup-blocking`],r=Ym(e,t,n);try{let i=t?t.split(`,`):[],a=!1;for(let e of n)i.includes(e)||(i.push(e),a=!0);a&&(process.env.AGENT_BROWSER_ARGS=i.join(`,`)),r.changedAgentBrowserArgs=a,r.agentBrowserArgsAfter=process.env.AGENT_BROWSER_ARGS??``;let o=Jn();try{await o.launch(`ui`),r.engineLaunch.ok=!0,r.lastExecAfterLaunch=Km(o)}catch(e){r.engineLaunch.firstError=Gm(e),r.lastExecAfterLaunch=Km(o),r.engineLaunch.retried=!0,console.warn(`[present] Engine launch failed, retrying once:`,r.engineLaunch.firstError),await o.close().catch(()=>{});try{await o.launch(`ui`),r.engineLaunch.ok=!0,r.lastExecAfterLaunch=Km(o),console.warn(`[present] Engine launch retry succeeded`)}catch(e){throw r.engineLaunch.retryError=Gm(e),r.lastExecAfterLaunch=Km(o),console.warn(`[present] Engine launch retry also failed:`,r.engineLaunch.retryError),e}}o.resetIdleTimer();let s=`t0`;try{s=await o.open(e),r.engineOpen.ok=!0,r.engineOpen.pageId=s,r.lastExecAfterOpen=Km(o)}catch(t){r.engineOpen.firstError=Gm(t),r.lastExecAfterOpen=Km(o),r.engineOpen.retried=!0,console.warn(`[present] Engine open failed, restarting engine and retrying:`,r.engineOpen.firstError),await o.close().catch(()=>{}),await o.launch(`ui`),r.lastExecAfterLaunch=Km(o),o.resetIdleTimer();try{s=await o.open(e),r.engineOpen.ok=!0,r.engineOpen.pageId=s,r.lastExecAfterOpen=Km(o),console.warn(`[present] Engine open retry succeeded`)}catch(e){throw r.engineOpen.retryError=Gm(e),r.lastExecAfterOpen=Km(o),console.warn(`[present] Engine open retry also failed:`,r.engineOpen.retryError),e}}try{o.exec(`eval`,`setTimeout(function(){window.focus()}, 300);`).catch(e=>{let t=e instanceof Error?e.message:String(e);console.warn(`[present] window.focus eval failed (non-critical):`,t)})}catch{}return Qm({kind:`opened_managed`,url:e,pageId:s},r)}catch(t){return r.fallback={used:!0,reason:Gm(t)},Wm(e),Qm({kind:`opened_system`,url:e},r)}}function th(e,t,n,r){let i=[e.title];return e.description&&i.push(e.description),i.push(``),n.kind===`opened_managed`?i.push(`Opened in browser — ${t}`):n.kind===`opened_system`?i.push(`Opened in system browser — ${t}`):(i.push(`Failed to open browser: ${n.reason}`),i.push(`Manual URL: ${t}`)),i.push(r),i.join(`
2924
+ `)}function nh(e){return e.some(e=>e.id!==`__dismiss`)}function rh(e){return e.replace(`</head>`,`${sg}\n</head>`).replace(`</body>`,`${cg}\n</body>`)}function ih(e){if(!e.headersSent)try{e.writeHead(500,{"Content-Type":`text/plain`}),e.end(`Internal Server Error`)}catch{try{e.end()}catch{}}}function ah(e,t){let n=e.headers.referer;return typeof n==`string`&&n.length>0?n:`http://127.0.0.1:${t.port}`}async function oh(e,t){let n=Jn();n.isLaunched()||await n.launch(`headless`);let{base64:r}=await n.screenshotActiveTab({fullPage:t?.fullPage!==!1,format:t?.format,quality:t?.quality,annotate:t?.annotate});return Buffer.from(r,`base64`)}async function sh(e,t){if(!t){e.writeHead(503,{"Content-Type":`text/plain; charset=utf-8`}),e.end(`Screenshot target is not ready.`);return}try{let n=await oh(t);e.writeHead(200,{"Content-Type":`image/png`,"Cache-Control":`no-store`}),e.end(n)}catch(t){let n=t instanceof Error?t.message:String(t);console.warn(`[present] Screenshot capture failed:`,n),ih(e)}}async function ch(e,t){if(!t){Q(e,503,`CLIPBOARD_CAPTURE_TARGET_MISSING`,`Clipboard target is not ready.`);return}try{let n=await oh(t);e.writeHead(200,{"Content-Type":`image/png`,"Cache-Control":`no-store`}),e.end(n)}catch(t){let n=t instanceof Error?t.message:String(t);console.warn(`[present] Clipboard capture failed:`,n),Q(e,500,`CLIPBOARD_CAPTURE_FAILED`,`Clipboard capture failed: ${n}`)}}async function lh(e,t){let n=[];e.on(`data`,e=>n.push(e)),e.on(`end`,async()=>{let e=Buffer.concat(n);if(e.length===0){Q(t,400,`EMPTY_BODY`,`No image data received.`);return}try{await uh(e),t.writeHead(200,{"Content-Type":`application/json`}),t.end(JSON.stringify({ok:!0}))}catch(e){let n=e instanceof Error?e.message:String(e);console.warn(`[present] System clipboard write failed:`,n),Q(t,500,`SYSTEM_CLIPBOARD_WRITE_FAILED`,`System clipboard write failed: ${n}`)}}),e.on(`error`,e=>{console.warn(`[present] System clipboard write request error:`,e.message),Q(t,500,`REQUEST_ERROR`,`Request stream error.`)})}async function uh(e){let t=F(qn(),`aikit-clipboard-${Date.now()}-${Je(4).toString(`hex`)}.png`);try{if(Pe(t,e),process.platform===`win32`){let e=[`Add-Type -AssemblyName System.Drawing;`,`Add-Type -AssemblyName System.Windows.Forms;`,`$path = '${t.replace(/'/g,`''`)}';`,`$img = [System.Drawing.Image]::FromFile($path);`,`$img2 = [System.Drawing.Bitmap]::FromImage($img);`,`$img.Dispose();`,`[System.Windows.Forms.Clipboard]::SetImage($img2);`,`Start-Sleep -Milliseconds 500;`,`$img2.Dispose();`].join(` `);await new Promise((t,n)=>{gr(`powershell.exe -NoProfile -STA -Command "${e.replace(/"/g,`\\"`)}"`,{timeout:15e3,windowsHide:!0},e=>{e?n(Error(`PowerShell clipboard write failed: ${e.message}`)):t()})})}else if(process.platform===`darwin`)await new Promise((e,n)=>{gr(`osascript -e 'set the clipboard to (read (POSIX file "${t}") as picture)'`,{timeout:15e3},t=>{t?n(Error(`macOS clipboard write failed: ${t.message}`)):e()})});else try{await new Promise((e,n)=>{gr(`wl-copy --type image/png < "${t}" 2>/dev/null`,{timeout:1e4},(t,r)=>{t?n(Error(`wl-copy failed: ${t.message}`)):e(r)})});return}catch{await new Promise((e,n)=>{gr(`xclip -selection clipboard -t image/png -i "${t}"`,{timeout:15e3},t=>{t?n(Error(`Linux clipboard write failed (tried wl-copy then xclip): ${t.message}. Install wl-clipboard (Wayland) or xclip (X11) for clipboard image support.`)):e()})})}}finally{try{Ne(t)}catch{}}}function dh(e,t){return e.replace(/'\/callback'/g,`'/present/${t}/callback'`).replace(/"\/callback"/g,`"/present/${t}/callback"`).replace(/'\/ready'/g,`'/present/${t}/ready'`).replace(/"\/ready"/g,`"/present/${t}/ready"`)}function fh(e,t){return e.replace(/src="\/viewer"/g,`src="/present/${t}/viewer"`)}async function ph(e,t,n){if(zh(`<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=En({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(`
2925
+ `);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 r=rh(Sp(t.resolveHtml(),e.data??null,t.injectId,t.transformData)),i=Nm(),a=Je(16).toString(`hex`),o=i.createSession({surfaceId:`viewer`,transport:`viewer`,nonce:a});if(!o.ok)return{content:[{type:`text`,text:`${e.title}\n\nUnable to start local browser transport.`}],structuredContent:{kind:`error`,error:{code:`BROWSER_START_FAILED`,message:o.error.message}},isError:!0};let s=o.session.id,c=hm(`viewer`,e.actions??[],i,s,a),l=fh(Tr({title:e.title,subtitle:e.description,html:[`<div class="present-viewer-container">`,` <iframe class="present-viewer-iframe" src="/viewer" sandbox="allow-scripts allow-same-origin"></iframe>`,` ${lg(a)}`,`</div>`].join(`
2926
2926
  `),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(`
2927
- `)],islands:[],payload:void 0,nonce:a,generatedAt:new Date().toISOString(),colorScheme:e.colorScheme,lang:e.lang,dir:e.dir,transport:`browser`,exportPolicy:`local-interactive`,imageExportMode:`browser-server`,footerContentHtml:gm}),s);Z.set(s,{callbackSession:c,html:l,viewerHtml:r,ready:!1,completed:!1,createdAt:Date.now()});let u=``;try{u=`http://127.0.0.1:${await Pm()}/present/${s}`}catch(t){return Z.delete(s),i.removeSession(s),{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}}let d=await $m(u),f=Z.get(s);f&&(f.launchOutcome=d);let p=n?.responseTimeoutMs??Tm;return setTimeout(()=>{Z.delete(s),i.removeSession(s)},p),{content:[{type:`text`,text:eh(e,u,d,`Rendered.`)}],structuredContent:{kind:`rendered`,reason:`no-response-required`},_meta:Qm(d)}}async function ph(e,t){Rh(`<html><body style="font-family:system-ui;padding:2rem;color:#888;text-align:center"><p>Content opened in browser window.</p></body></html>`);let n=Nm(),r=Je(16).toString(`hex`),i=Nr(e,{transport:`browser`,registry:Jp,blockVendorScripts:pp(),nonce:r}),a=n.createSession({surfaceId:i.surfaceId,transport:`browser`,nonce:r});if(!a.ok)return{content:[{type:`text`,text:`${e.title}\n\nUnable to start local browser transport.`}],structuredContent:{kind:`error`,error:{code:`BROWSER_START_FAILED`,message:a.error.message}},isError:!0};let o=a.session.id,s=hm(i.surfaceId,i.actions,n,o,r),c=Cm(i.vendorScripts,`browser`);wm();let l=i.actions.length>0?Hm(i.actions):``,u=i.actions.length>0?Um(i.actions,s.nonce):``,d=Tr({title:e.title,subtitle:e.description,html:[i.html,l,u].filter(Boolean).join(`
2928
- `),css:i.css,islands:i.islands,payload:i.payload,nonce:i.nonce,generatedAt:new Date().toISOString(),colorScheme:e.colorScheme,lang:e.lang,dir:e.dir,transport:`browser`,exportPolicy:i.exportPolicy,imageExportMode:`browser-server`,footerContentHtml:gm,headScripts:c}),f=uh(i.actions.length>0?mg(d,i.nonce):d,o);Z.set(o,{callbackSession:s,html:f,ready:!1,completed:!1,createdAt:Date.now()});let p=``;try{p=`http://127.0.0.1:${await Pm()}/present/${o}`}catch(t){return Z.delete(o),n.removeSession(o),n.shutdown(),{content:[{type:`text`,text:`${e.title}\n\nUnable to start local browser transport.`}],structuredContent:s.settleError(`BROWSER_START_FAILED`,t instanceof Error?t.message:`Unable to start browser transport`),isError:!0}}let m=await $m(p),h=Z.get(o);h&&(h.launchOutcome=m);let g=th(i.actions),_=t?.responseTimeoutMs??Tm,v=t?.responseTimeoutMs?Math.min(t.responseTimeoutMs,Em):Em;if(!g)return t?.responseRequired?(setTimeout(()=>{Z.delete(o);try{n.removeSession(o)}catch{}},v),{content:[{type:`text`,text:eh(e,p,m,`Response required but no interactive actions available.`)}],structuredContent:s.settleError(`NO_INTERACTIVE_ACTIONS`,`The surface has response.required=true but no interactive actions to respond to.`),_meta:Qm(m),isError:!0}):(setTimeout(()=>{Z.delete(o);try{n.removeSession(o)}catch{}},_),{content:[{type:`text`,text:eh(e,p,m,`Rendered.`)}],structuredContent:{kind:`rendered`,reason:`no-response-required`},_meta:Qm(m)});let y=await Promise.race([s.promise,new Promise(e=>{setTimeout(()=>{let t=Z.get(o);if(t?.ready||t?.completed)return;Z.delete(o);let n=m.kind===`opened_managed`?`No browser client ready within ${v}ms.`:m.kind===`opened_system`?`Fell back to system browser, but no browser client ready within ${v}ms.`:`Browser open failed: ${m.reason}. No client ready within ${v}ms.`;e(s.settleError(`BROWSER_CONNECT_TIMEOUT`,n))},v)}),new Promise(e=>{setTimeout(()=>e(s.settleTimeout(_)),_)})]),b=Z.get(o);b&&(b.completed=!0),setTimeout(()=>{Z.delete(o);try{n.removeSession(o)}catch{}},_);let x=y.kind===`result`?`Selected action: ${y.result.actionId}`:y.kind===`timeout`?`Timed out after ${y.waitedMs}ms.`:y.kind===`cancelled`?`Cancelled: ${y.reason}.`:y.kind===`error`?`Error: ${y.error.message}`:`Rendered.`;return{content:[{type:`text`,text:eh(e,p,m,x)}],structuredContent:y,_meta:Qm(m),isError:y.kind===`error`}}const mh={id:`browser`,priority:20,canHandle(e,t){let n=rg(e);return Xp(n)||!!t.preferBrowser&&!!ig(n)},async render(e,t){return ph(e,t.session)}},hh=`openai/outputTemplate`,gh=`ui/resourceUri`,_h={connectDomains:[],resourceDomains:[]},vh={connect_domains:[],resource_domains:[]};function yh(e){return{ui:{resourceUri:e,visibility:[`model`,`app`]},[gh]:e,[hh]:e,"openai/widgetAccessible":!0}}function bh(){return{ui:{prefersBorder:!1,csp:_h},"openai/widgetDescription":`AI Kit renders structured visual surfaces such as dashboards, charts, reports, and diagrams.`,"openai/widgetPrefersBorder":!1,"openai/widgetCSP":vh}}function xh(e){return{ui:{resourceUri:e},[gh]:e,[hh]:e}}function Sh(e){return{...e,schemaVersion:1}}function Ch(e){try{let t=Nr(e,{transport:`mcp-app`,registry:Jp,blockVendorScripts:pp()}),n=Cm(t.vendorScripts,`mcp-app`),r=Tr({title:e.title,subtitle:e.description,html:t.html,css:t.css,islands:t.islands,payload:t.payload,nonce:t.nonce,colorScheme:e.colorScheme,lang:e.lang,dir:e.dir,transport:`mcp-app`,exportPolicy:t.exportPolicy,imageExportMode:`disabled`,showToolbox:t.exportPolicy!==`static-only`,showInstallGuide:!1,footerContentHtml:gm,headScripts:n}),i={kind:`rendered`,reason:`no-response-required`},a=ug(r);Rh(a);let o=ag(e,i,{includeSurfaceHeader:!1}),s=Ih(),c=Vh(s);return c&&zh(c,a),{content:[{type:`text`,text:o}],structuredContent:Sh(e),_meta:xh(s),ui:{type:`resource`,uri:s}}}catch(t){return gg(`RENDER_FAILED`,t instanceof Error?t.message:`Failed to render ChannelSurface`,void 0,e.title)}}const wh={id:`mcp-app`,priority:30,canHandle(e,t){return!0},async render(e,t){return Ch(e)}};var Th=class{handlers=[];register(e){let t=this.handlers.findIndex(t=>t.id===e.id);t===-1?this.handlers.push(e):this.handlers[t]=e}unregister(e){let t=this.handlers.findIndex(t=>t.id===e);t!==-1&&this.handlers.splice(t,1)}select(e,t){return[...this.handlers].sort((e,t)=>(e.priority??99)-(t.priority??99)).find(n=>n.canHandle(e,t))??null}getAll(){return[...this.handlers]}};function Eh(e){return`<script nonce="${Y(e)}">
2927
+ `)],islands:[],payload:void 0,nonce:a,generatedAt:new Date().toISOString(),colorScheme:e.colorScheme,lang:e.lang,dir:e.dir,transport:`browser`,exportPolicy:`local-interactive`,imageExportMode:`browser-server`,footerContentHtml:gm}),s);Z.set(s,{callbackSession:c,html:l,viewerHtml:r,ready:!1,completed:!1,createdAt:Date.now()}),Zm({kind:`session_created`,sessionId:s,surfaceId:`viewer`,detail:e.title?.slice(0,80)});let u=``;try{u=`http://127.0.0.1:${await Pm()}/present/${s}`}catch(t){return Z.delete(s),i.removeSession(s),Zm({kind:`server_start_failed`,sessionId:s,error:t instanceof Error?t.message:`server start error`}),{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}}let d=await eh(u),f=Z.get(s);f&&(f.launchOutcome=d),Zm({kind:d.kind===`opened_managed`?`browser_opened_managed`:`browser_opened_system`,sessionId:s,detail:d.kind===`opened_managed`?`pageId=${d.pageId}`:d.kind===`opened_system`?`system_fallback`:`failed: ${d.reason}`});let p=n?.responseTimeoutMs??Tm;return setTimeout(()=>{Z.delete(s),Zm({kind:`session_cleaned_up`,sessionId:s,detail:`viewer_timeout`,timingMs:p}),i.removeSession(s)},p),{content:[{type:`text`,text:th(e,u,d,`Rendered.`)}],structuredContent:{kind:`rendered`,reason:`no-response-required`},_meta:$m(d)}}async function mh(e,t){zh(`<html><body style="font-family:system-ui;padding:2rem;color:#888;text-align:center"><p>Content opened in browser window.</p></body></html>`);let n=Nm(),r=Je(16).toString(`hex`),i=Nr(e,{transport:`browser`,registry:Jp,blockVendorScripts:pp(),nonce:r}),a=n.createSession({surfaceId:i.surfaceId,transport:`browser`,nonce:r});if(!a.ok)return{content:[{type:`text`,text:`${e.title}\n\nUnable to start local browser transport.`}],structuredContent:{kind:`error`,error:{code:`BROWSER_START_FAILED`,message:a.error.message}},isError:!0};let o=a.session.id,s=hm(i.surfaceId,i.actions,n,o,r),c=Cm(i.vendorScripts,`browser`);wm();let l=i.actions.length>0?Hm(i.actions):``,u=i.actions.length>0?Um(i.actions,s.nonce):``,d=Tr({title:e.title,subtitle:e.description,html:[i.html,l,u].filter(Boolean).join(`
2928
+ `),css:i.css,islands:i.islands,payload:i.payload,nonce:i.nonce,generatedAt:new Date().toISOString(),colorScheme:e.colorScheme,lang:e.lang,dir:e.dir,transport:`browser`,exportPolicy:i.exportPolicy,imageExportMode:`browser-server`,footerContentHtml:gm,headScripts:c}),f=dh(i.actions.length>0?hg(d,i.nonce):d,o);Z.set(o,{callbackSession:s,html:f,ready:!1,completed:!1,createdAt:Date.now()}),Zm({kind:`session_created`,sessionId:o,surfaceId:i.surfaceId,detail:e.title?.slice(0,80)});let p=``;try{p=`http://127.0.0.1:${await Pm()}/present/${o}`}catch(t){return Z.delete(o),n.removeSession(o),n.shutdown(),Zm({kind:`server_start_failed`,sessionId:o,error:t instanceof Error?t.message:`server start error`}),{content:[{type:`text`,text:`${e.title}\n\nUnable to start local browser transport.`}],structuredContent:s.settleError(`BROWSER_START_FAILED`,t instanceof Error?t.message:`Unable to start browser transport`),isError:!0}}let m=await eh(p),h=Z.get(o);h&&(h.launchOutcome=m),Zm({kind:m.kind===`opened_managed`?`browser_opened_managed`:`browser_opened_system`,sessionId:o,detail:m.kind===`opened_managed`?`pageId=${m.pageId}`:m.kind===`opened_system`?`system_fallback`:`failed: ${m.reason}`});let g=nh(i.actions),_=t?.responseTimeoutMs??Tm,v=t?.responseTimeoutMs?Math.min(t.responseTimeoutMs,Em):Em;if(!g)return t?.responseRequired?(setTimeout(()=>{Z.delete(o),Zm({kind:`session_cleaned_up`,sessionId:o,detail:`no_interactive_actions_required`});try{n.removeSession(o)}catch{}},v),{content:[{type:`text`,text:th(e,p,m,`Response required but no interactive actions available.`)}],structuredContent:s.settleError(`NO_INTERACTIVE_ACTIONS`,`The surface has response.required=true but no interactive actions to respond to.`),_meta:$m(m),isError:!0}):(setTimeout(()=>{Z.delete(o),Zm({kind:`session_cleaned_up`,sessionId:o,detail:`display_only`,timingMs:_});try{n.removeSession(o)}catch{}},_),{content:[{type:`text`,text:th(e,p,m,`Rendered.`)}],structuredContent:{kind:`rendered`,reason:`no-response-required`},_meta:$m(m)});let y=await Promise.race([s.promise,new Promise(e=>{setTimeout(()=>{let t=Z.get(o);if(t?.ready||t?.completed)return;Z.delete(o);let n=m.kind===`opened_managed`?`No browser client ready within ${v}ms.`:m.kind===`opened_system`?`Fell back to system browser, but no browser client ready within ${v}ms.`:`Browser open failed: ${m.reason}. No client ready within ${v}ms.`;e(s.settleError(`BROWSER_CONNECT_TIMEOUT`,n))},v)}),new Promise(e=>{setTimeout(()=>e(s.settleTimeout(_)),_)})]),b=Z.get(o);b&&(b.completed=!0),Zm({kind:y.kind===`result`?`session_callback_received`:`session_${y.kind}`,sessionId:o,detail:y.kind===`result`?`action=${y.result.actionId}`:y.kind===`timeout`?`waited=${y.waitedMs}ms`:y.kind===`cancelled`?y.reason:y.kind===`error`?y.error.message:void 0}),setTimeout(()=>{Z.delete(o),Zm({kind:`session_cleaned_up`,sessionId:o,detail:`interactive_complete`,timingMs:_});try{n.removeSession(o)}catch{}},_);let x=y.kind===`result`?`Selected action: ${y.result.actionId}`:y.kind===`timeout`?`Timed out after ${y.waitedMs}ms.`:y.kind===`cancelled`?`Cancelled: ${y.reason}.`:y.kind===`error`?`Error: ${y.error.message}`:`Rendered.`;return{content:[{type:`text`,text:th(e,p,m,x)}],structuredContent:y,_meta:$m(m),isError:y.kind===`error`}}const hh={id:`browser`,priority:20,canHandle(e,t){let n=ig(e);return Xp(n)||!!t.preferBrowser&&!!ag(n)},async render(e,t){return mh(e,t.session)}},gh=`openai/outputTemplate`,_h=`ui/resourceUri`,vh={connectDomains:[],resourceDomains:[]},yh={connect_domains:[],resource_domains:[]};function bh(e){return{ui:{resourceUri:e,visibility:[`model`,`app`]},[_h]:e,[gh]:e,"openai/widgetAccessible":!0}}function xh(){return{ui:{prefersBorder:!1,csp:vh},"openai/widgetDescription":`AI Kit renders structured visual surfaces such as dashboards, charts, reports, and diagrams.`,"openai/widgetPrefersBorder":!1,"openai/widgetCSP":yh}}function Sh(e){return{ui:{resourceUri:e},[_h]:e,[gh]:e}}function Ch(e){return{...e,schemaVersion:1}}function wh(e){try{let t=Nr(e,{transport:`mcp-app`,registry:Jp,blockVendorScripts:pp()}),n=Cm(t.vendorScripts,`mcp-app`),r=Tr({title:e.title,subtitle:e.description,html:t.html,css:t.css,islands:t.islands,payload:t.payload,nonce:t.nonce,colorScheme:e.colorScheme,lang:e.lang,dir:e.dir,transport:`mcp-app`,exportPolicy:t.exportPolicy,imageExportMode:`disabled`,showToolbox:t.exportPolicy!==`static-only`,showInstallGuide:!1,footerContentHtml:gm,headScripts:n}),i={kind:`rendered`,reason:`no-response-required`},a=dg(r);zh(a);let o=og(e,i,{includeSurfaceHeader:!1}),s=Lh(),c=Hh(s);return c&&Bh(c,a),{content:[{type:`text`,text:o}],structuredContent:Ch(e),_meta:Sh(s),ui:{type:`resource`,uri:s}}}catch(t){return _g(`RENDER_FAILED`,t instanceof Error?t.message:`Failed to render ChannelSurface`,void 0,e.title)}}const Th={id:`mcp-app`,priority:30,canHandle(e,t){return!0},async render(e,t){return wh(e)}};var Eh=class{handlers=[];register(e){let t=this.handlers.findIndex(t=>t.id===e.id);t===-1?this.handlers.push(e):this.handlers[t]=e}unregister(e){let t=this.handlers.findIndex(t=>t.id===e);t!==-1&&this.handlers.splice(t,1)}select(e,t){return[...this.handlers].sort((e,t)=>(e.priority??99)-(t.priority??99)).find(n=>n.canHandle(e,t))??null}getAll(){return[...this.handlers]}};function Dh(e){return`<script nonce="${Y(e)}">
2929
2929
  window.addEventListener('message', function(e) {
2930
2930
  if (e.data && e.data.type === 'aikit-viewer-height') {
2931
2931
  var container = document.querySelector('.present-viewer-container');
2932
2932
  if (container) { container.style.minHeight = e.data.height + 'px'; }
2933
2933
  }
2934
2934
  });
2935
- <\/script>`}async function Dh(e,t){try{let n=lg(Sp(t.resolveHtml(),e.data??null,t.injectId,t.transformData)).replace(/&/g,`&amp;`).replace(/"/g,`&quot;`),r=Je(16).toString(`hex`),i={kind:`rendered`,reason:`no-response-required`};Rh(ug(Tr({title:e.title,subtitle:e.description,html:[`<div class="present-viewer-container">`,` <iframe class="present-viewer-iframe" srcdoc="${n}" sandbox="allow-scripts allow-same-origin"></iframe>`,` ${cg(r)}`,` ${Eh(r)}`,`</div>`].join(`
2935
+ <\/script>`}async function Oh(e,t){try{let n=ug(Sp(t.resolveHtml(),e.data??null,t.injectId,t.transformData)).replace(/&/g,`&amp;`).replace(/"/g,`&quot;`),r=Je(16).toString(`hex`),i={kind:`rendered`,reason:`no-response-required`};zh(dg(Tr({title:e.title,subtitle:e.description,html:[`<div class="present-viewer-container">`,` <iframe class="present-viewer-iframe" srcdoc="${n}" sandbox="allow-scripts allow-same-origin"></iframe>`,` ${lg(r)}`,` ${Dh(r)}`,`</div>`].join(`
2936
2936
  `),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(`
2937
- `)],islands:[],payload:void 0,nonce:r,generatedAt:new Date().toISOString(),footerContentHtml:gm,colorScheme:e.colorScheme,lang:e.lang,dir:e.dir,transport:`mcp-app`,exportPolicy:`local-interactive`,imageExportMode:`disabled`})));let a=ag(e,i,{includeSurfaceHeader:!1}),o=Ih();return{content:[{type:`text`,text:a}],structuredContent:Sh(e),_meta:xh(o),ui:{type:`resource`,uri:o}}}catch(t){return gg(`VIEWER_RENDER_FAILED`,t instanceof Error?t.message:`Failed to render viewer template`,void 0,e.title)}}const Oh={id:`viewer`,priority:10,canHandle(e,t){return e.template?yp(e.template)!=null:!1},async render(e,t){let n=yp(e.template??``);if(!n)return gg(`VIEWER_NOT_FOUND`,`Viewer template "${e.template}" not found`,void 0,e.title);if(e.data!=null&&n.inputSchema){let t=En({data:e.data,schema:n.inputSchema});if(!t.valid){let r=t.errors.map(e=>` ${e.path}: ${e.message}${e.expected?` (expected: ${e.expected}, got: ${e.received})`:``}`).join(`
2938
- `);return gg(`VIEWER_DATA_INVALID`,`Template "${n.id}" data validation failed:\n${r}\n\nExpected schema: ${JSON.stringify(n.inputSchema,null,2)}`,void 0,e.title)}}let r=n.supportedTransports.includes(`browser`),i=n.supportedTransports.includes(`mcp-app`);return t.preferBrowser||r&&!i?await fh(e,n,t.session):i?Dh(e,n):gg(`VIEWER_TRANSPORT_UNSUPPORTED`,`Viewer template "${n.id}" does not support an available transport`,void 0,e.title)}},kh=`ui://aikit/present.html`,Ah=`ui://aikit/present/{id}.html`,jh=A(`present`);let Mh=0,Nh=``;const Ph=new Map,Fh=new Map;function Ih(){return`ui://aikit/present/${`${Date.now().toString(36)}_${(++Mh).toString(36)}`}.html`}function Lh(){return Nh}function Rh(e){Nh=e}function zh(e,t){let n=Fh.get(e);n&&clearTimeout(n),Ph.set(e,t),Fh.set(e,setTimeout(()=>{Ph.delete(e),Fh.delete(e)},3e4))}function Bh(e){return Ph.get(e)}function Vh(e){return e.match(/\/present\/(.+)\.html$/)?.[1]}const Hh=new Th;Hh.register(Oh),Hh.register(mh),Hh.register(wh);function Uh(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const Wh=/\\u[0-9a-fA-F]{4}/,Gh=/^\s*\|(?:[^|\r\n]+\|){2,}\s*$/,Kh=/^\s*\|?(?:\s*:?-{3,}:?\s*\|){2,}\s*$/,qh=/\b(cli|terminal|tty|console|command(?:-|\s)?line)\b/i;function Jh(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 Yh(e){let t=e.split(/\r?\n/);for(let e=0;e<t.length-1;e+=1)if(Gh.test(t[e])&&Kh.test(t[e+1]))return!0;return!1}function Xh(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 Zh(e,t){if(t<2)return!1;let n=e.trim();return n.startsWith(`|`)?Xh(n).length===t:!1}function Qh(e){let t=e.split(/\r?\n/),n=[],r=[],i=()=>{r.length!==0&&(n.push({type:`text`,content:r.join(`
2939
- `)}),r.length=0)},a=0;for(;a<t.length;){let e=t[a],o=t[a+1];if(o!==void 0&&Gh.test(e)&&Kh.test(o)){let r=Xh(e),o=[];i();let s=a+2;for(;s<t.length&&Zh(t[s],r.length);)o.push(Xh(t[s])),s+=1;n.push({type:`table`,headers:r,rows:o}),a=s;continue}r.push(e),a+=1}return i(),n}function $h(e){let t=Jh(e);return!t||!Yh(t)?[e]:Qh(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 eg(e){if(typeof e==`string`)return qh.test(e);if(Array.isArray(e))return e.some(e=>eg(e));if(!Uh(e))return!1;let t=[`client`,`clientInfo`,`host`,`source`,`mode`,`name`,`title`,`channel`];return Object.entries(e).some(([e,n])=>t.includes(e)?eg(n):!1)}function tg(e,t){return{preferBrowser:[t,e._meta,Uh(e.metadata)?e.metadata.source:void 0].some(e=>eg(e))}}const ng={id:`__dismiss`,type:`button`,label:`Done`,variant:`default`};function rg(e){if((e.actions?.length??0)>0||!e.template)return e;let t=Yp(e);return t?.supportedTransports.includes(`browser`)===!0&&!t.supportedTransports.includes(`mcp-app`)?{...e,actions:[ng]}:e}function ig(e){if(!e.template)return!0;let t=yp(e.template);return t?t.supportedTransports.includes(`browser`):Yp(e)?.supportedTransports.includes(`browser`)??!1}function ag(e,t,n={}){let r=n.includeSurfaceHeader??!0,i=r?[e.title]:[];return r&&e.description&&i.push(e.description),Ar(t)?i.push(``,`Selected action: ${t.result.actionId}`):kr(t)?i.push(``,`Error: ${t.error.message}`):t.kind===`timeout`?i.push(``,`Timed out after ${t.waitedMs}ms.`):t.kind===`cancelled`?i.push(``,`Cancelled: ${t.reason}.`):r||i.push(`Rendered inline.`),i.join(`
2940
- `)}const og=`<style>
2937
+ `)],islands:[],payload:void 0,nonce:r,generatedAt:new Date().toISOString(),footerContentHtml:gm,colorScheme:e.colorScheme,lang:e.lang,dir:e.dir,transport:`mcp-app`,exportPolicy:`local-interactive`,imageExportMode:`disabled`})));let a=og(e,i,{includeSurfaceHeader:!1}),o=Lh();return{content:[{type:`text`,text:a}],structuredContent:Ch(e),_meta:Sh(o),ui:{type:`resource`,uri:o}}}catch(t){return _g(`VIEWER_RENDER_FAILED`,t instanceof Error?t.message:`Failed to render viewer template`,void 0,e.title)}}const kh={id:`viewer`,priority:10,canHandle(e,t){return e.template?yp(e.template)!=null:!1},async render(e,t){let n=yp(e.template??``);if(!n)return _g(`VIEWER_NOT_FOUND`,`Viewer template "${e.template}" not found`,void 0,e.title);if(e.data!=null&&n.inputSchema){let t=En({data:e.data,schema:n.inputSchema});if(!t.valid){let r=t.errors.map(e=>` ${e.path}: ${e.message}${e.expected?` (expected: ${e.expected}, got: ${e.received})`:``}`).join(`
2938
+ `);return _g(`VIEWER_DATA_INVALID`,`Template "${n.id}" data validation failed:\n${r}\n\nExpected schema: ${JSON.stringify(n.inputSchema,null,2)}`,void 0,e.title)}}let r=n.supportedTransports.includes(`browser`),i=n.supportedTransports.includes(`mcp-app`);return t.preferBrowser||r&&!i?await ph(e,n,t.session):i?Oh(e,n):_g(`VIEWER_TRANSPORT_UNSUPPORTED`,`Viewer template "${n.id}" does not support an available transport`,void 0,e.title)}},Ah=`ui://aikit/present.html`,jh=`ui://aikit/present/{id}.html`,Mh=A(`present`);let Nh=0,Ph=``;const Fh=new Map,Ih=new Map;function Lh(){return`ui://aikit/present/${`${Date.now().toString(36)}_${(++Nh).toString(36)}`}.html`}function Rh(){return Ph}function zh(e){Ph=e}function Bh(e,t){let n=Ih.get(e);n&&clearTimeout(n),Fh.set(e,t),Ih.set(e,setTimeout(()=>{Fh.delete(e),Ih.delete(e)},3e4))}function Vh(e){return Fh.get(e)}function Hh(e){return e.match(/\/present\/(.+)\.html$/)?.[1]}const Uh=new Eh;Uh.register(kh),Uh.register(hh),Uh.register(Th);function Wh(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const Gh=/\\u[0-9a-fA-F]{4}/,Kh=/^\s*\|(?:[^|\r\n]+\|){2,}\s*$/,qh=/^\s*\|?(?:\s*:?-{3,}:?\s*\|){2,}\s*$/,Jh=/\b(cli|terminal|tty|console|command(?:-|\s)?line)\b/i;function Yh(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 Xh(e){let t=e.split(/\r?\n/);for(let e=0;e<t.length-1;e+=1)if(Kh.test(t[e])&&qh.test(t[e+1]))return!0;return!1}function Zh(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 Qh(e,t){if(t<2)return!1;let n=e.trim();return n.startsWith(`|`)?Zh(n).length===t:!1}function $h(e){let t=e.split(/\r?\n/),n=[],r=[],i=()=>{r.length!==0&&(n.push({type:`text`,content:r.join(`
2939
+ `)}),r.length=0)},a=0;for(;a<t.length;){let e=t[a],o=t[a+1];if(o!==void 0&&Kh.test(e)&&qh.test(o)){let r=Zh(e),o=[];i();let s=a+2;for(;s<t.length&&Qh(t[s],r.length);)o.push(Zh(t[s])),s+=1;n.push({type:`table`,headers:r,rows:o}),a=s;continue}r.push(e),a+=1}return i(),n}function eg(e){let t=Yh(e);return!t||!Xh(t)?[e]:$h(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 tg(e){if(typeof e==`string`)return Jh.test(e);if(Array.isArray(e))return e.some(e=>tg(e));if(!Wh(e))return!1;let t=[`client`,`clientInfo`,`host`,`source`,`mode`,`name`,`title`,`channel`];return Object.entries(e).some(([e,n])=>t.includes(e)?tg(n):!1)}function ng(e,t){return{preferBrowser:[t,e._meta,Wh(e.metadata)?e.metadata.source:void 0].some(e=>tg(e))}}const rg={id:`__dismiss`,type:`button`,label:`Done`,variant:`default`};function ig(e){if((e.actions?.length??0)>0||!e.template)return e;let t=Yp(e);return t?.supportedTransports.includes(`browser`)===!0&&!t.supportedTransports.includes(`mcp-app`)?{...e,actions:[rg]}:e}function ag(e){if(!e.template)return!0;let t=yp(e.template);return t?t.supportedTransports.includes(`browser`):Yp(e)?.supportedTransports.includes(`browser`)??!1}function og(e,t,n={}){let r=n.includeSurfaceHeader??!0,i=r?[e.title]:[];return r&&e.description&&i.push(e.description),Ar(t)?i.push(``,`Selected action: ${t.result.actionId}`):kr(t)?i.push(``,`Error: ${t.error.message}`):t.kind===`timeout`?i.push(``,`Timed out after ${t.waitedMs}ms.`):t.kind===`cancelled`?i.push(``,`Cancelled: ${t.reason}.`):r||i.push(`Rendered inline.`),i.join(`
2940
+ `)}const sg=`<style>
2941
2941
  .toolbar, .badge, .aikit-header, .aikit-footer { display: none !important; }
2942
2942
  body { padding-top: 0 !important; margin-top: 0 !important; }
2943
- </style>`,sg=`<script>
2943
+ </style>`,cg=`<script>
2944
2944
  window.addEventListener('message', function(e) {
2945
2945
  // Accept from any origin — theme change is cosmetic-only.
2946
2946
  // Strict origin check breaks in MCP host custom protocols (ui://, vscode-webview://)
@@ -2952,7 +2952,7 @@ window.addEventListener('message', function(e) {
2952
2952
  }
2953
2953
  }
2954
2954
  });
2955
- <\/script>`;function cg(e){return`<script nonce="${e}">
2955
+ <\/script>`;function lg(e){return`<script nonce="${e}">
2956
2956
  (function() {
2957
2957
  var iframe = document.querySelector('.present-viewer-iframe');
2958
2958
  if (!iframe) return;
@@ -2971,7 +2971,7 @@ window.addEventListener('message', function(e) {
2971
2971
  iframe.addEventListener('load', sendTheme);
2972
2972
  trySend();
2973
2973
  })();
2974
- <\/script>`}function lg(e){let t=e.replace(`</head>`,`${og}\n</head>`);t===e&&jh.warn(`injectEmbeddedViewerRuntime: </head> not found — viewer style not injected`);let n=t.replace(`</body>`,`<script>
2974
+ <\/script>`}function ug(e){let t=e.replace(`</head>`,`${sg}\n</head>`);t===e&&Mh.warn(`injectEmbeddedViewerRuntime: </head> not found — viewer style not injected`);let n=t.replace(`</body>`,`<script>
2975
2975
  (function() {
2976
2976
  function report() {
2977
2977
  var h = document.documentElement.scrollHeight;
@@ -2981,7 +2981,7 @@ window.addEventListener('message', function(e) {
2981
2981
  ro.observe(document.documentElement);
2982
2982
  report();
2983
2983
  })();
2984
- <\/script>\n${sg}\n</body>`);return n===t&&jh.warn(`injectEmbeddedViewerRuntime: </body> not found — runtime scripts not injected`),n}function ug(e){let t=`<script>
2984
+ <\/script>\n${cg}\n</body>`);return n===t&&Mh.warn(`injectEmbeddedViewerRuntime: </body> not found — runtime scripts not injected`),n}function dg(e){let t=`<script>
2985
2985
  (function(){
2986
2986
  var last=0;
2987
2987
  function notify(){
@@ -2992,7 +2992,7 @@ window.addEventListener('message', function(e) {
2992
2992
  if(typeof ResizeObserver!=="undefined"){new ResizeObserver(notify).observe(document.documentElement)}
2993
2993
  else{setInterval(notify,500)}
2994
2994
  })();
2995
- <\/script>`;return e.includes(`</body>`)?e.replace(`</body>`,`${t}</body>`):`${e}${t}`}let dg=``;function fg(e){return`<script${e?` nonce="${Y(e)}"`:``}>
2995
+ <\/script>`;return e.includes(`</body>`)?e.replace(`</body>`,`${t}</body>`):`${e}${t}`}let fg=``;function pg(e){return`<script${e?` nonce="${Y(e)}"`:``}>
2996
2996
  (function(){
2997
2997
  var readyState = document.readyState;
2998
2998
  var boot = function() {
@@ -3005,14 +3005,14 @@ window.addEventListener('message', function(e) {
3005
3005
  boot();
3006
3006
  }
3007
3007
  })();
3008
- <\/script>`}function pg(e){dg=e||``}function mg(e,t){if(!dg)return e;let n=`${`<script${t?` nonce="${Y(t)}"`:``}>${dg}<\/script>`}\n${fg(t||``)}`;return e.includes(`</body>`)?e.replace(`</body>`,`${n}\n</body>`):`${e}${n}`}function hg(e,t){return[`<!DOCTYPE html>`,`<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">`,`<title>Error — ${Y(e)}</title>`,`<style>`,` * { box-sizing: border-box; margin: 0; padding: 0; }`,` body { font-family: system-ui, -apple-system, sans-serif; min-height: 100vh; display: flex; align-items: center; justify-content: center; padding: 2rem; background: #fafafa; color: #333; }`,` .error-card { max-width: 560px; width: 100%; padding: 2.5rem; border-radius: 1rem; background: #fff; border: 1px solid #e5e7eb; box-shadow: 0 1px 3px rgba(0,0,0,0.06); }`,` .error-badge { display: inline-block; font-size: 0.75rem; font-weight: 600; text-transform: uppercase; letter-spacing: 0.05em; color: #dc2626; background: #fef2f2; border: 1px solid #fecaca; border-radius: 0.375rem; padding: 0.25rem 0.625rem; margin-bottom: 1rem; }`,` .error-title { font-size: 1.25rem; font-weight: 600; margin-bottom: 0.75rem; color: #111; }`,` .error-message { font-size: 0.875rem; line-height: 1.6; color: #6b7280; white-space: pre-wrap; word-break: break-word; }`,`</style></head><body>`,`<div class="error-card">`,` <span class="error-badge">Render Error</span>`,` <h1 class="error-title">${Y(e)}</h1>`,` <p class="error-message">${Y(t)}</p>`,`</div>`,`</body></html>`].join(`
3009
- `)}function gg(e,t,n,r){return Rh(hg(r??`Present`,t)),{content:[{type:`text`,text:`[ERROR:VALIDATION] ${t}`}],isError:!0}}function _g(e,t){if(!Uh(e)||!(`schemaVersion`in e))return{ok:!1,response:gg(`INVALID_CHANNEL_SURFACE`,`present expects a ChannelSurface object with schemaVersion: 1`)};if(e.schemaVersion!==1)return{ok:!1,response:gg(`UNSUPPORTED_SCHEMA_VERSION`,`Unsupported ChannelSurface schemaVersion: ${String(e.schemaVersion)}`)};if(typeof e.title==`string`&&Wh.test(e.title))return{ok:!1,response:gg(`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(!Uh(e)||e.type!==`markdown`)return[e];let t=Jh(e);return!t||!Yh(t)?[e]:$h(e)})}:e;return{ok:!0,surface:n,options:tg(n,t)}}function vg(e){return(e.actions?.length??0)>0||e.response?.required===!0?Hh.getAll().some(e=>e.id===`browser`):!1}async function yg(e,t={}){let n=vg(e)?{...t,preferBrowser:!0}:t,r=rg(e),i=Hh.select(r,n),a;if(a=i?await i.render(r,n):Ch(r),e.blocks&&e.blocks.length>0&&a.isError!==!0)try{let t=new Set;for(let n of e.blocks){if(typeof n!=`object`||!n)continue;let e=typeof n.type==`string`?n.type:null;e&&!mp(e)&&t.add(e)}if(t.size>0){let e=[...t].map(e=>`"${e}"`).join(`, `);jh.warn(`Unknown block types: ${e}`),a.content=[{type:`text`,text:`[Block type(s) not recognized: ${e}. They rendered as raw text. Use aikit://schemas/channel-surface for supported block types.]`},...a.content]}}catch(e){jh.warn(`Block type validation failed`,M(e))}if(t.compact){let{structuredContent:e,...t}=a;return t}return a}function bg(e,t=``){return typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`?String(e):t}function xg(e){return{type:`kv`,value:e}}function Sg(e){if(Array.isArray(e))return e}const Cg=[{name:`summary`,description:`Title + markdown summary + optional metrics (pass/fail counts)`,expand(e){let t=bg(e.title,`Summary`),n=[{type:`heading`,value:t}],r=bg(e.summary);r&&n.push({type:`markdown`,value:r});let i=Number(e.passed)||0,a=Number(e.failed)||0;if(i>0||a>0){let e=[];i>0&&e.push({label:`Passed`,value:i,status:`success`}),a>0&&e.push({label:`Failed`,value:a,status:`error`}),n.push({type:`metrics`,value:e})}return{title:t,blocks:n}}},{name:`plan`,description:`Title + heading per step + checklist items`,expand(e){let t=bg(e.title,`Plan`),n=[{type:`heading`,value:t}],r=Sg(e.steps);return r&&n.push({type:`checklist`,value:{items:r}}),{title:t,blocks:n}}},{name:`understanding`,description:`Title + markdown explanation + kv pairs`,expand(e){let t=bg(e.title,`Understanding`),n=[{type:`heading`,value:t}],r=bg(e.explanation);return r&&n.push({type:`markdown`,value:r}),e.details&&typeof e.details==`object`&&!Array.isArray(e.details)&&n.push(xg(e.details)),{title:t,blocks:n}}},{name:`bug-analyze`,description:`Title + heading + severity/status kv + code block + markdown`,expand(e){let t=bg(e.title,`Bug Analysis`),n=[{type:`heading`,value:t}],r={};e.severity&&(r.Severity=e.severity),e.status&&(r.Status=e.status),Object.keys(r).length>0&&n.push({type:`kv`,value:r});let i=bg(e.code);i&&n.push({type:`code`,value:i});let a=bg(e.analysis);return a&&n.push({type:`markdown`,value:a}),{title:t,blocks:n}}},{name:`task-done`,description:`Title + checklist of completed items + optional metrics`,expand(e){let t=bg(e.title,`Task Complete`),n=[{type:`heading`,value:t}],r=Sg(e.items);r&&n.push({type:`checklist`,value:{items:r}});let i=e.completed,a=e.total;if(i!==void 0||a!==void 0){let e=[];i!==void 0&&e.push({label:`Completed`,value:Number(i)||i,status:`success`}),a!==void 0&&e.push({label:`Total`,value:Number(a)||a}),n.push({type:`metrics`,value:e})}return{title:t,blocks:n}}},{name:`review`,description:`Title + criteria checklist + annotation items + approval controls`,expand(e){let t=bg(e.title,`Review`),n=[{type:`heading`,value:t}],r=Sg(e.criteria);r&&n.push({type:`checklist`,value:{items:r}});let i=e.annotations;Array.isArray(i)&&i.length>0&&n.push({type:`annotation`,value:i});let a=e.approval;return a&&typeof a==`object`?n.push({type:`approval`,value:a}):n.push({type:`actions`,value:[{type:`button`,id:`approve`,label:`Approve`,variant:`primary`},{type:`button`,id:`reject`,label:`Reject`,variant:`danger`}]}),{title:t,blocks:n}}},{name:`explore`,description:`Title + heading per finding + code blocks`,expand(e){let t=bg(e.title,`Exploration`),n=[{type:`heading`,value:t}],r=Sg(e.findings);if(r)for(let e of r)n.push({type:`heading`,value:bg(e.heading,`Finding`)}),e.code&&n.push({type:`code`,value:e.code});return{title:t,blocks:n}}},{name:`decision`,description:`Title + kv for recommendation + comparison blocks per option`,expand(e){let t=bg(e.title,`Decision`),n=[{type:`heading`,value:t}];e.recommendation&&n.push({type:`kv`,value:{Recommendation:e.recommendation}});let r=Sg(e.options);return r&&r.length>0&&n.push({type:`comparison`,value:r.map(e=>({title:bg(e.title,`Option`),items:Array.isArray(e.items)?e.items:[]}))}),{title:t,blocks:n}}}],wg=new Map;for(let e of Cg)wg.set(e.name,e);function Tg(e,t){let n=wg.get(e);return n?n.expand(t):null}function Eg(e){let t=[],n=!1,r=!1;for(let i of e){if(r){r=!1,t.push(i);continue}if(i===`\\`&&n){r=!0,t.push(i);continue}if(i===`"`){n=!n,t.push(i);continue}if(n&&(i===`
3010
- `||i===`\r`)){t.push(`\\n`);continue}t.push(i)}return t.join(``)}function Dg(e){let t=[],n=!1,r=!1;for(let i of e){if(r){r=!1,t.push(i);continue}if(i===`\\`&&n){r=!0,t.push(i);continue}if(i===`"`){n=!n,t.push(i);continue}if(n){t.push(i);continue}if(i===`]`||i===`}`)for(let e=t.length-1;e>=0;e--){let n=t[e];if(!(n===` `||n===`
3011
- `||n===` `||n===`\r`||n===``)){n===`,`&&(t[e]=``);break}}t.push(i)}return t.join(``)}function Og(e){try{return JSON.parse(e)}catch{}let t=Dg(Eg(e));try{return JSON.parse(t)}catch(e){try{return JSON.parse(t.replaceAll(`'`,`"`))}catch{throw e}}}const kg={h:`heading`,m:`markdown`,t:`table`,p:`paragraph`,c:`code`,s:`separator`,M:`metrics`,C:`chart`,T:`timeline`,g:`graph`,tr:`tree`,tl:`timeline`,cl:`checklist`,pr:`progress`,sb:`status-board`,kv:`kv`,ac:`actions`,di:`mermaid`},Ag=/^(#{1,6})\s/,jg=/^(`{3,}|~{3,})/,Mg=/^\|.+\|.+\|/m;function Ng(e){let t=e.trim(),n=t.match(Ag);if(n)return{type:`heading`,value:t.slice(n[0].length)};if(jg.test(t)){let e=t.indexOf(`
3012
- `),n=t.lastIndexOf(t[0]);return{type:`code`,value:e>=0?t.slice(e+1,n).trimEnd():t}}return Mg.test(t)?{type:`table`,value:t}:{type:`markdown`,value:t}}function Pg(e,t){let n=kg[e];if(!n)return null;switch(e){case`M`:return{type:`metrics`,value:t};case`C`:return{type:`chart`,value:t};case`T`:case`tl`:return{type:`timeline`,value:t};case`g`:return{type:`graph`,value:t};case`tr`:return{type:`tree`,value:t};case`cl`:return{type:`checklist`,value:t};case`pr`:return{type:`progress`,value:t};case`sb`:return{type:`status-board`,value:t};case`kv`:return{type:`kv`,value:t};case`ac`:return{type:`actions`,value:t};case`di`:return{type:`mermaid`,value:t};case`s`:return{type:`separator`,value:t||!0};default:return{type:n,value:typeof t==`string`?t:String(t??``)}}}function Fg(e){if(typeof e==`string`){let t=Ng(e);return{type:t.type,value:t.value}}if(Array.isArray(e)){let[t,n]=e;if(typeof t==`string`){let e=Pg(t,n);if(e)return e}return{type:`markdown`,value:String(t??``)}}if(typeof e==`object`&&e){let{blockId:t,...n}=e;return n}return{type:`markdown`,value:String(e??``)}}function Ig(e){return{title:e.title??``,blocks:Array.isArray(e.blocks)?e.blocks.map(Fg):[]}}function Lg(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Rg(e){return Lg(e)&&typeof e.schemaVersion==`number`&&e.schemaVersion===1}function zg(e){return Lg(e)&&typeof e.schemaVersion==`number`&&e.schemaVersion!==1}function Bg(e){return e.schemaVersion===1?typeof e.title!=`string`||e.title.length===0?{ok:!1,error:{code:`MISSING_TITLE`,reason:`ChannelSurface requires a non-empty title`}}:e.blocks!==void 0&&!Array.isArray(e.blocks)?{ok:!1,error:{code:`INVALID_BLOCKS`,reason:`blocks must be an array of TypedBlock objects`}}:{ok:!0,surface:e}:{ok:!1,error:{code:`UNSUPPORTED_SCHEMA_VERSION`,reason:`Unsupported schemaVersion: ${String(e.schemaVersion)}`}}}function Vg(e){try{let t=Og(e);return Lg(t)?(t.schemaVersion===void 0&&(t.schemaVersion=1),Hg(t)):{ok:!1,error:{code:`INVALID_RAW_INPUT`,reason:`raw field must contain a JSON object (ChannelSurface)`}}}catch(e){return{ok:!1,error:{code:`INVALID_RAW_JSON`,reason:`Failed to parse raw field: ${e.message}`,hint:`JSON repair attempted. Ensure the raw string contains a valid ChannelSurface object. Common LLM errors (newlines in strings, trailing commas) are auto-repaired.`}}}}function Hg(e){if(Array.isArray(e)){if(e.length!==2)return{ok:!1,error:{code:`INVALID_PRESET_INPUT`,reason:`Preset input must be a [name, data] tuple`,hint:`Use [presetName, { title, ...fields }]`}};let[t,n]=e;if(typeof t!=`string`)return{ok:!1,error:{code:`INVALID_PRESET_INPUT`,reason:`Preset name must be a string`}};if(!Lg(n))return{ok:!1,error:{code:`INVALID_PRESET_INPUT`,reason:`Preset data must be an object`}};let r=Tg(t,n);return r?{ok:!0,surface:{schemaVersion:1,title:r.title,blocks:r.blocks}}:{ok:!1,error:{code:`UNKNOWN_PRESET`,reason:`Unknown preset: ${t}`,hint:`Available presets: summary, plan, understanding, bug-analyze, task-done, review, explore, decision`}}}if(zg(e))return{ok:!1,error:{code:`UNSUPPORTED_SCHEMA_VERSION`,reason:`Unsupported schemaVersion: ${String(e.schemaVersion)}`,hint:`Use schemaVersion: 1`}};if(Lg(e)&&typeof e.raw==`string`)return Vg(e.raw);if(Rg(e))return Bg(e);if(typeof e==`string`){let t=Ig({blocks:[e]});return{ok:!0,surface:{schemaVersion:1,title:t.title||`Present`,blocks:t.blocks}}}if(Lg(e)){if(!(`blocks`in e)&&!(`title`in e))return{ok:!1,error:{code:`INVALID_INPUT`,reason:`Expected a ChannelSurface object, preset tuple, or shorthand input`}};let t=Ig(e);return{ok:!0,surface:{schemaVersion:1,title:t.title||`Present`,blocks:t.blocks}}}return{ok:!1,error:{code:`INVALID_INPUT`,reason:`Expected a ChannelSurface object, preset tuple, or shorthand input`}}}const Ug=L.object({label:L.string(),value:L.string(),description:L.string().optional()}),Wg=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(Ug).optional(),schema:L.record(L.string(),L.unknown()).optional()}),Gg=L.object({type:L.string(),title:L.string().optional(),value:L.unknown().optional(),language:L.string().optional()}).catchall(L.unknown()),Kg={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(Gg).optional().describe(`Typed block content for the surface.`),data:L.unknown().optional().describe(`Template data payload, if the template expands data.`),actions:L.array(Wg).optional().describe(`Interactive actions. Presence triggers browser transport.`),response:L.object({timeout:L.number().finite().min(0).max(3e5).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(),raw:L.string().optional().describe(`Raw JSON string with auto-repair. Accepts common LLM JSON errors (unescaped newlines in strings, trailing commas). Use for complex payloads with mermaid/code/markdown blocks.`),preferBrowser:L.boolean().optional().default(!0).describe(`Prefer browser transport instead of inline rendering. Default: true — most clients render in an external browser window. Set preferBrowser: false to request inline/embedded rendering (only honored when the client supports inline display; auto-falls back to browser if not).`)};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 qg(e){let t=e.server?.getClientCapabilities?.();if(!t)return`unknown`;let n=fr(t);return!n||Array.isArray(n.mimeTypes)&&n.mimeTypes.length>0&&!n.mimeTypes.includes(dr)?`unsupported`:`supported`}const Jg=[{name:`summary`,description:`Title + markdown summary + optional metrics (pass/fail counts)`,inputSchema:{type:`object`,properties:{title:{type:`string`,description:`Section heading`},summary:{type:`string`,description:`Free-form markdown summary`},passed:{type:`number`,description:`Pass count for metrics`},failed:{type:`number`,description:`Fail count for metrics`}},required:[`title`]},example:JSON.stringify({title:`Build Summary`,summary:`All tests passed.`,passed:42,failed:0}),expandsTo:`blocks: [heading, markdown, metrics]`},{name:`plan`,description:`Title + heading per step + checklist items`,inputSchema:{type:`object`,properties:{title:{type:`string`},steps:{type:`array`,items:{type:`object`,properties:{label:{type:`string`},checked:{type:`boolean`}}}}},required:[`title`]},example:JSON.stringify({title:`Sprint Plan`,steps:[{label:`Write tests`,checked:!1},{label:`Deploy`,checked:!1}]}),expandsTo:`blocks: [heading, checklist]`},{name:`understanding`,description:`Title + markdown explanation + kv pairs`,inputSchema:{type:`object`,properties:{title:{type:`string`},explanation:{type:`string`},details:{type:`object`,additionalProperties:{type:`string`}}},required:[`title`,`explanation`]},example:JSON.stringify({title:`Architecture Overview`,explanation:`The system uses microservices.`,details:{Language:`TypeScript`,Runtime:`Node`}}),expandsTo:`blocks: [heading, markdown, kv]`},{name:`bug-analyze`,description:`Title + heading + severity/status kv + code block + markdown`,inputSchema:{type:`object`,properties:{title:{type:`string`},severity:{type:`string`},status:{type:`string`},code:{type:`string`},analysis:{type:`string`}},required:[`title`,`severity`,`status`]},example:JSON.stringify({title:`Null pointer in auth`,severity:`high`,status:`open`,code:`const x = obj.prop;`,analysis:`obj may be null when token missing.`}),expandsTo:`blocks: [heading, kv, code, markdown]`},{name:`task-done`,description:`Title + checklist of completed items + optional metrics`,inputSchema:{type:`object`,properties:{title:{type:`string`},items:{type:`array`,items:{type:`object`,properties:{label:{type:`string`},checked:{type:`boolean`}}}},completed:{type:`number`},total:{type:`number`}},required:[`title`,`items`]},example:JSON.stringify({title:`PR #42 Done`,items:[{label:`Lint pass`,checked:!0},{label:`Tests pass`,checked:!0}],completed:2,total:2}),expandsTo:`blocks: [heading, checklist, metrics]`},{name:`review`,description:`Title + criteria checklist + approval actions`,inputSchema:{type:`object`,properties:{title:{type:`string`,description:`Review title`},criteria:{type:`array`,description:`Checklist criteria items`,items:{type:`object`,properties:{label:{type:`string`},checked:{type:`boolean`}}}},annotations:{type:`array`,description:`Optional annotation items`,items:{type:`object`,properties:{label:{type:`string`},description:{type:`string`},severity:{type:`string`}}}},approval:{type:`object`,description:`Optional approval config`,properties:{prompt:{type:`string`},options:{type:`array`,items:{type:`object`,properties:{label:{type:`string`},value:{type:`string`}}}}}}},required:[`title`,`criteria`]},example:JSON.stringify({title:`Code Review`,criteria:[{label:`Tests included`,checked:!0},{label:`No regressions`,checked:!1}]}),expandsTo:`blocks: [heading, checklist] + actions: [approve, reject]`},{name:`explore`,description:`Title + heading per finding + code blocks`,inputSchema:{type:`object`,properties:{title:{type:`string`},findings:{type:`array`,items:{type:`object`,properties:{heading:{type:`string`},code:{type:`string`}}}}},required:[`title`,`findings`]},example:JSON.stringify({title:`Codebase Exploration`,findings:[{heading:`Auth flow`,code:`function login()`},{heading:`API routes`,code:`router.get("/api")`}]}),expandsTo:`blocks: [heading, code] per finding`},{name:`decision`,description:`Title + kv for recommendation + comparison blocks per option`,inputSchema:{type:`object`,properties:{title:{type:`string`},recommendation:{type:`string`},options:{type:`array`,items:{type:`object`,properties:{title:{type:`string`},items:{type:`array`,items:{type:`string`}}}}}},required:[`title`,`recommendation`]},example:JSON.stringify({title:`DB Choice`,recommendation:`PostgreSQL`,options:[{title:`Postgres`,items:[`ACID`,`Rich types`]},{title:`Mongo`,items:[`Schema-less`,`Horizontal`]}]}),expandsTo:`blocks: [heading, kv, comparison]`}];function Yg(e,t){let n=U(`present`);try{let e=r(`present`);e&&pg(P(I(e,`dist`,`annotation-layer.js`),`utf8`))}catch{}mr(e,`present`,{title:n.title,description:"Render a ChannelSurface. Required: schemaVersion: 1, title. Supports blocks, template+data, named presets, and raw JSON string with auto-repair. Use `raw` for complex payloads (mermaid, code, many blocks) — common LLM JSON errors are auto-fixed. IMPORTANT: when using `raw`, do NOT pass `schemaVersion` or `title` at the top level — the `raw` JSON must be a self-contained ChannelSurface with its own `schemaVersion: 1`, `title`, and `blocks`. preferBrowser defaults to true (browser rendering). Set preferBrowser: false explicitly when you want inline — only honored if the client supports it; auto-falls back to browser otherwise. Actions always use browser transport. Resources: aikit://schemas/channel-surface (schema+blocks), aikit://present/presets (presets), aikit://present/templates (viewers).",inputSchema:Kg,annotations:n.annotations,_meta:yh(Ah)},J(`present`,async(t,n)=>{let r=t,i=typeof r.preferBrowser==`boolean`?r.preferBrowser:void 0,a=Hg(t);if(!a.ok)return gg(a.error.code,a.error.reason,void 0,`Present`);let o=_g(a.surface,n);if(!o.ok)return o.response;let s=qg(e),c=!(i===!1&&s===`supported`),l={responseTimeoutMs:o.surface.response?.timeout,responseRequired:o.surface.response?.required,transportReason:c?`caller-preferred`:`inline-unsupported`};return await yg(o.surface,{...o.options,preferBrowser:c,session:l})}));try{let t=new Xn(Ah,{list:void 0});e.registerResource(`Present View`,t,{description:`AI Kit present tool viewer`},async(e,t,n)=>{let r=Array.isArray(t.id)?t.id[0]:t.id,i=r?Bh(r):void 0;return{contents:[{uri:e.href,mimeType:dr,_meta:bh(),text:i??Lh()??`<html><body><p>No content generated yet. Call the present tool first.</p></body></html>`}]}})}catch{}function i(){try{let e=r(`present`);if(e)return P(I(e,`dist`,`index.html`),`utf8`)}catch{}return Lh()||`<html><body><p>Loading...</p></body></html>`}try{e.registerResource(`Present App`,kh,{description:`AI Kit present app - entry point`},async()=>({contents:[{uri:kh,mimeType:dr,_meta:bh(),text:i()}]}))}catch{}try{e.registerResource(`present-templates`,`aikit://present/templates`,{description:`List all registered present viewer templates with their input schemas`},async()=>{let e=xp().map(e=>({id:e.id,label:e.label,description:e.description,transports:e.supportedTransports,inputSchema:e.inputSchema}));return{contents:[{uri:`aikit://present/templates`,mimeType:`application/json`,text:JSON.stringify(e,null,2)}]}})}catch{}try{e.registerResource(`present-presets`,`aikit://present/presets`,{description:`List all registered present presets with input schemas and examples`},async()=>({contents:[{uri:`aikit://present/presets`,mimeType:`application/json`,text:JSON.stringify(Jg,null,2)}]}))}catch{}}const Xg=A(`tools`);function Zg(e,t){let n=new tr({structure:new rr,dependencies:new Qn,symbols:new ir,patterns:new nr,entryPoints:new er,diagrams:new $n}),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},J(`produce_knowledge`,async({scope:e,aspects:t},r)=>{let i;try{i=Rc(r).createTask(`Produce Knowledge`,3),i.progress(0,`Running analyzers`);let a=e??`.`;Xg.info(`Running knowledge production`,{rootPath:a,aspects:t});let o=await n.runExtraction(a,t);try{let e=F(Cn(I(a)),fe.onboard);Oe(e,{recursive:!0});let t=`<!-- Generated by produce_knowledge at ${new Date().toISOString()} -->\n\n`;for(let[n,r]of Object.entries(o))r&&typeof r==`string`&&Pe(F(e,`${n}.md`),t+r,`utf-8`);Xg.info(`Knowledge persisted to .ai/context/`,{files:Object.keys(o).length})}catch(e){Xg.warn(`Failed to persist knowledge to .ai/context/`,{error:M(e)})}i.progress(1,`Synthesizing results`);let s=n.buildSynthesisInstructions(o,t);return i.complete(`Knowledge production complete`),{content:[{type:`text`,text:s+`
3008
+ <\/script>`}function mg(e){fg=e||``}function hg(e,t){if(!fg)return e;let n=`${`<script${t?` nonce="${Y(t)}"`:``}>${fg}<\/script>`}\n${pg(t||``)}`;return e.includes(`</body>`)?e.replace(`</body>`,`${n}\n</body>`):`${e}${n}`}function gg(e,t){return[`<!DOCTYPE html>`,`<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">`,`<title>Error — ${Y(e)}</title>`,`<style>`,` * { box-sizing: border-box; margin: 0; padding: 0; }`,` body { font-family: system-ui, -apple-system, sans-serif; min-height: 100vh; display: flex; align-items: center; justify-content: center; padding: 2rem; background: #fafafa; color: #333; }`,` .error-card { max-width: 560px; width: 100%; padding: 2.5rem; border-radius: 1rem; background: #fff; border: 1px solid #e5e7eb; box-shadow: 0 1px 3px rgba(0,0,0,0.06); }`,` .error-badge { display: inline-block; font-size: 0.75rem; font-weight: 600; text-transform: uppercase; letter-spacing: 0.05em; color: #dc2626; background: #fef2f2; border: 1px solid #fecaca; border-radius: 0.375rem; padding: 0.25rem 0.625rem; margin-bottom: 1rem; }`,` .error-title { font-size: 1.25rem; font-weight: 600; margin-bottom: 0.75rem; color: #111; }`,` .error-message { font-size: 0.875rem; line-height: 1.6; color: #6b7280; white-space: pre-wrap; word-break: break-word; }`,`</style></head><body>`,`<div class="error-card">`,` <span class="error-badge">Render Error</span>`,` <h1 class="error-title">${Y(e)}</h1>`,` <p class="error-message">${Y(t)}</p>`,`</div>`,`</body></html>`].join(`
3009
+ `)}function _g(e,t,n,r){return zh(gg(r??`Present`,t)),{content:[{type:`text`,text:`[ERROR:VALIDATION] ${t}`}],isError:!0}}function vg(e,t){if(!Wh(e)||!(`schemaVersion`in e))return{ok:!1,response:_g(`INVALID_CHANNEL_SURFACE`,`present expects a ChannelSurface object with schemaVersion: 1`)};if(e.schemaVersion!==1)return{ok:!1,response:_g(`UNSUPPORTED_SCHEMA_VERSION`,`Unsupported ChannelSurface schemaVersion: ${String(e.schemaVersion)}`)};if(typeof e.title==`string`&&Gh.test(e.title))return{ok:!1,response:_g(`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(!Wh(e)||e.type!==`markdown`)return[e];let t=Yh(e);return!t||!Xh(t)?[e]:eg(e)})}:e;return{ok:!0,surface:n,options:ng(n,t)}}function yg(e){return(e.actions?.length??0)>0||e.response?.required===!0?Uh.getAll().some(e=>e.id===`browser`):!1}async function bg(e,t={}){let n=yg(e)?{...t,preferBrowser:!0}:t,r=ig(e),i=Uh.select(r,n),a;if(a=i?await i.render(r,n):wh(r),e.blocks&&e.blocks.length>0&&a.isError!==!0)try{let t=new Set;for(let n of e.blocks){if(typeof n!=`object`||!n)continue;let e=typeof n.type==`string`?n.type:null;e&&!mp(e)&&t.add(e)}if(t.size>0){let e=[...t].map(e=>`"${e}"`).join(`, `);Mh.warn(`Unknown block types: ${e}`),a.content=[{type:`text`,text:`[Block type(s) not recognized: ${e}. They rendered as raw text. Use aikit://schemas/channel-surface for supported block types.]`},...a.content]}}catch(e){Mh.warn(`Block type validation failed`,M(e))}if(t.compact){let{structuredContent:e,...t}=a;return t}return a}function xg(e,t=``){return typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`?String(e):t}function Sg(e){return{type:`kv`,value:e}}function Cg(e){if(Array.isArray(e))return e}const wg=[{name:`summary`,description:`Title + markdown summary + optional metrics (pass/fail counts)`,expand(e){let t=xg(e.title,`Summary`),n=[{type:`heading`,value:t}],r=xg(e.summary);r&&n.push({type:`markdown`,value:r});let i=Number(e.passed)||0,a=Number(e.failed)||0;if(i>0||a>0){let e=[];i>0&&e.push({label:`Passed`,value:i,status:`success`}),a>0&&e.push({label:`Failed`,value:a,status:`error`}),n.push({type:`metrics`,value:e})}return{title:t,blocks:n}}},{name:`plan`,description:`Title + heading per step + checklist items`,expand(e){let t=xg(e.title,`Plan`),n=[{type:`heading`,value:t}],r=Cg(e.steps);return r&&n.push({type:`checklist`,value:{items:r}}),{title:t,blocks:n}}},{name:`understanding`,description:`Title + markdown explanation + kv pairs`,expand(e){let t=xg(e.title,`Understanding`),n=[{type:`heading`,value:t}],r=xg(e.explanation);return r&&n.push({type:`markdown`,value:r}),e.details&&typeof e.details==`object`&&!Array.isArray(e.details)&&n.push(Sg(e.details)),{title:t,blocks:n}}},{name:`bug-analyze`,description:`Title + heading + severity/status kv + code block + markdown`,expand(e){let t=xg(e.title,`Bug Analysis`),n=[{type:`heading`,value:t}],r={};e.severity&&(r.Severity=e.severity),e.status&&(r.Status=e.status),Object.keys(r).length>0&&n.push({type:`kv`,value:r});let i=xg(e.code);i&&n.push({type:`code`,value:i});let a=xg(e.analysis);return a&&n.push({type:`markdown`,value:a}),{title:t,blocks:n}}},{name:`task-done`,description:`Title + checklist of completed items + optional metrics`,expand(e){let t=xg(e.title,`Task Complete`),n=[{type:`heading`,value:t}],r=Cg(e.items);r&&n.push({type:`checklist`,value:{items:r}});let i=e.completed,a=e.total;if(i!==void 0||a!==void 0){let e=[];i!==void 0&&e.push({label:`Completed`,value:Number(i)||i,status:`success`}),a!==void 0&&e.push({label:`Total`,value:Number(a)||a}),n.push({type:`metrics`,value:e})}return{title:t,blocks:n}}},{name:`review`,description:`Title + criteria checklist + annotation items + approval controls`,expand(e){let t=xg(e.title,`Review`),n=[{type:`heading`,value:t}],r=Cg(e.criteria);r&&n.push({type:`checklist`,value:{items:r}});let i=e.annotations;Array.isArray(i)&&i.length>0&&n.push({type:`annotation`,value:i});let a=e.approval;return a&&typeof a==`object`?n.push({type:`approval`,value:a}):n.push({type:`actions`,value:[{type:`button`,id:`approve`,label:`Approve`,variant:`primary`},{type:`button`,id:`reject`,label:`Reject`,variant:`danger`}]}),{title:t,blocks:n}}},{name:`explore`,description:`Title + heading per finding + code blocks`,expand(e){let t=xg(e.title,`Exploration`),n=[{type:`heading`,value:t}],r=Cg(e.findings);if(r)for(let e of r)n.push({type:`heading`,value:xg(e.heading,`Finding`)}),e.code&&n.push({type:`code`,value:e.code});return{title:t,blocks:n}}},{name:`decision`,description:`Title + kv for recommendation + comparison blocks per option`,expand(e){let t=xg(e.title,`Decision`),n=[{type:`heading`,value:t}];e.recommendation&&n.push({type:`kv`,value:{Recommendation:e.recommendation}});let r=Cg(e.options);return r&&r.length>0&&n.push({type:`comparison`,value:r.map(e=>({title:xg(e.title,`Option`),items:Array.isArray(e.items)?e.items:[]}))}),{title:t,blocks:n}}}],Tg=new Map;for(let e of wg)Tg.set(e.name,e);function Eg(e,t){let n=Tg.get(e);return n?n.expand(t):null}function Dg(e){let t=[],n=!1,r=!1;for(let i of e){if(r){r=!1,t.push(i);continue}if(i===`\\`&&n){r=!0,t.push(i);continue}if(i===`"`){n=!n,t.push(i);continue}if(n&&(i===`
3010
+ `||i===`\r`)){t.push(`\\n`);continue}t.push(i)}return t.join(``)}function Og(e){let t=[],n=!1,r=!1;for(let i of e){if(r){r=!1,t.push(i);continue}if(i===`\\`&&n){r=!0,t.push(i);continue}if(i===`"`){n=!n,t.push(i);continue}if(n){t.push(i);continue}if(i===`]`||i===`}`)for(let e=t.length-1;e>=0;e--){let n=t[e];if(!(n===` `||n===`
3011
+ `||n===` `||n===`\r`||n===``)){n===`,`&&(t[e]=``);break}}t.push(i)}return t.join(``)}function kg(e){try{return JSON.parse(e)}catch{}let t=Og(Dg(e));try{return JSON.parse(t)}catch(e){try{return JSON.parse(t.replaceAll(`'`,`"`))}catch{throw e}}}const Ag={h:`heading`,m:`markdown`,t:`table`,p:`paragraph`,c:`code`,s:`separator`,M:`metrics`,C:`chart`,T:`timeline`,g:`graph`,tr:`tree`,tl:`timeline`,cl:`checklist`,pr:`progress`,sb:`status-board`,kv:`kv`,ac:`actions`,di:`mermaid`},jg=/^(#{1,6})\s/,Mg=/^(`{3,}|~{3,})/,Ng=/^\|.+\|.+\|/m;function Pg(e){let t=e.trim(),n=t.match(jg);if(n)return{type:`heading`,value:t.slice(n[0].length)};if(Mg.test(t)){let e=t.indexOf(`
3012
+ `),n=t.lastIndexOf(t[0]);return{type:`code`,value:e>=0?t.slice(e+1,n).trimEnd():t}}return Ng.test(t)?{type:`table`,value:t}:{type:`markdown`,value:t}}function Fg(e,t){let n=Ag[e];if(!n)return null;switch(e){case`M`:return{type:`metrics`,value:t};case`C`:return{type:`chart`,value:t};case`T`:case`tl`:return{type:`timeline`,value:t};case`g`:return{type:`graph`,value:t};case`tr`:return{type:`tree`,value:t};case`cl`:return{type:`checklist`,value:t};case`pr`:return{type:`progress`,value:t};case`sb`:return{type:`status-board`,value:t};case`kv`:return{type:`kv`,value:t};case`ac`:return{type:`actions`,value:t};case`di`:return{type:`mermaid`,value:t};case`s`:return{type:`separator`,value:t||!0};default:return{type:n,value:typeof t==`string`?t:String(t??``)}}}function Ig(e){if(typeof e==`string`){let t=Pg(e);return{type:t.type,value:t.value}}if(Array.isArray(e)){let[t,n]=e;if(typeof t==`string`){let e=Fg(t,n);if(e)return e}return{type:`markdown`,value:String(t??``)}}if(typeof e==`object`&&e){let{blockId:t,...n}=e;return n}return{type:`markdown`,value:String(e??``)}}function Lg(e){return{title:e.title??``,blocks:Array.isArray(e.blocks)?e.blocks.map(Ig):[]}}function Rg(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function zg(e){return Rg(e)&&typeof e.schemaVersion==`number`&&e.schemaVersion===1}function Bg(e){return Rg(e)&&typeof e.schemaVersion==`number`&&e.schemaVersion!==1}function Vg(e){return e.schemaVersion===1?typeof e.title!=`string`||e.title.length===0?{ok:!1,error:{code:`MISSING_TITLE`,reason:`ChannelSurface requires a non-empty title`}}:e.blocks!==void 0&&!Array.isArray(e.blocks)?{ok:!1,error:{code:`INVALID_BLOCKS`,reason:`blocks must be an array of TypedBlock objects`}}:{ok:!0,surface:e}:{ok:!1,error:{code:`UNSUPPORTED_SCHEMA_VERSION`,reason:`Unsupported schemaVersion: ${String(e.schemaVersion)}`}}}function Hg(e){try{let t=kg(e);return Rg(t)?(t.schemaVersion===void 0&&(t.schemaVersion=1),Ug(t)):{ok:!1,error:{code:`INVALID_RAW_INPUT`,reason:`raw field must contain a JSON object (ChannelSurface)`}}}catch(e){return{ok:!1,error:{code:`INVALID_RAW_JSON`,reason:`Failed to parse raw field: ${e.message}`,hint:`JSON repair attempted. Ensure the raw string contains a valid ChannelSurface object. Common LLM errors (newlines in strings, trailing commas) are auto-repaired.`}}}}function Ug(e){if(Array.isArray(e)){if(e.length!==2)return{ok:!1,error:{code:`INVALID_PRESET_INPUT`,reason:`Preset input must be a [name, data] tuple`,hint:`Use [presetName, { title, ...fields }]`}};let[t,n]=e;if(typeof t!=`string`)return{ok:!1,error:{code:`INVALID_PRESET_INPUT`,reason:`Preset name must be a string`}};if(!Rg(n))return{ok:!1,error:{code:`INVALID_PRESET_INPUT`,reason:`Preset data must be an object`}};let r=Eg(t,n);return r?{ok:!0,surface:{schemaVersion:1,title:r.title,blocks:r.blocks}}:{ok:!1,error:{code:`UNKNOWN_PRESET`,reason:`Unknown preset: ${t}`,hint:`Available presets: summary, plan, understanding, bug-analyze, task-done, review, explore, decision`}}}if(Bg(e))return{ok:!1,error:{code:`UNSUPPORTED_SCHEMA_VERSION`,reason:`Unsupported schemaVersion: ${String(e.schemaVersion)}`,hint:`Use schemaVersion: 1`}};if(Rg(e)&&typeof e.raw==`string`)return Hg(e.raw);if(zg(e))return Vg(e);if(typeof e==`string`){let t=Lg({blocks:[e]});return{ok:!0,surface:{schemaVersion:1,title:t.title||`Present`,blocks:t.blocks}}}if(Rg(e)){if(!(`blocks`in e)&&!(`title`in e))return{ok:!1,error:{code:`INVALID_INPUT`,reason:`Expected a ChannelSurface object, preset tuple, or shorthand input`}};let t=Lg(e);return{ok:!0,surface:{schemaVersion:1,title:t.title||`Present`,blocks:t.blocks}}}return{ok:!1,error:{code:`INVALID_INPUT`,reason:`Expected a ChannelSurface object, preset tuple, or shorthand input`}}}const Wg=L.object({label:L.string(),value:L.string(),description:L.string().optional()}),Gg=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(Wg).optional(),schema:L.record(L.string(),L.unknown()).optional()}),Kg=L.object({type:L.string(),title:L.string().optional(),value:L.unknown().optional(),language:L.string().optional()}).catchall(L.unknown()),qg={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(Kg).optional().describe(`Typed block content for the surface.`),data:L.unknown().optional().describe(`Template data payload, if the template expands data.`),actions:L.array(Gg).optional().describe(`Interactive actions. Presence triggers browser transport.`),response:L.object({timeout:L.number().finite().min(0).max(3e5).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(),raw:L.string().optional().describe(`Raw JSON string with auto-repair. Accepts common LLM JSON errors (unescaped newlines in strings, trailing commas). Use for complex payloads with mermaid/code/markdown blocks.`),preferBrowser:L.boolean().optional().default(!0).describe(`Prefer browser transport instead of inline rendering. Default: true — most clients render in an external browser window. Set preferBrowser: false to request inline/embedded rendering (only honored when the client supports inline display; auto-falls back to browser if not).`)};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 Jg(e){let t=e.server?.getClientCapabilities?.();if(!t)return`unknown`;let n=fr(t);return!n||Array.isArray(n.mimeTypes)&&n.mimeTypes.length>0&&!n.mimeTypes.includes(dr)?`unsupported`:`supported`}const Yg=[{name:`summary`,description:`Title + markdown summary + optional metrics (pass/fail counts)`,inputSchema:{type:`object`,properties:{title:{type:`string`,description:`Section heading`},summary:{type:`string`,description:`Free-form markdown summary`},passed:{type:`number`,description:`Pass count for metrics`},failed:{type:`number`,description:`Fail count for metrics`}},required:[`title`]},example:JSON.stringify({title:`Build Summary`,summary:`All tests passed.`,passed:42,failed:0}),expandsTo:`blocks: [heading, markdown, metrics]`},{name:`plan`,description:`Title + heading per step + checklist items`,inputSchema:{type:`object`,properties:{title:{type:`string`},steps:{type:`array`,items:{type:`object`,properties:{label:{type:`string`},checked:{type:`boolean`}}}}},required:[`title`]},example:JSON.stringify({title:`Sprint Plan`,steps:[{label:`Write tests`,checked:!1},{label:`Deploy`,checked:!1}]}),expandsTo:`blocks: [heading, checklist]`},{name:`understanding`,description:`Title + markdown explanation + kv pairs`,inputSchema:{type:`object`,properties:{title:{type:`string`},explanation:{type:`string`},details:{type:`object`,additionalProperties:{type:`string`}}},required:[`title`,`explanation`]},example:JSON.stringify({title:`Architecture Overview`,explanation:`The system uses microservices.`,details:{Language:`TypeScript`,Runtime:`Node`}}),expandsTo:`blocks: [heading, markdown, kv]`},{name:`bug-analyze`,description:`Title + heading + severity/status kv + code block + markdown`,inputSchema:{type:`object`,properties:{title:{type:`string`},severity:{type:`string`},status:{type:`string`},code:{type:`string`},analysis:{type:`string`}},required:[`title`,`severity`,`status`]},example:JSON.stringify({title:`Null pointer in auth`,severity:`high`,status:`open`,code:`const x = obj.prop;`,analysis:`obj may be null when token missing.`}),expandsTo:`blocks: [heading, kv, code, markdown]`},{name:`task-done`,description:`Title + checklist of completed items + optional metrics`,inputSchema:{type:`object`,properties:{title:{type:`string`},items:{type:`array`,items:{type:`object`,properties:{label:{type:`string`},checked:{type:`boolean`}}}},completed:{type:`number`},total:{type:`number`}},required:[`title`,`items`]},example:JSON.stringify({title:`PR #42 Done`,items:[{label:`Lint pass`,checked:!0},{label:`Tests pass`,checked:!0}],completed:2,total:2}),expandsTo:`blocks: [heading, checklist, metrics]`},{name:`review`,description:`Title + criteria checklist + approval actions`,inputSchema:{type:`object`,properties:{title:{type:`string`,description:`Review title`},criteria:{type:`array`,description:`Checklist criteria items`,items:{type:`object`,properties:{label:{type:`string`},checked:{type:`boolean`}}}},annotations:{type:`array`,description:`Optional annotation items`,items:{type:`object`,properties:{label:{type:`string`},description:{type:`string`},severity:{type:`string`}}}},approval:{type:`object`,description:`Optional approval config`,properties:{prompt:{type:`string`},options:{type:`array`,items:{type:`object`,properties:{label:{type:`string`},value:{type:`string`}}}}}}},required:[`title`,`criteria`]},example:JSON.stringify({title:`Code Review`,criteria:[{label:`Tests included`,checked:!0},{label:`No regressions`,checked:!1}]}),expandsTo:`blocks: [heading, checklist] + actions: [approve, reject]`},{name:`explore`,description:`Title + heading per finding + code blocks`,inputSchema:{type:`object`,properties:{title:{type:`string`},findings:{type:`array`,items:{type:`object`,properties:{heading:{type:`string`},code:{type:`string`}}}}},required:[`title`,`findings`]},example:JSON.stringify({title:`Codebase Exploration`,findings:[{heading:`Auth flow`,code:`function login()`},{heading:`API routes`,code:`router.get("/api")`}]}),expandsTo:`blocks: [heading, code] per finding`},{name:`decision`,description:`Title + kv for recommendation + comparison blocks per option`,inputSchema:{type:`object`,properties:{title:{type:`string`},recommendation:{type:`string`},options:{type:`array`,items:{type:`object`,properties:{title:{type:`string`},items:{type:`array`,items:{type:`string`}}}}}},required:[`title`,`recommendation`]},example:JSON.stringify({title:`DB Choice`,recommendation:`PostgreSQL`,options:[{title:`Postgres`,items:[`ACID`,`Rich types`]},{title:`Mongo`,items:[`Schema-less`,`Horizontal`]}]}),expandsTo:`blocks: [heading, kv, comparison]`}];function Xg(e,t){let n=U(`present`);try{let e=r(`present`);e&&mg(P(I(e,`dist`,`annotation-layer.js`),`utf8`))}catch{}mr(e,`present`,{title:n.title,description:"Render a ChannelSurface. Required: schemaVersion: 1, title. Supports blocks, template+data, named presets, and raw JSON string with auto-repair. Use `raw` for complex payloads (mermaid, code, many blocks) — common LLM JSON errors are auto-fixed. IMPORTANT: when using `raw`, do NOT pass `schemaVersion` or `title` at the top level — the `raw` JSON must be a self-contained ChannelSurface with its own `schemaVersion: 1`, `title`, and `blocks`. preferBrowser defaults to true (browser rendering). Set preferBrowser: false explicitly when you want inline — only honored if the client supports it; auto-falls back to browser otherwise. Actions always use browser transport. Resources: aikit://schemas/channel-surface (schema+blocks), aikit://present/presets (presets), aikit://present/templates (viewers).",inputSchema:qg,annotations:n.annotations,_meta:bh(jh)},J(`present`,async(t,n)=>{let r=t,i=typeof r.preferBrowser==`boolean`?r.preferBrowser:void 0,a=Ug(t);if(!a.ok)return _g(a.error.code,a.error.reason,void 0,`Present`);let o=vg(a.surface,n);if(!o.ok)return o.response;let s=Jg(e),c=!(i===!1&&s===`supported`),l={responseTimeoutMs:o.surface.response?.timeout,responseRequired:o.surface.response?.required,transportReason:c?`caller-preferred`:`inline-unsupported`};return await bg(o.surface,{...o.options,preferBrowser:c,session:l})}));try{let t=new Xn(jh,{list:void 0});e.registerResource(`Present View`,t,{description:`AI Kit present tool viewer`},async(e,t,n)=>{let r=Array.isArray(t.id)?t.id[0]:t.id,i=r?Vh(r):void 0;return{contents:[{uri:e.href,mimeType:dr,_meta:xh(),text:i??Rh()??`<html><body><p>No content generated yet. Call the present tool first.</p></body></html>`}]}})}catch{}function i(){try{let e=r(`present`);if(e)return P(I(e,`dist`,`index.html`),`utf8`)}catch{}return Rh()||`<html><body><p>Loading...</p></body></html>`}try{e.registerResource(`Present App`,Ah,{description:`AI Kit present app - entry point`},async()=>({contents:[{uri:Ah,mimeType:dr,_meta:xh(),text:i()}]}))}catch{}try{e.registerResource(`present-templates`,`aikit://present/templates`,{description:`List all registered present viewer templates with their input schemas`},async()=>{let e=xp().map(e=>({id:e.id,label:e.label,description:e.description,transports:e.supportedTransports,inputSchema:e.inputSchema}));return{contents:[{uri:`aikit://present/templates`,mimeType:`application/json`,text:JSON.stringify(e,null,2)}]}})}catch{}try{e.registerResource(`present-presets`,`aikit://present/presets`,{description:`List all registered present presets with input schemas and examples`},async()=>({contents:[{uri:`aikit://present/presets`,mimeType:`application/json`,text:JSON.stringify(Yg,null,2)}]}))}catch{}}const Zg=A(`tools`);function Qg(e,t){let n=new tr({structure:new rr,dependencies:new Qn,symbols:new ir,patterns:new nr,entryPoints:new er,diagrams:new $n}),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},J(`produce_knowledge`,async({scope:e,aspects:t},r)=>{let i;try{i=Rc(r).createTask(`Produce Knowledge`,3),i.progress(0,`Running analyzers`);let a=e??`.`;Zg.info(`Running knowledge production`,{rootPath:a,aspects:t});let o=await n.runExtraction(a,t);try{let e=F(Cn(I(a)),fe.onboard);Oe(e,{recursive:!0});let t=`<!-- Generated by produce_knowledge at ${new Date().toISOString()} -->\n\n`;for(let[n,r]of Object.entries(o))r&&typeof r==`string`&&Pe(F(e,`${n}.md`),t+r,`utf-8`);Zg.info(`Knowledge persisted to .ai/context/`,{files:Object.keys(o).length})}catch(e){Zg.warn(`Failed to persist knowledge to .ai/context/`,{error:M(e)})}i.progress(1,`Synthesizing results`);let s=n.buildSynthesisInstructions(o,t);return i.complete(`Knowledge production complete`),{content:[{type:`text`,text:s+`
3013
3013
 
3014
3014
  ---
3015
- _Next: Review the baselines above and use \`remember\` to store synthesized knowledge entries._`}]}}catch(e){return i?.fail?.(`Production failed`),Xg.error(`Knowledge production failed`,M(e)),q(`INTERNAL`,`Knowledge production failed: ${e instanceof Error?e.message:String(e)}`)}}))}const Qg=A(`tools`);function $g(e,t,n,r,i,a,o,s){let c=U(`reindex`);e.registerTool(`reindex`,{title:c.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:c.annotations},J(`reindex`,async({full:e,force:c},l)=>{try{if(t.isIndexing)return{content:[{type:`text`,text:`## Reindex Already in Progress
3015
+ _Next: Review the baselines above and use \`remember\` to store synthesized knowledge entries._`}]}}catch(e){return i?.fail?.(`Production failed`),Zg.error(`Knowledge production failed`,M(e)),q(`INTERNAL`,`Knowledge production failed: ${e instanceof Error?e.message:String(e)}`)}}))}const $g=A(`tools`);function e_(e,t,n,r,i,a,o,s){let c=U(`reindex`);e.registerTool(`reindex`,{title:c.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:c.annotations},J(`reindex`,async({full:e,force:c},l)=>{try{if(t.isIndexing)return{content:[{type:`text`,text:`## Reindex Already in Progress
3016
3016
 
3017
3017
  A reindex operation is currently running. Search and other tools continue to work with existing data. Use \`status({})\` to check when it completes.`}]};if(o===`smart`&&!c)return{content:[{type:`text`,text:`## Smart Indexing Active
3018
3018
 
@@ -3020,41 +3020,41 @@ Smart indexing (trickle mode) is enabled — files are automatically indexed as
3020
3020
 
3021
3021
  **If the index is severely outdated**, use \`reindex({ force: true })\` to override.
3022
3022
 
3023
- Use \`status({})\` to check smart indexing queue status.`}]};let u=Rc(l).createTask(`Reindex`,1);u.progress(0,`Starting ${e?`full`:`incremental`} reindex`),Qg.info(`Starting background re-index`,{mode:e?`full`:`incremental`});let d=e=>t=>{t.phase===`chunking`&&t.currentFile&&Qg.debug(`Re-index progress`,{prefix:e,current:t.filesProcessed+1,total:t.filesTotal,file:t.currentFile})};return(e?t.reindexAll(n,d(`Reindex`)):t.index(n,d(`Index`))).then(async e=>{if(Qg.info(`Background re-index complete`,{filesProcessed:e.filesProcessed,chunksCreated:e.chunksCreated,durationMs:e.durationMs}),u.complete(`Reindex complete: ${e.filesProcessed} files, ${e.chunksCreated} chunks in ${e.durationMs}ms`),i)try{await i.createFtsIndex(),Qg.info(`FTS index rebuilt after reindex`)}catch(e){Qg.warn(`FTS index rebuild failed`,M(e))}try{let e=await r.reindexAll();Qg.info(`Curated re-index complete`,{indexed:e.indexed})}catch(e){Qg.warn(`Curated re-index failed`,M(e))}if(a)try{await a.notifyAfterReindex()}catch(e){Qg.warn(`Post-reindex resource notification failed`,M(e))}if(s)try{s.emit({type:`reindex:done`,timestamp:Date.now(),eventId:`reindex-done-${Date.now()}`,workspaceId:`ws:default`,source:`reindex-tool`,result:`completed`,filesProcessed:e.filesProcessed,durationMs:e.durationMs}),Qg.info(`reindex:done event emitted`)}catch(e){Qg.warn(`Failed to emit reindex:done event`,M(e))}}).catch(e=>{u.fail(`Reindex failed: ${e instanceof Error?e.message:String(e)}`),Qg.error(`Background reindex failed`,M(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 Qg.error(`Reindex failed`,M(e)),q(`INTERNAL`,`Reindex failed: ${e instanceof Error?e.message:String(e)}`)}}))}const e_=A(`tools`);function t_(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)`),max_tokens:L.number().optional().describe(`Approximate token limit for output. Entries are condensed to fit.`)},annotations:t.annotations},J(`replay`,async({action:e,last:t,tool:n,source:r,since:i,max_tokens:a})=>{try{if(e===`clear`)return vn(),{content:[{type:`text`,text:`Replay log cleared.`}]};let o=yn({last:t,tool:n,source:r,since:i,maxTokens:a});if(o.length===0)return{content:[{type:`text`,text:`No replay entries found. Activity is logged when tools are invoked via MCP or CLI.`}]};let s=o.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 bn().catch(()=>{}),{content:[{type:`text`,text:`**Replay Log** (${o.length} entries)\n\n${s.join(`
3023
+ Use \`status({})\` to check smart indexing queue status.`}]};let u=Rc(l).createTask(`Reindex`,1);u.progress(0,`Starting ${e?`full`:`incremental`} reindex`),$g.info(`Starting background re-index`,{mode:e?`full`:`incremental`});let d=e=>t=>{t.phase===`chunking`&&t.currentFile&&$g.debug(`Re-index progress`,{prefix:e,current:t.filesProcessed+1,total:t.filesTotal,file:t.currentFile})};return(e?t.reindexAll(n,d(`Reindex`)):t.index(n,d(`Index`))).then(async e=>{if($g.info(`Background re-index complete`,{filesProcessed:e.filesProcessed,chunksCreated:e.chunksCreated,durationMs:e.durationMs}),u.complete(`Reindex complete: ${e.filesProcessed} files, ${e.chunksCreated} chunks in ${e.durationMs}ms`),i)try{await i.createFtsIndex(),$g.info(`FTS index rebuilt after reindex`)}catch(e){$g.warn(`FTS index rebuild failed`,M(e))}try{let e=await r.reindexAll();$g.info(`Curated re-index complete`,{indexed:e.indexed})}catch(e){$g.warn(`Curated re-index failed`,M(e))}if(a)try{await a.notifyAfterReindex()}catch(e){$g.warn(`Post-reindex resource notification failed`,M(e))}if(s)try{s.emit({type:`reindex:done`,timestamp:Date.now(),eventId:`reindex-done-${Date.now()}`,workspaceId:`ws:default`,source:`reindex-tool`,result:`completed`,filesProcessed:e.filesProcessed,durationMs:e.durationMs}),$g.info(`reindex:done event emitted`)}catch(e){$g.warn(`Failed to emit reindex:done event`,M(e))}}).catch(e=>{u.fail(`Reindex failed: ${e instanceof Error?e.message:String(e)}`),$g.error(`Background reindex failed`,M(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 $g.error(`Reindex failed`,M(e)),q(`INTERNAL`,`Reindex failed: ${e instanceof Error?e.message:String(e)}`)}}))}const t_=A(`tools`);function n_(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)`),max_tokens:L.number().optional().describe(`Approximate token limit for output. Entries are condensed to fit.`)},annotations:t.annotations},J(`replay`,async({action:e,last:t,tool:n,source:r,since:i,max_tokens:a})=>{try{if(e===`clear`)return vn(),{content:[{type:`text`,text:`Replay log cleared.`}]};let o=yn({last:t,tool:n,source:r,since:i,maxTokens:a});if(o.length===0)return{content:[{type:`text`,text:`No replay entries found. Activity is logged when tools are invoked via MCP or CLI.`}]};let s=o.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 bn().catch(()=>{}),{content:[{type:`text`,text:`**Replay Log** (${o.length} entries)\n\n${s.join(`
3024
3024
 
3025
- `)}`}]}}catch(e){return e_.error(`Replay failed`,M(e)),q(`INTERNAL`,`Replay failed: ${e instanceof Error?e.message:String(e)}`)}}))}const n_=A(`tools`);function r_(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=qt().slice(0,n);return e.length===0?{content:[{type:`text`,text:`No restore points found.`}]}:{content:[{type:`text`,text:`## Restore Points\n\n${e.map(e=>`- **${e.id}** (${e.timestamp}) — ${e.operation}: ${e.description} (${e.files.length} files)`).join(`
3025
+ `)}`}]}}catch(e){return t_.error(`Replay failed`,M(e)),q(`INTERNAL`,`Replay failed: ${e instanceof Error?e.message:String(e)}`)}}))}const r_=A(`tools`);function i_(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=qt().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(`
3026
3026
  `)}`}]}}if(!t)throw Error(`id is required for restore action`);let r=await wn(t);return{content:[{type:`text`,text:`Restored ${r.length} files:\n${r.map(e=>`- \`${e}\``).join(`
3027
- `)}`}]}}catch(e){return n_.error(`Restore failed`,M(e)),q(`INTERNAL`,`Restore failed: ${e instanceof Error?e.message:String(e)}`)}})}const i_=/<\/?curated-context>/gi;function a_(e){return e.replace(i_,``)}function o_(e){return`<curated-context>\n${a_(e)}\n</curated-context>`}const s_=A(`tools`);function c_(e,t,n,r){i(e,t,n);let a=e.memoryMetaGet(t);if(!a)return;let o=re(a,{...l,...r});o&&(c(e,t,o),p(e,t,n))}function l_(e,t){let n=[],r=j(),i=r?Fe(r):``;i&&n.push(`[project: ${i}]`);let a=t?Nn(t,`__context_boost`):void 0;return a&&n.push(`[focus: ${a.value}]`),n.length===0?e:`${n.join(` `)} ${e}`}function u_(e,t,n){return n?e:t===`curated`?e*1.2:e}function d_(e,t){return t?e:e.map(e=>({record:e.record,score:u_(e.score,e.record.origin,t)})).sort((e,t)=>t.score-e.score)}function f_(e,t){let n=e?Math.floor(e/Math.max(1,t)):96;return Math.max(40,Math.min(160,n))}function p_(e,t){let n=e.origin===`curated`?o_(e.content):e.content,r=Vn(n,t);return{body:r,truncated:r!==n}}async function m_(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:ur(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 s_.warn(`ER fallback failed`,M(e)),{results:n,triggered:!0,cacheHit:a}}}function h_(e,t,n=60){let r=new Map,i=e[0]?.score||1,a=t[0]?.score||1;for(let t=0;t<e.length;t++){let a=e[t],o=a.score/i;r.set(a.record.id,{record:a.record,score:1/(n+t+1)*o})}for(let e=0;e<t.length;e++){let i=t[e],o=i.score/a,s=r.get(i.record.id);s?s.score+=1/(n+e+1)*o:r.set(i.record.id,{record:i.record,score:1/(n+e+1)*o})}return[...r.values()].sort((e,t)=>t.score-e.score).map(({record:e,score:t})=>({record:e,score:t*(n+1)}))}function g_(e,t){let n=t.toLowerCase().split(/\s+/).filter(e=>e.length>=2);return n.length<2?e:e.map(e=>{let t=e.record.content.toLowerCase();if(t.length>5e3)return e;let r=n.map(e=>{let n=[],r=t.indexOf(e);for(;r!==-1&&n.length<10;)n.push(r),r=t.indexOf(e,r+1);return n});if(r.some(e=>e.length===0))return e;let i=t.length;for(let e of r[0]){let t=e,a=e+n[0].length;for(let i=1;i<r.length;i++){let o=r[i][0],s=Math.abs(o-e);for(let t=1;t<r[i].length;t++){let n=Math.abs(r[i][t]-e);n<s&&(s=n,o=r[i][t])}t=Math.min(t,o),a=Math.max(a,o+n[i].length)}i=Math.min(i,a-t)}let a=1+.25/(1+i/200);return{record:e.record,score:e.score*a}}).sort((e,t)=>t.score-e.score)}function __(e){if(e.length<=1)return e;let t=new Set;return e.filter(e=>{let n=e.record.contentHash;return n?t.has(n)?!1:(t.add(n),!0):!0})}function v_(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&&!y_.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 y_=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 b_(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 We(e)).mtimeMs>r&&o++}catch{o++}let s=Math.max(1,Math.ceil(a.length*.3)),c=0;for(let e of a)try{(await We(e)).mtimeMs>r+12e4&&c++}catch{c++}if(c>=s){let e=i-r,t=Math.floor(e/6e4),n=t<1?`<1 min`:`${t} min`;return`> ⚠️ **Index may be stale** — ${c}/${a.length} sampled files modified since last index (${n} ago). Use \`reindex\` to refresh.`}}catch{}}function x_(e,t,n,r,i,a,o,s,c,l,u){let d=U(`search`);e.registerTool(`search`,{title:d.title,description:`Search AI Kit for code, docs, and prior decisions. Default choice for discovery. Modes: hybrid (default), semantic, keyword. For multi-strategy precision queries use find; for a known file path use lookup.`,outputSchema:Fs,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(pe).optional().describe(`Filter by content type`),source_type:L.enum(_e).optional().describe(`Coarse filter: "source" (code only), "documentation" (md, curated), "test", "config". Overrides content_type if both set.`),origin:L.enum(ge).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 exact tag membership (any supplied tag may match)`),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.`),min_confidence:L.enum([`extracted`,`inferred`,`ambiguous`]).optional().describe(`Minimum confidence level for results: "extracted" (guaranteed correct from source code), "inferred" (LLM-derived), "ambiguous" (uncertain, needs verification). Lower values include more results.`),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:d.annotations},async({query:e,limit:d,search_mode:f,content_type:p,source_type:m,origin:h,category:g,tags:_,min_score:v,min_confidence:y,graph_hops:b,max_tokens:x,dedup:S,workspaces:C})=>{let w=Date.now();try{let T={limit:d,minScore:v,contentType:p,sourceType:m,origin:h,category:g,tags:_},E,D=!1,ee=!1,O=``,te=f!==`keyword`,ne=l_(e,s);if(f===`keyword`)E=await n.ftsSearch(e,T),E=E.slice(0,d);else if(f===`semantic`)try{let r=await t.embedQuery(ne);E=await n.search(r,T);let a=await m_(i,E[0]?.score??0,E,e,d);E=a.results,D=a.triggered,ee=a.cacheHit}catch(t){te=!1,s_.warn(`Embedder unavailable in semantic mode, falling back to FTS`,M(t)),E=await n.ftsSearch(e,{...T,limit:d}),O=`> _⚠️ Semantic search unavailable (embedder recovering). Showing keyword results instead._
3027
+ `)}`}]}}catch(e){return r_.error(`Restore failed`,M(e)),q(`INTERNAL`,`Restore failed: ${e instanceof Error?e.message:String(e)}`)}})}const a_=/<\/?curated-context>/gi;function o_(e){return e.replace(a_,``)}function s_(e){return`<curated-context>\n${o_(e)}\n</curated-context>`}const c_=A(`tools`);function l_(e,t,n,r){i(e,t,n);let a=e.memoryMetaGet(t);if(!a)return;let o=re(a,{...l,...r});o&&(c(e,t,o),p(e,t,n))}function u_(e,t){let n=[],r=j(),i=r?Fe(r):``;i&&n.push(`[project: ${i}]`);let a=t?Nn(t,`__context_boost`):void 0;return a&&n.push(`[focus: ${a.value}]`),n.length===0?e:`${n.join(` `)} ${e}`}function d_(e,t,n){return n?e:t===`curated`?e*1.2:e}function f_(e,t){return t?e:e.map(e=>({record:e.record,score:d_(e.score,e.record.origin,t)})).sort((e,t)=>t.score-e.score)}function p_(e,t){let n=e?Math.floor(e/Math.max(1,t)):96;return Math.max(40,Math.min(160,n))}function m_(e,t){let n=e.origin===`curated`?s_(e.content):e.content,r=Vn(n,t);return{body:r,truncated:r!==n}}async function h_(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:ur(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 c_.warn(`ER fallback failed`,M(e)),{results:n,triggered:!0,cacheHit:a}}}function g_(e,t,n=60){let r=new Map,i=e[0]?.score||1,a=t[0]?.score||1;for(let t=0;t<e.length;t++){let a=e[t],o=a.score/i;r.set(a.record.id,{record:a.record,score:1/(n+t+1)*o})}for(let e=0;e<t.length;e++){let i=t[e],o=i.score/a,s=r.get(i.record.id);s?s.score+=1/(n+e+1)*o:r.set(i.record.id,{record:i.record,score:1/(n+e+1)*o})}return[...r.values()].sort((e,t)=>t.score-e.score).map(({record:e,score:t})=>({record:e,score:t*(n+1)}))}function __(e,t){let n=t.toLowerCase().split(/\s+/).filter(e=>e.length>=2);return n.length<2?e:e.map(e=>{let t=e.record.content.toLowerCase();if(t.length>5e3)return e;let r=n.map(e=>{let n=[],r=t.indexOf(e);for(;r!==-1&&n.length<10;)n.push(r),r=t.indexOf(e,r+1);return n});if(r.some(e=>e.length===0))return e;let i=t.length;for(let e of r[0]){let t=e,a=e+n[0].length;for(let i=1;i<r.length;i++){let o=r[i][0],s=Math.abs(o-e);for(let t=1;t<r[i].length;t++){let n=Math.abs(r[i][t]-e);n<s&&(s=n,o=r[i][t])}t=Math.min(t,o),a=Math.max(a,o+n[i].length)}i=Math.min(i,a-t)}let a=1+.25/(1+i/200);return{record:e.record,score:e.score*a}}).sort((e,t)=>t.score-e.score)}function v_(e){if(e.length<=1)return e;let t=new Set;return e.filter(e=>{let n=e.record.contentHash;return n?t.has(n)?!1:(t.add(n),!0):!0})}function y_(e,t,n=8){let r=new Set(t.toLowerCase().split(/\s+/).filter(e=>e.length>=2)),i=new Map,a=e.length;for(let t of e){let e=t.record.content.split(/[^a-zA-Z0-9_]+/).filter(e=>e.length>=3&&!b_.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 b_=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 x_(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 We(e)).mtimeMs>r&&o++}catch{o++}let s=Math.max(1,Math.ceil(a.length*.3)),c=0;for(let e of a)try{(await We(e)).mtimeMs>r+12e4&&c++}catch{c++}if(c>=s){let e=i-r,t=Math.floor(e/6e4),n=t<1?`<1 min`:`${t} min`;return`> ⚠️ **Index may be stale** — ${c}/${a.length} sampled files modified since last index (${n} ago). Use \`reindex\` to refresh.`}}catch{}}function S_(e,t,n,r,i,a,o,s,c,l,u){let d=U(`search`);e.registerTool(`search`,{title:d.title,description:`Search AI Kit for code, docs, and prior decisions. Default choice for discovery. Modes: hybrid (default), semantic, keyword. For multi-strategy precision queries use find; for a known file path use lookup.`,outputSchema:Fs,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(pe).optional().describe(`Filter by content type`),source_type:L.enum(_e).optional().describe(`Coarse filter: "source" (code only), "documentation" (md, curated), "test", "config". Overrides content_type if both set.`),origin:L.enum(ge).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 exact tag membership (any supplied tag may match)`),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.`),min_confidence:L.enum([`extracted`,`inferred`,`ambiguous`]).optional().describe(`Minimum confidence level for results: "extracted" (guaranteed correct from source code), "inferred" (LLM-derived), "ambiguous" (uncertain, needs verification). Lower values include more results.`),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:d.annotations},async({query:e,limit:d,search_mode:f,content_type:p,source_type:m,origin:h,category:g,tags:_,min_score:v,min_confidence:y,graph_hops:b,max_tokens:x,dedup:S,workspaces:C})=>{let w=Date.now();try{let T={limit:d,minScore:v,contentType:p,sourceType:m,origin:h,category:g,tags:_},E,D=!1,ee=!1,O=``,te=f!==`keyword`,ne=u_(e,s);if(f===`keyword`)E=await n.ftsSearch(e,T),E=E.slice(0,d);else if(f===`semantic`)try{let r=await t.embedQuery(ne);E=await n.search(r,T);let a=await h_(i,E[0]?.score??0,E,e,d);E=a.results,D=a.triggered,ee=a.cacheHit}catch(t){te=!1,c_.warn(`Embedder unavailable in semantic mode, falling back to FTS`,M(t)),E=await n.ftsSearch(e,{...T,limit:d}),O=`> _⚠️ Semantic search unavailable (embedder recovering). Showing keyword results instead._
3028
3028
 
3029
- `}else{let r=[],a=[];try{let i=await t.embedQuery(ne),o=n.coarseSearch,s=o?o.bind(n):n.search.bind(n);[r,a]=await Promise.all([s(i,{...T,limit:d*2}),n.ftsSearch(e,{...T,limit:d*2}).catch(()=>[])])}catch(t){te=!1,s_.warn(`Embedder unavailable, falling back to FTS-only`,M(t)),a=await n.ftsSearch(e,{...T,limit:d*2}),O=`> _⚠️ Vector search unavailable (embedder recovering). Results from keyword search only._
3029
+ `}else{let r=[],a=[];try{let i=await t.embedQuery(ne),o=n.coarseSearch,s=o?o.bind(n):n.search.bind(n);[r,a]=await Promise.all([s(i,{...T,limit:d*2}),n.ftsSearch(e,{...T,limit:d*2}).catch(()=>[])])}catch(t){te=!1,c_.warn(`Embedder unavailable, falling back to FTS-only`,M(t)),a=await n.ftsSearch(e,{...T,limit:d*2}),O=`> _⚠️ Vector search unavailable (embedder recovering). Results from keyword search only._
3030
3030
 
3031
- `}if(te?r.length===0&&a.length>0?(E=a.slice(0,d),O=` (FTS-only: vector index rebuilding)`):E=a.length===0&&r.length>0?r.slice(0,d):h_(r,a).slice(0,d):E=a.slice(0,d),te){let t=await m_(i,r[0]?.score??0,E,e,d);E=t.results,D=t.triggered,ee=t.cacheHit}}E=d_(E,h).slice(0,d),a&&a.recordSearch(e,D,ee),E.length>1&&(E=g_(E,e)),E=__(E);let re=``;if(C&&C.length>0){let n=hl(C,u);if(n.length>0){let{stores:r,closeAll:i}=await gl(n);try{let i;i=f===`keyword`||!te?await vl(r,e,{...T,limit:d}):await _l(r,await t.embedQuery(e),{...T,limit:d});for(let e of i)E.push({record:{...e.record,sourcePath:`[${e.workspace}] ${e.record.sourcePath}`},score:e.score});E=E.sort((e,t)=>t.score-e.score).slice(0,d),re=` + ${n.length} workspace(s)`}finally{await i()}}}if(S===`file`&&E.length>1){let e=new Map;for(let t of E){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}]})}E=[...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(E.length>1){let e=E[0].score,t=Math.max(e*.4,.1);E=E.filter(e=>e.score>=t)}let ie={extracted:3,inferred:2,ambiguous:1};if(y){let e=ie[y]??0;E=E.filter(t=>(t.record.confidence?ie[t.record.confidence]??2:2)>=e)}if(E.length===0){if(o?.available)try{let r=(await o.createMessage({prompt:`The search query "${e}" returned 0 results in AI Kit code search. Suggest ONE alternative search query that might find relevant results. Reply with ONLY the alternative query, nothing else.`,systemPrompt:`You are a search query optimizer for AI Kit code search. Generate a single alternative query.`,maxTokens:100,timeoutMs:1e4})).text.trim().split(`
3032
- `)[0].slice(0,500);if(r&&r!==e){let i=f===`keyword`||!te?await n.ftsSearch(r,T):await n.search(await t.embedQuery(r),T);i.length>0&&(E=i,O=`> _Original query "${e}" returned 0 results. Auto-reformulated to "${r}"._\n\n`,s_.debug(`Smart search fallback succeeded`,{originalQuery:e,altQuery:r,resultCount:i.length}))}}catch(e){s_.debug(`Smart search fallback failed`,{error:String(e)})}if(E.length===0){let t=yt({text:`No results found for the given query.`,query:e,searchMode:f,limit:d,results:[],durationMs:Date.now()-w}),n=yl(t.summary);return{content:[{type:`text`,text:bl(t.summary,n)}],isError:!t.ok,structuredContent:{...t.data??{results:[],totalResults:0,searchMode:f,query:e},ref:n}}}}let k,ae;if(b>0&&!r&&(ae="> **Note:** `graph_hops` was set but no graph store is available. Graph augmentation skipped."),b>0&&r)try{let e=await Lt(r,E.map(e=>({recordId:e.record.id,score:e.score,sourcePath:e.record.sourcePath})),{hops:b,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(`
3031
+ `}if(te?r.length===0&&a.length>0?(E=a.slice(0,d),O=` (FTS-only: vector index rebuilding)`):E=a.length===0&&r.length>0?r.slice(0,d):g_(r,a).slice(0,d):E=a.slice(0,d),te){let t=await h_(i,r[0]?.score??0,E,e,d);E=t.results,D=t.triggered,ee=t.cacheHit}}E=f_(E,h).slice(0,d),a&&a.recordSearch(e,D,ee),E.length>1&&(E=__(E,e)),E=v_(E);let re=``;if(C&&C.length>0){let n=hl(C,u);if(n.length>0){let{stores:r,closeAll:i}=await gl(n);try{let i;i=f===`keyword`||!te?await vl(r,e,{...T,limit:d}):await _l(r,await t.embedQuery(e),{...T,limit:d});for(let e of i)E.push({record:{...e.record,sourcePath:`[${e.workspace}] ${e.record.sourcePath}`},score:e.score});E=E.sort((e,t)=>t.score-e.score).slice(0,d),re=` + ${n.length} workspace(s)`}finally{await i()}}}if(S===`file`&&E.length>1){let e=new Map;for(let t of E){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}]})}E=[...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(E.length>1){let e=E[0].score,t=Math.max(e*.4,.1);E=E.filter(e=>e.score>=t)}let ie={extracted:3,inferred:2,ambiguous:1};if(y){let e=ie[y]??0;E=E.filter(t=>(t.record.confidence?ie[t.record.confidence]??2:2)>=e)}if(E.length===0){if(o?.available)try{let r=(await o.createMessage({prompt:`The search query "${e}" returned 0 results in AI Kit code search. Suggest ONE alternative search query that might find relevant results. Reply with ONLY the alternative query, nothing else.`,systemPrompt:`You are a search query optimizer for AI Kit code search. Generate a single alternative query.`,maxTokens:100,timeoutMs:1e4})).text.trim().split(`
3032
+ `)[0].slice(0,500);if(r&&r!==e){let i=f===`keyword`||!te?await n.ftsSearch(r,T):await n.search(await t.embedQuery(r),T);i.length>0&&(E=i,O=`> _Original query "${e}" returned 0 results. Auto-reformulated to "${r}"._\n\n`,c_.debug(`Smart search fallback succeeded`,{originalQuery:e,altQuery:r,resultCount:i.length}))}}catch(e){c_.debug(`Smart search fallback failed`,{error:String(e)})}if(E.length===0){let t=yt({text:`No results found for the given query.`,query:e,searchMode:f,limit:d,results:[],durationMs:Date.now()-w}),n=yl(t.summary);return{content:[{type:`text`,text:bl(t.summary,n)}],isError:!t.ok,structuredContent:{...t.data??{results:[],totalResults:0,searchMode:f,query:e},ref:n}}}}let k,ae;if(b>0&&!r&&(ae="> **Note:** `graph_hops` was set but no graph store is available. Graph augmentation skipped."),b>0&&r)try{let e=await Lt(r,E.map(e=>({recordId:e.record.id,score:e.score,sourcePath:e.record.sourcePath})),{hops:b,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(`
3033
3033
  `),n=new Map;for(let e of t.graphContext.nodes)n.set(e.id,e.name);let r=t.graphContext.edges.slice(0,5).map(e=>` - ${n.get(e.fromId)??e.fromId} —[${e.type}]→ ${n.get(e.toId)??e.toId}`).join(`
3034
3034
  `),i=[`- **Graph Context** (${b} hop${b>1?`s`:``}):`];e&&i.push(` Entities:\n${e}`),r&&i.push(` Relationships:\n${r}`),k.set(t.recordId,i.join(`
3035
- `))}}catch(e){s_.warn(`Graph augmentation failed`,M(e)),ae=`> **Note:** Graph augmentation failed. Results shown without graph context.`}let oe=Date.now();for(let e of E)if(e.record.origin===`curated`&&e.record.indexedAt){let t=oe-new Date(e.record.indexedAt).getTime(),n=Math.max(0,t/864e5);e.score*=.95**n}if(E.sort((e,t)=>t.score-e.score),E=nt(E),s)for(let e of E){if(e.record.origin!==`curated`)continue;let t=id(e.record.sourcePath);t&&c_(s,t,c,l)}let se=f_(x,E.length),ce=!1,le=E.map((e,t)=>{let n=e.record,r=`### Result ${t+1} (score: ${e.score.toFixed(3)})`,i=[`- **Source**: ${n.sourcePath}`,n.headingPath?`- **Section**: ${n.headingPath}`:null,`- **Type**: ${n.contentType}`,n.startLine?`- **Lines**: ${n.startLine}-${n.endLine}`:null,n.origin===`indexed`?null:`- **Origin**: ${n.origin}`,n.category?`- **Category**: ${n.category}`:null,n.tags?.length?`- **Tags**: ${n.tags.join(`, `)}`:null,k?.get(n.id)??null].filter(Boolean).join(`
3036
- `),{body:a,truncated:o}=p_(n,se);return ce||=o,`${r}\n${i}\n\n${a}${o?`\n\n_Full content: use \`lookup\` on \`${n.sourcePath}\`._`:``}`}).join(`
3035
+ `))}}catch(e){c_.warn(`Graph augmentation failed`,M(e)),ae=`> **Note:** Graph augmentation failed. Results shown without graph context.`}let oe=Date.now();for(let e of E)if(e.record.origin===`curated`&&e.record.indexedAt){let t=oe-new Date(e.record.indexedAt).getTime(),n=Math.max(0,t/864e5);e.score*=.95**n}if(E.sort((e,t)=>t.score-e.score),E=nt(E),s)for(let e of E){if(e.record.origin!==`curated`)continue;let t=id(e.record.sourcePath);t&&l_(s,t,c,l)}let se=p_(x,E.length),ce=!1,le=E.map((e,t)=>{let n=e.record,r=`### Result ${t+1} (score: ${e.score.toFixed(3)})`,i=[`- **Source**: ${n.sourcePath}`,n.headingPath?`- **Section**: ${n.headingPath}`:null,`- **Type**: ${n.contentType}`,n.startLine?`- **Lines**: ${n.startLine}-${n.endLine}`:null,n.origin===`indexed`?null:`- **Origin**: ${n.origin}`,n.category?`- **Category**: ${n.category}`:null,n.tags?.length?`- **Tags**: ${n.tags.join(`, `)}`:null,k?.get(n.id)??null].filter(Boolean).join(`
3036
+ `),{body:a,truncated:o}=m_(n,se);return ce||=o,`${r}\n${i}\n\n${a}${o?`\n\n_Full content: use \`lookup\` on \`${n.sourcePath}\`._`:``}`}).join(`
3037
3037
 
3038
3038
  ---
3039
3039
 
3040
- `),ue=(f===`hybrid`?`hybrid (vector + keyword RRF)`:f===`keyword`?`keyword (FTS)`:`semantic (vector)`)+re,de=v_(E,e),fe=de.length>0?`\n_Distinctive terms: ${de.map(e=>`\`${e}\``).join(`, `)}_`:``,pe=await b_(n,E),me=[];if(E.length===0)me.push("`reindex` — no results found, index may be stale"),me.push("`find` — try federated search with glob/regex");else{let e=E[0]?.record.sourcePath;e&&me.push(`\`lookup\` — see all chunks from \`${e}\``),me.push("`symbol` — resolve a specific symbol from the results"),me.push("`compact` — compress a result file for focused reading"),me.push("reuse `ctxc_` ref above to avoid re-querying")}let he=[ae?`${ae}\n\n`:``,pe?`${pe}\n\n`:``,le,`\n\n---\n_Search mode: ${ue} | ${E.length} results_${fe}`,`\n_Next: ${me.join(` | `)}_`],ge=O+he.join(``),_e=!1;if(x){let e=Vn(ge,x);_e=e!==ge,ge=e}_e||=ce;let ve=E.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}:{}})),ye=[ae,pe].filter(e=>!!e),A=yt({text:ge,query:e,searchMode:f,limit:d,results:ve,durationMs:Date.now()-w,truncated:_e,caveats:ye}),be=yl(A.summary),xe=new Set,Se=[];for(let e of E){if(e.record.origin!==`curated`||e.record.sourcePath.startsWith(`[`))continue;let t=id(e.record.sourcePath);if(!t)continue;let n=nd(t,e.record.headingPath??t);n&&!xe.has(n.uri)&&(xe.add(n.uri),Se.push(n))}return{content:[{type:`text`,text:bl(A.summary,be)},...Se],isError:!A.ok,structuredContent:{...A.data??{results:[],totalResults:0,searchMode:f,query:e},ref:be}}}catch(t){s_.error(`Search failed`,M(t));let n=yt({text:`Search failed: ${t instanceof Error?t.message:String(t)}`,query:e??``,searchMode:f??`hybrid`,limit:d,results:[],durationMs:Date.now()-w}),r=yl(n.summary);return{content:[{type:`text`,text:bl(n.summary,r)}],structuredContent:{...n.data??{results:[],totalResults:0,searchMode:f??`hybrid`,query:e??``},ref:r}}}})}const S_=1e4,C_={defaultTtlSeconds:300,defaultLeaseTtlMinutes:10,globalEnabled:!1};function w_(e){return e??C_}function T_(e,t){let n=e.trim();if(!n)throw Error(`${t} is required`);return n}function E_(e,t,n){let r=T_(e,t);if(r.length>n)throw Error(`${t} exceeds max length of ${n}`);return r}function D_(e,t){if(!Number.isFinite(e)||e<=0)throw Error(`${t} must be greater than 0`);return Math.trunc(e)}function O_(e,t=!1,n){T_(e,`workspace`);let r=w_(n);if(!t)return e;if(!r.globalEnabled)throw Error(`Global signal scope is disabled`);return`__global__`}function k_(e,t,n){let r=w_(n),i=O_(t.workspace,t.global??!1,r),a=E_(t.key,`key`,500),o=E_(t.value,`value`,S_),s=t.agent?E_(t.agent,`agent`,500):void 0,c=D_(t.ttlSeconds??r.defaultTtlSeconds,`ttlSeconds`);return e.signalPost(i,a,o,s,c)}function A_(e,t,n){let r=T_(t,`workspace`),i=E_(n,`key`,500);return e.signalGet(r,i)}function j_(e,t){let n=T_(t,`workspace`);return e.signalList(n)}function M_(e,t,n){let r=T_(t,`workspace`),i=n===void 0?void 0:E_(n,`key`,500);return e.signalClear(r,i)}function N_(e,t,n){let r=w_(n),i=E_(t.resource,`resource`,500),a=E_(t.holder,`holder`,500),o=T_(t.workspace,`workspace`),s=t.intent?E_(t.intent,`intent`,S_):void 0,c=D_(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 P_(e,t,n,r){let i=T_(t,`workspace`),a=E_(n,`resource`,500),o=E_(r,`holder`,500);return e.leaseRelease(a,o,i)}function F_(e,t){let n=T_(t,`workspace`);return e.leaseList(n)}const I_=A(`tools:session`);function $(e,t){if(e==null)throw Error(`${t} is required`)}function L_(e,t){if(!e||e.length===0)throw Error(`${t} are required`)}const R_={action:L.enum(`signal.post,signal.get,signal.list,signal.clear,signal.lease,signal.unlease,signal.leases,compliance.score,session.digest,stash.set,stash.get,stash.list,stash.delete,stash.clear,checkpoint.save,checkpoint.load,checkpoint.list,checkpoint.latest,checkpoint.diff,checkpoint.history,checkpoint.gc,workset.save,workset.get,workset.list,workset.delete,workset.add,workset.remove,lane.create,lane.list,lane.status,lane.diff,lane.merge,lane.discard,lane.lease,lane.unlease,lane.leases`.split(`,`)).describe(`Namespaced session action to perform (e.g. signal.post, stash.set, checkpoint.save)`),workspace:L.string().optional().describe(`Workspace identifier`),key:L.string().optional().describe(`Key (for signal get/post/clear, stash get/set/delete)`),value:L.string().optional().describe(`Value (for signal post, stash set)`),agent:L.string().optional().describe(`Agent identifier (for signal lease, lane lease)`),resource:L.string().optional().describe(`Resource path (for signal lease/unlease)`),holder:L.string().optional().describe(`Lease holder ID (for signal 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 signal scope (default: false)`),last_n:L.number().min(1).max(500).optional().describe(`Max recent replay entries to score`),scope:L.enum([`tools`,`stash`,`all`]).optional().describe(`Digest scope`),since:L.string().optional().describe(`ISO timestamp — include activity after this time`),last:L.number().min(1).max(500).optional().describe(`Max replay entries to consider`),focus:L.string().optional().describe(`Focus query — prioritize entries matching this topic`),mode:L.enum([`deterministic`,`sampling`]).optional().describe(`Summary mode`),token_budget:L.number().min(100).max(8e3).optional().describe(`Target token budget`),persist:L.boolean().optional().describe(`Auto-save digest to stash for crash recovery`),label:L.string().optional().describe(`Checkpoint label / lane name / workset name`),data:L.string().max(5e5).optional().describe(`JSON object string for checkpoint save`),notes:L.string().max(1e4).optional().describe(`Optional notes for checkpoint save`),from_id:L.string().optional().describe(`Checkpoint ID to diff FROM`),to_id:L.string().optional().describe(`Checkpoint ID to diff TO`),limit:L.number().min(1).max(50).optional().describe(`Max entries to return`),keep_last:L.number().min(1).max(100).optional().describe(`Keep N recent checkpoints per label (gc)`),max_age_days:L.number().min(1).optional().describe(`Delete checkpoints older than N days (gc)`),dry_run:L.boolean().optional().describe(`Preview changes without deleting (gc)`),name:L.string().optional().describe(`Workset name or lane name`),files:L.array(L.string()).optional().describe(`File paths for workset/lane operations`),description:L.string().optional().describe(`Description (for workset save)`),id:L.string().optional().describe(`Lease ID (for lane unlease)`),symbols:L.array(L.string()).optional().describe(`Symbol names within files (for lane lease)`),ttl_minutes:L.number().optional().describe(`Lease TTL in minutes (for lane lease)`)};function z_(e,t,n){let r=U(`session`);e.registerTool(`session`,{title:r.title,description:`Unified session management — signals, compliance scoring, session digest, stash, checkpoints, worksets, and lanes. Use namespaced actions like signal.post, stash.set, checkpoint.save, workset.list, lane.create.`,inputSchema:R_,annotations:r.annotations},J(`session`,async e=>{try{let r=e.action,[i]=r.split(`.`);switch(i){case`signal`:return B_(t,r,e);case`compliance`:return V_(r,e);case`session`:return await H_(t,n,r,e);case`stash`:return U_(t,r,e);case`checkpoint`:return W_(t,r,e);case`workset`:return G_(r,e);case`lane`:return K_(r,e);default:throw Error(`Unknown session action namespace: ${i}`)}}catch(e){return I_.error(`Session operation failed`,M(e)),q(`INTERNAL`,`Session operation failed: ${e instanceof Error?e.message:String(e)}`)}}))}function B_(e,t,n){if(!e)throw Error(`stateStore is required for signal operations`);let{workspace:r,key:i,value:a,agent:o,resource:s,holder:c,intent:l,ttl:u,global:d}=n,f=C_;switch(t){case`signal.post`:{if($(i,`key`),a===void 0)throw Error(`value is required for signal.post`);let t=k_(e,{workspace:r,key:i,value:a,agent:o,ttlSeconds:u,global:d},f);return{content:[{type:`text`,text:JSON.stringify({id:t},null,2)}],structuredContent:{id:t}}}case`signal.get`:{$(i,`key`);let t=A_(e,O_(r,d??!1,f),i);return{content:[{type:`text`,text:t.length===0?`[]`:JSON.stringify(t,null,2)}],structuredContent:{signals:t}}}case`signal.list`:{let t=j_(e,O_(r,d??!1,f));return{content:[{type:`text`,text:t.length===0?`[]`:JSON.stringify(t,null,2)}],structuredContent:{signals:t}}}case`signal.clear`:{let t=M_(e,O_(r,d??!1,f),i);return{content:[{type:`text`,text:JSON.stringify({cleared:t},null,2)}],structuredContent:{cleared:t}}}case`signal.lease`:{$(s,`resource`),$(c,`holder`);let t=N_(e,{resource:s,holder:c,workspace:r,intent:l,ttlMinutes:u},f);return{content:[{type:`text`,text:JSON.stringify(t,null,2)}],structuredContent:t}}case`signal.unlease`:{$(s,`resource`),$(c,`holder`);let t=P_(e,r,s,c);return{content:[{type:`text`,text:JSON.stringify({released:t},null,2)}],structuredContent:{released:t}}}case`signal.leases`:{let t=F_(e,r);return{content:[{type:`text`,text:t.length===0?`[]`:JSON.stringify(t,null,2)}],structuredContent:{leases:t}}}default:throw Error(`Unknown signal action: ${t}`)}}function V_(e,t){switch(e){case`compliance.score`:{let e=t.last_n??50;return{content:[{type:`text`,text:q_(On(yn({last:e}),{lastN:e}))}]}}default:throw Error(`Unknown compliance action: ${e}`)}}async function H_(e,t,n,r){switch(n){case`session.digest`:{let n={scope:r.scope,since:r.since,last:r.last,focus:r.focus,mode:r.mode??`deterministic`,tokenBudget:r.token_budget??2e3,persist:r.persist??!0},i=e?{stateStore:e}:void 0;return{content:[{type:`text`,text:(n.mode===`sampling`&&t?.available?await An(n,async(e,n,r)=>(await t.createMessage({prompt:e,systemPrompt:n,maxTokens:r})).text,i):kn(n,i)).digest}]}}default:throw Error(`Unknown session action: ${n}`)}}function U_(e,t,n){if(!e)throw Error(`stateStore is required for stash operations`);let{key:r,value:i}=n;switch(t){case`stash.set`:{$(r,`key`);let t=Fn(e,r,Y_(i??``));return{content:[{type:`text`,text:`Stored stash entry "${t.key}" (${t.type}) at ${t.storedAt}.`}]}}case`stash.get`:{$(r,`key`);let t=Nn(e,r);return{content:[{type:`text`,text:t?JSON.stringify(t):`Stash entry "${r}" not found.`}]}}case`stash.list`:{let t=Pn(e);return{content:[{type:`text`,text:t.length===0?`Stash is empty.`:t.map(e=>`- ${e.key} (${e.type}) — ${e.storedAt}`).join(`
3041
- `)}]}}case`stash.delete`:return $(r,`key`),{content:[{type:`text`,text:Mn(e,r)?`Deleted stash entry "${r}".`:`Stash entry "${r}" not found.`}]};case`stash.clear`:{let t=jn(e);return{content:[{type:`text`,text:`Cleared ${t} stash entr${t===1?`y`:`ies`}.`}]}}default:throw Error(`Unknown stash action: ${t}`)}}function W_(e,t,n){if(!e)throw Error(`stateStore is required for checkpoint operations`);let{label:r,data:i,notes:a,from_id:o,to_id:s,limit:c,keep_last:l,max_age_days:u,dry_run:d}=n;switch(t){case`checkpoint.save`:return $(r,`label`),{content:[{type:`text`,text:J_(ft(e,r,X_(i),{notes:a}))}]};case`checkpoint.load`:{$(r,`label`);let t=dt(e,r);return{content:[{type:`text`,text:t?J_(t):`Checkpoint "${r}" not found.`}]}}case`checkpoint.list`:{let t=ut(e,{label:r,limit:c});return{content:[{type:`text`,text:t.length===0?`No checkpoints saved.`:t.map(e=>`- ${e.id} — ${e.label} (${e.createdAt})`).join(`
3042
- `)}]}}case`checkpoint.latest`:{let t=lt(e,{label:r});return{content:[{type:`text`,text:t?J_(t):`No checkpoints saved.`}]}}case`checkpoint.diff`:{$(o,`from_id`),$(s,`to_id`);let t=ot(e,o,s);return t?{content:[{type:`text`,text:[`## Checkpoint Diff: ${o} → ${s}`,t.added.length?`**Added:** ${t.added.join(`, `)}`:``,t.removed.length?`**Removed:** ${t.removed.join(`, `)}`:``,t.modified.length?`**Modified:** ${t.modified.join(`, `)}`:``,!t.added.length&&!t.removed.length&&!t.modified.length?`No differences found.`:``].filter(Boolean).join(`
3040
+ `),ue=(f===`hybrid`?`hybrid (vector + keyword RRF)`:f===`keyword`?`keyword (FTS)`:`semantic (vector)`)+re,de=y_(E,e),fe=de.length>0?`\n_Distinctive terms: ${de.map(e=>`\`${e}\``).join(`, `)}_`:``,pe=await x_(n,E),me=[];if(E.length===0)me.push("`reindex` — no results found, index may be stale"),me.push("`find` — try federated search with glob/regex");else{let e=E[0]?.record.sourcePath;e&&me.push(`\`lookup\` — see all chunks from \`${e}\``),me.push("`symbol` — resolve a specific symbol from the results"),me.push("`compact` — compress a result file for focused reading"),me.push("reuse `ctxc_` ref above to avoid re-querying")}let he=[ae?`${ae}\n\n`:``,pe?`${pe}\n\n`:``,le,`\n\n---\n_Search mode: ${ue} | ${E.length} results_${fe}`,`\n_Next: ${me.join(` | `)}_`],ge=O+he.join(``),_e=!1;if(x){let e=Vn(ge,x);_e=e!==ge,ge=e}_e||=ce;let ve=E.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}:{}})),ye=[ae,pe].filter(e=>!!e),A=yt({text:ge,query:e,searchMode:f,limit:d,results:ve,durationMs:Date.now()-w,truncated:_e,caveats:ye}),be=yl(A.summary),xe=new Set,Se=[];for(let e of E){if(e.record.origin!==`curated`||e.record.sourcePath.startsWith(`[`))continue;let t=id(e.record.sourcePath);if(!t)continue;let n=nd(t,e.record.headingPath??t);n&&!xe.has(n.uri)&&(xe.add(n.uri),Se.push(n))}return{content:[{type:`text`,text:bl(A.summary,be)},...Se],isError:!A.ok,structuredContent:{...A.data??{results:[],totalResults:0,searchMode:f,query:e},ref:be}}}catch(t){c_.error(`Search failed`,M(t));let n=yt({text:`Search failed: ${t instanceof Error?t.message:String(t)}`,query:e??``,searchMode:f??`hybrid`,limit:d,results:[],durationMs:Date.now()-w}),r=yl(n.summary);return{content:[{type:`text`,text:bl(n.summary,r)}],structuredContent:{...n.data??{results:[],totalResults:0,searchMode:f??`hybrid`,query:e??``},ref:r}}}})}const C_=1e4,w_={defaultTtlSeconds:300,defaultLeaseTtlMinutes:10,globalEnabled:!1};function T_(e){return e??w_}function E_(e,t){let n=e.trim();if(!n)throw Error(`${t} is required`);return n}function D_(e,t,n){let r=E_(e,t);if(r.length>n)throw Error(`${t} exceeds max length of ${n}`);return r}function O_(e,t){if(!Number.isFinite(e)||e<=0)throw Error(`${t} must be greater than 0`);return Math.trunc(e)}function k_(e,t=!1,n){E_(e,`workspace`);let r=T_(n);if(!t)return e;if(!r.globalEnabled)throw Error(`Global signal scope is disabled`);return`__global__`}function A_(e,t,n){let r=T_(n),i=k_(t.workspace,t.global??!1,r),a=D_(t.key,`key`,500),o=D_(t.value,`value`,C_),s=t.agent?D_(t.agent,`agent`,500):void 0,c=O_(t.ttlSeconds??r.defaultTtlSeconds,`ttlSeconds`);return e.signalPost(i,a,o,s,c)}function j_(e,t,n){let r=E_(t,`workspace`),i=D_(n,`key`,500);return e.signalGet(r,i)}function M_(e,t){let n=E_(t,`workspace`);return e.signalList(n)}function N_(e,t,n){let r=E_(t,`workspace`),i=n===void 0?void 0:D_(n,`key`,500);return e.signalClear(r,i)}function P_(e,t,n){let r=T_(n),i=D_(t.resource,`resource`,500),a=D_(t.holder,`holder`,500),o=E_(t.workspace,`workspace`),s=t.intent?D_(t.intent,`intent`,C_):void 0,c=O_(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 F_(e,t,n,r){let i=E_(t,`workspace`),a=D_(n,`resource`,500),o=D_(r,`holder`,500);return e.leaseRelease(a,o,i)}function I_(e,t){let n=E_(t,`workspace`);return e.leaseList(n)}const L_=A(`tools:session`);function $(e,t){if(e==null)throw Error(`${t} is required`)}function R_(e,t){if(!e||e.length===0)throw Error(`${t} are required`)}const z_={action:L.enum(`signal.post,signal.get,signal.list,signal.clear,signal.lease,signal.unlease,signal.leases,compliance.score,session.digest,stash.set,stash.get,stash.list,stash.delete,stash.clear,checkpoint.save,checkpoint.load,checkpoint.list,checkpoint.latest,checkpoint.diff,checkpoint.history,checkpoint.gc,workset.save,workset.get,workset.list,workset.delete,workset.add,workset.remove,lane.create,lane.list,lane.status,lane.diff,lane.merge,lane.discard,lane.lease,lane.unlease,lane.leases`.split(`,`)).describe(`Namespaced session action to perform (e.g. signal.post, stash.set, checkpoint.save)`),workspace:L.string().optional().describe(`Workspace identifier`),key:L.string().optional().describe(`Key (for signal get/post/clear, stash get/set/delete)`),value:L.string().optional().describe(`Value (for signal post, stash set)`),agent:L.string().optional().describe(`Agent identifier (for signal lease, lane lease)`),resource:L.string().optional().describe(`Resource path (for signal lease/unlease)`),holder:L.string().optional().describe(`Lease holder ID (for signal 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 signal scope (default: false)`),last_n:L.number().min(1).max(500).optional().describe(`Max recent replay entries to score`),scope:L.enum([`tools`,`stash`,`all`]).optional().describe(`Digest scope`),since:L.string().optional().describe(`ISO timestamp — include activity after this time`),last:L.number().min(1).max(500).optional().describe(`Max replay entries to consider`),focus:L.string().optional().describe(`Focus query — prioritize entries matching this topic`),mode:L.enum([`deterministic`,`sampling`]).optional().describe(`Summary mode`),token_budget:L.number().min(100).max(8e3).optional().describe(`Target token budget`),persist:L.boolean().optional().describe(`Auto-save digest to stash for crash recovery`),label:L.string().optional().describe(`Checkpoint label / lane name / workset name`),data:L.string().max(5e5).optional().describe(`JSON object string for checkpoint save`),notes:L.string().max(1e4).optional().describe(`Optional notes for checkpoint save`),from_id:L.string().optional().describe(`Checkpoint ID to diff FROM`),to_id:L.string().optional().describe(`Checkpoint ID to diff TO`),limit:L.number().min(1).max(50).optional().describe(`Max entries to return`),keep_last:L.number().min(1).max(100).optional().describe(`Keep N recent checkpoints per label (gc)`),max_age_days:L.number().min(1).optional().describe(`Delete checkpoints older than N days (gc)`),dry_run:L.boolean().optional().describe(`Preview changes without deleting (gc)`),name:L.string().optional().describe(`Workset name or lane name`),files:L.array(L.string()).optional().describe(`File paths for workset/lane operations`),description:L.string().optional().describe(`Description (for workset save)`),id:L.string().optional().describe(`Lease ID (for lane unlease)`),symbols:L.array(L.string()).optional().describe(`Symbol names within files (for lane lease)`),ttl_minutes:L.number().optional().describe(`Lease TTL in minutes (for lane lease)`)};function B_(e,t,n){let r=U(`session`);e.registerTool(`session`,{title:r.title,description:`Unified session management — signals, compliance scoring, session digest, stash, checkpoints, worksets, and lanes. Use namespaced actions like signal.post, stash.set, checkpoint.save, workset.list, lane.create.`,inputSchema:z_,annotations:r.annotations},J(`session`,async e=>{try{let r=e.action,[i]=r.split(`.`);switch(i){case`signal`:return V_(t,r,e);case`compliance`:return H_(r,e);case`session`:return await U_(t,n,r,e);case`stash`:return W_(t,r,e);case`checkpoint`:return G_(t,r,e);case`workset`:return K_(r,e);case`lane`:return q_(r,e);default:throw Error(`Unknown session action namespace: ${i}`)}}catch(e){return L_.error(`Session operation failed`,M(e)),q(`INTERNAL`,`Session operation failed: ${e instanceof Error?e.message:String(e)}`)}}))}function V_(e,t,n){if(!e)throw Error(`stateStore is required for signal operations`);let{workspace:r,key:i,value:a,agent:o,resource:s,holder:c,intent:l,ttl:u,global:d}=n,f=w_;switch(t){case`signal.post`:{if($(i,`key`),a===void 0)throw Error(`value is required for signal.post`);let t=A_(e,{workspace:r,key:i,value:a,agent:o,ttlSeconds:u,global:d},f);return{content:[{type:`text`,text:JSON.stringify({id:t},null,2)}],structuredContent:{id:t}}}case`signal.get`:{$(i,`key`);let t=j_(e,k_(r,d??!1,f),i);return{content:[{type:`text`,text:t.length===0?`[]`:JSON.stringify(t,null,2)}],structuredContent:{signals:t}}}case`signal.list`:{let t=M_(e,k_(r,d??!1,f));return{content:[{type:`text`,text:t.length===0?`[]`:JSON.stringify(t,null,2)}],structuredContent:{signals:t}}}case`signal.clear`:{let t=N_(e,k_(r,d??!1,f),i);return{content:[{type:`text`,text:JSON.stringify({cleared:t},null,2)}],structuredContent:{cleared:t}}}case`signal.lease`:{$(s,`resource`),$(c,`holder`);let t=P_(e,{resource:s,holder:c,workspace:r,intent:l,ttlMinutes:u},f);return{content:[{type:`text`,text:JSON.stringify(t,null,2)}],structuredContent:t}}case`signal.unlease`:{$(s,`resource`),$(c,`holder`);let t=F_(e,r,s,c);return{content:[{type:`text`,text:JSON.stringify({released:t},null,2)}],structuredContent:{released:t}}}case`signal.leases`:{let t=I_(e,r);return{content:[{type:`text`,text:t.length===0?`[]`:JSON.stringify(t,null,2)}],structuredContent:{leases:t}}}default:throw Error(`Unknown signal action: ${t}`)}}function H_(e,t){switch(e){case`compliance.score`:{let e=t.last_n??50;return{content:[{type:`text`,text:J_(On(yn({last:e}),{lastN:e}))}]}}default:throw Error(`Unknown compliance action: ${e}`)}}async function U_(e,t,n,r){switch(n){case`session.digest`:{let n={scope:r.scope,since:r.since,last:r.last,focus:r.focus,mode:r.mode??`deterministic`,tokenBudget:r.token_budget??2e3,persist:r.persist??!0},i=e?{stateStore:e}:void 0;return{content:[{type:`text`,text:(n.mode===`sampling`&&t?.available?await An(n,async(e,n,r)=>(await t.createMessage({prompt:e,systemPrompt:n,maxTokens:r})).text,i):kn(n,i)).digest}]}}default:throw Error(`Unknown session action: ${n}`)}}function W_(e,t,n){if(!e)throw Error(`stateStore is required for stash operations`);let{key:r,value:i}=n;switch(t){case`stash.set`:{$(r,`key`);let t=Fn(e,r,X_(i??``));return{content:[{type:`text`,text:`Stored stash entry "${t.key}" (${t.type}) at ${t.storedAt}.`}]}}case`stash.get`:{$(r,`key`);let t=Nn(e,r);return{content:[{type:`text`,text:t?JSON.stringify(t):`Stash entry "${r}" not found.`}]}}case`stash.list`:{let t=Pn(e);return{content:[{type:`text`,text:t.length===0?`Stash is empty.`:t.map(e=>`- ${e.key} (${e.type}) — ${e.storedAt}`).join(`
3041
+ `)}]}}case`stash.delete`:return $(r,`key`),{content:[{type:`text`,text:Mn(e,r)?`Deleted stash entry "${r}".`:`Stash entry "${r}" not found.`}]};case`stash.clear`:{let t=jn(e);return{content:[{type:`text`,text:`Cleared ${t} stash entr${t===1?`y`:`ies`}.`}]}}default:throw Error(`Unknown stash action: ${t}`)}}function G_(e,t,n){if(!e)throw Error(`stateStore is required for checkpoint operations`);let{label:r,data:i,notes:a,from_id:o,to_id:s,limit:c,keep_last:l,max_age_days:u,dry_run:d}=n;switch(t){case`checkpoint.save`:return $(r,`label`),{content:[{type:`text`,text:Y_(ft(e,r,Z_(i),{notes:a}))}]};case`checkpoint.load`:{$(r,`label`);let t=dt(e,r);return{content:[{type:`text`,text:t?Y_(t):`Checkpoint "${r}" not found.`}]}}case`checkpoint.list`:{let t=ut(e,{label:r,limit:c});return{content:[{type:`text`,text:t.length===0?`No checkpoints saved.`:t.map(e=>`- ${e.id} — ${e.label} (${e.createdAt})`).join(`
3042
+ `)}]}}case`checkpoint.latest`:{let t=lt(e,{label:r});return{content:[{type:`text`,text:t?Y_(t):`No checkpoints saved.`}]}}case`checkpoint.diff`:{$(o,`from_id`),$(s,`to_id`);let t=ot(e,o,s);return t?{content:[{type:`text`,text:[`## Checkpoint Diff: ${o} → ${s}`,t.added.length?`**Added:** ${t.added.join(`, `)}`:``,t.removed.length?`**Removed:** ${t.removed.join(`, `)}`:``,t.modified.length?`**Modified:** ${t.modified.join(`, `)}`:``,!t.added.length&&!t.removed.length&&!t.modified.length?`No differences found.`:``].filter(Boolean).join(`
3043
3043
  `)}]}:{content:[{type:`text`,text:`One or both checkpoints not found.`}]}}case`checkpoint.history`:{$(r,`label`);let t=ct(e,r,{limit:c??20});return t.length===0?{content:[{type:`text`,text:`No history found for "${r}".`}]}:{content:[{type:`text`,text:`## History: ${r}\n${t.map(e=>`- ${e.sha?e.sha.slice(0,8):e.id} — ${e.createdAt}${e.label?` (${e.label})`:``}`).join(`
3044
3044
  `)}`}]}}case`checkpoint.gc`:{let t=st(e,{label:r,keepLast:l,maxAgeDays:u,dryRun:d});return{content:[{type:`text`,text:[`## Checkpoint GC${t.labels.length?`: ${t.labels.join(`, `)}`:``}`,`Deleted: ${t.deleted}`,`Kept: ${t.kept}`,`Mode: ${d??!0?`dry-run`:`delete`}`,t.deletedIds.length?`Deleted IDs: ${t.deletedIds.join(`, `)}`:`Deleted IDs: none`].join(`
3045
- `)}]}}default:throw Error(`Unknown checkpoint action: ${t}`)}}function G_(e,t){let{name:n,files:r,description:i}=t;switch(e){case`workset.save`:{$(n,`name`),L_(r,`files`);let e=Tn(n,r,{description:i});return{content:[{type:`text`,text:`Saved workset "${e.name}" with ${e.files.length} files.`}]}}case`workset.get`:{$(n,`name`);let e=Ft(n);return e?{content:[{type:`text`,text:JSON.stringify(e)}]}:{content:[{type:`text`,text:`Workset "${n}" not found.`}]}}case`workset.list`:{let e=Jt();return e.length===0?{content:[{type:`text`,text:`No worksets.`}]}:{content:[{type:`text`,text:e.map(e=>`- **${e.name}** (${e.files.length} files) — ${e.description??`no description`}`).join(`
3046
- `)}]}}case`workset.delete`:return $(n,`name`),{content:[{type:`text`,text:St(n)?`Deleted workset "${n}".`:`Workset "${n}" not found.`}]};case`workset.add`:{$(n,`name`),L_(r,`files`);let e=et(n,r);return{content:[{type:`text`,text:`Added to workset "${e.name}": now ${e.files.length} files.`}]}}case`workset.remove`:{$(n,`name`),L_(r,`files`);let e=gn(n,r);return e?{content:[{type:`text`,text:`Removed from workset "${e.name}": now ${e.files.length} files.`}]}:{content:[{type:`text`,text:`Workset "${n}" not found.`}]}}default:throw Error(`Unknown workset action: ${e}`)}}function K_(e,t){let{name:n,files:r,agent:i,intent:a,id:o,symbols:s,ttl_minutes:c}=t;switch(e){case`lane.create`:{$(n,`name`),L_(r,`files`);let e=Bt(n,r);return{content:[{type:`text`,text:JSON.stringify(e)}]}}case`lane.list`:return{content:[{type:`text`,text:JSON.stringify(Ut())}]};case`lane.status`:return $(n,`name`),{content:[{type:`text`,text:JSON.stringify(Gt(n))}]};case`lane.diff`:return $(n,`name`),{content:[{type:`text`,text:JSON.stringify(Vt(n))}]};case`lane.merge`:return $(n,`name`),{content:[{type:`text`,text:JSON.stringify(Wt(n))}]};case`lane.discard`:return $(n,`name`),{content:[{type:`text`,text:JSON.stringify({discarded:Ht(n)})}]};case`lane.lease`:{$(i,`agent`),L_(r,`files`),$(a,`intent`);let e=$e({agent:i,files:r,intent:a,symbols:s,ttl_minutes:c});return{content:[{type:`text`,text:JSON.stringify(e)}]}}case`lane.unlease`:{$(o,`id`);let e=hn({id:o});return{content:[{type:`text`,text:JSON.stringify(e)}]}}case`lane.leases`:{let e=Kt({agent:i});return{content:[{type:`text`,text:JSON.stringify(e)}]}}default:throw Error(`Unknown lane action: ${e}`)}}function q_(e){let t=[`Compliance score: ${e.score}/100`,`Calls scored: ${e.totalCalls}`,`Summary: ${e.summary}`];if(e.violations.length===0)return`${t.join(`
3045
+ `)}]}}default:throw Error(`Unknown checkpoint action: ${t}`)}}function K_(e,t){let{name:n,files:r,description:i}=t;switch(e){case`workset.save`:{$(n,`name`),R_(r,`files`);let e=Tn(n,r,{description:i});return{content:[{type:`text`,text:`Saved workset "${e.name}" with ${e.files.length} files.`}]}}case`workset.get`:{$(n,`name`);let e=Ft(n);return e?{content:[{type:`text`,text:JSON.stringify(e)}]}:{content:[{type:`text`,text:`Workset "${n}" not found.`}]}}case`workset.list`:{let e=Jt();return e.length===0?{content:[{type:`text`,text:`No worksets.`}]}:{content:[{type:`text`,text:e.map(e=>`- **${e.name}** (${e.files.length} files) — ${e.description??`no description`}`).join(`
3046
+ `)}]}}case`workset.delete`:return $(n,`name`),{content:[{type:`text`,text:St(n)?`Deleted workset "${n}".`:`Workset "${n}" not found.`}]};case`workset.add`:{$(n,`name`),R_(r,`files`);let e=et(n,r);return{content:[{type:`text`,text:`Added to workset "${e.name}": now ${e.files.length} files.`}]}}case`workset.remove`:{$(n,`name`),R_(r,`files`);let e=gn(n,r);return e?{content:[{type:`text`,text:`Removed from workset "${e.name}": now ${e.files.length} files.`}]}:{content:[{type:`text`,text:`Workset "${n}" not found.`}]}}default:throw Error(`Unknown workset action: ${e}`)}}function q_(e,t){let{name:n,files:r,agent:i,intent:a,id:o,symbols:s,ttl_minutes:c}=t;switch(e){case`lane.create`:{$(n,`name`),R_(r,`files`);let e=Bt(n,r);return{content:[{type:`text`,text:JSON.stringify(e)}]}}case`lane.list`:return{content:[{type:`text`,text:JSON.stringify(Ut())}]};case`lane.status`:return $(n,`name`),{content:[{type:`text`,text:JSON.stringify(Gt(n))}]};case`lane.diff`:return $(n,`name`),{content:[{type:`text`,text:JSON.stringify(Vt(n))}]};case`lane.merge`:return $(n,`name`),{content:[{type:`text`,text:JSON.stringify(Wt(n))}]};case`lane.discard`:return $(n,`name`),{content:[{type:`text`,text:JSON.stringify({discarded:Ht(n)})}]};case`lane.lease`:{$(i,`agent`),R_(r,`files`),$(a,`intent`);let e=$e({agent:i,files:r,intent:a,symbols:s,ttl_minutes:c});return{content:[{type:`text`,text:JSON.stringify(e)}]}}case`lane.unlease`:{$(o,`id`);let e=hn({id:o});return{content:[{type:`text`,text:JSON.stringify(e)}]}}case`lane.leases`:{let e=Kt({agent:i});return{content:[{type:`text`,text:JSON.stringify(e)}]}}default:throw Error(`Unknown lane action: ${e}`)}}function J_(e){let t=[`Compliance score: ${e.score}/100`,`Calls scored: ${e.totalCalls}`,`Summary: ${e.summary}`];if(e.violations.length===0)return`${t.join(`
3047
3047
  `)}\n\nNo violations detected.`;let n=e.violations.map(e=>`- ${e.ruleId} | ${e.tool} | ${e.timestamp}\n ${e.rule}\n Suggestion: ${e.suggestion}`);return`${t.join(`
3048
3048
  `)}\n\nViolations:\n${n.join(`
3049
- `)}`}function J_(e){let t=[e.id,`Label: ${e.label}`,`Created: ${e.createdAt}`];return e.notes&&t.push(`Notes: ${e.notes}`),t.push(``,`Data:`,JSON.stringify(e.data)),t.join(`
3050
- `)}function Y_(e){let t=e.trim();if(!t)return``;try{return JSON.parse(t)}catch{return e}}function X_(e){let t=e?.trim();if(!t)return{};let n;try{n=JSON.parse(t)}catch{throw Error(`data must be a valid JSON object string`)}if(!n||typeof n!=`object`||Array.isArray(n))throw Error(`data must be a JSON object string`);return n}let Z_={totalInputChars:0,totalOutputChars:0,callCount:0,startTime:new Date().toISOString()};function Q_(){return{...Z_}}const $_=new Map,ev=[];function tv(){return Array.from($_.entries()).map(([e,t])=>({tool:e,...t}))}function nv(){return ev}A(`auto-gc`);function rv(){let e=[...nv()];if(e.length<10)return 0;e.sort((e,t)=>e-t);let t=Math.floor(e.length*.95);return e[Math.min(t,e.length-1)]}function iv(){return{state:`warming`,p95:rv(),lastGcAt:null,gcCount:0,bufferSize:nv().length}}function av(e){if(!e||!Le(e))return;let t=I(e);if(Fe(t)!==fe.onboard)return;let n=Ie(t);if(Fe(Ie(n))===de.workspaces)return Sn(n)}function ov(e){let t=[];if(e?.skillDir)t.push(e.skillDir);else if(e?.onboardDir){let n=av(e.onboardDir);n&&t.push(n)}return t}function sv(e){return ov(e)[0]}const cv=A(`tools`),lv=14400*1e3,uv={includePrelude:L.boolean().default(!1).describe(`Include session prelude with top lessons, conventions, and last checkpoint`)};function dv(e,t,n,r=15e3){let i,a=new Promise(e=>{i=setTimeout(()=>{cv.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),cv.warn(`Status sub-operation "${n}" failed: ${e instanceof Error?e.message:String(e)}`),{value:t,timedOut:!1})),a])}function fv(e){return e.onboarded?e.onboardFreshness===`stale`||e.onboardFreshness===`unknown`?{kind:`update_onboard`,reason:`Onboard context is not fresh. Run onboard({ path: ".", update: true }) before relying on package map or architecture context.`,command:`onboard({ path: ".", update: true })`}: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 pv(e){return e.lastSourceIndexedAt??e.lastIndexedAt??null}function mv(){let e=or.get(),t=ar.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(`
3049
+ `)}`}function Y_(e){let t=[e.id,`Label: ${e.label}`,`Created: ${e.createdAt}`];return e.notes&&t.push(`Notes: ${e.notes}`),t.push(``,`Data:`,JSON.stringify(e.data)),t.join(`
3050
+ `)}function X_(e){let t=e.trim();if(!t)return``;try{return JSON.parse(t)}catch{return e}}function Z_(e){let t=e?.trim();if(!t)return{};let n;try{n=JSON.parse(t)}catch{throw Error(`data must be a valid JSON object string`)}if(!n||typeof n!=`object`||Array.isArray(n))throw Error(`data must be a JSON object string`);return n}let Q_={totalInputChars:0,totalOutputChars:0,callCount:0,startTime:new Date().toISOString()};function $_(){return{...Q_}}const ev=new Map,tv=[];function nv(){return Array.from(ev.entries()).map(([e,t])=>({tool:e,...t}))}function rv(){return tv}A(`auto-gc`);function iv(){let e=[...rv()];if(e.length<10)return 0;e.sort((e,t)=>e-t);let t=Math.floor(e.length*.95);return e[Math.min(t,e.length-1)]}function av(){return{state:`warming`,p95:iv(),lastGcAt:null,gcCount:0,bufferSize:rv().length}}function ov(e){if(!e||!Le(e))return;let t=I(e);if(Fe(t)!==fe.onboard)return;let n=Ie(t);if(Fe(Ie(n))===de.workspaces)return Sn(n)}function sv(e){let t=[];if(e?.skillDir)t.push(e.skillDir);else if(e?.onboardDir){let n=ov(e.onboardDir);n&&t.push(n)}return t}function cv(e){return sv(e)[0]}const lv=A(`tools`),uv=14400*1e3,dv={includePrelude:L.boolean().default(!1).describe(`Include session prelude with top lessons, conventions, and last checkpoint`)};function fv(e,t,n,r=15e3){let i,a=new Promise(e=>{i=setTimeout(()=>{lv.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),lv.warn(`Status sub-operation "${n}" failed: ${e instanceof Error?e.message:String(e)}`),{value:t,timedOut:!1})),a])}function pv(e){return e.onboarded?e.onboardFreshness===`stale`||e.onboardFreshness===`unknown`?{kind:`update_onboard`,reason:`Onboard context is not fresh. Run onboard({ path: ".", update: true }) before relying on package map or architecture context.`,command:`onboard({ path: ".", update: true })`}:e.indexStale?{kind:`reindex`,reason:`Index stale. Run reindex() to update.`}:e.contextPressure>70?{kind:`handoff`,reason:`Context pressure high. Consider session handoff.`}:{kind:`proceed`,reason:`Ready to work.`}:{kind:`onboard`,reason:`Index not initialized. Run onboard({ path: "." }) first.`}}function mv(e){return e.lastSourceIndexedAt??e.lastIndexedAt??null}function hv(){let e=or.get(),t=ar.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(`
3051
3051
  `):` 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(`
3052
- `)}const hv=5*6e4;let gv=null,_v=null;function vv(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 yv(){let e=Date.now();if(gv&&e-gv.ts<hv)return gv.value;try{let t=I(Kn(),`.copilot`,`.aikit-scaffold.json`);if(!N(t))return gv={value:null,ts:e},null;let n=JSON.parse(P(t,`utf-8`)).version??null;return gv={value:n,ts:e},n}catch{return gv={value:null,ts:e},null}}function bv(){let e=Date.now();if(_v&&e-_v.ts<hv)return _v.value;try{let t=I(process.cwd(),`.github`,`.aikit-scaffold.json`);if(!N(t))return _v={value:null,ts:e},null;let n=JSON.parse(P(t,`utf-8`)).version??null;return _v={value:n,ts:e},n}catch{return _v={value:null,ts:e},null}}function xv(e){let t=U(`status`);e.registerTool(`status`,{title:t.title,description:`Get the current status and statistics of the AI Kit index.`,inputSchema:uv,annotations:t.annotations},J(`status`,async()=>{let e=S(),t=yv(),n=bv(),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)**: ${or.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=O(),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`?(te(),a.push(``,`### ⬆ Upgrade Available (auto-upgrade failed, retrying)`,`- Server v${e} ≠ ${c}`,`- Error: ${o.error??`unknown`}`)):(te(),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:!!or.get(),wasmDiagnostics:ar.get(),graphStats:null,curatedCount:0,serverVersion:e,scaffoldVersion:t??null,workspaceScaffoldVersion:n??null,upgradeAvailable:r||i,contextPressure:0,nextAction:fv({onboarded:!1,indexStale:!1,contextPressure:0})};return{content:[{type:`text`,text:a.join(`
3053
- `)}],structuredContent:o}}))}function Sv(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h){let g=U(`status`);e.registerTool(`status`,{title:g.title,description:`Get the current status and statistics of the AI Kit index.`,inputSchema:uv,annotations:g.annotations},J(`status`,async({includePrelude:e=!1})=>{let g=[];try{let[_,v]=await Promise.all([dv(t.getStats(),{totalRecords:0,totalFiles:0,lastIndexedAt:null,lastSourceIndexedAt:null,contentTypeBreakdown:{},storeBackend:`unknown`,embeddingModel:`unknown`},`store.getStats`),dv(t.listSourcePaths(),[],`store.listSourcePaths`)]),y=_.value;_.timedOut&&g.push(`⚠ Index stats timed out — values may be incomplete`);let b=v.value;v.timedOut&&g.push(`⚠ File listing timed out`);let x=b.filter(e=>!e.startsWith(`.ai/curated/context/auto-`)&&!e.startsWith(`.ai/curated/workflow/auto-`)&&!e.includes(`node_modules/`)&&!e.startsWith(`.git/`)),C=b.length-x.length,w=null,T=0,D=[`## AI Kit Status`,``,`- **Total Records**: ${y.totalRecords}`,`- **Total Files**: ${y.totalFiles}`,`- **Last Indexed**: ${y.lastIndexedAt??`Never`}`,``,`### Content Types`,...Object.entries(y.contentTypeBreakdown).map(([e,t])=>`- ${e}: ${t}`),``,`### Indexed Files`,...x.slice(0,50).map(e=>`- ${e}`),x.length>50?`\n... and ${x.length-50} more files`:``,C>0?`\n_(${C} internal/auto-curated files hidden — use \`find\` to explore them)_`:``];if(n)try{let e=await dv(n.getStats(),{nodeCount:0,edgeCount:0,nodeTypes:{},edgeTypes:{}},`graphStore.getStats`);if(e.timedOut)g.push(`⚠ Graph stats timed out`),D.push(``,`### Knowledge Graph`,`- Graph stats timed out`);else{let t=e.value;w={nodes:t.nodeCount,edges:t.edgeCount},D.push(``,`### Knowledge Graph`,`- **Nodes**: ${t.nodeCount}`,`- **Edges**: ${t.edgeCount}`,...Object.entries(t.nodeTypes).map(([e,t])=>` - ${e}: ${t}`));try{let e=await dv(n.validate(),{valid:!0,danglingEdges:[],orphanNodes:[],stats:{nodeCount:0,edgeCount:0,nodeTypes:{},edgeTypes:{}}},`graphStore.validate`);if(!e.timedOut){let t=e.value;t.valid||D.push(`- **⚠ Integrity Issues**: ${t.danglingEdges.length} dangling edges`),t.orphanNodes.length>0&&D.push(`- **Orphan nodes**: ${t.orphanNodes.length}`)}}catch{}}}catch{D.push(``,`### Knowledge Graph`,`- Graph store unavailable`)}let ee=a?.onboardDir??``,ne=N(ee),re=i?.onboardComplete||ne,k=ie(ee,{lastIndexedAt:pv(y)});if(D.push(``,`### Onboard Status`,re?`- ✅ Complete${i?.onboardTimestamp?` (last: ${i.onboardTimestamp})`:``}`:'- ❌ Not run — call `onboard({ path: "." })` to analyze the codebase',`- **Onboard Directory**: \`${ee}\``),k){let e=k.packageMap.totalPackages,t=k.freshness.status===`fresh`?`✅`:k.freshness.status===`stale`?`⚠`:`❔`;D.push(`- **Onboard context**: ${k.readInstruction}`,`- **Onboard freshness**: ${t} ${k.freshness.status} (${k.freshness.reason})`,e>0?`- **Package map**: ${e} packages/containers in \`${k.packageMap.sourcePath}\``:"- **Package map**: read `structure.md` and `dependencies.md` from the onboard directory")}if(r)try{let e=await dv(r.count(),0,`curated.count`);e.timedOut?(g.push(`⚠ Curated knowledge count timed out`),D.push(``,`### Curated Knowledge`,`- Listing timed out`)):(T=e.value,D.push(``,`### Curated Knowledge`,T>0?`- ${T} entries`:'- Empty — use `knowledge({ action: "remember", ... })` to persist decisions'))}catch{D.push(``,`### Curated Knowledge`,`- Unable to read curated entries`)}let ae=Un().filter(e=>e.status===`watching`);if(ae.length>0){D.push(``,`### File Watchers`,`- **Active**: ${ae.length}`);for(let e of ae){let t=e.pendingFiles?.length??0;if(D.push(` - \`${e.path}\`: ${e.eventCount} events, ${t} pending files`),t>0&&t<=10)for(let t of e.pendingFiles)D.push(` - \`${t}\``);else t>10&&D.push(` - ${t} pending files (use \`watch({ action: 'list' })\` for details)`)}}let oe=vv(y.totalRecords,w?.nodes??0,w?.edges??0,T),se=y.lastIndexedAt?new Date(y.lastIndexedAt).getTime():0,ce=se>0?Date.now()-se:1/0,le=re&&ce>1440*60*1e3,ue=fv({onboarded:re,onboardFreshness:k?.freshness.status??null,indexStale:le,contextPressure:oe});D.push(``),D.push(`## 📊 Context Pressure: ${oe}/100`),oe>=80?D.push(`⚠️ High pressure — consider pruning stale entries or compacting context.`):oe>=50?D.push(`ℹ️ Moderate pressure — AI Kit memory is well-populated.`):D.push(`✅ Low pressure — plenty of headroom for more content.`);let de=0;if(y.lastIndexedAt){de=new Date(y.lastIndexedAt).getTime();let e=(Date.now()-de)/(1e3*60*60);D.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`)}D.push(``,`### Next Action`,`- **${ue.kind}**: ${ue.reason}`);let fe=null,pe=t;if(typeof pe.getDiagnostics==`function`)try{let e=pe.getDiagnostics();fe={adapterType:e.adapterType,vectorSearchEnabled:e.vectorSearchEnabled,ftsEnabled:e.ftsEnabled,degradedMode:e.degradedMode,dbPath:e.dbPath,dbSizeBytes:e.dbSizeBytes,embeddingDim:e.embeddingDim,vectorDtype:e.vectorDtype},D.push(``,`### Storage`,`- **Backend**: ${a?.store?.backend??`unknown`}`,`- **Adapter**: ${fe.adapterType}`,`- **Vector search**: ${fe.vectorSearchEnabled?`✅ enabled`:`⚠ disabled (FTS-only fallback)`}`,fe.dbPath?`- **DB**: ${fe.dbPath}`:``,fe.dbSizeBytes==null?``:`- **DB size**: ${(fe.dbSizeBytes/1024/1024).toFixed(2)} MB`,`- **Embedding dim**: ${fe.embeddingDim}`,`- **Vector dtype**: ${fe.vectorDtype}`)}catch{}if(o===`smart`)if(D.push(``,`### Smart Indexing`),s){let e=s();e?D.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}`):D.push(`- **Mode**: Smart (trickle)`,`- **Status**: scheduler state unavailable (init may have failed)`)}else D.push(`- **Mode**: Smart (trickle) — scheduler state unavailable`);if(h)try{let e=h.getReport(),t=h.checkThresholds(),n=Object.entries(e.counters),r=Object.entries(e.gauges);if(n.length>0||r.length>0||t.length>0){if(D.push(``,`### 📊 Metrics`),n.length>0){D.push(`**Counters:**`);for(let[e,t]of n)D.push(`- \`${e}\`: ${t}`)}if(r.length>0){D.push(`**Gauges:**`);for(let[e,t]of r)D.push(`- \`${e}\`: ${t}`)}if(t.length>0){D.push(`**⚠ Threshold violations:**`);for(let e of t)D.push(`- ${e}`)}else(n.length>0||r.length>0)&&D.push(`- ✅ All thresholds within limits`)}}catch{D.push(``,`### 📊 Metrics`,`- Metrics unavailable`)}{let e=[];if(u)try{let t=u.getStats();e.push(`- **Decision Hooks**: ${t.count} registered${t.hooks.length>0?` (IDs: ${t.hooks.map(e=>e.id).join(`, `)})`:``}`)}catch{e.push(`- **Decision Hooks**: unavailable`)}else e.push(`- **Decision Hooks**: not configured`);if(d)try{let t=d.getStats(),n=Object.entries(t.byTool).map(([e,t])=>`${e}=${t}`).join(`, `);e.push(`- **Observations**: ${t.totalObservations} total, byTool: ${n||`none`}`)}catch{e.push(`- **Observations**: unavailable`)}else e.push(`- **Observations**: not configured`);if(f)try{let t=f.getStats(),n=Object.keys(t.byName);e.push(`- **Extractors**: ${t.count} registered${n.length>0?` (IDs: ${n.join(`, `)})`:``}`)}catch{e.push(`- **Extractors**: unavailable`)}else e.push(`- **Extractors**: not configured`);if(m)try{let t=m.getStats(),n=t.skillExists?t.isStale?`⚠ Stale`:`✅ Fresh`:`❌ No skill`;e.push(`- **Skill Compiler**: ${n}, version: ${t.skillVersion}, last compiled: ${t.lastCompiledAt?new Date(t.lastCompiledAt).toLocaleString():`Never`}`)}catch{e.push(`- **Skill Compiler**: unavailable`)}else e.push(`- **Skill Compiler**: not configured`);if(p)try{let t=p.getStats();e.push(`- **Promotion Engine**: ${t.held} candidates held, ${t.promoted} promoted, ${t.observedFacts} distinct facts tracked`)}catch{e.push(`- **Promotion Engine**: unavailable`)}else e.push(`- **Promotion Engine**: not configured`);D.push(``,`### 🧩 Feature Coverage`,...e)}let ge=0;{try{let e=a?.stateDir?F(a.stateDir,`stash`):null;if(e&&N(e)){let t=Me(e).mtimeMs;t>de&&(de=t)}}catch{}let e=[];if(r)try{let t=T>0?await r.list({limit:5,orderBy:`updated`,order:`desc`}):[];for(let e of t){let t=new Date(e.updated||e.created).getTime();t>de&&(de=t)}e.push(...t)}catch{}if(ge=de>0?Date.now()-de:0,ge>=lv){let t=Math.floor(ge/36e5);if(D.push(``,`### 🌅 Session Briefing`,`_${t}+ hours since last activity — here's what to pick up:_`,``),e.length>0){D.push(`**Recent decisions/notes:**`);for(let t of e)D.push(`- **${t.title}** (${t.category??`note`}) — ${(t.contentPreview??``).slice(0,80)}…`)}D.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')}}D.push(``,`### Runtime`,mv());let _e=he.instance().getAll(),ve=_e.filter(e=>e.status!==`healthy`);if(ve.length>0){D.push(``,`### ⚠️ Subsystem Health`);for(let e of ve){let t=Math.round((Date.now()-e.since)/1e3);D.push(`- **${e.name}**: ${e.status} (${t}s ago${e.reason?` — ${e.reason}`:``})`)}}else _e.length>0&&D.push(``,`### ✅ Subsystem Health`,`- All ${_e.length} subsystems healthy`);let ye=me.getAll();if(ye.size>0){D.push(``,`### 🔌 Circuit Breakers`);for(let[e,t]of ye){let n=t.getState(),r=`- **${e}**: ${n===`closed`?`🟢`:n===`open`?`🔴`:`🟡`} ${n}`;if(n===`open`){let e=t.remainingCooldownMs();r+=` (recovery in ${Math.ceil(e/1e3)}s)`}D.push(r)}}let A=yv(),be=bv(),xe=S(),Se=A!=null&&A!==xe,Ce=be!=null&&be!==xe;if(Se||Ce){let e=O(),t=[];Se&&t.push(`user scaffold v${A}`),Ce&&t.push(`workspace scaffold v${be}`);let n=t.join(`, `);e.state===`success`?D.push(``,`### ✅ Upgrade Applied`,`- Server v${xe} — ${n} auto-upgraded successfully.`,`- _Restart the MCP server to use the updated version._`):e.state===`pending`?D.push(``,`### ⏳ Upgrade In Progress`,`- Server v${xe} ≠ ${n}`,`- Auto-upgrade is running in the background…`):e.state===`failed`?(te(),D.push(``,`### ⬆ Upgrade Available (auto-upgrade failed, retrying)`,`- Server v${xe} ≠ ${n}`,`- Error: ${e.error??`unknown`}`)):(te(),D.push(``,`### ⬆ Upgrade Available`,`- Server v${xe} ≠ ${n}`,`- Auto-upgrade triggered — check again shortly.`))}g.length>0&&D.push(``,`### ⚠ Warnings`,...g.map(e=>`- ${e}`));let we=tv();if(we.length>0){let e=we.sort((e,t)=>t.callCount-e.callCount);D.push(``,`### Tool Usage This Session`,``),D.push(`| Tool | Calls | Tokens In | Tokens Out | Errors | Avg Latency |`),D.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);D.push(`| ${t.tool} | ${t.callCount} | ${e.toLocaleString()} | ${n.toLocaleString()} | ${t.errorCount} | ${r}ms |`)}}let j=Q_();j.callCount>0&&(D.push(``),D.push(`### Session Token Usage`),D.push(`- Tool calls: ${j.callCount}`),D.push(`- Input chars: ${j.totalInputChars.toLocaleString()}`),D.push(`- Output chars: ${j.totalOutputChars.toLocaleString()}`),D.push(`- Est. input tokens: ${Math.round(j.totalInputChars/4).toLocaleString()}`),D.push(`- Est. total tokens: ${Math.round((j.totalInputChars+j.totalOutputChars)/4).toLocaleString()}`));let Te=iv();if(Te.bufferSize>=10){let e=Te.state===`healthy`?`🟢`:Te.state===`degraded`?`🔴`:`🟡`;D.push(``,`### Auto-GC: ${e} ${Te.state}`),D.push(`- p95 latency: ${Te.p95}ms | buffer: ${Te.bufferSize} samples`),Te.gcCount>0&&D.push(`- GC cycles triggered: ${Te.gcCount}`)}if(l){let e=l.getStats();if(e.totalSubscribers>0){D.push(``,`### 🔌 Hooks (EventBus Subscribers)`),D.push(`- Total subscribers: ${e.totalSubscribers}`);for(let[t,n]of Object.entries(e.byEvent))D.push(` - ${t}: ${n} subscriber(s)`);for(let t of e.subscriptions)D.push(` - ${t.name} (${t.eventType}, ${t.policy})`);if(e.autoDisabled.length>0){D.push(``),D.push(` **Auto-disabled subscribers:**`);for(let t of e.autoDisabled)D.push(` - ${t.name} (${t.id}): ${t.reason}`)}}}if(u&&u.size>0){let e=u.getStats();D.push(``,`### 🪝 Decision Hooks`),D.push(`- Total hooks: ${e.count}`);for(let t of e.hooks){let e=t.decisionTypes.join(`, `);D.push(` - ${t.id} (order=${t.order}, policy=${t.failurePolicy}, types=[${e}])`)}}if(d){let e=d.getStats();D.push(``,`### 👁 Observations`),D.push(`- Total observations: ${e.totalObservations}`),D.push(` - Success: ${e.byError.success}, Error: ${e.byError.error}`),D.push(` - Artifacts stored: ${e.artifactCount}`),D.push(` - Truncations: ${e.truncationCount}`),D.push(` - Store entries: ${e.storeSize}`);let t=Object.entries(e.byOrigin);t.length>0&&D.push(` - By origin: ${t.map(([e,t])=>`${e}=${t}`).join(`, `)}`)}if(f){let e=f.getStats();D.push(``,`### 🧩 Extractors`),D.push(`- Total extractors: ${e.count}`);for(let[t,n]of Object.entries(e.byName))D.push(` - ${t} (${n.tools} tool(s), maxFacts: ${n.maxFactsPerEvent??`default`})`)}if(p){let e=p.getStats();if(D.push(``,`### 🏆 Promotion Engine`),D.push(`- Total evaluated: ${e.totalEvaluated}`),D.push(`- Promoted: ${e.promoted}`),D.push(`- Held: ${e.held}`),D.push(`- Rejected: ${e.rejected}`),D.push(`- Superseded: ${e.superseded}`),D.push(`- Decayed: ${e.decayed}`),D.push(`- Distinct facts tracked: ${e.observedFacts}`),e.recentDecisions.length>0){D.push(` Recent decisions:`);for(let t of e.recentDecisions.slice(-5))D.push(` - ${t.decision.status}: "${t.factTitle}" (${t.decision.reason.slice(0,80)})`)}}if(m){let e=m.getStats();if(D.push(``,`### 📋 Workspace Skill`),D.push(`- **Skill exists**: ${e.skillExists?`✅`:`❌`}`),D.push(`- **Stale**: ${e.isStale?`⚠ Yes — regenerating on next trigger`:`✅ Fresh`}`),D.push(`- **Last compiled**: ${e.lastCompiledAt?new Date(e.lastCompiledAt).toLocaleString():`Never`}`),D.push(`- **Version**: ${e.skillVersion}`),D.push(`- **Total compiles**: ${e.totalCompiles}`),e.failedCompiles>0&&D.push(`- **Failed compiles**: ${e.failedCompiles}`),e.skillSize>0&&D.push(`- **Skill size**: ${e.skillSize} bytes`),e.isCompiling&&D.push(`- ⏳ **Currently compiling**`),e.pendingRegeneration&&D.push(`- ⏳ **Regeneration pending**`),e.skillQuality&&D.push(`- **Quality**: ${e.skillQuality}`),e.skillQualityErrors&&e.skillQualityErrors.length>0){D.push(`- **Quality errors (${e.skillQualityErrors.length})**:`);for(let t of e.skillQualityErrors.slice(0,3))D.push(` - ${t}`)}if(e.skillQualityWarnings&&e.skillQualityWarnings.length>0){D.push(`- **Quality warnings (${e.skillQualityWarnings.length})**:`);for(let t of e.skillQualityWarnings.slice(0,3))D.push(` - ${t}`)}let t=m?.getWarnings()??[];if(t.length>0){D.push(`- **Compiler warnings (${t.length})**:`);for(let e of t.slice(0,5))D.push(` - ${e}`);t.length>5&&D.push(` - ... and ${t.length-5} more`)}D.push(``," Read `aikit://skill/SKILL.md` to load full workspace context.")}{let e=Pt();(e.cacheSize>0||e.refReuseCount>0)&&(D.push(``,`### 🔄 Ref Reuse`),D.push(`- **Refs stored**: ${e.refStoreCount}`),D.push(`- **Refs reused**: ${e.refReuseCount}`),e.refStaleCount>0&&D.push(`- **⚠ Stale refs detected**: ${e.refStaleCount}`),D.push(`- **Cache entries**: ${e.cacheSize}`))}let M=D.join(`
3054
- `),Ee=ge>=lv,De=ov(a),Oe=e||Ee?await E(r,c,void 0,De.length>0?De:void 0,k):void 0,P=ae.length>0?ae.map(e=>({id:e.id,path:e.path,eventCount:e.eventCount,pendingFiles:e.pendingFiles??[]})):void 0,ke={totalRecords:y.totalRecords,totalFiles:y.totalFiles,lastIndexedAt:y.lastIndexedAt??null,lastSourceIndexedAt:y.lastSourceIndexedAt??null,onboarded:re,onboardDir:ee,onboard_context:k,contentTypes:y.contentTypeBreakdown,wasmAvailable:!!or.get(),wasmDiagnostics:ar.get(),graphStats:w,curatedCount:T,serverVersion:xe,scaffoldVersion:A??null,workspaceScaffoldVersion:be??null,upgradeAvailable:Se||Ce,storeBackend:a?.store?.backend,storeDiagnostics:fe??null,contextPressure:oe,nextAction:ue,workspace_skill:(()=>{if(!m)return null;try{let e=m.getStats(),t=m?.getWarnings()??[],n=e.skillExists?e.skillQuality??`fallback`:`fallback`;return{exists:e.skillExists,version:e.skillVersion,fresh:!e.isStale,quality:n,warnings:t,uri:`aikit://skill/SKILL.md`,path:e.skillPath,read_instruction:`Read aikit://skill/SKILL.md before working in this repo for full workspace context.`,last_updated:e.lastCompiledAt?new Date(e.lastCompiledAt).toISOString():null,size:e.skillSize}}catch{return null}})(),skill_warnings:m?.getWarnings(m?.resolveActiveFlowSlug()??void 0)??[],watchers:P,sessionTokens:{callCount:j.callCount,totalInputChars:j.totalInputChars,totalOutputChars:j.totalOutputChars,estInputTokens:Math.round(j.totalInputChars/4),estTotalTokens:Math.round((j.totalInputChars+j.totalOutputChars)/4),startTime:j.startTime},...Oe===void 0?{}:{prelude:Oe}};return{content:[{type:`text`,text:M+(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:ke}}catch(e){return cv.error(`Status failed`,M(e)),q(`INTERNAL`,`Status check failed: ${e instanceof Error?e.message:String(e)}`)}}))}const Cv=A(`tools`);function wv(e){return e instanceof Error?(`code`in e?e.code:void 0)===`ENOENT`||e.message.startsWith(`File not found:`)||e.message.startsWith(`Path not found:`):!1}function Tv(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},J(`web_search`,async({queries:e,limit:t,site:n,provider:r})=>{let i=e,a=async e=>{let i=await Gn({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(`
3055
- `)};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 Cv.error(`Web search failed`,M(e)),q(`INTERNAL`,`Web search failed: ${e instanceof Error?e.message:String(e)}`)}let o=await Promise.allSettled(i.map(e=>a(e))),s=[],c=0;for(let e=0;e<o.length;e++){let t=o[e];if(t.status===`fulfilled`)s.push(t.value);else{c++;let n=t.reason instanceof Error?t.reason.message:String(t.reason);Cv.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(`
3052
+ `)}const gv=5*6e4;let _v=null,vv=null;function yv(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 bv(){let e=Date.now();if(_v&&e-_v.ts<gv)return _v.value;try{let t=I(Kn(),`.copilot`,`.aikit-scaffold.json`);if(!N(t))return _v={value:null,ts:e},null;let n=JSON.parse(P(t,`utf-8`)).version??null;return _v={value:n,ts:e},n}catch{return _v={value:null,ts:e},null}}function xv(){let e=Date.now();if(vv&&e-vv.ts<gv)return vv.value;try{let t=I(process.cwd(),`.github`,`.aikit-scaffold.json`);if(!N(t))return vv={value:null,ts:e},null;let n=JSON.parse(P(t,`utf-8`)).version??null;return vv={value:n,ts:e},n}catch{return vv={value:null,ts:e},null}}function Sv(e){let t=U(`status`);e.registerTool(`status`,{title:t.title,description:`Get the current status and statistics of the AI Kit index.`,inputSchema:dv,annotations:t.annotations},J(`status`,async()=>{let e=S(),t=bv(),n=xv(),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)**: ${or.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=O(),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`?(te(),a.push(``,`### ⬆ Upgrade Available (auto-upgrade failed, retrying)`,`- Server v${e} ≠ ${c}`,`- Error: ${o.error??`unknown`}`)):(te(),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:!!or.get(),wasmDiagnostics:ar.get(),graphStats:null,curatedCount:0,serverVersion:e,scaffoldVersion:t??null,workspaceScaffoldVersion:n??null,upgradeAvailable:r||i,contextPressure:0,nextAction:pv({onboarded:!1,indexStale:!1,contextPressure:0})};return{content:[{type:`text`,text:a.join(`
3053
+ `)}],structuredContent:o}}))}function Cv(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h){let g=U(`status`);e.registerTool(`status`,{title:g.title,description:`Get the current status and statistics of the AI Kit index.`,inputSchema:dv,annotations:g.annotations},J(`status`,async({includePrelude:e=!1})=>{let g=[];try{let[_,v]=await Promise.all([fv(t.getStats(),{totalRecords:0,totalFiles:0,lastIndexedAt:null,lastSourceIndexedAt:null,contentTypeBreakdown:{},storeBackend:`unknown`,embeddingModel:`unknown`},`store.getStats`),fv(t.listSourcePaths(),[],`store.listSourcePaths`)]),y=_.value;_.timedOut&&g.push(`⚠ Index stats timed out — values may be incomplete`);let b=v.value;v.timedOut&&g.push(`⚠ File listing timed out`);let x=b.filter(e=>!e.startsWith(`.ai/curated/context/auto-`)&&!e.startsWith(`.ai/curated/workflow/auto-`)&&!e.includes(`node_modules/`)&&!e.startsWith(`.git/`)),C=b.length-x.length,w=null,T=0,D=[`## AI Kit Status`,``,`- **Total Records**: ${y.totalRecords}`,`- **Total Files**: ${y.totalFiles}`,`- **Last Indexed**: ${y.lastIndexedAt??`Never`}`,``,`### Content Types`,...Object.entries(y.contentTypeBreakdown).map(([e,t])=>`- ${e}: ${t}`),``,`### Indexed Files`,...x.slice(0,50).map(e=>`- ${e}`),x.length>50?`\n... and ${x.length-50} more files`:``,C>0?`\n_(${C} internal/auto-curated files hidden — use \`find\` to explore them)_`:``];if(n)try{let e=await fv(n.getStats(),{nodeCount:0,edgeCount:0,nodeTypes:{},edgeTypes:{}},`graphStore.getStats`);if(e.timedOut)g.push(`⚠ Graph stats timed out`),D.push(``,`### Knowledge Graph`,`- Graph stats timed out`);else{let t=e.value;w={nodes:t.nodeCount,edges:t.edgeCount},D.push(``,`### Knowledge Graph`,`- **Nodes**: ${t.nodeCount}`,`- **Edges**: ${t.edgeCount}`,...Object.entries(t.nodeTypes).map(([e,t])=>` - ${e}: ${t}`));try{let e=await fv(n.validate(),{valid:!0,danglingEdges:[],orphanNodes:[],stats:{nodeCount:0,edgeCount:0,nodeTypes:{},edgeTypes:{}}},`graphStore.validate`);if(!e.timedOut){let t=e.value;t.valid||D.push(`- **⚠ Integrity Issues**: ${t.danglingEdges.length} dangling edges`),t.orphanNodes.length>0&&D.push(`- **Orphan nodes**: ${t.orphanNodes.length}`)}}catch{}}}catch{D.push(``,`### Knowledge Graph`,`- Graph store unavailable`)}let ee=a?.onboardDir??``,ne=N(ee),re=i?.onboardComplete||ne,k=ie(ee,{lastIndexedAt:mv(y)});if(D.push(``,`### Onboard Status`,re?`- ✅ Complete${i?.onboardTimestamp?` (last: ${i.onboardTimestamp})`:``}`:'- ❌ Not run — call `onboard({ path: "." })` to analyze the codebase',`- **Onboard Directory**: \`${ee}\``),k){let e=k.packageMap.totalPackages,t=k.freshness.status===`fresh`?`✅`:k.freshness.status===`stale`?`⚠`:`❔`;D.push(`- **Onboard context**: ${k.readInstruction}`,`- **Onboard freshness**: ${t} ${k.freshness.status} (${k.freshness.reason})`,e>0?`- **Package map**: ${e} packages/containers in \`${k.packageMap.sourcePath}\``:"- **Package map**: read `structure.md` and `dependencies.md` from the onboard directory")}if(r)try{let e=await fv(r.count(),0,`curated.count`);e.timedOut?(g.push(`⚠ Curated knowledge count timed out`),D.push(``,`### Curated Knowledge`,`- Listing timed out`)):(T=e.value,D.push(``,`### Curated Knowledge`,T>0?`- ${T} entries`:'- Empty — use `knowledge({ action: "remember", ... })` to persist decisions'))}catch{D.push(``,`### Curated Knowledge`,`- Unable to read curated entries`)}let ae=Un().filter(e=>e.status===`watching`);if(ae.length>0){D.push(``,`### File Watchers`,`- **Active**: ${ae.length}`);for(let e of ae){let t=e.pendingFiles?.length??0;if(D.push(` - \`${e.path}\`: ${e.eventCount} events, ${t} pending files`),t>0&&t<=10)for(let t of e.pendingFiles)D.push(` - \`${t}\``);else t>10&&D.push(` - ${t} pending files (use \`watch({ action: 'list' })\` for details)`)}}let oe=yv(y.totalRecords,w?.nodes??0,w?.edges??0,T),se=y.lastIndexedAt?new Date(y.lastIndexedAt).getTime():0,ce=se>0?Date.now()-se:1/0,le=re&&ce>1440*60*1e3,ue=pv({onboarded:re,onboardFreshness:k?.freshness.status??null,indexStale:le,contextPressure:oe});D.push(``),D.push(`## 📊 Context Pressure: ${oe}/100`),oe>=80?D.push(`⚠️ High pressure — consider pruning stale entries or compacting context.`):oe>=50?D.push(`ℹ️ Moderate pressure — AI Kit memory is well-populated.`):D.push(`✅ Low pressure — plenty of headroom for more content.`);let de=0;if(y.lastIndexedAt){de=new Date(y.lastIndexedAt).getTime();let e=(Date.now()-de)/(1e3*60*60);D.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`)}D.push(``,`### Next Action`,`- **${ue.kind}**: ${ue.reason}`);let fe=null,pe=t;if(typeof pe.getDiagnostics==`function`)try{let e=pe.getDiagnostics();fe={adapterType:e.adapterType,vectorSearchEnabled:e.vectorSearchEnabled,ftsEnabled:e.ftsEnabled,degradedMode:e.degradedMode,dbPath:e.dbPath,dbSizeBytes:e.dbSizeBytes,embeddingDim:e.embeddingDim,vectorDtype:e.vectorDtype},D.push(``,`### Storage`,`- **Backend**: ${a?.store?.backend??`unknown`}`,`- **Adapter**: ${fe.adapterType}`,`- **Vector search**: ${fe.vectorSearchEnabled?`✅ enabled`:`⚠ disabled (FTS-only fallback)`}`,fe.dbPath?`- **DB**: ${fe.dbPath}`:``,fe.dbSizeBytes==null?``:`- **DB size**: ${(fe.dbSizeBytes/1024/1024).toFixed(2)} MB`,`- **Embedding dim**: ${fe.embeddingDim}`,`- **Vector dtype**: ${fe.vectorDtype}`)}catch{}if(o===`smart`)if(D.push(``,`### Smart Indexing`),s){let e=s();e?D.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}`):D.push(`- **Mode**: Smart (trickle)`,`- **Status**: scheduler state unavailable (init may have failed)`)}else D.push(`- **Mode**: Smart (trickle) — scheduler state unavailable`);if(h)try{let e=h.getReport(),t=h.checkThresholds(),n=Object.entries(e.counters),r=Object.entries(e.gauges);if(n.length>0||r.length>0||t.length>0){if(D.push(``,`### 📊 Metrics`),n.length>0){D.push(`**Counters:**`);for(let[e,t]of n)D.push(`- \`${e}\`: ${t}`)}if(r.length>0){D.push(`**Gauges:**`);for(let[e,t]of r)D.push(`- \`${e}\`: ${t}`)}if(t.length>0){D.push(`**⚠ Threshold violations:**`);for(let e of t)D.push(`- ${e}`)}else(n.length>0||r.length>0)&&D.push(`- ✅ All thresholds within limits`)}}catch{D.push(``,`### 📊 Metrics`,`- Metrics unavailable`)}{let e=[];if(u)try{let t=u.getStats();e.push(`- **Decision Hooks**: ${t.count} registered${t.hooks.length>0?` (IDs: ${t.hooks.map(e=>e.id).join(`, `)})`:``}`)}catch{e.push(`- **Decision Hooks**: unavailable`)}else e.push(`- **Decision Hooks**: not configured`);if(d)try{let t=d.getStats(),n=Object.entries(t.byTool).map(([e,t])=>`${e}=${t}`).join(`, `);e.push(`- **Observations**: ${t.totalObservations} total, byTool: ${n||`none`}`)}catch{e.push(`- **Observations**: unavailable`)}else e.push(`- **Observations**: not configured`);if(f)try{let t=f.getStats(),n=Object.keys(t.byName);e.push(`- **Extractors**: ${t.count} registered${n.length>0?` (IDs: ${n.join(`, `)})`:``}`)}catch{e.push(`- **Extractors**: unavailable`)}else e.push(`- **Extractors**: not configured`);if(m)try{let t=m.getStats(),n=t.skillExists?t.isStale?`⚠ Stale`:`✅ Fresh`:`❌ No skill`;e.push(`- **Skill Compiler**: ${n}, version: ${t.skillVersion}, last compiled: ${t.lastCompiledAt?new Date(t.lastCompiledAt).toLocaleString():`Never`}`)}catch{e.push(`- **Skill Compiler**: unavailable`)}else e.push(`- **Skill Compiler**: not configured`);if(p)try{let t=p.getStats();e.push(`- **Promotion Engine**: ${t.held} candidates held, ${t.promoted} promoted, ${t.observedFacts} distinct facts tracked`)}catch{e.push(`- **Promotion Engine**: unavailable`)}else e.push(`- **Promotion Engine**: not configured`);D.push(``,`### 🧩 Feature Coverage`,...e)}let ge=0;{try{let e=a?.stateDir?F(a.stateDir,`stash`):null;if(e&&N(e)){let t=Me(e).mtimeMs;t>de&&(de=t)}}catch{}let e=[];if(r)try{let t=T>0?await r.list({limit:5,orderBy:`updated`,order:`desc`}):[];for(let e of t){let t=new Date(e.updated||e.created).getTime();t>de&&(de=t)}e.push(...t)}catch{}if(ge=de>0?Date.now()-de:0,ge>=uv){let t=Math.floor(ge/36e5);if(D.push(``,`### 🌅 Session Briefing`,`_${t}+ hours since last activity — here's what to pick up:_`,``),e.length>0){D.push(`**Recent decisions/notes:**`);for(let t of e)D.push(`- **${t.title}** (${t.category??`note`}) — ${(t.contentPreview??``).slice(0,80)}…`)}D.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')}}D.push(``,`### Runtime`,hv());let _e=he.instance().getAll(),ve=_e.filter(e=>e.status!==`healthy`);if(ve.length>0){D.push(``,`### ⚠️ Subsystem Health`);for(let e of ve){let t=Math.round((Date.now()-e.since)/1e3);D.push(`- **${e.name}**: ${e.status} (${t}s ago${e.reason?` — ${e.reason}`:``})`)}}else _e.length>0&&D.push(``,`### ✅ Subsystem Health`,`- All ${_e.length} subsystems healthy`);let ye=me.getAll();if(ye.size>0){D.push(``,`### 🔌 Circuit Breakers`);for(let[e,t]of ye){let n=t.getState(),r=`- **${e}**: ${n===`closed`?`🟢`:n===`open`?`🔴`:`🟡`} ${n}`;if(n===`open`){let e=t.remainingCooldownMs();r+=` (recovery in ${Math.ceil(e/1e3)}s)`}D.push(r)}}let A=bv(),be=xv(),xe=S(),Se=A!=null&&A!==xe,Ce=be!=null&&be!==xe;if(Se||Ce){let e=O(),t=[];Se&&t.push(`user scaffold v${A}`),Ce&&t.push(`workspace scaffold v${be}`);let n=t.join(`, `);e.state===`success`?D.push(``,`### ✅ Upgrade Applied`,`- Server v${xe} — ${n} auto-upgraded successfully.`,`- _Restart the MCP server to use the updated version._`):e.state===`pending`?D.push(``,`### ⏳ Upgrade In Progress`,`- Server v${xe} ≠ ${n}`,`- Auto-upgrade is running in the background…`):e.state===`failed`?(te(),D.push(``,`### ⬆ Upgrade Available (auto-upgrade failed, retrying)`,`- Server v${xe} ≠ ${n}`,`- Error: ${e.error??`unknown`}`)):(te(),D.push(``,`### ⬆ Upgrade Available`,`- Server v${xe} ≠ ${n}`,`- Auto-upgrade triggered — check again shortly.`))}g.length>0&&D.push(``,`### ⚠ Warnings`,...g.map(e=>`- ${e}`));let we=nv();if(we.length>0){let e=we.sort((e,t)=>t.callCount-e.callCount);D.push(``,`### Tool Usage This Session`,``),D.push(`| Tool | Calls | Tokens In | Tokens Out | Errors | Avg Latency |`),D.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);D.push(`| ${t.tool} | ${t.callCount} | ${e.toLocaleString()} | ${n.toLocaleString()} | ${t.errorCount} | ${r}ms |`)}}let j=$_();j.callCount>0&&(D.push(``),D.push(`### Session Token Usage`),D.push(`- Tool calls: ${j.callCount}`),D.push(`- Input chars: ${j.totalInputChars.toLocaleString()}`),D.push(`- Output chars: ${j.totalOutputChars.toLocaleString()}`),D.push(`- Est. input tokens: ${Math.round(j.totalInputChars/4).toLocaleString()}`),D.push(`- Est. total tokens: ${Math.round((j.totalInputChars+j.totalOutputChars)/4).toLocaleString()}`));let Te=av();if(Te.bufferSize>=10){let e=Te.state===`healthy`?`🟢`:Te.state===`degraded`?`🔴`:`🟡`;D.push(``,`### Auto-GC: ${e} ${Te.state}`),D.push(`- p95 latency: ${Te.p95}ms | buffer: ${Te.bufferSize} samples`),Te.gcCount>0&&D.push(`- GC cycles triggered: ${Te.gcCount}`)}if(l){let e=l.getStats();if(e.totalSubscribers>0){D.push(``,`### 🔌 Hooks (EventBus Subscribers)`),D.push(`- Total subscribers: ${e.totalSubscribers}`);for(let[t,n]of Object.entries(e.byEvent))D.push(` - ${t}: ${n} subscriber(s)`);for(let t of e.subscriptions)D.push(` - ${t.name} (${t.eventType}, ${t.policy})`);if(e.autoDisabled.length>0){D.push(``),D.push(` **Auto-disabled subscribers:**`);for(let t of e.autoDisabled)D.push(` - ${t.name} (${t.id}): ${t.reason}`)}}}if(u&&u.size>0){let e=u.getStats();D.push(``,`### 🪝 Decision Hooks`),D.push(`- Total hooks: ${e.count}`);for(let t of e.hooks){let e=t.decisionTypes.join(`, `);D.push(` - ${t.id} (order=${t.order}, policy=${t.failurePolicy}, types=[${e}])`)}}if(d){let e=d.getStats();D.push(``,`### 👁 Observations`),D.push(`- Total observations: ${e.totalObservations}`),D.push(` - Success: ${e.byError.success}, Error: ${e.byError.error}`),D.push(` - Artifacts stored: ${e.artifactCount}`),D.push(` - Truncations: ${e.truncationCount}`),D.push(` - Store entries: ${e.storeSize}`);let t=Object.entries(e.byOrigin);t.length>0&&D.push(` - By origin: ${t.map(([e,t])=>`${e}=${t}`).join(`, `)}`)}if(f){let e=f.getStats();D.push(``,`### 🧩 Extractors`),D.push(`- Total extractors: ${e.count}`);for(let[t,n]of Object.entries(e.byName))D.push(` - ${t} (${n.tools} tool(s), maxFacts: ${n.maxFactsPerEvent??`default`})`)}if(p){let e=p.getStats();if(D.push(``,`### 🏆 Promotion Engine`),D.push(`- Total evaluated: ${e.totalEvaluated}`),D.push(`- Promoted: ${e.promoted}`),D.push(`- Held: ${e.held}`),D.push(`- Rejected: ${e.rejected}`),D.push(`- Superseded: ${e.superseded}`),D.push(`- Decayed: ${e.decayed}`),D.push(`- Distinct facts tracked: ${e.observedFacts}`),e.recentDecisions.length>0){D.push(` Recent decisions:`);for(let t of e.recentDecisions.slice(-5))D.push(` - ${t.decision.status}: "${t.factTitle}" (${t.decision.reason.slice(0,80)})`)}}if(m){let e=m.getStats();if(D.push(``,`### 📋 Workspace Skill`),D.push(`- **Skill exists**: ${e.skillExists?`✅`:`❌`}`),D.push(`- **Stale**: ${e.isStale?`⚠ Yes — regenerating on next trigger`:`✅ Fresh`}`),D.push(`- **Last compiled**: ${e.lastCompiledAt?new Date(e.lastCompiledAt).toLocaleString():`Never`}`),D.push(`- **Version**: ${e.skillVersion}`),D.push(`- **Total compiles**: ${e.totalCompiles}`),e.failedCompiles>0&&D.push(`- **Failed compiles**: ${e.failedCompiles}`),e.skillSize>0&&D.push(`- **Skill size**: ${e.skillSize} bytes`),e.isCompiling&&D.push(`- ⏳ **Currently compiling**`),e.pendingRegeneration&&D.push(`- ⏳ **Regeneration pending**`),e.skillQuality&&D.push(`- **Quality**: ${e.skillQuality}`),e.skillQualityErrors&&e.skillQualityErrors.length>0){D.push(`- **Quality errors (${e.skillQualityErrors.length})**:`);for(let t of e.skillQualityErrors.slice(0,3))D.push(` - ${t}`)}if(e.skillQualityWarnings&&e.skillQualityWarnings.length>0){D.push(`- **Quality warnings (${e.skillQualityWarnings.length})**:`);for(let t of e.skillQualityWarnings.slice(0,3))D.push(` - ${t}`)}let t=m?.getWarnings()??[];if(t.length>0){D.push(`- **Compiler warnings (${t.length})**:`);for(let e of t.slice(0,5))D.push(` - ${e}`);t.length>5&&D.push(` - ... and ${t.length-5} more`)}D.push(``," Read `aikit://skill/SKILL.md` to load full workspace context.")}{let e=Pt();(e.cacheSize>0||e.refReuseCount>0)&&(D.push(``,`### 🔄 Ref Reuse`),D.push(`- **Refs stored**: ${e.refStoreCount}`),D.push(`- **Refs reused**: ${e.refReuseCount}`),e.refStaleCount>0&&D.push(`- **⚠ Stale refs detected**: ${e.refStaleCount}`),D.push(`- **Cache entries**: ${e.cacheSize}`))}let M=D.join(`
3054
+ `),Ee=ge>=uv,De=sv(a),Oe=e||Ee?await E(r,c,void 0,De.length>0?De:void 0,k):void 0,P=ae.length>0?ae.map(e=>({id:e.id,path:e.path,eventCount:e.eventCount,pendingFiles:e.pendingFiles??[]})):void 0,ke={totalRecords:y.totalRecords,totalFiles:y.totalFiles,lastIndexedAt:y.lastIndexedAt??null,lastSourceIndexedAt:y.lastSourceIndexedAt??null,onboarded:re,onboardDir:ee,onboard_context:k,contentTypes:y.contentTypeBreakdown,wasmAvailable:!!or.get(),wasmDiagnostics:ar.get(),graphStats:w,curatedCount:T,serverVersion:xe,scaffoldVersion:A??null,workspaceScaffoldVersion:be??null,upgradeAvailable:Se||Ce,storeBackend:a?.store?.backend,storeDiagnostics:fe??null,contextPressure:oe,nextAction:ue,workspace_skill:(()=>{if(!m)return null;try{let e=m.getStats(),t=m?.getWarnings()??[],n=e.skillExists?e.skillQuality??`fallback`:`fallback`;return{exists:e.skillExists,version:e.skillVersion,fresh:!e.isStale,quality:n,warnings:t,uri:`aikit://skill/SKILL.md`,path:e.skillPath,read_instruction:`Read aikit://skill/SKILL.md before working in this repo for full workspace context.`,last_updated:e.lastCompiledAt?new Date(e.lastCompiledAt).toISOString():null,size:e.skillSize}}catch{return null}})(),skill_warnings:m?.getWarnings(m?.resolveActiveFlowSlug()??void 0)??[],watchers:P,sessionTokens:{callCount:j.callCount,totalInputChars:j.totalInputChars,totalOutputChars:j.totalOutputChars,estInputTokens:Math.round(j.totalInputChars/4),estTotalTokens:Math.round((j.totalInputChars+j.totalOutputChars)/4),startTime:j.startTime},...Oe===void 0?{}:{prelude:Oe}};return{content:[{type:`text`,text:M+(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:ke}}catch(e){return lv.error(`Status failed`,M(e)),q(`INTERNAL`,`Status check failed: ${e instanceof Error?e.message:String(e)}`)}}))}const wv=A(`tools`);function Tv(e){return e instanceof Error?(`code`in e?e.code:void 0)===`ENOENT`||e.message.startsWith(`File not found:`)||e.message.startsWith(`Path not found:`):!1}function Ev(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},J(`web_search`,async({queries:e,limit:t,site:n,provider:r})=>{let i=e,a=async e=>{let i=await Gn({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(`
3055
+ `)};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 wv.error(`Web search failed`,M(e)),q(`INTERNAL`,`Web search failed: ${e instanceof Error?e.message:String(e)}`)}let o=await Promise.allSettled(i.map(e=>a(e))),s=[],c=0;for(let e=0;e<o.length;e++){let t=o[e];if(t.status===`fulfilled`)s.push(t.value);else{c++;let n=t.reason instanceof Error?t.reason.message:String(t.reason);wv.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(`
3056
3056
 
3057
- `);return c===o.length?q(`INTERNAL`,u):{content:[{type:`text`,text:u}]}}))}function Ev(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:Ds,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)`),include_hidden:L.boolean().optional().describe(`Include hidden trees such as .generated and .cache. Default false.`),max_tokens:L.number().min(100).max(5e4).optional().describe(`Maximum token budget for the response. When set, output is truncated to fit.`)},annotations:t.annotations},J(`measure`,async({path:e,extensions:t,include_hidden:n,max_tokens:r})=>{try{let i=await Yt({path:e,extensions:t,includeHidden:n}),a=[`## Code Metrics`,``,`**Files:** ${i.summary.totalFiles}`,`**Total lines:** ${i.summary.totalLines} (${i.summary.totalCodeLines} code)`,`**Functions:** ${i.summary.totalFunctions}`,`**Avg complexity:** ${i.summary.avgComplexity}`,`**Max complexity:** ${i.summary.maxComplexity.value} (${i.summary.maxComplexity.file})`,``,`### Top files by complexity`,``,`| File | Lines | Code | Complexity | Cognitive | Functions | Imports |`,`|------|-------|------|------------|-----------|-----------|---------|`];for(let e of i.files.slice(0,20)){let t=e.cognitiveComplexity===void 0?`—`:String(e.cognitiveComplexity);a.push(`| ${e.path} | ${e.lines.total} | ${e.lines.code} | ${e.complexity} | ${t} | ${e.functions} | ${e.imports} |`)}i.files.length>20&&a.push(``,`_...and ${i.files.length-20} more files_`);let o={summary:{totalFiles:i.summary.totalFiles,totalLines:i.summary.totalLines,totalCodeLines:i.summary.totalCodeLines,totalFunctions:i.summary.totalFunctions,avgComplexity:i.summary.avgComplexity,maxComplexity:{value:i.summary.maxComplexity.value,file:i.summary.maxComplexity.file}},files:i.files.map(e=>({path:e.path,lines:e.lines.total,code:e.lines.code,complexity:e.complexity,functions:e.functions}))};return{content:[{type:`text`,text:r?Vn(a.join(`
3057
+ `);return c===o.length?q(`INTERNAL`,u):{content:[{type:`text`,text:u}]}}))}function Dv(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:Ds,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)`),include_hidden:L.boolean().optional().describe(`Include hidden trees such as .generated and .cache. Default false.`),max_tokens:L.number().min(100).max(5e4).optional().describe(`Maximum token budget for the response. When set, output is truncated to fit.`)},annotations:t.annotations},J(`measure`,async({path:e,extensions:t,include_hidden:n,max_tokens:r})=>{try{let i=await Yt({path:e,extensions:t,includeHidden:n}),a=[`## Code Metrics`,``,`**Files:** ${i.summary.totalFiles}`,`**Total lines:** ${i.summary.totalLines} (${i.summary.totalCodeLines} code)`,`**Functions:** ${i.summary.totalFunctions}`,`**Avg complexity:** ${i.summary.avgComplexity}`,`**Max complexity:** ${i.summary.maxComplexity.value} (${i.summary.maxComplexity.file})`,``,`### Top files by complexity`,``,`| File | Lines | Code | Complexity | Cognitive | Functions | Imports |`,`|------|-------|------|------------|-----------|-----------|---------|`];for(let e of i.files.slice(0,20)){let t=e.cognitiveComplexity===void 0?`—`:String(e.cognitiveComplexity);a.push(`| ${e.path} | ${e.lines.total} | ${e.lines.code} | ${e.complexity} | ${t} | ${e.functions} | ${e.imports} |`)}i.files.length>20&&a.push(``,`_...and ${i.files.length-20} more files_`);let o={summary:{totalFiles:i.summary.totalFiles,totalLines:i.summary.totalLines,totalCodeLines:i.summary.totalCodeLines,totalFunctions:i.summary.totalFunctions,avgComplexity:i.summary.avgComplexity,maxComplexity:{value:i.summary.maxComplexity.value,file:i.summary.maxComplexity.file}},files:i.files.map(e=>({path:e.path,lines:e.lines.total,code:e.lines.code,complexity:e.complexity,functions:e.functions}))};return{content:[{type:`text`,text:r?Vn(a.join(`
3058
3058
  `),r):a.join(`
3059
- `)}],structuredContent:o}}catch(e){return wv(e)?(Cv.warn(`Measure failed`,{error:`File not found`}),q(`NOT_FOUND`,`File not found`)):(Cv.error(`Measure failed`,M(e)),q(`INTERNAL`,`Measure failed: ${e instanceof Error?e.message:String(e)}`))}}))}function Dv(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:Os,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},J(`env`,async({include_env:e,filter_env:t,show_sensitive:n})=>{let r=Tt({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(`
3060
- `)}],structuredContent:a}}))}const Ov=A(`register-tools`);function kv(e){return t=>!e||e.has(t)}function Av(e){try{let t=F(e,`.flows`);if(!N(t))return null;let n=ke(t,{withFileTypes:!0});for(let e of n){if(!e.isDirectory())continue;let n=F(t,e.name,`meta.json`);if(N(n)&&JSON.parse(P(n,`utf-8`)).status===`active`)return e.name}}catch{return null}return null}let jv=null,Mv=null;function Nv(){jv?.(),jv=null}function Pv(){return Mv?.flush()??Promise.resolve()}function Fv(e){let{server:t,aikit:n,config:r,elicitor:i,resourceNotifier:a,samplingClient:o,indexMode:s,getSmartState:c,getSmartScheduler:l,precomputedActiveTools:u}=e,d=new ko,f=r.sources[0]?.path??Te(),p=ye(f),m={activeSlug:null};m.activeSlug=Av(f);let h=new Ha(F(r.stateDir??``,`flow-context`),()=>m.activeSlug),g=new Ea;g.register(pi()),g.register(ya),g.register(Ai),g.register(ia),g.register(bi),g.register(mi),g.register(hi),g.register(ga),g.register(_i),g.register(Ca),g.register(ra(()=>m.activeSlug?{active:!0,slug:m.activeSlug}:null)),g.register(ca),g.register(xa),g.register(Di),g.register(oa);let _=new Qa(void 0,n.stateStore),v=n.eventBus,y=sv(r),b=y?new ro(y,{debounceMs:5e3},v??void 0,n.curated,void 0,f):null;b&&b.compileNow(`startup`).catch(e=>{Ov.warn(`Startup skill compile failed — will retry on next trigger`,{error:String(e)})});let x=new ka(g,n.curated,{},h,_,v??void 0,n.stateStore);Mv=x;let S=u??Ss(r,[...La,...Go],Ia,qo(r)),C=kv(S),w=new Set([...S].filter(e=>!Rf.includes(e)&&!Wa.has(e))),T=new Ja;d.use(Xo(),{order:1,name:`structured-content-guard`}),d.use(Va(Ba(r.tokenBudget)),{order:90,name:`compression`});let E=d.decisionHookRegistry;E.register({id:`search-budget`,order:10,scope:`search`,timeoutMs:100,failurePolicy:`degrade-with-warning`,decisionTypes:[`budgetHint`],reason:`Enforce token budget on search results`,fn:()=>({type:`decision`,hookId:`search-budget`,decision:`allow`,reason:`Budget hook active`})}),E.register({id:`find-path-containment`,order:10,scope:`find`,timeoutMs:50,failurePolicy:`fail-closed`,decisionTypes:[`deny`],reason:`Validate find scope against workspace boundaries`,fn:()=>({type:`decision`,hookId:`find-path-containment`,decision:`allow`,reason:`Path permitted`})}),E.register({id:`knowledge-mutation-safety`,order:10,scope:`knowledge`,timeoutMs:100,failurePolicy:`degrade-with-warning`,decisionTypes:[`deny`],reason:`Guard against unintended knowledge mutations`,fn:()=>({type:`decision`,hookId:`knowledge-mutation-safety`,decision:`allow`,reason:`Mutation permitted`})}),E.register({id:`check-scoped-run`,order:10,scope:`check`,timeoutMs:100,failurePolicy:`degrade-with-warning`,decisionTypes:[`allow`],reason:`Log check run scope for audit`,fn:()=>({type:`decision`,hookId:`check-scoped-run`,decision:`allow`,reason:`Check run permitted`})}),E.register({id:`test-run-scoped`,order:10,scope:`test_run`,timeoutMs:100,failurePolicy:`degrade-with-warning`,decisionTypes:[`allow`],reason:`Log test run scope for audit`,fn:()=>({type:`decision`,hookId:`test-run-scoped`,decision:`allow`,reason:`Test run permitted`})}),E.register({id:`onboard-path-correctness`,order:10,scope:`onboard`,timeoutMs:50,failurePolicy:`fail-closed`,decisionTypes:[`deny`],reason:`Validate onboard target path is valid and accessible`,fn:()=>({type:`decision`,hookId:`onboard-path-correctness`,decision:`allow`,reason:`Path valid`})}),E.register({id:`compact-budget-hints`,order:10,scope:`compact`,timeoutMs:100,failurePolicy:`degrade-with-warning`,decisionTypes:[`budgetHint`],reason:`Enforce token budget on compact output`,fn:()=>({type:`decision`,hookId:`compact-budget-hints`,decision:`allow`,reason:`Budget hook active`})}),E.register({id:`flow-step-safety`,order:10,scope:`flow`,timeoutMs:100,failurePolicy:`degrade-with-warning`,decisionTypes:[`allow`],reason:`Log flow step transitions`,fn:()=>({type:`decision`,hookId:`flow-step-safety`,decision:`allow`,reason:`Step permitted`})}),E.register({id:`present-transport-capability`,order:10,scope:`present`,timeoutMs:100,failurePolicy:`degrade-with-warning`,decisionTypes:[`allow`],reason:`Verify presentation transport is available`,fn:()=>({type:`decision`,hookId:`present-transport-capability`,decision:`allow`,reason:`Transport available`})});let D=new Mo(r.metricThresholds);ss(t,d,r.toolPrefix??``,n.eventBus,()=>{let e=r.sources[0]?.path??Te();try{return ye(e)}catch{return`partition:${qe(`sha256`).update(e).digest(`hex`).slice(0,8)}`}}),v&&(v.subscribe({id:`sub-auto-knowledge`,eventType:`tool:after`,policy:`async`,handler:async e=>{if(!(`toolName`in e)||!(`args`in e)||!(`result`in e))return;let t=e;try{D.incrementCounter(`tool.call`,{tool:t.toolName}),t.isError&&D.incrementCounter(`tool.error`,{tool:t.toolName}),x.push({toolName:t.toolName,args:t.args,result:t.result,durationMs:t.durationMs,isError:t.isError,timestamp:new Date(t.timestamp).toISOString(),origin:t.origin,workspaceId:t.workspaceId,requestId:t.requestId})}catch{}},name:`auto-knowledge`}),v.subscribe({id:`sub-replay`,eventType:`tool:after`,policy:`async`,handler:async e=>{if(!(`toolName`in e)||!(`args`in e)||!(`result`in e))return;let t=e;try{let{replayAppend:e}=await import(`../../tools/dist/index.js`),n=JSON.stringify(t.args),r=JSON.stringify(t.result);e({ts:new Date(t.timestamp).toISOString(),source:`mcp`,tool:t.toolName,input:n.slice(0,2e3),outputChars:r.length,inputChars:n.length,durationMs:t.durationMs,status:t.isError?`error`:`ok`,output:r.slice(0,2e3),traceId:t.requestId??``})}catch{}},name:`replay`}),v.subscribe({id:`sub-procedural`,eventType:`tool:after`,policy:`async`,handler:async e=>{if(!(`toolName`in e)||!(`isError`in e))return;let t=e;try{w.has(t.toolName)&&T.record(t.toolName,!t.isError)}catch{}},name:`procedural-memory`}),v.subscribe({id:`sub-observations`,eventType:`tool:after`,policy:`async`,handler:async e=>{if(!(`toolName`in e)||!(`result`in e))return;let t=e;try{let{ObservationEngine:e,DEFAULT_OBSERVATION_CONFIG:r}=await import(`./observations-BhMmh4uj.js`),i=new e(n.stateStore,n.curated),{captureFrom:a}=r;a.includes(t.toolName)&&await i.processToolResult(t.toolName,t.result,{})}catch{}},name:`observation-capture`}),v.subscribe({id:`sub-knowledge-metrics`,eventType:`tool:after`,policy:`async`,handler:async e=>{if(!(`toolName`in e)||!(`result`in e))return;let t=e;if(t.toolName===`knowledge`)try{let e=t.result,n=t.args?.action;(n===`remember`||n===`update`)&&(D.incrementCounter(`fact.total`),(e?.status===`unchanged`||e?.result===`unchanged`)&&D.incrementCounter(`fact.duplicate`))}catch{}},name:`knowledge-metrics`}),v.subscribe({id:`sub-session`,eventType:`session:start`,policy:`async`,handler:async e=>{let t=e,n={serverVersion:t.serverVersion,workspaceRoot:t.workspaceRoot,handoff:t.handoff?`${t.handoff.from} (session ${t.handoff.sessionId})`:void 0};Ov.info(`Session started`,n)},name:`session-lifecycle`}),b&&(jv=b.subscribeToEventBus(v)));let ee=[...S].filter(e=>Ko.has(e)?Wo.includes(e)?!!n.bridge:e===`er_update_policy`?!!n.policyStore:e===`er_evolve_review`?!!n.evolutionCollector:!1:!0),O={store:n.store,graphStore:n.graphStore,embedder:n.embedder},te={onboardComplete:n.onboardComplete,onboardTimestamp:n.onboardTimestamp},ne={search:[{name:`search`,register:()=>x_(t,n.embedder,n.store,n.graphStore,n.bridge,n.evolutionCollector,o,n.stateStore,r.memory?.retention,r.memory?.consolidation,p)},{name:`find`,register:()=>Tl(t,n.embedder,n.store)},{name:`symbol`,register:()=>El(t,n.embedder,n.store,n.graphStore,O)},{name:`trace`,register:()=>Dl(t,n.embedder,n.store,n.graphStore,O)},{name:`scope_map`,register:()=>wl(t,n.embedder,n.store,O)},{name:`file_summary`,register:()=>zl(t,n.embedder,n.fileCache)}],analysis:[{name:`analyze`,register:()=>Pc(t,n.store,n.embedder)},{name:`blast_radius`,register:()=>Fc(t,n.store,n.embedder,n.graphStore,O)}],knowledge:[{name:`knowledge`,register:()=>wf(t,n.curated,n.policyStore,n.evolutionCollector,a,void 0,n.stateStore,r.memory?.retention,r.memory?.supersession,r.memory?.consolidation,r.memory?.lessons,O,n.graphStore)},{name:`produce_knowledge`,register:()=>Zg(t,a)}],compression:[{name:`digest`,register:()=>Gu(t,n.embedder)}],forge:[{name:`forge_ground`,register:()=>Ku(t,n.embedder,n.store)},{name:`evidence_map`,register:()=>Wu(t)}],presentation:[{name:`present`,register:()=>Yg(t,i)}],execution:[{name:`check`,register:()=>Ml(t,O,r.tokenBudget)},{name:`test_run`,register:()=>Pl(t,O)},{name:`eval`,register:()=>Nl(t)},{name:`audit`,register:()=>Bc(t,n.store,n.embedder)}],web:[{name:`browser`,register:()=>Yn(t,r)},{name:`web_fetch`,register:()=>td(t)},{name:`web_search`,register:()=>Tv(t)}],manipulation:[{name:`rename`,register:()=>Of(t,r)},{name:`restore`,register:()=>r_(t)},{name:`codemod`,register:()=>kf(t,r)}],session:[{name:`session`,register:()=>z_(t,n.stateStore,o)}],git:[{name:`git`,register:()=>Ju(t)},{name:`parse_output`,register:()=>Fl(t)}],process:[{name:`process`,register:()=>ed(t)},{name:`delegate`,register:()=>Il(t,o)}],system:[{name:`config`,register:()=>pl(t,r)},{name:`status`,register:()=>Sv(t,n.store,n.graphStore,n.curated,te,r,s,c,n.stateStore,n.eventBus,d.decisionHookRegistry,d.getObservationCompressor(),g,_,b)},{name:`reindex`,register:()=>$g(t,n.indexer,r,n.curated,n.store,a,s,n.eventBus)},{name:`onboard`,register:()=>op(t,n.store,n.embedder,r,te,O,o,a)},{name:`graph`,register:()=>Qu(t,n.graphStore)},{name:`replay`,register:()=>t_(t)}],utilities:[{name:`measure`,register:()=>Ev(t)},{name:`env`,register:()=>Dv(t)}],queue:[{name:`queue`,register:()=>cp(t)}],flow:[{name:`flow`,register:()=>Hu(t,r,{store:n.store?{search:async(e,t)=>(await n.store.ftsSearch(e,t)).map(e=>({content:e.record.content}))}:null,graphStore:n.graphStore,embedder:n.embedder,curated:n.curated??null,eventBus:n.eventBus??null,skillCompiler:b},e=>{m.activeSlug=e})}]};for(let[,e]of Object.entries(ne))for(let{name:t,register:n}of e)C(t)&&n();n.bridge&&(C(`er_push`)&&Wc(t,n.bridge,n.evolutionCollector),C(`er_pull`)&&Gc(t,n.bridge),C(`er_sync_status`)&&Kc(t,n.bridge)),n.policyStore&&C(`er_update_policy`)&&dp(t,n.policyStore),n.evolutionCollector&&C(`er_evolve_review`)&&Al(t,n.evolutionCollector),Rf.some(e=>C(e))&&zf(t,r,ee,n.onboardComplete),Uo(t,n.store,n.curated,y,n.eventBus,d.decisionHookRegistry,b)}function Iv(e,t,n){let r=kv(n);r(`check`)&&Ml(e,void 0,t.tokenBudget),r(`eval`)&&Nl(e),r(`test_run`)&&Pl(e),r(`parse_output`)&&Fl(e),r(`delegate`)&&Il(e),r(`git`)&&Ju(e),r(`rename`)&&Of(e,t),r(`codemod`)&&kf(e,t),r(`restore`)&&r_(e),r(`queue`)&&cp(e),r(`process`)&&ed(e),r(`web_fetch`)&&td(e),Rf.some(e=>r(e))&&zf(e,t,[...n??new Set(La)]),r(`evidence_map`)&&Wu(e),r(`present`)&&Yg(e),r(`browser`)&&Yn(e,t),r(`produce_knowledge`)&&Zg(e),r(`replay`)&&t_(e),r(`status`)&&xv(e),r(`flow`)&&Hu(e,t),r(`web_search`)&&Tv(e),r(`measure`)&&Ev(e),r(`env`)&&Dv(e)}export{U as S,co as _,Og as a,Ia as b,Uc as c,Xo as d,ns as f,ko as g,qo as h,Iv as i,Ss as l,Go as m,Pv as n,Xf as o,Jo as p,Fv as r,$f as s,Nv as t,ss as u,La as v,Ra as x,za as y};
3059
+ `)}],structuredContent:o}}catch(e){return Tv(e)?(wv.warn(`Measure failed`,{error:`File not found`}),q(`NOT_FOUND`,`File not found`)):(wv.error(`Measure failed`,M(e)),q(`INTERNAL`,`Measure failed: ${e instanceof Error?e.message:String(e)}`))}}))}function Ov(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:Os,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},J(`env`,async({include_env:e,filter_env:t,show_sensitive:n})=>{let r=Tt({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(`
3060
+ `)}],structuredContent:a}}))}const kv=A(`register-tools`);function Av(e){return t=>!e||e.has(t)}function jv(e){try{let t=F(e,`.flows`);if(!N(t))return null;let n=ke(t,{withFileTypes:!0});for(let e of n){if(!e.isDirectory())continue;let n=F(t,e.name,`meta.json`);if(N(n)&&JSON.parse(P(n,`utf-8`)).status===`active`)return e.name}}catch{return null}return null}let Mv=null,Nv=null;function Pv(){Mv?.(),Mv=null}function Fv(){return Nv?.flush()??Promise.resolve()}function Iv(e){let{server:t,aikit:n,config:r,elicitor:i,resourceNotifier:a,samplingClient:o,indexMode:s,getSmartState:c,getSmartScheduler:l,precomputedActiveTools:u}=e,d=new ko,f=r.sources[0]?.path??Te(),p=ye(f),m={activeSlug:null};m.activeSlug=jv(f);let h=new Ha(F(r.stateDir??``,`flow-context`),()=>m.activeSlug),g=new Ea;g.register(pi()),g.register(ya),g.register(Ai),g.register(ia),g.register(bi),g.register(mi),g.register(hi),g.register(ga),g.register(_i),g.register(Ca),g.register(ra(()=>m.activeSlug?{active:!0,slug:m.activeSlug}:null)),g.register(ca),g.register(xa),g.register(Di),g.register(oa);let _=new Qa(void 0,n.stateStore),v=n.eventBus,y=cv(r),b=y?new ro(y,{debounceMs:5e3},v??void 0,n.curated,void 0,f):null;b&&b.compileNow(`startup`).catch(e=>{kv.warn(`Startup skill compile failed — will retry on next trigger`,{error:String(e)})});let x=new ka(g,n.curated,{},h,_,v??void 0,n.stateStore);Nv=x;let S=u??Ss(r,[...La,...Go],Ia,qo(r)),C=Av(S),w=new Set([...S].filter(e=>!Rf.includes(e)&&!Wa.has(e))),T=new Ja;d.use(Xo(),{order:1,name:`structured-content-guard`}),d.use(Va(Ba(r.tokenBudget)),{order:90,name:`compression`});let E=d.decisionHookRegistry;E.register({id:`search-budget`,order:10,scope:`search`,timeoutMs:100,failurePolicy:`degrade-with-warning`,decisionTypes:[`budgetHint`],reason:`Enforce token budget on search results`,fn:()=>({type:`decision`,hookId:`search-budget`,decision:`allow`,reason:`Budget hook active`})}),E.register({id:`find-path-containment`,order:10,scope:`find`,timeoutMs:50,failurePolicy:`fail-closed`,decisionTypes:[`deny`],reason:`Validate find scope against workspace boundaries`,fn:()=>({type:`decision`,hookId:`find-path-containment`,decision:`allow`,reason:`Path permitted`})}),E.register({id:`knowledge-mutation-safety`,order:10,scope:`knowledge`,timeoutMs:100,failurePolicy:`degrade-with-warning`,decisionTypes:[`deny`],reason:`Guard against unintended knowledge mutations`,fn:()=>({type:`decision`,hookId:`knowledge-mutation-safety`,decision:`allow`,reason:`Mutation permitted`})}),E.register({id:`check-scoped-run`,order:10,scope:`check`,timeoutMs:100,failurePolicy:`degrade-with-warning`,decisionTypes:[`allow`],reason:`Log check run scope for audit`,fn:()=>({type:`decision`,hookId:`check-scoped-run`,decision:`allow`,reason:`Check run permitted`})}),E.register({id:`test-run-scoped`,order:10,scope:`test_run`,timeoutMs:100,failurePolicy:`degrade-with-warning`,decisionTypes:[`allow`],reason:`Log test run scope for audit`,fn:()=>({type:`decision`,hookId:`test-run-scoped`,decision:`allow`,reason:`Test run permitted`})}),E.register({id:`onboard-path-correctness`,order:10,scope:`onboard`,timeoutMs:50,failurePolicy:`fail-closed`,decisionTypes:[`deny`],reason:`Validate onboard target path is valid and accessible`,fn:()=>({type:`decision`,hookId:`onboard-path-correctness`,decision:`allow`,reason:`Path valid`})}),E.register({id:`compact-budget-hints`,order:10,scope:`compact`,timeoutMs:100,failurePolicy:`degrade-with-warning`,decisionTypes:[`budgetHint`],reason:`Enforce token budget on compact output`,fn:()=>({type:`decision`,hookId:`compact-budget-hints`,decision:`allow`,reason:`Budget hook active`})}),E.register({id:`flow-step-safety`,order:10,scope:`flow`,timeoutMs:100,failurePolicy:`degrade-with-warning`,decisionTypes:[`allow`],reason:`Log flow step transitions`,fn:()=>({type:`decision`,hookId:`flow-step-safety`,decision:`allow`,reason:`Step permitted`})}),E.register({id:`present-transport-capability`,order:10,scope:`present`,timeoutMs:100,failurePolicy:`degrade-with-warning`,decisionTypes:[`allow`],reason:`Verify presentation transport is available`,fn:()=>({type:`decision`,hookId:`present-transport-capability`,decision:`allow`,reason:`Transport available`})});let D=new Mo(r.metricThresholds);ss(t,d,r.toolPrefix??``,n.eventBus,()=>{let e=r.sources[0]?.path??Te();try{return ye(e)}catch{return`partition:${qe(`sha256`).update(e).digest(`hex`).slice(0,8)}`}}),v&&(v.subscribe({id:`sub-auto-knowledge`,eventType:`tool:after`,policy:`async`,handler:async e=>{if(!(`toolName`in e)||!(`args`in e)||!(`result`in e))return;let t=e;try{D.incrementCounter(`tool.call`,{tool:t.toolName}),t.isError&&D.incrementCounter(`tool.error`,{tool:t.toolName}),x.push({toolName:t.toolName,args:t.args,result:t.result,durationMs:t.durationMs,isError:t.isError,timestamp:new Date(t.timestamp).toISOString(),origin:t.origin,workspaceId:t.workspaceId,requestId:t.requestId})}catch{}},name:`auto-knowledge`}),v.subscribe({id:`sub-replay`,eventType:`tool:after`,policy:`async`,handler:async e=>{if(!(`toolName`in e)||!(`args`in e)||!(`result`in e))return;let t=e;try{let{replayAppend:e}=await import(`../../tools/dist/index.js`),n=JSON.stringify(t.args),r=JSON.stringify(t.result);e({ts:new Date(t.timestamp).toISOString(),source:`mcp`,tool:t.toolName,input:n.slice(0,2e3),outputChars:r.length,inputChars:n.length,durationMs:t.durationMs,status:t.isError?`error`:`ok`,output:r.slice(0,2e3),traceId:t.requestId??``})}catch{}},name:`replay`}),v.subscribe({id:`sub-procedural`,eventType:`tool:after`,policy:`async`,handler:async e=>{if(!(`toolName`in e)||!(`isError`in e))return;let t=e;try{w.has(t.toolName)&&T.record(t.toolName,!t.isError)}catch{}},name:`procedural-memory`}),v.subscribe({id:`sub-observations`,eventType:`tool:after`,policy:`async`,handler:async e=>{if(!(`toolName`in e)||!(`result`in e))return;let t=e;try{let{ObservationEngine:e,DEFAULT_OBSERVATION_CONFIG:r}=await import(`./observations-BhMmh4uj.js`),i=new e(n.stateStore,n.curated),{captureFrom:a}=r;a.includes(t.toolName)&&await i.processToolResult(t.toolName,t.result,{})}catch{}},name:`observation-capture`}),v.subscribe({id:`sub-knowledge-metrics`,eventType:`tool:after`,policy:`async`,handler:async e=>{if(!(`toolName`in e)||!(`result`in e))return;let t=e;if(t.toolName===`knowledge`)try{let e=t.result,n=t.args?.action;(n===`remember`||n===`update`)&&(D.incrementCounter(`fact.total`),(e?.status===`unchanged`||e?.result===`unchanged`)&&D.incrementCounter(`fact.duplicate`))}catch{}},name:`knowledge-metrics`}),v.subscribe({id:`sub-session`,eventType:`session:start`,policy:`async`,handler:async e=>{let t=e,n={serverVersion:t.serverVersion,workspaceRoot:t.workspaceRoot,handoff:t.handoff?`${t.handoff.from} (session ${t.handoff.sessionId})`:void 0};kv.info(`Session started`,n)},name:`session-lifecycle`}),b&&(Mv=b.subscribeToEventBus(v)));let ee=[...S].filter(e=>Ko.has(e)?Wo.includes(e)?!!n.bridge:e===`er_update_policy`?!!n.policyStore:e===`er_evolve_review`?!!n.evolutionCollector:!1:!0),O={store:n.store,graphStore:n.graphStore,embedder:n.embedder},te={onboardComplete:n.onboardComplete,onboardTimestamp:n.onboardTimestamp},ne={search:[{name:`search`,register:()=>S_(t,n.embedder,n.store,n.graphStore,n.bridge,n.evolutionCollector,o,n.stateStore,r.memory?.retention,r.memory?.consolidation,p)},{name:`find`,register:()=>Tl(t,n.embedder,n.store)},{name:`symbol`,register:()=>El(t,n.embedder,n.store,n.graphStore,O)},{name:`trace`,register:()=>Dl(t,n.embedder,n.store,n.graphStore,O)},{name:`scope_map`,register:()=>wl(t,n.embedder,n.store,O)},{name:`file_summary`,register:()=>zl(t,n.embedder,n.fileCache)}],analysis:[{name:`analyze`,register:()=>Pc(t,n.store,n.embedder)},{name:`blast_radius`,register:()=>Fc(t,n.store,n.embedder,n.graphStore,O)}],knowledge:[{name:`knowledge`,register:()=>wf(t,n.curated,n.policyStore,n.evolutionCollector,a,void 0,n.stateStore,r.memory?.retention,r.memory?.supersession,r.memory?.consolidation,r.memory?.lessons,O,n.graphStore)},{name:`produce_knowledge`,register:()=>Qg(t,a)}],compression:[{name:`digest`,register:()=>Gu(t,n.embedder)}],forge:[{name:`forge_ground`,register:()=>Ku(t,n.embedder,n.store)},{name:`evidence_map`,register:()=>Wu(t)}],presentation:[{name:`present`,register:()=>Xg(t,i)}],execution:[{name:`check`,register:()=>Ml(t,O,r.tokenBudget)},{name:`test_run`,register:()=>Pl(t,O)},{name:`eval`,register:()=>Nl(t)},{name:`audit`,register:()=>Bc(t,n.store,n.embedder)}],web:[{name:`browser`,register:()=>Yn(t,r)},{name:`web_fetch`,register:()=>td(t)},{name:`web_search`,register:()=>Ev(t)}],manipulation:[{name:`rename`,register:()=>Of(t,r)},{name:`restore`,register:()=>i_(t)},{name:`codemod`,register:()=>kf(t,r)}],session:[{name:`session`,register:()=>B_(t,n.stateStore,o)}],git:[{name:`git`,register:()=>Ju(t)},{name:`parse_output`,register:()=>Fl(t)}],process:[{name:`process`,register:()=>ed(t)},{name:`delegate`,register:()=>Il(t,o)}],system:[{name:`config`,register:()=>pl(t,r)},{name:`status`,register:()=>Cv(t,n.store,n.graphStore,n.curated,te,r,s,c,n.stateStore,n.eventBus,d.decisionHookRegistry,d.getObservationCompressor(),g,_,b)},{name:`reindex`,register:()=>e_(t,n.indexer,r,n.curated,n.store,a,s,n.eventBus)},{name:`onboard`,register:()=>op(t,n.store,n.embedder,r,te,O,o,a)},{name:`graph`,register:()=>Qu(t,n.graphStore)},{name:`replay`,register:()=>n_(t)}],utilities:[{name:`measure`,register:()=>Dv(t)},{name:`env`,register:()=>Ov(t)}],queue:[{name:`queue`,register:()=>cp(t)}],flow:[{name:`flow`,register:()=>Hu(t,r,{store:n.store?{search:async(e,t)=>(await n.store.ftsSearch(e,t)).map(e=>({content:e.record.content}))}:null,graphStore:n.graphStore,embedder:n.embedder,curated:n.curated??null,eventBus:n.eventBus??null,skillCompiler:b},e=>{m.activeSlug=e})}]};for(let[,e]of Object.entries(ne))for(let{name:t,register:n}of e)C(t)&&n();n.bridge&&(C(`er_push`)&&Wc(t,n.bridge,n.evolutionCollector),C(`er_pull`)&&Gc(t,n.bridge),C(`er_sync_status`)&&Kc(t,n.bridge)),n.policyStore&&C(`er_update_policy`)&&dp(t,n.policyStore),n.evolutionCollector&&C(`er_evolve_review`)&&Al(t,n.evolutionCollector),Rf.some(e=>C(e))&&zf(t,r,ee,n.onboardComplete),Uo(t,n.store,n.curated,y,n.eventBus,d.decisionHookRegistry,b)}function Lv(e,t,n){let r=Av(n);r(`check`)&&Ml(e,void 0,t.tokenBudget),r(`eval`)&&Nl(e),r(`test_run`)&&Pl(e),r(`parse_output`)&&Fl(e),r(`delegate`)&&Il(e),r(`git`)&&Ju(e),r(`rename`)&&Of(e,t),r(`codemod`)&&kf(e,t),r(`restore`)&&i_(e),r(`queue`)&&cp(e),r(`process`)&&ed(e),r(`web_fetch`)&&td(e),Rf.some(e=>r(e))&&zf(e,t,[...n??new Set(La)]),r(`evidence_map`)&&Wu(e),r(`present`)&&Xg(e),r(`browser`)&&Yn(e,t),r(`produce_knowledge`)&&Qg(e),r(`replay`)&&n_(e),r(`status`)&&Sv(e),r(`flow`)&&Hu(e,t),r(`web_search`)&&Ev(e),r(`measure`)&&Dv(e),r(`env`)&&Ov(e)}export{U as S,co as _,kg as a,Ia as b,Uc as c,Xo as d,ns as f,ko as g,qo as h,Lv as i,Ss as l,Go as m,Fv as n,Xf as o,Jo as p,Iv as r,$f as s,Pv as t,ss as u,La as v,Ra as x,za as y};