@vpxa/aikit 0.1.389 → 0.1.390

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.389",
3
+ "version": "0.1.390",
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",
@@ -1,4 +1,4 @@
1
- import{exec as e,execFile as t,execFileSync as n,execSync as r}from"node:child_process";import{copyFileSync as i,existsSync as a,mkdirSync as o,readFileSync as s,readdirSync as c,unlinkSync as l,writeFileSync as u}from"node:fs";import{homedir as d,platform as f,tmpdir as p}from"node:os";import{join as m}from"node:path";import{z as h}from"zod";const g=`0.26.0`,_=`.agent-browser-version`;function ee(e){return typeof e==`string`?e.trim():e instanceof Buffer?e.toString(`utf8`).trim():``}function v(){return m(d(),`.aikit`,`browsers`)}function y(e){return e.browsersPath??process.env.AIKIT_BROWSER_PATH??process.env.AIKIT_BROWSER_BROWSERS_PATH??v()}function b(){try{let e=r(`${f()===`win32`?`where`:`which`} agent-browser`,{encoding:`utf8`,stdio:`pipe`,timeout:3e3}).trim().split(/\r?\n/)[0];if(!e)return null;if(f()===`win32`){if(a(`${e}.cmd`))return`${e}.cmd`;if(a(`${e}.bat`))return`${e}.bat`;if(a(`${e}.exe`))return`${e}.exe`}return a(e)?e:null}catch{return null}}function x(e){return m(e,`agent-browser`,te())}function te(){switch(f()){case`win32`:return`agent-browser.exe`;default:return`agent-browser`}}function ne(e,t){try{u(m(e,_),t,`utf8`)}catch{}}function re(e){try{return s(m(e,_),`utf8`).trim()}catch{return null}}function ie(e){let t=re(e);return t?ae(t,g)>=0:!1}function ae(e,t){let n=e.split(`.`).map(Number),r=t.split(`.`).map(Number);for(let e=0;e<Math.max(n.length,r.length);e++){let t=n[e]||0,i=r[e]||0;if(t!==i)return t-i}return 0}function oe(e){return!!(a(m(e,`chrome`))||a(m(d(),`.cache`,`agent-browser`,`chrome`)))}async function se(t,n){let s=b();if(s)return n?.(`Using globally installed agent-browser`),s;let l=y(t);a(l)||o(l,{recursive:!0});let u=x(l);if(a(u)&&ie(l))return n?.(`Using cached agent-browser at ${u}`),u;n?.(`Downloading agent-browser (first use)...`),await new Promise((t,n)=>{let r=new AbortController,i=setTimeout(()=>r.abort(),12e4),a=e(`npx -y agent-browser@latest install --install-dir "${l}"`,{timeout:12e4,encoding:`utf8`,env:{...process.env,AGENT_BROWSER_CACHE_DIR:l},signal:r.signal},(e,r,a)=>{if(clearTimeout(i),e){let t=ee(a)||e.message||`Unknown agent-browser install failure`;n(Error(`Failed to install agent-browser: ${t}`));return}t()});a.stdin&&a.stdin.destroy()});let d=u;try{let e=r(f()===`win32`?`npx -y -p agent-browser node -e "process.stdout.write(__dirname)"`:`npx -y -p agent-browser which agent-browser 2>/dev/null || true`,{encoding:`utf8`,timeout:15e3,stdio:`pipe`}).trim(),t=f()===`win32`?`agent-browser-win32-x64.exe`:f()===`darwin`?process.arch===`arm64`?`agent-browser-darwin-arm64`:`agent-browser-darwin-x64`:`agent-browser-linux-${process.arch===`arm64`?`arm64`:`x64`}`,s=[];e&&!e.includes(`MODULE_NOT_FOUND`)&&(s.push(e),s.push(m(e,`..`)));try{let e=m(r(`npm config get cache`,{encoding:`utf8`,timeout:5e3,stdio:`pipe`}).trim(),`_npx`);if(a(e)){let n=c(e,{withFileTypes:!0});for(let r of n){if(!r.isDirectory())continue;let n=m(e,r.name,`node_modules`,`agent-browser`);if(a(m(n,`bin`,t))){s.push(n);break}}}}catch{}for(let e of s){let r=m(e,`bin`,t);if(a(r)){let t=m(l,`agent-browser`);a(t)||o(t,{recursive:!0});let s=x(l);i(r,s);let c=m(e,`bin`,`agent-browser.js`);a(c)&&i(c,m(t,`agent-browser.js`)),ne(l,g),d=s,n?.(`Cached agent-browser at ${s}`);break}}}catch{}return n?.(`agent-browser ready`),d}async function ce(e){try{return n(e,[`--version`],{encoding:`utf8`,stdio:`pipe`,timeout:5e3}).trim()}catch{return null}}function le(e){if(b())return!0;let t=y(e);return oe(t)||a(x(t))}const ue=[`ui`,`headless`];function de(e){return ue.includes(e)?e:`headless`}function fe(e){let t=[];return e===`headless`&&t.push(`--headless`),t}function pe(e){return{headless:e===`headless`,args:fe(e)}}var S=class{tabs=new Map;labelToId=new Map;register(e,t,n,r){return this.tabs.set(e,{tabId:e,url:t,title:n??t,label:r,createdAt:new Date}),r&&this.labelToId.set(r,e),e}resolve(e){return this.tabs.has(e)?e:this.labelToId.get(e)||e}getTab(e){let t=this.tabs.get(e);if(!t)throw Error(`Tab not found: ${e}`);return t}updateTabInfo(e,t,n){let r=this.tabs.get(e);r&&this.tabs.set(e,{...r,url:t,title:n})}setSnapshot(e,t){let n=this.tabs.get(e);n&&this.tabs.set(e,{...n,snapshot:t})}getSnapshot(e){return this.tabs.get(e)?.snapshot}async removeTab(e){let t=this.tabs.get(e);t&&(t.label&&this.labelToId.delete(t.label),this.tabs.delete(e))}listTabs(){return[...this.tabs.values()]}listPages(){return this.listTabs().map(e=>({pageId:e.tabId,url:e.url,title:e.title,label:e.label,createdAt:e.createdAt}))}async closeAll(){this.tabs.clear(),this.labelToId.clear()}clear(){this.tabs.clear(),this.labelToId.clear()}get size(){return this.tabs.size}},me=class{tabs=new S;registerPage(e,t,n,r){return this.tabs.register(e,t,n,r)}getPage(e){throw Error(`Direct Playwright Page access no longer supported with agent-browser. Use engine.exec() or engine.tabExec() for browser operations.`)}getPageInfo(e){let t=this.tabs.getTab(e);return{pageId:t.tabId,url:t.url,title:t.title,label:t.label,createdAt:t.createdAt}}resolvePageId(e){return this.tabs.resolve(e)}setSnapshot(e,t){this.tabs.setSnapshot(e,t)}getSnapshot(e){return this.tabs.getSnapshot(e)}updatePageInfo(e,t,n){this.tabs.updateTabInfo(e,t,n)}async removePage(e){await this.tabs.removeTab(e)}listPages(){return this.tabs.listPages()}async closeAll(){await this.tabs.closeAll()}get size(){return this.tabs.size}};const C={defaultMode:`ui`,browsersPath:null,userDataDirRoot:null,idleShutdownMinutes:10,allowInternalSchemes:!1,allowLoopback:!1,evalTimeoutMs:3e4,evalMaxResultBytes:262144,redactPasswordFieldsInScreenshots:!0,engine:`chrome`};var w=class{binaryPath=null;_currentMode=null;_isLaunched=!1;idleTimer=null;tabs=new S;config;constructor(e={}){this.config={...C,...e}}get currentMode(){return this._currentMode}async launch(e,t){let n=de(e??this.config.defaultMode);if(!(this._isLaunched&&this._currentMode===n)){this._isLaunched&&this._currentMode!==n&&await this.close(),this._currentMode=n,this.binaryPath=await se(this.config,t);try{let e=await this.exec(`--version`);t?.(`agent-browser ${e.stdout.trim()}`)}catch(e){throw Error(`agent-browser binary failed: ${e instanceof Error?e.message:String(e)}`)}this._isLaunched=!0,this.resetIdleTimer()}}async exec(e,...t){if(!this.binaryPath)throw Error(`agent-browser not launched. Call launch() first, or use getEngine() singleton.`);let n=this.binaryPath;f()===`win32`&&!n.endsWith(`.cmd`)&&!n.endsWith(`.bat`)&&!n.endsWith(`.exe`)&&a(`${n}.cmd`)&&(n=`${n}.cmd`);let r=[e,...t];if(f()===`win32`&&(n.endsWith(`.cmd`)||n.endsWith(`.bat`))){let e=`"${n}" ${r.map(e=>/[^\w/:@.\-_{}()/\\]/.test(e)?`"${e.replace(/"/g,`""`)}"`:e).join(` `)}`;return await this.execViaShell(e)}return await this.execViaExecFile(n,r)}execViaExecFile(e,n){return new Promise((r,i)=>{t(e,n,{timeout:this.config.evalTimeoutMs,windowsHide:!0},(t,a,o)=>{if(t){let s=t;if(s.code===`ENOENT`){i(Error(`agent-browser binary not found at ${this.binaryPath}`));return}if(s.killed||s.signal){i(Error(`agent-browser command timed out after ${this.config.evalTimeoutMs}ms: ${e} ${n.join(` `)}`));return}r({stdout:a??``,stderr:o??``,exitCode:typeof s.code==`number`?s.code:1});return}r({stdout:a??``,stderr:o??``,exitCode:0})}).stdin?.end()})}execViaShell(t){return new Promise((n,r)=>{e(t,{timeout:this.config.evalTimeoutMs,windowsHide:!0},(e,i,a)=>{if(e){let o=e;if(o.code===`ENOENT`){r(Error(`agent-browser binary not found at ${this.binaryPath}`));return}if(o.killed||o.signal){r(Error(`agent-browser command timed out after ${this.config.evalTimeoutMs}ms: ${t}`));return}n({stdout:i??``,stderr:a??``,exitCode:typeof o.code==`number`?o.code:1});return}n({stdout:i??``,stderr:a??``,exitCode:0})})})}async tabExec(e,t,...n){return this.exec(`tab`,e,t,...n)}async open(e,t,n){await this.launch(t);let r=this._currentMode===`ui`?[`open`,e,`--headed`]:[`open`,e],i=await this.exec(...r);if(i.exitCode!==0)throw Error(`agent-browser failed to open URL (exit ${i.exitCode}): ${i.stderr||i.stdout||`Unknown error`}`);return this.tabs.register(`t0`,e,i.stdout.trim(),n),this.resetIdleTimer(),`t0`}async screenshot(e,t){let n=t?.format??`png`,r=n===`jpeg`?`image/jpeg`:`image/png`,i=n===`jpeg`?`jpg`:`png`,a=m(t?.screenshotDir??p(),`aikit-screenshot-${Date.now()}.${i}`),o=[a];t?.fullPage&&o.push(`--full`),t?.screenshotDir&&o.push(`--screenshot-dir`,t.screenshotDir),t?.format===`jpeg`&&o.push(`--screenshot-format`,`jpeg`),t?.quality&&o.push(`--screenshot-quality`,String(t.quality)),t?.annotate&&o.push(`--annotate`),await this.exec(`screenshot`,...o);let c=s(a),u=c.toString(`base64`);try{l(a)}catch{}return this.resetIdleTimer(),{base64:u,mimeType:r,bytes:c.length}}async readSnapshot(e,t=!1){let n=t?[`-c`,`--json`]:[`-i`,`--json`],r=await this.tabExec(e,`snapshot`,...n);return this.resetIdleTimer(),r.stdout}async navigate(e,t){let n=await this.tabExec(e,`goto`,t);return this.resetIdleTimer(),n}async close(){if(this.stopIdleTimer(),this._isLaunched){try{await this.exec(`close`).catch(()=>{})}catch{}this.tabs.clear(),this._isLaunched=!1,this._currentMode=null}}isLaunched(){return this._isLaunched}getConfig(){return this.config}getBinaryPath(){return this.binaryPath}resolvePageId(e){return this.tabs.resolve(e)}resetIdleTimer(){this.stopIdleTimer();let e=setTimeout(()=>{this.close()},this.config.idleShutdownMinutes*6e4);this._currentMode!==`ui`&&e.unref?.(),this.idleTimer=e}stopIdleTimer(){this.idleTimer&&=(clearTimeout(this.idleTimer),null)}};let T=null;function E(e){return T||=new w(e),T}async function he(){T&&=(await T.close(),null)}function D(e,t){try{let n=new URL(e),r=n.hostname.toLowerCase(),i=n.protocol.toLowerCase();return[`file:`,`chrome:`,`chrome-extension:`,`data:`,`javascript:`].includes(i)?t?.allowInternalSchemes?{allowed:!0}:{allowed:!1,reason:`Scheme '${i}' is blocked for security`}:[`169.254.169.254`,`metadata.google.internal`,`metadata.instance`].includes(r)?{allowed:!1,reason:`Cloud metadata endpoint '${r}' is blocked`}:n.hostname===`localhost`||r===`127.0.0.1`||r===`::1`||r.startsWith(`10.`)||r.startsWith(`172.`)||r.startsWith(`192.168.`)?t?.allowLoopback?{allowed:!0}:{allowed:!1,reason:`Internal host '${r}' requires allowLoopback=true`}:{allowed:!0}}catch{return{allowed:!1,reason:`Invalid URL`}}}function O(e,t){return Buffer.byteLength(e,`utf8`)<=t?{valid:!0,result:e,truncated:!1}:{valid:!0,result:`${Buffer.from(e).subarray(0,t).toString(`utf8`)}\n... [truncated]`,truncated:!0,reason:`Result exceeded ${t} bytes, truncated to ${t} bytes`}}const ge=[`ui`,`headless`];function _e(e){return typeof e==`object`&&e?e:null}function k(e){return typeof e==`string`&&e.length>0?e:void 0}function A(e){return typeof e==`boolean`?e:void 0}function j(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}function M(e){return typeof e==`string`&&ge.includes(e)?e:void 0}function N(e){let t=process.env[e];if(!t)return;let n=Number(t);return Number.isFinite(n)?n:void 0}function ve(e){let t=_e(e.browser)??{};return{...C,defaultMode:M(process.env.AIKIT_BROWSER_DEFAULT_MODE)??M(t.defaultMode)??C.defaultMode,browsersPath:k(process.env.AIKIT_BROWSER_PATH)??k(process.env.AIKIT_BROWSER_BROWSERS_PATH)??k(t.browsersPath)??C.browsersPath,userDataDirRoot:k(t.userDataDirRoot)??C.userDataDirRoot,idleShutdownMinutes:N(`AIKIT_BROWSER_IDLE_MINUTES`)??j(t.idleShutdownMinutes)??C.idleShutdownMinutes,allowInternalSchemes:A(t.allowInternalSchemes)??C.allowInternalSchemes,allowLoopback:A(t.allowLoopback)??C.allowLoopback,evalTimeoutMs:N(`AIKIT_BROWSER_EVAL_TIMEOUT_MS`)??j(t.evalTimeoutMs)??C.evalTimeoutMs,evalMaxResultBytes:j(t.evalMaxResultBytes)??C.evalMaxResultBytes,redactPasswordFieldsInScreenshots:A(t.redactPasswordFieldsInScreenshots)??C.redactPasswordFieldsInScreenshots,engine:k(t.engine)??C.engine,proxy:k(t.proxy),viewport:k(t.viewport)}}function P(e,t){return{content:[{type:`text`,text:e}],structuredContent:t}}function F(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}function I(e){try{let t=JSON.parse(e);if(t&&typeof t==`object`){let e=L(t);if(e.length>0)return e.join(`
1
+ import{exec as e,execFile as t,execFileSync as n,execSync as r}from"node:child_process";import{copyFileSync as i,existsSync as a,mkdirSync as o,readFileSync as s,readdirSync as c,unlinkSync as l,writeFileSync as u}from"node:fs";import{homedir as d,platform as f,tmpdir as p}from"node:os";import{join as m}from"node:path";import{z as h}from"zod";const g=`0.26.0`,_=`.agent-browser-version`;function ee(e){return typeof e==`string`?e.trim():e instanceof Buffer?e.toString(`utf8`).trim():``}function v(){return m(d(),`.aikit`,`browsers`)}function y(e){return e.browsersPath??process.env.AIKIT_BROWSER_PATH??process.env.AIKIT_BROWSER_BROWSERS_PATH??v()}function b(){try{let e=r(`${f()===`win32`?`where`:`which`} agent-browser`,{encoding:`utf8`,windowsHide:!0,stdio:`pipe`,timeout:3e3}).trim().split(/\r?\n/)[0];if(!e)return null;if(f()===`win32`){if(a(`${e}.cmd`))return`${e}.cmd`;if(a(`${e}.bat`))return`${e}.bat`;if(a(`${e}.exe`))return`${e}.exe`}return a(e)?e:null}catch{return null}}function x(e){return m(e,`agent-browser`,te())}function te(){switch(f()){case`win32`:return`agent-browser.exe`;default:return`agent-browser`}}function ne(e,t){try{u(m(e,_),t,`utf8`)}catch{}}function re(e){try{return s(m(e,_),`utf8`).trim()}catch{return null}}function ie(e){let t=re(e);return t?ae(t,g)>=0:!1}function ae(e,t){let n=e.split(`.`).map(Number),r=t.split(`.`).map(Number);for(let e=0;e<Math.max(n.length,r.length);e++){let t=n[e]||0,i=r[e]||0;if(t!==i)return t-i}return 0}function oe(e){return!!(a(m(e,`chrome`))||a(m(d(),`.cache`,`agent-browser`,`chrome`)))}async function se(t,n){let s=b();if(s)return n?.(`Using globally installed agent-browser`),s;let l=y(t);a(l)||o(l,{recursive:!0});let u=x(l);if(a(u)&&ie(l))return n?.(`Using cached agent-browser at ${u}`),u;n?.(`Downloading agent-browser (first use)...`),await new Promise((t,n)=>{let r=new AbortController,i=setTimeout(()=>r.abort(),12e4),a=e(`npx -y agent-browser@latest install --install-dir "${l}"`,{timeout:12e4,windowsHide:!0,encoding:`utf8`,env:{...process.env,AGENT_BROWSER_CACHE_DIR:l},signal:r.signal},(e,r,a)=>{if(clearTimeout(i),e){let t=ee(a)||e.message||`Unknown agent-browser install failure`;n(Error(`Failed to install agent-browser: ${t}`));return}t()});a.stdin&&a.stdin.destroy()});let d=u;try{let e=r(f()===`win32`?`npx -y -p agent-browser node -e "process.stdout.write(__dirname)"`:`npx -y -p agent-browser which agent-browser 2>/dev/null || true`,{encoding:`utf8`,timeout:15e3,windowsHide:!0,stdio:`pipe`}).trim(),t=f()===`win32`?`agent-browser-win32-x64.exe`:f()===`darwin`?process.arch===`arm64`?`agent-browser-darwin-arm64`:`agent-browser-darwin-x64`:`agent-browser-linux-${process.arch===`arm64`?`arm64`:`x64`}`,s=[];e&&!e.includes(`MODULE_NOT_FOUND`)&&(s.push(e),s.push(m(e,`..`)));try{let e=m(r(`npm config get cache`,{encoding:`utf8`,timeout:5e3,windowsHide:!0,stdio:`pipe`}).trim(),`_npx`);if(a(e)){let n=c(e,{withFileTypes:!0});for(let r of n){if(!r.isDirectory())continue;let n=m(e,r.name,`node_modules`,`agent-browser`);if(a(m(n,`bin`,t))){s.push(n);break}}}}catch{}for(let e of s){let r=m(e,`bin`,t);if(a(r)){let t=m(l,`agent-browser`);a(t)||o(t,{recursive:!0});let s=x(l);i(r,s);let c=m(e,`bin`,`agent-browser.js`);a(c)&&i(c,m(t,`agent-browser.js`)),ne(l,g),d=s,n?.(`Cached agent-browser at ${s}`);break}}}catch{}return n?.(`agent-browser ready`),d}async function ce(e){try{return n(e,[`--version`],{encoding:`utf8`,windowsHide:!0,stdio:`pipe`,timeout:5e3}).trim()}catch{return null}}function le(e){if(b())return!0;let t=y(e);return oe(t)||a(x(t))}const ue=[`ui`,`headless`];function de(e){return ue.includes(e)?e:`headless`}function fe(e){let t=[];return e===`headless`&&t.push(`--headless`),t}function pe(e){return{headless:e===`headless`,args:fe(e)}}var S=class{tabs=new Map;labelToId=new Map;register(e,t,n,r){return this.tabs.set(e,{tabId:e,url:t,title:n??t,label:r,createdAt:new Date}),r&&this.labelToId.set(r,e),e}resolve(e){return this.tabs.has(e)?e:this.labelToId.get(e)||e}getTab(e){let t=this.tabs.get(e);if(!t)throw Error(`Tab not found: ${e}`);return t}updateTabInfo(e,t,n){let r=this.tabs.get(e);r&&this.tabs.set(e,{...r,url:t,title:n})}setSnapshot(e,t){let n=this.tabs.get(e);n&&this.tabs.set(e,{...n,snapshot:t})}getSnapshot(e){return this.tabs.get(e)?.snapshot}async removeTab(e){let t=this.tabs.get(e);t&&(t.label&&this.labelToId.delete(t.label),this.tabs.delete(e))}listTabs(){return[...this.tabs.values()]}listPages(){return this.listTabs().map(e=>({pageId:e.tabId,url:e.url,title:e.title,label:e.label,createdAt:e.createdAt}))}async closeAll(){this.tabs.clear(),this.labelToId.clear()}clear(){this.tabs.clear(),this.labelToId.clear()}get size(){return this.tabs.size}},me=class{tabs=new S;registerPage(e,t,n,r){return this.tabs.register(e,t,n,r)}getPage(e){throw Error(`Direct Playwright Page access no longer supported with agent-browser. Use engine.exec() or engine.tabExec() for browser operations.`)}getPageInfo(e){let t=this.tabs.getTab(e);return{pageId:t.tabId,url:t.url,title:t.title,label:t.label,createdAt:t.createdAt}}resolvePageId(e){return this.tabs.resolve(e)}setSnapshot(e,t){this.tabs.setSnapshot(e,t)}getSnapshot(e){return this.tabs.getSnapshot(e)}updatePageInfo(e,t,n){this.tabs.updateTabInfo(e,t,n)}async removePage(e){await this.tabs.removeTab(e)}listPages(){return this.tabs.listPages()}async closeAll(){await this.tabs.closeAll()}get size(){return this.tabs.size}};const C={defaultMode:`ui`,browsersPath:null,userDataDirRoot:null,idleShutdownMinutes:10,allowInternalSchemes:!1,allowLoopback:!1,evalTimeoutMs:3e4,evalMaxResultBytes:262144,redactPasswordFieldsInScreenshots:!0,engine:`chrome`};var w=class{binaryPath=null;_currentMode=null;_isLaunched=!1;idleTimer=null;tabs=new S;config;constructor(e={}){this.config={...C,...e}}get currentMode(){return this._currentMode}async launch(e,t){let n=de(e??this.config.defaultMode);if(!(this._isLaunched&&this._currentMode===n)){this._isLaunched&&this._currentMode!==n&&await this.close(),this._currentMode=n,this.binaryPath=await se(this.config,t);try{let e=await this.exec(`--version`);t?.(`agent-browser ${e.stdout.trim()}`)}catch(e){throw Error(`agent-browser binary failed: ${e instanceof Error?e.message:String(e)}`)}this._isLaunched=!0,this.resetIdleTimer()}}async exec(e,...t){if(!this.binaryPath)throw Error(`agent-browser not launched. Call launch() first, or use getEngine() singleton.`);let n=this.binaryPath;f()===`win32`&&!n.endsWith(`.cmd`)&&!n.endsWith(`.bat`)&&!n.endsWith(`.exe`)&&a(`${n}.cmd`)&&(n=`${n}.cmd`);let r=[e,...t];if(f()===`win32`&&(n.endsWith(`.cmd`)||n.endsWith(`.bat`))){let e=`"${n}" ${r.map(e=>/[^\w/:@.\-_{}()/\\]/.test(e)?`"${e.replace(/"/g,`""`)}"`:e).join(` `)}`;return await this.execViaShell(e)}return await this.execViaExecFile(n,r)}execViaExecFile(e,n){return new Promise((r,i)=>{t(e,n,{timeout:this.config.evalTimeoutMs,windowsHide:!0},(t,a,o)=>{if(t){let s=t;if(s.code===`ENOENT`){i(Error(`agent-browser binary not found at ${this.binaryPath}`));return}if(s.killed||s.signal){i(Error(`agent-browser command timed out after ${this.config.evalTimeoutMs}ms: ${e} ${n.join(` `)}`));return}r({stdout:a??``,stderr:o??``,exitCode:typeof s.code==`number`?s.code:1});return}r({stdout:a??``,stderr:o??``,exitCode:0})}).stdin?.end()})}execViaShell(t){return new Promise((n,r)=>{e(t,{timeout:this.config.evalTimeoutMs,windowsHide:!0},(e,i,a)=>{if(e){let o=e;if(o.code===`ENOENT`){r(Error(`agent-browser binary not found at ${this.binaryPath}`));return}if(o.killed||o.signal){r(Error(`agent-browser command timed out after ${this.config.evalTimeoutMs}ms: ${t}`));return}n({stdout:i??``,stderr:a??``,exitCode:typeof o.code==`number`?o.code:1});return}n({stdout:i??``,stderr:a??``,exitCode:0})})})}async tabExec(e,t,...n){return this.exec(`tab`,e,t,...n)}async open(e,t,n){await this.launch(t);let r=this._currentMode===`ui`?[`open`,e,`--headed`]:[`open`,e],i=await this.exec(...r);if(i.exitCode!==0)throw Error(`agent-browser failed to open URL (exit ${i.exitCode}): ${i.stderr||i.stdout||`Unknown error`}`);return this.tabs.register(`t0`,e,i.stdout.trim(),n),this.resetIdleTimer(),`t0`}async screenshot(e,t){let n=t?.format??`png`,r=n===`jpeg`?`image/jpeg`:`image/png`,i=n===`jpeg`?`jpg`:`png`,a=m(t?.screenshotDir??p(),`aikit-screenshot-${Date.now()}.${i}`),o=[a];t?.fullPage&&o.push(`--full`),t?.screenshotDir&&o.push(`--screenshot-dir`,t.screenshotDir),t?.format===`jpeg`&&o.push(`--screenshot-format`,`jpeg`),t?.quality&&o.push(`--screenshot-quality`,String(t.quality)),t?.annotate&&o.push(`--annotate`),await this.exec(`screenshot`,...o);let c=s(a),u=c.toString(`base64`);try{l(a)}catch{}return this.resetIdleTimer(),{base64:u,mimeType:r,bytes:c.length}}async readSnapshot(e,t=!1){let n=t?[`-c`,`--json`]:[`-i`,`--json`],r=await this.tabExec(e,`snapshot`,...n);return this.resetIdleTimer(),r.stdout}async navigate(e,t){let n=await this.tabExec(e,`goto`,t);return this.resetIdleTimer(),n}async close(){if(this.stopIdleTimer(),this._isLaunched){try{await this.exec(`close`).catch(()=>{})}catch{}this.tabs.clear(),this._isLaunched=!1,this._currentMode=null}}isLaunched(){return this._isLaunched}getConfig(){return this.config}getBinaryPath(){return this.binaryPath}resolvePageId(e){return this.tabs.resolve(e)}resetIdleTimer(){this.stopIdleTimer();let e=setTimeout(()=>{this.close()},this.config.idleShutdownMinutes*6e4);this._currentMode!==`ui`&&e.unref?.(),this.idleTimer=e}stopIdleTimer(){this.idleTimer&&=(clearTimeout(this.idleTimer),null)}};let T=null;function E(e){return T||=new w(e),T}async function he(){T&&=(await T.close(),null)}function D(e,t){try{let n=new URL(e),r=n.hostname.toLowerCase(),i=n.protocol.toLowerCase();return[`file:`,`chrome:`,`chrome-extension:`,`data:`,`javascript:`].includes(i)?t?.allowInternalSchemes?{allowed:!0}:{allowed:!1,reason:`Scheme '${i}' is blocked for security`}:[`169.254.169.254`,`metadata.google.internal`,`metadata.instance`].includes(r)?{allowed:!1,reason:`Cloud metadata endpoint '${r}' is blocked`}:n.hostname===`localhost`||r===`127.0.0.1`||r===`::1`||r.startsWith(`10.`)||r.startsWith(`172.`)||r.startsWith(`192.168.`)?t?.allowLoopback?{allowed:!0}:{allowed:!1,reason:`Internal host '${r}' requires allowLoopback=true`}:{allowed:!0}}catch{return{allowed:!1,reason:`Invalid URL`}}}function O(e,t){return Buffer.byteLength(e,`utf8`)<=t?{valid:!0,result:e,truncated:!1}:{valid:!0,result:`${Buffer.from(e).subarray(0,t).toString(`utf8`)}\n... [truncated]`,truncated:!0,reason:`Result exceeded ${t} bytes, truncated to ${t} bytes`}}const ge=[`ui`,`headless`];function _e(e){return typeof e==`object`&&e?e:null}function k(e){return typeof e==`string`&&e.length>0?e:void 0}function A(e){return typeof e==`boolean`?e:void 0}function j(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}function M(e){return typeof e==`string`&&ge.includes(e)?e:void 0}function N(e){let t=process.env[e];if(!t)return;let n=Number(t);return Number.isFinite(n)?n:void 0}function ve(e){let t=_e(e.browser)??{};return{...C,defaultMode:M(process.env.AIKIT_BROWSER_DEFAULT_MODE)??M(t.defaultMode)??C.defaultMode,browsersPath:k(process.env.AIKIT_BROWSER_PATH)??k(process.env.AIKIT_BROWSER_BROWSERS_PATH)??k(t.browsersPath)??C.browsersPath,userDataDirRoot:k(t.userDataDirRoot)??C.userDataDirRoot,idleShutdownMinutes:N(`AIKIT_BROWSER_IDLE_MINUTES`)??j(t.idleShutdownMinutes)??C.idleShutdownMinutes,allowInternalSchemes:A(t.allowInternalSchemes)??C.allowInternalSchemes,allowLoopback:A(t.allowLoopback)??C.allowLoopback,evalTimeoutMs:N(`AIKIT_BROWSER_EVAL_TIMEOUT_MS`)??j(t.evalTimeoutMs)??C.evalTimeoutMs,evalMaxResultBytes:j(t.evalMaxResultBytes)??C.evalMaxResultBytes,redactPasswordFieldsInScreenshots:A(t.redactPasswordFieldsInScreenshots)??C.redactPasswordFieldsInScreenshots,engine:k(t.engine)??C.engine,proxy:k(t.proxy),viewport:k(t.viewport)}}function P(e,t){return{content:[{type:`text`,text:e}],structuredContent:t}}function F(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}function I(e){try{let t=JSON.parse(e);if(t&&typeof t==`object`){let e=L(t);if(e.length>0)return e.join(`
2
2
  `)}return JSON.stringify(t,null,2)}catch{return e}}function L(e,t=0,n=[]){let r=` `.repeat(t),i=typeof e.role==`string`?e.role.toUpperCase():``,a=typeof e.ref==`string`?e.ref:``,o=typeof e.name==`string`?e.name:``,s=typeof e.value==`string`?`="${e.value}"`:``,c=Array.isArray(e.children)?e.children:[];if(i&&a){let e=ye(i),t=o||s||``;n.push(`${r}[${e}] [${a}] ${t}`.trimEnd())}else if(o||i){let e=i.toLowerCase();n.push(`${r}${e}: ${o}`.trimEnd())}for(let e of c)typeof e==`object`&&e&&L(e,t+1,n);return n}function ye(e){return{BUTTON:`BUTTON`,LINK:`LINK`,TEXT_FIELD:`TEXTFIELD`,TEXTBOX:`TEXTFIELD`,COMBOBOX:`SELECT`,CHECKBOX:`CHECKBOX`,RADIO:`RADIO`,SWITCH:`SWITCH`,SLIDER:`SLIDER`,TAB:`TAB`,MENU_ITEM:`MENUITEM`,LISTBOX:`LIST`,GRID:`GRID`,TABLE:`TABLE`,HEADING:`HEADING`,IMAGE:`IMAGE`,IMG:`IMAGE`,PROGRESSBAR:`PROGRESS`,DIALOG:`DIALOG`,TOOLTIP:`TOOLTIP`,ALERT:`ALERT`,MENU:`MENU`,NAVIGATION:`NAV`,SEARCH:`SEARCH`,MAIN:`MAIN`,COMPLEMENTARY:`COMPLEMENT`,CONTENTINFO:`INFO`,REGION:`REGION`}[e]??e.slice(0,8)}function be(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=E(e),m=p.resolvePageId(t);switch(n){case`click`:{let e=F({ref:r,selector:i,element:a},`browser_act(click)`);await p.tabExec(m,`click`,e);break}case`type`:{let e=F({ref:r,selector:i,element:a},`browser_act(type)`);await p.tabExec(m,`fill`,e,o??``);break}case`press`:{let e=F({ref:r,selector:i,element:a},`browser_act(press)`);if(!s)throw Error(`browser_act(press) requires key`);await p.tabExec(m,`press`,e,s);break}case`hover`:{let e=F({ref:r,selector:i,element:a},`browser_act(hover)`);await p.tabExec(m,`hover`,e);break}case`drag`:{let e=F({ref:l??r,selector:u??i,element:a},`browser_act(drag) source`),t=F({ref:d,selector:f??c,element:a},`browser_act(drag) target`);await p.tabExec(m,`drag`,e,t);break}case`select`:{let e=F({ref:r,selector:i,element:a},`browser_act(select)`);if(c===void 0)throw Error(`browser_act(select) requires value`);await p.tabExec(m,`select`,e,c);break}case`scroll`:{if(i||r||a){let e=F({ref:r,selector:i,element:a},`browser_act(scroll)`);await p.tabExec(m,`scrollintoview`,e);break}let e=c??`down 500`;await p.tabExec(m,`scroll`,e);break}case`upload`:{let e=F({ref:r,selector:i,element:a},`browser_act(upload)`);if(!c)throw Error(`value (file path) required for upload`);await p.tabExec(m,`upload`,e,c);break}}return p.resetIdleTimer(),P(`ok`,{ok:!0})}}function xe(e){return async({pageId:t,subAction:n,level:r,bufferSize:i,expression:a})=>{let o=E(e),s=o.resolvePageId(t);switch(n){case`enable`:{let e=[`--enable`];return i&&e.push(`--buffer-size`,String(i)),r&&e.push(`--level`,r),await o.tabExec(s,`console`,...e),o.resetIdleTimer(),P(`Console capture enabled`,{enabled:!0})}case`get`:{let t=[`--json`];r&&t.push(`--level`,r);let n=await o.tabExec(s,`console`,...t);o.resetIdleTimer();let i=[];try{i=JSON.parse(n.stdout)}catch{i=[{raw:n.stdout}]}let c,l;if(a)try{c=(await o.tabExec(s,`evaluate`,`--timeout=${e.evalTimeoutMs}`,`--`,a)).stdout}catch(e){l=e instanceof Error?e.message:String(e)}return P(c===void 0?`Console has ${i.length} entries`:`Console has ${i.length} entries\nEvaluation: ${c}`,{entries:i,count:i.length,expression:a,evalResult:c,evalError:l})}case`clear`:return await o.tabExec(s,`console`,`clear`),o.resetIdleTimer(),P(`Console cleared`,{cleared:!0});default:return P(`Unknown console sub-action`,{error:`Unknown console sub-action`})}}}function Se(e){return async({pageId:t,accept:n,promptText:r})=>{let i=E(e),a=i.resolvePageId(t);if(n){let e=r?[`accept`,`--text`,r]:[`accept`];await i.tabExec(a,`dialog`,...e)}else await i.tabExec(a,`dialog`,`dismiss`);return i.resetIdleTimer(),P(`Dialog ${n?`accepted`:`dismissed`}`,{accepted:n})}}function Ce(e){return async({pageId:t})=>{let n=E(e),r=n.resolvePageId(t),i=await n.tabExec(r,`diff`,`snapshot`);return n.resetIdleTimer(),P(i.stdout,{pageId:r,diff:i.stdout})}}function we(e){return async({pageId:t,code:n,timeoutMs:r})=>{let i=E(e),a=i.resolvePageId(t),o=r??e.evalTimeoutMs,s=await i.tabExec(a,`evaluate`,`--timeout=${o}`,`--`,n);i.resetIdleTimer();let c=O(s.stdout,e.evalMaxResultBytes);return P(c.result,{pageId:a,result:c.result,truncated:c.truncated})}}function Te(e){return async({pageId:t,url:n,method:r,headers:i,body:a,timeoutMs:o,includeHeaders:s})=>{let c=E(e),l=c.resolvePageId(t),u=o??e.evalTimeoutMs,d=Ee(n,r??`GET`,s??!0,i,a),f=await c.tabExec(l,`evaluate`,`--timeout=${u}`,`--`,d);return c.resetIdleTimer(),P(f.stdout,{pageId:l,response:f.stdout})}}function Ee(e,t,n,r,i){let a={method:t,headers:r??{}};i&&[`POST`,`PUT`,`PATCH`].includes(t.toUpperCase())&&(a.body=i);let o=JSON.stringify(a);return n?`fetch(${JSON.stringify(e)}, ${o}).then(async r => {
3
3
  const text = await r.text();
4
4
  const headers = {};
@@ -2,7 +2,7 @@
2
2
  "manifest_version": "0.3",
3
3
  "name": "aikit",
4
4
  "display_name": "AI Kit",
5
- "version": "0.1.389",
5
+ "version": "0.1.390",
6
6
  "description": "Local-first AI developer toolkit — knowledge base, code analysis, context management, and developer tools for LLM agents",
7
7
  "author": {
8
8
  "name": "AnVPX",
@@ -5,4 +5,4 @@ import{fileURLToPath as e,pathToFileURL as t}from"node:url";import{parseArgs as
5
5
  `).length,fileHash:this.hash(e.content),indexedAt:t,origin:`curated`,tags:e.frontmatter.tags,category:e.frontmatter.category,version:e.frontmatter.version}});try{return await this.store.upsert(i,r),e.length}catch(t){z.error(`Failed to upsert curated batch`,{batchSize:e.length,...o(t)});for(let t of e)n.push(`${t.relativePath}: upsert failed`);return 0}}catch(r){if(e.length===1)return z.error(`Failed to embed curated item`,{relativePath:e[0].relativePath,...o(r)}),n.push(`${e[0].relativePath}: reindex failed`),0;z.warn(`Curated embed batch failed, retrying with smaller chunks`,{batchSize:e.length,...o(r)});let i=Math.ceil(e.length/2),a=e.slice(0,i),s=e.slice(i);return await this.embedAndUpsertBatch(a,t,n)+await this.embedAndUpsertBatch(s,t,n)}}gitCommitKnowledge(e,t,n){try{if(!b(this.curatedDir))return;let r=this.knowledgeRefForPath(e);if(!r)return;x(r,`entry.md`,t,n,this.curatedDir)}catch{}}gitDeleteKnowledgeRef(e){try{if(!b(this.curatedDir))return;let t=this.knowledgeRefForPath(e);if(!t)return;S([`update-ref`,`-d`,t],this.curatedDir)}catch{}}knowledgeRefForPath(e){let t=e.replace(/\.md$/,``).split(`/`).map(e=>C(e)).join(`/`);return t.split(`/`).every(e=>y.test(e))?`${R}/${t}`:null}async indexCuratedFile(e,t,n){let r=await this.embedder.embed(t),i=`.ai/curated/${e}`,a=new Date().toISOString(),o={id:this.hashId(i,0),content:t,sourcePath:i,contentType:`curated-knowledge`,headingPath:n.title,chunkIndex:0,totalChunks:1,startLine:1,endLine:t.split(`
6
6
  `).length,fileHash:this.hash(t),indexedAt:a,origin:`curated`,tags:n.tags,category:n.category,version:n.version};await this.store.upsert([o],[r])}async indexCuratedFileBestEffort(e,t,n,i){if(r.instance().isDegraded(`embedder`)){z.debug(`Skipping vector indexing — embedder degraded`,{relativePath:e,operation:i,subsystem:`embedder`});return}try{await this.indexCuratedFile(e,t,n)}catch(t){z.warn(`Curated file persisted but vector indexing deferred`,{relativePath:e,operation:i,...o(t)})}}async discoverCategories(){return this.adapter.listDirectories()}guardPath(e){let t=e.replace(/^\.ai\/curated\//,``);if(t.endsWith(`.md`)||(t+=`.md`),t.includes(`..`)||l(t))throw Error(`Invalid path: ${t}. Must be relative within .ai/curated/ directory.`);let n=t.split(`/`)[0];return this.validateCategoryName(n),t}validateCategoryName(e){if(!/^[a-z][a-z0-9-]*$/.test(e))throw Error(`Invalid category name: "${e}". Must be lowercase kebab-case (e.g., "decisions", "api-contracts").`)}validateContentSize(e){if(Buffer.byteLength(e,`utf-8`)>L)throw Error(`Content exceeds maximum size of ${L/1024}KB`)}slugify(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-|-$/g,``).slice(0,80)}normalizeTags(e){return[...new Set(e.map(e=>e.trim()).filter(Boolean))]}sameTags(e,t){if(e.length!==t.length)return!1;let n=new Set(e);return t.every(e=>n.has(e))}ensureCategoryPath(e,t){if(!e.startsWith(`${t}/`))throw Error(`Curated path "${e}" must stay within category "${t}"`)}async uniqueRelativePath(e,t){let n=`${e}/${t}.md`;if(!await this.adapter.exists(n))return n;for(let n=2;n<=100;n++){let r=`${e}/${t}-${n}.md`;if(!await this.adapter.exists(r))return r}throw Error(`Too many entries with slug "${t}" in category "${e}"`)}hash(e){return v(`sha256`).update(e).digest(`hex`).slice(0,16)}hashId(e,t){return this.hash(`${e}::${t}`)}serializeFile(e,t){return`${[`---`,`title: "${t.title.replace(/"/g,`\\"`)}"`,`category: ${t.category}`,`tags: [${t.tags.map(e=>`"${e}"`).join(`, `)}]`,`created: ${t.created}`,`updated: ${t.updated}`,`version: ${t.version}`,`origin: ${t.origin}`,`changelog:`,...t.changelog.map(e=>` - version: ${e.version}\n date: ${e.date}\n reason: "${e.reason.replace(/"/g,`\\"`)}"`),`---`].join(`
7
7
  `)}\n\n${e}\n`}parseFile(e){let t=e.match(/^---\n([\s\S]*?)\n---\n\n?([\s\S]*)$/);if(!t)return{frontmatter:{title:`Untitled`,category:`notes`,tags:[],created:``,updated:``,version:1,origin:`curated`,changelog:[]},content:e};let n=t[1],r=t[2].trim(),i={},a=[],o=n.split(`
8
- `),s=!1,c={};for(let e of o){if(/^changelog:\s*$/.test(e)){s=!0;continue}if(s){let t=e.match(/^\s+-\s+version:\s*(\d+)$/);if(t){c.version!=null&&a.push(c),c={version:parseInt(t[1],10)};continue}let n=e.match(/^\s+date:\s*(.+)$/);if(n){c.date=n[1].trim();continue}let r=e.match(/^\s+reason:\s*"?(.*?)"?\s*$/);if(r){c.reason=r[1];continue}/^\w/.test(e)&&(s=!1,c.version!=null&&a.push(c),c={});continue}let t=e.match(/^(\w+):\s*(.*)$/);if(t){let e=t[1],n=t[2];typeof n==`string`&&n.startsWith(`[`)&&n.endsWith(`]`)?n=n.slice(1,-1).split(`,`).map(e=>e.trim().replace(/^"|"$/g,``)).filter(e=>e.length>0):typeof n==`string`&&/^\d+$/.test(n)?n=parseInt(n,10):typeof n==`string`&&n.startsWith(`"`)&&n.endsWith(`"`)&&(n=n.slice(1,-1)),i[e]=n}}return c.version!=null&&a.push(c),{frontmatter:{title:i.title??`Untitled`,category:i.category??`notes`,tags:i.tags??[],created:i.created??``,updated:i.updated??``,version:i.version??1,origin:`curated`,changelog:a},content:r}}};const V=i(`server`);function H(e,t){return t?{version:e,...o(t)}:{version:e}}function U(){return process.env.AIKIT_TRANSPORT?process.env.AIKIT_TRANSPORT:process.stdin.isTTY?`http`:`stdio`}function W(){let e=process.argv[1];if(!e)return!1;try{return import.meta.url===t(e).href}catch{return!1}}function G(){return W()?n({allowPositionals:!0,options:{transport:{type:`string`,default:U()},port:{type:`string`,default:process.env.AIKIT_PORT??`3210`}}}).values:{transport:U(),port:process.env.AIKIT_PORT??`3210`}}async function K(){let e=t=>{t.name===`ExperimentalWarning`&&t.message.includes(`SQLite`)||(process.off(`warning`,e),process.emitWarning(t),process.on(`warning`,e))};process.on(`warning`,e);let t=w(),n=G();if(process.on(`unhandledRejection`,e=>{V.error(`Unhandled rejection`,H(t,e))}),process.on(`uncaughtException`,e=>{V.error(`Uncaught exception — exiting`,H(t,e)),process.exit(1)}),V.info(`Starting MCP AI Kit server`,{version:t}),n.transport===`http`){let{startHttpMode:e}=await import(`./server-http-CHmo5k59.js`);await e(t,n.port)}else{let{startStdioMode:e}=await import(`./server-stdio-D7rUgIc4.js`);await e(t)}}K();export{T as a,k as i,I as n,E as o,F as r,O as s,B as t};
8
+ `),s=!1,c={};for(let e of o){if(/^changelog:\s*$/.test(e)){s=!0;continue}if(s){let t=e.match(/^\s+-\s+version:\s*(\d+)$/);if(t){c.version!=null&&a.push(c),c={version:parseInt(t[1],10)};continue}let n=e.match(/^\s+date:\s*(.+)$/);if(n){c.date=n[1].trim();continue}let r=e.match(/^\s+reason:\s*"?(.*?)"?\s*$/);if(r){c.reason=r[1];continue}/^\w/.test(e)&&(s=!1,c.version!=null&&a.push(c),c={});continue}let t=e.match(/^(\w+):\s*(.*)$/);if(t){let e=t[1],n=t[2];typeof n==`string`&&n.startsWith(`[`)&&n.endsWith(`]`)?n=n.slice(1,-1).split(`,`).map(e=>e.trim().replace(/^"|"$/g,``)).filter(e=>e.length>0):typeof n==`string`&&/^\d+$/.test(n)?n=parseInt(n,10):typeof n==`string`&&n.startsWith(`"`)&&n.endsWith(`"`)&&(n=n.slice(1,-1)),i[e]=n}}return c.version!=null&&a.push(c),{frontmatter:{title:i.title??`Untitled`,category:i.category??`notes`,tags:i.tags??[],created:i.created??``,updated:i.updated??``,version:i.version??1,origin:`curated`,changelog:a},content:r}}};const V=i(`server`);function H(e,t){return t?{version:e,...o(t)}:{version:e}}function U(){return process.env.AIKIT_TRANSPORT?process.env.AIKIT_TRANSPORT:process.stdin.isTTY?`http`:`stdio`}function W(){let e=process.argv[1];if(!e)return!1;try{return import.meta.url===t(e).href}catch{return!1}}function G(){return W()?n({allowPositionals:!0,options:{transport:{type:`string`,default:U()},port:{type:`string`,default:process.env.AIKIT_PORT??`3210`}}}).values:{transport:U(),port:process.env.AIKIT_PORT??`3210`}}async function K(){let e=t=>{t.name===`ExperimentalWarning`&&t.message.includes(`SQLite`)||(process.off(`warning`,e),process.emitWarning(t),process.on(`warning`,e))};process.on(`warning`,e);let t=w(),n=G();if(process.on(`unhandledRejection`,e=>{V.error(`Unhandled rejection`,H(t,e))}),process.on(`uncaughtException`,e=>{V.error(`Uncaught exception — exiting`,H(t,e)),process.exit(1)}),V.info(`Starting MCP AI Kit server`,{version:t}),n.transport===`http`){let{startHttpMode:e}=await import(`./server-http-DvRZFLCZ.js`);await e(t,n.port)}else{let{startStdioMode:e}=await import(`./server-stdio-BrcBWKFl.js`);await e(t)}}K();export{T as a,k as i,I as n,E as o,F as r,O as s,B as t};
@@ -351,4 +351,4 @@ svg text{fill:var(--body);font-family:var(--sans);font-size:12px}
351
351
  <\/script>
352
352
  </body>
353
353
  </html>`}const U=`<!-- DIAGRAM:SVG -->`;function W(e){let t=e.indexOf(U);if(t===-1)return null;let n=t+20,r=e.indexOf(U,n);if(r===-1)return null;let i=e.slice(n,r).trim();if(i.startsWith(`<svg`))return i;let a=e.slice(Math.max(0,t),r+20),o=a.match(/viewBox="([^"]+)"/),s=o?o[1]:`0 0 1200 800`,c=a.match(/width="(\d+)"/),l=c?c[1]:`1200`,u=a.match(/height="(\d+)"/);return[`<svg xmlns="http://www.w3.org/2000/svg" viewBox="${s}" width="${l}" height="${u?u[1]:`800`}">`,` <defs>`,` <style>`,` text { font-family: system-ui, -apple-system, sans-serif; }`,` .title { font-size: 20px; font-weight: 600; fill: #fff; }`,` .subtitle { font-size: 14px; fill: #94a3b8; }`,` </style>`,` </defs>`,i,`</svg>`].join(`
354
- `)}function he(e){let t=e.match(/<title>([^<]+)<\/title>/);return t?t[1]:`diagram`}async function ge(e,t,n){let r=m(n);await h(r,{recursive:!0});let i=he(e).replace(/[^a-zA-Z0-9\s-]/g,``).replace(/\s+/g,`-`).replace(/-+/g,`-`).replace(/^-|-$/g,``).toLowerCase().slice(0,80)||`diagram`,a=p(r,`${i}.html`);await g(a,e,`utf-8`);let o=null,s=W(e);s&&(o=p(r,`${i}.svg`),await g(o,s,`utf-8`));let c=null;return t&&(c=p(r,`${i}.md`),await g(c,t,`utf-8`)),{htmlPath:a,svgPath:o,mdPath:c}}const G=10*1024*1024,K=2e3;function _e(e){try{return JSON.stringify(e)}catch{return``}}function ve(e){switch(e.diagram_type){case`architecture`:return ae(e);case`workflow`:return H(e);case`sequence`:return R(e);case`dataflow`:return ce(e);case`lifecycle`:return P(e)}}function q(e,t={}){Y(e);let n=J(e);if(n.length>0)throw Error(`Diagram validation failed: ${n.join(`; `)}`);let r=t.title??e.meta.title,i=t.subtitle??e.meta.subtitle,a=t.dualOutput??!0,{svg:o,cardsHtml:s,detailData:c}=ve(e),l=c&&Object.keys(c).length>0?`\n<script id="diagram-node-data" type="application/json">${_e(c)}<\/script>`:``,u=e.meta?.palette===`warm`?`warm`:`technical`;return{html:me().replaceAll(`[TITLE]`,X(r)).replaceAll(`[SUBTITLE]`,X(i??``)).replaceAll(`[PALETTE]`,u===`warm`?` data-palette="warm"`:``).replaceAll(`<!-- DIAGRAM:SVG -->`,o).replaceAll(`<!-- DIAGRAM:CARDS -->`,s).replace(`</body>`,`${l}\n</body>`),markdown:a?_(e):void 0}}function ye(e,t={}){return q(e,{...t,dualOutput:!1}).html}function be(e){return _(e)}function xe(e){try{return Y(e),J(e)}catch(e){return[e.message]}}function J(e){if(!e||typeof e!=`object`)return[`Input must be an object`];if(!e.diagram_type)return[`Missing diagram_type`];if(!e.meta?.title)return[`meta.title is required`];if(e.schema_version!==1)return[`schema_version must be 1`];let t=e.diagram_type,n=e,r=n.components??n.nodes??n.participants??n.states??[],i=n.connections??n.edges??n.messages??n.flows??n.transitions??[],a=new Set(r.map(e=>e.id));if(a.size!==r.length)return[`${t}: Node/component IDs must be unique`];for(let e of i){if(e.from&&!a.has(e.from))return[`${t}: Edge references unknown source "${e.from}"`];if(e.to&&!a.has(e.to))return[`${t}: Edge references unknown target "${e.to}"`]}return[]}function Y(e){let t=JSON.stringify(e),n=Buffer.byteLength(t,`utf-8`);if(n>G)throw Error(`Input too large: ${(n/1024/1024).toFixed(1)}MB (max ${G/1024/1024}MB)`);let r=e,i=r.components??r.nodes??r.participants??[];if(i.length>500)throw Error(`Too many components/nodes: ${i.length} (max 500)`);let a=r.connections??r.edges??r.messages??r.flows??r.transitions??[];if(a.length>K)throw Error(`Too many edges/connections: ${a.length} (max ${K})`)}function Se(e){return e.replace(/[^a-zA-Z0-9-_]/g,`_`).toLowerCase().slice(0,120)}function X(e){let t={"&":`&amp;`,"<":`&lt;`,">":`&gt;`,'"':`&quot;`,"'":`&#39;`};return String(e??``).replace(/[&<>"']/g,e=>t[e]??e)}const Z=d(`server`);function Q(e,t){return t?{version:e,...f(t)}:{version:e}}function $(){return process.env.AIKIT_TRANSPORT?process.env.AIKIT_TRANSPORT:process.stdin.isTTY?`http`:`stdio`}function Ce(){let e=process.argv[1];if(!e)return!1;try{return import.meta.url===l(e).href}catch{return!1}}function we(){return Ce()?u({allowPositionals:!0,options:{transport:{type:`string`,default:$()},port:{type:`string`,default:process.env.AIKIT_PORT??`3210`}}}).values:{transport:$(),port:process.env.AIKIT_PORT??`3210`}}async function Te(){let e=t=>{t.name===`ExperimentalWarning`&&t.message.includes(`SQLite`)||(process.off(`warning`,e),process.emitWarning(t),process.on(`warning`,e))};process.on(`warning`,e);let n=t(),r=we();if(process.on(`unhandledRejection`,e=>{Z.error(`Unhandled rejection`,Q(n,e))}),process.on(`uncaughtException`,e=>{Z.error(`Uncaught exception — exiting`,Q(n,e)),process.exit(1)}),Z.info(`Starting MCP AI Kit server`,{version:n}),r.transport===`http`){let{startHttpMode:e}=await import(`./server-http-D0frtIQs.js`);await e(n,r.port)}else{let{startStdioMode:e}=await import(`./server-stdio-DYB7zm50.js`);await e(n)}}export{c as CuratedKnowledgeManager,s as applyWorkspaceRoots,a as bootstrapWorkspaceRoots,i as createSlidingWindowRateLimiter,ge as exportDiagram,W as extractSvg,n as getSessionIdHeader,Te as main,r as readPositiveIntEnv,t as readVersion,ye as renderHtml,be as renderMd,q as renderToResult,e as resolveCorsOrigin,Se as sanitizeTitle,o as selectWorkspaceRoot,xe as validate};
354
+ `)}function he(e){let t=e.match(/<title>([^<]+)<\/title>/);return t?t[1]:`diagram`}async function ge(e,t,n){let r=m(n);await h(r,{recursive:!0});let i=he(e).replace(/[^a-zA-Z0-9\s-]/g,``).replace(/\s+/g,`-`).replace(/-+/g,`-`).replace(/^-|-$/g,``).toLowerCase().slice(0,80)||`diagram`,a=p(r,`${i}.html`);await g(a,e,`utf-8`);let o=null,s=W(e);s&&(o=p(r,`${i}.svg`),await g(o,s,`utf-8`));let c=null;return t&&(c=p(r,`${i}.md`),await g(c,t,`utf-8`)),{htmlPath:a,svgPath:o,mdPath:c}}const G=10*1024*1024,K=2e3;function _e(e){try{return JSON.stringify(e)}catch{return``}}function ve(e){switch(e.diagram_type){case`architecture`:return ae(e);case`workflow`:return H(e);case`sequence`:return R(e);case`dataflow`:return ce(e);case`lifecycle`:return P(e)}}function q(e,t={}){Y(e);let n=J(e);if(n.length>0)throw Error(`Diagram validation failed: ${n.join(`; `)}`);let r=t.title??e.meta.title,i=t.subtitle??e.meta.subtitle,a=t.dualOutput??!0,{svg:o,cardsHtml:s,detailData:c}=ve(e),l=c&&Object.keys(c).length>0?`\n<script id="diagram-node-data" type="application/json">${_e(c)}<\/script>`:``,u=e.meta?.palette===`warm`?`warm`:`technical`;return{html:me().replaceAll(`[TITLE]`,X(r)).replaceAll(`[SUBTITLE]`,X(i??``)).replaceAll(`[PALETTE]`,u===`warm`?` data-palette="warm"`:``).replaceAll(`<!-- DIAGRAM:SVG -->`,o).replaceAll(`<!-- DIAGRAM:CARDS -->`,s).replace(`</body>`,`${l}\n</body>`),markdown:a?_(e):void 0}}function ye(e,t={}){return q(e,{...t,dualOutput:!1}).html}function be(e){return _(e)}function xe(e){try{return Y(e),J(e)}catch(e){return[e.message]}}function J(e){if(!e||typeof e!=`object`)return[`Input must be an object`];if(!e.diagram_type)return[`Missing diagram_type`];if(!e.meta?.title)return[`meta.title is required`];if(e.schema_version!==1)return[`schema_version must be 1`];let t=e.diagram_type,n=e,r=n.components??n.nodes??n.participants??n.states??[],i=n.connections??n.edges??n.messages??n.flows??n.transitions??[],a=new Set(r.map(e=>e.id));if(a.size!==r.length)return[`${t}: Node/component IDs must be unique`];for(let e of i){if(e.from&&!a.has(e.from))return[`${t}: Edge references unknown source "${e.from}"`];if(e.to&&!a.has(e.to))return[`${t}: Edge references unknown target "${e.to}"`]}return[]}function Y(e){let t=JSON.stringify(e),n=Buffer.byteLength(t,`utf-8`);if(n>G)throw Error(`Input too large: ${(n/1024/1024).toFixed(1)}MB (max ${G/1024/1024}MB)`);let r=e,i=r.components??r.nodes??r.participants??[];if(i.length>500)throw Error(`Too many components/nodes: ${i.length} (max 500)`);let a=r.connections??r.edges??r.messages??r.flows??r.transitions??[];if(a.length>K)throw Error(`Too many edges/connections: ${a.length} (max ${K})`)}function Se(e){return e.replace(/[^a-zA-Z0-9-_]/g,`_`).toLowerCase().slice(0,120)}function X(e){let t={"&":`&amp;`,"<":`&lt;`,">":`&gt;`,'"':`&quot;`,"'":`&#39;`};return String(e??``).replace(/[&<>"']/g,e=>t[e]??e)}const Z=d(`server`);function Q(e,t){return t?{version:e,...f(t)}:{version:e}}function $(){return process.env.AIKIT_TRANSPORT?process.env.AIKIT_TRANSPORT:process.stdin.isTTY?`http`:`stdio`}function Ce(){let e=process.argv[1];if(!e)return!1;try{return import.meta.url===l(e).href}catch{return!1}}function we(){return Ce()?u({allowPositionals:!0,options:{transport:{type:`string`,default:$()},port:{type:`string`,default:process.env.AIKIT_PORT??`3210`}}}).values:{transport:$(),port:process.env.AIKIT_PORT??`3210`}}async function Te(){let e=t=>{t.name===`ExperimentalWarning`&&t.message.includes(`SQLite`)||(process.off(`warning`,e),process.emitWarning(t),process.on(`warning`,e))};process.on(`warning`,e);let n=t(),r=we();if(process.on(`unhandledRejection`,e=>{Z.error(`Unhandled rejection`,Q(n,e))}),process.on(`uncaughtException`,e=>{Z.error(`Uncaught exception — exiting`,Q(n,e)),process.exit(1)}),Z.info(`Starting MCP AI Kit server`,{version:n}),r.transport===`http`){let{startHttpMode:e}=await import(`./server-http-h39zcvrs.js`);await e(n,r.port)}else{let{startStdioMode:e}=await import(`./server-stdio-CouE9XCw.js`);await e(n)}}export{c as CuratedKnowledgeManager,s as applyWorkspaceRoots,a as bootstrapWorkspaceRoots,i as createSlidingWindowRateLimiter,ge as exportDiagram,W as extractSvg,n as getSessionIdHeader,Te as main,r as readPositiveIntEnv,t as readVersion,ye as renderHtml,be as renderMd,q as renderToResult,e as resolveCorsOrigin,Se as sanitizeTitle,o as selectWorkspaceRoot,xe as validate};
@@ -2906,7 +2906,7 @@ None.`:`### Stale Lessons\n${l.map(e=>`- **${e.title}** (\`${e.path}\`) — effe
2906
2906
  });
2907
2907
  })();
