@vpxa/aikit 0.1.402 → 0.1.403

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vpxa/aikit",
3
- "version": "0.1.402",
3
+ "version": "0.1.403",
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,execFileSync as t,execSync as n,spawn as r}from"node:child_process";import{appendFileSync as i,closeSync as a,copyFileSync as o,existsSync as s,mkdirSync as c,openSync as l,readFileSync as u,readdirSync as d,unlinkSync as f,writeFileSync as p}from"node:fs";import{homedir as m,platform as h,tmpdir as g}from"node:os";import{dirname as _,join as v}from"node:path";import{z as y}from"zod";const b=`0.26.0`,x=`.agent-browser-version`;function S(e){return typeof e==`string`?e.trim():e instanceof Buffer?e.toString(`utf8`).trim():``}function C(){return v(m(),`.aikit`,`browsers`)}function w(e){return e.browsersPath??process.env.AIKIT_BROWSER_PATH??process.env.AIKIT_BROWSER_BROWSERS_PATH??C()}function T(){try{let e=n(`${h()===`win32`?`where`:`which`} agent-browser`,{encoding:`utf8`,windowsHide:!0,stdio:`pipe`,timeout:3e3}).trim().split(/\r?\n/).filter(Boolean);if(e.length===0)return null;if(h()===`win32`){for(let t of e){if(t.endsWith(`.exe`)&&s(t))return t;let e=v(_(t),`node_modules`,`agent-browser`,`bin`,`agent-browser-win32-x64.exe`);if(s(e))return e}for(let t of e){if(s(`${t}.exe`))return`${t}.exe`;if(s(`${t}.cmd`))return`${t}.cmd`;if(s(`${t}.bat`))return`${t}.bat`}}let t=e[0];return s(t)?t:null}catch{return null}}function E(e){return v(e,`agent-browser`,ee())}function ee(){switch(h()){case`win32`:return`agent-browser.exe`;default:return`agent-browser`}}function te(e,t){try{p(v(e,x),t,`utf8`)}catch{}}function ne(e){try{return u(v(e,x),`utf8`).trim()}catch{return null}}function re(e){let t=ne(e);return t?ie(t,b)>=0:!1}function ie(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 ae(e){return!!(s(v(e,`chrome`))||s(v(m(),`.cache`,`agent-browser`,`chrome`)))}async function oe(t,r){let i=T();if(i)return r?.(`Using globally installed agent-browser`),i;let a=w(t);s(a)||c(a,{recursive:!0});let l=E(a);if(s(l)&&re(a))return r?.(`Using cached agent-browser at ${l}`),l;r?.(`Downloading agent-browser (first use)...`),await new Promise((t,n)=>{let r=new AbortController,i=setTimeout(()=>r.abort(),12e4),o=e(`npx -y agent-browser@latest install --install-dir "${a}"`,{timeout:12e4,windowsHide:!0,encoding:`utf8`,env:{...process.env,AGENT_BROWSER_CACHE_DIR:a},signal:r.signal},(e,r,a)=>{if(clearTimeout(i),e){let t=S(a)||e.message||`Unknown agent-browser install failure`;n(Error(`Failed to install agent-browser: ${t}`));return}t()});o.stdin&&o.stdin.destroy()});let u=l;try{let e=n(h()===`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=h()===`win32`?`agent-browser-win32-x64.exe`:h()===`darwin`?process.arch===`arm64`?`agent-browser-darwin-arm64`:`agent-browser-darwin-x64`:`agent-browser-linux-${process.arch===`arm64`?`arm64`:`x64`}`,i=[];e&&!e.includes(`MODULE_NOT_FOUND`)&&(i.push(e),i.push(v(e,`..`)));try{let e=v(n(`npm config get cache`,{encoding:`utf8`,timeout:5e3,windowsHide:!0,stdio:`pipe`}).trim(),`_npx`);if(s(e)){let n=d(e,{withFileTypes:!0});for(let r of n){if(!r.isDirectory())continue;let n=v(e,r.name,`node_modules`,`agent-browser`);if(s(v(n,`bin`,t))){i.push(n);break}}}}catch{}for(let e of i){let n=v(e,`bin`,t);if(s(n)){let t=v(a,`agent-browser`);s(t)||c(t,{recursive:!0});let i=E(a);o(n,i);let l=v(e,`bin`,`agent-browser.js`);s(l)&&o(l,v(t,`agent-browser.js`)),te(a,b),u=i,r?.(`Cached agent-browser at ${i}`);break}}}catch{}return r?.(`agent-browser ready`),u}async function se(e){try{return t(e,[`--version`],{encoding:`utf8`,windowsHide:!0,stdio:`pipe`,timeout:5e3}).trim()}catch{return null}}function ce(e){if(T())return!0;let t=w(e);return ae(t)||s(E(t))}const le=[`ui`,`headless`];function ue(e){return le.includes(e)?e:`headless`}function de(e){let t=[];return e===`headless`&&t.push(`--headless`),t}function fe(e){return{headless:e===`headless`,args:de(e)}}var D=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}},pe=class{tabs=new D;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 O={defaultMode:`ui`,browsersPath:null,userDataDirRoot:null,idleShutdownMinutes:0,allowInternalSchemes:!1,allowLoopback:!1,evalTimeoutMs:3e4,evalMaxResultBytes:262144,redactPasswordFieldsInScreenshots:!0,engine:`chrome`};function me(e){if(e.endsWith(`.exe`))return e;let t=v(_(e),`node_modules`,`agent-browser`,`bin`,`agent-browser-win32-x64.exe`);if(s(t))return t;if(!e.endsWith(`.cmd`)&&!e.endsWith(`.bat`)){if(s(`${e}.exe`))return`${e}.exe`;if(s(`${e}.cmd`))return`${e}.cmd`;if(s(`${e}.bat`))return`${e}.bat`}return e}function k(){return process.env.AIKIT_TMP_DIR||v(m(),`.aikit`,`tmp`)}function A(){return v(k(),`agent-browser-exec.jsonl`)}function j(e){try{c(k(),{recursive:!0}),i(A(),`${JSON.stringify(e)}\n`,`utf8`)}catch{}}var M=class{binaryPath=null;_currentMode=null;_isLaunched=!1;idleTimer=null;healthInterval=null;_lastExecDiagnostics=null;_daemonPid=null;tabs=new D;config;constructor(e={}){this.config={...O,...e}}get currentMode(){return this._currentMode}async launch(e,t){let n=ue(e??this.config.defaultMode);if(this._isLaunched&&this._currentMode===n)return;this._isLaunched&&this._currentMode!==n&&await this.close(),this._currentMode=n;let r=Date.now();this.binaryPath=await oe(this.config,t),j({kind:`install`,binaryPath:this.binaryPath,durationMs:Date.now()-r,timestamp:new Date().toISOString(),error:void 0});try{let e=(await this.exec(`--version`)).stdout.trim();t?.(`agent-browser ${e}`),j({kind:`version_check`,version:e,binaryPath:this.binaryPath,timestamp:new Date().toISOString(),error:void 0})}catch(e){throw j({kind:`version_check`,version:null,binaryPath:this.binaryPath,timestamp:new Date().toISOString(),error:e instanceof Error?e.message:String(e)}),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;if(h()===`win32`){let e=me(n);e!==n&&j({kind:`binary_path_resolved`,original:n,resolved:e,timestamp:new Date().toISOString()}),n=e}let r=[e,...t];if(h()===`win32`&&(n.endsWith(`.cmd`)||n.endsWith(`.bat`))){let e=`"${n}" ${r.map(e=>/[^\w/:@.\-_{}()/\\]/.test(e)?`"${e.replace(/"/g,`""`)}"`:e).join(` `)}`;return await this.execWithDiagnostics(e,[],!0,e,n,r)}return await this.execWithDiagnostics(n,r,!1,[n,...r].join(` `),n,r)}getLastExecDiagnostics(){return this._lastExecDiagnostics}get daemonPid(){return this._daemonPid}getExecLogPath(){return A()}startHealthChecks(e=15e3){this.stopHealthChecks(),this.healthInterval=setInterval(()=>{this.exec(`tab`,`list`,`--json`).catch(e=>{let t=e instanceof Error?e.message:String(e);j({kind:`health_check_failure`,command:`tab list --json`,exitCode:null,durationMs:0,daemonPid:this._daemonPid,timestamp:new Date().toISOString(),error:t})})},e)}stopHealthChecks(){this.healthInterval&&=(clearInterval(this.healthInterval),null)}async execWithDiagnostics(e,t,n,r,i,a){let o=Date.now(),s={timestamp:new Date().toISOString(),binaryPath:this.binaryPath??``,resolvedBinaryPath:i,args:a,usedShell:n,displayCommand:r};this._lastExecDiagnostics=s;try{let i=await this.execViaSpawn(e,t,{shell:n,displayCommand:r}),a=Date.now()-o;return s.exitCode=i.exitCode,this._lastExecDiagnostics=s,j({kind:`exec`,command:r,exitCode:i.exitCode,durationMs:a,daemonPid:this._daemonPid,timestamp:s.timestamp,stderr:i.exitCode===0?void 0:i.stderr.slice(0,2e3)}),i}catch(e){let t=Date.now()-o;throw s.error=e instanceof Error?e.message:String(e),this._lastExecDiagnostics=s,j({kind:`exec`,command:r,exitCode:null,durationMs:t,daemonPid:this._daemonPid,timestamp:s.timestamp,error:s.error}),e}}execViaSpawn(e,t,n={}){return new Promise((i,o)=>{let s=n.displayCommand??[e,...t].join(` `),c=!1,d=!1,p,m=`${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}`,h=v(g(),`aikit-agent-browser-${m}.stdout`),_=v(g(),`aikit-agent-browser-${m}.stderr`),y=l(h,`w+`),b=l(_,`w+`),x=r(e,t,{shell:n.shell??!1,stdio:[`ignore`,y,b],windowsHide:!0});x.unref(),a(y),a(b);let S=e=>{try{f(e)}catch{}},C=()=>{let e=``,t=``;try{e=u(h,`utf8`)}catch{e=``}try{t=u(_,`utf8`)}catch{t=``}return S(h),S(_),{stdout:e,stderr:t}},w=e=>{c||(c=!0,p&&clearTimeout(p),e())};p=setTimeout(()=>{d=!0,x.kill()},this.config.evalTimeoutMs),x.once(`error`,e=>{w(()=>{if(S(h),S(_),e.code===`ENOENT`){o(Error(`agent-browser binary not found at ${this.binaryPath}`));return}o(e)})}),x.once(`exit`,(e,t)=>{w(()=>{let n=C();if(d||t){o(Error(`agent-browser command timed out after ${this.config.evalTimeoutMs}ms: `+s));return}i({stdout:n.stdout,stderr:n.stderr,exitCode:e??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`,`--json`]:[`tab`,`new`,e,`--json`],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`}`);let a=N(i.stdout)??await this.readActiveTabId()??this.nextLocalTabId();return this.tabs.register(a,e,i.stdout.trim(),n),this.resetIdleTimer(),a}async screenshot(e,t){let n=t?.format??`png`,r=n===`jpeg`?`image/jpeg`:`image/png`,i=n===`jpeg`?`jpg`:`png`,a=v(t?.screenshotDir??g(),`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.tabExec(e,`screenshot`,...o);let s=u(a),c=s.toString(`base64`);try{f(a)}catch{}return this.resetIdleTimer(),{base64:c,mimeType:r,bytes:s.length}}async screenshotActiveTab(e){let t=e?.format??`png`,n=t===`jpeg`?`image/jpeg`:`image/png`,r=t===`jpeg`?`jpg`:`png`,i=v(e?.screenshotDir??g(),`aikit-screenshot-${Date.now()}.${r}`),a=[i];e?.fullPage&&a.push(`--full`),e?.screenshotDir&&a.push(`--screenshot-dir`,e.screenshotDir),e?.format===`jpeg`&&a.push(`--screenshot-format`,`jpeg`),e?.quality&&a.push(`--screenshot-quality`,String(e.quality)),e?.annotate&&a.push(`--annotate`),e?.selector&&a.push(`--element`,e.selector),await this.exec(`screenshot`,...a);let o=u(i),s=o.toString(`base64`);try{f(i)}catch{}return this.resetIdleTimer(),{base64:s,mimeType:n,bytes:o.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(){this.stopIdleTimer(),this._isLaunched&&(await this.closeRuntimeSession(),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(){if(this.stopIdleTimer(),!Number.isFinite(this.config.idleShutdownMinutes)||this.config.idleShutdownMinutes<=0){this._currentMode===`ui`&&this.startHealthChecks(15e3);return}let e=setTimeout(()=>{this.stopHealthChecks(),this.close()},this.config.idleShutdownMinutes*6e4);this._currentMode!==`ui`&&e.unref?.(),this.idleTimer=e}stopIdleTimer(){this.stopHealthChecks(),this.idleTimer&&=(clearTimeout(this.idleTimer),null)}async closeRuntimeSession(){try{await this.exec(`close`,`--all`).catch(()=>{})}catch{}}async readActiveTabId(){let e=await this.exec(`tab`,`list`,`--json`).catch(()=>null);return e?.exitCode===0?N(e.stdout):null}nextLocalTabId(){let e=this.tabs.listTabs().map(e=>/^t(\d+)$/.exec(e.tabId)?.[1]).filter(e=>e!==void 0).map(Number);return`t${e.length===0?1:Math.max(...e)+1}`}};function N(e){try{let t=JSON.parse(e);if(typeof t.data?.tabId==`string`)return t.data.tabId;let n=t.data?.tabs?.find(e=>e.active===!0);if(typeof n?.tabId==`string`)return n.tabId}catch{}return null}let P=null;function F(e){return P||=new M(e),P}async function he(){P&&=(await P.close(),null)}function I(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 L(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 R(e){return typeof e==`string`&&e.length>0?e:void 0}function z(e){return typeof e==`boolean`?e:void 0}function B(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}function V(e){return typeof e==`string`&&ge.includes(e)?e:void 0}function H(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{...O,defaultMode:V(process.env.AIKIT_BROWSER_DEFAULT_MODE)??V(t.defaultMode)??O.defaultMode,browsersPath:R(process.env.AIKIT_BROWSER_PATH)??R(process.env.AIKIT_BROWSER_BROWSERS_PATH)??R(t.browsersPath)??O.browsersPath,userDataDirRoot:R(t.userDataDirRoot)??O.userDataDirRoot,idleShutdownMinutes:H(`AIKIT_BROWSER_IDLE_MINUTES`)??B(t.idleShutdownMinutes)??O.idleShutdownMinutes,allowInternalSchemes:z(t.allowInternalSchemes)??O.allowInternalSchemes,allowLoopback:z(t.allowLoopback)??O.allowLoopback,evalTimeoutMs:H(`AIKIT_BROWSER_EVAL_TIMEOUT_MS`)??B(t.evalTimeoutMs)??O.evalTimeoutMs,evalMaxResultBytes:B(t.evalMaxResultBytes)??O.evalMaxResultBytes,redactPasswordFieldsInScreenshots:z(t.redactPasswordFieldsInScreenshots)??O.redactPasswordFieldsInScreenshots,engine:R(t.engine)??O.engine,proxy:R(t.proxy),viewport:R(t.viewport)}}function U(e,t){return{content:[{type:`text`,text:e}],structuredContent:t}}function W(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 G(e){try{let t=JSON.parse(e);if(t&&typeof t==`object`){let e=ye(t);if(e.length>0)return e.join(`
1
+ import{exec as e,execFileSync as t,execSync as n,spawn as r}from"node:child_process";import{appendFileSync as i,closeSync as a,copyFileSync as o,existsSync as s,mkdirSync as c,openSync as l,readFileSync as u,readdirSync as d,unlinkSync as f,writeFileSync as p}from"node:fs";import{homedir as m,platform as h,tmpdir as g}from"node:os";import{dirname as _,join as v}from"node:path";import{z as y}from"zod";const b=`0.26.0`,x=`.agent-browser-version`;function S(e){return typeof e==`string`?e.trim():e instanceof Buffer?e.toString(`utf8`).trim():``}function C(){return v(m(),`.aikit`,`browsers`)}function w(e){return e.browsersPath??process.env.AIKIT_BROWSER_PATH??process.env.AIKIT_BROWSER_BROWSERS_PATH??C()}function T(){try{let e=n(`${h()===`win32`?`where`:`which`} agent-browser`,{encoding:`utf8`,windowsHide:!0,stdio:`pipe`,timeout:3e3}).trim().split(/\r?\n/).filter(Boolean);if(e.length===0)return null;if(h()===`win32`){for(let t of e){if(t.endsWith(`.exe`)&&s(t))return t;let e=v(_(t),`node_modules`,`agent-browser`,`bin`,`agent-browser-win32-x64.exe`);if(s(e))return e}for(let t of e){if(s(`${t}.exe`))return`${t}.exe`;if(s(`${t}.cmd`))return`${t}.cmd`;if(s(`${t}.bat`))return`${t}.bat`}}let t=e[0];return s(t)?t:null}catch{return null}}function E(e){return v(e,`agent-browser`,ee())}function ee(){switch(h()){case`win32`:return`agent-browser.exe`;default:return`agent-browser`}}function te(e,t){try{p(v(e,x),t,`utf8`)}catch{}}function ne(e){try{return u(v(e,x),`utf8`).trim()}catch{return null}}function re(e){let t=ne(e);return t?ie(t,b)>=0:!1}function ie(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 ae(e){return!!(s(v(e,`chrome`))||s(v(m(),`.cache`,`agent-browser`,`chrome`)))}async function oe(t,r){let i=T();if(i)return r?.(`Using globally installed agent-browser`),i;let a=w(t);s(a)||c(a,{recursive:!0});let l=E(a);if(s(l)&&re(a))return r?.(`Using cached agent-browser at ${l}`),l;r?.(`Downloading agent-browser (first use)...`),await new Promise((t,n)=>{let r=new AbortController,i=setTimeout(()=>r.abort(),12e4),o=e(`npx -y agent-browser@latest install --install-dir "${a}"`,{timeout:12e4,windowsHide:!0,encoding:`utf8`,env:{...process.env,AGENT_BROWSER_CACHE_DIR:a},signal:r.signal},(e,r,a)=>{if(clearTimeout(i),e){let t=S(a)||e.message||`Unknown agent-browser install failure`;n(Error(`Failed to install agent-browser: ${t}`));return}t()});o.stdin&&o.stdin.destroy()});let u=l;try{let e=n(h()===`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=h()===`win32`?`agent-browser-win32-x64.exe`:h()===`darwin`?process.arch===`arm64`?`agent-browser-darwin-arm64`:`agent-browser-darwin-x64`:`agent-browser-linux-${process.arch===`arm64`?`arm64`:`x64`}`,i=[];e&&!e.includes(`MODULE_NOT_FOUND`)&&(i.push(e),i.push(v(e,`..`)));try{let e=v(n(`npm config get cache`,{encoding:`utf8`,timeout:5e3,windowsHide:!0,stdio:`pipe`}).trim(),`_npx`);if(s(e)){let n=d(e,{withFileTypes:!0});for(let r of n){if(!r.isDirectory())continue;let n=v(e,r.name,`node_modules`,`agent-browser`);if(s(v(n,`bin`,t))){i.push(n);break}}}}catch{}for(let e of i){let n=v(e,`bin`,t);if(s(n)){let t=v(a,`agent-browser`);s(t)||c(t,{recursive:!0});let i=E(a);o(n,i);let l=v(e,`bin`,`agent-browser.js`);s(l)&&o(l,v(t,`agent-browser.js`)),te(a,b),u=i,r?.(`Cached agent-browser at ${i}`);break}}}catch{}return r?.(`agent-browser ready`),u}async function se(e){try{return t(e,[`--version`],{encoding:`utf8`,windowsHide:!0,stdio:`pipe`,timeout:5e3}).trim()}catch{return null}}function ce(e){if(T())return!0;let t=w(e);return ae(t)||s(E(t))}const le=[`ui`,`headless`];function ue(e){return le.includes(e)?e:`headless`}function de(e){let t=[];return e===`headless`&&t.push(`--headless`),t}function fe(e){return{headless:e===`headless`,args:de(e)}}var D=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}},pe=class{tabs=new D;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 O={defaultMode:`ui`,browsersPath:null,userDataDirRoot:null,idleShutdownMinutes:0,allowInternalSchemes:!1,allowLoopback:!1,evalTimeoutMs:3e4,evalMaxResultBytes:262144,redactPasswordFieldsInScreenshots:!0,engine:`chrome`};function me(e){if(e.endsWith(`.exe`))return e;let t=v(_(e),`node_modules`,`agent-browser`,`bin`,`agent-browser-win32-x64.exe`);if(s(t))return t;if(!e.endsWith(`.cmd`)&&!e.endsWith(`.bat`)){if(s(`${e}.exe`))return`${e}.exe`;if(s(`${e}.cmd`))return`${e}.cmd`;if(s(`${e}.bat`))return`${e}.bat`}return e}function k(){return process.env.AIKIT_TMP_DIR||v(m(),`.aikit`,`tmp`)}function A(){return v(k(),`agent-browser-exec.jsonl`)}function j(e){try{c(k(),{recursive:!0}),i(A(),`${JSON.stringify(e)}\n`,`utf8`)}catch{}}var M=class{binaryPath=null;_currentMode=null;_isLaunched=!1;idleTimer=null;healthInterval=null;_lastExecDiagnostics=null;_daemonPid=null;tabs=new D;config;constructor(e={}){this.config={...O,...e}}get currentMode(){return this._currentMode}async launch(e,t){let n=ue(e??this.config.defaultMode);if(this._isLaunched&&this._currentMode===n)return;this._isLaunched&&this._currentMode!==n&&await this.close(),this._currentMode=n;let r=Date.now();this.binaryPath=await oe(this.config,t),j({kind:`install`,binaryPath:this.binaryPath,durationMs:Date.now()-r,timestamp:new Date().toISOString(),error:void 0});try{let e=(await this.exec(`--version`)).stdout.trim();t?.(`agent-browser ${e}`),j({kind:`version_check`,version:e,binaryPath:this.binaryPath,timestamp:new Date().toISOString(),error:void 0})}catch(e){throw j({kind:`version_check`,version:null,binaryPath:this.binaryPath,timestamp:new Date().toISOString(),error:e instanceof Error?e.message:String(e)}),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;if(h()===`win32`){let e=me(n);e!==n&&j({kind:`binary_path_resolved`,original:n,resolved:e,timestamp:new Date().toISOString()}),n=e}let r=[e,...t];if(h()===`win32`&&(n.endsWith(`.cmd`)||n.endsWith(`.bat`))){let e=`"${n}" ${r.map(e=>/[^\w/:@.\-_{}()/\\]/.test(e)?`"${e.replace(/"/g,`""`)}"`:e).join(` `)}`;return await this.execWithDiagnostics(e,[],!0,e,n,r)}return await this.execWithDiagnostics(n,r,!1,[n,...r].join(` `),n,r)}getLastExecDiagnostics(){return this._lastExecDiagnostics}get daemonPid(){return this._daemonPid}getExecLogPath(){return A()}startHealthChecks(e=15e3){!this._isLaunched||!this.binaryPath||(this.stopHealthChecks(),this.healthInterval=setInterval(()=>{this.exec(`tab`,`list`,`--json`).catch(e=>{let t=e instanceof Error?e.message:String(e);j({kind:`health_check_failure`,command:`tab list --json`,exitCode:null,durationMs:0,daemonPid:this._daemonPid,timestamp:new Date().toISOString(),error:t})})},e))}stopHealthChecks(){this.healthInterval&&=(clearInterval(this.healthInterval),null)}async execWithDiagnostics(e,t,n,r,i,a){let o=Date.now(),s={timestamp:new Date().toISOString(),binaryPath:this.binaryPath??``,resolvedBinaryPath:i,args:a,usedShell:n,displayCommand:r};this._lastExecDiagnostics=s;try{let i=await this.execViaSpawn(e,t,{shell:n,displayCommand:r}),a=Date.now()-o;return s.exitCode=i.exitCode,this._lastExecDiagnostics=s,j({kind:`exec`,command:r,exitCode:i.exitCode,durationMs:a,daemonPid:this._daemonPid,timestamp:s.timestamp,stderr:i.exitCode===0?void 0:i.stderr.slice(0,2e3)}),i}catch(e){let t=Date.now()-o;throw s.error=e instanceof Error?e.message:String(e),this._lastExecDiagnostics=s,j({kind:`exec`,command:r,exitCode:null,durationMs:t,daemonPid:this._daemonPid,timestamp:s.timestamp,error:s.error}),e}}execViaSpawn(e,t,n={}){return new Promise((i,o)=>{let s=n.displayCommand??[e,...t].join(` `),c=!1,d=!1,p,m=`${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}`,h=v(g(),`aikit-agent-browser-${m}.stdout`),_=v(g(),`aikit-agent-browser-${m}.stderr`),y=l(h,`w+`),b=l(_,`w+`),x=r(e,t,{shell:n.shell??!1,stdio:[`ignore`,y,b],windowsHide:!0});x.unref(),a(y),a(b);let S=e=>{try{f(e)}catch{}},C=()=>{let e=``,t=``;try{e=u(h,`utf8`)}catch{e=``}try{t=u(_,`utf8`)}catch{t=``}return S(h),S(_),{stdout:e,stderr:t}},w=e=>{c||(c=!0,p&&clearTimeout(p),e())};p=setTimeout(()=>{d=!0;try{x.kill()}catch{}},this.config.evalTimeoutMs),x.once(`error`,e=>{w(()=>{if(S(h),S(_),e.code===`ENOENT`){o(Error(`agent-browser binary not found at ${this.binaryPath}`));return}o(e)})}),x.once(`exit`,(e,t)=>{w(()=>{let n=C();if(d){o(Error(`agent-browser command timed out after ${this.config.evalTimeoutMs}ms: ${s}`));return}if(t){o(Error(`agent-browser command killed by signal ${t}: ${s}`));return}let r=e??0;if(r!==0){let e=n.stderr||n.stdout||`Unknown error`;o(Error(`agent-browser command failed (exit ${r}): ${e.trim().slice(0,500)}: ${s}`));return}i({stdout:n.stdout,stderr:n.stderr,exitCode:r})})})})}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`,`--json`]:[`tab`,`new`,e,`--json`],i=await this.exec(...r),a=N(i.stdout)??await this.readActiveTabId()??this.nextLocalTabId();return this.tabs.register(a,e,i.stdout.trim(),n),this.resetIdleTimer(),a}async screenshot(e,t){let n=t?.format??`png`,r=n===`jpeg`?`image/jpeg`:`image/png`,i=n===`jpeg`?`jpg`:`png`,a=v(t?.screenshotDir??g(),`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.tabExec(e,`screenshot`,...o);let s=u(a),c=s.toString(`base64`);try{f(a)}catch{}return this.resetIdleTimer(),{base64:c,mimeType:r,bytes:s.length}}async screenshotActiveTab(e){let t=e?.format??`png`,n=t===`jpeg`?`image/jpeg`:`image/png`,r=t===`jpeg`?`jpg`:`png`,i=v(e?.screenshotDir??g(),`aikit-screenshot-${Date.now()}.${r}`),a=[i];e?.fullPage&&a.push(`--full`),e?.screenshotDir&&a.push(`--screenshot-dir`,e.screenshotDir),e?.format===`jpeg`&&a.push(`--screenshot-format`,`jpeg`),e?.quality&&a.push(`--screenshot-quality`,String(e.quality)),e?.annotate&&a.push(`--annotate`),e?.selector&&a.push(`--element`,e.selector),await this.exec(`screenshot`,...a);let o=u(i),s=o.toString(`base64`);try{f(i)}catch{}return this.resetIdleTimer(),{base64:s,mimeType:n,bytes:o.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(){this.stopIdleTimer(),this._isLaunched&&(await this.closeRuntimeSession(),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(){if(this.stopIdleTimer(),!Number.isFinite(this.config.idleShutdownMinutes)||this.config.idleShutdownMinutes<=0){this._currentMode===`ui`&&this.startHealthChecks(15e3);return}let e=setTimeout(()=>{this.stopHealthChecks(),this.close()},this.config.idleShutdownMinutes*6e4);this._currentMode!==`ui`&&e.unref?.(),this.idleTimer=e}stopIdleTimer(){this.stopHealthChecks(),this.idleTimer&&=(clearTimeout(this.idleTimer),null)}async closeRuntimeSession(){try{await this.exec(`close`,`--all`).catch(()=>{})}catch{}}async readActiveTabId(){let e=await this.exec(`tab`,`list`,`--json`).catch(()=>null);return e?.exitCode===0?N(e.stdout):null}nextLocalTabId(){let e=this.tabs.listTabs().map(e=>/^t(\d+)$/.exec(e.tabId)?.[1]).filter(e=>e!==void 0).map(Number);return`t${e.length===0?1:Math.max(...e)+1}`}};function N(e){try{let t=JSON.parse(e);if(typeof t.data?.tabId==`string`)return t.data.tabId;let n=t.data?.tabs?.find(e=>e.active===!0);if(typeof n?.tabId==`string`)return n.tabId}catch{}return null}let P=null;function F(e){return P||=new M(e),P}async function he(){P&&=(await P.close(),null)}function I(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 L(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 R(e){return typeof e==`string`&&e.length>0?e:void 0}function z(e){return typeof e==`boolean`?e:void 0}function B(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}function V(e){return typeof e==`string`&&ge.includes(e)?e:void 0}function H(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{...O,defaultMode:V(process.env.AIKIT_BROWSER_DEFAULT_MODE)??V(t.defaultMode)??O.defaultMode,browsersPath:R(process.env.AIKIT_BROWSER_PATH)??R(process.env.AIKIT_BROWSER_BROWSERS_PATH)??R(t.browsersPath)??O.browsersPath,userDataDirRoot:R(t.userDataDirRoot)??O.userDataDirRoot,idleShutdownMinutes:H(`AIKIT_BROWSER_IDLE_MINUTES`)??B(t.idleShutdownMinutes)??O.idleShutdownMinutes,allowInternalSchemes:z(t.allowInternalSchemes)??O.allowInternalSchemes,allowLoopback:z(t.allowLoopback)??O.allowLoopback,evalTimeoutMs:H(`AIKIT_BROWSER_EVAL_TIMEOUT_MS`)??B(t.evalTimeoutMs)??O.evalTimeoutMs,evalMaxResultBytes:B(t.evalMaxResultBytes)??O.evalMaxResultBytes,redactPasswordFieldsInScreenshots:z(t.redactPasswordFieldsInScreenshots)??O.redactPasswordFieldsInScreenshots,engine:R(t.engine)??O.engine,proxy:R(t.proxy),viewport:R(t.viewport)}}function U(e,t){return{content:[{type:`text`,text:e}],structuredContent:t}}function W(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 G(e){try{let t=JSON.parse(e);if(t&&typeof t==`object`){let e=ye(t);if(e.length>0)return e.join(`
2
2
  `)}return JSON.stringify(t,null,2)}catch{return e}}function ye(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=be(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&&ye(e,t+1,n);return n}function be(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 xe(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=F(e),m=p.resolvePageId(t);switch(n){case`click`:{let e=W({ref:r,selector:i,element:a},`browser_act(click)`);await p.tabExec(m,`click`,e);break}case`type`:{let e=W({ref:r,selector:i,element:a},`browser_act(type)`);await p.tabExec(m,`fill`,e,o??``);break}case`press`:{let e=W({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=W({ref:r,selector:i,element:a},`browser_act(hover)`);await p.tabExec(m,`hover`,e);break}case`drag`:{let e=W({ref:l??r,selector:u??i,element:a},`browser_act(drag) source`),t=W({ref:d,selector:f??c,element:a},`browser_act(drag) target`);await p.tabExec(m,`drag`,e,t);break}case`select`:{let e=W({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=W({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=W({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(),U(`ok`,{ok:!0})}}function Se(e){return async({pageId:t,subAction:n,level:r,bufferSize:i,expression:a})=>{let o=F(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(),U(`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 U(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(),U(`Console cleared`,{cleared:!0});default:return U(`Unknown console sub-action`,{error:`Unknown console sub-action`})}}}function Ce(e){return async({pageId:t,accept:n,promptText:r})=>{let i=F(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(),U(`Dialog ${n?`accepted`:`dismissed`}`,{accepted:n})}}function we(e){return async({pageId:t})=>{let n=F(e),r=n.resolvePageId(t),i=await n.tabExec(r,`diff`,`snapshot`);return n.resetIdleTimer(),U(i.stdout,{pageId:r,diff:i.stdout})}}function Te(e){return async({pageId:t,code:n,timeoutMs:r})=>{let i=F(e),a=i.resolvePageId(t),o=r??e.evalTimeoutMs,s=await i.tabExec(a,`evaluate`,`--timeout=${o}`,`--`,n);i.resetIdleTimer();let c=L(s.stdout,e.evalMaxResultBytes);return U(c.result,{pageId:a,result:c.result,truncated:c.truncated})}}function Ee(e){return async({pageId:t,url:n,method:r,headers:i,body:a,timeoutMs:o,includeHeaders:s})=>{let c=F(e),l=c.resolvePageId(t),u=o??e.evalTimeoutMs,d=De(n,r??`GET`,s??!0,i,a),f=await c.tabExec(l,`evaluate`,`--timeout=${u}`,`--`,d);return c.resetIdleTimer(),U(f.stdout,{pageId:l,response:f.stdout})}}function De(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.402",
5
+ "version": "0.1.403",
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-LWbGDuOu.js`);await e(t,n.port)}else{let{startStdioMode:e}=await import(`./server-stdio-DjMKdjKp.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-PS0cutWS.js`);await e(t,n.port)}else{let{startStdioMode:e}=await import(`./server-stdio-BaGZP7jB.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-BRle4CHZ.js`);await e(n,r.port)}else{let{startStdioMode:e}=await import(`./server-stdio-BxNn-z-v.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-CM9is7PK.js`);await e(n,r.port)}else{let{startStdioMode:e}=await import(`./server-stdio-BPkj14FV.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};
@@ -2919,7 +2919,7 @@ None.`:`### Stale Lessons\n${l.map(e=>`- **${e.title}** (\`${e.path}\`) — effe
2919
2919
  navigator.sendBeacon('/callback', new Blob([body], { type: 'application/json' }));
2920
2920
  });
2921
2921
  })();
2922
- <\/script>`}function Gm(e){try{if(process.platform===`win32`){let t=Xn(`rundll32`,[`url.dll,FileProtocolHandler`,e],{detached:!0,stdio:`ignore`,windowsHide:!0});t.on(`error`,()=>{}),t.unref();return}if(process.platform===`darwin`){Jn(`open`,[e]);return}Jn(`xdg-open`,[e])}catch{}}function Km(e){let t=e instanceof Error?e.message:String(e);return t.length>500?`${t.slice(0,497)}...`:t}function qm(e){let t=e.getLastExecDiagnostics;return typeof t==`function`?t.call(e):void 0}function Jm(){return process.env.AIKIT_TMP_DIR||P(Zn(),`.aikit`,`tmp`)}function Ym(){return P(Jm(),`present-browser-launch.jsonl`)}function Xm(e,t,n){return{traceId:Ye(8).toString(`hex`),timestamp:new Date().toISOString(),url:e,platform:process.platform,agentBrowserArgsBefore:t,requiredAgentBrowserArgs:n,changedAgentBrowserArgs:!1,engineLaunch:{ok:!1,retried:!1},engineOpen:{ok:!1,retried:!1},viewport:{ok:!1}}}function Zm(e,t){if(!(process.env.VITEST||process.env.NODE_ENV===`test`))try{ke(Jm(),{recursive:!0}),De(Ym(),`${JSON.stringify({event:`launch_outcome`,outcome:e.kind,pageId:e.kind===`opened_managed`?e.pageId:void 0,reason:e.kind===`failed`?e.reason:t.fallback?.reason,diagnostics:t})}\n`,`utf8`)}catch{}}function Qm(e){if(!(process.env.VITEST||process.env.NODE_ENV===`test`))try{ke(Jm(),{recursive:!0}),De(Ym(),`${JSON.stringify({event:`session`,kind:e.kind,sessionId:e.sessionId,surfaceId:e.surfaceId,detail:e.detail,timingMs:e.timingMs,error:e.error,timestamp:new Date().toISOString()})}\n`,`utf8`)}catch{}}function $m(e,t){let n={...e,diagnostics:t};return Zm(n,t),n}function eh(e){let t=e.diagnostics;return t?{presentBrowserLaunch:{outcome:e.kind,pageId:e.kind===`opened_managed`?e.pageId:void 0,reason:e.kind===`failed`?e.reason:t.fallback?.reason,logPath:Ym(),...t}}:{}}async function th(e){let t=process.env.AGENT_BROWSER_ARGS??``,n=[`--start-maximized`,`--disable-infobars`,`--disable-popup-blocking`],r=Xm(e,t,n);try{let i=t?t.split(`,`):[],a=!1;for(let e of n)i.includes(e)||(i.push(e),a=!0);a&&(process.env.AGENT_BROWSER_ARGS=i.join(`,`)),r.changedAgentBrowserArgs=a,r.agentBrowserArgsAfter=process.env.AGENT_BROWSER_ARGS??``;let o=$n();try{await o.launch(`ui`),r.engineLaunch.ok=!0,r.lastExecAfterLaunch=qm(o)}catch(e){r.engineLaunch.firstError=Km(e),r.lastExecAfterLaunch=qm(o),r.engineLaunch.retried=!0,console.warn(`[present] Engine launch failed, retrying once:`,r.engineLaunch.firstError),await o.close().catch(()=>{});try{await o.launch(`ui`),r.engineLaunch.ok=!0,r.lastExecAfterLaunch=qm(o),console.warn(`[present] Engine launch retry succeeded`)}catch(e){throw r.engineLaunch.retryError=Km(e),r.lastExecAfterLaunch=qm(o),console.warn(`[present] Engine launch retry also failed:`,r.engineLaunch.retryError),e}}o.startHealthChecks(15e3),o.resetIdleTimer();let s=`t0`;try{s=await o.open(e),r.engineOpen.ok=!0,r.engineOpen.pageId=s,r.lastExecAfterOpen=qm(o)}catch(t){r.engineOpen.firstError=Km(t),r.lastExecAfterOpen=qm(o),r.engineOpen.retried=!0,console.warn(`[present] Engine open failed, restarting engine and retrying:`,r.engineOpen.firstError),await o.close().catch(()=>{}),await o.launch(`ui`),r.lastExecAfterLaunch=qm(o),o.resetIdleTimer();try{s=await o.open(e),r.engineOpen.ok=!0,r.engineOpen.pageId=s,r.lastExecAfterOpen=qm(o),console.warn(`[present] Engine open retry succeeded`)}catch(e){throw r.engineOpen.retryError=Km(e),r.lastExecAfterOpen=qm(o),console.warn(`[present] Engine open retry also failed:`,r.engineOpen.retryError),e}}try{await o.exec(`set`,`viewport`,`1920`,`1080`),r.lastExecAfterViewport=qm(o),await o.exec(`eval`,`setTimeout(function(){window.focus()}, 300);`).catch(()=>{}),r.viewport.ok=!0}catch(e){r.viewport.error=Km(e),r.lastExecAfterViewport=qm(o)}return $m({kind:`opened_managed`,url:e,pageId:s},r)}catch(t){return r.fallback={used:!0,reason:Km(t)},Gm(e),$m({kind:`opened_system`,url:e},r)}}function nh(e,t,n,r){let i=[e.title];return e.description&&i.push(e.description),i.push(``),n.kind===`opened_managed`?i.push(`Opened in browser — ${t}`):n.kind===`opened_system`?i.push(`Opened in system browser — ${t}`):(i.push(`Failed to open browser: ${n.reason}`),i.push(`Manual URL: ${t}`)),i.push(r),i.join(`
2922
+ <\/script>`}function Gm(e){try{if(process.platform===`win32`){let t=Xn(`rundll32`,[`url.dll,FileProtocolHandler`,e],{detached:!0,stdio:`ignore`,windowsHide:!0});t.on(`error`,()=>{}),t.unref();return}if(process.platform===`darwin`){Jn(`open`,[e]);return}Jn(`xdg-open`,[e])}catch{}}function Km(e){let t=e instanceof Error?e.message:String(e);return t.length>500?`${t.slice(0,497)}...`:t}function qm(e){let t=e.getLastExecDiagnostics;return typeof t==`function`?t.call(e):void 0}function Jm(){return process.env.AIKIT_TMP_DIR||P(Zn(),`.aikit`,`tmp`)}function Ym(){return P(Jm(),`present-browser-launch.jsonl`)}function Xm(e,t,n){return{traceId:Ye(8).toString(`hex`),timestamp:new Date().toISOString(),url:e,platform:process.platform,agentBrowserArgsBefore:t,requiredAgentBrowserArgs:n,changedAgentBrowserArgs:!1,engineLaunch:{ok:!1,retried:!1},engineOpen:{ok:!1,retried:!1}}}function Zm(e,t){if(!(process.env.VITEST||process.env.NODE_ENV===`test`))try{ke(Jm(),{recursive:!0}),De(Ym(),`${JSON.stringify({event:`launch_outcome`,outcome:e.kind,pageId:e.kind===`opened_managed`?e.pageId:void 0,reason:e.kind===`failed`?e.reason:t.fallback?.reason,diagnostics:t})}\n`,`utf8`)}catch{}}function Qm(e){if(!(process.env.VITEST||process.env.NODE_ENV===`test`))try{ke(Jm(),{recursive:!0}),De(Ym(),`${JSON.stringify({event:`session`,kind:e.kind,sessionId:e.sessionId,surfaceId:e.surfaceId,detail:e.detail,timingMs:e.timingMs,error:e.error,timestamp:new Date().toISOString()})}\n`,`utf8`)}catch{}}function $m(e,t){let n={...e,diagnostics:t};return Zm(n,t),n}function eh(e){let t=e.diagnostics;return t?{presentBrowserLaunch:{outcome:e.kind,pageId:e.kind===`opened_managed`?e.pageId:void 0,reason:e.kind===`failed`?e.reason:t.fallback?.reason,logPath:Ym(),...t}}:{}}async function th(e){let t=process.env.AGENT_BROWSER_ARGS??``,n=[`--start-maximized`,`--disable-infobars`,`--disable-popup-blocking`],r=Xm(e,t,n);try{let i=t?t.split(`,`):[],a=!1;for(let e of n)i.includes(e)||(i.push(e),a=!0);a&&(process.env.AGENT_BROWSER_ARGS=i.join(`,`)),r.changedAgentBrowserArgs=a,r.agentBrowserArgsAfter=process.env.AGENT_BROWSER_ARGS??``;let o=$n();try{await o.launch(`ui`),r.engineLaunch.ok=!0,r.lastExecAfterLaunch=qm(o)}catch(e){r.engineLaunch.firstError=Km(e),r.lastExecAfterLaunch=qm(o),r.engineLaunch.retried=!0,console.warn(`[present] Engine launch failed, retrying once:`,r.engineLaunch.firstError),await o.close().catch(()=>{});try{await o.launch(`ui`),r.engineLaunch.ok=!0,r.lastExecAfterLaunch=qm(o),console.warn(`[present] Engine launch retry succeeded`)}catch(e){throw r.engineLaunch.retryError=Km(e),r.lastExecAfterLaunch=qm(o),console.warn(`[present] Engine launch retry also failed:`,r.engineLaunch.retryError),e}}o.resetIdleTimer();let s=`t0`;try{s=await o.open(e),r.engineOpen.ok=!0,r.engineOpen.pageId=s,r.lastExecAfterOpen=qm(o)}catch(t){r.engineOpen.firstError=Km(t),r.lastExecAfterOpen=qm(o),r.engineOpen.retried=!0,console.warn(`[present] Engine open failed, restarting engine and retrying:`,r.engineOpen.firstError),await o.close().catch(()=>{}),await o.launch(`ui`),r.lastExecAfterLaunch=qm(o),o.resetIdleTimer();try{s=await o.open(e),r.engineOpen.ok=!0,r.engineOpen.pageId=s,r.lastExecAfterOpen=qm(o),console.warn(`[present] Engine open retry succeeded`)}catch(e){throw r.engineOpen.retryError=Km(e),r.lastExecAfterOpen=qm(o),console.warn(`[present] Engine open retry also failed:`,r.engineOpen.retryError),e}}try{o.exec(`eval`,`setTimeout(function(){window.focus()}, 300);`).catch(e=>{let t=e instanceof Error?e.message:String(e);console.warn(`[present] window.focus eval failed (non-critical):`,t)})}catch{}return $m({kind:`opened_managed`,url:e,pageId:s},r)}catch(t){return r.fallback={used:!0,reason:Km(t)},Gm(e),$m({kind:`opened_system`,url:e},r)}}function nh(e,t,n,r){let i=[e.title];return e.description&&i.push(e.description),i.push(``),n.kind===`opened_managed`?i.push(`Opened in browser — ${t}`):n.kind===`opened_system`?i.push(`Opened in system browser — ${t}`):(i.push(`Failed to open browser: ${n.reason}`),i.push(`Manual URL: ${t}`)),i.push(r),i.join(`
2923
2923
  `)}function rh(e){return e.some(e=>e.id!==`__dismiss`)}function ih(e){return e.replace(`</head>`,`${cg}\n</head>`).replace(`</body>`,`${lg}\n</body>`)}function ah(e){if(!e.headersSent)try{e.writeHead(500,{"Content-Type":`text/plain`}),e.end(`Internal Server Error`)}catch{try{e.end()}catch{}}}function oh(e,t){let n=e.headers.referer;return typeof n==`string`&&n.length>0?n:`http://127.0.0.1:${t.port}`}async function sh(e,t){let n=$n();n.isLaunched()||await n.launch(`headless`);let{base64:r}=await n.screenshotActiveTab({fullPage:t?.fullPage!==!1,format:t?.format,quality:t?.quality,annotate:t?.annotate});return Buffer.from(r,`base64`)}async function ch(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 sh(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),ah(e)}}async function lh(e,t){if(!t){Z(e,503,`CLIPBOARD_CAPTURE_TARGET_MISSING`,`Clipboard target is not ready.`);return}try{let n=await sh(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),Z(e,500,`CLIPBOARD_CAPTURE_FAILED`,`Clipboard capture failed: ${n}`)}}async function uh(e,t){let n=[];e.on(`data`,e=>n.push(e)),e.on(`end`,async()=>{let e=Buffer.concat(n);if(e.length===0){Z(t,400,`EMPTY_BODY`,`No image data received.`);return}try{await dh(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),Z(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),Z(t,500,`REQUEST_ERROR`,`Request stream error.`)})}async function dh(e){let t=P(Qn(),`aikit-clipboard-${Date.now()}-${Ye(4).toString(`hex`)}.png`);try{if(Fe(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)=>{qn(`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)=>{qn(`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)=>{qn(`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)=>{qn(`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{Pe(t)}catch{}}}function fh(e,t){return e.replace(/'\/callback'/g,`'/present/${t}/callback'`).replace(/"\/callback"/g,`"/present/${t}/callback"`).replace(/'\/ready'/g,`'/present/${t}/ready'`).replace(/"\/ready"/g,`"/present/${t}/ready"`)}function ph(e,t){return e.replace(/src="\/viewer"/g,`src="/present/${t}/viewer"`)}async function mh(e,t,n){if(Bh(`<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=Dn({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(`
2924
2924
  `);return{content:[{type:`text`,text:`[ERROR:VALIDATION] Template "${t.id}" data validation failed:\n${e}\n\nExpected schema: ${JSON.stringify(t.inputSchema,null,2)}`}],structuredContent:{kind:`error`,error:{code:`VIEWER_DATA_INVALID`,message:`Template "${t.id}" data validation failed:\n${e}\n\nExpected schema: ${JSON.stringify(t.inputSchema,null,2)}`}},isError:!0}}}let r=ih(Cp(t.resolveHtml(),e.data??null,t.injectId,t.transformData)),i=Pm(),a=Ye(16).toString(`hex`),o=i.createSession({surfaceId:`viewer`,transport:`viewer`,nonce:a});if(!o.ok)return{content:[{type:`text`,text:`${e.title}\n\nUnable to start local browser transport.`}],structuredContent:{kind:`error`,error:{code:`BROWSER_START_FAILED`,message:o.error.message}},isError:!0};let s=o.session.id,c=gm(`viewer`,e.actions??[],i,s,a),l=ph(Er({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>`,` ${ug(a)}`,`</div>`].join(`
2925
2925
  `),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(`
@@ -2920,7 +2920,7 @@ None.`:`### Stale Lessons\n${l.map(e=>`- **${e.title}** (\`${e.path}\`) — effe
2920
2920
  navigator.sendBeacon('/callback', new Blob([body], { type: 'application/json' }));
2921
2921
  });
2922
2922
  })();
2923
- <\/script>`}function Wm(e){try{if(process.platform===`win32`){let t=yr(`rundll32`,[`url.dll,FileProtocolHandler`,e],{detached:!0,stdio:`ignore`,windowsHide:!0});t.on(`error`,()=>{}),t.unref();return}if(process.platform===`darwin`){_r(`open`,[e]);return}_r(`xdg-open`,[e])}catch{}}function Gm(e){let t=e instanceof Error?e.message:String(e);return t.length>500?`${t.slice(0,497)}...`:t}function Km(e){let t=e.getLastExecDiagnostics;return typeof t==`function`?t.call(e):void 0}function qm(){return process.env.AIKIT_TMP_DIR||F(Kn(),`.aikit`,`tmp`)}function Jm(){return F(qm(),`present-browser-launch.jsonl`)}function Ym(e,t,n){return{traceId:Je(8).toString(`hex`),timestamp:new Date().toISOString(),url:e,platform:process.platform,agentBrowserArgsBefore:t,requiredAgentBrowserArgs:n,changedAgentBrowserArgs:!1,engineLaunch:{ok:!1,retried:!1},engineOpen:{ok:!1,retried:!1},viewport:{ok:!1}}}function Xm(e,t){if(!(process.env.VITEST||process.env.NODE_ENV===`test`))try{Oe(qm(),{recursive:!0}),Ee(Jm(),`${JSON.stringify({event:`launch_outcome`,outcome:e.kind,pageId:e.kind===`opened_managed`?e.pageId:void 0,reason:e.kind===`failed`?e.reason:t.fallback?.reason,diagnostics:t})}\n`,`utf8`)}catch{}}function Zm(e){if(!(process.env.VITEST||process.env.NODE_ENV===`test`))try{Oe(qm(),{recursive:!0}),Ee(Jm(),`${JSON.stringify({event:`session`,kind:e.kind,sessionId:e.sessionId,surfaceId:e.surfaceId,detail:e.detail,timingMs:e.timingMs,error:e.error,timestamp:new Date().toISOString()})}\n`,`utf8`)}catch{}}function Qm(e,t){let n={...e,diagnostics:t};return Xm(n,t),n}function $m(e){let t=e.diagnostics;return t?{presentBrowserLaunch:{outcome:e.kind,pageId:e.kind===`opened_managed`?e.pageId:void 0,reason:e.kind===`failed`?e.reason:t.fallback?.reason,logPath:Jm(),...t}}:{}}async function eh(e){let t=process.env.AGENT_BROWSER_ARGS??``,n=[`--start-maximized`,`--disable-infobars`,`--disable-popup-blocking`],r=Ym(e,t,n);try{let i=t?t.split(`,`):[],a=!1;for(let e of n)i.includes(e)||(i.push(e),a=!0);a&&(process.env.AGENT_BROWSER_ARGS=i.join(`,`)),r.changedAgentBrowserArgs=a,r.agentBrowserArgsAfter=process.env.AGENT_BROWSER_ARGS??``;let o=Jn();try{await o.launch(`ui`),r.engineLaunch.ok=!0,r.lastExecAfterLaunch=Km(o)}catch(e){r.engineLaunch.firstError=Gm(e),r.lastExecAfterLaunch=Km(o),r.engineLaunch.retried=!0,console.warn(`[present] Engine launch failed, retrying once:`,r.engineLaunch.firstError),await o.close().catch(()=>{});try{await o.launch(`ui`),r.engineLaunch.ok=!0,r.lastExecAfterLaunch=Km(o),console.warn(`[present] Engine launch retry succeeded`)}catch(e){throw r.engineLaunch.retryError=Gm(e),r.lastExecAfterLaunch=Km(o),console.warn(`[present] Engine launch retry also failed:`,r.engineLaunch.retryError),e}}o.startHealthChecks(15e3),o.resetIdleTimer();let s=`t0`;try{s=await o.open(e),r.engineOpen.ok=!0,r.engineOpen.pageId=s,r.lastExecAfterOpen=Km(o)}catch(t){r.engineOpen.firstError=Gm(t),r.lastExecAfterOpen=Km(o),r.engineOpen.retried=!0,console.warn(`[present] Engine open failed, restarting engine and retrying:`,r.engineOpen.firstError),await o.close().catch(()=>{}),await o.launch(`ui`),r.lastExecAfterLaunch=Km(o),o.resetIdleTimer();try{s=await o.open(e),r.engineOpen.ok=!0,r.engineOpen.pageId=s,r.lastExecAfterOpen=Km(o),console.warn(`[present] Engine open retry succeeded`)}catch(e){throw r.engineOpen.retryError=Gm(e),r.lastExecAfterOpen=Km(o),console.warn(`[present] Engine open retry also failed:`,r.engineOpen.retryError),e}}try{await o.exec(`set`,`viewport`,`1920`,`1080`),r.lastExecAfterViewport=Km(o),await o.exec(`eval`,`setTimeout(function(){window.focus()}, 300);`).catch(()=>{}),r.viewport.ok=!0}catch(e){r.viewport.error=Gm(e),r.lastExecAfterViewport=Km(o)}return Qm({kind:`opened_managed`,url:e,pageId:s},r)}catch(t){return r.fallback={used:!0,reason:Gm(t)},Wm(e),Qm({kind:`opened_system`,url:e},r)}}function th(e,t,n,r){let i=[e.title];return e.description&&i.push(e.description),i.push(``),n.kind===`opened_managed`?i.push(`Opened in browser — ${t}`):n.kind===`opened_system`?i.push(`Opened in system browser — ${t}`):(i.push(`Failed to open browser: ${n.reason}`),i.push(`Manual URL: ${t}`)),i.push(r),i.join(`
2923
+ <\/script>`}function Wm(e){try{if(process.platform===`win32`){let t=yr(`rundll32`,[`url.dll,FileProtocolHandler`,e],{detached:!0,stdio:`ignore`,windowsHide:!0});t.on(`error`,()=>{}),t.unref();return}if(process.platform===`darwin`){_r(`open`,[e]);return}_r(`xdg-open`,[e])}catch{}}function Gm(e){let t=e instanceof Error?e.message:String(e);return t.length>500?`${t.slice(0,497)}...`:t}function Km(e){let t=e.getLastExecDiagnostics;return typeof t==`function`?t.call(e):void 0}function qm(){return process.env.AIKIT_TMP_DIR||F(Kn(),`.aikit`,`tmp`)}function Jm(){return F(qm(),`present-browser-launch.jsonl`)}function Ym(e,t,n){return{traceId:Je(8).toString(`hex`),timestamp:new Date().toISOString(),url:e,platform:process.platform,agentBrowserArgsBefore:t,requiredAgentBrowserArgs:n,changedAgentBrowserArgs:!1,engineLaunch:{ok:!1,retried:!1},engineOpen:{ok:!1,retried:!1}}}function Xm(e,t){if(!(process.env.VITEST||process.env.NODE_ENV===`test`))try{Oe(qm(),{recursive:!0}),Ee(Jm(),`${JSON.stringify({event:`launch_outcome`,outcome:e.kind,pageId:e.kind===`opened_managed`?e.pageId:void 0,reason:e.kind===`failed`?e.reason:t.fallback?.reason,diagnostics:t})}\n`,`utf8`)}catch{}}function Zm(e){if(!(process.env.VITEST||process.env.NODE_ENV===`test`))try{Oe(qm(),{recursive:!0}),Ee(Jm(),`${JSON.stringify({event:`session`,kind:e.kind,sessionId:e.sessionId,surfaceId:e.surfaceId,detail:e.detail,timingMs:e.timingMs,error:e.error,timestamp:new Date().toISOString()})}\n`,`utf8`)}catch{}}function Qm(e,t){let n={...e,diagnostics:t};return Xm(n,t),n}function $m(e){let t=e.diagnostics;return t?{presentBrowserLaunch:{outcome:e.kind,pageId:e.kind===`opened_managed`?e.pageId:void 0,reason:e.kind===`failed`?e.reason:t.fallback?.reason,logPath:Jm(),...t}}:{}}async function eh(e){let t=process.env.AGENT_BROWSER_ARGS??``,n=[`--start-maximized`,`--disable-infobars`,`--disable-popup-blocking`],r=Ym(e,t,n);try{let i=t?t.split(`,`):[],a=!1;for(let e of n)i.includes(e)||(i.push(e),a=!0);a&&(process.env.AGENT_BROWSER_ARGS=i.join(`,`)),r.changedAgentBrowserArgs=a,r.agentBrowserArgsAfter=process.env.AGENT_BROWSER_ARGS??``;let o=Jn();try{await o.launch(`ui`),r.engineLaunch.ok=!0,r.lastExecAfterLaunch=Km(o)}catch(e){r.engineLaunch.firstError=Gm(e),r.lastExecAfterLaunch=Km(o),r.engineLaunch.retried=!0,console.warn(`[present] Engine launch failed, retrying once:`,r.engineLaunch.firstError),await o.close().catch(()=>{});try{await o.launch(`ui`),r.engineLaunch.ok=!0,r.lastExecAfterLaunch=Km(o),console.warn(`[present] Engine launch retry succeeded`)}catch(e){throw r.engineLaunch.retryError=Gm(e),r.lastExecAfterLaunch=Km(o),console.warn(`[present] Engine launch retry also failed:`,r.engineLaunch.retryError),e}}o.resetIdleTimer();let s=`t0`;try{s=await o.open(e),r.engineOpen.ok=!0,r.engineOpen.pageId=s,r.lastExecAfterOpen=Km(o)}catch(t){r.engineOpen.firstError=Gm(t),r.lastExecAfterOpen=Km(o),r.engineOpen.retried=!0,console.warn(`[present] Engine open failed, restarting engine and retrying:`,r.engineOpen.firstError),await o.close().catch(()=>{}),await o.launch(`ui`),r.lastExecAfterLaunch=Km(o),o.resetIdleTimer();try{s=await o.open(e),r.engineOpen.ok=!0,r.engineOpen.pageId=s,r.lastExecAfterOpen=Km(o),console.warn(`[present] Engine open retry succeeded`)}catch(e){throw r.engineOpen.retryError=Gm(e),r.lastExecAfterOpen=Km(o),console.warn(`[present] Engine open retry also failed:`,r.engineOpen.retryError),e}}try{o.exec(`eval`,`setTimeout(function(){window.focus()}, 300);`).catch(e=>{let t=e instanceof Error?e.message:String(e);console.warn(`[present] window.focus eval failed (non-critical):`,t)})}catch{}return Qm({kind:`opened_managed`,url:e,pageId:s},r)}catch(t){return r.fallback={used:!0,reason:Gm(t)},Wm(e),Qm({kind:`opened_system`,url:e},r)}}function th(e,t,n,r){let i=[e.title];return e.description&&i.push(e.description),i.push(``),n.kind===`opened_managed`?i.push(`Opened in browser — ${t}`):n.kind===`opened_system`?i.push(`Opened in system browser — ${t}`):(i.push(`Failed to open browser: ${n.reason}`),i.push(`Manual URL: ${t}`)),i.push(r),i.join(`
2924
2924
  `)}function nh(e){return e.some(e=>e.id!==`__dismiss`)}function rh(e){return e.replace(`</head>`,`${sg}\n</head>`).replace(`</body>`,`${cg}\n</body>`)}function ih(e){if(!e.headersSent)try{e.writeHead(500,{"Content-Type":`text/plain`}),e.end(`Internal Server Error`)}catch{try{e.end()}catch{}}}function ah(e,t){let n=e.headers.referer;return typeof n==`string`&&n.length>0?n:`http://127.0.0.1:${t.port}`}async function oh(e,t){let n=Jn();n.isLaunched()||await n.launch(`headless`);let{base64:r}=await n.screenshotActiveTab({fullPage:t?.fullPage!==!1,format:t?.format,quality:t?.quality,annotate:t?.annotate});return Buffer.from(r,`base64`)}async function sh(e,t){if(!t){e.writeHead(503,{"Content-Type":`text/plain; charset=utf-8`}),e.end(`Screenshot target is not ready.`);return}try{let n=await oh(t);e.writeHead(200,{"Content-Type":`image/png`,"Cache-Control":`no-store`}),e.end(n)}catch(t){let n=t instanceof Error?t.message:String(t);console.warn(`[present] Screenshot capture failed:`,n),ih(e)}}async function ch(e,t){if(!t){Q(e,503,`CLIPBOARD_CAPTURE_TARGET_MISSING`,`Clipboard target is not ready.`);return}try{let n=await oh(t);e.writeHead(200,{"Content-Type":`image/png`,"Cache-Control":`no-store`}),e.end(n)}catch(t){let n=t instanceof Error?t.message:String(t);console.warn(`[present] Clipboard capture failed:`,n),Q(e,500,`CLIPBOARD_CAPTURE_FAILED`,`Clipboard capture failed: ${n}`)}}async function lh(e,t){let n=[];e.on(`data`,e=>n.push(e)),e.on(`end`,async()=>{let e=Buffer.concat(n);if(e.length===0){Q(t,400,`EMPTY_BODY`,`No image data received.`);return}try{await uh(e),t.writeHead(200,{"Content-Type":`application/json`}),t.end(JSON.stringify({ok:!0}))}catch(e){let n=e instanceof Error?e.message:String(e);console.warn(`[present] System clipboard write failed:`,n),Q(t,500,`SYSTEM_CLIPBOARD_WRITE_FAILED`,`System clipboard write failed: ${n}`)}}),e.on(`error`,e=>{console.warn(`[present] System clipboard write request error:`,e.message),Q(t,500,`REQUEST_ERROR`,`Request stream error.`)})}async function uh(e){let t=F(qn(),`aikit-clipboard-${Date.now()}-${Je(4).toString(`hex`)}.png`);try{if(Pe(t,e),process.platform===`win32`){let e=[`Add-Type -AssemblyName System.Drawing;`,`Add-Type -AssemblyName System.Windows.Forms;`,`$path = '${t.replace(/'/g,`''`)}';`,`$img = [System.Drawing.Image]::FromFile($path);`,`$img2 = [System.Drawing.Bitmap]::FromImage($img);`,`$img.Dispose();`,`[System.Windows.Forms.Clipboard]::SetImage($img2);`,`Start-Sleep -Milliseconds 500;`,`$img2.Dispose();`].join(` `);await new Promise((t,n)=>{gr(`powershell.exe -NoProfile -STA -Command "${e.replace(/"/g,`\\"`)}"`,{timeout:15e3,windowsHide:!0},e=>{e?n(Error(`PowerShell clipboard write failed: ${e.message}`)):t()})})}else if(process.platform===`darwin`)await new Promise((e,n)=>{gr(`osascript -e 'set the clipboard to (read (POSIX file "${t}") as picture)'`,{timeout:15e3},t=>{t?n(Error(`macOS clipboard write failed: ${t.message}`)):e()})});else try{await new Promise((e,n)=>{gr(`wl-copy --type image/png < "${t}" 2>/dev/null`,{timeout:1e4},(t,r)=>{t?n(Error(`wl-copy failed: ${t.message}`)):e(r)})});return}catch{await new Promise((e,n)=>{gr(`xclip -selection clipboard -t image/png -i "${t}"`,{timeout:15e3},t=>{t?n(Error(`Linux clipboard write failed (tried wl-copy then xclip): ${t.message}. Install wl-clipboard (Wayland) or xclip (X11) for clipboard image support.`)):e()})})}}finally{try{Ne(t)}catch{}}}function dh(e,t){return e.replace(/'\/callback'/g,`'/present/${t}/callback'`).replace(/"\/callback"/g,`"/present/${t}/callback"`).replace(/'\/ready'/g,`'/present/${t}/ready'`).replace(/"\/ready"/g,`"/present/${t}/ready"`)}function fh(e,t){return e.replace(/src="\/viewer"/g,`src="/present/${t}/viewer"`)}async function ph(e,t,n){if(zh(`<html><body style="font-family:system-ui;padding:2rem;color:#888;text-align:center"><p>Content opened in browser window.</p></body></html>`),e.data!=null&&t.inputSchema){let n=En({data:e.data,schema:t.inputSchema});if(!n.valid){let e=n.errors.map(e=>` ${e.path}: ${e.message}${e.expected?` (expected: ${e.expected}, got: ${e.received})`:``}`).join(`
2925
2925
  `);return{content:[{type:`text`,text:`[ERROR:VALIDATION] Template "${t.id}" data validation failed:\n${e}\n\nExpected schema: ${JSON.stringify(t.inputSchema,null,2)}`}],structuredContent:{kind:`error`,error:{code:`VIEWER_DATA_INVALID`,message:`Template "${t.id}" data validation failed:\n${e}\n\nExpected schema: ${JSON.stringify(t.inputSchema,null,2)}`}},isError:!0}}}let r=rh(Sp(t.resolveHtml(),e.data??null,t.injectId,t.transformData)),i=Nm(),a=Je(16).toString(`hex`),o=i.createSession({surfaceId:`viewer`,transport:`viewer`,nonce:a});if(!o.ok)return{content:[{type:`text`,text:`${e.title}\n\nUnable to start local browser transport.`}],structuredContent:{kind:`error`,error:{code:`BROWSER_START_FAILED`,message:o.error.message}},isError:!0};let s=o.session.id,c=hm(`viewer`,e.actions??[],i,s,a),l=fh(Tr({title:e.title,subtitle:e.description,html:[`<div class="present-viewer-container">`,` <iframe class="present-viewer-iframe" src="/viewer" sandbox="allow-scripts allow-same-origin"></iframe>`,` ${lg(a)}`,`</div>`].join(`
2926
2926
  `),css:[[`.present-viewer-container {`,` flex: 1;`,` min-height: calc(100vh - 12rem);`,` position: relative;`,` border-radius: 0.75rem;`,` overflow: hidden;`,` border: none;`,`}`,`.present-viewer-iframe {`,` border: none;`,` width: 100%;`,` height: 100%;`,` position: absolute;`,` inset: 0;`,` border-radius: inherit;`,`}`].join(`
@@ -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-BljeQpDp.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-Bmm0Ash4.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-D3422mfM.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-C_oHo3aD.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 +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-BljeQpDp.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-DMdfr-tm.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-Bmm0Ash4.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-BVSIwPMg.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{a as n,i as r,o as i,s as a}from"./bin.js";import{t as o}from"./register-tools-D3422mfM.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-C8gS4eHg.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-C_oHo3aD.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-CbSO2D5h.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{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-BljeQpDp.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-DMdfr-tm.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-Bmm0Ash4.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-BVSIwPMg.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,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-D3422mfM.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-C8gS4eHg.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-C_oHo3aD.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-CbSO2D5h.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};