@vpxa/aikit 0.1.190 → 0.1.192
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@vpxa/aikit",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.192",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Local-first AI developer toolkit — knowledge base, code analysis, context management, and developer tools for LLM agents",
|
|
6
6
|
"license": "MIT",
|
|
@@ -113,6 +113,6 @@
|
|
|
113
113
|
"release:dry": "node scripts/release.mjs --dry-run",
|
|
114
114
|
"nodeprune": "pnpm clean && pnpm store prune && pnpm -s dlx npkill -D -y",
|
|
115
115
|
"test:watch": "vitest",
|
|
116
|
-
"validate": "pnpm
|
|
116
|
+
"validate": "pnpm build && pnpm test && pnpm lint:fix && pnpm typecheck"
|
|
117
117
|
}
|
|
118
118
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{createRequire as e}from"node:module";import{createHash as t,randomUUID as n}from"node:crypto";import{homedir as r}from"node:os";import{join as i}from"node:path";import{execFileSync as a}from"node:child_process";import{existsSync as o,readdirSync as s}from"node:fs";import{Buffer as c}from"node:buffer";import{z as l}from"zod";var u=class{#e;#t;#n=0;#r=0;constructor(e=200){if(!Number.isInteger(e)||e<1)throw RangeError(`CircularBuffer capacity must be a positive integer.`);this.#e=e,this.#t=Array(e)}push(e){this.#t[this.#n]=e,this.#n=(this.#n+1)%this.#e,this.#r<this.#e&&(this.#r+=1)}toArray(){if(this.#r===0)return[];let e=(this.#n-this.#r+this.#e)%this.#e,t=[];for(let n=0;n<this.#r;n+=1)t.push(this.#t[(e+n)%this.#e]);return t}clear(){this.#t=Array(this.#e),this.#n=0,this.#r=0}get size(){return this.#r}get capacity(){return this.#e}isEmpty(){return this.#r===0}};const d=[`xhr`,`fetch`,`websocket`,`document`],f=[/^authorization$/i,/^cookie$/i,/^set-cookie$/i,/^x-api-key$/i,/^x-access-token$/i,/^x-auth-token$/i,/^x-session$/i,/^x-secret$/i,/^x-password$/i,/^proxy-authorization$/i,/^www-authenticate$/i,/^x-csrf-token$/i,/^x-xsrf-token$/i];function p(e,t){if(t?.showSensitive)return{...e};let n=[...f,...t?.additionalPatterns??[]],r={};for(let[t,i]of Object.entries(e))r[t]=n.some(e=>e.test(t))?`[REDACTED]`:i;return r}function m(e,t=512){if(e)return e.length<=t?e:`${e.slice(0,t)}...[truncated]`}function ee(){return{networkBuffer:new u(200),consoleBuffer:new u(1e3),networkEnabled:!1,consoleEnabled:!1,networkFilter:{},nextRequestSequence:0,pendingRequests:new Map}}function te(e,t){if(e.capacity===t)return e;let n=new u(t),r=e.toArray(),i=Math.max(0,r.length-t);for(let e of r.slice(i))n.push(e);return n}function ne(e){switch(e){case`error`:case`info`:case`log`:case`debug`:return e;case`warning`:return`warn`;default:return`log`}}function re(e){if(e)return Buffer.byteLength(e)<=5242880?m(e):void 0}function ie(e){if(!e)return{};let t=Buffer.byteLength(e);return{bodySize:t,bodyPreview:t<=5242880?m(e):void 0}}function ae(e,t){return!t.resourceTypes.has(e.resourceType)||t.urlPattern&&!t.urlPattern.test(e.url)?!1:!t.excludeUrls.some(t=>t.test(e.url))}function h(e){if(e.length>200)throw Error(`Network filter regex patterns must be 200 characters or fewer`);try{let t=new RegExp(e);return t.test(`a`.repeat(100)),t}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`Invalid network filter regex pattern: ${t}`)}}function g(e={}){return{resourceTypes:new Set(e.resourceTypes??d),urlPattern:e.urlPattern?h(e.urlPattern):void 0,excludeUrls:(e.excludeUrls??[]).map(e=>h(e))}}function oe(e){return e.nextRequestSequence+=1,`req-${e.nextRequestSequence}`}function se(e,t,n){let r={request:t,previous:e.pendingRequestTail};e.pendingRequestTail?e.pendingRequestTail.next=r:e.pendingRequestHead=r,e.pendingRequestTail=r,e.pendingRequests.set(t,{entry:n,node:r})}function _(e,t){t.previous?t.previous.next=t.next:e.pendingRequestHead=t.next,t.next?t.next.previous=t.previous:e.pendingRequestTail=t.previous,delete t.previous,delete t.next}function ce(e){for(;e.pendingRequests.size>e.networkBuffer.capacity;){let t=e.pendingRequestHead;if(!t)return;_(e,t),e.pendingRequests.delete(t.request)}}function v(e){e.pendingRequests.clear(),e.pendingRequestHead=void 0,e.pendingRequestTail=void 0}var le=class{states=new Map;getOrCreate(e){let t=this.states.get(e);if(t)return t;let n=ee();return this.states.set(e,n),n}get(e){return this.states.get(e)}remove(e){let t=this.states.get(e);t&&(t.networkEnabled=!1,t.consoleEnabled=!1,this.detachNetworkListeners(t),this.detachConsoleListeners(t),v(t),this.states.delete(e))}clear(){for(let e of this.states.values())e.networkEnabled=!1,e.consoleEnabled=!1,this.detachNetworkListeners(e),this.detachConsoleListeners(e),v(e);this.states.clear()}enableNetwork(e,t,n,r){let i=this.getOrCreate(e);i.networkEnabled&&this.disableNetwork(e,t),i.page=t,i.networkEnabled=!0,i.networkFilter=n?{...n}:{},i.compiledNetworkFilter=g(i.networkFilter),r?.bufferSize&&(i.networkBuffer=te(i.networkBuffer,r.bufferSize));let a=e=>{let t=i.compiledNetworkFilter??g(i.networkFilter),n={resourceType:e.resourceType(),url:e.url()};if(!ae(n,t))return;let a={...e.headers()},o=Date.now(),s={id:oe(i),url:n.url,method:e.method(),resourceType:n.resourceType,headers:r?.showSensitive?a:p(a),postData:r?.includeBody?re(e.postData()??void 0):void 0,timestamp:o};i.networkBuffer.push(s),se(i,e,s),ce(i)},o=async e=>{let t=e.request(),n=i.pendingRequests.get(t);if(!n)return;i.pendingRequests.delete(t),_(i,n.node);let a;if(r?.includeBody)try{a=ie(await e.text())}catch{a=void 0}let o={...e.headers()};n.entry.response={status:e.status(),statusText:e.statusText(),headers:r?.showSensitive?o:p(o),bodySize:a?.bodySize,bodyPreview:a?.bodyPreview,timing:Date.now()-n.entry.timestamp}};i.listenerRefs={...i.listenerRefs,requestHandler:a,responseHandler:o},this.ensurePageCloseHandler(e,i,t),t.on(`request`,a),t.on(`response`,o)}disableNetwork(e,t){let n=this.states.get(e);n&&(n.page=n.page??t,n.networkEnabled=!1,this.detachNetworkListeners(n),v(n))}enableConsole(e,t,n){let r=this.getOrCreate(e);r.consoleEnabled&&this.disableConsole(e,t),r.page=t,r.consoleEnabled=!0,n?.bufferSize&&(r.consoleBuffer=te(r.consoleBuffer,n.bufferSize));let i=e=>{let t=e.location();r.consoleBuffer.push({level:ne(e.type()),text:e.text(),timestamp:Date.now(),location:t.url?{url:t.url,line:t.lineNumber,column:t.columnNumber}:void 0,args:e.args().map(e=>e.toString())})};r.listenerRefs={...r.listenerRefs,consoleHandler:i},this.ensurePageCloseHandler(e,r,t),t.on(`console`,i)}disableConsole(e,t){let n=this.states.get(e);n&&(n.page=n.page??t,n.consoleEnabled=!1,this.detachConsoleListeners(n))}detachNetworkListeners(e){let t=e.page,n=e.listenerRefs?.requestHandler,r=e.listenerRefs?.responseHandler;t&&n&&t.off(`request`,n),t&&r&&t.off(`response`,r),e.listenerRefs&&(delete e.listenerRefs.requestHandler,delete e.listenerRefs.responseHandler),this.detachPageCloseHandlerIfUnused(e)}detachConsoleListeners(e){let t=e.page,n=e.listenerRefs?.consoleHandler;t&&n&&t.off(`console`,n),e.listenerRefs&&delete e.listenerRefs.consoleHandler,this.detachPageCloseHandlerIfUnused(e)}ensurePageCloseHandler(e,t,n){if(t.listenerRefs?.pageCloseHandler)return;let r=()=>{this.remove(e)};t.listenerRefs={...t.listenerRefs,pageCloseHandler:r},n.on(`close`,r)}detachPageCloseHandlerIfUnused(e){if(e.networkEnabled||e.consoleEnabled)return;let t=e.page,n=e.listenerRefs?.pageCloseHandler;t&&n&&t.off(`close`,n),e.listenerRefs&&delete e.listenerRefs.pageCloseHandler,e.listenerRefs&&!e.listenerRefs.requestHandler&&!e.listenerRefs.responseHandler&&!e.listenerRefs.consoleHandler&&!e.listenerRefs.pageCloseHandler&&delete e.listenerRefs}};let ue=null;function y(){return ue||=new le,ue}const de=e(import.meta.url);function fe(e){return typeof e==`string`?e.trim():e instanceof Buffer?e.toString(`utf8`).trim():``}function pe(e){process.env.PLAYWRIGHT_BROWSERS_PATH=e}async function me(e){pe(e);let{chromium:t}=await import(`playwright-core`),n=t.executablePath();if(!n)throw Error(`Chromium executable not found in ${e}`);return n}function he(){return i(r(),`.aikit`,`browsers`)}function b(e){return e.browsersPath??process.env.PLAYWRIGHT_BROWSERS_PATH??he()}function x(e){return o(e)?s(e,{withFileTypes:!0}).some(e=>e.isDirectory()&&e.name.toLowerCase().startsWith(`chromium-`)):!1}async function S(e,t){let n=b(e);if(pe(n),t?.(`Using Chromium cache at ${n}`),x(n))return t?.(`Chromium already installed`),me(n);let r=i(de.resolve(`playwright-core`),`..`,`cli.js`);t?.(`Installing Chromium via playwright-core`);try{a(process.execPath,[r,`install`,`chromium`],{env:{...process.env,PLAYWRIGHT_BROWSERS_PATH:n},encoding:`utf8`,stdio:`pipe`})}catch(e){let t=e,n=fe(t.stderr),r=fe(t.stdout),i=n||r||t.message||`Unknown playwright install failure`;throw Error(`Failed to install Chromium: ${i}`)}return t?.(`Chromium install complete`),me(n)}function C(){return process.platform===`win32`||process.platform===`darwin`?!0:!!(process.env.DISPLAY||process.env.WAYLAND_DISPLAY)}function w(e){return e===`headless`||!C()?`headless`:e}function T(e){switch(e){case`headless`:return{headless:!0,args:[]};default:return{headless:!1,args:[]}}}var E=class{pages=new Map;registerPage(e,t,r,i){let a=n();return this.pages.set(a,{page:e,url:t,title:r,label:i,createdAt:new Date}),a}getPageByLabel(e){for(let t of this.pages.values())if(t.label===e)return t.page;throw Error(`Page not found: ${e}`)}resolvePageId(e){if(this.pages.has(e))return e;for(let[t,n]of this.pages.entries())if(n.label===e)return t;throw Error(`Page not found: ${e}`)}getPage(e){let t=this.pages.get(e);if(!t)throw Error(`Page not found: ${e}`);return t.page}getPageInfo(e){let t=this.pages.get(e);if(!t)throw Error(`Page not found: ${e}`);return{pageId:e,url:t.url,title:t.title,label:t.label,createdAt:t.createdAt}}setSnapshot(e,t){let n=this.pages.get(e);if(!n)throw Error(`Page not found: ${e}`);this.pages.set(e,{...n,lastSnapshot:t})}getSnapshot(e){let t=this.pages.get(e);if(!t)throw Error(`Page not found: ${e}`);return t.lastSnapshot}updatePageInfo(e,t,n){let r=this.pages.get(e);if(!r)throw Error(`Page not found: ${e}`);this.pages.set(e,{...r,url:t,title:n})}async removePage(e){let t=this.pages.get(e);t&&(await t.page.close(),this.pages.delete(e))}listPages(){return[...this.pages.entries()].map(([e,t])=>({pageId:e,url:t.url,title:t.title,label:t.label,createdAt:t.createdAt}))}async closeAll(){await Promise.allSettled([...this.pages.keys()].map(async e=>this.removePage(e)))}get size(){return this.pages.size}};const D={defaultMode:`ui`,browsersPath:null,userDataDirRoot:null,idleShutdownMinutes:10,allowInternalSchemes:!1,evalTimeoutMs:1e4,evalMaxResultBytes:262144,redactPasswordFieldsInScreenshots:!0};var O=class{browser=null;context=null;idleTimer=null;launchPromise=null;currentMode=null;session=new E;config;constructor(e={}){this.config={...D,...e}}async launch(e,t){let n=w(e??this.config.defaultMode);if(this.context&&this.currentMode!==n&&await this.close(),!this.context){if(this.launchPromise)return this.launchPromise;this.launchPromise=this.doLaunch(n,t);try{await this.launchPromise}finally{this.launchPromise=null}}}async doLaunch(e,n){if(this.browser&&this.context)return;let a=b(this.config);process.env.PLAYWRIGHT_BROWSERS_PATH=a;let{chromium:o}=await import(`playwright-core`),s=await S(this.config,n),c=T(e),l=t(`sha256`).update(process.cwd()).digest(`hex`).slice(0,12),u=i(this.config.userDataDirRoot??i(r(),`.aikit`,`profiles`),l);if(n?.(`Launching Chromium in ${e} mode`),this.context=await o.launchPersistentContext(u,{headless:c.headless,args:c.args,executablePath:s,viewport:null}),this.browser=this.context.browser(),!this.browser)throw await this.context.close(),this.context=null,Error(`Failed to acquire Chromium browser instance`);this.currentMode=e,this.browser.on(`disconnected`,()=>{this.browser=null,this.context=null,this.currentMode=null,y().clear(),this.session.closeAll().catch(()=>{}),this.stopIdleTimer()}),this.resetIdleTimer()}stopIdleTimer(){this.idleTimer&&=(clearTimeout(this.idleTimer),null)}resetIdleTimer(){this.stopIdleTimer();let e=setTimeout(()=>{this.close()},this.config.idleShutdownMinutes*6e4);e.unref?.(),this.idleTimer=e}async close(){this.stopIdleTimer(),this.launchPromise=null;let e=this.context,t=this.browser;this.context=null,this.browser=null,this.currentMode=null;let n;try{y().clear()}catch(e){n=e}try{await this.session.closeAll()}catch(e){n??=e}try{e&&await e.close()}catch(e){n??=e}finally{try{t&&await t.close()}catch(e){n??=e}}if(n)throw n}getContext(){if(!this.context)throw Error(`Browser not launched. Call launch() first.`);return this.context}getConfig(){return this.config}isLaunched(){return this.browser!==null}};let k=null;function A(e){return k||=new O(e),k}async function ge(){k&&=(await k.close(),null)}const _e=[`file:`,`chrome:`,`chrome-extension:`,`data:`,`javascript:`],ve=[`169.254.169.254`,`metadata.google.internal`,`metadata.google.com`],j=[`localhost`,`127.0.0.1`,`::1`,`[::1]`];function ye(e){return e.replace(/^\[(.*)\]$/,`$1`).toLowerCase()}function be(e){let t=new WeakSet,n=JSON.stringify(e,(e,n)=>{if(typeof n==`bigint`)return n.toString();if(typeof n==`function`)return`[Function ${n.name||`anonymous`}]`;if(typeof n==`symbol`)return n.toString();if(n instanceof Error)return{name:n.name,message:n.message,stack:n.stack};if(typeof n==`object`&&n){if(t.has(n))return`[Circular]`;t.add(n)}return n});return n===void 0?e===void 0?`undefined`:String(e):n}function xe(e,t){let n=c.from(e,`utf8`);return n.byteLength<=t?e:n.subarray(0,t).toString(`utf8`)}function M(e,t){let n;try{n=new URL(e)}catch{return{allowed:!1,reason:`Invalid URL: ${e}`}}let r=n.protocol.toLowerCase();if(_e.includes(r)&&!t.allowInternalSchemes)return{allowed:!1,reason:`Blocked URL scheme: ${r}`};let i=ye(n.hostname);return ve.includes(i)?{allowed:!1,reason:`Blocked host: ${n.hostname}`}:(j.includes(i)||j.includes(n.hostname),{allowed:!0})}function N(e){return e?{allowed:!0}:{allowed:!1,reason:`Cookie access requires explicit confirmation (confirm: true)`}}function P(e,t){if(t<=0)return{valid:!1,reason:`maxBytes must be greater than 0`};try{let n=be(e);return c.byteLength(n,`utf8`)<=t?{valid:!0,result:n,truncated:!1}:{valid:!0,result:`${xe(n,Math.max(t-3,0))}...`,truncated:!0,reason:`Result exceeded ${t} bytes and was truncated`}}catch(e){return{valid:!1,reason:`Unable to serialize eval result: ${e instanceof Error?e.message:String(e)}`}}}function Se(e){return e.replace(/<input\b[^>]*>/gi,e=>/\btype\s*=\s*(["'])password\1/i.test(e)?/\bvalue\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+)/i.test(e)?e.replace(/\bvalue\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+)/i,`value="***"`):e.replace(/\s*\/?>$/,e=>` value="***"${e}`):e)}const Ce=[`ui`,`headless`];function we(e){return typeof e==`object`&&e?e:null}function F(e){return typeof e==`string`&&e.length>0?e:void 0}function I(e){return typeof e==`boolean`?e:void 0}function L(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}function R(e){return typeof e==`string`&&Ce.includes(e)?e:void 0}function z(e){let t=process.env[e];if(!t)return;let n=Number(t);return Number.isFinite(n)?n:void 0}function Te(e){let t=we(e.browser)??{};return{...D,defaultMode:R(process.env.AIKIT_BROWSER_DEFAULT_MODE)??R(t.defaultMode)??D.defaultMode,browsersPath:F(process.env.AIKIT_BROWSER_PATH)??F(process.env.AIKIT_BROWSER_BROWSERS_PATH)??F(t.browsersPath)??D.browsersPath,userDataDirRoot:F(t.userDataDirRoot)??D.userDataDirRoot,idleShutdownMinutes:z(`AIKIT_BROWSER_IDLE_MINUTES`)??L(t.idleShutdownMinutes)??D.idleShutdownMinutes,allowInternalSchemes:I(t.allowInternalSchemes)??D.allowInternalSchemes,evalTimeoutMs:z(`AIKIT_BROWSER_EVAL_TIMEOUT_MS`)??L(t.evalTimeoutMs)??D.evalTimeoutMs,evalMaxResultBytes:L(t.evalMaxResultBytes)??D.evalMaxResultBytes,redactPasswordFieldsInScreenshots:I(t.redactPasswordFieldsInScreenshots)??D.redactPasswordFieldsInScreenshots}}function B(e,t){return{content:[{type:`text`,text:e}],structuredContent:t}}function V(e,t){let n=e.selector??e.ref??(e.element?`text=${e.element}`:void 0);if(!n)throw Error(`${t} requires selector, ref, or element`);return n}async function Ee(e,t,n){let r=null;try{return await Promise.race([e,new Promise((e,i)=>{r=setTimeout(()=>{i(Error(`${n} timed out after ${t}ms`))},t)})])}finally{r&&clearTimeout(r)}}l.string().describe(`Tracked browser page identifier`),l.enum([`click`,`type`,`press`,`hover`,`drag`,`select`,`scroll`,`upload`]).describe(`Interaction kind: click, type, press, hover, drag, select, scroll, upload`),l.string().optional().describe(`Target ref alias`),l.string().optional().describe(`Playwright selector`),l.string().optional().describe(`Human-readable element label`),l.string().optional().describe(`Text to type`),l.string().optional().describe(`Key to press`),l.string().optional().describe(`Option value, drag target, scroll spec, or file path(s)`),l.string().optional().describe(`Drag source ref`),l.string().optional().describe(`Drag source selector`),l.string().optional().describe(`Drag target ref`),l.string().optional().describe(`Drag target selector`);function De(e){return async({pageId:t,kind:n,ref:r,selector:i,element:a,text:o,key:s,value:c,fromRef:l,fromSelector:u,toRef:d,toSelector:f})=>{let p=A(e),m=p.session.getPage(t);switch(n){case`click`:{let e=V({ref:r,selector:i,element:a},`browser_act(click)`);await m.click(e);break}case`type`:{let e=V({ref:r,selector:i,element:a},`browser_act(type)`);await m.fill(e,o??``);break}case`press`:{let e=V({ref:r,selector:i,element:a},`browser_act(press)`);if(!s)throw Error(`browser_act(press) requires key`);await m.press(e,s);break}case`hover`:{let e=V({ref:r,selector:i,element:a},`browser_act(hover)`);await m.hover(e);break}case`drag`:{let e=V({ref:l??r,selector:u??i,element:a},`browser_act(drag) source`),t=V({ref:d,selector:f??c,element:a},`browser_act(drag) target`);await m.dragAndDrop(e,t);break}case`select`:{let e=V({ref:r,selector:i,element:a},`browser_act(select)`);if(c===void 0)throw Error(`browser_act(select) requires value`);await m.selectOption(e,c);break}case`scroll`:{if(i||r||a){let e=V({ref:r,selector:i,element:a},`browser_act(scroll)`);await m.locator(e).scrollIntoViewIfNeeded();break}let e=c??`down 500`;await m.evaluate(e=>{if(e===`bottom`){window.scrollTo(0,document.body.scrollHeight);return}if(e===`top`){window.scrollTo(0,0);return}let t=e.split(` `),n=t[0]||`down`,r=Number.parseInt(t[1]||`500`,10),i=n===`left`?-r:n===`right`?r:0,a=n===`up`?-r:n===`down`?r:0;window.scrollBy(i,a)},e);break}case`upload`:{let e=V({ref:r,selector:i,element:a},`browser_act(upload)`);if(!c)throw Error(`value (file path or JSON array of paths) required for upload`);let t;try{let e=JSON.parse(c);t=Array.isArray(e)?e:[c]}catch{t=[c]}await m.locator(e).setInputFiles(t);break}}return p.resetIdleTimer(),B(`ok`,{ok:!0})}}function Oe(e,t){return t?e.filter(e=>e.level===t):e}function ke(e){return e.map(e=>{let t=e.location?` (${e.location.url}:${e.location.line})`:``;return`[${e.level.toUpperCase()}] ${e.text}${t}`}).join(`
|
|
1
|
+
import{createRequire as e}from"node:module";import{createHash as t,randomUUID as n}from"node:crypto";import{homedir as r}from"node:os";import{join as i}from"node:path";import{execFileSync as a}from"node:child_process";import{existsSync as o,readdirSync as s}from"node:fs";import{Buffer as c}from"node:buffer";import{z as l}from"zod";var u=class{#e;#t;#n=0;#r=0;constructor(e=200){if(!Number.isInteger(e)||e<1)throw RangeError(`CircularBuffer capacity must be a positive integer.`);this.#e=e,this.#t=Array(e)}push(e){this.#t[this.#n]=e,this.#n=(this.#n+1)%this.#e,this.#r<this.#e&&(this.#r+=1)}toArray(){if(this.#r===0)return[];let e=(this.#n-this.#r+this.#e)%this.#e,t=[];for(let n=0;n<this.#r;n+=1)t.push(this.#t[(e+n)%this.#e]);return t}clear(){this.#t=Array(this.#e),this.#n=0,this.#r=0}get size(){return this.#r}get capacity(){return this.#e}isEmpty(){return this.#r===0}};const d=[`xhr`,`fetch`,`websocket`,`document`],f=[/^authorization$/i,/^cookie$/i,/^set-cookie$/i,/^x-api-key$/i,/^x-access-token$/i,/^x-auth-token$/i,/^x-session$/i,/^x-secret$/i,/^x-password$/i,/^proxy-authorization$/i,/^www-authenticate$/i,/^x-csrf-token$/i,/^x-xsrf-token$/i];function p(e,t){if(t?.showSensitive)return{...e};let n=[...f,...t?.additionalPatterns??[]],r={};for(let[t,i]of Object.entries(e))r[t]=n.some(e=>e.test(t))?`[REDACTED]`:i;return r}function m(e,t=512){if(e)return e.length<=t?e:`${e.slice(0,t)}...[truncated]`}function ee(){return{networkBuffer:new u(200),consoleBuffer:new u(1e3),networkEnabled:!1,consoleEnabled:!1,networkFilter:{},nextRequestSequence:0,pendingRequests:new Map}}function te(e,t){if(e.capacity===t)return e;let n=new u(t),r=e.toArray(),i=Math.max(0,r.length-t);for(let e of r.slice(i))n.push(e);return n}function ne(e){switch(e){case`error`:case`info`:case`log`:case`debug`:return e;case`warning`:return`warn`;default:return`log`}}function re(e){if(e)return Buffer.byteLength(e)<=5242880?m(e):void 0}function ie(e){if(!e)return{};let t=Buffer.byteLength(e);return{bodySize:t,bodyPreview:t<=5242880?m(e):void 0}}function ae(e,t){return!t.resourceTypes.has(e.resourceType)||t.urlPattern&&!t.urlPattern.test(e.url)?!1:!t.excludeUrls.some(t=>t.test(e.url))}function h(e){if(e.length>200)throw Error(`Network filter regex patterns must be 200 characters or fewer`);try{let t=new RegExp(e);return t.test(`a`.repeat(100)),t}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`Invalid network filter regex pattern: ${t}`)}}function g(e={}){return{resourceTypes:new Set(e.resourceTypes??d),urlPattern:e.urlPattern?h(e.urlPattern):void 0,excludeUrls:(e.excludeUrls??[]).map(e=>h(e))}}function oe(e){return e.nextRequestSequence+=1,`req-${e.nextRequestSequence}`}function se(e,t,n){let r={request:t,previous:e.pendingRequestTail};e.pendingRequestTail?e.pendingRequestTail.next=r:e.pendingRequestHead=r,e.pendingRequestTail=r,e.pendingRequests.set(t,{entry:n,node:r})}function _(e,t){t.previous?t.previous.next=t.next:e.pendingRequestHead=t.next,t.next?t.next.previous=t.previous:e.pendingRequestTail=t.previous,delete t.previous,delete t.next}function ce(e){for(;e.pendingRequests.size>e.networkBuffer.capacity;){let t=e.pendingRequestHead;if(!t)return;_(e,t),e.pendingRequests.delete(t.request)}}function v(e){e.pendingRequests.clear(),e.pendingRequestHead=void 0,e.pendingRequestTail=void 0}var le=class{states=new Map;getOrCreate(e){let t=this.states.get(e);if(t)return t;let n=ee();return this.states.set(e,n),n}get(e){return this.states.get(e)}remove(e){let t=this.states.get(e);t&&(t.networkEnabled=!1,t.consoleEnabled=!1,this.detachNetworkListeners(t),this.detachConsoleListeners(t),v(t),this.states.delete(e))}clear(){for(let e of this.states.values())e.networkEnabled=!1,e.consoleEnabled=!1,this.detachNetworkListeners(e),this.detachConsoleListeners(e),v(e);this.states.clear()}enableNetwork(e,t,n,r){let i=this.getOrCreate(e);i.networkEnabled&&this.disableNetwork(e,t),i.page=t,i.networkEnabled=!0,i.networkFilter=n?{...n}:{},i.compiledNetworkFilter=g(i.networkFilter),r?.bufferSize&&(i.networkBuffer=te(i.networkBuffer,r.bufferSize));let a=e=>{let t=i.compiledNetworkFilter??g(i.networkFilter),n={resourceType:e.resourceType(),url:e.url()};if(!ae(n,t))return;let a={...e.headers()},o=Date.now(),s={id:oe(i),url:n.url,method:e.method(),resourceType:n.resourceType,headers:r?.showSensitive?a:p(a),postData:r?.includeBody?re(e.postData()??void 0):void 0,timestamp:o};i.networkBuffer.push(s),se(i,e,s),ce(i)},o=async e=>{let t=e.request(),n=i.pendingRequests.get(t);if(!n)return;i.pendingRequests.delete(t),_(i,n.node);let a;if(r?.includeBody)try{a=ie(await e.text())}catch{a=void 0}let o={...e.headers()};n.entry.response={status:e.status(),statusText:e.statusText(),headers:r?.showSensitive?o:p(o),bodySize:a?.bodySize,bodyPreview:a?.bodyPreview,timing:Date.now()-n.entry.timestamp}};i.listenerRefs={...i.listenerRefs,requestHandler:a,responseHandler:o},this.ensurePageCloseHandler(e,i,t),t.on(`request`,a),t.on(`response`,o)}disableNetwork(e,t){let n=this.states.get(e);n&&(n.page=n.page??t,n.networkEnabled=!1,this.detachNetworkListeners(n),v(n))}enableConsole(e,t,n){let r=this.getOrCreate(e);r.consoleEnabled&&this.disableConsole(e,t),r.page=t,r.consoleEnabled=!0,n?.bufferSize&&(r.consoleBuffer=te(r.consoleBuffer,n.bufferSize));let i=e=>{let t=e.location();r.consoleBuffer.push({level:ne(e.type()),text:e.text(),timestamp:Date.now(),location:t.url?{url:t.url,line:t.lineNumber,column:t.columnNumber}:void 0,args:e.args().map(e=>e.toString())})};r.listenerRefs={...r.listenerRefs,consoleHandler:i},this.ensurePageCloseHandler(e,r,t),t.on(`console`,i)}disableConsole(e,t){let n=this.states.get(e);n&&(n.page=n.page??t,n.consoleEnabled=!1,this.detachConsoleListeners(n))}detachNetworkListeners(e){let t=e.page,n=e.listenerRefs?.requestHandler,r=e.listenerRefs?.responseHandler;t&&n&&t.off(`request`,n),t&&r&&t.off(`response`,r),e.listenerRefs&&(delete e.listenerRefs.requestHandler,delete e.listenerRefs.responseHandler),this.detachPageCloseHandlerIfUnused(e)}detachConsoleListeners(e){let t=e.page,n=e.listenerRefs?.consoleHandler;t&&n&&t.off(`console`,n),e.listenerRefs&&delete e.listenerRefs.consoleHandler,this.detachPageCloseHandlerIfUnused(e)}ensurePageCloseHandler(e,t,n){if(t.listenerRefs?.pageCloseHandler)return;let r=()=>{this.remove(e)};t.listenerRefs={...t.listenerRefs,pageCloseHandler:r},n.on(`close`,r)}detachPageCloseHandlerIfUnused(e){if(e.networkEnabled||e.consoleEnabled)return;let t=e.page,n=e.listenerRefs?.pageCloseHandler;t&&n&&t.off(`close`,n),e.listenerRefs&&delete e.listenerRefs.pageCloseHandler,e.listenerRefs&&!e.listenerRefs.requestHandler&&!e.listenerRefs.responseHandler&&!e.listenerRefs.consoleHandler&&!e.listenerRefs.pageCloseHandler&&delete e.listenerRefs}};let ue=null;function y(){return ue||=new le,ue}const de=e(import.meta.url);function fe(e){return typeof e==`string`?e.trim():e instanceof Buffer?e.toString(`utf8`).trim():``}function pe(e){process.env.PLAYWRIGHT_BROWSERS_PATH=e}async function me(e){pe(e);let{chromium:t}=await import(`playwright-core`),n=t.executablePath();if(!n)throw Error(`Chromium executable not found in ${e}`);return n}function he(){return i(r(),`.aikit`,`browsers`)}function b(e){return e.browsersPath??process.env.PLAYWRIGHT_BROWSERS_PATH??he()}function x(e){return o(e)?s(e,{withFileTypes:!0}).some(e=>e.isDirectory()&&e.name.toLowerCase().startsWith(`chromium-`)):!1}async function S(e,t){let n=b(e);if(pe(n),t?.(`Using Chromium cache at ${n}`),x(n))return t?.(`Chromium already installed`),me(n);let r=i(de.resolve(`playwright-core`),`..`,`cli.js`);t?.(`Installing Chromium via playwright-core`);try{a(process.execPath,[r,`install`,`chromium`],{env:{...process.env,PLAYWRIGHT_BROWSERS_PATH:n},encoding:`utf8`,stdio:`pipe`})}catch(e){let t=e,n=fe(t.stderr),r=fe(t.stdout),i=n||r||t.message||`Unknown playwright install failure`;throw Error(`Failed to install Chromium: ${i}`)}return t?.(`Chromium install complete`),me(n)}function C(){return process.platform===`win32`||process.platform===`darwin`?!0:!!(process.env.DISPLAY||process.env.WAYLAND_DISPLAY)}function w(e){return e===`headless`||!C()?`headless`:e}function T(e){switch(e){case`headless`:return{headless:!0,args:[]};default:return{headless:!1,args:[]}}}var E=class{pages=new Map;registerPage(e,t,r,i){let a=n();return this.pages.set(a,{page:e,url:t,title:r,label:i,createdAt:new Date}),a}getPageByLabel(e){for(let t of this.pages.values())if(t.label===e)return t.page;throw Error(`Page not found: ${e}`)}resolvePageId(e){if(this.pages.has(e))return e;for(let[t,n]of this.pages.entries())if(n.label===e)return t;throw Error(`Page not found: ${e}`)}getPage(e){let t=this.pages.get(e);if(!t)throw Error(`Page not found: ${e}`);return t.page}getPageInfo(e){let t=this.pages.get(e);if(!t)throw Error(`Page not found: ${e}`);return{pageId:e,url:t.url,title:t.title,label:t.label,createdAt:t.createdAt}}setSnapshot(e,t){let n=this.pages.get(e);if(!n)throw Error(`Page not found: ${e}`);this.pages.set(e,{...n,lastSnapshot:t})}getSnapshot(e){let t=this.pages.get(e);if(!t)throw Error(`Page not found: ${e}`);return t.lastSnapshot}updatePageInfo(e,t,n){let r=this.pages.get(e);if(!r)throw Error(`Page not found: ${e}`);this.pages.set(e,{...r,url:t,title:n})}async removePage(e){let t=this.pages.get(e);t&&(await t.page.close(),this.pages.delete(e))}listPages(){return[...this.pages.entries()].map(([e,t])=>({pageId:e,url:t.url,title:t.title,label:t.label,createdAt:t.createdAt}))}async closeAll(){await Promise.allSettled([...this.pages.keys()].map(async e=>this.removePage(e)))}get size(){return this.pages.size}};const D={defaultMode:`ui`,browsersPath:null,userDataDirRoot:null,idleShutdownMinutes:10,allowInternalSchemes:!1,evalTimeoutMs:1e4,evalMaxResultBytes:262144,redactPasswordFieldsInScreenshots:!0};var O=class{browser=null;context=null;idleTimer=null;launchPromise=null;currentMode=null;session=new E;config;constructor(e={}){this.config={...D,...e}}async launch(e,t){let n=w(e??this.config.defaultMode);if(this.context&&this.currentMode!==n)if(this.currentMode===`headless`&&n===`ui`)await this.close();else return;if(!this.context){if(this.launchPromise)return this.launchPromise;this.launchPromise=this.doLaunch(n,t);try{await this.launchPromise}finally{this.launchPromise=null}}}async doLaunch(e,n){if(this.browser&&this.context)return;let a=b(this.config);process.env.PLAYWRIGHT_BROWSERS_PATH=a;let{chromium:o}=await import(`playwright-core`),s=await S(this.config,n),c=T(e),l=t(`sha256`).update(process.cwd()).digest(`hex`).slice(0,12),u=i(this.config.userDataDirRoot??i(r(),`.aikit`,`profiles`),l);if(n?.(`Launching Chromium in ${e} mode`),this.context=await o.launchPersistentContext(u,{headless:c.headless,args:c.args,executablePath:s,viewport:null}),this.browser=this.context.browser(),!this.browser)throw await this.context.close(),this.context=null,Error(`Failed to acquire Chromium browser instance`);this.currentMode=e,this.browser.on(`disconnected`,()=>{this.browser=null,this.context=null,this.currentMode=null,y().clear(),this.session.closeAll().catch(()=>{}),this.stopIdleTimer()}),this.resetIdleTimer()}stopIdleTimer(){this.idleTimer&&=(clearTimeout(this.idleTimer),null)}resetIdleTimer(){this.stopIdleTimer();let e=setTimeout(()=>{this.close()},this.config.idleShutdownMinutes*6e4);e.unref?.(),this.idleTimer=e}async close(){this.stopIdleTimer(),this.launchPromise=null;let e=this.context,t=this.browser;this.context=null,this.browser=null,this.currentMode=null;let n;try{y().clear()}catch(e){n=e}try{await this.session.closeAll()}catch(e){n??=e}try{e&&await e.close()}catch(e){n??=e}finally{try{t&&await t.close()}catch(e){n??=e}}if(n)throw n}getContext(){if(!this.context)throw Error(`Browser not launched. Call launch() first.`);return this.context}getConfig(){return this.config}isLaunched(){return this.browser!==null}};let k=null;function A(e){return k||=new O(e),k}async function ge(){k&&=(await k.close(),null)}const _e=[`file:`,`chrome:`,`chrome-extension:`,`data:`,`javascript:`],ve=[`169.254.169.254`,`metadata.google.internal`,`metadata.google.com`],j=[`localhost`,`127.0.0.1`,`::1`,`[::1]`];function ye(e){return e.replace(/^\[(.*)\]$/,`$1`).toLowerCase()}function be(e){let t=new WeakSet,n=JSON.stringify(e,(e,n)=>{if(typeof n==`bigint`)return n.toString();if(typeof n==`function`)return`[Function ${n.name||`anonymous`}]`;if(typeof n==`symbol`)return n.toString();if(n instanceof Error)return{name:n.name,message:n.message,stack:n.stack};if(typeof n==`object`&&n){if(t.has(n))return`[Circular]`;t.add(n)}return n});return n===void 0?e===void 0?`undefined`:String(e):n}function xe(e,t){let n=c.from(e,`utf8`);return n.byteLength<=t?e:n.subarray(0,t).toString(`utf8`)}function M(e,t){let n;try{n=new URL(e)}catch{return{allowed:!1,reason:`Invalid URL: ${e}`}}let r=n.protocol.toLowerCase();if(_e.includes(r)&&!t.allowInternalSchemes)return{allowed:!1,reason:`Blocked URL scheme: ${r}`};let i=ye(n.hostname);return ve.includes(i)?{allowed:!1,reason:`Blocked host: ${n.hostname}`}:(j.includes(i)||j.includes(n.hostname),{allowed:!0})}function N(e){return e?{allowed:!0}:{allowed:!1,reason:`Cookie access requires explicit confirmation (confirm: true)`}}function P(e,t){if(t<=0)return{valid:!1,reason:`maxBytes must be greater than 0`};try{let n=be(e);return c.byteLength(n,`utf8`)<=t?{valid:!0,result:n,truncated:!1}:{valid:!0,result:`${xe(n,Math.max(t-3,0))}...`,truncated:!0,reason:`Result exceeded ${t} bytes and was truncated`}}catch(e){return{valid:!1,reason:`Unable to serialize eval result: ${e instanceof Error?e.message:String(e)}`}}}function Se(e){return e.replace(/<input\b[^>]*>/gi,e=>/\btype\s*=\s*(["'])password\1/i.test(e)?/\bvalue\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+)/i.test(e)?e.replace(/\bvalue\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+)/i,`value="***"`):e.replace(/\s*\/?>$/,e=>` value="***"${e}`):e)}const Ce=[`ui`,`headless`];function we(e){return typeof e==`object`&&e?e:null}function F(e){return typeof e==`string`&&e.length>0?e:void 0}function I(e){return typeof e==`boolean`?e:void 0}function L(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}function R(e){return typeof e==`string`&&Ce.includes(e)?e:void 0}function z(e){let t=process.env[e];if(!t)return;let n=Number(t);return Number.isFinite(n)?n:void 0}function Te(e){let t=we(e.browser)??{};return{...D,defaultMode:R(process.env.AIKIT_BROWSER_DEFAULT_MODE)??R(t.defaultMode)??D.defaultMode,browsersPath:F(process.env.AIKIT_BROWSER_PATH)??F(process.env.AIKIT_BROWSER_BROWSERS_PATH)??F(t.browsersPath)??D.browsersPath,userDataDirRoot:F(t.userDataDirRoot)??D.userDataDirRoot,idleShutdownMinutes:z(`AIKIT_BROWSER_IDLE_MINUTES`)??L(t.idleShutdownMinutes)??D.idleShutdownMinutes,allowInternalSchemes:I(t.allowInternalSchemes)??D.allowInternalSchemes,evalTimeoutMs:z(`AIKIT_BROWSER_EVAL_TIMEOUT_MS`)??L(t.evalTimeoutMs)??D.evalTimeoutMs,evalMaxResultBytes:L(t.evalMaxResultBytes)??D.evalMaxResultBytes,redactPasswordFieldsInScreenshots:I(t.redactPasswordFieldsInScreenshots)??D.redactPasswordFieldsInScreenshots}}function B(e,t){return{content:[{type:`text`,text:e}],structuredContent:t}}function V(e,t){let n=e.selector??e.ref??(e.element?`text=${e.element}`:void 0);if(!n)throw Error(`${t} requires selector, ref, or element`);return n}async function Ee(e,t,n){let r=null;try{return await Promise.race([e,new Promise((e,i)=>{r=setTimeout(()=>{i(Error(`${n} timed out after ${t}ms`))},t)})])}finally{r&&clearTimeout(r)}}l.string().describe(`Tracked browser page identifier`),l.enum([`click`,`type`,`press`,`hover`,`drag`,`select`,`scroll`,`upload`]).describe(`Interaction kind: click, type, press, hover, drag, select, scroll, upload`),l.string().optional().describe(`Target ref alias`),l.string().optional().describe(`Playwright selector`),l.string().optional().describe(`Human-readable element label`),l.string().optional().describe(`Text to type`),l.string().optional().describe(`Key to press`),l.string().optional().describe(`Option value, drag target, scroll spec, or file path(s)`),l.string().optional().describe(`Drag source ref`),l.string().optional().describe(`Drag source selector`),l.string().optional().describe(`Drag target ref`),l.string().optional().describe(`Drag target selector`);function De(e){return async({pageId:t,kind:n,ref:r,selector:i,element:a,text:o,key:s,value:c,fromRef:l,fromSelector:u,toRef:d,toSelector:f})=>{let p=A(e),m=p.session.getPage(t);switch(n){case`click`:{let e=V({ref:r,selector:i,element:a},`browser_act(click)`);await m.click(e);break}case`type`:{let e=V({ref:r,selector:i,element:a},`browser_act(type)`);await m.fill(e,o??``);break}case`press`:{let e=V({ref:r,selector:i,element:a},`browser_act(press)`);if(!s)throw Error(`browser_act(press) requires key`);await m.press(e,s);break}case`hover`:{let e=V({ref:r,selector:i,element:a},`browser_act(hover)`);await m.hover(e);break}case`drag`:{let e=V({ref:l??r,selector:u??i,element:a},`browser_act(drag) source`),t=V({ref:d,selector:f??c,element:a},`browser_act(drag) target`);await m.dragAndDrop(e,t);break}case`select`:{let e=V({ref:r,selector:i,element:a},`browser_act(select)`);if(c===void 0)throw Error(`browser_act(select) requires value`);await m.selectOption(e,c);break}case`scroll`:{if(i||r||a){let e=V({ref:r,selector:i,element:a},`browser_act(scroll)`);await m.locator(e).scrollIntoViewIfNeeded();break}let e=c??`down 500`;await m.evaluate(e=>{if(e===`bottom`){window.scrollTo(0,document.body.scrollHeight);return}if(e===`top`){window.scrollTo(0,0);return}let t=e.split(` `),n=t[0]||`down`,r=Number.parseInt(t[1]||`500`,10),i=n===`left`?-r:n===`right`?r:0,a=n===`up`?-r:n===`down`?r:0;window.scrollBy(i,a)},e);break}case`upload`:{let e=V({ref:r,selector:i,element:a},`browser_act(upload)`);if(!c)throw Error(`value (file path or JSON array of paths) required for upload`);let t;try{let e=JSON.parse(c);t=Array.isArray(e)?e:[c]}catch{t=[c]}await m.locator(e).setInputFiles(t);break}}return p.resetIdleTimer(),B(`ok`,{ok:!0})}}function Oe(e,t){return t?e.filter(e=>e.level===t):e}function ke(e){return e.map(e=>{let t=e.location?` (${e.location.url}:${e.location.line})`:``;return`[${e.level.toUpperCase()}] ${e.text}${t}`}).join(`
|
|
2
2
|
`)}async function Ae(e,t){let n=y();switch(t.subAction){case`enable`:return n.enableConsole(t.pageId,e,{bufferSize:t.bufferSize}),B(`Console capture enabled for page ${t.pageId}`,{enabled:!0,bufferSize:t.bufferSize??1e3});case`get`:{let e=n.get(t.pageId);if(!e?.consoleEnabled)return B(`Console capture not enabled. Call with subAction: "enable" first.`,{enabled:!1,entries:[]});let r=Oe(e.consoleBuffer.toArray(),t.level);return B(ke(r)||`No console messages captured yet.`,{enabled:!0,count:r.length,entries:r})}case`clear`:{let e=n.get(t.pageId);return e&&e.consoleBuffer.clear(),B(`Console buffer cleared.`,{cleared:!0})}}}function je(e){return async t=>{let n=A(e),r=await Ae(n.session.getPage(t.pageId),t);return n.resetIdleTimer(),r}}l.string().describe(`Tracked browser page identifier`),l.boolean().describe(`Whether to accept the next dialog`),l.string().optional().describe(`Text to provide when accepting a prompt dialog`);function Me(e){return async({pageId:t,accept:n,promptText:r})=>{let i=A(e);return i.session.getPage(t).once(`dialog`,async e=>{n?await e.accept(r):await e.dismiss()}),i.resetIdleTimer(),B(`ok`,{ok:!0})}}function Ne(e){return async({pageId:t})=>{let n=A(e),r=await n.session.getPage(t).accessibility.snapshot()??{},i=JSON.stringify(r,null,2),a=n.session.getSnapshot(t);if(n.session.setSnapshot(t,i),n.resetIdleTimer(),!a)return B(`First snapshot captured (no previous to diff against).\n${i}`,{pageId:t,hasChanges:!1,isFirst:!0,snapshot:r});if(a===i)return B(`No changes detected.`,{pageId:t,hasChanges:!1});let o=a.split(`
|
|
3
3
|
`),s=i.split(`
|
|
4
4
|
`),c=new Set(o),l=new Set(s),u=s.filter(e=>!c.has(e)),d=o.filter(e=>!l.has(e)),f=u.length>0||d.length>0;return B([u.length>0?`Added:\n${u.join(`
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{t as e}from"./curated-manager-BnP6VqvL.js";import{randomUUID as t}from"node:crypto";import{readFileSync as n}from"node:fs";import{dirname as r,resolve as i}from"node:path";import{fileURLToPath as a,pathToFileURL as o}from"node:url";import{parseArgs as s}from"node:util";import{createLogger as c,serializeError as l}from"../../core/dist/index.js";var u=class{stateStore;options;gcTimer=null;constructor(e,t={}){this.stateStore=e,this.options=t}onSessionStart(e,t){this.stateStore.sessionCreate(e,t)}onSessionActivity(e){this.stateStore.sessionTouch(e)}onSessionEnd(e){this.stateStore.sessionDelete(e)}startGC(){if(this.gcTimer)return;let e=(this.options.gcIntervalMinutes??5)*60*1e3;this.gcTimer=setInterval(()=>{this.runGC()},e),this.gcTimer.unref()}runGC(){let e=this.options.staleTimeoutMinutes??30;return this.stateStore.sessionDeleteStale(e)}stop(){this.gcTimer&&=(clearInterval(this.gcTimer),null)}getActiveSessions(){return this.stateStore.sessionList().length}};const d=r(a(import.meta.url)),f=(()=>{try{let e=i(d,`..`,`..`,`..`,`package.json`);return JSON.parse(n(e,`utf-8`)).version??`0.0.0`}catch{return`0.0.0`}})(),p=c(`server`);function m(){return process.env.AIKIT_TRANSPORT?process.env.AIKIT_TRANSPORT:process.stdin.isTTY?`http`:`stdio`}const h=(()=>{let e=process.argv[1];if(!e)return!1;try{return import.meta.url===o(e).href}catch{return!1}})();function g(e){let t=e.headers[`mcp-session-id`];return Array.isArray(t)?t[0]:t}const{values:_}=h?s({allowPositionals:!0,options:{transport:{type:`string`,default:m()},port:{type:`string`,default:process.env.AIKIT_PORT??`3210`}}}):{values:{transport:m(),port:process.env.AIKIT_PORT??`3210`}};async function v(){if(process.on(`unhandledRejection`,e=>{p.error(`Unhandled rejection`,l(e))}),process.on(`uncaughtException`,e=>{p.error(`Uncaught exception — exiting`,l(e)),process.exit(1)}),p.info(`Starting MCP AI Kit server`,{version:f}),_.transport===`http`){let[{default:e},{loadConfig:n,resolveIndexMode:r},{registerDashboardRoutes:i,resolveDashboardDir:a},{registerSettingsRoutes:o,resolveSettingsDir:s},{createSettingsRouter:c},{authMiddleware:d,getOrCreateToken:f}]=await Promise.all([import(`express`),import(`./config-DAnAxrUW.js`),import(`./dashboard-static-CnXafYTs.js`),import(`./settings-static-BkVLqWOr.js`),import(`./routes-CR3fI-HJ.js`),import(`./auth-BfqgawfR.js`).then(e=>e.t)]),m=n();p.info(`Config loaded`,{sourceCount:m.sources.length,storePath:m.store.path});let h=e();h.use(e.json());let v=Number(_.port);h.use((e,t,n)=>{if(t.setHeader(`Access-Control-Allow-Origin`,process.env.AIKIT_CORS_ORIGIN??`http://localhost:${v}`),t.setHeader(`Access-Control-Allow-Methods`,`GET, POST, PUT, PATCH, DELETE, OPTIONS`),t.setHeader(`Access-Control-Allow-Headers`,`Content-Type, Authorization, Mcp-Session-Id, Mcp-Protocol-Version, Last-Event-ID`),t.setHeader(`Access-Control-Expose-Headers`,`Mcp-Session-Id`),e.method===`OPTIONS`){t.status(204).end();return}n()});let y=f();console.error(`[aikit] Auth token: ~/.aikit/token`),h.use(d(y)),i(h,a(),p);let b=new Date().toISOString();h.use(`/settings/api`,c({log:p,mcpInfo:()=>({transport:`http`,port:v,pid:process.pid,startedAt:b})})),o(h,s(),p),h.get(`/health`,(e,t)=>{t.json({status:`ok`})});let x=!1,S=null,C=null,w=null,T=null,E=null,D=null,O=Promise.resolve(),k=async(e,n)=>{if(!x||!w||!T){n.status(503).json({jsonrpc:`2.0`,error:{code:-32603,message:`Server initializing — please retry in a few seconds`},id:null});return}let r=O,i;O=new Promise(e=>{i=e}),await r;try{let r=g(e);if(!E){if(r){n.status(404).json({jsonrpc:`2.0`,error:{code:-32001,message:`Session not found`},id:null});return}let e=new T({sessionIdGenerator:()=>t(),onsessioninitialized:async e=>{D=e,C?.onSessionStart(e,{transport:`http`})},onsessionclosed:async e=>{e&&C?.onSessionEnd(e),D=null}});e.onclose=()=>{E===e&&(E=null),D===e.sessionId&&(D=null)},E=e,await w.connect(e)}let i=E;await i.handleRequest(e,n,e.body),e.method!==`DELETE`&&(!r&&i.sessionId?(D=i.sessionId,C?.onSessionStart(i.sessionId,{transport:`http`}),C?.onSessionActivity(i.sessionId)):r&&C?.onSessionActivity(r))}catch(e){if(p.error(`MCP handler error`,l(e)),!n.headersSent){let t=e instanceof Error?e.message:String(e),r=t.includes(`Not Acceptable`);n.status(r?406:500).json({jsonrpc:`2.0`,error:{code:r?-32e3:-32603,message:r?t:`Internal server error`},id:null})}}finally{i()}};h.post(`/mcp`,k),h.get(`/mcp`,k),h.delete(`/mcp`,k);let A=h.listen(v,`127.0.0.1`,()=>{p.info(`MCP server listening`,{url:`http://127.0.0.1:${v}/mcp`,port:v}),setTimeout(async()=>{try{let[{createLazyServer:e,ALL_TOOL_NAMES:t},{StreamableHTTPServerTransport:n},{checkForUpdates:i,autoUpgradeScaffold:a}]=await Promise.all([import(`./server-
|
|
1
|
+
import{t as e}from"./curated-manager-BnP6VqvL.js";import{randomUUID as t}from"node:crypto";import{readFileSync as n}from"node:fs";import{dirname as r,resolve as i}from"node:path";import{fileURLToPath as a,pathToFileURL as o}from"node:url";import{parseArgs as s}from"node:util";import{createLogger as c,serializeError as l}from"../../core/dist/index.js";var u=class{stateStore;options;gcTimer=null;constructor(e,t={}){this.stateStore=e,this.options=t}onSessionStart(e,t){this.stateStore.sessionCreate(e,t)}onSessionActivity(e){this.stateStore.sessionTouch(e)}onSessionEnd(e){this.stateStore.sessionDelete(e)}startGC(){if(this.gcTimer)return;let e=(this.options.gcIntervalMinutes??5)*60*1e3;this.gcTimer=setInterval(()=>{this.runGC()},e),this.gcTimer.unref()}runGC(){let e=this.options.staleTimeoutMinutes??30;return this.stateStore.sessionDeleteStale(e)}stop(){this.gcTimer&&=(clearInterval(this.gcTimer),null)}getActiveSessions(){return this.stateStore.sessionList().length}};const d=r(a(import.meta.url)),f=(()=>{try{let e=i(d,`..`,`..`,`..`,`package.json`);return JSON.parse(n(e,`utf-8`)).version??`0.0.0`}catch{return`0.0.0`}})(),p=c(`server`);function m(){return process.env.AIKIT_TRANSPORT?process.env.AIKIT_TRANSPORT:process.stdin.isTTY?`http`:`stdio`}const h=(()=>{let e=process.argv[1];if(!e)return!1;try{return import.meta.url===o(e).href}catch{return!1}})();function g(e){let t=e.headers[`mcp-session-id`];return Array.isArray(t)?t[0]:t}const{values:_}=h?s({allowPositionals:!0,options:{transport:{type:`string`,default:m()},port:{type:`string`,default:process.env.AIKIT_PORT??`3210`}}}):{values:{transport:m(),port:process.env.AIKIT_PORT??`3210`}};async function v(){if(process.on(`unhandledRejection`,e=>{p.error(`Unhandled rejection`,l(e))}),process.on(`uncaughtException`,e=>{p.error(`Uncaught exception — exiting`,l(e)),process.exit(1)}),p.info(`Starting MCP AI Kit server`,{version:f}),_.transport===`http`){let[{default:e},{loadConfig:n,resolveIndexMode:r},{registerDashboardRoutes:i,resolveDashboardDir:a},{registerSettingsRoutes:o,resolveSettingsDir:s},{createSettingsRouter:c},{authMiddleware:d,getOrCreateToken:f}]=await Promise.all([import(`express`),import(`./config-DAnAxrUW.js`),import(`./dashboard-static-CnXafYTs.js`),import(`./settings-static-BkVLqWOr.js`),import(`./routes-CR3fI-HJ.js`),import(`./auth-BfqgawfR.js`).then(e=>e.t)]),m=n();p.info(`Config loaded`,{sourceCount:m.sources.length,storePath:m.store.path});let h=e();h.use(e.json());let v=Number(_.port);h.use((e,t,n)=>{if(t.setHeader(`Access-Control-Allow-Origin`,process.env.AIKIT_CORS_ORIGIN??`http://localhost:${v}`),t.setHeader(`Access-Control-Allow-Methods`,`GET, POST, PUT, PATCH, DELETE, OPTIONS`),t.setHeader(`Access-Control-Allow-Headers`,`Content-Type, Authorization, Mcp-Session-Id, Mcp-Protocol-Version, Last-Event-ID`),t.setHeader(`Access-Control-Expose-Headers`,`Mcp-Session-Id`),e.method===`OPTIONS`){t.status(204).end();return}n()});let y=f();console.error(`[aikit] Auth token: ~/.aikit/token`),h.use(d(y)),i(h,a(),p);let b=new Date().toISOString();h.use(`/settings/api`,c({log:p,mcpInfo:()=>({transport:`http`,port:v,pid:process.pid,startedAt:b})})),o(h,s(),p),h.get(`/health`,(e,t)=>{t.json({status:`ok`})});let x=!1,S=null,C=null,w=null,T=null,E=null,D=null,O=Promise.resolve(),k=async(e,n)=>{if(!x||!w||!T){n.status(503).json({jsonrpc:`2.0`,error:{code:-32603,message:`Server initializing — please retry in a few seconds`},id:null});return}let r=O,i;O=new Promise(e=>{i=e}),await r;try{let r=g(e);if(!E){if(r){n.status(404).json({jsonrpc:`2.0`,error:{code:-32001,message:`Session not found`},id:null});return}let e=new T({sessionIdGenerator:()=>t(),onsessioninitialized:async e=>{D=e,C?.onSessionStart(e,{transport:`http`})},onsessionclosed:async e=>{e&&C?.onSessionEnd(e),D=null}});e.onclose=()=>{E===e&&(E=null),D===e.sessionId&&(D=null)},E=e,await w.connect(e)}let i=E;await i.handleRequest(e,n,e.body),e.method!==`DELETE`&&(!r&&i.sessionId?(D=i.sessionId,C?.onSessionStart(i.sessionId,{transport:`http`}),C?.onSessionActivity(i.sessionId)):r&&C?.onSessionActivity(r))}catch(e){if(p.error(`MCP handler error`,l(e)),!n.headersSent){let t=e instanceof Error?e.message:String(e),r=t.includes(`Not Acceptable`);n.status(r?406:500).json({jsonrpc:`2.0`,error:{code:r?-32e3:-32603,message:r?t:`Internal server error`},id:null})}}finally{i()}};h.post(`/mcp`,k),h.get(`/mcp`,k),h.delete(`/mcp`,k);let A=h.listen(v,`127.0.0.1`,()=>{p.info(`MCP server listening`,{url:`http://127.0.0.1:${v}/mcp`,port:v}),setTimeout(async()=>{try{let[{createLazyServer:e,ALL_TOOL_NAMES:t},{StreamableHTTPServerTransport:n},{checkForUpdates:i,autoUpgradeScaffold:a}]=await Promise.all([import(`./server-Ba4DFlFb.js`),import(`@modelcontextprotocol/sdk/server/streamableHttp.js`),import(`./version-check-BgHzxxCW.js`)]);i(),a();let o=r(m),s=e(m,o);w=s.server,T=n,x=!0,p.info(`MCP server configured (lazy — AI Kit initializing in background)`,{toolCount:t.length,resourceCount:2}),s.startInit(),s.ready.then(()=>{if(!s.aikit)throw Error(`AI Kit components are not available after initialization`);C=new u(s.aikit.stateStore),C.startGC(),D&&(C.onSessionStart(D,{transport:`http`}),C.onSessionActivity(D))}).catch(e=>p.error(`Failed to start session manager`,l(e))),o===`auto`?s.ready.then(async()=>{try{let e=m.sources.map(e=>e.path).join(`, `);p.info(`Running initial index`,{sourcePaths:e}),await s.runInitialIndex(),p.info(`Initial index complete`)}catch(e){p.error(`Initial index failed; will retry on aikit_reindex`,l(e))}}).catch(e=>p.error(`AI Kit init or indexing failed`,l(e))):o===`smart`?s.ready.then(async()=>{try{if(!s.aikit)throw Error(`AI Kit components are not available after initialization`);let{SmartIndexScheduler:e}=await import(`../../indexer/dist/index.js`),t=new e(s.aikit.indexer,m,s.aikit.store),n=s.aikit.store;S=t,t.start(),n.onBeforeClose&&n.onBeforeClose(()=>t.stop()),s.setSmartScheduler(t),p.info(`Smart index scheduler started (HTTP mode)`)}catch(e){p.error(`Failed to start smart index scheduler`,l(e))}}).catch(e=>p.error(`AI Kit initialization failed`,l(e))):(s.ready.catch(e=>p.error(`AI Kit initialization failed`,l(e))),p.info(`Initial full indexing skipped in HTTP mode`,{indexMode:o}))}catch(e){p.error(`Failed to load server modules`,l(e))}},100)}),j=async e=>{p.info(`Shutdown signal received`,{signal:e}),S?.stop(),C?.stop(),D&&C?.onSessionEnd(D),E&&(await E.close().catch(()=>void 0),E=null,D=null),A.close(),w&&await w.close(),process.exit(0)};process.on(`SIGINT`,()=>j(`SIGINT`)),process.on(`SIGTERM`,()=>j(`SIGTERM`))}else{let[{loadConfig:e,reconfigureForWorkspace:t,resolveIndexMode:n},{createLazyServer:r},{checkForUpdates:i,autoUpgradeScaffold:o},{RootsListChangedNotificationSchema:s}]=await Promise.all([import(`./config-DAnAxrUW.js`),import(`./server-Ba4DFlFb.js`),import(`./version-check-BgHzxxCW.js`),import(`@modelcontextprotocol/sdk/types.js`)]),c=e();p.info(`Config loaded`,{sourceCount:c.sources.length,storePath:c.store.path}),i(),o();let u=n(c),d=r(c,u),{server:f,startInit:m,ready:h,runInitialIndex:g}=d,{StdioServerTransport:_}=await import(`@modelcontextprotocol/sdk/server/stdio.js`),v=new _;await f.connect(v),p.info(`MCP server started`,{transport:`stdio`});let y=e=>{if(e.length===0)return!1;let n=e[0].uri,r=n.startsWith(`file://`)?a(n):n;return p.info(`MCP roots resolved`,{rootUri:n,rootPath:r,rootCount:e.length}),t(c,r),c.allRoots=e.map(e=>{let t=e.uri;return t.startsWith(`file://`)?a(t):t}),!0},b=!1;try{b=y((await f.server.listRoots()).roots),b||p.info(`No MCP roots yet; waiting for roots/list_changed notification`)}catch(e){p.warn(`MCP roots/list not supported by client; using cwd fallback`,{cwd:process.cwd(),...l(e)}),b=!0}b||=await new Promise(e=>{let t=setTimeout(()=>{p.warn(`Timed out waiting for MCP roots/list_changed; using cwd fallback`,{cwd:process.cwd()}),e(!1)},5e3);f.server.setNotificationHandler(s,async()=>{clearTimeout(t);try{e(y((await f.server.listRoots()).roots))}catch(t){p.warn(`roots/list retry failed after notification`,l(t)),e(!1)}})}),m();let x=null,S=()=>{x&&clearTimeout(x),x=setTimeout(async()=>{p.info(`Auto-shutdown: no activity for 30 minutes — shutting down gracefully`);try{let e=d.aikit;e&&await Promise.all([e.embedder.shutdown?.().catch(()=>{})??Promise.resolve(),e.graphStore.close().catch(()=>{}),e.store.close().catch(()=>{})])}catch{}process.exit(0)},18e5),x.unref&&x.unref()};S(),process.stdin.on(`data`,()=>S()),h.catch(e=>{p.error(`Initialization failed — server will continue with limited tools`,l(e))}),u===`auto`?g().catch(e=>p.error(`Initial index failed`,l(e))):u===`smart`?h.then(async()=>{try{if(!d.aikit)throw Error(`AI Kit components are not available after initialization`);let{SmartIndexScheduler:e}=await import(`../../indexer/dist/index.js`),t=new e(d.aikit.indexer,c,d.aikit.store),n=d.aikit.store;t.start(),n.onBeforeClose&&n.onBeforeClose(()=>t.stop()),d.setSmartScheduler(t),p.info(`Smart index scheduler started (stdio mode)`)}catch(e){p.error(`Failed to start smart index scheduler`,l(e))}}).catch(e=>p.error(`AI Kit init failed for smart scheduler`,l(e))):p.warn(`Initial full indexing skipped; use aikit_reindex to index manually`,{indexMode:u})}}v().catch(e=>{p.error(`Fatal error`,l(e)),process.exit(1)});export{e as CuratedKnowledgeManager};
|
|
@@ -2763,7 +2763,7 @@ Complements: \`symbol\` (single lookup), \`trace\` (call-chain AST), \`blast_rad
|
|
|
2763
2763
|
navigator.sendBeacon('/callback', new Blob([body], { type: 'application/json' }));
|
|
2764
2764
|
});
|
|
2765
2765
|
})();
|
|
2766
|
-
<\/script>`}function tf(e){try{bn(process.platform===`win32`?`start "" "${e}"`:process.platform===`darwin`?`open "${e}"`:`xdg-open "${e}"`)}catch{}}async function nf(e){try{let t=kn();await t.launch(`ui`),await(await t.getContext().newPage()).goto(e,{waitUntil:`domcontentloaded`})}catch{tf(e)}}function rf(e,t,n){let r=[e.title];return e.description&&r.push(e.description),r.push(``,`Opened in browser at ${t}`,n),r.join(`
|
|
2766
|
+
<\/script>`}function tf(e){try{bn(process.platform===`win32`?`start "" "${e}"`:process.platform===`darwin`?`open "${e}"`:`xdg-open "${e}"`)}catch{}}async function nf(e){try{let t=kn();await t.launch(`ui`),t.resetIdleTimer(),await(await t.getContext().newPage()).goto(e,{waitUntil:`domcontentloaded`})}catch{tf(e)}}function rf(e,t,n){let r=[e.title];return e.description&&r.push(e.description),r.push(``,`Opened in browser at ${t}`,n),r.join(`
|
|
2767
2767
|
`)}function af(e){return e.some(e=>e.id!==`__dismiss`)}function of(e){let t=e?.split(`?`)[0];if(t?.startsWith(`/@aikit/blocks-interactive/dist/`))return N(M(Qd.resolve(`@aikit/blocks-interactive/package.json`)),`dist`,t.slice(32))}function sf(e){return e.replace(`</head>`,`<style>
|
|
2768
2768
|
.toolbar, .badge, body > header, body > footer { display: none !important; }
|
|
2769
2769
|
body { padding-top: 0 !important; margin-top: 0 !important; }
|
|
@@ -2775,7 +2775,7 @@ window.addEventListener('message', function(e) {
|
|
|
2775
2775
|
}
|
|
2776
2776
|
});
|
|
2777
2777
|
<\/script>
|
|
2778
|
-
</body>`)}function cf(){let e=X;e&&(e.close(),
|
|
2778
|
+
</body>`)}function cf(){let e=X;e&&(X=null,setTimeout(()=>{try{e.close()}catch{}},2e3))}async function lf(e,t){if(mf(`<html><body style="font-family:system-ui;padding:2rem;color:#888;text-align:center"><p>Content opened in browser window.</p></body></html>`),e.data!=null&&t.inputSchema){let n=Gt({data:e.data,schema:t.inputSchema});if(!n.valid){let e=n.errors.map(e=>` ${e.path}: ${e.message}${e.expected?` (expected: ${e.expected}, got: ${e.received})`:``}`).join(`
|
|
2779
2779
|
`);return{content:[{type:`text`,text:`[ERROR:VALIDATION] Template "${t.id}" data validation failed:\n${e}\n\nExpected schema: ${JSON.stringify(t.inputSchema,null,2)}`}],structuredContent:{kind:`error`,error:{code:`VIEWER_DATA_INVALID`,message:`Template "${t.id}" data validation failed:\n${e}\n\nExpected schema: ${JSON.stringify(t.inputSchema,null,2)}`}},isError:!0}}}let n=sf(yd(t.resolveHtml(),e.data??null,t.injectId,t.transformData)),r=ir({title:e.title,html:[$d(e),`<div class="present-viewer-container">`,` <iframe class="present-viewer-iframe" src="/viewer" sandbox="allow-scripts allow-same-origin"></iframe>`,` <script>
|
|
2780
2780
|
(function() {
|
|
2781
2781
|
const iframe = document.querySelector('.present-viewer-iframe');
|
|
@@ -2792,8 +2792,8 @@ window.addEventListener('message', function(e) {
|
|
|
2792
2792
|
})();
|
|
2793
2793
|
<\/script>`,`</div>`].join(`
|
|
2794
2794
|
`),css:[[`.present-viewer-container {`,` flex: 1;`,` min-height: calc(100vh - 12rem);`,` position: relative;`,` border-radius: 0.75rem;`,` overflow: hidden;`,` border: none;`,`}`,`.present-viewer-iframe {`,` border: none;`,` width: 100%;`,` height: 100%;`,` position: absolute;`,` inset: 0;`,` border-radius: inherit;`,`}`].join(`
|
|
2795
|
-
`)],islands:[],payload:void 0,nonce:``,generatedAt:new Date().toISOString(),colorScheme:e.colorScheme,lang:e.lang,dir:e.dir,transport:`browser`,exportPolicy:`local-interactive`}),i=``;try{cf(),i=await new Promise((e,t)=>{let i=pr((e,t)=>{if(e.url===`/viewer`){t.writeHead(200,{"Content-Type":`text/html; charset=utf-8`}),t.end(n);return}t.writeHead(200,{"Content-Type":`text/html; charset=utf-8`}),t.end(r)});i.listen(0,`127.0.0.1`,()=>{let n=i.address();if(typeof n!=`object`||!n){t(Error(`Failed to resolve local browser address`));return}X=i,e(`http://127.0.0.1:${n.port}`)})})}catch(t){return{content:[{type:`text`,text:`${e.title}\n\nUnable to start local browser transport.`}],structuredContent:{kind:`error`,error:{code:`BROWSER_START_FAILED`,message:t instanceof Error?t.message:`Unable to start browser transport`}},isError:!0}}
|
|
2796
|
-
`),css:t.css,islands:t.islands,payload:t.payload,nonce:t.nonce,generatedAt:new Date().toISOString(),colorScheme:e.colorScheme,lang:e.lang,dir:e.dir,transport:`browser`,exportPolicy:t.exportPolicy,headScripts:r}),o=``,s=``;try{let e=X;e&&(e.close(),X=null),o=await new Promise((e,t)=>{let r=pr((e,t)=>{if(e.method===`OPTIONS`){t.writeHead(204,{"Access-Control-Allow-Origin":s||`*`,"Access-Control-Allow-Methods":`POST`,"Access-Control-Allow-Headers":`Content-Type`}),t.end();return}if(e.method===`POST`&&e.url===`/callback`){n.handle(e,t,s);return}let r=i.find(t=>e.url===t.route);if(r){let e=r.getSource();if(e){t.writeHead(200,{"Content-Type":`application/javascript; charset=utf-8`,"Cache-Control":`public, max-age=86400`}),t.end(e);return}t.writeHead(302,{Location:r.cdn}),t.end();return}let o=of(e.url);if(o)try{let e=k(o,`utf8`);t.writeHead(200,{"Content-Type":`application/javascript; charset=utf-8`}),t.end(e);return}catch{}t.writeHead(200,{"Content-Type":`text/html; charset=utf-8`}),t.end(a)});r.listen(0,`127.0.0.1`,()=>{let n=r.address();if(typeof n!=`object`||!n){t(Error(`Failed to resolve local browser address`));return}X=r,s=`http://127.0.0.1:${n.port}`,e(s)})})}catch(t){return{content:[{type:`text`,text:`${e.title}\n\nUnable to start local browser transport.`}],structuredContent:n.settleError(`BROWSER_START_FAILED`,t instanceof Error?t.message:`Unable to start browser transport`),isError:!0}}if(nf(o),!af(t.actions)){let t=X;return t&&(n.promise.finally(()=>{X===t&&(t.close(),X=null)}),setTimeout(()=>{X===t&&(t.close(),X=null)},Zd)),{content:[{type:`text`,text:rf(e,o,`Rendered.`)}],structuredContent:{kind:`rendered`,reason:`no-response-required`}}}let c=await Promise.race([n.promise,new Promise(e=>{setTimeout(()=>e(n.settleTimeout(Zd)),Zd)})]),l=X;l&&(l.close(),X=null);let u=c.kind===`result`?`Selected action: ${c.result.actionId}`:c.kind===`timeout`?`Timed out after ${c.waitedMs}ms.`:c.kind===`cancelled`?`Cancelled: ${c.reason}.`:c.kind===`error`?`Error: ${c.error.message}`:`Rendered.`;return{content:[{type:`text`,text:rf(e,o,u)}],structuredContent:c,isError:c.kind===`error`}}const df=`ui://aikit/present.html`;let ff=``;function pf(){return ff}function mf(e){ff=e}function hf(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const gf=/\\u[0-9a-fA-F]{4}/,_f=/^\s*\|(?:[^|\r\n]+\|){2,}\s*$/,vf=/^\s*\|?(?:\s*:?-{3,}:?\s*\|){2,}\s*$/,yf=/\b(cli|terminal|tty|console|command(?:-|\s)?line)\b/i;function bf(e){let t=[e.value,e.markdown,e.text,e.content];for(let e of t)if(typeof e==`string`&&e.trim().length>0)return e}function xf(e){let t=e.split(/\r?\n/);for(let e=0;e<t.length-1;e+=1)if(_f.test(t[e])&&vf.test(t[e+1]))return!0;return!1}function Sf(e){let t=e.trim().split(`|`),n=+(t[0]?.trim()===``),r=t.at(-1)?.trim()===``?t.length-1:t.length;return t.slice(n,r).map(e=>e.trim())}function Cf(e,t){if(t<2)return!1;let n=e.trim();return n.startsWith(`|`)?Sf(n).length===t:!1}function wf(e){let t=e.split(/\r?\n/),n=[],r=[],i=()=>{r.length!==0&&(n.push({type:`text`,content:r.join(`
|
|
2795
|
+
`)],islands:[],payload:void 0,nonce:``,generatedAt:new Date().toISOString(),colorScheme:e.colorScheme,lang:e.lang,dir:e.dir,transport:`browser`,exportPolicy:`local-interactive`}),i=``;try{cf(),i=await new Promise((e,t)=>{let i=pr((e,t)=>{if(e.url===`/viewer`){t.writeHead(200,{"Content-Type":`text/html; charset=utf-8`}),t.end(n);return}t.writeHead(200,{"Content-Type":`text/html; charset=utf-8`}),t.end(r)});i.listen(0,`127.0.0.1`,()=>{let n=i.address();if(typeof n!=`object`||!n){t(Error(`Failed to resolve local browser address`));return}X=i,e(`http://127.0.0.1:${n.port}`)})})}catch(t){return{content:[{type:`text`,text:`${e.title}\n\nUnable to start local browser transport.`}],structuredContent:{kind:`error`,error:{code:`BROWSER_START_FAILED`,message:t instanceof Error?t.message:`Unable to start browser transport`}},isError:!0}}nf(i);let a=X;return a&&setTimeout(()=>{X===a&&(a.close(),X=null)},Zd),{content:[{type:`text`,text:rf(e,i,`Rendered.`)}],structuredContent:{kind:`rendered`,reason:`no-response-required`}}}async function uf(e){mf(`<html><body style="font-family:system-ui;padding:2rem;color:#888;text-align:center"><p>Content opened in browser window.</p></body></html>`);let t=fr(e,{transport:`browser`,registry:Hd,blockVendorScripts:$u()}),n=dd(t.surfaceId,t.actions),r=Yd(t.vendorScripts,`browser`),i=Xd(),a=ir({title:e.title,html:[$d(e),t.html,ef(t.actions,n.nonce)].filter(Boolean).join(`
|
|
2796
|
+
`),css:t.css,islands:t.islands,payload:t.payload,nonce:t.nonce,generatedAt:new Date().toISOString(),colorScheme:e.colorScheme,lang:e.lang,dir:e.dir,transport:`browser`,exportPolicy:t.exportPolicy,headScripts:r}),o=``,s=``;try{let e=X;e&&(e.close(),X=null),o=await new Promise((e,t)=>{let r=pr((e,t)=>{if(e.method===`OPTIONS`){t.writeHead(204,{"Access-Control-Allow-Origin":s||`*`,"Access-Control-Allow-Methods":`POST`,"Access-Control-Allow-Headers":`Content-Type`}),t.end();return}if(e.method===`POST`&&e.url===`/callback`){n.handle(e,t,s);return}let r=i.find(t=>e.url===t.route);if(r){let e=r.getSource();if(e){t.writeHead(200,{"Content-Type":`application/javascript; charset=utf-8`,"Cache-Control":`public, max-age=86400`}),t.end(e);return}t.writeHead(302,{Location:r.cdn}),t.end();return}let o=of(e.url);if(o)try{let e=k(o,`utf8`);t.writeHead(200,{"Content-Type":`application/javascript; charset=utf-8`}),t.end(e);return}catch{}t.writeHead(200,{"Content-Type":`text/html; charset=utf-8`}),t.end(a)});r.listen(0,`127.0.0.1`,()=>{let n=r.address();if(typeof n!=`object`||!n){t(Error(`Failed to resolve local browser address`));return}X=r,s=`http://127.0.0.1:${n.port}`,e(s)})})}catch(t){return{content:[{type:`text`,text:`${e.title}\n\nUnable to start local browser transport.`}],structuredContent:n.settleError(`BROWSER_START_FAILED`,t instanceof Error?t.message:`Unable to start browser transport`),isError:!0}}if(nf(o),!af(t.actions)){let t=X;return t&&(n.promise.finally(()=>{X===t&&(t.close(),X=null)}),setTimeout(()=>{X===t&&(t.close(),X=null)},Zd)),{content:[{type:`text`,text:rf(e,o,`Rendered.`)}],structuredContent:{kind:`rendered`,reason:`no-response-required`}}}let c=await Promise.race([n.promise,new Promise(e=>{setTimeout(()=>e(n.settleTimeout(Zd)),Zd)})]),l=X;l&&setTimeout(()=>{X===l&&(l.close(),X=null)},3e3);let u=c.kind===`result`?`Selected action: ${c.result.actionId}`:c.kind===`timeout`?`Timed out after ${c.waitedMs}ms.`:c.kind===`cancelled`?`Cancelled: ${c.reason}.`:c.kind===`error`?`Error: ${c.error.message}`:`Rendered.`;return{content:[{type:`text`,text:rf(e,o,u)}],structuredContent:c,isError:c.kind===`error`}}const df=`ui://aikit/present.html`;let ff=``;function pf(){return ff}function mf(e){ff=e}function hf(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const gf=/\\u[0-9a-fA-F]{4}/,_f=/^\s*\|(?:[^|\r\n]+\|){2,}\s*$/,vf=/^\s*\|?(?:\s*:?-{3,}:?\s*\|){2,}\s*$/,yf=/\b(cli|terminal|tty|console|command(?:-|\s)?line)\b/i;function bf(e){let t=[e.value,e.markdown,e.text,e.content];for(let e of t)if(typeof e==`string`&&e.trim().length>0)return e}function xf(e){let t=e.split(/\r?\n/);for(let e=0;e<t.length-1;e+=1)if(_f.test(t[e])&&vf.test(t[e+1]))return!0;return!1}function Sf(e){let t=e.trim().split(`|`),n=+(t[0]?.trim()===``),r=t.at(-1)?.trim()===``?t.length-1:t.length;return t.slice(n,r).map(e=>e.trim())}function Cf(e,t){if(t<2)return!1;let n=e.trim();return n.startsWith(`|`)?Sf(n).length===t:!1}function wf(e){let t=e.split(/\r?\n/),n=[],r=[],i=()=>{r.length!==0&&(n.push({type:`text`,content:r.join(`
|
|
2797
2797
|
`)}),r.length=0)},a=0;for(;a<t.length;){let e=t[a],o=t[a+1];if(o!==void 0&&_f.test(e)&&vf.test(o)){let r=Sf(e),o=[];i();let s=a+2;for(;s<t.length&&Cf(t[s],r.length);)o.push(Sf(t[s])),s+=1;n.push({type:`table`,headers:r,rows:o}),a=s;continue}r.push(e),a+=1}return i(),n}function Tf(e){let t=bf(e);return!t||!xf(t)?[e]:wf(t).flatMap(e=>{if(e.type===`text`){let t=e.content.trim();return t.length>0?[{type:`markdown`,value:t}]:[]}return[{type:`table`,value:{headers:e.headers,rows:e.rows}}]})}function Ef(e){if(typeof e==`string`)return yf.test(e);if(Array.isArray(e))return e.some(e=>Ef(e));if(!hf(e))return!1;let t=[`client`,`clientInfo`,`host`,`source`,`mode`,`name`,`title`,`channel`];return Object.entries(e).some(([e,n])=>t.includes(e)?Ef(n):!1)}function Df(e,t){return{preferBrowser:[t,e._meta,hf(e.metadata)?e.metadata.source:void 0].some(e=>Ef(e))}}function Of(e){if(!e.template)return!0;let t=gd(e.template);return t?t.supportedTransports.includes(`browser`):Ud(e)?.supportedTransports.includes(`browser`)??!1}function kf(e){let t=typeof e.description==`string`&&e.description.trim().length>0?`<p class="present-surface-description">${q(e.description)}</p>`:``;return[`<section class="present-surface-header">`,` <h1>${q(e.title)}</h1>`,t,`</section>`,`<style>`,` .present-surface-header { display: grid; gap: 0.75rem; margin-bottom: 1.5rem; }`,` .present-surface-header h1 { margin: 0; font-size: 1.875rem; }`,` .present-surface-description { margin: 0; color: var(--dt-text-secondary, #475467); }`,`</style>`].filter(Boolean).join(`
|
|
2798
2798
|
`)}function Af(e,t){let n=[e.title];return e.description&&n.push(e.description),lr(t)?n.push(``,`Selected action: ${t.result.actionId}`):cr(t)?n.push(``,`Error: ${t.error.message}`):t.kind===`timeout`?n.push(``,`Timed out after ${t.waitedMs}ms.`):t.kind===`cancelled`&&n.push(``,`Cancelled: ${t.reason}.`),n.join(`
|
|
2799
2799
|
`)}const jf={id:`__dismiss`,type:`button`,label:`Done`,variant:`default`};function Mf(e){if((e.actions?.length??0)>0||!e.template)return e;let t=Ud(e);return t?.supportedTransports.includes(`browser`)===!0&&!t.supportedTransports.includes(`mcp-app`)?{...e,actions:[jf]}:e}function Nf(e){return e.replace(`</head>`,`<style>
|
|
@@ -2829,8 +2829,9 @@ window.addEventListener('message', function(e) {
|
|
|
2829
2829
|
if(typeof ResizeObserver!=="undefined"){new ResizeObserver(notify).observe(document.documentElement)}
|
|
2830
2830
|
else{setInterval(notify,500)}
|
|
2831
2831
|
})();
|
|
2832
|
-
<\/script>`;return e.includes(`</body>`)?e.replace(`</body>`,`${t}</body>`):`${e}${t}`}function Ff(e,t
|
|
2833
|
-
`)
|
|
2832
|
+
<\/script>`;return e.includes(`</body>`)?e.replace(`</body>`,`${t}</body>`):`${e}${t}`}function Ff(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 — ${q(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">${q(e)}</h1>`,` <p class="error-message">${q(t)}</p>`,`</div>`,`</body></html>`].join(`
|
|
2833
|
+
`)}function If(e,t,n,r){return mf(Ff(r??`Present`,t)),{content:[{type:`text`,text:`[ERROR:VALIDATION] ${t}`}],isError:!0}}function Lf(e,t){if(!hf(e)||!(`schemaVersion`in e))return{ok:!1,response:If(`INVALID_CHANNEL_SURFACE`,`present expects a ChannelSurface object with schemaVersion: 1`)};if(e.schemaVersion!==1)return{ok:!1,response:If(`UNSUPPORTED_SCHEMA_VERSION`,`Unsupported ChannelSurface schemaVersion: ${String(e.schemaVersion)}`)};if(typeof e.title==`string`&&gf.test(e.title))return{ok:!1,response:If(`TITLE_UNICODE_ESCAPE_NOT_ALLOWED`,`Use actual Unicode characters in title, not escape sequences.`)};let n=Array.isArray(e.blocks)?{...e,blocks:e.blocks.flatMap(e=>{if(!hf(e)||e.type!==`markdown`)return[e];let t=bf(e);return!t||!xf(t)?[e]:Tf(e)})}:e;return{ok:!0,surface:n,options:Df(n,t)}}async function Rf(e,t={}){let n=Mf(e);if(e.template){let r=gd(e.template);if(r)return await zf(n,r,t)}return Wd(n)||t.preferBrowser&&Of(n)?await uf(n):Bf(n)}async function zf(e,t,n={}){if(e.data!=null&&t.inputSchema){let n=Gt({data:e.data,schema:t.inputSchema});if(!n.valid){let r=n.errors.map(e=>` ${e.path}: ${e.message}${e.expected?` (expected: ${e.expected}, got: ${e.received})`:``}`).join(`
|
|
2834
|
+
`);return If(`VIEWER_DATA_INVALID`,`Template "${t.id}" data validation failed:\n${r}\n\nExpected schema: ${JSON.stringify(t.inputSchema,null,2)}`,void 0,e.title)}}let r=t.supportedTransports.includes(`browser`),i=t.supportedTransports.includes(`mcp-app`);if(n.preferBrowser&&r||r&&!i)return await lf(e,t);if(!i)return If(`VIEWER_TRANSPORT_UNSUPPORTED`,`Viewer template "${t.id}" does not support an available transport`,void 0,e.title);try{let n=Nf(yd(t.resolveHtml(),e.data??null,t.injectId,t.transformData)).replace(/&/g,`&`).replace(/"/g,`"`);return mf(Pf(ir({title:e.title,html:[kf(e),`<div class="present-viewer-container">`,` <iframe class="present-viewer-iframe" srcdoc="${n}" sandbox="allow-scripts allow-same-origin"></iframe>`,` <script>
|
|
2834
2835
|
(function() {
|
|
2835
2836
|
const iframe = document.querySelector('.present-viewer-iframe');
|
|
2836
2837
|
if (!iframe) return;
|
|
@@ -2855,14 +2856,14 @@ window.addEventListener('message', function(e) {
|
|
|
2855
2856
|
`),css:[[`.present-viewer-container {`,` flex: 1;`,` min-height: 640px;`,` position: relative;`,` border-radius: 0.75rem;`,` overflow: hidden;`,` border: none;`,`}`,`.present-viewer-iframe {`,` border: none;`,` width: 100%;`,` height: 100%;`,` position: absolute;`,` inset: 0;`,` border-radius: inherit;`,`}`].join(`
|
|
2856
2857
|
`)],islands:[],payload:void 0,nonce:``,generatedAt:new Date().toISOString(),colorScheme:e.colorScheme,lang:e.lang,dir:e.dir,transport:`mcp-app`,exportPolicy:`local-interactive`}))),{content:[{type:`text`,text:[Af(e,{kind:`rendered`,reason:`no-response-required`}),`If this content doesn't render inline, retry with format: 'browser'.`].join(`
|
|
2857
2858
|
|
|
2858
|
-
`)}],ui:{type:`resource`,uri:df}}}catch(
|
|
2859
|
+
`)}],ui:{type:`resource`,uri:df}}}catch(t){return If(`VIEWER_RENDER_FAILED`,t instanceof Error?t.message:`Failed to render viewer template`,void 0,e.title)}}function Bf(e){try{let t=fr(e,{transport:`mcp-app`,registry:Hd,blockVendorScripts:$u()}),n=Yd(t.vendorScripts,`mcp-app`);return ff=Pf(ir({title:e.title,html:[kf(e),t.html].filter(Boolean).join(`
|
|
2859
2860
|
`),css:t.css,islands:t.islands,payload:t.payload,nonce:t.nonce,colorScheme:e.colorScheme,lang:e.lang,dir:e.dir,transport:`mcp-app`,exportPolicy:t.exportPolicy,headScripts:n})),{content:[{type:`text`,text:[Af(e,{kind:`rendered`,reason:`no-response-required`}),`If this content doesn't render inline, retry with format: 'browser'.`].join(`
|
|
2860
2861
|
|
|
2861
|
-
`)}],ui:{type:`resource`,uri:df}}}catch(
|
|
2862
|
-
`);Xn(e,`present`,{title:n.title,description:r,inputSchema:
|
|
2862
|
+
`)}],ui:{type:`resource`,uri:df}}}catch(t){return If(`RENDER_FAILED`,t instanceof Error?t.message:`Failed to render ChannelSurface`,void 0,e.title)}}const Vf=L.object({label:L.string(),value:L.string(),description:L.string().optional()}),Hf=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(Vf).optional(),schema:L.record(L.string(),L.unknown()).optional()}),Uf=L.object({type:L.string(),title:L.string().optional(),value:L.unknown().optional(),language:L.string().optional()}).catchall(L.unknown()),Wf={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(Uf).optional().describe(`Typed block content for the surface.`),data:L.unknown().optional().describe(`Template data payload, if the template expands data.`),actions:L.array(Hf).optional().describe(`Interactive actions. Presence triggers browser transport.`),response:L.object({timeout:L.number().optional(),required:L.boolean().optional()}).optional(),metadata:L.object({surfaceId:L.string().optional(),createdAt:L.string().optional(),source:L.string().optional()}).optional(),colorScheme:L.enum([`light`,`dark`,`auto`]).optional(),lang:L.string().optional(),dir:L.enum([`ltr`,`rtl`,`auto`]).optional()};L.object({surfaceId:L.string(),actionId:L.string(),actionType:L.enum([`button`,`select`,`multi-select`,`form-submit`,`text-submit`,`confirm`,`custom`]),value:L.unknown().optional(),formData:L.record(L.string(),L.unknown()).optional(),selection:L.union([L.string(),L.array(L.string())]).optional(),label:L.string().optional(),timestamp:L.string(),sourceTransport:L.enum([`mcp-app`,`browser`,`export`])});function Gf(e,t){let n=U(`present`),r=[`Render a ChannelSurface for the user.`,`Quick ref:`,`- Full schema: aikit://schemas/channel-surface`,`- Required: schemaVersion: 1, title`,`- Content: blocks[] for direct rendering, or template + data for registry-backed rendering`,`- Actions: actions[] of SurfaceAction; interactive surfaces use browser transport and return ChannelOutcome`,`- Optional fields: description, layout, response, metadata, colorScheme, lang, dir`,`- Transports: mcp-app, browser, export`,`- Use schema resource for block enums and action details.`].join(`
|
|
2863
|
+
`);Xn(e,`present`,{title:n.title,description:r,inputSchema:Wf,annotations:n.annotations,_meta:{ui:{resourceUri:df}}},async(e,t)=>{let n=Lf(e,t);return n.ok?await Rf(n.surface,n.options):n.response});try{Yn(e,`Present View`,df,{description:`AI Kit present tool viewer`},async()=>({contents:[{uri:df,mimeType:Jn,text:pf()||`<html><body><p>No content generated yet. Call the present tool first.</p></body></html>`}]}))}catch{}try{e.registerResource(`present-templates`,`aikit://present/templates`,{description:`List all registered present viewer templates with their input schemas`},async()=>{let e=vd().map(e=>({id:e.id,label:e.label,description:e.description,transports:e.supportedTransports,inputSchema:e.inputSchema}));return{contents:[{uri:`aikit://present/templates`,mimeType:`application/json`,text:JSON.stringify(e,null,2)}]}})}catch{}}const Kf=F(`tools`);function qf(e,t){let n=new Fn({structure:new Ln,dependencies:new Mn,symbols:new Rn,patterns:new In,entryPoints:new Pn,diagrams:new Nn}),r=U(`produce_knowledge`);e.registerTool(`produce_knowledge`,{title:r.title,description:`Run automated codebase analysis and produce synthesis instructions. Executes Tier 1 deterministic analyzers, then returns structured baselines and instructions for you to synthesize knowledge using remember.`,inputSchema:{scope:L.string().optional().describe(`Root path to analyze (defaults to workspace root)`),aspects:L.array(L.enum([`all`,`structure`,`dependencies`,`symbols`,`patterns`,`entry-points`,`diagrams`])).default([`all`]).describe(`Which analysis aspects to run`)},annotations:r.annotations},async({scope:e,aspects:r})=>{try{let i=e??`.`;Kf.info(`Running knowledge production`,{rootPath:i,aspects:r});let a=await n.runExtraction(i,r);try{let e=t?.onboardDir??``;if(!e)throw Kf.warn(`onboardDir not configured — skipping artifact persistence.`),Error(`skip`);O(e,{recursive:!0});let n=`<!-- Generated by produce_knowledge at ${new Date().toISOString()} -->\n\n`;for(let[t,r]of Object.entries(a))r&&typeof r==`string`&&ne(N(e,`${t}.md`),n+r,`utf-8`);Kf.info(`Knowledge persisted to .ai/context/`,{files:Object.keys(a).length})}catch(e){Kf.warn(`Failed to persist knowledge to .ai/context/`,{error:I(e)})}return{content:[{type:`text`,text:n.buildSynthesisInstructions(a,r)+`
|
|
2863
2864
|
|
|
2864
2865
|
---
|
|
2865
|
-
_Next: Review the baselines above and use \`remember\` to store synthesized knowledge entries._`}]}}catch(e){return
|
|
2866
|
+
_Next: Review the baselines above and use \`remember\` to store synthesized knowledge entries._`}]}}catch(e){return Kf.error(`Knowledge production failed`,I(e)),K(`INTERNAL`,`Knowledge production failed: ${e instanceof Error?e.message:String(e)}`)}})}const Jf=F(`tools`);function Yf(e,t,n,r,i,a,o){let s=U(`reindex`);e.registerTool(`reindex`,{title:s.title,description:`Trigger re-indexing of the AI Kit index. Can do incremental (only changed files) or full re-index. When smart indexing is active, use force: true to override the automatic trickle indexer.`,inputSchema:{full:L.boolean().default(!1).describe(`If true, force full re-index ignoring file hashes`),force:L.boolean().default(!1).describe(`If true, override smart indexing guard and run reindex anyway`)},annotations:s.annotations},async({full:e,force:s},c)=>{try{if(t.isIndexing)return{content:[{type:`text`,text:`## Reindex Already in Progress
|
|
2866
2867
|
|
|
2867
2868
|
A reindex operation is currently running. Search and other tools continue to work with existing data. Use \`status({})\` to check when it completes.`}]};if(o===`smart`&&!s)return{content:[{type:`text`,text:`## Smart Indexing Active
|
|
2868
2869
|
|
|
@@ -2870,40 +2871,40 @@ Smart indexing (trickle mode) is enabled — files are automatically indexed as
|
|
|
2870
2871
|
|
|
2871
2872
|
**If the index is severely outdated**, use \`reindex({ force: true })\` to override.
|
|
2872
2873
|
|
|
2873
|
-
Use \`status({})\` to check smart indexing queue status.`}]};let l=Ss(c).createTask(`Reindex`,1);l.progress(0,`Starting ${e?`full`:`incremental`} reindex`),
|
|
2874
|
+
Use \`status({})\` to check smart indexing queue status.`}]};let l=Ss(c).createTask(`Reindex`,1);l.progress(0,`Starting ${e?`full`:`incremental`} reindex`),Jf.info(`Starting background re-index`,{mode:e?`full`:`incremental`});let u=e=>t=>{t.phase===`chunking`&&t.currentFile&&Jf.debug(`Re-index progress`,{prefix:e,current:t.filesProcessed+1,total:t.filesTotal,file:t.currentFile})};return(e?t.reindexAll(n,u(`Reindex`)):t.index(n,u(`Index`))).then(async e=>{if(Jf.info(`Background re-index complete`,{filesProcessed:e.filesProcessed,chunksCreated:e.chunksCreated,durationMs:e.durationMs}),l.complete(`Reindex complete: ${e.filesProcessed} files, ${e.chunksCreated} chunks in ${e.durationMs}ms`),i)try{await i.createFtsIndex(),Jf.info(`FTS index rebuilt after reindex`)}catch(e){Jf.warn(`FTS index rebuild failed`,I(e))}try{let e=await r.reindexAll();Jf.info(`Curated re-index complete`,{indexed:e.indexed})}catch(e){Jf.warn(`Curated re-index failed`,I(e))}if(a)try{await a.notifyAfterReindex()}catch(e){Jf.warn(`Post-reindex resource notification failed`,I(e))}}).catch(e=>{l.fail(`Reindex failed: ${e instanceof Error?e.message:String(e)}`),Jf.error(`Background reindex failed`,I(e))}),{content:[{type:`text`,text:`## Reindex Started (Background)\n\n- **Mode**: ${e?`Full`:`Incremental`}\n- Search and other tools continue to work with existing data during reindex.\n- Completion will be logged. Use \`status({})\` to check index stats afterward.\n\n---\n_Next: Continue working — the reindex runs in the background._`}]}}catch(e){return Jf.error(`Reindex failed`,I(e)),K(`INTERNAL`,`Reindex failed: ${e instanceof Error?e.message:String(e)}`)}})}const Xf=F(`tools`);function Zf(e){let t=U(`replay`);e.registerTool(`replay`,{title:t.title,description:`View or clear the audit trail of recent MCP tool and CLI invocations. Shows tool name, duration, status, and input/output summaries.`,inputSchema:{action:L.enum([`list`,`clear`]).default(`list`).describe(`Action: "list" (default) to view entries, "clear" to wipe the log`),last:L.number().optional().describe(`Number of entries to return (default: 20, list only)`),tool:L.string().optional().describe(`Filter by tool name (list only)`),source:L.enum([`mcp`,`cli`]).optional().describe(`Filter by source: "mcp" or "cli" (list only)`),since:L.string().optional().describe(`ISO timestamp — only show entries after this time (list only)`)},annotations:t.annotations},async({action:e,last:t,tool:n,source:r,since:i})=>{try{if(e===`clear`)return Bt(),{content:[{type:`text`,text:`Replay log cleared.`}]};let a=Vt({last:t,tool:n,source:r,since:i});if(a.length===0)return{content:[{type:`text`,text:`No replay entries found. Activity is logged when tools are invoked via MCP or CLI.`}]};let o=a.map(e=>`${e.ts.split(`T`)[1]?.split(`.`)[0]??e.ts} ${e.status===`ok`?`✓`:`✗`} ${e.tool} (${e.durationMs}ms) [${e.source}]\n in: ${e.input}\n out: ${e.output}`);return Ht().catch(()=>{}),{content:[{type:`text`,text:`**Replay Log** (${a.length} entries)\n\n${o.join(`
|
|
2874
2875
|
|
|
2875
|
-
`)}`}]}}catch(e){return
|
|
2876
|
+
`)}`}]}}catch(e){return Xf.error(`Replay failed`,I(e)),K(`INTERNAL`,`Replay failed: ${e instanceof Error?e.message:String(e)}`)}})}const Qf=F(`tools`);function $f(e){let t=U(`restore`);e.registerTool(`restore`,{title:t.title,description:`List and restore file snapshots taken before destructive operations (codemod, rename, forget). Use action=list to see available restore points, action=restore with an id to undo.`,inputSchema:{action:L.enum([`list`,`restore`]).describe(`list: show restore points, restore: apply a restore point`),id:L.string().optional().describe(`Restore point ID (required for action=restore)`),limit:L.number().min(1).max(50).default(10).describe(`Max restore points to list`)},annotations:t.annotations},async({action:e,id:t,limit:n})=>{try{if(e===`list`){let e=ht().slice(0,n);return e.length===0?{content:[{type:`text`,text:`No restore points found.`}]}:{content:[{type:`text`,text:`## Restore Points\n\n${e.map(e=>`- **${e.id}** (${e.timestamp}) — ${e.operation}: ${e.description} (${e.files.length} files)`).join(`
|
|
2876
2877
|
`)}`}]}}if(!t)throw Error(`id is required for restore action`);let r=await Ut(t);return{content:[{type:`text`,text:`Restored ${r.length} files:\n${r.map(e=>`- \`${e}\``).join(`
|
|
2877
|
-
`)}`}]}}catch(e){return
|
|
2878
|
-
`)[0].slice(0,500);if(r&&r!==e){let i=await t.embedQuery(r),a=await n.search(i,S);a.length>0&&(C=a,E=`> _Original query "${e}" returned 0 results. Auto-reformulated to "${r}"._\n\n`,
|
|
2878
|
+
`)}`}]}}catch(e){return Qf.error(`Restore failed`,I(e)),K(`INTERNAL`,`Restore failed: ${e instanceof Error?e.message:String(e)}`)}})}const ep=/<\/?curated-context>/gi;function tp(e){return e.replace(ep,``)}function np(e){return`<curated-context>\n${tp(e)}\n</curated-context>`}const rp=F(`tools`);function ip(e,t,i,a){r(e,t,i);let o=e.memoryMetaGet(t);if(!o)return;let s=_(o,{...n,...a});s&&(v(e,t,s),h(e,t,i))}function ap(e,t){let n=[],r=re(process.cwd());r&&n.push(`[project: ${r}]`);let i=t?Zt(t,`__context_boost`):void 0;return i&&n.push(`[focus: ${i.value}]`),n.length===0?e:`${n.join(` `)} ${e}`}function op(e,t,n){return n?e:t===`curated`?e*1.2:e}function sp(e,t){return t?e:e.map(e=>({record:e.record,score:op(e.score,e.record.origin,t)})).sort((e,t)=>t.score-e.score)}async function cp(e,t,n,r,i){if(!e||t>=e.config.fallbackThreshold&&n.length>0)return{results:n,triggered:!1,cacheHit:!1};let a=!1;try{let t=e.cache.get(r);return t?a=!0:(t=await e.client.search(r,i),t.length>0&&e.cache.set(r,t)),t.length>0?{results:qn(n,t,i).map(e=>({record:{id:`er:${e.sourcePath}`,content:e.content,sourcePath:e.source===`er`?`[ER] ${e.sourcePath}`:e.sourcePath,startLine:e.startLine??0,endLine:e.endLine??0,contentType:e.contentType??`documentation`,headingPath:e.headingPath,origin:e.source===`er`?`curated`:e.origin??`indexed`,category:e.category,tags:e.tags??[],chunkIndex:0,totalChunks:1,fileHash:``,indexedAt:new Date().toISOString(),version:1},score:e.score})),triggered:!0,cacheHit:a}:{results:n,triggered:!0,cacheHit:a}}catch(e){return rp.warn(`ER fallback failed`,I(e)),{results:n,triggered:!0,cacheHit:a}}}function lp(e,t,n=60){let r=new Map,i=e[0]?.score||1,a=t[0]?.score||1;for(let t=0;t<e.length;t++){let a=e[t],o=a.score/i;r.set(a.record.id,{record:a.record,score:1/(n+t+1)*o})}for(let e=0;e<t.length;e++){let i=t[e],o=i.score/a,s=r.get(i.record.id);s?s.score+=1/(n+e+1)*o:r.set(i.record.id,{record:i.record,score:1/(n+e+1)*o})}return[...r.values()].sort((e,t)=>t.score-e.score).map(({record:e,score:t})=>({record:e,score:t}))}function up(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 dp(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 fp(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&&!pp.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 pp=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 mp(e,t){try{let n=await e.getStats();if(!n.lastIndexedAt)return;let r=new Date(n.lastIndexedAt).getTime(),i=Date.now(),a=[...new Set(t.map(e=>e.record.sourcePath))].filter(e=>!e.startsWith(`[ER]`)).slice(0,5);if(a.length===0)return;let o=0;for(let e of a)try{(await _n(e)).mtimeMs>r&&o++}catch{o++}if(o>0){let e=i-r,t=Math.floor(e/6e4),n=t<1?`<1 min`:`${t} min`;return`> ⚠️ **Index may be stale** — ${o} file(s) modified since last index (${n} ago). Use \`reindex\` to refresh.`}}catch{}}function hp(e,t,n,r,i,a,o,s,c,l){let u=U(`search`);e.registerTool(`search`,{title:u.title,description:`Search AI Kit for code, docs, and prior decisions. Default choice for discovery. Modes: hybrid (default), semantic, keyword. For multi-strategy precision queries use find; for a known file path use lookup.`,outputSchema:So,inputSchema:{query:L.string().max(5e3).describe(`Natural language search query`),limit:L.number().min(1).max(20).default(5).describe(`Maximum results to return`),search_mode:L.enum([`hybrid`,`semantic`,`keyword`]).default(`hybrid`).describe(`Search strategy: hybrid (vector + FTS + RRF fusion, default), semantic (vector only), keyword (FTS only)`),content_type:L.enum(le).optional().describe(`Filter by content type`),source_type:L.enum(fe).optional().describe(`Coarse filter: "source" (code only), "documentation" (md, curated), "test", "config". Overrides content_type if both set.`),origin:L.enum(de).optional().describe(`Filter by knowledge origin`),category:L.string().optional().describe(`Filter by category (e.g., decisions, patterns, conventions)`),tags:L.array(L.string()).optional().describe(`Filter by tags (returns results matching ANY of the specified tags)`),min_score:L.number().min(0).max(1).default(.25).describe(`Minimum similarity score`),graph_hops:L.number().min(0).max(3).default(1).describe(`Number of graph hops to augment results with connected entities (0 = disabled, 1 = direct connections, 2-3 = deeper traversal). Default 1 provides module/symbol context automatically.`),max_tokens:L.number().min(100).max(5e4).optional().describe(`Maximum token budget for the response. When set, output is truncated to fit.`),dedup:L.enum([`file`,`chunk`]).default(`chunk`).describe(`Deduplication mode: "chunk" (default, show all matching chunks) or "file" (collapse chunks from same file into single result with merged line ranges)`),workspaces:L.array(L.string()).optional().describe(`Cross-workspace search: partition names or folder basenames to include. Use ["*"] for all registered workspaces. Only works in user-level install mode.`)},annotations:u.annotations},async({query:e,limit:u,search_mode:d,content_type:f,source_type:p,origin:m,category:h,tags:g,min_score:_,graph_hops:v,max_tokens:y,dedup:b,workspaces:x})=>{try{let S={limit:u,minScore:_,contentType:f,sourceType:p,origin:m,category:h,tags:g},C,w=!1,T=!1,E=``,D=ap(e,s);if(d===`keyword`)C=await n.ftsSearch(e,S),C=C.slice(0,u);else if(d===`semantic`){let r=await t.embedQuery(D);C=await n.search(r,S);let a=await cp(i,C[0]?.score??0,C,e,u);C=a.results,w=a.triggered,T=a.cacheHit}else{let r=await t.embedQuery(D),a=n.coarseSearch,o=a?a.bind(n):n.search.bind(n),[s,c]=await Promise.all([o(r,{...S,limit:u*2}),n.ftsSearch(e,{...S,limit:u*2}).catch(()=>[])]);s.length===0&&c.length>0?(C=c.slice(0,u),E=` (FTS-only: vector index rebuilding)`):C=c.length===0&&s.length>0?s.slice(0,u):lp(s,c).slice(0,u);let l=await cp(i,s[0]?.score??0,C,e,u);C=l.results,w=l.triggered,T=l.cacheHit}C=sp(C,m).slice(0,u),a&&a.recordSearch(e,w,T),C.length>1&&(C=up(C,e)),C=dp(C);let O=``;if(x&&x.length>0){let n=Qs(x,he(process.cwd()));if(n.length>0){let{stores:r,closeAll:i}=await $s(n);try{let i;i=d===`keyword`?await tc(r,e,{...S,limit:u}):await ec(r,await t.embedQuery(e),{...S,limit:u});for(let e of i)C.push({record:{...e.record,sourcePath:`[${e.workspace}] ${e.record.sourcePath}`},score:e.score});C=C.sort((e,t)=>t.score-e.score).slice(0,u),O=` + ${n.length} workspace(s)`}finally{await i()}}}if(b===`file`&&C.length>1){let e=new Map;for(let t of C){let n=t.record.sourcePath,r=e.get(n);r?(t.score>r.best.score&&(r.best=t),r.ranges.push({start:t.record.startLine,end:t.record.endLine})):e.set(n,{best:t,ranges:[{start:t.record.startLine,end:t.record.endLine}]})}C=[...e.values()].sort((e,t)=>t.best.score-e.best.score).map(({best:e,ranges:t})=>({record:{...e.record,content:t.length>1?`${e.record.content}\n\n_Matched ${t.length} sections: ${t.sort((e,t)=>e.start-t.start).map(e=>`L${e.start}-${e.end}`).join(`, `)}_`:e.record.content},score:e.score}))}if(C.length>1){let e=C[0].score,t=Math.max(e*.4,.1);C=C.filter(e=>e.score>=t)}if(C.length===0){if(o?.available)try{let r=(await o.createMessage({prompt:`The search query "${e}" returned 0 results in AI Kit code search. Suggest ONE alternative search query that might find relevant results. Reply with ONLY the alternative query, nothing else.`,systemPrompt:`You are a search query optimizer for AI Kit code search. Generate a single alternative query.`,maxTokens:100})).text.trim().split(`
|
|
2879
|
+
`)[0].slice(0,500);if(r&&r!==e){let i=await t.embedQuery(r),a=await n.search(i,S);a.length>0&&(C=a,E=`> _Original query "${e}" returned 0 results. Auto-reformulated to "${r}"._\n\n`,rp.info(`Smart search fallback succeeded`,{originalQuery:e,altQuery:r,resultCount:a.length}))}}catch(e){rp.debug(`Smart search fallback failed`,{error:String(e)})}if(C.length===0)return{content:[{type:`text`,text:`No results found for the given query.`}],structuredContent:{results:[],totalResults:0,searchMode:d,query:e}}}let k,A;if(v>0&&!r&&(A="> **Note:** `graph_hops` was set but no graph store is available. Graph augmentation skipped."),v>0&&r)try{let e=await rt(r,C.map(e=>({recordId:e.record.id,score:e.score,sourcePath:e.record.sourcePath})),{hops:v,maxPerHit:5});k=new Map;for(let t of e)if(t.graphContext.nodes.length>0){let e=t.graphContext.nodes.slice(0,5).map(e=>` - **${e.name}** (${e.type})`).join(`
|
|
2879
2880
|
`),n=new Map;for(let e of t.graphContext.nodes)n.set(e.id,e.name);let r=t.graphContext.edges.slice(0,5).map(e=>` - ${n.get(e.fromId)??e.fromId} —[${e.type}]→ ${n.get(e.toId)??e.toId}`).join(`
|
|
2880
2881
|
`),i=[`- **Graph Context** (${v} hop${v>1?`s`:``}):`];e&&i.push(` Entities:\n${e}`),r&&i.push(` Relationships:\n${r}`),k.set(t.recordId,i.join(`
|
|
2881
|
-
`))}}catch(e){
|
|
2882
|
-
`)}\n\n${n.origin===`curated`?
|
|
2882
|
+
`))}}catch(e){rp.warn(`Graph augmentation failed`,I(e)),A=`> **Note:** Graph augmentation failed. Results shown without graph context.`}let j=Date.now();for(let e of C)if(e.record.origin===`curated`&&e.record.indexedAt){let t=j-new Date(e.record.indexedAt).getTime(),n=Math.max(0,t/864e5);e.score*=.95**n}if(C.sort((e,t)=>t.score-e.score),C=we(C),s)for(let e of C){if(e.record.origin!==`curated`)continue;let t=El(e.record.sourcePath);t&&ip(s,t,c,l)}let ee=C.map((e,t)=>{let n=e.record;return`${`### Result ${t+1} (score: ${e.score.toFixed(3)})`}\n${[`- **Source**: ${n.sourcePath}`,n.headingPath?`- **Section**: ${n.headingPath}`:null,`- **Type**: ${n.contentType}`,n.startLine?`- **Lines**: ${n.startLine}-${n.endLine}`:null,n.origin===`indexed`?null:`- **Origin**: ${n.origin}`,n.category?`- **Category**: ${n.category}`:null,n.tags?.length?`- **Tags**: ${n.tags.join(`, `)}`:null,k?.get(n.id)??null].filter(Boolean).join(`
|
|
2883
|
+
`)}\n\n${n.origin===`curated`?np(n.content):n.content}`}).join(`
|
|
2883
2884
|
|
|
2884
2885
|
---
|
|
2885
2886
|
|
|
2886
|
-
`),te=(d===`hybrid`?`hybrid (vector + keyword RRF)`:d===`keyword`?`keyword (FTS)`:`semantic (vector)`)+O,ne=
|
|
2887
|
+
`),te=(d===`hybrid`?`hybrid (vector + keyword RRF)`:d===`keyword`?`keyword (FTS)`:`semantic (vector)`)+O,ne=fp(C,e),re=ne.length>0?`\n_Distinctive terms: ${ne.map(e=>`\`${e}\``).join(`, `)}_`:``,M=await mp(n,C),ie=[];if(C.length===0)ie.push("`reindex` — no results found, index may be stale"),ie.push("`find` — try federated search with glob/regex");else{let e=C[0]?.record.sourcePath;e&&ie.push(`\`lookup\` — see all chunks from \`${e}\``),ie.push("`symbol` — resolve a specific symbol from the results"),ie.push("`compact` — compress a result file for focused reading")}let N=[A?`${A}\n\n`:``,M?`${M}\n\n`:``,ee,`\n\n---\n_Search mode: ${te} | ${C.length} results_${re}`,`\n_Next: ${ie.join(` | `)}_`],ae=E+N.join(``);y&&(ae=sn(ae,y));let P=new Set,oe=[];for(let e of C){if(e.record.origin!==`curated`||e.record.sourcePath.startsWith(`[`))continue;let t=El(e.record.sourcePath);if(!t)continue;let n=wl(t,e.record.headingPath??t);n&&!P.has(n.uri)&&(P.add(n.uri),oe.push(n))}return{content:[{type:`text`,text:ae},...oe],structuredContent:{results:C.map(e=>({sourcePath:e.record.sourcePath,contentType:e.record.contentType,score:e.score,...e.record.headingPath?{headingPath:e.record.headingPath}:{},...e.record.startLine?{startLine:e.record.startLine}:{},...e.record.endLine?{endLine:e.record.endLine}:{},...e.record.origin===`indexed`?{}:{origin:e.record.origin},...e.record.category?{category:e.record.category}:{},...e.record.tags?.length?{tags:e.record.tags}:{}})),totalResults:C.length,searchMode:d,query:e}}}catch(e){return rp.error(`Search failed`,I(e)),K(`INTERNAL`,`Search failed: ${e instanceof Error?e.message:String(e)}`)}})}const gp=F(`tools`);function _p(e,t,n){let r=U(`session_digest`);e.registerTool(`session_digest`,{title:r.title,description:`Compress the current session's tool trajectory into a focused digest. Aggregates replay log, stash state, and checkpoints. Supports deterministic and LLM-assisted (sampling) modes with configurable token budget.`,inputSchema:{scope:L.enum([`tools`,`stash`,`all`]).default(`all`).describe(`What to include: tools (replay only), stash (stash + checkpoints only), or all`),since:L.string().optional().describe(`ISO timestamp — only include activity after this time`),last:L.number().min(1).max(500).optional().describe(`Max replay entries to consider (default: 50)`),focus:L.string().optional().describe(`Focus query — prioritize entries matching this topic`),mode:L.enum([`deterministic`,`sampling`]).default(`deterministic`).describe(`Summary mode: deterministic (fast, template-based) or sampling (LLM-assisted, richer)`),token_budget:L.number().min(100).max(8e3).default(2e3).describe(`Target token budget for the digest output`),persist:L.boolean().default(!0).describe(`Auto-save digest to stash for crash recovery`)},annotations:r.annotations},async({scope:e,since:r,last:i,focus:a,mode:o,token_budget:s,persist:c})=>{try{let l={scope:e,since:r,last:i,focus:a,mode:o,tokenBudget:s,persist:c},u=t?{stateStore:t}:void 0;return{content:[{type:`text`,text:(o===`sampling`&&n?.available?await Jt(l,async(e,t,r)=>(await n.createMessage({prompt:e,systemPrompt:t,maxTokens:r})).text,u):qt(l,u)).digest}]}}catch(e){return gp.error(`Session digest failed`,I(e)),K(`INTERNAL`,`Session digest failed: ${e instanceof Error?e.message:String(e)}`)}})}const vp=1e4,yp={defaultTtlSeconds:300,defaultLeaseTtlMinutes:10,globalEnabled:!1};function bp(e){return e??yp}function xp(e,t){let n=e.trim();if(!n)throw Error(`${t} is required`);return n}function Sp(e,t,n){let r=xp(e,t);if(r.length>n)throw Error(`${t} exceeds max length of ${n}`);return r}function Cp(e,t){if(!Number.isFinite(e)||e<=0)throw Error(`${t} must be greater than 0`);return Math.trunc(e)}function wp(e,t=!1,n){xp(e,`workspace`);let r=bp(n);if(!t)return e;if(!r.globalEnabled)throw Error(`Global signal scope is disabled`);return`__global__`}function Tp(e,t,n){let r=bp(n),i=wp(t.workspace,t.global??!1,r),a=Sp(t.key,`key`,500),o=Sp(t.value,`value`,vp),s=t.agent?Sp(t.agent,`agent`,500):void 0,c=Cp(t.ttlSeconds??r.defaultTtlSeconds,`ttlSeconds`);return e.signalPost(i,a,o,s,c)}function Ep(e,t,n){let r=xp(t,`workspace`),i=Sp(n,`key`,500);return e.signalGet(r,i)}function Dp(e,t){let n=xp(t,`workspace`);return e.signalList(n)}function Op(e,t,n){let r=xp(t,`workspace`),i=n===void 0?void 0:Sp(n,`key`,500);return e.signalClear(r,i)}function kp(e,t,n){let r=bp(n),i=Sp(t.resource,`resource`,500),a=Sp(t.holder,`holder`,500),o=xp(t.workspace,`workspace`),s=t.intent?Sp(t.intent,`intent`,vp):void 0,c=Cp(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 Ap(e,t,n,r){let i=xp(t,`workspace`),a=Sp(n,`resource`,500),o=Sp(r,`holder`,500);return e.leaseRelease(a,o,i)}function jp(e,t){let n=xp(t,`workspace`);return e.leaseList(n)}const Mp=F(`tools:signal`);function Np(e){return JSON.stringify(e,null,2)}function Pp(e,t,n){let r=U(`signal`),i={...yp,...n};e.registerTool(`signal`,{title:r.title,description:`Inter-agent signaling and lease coordination`,inputSchema:{action:L.enum([`post`,`get`,`list`,`clear`,`lease`,`unlease`,`leases`]).describe(`Signal action to perform`),workspace:L.string().describe(`Workspace identifier (required)`),key:L.string().optional().describe(`Signal key (for post/get/clear)`),value:L.string().optional().describe(`Signal value (for post)`),agent:L.string().optional().describe(`Agent identifier`),resource:L.string().optional().describe(`Resource path (for lease/unlease)`),holder:L.string().optional().describe(`Lease holder ID (for lease/unlease)`),intent:L.string().optional().describe(`What the holder plans to do`),ttl:L.number().optional().describe(`TTL (seconds for signals, minutes for leases)`),global:L.boolean().optional().describe(`Use global scope (default: false)`)},annotations:r.annotations},async({action:e,workspace:n,key:r,value:a,agent:o,resource:s,holder:c,intent:l,ttl:u,global:d})=>{try{switch(e){case`post`:{if(!r||a===void 0)throw Error(`key and value are required for post`);let e=Tp(t,{workspace:n,key:r,value:a,agent:o,ttlSeconds:u,global:d},i);return{content:[{type:`text`,text:Np({id:e})}],structuredContent:{id:e}}}case`get`:{if(!r)throw Error(`key is required for get`);let e=Ep(t,wp(n,d??!1,i),r);return{content:[{type:`text`,text:e.length===0?`[]`:Np(e)}],structuredContent:{signals:e}}}case`list`:{let e=Dp(t,wp(n,d??!1,i));return{content:[{type:`text`,text:e.length===0?`[]`:Np(e)}],structuredContent:{signals:e}}}case`clear`:{let e=Op(t,wp(n,d??!1,i),r);return{content:[{type:`text`,text:Np({cleared:e})}],structuredContent:{cleared:e}}}case`lease`:{if(!s||!c)throw Error(`resource and holder are required for lease`);let e=kp(t,{resource:s,holder:c,workspace:n,intent:l,ttlMinutes:u},i);return{content:[{type:`text`,text:Np(e)}],structuredContent:e}}case`unlease`:{if(!s||!c)throw Error(`resource and holder are required for unlease`);let e=Ap(t,n,s,c);return{content:[{type:`text`,text:Np({released:e})}],structuredContent:{released:e}}}case`leases`:{let e=jp(t,n);return{content:[{type:`text`,text:e.length===0?`[]`:Np(e)}],structuredContent:{leases:e}}}}}catch(e){return Mp.error(`Signal operation failed`,I(e)),K(`INTERNAL`,`Signal operation failed: ${e instanceof Error?e.message:String(e)}`)}})}const Fp=F(`tools`);function Ip(e,t,n,r=15e3){let i,a=new Promise(e=>{i=setTimeout(()=>{Fp.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),Fp.warn(`Status sub-operation "${n}" failed: ${e instanceof Error?e.message:String(e)}`),{value:t,timedOut:!1})),a])}function Lp(e){return e.onboarded?e.indexStale?{kind:`reindex`,reason:`Index stale. Run reindex() to update.`}:e.contextPressure>70?{kind:`handoff`,reason:`Context pressure high. Consider session handoff.`}:{kind:`proceed`,reason:`Ready to work.`}:{kind:`onboard`,reason:`Index not initialized. Run onboard({ path: "." }) first.`}}function Rp(){let e=Bn.get(),t=zn.get();if(e)return`- **Tree-sitter (WASM)**: ✅ Available (${t.grammarCount} grammars, dir: ${t.wasmDir})`;let n=t.pathsChecked.length?t.pathsChecked.map(e=>` ${e.exists?`✓`:`✗`} ${e.path}`).join(`
|
|
2887
2888
|
`):` none`,r=t.healAttempted?` Auto-heal: ${t.healSuccess?`✓ succeeded`:`✗ failed (${t.healError??`unknown`})`}`:` Auto-heal: not attempted`;return[`- **Tree-sitter (WASM)**: ⚠ Unavailable (regex fallback)`,` Reason: ${t.reason||`unknown`}`,` Paths checked:`,n,r,` OS: ${t.os} ${t.arch} | Node: ${t.nodeVersion}`,` Fix: Reinstall package or run vendor:wasm script`].join(`
|
|
2888
|
-
`)}const
|
|
2889
|
-
`)}],structuredContent:o}})}function
|
|
2890
|
-
`),ae={totalRecords:u.totalRecords,totalFiles:u.totalFiles,lastIndexedAt:u.lastIndexedAt??null,onboarded:_,onboardDir:h,contentTypes:u.contentTypeBreakdown,wasmAvailable:!!Bn.get(),wasmDiagnostics:zn.get(),graphStats:f,curatedCount:p,serverVersion:j,scaffoldVersion:k??null,workspaceScaffoldVersion:A??null,upgradeAvailable:ee||ne,storeBackend:a?.store?.backend,storeDiagnostics:E??null,contextPressure:v,nextAction:w};return{content:[{type:`text`,text:ie+(o===`smart`?"\n\n---\n_Next: Use `search` to query indexed content or `graph({action:'find_nodes', name_pattern:'<top-level-module>'})` → then `graph({action:'neighbors', node_id})` for relationships. Smart indexing handles updates automatically._":"\n\n---\n_Next: Use `search` to query indexed content, `graph({action:'find_nodes', name_pattern:'<top-level-module>'})` → then `graph({action:'neighbors', node_id})` for relationships, or `reindex` to refresh the index._")}],structuredContent:ae}}catch(e){return
|
|
2891
|
-
`)};if(i.length===1)try{return{content:[{type:`text`,text:`${await a(i[0])}\n---\n_Next: Use \`web_fetch\` to read any of these pages in full._`}]}}catch(e){return
|
|
2889
|
+
`)}const zp=5*6e4;let Bp=null,Vp=null;function Hp(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 Up(){let e=Date.now();if(Bp&&e-Bp.ts<zp)return Bp.value;try{let t=P(Sn(),`.copilot`,`.aikit-scaffold.json`);if(!D(t))return Bp={value:null,ts:e},null;let n=JSON.parse(k(t,`utf-8`)).version??null;return Bp={value:n,ts:e},n}catch{return Bp={value:null,ts:e},null}}function Wp(){let e=Date.now();if(Vp&&e-Vp.ts<zp)return Vp.value;try{let t=P(process.cwd(),`.github`,`.aikit-scaffold.json`);if(!D(t))return Vp={value:null,ts:e},null;let n=JSON.parse(k(t,`utf-8`)).version??null;return Vp={value:n,ts:e},n}catch{return Vp={value:null,ts:e},null}}function Gp(e){let t=U(`status`);e.registerTool(`status`,{title:t.title,description:`Get the current status and statistics of the AI Kit index.`,outputSchema:po,annotations:t.annotations},async()=>{let e=b(),t=Up(),n=Wp(),r=t!=null&&t!==e,i=n!=null&&n!==e,a=[`## AI Kit Status`,``,`⏳ **AI Kit is initializing** — index stats will be available shortly.`,``,`### Runtime`,`- **Tree-sitter (WASM)**: ${Bn.get()?`✅ Available (AST analysis)`:`⚠ Unavailable (regex fallback)`}`,``,`### Version`,`- **Server**: ${e}`,`- **Scaffold (user)**: ${t??`not installed`}`,`- **Scaffold (workspace)**: ${n??`not installed`}`];if(r||i){let o=x(),s=[];r&&s.push(`user scaffold v${t}`),i&&s.push(`workspace scaffold v${n}`);let c=s.join(`, `);o.state===`success`?a.push(``,`### ✅ Upgrade Applied`,`- Server v${e} — ${c} auto-upgraded successfully.`,`- _Restart the MCP server to use the updated version._`):o.state===`pending`?a.push(``,`### ⏳ Upgrade In Progress`,`- Server v${e} ≠ ${c}`,`- Auto-upgrade is running in the background…`):o.state===`failed`?(y(),a.push(``,`### ⬆ Upgrade Available (auto-upgrade failed, retrying)`,`- Server v${e} ≠ ${c}`,`- Error: ${o.error??`unknown`}`)):(y(),a.push(``,`### ⬆ Upgrade Available`,`- Server v${e} ≠ ${c}`,`- Auto-upgrade triggered — check again shortly.`))}let o={totalRecords:0,totalFiles:0,lastIndexedAt:null,onboarded:!1,onboardDir:``,contentTypes:{},wasmAvailable:!!Bn.get(),wasmDiagnostics:zn.get(),graphStats:null,curatedCount:0,serverVersion:e,scaffoldVersion:t??null,workspaceScaffoldVersion:n??null,upgradeAvailable:r||i,contextPressure:0,nextAction:Lp({onboarded:!1,indexStale:!1,contextPressure:0})};return{content:[{type:`text`,text:a.join(`
|
|
2890
|
+
`)}],structuredContent:o}})}function Kp(e,t,n,r,i,a,o,s){let c=U(`status`);e.registerTool(`status`,{title:c.title,description:`Get the current status and statistics of the AI Kit index.`,outputSchema:po,annotations:c.annotations},async()=>{let e=[];try{let[c,l]=await Promise.all([Ip(t.getStats(),{totalRecords:0,totalFiles:0,lastIndexedAt:null,contentTypeBreakdown:{}},`store.getStats`),Ip(t.listSourcePaths(),[],`store.listSourcePaths`)]),u=c.value;c.timedOut&&e.push(`⚠ Index stats timed out — values may be incomplete`);let d=l.value;l.timedOut&&e.push(`⚠ File listing timed out`);let f=null,p=0,m=[`## AI Kit Status`,``,`- **Total Records**: ${u.totalRecords}`,`- **Total Files**: ${u.totalFiles}`,`- **Last Indexed**: ${u.lastIndexedAt??`Never`}`,``,`### Content Types`,...Object.entries(u.contentTypeBreakdown).map(([e,t])=>`- ${e}: ${t}`),``,`### Indexed Files`,...d.slice(0,50).map(e=>`- ${e}`),d.length>50?`\n... and ${d.length-50} more files`:``];if(n)try{let t=await Ip(n.getStats(),{nodeCount:0,edgeCount:0,nodeTypes:{},edgeTypes:{}},`graphStore.getStats`);if(t.timedOut)e.push(`⚠ Graph stats timed out`),m.push(``,`### Knowledge Graph`,`- Graph stats timed out`);else{let e=t.value;f={nodes:e.nodeCount,edges:e.edgeCount},m.push(``,`### Knowledge Graph`,`- **Nodes**: ${e.nodeCount}`,`- **Edges**: ${e.edgeCount}`,...Object.entries(e.nodeTypes).map(([e,t])=>` - ${e}: ${t}`));try{let e=await Ip(n.validate(),{valid:!0,danglingEdges:[],orphanNodes:[],stats:{nodeCount:0,edgeCount:0,nodeTypes:{},edgeTypes:{}}},`graphStore.validate`);if(!e.timedOut){let t=e.value;t.valid||m.push(`- **⚠ Integrity Issues**: ${t.danglingEdges.length} dangling edges`),t.orphanNodes.length>0&&m.push(`- **Orphan nodes**: ${t.orphanNodes.length}`)}}catch{}}}catch{m.push(``,`### Knowledge Graph`,`- Graph store unavailable`)}let h=a?.onboardDir??``,g=D(h),_=i?.onboardComplete||g;if(m.push(``,`### Onboard Status`,_?`- ✅ Complete${i?.onboardTimestamp?` (last: ${i.onboardTimestamp})`:``}`:'- ❌ Not run — call `onboard({ path: "." })` to analyze the codebase',`- **Onboard Directory**: \`${h}\``),r)try{let t=await Ip(r.list(),[],`curated.list`);if(t.timedOut)e.push(`⚠ Curated knowledge listing timed out`),m.push(``,`### Curated Knowledge`,`- Listing timed out`);else{let e=t.value;p=e.length,m.push(``,`### Curated Knowledge`,e.length>0?`- ${e.length} entries`:'- Empty — use `knowledge({ action: "remember", ... })` to persist decisions')}}catch{m.push(``,`### Curated Knowledge`,`- Unable to read curated entries`)}let v=Hp(u.totalRecords,f?.nodes??0,f?.edges??0,p),S=u.lastIndexedAt?new Date(u.lastIndexedAt).getTime():0,C=S>0?Date.now()-S:1/0,w=Lp({onboarded:_,indexStale:_&&C>1440*60*1e3,contextPressure:v});m.push(``),m.push(`## 📊 Context Pressure: ${v}/100`),v>=80?m.push(`⚠️ High pressure — consider pruning stale entries or compacting context.`):v>=50?m.push(`ℹ️ Moderate pressure — AI Kit memory is well-populated.`):m.push(`✅ Low pressure — plenty of headroom for more content.`);let T=0;if(u.lastIndexedAt){T=new Date(u.lastIndexedAt).getTime();let e=(Date.now()-T)/(1e3*60*60);m.push(``,`### Index Freshness`,e>24?o===`smart`?`- ⚠ Last indexed ${Math.floor(e)}h ago — smart indexing will refresh automatically`:`- ⚠ Last indexed ${Math.floor(e)}h ago — may be stale. Run \`reindex({})\``:`- ✅ Last indexed ${e<1?`less than 1h`:`${Math.floor(e)}h`} ago`)}m.push(``,`### Next Action`,`- **${w.kind}**: ${w.reason}`);let E=null,O=t;if(typeof O.getDiagnostics==`function`)try{E=O.getDiagnostics(),m.push(``,`### Storage`,`- **Backend**: ${a?.store?.backend??`unknown`}`,`- **Adapter**: ${E.adapterType}`,`- **Vector search**: ${E.vectorSearchEnabled?`✅ enabled`:`⚠ disabled (FTS-only fallback)`}`,E.dbPath?`- **DB**: ${E.dbPath}`:``,E.dbSizeBytes==null?``:`- **DB size**: ${(E.dbSizeBytes/1024/1024).toFixed(2)} MB`,`- **Embedding dim**: ${E.embeddingDim}`,`- **Vector dtype**: ${E.vectorDtype}`)}catch{}if(o===`smart`)if(m.push(``,`### Smart Indexing`),s){let e=s();e?m.push(`- **Mode**: Smart (trickle)`,`- **Status**: ${e.running?`✅ Running`:`⏸ Stopped`}`,`- **Queue**: ${e.queueSize} files pending`,`- **Changed files**: ${e.changedFilesSize} detected`,`- **Interval**: ${Math.round(e.intervalMs/1e3)}s per batch of ${e.batchSize}`):m.push(`- **Mode**: Smart (trickle)`,`- **Status**: scheduler state unavailable (init may have failed)`)}else m.push(`- **Mode**: Smart (trickle) — scheduler state unavailable`);{try{let e=a?.stateDir?N(a.stateDir,`stash`):null;if(e&&D(e)){let t=te(e).mtimeMs;t>T&&(T=t)}}catch{}let e=[];if(r)try{let t=p>0?await r.list():[];for(let e of t){let t=new Date(e.updated||e.created).getTime();t>T&&(T=t)}e.push(...t.sort((e,t)=>new Date(t.updated).getTime()-new Date(e.updated).getTime()).slice(0,5))}catch{}let t=T>0?Date.now()-T:0;if(t>=144e5){let n=Math.floor(t/36e5);if(m.push(``,`### 🌅 Session Briefing`,`_${n}+ hours since last activity — here's what to pick up:_`,``),e.length>0){m.push(`**Recent decisions/notes:**`);for(let t of e)m.push(`- **${t.title}** (${t.category??`note`}) — ${(t.contentPreview??``).slice(0,80)}…`)}m.push(``,`**Suggested next steps:**`,'- `search({ query: "SESSION CHECKPOINT", origin: "curated" })` — find your last checkpoint',"- `restore({})` — resume from a saved checkpoint",'- `knowledge({ action: "list" })` — browse all stored knowledge')}}m.push(``,`### Runtime`,Rp());let k=Up(),A=Wp(),j=b(),ee=k!=null&&k!==j,ne=A!=null&&A!==j;if(ee||ne){let e=x(),t=[];ee&&t.push(`user scaffold v${k}`),ne&&t.push(`workspace scaffold v${A}`);let n=t.join(`, `);e.state===`success`?m.push(``,`### ✅ Upgrade Applied`,`- Server v${j} — ${n} auto-upgraded successfully.`,`- _Restart the MCP server to use the updated version._`):e.state===`pending`?m.push(``,`### ⏳ Upgrade In Progress`,`- Server v${j} ≠ ${n}`,`- Auto-upgrade is running in the background…`):e.state===`failed`?(y(),m.push(``,`### ⬆ Upgrade Available (auto-upgrade failed, retrying)`,`- Server v${j} ≠ ${n}`,`- Error: ${e.error??`unknown`}`)):(y(),m.push(``,`### ⬆ Upgrade Available`,`- Server v${j} ≠ ${n}`,`- Auto-upgrade triggered — check again shortly.`))}e.length>0&&m.push(``,`### ⚠ Warnings`,...e.map(e=>`- ${e}`));let re=xa();if(re.length>0){let e=re.sort((e,t)=>t.callCount-e.callCount);m.push(``,`### Tool Usage This Session`,``),m.push(`| Tool | Calls | Tokens In | Tokens Out | Errors | Avg Latency |`),m.push(`|------|-------|-----------|------------|--------|-------------|`);for(let t of e.slice(0,15)){let e=Math.round(t.totalInputChars/4),n=Math.round(t.totalOutputChars/4),r=Math.round(t.totalDurationMs/t.callCount);m.push(`| ${t.tool} | ${t.callCount} | ${e.toLocaleString()} | ${n.toLocaleString()} | ${t.errorCount} | ${r}ms |`)}}let M=pa();if(M.bufferSize>=10){let e=M.state===`healthy`?`🟢`:M.state===`degraded`?`🔴`:`🟡`;m.push(``,`### Auto-GC: ${e} ${M.state}`),m.push(`- p95 latency: ${M.p95}ms | buffer: ${M.bufferSize} samples`),M.gcCount>0&&m.push(`- GC cycles triggered: ${M.gcCount}`)}let ie=m.join(`
|
|
2891
|
+
`),ae={totalRecords:u.totalRecords,totalFiles:u.totalFiles,lastIndexedAt:u.lastIndexedAt??null,onboarded:_,onboardDir:h,contentTypes:u.contentTypeBreakdown,wasmAvailable:!!Bn.get(),wasmDiagnostics:zn.get(),graphStats:f,curatedCount:p,serverVersion:j,scaffoldVersion:k??null,workspaceScaffoldVersion:A??null,upgradeAvailable:ee||ne,storeBackend:a?.store?.backend,storeDiagnostics:E??null,contextPressure:v,nextAction:w};return{content:[{type:`text`,text:ie+(o===`smart`?"\n\n---\n_Next: Use `search` to query indexed content or `graph({action:'find_nodes', name_pattern:'<top-level-module>'})` → then `graph({action:'neighbors', node_id})` for relationships. Smart indexing handles updates automatically._":"\n\n---\n_Next: Use `search` to query indexed content, `graph({action:'find_nodes', name_pattern:'<top-level-module>'})` → then `graph({action:'neighbors', node_id})` for relationships, or `reindex` to refresh the index._")}],structuredContent:ae}}catch(e){return Fp.error(`Status failed`,I(e)),K(`INTERNAL`,`Status check failed: ${e instanceof Error?e.message:String(e)}`)}})}const qp=F(`tools`);function Jp(e){let t=U(`web_search`);e.registerTool(`web_search`,{title:t.title,description:`PREFERRED web search — fans out to multiple keyless providers (DuckDuckGo + Bing-HTML + Mojeek) by default, returning a deduplicated, consensus-ranked union within a 10s deadline. Optional providers (SearXNG, Google, Brave, Bing API) join the fan-out automatically when their env vars are set. Pass one query or multiple for parallel searching.`,inputSchema:{queries:L.array(L.string().max(2e3)).min(1).max(5).describe('Search queries (1–5). Single: `["react hooks"]`. Multiple searched in parallel.'),limit:L.number().min(1).max(20).default(5).describe(`Max results per query`),site:L.string().optional().describe(`Restrict to domain (e.g., "docs.aws.amazon.com")`),provider:L.enum([`multi`,`duckduckgo`,`bing-html`,`mojeek`,`searxng`,`google`,`brave`,`bing`]).optional().describe("Search provider. Defaults to env AIKIT_SEARCH_PROVIDER, then `multi` (fan-out). Single keyless: `duckduckgo`, `bing-html`, `mojeek`. Self-hosted: `searxng` (requires SEARXNG_URL). Keyed APIs: `google` (GOOGLE_API_KEY+GOOGLE_CSE_ID), `brave` (BRAVE_API_KEY), `bing` (BING_API_KEY). Missing keys auto-fall back to duckduckgo.")},annotations:t.annotations},async({queries:e,limit:t,site:n,provider:r})=>{let i=e,a=async e=>{let i=await fn({query:e,limit:t,site:n,provider:r}),a=[`## Search: ${i.query} _(via ${i.provider})_`,``];if(i.results.length===0)a.push(`No results found.`);else for(let e of i.results)a.push(`### [${e.title}](${e.url})`,e.snippet,``);return a.join(`
|
|
2892
|
+
`)};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 qp.error(`Web search failed`,I(e)),K(`INTERNAL`,`Web search failed: ${e instanceof Error?e.message:String(e)}`)}let o=await Promise.allSettled(i.map(e=>a(e))),s=[],c=0;for(let e=0;e<o.length;e++){let t=o[e];if(t.status===`fulfilled`)s.push(t.value);else{c++;let n=t.reason instanceof Error?t.reason.message:String(t.reason);qp.error(`Web search failed`,{query:i[e],error:n}),s.push(`## ❌ Search failed: ${i[e]}\n\n${n}`)}}let l=`_Searched ${o.length-c}/${o.length} queries successfully._`;s.push(``,`---`,l,"_Next: Use `web_fetch` to read any of these pages in full._");let u=s.join(`
|
|
2892
2893
|
|
|
2893
|
-
`);return c===o.length?K(`INTERNAL`,u):{content:[{type:`text`,text:u}]}})}function
|
|
2894
|
-
`)}]}}catch(e){return
|
|
2895
|
-
`)}]}})}function
|
|
2896
|
-
`)}],structuredContent:i}}catch(e){return
|
|
2894
|
+
`);return c===o.length?K(`INTERNAL`,u):{content:[{type:`text`,text:u}]}})}function Yp(e){let t=U(`http`);e.registerTool(`http`,{title:t.title,description:`Make HTTP requests (GET/POST/PUT/PATCH/DELETE/HEAD) for API testing. Returns status, headers, and formatted body with timing info.`,inputSchema:{url:L.string().url().describe(`Request URL (http/https only)`),method:L.enum([`GET`,`POST`,`PUT`,`PATCH`,`DELETE`,`HEAD`]).default(`GET`).describe(`HTTP method`),headers:L.record(L.string(),L.string()).optional().describe(`Request headers as key-value pairs`),body:L.string().optional().describe(`Request body (for POST/PUT/PATCH)`),timeout:L.number().min(1e3).max(6e4).default(15e3).describe(`Timeout in milliseconds`)},annotations:t.annotations},async({url:e,method:t,headers:n,body:r,timeout:i})=>{try{let a=await st({url:e,method:t,headers:n,body:r,timeout:i}),o=[`## ${t} ${e}`,``,`**Status:** ${a.status} ${a.statusText}`,`**Time:** ${a.durationMs}ms`,`**Size:** ${a.sizeBytes} bytes`,`**Content-Type:** ${a.contentType}`,``,`### Headers`,"```json",JSON.stringify(a.headers),"```",``,`### Body`,a.contentType.includes(`json`)?"```json":"```",a.body,"```"];return a.truncated&&o.push(``,`_Response truncated — total size: ${a.sizeBytes} bytes_`),{content:[{type:`text`,text:o.join(`
|
|
2895
|
+
`)}]}}catch(e){return qp.error(`HTTP request failed`,I(e)),K(`INTERNAL`,`HTTP request failed: ${e instanceof Error?e.message:String(e)}`)}})}function Xp(e){let t=U(`regex_test`);e.registerTool(`regex_test`,{title:t.title,description:`Test a regex pattern against sample strings. Supports match, replace, and split modes.`,inputSchema:{pattern:L.string().max(500).describe(`Regex pattern (without delimiters)`),flags:L.string().max(10).regex(/^[gimsuy]*$/).default(``).describe(`Regex flags (g, i, m, s, etc.)`),test_strings:L.array(L.string().max(1e4)).max(50).describe(`Strings to test the pattern against`),mode:L.enum([`match`,`replace`,`split`]).default(`match`).describe(`Test mode`),replacement:L.string().optional().describe(`Replacement string (for replace mode)`)},annotations:t.annotations},async({pattern:e,flags:t,test_strings:n,mode:r,replacement:i})=>{let a=Ft({pattern:e,flags:t,testStrings:n,mode:r,replacement:i});if(!a.valid)return K(`VALIDATION`,`Invalid regex: ${a.error}`);let o=[`## Regex: \`/${a.pattern}/${a.flags}\``,``,`Mode: ${r}`,``];for(let e of a.results){if(o.push(`**Input:** \`${e.input}\``),o.push(`**Matched:** ${e.matched}`),e.matches)for(let t of e.matches){let e=t.groups.length>0?` groups: [${t.groups.join(`, `)}]`:``;o.push(` - "${t.full}" at index ${t.index}${e}`)}e.replaced!==void 0&&o.push(`**Result:** \`${e.replaced}\``),e.split&&o.push(`**Split:** ${JSON.stringify(e.split)}`),o.push(``)}return{content:[{type:`text`,text:o.join(`
|
|
2896
|
+
`)}]}})}function Zp(e){let t=U(`encode`);e.registerTool(`encode`,{title:t.title,description:`Encode, decode, or hash text. Supports base64, URL encoding, SHA-256, MD5, JWT decode, hex.`,inputSchema:{operation:L.enum([`base64_encode`,`base64_decode`,`url_encode`,`url_decode`,`sha256`,`md5`,`jwt_decode`,`hex_encode`,`hex_decode`]).describe(`Operation to perform`),input:L.string().max(1e6).describe(`Input text`)},annotations:t.annotations},async({operation:e,input:t})=>{try{let n=We({operation:e,input:t});return{content:[{type:`text`,text:`## ${e}\n\n**Input:** \`${t.length>100?`${t.slice(0,100)}...`:t}\`\n**Output:**\n\`\`\`\n${n.output}\n\`\`\``}]}}catch(e){return qp.error(`Encode failed`,I(e)),K(`INTERNAL`,`Encode failed: ${e instanceof Error?e.message:String(e)}`)}})}function Qp(e){let t=U(`measure`);e.registerTool(`measure`,{title:t.title,description:`Measure code complexity, line counts, and function counts for a file or directory. Returns per-file metrics sorted by complexity.`,outputSchema:ho,inputSchema:{path:L.string().describe(`File or directory path to measure`),extensions:L.array(L.string()).optional().describe(`File extensions to include (default: .ts,.tsx,.js,.jsx)`)},annotations:t.annotations},async({path:e,extensions:t})=>{try{let n=await _t({path:e,extensions:t}),r=[`## Code Metrics`,``,`**Files:** ${n.summary.totalFiles}`,`**Total lines:** ${n.summary.totalLines} (${n.summary.totalCodeLines} code)`,`**Functions:** ${n.summary.totalFunctions}`,`**Avg complexity:** ${n.summary.avgComplexity}`,`**Max complexity:** ${n.summary.maxComplexity.value} (${n.summary.maxComplexity.file})`,``,`### Top files by complexity`,``,`| File | Lines | Code | Complexity | Cognitive | Functions | Imports |`,`|------|-------|------|------------|-----------|-----------|---------|`];for(let e of n.files.slice(0,20)){let t=e.cognitiveComplexity===void 0?`—`:String(e.cognitiveComplexity);r.push(`| ${e.path} | ${e.lines.total} | ${e.lines.code} | ${e.complexity} | ${t} | ${e.functions} | ${e.imports} |`)}n.files.length>20&&r.push(``,`_...and ${n.files.length-20} more files_`);let i={summary:{totalFiles:n.summary.totalFiles,totalLines:n.summary.totalLines,totalCodeLines:n.summary.totalCodeLines,totalFunctions:n.summary.totalFunctions,avgComplexity:n.summary.avgComplexity,maxComplexity:{value:n.summary.maxComplexity.value,file:n.summary.maxComplexity.file}},files:n.files.map(e=>({path:e.path,lines:e.lines.total,code:e.lines.code,complexity:e.complexity,functions:e.functions}))};return{content:[{type:`text`,text:r.join(`
|
|
2897
|
+
`)}],structuredContent:i}}catch(e){return qp.error(`Measure failed`,I(e)),K(`INTERNAL`,`Measure failed: ${e instanceof Error?e.message:String(e)}`)}})}function $p(e){let t=U(`changelog`);e.registerTool(`changelog`,{title:t.title,description:`Generate a changelog from git history between two refs. Groups by conventional commit type.`,inputSchema:{from:L.string().max(200).describe(`Start ref (tag, SHA, HEAD~N)`),to:L.string().max(200).default(`HEAD`).describe(`End ref (default: HEAD)`),format:L.enum([`grouped`,`chronological`,`per-scope`]).default(`grouped`).describe(`Output format`),include_breaking:L.boolean().default(!0).describe(`Highlight breaking changes`),cwd:L.string().optional().describe(`Repository root or working directory`)},annotations:t.annotations},async({from:e,to:t,format:n,include_breaking:r,cwd:i})=>{try{let a=Te({from:e,to:t,format:n,includeBreaking:r,cwd:i}),o=`${a.stats.total} commits (${Object.entries(a.stats.types).map(([e,t])=>`${t} ${e}`).join(`, `)})`;return{content:[{type:`text`,text:`${a.markdown}\n---\n_${o}_`}]}}catch(e){return qp.error(`Changelog failed`,I(e)),K(`INTERNAL`,`Changelog failed: ${e instanceof Error?e.message:String(e)}`)}})}function em(e){let t=U(`schema_validate`);e.registerTool(`schema_validate`,{title:t.title,description:`Validate JSON data against a JSON Schema. Supports type, required, properties, items, enum, pattern, min/max.`,inputSchema:{data:L.string().max(5e5).describe(`JSON data to validate (as string)`),schema:L.string().max(5e5).describe(`JSON Schema to validate against (as string)`)},annotations:t.annotations},async({data:e,schema:t})=>{try{let n=Gt({data:JSON.parse(e),schema:JSON.parse(t)});if(n.valid)return{content:[{type:`text`,text:`## Validation: PASSED
|
|
2897
2898
|
|
|
2898
2899
|
Data matches the schema.`}]};let r=[`## Validation: FAILED`,``,`**${n.errors.length} error(s):**`,``];for(let e of n.errors){let t=e.expected?` (expected: ${e.expected}, got: ${e.received})`:``;r.push(`- \`${e.path}\`: ${e.message}${t}`)}return{content:[{type:`text`,text:r.join(`
|
|
2899
|
-
`)}]}}catch(e){return
|
|
2900
|
-
`)}],structuredContent:a}})}function
|
|
2901
|
-
`)}],structuredContent:o}}catch(e){return
|
|
2900
|
+
`)}]}}catch(e){return qp.error(`Schema validation failed`,I(e)),K(`INTERNAL`,`Schema validation failed: ${e instanceof Error?e.message:String(e)}`)}})}function tm(e){let t=U(`env`);e.registerTool(`env`,{title:t.title,description:`Get system and runtime environment info. Sensitive env vars are redacted by default.`,outputSchema:go,inputSchema:{include_env:L.boolean().default(!1).describe(`Include environment variables`),filter_env:L.string().optional().describe(`Filter env vars by name substring`),show_sensitive:L.boolean().default(!1).describe(`Show sensitive values (keys, tokens, etc.) — redacted by default`)},annotations:t.annotations},async({include_env:e,filter_env:t,show_sensitive:n})=>{let r=Ke({includeEnv:e,filterEnv:t,showSensitive:n}),i=[`## Environment`,``,`**Platform:** ${r.system.platform} ${r.system.arch}`,`**OS:** ${r.system.type} ${r.system.release}`,`**Host:** ${r.system.hostname}`,`**CPUs:** ${r.system.cpus}`,`**Memory:** ${r.system.memoryFreeGb}GB free / ${r.system.memoryTotalGb}GB total`,``,`**Node:** ${r.runtime.node}`,`**V8:** ${r.runtime.v8}`,`**CWD:** ${r.cwd}`];if(r.env){i.push(``,`### Environment Variables`,``);for(let[e,t]of Object.entries(r.env))i.push(`- \`${e}\`: ${t}`)}let a={platform:r.system.platform,arch:r.system.arch,nodeVersion:r.runtime.node,cwd:r.cwd,cpus:r.system.cpus,memoryFreeGb:r.system.memoryFreeGb,memoryTotalGb:r.system.memoryTotalGb};return{content:[{type:`text`,text:i.join(`
|
|
2901
|
+
`)}],structuredContent:a}})}function nm(e){let t=U(`time`);e.registerTool(`time`,{title:t.title,description:`Parse dates, convert timezones, calculate durations, add time. Supports ISO 8601, unix timestamps, and human-readable formats.`,outputSchema:_o,inputSchema:{operation:L.enum([`now`,`parse`,`convert`,`diff`,`add`]).describe(`now: current time | parse: parse a date string | convert: timezone conversion | diff: duration between two dates | add: add duration to date`),input:L.string().optional().describe(`Date input (ISO, unix timestamp, or parseable string). For diff: two comma-separated dates`),timezone:L.string().optional().describe(`Target timezone (e.g., "America/New_York", "Asia/Tokyo")`),duration:L.string().optional().describe(`Duration to add (e.g., "2h30m", "1d", "30s") — for add operation`)},annotations:t.annotations},async({operation:e,input:t,timezone:n,duration:r})=>{try{let i=an({operation:e,input:t,timezone:n,duration:r}),a=[`**${i.output}**`,``,`ISO: ${i.iso}`,`Unix: ${i.unix}`];i.details&&a.push(``,"```json",JSON.stringify(i.details),"```");let o={iso:i.iso,unix:i.unix,timezone:n??Intl.DateTimeFormat().resolvedOptions().timeZone,formatted:i.output};return{content:[{type:`text`,text:a.join(`
|
|
2902
|
+
`)}],structuredContent:o}}catch(e){return qp.error(`Time failed`,I(e)),K(`INTERNAL`,`Time failed: ${e instanceof Error?e.message:String(e)}`)}})}function rm(e){try{let t=N(e,`.flows`);if(!D(t))return null;let n=A(t,{withFileTypes:!0});for(let e of n){if(!e.isDirectory())continue;let n=N(t,e.name,`meta.json`);if(D(n)&&JSON.parse(k(n,`utf-8`)).status===`active`)return e.name}}catch{return null}return null}function im(e,t,n,r,i,a,o,s,c,l){let u=new oa,d=n.sources[0]?.path??process.cwd(),f={activeSlug:null};f.activeSlug=rm(d);let p=new Ei(N(n.stateDir??``,`flow-context`),()=>f.activeSlug),m=new _i;m.register(mi),m.register(Vr),m.register(di),m.register(Rr),m.register(Pr),m.register(Fr),m.register(gi),m.register(ui(()=>f.activeSlug?{active:!0,slug:f.activeSlug}:null));let h=new Si(m,t.curated,{},p),g=l??lo(n,[...La,...ja],H,Na(n)),_=e=>g.has(e),v=new Set([...g].filter(e=>!Nu.includes(e)&&!Ki.has(e))),y=new Xi;u.use(bi(h),{order:5,name:`auto-knowledge`}),u.use(Ca(),{order:10,name:`replay`}),u.use($i(y,{stateStore:t.stateStore,curatedStore:t.curated},{trackedTools:v}),{order:94,name:`procedural-memory`}),u.use(Hi(new Bi(t.stateStore,t.curated)),{order:95,name:`observation-capture`}),u.use(za(),{order:1,name:`structured-content-guard`}),u.use(Ti(wi(n.tokenBudget)),{order:90,name:`compression`}),Ja(e,u,n.toolPrefix??``);let b=[...g].filter(e=>Ma.has(e)?Aa.includes(e)?!!t.bridge:e===`er_update_policy`?!!t.policyStore:e===`er_evolve_review`?!!t.evolutionCollector:!1:!0);_(`search`)&&hp(e,t.embedder,t.store,t.graphStore,t.bridge,t.evolutionCollector,a,t.stateStore,n.memory?.retention,n.memory?.consolidation);let x={store:t.store,graphStore:t.graphStore,embedder:t.embedder},S=c?e=>{c()?.prioritize(e)}:void 0;_(`lookup`)&&wu(e,t.store,x);let C={onboardComplete:t.onboardComplete,onboardTimestamp:t.onboardTimestamp};_(`status`)&&Kp(e,t.store,t.graphStore,t.curated,C,n,o,s),_(`config`)&&Xs(e,n),_(`reindex`)&&Yf(e,t.indexer,n,t.curated,t.store,i,o),_(`knowledge`)&&Su(e,t.curated,t.policyStore,t.evolutionCollector,i,p,t.stateStore,n.memory?.retention,n.memory?.supersession,n.memory?.consolidation,n.memory?.lessons),_(`analyze`)&&vs(e,t.store,t.embedder,x),_(`blast_radius`)&&ys(e,t.store,t.embedder,t.graphStore,x),_(`produce_knowledge`)&&qf(e,n),_(`onboard`)&&zu(e,t.store,t.embedder,n,C,x),_(`graph`)&&pl(e,t.graphStore),_(`audit`)&&ws(e,t.store,t.embedder,n.tokenBudget),_(`compact`)&&sc(e,t.embedder,t.fileCache,d,n.allRoots,x,S),_(`scope_map`)&&cc(e,t.embedder,t.store,x),_(`find`)&&lc(e,t.embedder,t.store,d,x),_(`parse_output`)&&Cc(e),_(`workset`)&&Vu(e),_(`check`)&&bc(e,x,n.tokenBudget),_(`symbol`)&&uc(e,t.embedder,t.store,t.graphStore),_(`eval`)&&xc(e),_(`test_run`)&&Sc(e,x),_(`stash`)&&Hu(e,t.stateStore),_(`signal`)&&Pp(e,t.stateStore),_(`git_context`)&&Eu(e),_(`diff_parse`)&&Du(e),_(`rename`)&&Ou(e),_(`codemod`)&&ku(e),_(`restore`)&&$f(e),_(`file_summary`)&&dc(e,t.fileCache,d,n.allRoots,x,S),_(`checkpoint`)&&Uu(e,t.stateStore),_(`data_transform`)&&Au(e),_(`trace`)&&fc(e,t.embedder,t.store,t.graphStore),_(`process`)&&hl(e),_(`watch`)&&gl(e),_(`dead_symbols`)&&pc(e,t.embedder,t.store,d,n.allRoots,x),_(`delegate`)&&wc(e,a),_(`health`)&&_l(e),_(`lane`)&&Wu(e),_(`queue`)&&Gu(e),_(`web_fetch`)&&vl(e),_(`guide`)&&yl(e,o),Nu.some(e=>_(e))&&Pu(e,n,b),_(`evidence_map`)&&al(e),_(`digest`)&&ol(e,t.embedder),_(`forge_classify`)&&sl(e),_(`stratum_card`)&&cl(e,t.embedder,t.fileCache),_(`forge_ground`)&&ll(e,t.embedder,t.store),_(`present`)&&Gf(e,r),_(`browser`)&&An(e,n),_(`web_search`)&&Jp(e),_(`http`)&&Yp(e),_(`regex_test`)&&Xp(e),_(`encode`)&&Zp(e),_(`measure`)&&Qp(e),_(`changelog`)&&$p(e),_(`schema_validate`)&&em(e),_(`env`)&&tm(e),_(`time`)&&nm(e),_(`flow`)&&rl(e,n,e=>{f.activeSlug=e}),t.bridge&&Aa.some(e=>_(e))&&(Os(e,t.bridge,t.evolutionCollector),ks(e,t.bridge),As(e,t.bridge)),t.policyStore&&_(`er_update_policy`)&&Zu(e,t.policyStore),t.evolutionCollector&&_(`er_evolve_review`)&&vc(e,t.evolutionCollector),ka(e,t.store,t.curated),_(`replay`)&&Zf(e),_(`session_digest`)&&_p(e,t.stateStore,a)}function am(e,t,n){let r=e=>!n||n.has(e);r(`check`)&&bc(e,void 0,t.tokenBudget),r(`eval`)&&xc(e),r(`test_run`)&&Sc(e),r(`parse_output`)&&Cc(e),r(`delegate`)&&wc(e),r(`git_context`)&&Eu(e),r(`diff_parse`)&&Du(e),r(`rename`)&&Ou(e),r(`codemod`)&&ku(e),r(`data_transform`)&&Au(e),r(`workset`)&&Vu(e),r(`restore`)&&$f(e),r(`lane`)&&Wu(e),r(`queue`)&&Gu(e),r(`session_digest`)&&_p(e),r(`health`)&&_l(e),r(`process`)&&hl(e),r(`watch`)&&gl(e),r(`web_fetch`)&&vl(e),r(`guide`)&&yl(e),Nu.some(e=>r(e))&&Pu(e,t,[...n??new Set(La)]),r(`evidence_map`)&&al(e),r(`forge_classify`)&&sl(e),r(`present`)&&Gf(e),r(`browser`)&&An(e,t),r(`produce_knowledge`)&&qf(e),r(`replay`)&&Zf(e),r(`status`)&&Gp(e),r(`flow`)&&rl(e,t),r(`web_search`)&&Jp(e),r(`http`)&&Yp(e),r(`regex_test`)&&Xp(e),r(`encode`)&&Zp(e),r(`measure`)&&Qp(e),r(`changelog`)&&$p(e),r(`schema_validate`)&&em(e),r(`env`)&&tm(e),r(`time`)&&nm(e)}const om=F(`resource-notifier`);var sm=class{mcpServer;constructor(e){this.mcpServer=e}async notifyStatusChanged(){await this.sendUpdate(`aikit://status`)}async notifyFileTreeChanged(){await this.sendUpdate(`aikit://file-tree`)}async notifyCuratedIndexChanged(){await this.sendUpdate(`aikit://curated`)}async notifyCuratedEntryChanged(e){await this.sendUpdate(`aikit://curated/${e}`)}async notifyResourceListChanged(){try{await this.mcpServer.server.sendResourceListChanged()}catch(e){om.debug(`sendResourceListChanged failed`,{error:String(e)})}}async notifyAfterReindex(){await Promise.allSettled([this.notifyStatusChanged(),this.notifyFileTreeChanged()])}async notifyAfterCuratedWrite(e){let t=[this.notifyStatusChanged(),this.notifyCuratedIndexChanged()];e&&t.push(this.notifyCuratedEntryChanged(e)),await Promise.allSettled(t)}async sendUpdate(e){try{await this.mcpServer.server.sendResourceUpdated({uri:e})}catch(t){om.debug(`sendResourceUpdated failed`,{uri:e,error:String(t)})}}};const Z=F(`server`);async function cm(n){Z.info(`Initializing AI Kit components`);let r=n.store.backend,i=n.store.path,a=null;if(r===`sqlite-vec`){let e=N(i,`aikit.db`);D(i)||O(i,{recursive:!0}),a=await $n(e),Z.info(`SQLite adapter ready`,{type:a.type,vectorCapable:a.vectorCapable,dbPath:e}),a.vectorCapable||Z.warn(`┌──────────────────────────────────────────────────────────────────┐
|
|
2902
2903
|
│ ⚠ SQLite vector extension unavailable — DEGRADED MODE │
|
|
2903
2904
|
│ Vector search is disabled. Hybrid search returns FTS only. │
|
|
2904
2905
|
│ To enable: install/rebuild better-sqlite3 (native module). │
|
|
2905
|
-
└──────────────────────────────────────────────────────────────────┘`);let t=N(i,`lance`);D(t)&&Z.info(`Old LanceDB data found at ${t} — ignored. Safe to delete after verifying sqlite-vec works.`)}let o;if(a)o=a;else{let e=N(i,`aikit-state.db`);D(i)||O(i,{recursive:!0}),o=await $n(e),nr(o,Qn),Z.info(`State store adapter ready`,{type:o.type,dbPath:e})}let[s,c,l,u]=await Promise.all([(async()=>{if(n.embedding.childProcess!==!1){let e=new mr({model:n.embedding.model,dimensions:n.embedding.dimensions,interOpNumThreads:n.embedding.interOpNumThreads,intraOpNumThreads:n.embedding.intraOpNumThreads,idleTimeoutMs:n.embedding.idleTimeoutMs});return await e.initialize(),Z.info(`Embedder loaded (child process)`,{modelId:e.modelId,dimensions:e.dimensions}),e}let{OnnxEmbedder:e}=await import(`../../embeddings/dist/index.js`),t=new e({model:n.embedding.model,dimensions:n.embedding.dimensions,interOpNumThreads:n.embedding.interOpNumThreads,intraOpNumThreads:n.embedding.intraOpNumThreads});return await t.initialize(),Z.info(`Embedder loaded (in-process)`,{modelId:t.modelId,dimensions:t.dimensions}),t})(),(async()=>{let e=await tr({backend:r,path:i,adapter:a??void 0,embeddingDim:n.embedding.dimensions});return await e.initialize(),Z.info(`Store initialized`,{backend:r}),e})(),(async()=>{let e=a?new Zn({adapter:a}):new Zn({path:i});return await e.initialize(),Z.info(`Graph store initialized`,{shared:!!a}),e})(),(async()=>{let e=await Vn();if(e){let e=zn.get();Z.info(`WASM tree-sitter enabled`,{grammars:e.grammarCount,dir:e.wasmDir})}else{let e=zn.get();Z.warn(`WASM tree-sitter not available; analyzers will use regex fallback`,{reason:e.reason,os:e.os,arch:e.arch,healAttempted:e.healAttempted,healSuccess:e.healSuccess,healError:e.healError,pathsChecked:e.pathsChecked.map(e=>`${e.path} (${e.exists?`found`:`missing`})`)})}return e})()]),d=new gr(s,c),f=er(o),p=new hr(n.store.path);p.load(),d.setHashCache(p);let m=n.curated.path,h=new e(m);await h.initialize();let g=new t(m,c,s,h);d.setGraphStore(l);let _=Ds(n.er),v=_?new Gn(n.curated.path):void 0;v&&Z.info(`Policy store initialized`,{ruleCount:v.getRules().length});let y=_?new Wn:void 0,b=P(n.sources[0]?.path??process.cwd(),ce.aiContext),x=D(b),S=n.onboardDir?D(n.onboardDir):!1,C=x||S,w,T=x?b:n.onboardDir;if(C&&T)try{w=te(T).mtime.toISOString()}catch{}return Z.info(`Onboard state detected`,{onboardComplete:C,onboardTimestamp:w,aiKbExists:x,onboardDirExists:S}),{embedder:s,store:c,stateStore:f,closeStateStore:o===a?void 0:async()=>o.close(),indexer:d,curated:g,graphStore:l,fileCache:new be,bridge:_,policyStore:v,evolutionCollector:y,onboardComplete:C,onboardTimestamp:w}}function
|
|
2906
|
-
`)}const
|
|
2907
|
-
`),`utf8`),Q.info(`Auto-heal: created ESM shim for @huggingface/transformers (.mjs wrapper → .cjs)`,{path:t}))}catch(e){Q.warn(`Auto-heal: failed to create ESM shim`,{error:e instanceof Error?e.message:String(e),path:t})}}}if(n.includes(`embedding`)||n.includes(`onnx`)||n.includes(`protobuf`)||n.includes(`model`)){let t=e.embedding?.model??ue.model,n=N(Sn(),`.cache`,`huggingface`,`transformers-js`,t);try{await r(n,{recursive:!0,force:!0}),Q.info(`Auto-heal: cleared embedding model cache`,{path:n})}catch{}}if(n.includes(`lance`)||n.includes(`database`)||n.includes(`store`)){let t=N(e.store.path,`lance`);try{await r(t,{recursive:!0,force:!0}),Q.info(`Auto-heal: cleared LanceDB store`,{path:t})}catch{}}if(n.includes(`sqlite`)||n.includes(`database disk image`)||n.includes(`graph`)){let t=N(e.store.path,`graph.db`);try{await r(t,{force:!0}),Q.info(`Auto-heal: cleared graph database`,{path:t})}catch{}let n=N(e.store.path,`aikit.db`);try{await r(n,{force:!0}),await r(`${n}-wal`,{force:!0}).catch(()=>{}),await r(`${n}-shm`,{force:!0}).catch(()=>{}),Q.info(`Auto-heal: cleared corrupted aikit database`,{path:n})}catch{}}if(n.includes(`cannot find module`)&&!n.includes(`huggingface`)&&!n.includes(`.cache`)){let{fileURLToPath:e}=await import(`node:url`),t=e(import.meta.url);if(t.includes(`_npx`)||t.includes(`npm-cache`)){let e=
|
|
2906
|
+
└──────────────────────────────────────────────────────────────────┘`);let t=N(i,`lance`);D(t)&&Z.info(`Old LanceDB data found at ${t} — ignored. Safe to delete after verifying sqlite-vec works.`)}let o;if(a)o=a;else{let e=N(i,`aikit-state.db`);D(i)||O(i,{recursive:!0}),o=await $n(e),nr(o,Qn),Z.info(`State store adapter ready`,{type:o.type,dbPath:e})}let[s,c,l,u]=await Promise.all([(async()=>{if(n.embedding.childProcess!==!1){let e=new mr({model:n.embedding.model,dimensions:n.embedding.dimensions,interOpNumThreads:n.embedding.interOpNumThreads,intraOpNumThreads:n.embedding.intraOpNumThreads,idleTimeoutMs:n.embedding.idleTimeoutMs});return await e.initialize(),Z.info(`Embedder loaded (child process)`,{modelId:e.modelId,dimensions:e.dimensions}),e}let{OnnxEmbedder:e}=await import(`../../embeddings/dist/index.js`),t=new e({model:n.embedding.model,dimensions:n.embedding.dimensions,interOpNumThreads:n.embedding.interOpNumThreads,intraOpNumThreads:n.embedding.intraOpNumThreads});return await t.initialize(),Z.info(`Embedder loaded (in-process)`,{modelId:t.modelId,dimensions:t.dimensions}),t})(),(async()=>{let e=await tr({backend:r,path:i,adapter:a??void 0,embeddingDim:n.embedding.dimensions});return await e.initialize(),Z.info(`Store initialized`,{backend:r}),e})(),(async()=>{let e=a?new Zn({adapter:a}):new Zn({path:i});return await e.initialize(),Z.info(`Graph store initialized`,{shared:!!a}),e})(),(async()=>{let e=await Vn();if(e){let e=zn.get();Z.info(`WASM tree-sitter enabled`,{grammars:e.grammarCount,dir:e.wasmDir})}else{let e=zn.get();Z.warn(`WASM tree-sitter not available; analyzers will use regex fallback`,{reason:e.reason,os:e.os,arch:e.arch,healAttempted:e.healAttempted,healSuccess:e.healSuccess,healError:e.healError,pathsChecked:e.pathsChecked.map(e=>`${e.path} (${e.exists?`found`:`missing`})`)})}return e})()]),d=new gr(s,c),f=er(o),p=new hr(n.store.path);p.load(),d.setHashCache(p);let m=n.curated.path,h=new e(m);await h.initialize();let g=new t(m,c,s,h);d.setGraphStore(l);let _=Ds(n.er),v=_?new Gn(n.curated.path):void 0;v&&Z.info(`Policy store initialized`,{ruleCount:v.getRules().length});let y=_?new Wn:void 0,b=P(n.sources[0]?.path??process.cwd(),ce.aiContext),x=D(b),S=n.onboardDir?D(n.onboardDir):!1,C=x||S,w,T=x?b:n.onboardDir;if(C&&T)try{w=te(T).mtime.toISOString()}catch{}return Z.info(`Onboard state detected`,{onboardComplete:C,onboardTimestamp:w,aiKbExists:x,onboardDirExists:S}),{embedder:s,store:c,stateStore:f,closeStateStore:o===a?void 0:async()=>o.close(),indexer:d,curated:g,graphStore:l,fileCache:new be,bridge:_,policyStore:v,evolutionCollector:y,onboardComplete:C,onboardTimestamp:w}}function lm(e,t,n){if(e.serverInstructions)return e.serverInstructions;let r=new Set;for(let e of t){let t=n[e];if(t?.category)for(let e of t.category)r.add(e)}let i=[`This server provides ${t.size} tools across ${r.size} categories: ${[...r].sort().join(`, `)}.`,`TOOL ROUTING:`,`- Understand a file -> file_summary (structure) or compact (extract section)`,`- Find code/symbols -> search (hybrid) or symbol (definition + refs)`,`- Validate changes -> check (typecheck+lint) or test_run (tests)`,`- Read file for editing -> read_file (only for exact lines before edits)`,`FORBIDDEN: DO NOT USE native equivalents when AI Kit provides same:`,`- grep/find -> search or find tool`,`- cat/read_file (for understanding) -> file_summary or compact`,`- terminal tsc/lint -> check tool`,`- terminal test -> test_run tool`];return e.readOnly&&i.push(`Server is in read-only mode. Mutating operations are disabled.`),e.features?.length&&i.push(`Active feature groups: ${e.features.join(`, `)}.`),i.join(`
|
|
2907
|
+
`)}const um=F(`background-task`);var dm=class{queue=[];running=null;get isRunning(){return this.running!==null}get currentTask(){return this.running}get pendingCount(){return this.queue.length}schedule(e){return new Promise((t,n)=>{this.queue.push({...e,resolve:t,reject:n}),this.running||this.processQueue()})}async processQueue(){for(;this.queue.length>0;){let e=this.queue.shift();if(!e)break;this.running=e.name,um.info(`Background task started`,{task:e.name,pending:this.queue.length});let t=Date.now();try{await e.fn();let n=Date.now()-t;um.info(`Background task completed`,{task:e.name,durationMs:n}),e.resolve()}catch(n){let r=Date.now()-t;um.error(`Background task failed`,{task:e.name,durationMs:r,err:n}),e.reject(n instanceof Error?n:Error(String(n)))}}this.running=null}};const fm=F(`idle-timer`);var pm=class{timer=null;cleanupFns=[];idleMs;disposed=!1;sessionActive=!1;_busy=!1;constructor(e){this.idleMs=e?.idleMs??3e5}setBusy(e){this._busy=e,e?this.cancel():this.touch()}onIdle(e){this.cleanupFns.push(e)}markSessionActive(){this.sessionActive=!0}touch(){this.disposed||this._busy||(this.cancel(),this.timer=setTimeout(()=>{this.runCleanup()},this.idleMs),this.timer.unref&&this.timer.unref())}cancel(){this.timer&&=(clearTimeout(this.timer),null)}dispose(){this.cancel(),this.cleanupFns.length=0,this.disposed=!0}async runCleanup(){if(!this.sessionActive){fm.info(`Idle timeout reached with no active session — skipping cleanup (waiting for first tool call)`);return}if(this._busy){fm.info(`Skipping idle cleanup — background work in progress`);return}fm.info(`Idle for ${this.idleMs/1e3}s — running cleanup`);let e=await Promise.allSettled(this.cleanupFns.map(e=>e()));for(let t of e)t.status===`rejected`&&fm.warn(`Idle cleanup callback failed`,{error:String(t.reason)})}};const mm=F(`memory-monitor`);var hm=class{timer=null;warningBytes;criticalBytes;intervalMs;pressureFns=[];memoryPressureFns=[];lastLevel=`normal`;constructor(e){this.warningBytes=e?.warningBytes??4294967296,this.criticalBytes=e?.criticalBytes??8589934592,this.intervalMs=e?.intervalMs??6e4}onPressure(e){this.pressureFns.push(e)}registerMemoryPressureCallback(e){this.memoryPressureFns.push(e)}start(){this.timer||(this.timer=setInterval(()=>this.check(),this.intervalMs),this.timer.unref&&this.timer.unref(),mm.info(`Memory monitor started`,{warningMB:Math.round(this.warningBytes/1024/1024),criticalMB:Math.round(this.criticalBytes/1024/1024),intervalSec:Math.round(this.intervalMs/1e3)}))}stop(){this.timer&&=(clearInterval(this.timer),null)}getRssBytes(){return process.memoryUsage.rss()}check(){let e=this.getRssBytes(),t=`normal`;if(e>=this.criticalBytes?t=`critical`:e>=this.warningBytes&&(t=`warning`),t!==this.lastLevel||t===`critical`){let n=Math.round(e/1024/1024);t===`critical`?mm.warn(`Memory CRITICAL: ${n}MB RSS — consider restarting the server`):t===`warning`?mm.warn(`Memory WARNING: ${n}MB RSS`):this.lastLevel!==`normal`&&mm.info(`Memory returned to normal: ${n}MB RSS`),this.lastLevel=t}if(t!==`normal`)for(let n of this.pressureFns)try{n(t,e)}catch{}if(t===`critical`)for(let e of this.memoryPressureFns)try{let t=e();t&&typeof t.catch==`function`&&t.catch(()=>{})}catch{}return t===`critical`&&typeof globalThis.gc==`function`&&globalThis.gc(),t}};const gm=F(`tool-timeout`),_m=new Set([`onboard`,`reindex`,`produce_knowledge`,`analyze`,`codemod`,`audit`]);var vm=class extends Error{toolName;timeoutMs;constructor(e,t){super(`Tool "${e}" timed out after ${t}ms`),this.toolName=e,this.timeoutMs=t,this.name=`ToolTimeoutError`}};function ym(e){return _m.has(e)?6e5:12e4}function bm(e,t,n){return new Promise((r,i)=>{let a=!1,o=setTimeout(()=>{if(!a){a=!0;let e=new vm(n,t);gm.warn(e.message),i(e)}},t);o.unref&&o.unref(),e().then(e=>{a||(a=!0,clearTimeout(o),r(e))},e=>{a||(a=!0,clearTimeout(o),i(e))})})}const Q=F(`server`),xm=new Set([`status`,`list_tools`,`describe_tool`,`config`,`env`]);function Sm(e,t=28){let n=e.replace(/\s+/g,` `).trim();return n.length<=t?n:`${n.slice(0,t-3)}...`}function Cm(e){let t=[`query`,`path`,`task`,`name`,`start`,`symbol`,`file`,`pattern`],n=[];for(let r of t){let t=e[r];typeof t==`string`&&t.length>0&&t.length<200&&n.push(t)}return n.join(` `).slice(0,200)}async function wm(e,t,n){let r=[];try{t.statePath&&Ge(e.stateStore,{stateDir:t.statePath});let i=e.stateStore.stashList().map(e=>e.key);if(i.length>0){let e=n.toLowerCase().split(/\s+/).filter(e=>e.length>2);if(e.length===0)r.push(`stash: ${i.length} entries available`);else{let t=i.filter(t=>e.some(e=>t.toLowerCase().includes(e))).slice(0,3);t.length>0?r.push(`stash: ${t.map(e=>`"${Sm(e)}"`).join(`, `)}${i.length>t.length?` (${i.length} total)`:``}`):r.push(`stash: ${i.length} entries available`)}}}catch{}try{if(n){let t=await Promise.race([e.store.ftsSearch(n,{limit:3}),new Promise(e=>setTimeout(()=>e(null),50))]);if(Array.isArray(t)&&t.length>0){let e=t.filter(e=>e&&typeof e==`object`&&`record`in e&&(e.record.origin===`produced`||e.record.origin===`curated`));if(e.length>0){let t=e.slice(0,2).map(e=>{let t=e.record;return`"${Sm(t.headingPath||t.sourcePath||`knowledge`)}"`});r.push(`knowledge: ${t.join(`, `)}`)}}}}catch{}return r.length===0?null:`\n---\nContext available: ${r.join(` | `)}\nPull with: stash({action:'get', key:'...'}) or search({query:'...', origin:'produced'})\n---`}function Tm(e,t,n){let r=3;for(let[i,a]of Object.entries(e)){let e=a.handler;a.handler=async(...a)=>{let o=await e(...a);if(!o||typeof o!=`object`||r<=0||o.isError||xm.has(i))return o;try{r--;let e=a[0],i=await wm(t,n,Cm(e&&typeof e==`object`?e:{}));i&&(o.content=Array.isArray(o.content)?o.content:[],o.content.push({type:`text`,text:i}))}catch{}return o}}}function Em(e){let t=e.toLowerCase();return[`protobuf`,`invalid model`,`invalid onnx`,`unexpected end`,`unexpected token`,`failed to load`,`failed to initialize embedding`,`checksum`,`corrupt`,`malformed`,`could not load`,`onnx`,`database disk image is malformed`,`file is not a database`,`lance`,`cannot find module`,`module not found`].some(e=>t.includes(e))}function Dm(e){let t=e.indexOf(`node_modules`);return t>0?e.substring(0,t-1):null}async function Om(e,t){let n=t.toLowerCase(),r;try{({rm:r}=await import(`node:fs/promises`))}catch{return}if(n.includes(`transformers.node.mjs`)&&n.includes(`cannot find module`)){let e=t.match(/Cannot find module '([^']+transformers\.node\.mjs)'/);if(e){let t=e[1],n=t.replace(/\.mjs$/,`.cjs`);try{let{existsSync:e,writeFileSync:r}=await import(`node:fs`);e(n)&&!e(t)&&(r(t,[`// Auto-generated ESM shim — published package missing this file`,`import { createRequire } from 'node:module';`,`const require = createRequire(import.meta.url);`,`const mod = require('./transformers.node.cjs');`,`export default mod;`,``].join(`
|
|
2908
|
+
`),`utf8`),Q.info(`Auto-heal: created ESM shim for @huggingface/transformers (.mjs wrapper → .cjs)`,{path:t}))}catch(e){Q.warn(`Auto-heal: failed to create ESM shim`,{error:e instanceof Error?e.message:String(e),path:t})}}}if(n.includes(`embedding`)||n.includes(`onnx`)||n.includes(`protobuf`)||n.includes(`model`)){let t=e.embedding?.model??ue.model,n=N(Sn(),`.cache`,`huggingface`,`transformers-js`,t);try{await r(n,{recursive:!0,force:!0}),Q.info(`Auto-heal: cleared embedding model cache`,{path:n})}catch{}}if(n.includes(`lance`)||n.includes(`database`)||n.includes(`store`)){let t=N(e.store.path,`lance`);try{await r(t,{recursive:!0,force:!0}),Q.info(`Auto-heal: cleared LanceDB store`,{path:t})}catch{}}if(n.includes(`sqlite`)||n.includes(`database disk image`)||n.includes(`graph`)){let t=N(e.store.path,`graph.db`);try{await r(t,{force:!0}),Q.info(`Auto-heal: cleared graph database`,{path:t})}catch{}let n=N(e.store.path,`aikit.db`);try{await r(n,{force:!0}),await r(`${n}-wal`,{force:!0}).catch(()=>{}),await r(`${n}-shm`,{force:!0}).catch(()=>{}),Q.info(`Auto-heal: cleared corrupted aikit database`,{path:n})}catch{}}if(n.includes(`cannot find module`)&&!n.includes(`huggingface`)&&!n.includes(`.cache`)){let{fileURLToPath:e}=await import(`node:url`),t=e(import.meta.url);if(t.includes(`_npx`)||t.includes(`npm-cache`)){let e=Dm(t);if(e)try{let{execSync:t}=await import(`node:child_process`);t(`npm install --prefer-offline --no-audit --no-fund`,{cwd:e,stdio:`ignore`,timeout:6e4}),Q.info(`Auto-heal: re-ran npm install to restore missing module`,{path:e})}catch{Q.warn(`Auto-heal: npm install failed during module restoration`,{hint:`Run: npm cache clean --force && npx -y @vpxa/aikit serve`})}}}}function km(e,t){let n=lo(e,La,H,Na(e)),r=lm(e,n,H),i=new Cn({name:e.serverName??`aikit`,version:b()},{capabilities:{logging:{},completions:{},prompts:{}},instructions:r}),a=`initializing`,o=``,s=!1,c=null,l=null,u=null;function d(e){if(!e||typeof e!=`object`)return[];let t=e,n=[];for(let e of[`path`,`file`,`source_path`,`sourcePath`,`filePath`]){let r=t[e];typeof r==`string`&&r&&n.push(r)}for(let e of[`changed_files`,`paths`,`files`]){let r=t[e];if(Array.isArray(r))for(let e of r){if(typeof e==`string`){n.push(e);continue}e&&typeof e==`object`&&typeof e.path==`string`&&n.push(e.path)}}if(Array.isArray(t.sources))for(let e of t.sources)e&&typeof e==`object`&&typeof e.path==`string`&&n.push(e.path);return n}let f=()=>a===`failed`?[`❌ AI Kit initialization failed — this tool is unavailable.`,``,o?`Error: ${o}`:``,``,`**${Ia.size} tools are still available** and fully functional:`,`check, eval, test_run, git_context, health, measure, web_fetch, web_search,`,`flow, regex_test, encode,`,`stash, checkpoint, lane, process, time, env, and more.`,``,`To fix embedding errors, try deleting the cached model:`,` rm -rf ~/.cache/huggingface/transformers-js/mixedbread-ai/`,`Then restart the server to re-download a fresh copy.`,``,`Try restarting the MCP server to retry initialization.`].filter(Boolean).join(`
|
|
2908
2909
|
`):[`AI Kit is still initializing (loading embeddings model & store).`,``,`**${Ia.size} tools are already available** while initialization completes — including:`,`check, eval, test_run, git_context, health, measure, web_fetch, web_search,`,`flow, regex_test, encode,`,`stash, checkpoint, lane, process, time, env, and more.`,``,`This tool requires the AI Kit index. Please retry in a few seconds,`,`or use one of the available tools above in the meantime.`].join(`
|
|
2909
|
-
`);yr(i);let p=new oa;p.use(za(),{order:1,name:`structured-content-guard`}),Ja(i,p,e.toolPrefix??``);let m=i.sendToolListChanged.bind(i);i.sendToolListChanged=()=>{};let h=[];for(let e of La){if(!n.has(e))continue;let t=U(e),r=i.registerTool(e,{title:t.title,description:`${t.title} — initializing, available shortly`,inputSchema:{},annotations:t.annotations},async()=>({content:[{type:`text`,text:f()}]}));Ia.has(e)?r.remove():h.push(r)}
|
|
2910
|
+
`);yr(i);let p=new oa;p.use(za(),{order:1,name:`structured-content-guard`}),Ja(i,p,e.toolPrefix??``);let m=i.sendToolListChanged.bind(i);i.sendToolListChanged=()=>{};let h=[];for(let e of La){if(!n.has(e))continue;let t=U(e),r=i.registerTool(e,{title:t.title,description:`${t.title} — initializing, available shortly`,inputSchema:{},annotations:t.annotations},async()=>({content:[{type:`text`,text:f()}]}));Ia.has(e)?r.remove():h.push(r)}am(i,e,n),i.sendToolListChanged=m;let g=i.registerResource(`aikit-status`,`aikit://status`,{description:`AI Kit status (initializing...)`,mimeType:`text/plain`},async()=>({contents:[{uri:`aikit://status`,text:`AI Kit is initializing...`,mimeType:`text/plain`}]})),_=i.registerPrompt(`_init`,{description:`Initializing AI Kit…`,argsSchema:{_dummy:On(L.string(),()=>[])}},async()=>({messages:[]})),v,y,x=new Promise((e,t)=>{v=e,y=t}),S,C=new Promise(e=>{S=e}),w=()=>S?.(),T=(async()=>{await C;let n=[];try{let{createRequire:e}=await import(`node:module`),{readFileSync:t}=await import(`node:fs`),{fileURLToPath:r}=await import(`node:url`),{resolve:i,dirname:a}=await import(`node:path`),o=e(import.meta.url),s=i(a(r(import.meta.url)),`..`,`package.json`),c=JSON.parse(t(s,`utf8`)),l=Object.keys(c.dependencies??{}),u=[`@mixmark-io/domino`],d=[...l,...u.filter(e=>!l.includes(e))];for(let e of d)try{o.resolve(e)}catch{n.push(e)}if(n.length>0){Q.warn(`${n.length} dependencies not resolvable — attempting auto-repair`,{missing:n});let e=r(import.meta.url);if(e.includes(`_npx`)||e.includes(`npm-cache`))try{let{execSync:t}=await import(`node:child_process`),r=Dm(e);if(r){Q.info(`Auto-heal: running npm install in npx cache to restore missing deps`,{path:r,missing:n}),t(`npm install --prefer-offline --no-audit --no-fund`,{cwd:r,stdio:`ignore`,timeout:6e4});let e=[];for(let t of n)try{o.resolve(t)}catch{e.push(t)}e.length===0?(Q.info(`Auto-heal: all missing dependencies restored successfully`),n=[]):(Q.warn(`Auto-heal: some deps still missing after npm install`,{stillMissing:e,hint:`Run: npm cache clean --force && npx -y @vpxa/aikit serve`}),n=e)}}catch(e){Q.warn(`Auto-heal: npm install failed — server may operate in degraded mode`,{error:e instanceof Error?e.message:String(e),hint:`Run: npm cache clean --force && npx -y @vpxa/aikit serve`})}else Q.warn(`Missing dependencies detected in non-npx environment`,{missing:n,hint:`Run: npm install (or pnpm install) to restore missing packages`})}}catch{}let r;try{r=await cm(e)}catch(t){let n=t instanceof Error?t.message:String(t);if(Em(n)){Q.warn(`AI Kit initialization failed with recoverable error — attempting auto-heal retry`,{error:n}),await Om(e,n);try{r=await cm(e),Q.info(`AI Kit auto-heal successful — initialization recovered after retry`)}catch(e){a=`failed`,o=e instanceof Error?e.message:String(e),Q.error(`AI Kit initialization failed after auto-heal attempt — server continuing with zero-dep tools only`,{error:o,originalError:n}),y?.(e instanceof Error?e:Error(o));return}}else{a=`failed`,o=n,Q.error(`AI Kit initialization failed — server continuing with zero-dep tools only`,{error:o}),y?.(t instanceof Error?t:Error(o));return}}let f=i.sendToolListChanged.bind(i);i.sendToolListChanged=()=>{};let p=i.sendPromptListChanged.bind(i);i.sendPromptListChanged=()=>{};let m=i.sendResourceListChanged.bind(i);i.sendResourceListChanged=()=>{};for(let e of h)e.remove();g.remove(),_.remove();let b=i._registeredTools??{};for(let e of Ia)b[e]?.remove();let x=new sm(i),S=kc(i);im(i,r,e,_r(i),x,S,t,t===`smart`?(()=>{let e=u;return e?.getState?e.getState():null}):null,t===`smart`?()=>{let e=u;return e?{prioritize:e.prioritize.bind(e)}:null}:null),Ar(i,{curated:r.curated,store:r.store,graphStore:r.graphStore,stateStore:r.stateStore},t),i.sendToolListChanged=f,i.sendPromptListChanged=p,i.sendResourceListChanged=m,Promise.resolve(i.sendToolListChanged()).catch(()=>{}),Promise.resolve(i.sendPromptListChanged()).catch(()=>{}),Promise.resolve(i.sendResourceListChanged()).catch(()=>{});let w=i._registeredTools??{};for(let[e,t]of Object.entries(w)){if(Pa.has(e))continue;let n=t.handler;t.handler=async(...i)=>{if(!r.indexer.isIndexing)return n(...i);let a=s?`re-indexing`:`running initial index`,o=new Promise(n=>setTimeout(()=>n({content:[{type:`text`,text:`⏳ AI Kit is ${a}. The tool "${e}" timed out waiting for index data (${Fa/1e3}s).\n\nThe existing index may be temporarily locked. Please retry shortly — indexing will complete automatically.`}],...t.config?.outputSchema?{structuredContent:Wa(t.config.outputSchema)}:{}}),Fa));return Promise.race([n(...i),o])}}for(let[e,t]of Object.entries(w)){let n=t.handler,r=ym(e);t.handler=async(...i)=>{try{return await bm(()=>n(...i),r,e)}catch(n){if(n instanceof vm)return{content:[{type:`text`,text:`⏳ Tool "${e}" timed out after ${r/1e3}s. This may indicate a long-running operation. Please retry or break the task into smaller steps.`}],...t.config?.outputSchema?{structuredContent:Wa(t.config.outputSchema)}:{}};throw n}}}let T=Object.keys(w).length;T<La.length&&Q.warn(`ALL_TOOL_NAMES count mismatch`,{expectedToolCount:La.length,registeredToolCount:T}),Q.info(`MCP server configured`,{toolCount:La.length,resourceCount:4});let E=new hm;E.onPressure((e,t)=>{e===`warning`&&Cr(),e===`critical`&&(Q.warn(`Memory pressure critical — consider restarting`,{rssMB:Math.round(t/1024/1024)}),Cr())}),E.registerMemoryPressureCallback(()=>r.embedder.shutdown?.()),E.start();let O=new pm;l=O,O.onIdle(async()=>{if(D.isRunning||r.indexer.isIndexing){Q.info(`Idle cleanup deferred — background tasks still running`),O.touch();return}Q.info(`Idle cleanup: releasing cached memory (connections stay open)`);try{r.store.releaseMemory?.(),r.graphStore.releaseMemory?.()}catch{}}),O.touch();let k=!1;for(let e of Object.values(w)){let t=e.handler;e.handler=async(...e)=>{if(k||(k=!0,O.markSessionActive()),O.touch(),u){let t=d(e[0]);t.length>0&&u.prioritize(...t)}return t(...e)}}Tm(w,r,{statePath:e.stateDir??``}),process.stdin.on(`end`,()=>(Q.info(`stdin closed — MCP client disconnected. Shutting down.`),process.exit(0))),process.stdin.on(`error`,()=>(Q.info(`stdin error — MCP client disconnected. Shutting down.`),process.exit(0))),c=r,v?.(r)})(),E=async()=>{let t;try{t=await x}catch{Q.warn(`Skipping initial index — AI Kit initialization failed`);return}l?.setBusy(!0);try{let n=e.sources.map(e=>e.path).join(`, `);Q.info(`Running initial index`,{sourcePaths:n});let r=await t.indexer.index(e,e=>{e.phase===`crawling`||e.phase===`done`||(e.phase===`chunking`&&e.currentFile&&Q.debug(`Indexing file`,{current:e.filesProcessed+1,total:e.filesTotal,file:e.currentFile}),e.phase===`cleanup`&&Q.debug(`Index cleanup`,{staleEntries:e.filesTotal-e.filesProcessed}))});s=!0,Q.info(`Initial index complete`,{filesProcessed:r.filesProcessed,filesSkipped:r.filesSkipped,chunksCreated:r.chunksCreated,durationMs:r.durationMs});try{await t.store.createFtsIndex()}catch(e){Q.warn(`FTS index creation failed`,I(e))}try{let e=await t.curated.reindexAll();Q.info(`Curated re-index complete`,{indexed:e.indexed})}catch(e){Q.error(`Curated re-index failed`,I(e))}}catch(e){Q.error(`Initial index failed; will retry on aikit_reindex`,I(e))}finally{l?.setBusy(!1)}},D=new dm,O=()=>D.schedule({name:`initial-index`,fn:E}),k=process.ppid,A=setInterval(()=>{try{process.kill(k,0)}catch{Q.info(`Parent process died; shutting down`,{parentPid:k}),clearInterval(A),u?.stop&&u.stop(),import(`../../tools/dist/index.js`).then(({processStopAll:e})=>e()).catch(()=>{}),x.then(async e=>{await Promise.all([e.embedder.shutdown?.().catch(()=>{})??Promise.resolve(),e.graphStore.close().catch(()=>{}),e.closeStateStore?.().catch(()=>{})??Promise.resolve(),e.store.close().catch(()=>{})])}).catch(()=>{}).finally(()=>process.exit(0))}},5e3);return A.unref(),{server:i,startInit:w,ready:T,runInitialIndex:O,get aikit(){return c},scheduler:D,setSmartScheduler(e){u=e}}}const $=F(`server`);function Am(e,t){let n=lo(t,[...La,...ja],H,Na(t)),r=lm(t,n,H),i=new Cn({name:t.serverName??`aikit`,version:b()},{capabilities:{logging:{},completions:{},prompts:{}},instructions:r});return yr(i),im(i,e,t,_r(i),new sm(i),kc(i),void 0,null,null,n),Ar(i,{curated:e.curated,store:e.store,graphStore:e.graphStore,stateStore:e.stateStore},t.indexMode),i}async function jm(e){let t=await cm(e),n=Am(t,e);$.info(`MCP server configured`,{toolCount:La.length,resourceCount:2});let r=async()=>{try{let n=e.sources.map(e=>e.path).join(`, `);$.info(`Running initial index`,{sourcePaths:n});let r=await t.indexer.index(e,e=>{e.phase===`crawling`||e.phase===`done`||(e.phase===`chunking`&&e.currentFile&&$.debug(`Indexing file`,{current:e.filesProcessed+1,total:e.filesTotal,file:e.currentFile}),e.phase===`cleanup`&&$.debug(`Index cleanup`,{staleEntries:e.filesTotal-e.filesProcessed}))});$.info(`Initial index complete`,{filesProcessed:r.filesProcessed,filesSkipped:r.filesSkipped,chunksCreated:r.chunksCreated,durationMs:r.durationMs});try{await t.store.createFtsIndex()}catch(e){$.warn(`FTS index creation failed`,I(e))}try{let e=await t.curated.reindexAll();$.info(`Curated re-index complete`,{indexed:e.indexed})}catch(e){$.error(`Curated re-index failed`,I(e))}}catch(e){$.error(`Initial index failed; will retry on aikit_reindex`,I(e))}},i=async()=>{$.info(`Shutting down`),await Promise.all([t.embedder.shutdown?.().catch(()=>{})??Promise.resolve(),t.graphStore.close().catch(()=>{}),t.closeStateStore?.().catch(()=>{})??Promise.resolve(),t.store.close().catch(()=>{})]),process.exit(0)};process.on(`SIGINT`,i),process.on(`SIGTERM`,i);let a=process.ppid,o=setInterval(()=>{try{process.kill(a,0)}catch{$.info(`Parent process died; shutting down`,{parentPid:a}),clearInterval(o),i()}},5e3);return o.unref(),{server:n,runInitialIndex:r,shutdown:i}}export{La as ALL_TOOL_NAMES,km as createLazyServer,Am as createMcpServer,jm as createServer,cm as initializeAikit,im as registerMcpTools};
|