2908
2908
  <\/script>`}function Hm(e){try{if(process.platform===`win32`){gr(`powershell`,[`-NoProfile`,`-Command`,`Start-Process "${e}"`],{windowsHide:!0});return}if(process.platform===`darwin`){gr(`open`,[e]);return}gr(`xdg-open`,[e])}catch{}}async function Um(e){try{let t=process.env.AGENT_BROWSER_ARGS??``,n=[`--start-maximized`,`--disable-infobars`],r=t?t.split(`,`):[],i=!1;for(let e of n)r.includes(e)||(r.push(e),i=!0);i&&(process.env.AGENT_BROWSER_ARGS=r.join(`,`));let a=qn();await a.launch(`ui`),a.resetIdleTimer(),await a.open(e);try{await a.exec(`set`,`viewport`,`1920`,`1080`),await a.exec(`eval`,`window.focus();`).catch(()=>{})}catch{}return!0}catch{return Hm(e),!1}}function Wm(e,t,n){let r=[e.title];return e.description&&r.push(e.description),r.push(``,`Opened in browser — ${t}`,n),r.join(`
2909
- `)}function Gm(e){return e.some(e=>e.id!==`__dismiss`)}function Km(e){return e.replace(`</head>`,`${Xh}\n</head>`).replace(`</body>`,`${Zh}\n</body>`)}function qm(e){if(!e.headersSent)try{e.writeHead(500,{"Content-Type":`text/plain`}),e.end(`Internal Server Error`)}catch{try{e.end()}catch{}}}function Jm(e,t){let n=e.headers.referer;return typeof n==`string`&&n.length>0?n:`http://127.0.0.1:${t.port}`}async function Ym(e,t){let n=qn(),r=`ss-${Date.now()}`;n.isLaunched()||await n.launch(`headless`);let{base64:i}=await n.screenshot(r,{fullPage:t?.fullPage!==!1,format:t?.format,quality:t?.quality,annotate:t?.annotate});return Buffer.from(i,`base64`)}async function Xm(e,t){if(!t){e.writeHead(503,{"Content-Type":`text/plain; charset=utf-8`}),e.end(`Screenshot target is not ready.`);return}try{let n=await Ym(t);e.writeHead(200,{"Content-Type":`image/png`,"Cache-Control":`no-store`}),e.end(n)}catch(t){let n=t instanceof Error?t.message:String(t);console.warn(`[present] Screenshot capture failed:`,n),qm(e)}}async function Zm(e,t){if(!t){Rm(e,503,`CLIPBOARD_CAPTURE_TARGET_MISSING`,`Clipboard target is not ready.`);return}try{let n=await Ym(t);e.writeHead(200,{"Content-Type":`image/png`,"Cache-Control":`no-store`}),e.end(n)}catch(t){let n=t instanceof Error?t.message:String(t);console.warn(`[present] Clipboard capture failed:`,n),Rm(e,500,`CLIPBOARD_CAPTURE_FAILED`,`Clipboard capture failed: ${n}`)}}async function Qm(e,t){let n=[];e.on(`data`,e=>n.push(e)),e.on(`end`,async()=>{let e=Buffer.concat(n);if(e.length===0){Rm(t,400,`EMPTY_BODY`,`No image data received.`);return}try{await $m(e),t.writeHead(200,{"Content-Type":`application/json`}),t.end(JSON.stringify({ok:!0}))}catch(e){let n=e instanceof Error?e.message:String(e);console.warn(`[present] System clipboard write failed:`,n),Rm(t,500,`SYSTEM_CLIPBOARD_WRITE_FAILED`,`System clipboard write failed: ${n}`)}}),e.on(`error`,e=>{console.warn(`[present] System clipboard write request error:`,e.message),Rm(t,500,`REQUEST_ERROR`,`Request stream error.`)})}async function $m(e){let t=F(Kn(),`aikit-clipboard-${Date.now()}-${qe(4).toString(`hex`)}.png`);Ne(t,e);try{if(process.platform===`win32`){let e=[`Add-Type -AssemblyName System.Drawing;`,`Add-Type -AssemblyName System.Windows.Forms;`,`$path = '${t.replace(/'/g,`''`)}';`,`$img = [System.Drawing.Image]::FromFile($path);`,`$img2 = [System.Drawing.Bitmap]::FromImage($img);`,`$img.Dispose();`,`[System.Windows.Forms.Clipboard]::SetImage($img2);`,`Start-Sleep -Milliseconds 500;`,`$img2.Dispose();`].join(` `);await new Promise((t,n)=>{hr(`powershell.exe -NoProfile -STA -Command "${e.replace(/"/g,`\\"`)}"`,{timeout:15e3},e=>{e?n(Error(`PowerShell clipboard write failed: ${e.message}`)):t()})})}else if(process.platform===`darwin`)await new Promise((e,n)=>{hr(`osascript -e 'set the clipboard to (read (POSIX file "${t}") as picture)'`,{timeout:15e3},t=>{t?n(Error(`macOS clipboard write failed: ${t.message}`)):e()})});else try{await new Promise((e,n)=>{hr(`wl-copy --type image/png < "${t}" 2>/dev/null`,{timeout:1e4},(t,r)=>{t?n(Error(`wl-copy failed: ${t.message}`)):e(r)})});return}catch{await new Promise((e,n)=>{hr(`xclip -selection clipboard -t image/png -i "${t}"`,{timeout:15e3},t=>{t?n(Error(`Linux clipboard write failed (tried wl-copy then xclip): ${t.message}. Install wl-clipboard (Wayland) or xclip (X11) for clipboard image support.`)):e()})})}}finally{try{Me(t)}catch{}}}function eh(e,t){return e.replace(/'\/callback'/g,`'/present/${t}/callback'`).replace(/"\/callback"/g,`"/present/${t}/callback"`)}function th(e,t){return e.replace(/src="\/viewer"/g,`src="/present/${t}/viewer"`)}async function nh(e,t){if(Oh(`<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=Tn({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(`
2909
+ `)}function Gm(e){return e.some(e=>e.id!==`__dismiss`)}function Km(e){return e.replace(`</head>`,`${Xh}\n</head>`).replace(`</body>`,`${Zh}\n</body>`)}function qm(e){if(!e.headersSent)try{e.writeHead(500,{"Content-Type":`text/plain`}),e.end(`Internal Server Error`)}catch{try{e.end()}catch{}}}function Jm(e,t){let n=e.headers.referer;return typeof n==`string`&&n.length>0?n:`http://127.0.0.1:${t.port}`}async function Ym(e,t){let n=qn(),r=`ss-${Date.now()}`;n.isLaunched()||await n.launch(`headless`);let{base64:i}=await n.screenshot(r,{fullPage:t?.fullPage!==!1,format:t?.format,quality:t?.quality,annotate:t?.annotate});return Buffer.from(i,`base64`)}async function Xm(e,t){if(!t){e.writeHead(503,{"Content-Type":`text/plain; charset=utf-8`}),e.end(`Screenshot target is not ready.`);return}try{let n=await Ym(t);e.writeHead(200,{"Content-Type":`image/png`,"Cache-Control":`no-store`}),e.end(n)}catch(t){let n=t instanceof Error?t.message:String(t);console.warn(`[present] Screenshot capture failed:`,n),qm(e)}}async function Zm(e,t){if(!t){Rm(e,503,`CLIPBOARD_CAPTURE_TARGET_MISSING`,`Clipboard target is not ready.`);return}try{let n=await Ym(t);e.writeHead(200,{"Content-Type":`image/png`,"Cache-Control":`no-store`}),e.end(n)}catch(t){let n=t instanceof Error?t.message:String(t);console.warn(`[present] Clipboard capture failed:`,n),Rm(e,500,`CLIPBOARD_CAPTURE_FAILED`,`Clipboard capture failed: ${n}`)}}async function Qm(e,t){let n=[];e.on(`data`,e=>n.push(e)),e.on(`end`,async()=>{let e=Buffer.concat(n);if(e.length===0){Rm(t,400,`EMPTY_BODY`,`No image data received.`);return}try{await $m(e),t.writeHead(200,{"Content-Type":`application/json`}),t.end(JSON.stringify({ok:!0}))}catch(e){let n=e instanceof Error?e.message:String(e);console.warn(`[present] System clipboard write failed:`,n),Rm(t,500,`SYSTEM_CLIPBOARD_WRITE_FAILED`,`System clipboard write failed: ${n}`)}}),e.on(`error`,e=>{console.warn(`[present] System clipboard write request error:`,e.message),Rm(t,500,`REQUEST_ERROR`,`Request stream error.`)})}async function $m(e){let t=F(Kn(),`aikit-clipboard-${Date.now()}-${qe(4).toString(`hex`)}.png`);try{if(Ne(t,e),process.platform===`win32`){let e=[`Add-Type -AssemblyName System.Drawing;`,`Add-Type -AssemblyName System.Windows.Forms;`,`$path = '${t.replace(/'/g,`''`)}';`,`$img = [System.Drawing.Image]::FromFile($path);`,`$img2 = [System.Drawing.Bitmap]::FromImage($img);`,`$img.Dispose();`,`[System.Windows.Forms.Clipboard]::SetImage($img2);`,`Start-Sleep -Milliseconds 500;`,`$img2.Dispose();`].join(` `);await new Promise((t,n)=>{hr(`powershell.exe -NoProfile -STA -Command "${e.replace(/"/g,`\\"`)}"`,{timeout:15e3,windowsHide:!0},e=>{e?n(Error(`PowerShell clipboard write failed: ${e.message}`)):t()})})}else if(process.platform===`darwin`)await new Promise((e,n)=>{hr(`osascript -e 'set the clipboard to (read (POSIX file "${t}") as picture)'`,{timeout:15e3},t=>{t?n(Error(`macOS clipboard write failed: ${t.message}`)):e()})});else try{await new Promise((e,n)=>{hr(`wl-copy --type image/png < "${t}" 2>/dev/null`,{timeout:1e4},(t,r)=>{t?n(Error(`wl-copy failed: ${t.message}`)):e(r)})});return}catch{await new Promise((e,n)=>{hr(`xclip -selection clipboard -t image/png -i "${t}"`,{timeout:15e3},t=>{t?n(Error(`Linux clipboard write failed (tried wl-copy then xclip): ${t.message}. Install wl-clipboard (Wayland) or xclip (X11) for clipboard image support.`)):e()})})}}finally{try{Me(t)}catch{}}}function eh(e,t){return e.replace(/'\/callback'/g,`'/present/${t}/callback'`).replace(/"\/callback"/g,`"/present/${t}/callback"`)}function th(e,t){return e.replace(/src="\/viewer"/g,`src="/present/${t}/viewer"`)}async function nh(e,t){if(Oh(`<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=Tn({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(`
2910
2910
  `);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=Km(yp(t.resolveHtml(),e.data??null,t.injectId,t.transformData)),r=jm(),i=qe(16).toString(`hex`),a=r.createSession({surfaceId:`viewer`,transport:`viewer`,nonce:i});if(!a.ok)return{content:[{type:`text`,text:`${e.title}\n\nUnable to start local browser transport.`}],structuredContent:{kind:`error`,error:{code:`BROWSER_START_FAILED`,message:a.error.message}},isError:!0};let o=a.session.id,s=fm(`viewer`,e.actions??[],r,o,i),c=th(Cr({title:e.title,subtitle:e.description,html:[`<div class="present-viewer-container">`,` <iframe class="present-viewer-iframe" src="/viewer" sandbox="allow-scripts allow-same-origin"></iframe>`,` ${Qh(i)}`,`</div>`].join(`
2911
2911
  `),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(`
2912
2912
  `)],islands:[],payload:void 0,nonce:i,generatedAt:new Date().toISOString(),colorScheme:e.colorScheme,lang:e.lang,dir:e.dir,transport:`browser`,exportPolicy:`local-interactive`,imageExportMode:`browser-server`,footerContentHtml:pm}),o);Om.set(o,{callbackSession:s,html:c,viewerHtml:n,hasClientConnected:!1,createdAt:Date.now()});let l=``;try{l=`http://127.0.0.1:${await Mm()}/present/${o}`}catch(t){return Om.delete(o),r.removeSession(o),{content:[{type:`text`,text:`${e.title}\n\nUnable to start local browser transport.`}],structuredContent:{kind:`error`,error:{code:`BROWSER_START_FAILED`,message:t instanceof Error?t.message:`Unable to start browser transport`}},isError:!0}}return await Um(l),setTimeout(()=>{Om.delete(o),r.removeSession(o)},Sm),{content:[{type:`text`,text:Wm(e,l,`Rendered.`)}],structuredContent:{kind:`rendered`,reason:`no-response-required`}}}async function rh(e){Oh(`<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=jm(),n=qe(16).toString(`hex`),r=jr(e,{transport:`browser`,registry:Gp,blockVendorScripts:up(),nonce:n}),i=t.createSession({surfaceId:r.surfaceId,transport:`browser`,nonce:n});if(!i.ok)return{content:[{type:`text`,text:`${e.title}\n\nUnable to start local browser transport.`}],structuredContent:{kind:`error`,error:{code:`BROWSER_START_FAILED`,message:i.error.message}},isError:!0};let a=i.session.id,o=fm(r.surfaceId,r.actions,t,a,n),s=bm(r.vendorScripts,`browser`);xm();let c=r.actions.length>0?Bm(r.actions):``,l=r.actions.length>0?Vm(r.actions,o.nonce):``,u=Cr({title:e.title,subtitle:e.description,html:[r.html,c,l].filter(Boolean).join(`
@@ -2905,7 +2905,7 @@ None.`:`### Stale Lessons\n${l.map(e=>`- **${e.title}** (\`${e.path}\`) — effe
2905
2905
  });
2906
2906
  })();
2907
2907
  <\/script>`}function Hm(e){try{if(process.platform===`win32`){qn(`powershell`,[`-NoProfile`,`-Command`,`Start-Process "${e}"`],{windowsHide:!0});return}if(process.platform===`darwin`){qn(`open`,[e]);return}qn(`xdg-open`,[e])}catch{}}async function Um(e){try{let t=process.env.AGENT_BROWSER_ARGS??``,n=[`--start-maximized`,`--disable-infobars`],r=t?t.split(`,`):[],i=!1;for(let e of n)r.includes(e)||(r.push(e),i=!0);i&&(process.env.AGENT_BROWSER_ARGS=r.join(`,`));let a=Zn();await a.launch(`ui`),a.resetIdleTimer(),await a.open(e);try{await a.exec(`set`,`viewport`,`1920`,`1080`),await a.exec(`eval`,`window.focus();`).catch(()=>{})}catch{}return!0}catch{return Hm(e),!1}}function Wm(e,t,n){let r=[e.title];return e.description&&r.push(e.description),r.push(``,`Opened in browser — ${t}`,n),r.join(`
2908
- `)}function Gm(e){return e.some(e=>e.id!==`__dismiss`)}function Km(e){return e.replace(`</head>`,`${Xh}\n</head>`).replace(`</body>`,`${Zh}\n</body>`)}function qm(e){if(!e.headersSent)try{e.writeHead(500,{"Content-Type":`text/plain`}),e.end(`Internal Server Error`)}catch{try{e.end()}catch{}}}function Jm(e,t){let n=e.headers.referer;return typeof n==`string`&&n.length>0?n:`http://127.0.0.1:${t.port}`}async function Ym(e,t){let n=Zn(),r=`ss-${Date.now()}`;n.isLaunched()||await n.launch(`headless`);let{base64:i}=await n.screenshot(r,{fullPage:t?.fullPage!==!1,format:t?.format,quality:t?.quality,annotate:t?.annotate});return Buffer.from(i,`base64`)}async function Xm(e,t){if(!t){e.writeHead(503,{"Content-Type":`text/plain; charset=utf-8`}),e.end(`Screenshot target is not ready.`);return}try{let n=await Ym(t);e.writeHead(200,{"Content-Type":`image/png`,"Cache-Control":`no-store`}),e.end(n)}catch(t){let n=t instanceof Error?t.message:String(t);console.warn(`[present] Screenshot capture failed:`,n),qm(e)}}async function Zm(e,t){if(!t){Rm(e,503,`CLIPBOARD_CAPTURE_TARGET_MISSING`,`Clipboard target is not ready.`);return}try{let n=await Ym(t);e.writeHead(200,{"Content-Type":`image/png`,"Cache-Control":`no-store`}),e.end(n)}catch(t){let n=t instanceof Error?t.message:String(t);console.warn(`[present] Clipboard capture failed:`,n),Rm(e,500,`CLIPBOARD_CAPTURE_FAILED`,`Clipboard capture failed: ${n}`)}}async function Qm(e,t){let n=[];e.on(`data`,e=>n.push(e)),e.on(`end`,async()=>{let e=Buffer.concat(n);if(e.length===0){Rm(t,400,`EMPTY_BODY`,`No image data received.`);return}try{await $m(e),t.writeHead(200,{"Content-Type":`application/json`}),t.end(JSON.stringify({ok:!0}))}catch(e){let n=e instanceof Error?e.message:String(e);console.warn(`[present] System clipboard write failed:`,n),Rm(t,500,`SYSTEM_CLIPBOARD_WRITE_FAILED`,`System clipboard write failed: ${n}`)}}),e.on(`error`,e=>{console.warn(`[present] System clipboard write request error:`,e.message),Rm(t,500,`REQUEST_ERROR`,`Request stream error.`)})}async function $m(e){let t=P(Xn(),`aikit-clipboard-${Date.now()}-${Je(4).toString(`hex`)}.png`);Pe(t,e);try{if(process.platform===`win32`){let e=[`Add-Type -AssemblyName System.Drawing;`,`Add-Type -AssemblyName System.Windows.Forms;`,`$path = '${t.replace(/'/g,`''`)}';`,`$img = [System.Drawing.Image]::FromFile($path);`,`$img2 = [System.Drawing.Bitmap]::FromImage($img);`,`$img.Dispose();`,`[System.Windows.Forms.Clipboard]::SetImage($img2);`,`Start-Sleep -Milliseconds 500;`,`$img2.Dispose();`].join(` `);await new Promise((t,n)=>{Kn(`powershell.exe -NoProfile -STA -Command "${e.replace(/"/g,`\\"`)}"`,{timeout:15e3},e=>{e?n(Error(`PowerShell clipboard write failed: ${e.message}`)):t()})})}else if(process.platform===`darwin`)await new Promise((e,n)=>{Kn(`osascript -e 'set the clipboard to (read (POSIX file "${t}") as picture)'`,{timeout:15e3},t=>{t?n(Error(`macOS clipboard write failed: ${t.message}`)):e()})});else try{await new Promise((e,n)=>{Kn(`wl-copy --type image/png < "${t}" 2>/dev/null`,{timeout:1e4},(t,r)=>{t?n(Error(`wl-copy failed: ${t.message}`)):e(r)})});return}catch{await new Promise((e,n)=>{Kn(`xclip -selection clipboard -t image/png -i "${t}"`,{timeout:15e3},t=>{t?n(Error(`Linux clipboard write failed (tried wl-copy then xclip): ${t.message}. Install wl-clipboard (Wayland) or xclip (X11) for clipboard image support.`)):e()})})}}finally{try{Ne(t)}catch{}}}function eh(e,t){return e.replace(/'\/callback'/g,`'/present/${t}/callback'`).replace(/"\/callback"/g,`"/present/${t}/callback"`)}function th(e,t){return e.replace(/src="\/viewer"/g,`src="/present/${t}/viewer"`)}async function nh(e,t){if(Oh(`<html><body style="font-family:system-ui;padding:2rem;color:#888;text-align:center"><p>Content opened in browser window.</p></body></html>`),e.data!=null&&t.inputSchema){let n=En({data:e.data,schema:t.inputSchema});if(!n.valid){let e=n.errors.map(e=>` ${e.path}: ${e.message}${e.expected?` (expected: ${e.expected}, got: ${e.received})`:``}`).join(`
2908
+ `)}function Gm(e){return e.some(e=>e.id!==`__dismiss`)}function Km(e){return e.replace(`</head>`,`${Xh}\n</head>`).replace(`</body>`,`${Zh}\n</body>`)}function qm(e){if(!e.headersSent)try{e.writeHead(500,{"Content-Type":`text/plain`}),e.end(`Internal Server Error`)}catch{try{e.end()}catch{}}}function Jm(e,t){let n=e.headers.referer;return typeof n==`string`&&n.length>0?n:`http://127.0.0.1:${t.port}`}async function Ym(e,t){let n=Zn(),r=`ss-${Date.now()}`;n.isLaunched()||await n.launch(`headless`);let{base64:i}=await n.screenshot(r,{fullPage:t?.fullPage!==!1,format:t?.format,quality:t?.quality,annotate:t?.annotate});return Buffer.from(i,`base64`)}async function Xm(e,t){if(!t){e.writeHead(503,{"Content-Type":`text/plain; charset=utf-8`}),e.end(`Screenshot target is not ready.`);return}try{let n=await Ym(t);e.writeHead(200,{"Content-Type":`image/png`,"Cache-Control":`no-store`}),e.end(n)}catch(t){let n=t instanceof Error?t.message:String(t);console.warn(`[present] Screenshot capture failed:`,n),qm(e)}}async function Zm(e,t){if(!t){Rm(e,503,`CLIPBOARD_CAPTURE_TARGET_MISSING`,`Clipboard target is not ready.`);return}try{let n=await Ym(t);e.writeHead(200,{"Content-Type":`image/png`,"Cache-Control":`no-store`}),e.end(n)}catch(t){let n=t instanceof Error?t.message:String(t);console.warn(`[present] Clipboard capture failed:`,n),Rm(e,500,`CLIPBOARD_CAPTURE_FAILED`,`Clipboard capture failed: ${n}`)}}async function Qm(e,t){let n=[];e.on(`data`,e=>n.push(e)),e.on(`end`,async()=>{let e=Buffer.concat(n);if(e.length===0){Rm(t,400,`EMPTY_BODY`,`No image data received.`);return}try{await $m(e),t.writeHead(200,{"Content-Type":`application/json`}),t.end(JSON.stringify({ok:!0}))}catch(e){let n=e instanceof Error?e.message:String(e);console.warn(`[present] System clipboard write failed:`,n),Rm(t,500,`SYSTEM_CLIPBOARD_WRITE_FAILED`,`System clipboard write failed: ${n}`)}}),e.on(`error`,e=>{console.warn(`[present] System clipboard write request error:`,e.message),Rm(t,500,`REQUEST_ERROR`,`Request stream error.`)})}async function $m(e){let t=P(Xn(),`aikit-clipboard-${Date.now()}-${Je(4).toString(`hex`)}.png`);try{if(Pe(t,e),process.platform===`win32`){let e=[`Add-Type -AssemblyName System.Drawing;`,`Add-Type -AssemblyName System.Windows.Forms;`,`$path = '${t.replace(/'/g,`''`)}';`,`$img = [System.Drawing.Image]::FromFile($path);`,`$img2 = [System.Drawing.Bitmap]::FromImage($img);`,`$img.Dispose();`,`[System.Windows.Forms.Clipboard]::SetImage($img2);`,`Start-Sleep -Milliseconds 500;`,`$img2.Dispose();`].join(` `);await new Promise((t,n)=>{Kn(`powershell.exe -NoProfile -STA -Command "${e.replace(/"/g,`\\"`)}"`,{timeout:15e3,windowsHide:!0},e=>{e?n(Error(`PowerShell clipboard write failed: ${e.message}`)):t()})})}else if(process.platform===`darwin`)await new Promise((e,n)=>{Kn(`osascript -e 'set the clipboard to (read (POSIX file "${t}") as picture)'`,{timeout:15e3},t=>{t?n(Error(`macOS clipboard write failed: ${t.message}`)):e()})});else try{await new Promise((e,n)=>{Kn(`wl-copy --type image/png < "${t}" 2>/dev/null`,{timeout:1e4},(t,r)=>{t?n(Error(`wl-copy failed: ${t.message}`)):e(r)})});return}catch{await new Promise((e,n)=>{Kn(`xclip -selection clipboard -t image/png -i "${t}"`,{timeout:15e3},t=>{t?n(Error(`Linux clipboard write failed (tried wl-copy then xclip): ${t.message}. Install wl-clipboard (Wayland) or xclip (X11) for clipboard image support.`)):e()})})}}finally{try{Ne(t)}catch{}}}function eh(e,t){return e.replace(/'\/callback'/g,`'/present/${t}/callback'`).replace(/"\/callback"/g,`"/present/${t}/callback"`)}function th(e,t){return e.replace(/src="\/viewer"/g,`src="/present/${t}/viewer"`)}async function nh(e,t){if(Oh(`<html><body style="font-family:system-ui;padding:2rem;color:#888;text-align:center"><p>Content opened in browser window.</p></body></html>`),e.data!=null&&t.inputSchema){let n=En({data:e.data,schema:t.inputSchema});if(!n.valid){let e=n.errors.map(e=>` ${e.path}: ${e.message}${e.expected?` (expected: ${e.expected}, got: ${e.received})`:``}`).join(`
2909
2909
  `);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=Km(yp(t.resolveHtml(),e.data??null,t.injectId,t.transformData)),r=jm(),i=Je(16).toString(`hex`),a=r.createSession({surfaceId:`viewer`,transport:`viewer`,nonce:i});if(!a.ok)return{content:[{type:`text`,text:`${e.title}\n\nUnable to start local browser transport.`}],structuredContent:{kind:`error`,error:{code:`BROWSER_START_FAILED`,message:a.error.message}},isError:!0};let o=a.session.id,s=fm(`viewer`,e.actions??[],r,o,i),c=th(wr({title:e.title,subtitle:e.description,html:[`<div class="present-viewer-container">`,` <iframe class="present-viewer-iframe" src="/viewer" sandbox="allow-scripts allow-same-origin"></iframe>`,` ${Qh(i)}`,`</div>`].join(`
2910
2910
  `),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(`
2911
2911
  `)],islands:[],payload:void 0,nonce:i,generatedAt:new Date().toISOString(),colorScheme:e.colorScheme,lang:e.lang,dir:e.dir,transport:`browser`,exportPolicy:`local-interactive`,imageExportMode:`browser-server`,footerContentHtml:pm}),o);Om.set(o,{callbackSession:s,html:c,viewerHtml:n,hasClientConnected:!1,createdAt:Date.now()});let l=``;try{l=`http://127.0.0.1:${await Mm()}/present/${o}`}catch(t){return Om.delete(o),r.removeSession(o),{content:[{type:`text`,text:`${e.title}\n\nUnable to start local browser transport.`}],structuredContent:{kind:`error`,error:{code:`BROWSER_START_FAILED`,message:t instanceof Error?t.message:`Unable to start browser transport`}},isError:!0}}return await Um(l),setTimeout(()=>{Om.delete(o),r.removeSession(o)},Sm),{content:[{type:`text`,text:Wm(e,l,`Rendered.`)}],structuredContent:{kind:`rendered`,reason:`no-response-required`}}}async function rh(e){Oh(`<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=jm(),n=Je(16).toString(`hex`),r=Mr(e,{transport:`browser`,registry:Gp,blockVendorScripts:up(),nonce:n}),i=t.createSession({surfaceId:r.surfaceId,transport:`browser`,nonce:n});if(!i.ok)return{content:[{type:`text`,text:`${e.title}\n\nUnable to start local browser transport.`}],structuredContent:{kind:`error`,error:{code:`BROWSER_START_FAILED`,message:i.error.message}},isError:!0};let a=i.session.id,o=fm(r.surfaceId,r.actions,t,a,n),s=bm(r.vendorScripts,`browser`);xm();let c=r.actions.length>0?Bm(r.actions):``,l=r.actions.length>0?Vm(r.actions,o.nonce):``,u=wr({title:e.title,subtitle:e.description,html:[r.html,c,l].filter(Boolean).join(`
@@ -1,4 +1,4 @@
1
- import{n as e,t}from"./curated-manager-D4MOFQ-t.js";import{c as n,f as r,p as i,s as a}from"./startup-maintenance-QrloHssd.js";import{reconfigureForWorkspace as o}from"./config-BS9mkd50.js";import{S as s,_ as c,b as l,c as u,d,f,g as p,h as m,i as h,l as g,m as _,n as ee,o as v,p as te,r as y,s as b,t as x,u as S,v as C,x as w,y as ne}from"./register-tools-Dcut-2_z.js";import{fileURLToPath as T}from"node:url";import{AIKIT_PATHS as re,DISPLAY_SERVER_NAME as E,EMBEDDING_DEFAULTS as D,MODEL_REGISTRY as O,addLogListener as k,computePartitionKey as A,createLogger as j,safeCwdOrHome as M,serializeError as N}from"../../core/dist/index.js";import{existsSync as P,mkdirSync as F,statSync as ie}from"node:fs";import{join as I,resolve as ae}from"node:path";import{FileCache as oe,checkpointList as L,checkpointSave as se,listWorksets as R,stashList as ce}from"../../tools/dist/index.js";import{homedir as z}from"node:os";import{McpServer as le}from"@modelcontextprotocol/sdk/server/mcp.js";import{WasmDiagnostics as B,initializeWasm as ue}from"../../chunker/dist/index.js";import{z as V}from"zod";import{EvolutionCollector as de,PolicyStore as fe}from"../../enterprise-bridge/dist/index.js";import{SqliteGraphStore as pe,allMigrations as me,createSqliteAdapter as H,createStateStore as he,createStore as ge,runMigrations as _e}from"../../store/dist/index.js";import{RootsListChangedNotificationSchema as ve}from"@modelcontextprotocol/sdk/types.js";import{buildFormSchema as U,field as W,normalizeResponse as ye}from"../../elicitation/dist/index.js";import{completable as G}from"@modelcontextprotocol/sdk/server/completable.js";import{EmbedderProxy as be}from"../../embeddings/dist/index.js";import{FileHashCache as xe,IncrementalIndexer as Se}from"../../indexer/dist/index.js";import{AsyncLocalStorage as Ce}from"node:async_hooks";function we(e){function t(){return!!e.server?.getClientCapabilities?.()?.elicitation}async function n(n,r){if(t())try{let t=await e.server.elicitInput({message:n,requestedSchema:r});return ye(t?{action:t.action,content:t.content}:void 0)}catch{return}}return{get available(){return t()},async ask(e){return await n(e.message,e.schema)||{action:`decline`}},async confirm(e){let t=await n(e,U({confirmed:W.confirm(e)}));return t?.action===`accept`&&t.content?.confirmed===!0},async selectOne(e,t){let r=await n(e,U({selection:W.select(`Choose one`,t)}));if(r?.action!==`accept`)return null;let i=r.content?.selection;return typeof i==`string`?i:null},async selectMany(e,t){let r=await n(e,U({selections:W.multi(`Choose one or more`,t)}));if(r?.action!==`accept`)return[];let i=r.content?.selections;return Array.isArray(i)?i:[]},async promptText(e,t){let r=await n(e,U({text:W.text(e,{description:t})}));if(r?.action!==`accept`)return null;let i=r.content?.text;return typeof i==`string`?i:null}}}const Te={debug:`debug`,info:`info`,warn:`warning`,error:`error`};function Ee(e){return k(({level:t,component:n,message:r,data:i})=>{try{Promise.resolve(e.sendLoggingMessage({level:Te[t],logger:n,data:i?{message:r,...i}:r})).catch(()=>{})}catch{}})}const K=3e4,q=new Map;function De(e,t,n){let r=q.get(e);if(r&&Date.now()<r.expires)return Promise.resolve(r.data);let i=n();return Promise.resolve(i).then(n=>(q.set(e,{data:n,expires:Date.now()+t}),n))}function Oe(){q.clear()}function ke(e,t){return De(`curated-paths`,K,async()=>e.listPaths({limit:5e3})).then(e=>e.filter(e=>e.toLowerCase().includes(t.toLowerCase())).slice(0,20))}function Ae(e,t){return De(`file-paths`,K,()=>e.listSourcePaths()).then(e=>e.filter(e=>e.toLowerCase().includes(t.toLowerCase())).slice(0,20))}function je(e,t){return De(`symbol-names`,K,async()=>(await e.findNodes({type:`symbol`,limit:500})).map(e=>e.name)).then(e=>e.filter(e=>e.toLowerCase().includes(t.toLowerCase())).slice(0,20))}function Me(e,t){return t?ce(t).map(e=>e.key).filter(t=>t.toLowerCase().includes(e.toLowerCase())).slice(0,20):[]}function Ne(e){return R().map(e=>e.name).filter(t=>t.toLowerCase().includes(e.toLowerCase())).slice(0,20)}function Pe(e,t){return t?L(t).map(e=>e.label).filter(t=>t.toLowerCase().includes(e.toLowerCase())).slice(0,20):[]}function Fe(e,t,n){if(e.registerPrompt(`ready`,{title:`AI Kit Ready`,description:`AI Kit is ready — quick-start guide for search, onboard, and workflows`},async()=>({messages:[{role:`user`,content:{type:`text`,text:[`AI Kit is ready. Quick start:`,``,'• **New project?** → `onboard({ path: "." })` for full codebase analysis','• **Returning?** → `status({})` then `search({ query: "SESSION CHECKPOINT", origin: "curated" })`','• **Exploring?** → `guide({ goal: "your task" })` for workflow recommendations','• **Quick lookup?** → `search({ query: "your question" })`'].join(`
1
+ import{n as e,t}from"./curated-manager-D4MOFQ-t.js";import{c as n,f as r,p as i,s as a}from"./startup-maintenance-QrloHssd.js";import{reconfigureForWorkspace as o}from"./config-BS9mkd50.js";import{S as s,_ as c,b as l,c as u,d,f,g as p,h as m,i as h,l as g,m as _,n as ee,o as v,p as te,r as y,s as b,t as x,u as S,v as C,x as w,y as ne}from"./register-tools-DvUjjiBA.js";import{fileURLToPath as T}from"node:url";import{AIKIT_PATHS as re,DISPLAY_SERVER_NAME as E,EMBEDDING_DEFAULTS as D,MODEL_REGISTRY as O,addLogListener as k,computePartitionKey as A,createLogger as j,safeCwdOrHome as M,serializeError as N}from"../../core/dist/index.js";import{existsSync as P,mkdirSync as F,statSync as ie}from"node:fs";import{join as I,resolve as ae}from"node:path";import{FileCache as oe,checkpointList as L,checkpointSave as se,listWorksets as R,stashList as ce}from"../../tools/dist/index.js";import{homedir as z}from"node:os";import{McpServer as le}from"@modelcontextprotocol/sdk/server/mcp.js";import{WasmDiagnostics as B,initializeWasm as ue}from"../../chunker/dist/index.js";import{z as V}from"zod";import{EvolutionCollector as de,PolicyStore as fe}from"../../enterprise-bridge/dist/index.js";import{SqliteGraphStore as pe,allMigrations as me,createSqliteAdapter as H,createStateStore as he,createStore as ge,runMigrations as _e}from"../../store/dist/index.js";import{RootsListChangedNotificationSchema as ve}from"@modelcontextprotocol/sdk/types.js";import{buildFormSchema as U,field as W,normalizeResponse as ye}from"../../elicitation/dist/index.js";import{completable as G}from"@modelcontextprotocol/sdk/server/completable.js";import{EmbedderProxy as be}from"../../embeddings/dist/index.js";import{FileHashCache as xe,IncrementalIndexer as Se}from"../../indexer/dist/index.js";import{AsyncLocalStorage as Ce}from"node:async_hooks";function we(e){function t(){return!!e.server?.getClientCapabilities?.()?.elicitation}async function n(n,r){if(t())try{let t=await e.server.elicitInput({message:n,requestedSchema:r});return ye(t?{action:t.action,content:t.content}:void 0)}catch{return}}return{get available(){return t()},async ask(e){return await n(e.message,e.schema)||{action:`decline`}},async confirm(e){let t=await n(e,U({confirmed:W.confirm(e)}));return t?.action===`accept`&&t.content?.confirmed===!0},async selectOne(e,t){let r=await n(e,U({selection:W.select(`Choose one`,t)}));if(r?.action!==`accept`)return null;let i=r.content?.selection;return typeof i==`string`?i:null},async selectMany(e,t){let r=await n(e,U({selections:W.multi(`Choose one or more`,t)}));if(r?.action!==`accept`)return[];let i=r.content?.selections;return Array.isArray(i)?i:[]},async promptText(e,t){let r=await n(e,U({text:W.text(e,{description:t})}));if(r?.action!==`accept`)return null;let i=r.content?.text;return typeof i==`string`?i:null}}}const Te={debug:`debug`,info:`info`,warn:`warning`,error:`error`};function Ee(e){return k(({level:t,component:n,message:r,data:i})=>{try{Promise.resolve(e.sendLoggingMessage({level:Te[t],logger:n,data:i?{message:r,...i}:r})).catch(()=>{})}catch{}})}const K=3e4,q=new Map;function De(e,t,n){let r=q.get(e);if(r&&Date.now()<r.expires)return Promise.resolve(r.data);let i=n();return Promise.resolve(i).then(n=>(q.set(e,{data:n,expires:Date.now()+t}),n))}function Oe(){q.clear()}function ke(e,t){return De(`curated-paths`,K,async()=>e.listPaths({limit:5e3})).then(e=>e.filter(e=>e.toLowerCase().includes(t.toLowerCase())).slice(0,20))}function Ae(e,t){return De(`file-paths`,K,()=>e.listSourcePaths()).then(e=>e.filter(e=>e.toLowerCase().includes(t.toLowerCase())).slice(0,20))}function je(e,t){return De(`symbol-names`,K,async()=>(await e.findNodes({type:`symbol`,limit:500})).map(e=>e.name)).then(e=>e.filter(e=>e.toLowerCase().includes(t.toLowerCase())).slice(0,20))}function Me(e,t){return t?ce(t).map(e=>e.key).filter(t=>t.toLowerCase().includes(e.toLowerCase())).slice(0,20):[]}function Ne(e){return R().map(e=>e.name).filter(t=>t.toLowerCase().includes(e.toLowerCase())).slice(0,20)}function Pe(e,t){return t?L(t).map(e=>e.label).filter(t=>t.toLowerCase().includes(e.toLowerCase())).slice(0,20):[]}function Fe(e,t,n){if(e.registerPrompt(`ready`,{title:`AI Kit Ready`,description:`AI Kit is ready — quick-start guide for search, onboard, and workflows`},async()=>({messages:[{role:`user`,content:{type:`text`,text:[`AI Kit is ready. Quick start:`,``,'• **New project?** → `onboard({ path: "." })` for full codebase analysis','• **Returning?** → `status({})` then `search({ query: "SESSION CHECKPOINT", origin: "curated" })`','• **Exploring?** → `guide({ goal: "your task" })` for workflow recommendations','• **Quick lookup?** → `search({ query: "your question" })`'].join(`
2
2
  `)}}]})),e.registerPrompt(`onboard`,{title:`Onboard Codebase`,description:`Analyze the codebase for first-time onboarding — runs all analyzers and produces a knowledge summary`,argsSchema:{path:V.string().optional().describe(`Path to analyze (default: workspace root)`)}},async({path:e})=>({messages:[{role:`user`,content:{type:`text`,text:[`Run the full onboarding workflow for "${e??`.`}"`,``,`1. \`onboard({ path: "${e??`.`}" })\` — full codebase analysis`,`2. \`produce_knowledge({ path: "${e??`.`}" })\` — generate synthesis`,'3. `knowledge({ action: "remember", ... })` for key curated entries',"4. `status` to verify index health"].join(`
3
3
  `)}}]})),e.registerPrompt(`sessionStart`,{title:`Start AI Kit Session`,description:`Initialize an AI Kit session — check status, list knowledge, and resume from last checkpoint`},async()=>({messages:[{role:`user`,content:{type:`text`,text:[`Run the session start protocol:`,``,"1. `status({})` — check AI Kit health and onboard state",'2. `knowledge({ action: "list" })` — see stored knowledge entries','3. `search({ query: "SESSION CHECKPOINT", origin: "curated" })` — resume prior work'].join(`
4
4
  `)}}]})),e.registerPrompt(`sessionEnd`,{title:`End AI Kit Session`,description:`Persist decisions and create a session checkpoint before ending`,argsSchema:{summary:V.string().describe(`Brief summary of decisions made, blockers encountered, and next steps`)}},async({summary:e})=>({messages:[{role:`user`,content:{type:`text`,text:[`Run the session end protocol:`,``,'1. `knowledge({ action: "remember", title: "Session checkpoint: '+e.slice(0,60)+`...", content: "`+e.replace(/"/g,`\\"`)+'", category: "session" })` — persist findings',n===`smart`?`2. Smart indexing is active — index refreshes automatically`:"2. `reindex({})` — refresh search index if files changed",`3. Confirm session data saved`].join(`
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{c as e,f as t,p as n,s as r}from"./startup-maintenance-D7tKqECM.js";import{n as i,t as a}from"./bin.js";import{reconfigureForWorkspace as o}from"./config-CkXCQx7E.js";import{S as s,_ as c,b as l,c as u,d,f,g as p,h as m,i as h,l as g,m as _,n as ee,o as v,p as te,r as y,s as b,t as x,u as S,v as C,x as w,y as ne}from"./register-tools-nx2aner6.js";import{fileURLToPath as T}from"node:url";import{AIKIT_PATHS as re,DISPLAY_SERVER_NAME as E,EMBEDDING_DEFAULTS as D,MODEL_REGISTRY as O,addLogListener as k,computePartitionKey as A,createLogger as j,safeCwdOrHome as M,serializeError as N}from"../../core/dist/index.js";import{existsSync as P,mkdirSync as F,statSync as ie}from"node:fs";import{join as I,resolve as ae}from"node:path";import{FileCache as oe,checkpointList as L,checkpointSave as se,listWorksets as R,stashList as ce}from"../../tools/dist/index.js";import{homedir as z}from"node:os";import{McpServer as le}from"@modelcontextprotocol/sdk/server/mcp.js";import{WasmDiagnostics as B,initializeWasm as ue}from"../../chunker/dist/index.js";import{z as V}from"zod";import{EvolutionCollector as de,PolicyStore as fe}from"../../enterprise-bridge/dist/index.js";import{SqliteGraphStore as pe,allMigrations as me,createSqliteAdapter as H,createStateStore as he,createStore as ge,runMigrations as _e}from"../../store/dist/index.js";import{RootsListChangedNotificationSchema as ve}from"@modelcontextprotocol/sdk/types.js";import{buildFormSchema as U,field as W,normalizeResponse as ye}from"../../elicitation/dist/index.js";import{completable as G}from"@modelcontextprotocol/sdk/server/completable.js";import{EmbedderProxy as be}from"../../embeddings/dist/index.js";import{FileHashCache as xe,IncrementalIndexer as Se}from"../../indexer/dist/index.js";import{AsyncLocalStorage as Ce}from"node:async_hooks";function we(e){function t(){return!!e.server?.getClientCapabilities?.()?.elicitation}async function n(n,r){if(t())try{let t=await e.server.elicitInput({message:n,requestedSchema:r});return ye(t?{action:t.action,content:t.content}:void 0)}catch{return}}return{get available(){return t()},async ask(e){return await n(e.message,e.schema)||{action:`decline`}},async confirm(e){let t=await n(e,U({confirmed:W.confirm(e)}));return t?.action===`accept`&&t.content?.confirmed===!0},async selectOne(e,t){let r=await n(e,U({selection:W.select(`Choose one`,t)}));if(r?.action!==`accept`)return null;let i=r.content?.selection;return typeof i==`string`?i:null},async selectMany(e,t){let r=await n(e,U({selections:W.multi(`Choose one or more`,t)}));if(r?.action!==`accept`)return[];let i=r.content?.selections;return Array.isArray(i)?i:[]},async promptText(e,t){let r=await n(e,U({text:W.text(e,{description:t})}));if(r?.action!==`accept`)return null;let i=r.content?.text;return typeof i==`string`?i:null}}}const Te={debug:`debug`,info:`info`,warn:`warning`,error:`error`};function Ee(e){return k(({level:t,component:n,message:r,data:i})=>{try{Promise.resolve(e.sendLoggingMessage({level:Te[t],logger:n,data:i?{message:r,...i}:r})).catch(()=>{})}catch{}})}const K=3e4,q=new Map;function De(e,t,n){let r=q.get(e);if(r&&Date.now()<r.expires)return Promise.resolve(r.data);let i=n();return Promise.resolve(i).then(n=>(q.set(e,{data:n,expires:Date.now()+t}),n))}function Oe(){q.clear()}function ke(e,t){return De(`curated-paths`,K,async()=>e.listPaths({limit:5e3})).then(e=>e.filter(e=>e.toLowerCase().includes(t.toLowerCase())).slice(0,20))}function Ae(e,t){return De(`file-paths`,K,()=>e.listSourcePaths()).then(e=>e.filter(e=>e.toLowerCase().includes(t.toLowerCase())).slice(0,20))}function je(e,t){return De(`symbol-names`,K,async()=>(await e.findNodes({type:`symbol`,limit:500})).map(e=>e.name)).then(e=>e.filter(e=>e.toLowerCase().includes(t.toLowerCase())).slice(0,20))}function Me(e,t){return t?ce(t).map(e=>e.key).filter(t=>t.toLowerCase().includes(e.toLowerCase())).slice(0,20):[]}function Ne(e){return R().map(e=>e.name).filter(t=>t.toLowerCase().includes(e.toLowerCase())).slice(0,20)}function Pe(e,t){return t?L(t).map(e=>e.label).filter(t=>t.toLowerCase().includes(e.toLowerCase())).slice(0,20):[]}function Fe(e,t,n){if(e.registerPrompt(`ready`,{title:`AI Kit Ready`,description:`AI Kit is ready — quick-start guide for search, onboard, and workflows`},async()=>({messages:[{role:`user`,content:{type:`text`,text:[`AI Kit is ready. Quick start:`,``,'• **New project?** → `onboard({ path: "." })` for full codebase analysis','• **Returning?** → `status({})` then `search({ query: "SESSION CHECKPOINT", origin: "curated" })`','• **Exploring?** → `guide({ goal: "your task" })` for workflow recommendations','• **Quick lookup?** → `search({ query: "your question" })`'].join(`
2
+ import{c as e,f as t,p as n,s as r}from"./startup-maintenance-D7tKqECM.js";import{n as i,t as a}from"./bin.js";import{reconfigureForWorkspace as o}from"./config-CkXCQx7E.js";import{S as s,_ as c,b as l,c as u,d,f,g as p,h as m,i as h,l as g,m as _,n as ee,o as v,p as te,r as y,s as b,t as x,u as S,v as C,x as w,y as ne}from"./register-tools-DrCEk_fv.js";import{fileURLToPath as T}from"node:url";import{AIKIT_PATHS as re,DISPLAY_SERVER_NAME as E,EMBEDDING_DEFAULTS as D,MODEL_REGISTRY as O,addLogListener as k,computePartitionKey as A,createLogger as j,safeCwdOrHome as M,serializeError as N}from"../../core/dist/index.js";import{existsSync as P,mkdirSync as F,statSync as ie}from"node:fs";import{join as I,resolve as ae}from"node:path";import{FileCache as oe,checkpointList as L,checkpointSave as se,listWorksets as R,stashList as ce}from"../../tools/dist/index.js";import{homedir as z}from"node:os";import{McpServer as le}from"@modelcontextprotocol/sdk/server/mcp.js";import{WasmDiagnostics as B,initializeWasm as ue}from"../../chunker/dist/index.js";import{z as V}from"zod";import{EvolutionCollector as de,PolicyStore as fe}from"../../enterprise-bridge/dist/index.js";import{SqliteGraphStore as pe,allMigrations as me,createSqliteAdapter as H,createStateStore as he,createStore as ge,runMigrations as _e}from"../../store/dist/index.js";import{RootsListChangedNotificationSchema as ve}from"@modelcontextprotocol/sdk/types.js";import{buildFormSchema as U,field as W,normalizeResponse as ye}from"../../elicitation/dist/index.js";import{completable as G}from"@modelcontextprotocol/sdk/server/completable.js";import{EmbedderProxy as be}from"../../embeddings/dist/index.js";import{FileHashCache as xe,IncrementalIndexer as Se}from"../../indexer/dist/index.js";import{AsyncLocalStorage as Ce}from"node:async_hooks";function we(e){function t(){return!!e.server?.getClientCapabilities?.()?.elicitation}async function n(n,r){if(t())try{let t=await e.server.elicitInput({message:n,requestedSchema:r});return ye(t?{action:t.action,content:t.content}:void 0)}catch{return}}return{get available(){return t()},async ask(e){return await n(e.message,e.schema)||{action:`decline`}},async confirm(e){let t=await n(e,U({confirmed:W.confirm(e)}));return t?.action===`accept`&&t.content?.confirmed===!0},async selectOne(e,t){let r=await n(e,U({selection:W.select(`Choose one`,t)}));if(r?.action!==`accept`)return null;let i=r.content?.selection;return typeof i==`string`?i:null},async selectMany(e,t){let r=await n(e,U({selections:W.multi(`Choose one or more`,t)}));if(r?.action!==`accept`)return[];let i=r.content?.selections;return Array.isArray(i)?i:[]},async promptText(e,t){let r=await n(e,U({text:W.text(e,{description:t})}));if(r?.action!==`accept`)return null;let i=r.content?.text;return typeof i==`string`?i:null}}}const Te={debug:`debug`,info:`info`,warn:`warning`,error:`error`};function Ee(e){return k(({level:t,component:n,message:r,data:i})=>{try{Promise.resolve(e.sendLoggingMessage({level:Te[t],logger:n,data:i?{message:r,...i}:r})).catch(()=>{})}catch{}})}const K=3e4,q=new Map;function De(e,t,n){let r=q.get(e);if(r&&Date.now()<r.expires)return Promise.resolve(r.data);let i=n();return Promise.resolve(i).then(n=>(q.set(e,{data:n,expires:Date.now()+t}),n))}function Oe(){q.clear()}function ke(e,t){return De(`curated-paths`,K,async()=>e.listPaths({limit:5e3})).then(e=>e.filter(e=>e.toLowerCase().includes(t.toLowerCase())).slice(0,20))}function Ae(e,t){return De(`file-paths`,K,()=>e.listSourcePaths()).then(e=>e.filter(e=>e.toLowerCase().includes(t.toLowerCase())).slice(0,20))}function je(e,t){return De(`symbol-names`,K,async()=>(await e.findNodes({type:`symbol`,limit:500})).map(e=>e.name)).then(e=>e.filter(e=>e.toLowerCase().includes(t.toLowerCase())).slice(0,20))}function Me(e,t){return t?ce(t).map(e=>e.key).filter(t=>t.toLowerCase().includes(e.toLowerCase())).slice(0,20):[]}function Ne(e){return R().map(e=>e.name).filter(t=>t.toLowerCase().includes(e.toLowerCase())).slice(0,20)}function Pe(e,t){return t?L(t).map(e=>e.label).filter(t=>t.toLowerCase().includes(e.toLowerCase())).slice(0,20):[]}function Fe(e,t,n){if(e.registerPrompt(`ready`,{title:`AI Kit Ready`,description:`AI Kit is ready — quick-start guide for search, onboard, and workflows`},async()=>({messages:[{role:`user`,content:{type:`text`,text:[`AI Kit is ready. Quick start:`,``,'• **New project?** → `onboard({ path: "." })` for full codebase analysis','• **Returning?** → `status({})` then `search({ query: "SESSION CHECKPOINT", origin: "curated" })`','• **Exploring?** → `guide({ goal: "your task" })` for workflow recommendations','• **Quick lookup?** → `search({ query: "your question" })`'].join(`
3
3
  `)}}]})),e.registerPrompt(`onboard`,{title:`Onboard Codebase`,description:`Analyze the codebase for first-time onboarding — runs all analyzers and produces a knowledge summary`,argsSchema:{path:V.string().optional().describe(`Path to analyze (default: workspace root)`)}},async({path:e})=>({messages:[{role:`user`,content:{type:`text`,text:[`Run the full onboarding workflow for "${e??`.`}"`,``,`1. \`onboard({ path: "${e??`.`}" })\` — full codebase analysis`,`2. \`produce_knowledge({ path: "${e??`.`}" })\` — generate synthesis`,'3. `knowledge({ action: "remember", ... })` for key curated entries',"4. `status` to verify index health"].join(`
4
4
  `)}}]})),e.registerPrompt(`sessionStart`,{title:`Start AI Kit Session`,description:`Initialize an AI Kit session — check status, list knowledge, and resume from last checkpoint`},async()=>({messages:[{role:`user`,content:{type:`text`,text:[`Run the session start protocol:`,``,"1. `status({})` — check AI Kit health and onboard state",'2. `knowledge({ action: "list" })` — see stored knowledge entries','3. `search({ query: "SESSION CHECKPOINT", origin: "curated" })` — resume prior work'].join(`
5
5
  `)}}]})),e.registerPrompt(`sessionEnd`,{title:`End AI Kit Session`,description:`Persist decisions and create a session checkpoint before ending`,argsSchema:{summary:V.string().describe(`Brief summary of decisions made, blockers encountered, and next steps`)}},async({summary:e})=>({messages:[{role:`user`,content:{type:`text`,text:[`Run the session end protocol:`,``,'1. `knowledge({ action: "remember", title: "Session checkpoint: '+e.slice(0,60)+`...", content: "`+e.replace(/"/g,`\\"`)+'", category: "session" })` — persist findings',n===`smart`?`2. Smart indexing is active — index refreshes automatically`:"2. `reindex({})` — refresh search index if files changed",`3. Confirm session data saved`].join(`
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- import{n as e,t}from"./startup-maintenance-D7tKqECM.js";import{a as n,i as r,o as i,s as a}from"./bin.js";import{t as o}from"./register-tools-nx2aner6.js";import{createLogger as s,serializeError as c,setDetailedErrorLoggingEnabled as l}from"../../core/dist/index.js";import{randomUUID as u}from"node:crypto";const d=`__pending__:`;function f(e){return e.startsWith(d)}function p(e){let t=e.headers[`mcp-session-id`];return Array.isArray(t)?t[0]:t}function m(e,t,n,r){e.status(t).json({jsonrpc:`2.0`,error:{code:n,message:r},id:null})}var h=class{options;runtimes=new Map;maxSessions;sessionTimeoutMs;now;constructor(e){this.options=e,this.maxSessions=e.maxSessions??8,this.sessionTimeoutMs=(e.sessionTimeoutMinutes??30)*60*1e3,this.now=e.now??(()=>Date.now())}hasSession(e){return this.runtimes.has(e)}getSessionCount(){return this.runtimes.size}async handleRequest(e,t,n=e.body){let r=p(e),i=r?this.runtimes.get(r):void 0;if(r&&!i){m(t,404,-32001,`Session not found`);return}if(!i){if(e.method!==`POST`){m(t,400,-32e3,`Session required`);return}if(i=await this.createRuntime(t),!i)return}await this.withRuntimeLock(i,async()=>{await i.transport.handleRequest(e,t,n),i.lastAccessAt=this.now();let r=i.transport.sessionId??i.id;e.method!==`DELETE`&&!f(r)&&this.options.onSessionActivity?.(r),e.method===`DELETE`&&!f(r)&&await this.closeSession(r,{closeTransport:!1})})}async closeExpiredSessions(){let e=[...this.runtimes.values()].filter(e=>this.now()-e.lastAccessAt>=this.sessionTimeoutMs).map(e=>e.id);for(let t of e)await this.closeSession(t);return e.length}async closeSession(e,t={}){let n=this.runtimes.get(e);return n?(this.runtimes.delete(e),t.notifySessionEnd!==!1&&!f(e)&&this.options.onSessionEnd?.(e),t.closeTransport!==!1&&await n.transport.close().catch(()=>void 0),await n.server.close().catch(()=>void 0),!0):!1}async closeAll(){let e=[...this.runtimes.keys()];for(let t of e)await this.closeSession(t)}async createRuntime(e){if(await this.closeExpiredSessions(),this.runtimes.size>=this.maxSessions){m(e,503,-32003,`Session capacity reached`);return}let t=this.now(),n=await this.options.createServer(),r={id:`${d}${u()}`,transport:void 0,createdAt:t,lastAccessAt:t,server:n,requestChain:Promise.resolve()},i=this.options.createTransport({sessionIdGenerator:()=>u(),onsessioninitialized:async e=>{this.runtimes.delete(r.id),r.id=e,this.runtimes.set(e,r),this.options.onSessionStart?.(e)},onsessionclosed:async e=>{e&&await this.closeSession(e,{closeTransport:!1})}});return r.transport=i,i.onclose=()=>{let e=r.transport.sessionId??r.id;this.closeSession(e,{closeTransport:!1})},this.runtimes.set(r.id,r),await n.connect(i),r}async withRuntimeLock(e,t){let n=e.requestChain,r;e.requestChain=new Promise(e=>{r=e}),await n;try{await t()}finally{r()}}};function g(e){let t=e.includes(`T`)?e:`${e.replace(` `,`T`)}Z`;return Date.parse(t)}var _=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),Promise.resolve(this.options.onSessionEndMaintenance?.(e)).catch(()=>{})}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.getStaleSessionIds();for(let t of e)this.options.onBeforeSessionDelete?.(t),Promise.resolve(this.options.onSessionEndMaintenance?.(t)).catch(()=>{}),this.stateStore.sessionDelete(t);return e.length}stop(){this.gcTimer&&=(clearInterval(this.gcTimer),null)}getActiveSessions(){return this.stateStore.sessionList().length}listSessions(){return this.stateStore.sessionList()}getStaleSessionIds(e=Date.now()){let t=(this.options.staleTimeoutMinutes??30)*60*1e3;return this.stateStore.sessionList().filter(n=>{let r=g(n.lastActivity);return Number.isFinite(r)&&e-r>=t}).map(e=>e.sessionId)}};const v=s(`server`);async function y(s,d){let[{default:f},{loadConfig:p,resolveIndexMode:m},{registerDashboardRoutes:g,resolveDashboardDir:y},{registerSettingsRoutes:b,resolveSettingsDir:x},{createSettingsRouter:S},{authMiddleware:C,getOrCreateToken:w}]=await Promise.all([import(`express`),import(`./config-CkXCQx7E.js`),import(`./dashboard-static-CVRj5Cbv.js`),import(`./settings-static-VnUkp9iU.js`),import(`./routes-Ct7q5jrL.js`),import(`./auth-bEP-6uqy.js`)]),T=p();l(T.logging?.errorDetails===!0),T.configError&&v.warn(`Config load failure`,{error:T.configError}),v.info(`Config loaded`,{sourceCount:T.sources.length,storePath:T.store.path});let E=f();E.use(f.json({limit:`1mb`}));let D=Number(d),O=`http://localhost:${D}`,k=process.env.AIKIT_CORS_ORIGIN??O,A=process.env.AIKIT_ALLOW_ANY_ORIGIN===`true`,j=i(`AIKIT_HTTP_MAX_SESSIONS`,8),M=i(`AIKIT_HTTP_SESSION_TIMEOUT_MINUTES`,30),N=i(`AIKIT_HTTP_SESSION_GC_INTERVAL_MINUTES`,5),P=r({limit:100,windowMs:6e4}),F=!1;E.use((e,t,n)=>{let r=Array.isArray(e.headers.origin)?e.headers.origin[0]:e.headers.origin,i=a({requestOrigin:r,configuredOrigin:k,allowAnyOrigin:A,fallbackOrigin:O});if(i.warn&&!F&&(F=!0,v.warn(`Rejected non-local CORS origin while AIKIT_CORS_ORIGIN=*`,{origin:r,allowAnyOriginEnv:`AIKIT_ALLOW_ANY_ORIGIN=true`})),r&&!i.allowOrigin){t.status(403).json({error:`Origin not allowed`});return}if(i.allowOrigin&&t.setHeader(`Access-Control-Allow-Origin`,i.allowOrigin),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 I=w();E.use(C(I)),E.use(`/mcp`,(e,t,r)=>{let i=n(e)??e.ip??e.socket.remoteAddress??`anonymous`;if(P.allow(i)){r();return}let a=Math.max(1,Math.ceil(P.getRetryAfterMs(i)/1e3));t.setHeader(`Retry-After`,String(a)),t.status(429).json({jsonrpc:`2.0`,error:{code:-32003,message:`Rate limit exceeded`},id:null})});let L;E.use(`/mcp`,(e,t,n)=>{if(!L){let t=e.headers[`x-workspace-root`];typeof t==`string`&&t.length>0&&(L=t,v.debug(`Captured workspace root from proxy header`,{wsRoot:t}))}n()}),g(E,y(),v);let R=new Date().toISOString();E.use(`/settings/api`,S({log:v,mcpInfo:()=>({transport:`http`,port:D,pid:process.pid,startedAt:R})})),b(E,x(),v),E.get(`/health`,(e,t)=>{t.json({status:`ok`})});let z=!1,B=null,V=null,H=null,U=null,W=null,G=null,K=null,q=null,J=Promise.resolve(),Y=async(e,t)=>{if(!z||!H||!U){t.status(503).json({jsonrpc:`2.0`,error:{code:-32603,message:`Server initializing — please retry in a few seconds`},id:null});return}let r=J,i;J=new Promise(e=>{i=e});let a={POST:6e4,GET:1e4,DELETE:1e4}[e.method]??3e4;if(!await Promise.race([r.then(()=>!0),new Promise(t=>{let n=setTimeout(()=>{v.warn(`mcpLock timed out waiting for previous request, resetting lock chain`,{method:e.method,timeoutMs:a}),t(!1)},a);n.unref&&n.unref()})])&&(J=Promise.resolve(),i=()=>{},G)){let e=G;G=null,K=null,e.close().catch(()=>{})}try{let r=n(e);if(!G){if(r){t.status(404).json({jsonrpc:`2.0`,error:{code:-32001,message:`Session not found`},id:null});return}let e=new U({sessionIdGenerator:()=>u(),onsessioninitialized:async e=>{K=e,V?.onSessionStart(e,{transport:`http`})},onsessionclosed:async e=>{e&&V?.onSessionEnd(e),K=null}});e.onclose=()=>{G===e&&(G=null),K===e.sessionId&&(K=null)},G=e,await H.connect(e)}let i=G;await i.handleRequest(e,t,e.body),e.method!==`DELETE`&&(!r&&i.sessionId?(K=i.sessionId,V?.onSessionStart(i.sessionId,{transport:`http`}),V?.onSessionActivity(i.sessionId)):r&&V?.onSessionActivity(r))}catch(e){if(v.error(`MCP handler error`,c(e)),!t.headersSent){let n=e instanceof Error?e.message:String(e),r=n.includes(`Not Acceptable`);t.status(r?406:500).json({jsonrpc:`2.0`,error:{code:r?-32e3:-32603,message:r?n:`Internal server error`},id:null})}}finally{i()}},X=async(e,t)=>{let r=n(e);if(W&&(!G||r!==K)){await W.handleRequest(e,t,e.body);return}await Y(e,t)};E.post(`/mcp`,X),E.get(`/mcp`,X),E.delete(`/mcp`,X);let Z=E.listen(D,`127.0.0.1`,()=>{v.info(`MCP server listening`,{url:`http://127.0.0.1:${D}/mcp`,port:D}),setTimeout(async()=>{try{typeof L==`string`&&L.length>0&&(T.sources[0]={path:L,excludePatterns:T.sources[0]?.excludePatterns??[]},T.allRoots=[L],v.debug(`Workspace root applied from proxy header`,{wsRoot:L}));let[{createLazyServer:n,createMcpServer:r,ALL_TOOL_NAMES:i},{StreamableHTTPServerTransport:a},{checkForUpdates:o,autoUpgradeScaffold:l}]=await Promise.all([import(`./server-CcYHQCrv.js`),import(`@modelcontextprotocol/sdk/server/streamableHttp.js`),import(`./startup-maintenance-D7tKqECM.js`).then(e=>e.u)]);o(),l(),setInterval(o,1440*60*1e3).unref();let u=!1,d=m(T),f=n(T,d);q=async()=>{f.aikit&&await Promise.all([f.aikit.embedder.shutdown?.().catch(()=>{})??Promise.resolve(),f.aikit.graphStore.close().catch(()=>{}),f.aikit.closeStateStore?.().catch(()=>{})??Promise.resolve(),f.aikit.store.close().catch(()=>{})])},H=f.server,U=a,z=!0,v.debug(`MCP server configured (lazy — AI Kit initializing in background)`,{toolCount:i.length,resourceCount:2}),f.startInit(),f.ready.then(async()=>{try{if(!f.aikit)throw Error(`AI Kit components are not available after initialization`);V=new _(f.aikit.stateStore,{staleTimeoutMinutes:M,gcIntervalMinutes:N,onBeforeSessionDelete:e=>{if(K===e&&G){let e=G;G=null,K=null,e.close().catch(()=>void 0)}W?.closeSession(e,{notifySessionEnd:!1})},onSessionEndMaintenance:async()=>{if(!f.aikit?.curated||!f.aikit?.stateStore)return;let{pruneLessons:e}=await import(`./startup-maintenance-D7tKqECM.js`).then(e=>e.x),t=await e(f.aikit.curated,f.aikit.stateStore,{dryRun:!1});t.pruned.length>0&&v.info(`Session-end lesson prune`,{pruned:t.pruned.length})}}),W=new h({createServer:()=>{if(!f.aikit)throw Error(`AI Kit components are not available after initialization`);return r(f.aikit,T)},createTransport:e=>new a(e),maxSessions:j,sessionTimeoutMinutes:M,onSessionStart:e=>V?.onSessionStart(e,{transport:`http`}),onSessionActivity:e=>V?.onSessionActivity(e),onSessionEnd:e=>V?.onSessionEnd(e)}),V.startGC(),K&&(V.onSessionStart(K,{transport:`http`}),V.onSessionActivity(K)),v.info(`HTTP session runtime ready`,{maxSessions:j,sessionTimeoutMinutes:M,gcIntervalMinutes:N})}catch(e){v.error(`Failed to start session manager`,c(e)),z=!1,u=!0,H=null,U=null,q=null}}),d===`auto`?f.ready.then(async()=>{try{let e=T.sources.map(e=>e.path).join(`, `);v.info(`Running initial index`,{sourcePaths:e}),await f.runInitialIndex(),v.info(`Initial index complete`)}catch(t){v.error(`Initial index failed; will retry on aikit_reindex`,e(s,t))}}):d===`smart`?u||f.ready.then(async()=>{try{if(!f.aikit)throw Error(`AI Kit components are not available after initialization`);let{SmartIndexScheduler:e}=await import(`../../indexer/dist/index.js`),t=new e(f.aikit.indexer,T,f.aikit.store),n=f.aikit.store;B=t,t.start(),n.onBeforeClose&&n.onBeforeClose(()=>t.stop()),f.setSmartScheduler(t),v.debug(`Smart index scheduler started (HTTP mode)`)}catch(t){v.error(`Failed to start smart index scheduler`,e(s,t))}}):v.info(`Initial full indexing skipped in HTTP mode`,{indexMode:d}),f.ready.catch(t=>{v.error(`AI Kit initialization failed`,e(s,t)),z=!1,u=!0,H=null,U=null,q=null}),t(f.ready,()=>f.aikit?{curated:f.aikit.curated,stateStore:f.aikit.stateStore}:null,s)}catch(t){v.error(`Failed to load server modules`,e(s,t)),z=!1,q=null}},100)}),Q=!1,$=async e=>{Q||(Q=!0,v.info(`Shutdown signal received`,{signal:e}),o(),B?.stop(),V?.stop(),await import(`../../tools/dist/index.js`).then(({processStopAll:e})=>e()).catch(()=>{}),await W?.closeAll().catch(()=>void 0),K&&V?.onSessionEnd(K),G&&(await G.close().catch(()=>void 0),G=null,K=null),Z.close(),H&&await H.close(),await q?.().catch(()=>void 0),process.exit(0))};process.on(`SIGINT`,()=>$(`SIGINT`)),process.on(`SIGTERM`,()=>$(`SIGTERM`))}export{y as startHttpMode};
2
+ import{n as e,t}from"./startup-maintenance-D7tKqECM.js";import{a as n,i as r,o as i,s as a}from"./bin.js";import{t as o}from"./register-tools-DrCEk_fv.js";import{createLogger as s,serializeError as c,setDetailedErrorLoggingEnabled as l}from"../../core/dist/index.js";import{randomUUID as u}from"node:crypto";const d=`__pending__:`;function f(e){return e.startsWith(d)}function p(e){let t=e.headers[`mcp-session-id`];return Array.isArray(t)?t[0]:t}function m(e,t,n,r){e.status(t).json({jsonrpc:`2.0`,error:{code:n,message:r},id:null})}var h=class{options;runtimes=new Map;maxSessions;sessionTimeoutMs;now;constructor(e){this.options=e,this.maxSessions=e.maxSessions??8,this.sessionTimeoutMs=(e.sessionTimeoutMinutes??30)*60*1e3,this.now=e.now??(()=>Date.now())}hasSession(e){return this.runtimes.has(e)}getSessionCount(){return this.runtimes.size}async handleRequest(e,t,n=e.body){let r=p(e),i=r?this.runtimes.get(r):void 0;if(r&&!i){m(t,404,-32001,`Session not found`);return}if(!i){if(e.method!==`POST`){m(t,400,-32e3,`Session required`);return}if(i=await this.createRuntime(t),!i)return}await this.withRuntimeLock(i,async()=>{await i.transport.handleRequest(e,t,n),i.lastAccessAt=this.now();let r=i.transport.sessionId??i.id;e.method!==`DELETE`&&!f(r)&&this.options.onSessionActivity?.(r),e.method===`DELETE`&&!f(r)&&await this.closeSession(r,{closeTransport:!1})})}async closeExpiredSessions(){let e=[...this.runtimes.values()].filter(e=>this.now()-e.lastAccessAt>=this.sessionTimeoutMs).map(e=>e.id);for(let t of e)await this.closeSession(t);return e.length}async closeSession(e,t={}){let n=this.runtimes.get(e);return n?(this.runtimes.delete(e),t.notifySessionEnd!==!1&&!f(e)&&this.options.onSessionEnd?.(e),t.closeTransport!==!1&&await n.transport.close().catch(()=>void 0),await n.server.close().catch(()=>void 0),!0):!1}async closeAll(){let e=[...this.runtimes.keys()];for(let t of e)await this.closeSession(t)}async createRuntime(e){if(await this.closeExpiredSessions(),this.runtimes.size>=this.maxSessions){m(e,503,-32003,`Session capacity reached`);return}let t=this.now(),n=await this.options.createServer(),r={id:`${d}${u()}`,transport:void 0,createdAt:t,lastAccessAt:t,server:n,requestChain:Promise.resolve()},i=this.options.createTransport({sessionIdGenerator:()=>u(),onsessioninitialized:async e=>{this.runtimes.delete(r.id),r.id=e,this.runtimes.set(e,r),this.options.onSessionStart?.(e)},onsessionclosed:async e=>{e&&await this.closeSession(e,{closeTransport:!1})}});return r.transport=i,i.onclose=()=>{let e=r.transport.sessionId??r.id;this.closeSession(e,{closeTransport:!1})},this.runtimes.set(r.id,r),await n.connect(i),r}async withRuntimeLock(e,t){let n=e.requestChain,r;e.requestChain=new Promise(e=>{r=e}),await n;try{await t()}finally{r()}}};function g(e){let t=e.includes(`T`)?e:`${e.replace(` `,`T`)}Z`;return Date.parse(t)}var _=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),Promise.resolve(this.options.onSessionEndMaintenance?.(e)).catch(()=>{})}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.getStaleSessionIds();for(let t of e)this.options.onBeforeSessionDelete?.(t),Promise.resolve(this.options.onSessionEndMaintenance?.(t)).catch(()=>{}),this.stateStore.sessionDelete(t);return e.length}stop(){this.gcTimer&&=(clearInterval(this.gcTimer),null)}getActiveSessions(){return this.stateStore.sessionList().length}listSessions(){return this.stateStore.sessionList()}getStaleSessionIds(e=Date.now()){let t=(this.options.staleTimeoutMinutes??30)*60*1e3;return this.stateStore.sessionList().filter(n=>{let r=g(n.lastActivity);return Number.isFinite(r)&&e-r>=t}).map(e=>e.sessionId)}};const v=s(`server`);async function y(s,d){let[{default:f},{loadConfig:p,resolveIndexMode:m},{registerDashboardRoutes:g,resolveDashboardDir:y},{registerSettingsRoutes:b,resolveSettingsDir:x},{createSettingsRouter:S},{authMiddleware:C,getOrCreateToken:w}]=await Promise.all([import(`express`),import(`./config-CkXCQx7E.js`),import(`./dashboard-static-CVRj5Cbv.js`),import(`./settings-static-VnUkp9iU.js`),import(`./routes-Ct7q5jrL.js`),import(`./auth-bEP-6uqy.js`)]),T=p();l(T.logging?.errorDetails===!0),T.configError&&v.warn(`Config load failure`,{error:T.configError}),v.info(`Config loaded`,{sourceCount:T.sources.length,storePath:T.store.path});let E=f();E.use(f.json({limit:`1mb`}));let D=Number(d),O=`http://localhost:${D}`,k=process.env.AIKIT_CORS_ORIGIN??O,A=process.env.AIKIT_ALLOW_ANY_ORIGIN===`true`,j=i(`AIKIT_HTTP_MAX_SESSIONS`,8),M=i(`AIKIT_HTTP_SESSION_TIMEOUT_MINUTES`,30),N=i(`AIKIT_HTTP_SESSION_GC_INTERVAL_MINUTES`,5),P=r({limit:100,windowMs:6e4}),F=!1;E.use((e,t,n)=>{let r=Array.isArray(e.headers.origin)?e.headers.origin[0]:e.headers.origin,i=a({requestOrigin:r,configuredOrigin:k,allowAnyOrigin:A,fallbackOrigin:O});if(i.warn&&!F&&(F=!0,v.warn(`Rejected non-local CORS origin while AIKIT_CORS_ORIGIN=*`,{origin:r,allowAnyOriginEnv:`AIKIT_ALLOW_ANY_ORIGIN=true`})),r&&!i.allowOrigin){t.status(403).json({error:`Origin not allowed`});return}if(i.allowOrigin&&t.setHeader(`Access-Control-Allow-Origin`,i.allowOrigin),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 I=w();E.use(C(I)),E.use(`/mcp`,(e,t,r)=>{let i=n(e)??e.ip??e.socket.remoteAddress??`anonymous`;if(P.allow(i)){r();return}let a=Math.max(1,Math.ceil(P.getRetryAfterMs(i)/1e3));t.setHeader(`Retry-After`,String(a)),t.status(429).json({jsonrpc:`2.0`,error:{code:-32003,message:`Rate limit exceeded`},id:null})});let L;E.use(`/mcp`,(e,t,n)=>{if(!L){let t=e.headers[`x-workspace-root`];typeof t==`string`&&t.length>0&&(L=t,v.debug(`Captured workspace root from proxy header`,{wsRoot:t}))}n()}),g(E,y(),v);let R=new Date().toISOString();E.use(`/settings/api`,S({log:v,mcpInfo:()=>({transport:`http`,port:D,pid:process.pid,startedAt:R})})),b(E,x(),v),E.get(`/health`,(e,t)=>{t.json({status:`ok`})});let z=!1,B=null,V=null,H=null,U=null,W=null,G=null,K=null,q=null,J=Promise.resolve(),Y=async(e,t)=>{if(!z||!H||!U){t.status(503).json({jsonrpc:`2.0`,error:{code:-32603,message:`Server initializing — please retry in a few seconds`},id:null});return}let r=J,i;J=new Promise(e=>{i=e});let a={POST:6e4,GET:1e4,DELETE:1e4}[e.method]??3e4;if(!await Promise.race([r.then(()=>!0),new Promise(t=>{let n=setTimeout(()=>{v.warn(`mcpLock timed out waiting for previous request, resetting lock chain`,{method:e.method,timeoutMs:a}),t(!1)},a);n.unref&&n.unref()})])&&(J=Promise.resolve(),i=()=>{},G)){let e=G;G=null,K=null,e.close().catch(()=>{})}try{let r=n(e);if(!G){if(r){t.status(404).json({jsonrpc:`2.0`,error:{code:-32001,message:`Session not found`},id:null});return}let e=new U({sessionIdGenerator:()=>u(),onsessioninitialized:async e=>{K=e,V?.onSessionStart(e,{transport:`http`})},onsessionclosed:async e=>{e&&V?.onSessionEnd(e),K=null}});e.onclose=()=>{G===e&&(G=null),K===e.sessionId&&(K=null)},G=e,await H.connect(e)}let i=G;await i.handleRequest(e,t,e.body),e.method!==`DELETE`&&(!r&&i.sessionId?(K=i.sessionId,V?.onSessionStart(i.sessionId,{transport:`http`}),V?.onSessionActivity(i.sessionId)):r&&V?.onSessionActivity(r))}catch(e){if(v.error(`MCP handler error`,c(e)),!t.headersSent){let n=e instanceof Error?e.message:String(e),r=n.includes(`Not Acceptable`);t.status(r?406:500).json({jsonrpc:`2.0`,error:{code:r?-32e3:-32603,message:r?n:`Internal server error`},id:null})}}finally{i()}},X=async(e,t)=>{let r=n(e);if(W&&(!G||r!==K)){await W.handleRequest(e,t,e.body);return}await Y(e,t)};E.post(`/mcp`,X),E.get(`/mcp`,X),E.delete(`/mcp`,X);let Z=E.listen(D,`127.0.0.1`,()=>{v.info(`MCP server listening`,{url:`http://127.0.0.1:${D}/mcp`,port:D}),setTimeout(async()=>{try{typeof L==`string`&&L.length>0&&(T.sources[0]={path:L,excludePatterns:T.sources[0]?.excludePatterns??[]},T.allRoots=[L],v.debug(`Workspace root applied from proxy header`,{wsRoot:L}));let[{createLazyServer:n,createMcpServer:r,ALL_TOOL_NAMES:i},{StreamableHTTPServerTransport:a},{checkForUpdates:o,autoUpgradeScaffold:l}]=await Promise.all([import(`./server-DZtwuagm.js`),import(`@modelcontextprotocol/sdk/server/streamableHttp.js`),import(`./startup-maintenance-D7tKqECM.js`).then(e=>e.u)]);o(),l(),setInterval(o,1440*60*1e3).unref();let u=!1,d=m(T),f=n(T,d);q=async()=>{f.aikit&&await Promise.all([f.aikit.embedder.shutdown?.().catch(()=>{})??Promise.resolve(),f.aikit.graphStore.close().catch(()=>{}),f.aikit.closeStateStore?.().catch(()=>{})??Promise.resolve(),f.aikit.store.close().catch(()=>{})])},H=f.server,U=a,z=!0,v.debug(`MCP server configured (lazy — AI Kit initializing in background)`,{toolCount:i.length,resourceCount:2}),f.startInit(),f.ready.then(async()=>{try{if(!f.aikit)throw Error(`AI Kit components are not available after initialization`);V=new _(f.aikit.stateStore,{staleTimeoutMinutes:M,gcIntervalMinutes:N,onBeforeSessionDelete:e=>{if(K===e&&G){let e=G;G=null,K=null,e.close().catch(()=>void 0)}W?.closeSession(e,{notifySessionEnd:!1})},onSessionEndMaintenance:async()=>{if(!f.aikit?.curated||!f.aikit?.stateStore)return;let{pruneLessons:e}=await import(`./startup-maintenance-D7tKqECM.js`).then(e=>e.x),t=await e(f.aikit.curated,f.aikit.stateStore,{dryRun:!1});t.pruned.length>0&&v.info(`Session-end lesson prune`,{pruned:t.pruned.length})}}),W=new h({createServer:()=>{if(!f.aikit)throw Error(`AI Kit components are not available after initialization`);return r(f.aikit,T)},createTransport:e=>new a(e),maxSessions:j,sessionTimeoutMinutes:M,onSessionStart:e=>V?.onSessionStart(e,{transport:`http`}),onSessionActivity:e=>V?.onSessionActivity(e),onSessionEnd:e=>V?.onSessionEnd(e)}),V.startGC(),K&&(V.onSessionStart(K,{transport:`http`}),V.onSessionActivity(K)),v.info(`HTTP session runtime ready`,{maxSessions:j,sessionTimeoutMinutes:M,gcIntervalMinutes:N})}catch(e){v.error(`Failed to start session manager`,c(e)),z=!1,u=!0,H=null,U=null,q=null}}),d===`auto`?f.ready.then(async()=>{try{let e=T.sources.map(e=>e.path).join(`, `);v.info(`Running initial index`,{sourcePaths:e}),await f.runInitialIndex(),v.info(`Initial index complete`)}catch(t){v.error(`Initial index failed; will retry on aikit_reindex`,e(s,t))}}):d===`smart`?u||f.ready.then(async()=>{try{if(!f.aikit)throw Error(`AI Kit components are not available after initialization`);let{SmartIndexScheduler:e}=await import(`../../indexer/dist/index.js`),t=new e(f.aikit.indexer,T,f.aikit.store),n=f.aikit.store;B=t,t.start(),n.onBeforeClose&&n.onBeforeClose(()=>t.stop()),f.setSmartScheduler(t),v.debug(`Smart index scheduler started (HTTP mode)`)}catch(t){v.error(`Failed to start smart index scheduler`,e(s,t))}}):v.info(`Initial full indexing skipped in HTTP mode`,{indexMode:d}),f.ready.catch(t=>{v.error(`AI Kit initialization failed`,e(s,t)),z=!1,u=!0,H=null,U=null,q=null}),t(f.ready,()=>f.aikit?{curated:f.aikit.curated,stateStore:f.aikit.stateStore}:null,s)}catch(t){v.error(`Failed to load server modules`,e(s,t)),z=!1,q=null}},100)}),Q=!1,$=async e=>{Q||(Q=!0,v.info(`Shutdown signal received`,{signal:e}),o(),B?.stop(),V?.stop(),await import(`../../tools/dist/index.js`).then(({processStopAll:e})=>e()).catch(()=>{}),await W?.closeAll().catch(()=>void 0),K&&V?.onSessionEnd(K),G&&(await G.close().catch(()=>void 0),G=null,K=null),Z.close(),H&&await H.close(),await q?.().catch(()=>void 0),process.exit(0))};process.on(`SIGINT`,()=>$(`SIGINT`)),process.on(`SIGTERM`,()=>$(`SIGTERM`))}export{y as startHttpMode};
@@ -1 +1 @@
1
- import{a as e,n as t,r as n,t as r}from"./server-utils-De-aZNQa.js";import{n as i,t as a}from"./startup-maintenance-QrloHssd.js";import{t as o}from"./register-tools-Dcut-2_z.js";import{createLogger as s,serializeError as c,setDetailedErrorLoggingEnabled as l}from"../../core/dist/index.js";import{randomUUID as u}from"node:crypto";const d=`__pending__:`;function f(e){return e.startsWith(d)}function p(e){let t=e.headers[`mcp-session-id`];return Array.isArray(t)?t[0]:t}function m(e,t,n,r){e.status(t).json({jsonrpc:`2.0`,error:{code:n,message:r},id:null})}var h=class{options;runtimes=new Map;maxSessions;sessionTimeoutMs;now;constructor(e){this.options=e,this.maxSessions=e.maxSessions??8,this.sessionTimeoutMs=(e.sessionTimeoutMinutes??30)*60*1e3,this.now=e.now??(()=>Date.now())}hasSession(e){return this.runtimes.has(e)}getSessionCount(){return this.runtimes.size}async handleRequest(e,t,n=e.body){let r=p(e),i=r?this.runtimes.get(r):void 0;if(r&&!i){m(t,404,-32001,`Session not found`);return}if(!i){if(e.method!==`POST`){m(t,400,-32e3,`Session required`);return}if(i=await this.createRuntime(t),!i)return}await this.withRuntimeLock(i,async()=>{await i.transport.handleRequest(e,t,n),i.lastAccessAt=this.now();let r=i.transport.sessionId??i.id;e.method!==`DELETE`&&!f(r)&&this.options.onSessionActivity?.(r),e.method===`DELETE`&&!f(r)&&await this.closeSession(r,{closeTransport:!1})})}async closeExpiredSessions(){let e=[...this.runtimes.values()].filter(e=>this.now()-e.lastAccessAt>=this.sessionTimeoutMs).map(e=>e.id);for(let t of e)await this.closeSession(t);return e.length}async closeSession(e,t={}){let n=this.runtimes.get(e);return n?(this.runtimes.delete(e),t.notifySessionEnd!==!1&&!f(e)&&this.options.onSessionEnd?.(e),t.closeTransport!==!1&&await n.transport.close().catch(()=>void 0),await n.server.close().catch(()=>void 0),!0):!1}async closeAll(){let e=[...this.runtimes.keys()];for(let t of e)await this.closeSession(t)}async createRuntime(e){if(await this.closeExpiredSessions(),this.runtimes.size>=this.maxSessions){m(e,503,-32003,`Session capacity reached`);return}let t=this.now(),n=await this.options.createServer(),r={id:`${d}${u()}`,transport:void 0,createdAt:t,lastAccessAt:t,server:n,requestChain:Promise.resolve()},i=this.options.createTransport({sessionIdGenerator:()=>u(),onsessioninitialized:async e=>{this.runtimes.delete(r.id),r.id=e,this.runtimes.set(e,r),this.options.onSessionStart?.(e)},onsessionclosed:async e=>{e&&await this.closeSession(e,{closeTransport:!1})}});return r.transport=i,i.onclose=()=>{let e=r.transport.sessionId??r.id;this.closeSession(e,{closeTransport:!1})},this.runtimes.set(r.id,r),await n.connect(i),r}async withRuntimeLock(e,t){let n=e.requestChain,r;e.requestChain=new Promise(e=>{r=e}),await n;try{await t()}finally{r()}}};function g(e){let t=e.includes(`T`)?e:`${e.replace(` `,`T`)}Z`;return Date.parse(t)}var _=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),Promise.resolve(this.options.onSessionEndMaintenance?.(e)).catch(()=>{})}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.getStaleSessionIds();for(let t of e)this.options.onBeforeSessionDelete?.(t),Promise.resolve(this.options.onSessionEndMaintenance?.(t)).catch(()=>{}),this.stateStore.sessionDelete(t);return e.length}stop(){this.gcTimer&&=(clearInterval(this.gcTimer),null)}getActiveSessions(){return this.stateStore.sessionList().length}listSessions(){return this.stateStore.sessionList()}getStaleSessionIds(e=Date.now()){let t=(this.options.staleTimeoutMinutes??30)*60*1e3;return this.stateStore.sessionList().filter(n=>{let r=g(n.lastActivity);return Number.isFinite(r)&&e-r>=t}).map(e=>e.sessionId)}};const v=s(`server`);async function y(s,d){let[{default:f},{loadConfig:p,resolveIndexMode:m},{registerDashboardRoutes:g,resolveDashboardDir:y},{registerSettingsRoutes:b,resolveSettingsDir:x},{createSettingsRouter:S},{authMiddleware:C,getOrCreateToken:w}]=await Promise.all([import(`express`),import(`./config-BS9mkd50.js`),import(`./dashboard-static-q97RHnd3.js`),import(`./settings-static-HY0egyKG.js`),import(`./routes-DsSm9ea0.js`),import(`./auth-7LFAZQBu.js`).then(e=>e.t)]),T=p();l(T.logging?.errorDetails===!0),T.configError&&v.warn(`Config load failure`,{error:T.configError}),v.info(`Config loaded`,{sourceCount:T.sources.length,storePath:T.store.path});let E=f();E.use(f.json({limit:`1mb`}));let D=Number(d),O=`http://localhost:${D}`,k=process.env.AIKIT_CORS_ORIGIN??O,A=process.env.AIKIT_ALLOW_ANY_ORIGIN===`true`,j=n(`AIKIT_HTTP_MAX_SESSIONS`,8),M=n(`AIKIT_HTTP_SESSION_TIMEOUT_MINUTES`,30),N=n(`AIKIT_HTTP_SESSION_GC_INTERVAL_MINUTES`,5),P=r({limit:100,windowMs:6e4}),F=!1;E.use((t,n,r)=>{let i=Array.isArray(t.headers.origin)?t.headers.origin[0]:t.headers.origin,a=e({requestOrigin:i,configuredOrigin:k,allowAnyOrigin:A,fallbackOrigin:O});if(a.warn&&!F&&(F=!0,v.warn(`Rejected non-local CORS origin while AIKIT_CORS_ORIGIN=*`,{origin:i,allowAnyOriginEnv:`AIKIT_ALLOW_ANY_ORIGIN=true`})),i&&!a.allowOrigin){n.status(403).json({error:`Origin not allowed`});return}if(a.allowOrigin&&n.setHeader(`Access-Control-Allow-Origin`,a.allowOrigin),n.setHeader(`Access-Control-Allow-Methods`,`GET, POST, PUT, PATCH, DELETE, OPTIONS`),n.setHeader(`Access-Control-Allow-Headers`,`Content-Type, Authorization, Mcp-Session-Id, Mcp-Protocol-Version, Last-Event-ID`),n.setHeader(`Access-Control-Expose-Headers`,`Mcp-Session-Id`),t.method===`OPTIONS`){n.status(204).end();return}r()});let I=w();E.use(C(I)),E.use(`/mcp`,(e,n,r)=>{let i=t(e)??e.ip??e.socket.remoteAddress??`anonymous`;if(P.allow(i)){r();return}let a=Math.max(1,Math.ceil(P.getRetryAfterMs(i)/1e3));n.setHeader(`Retry-After`,String(a)),n.status(429).json({jsonrpc:`2.0`,error:{code:-32003,message:`Rate limit exceeded`},id:null})});let L;E.use(`/mcp`,(e,t,n)=>{if(!L){let t=e.headers[`x-workspace-root`];typeof t==`string`&&t.length>0&&(L=t,v.debug(`Captured workspace root from proxy header`,{wsRoot:t}))}n()}),g(E,y(),v);let R=new Date().toISOString();E.use(`/settings/api`,S({log:v,mcpInfo:()=>({transport:`http`,port:D,pid:process.pid,startedAt:R})})),b(E,x(),v),E.get(`/health`,(e,t)=>{t.json({status:`ok`})});let z=!1,B=null,V=null,H=null,U=null,W=null,G=null,K=null,q=null,J=Promise.resolve(),Y=async(e,n)=>{if(!z||!H||!U){n.status(503).json({jsonrpc:`2.0`,error:{code:-32603,message:`Server initializing — please retry in a few seconds`},id:null});return}let r=J,i;J=new Promise(e=>{i=e});let a={POST:6e4,GET:1e4,DELETE:1e4}[e.method]??3e4;if(!await Promise.race([r.then(()=>!0),new Promise(t=>{let n=setTimeout(()=>{v.warn(`mcpLock timed out waiting for previous request, resetting lock chain`,{method:e.method,timeoutMs:a}),t(!1)},a);n.unref&&n.unref()})])&&(J=Promise.resolve(),i=()=>{},G)){let e=G;G=null,K=null,e.close().catch(()=>{})}try{let r=t(e);if(!G){if(r){n.status(404).json({jsonrpc:`2.0`,error:{code:-32001,message:`Session not found`},id:null});return}let e=new U({sessionIdGenerator:()=>u(),onsessioninitialized:async e=>{K=e,V?.onSessionStart(e,{transport:`http`})},onsessionclosed:async e=>{e&&V?.onSessionEnd(e),K=null}});e.onclose=()=>{G===e&&(G=null),K===e.sessionId&&(K=null)},G=e,await H.connect(e)}let i=G;await i.handleRequest(e,n,e.body),e.method!==`DELETE`&&(!r&&i.sessionId?(K=i.sessionId,V?.onSessionStart(i.sessionId,{transport:`http`}),V?.onSessionActivity(i.sessionId)):r&&V?.onSessionActivity(r))}catch(e){if(v.error(`MCP handler error`,c(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()}},X=async(e,n)=>{let r=t(e);if(W&&(!G||r!==K)){await W.handleRequest(e,n,e.body);return}await Y(e,n)};E.post(`/mcp`,X),E.get(`/mcp`,X),E.delete(`/mcp`,X);let Z=E.listen(D,`127.0.0.1`,()=>{v.info(`MCP server listening`,{url:`http://127.0.0.1:${D}/mcp`,port:D}),setTimeout(async()=>{try{typeof L==`string`&&L.length>0&&(T.sources[0]={path:L,excludePatterns:T.sources[0]?.excludePatterns??[]},T.allRoots=[L],v.debug(`Workspace root applied from proxy header`,{wsRoot:L}));let[{createLazyServer:e,createMcpServer:t,ALL_TOOL_NAMES:n},{StreamableHTTPServerTransport:r},{checkForUpdates:o,autoUpgradeScaffold:l}]=await Promise.all([import(`./server-Bm4hxs4N.js`),import(`@modelcontextprotocol/sdk/server/streamableHttp.js`),import(`./startup-maintenance-QrloHssd.js`).then(e=>e.u)]);o(),l(),setInterval(o,1440*60*1e3).unref();let u=!1,d=m(T),f=e(T,d);q=async()=>{f.aikit&&await Promise.all([f.aikit.embedder.shutdown?.().catch(()=>{})??Promise.resolve(),f.aikit.graphStore.close().catch(()=>{}),f.aikit.closeStateStore?.().catch(()=>{})??Promise.resolve(),f.aikit.store.close().catch(()=>{})])},H=f.server,U=r,z=!0,v.debug(`MCP server configured (lazy — AI Kit initializing in background)`,{toolCount:n.length,resourceCount:2}),f.startInit(),f.ready.then(async()=>{try{if(!f.aikit)throw Error(`AI Kit components are not available after initialization`);V=new _(f.aikit.stateStore,{staleTimeoutMinutes:M,gcIntervalMinutes:N,onBeforeSessionDelete:e=>{if(K===e&&G){let e=G;G=null,K=null,e.close().catch(()=>void 0)}W?.closeSession(e,{notifySessionEnd:!1})},onSessionEndMaintenance:async()=>{if(!f.aikit?.curated||!f.aikit?.stateStore)return;let{pruneLessons:e}=await import(`./startup-maintenance-QrloHssd.js`).then(e=>e.x),t=await e(f.aikit.curated,f.aikit.stateStore,{dryRun:!1});t.pruned.length>0&&v.info(`Session-end lesson prune`,{pruned:t.pruned.length})}}),W=new h({createServer:()=>{if(!f.aikit)throw Error(`AI Kit components are not available after initialization`);return t(f.aikit,T)},createTransport:e=>new r(e),maxSessions:j,sessionTimeoutMinutes:M,onSessionStart:e=>V?.onSessionStart(e,{transport:`http`}),onSessionActivity:e=>V?.onSessionActivity(e),onSessionEnd:e=>V?.onSessionEnd(e)}),V.startGC(),K&&(V.onSessionStart(K,{transport:`http`}),V.onSessionActivity(K)),v.info(`HTTP session runtime ready`,{maxSessions:j,sessionTimeoutMinutes:M,gcIntervalMinutes:N})}catch(e){v.error(`Failed to start session manager`,c(e)),z=!1,u=!0,H=null,U=null,q=null}}),d===`auto`?f.ready.then(async()=>{try{let e=T.sources.map(e=>e.path).join(`, `);v.info(`Running initial index`,{sourcePaths:e}),await f.runInitialIndex(),v.info(`Initial index complete`)}catch(e){v.error(`Initial index failed; will retry on aikit_reindex`,i(s,e))}}):d===`smart`?u||f.ready.then(async()=>{try{if(!f.aikit)throw Error(`AI Kit components are not available after initialization`);let{SmartIndexScheduler:e}=await import(`../../indexer/dist/index.js`),t=new e(f.aikit.indexer,T,f.aikit.store),n=f.aikit.store;B=t,t.start(),n.onBeforeClose&&n.onBeforeClose(()=>t.stop()),f.setSmartScheduler(t),v.debug(`Smart index scheduler started (HTTP mode)`)}catch(e){v.error(`Failed to start smart index scheduler`,i(s,e))}}):v.info(`Initial full indexing skipped in HTTP mode`,{indexMode:d}),f.ready.catch(e=>{v.error(`AI Kit initialization failed`,i(s,e)),z=!1,u=!0,H=null,U=null,q=null}),a(f.ready,()=>f.aikit?{curated:f.aikit.curated,stateStore:f.aikit.stateStore}:null,s)}catch(e){v.error(`Failed to load server modules`,i(s,e)),z=!1,q=null}},100)}),Q=!1,$=async e=>{Q||(Q=!0,v.info(`Shutdown signal received`,{signal:e}),o(),B?.stop(),V?.stop(),await import(`../../tools/dist/index.js`).then(({processStopAll:e})=>e()).catch(()=>{}),await W?.closeAll().catch(()=>void 0),K&&V?.onSessionEnd(K),G&&(await G.close().catch(()=>void 0),G=null,K=null),Z.close(),H&&await H.close(),await q?.().catch(()=>void 0),process.exit(0))};process.on(`SIGINT`,()=>$(`SIGINT`)),process.on(`SIGTERM`,()=>$(`SIGTERM`))}export{y as startHttpMode};
1
+ import{a as e,n as t,r as n,t as r}from"./server-utils-De-aZNQa.js";import{n as i,t as a}from"./startup-maintenance-QrloHssd.js";import{t as o}from"./register-tools-DvUjjiBA.js";import{createLogger as s,serializeError as c,setDetailedErrorLoggingEnabled as l}from"../../core/dist/index.js";import{randomUUID as u}from"node:crypto";const d=`__pending__:`;function f(e){return e.startsWith(d)}function p(e){let t=e.headers[`mcp-session-id`];return Array.isArray(t)?t[0]:t}function m(e,t,n,r){e.status(t).json({jsonrpc:`2.0`,error:{code:n,message:r},id:null})}var h=class{options;runtimes=new Map;maxSessions;sessionTimeoutMs;now;constructor(e){this.options=e,this.maxSessions=e.maxSessions??8,this.sessionTimeoutMs=(e.sessionTimeoutMinutes??30)*60*1e3,this.now=e.now??(()=>Date.now())}hasSession(e){return this.runtimes.has(e)}getSessionCount(){return this.runtimes.size}async handleRequest(e,t,n=e.body){let r=p(e),i=r?this.runtimes.get(r):void 0;if(r&&!i){m(t,404,-32001,`Session not found`);return}if(!i){if(e.method!==`POST`){m(t,400,-32e3,`Session required`);return}if(i=await this.createRuntime(t),!i)return}await this.withRuntimeLock(i,async()=>{await i.transport.handleRequest(e,t,n),i.lastAccessAt=this.now();let r=i.transport.sessionId??i.id;e.method!==`DELETE`&&!f(r)&&this.options.onSessionActivity?.(r),e.method===`DELETE`&&!f(r)&&await this.closeSession(r,{closeTransport:!1})})}async closeExpiredSessions(){let e=[...this.runtimes.values()].filter(e=>this.now()-e.lastAccessAt>=this.sessionTimeoutMs).map(e=>e.id);for(let t of e)await this.closeSession(t);return e.length}async closeSession(e,t={}){let n=this.runtimes.get(e);return n?(this.runtimes.delete(e),t.notifySessionEnd!==!1&&!f(e)&&this.options.onSessionEnd?.(e),t.closeTransport!==!1&&await n.transport.close().catch(()=>void 0),await n.server.close().catch(()=>void 0),!0):!1}async closeAll(){let e=[...this.runtimes.keys()];for(let t of e)await this.closeSession(t)}async createRuntime(e){if(await this.closeExpiredSessions(),this.runtimes.size>=this.maxSessions){m(e,503,-32003,`Session capacity reached`);return}let t=this.now(),n=await this.options.createServer(),r={id:`${d}${u()}`,transport:void 0,createdAt:t,lastAccessAt:t,server:n,requestChain:Promise.resolve()},i=this.options.createTransport({sessionIdGenerator:()=>u(),onsessioninitialized:async e=>{this.runtimes.delete(r.id),r.id=e,this.runtimes.set(e,r),this.options.onSessionStart?.(e)},onsessionclosed:async e=>{e&&await this.closeSession(e,{closeTransport:!1})}});return r.transport=i,i.onclose=()=>{let e=r.transport.sessionId??r.id;this.closeSession(e,{closeTransport:!1})},this.runtimes.set(r.id,r),await n.connect(i),r}async withRuntimeLock(e,t){let n=e.requestChain,r;e.requestChain=new Promise(e=>{r=e}),await n;try{await t()}finally{r()}}};function g(e){let t=e.includes(`T`)?e:`${e.replace(` `,`T`)}Z`;return Date.parse(t)}var _=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),Promise.resolve(this.options.onSessionEndMaintenance?.(e)).catch(()=>{})}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.getStaleSessionIds();for(let t of e)this.options.onBeforeSessionDelete?.(t),Promise.resolve(this.options.onSessionEndMaintenance?.(t)).catch(()=>{}),this.stateStore.sessionDelete(t);return e.length}stop(){this.gcTimer&&=(clearInterval(this.gcTimer),null)}getActiveSessions(){return this.stateStore.sessionList().length}listSessions(){return this.stateStore.sessionList()}getStaleSessionIds(e=Date.now()){let t=(this.options.staleTimeoutMinutes??30)*60*1e3;return this.stateStore.sessionList().filter(n=>{let r=g(n.lastActivity);return Number.isFinite(r)&&e-r>=t}).map(e=>e.sessionId)}};const v=s(`server`);async function y(s,d){let[{default:f},{loadConfig:p,resolveIndexMode:m},{registerDashboardRoutes:g,resolveDashboardDir:y},{registerSettingsRoutes:b,resolveSettingsDir:x},{createSettingsRouter:S},{authMiddleware:C,getOrCreateToken:w}]=await Promise.all([import(`express`),import(`./config-BS9mkd50.js`),import(`./dashboard-static-q97RHnd3.js`),import(`./settings-static-HY0egyKG.js`),import(`./routes-DsSm9ea0.js`),import(`./auth-7LFAZQBu.js`).then(e=>e.t)]),T=p();l(T.logging?.errorDetails===!0),T.configError&&v.warn(`Config load failure`,{error:T.configError}),v.info(`Config loaded`,{sourceCount:T.sources.length,storePath:T.store.path});let E=f();E.use(f.json({limit:`1mb`}));let D=Number(d),O=`http://localhost:${D}`,k=process.env.AIKIT_CORS_ORIGIN??O,A=process.env.AIKIT_ALLOW_ANY_ORIGIN===`true`,j=n(`AIKIT_HTTP_MAX_SESSIONS`,8),M=n(`AIKIT_HTTP_SESSION_TIMEOUT_MINUTES`,30),N=n(`AIKIT_HTTP_SESSION_GC_INTERVAL_MINUTES`,5),P=r({limit:100,windowMs:6e4}),F=!1;E.use((t,n,r)=>{let i=Array.isArray(t.headers.origin)?t.headers.origin[0]:t.headers.origin,a=e({requestOrigin:i,configuredOrigin:k,allowAnyOrigin:A,fallbackOrigin:O});if(a.warn&&!F&&(F=!0,v.warn(`Rejected non-local CORS origin while AIKIT_CORS_ORIGIN=*`,{origin:i,allowAnyOriginEnv:`AIKIT_ALLOW_ANY_ORIGIN=true`})),i&&!a.allowOrigin){n.status(403).json({error:`Origin not allowed`});return}if(a.allowOrigin&&n.setHeader(`Access-Control-Allow-Origin`,a.allowOrigin),n.setHeader(`Access-Control-Allow-Methods`,`GET, POST, PUT, PATCH, DELETE, OPTIONS`),n.setHeader(`Access-Control-Allow-Headers`,`Content-Type, Authorization, Mcp-Session-Id, Mcp-Protocol-Version, Last-Event-ID`),n.setHeader(`Access-Control-Expose-Headers`,`Mcp-Session-Id`),t.method===`OPTIONS`){n.status(204).end();return}r()});let I=w();E.use(C(I)),E.use(`/mcp`,(e,n,r)=>{let i=t(e)??e.ip??e.socket.remoteAddress??`anonymous`;if(P.allow(i)){r();return}let a=Math.max(1,Math.ceil(P.getRetryAfterMs(i)/1e3));n.setHeader(`Retry-After`,String(a)),n.status(429).json({jsonrpc:`2.0`,error:{code:-32003,message:`Rate limit exceeded`},id:null})});let L;E.use(`/mcp`,(e,t,n)=>{if(!L){let t=e.headers[`x-workspace-root`];typeof t==`string`&&t.length>0&&(L=t,v.debug(`Captured workspace root from proxy header`,{wsRoot:t}))}n()}),g(E,y(),v);let R=new Date().toISOString();E.use(`/settings/api`,S({log:v,mcpInfo:()=>({transport:`http`,port:D,pid:process.pid,startedAt:R})})),b(E,x(),v),E.get(`/health`,(e,t)=>{t.json({status:`ok`})});let z=!1,B=null,V=null,H=null,U=null,W=null,G=null,K=null,q=null,J=Promise.resolve(),Y=async(e,n)=>{if(!z||!H||!U){n.status(503).json({jsonrpc:`2.0`,error:{code:-32603,message:`Server initializing — please retry in a few seconds`},id:null});return}let r=J,i;J=new Promise(e=>{i=e});let a={POST:6e4,GET:1e4,DELETE:1e4}[e.method]??3e4;if(!await Promise.race([r.then(()=>!0),new Promise(t=>{let n=setTimeout(()=>{v.warn(`mcpLock timed out waiting for previous request, resetting lock chain`,{method:e.method,timeoutMs:a}),t(!1)},a);n.unref&&n.unref()})])&&(J=Promise.resolve(),i=()=>{},G)){let e=G;G=null,K=null,e.close().catch(()=>{})}try{let r=t(e);if(!G){if(r){n.status(404).json({jsonrpc:`2.0`,error:{code:-32001,message:`Session not found`},id:null});return}let e=new U({sessionIdGenerator:()=>u(),onsessioninitialized:async e=>{K=e,V?.onSessionStart(e,{transport:`http`})},onsessionclosed:async e=>{e&&V?.onSessionEnd(e),K=null}});e.onclose=()=>{G===e&&(G=null),K===e.sessionId&&(K=null)},G=e,await H.connect(e)}let i=G;await i.handleRequest(e,n,e.body),e.method!==`DELETE`&&(!r&&i.sessionId?(K=i.sessionId,V?.onSessionStart(i.sessionId,{transport:`http`}),V?.onSessionActivity(i.sessionId)):r&&V?.onSessionActivity(r))}catch(e){if(v.error(`MCP handler error`,c(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()}},X=async(e,n)=>{let r=t(e);if(W&&(!G||r!==K)){await W.handleRequest(e,n,e.body);return}await Y(e,n)};E.post(`/mcp`,X),E.get(`/mcp`,X),E.delete(`/mcp`,X);let Z=E.listen(D,`127.0.0.1`,()=>{v.info(`MCP server listening`,{url:`http://127.0.0.1:${D}/mcp`,port:D}),setTimeout(async()=>{try{typeof L==`string`&&L.length>0&&(T.sources[0]={path:L,excludePatterns:T.sources[0]?.excludePatterns??[]},T.allRoots=[L],v.debug(`Workspace root applied from proxy header`,{wsRoot:L}));let[{createLazyServer:e,createMcpServer:t,ALL_TOOL_NAMES:n},{StreamableHTTPServerTransport:r},{checkForUpdates:o,autoUpgradeScaffold:l}]=await Promise.all([import(`./server-D1xJ5iwA.js`),import(`@modelcontextprotocol/sdk/server/streamableHttp.js`),import(`./startup-maintenance-QrloHssd.js`).then(e=>e.u)]);o(),l(),setInterval(o,1440*60*1e3).unref();let u=!1,d=m(T),f=e(T,d);q=async()=>{f.aikit&&await Promise.all([f.aikit.embedder.shutdown?.().catch(()=>{})??Promise.resolve(),f.aikit.graphStore.close().catch(()=>{}),f.aikit.closeStateStore?.().catch(()=>{})??Promise.resolve(),f.aikit.store.close().catch(()=>{})])},H=f.server,U=r,z=!0,v.debug(`MCP server configured (lazy — AI Kit initializing in background)`,{toolCount:n.length,resourceCount:2}),f.startInit(),f.ready.then(async()=>{try{if(!f.aikit)throw Error(`AI Kit components are not available after initialization`);V=new _(f.aikit.stateStore,{staleTimeoutMinutes:M,gcIntervalMinutes:N,onBeforeSessionDelete:e=>{if(K===e&&G){let e=G;G=null,K=null,e.close().catch(()=>void 0)}W?.closeSession(e,{notifySessionEnd:!1})},onSessionEndMaintenance:async()=>{if(!f.aikit?.curated||!f.aikit?.stateStore)return;let{pruneLessons:e}=await import(`./startup-maintenance-QrloHssd.js`).then(e=>e.x),t=await e(f.aikit.curated,f.aikit.stateStore,{dryRun:!1});t.pruned.length>0&&v.info(`Session-end lesson prune`,{pruned:t.pruned.length})}}),W=new h({createServer:()=>{if(!f.aikit)throw Error(`AI Kit components are not available after initialization`);return t(f.aikit,T)},createTransport:e=>new r(e),maxSessions:j,sessionTimeoutMinutes:M,onSessionStart:e=>V?.onSessionStart(e,{transport:`http`}),onSessionActivity:e=>V?.onSessionActivity(e),onSessionEnd:e=>V?.onSessionEnd(e)}),V.startGC(),K&&(V.onSessionStart(K,{transport:`http`}),V.onSessionActivity(K)),v.info(`HTTP session runtime ready`,{maxSessions:j,sessionTimeoutMinutes:M,gcIntervalMinutes:N})}catch(e){v.error(`Failed to start session manager`,c(e)),z=!1,u=!0,H=null,U=null,q=null}}),d===`auto`?f.ready.then(async()=>{try{let e=T.sources.map(e=>e.path).join(`, `);v.info(`Running initial index`,{sourcePaths:e}),await f.runInitialIndex(),v.info(`Initial index complete`)}catch(e){v.error(`Initial index failed; will retry on aikit_reindex`,i(s,e))}}):d===`smart`?u||f.ready.then(async()=>{try{if(!f.aikit)throw Error(`AI Kit components are not available after initialization`);let{SmartIndexScheduler:e}=await import(`../../indexer/dist/index.js`),t=new e(f.aikit.indexer,T,f.aikit.store),n=f.aikit.store;B=t,t.start(),n.onBeforeClose&&n.onBeforeClose(()=>t.stop()),f.setSmartScheduler(t),v.debug(`Smart index scheduler started (HTTP mode)`)}catch(e){v.error(`Failed to start smart index scheduler`,i(s,e))}}):v.info(`Initial full indexing skipped in HTTP mode`,{indexMode:d}),f.ready.catch(e=>{v.error(`AI Kit initialization failed`,i(s,e)),z=!1,u=!0,H=null,U=null,q=null}),a(f.ready,()=>f.aikit?{curated:f.aikit.curated,stateStore:f.aikit.stateStore}:null,s)}catch(e){v.error(`Failed to load server modules`,i(s,e)),z=!1,q=null}},100)}),Q=!1,$=async e=>{Q||(Q=!0,v.info(`Shutdown signal received`,{signal:e}),o(),B?.stop(),V?.stop(),await import(`../../tools/dist/index.js`).then(({processStopAll:e})=>e()).catch(()=>{}),await W?.closeAll().catch(()=>void 0),K&&V?.onSessionEnd(K),G&&(await G.close().catch(()=>void 0),G=null,K=null),Z.close(),H&&await H.close(),await q?.().catch(()=>void 0),process.exit(0))};process.on(`SIGINT`,()=>$(`SIGINT`)),process.on(`SIGTERM`,()=>$(`SIGTERM`))}export{y as startHttpMode};
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- import{n as e,t}from"./startup-maintenance-D7tKqECM.js";import{r as n}from"./bin.js";import{a as r,t as i}from"./register-tools-nx2aner6.js";import{createLogger as a,serializeError as o,setDetailedErrorLoggingEnabled as s}from"../../core/dist/index.js";const c=a(`server`);var l=class{buffer;append(e){this.buffer=this.buffer?Buffer.concat([this.buffer,e]):e}readMessage(){if(!this.buffer)return null;for(let e=0;e<this.buffer.length;e++){if(this.buffer[e]!==10)continue;let t=this.buffer.toString(`utf8`,0,e).replace(/\r$/,``),n=e+1;try{let e=JSON.parse(t);return this.buffer=this.buffer.subarray(n),e}catch{try{let e=r(t);return c.warn(`JSON parse failed on MCP message — repair succeeded`,{preview:t.slice(0,80)}),this.buffer=this.buffer.subarray(n),e}catch{}}}return null}clear(){this.buffer=void 0}};async function u(r){let[{loadConfig:a,reconfigureForWorkspace:u,resolveIndexMode:d},{createLazyServer:f},{checkForUpdates:p,autoUpgradeScaffold:m},{RootsListChangedNotificationSchema:h}]=await Promise.all([import(`./config-CkXCQx7E.js`),import(`./server-CcYHQCrv.js`),import(`./startup-maintenance-D7tKqECM.js`).then(e=>e.u),import(`@modelcontextprotocol/sdk/types.js`)]),g=a();s(g.logging?.errorDetails===!0),g.configError&&c.warn(`Config load failure`,{error:g.configError}),c.info(`Config loaded`,{sourceCount:g.sources.length,storePath:g.store.path}),m(),setInterval(p,1440*60*1e3).unref();let _=d(g),v=f(g,_),{server:y,startInit:b,ready:x,runInitialIndex:S}=v,{StdioServerTransport:C}=await import(`@modelcontextprotocol/sdk/server/stdio.js`),w=new C;if(typeof w._readBuffer?.readMessage!=`function`)throw Error(`Cannot install JSON repair: StdioServerTransport._readBuffer has unexpected shape`);w._readBuffer=new l,c.debug(`JSON repair installed on stdio transport`),await y.connect(w),c.debug(`MCP server started`,{transport:`stdio`}),await n({config:g,indexMode:_,log:c,rootsChangedNotificationSchema:h,reconfigureForWorkspace:u,runInitialIndex:S,server:y,startInit:b,version:r});let T=null,E=null,D=!1,O=async e=>{D||(D=!0,c.info(`Shutdown signal received`,{signal:e}),i(),T&&=(clearTimeout(T),null),E?.stop(),await import(`../../tools/dist/index.js`).then(({processStopAll:e})=>e()).catch(()=>{}),await w.close().catch(()=>void 0),await y.close().catch(()=>void 0),v.aikit&&await Promise.all([v.aikit.embedder.shutdown?.().catch(()=>{})??Promise.resolve(),v.aikit.graphStore.close().catch(()=>{}),v.aikit.closeStateStore?.().catch(()=>{})??Promise.resolve(),v.aikit.store.close().catch(()=>{})]),process.exit(0))},k=()=>{T&&clearTimeout(T),T=setTimeout(async()=>{c.info(`Auto-shutdown: no activity for 30 minutes — releasing resources`),i();try{let e=v.aikit;e&&(e.embedder.shutdown?.().catch(()=>{}),e.store.releaseMemory?.(),e.graphStore.releaseMemory?.())}catch(e){c.warn(`Resource release failed during shutdown`,o(e))}},18e5),T.unref&&T.unref()};k(),process.stdin.on(`data`,()=>k()),process.stdin.on(`end`,()=>void O(`stdin-end`)),process.stdin.on(`close`,()=>void O(`stdin-close`)),process.stdin.on(`error`,()=>void O(`stdin-error`)),process.on(`SIGINT`,()=>void O(`SIGINT`)),process.on(`SIGTERM`,()=>void O(`SIGTERM`)),x.catch(t=>{c.error(`Initialization failed — server will continue with limited tools`,e(r,t))}),_===`smart`?x.then(async()=>{try{if(!v.aikit)throw Error(`AI Kit components are not available after initialization`);let{SmartIndexScheduler:e}=await import(`../../indexer/dist/index.js`),t=new e(v.aikit.indexer,g,v.aikit.store);E=t;let n=v.aikit.store;t.start(),n.onBeforeClose&&n.onBeforeClose(()=>t.stop()),v.setSmartScheduler(t),c.debug(`Smart index scheduler started (stdio mode)`)}catch(t){c.error(`Failed to start smart index scheduler`,e(r,t))}}).catch(t=>c.error(`AI Kit init failed for smart scheduler`,e(r,t))):c.warn(`Initial full indexing skipped; use aikit_reindex to index manually`,{indexMode:_}),t(x,()=>v.aikit?{curated:v.aikit.curated,stateStore:v.aikit.stateStore}:null,r)}export{u as startStdioMode};
2
+ import{n as e,t}from"./startup-maintenance-D7tKqECM.js";import{r as n}from"./bin.js";import{a as r,t as i}from"./register-tools-DrCEk_fv.js";import{createLogger as a,serializeError as o,setDetailedErrorLoggingEnabled as s}from"../../core/dist/index.js";const c=a(`server`);var l=class{buffer;append(e){this.buffer=this.buffer?Buffer.concat([this.buffer,e]):e}readMessage(){if(!this.buffer)return null;for(let e=0;e<this.buffer.length;e++){if(this.buffer[e]!==10)continue;let t=this.buffer.toString(`utf8`,0,e).replace(/\r$/,``),n=e+1;try{let e=JSON.parse(t);return this.buffer=this.buffer.subarray(n),e}catch{try{let e=r(t);return c.warn(`JSON parse failed on MCP message — repair succeeded`,{preview:t.slice(0,80)}),this.buffer=this.buffer.subarray(n),e}catch{}}}return null}clear(){this.buffer=void 0}};async function u(r){let[{loadConfig:a,reconfigureForWorkspace:u,resolveIndexMode:d},{createLazyServer:f},{checkForUpdates:p,autoUpgradeScaffold:m},{RootsListChangedNotificationSchema:h}]=await Promise.all([import(`./config-CkXCQx7E.js`),import(`./server-DZtwuagm.js`),import(`./startup-maintenance-D7tKqECM.js`).then(e=>e.u),import(`@modelcontextprotocol/sdk/types.js`)]),g=a();s(g.logging?.errorDetails===!0),g.configError&&c.warn(`Config load failure`,{error:g.configError}),c.info(`Config loaded`,{sourceCount:g.sources.length,storePath:g.store.path}),m(),setInterval(p,1440*60*1e3).unref();let _=d(g),v=f(g,_),{server:y,startInit:b,ready:x,runInitialIndex:S}=v,{StdioServerTransport:C}=await import(`@modelcontextprotocol/sdk/server/stdio.js`),w=new C;if(typeof w._readBuffer?.readMessage!=`function`)throw Error(`Cannot install JSON repair: StdioServerTransport._readBuffer has unexpected shape`);w._readBuffer=new l,c.debug(`JSON repair installed on stdio transport`),await y.connect(w),c.debug(`MCP server started`,{transport:`stdio`}),await n({config:g,indexMode:_,log:c,rootsChangedNotificationSchema:h,reconfigureForWorkspace:u,runInitialIndex:S,server:y,startInit:b,version:r});let T=null,E=null,D=!1,O=async e=>{D||(D=!0,c.info(`Shutdown signal received`,{signal:e}),i(),T&&=(clearTimeout(T),null),E?.stop(),await import(`../../tools/dist/index.js`).then(({processStopAll:e})=>e()).catch(()=>{}),await w.close().catch(()=>void 0),await y.close().catch(()=>void 0),v.aikit&&await Promise.all([v.aikit.embedder.shutdown?.().catch(()=>{})??Promise.resolve(),v.aikit.graphStore.close().catch(()=>{}),v.aikit.closeStateStore?.().catch(()=>{})??Promise.resolve(),v.aikit.store.close().catch(()=>{})]),process.exit(0))},k=()=>{T&&clearTimeout(T),T=setTimeout(async()=>{c.info(`Auto-shutdown: no activity for 30 minutes — releasing resources`),i();try{let e=v.aikit;e&&(e.embedder.shutdown?.().catch(()=>{}),e.store.releaseMemory?.(),e.graphStore.releaseMemory?.())}catch(e){c.warn(`Resource release failed during shutdown`,o(e))}},18e5),T.unref&&T.unref()};k(),process.stdin.on(`data`,()=>k()),process.stdin.on(`end`,()=>void O(`stdin-end`)),process.stdin.on(`close`,()=>void O(`stdin-close`)),process.stdin.on(`error`,()=>void O(`stdin-error`)),process.on(`SIGINT`,()=>void O(`SIGINT`)),process.on(`SIGTERM`,()=>void O(`SIGTERM`)),x.catch(t=>{c.error(`Initialization failed — server will continue with limited tools`,e(r,t))}),_===`smart`?x.then(async()=>{try{if(!v.aikit)throw Error(`AI Kit components are not available after initialization`);let{SmartIndexScheduler:e}=await import(`../../indexer/dist/index.js`),t=new e(v.aikit.indexer,g,v.aikit.store);E=t;let n=v.aikit.store;t.start(),n.onBeforeClose&&n.onBeforeClose(()=>t.stop()),v.setSmartScheduler(t),c.debug(`Smart index scheduler started (stdio mode)`)}catch(t){c.error(`Failed to start smart index scheduler`,e(r,t))}}).catch(t=>c.error(`AI Kit init failed for smart scheduler`,e(r,t))):c.warn(`Initial full indexing skipped; use aikit_reindex to index manually`,{indexMode:_}),t(x,()=>v.aikit?{curated:v.aikit.curated,stateStore:v.aikit.stateStore}:null,r)}export{u as startStdioMode};
@@ -1 +1 @@
1
- import{n as e}from"./workspace-bootstrap-DTnTU8p2.js";import{n as t,t as n}from"./startup-maintenance-QrloHssd.js";import{a as r,t as i}from"./register-tools-Dcut-2_z.js";import{createLogger as a,serializeError as o,setDetailedErrorLoggingEnabled as s}from"../../core/dist/index.js";const c=a(`server`);var l=class{buffer;append(e){this.buffer=this.buffer?Buffer.concat([this.buffer,e]):e}readMessage(){if(!this.buffer)return null;for(let e=0;e<this.buffer.length;e++){if(this.buffer[e]!==10)continue;let t=this.buffer.toString(`utf8`,0,e).replace(/\r$/,``),n=e+1;try{let e=JSON.parse(t);return this.buffer=this.buffer.subarray(n),e}catch{try{let e=r(t);return c.warn(`JSON parse failed on MCP message — repair succeeded`,{preview:t.slice(0,80)}),this.buffer=this.buffer.subarray(n),e}catch{}}}return null}clear(){this.buffer=void 0}};async function u(r){let[{loadConfig:a,reconfigureForWorkspace:u,resolveIndexMode:d},{createLazyServer:f},{checkForUpdates:p,autoUpgradeScaffold:m},{RootsListChangedNotificationSchema:h}]=await Promise.all([import(`./config-BS9mkd50.js`),import(`./server-Bm4hxs4N.js`),import(`./startup-maintenance-QrloHssd.js`).then(e=>e.u),import(`@modelcontextprotocol/sdk/types.js`)]),g=a();s(g.logging?.errorDetails===!0),g.configError&&c.warn(`Config load failure`,{error:g.configError}),c.info(`Config loaded`,{sourceCount:g.sources.length,storePath:g.store.path}),m(),setInterval(p,1440*60*1e3).unref();let _=d(g),v=f(g,_),{server:y,startInit:b,ready:x,runInitialIndex:S}=v,{StdioServerTransport:C}=await import(`@modelcontextprotocol/sdk/server/stdio.js`),w=new C;if(typeof w._readBuffer?.readMessage!=`function`)throw Error(`Cannot install JSON repair: StdioServerTransport._readBuffer has unexpected shape`);w._readBuffer=new l,c.debug(`JSON repair installed on stdio transport`),await y.connect(w),c.debug(`MCP server started`,{transport:`stdio`}),await e({config:g,indexMode:_,log:c,rootsChangedNotificationSchema:h,reconfigureForWorkspace:u,runInitialIndex:S,server:y,startInit:b,version:r});let T=null,E=null,D=!1,O=async e=>{D||(D=!0,c.info(`Shutdown signal received`,{signal:e}),i(),T&&=(clearTimeout(T),null),E?.stop(),await import(`../../tools/dist/index.js`).then(({processStopAll:e})=>e()).catch(()=>{}),await w.close().catch(()=>void 0),await y.close().catch(()=>void 0),v.aikit&&await Promise.all([v.aikit.embedder.shutdown?.().catch(()=>{})??Promise.resolve(),v.aikit.graphStore.close().catch(()=>{}),v.aikit.closeStateStore?.().catch(()=>{})??Promise.resolve(),v.aikit.store.close().catch(()=>{})]),process.exit(0))},k=()=>{T&&clearTimeout(T),T=setTimeout(async()=>{c.info(`Auto-shutdown: no activity for 30 minutes — releasing resources`),i();try{let e=v.aikit;e&&(e.embedder.shutdown?.().catch(()=>{}),e.store.releaseMemory?.(),e.graphStore.releaseMemory?.())}catch(e){c.warn(`Resource release failed during shutdown`,o(e))}},18e5),T.unref&&T.unref()};k(),process.stdin.on(`data`,()=>k()),process.stdin.on(`end`,()=>void O(`stdin-end`)),process.stdin.on(`close`,()=>void O(`stdin-close`)),process.stdin.on(`error`,()=>void O(`stdin-error`)),process.on(`SIGINT`,()=>void O(`SIGINT`)),process.on(`SIGTERM`,()=>void O(`SIGTERM`)),x.catch(e=>{c.error(`Initialization failed — server will continue with limited tools`,t(r,e))}),_===`smart`?x.then(async()=>{try{if(!v.aikit)throw Error(`AI Kit components are not available after initialization`);let{SmartIndexScheduler:e}=await import(`../../indexer/dist/index.js`),t=new e(v.aikit.indexer,g,v.aikit.store);E=t;let n=v.aikit.store;t.start(),n.onBeforeClose&&n.onBeforeClose(()=>t.stop()),v.setSmartScheduler(t),c.debug(`Smart index scheduler started (stdio mode)`)}catch(e){c.error(`Failed to start smart index scheduler`,t(r,e))}}).catch(e=>c.error(`AI Kit init failed for smart scheduler`,t(r,e))):c.warn(`Initial full indexing skipped; use aikit_reindex to index manually`,{indexMode:_}),n(x,()=>v.aikit?{curated:v.aikit.curated,stateStore:v.aikit.stateStore}:null,r)}export{u as startStdioMode};
1
+ import{n as e}from"./workspace-bootstrap-DTnTU8p2.js";import{n as t,t as n}from"./startup-maintenance-QrloHssd.js";import{a as r,t as i}from"./register-tools-DvUjjiBA.js";import{createLogger as a,serializeError as o,setDetailedErrorLoggingEnabled as s}from"../../core/dist/index.js";const c=a(`server`);var l=class{buffer;append(e){this.buffer=this.buffer?Buffer.concat([this.buffer,e]):e}readMessage(){if(!this.buffer)return null;for(let e=0;e<this.buffer.length;e++){if(this.buffer[e]!==10)continue;let t=this.buffer.toString(`utf8`,0,e).replace(/\r$/,``),n=e+1;try{let e=JSON.parse(t);return this.buffer=this.buffer.subarray(n),e}catch{try{let e=r(t);return c.warn(`JSON parse failed on MCP message — repair succeeded`,{preview:t.slice(0,80)}),this.buffer=this.buffer.subarray(n),e}catch{}}}return null}clear(){this.buffer=void 0}};async function u(r){let[{loadConfig:a,reconfigureForWorkspace:u,resolveIndexMode:d},{createLazyServer:f},{checkForUpdates:p,autoUpgradeScaffold:m},{RootsListChangedNotificationSchema:h}]=await Promise.all([import(`./config-BS9mkd50.js`),import(`./server-D1xJ5iwA.js`),import(`./startup-maintenance-QrloHssd.js`).then(e=>e.u),import(`@modelcontextprotocol/sdk/types.js`)]),g=a();s(g.logging?.errorDetails===!0),g.configError&&c.warn(`Config load failure`,{error:g.configError}),c.info(`Config loaded`,{sourceCount:g.sources.length,storePath:g.store.path}),m(),setInterval(p,1440*60*1e3).unref();let _=d(g),v=f(g,_),{server:y,startInit:b,ready:x,runInitialIndex:S}=v,{StdioServerTransport:C}=await import(`@modelcontextprotocol/sdk/server/stdio.js`),w=new C;if(typeof w._readBuffer?.readMessage!=`function`)throw Error(`Cannot install JSON repair: StdioServerTransport._readBuffer has unexpected shape`);w._readBuffer=new l,c.debug(`JSON repair installed on stdio transport`),await y.connect(w),c.debug(`MCP server started`,{transport:`stdio`}),await e({config:g,indexMode:_,log:c,rootsChangedNotificationSchema:h,reconfigureForWorkspace:u,runInitialIndex:S,server:y,startInit:b,version:r});let T=null,E=null,D=!1,O=async e=>{D||(D=!0,c.info(`Shutdown signal received`,{signal:e}),i(),T&&=(clearTimeout(T),null),E?.stop(),await import(`../../tools/dist/index.js`).then(({processStopAll:e})=>e()).catch(()=>{}),await w.close().catch(()=>void 0),await y.close().catch(()=>void 0),v.aikit&&await Promise.all([v.aikit.embedder.shutdown?.().catch(()=>{})??Promise.resolve(),v.aikit.graphStore.close().catch(()=>{}),v.aikit.closeStateStore?.().catch(()=>{})??Promise.resolve(),v.aikit.store.close().catch(()=>{})]),process.exit(0))},k=()=>{T&&clearTimeout(T),T=setTimeout(async()=>{c.info(`Auto-shutdown: no activity for 30 minutes — releasing resources`),i();try{let e=v.aikit;e&&(e.embedder.shutdown?.().catch(()=>{}),e.store.releaseMemory?.(),e.graphStore.releaseMemory?.())}catch(e){c.warn(`Resource release failed during shutdown`,o(e))}},18e5),T.unref&&T.unref()};k(),process.stdin.on(`data`,()=>k()),process.stdin.on(`end`,()=>void O(`stdin-end`)),process.stdin.on(`close`,()=>void O(`stdin-close`)),process.stdin.on(`error`,()=>void O(`stdin-error`)),process.on(`SIGINT`,()=>void O(`SIGINT`)),process.on(`SIGTERM`,()=>void O(`SIGTERM`)),x.catch(e=>{c.error(`Initialization failed — server will continue with limited tools`,t(r,e))}),_===`smart`?x.then(async()=>{try{if(!v.aikit)throw Error(`AI Kit components are not available after initialization`);let{SmartIndexScheduler:e}=await import(`../../indexer/dist/index.js`),t=new e(v.aikit.indexer,g,v.aikit.store);E=t;let n=v.aikit.store;t.start(),n.onBeforeClose&&n.onBeforeClose(()=>t.stop()),v.setSmartScheduler(t),c.debug(`Smart index scheduler started (stdio mode)`)}catch(e){c.error(`Failed to start smart index scheduler`,t(r,e))}}).catch(e=>c.error(`AI Kit init failed for smart scheduler`,t(r,e))):c.warn(`Initial full indexing skipped; use aikit_reindex to index manually`,{indexMode:_}),n(x,()=>v.aikit?{curated:v.aikit.curated,stateStore:v.aikit.stateStore}:null,r)}export{u as startStdioMode};