@vpxa/aikit 0.1.329 → 0.1.331
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 +1 -1
- package/packages/browser/dist/index.js +1 -1
- package/packages/server/dist/bin.js +1 -1
- package/packages/server/dist/index.js +1 -1
- package/packages/server/dist/{server-4xcIVuzC.js → server-BPpxMa6G.js} +1 -1
- package/packages/server/dist/{server-DIJ0L_8t.js → server-BlN0Hbye.js} +1 -1
- package/packages/server/dist/{server-http-Cda_MYnv.js → server-http-BPeLCfm4.js} +1 -1
- package/packages/server/dist/{server-http-o8cfhQys.js → server-http-D0sBtn4y.js} +1 -1
- package/packages/server/dist/{server-stdio-CmfhInUV.js → server-stdio-C24ENRdr.js} +1 -1
- package/packages/server/dist/{server-stdio-Bnw6B9K9.js → server-stdio-uwA3lNY2.js} +1 -1
package/package.json
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{exec as e,execFile as t,execFileSync as n,execSync as r}from"node:child_process";import{existsSync as i,mkdirSync as a,readFileSync as o,unlinkSync as s,writeFileSync as c}from"node:fs";import{homedir as l,platform as u,tmpdir as d}from"node:os";import{join as f}from"node:path";import{z as p}from"zod";const m=`0.26.0`,h=`.agent-browser-version`;function g(e){return typeof e==`string`?e.trim():e instanceof Buffer?e.toString(`utf8`).trim():``}function _(){return f(l(),`.aikit`,`browsers`)}function v(e){return e.browsersPath??process.env.AIKIT_BROWSER_PATH??process.env.AIKIT_BROWSER_BROWSERS_PATH??_()}function y(){try{let e=r(`${u()===`win32`?`where`:`which`} agent-browser`,{encoding:`utf8`,stdio:`pipe`,timeout:3e3}).trim().split(/\r?\n/)[0];if(!e)return null;if(u()===`win32`){if(i(`${e}.cmd`))return`${e}.cmd`;if(i(`${e}.bat`))return`${e}.bat`;if(i(`${e}.exe`))return`${e}.exe`}return i(e)?e:null}catch{return null}}function ee(e){return f(e,`agent-browser`,te())}function te(){switch(u()){case`win32`:return`agent-browser.exe`;default:return`agent-browser`}}function ne(e,t){try{c(f(e,h),t,`utf8`)}catch{}}function re(e){try{return o(f(e,h),`utf8`).trim()}catch{return null}}function ie(e){let t=re(e);return t?ae(t,m)>=0:!1}function ae(e,t){let n=e.split(`.`).map(Number),r=t.split(`.`).map(Number);for(let e=0;e<Math.max(n.length,r.length);e++){let t=n[e]||0,i=r[e]||0;if(t!==i)return t-i}return 0}function oe(e){return!!(i(f(e,`chrome`))||i(f(l(),`.cache`,`agent-browser`,`chrome`)))}async function b(e,t){let n=y();if(n)return t?.(`Using globally installed agent-browser`),n;let o=v(e);i(o)||a(o,{recursive:!0});let s=ee(o);if(i(s)&&ie(o))return t?.(`Using cached agent-browser at ${s}`),s;t?.(`Downloading agent-browser (first use)...`);try{r(`npx -y agent-browser@latest install --install-dir "${o}"`,{stdio:`pipe`,timeout:12e4,encoding:`utf8`,env:{...process.env,AGENT_BROWSER_CACHE_DIR:o}})}catch(e){let t=e,n=g(t.stderr)||g(t.stdout)||t.message||`Unknown agent-browser install failure`;throw Error(`Failed to install agent-browser: ${n}`)}let c=s;try{let e=r(`npx -y -p agent-browser which agent-browser 2>/dev/null || true`,{encoding:`utf8`,timeout:1e4,stdio:`pipe`}).trim();e&&i(e)&&(c=e,ne(o,m))}catch{try{let e=r(`npx -y agent-browser --version`,{encoding:`utf8`,timeout:1e4,stdio:`pipe`}).trim();e&&ne(o,e)}catch{}}return t?.(`agent-browser ready`),c}async function se(e){try{return n(e,[`--version`],{encoding:`utf8`,stdio:`pipe`,timeout:5e3}).trim()}catch{return null}}function ce(e){if(y())return!0;let t=v(e);return oe(t)||i(ee(t))}const le=[`ui`,`headless`];function x(e){return le.includes(e)?e:`headless`}function S(e){let t=[];return e===`headless`&&t.push(`--headless`),t}function ue(e){return{headless:e===`headless`,args:S(e)}}var C=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}},de=class{tabs=new C;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 w={defaultMode:`ui`,browsersPath:null,userDataDirRoot:null,idleShutdownMinutes:10,allowInternalSchemes:!1,allowLoopback:!1,evalTimeoutMs:1e4,evalMaxResultBytes:262144,redactPasswordFieldsInScreenshots:!0,engine:`chrome`};var T=class{binaryPath=null;_currentMode=null;_isLaunched=!1;idleTimer=null;tabs=new C;config;constructor(e={}){this.config={...w,...e}}get currentMode(){return this._currentMode}async launch(e,t){if(!this._isLaunched){this._currentMode=x(e??this.config.defaultMode),this.binaryPath=await b(this.config,t);try{let e=await this.exec(`--version`);t?.(`agent-browser ${e.stdout.trim()}`)}catch(e){throw Error(`agent-browser binary failed: ${e instanceof Error?e.message:String(e)}`)}this._isLaunched=!0,this.resetIdleTimer()}}async exec(e,...t){if(!this.binaryPath)throw Error(`agent-browser not launched. Call launch() first, or use getEngine() singleton.`);let n=this.binaryPath;u()===`win32`&&!n.endsWith(`.cmd`)&&!n.endsWith(`.bat`)&&!n.endsWith(`.exe`)&&i(`${n}.cmd`)&&(n=`${n}.cmd`);let r=[e,...t];try{return await this.execViaExecFile(n,r)}catch(e){if(u()===`win32`&&(n.endsWith(`.cmd`)||n.endsWith(`.bat`))&&e?.code===`EINVAL`){let e=`"${n}" ${r.map(e=>/[^\w/:@.\-_{}()/\\]/.test(e)?`"${e.replace(/"/g,`""`)}"`:e).join(` `)}`;return await this.execViaShell(e)}throw e}}execViaExecFile(e,n){return new Promise((r,i)=>{t(e,n,{timeout:this.config.evalTimeoutMs},(e,t,n)=>{if(e){e.code===`ENOENT`?i(Error(`agent-browser binary not found at ${this.binaryPath}`)):i(e);return}r({stdout:t??``,stderr:n??``,exitCode:0})})})}execViaShell(t){return new Promise((n,r)=>{e(t,{timeout:this.config.evalTimeoutMs},(e,t,i)=>{if(e&&e.code===`ENOENT`){r(Error(`agent-browser binary not found at ${this.binaryPath}`));return}n({stdout:t??``,stderr:i??``,exitCode:e?.code?Number(e.code):0})})})}async tabExec(e,t,...n){return this.exec(`tab`,e,t,...n)}async open(e,t,n){await this.launch(t);let r=await this.exec(`open`,e);return this.tabs.register(`t0`,e,r.stdout.trim(),n),this.resetIdleTimer(),`t0`}async screenshot(e,t){let n=t?.format??`png`,r=n===`jpeg`?`image/jpeg`:`image/png`,i=n===`jpeg`?`jpg`:`png`,a=f(d(),`aikit-screenshot-${Date.now()}.${i}`),c=[a];t?.fullPage&&c.push(`--full`),t?.format===`jpeg`&&c.push(`--screenshot-format`,`jpeg`),t?.quality&&c.push(`--screenshot-quality`,String(t.quality)),await this.exec(`screenshot`,...c);let l=o(a),u=l.toString(`base64`);try{s(a)}catch{}return this.resetIdleTimer(),{base64:u,mimeType:r,bytes:l.length}}async readSnapshot(e,t=!1){let n=t?[`-c`,`--json`]:[`-i`,`--json`],r=await this.tabExec(e,`snapshot`,...n);return this.resetIdleTimer(),r.stdout}async navigate(e,t){let n=await this.tabExec(e,`goto`,t);return this.resetIdleTimer(),n}async close(){if(this.stopIdleTimer(),this._isLaunched){try{await this.exec(`close`).catch(()=>{})}catch{}this.tabs.clear(),this._isLaunched=!1,this._currentMode=null}}isLaunched(){return this._isLaunched}getConfig(){return this.config}getBinaryPath(){return this.binaryPath}resolvePageId(e){return this.tabs.resolve(e)}resetIdleTimer(){this.stopIdleTimer();let e=setTimeout(()=>{this.close()},this.config.idleShutdownMinutes*6e4);e.unref?.(),this.idleTimer=e}stopIdleTimer(){this.idleTimer&&=(clearTimeout(this.idleTimer),null)}};let E=null;function D(e){return E||=new T(e),E}async function fe(){E&&=(await E.close(),null)}function O(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 k(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 pe=[`ui`,`headless`];function me(e){return typeof e==`object`&&e?e:null}function A(e){return typeof e==`string`&&e.length>0?e:void 0}function j(e){return typeof e==`boolean`?e:void 0}function M(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}function N(e){return typeof e==`string`&&pe.includes(e)?e:void 0}function P(e){let t=process.env[e];if(!t)return;let n=Number(t);return Number.isFinite(n)?n:void 0}function he(e){let t=me(e.browser)??{};return{...w,defaultMode:N(process.env.AIKIT_BROWSER_DEFAULT_MODE)??N(t.defaultMode)??w.defaultMode,browsersPath:A(process.env.AIKIT_BROWSER_PATH)??A(process.env.AIKIT_BROWSER_BROWSERS_PATH)??A(t.browsersPath)??w.browsersPath,userDataDirRoot:A(t.userDataDirRoot)??w.userDataDirRoot,idleShutdownMinutes:P(`AIKIT_BROWSER_IDLE_MINUTES`)??M(t.idleShutdownMinutes)??w.idleShutdownMinutes,allowInternalSchemes:j(t.allowInternalSchemes)??w.allowInternalSchemes,allowLoopback:j(t.allowLoopback)??w.allowLoopback,evalTimeoutMs:P(`AIKIT_BROWSER_EVAL_TIMEOUT_MS`)??M(t.evalTimeoutMs)??w.evalTimeoutMs,evalMaxResultBytes:M(t.evalMaxResultBytes)??w.evalMaxResultBytes,redactPasswordFieldsInScreenshots:j(t.redactPasswordFieldsInScreenshots)??w.redactPasswordFieldsInScreenshots,engine:A(t.engine)??w.engine,proxy:A(t.proxy),viewport:A(t.viewport)}}function F(e,t){return{content:[{type:`text`,text:e}],structuredContent:t}}function I(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 ge(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=D(e),m=p.resolvePageId(t);switch(n){case`click`:{let e=I({ref:r,selector:i,element:a},`browser_act(click)`);await p.tabExec(m,`click`,e);break}case`type`:{let e=I({ref:r,selector:i,element:a},`browser_act(type)`);await p.tabExec(m,`fill`,e,o??``);break}case`press`:{let e=I({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=I({ref:r,selector:i,element:a},`browser_act(hover)`);await p.tabExec(m,`hover`,e);break}case`drag`:{let e=I({ref:l??r,selector:u??i,element:a},`browser_act(drag) source`),t=I({ref:d,selector:f??c,element:a},`browser_act(drag) target`);await p.tabExec(m,`drag`,e,t);break}case`select`:{let e=I({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=I({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=I({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(),F(`ok`,{ok:!0})}}function _e(e){return async({pageId:t,subAction:n,level:r,bufferSize:i})=>{let a=D(e),o=a.resolvePageId(t);switch(n){case`enable`:{let e=[`--enable`];return i&&e.push(`--buffer-size`,String(i)),r&&e.push(`--level`,r),await a.tabExec(o,`console`,...e),a.resetIdleTimer(),F(`Console capture enabled`,{enabled:!0})}case`get`:{let e=[`--json`];r&&e.push(`--level`,r);let t=await a.tabExec(o,`console`,...e);a.resetIdleTimer();let n=[];try{n=JSON.parse(t.stdout)}catch{n=[{raw:t.stdout}]}return F(`Console has ${n.length} entries`,{entries:n,count:n.length})}case`clear`:return await a.tabExec(o,`console`,`clear`),a.resetIdleTimer(),F(`Console cleared`,{cleared:!0});default:return F(`Unknown console sub-action`,{error:`Unknown console sub-action`})}}}function ve(e){return async({pageId:t,accept:n,promptText:r})=>{let i=D(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(),F(`Dialog ${n?`accepted`:`dismissed`}`,{accepted:n})}}function ye(e){return async({pageId:t})=>{let n=D(e),r=n.resolvePageId(t),i=await n.tabExec(r,`diff`,`snapshot`);return n.resetIdleTimer(),F(i.stdout,{pageId:r,diff:i.stdout})}}function be(e){return async({pageId:t,code:n,timeoutMs:r})=>{let i=D(e),a=i.resolvePageId(t),o=r??e.evalTimeoutMs,s=await i.tabExec(a,`evaluate`,`--timeout=${o}`,`--`,n);i.resetIdleTimer();let c=k(s.stdout,e.evalMaxResultBytes);return F(c.result,{pageId:a,result:c.result,truncated:c.truncated})}}function xe(e){return async({pageId:t,url:n,method:r,headers:i,body:a,timeoutMs:o,includeHeaders:s})=>{let c=D(e),l=c.resolvePageId(t),u=o??e.evalTimeoutMs,d=Se(n,r??`GET`,s??!0,i,a),f=await c.tabExec(l,`evaluate`,`--timeout=${u}`,`--`,d);return c.resetIdleTimer(),F(f.stdout,{pageId:l,response:f.stdout})}}function Se(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 => {
|
|
1
|
+
import{exec as e,execFile as t,execFileSync as n,execSync as r}from"node:child_process";import{existsSync as i,mkdirSync as a,readFileSync as o,unlinkSync as s,writeFileSync as c}from"node:fs";import{homedir as l,platform as u,tmpdir as d}from"node:os";import{join as f}from"node:path";import{z as p}from"zod";const m=`0.26.0`,h=`.agent-browser-version`;function g(e){return typeof e==`string`?e.trim():e instanceof Buffer?e.toString(`utf8`).trim():``}function _(){return f(l(),`.aikit`,`browsers`)}function v(e){return e.browsersPath??process.env.AIKIT_BROWSER_PATH??process.env.AIKIT_BROWSER_BROWSERS_PATH??_()}function y(){try{let e=r(`${u()===`win32`?`where`:`which`} agent-browser`,{encoding:`utf8`,stdio:`pipe`,timeout:3e3}).trim().split(/\r?\n/)[0];if(!e)return null;if(u()===`win32`){if(i(`${e}.cmd`))return`${e}.cmd`;if(i(`${e}.bat`))return`${e}.bat`;if(i(`${e}.exe`))return`${e}.exe`}return i(e)?e:null}catch{return null}}function ee(e){return f(e,`agent-browser`,te())}function te(){switch(u()){case`win32`:return`agent-browser.exe`;default:return`agent-browser`}}function ne(e,t){try{c(f(e,h),t,`utf8`)}catch{}}function re(e){try{return o(f(e,h),`utf8`).trim()}catch{return null}}function ie(e){let t=re(e);return t?ae(t,m)>=0:!1}function ae(e,t){let n=e.split(`.`).map(Number),r=t.split(`.`).map(Number);for(let e=0;e<Math.max(n.length,r.length);e++){let t=n[e]||0,i=r[e]||0;if(t!==i)return t-i}return 0}function oe(e){return!!(i(f(e,`chrome`))||i(f(l(),`.cache`,`agent-browser`,`chrome`)))}async function b(e,t){let n=y();if(n)return t?.(`Using globally installed agent-browser`),n;let o=v(e);i(o)||a(o,{recursive:!0});let s=ee(o);if(i(s)&&ie(o))return t?.(`Using cached agent-browser at ${s}`),s;t?.(`Downloading agent-browser (first use)...`);try{r(`npx -y agent-browser@latest install --install-dir "${o}"`,{stdio:`pipe`,timeout:12e4,encoding:`utf8`,env:{...process.env,AGENT_BROWSER_CACHE_DIR:o}})}catch(e){let t=e,n=g(t.stderr)||g(t.stdout)||t.message||`Unknown agent-browser install failure`;throw Error(`Failed to install agent-browser: ${n}`)}let c=s;try{let e=r(`npx -y -p agent-browser which agent-browser 2>/dev/null || true`,{encoding:`utf8`,timeout:1e4,stdio:`pipe`}).trim();e&&i(e)&&(c=e,ne(o,m))}catch{try{let e=r(`npx -y agent-browser --version`,{encoding:`utf8`,timeout:1e4,stdio:`pipe`}).trim();e&&ne(o,e)}catch{}}return t?.(`agent-browser ready`),c}async function se(e){try{return n(e,[`--version`],{encoding:`utf8`,stdio:`pipe`,timeout:5e3}).trim()}catch{return null}}function ce(e){if(y())return!0;let t=v(e);return oe(t)||i(ee(t))}const le=[`ui`,`headless`];function x(e){return le.includes(e)?e:`headless`}function S(e){let t=[];return e===`headless`&&t.push(`--headless`),t}function ue(e){return{headless:e===`headless`,args:S(e)}}var C=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}},de=class{tabs=new C;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 w={defaultMode:`ui`,browsersPath:null,userDataDirRoot:null,idleShutdownMinutes:10,allowInternalSchemes:!1,allowLoopback:!1,evalTimeoutMs:1e4,evalMaxResultBytes:262144,redactPasswordFieldsInScreenshots:!0,engine:`chrome`};var T=class{binaryPath=null;_currentMode=null;_isLaunched=!1;idleTimer=null;tabs=new C;config;constructor(e={}){this.config={...w,...e}}get currentMode(){return this._currentMode}async launch(e,t){if(!this._isLaunched){this._currentMode=x(e??this.config.defaultMode),this.binaryPath=await b(this.config,t);try{let e=await this.exec(`--version`);t?.(`agent-browser ${e.stdout.trim()}`)}catch(e){throw Error(`agent-browser binary failed: ${e instanceof Error?e.message:String(e)}`)}this._isLaunched=!0,this.resetIdleTimer()}}async exec(e,...t){if(!this.binaryPath)throw Error(`agent-browser not launched. Call launch() first, or use getEngine() singleton.`);let n=this.binaryPath;u()===`win32`&&!n.endsWith(`.cmd`)&&!n.endsWith(`.bat`)&&!n.endsWith(`.exe`)&&i(`${n}.cmd`)&&(n=`${n}.cmd`);let r=[e,...t];try{return await this.execViaExecFile(n,r)}catch(e){if(u()===`win32`&&(n.endsWith(`.cmd`)||n.endsWith(`.bat`))&&e?.code===`EINVAL`){let e=`"${n}" ${r.map(e=>/[^\w/:@.\-_{}()/\\]/.test(e)?`"${e.replace(/"/g,`""`)}"`:e).join(` `)}`;return await this.execViaShell(e)}throw e}}execViaExecFile(e,n){return new Promise((r,i)=>{t(e,n,{timeout:this.config.evalTimeoutMs},(e,t,n)=>{if(e){if(e.code===`ENOENT`){i(Error(`agent-browser binary not found at ${this.binaryPath}`));return}r({stdout:t??``,stderr:n??``,exitCode:e.code?Number(e.code):0});return}r({stdout:t??``,stderr:n??``,exitCode:0})})})}execViaShell(t){return new Promise((n,r)=>{e(t,{timeout:this.config.evalTimeoutMs},(e,t,i)=>{if(e&&e.code===`ENOENT`){r(Error(`agent-browser binary not found at ${this.binaryPath}`));return}n({stdout:t??``,stderr:i??``,exitCode:e?.code?Number(e.code):0})})})}async tabExec(e,t,...n){return this.exec(`tab`,e,t,...n)}async open(e,t,n){await this.launch(t);let r=await this.exec(`open`,e);return this.tabs.register(`t0`,e,r.stdout.trim(),n),this.resetIdleTimer(),`t0`}async screenshot(e,t){let n=t?.format??`png`,r=n===`jpeg`?`image/jpeg`:`image/png`,i=n===`jpeg`?`jpg`:`png`,a=f(d(),`aikit-screenshot-${Date.now()}.${i}`),c=[a];t?.fullPage&&c.push(`--full`),t?.format===`jpeg`&&c.push(`--screenshot-format`,`jpeg`),t?.quality&&c.push(`--screenshot-quality`,String(t.quality)),await this.exec(`screenshot`,...c);let l=o(a),u=l.toString(`base64`);try{s(a)}catch{}return this.resetIdleTimer(),{base64:u,mimeType:r,bytes:l.length}}async readSnapshot(e,t=!1){let n=t?[`-c`,`--json`]:[`-i`,`--json`],r=await this.tabExec(e,`snapshot`,...n);return this.resetIdleTimer(),r.stdout}async navigate(e,t){let n=await this.tabExec(e,`goto`,t);return this.resetIdleTimer(),n}async close(){if(this.stopIdleTimer(),this._isLaunched){try{await this.exec(`close`).catch(()=>{})}catch{}this.tabs.clear(),this._isLaunched=!1,this._currentMode=null}}isLaunched(){return this._isLaunched}getConfig(){return this.config}getBinaryPath(){return this.binaryPath}resolvePageId(e){return this.tabs.resolve(e)}resetIdleTimer(){this.stopIdleTimer();let e=setTimeout(()=>{this.close()},this.config.idleShutdownMinutes*6e4);e.unref?.(),this.idleTimer=e}stopIdleTimer(){this.idleTimer&&=(clearTimeout(this.idleTimer),null)}};let E=null;function D(e){return E||=new T(e),E}async function fe(){E&&=(await E.close(),null)}function O(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 k(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 pe=[`ui`,`headless`];function me(e){return typeof e==`object`&&e?e:null}function A(e){return typeof e==`string`&&e.length>0?e:void 0}function j(e){return typeof e==`boolean`?e:void 0}function M(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}function N(e){return typeof e==`string`&&pe.includes(e)?e:void 0}function P(e){let t=process.env[e];if(!t)return;let n=Number(t);return Number.isFinite(n)?n:void 0}function he(e){let t=me(e.browser)??{};return{...w,defaultMode:N(process.env.AIKIT_BROWSER_DEFAULT_MODE)??N(t.defaultMode)??w.defaultMode,browsersPath:A(process.env.AIKIT_BROWSER_PATH)??A(process.env.AIKIT_BROWSER_BROWSERS_PATH)??A(t.browsersPath)??w.browsersPath,userDataDirRoot:A(t.userDataDirRoot)??w.userDataDirRoot,idleShutdownMinutes:P(`AIKIT_BROWSER_IDLE_MINUTES`)??M(t.idleShutdownMinutes)??w.idleShutdownMinutes,allowInternalSchemes:j(t.allowInternalSchemes)??w.allowInternalSchemes,allowLoopback:j(t.allowLoopback)??w.allowLoopback,evalTimeoutMs:P(`AIKIT_BROWSER_EVAL_TIMEOUT_MS`)??M(t.evalTimeoutMs)??w.evalTimeoutMs,evalMaxResultBytes:M(t.evalMaxResultBytes)??w.evalMaxResultBytes,redactPasswordFieldsInScreenshots:j(t.redactPasswordFieldsInScreenshots)??w.redactPasswordFieldsInScreenshots,engine:A(t.engine)??w.engine,proxy:A(t.proxy),viewport:A(t.viewport)}}function F(e,t){return{content:[{type:`text`,text:e}],structuredContent:t}}function I(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 ge(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=D(e),m=p.resolvePageId(t);switch(n){case`click`:{let e=I({ref:r,selector:i,element:a},`browser_act(click)`);await p.tabExec(m,`click`,e);break}case`type`:{let e=I({ref:r,selector:i,element:a},`browser_act(type)`);await p.tabExec(m,`fill`,e,o??``);break}case`press`:{let e=I({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=I({ref:r,selector:i,element:a},`browser_act(hover)`);await p.tabExec(m,`hover`,e);break}case`drag`:{let e=I({ref:l??r,selector:u??i,element:a},`browser_act(drag) source`),t=I({ref:d,selector:f??c,element:a},`browser_act(drag) target`);await p.tabExec(m,`drag`,e,t);break}case`select`:{let e=I({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=I({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=I({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(),F(`ok`,{ok:!0})}}function _e(e){return async({pageId:t,subAction:n,level:r,bufferSize:i})=>{let a=D(e),o=a.resolvePageId(t);switch(n){case`enable`:{let e=[`--enable`];return i&&e.push(`--buffer-size`,String(i)),r&&e.push(`--level`,r),await a.tabExec(o,`console`,...e),a.resetIdleTimer(),F(`Console capture enabled`,{enabled:!0})}case`get`:{let e=[`--json`];r&&e.push(`--level`,r);let t=await a.tabExec(o,`console`,...e);a.resetIdleTimer();let n=[];try{n=JSON.parse(t.stdout)}catch{n=[{raw:t.stdout}]}return F(`Console has ${n.length} entries`,{entries:n,count:n.length})}case`clear`:return await a.tabExec(o,`console`,`clear`),a.resetIdleTimer(),F(`Console cleared`,{cleared:!0});default:return F(`Unknown console sub-action`,{error:`Unknown console sub-action`})}}}function ve(e){return async({pageId:t,accept:n,promptText:r})=>{let i=D(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(),F(`Dialog ${n?`accepted`:`dismissed`}`,{accepted:n})}}function ye(e){return async({pageId:t})=>{let n=D(e),r=n.resolvePageId(t),i=await n.tabExec(r,`diff`,`snapshot`);return n.resetIdleTimer(),F(i.stdout,{pageId:r,diff:i.stdout})}}function be(e){return async({pageId:t,code:n,timeoutMs:r})=>{let i=D(e),a=i.resolvePageId(t),o=r??e.evalTimeoutMs,s=await i.tabExec(a,`evaluate`,`--timeout=${o}`,`--`,n);i.resetIdleTimer();let c=k(s.stdout,e.evalMaxResultBytes);return F(c.result,{pageId:a,result:c.result,truncated:c.truncated})}}function xe(e){return async({pageId:t,url:n,method:r,headers:i,body:a,timeoutMs:o,includeHeaders:s})=>{let c=D(e),l=c.resolvePageId(t),u=o??e.evalTimeoutMs,d=Se(n,r??`GET`,s??!0,i,a),f=await c.tabExec(l,`evaluate`,`--timeout=${u}`,`--`,d);return c.resetIdleTimer(),F(f.stdout,{pageId:l,response:f.stdout})}}function Se(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 => {
|
|
2
2
|
const text = await r.text();
|
|
3
3
|
const headers = {};
|
|
4
4
|
r.headers.forEach((v, k) => { headers[k] = v; });
|
|
@@ -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){R.error(`Failed to upsert curated batch`,{batchSize:e.length,...a(t)});for(let t of e)n.push(`${t.relativePath}: upsert failed`);return 0}}catch(r){if(e.length===1)return R.error(`Failed to embed curated item`,{relativePath:e[0].relativePath,...a(r)}),n.push(`${e[0].relativePath}: reindex failed`),0;R.warn(`Curated embed batch failed, retrying with smaller chunks`,{batchSize:e.length,...a(r)});let i=Math.ceil(e.length/2),o=e.slice(0,i),s=e.slice(i);return await this.embedAndUpsertBatch(o,t,n)+await this.embedAndUpsertBatch(s,t,n)}}gitCommitKnowledge(e,t,n){try{if(!p(this.curatedDir))return;let r=this.knowledgeRefForPath(e);if(!r)return;m(r,`entry.md`,t,n,this.curatedDir)}catch{}}gitDeleteKnowledgeRef(e){try{if(!p(this.curatedDir))return;let t=this.knowledgeRefForPath(e);if(!t)return;h([`update-ref`,`-d`,t],this.curatedDir)}catch{}}knowledgeRefForPath(e){let t=e.replace(/\.md$/,``).split(`/`).map(e=>g(e)).join(`/`);return t.split(`/`).every(e=>f.test(e))?`${L}/${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`)){R.debug(`Skipping vector indexing — embedder degraded`,{relativePath:e,operation:i,subsystem:`embedder`});return}try{await this.indexCuratedFile(e,t,n)}catch(t){R.warn(`Curated file persisted but vector indexing deferred`,{relativePath:e,operation:i,...a(t)})}}async discoverCategories(){return this.adapter.listDirectories()}guardPath(e){let t=e.replace(/^\.ai\/curated\//,``);if(t.endsWith(`.md`)||(t+=`.md`),t.includes(`..`)||c(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`)>I)throw Error(`Content exceeds maximum size of ${I/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 d(`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 B=i(`server`);function V(e,t){return t?{version:e,...a(t)}:{version:e}}function H(){return process.env.AIKIT_TRANSPORT?process.env.AIKIT_TRANSPORT:process.stdin.isTTY?`http`:`stdio`}function U(){let e=process.argv[1];if(!e)return!1;try{return import.meta.url===t(e).href}catch{return!1}}function W(){return U()?n({allowPositionals:!0,options:{transport:{type:`string`,default:H()},port:{type:`string`,default:process.env.AIKIT_PORT??`3210`}}}).values:{transport:H(),port:process.env.AIKIT_PORT??`3210`}}async function G(){let e=C(),t=W();if(process.on(`unhandledRejection`,t=>{B.error(`Unhandled rejection`,V(e,t))}),process.on(`uncaughtException`,t=>{B.error(`Uncaught exception — exiting`,V(e,t)),process.exit(1)}),B.info(`Starting MCP AI Kit server`,{version:e}),t.transport===`http`){let{startHttpMode:n}=await import(`./server-http-
|
|
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 B=i(`server`);function V(e,t){return t?{version:e,...a(t)}:{version:e}}function H(){return process.env.AIKIT_TRANSPORT?process.env.AIKIT_TRANSPORT:process.stdin.isTTY?`http`:`stdio`}function U(){let e=process.argv[1];if(!e)return!1;try{return import.meta.url===t(e).href}catch{return!1}}function W(){return U()?n({allowPositionals:!0,options:{transport:{type:`string`,default:H()},port:{type:`string`,default:process.env.AIKIT_PORT??`3210`}}}).values:{transport:H(),port:process.env.AIKIT_PORT??`3210`}}async function G(){let e=C(),t=W();if(process.on(`unhandledRejection`,t=>{B.error(`Unhandled rejection`,V(e,t))}),process.on(`uncaughtException`,t=>{B.error(`Uncaught exception — exiting`,V(e,t)),process.exit(1)}),B.info(`Starting MCP AI Kit server`,{version:e}),t.transport===`http`){let{startHttpMode:n}=await import(`./server-http-D0sBtn4y.js`);await n(e,t.port)}else{let{startStdioMode:t}=await import(`./server-stdio-C24ENRdr.js`);await t(e)}}G();export{w as a,O as i,F as n,T as o,P as r,D as s,z as t};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as e,i as t,n,r,t as i}from"./server-utils-De-aZNQa.js";import{n as a,r as o,t as s}from"./workspace-bootstrap-BJloolzr.js";import{t as c}from"./curated-manager-BrgM_znO.js";import{pathToFileURL as l}from"node:url";import{parseArgs as u}from"node:util";import{createLogger as d,serializeError as f}from"../../core/dist/index.js";const p=d(`server`);function m(e,t){return t?{version:e,...f(t)}:{version:e}}function h(){return process.env.AIKIT_TRANSPORT?process.env.AIKIT_TRANSPORT:process.stdin.isTTY?`http`:`stdio`}function g(){let e=process.argv[1];if(!e)return!1;try{return import.meta.url===l(e).href}catch{return!1}}function _(){return g()?u({allowPositionals:!0,options:{transport:{type:`string`,default:h()},port:{type:`string`,default:process.env.AIKIT_PORT??`3210`}}}).values:{transport:h(),port:process.env.AIKIT_PORT??`3210`}}async function v(){let e=t(),n=_();if(process.on(`unhandledRejection`,t=>{p.error(`Unhandled rejection`,m(e,t))}),process.on(`uncaughtException`,t=>{p.error(`Uncaught exception — exiting`,m(e,t)),process.exit(1)}),p.info(`Starting MCP AI Kit server`,{version:e}),n.transport===`http`){let{startHttpMode:t}=await import(`./server-http-
|
|
1
|
+
import{a as e,i as t,n,r,t as i}from"./server-utils-De-aZNQa.js";import{n as a,r as o,t as s}from"./workspace-bootstrap-BJloolzr.js";import{t as c}from"./curated-manager-BrgM_znO.js";import{pathToFileURL as l}from"node:url";import{parseArgs as u}from"node:util";import{createLogger as d,serializeError as f}from"../../core/dist/index.js";const p=d(`server`);function m(e,t){return t?{version:e,...f(t)}:{version:e}}function h(){return process.env.AIKIT_TRANSPORT?process.env.AIKIT_TRANSPORT:process.stdin.isTTY?`http`:`stdio`}function g(){let e=process.argv[1];if(!e)return!1;try{return import.meta.url===l(e).href}catch{return!1}}function _(){return g()?u({allowPositionals:!0,options:{transport:{type:`string`,default:h()},port:{type:`string`,default:process.env.AIKIT_PORT??`3210`}}}).values:{transport:h(),port:process.env.AIKIT_PORT??`3210`}}async function v(){let e=t(),n=_();if(process.on(`unhandledRejection`,t=>{p.error(`Unhandled rejection`,m(e,t))}),process.on(`uncaughtException`,t=>{p.error(`Uncaught exception — exiting`,m(e,t)),process.exit(1)}),p.info(`Starting MCP AI Kit server`,{version:e}),n.transport===`http`){let{startHttpMode:t}=await import(`./server-http-BPeLCfm4.js`);await t(e,n.port)}else{let{startStdioMode:t}=await import(`./server-stdio-uwA3lNY2.js`);await t(e)}}export{c as CuratedKnowledgeManager,s as applyWorkspaceRoots,a as bootstrapWorkspaceRoots,i as createSlidingWindowRateLimiter,n as getSessionIdHeader,v as main,r as readPositiveIntEnv,t as readVersion,e as resolveCorsOrigin,o as selectWorkspaceRoot};
|
|
@@ -2931,7 +2931,7 @@ window.addEventListener('message', function(e) {
|
|
|
2931
2931
|
}
|
|
2932
2932
|
});
|
|
2933
2933
|
<\/script>
|
|
2934
|
-
</body>`)}function qh(e){if(!e.headersSent)try{e.writeHead(500,{"Content-Type":`text/plain`}),e.end(`Internal Server Error`)}catch{try{e.end()}catch{}}}async function Jh(e){let t=Xn(),n=`ss-${Date.now()}`;await t.launch(`headless`),await t.
|
|
2934
|
+
</body>`)}function qh(e){if(!e.headersSent)try{e.writeHead(500,{"Content-Type":`text/plain`}),e.end(`Internal Server Error`)}catch{try{e.end()}catch{}}}async function Jh(e){let t=Xn(),n=`ss-${Date.now()}`;await t.launch(`headless`),await t.exec(`tab`,`new`,e).catch(()=>t.exec(`open`,e)),await t.exec(`wait`,`--load`,`networkidle`).catch(()=>{});try{let{base64:e}=await t.screenshot(n,{fullPage:!0});return Buffer.from(e,`base64`)}finally{t.exec(`tab`,`close`).catch(()=>{})}}async function Yh(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 Jh(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),qh(e)}}function Xh(e,t){return e.replace(/'\/callback'/g,`'/present/${t}/callback'`).replace(/"\/callback"/g,`"/present/${t}/callback"`)}function Zh(e,t){return e.replace(/src="\/viewer"/g,`src="/present/${t}/viewer"`)}async function Qh(e,t){if(Tg(`<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(`
|
|
2935
2935
|
`);return{content:[{type:`text`,text:`[ERROR:VALIDATION] Template "${t.id}" data validation failed:\n${e}\n\nExpected schema: ${JSON.stringify(t.inputSchema,null,2)}`}],structuredContent:{kind:`error`,error:{code:`VIEWER_DATA_INVALID`,message:`Template "${t.id}" data validation failed:\n${e}\n\nExpected schema: ${JSON.stringify(t.inputSchema,null,2)}`}},isError:!0}}}let n=Kh(ym(t.resolveHtml(),e.data??null,t.injectId,t.transformData)),r=Ah(),i=Ie(16).toString(`hex`),a=r.createSession({surfaceId:`viewer`,transport:`viewer`,nonce:i});if(!a.ok)return{content:[{type:`text`,text:`${e.title}\n\nUnable to start local browser transport.`}],structuredContent:{kind:`error`,error:{code:`BROWSER_START_FAILED`,message:a.error.message}},isError:!0};let o=a.session.id,s=dh(`viewer`,e.actions??[],r,o,i),c=Zh(Or({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>`,` ${Gh(i)}`,`</div>`].join(`
|
|
2936
2936
|
`),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(`
|
|
2937
2937
|
`)],islands:[],payload:void 0,nonce:i,generatedAt:new Date().toISOString(),colorScheme:e.colorScheme,lang:e.lang,dir:e.dir,transport:`browser`,exportPolicy:`local-interactive`,footerContentHtml:fh}),o);Dh.set(o,{callbackSession:s,html:c,viewerHtml:n,hasClientConnected:!1,createdAt:Date.now()});let l=``;try{l=`http://127.0.0.1:${await jh()}/present/${o}`}catch(t){return Dh.delete(o),r.removeSession(o),{content:[{type:`text`,text:`${e.title}\n\nUnable to start local browser transport.`}],structuredContent:{kind:`error`,error:{code:`BROWSER_START_FAILED`,message:t instanceof Error?t.message:`Unable to start browser transport`}},isError:!0}}return await Hh(l),setTimeout(()=>{Dh.delete(o),r.removeSession(o)},xh),{content:[{type:`text`,text:Uh(e,l,`Rendered.`)}],structuredContent:{kind:`rendered`,reason:`no-response-required`}}}async function $h(e){Tg(`<html><body style="font-family:system-ui;padding:2rem;color:#888;text-align:center"><p>Content opened in browser window.</p></body></html>`);let t=Ah(),n=Ie(16).toString(`hex`),r=Ir(e,{transport:`browser`,registry:Hm,blockVendorScripts:Km(),nonce:n}),i=t.createSession({surfaceId:r.surfaceId,transport:`browser`,nonce:n});if(!i.ok)return{content:[{type:`text`,text:`${e.title}\n\nUnable to start local browser transport.`}],structuredContent:{kind:`error`,error:{code:`BROWSER_START_FAILED`,message:i.error.message}},isError:!0};let a=i.session.id,o=dh(r.surfaceId,r.actions,t,a,n),s=yh(r.vendorScripts,`browser`);bh();let c=r.actions.length>0?zh(r.actions):``,l=r.actions.length>0?Bh(r.actions,o.nonce):``,u=Xh(Qg(Or({title:e.title,subtitle:e.description,html:[r.html,c,l].filter(Boolean).join(`
|
|
@@ -2930,7 +2930,7 @@ window.addEventListener('message', function(e) {
|
|
|
2930
2930
|
}
|
|
2931
2931
|
});
|
|
2932
2932
|
<\/script>
|
|
2933
|
-
</body>`)}function qh(e){if(!e.headersSent)try{e.writeHead(500,{"Content-Type":`text/plain`}),e.end(`Internal Server Error`)}catch{try{e.end()}catch{}}}async function Jh(e){let t=Qn(),n=`ss-${Date.now()}`;await t.launch(`headless`),await t.
|
|
2933
|
+
</body>`)}function qh(e){if(!e.headersSent)try{e.writeHead(500,{"Content-Type":`text/plain`}),e.end(`Internal Server Error`)}catch{try{e.end()}catch{}}}async function Jh(e){let t=Qn(),n=`ss-${Date.now()}`;await t.launch(`headless`),await t.exec(`tab`,`new`,e).catch(()=>t.exec(`open`,e)),await t.exec(`wait`,`--load`,`networkidle`).catch(()=>{});try{let{base64:e}=await t.screenshot(n,{fullPage:!0});return Buffer.from(e,`base64`)}finally{t.exec(`tab`,`close`).catch(()=>{})}}async function Yh(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 Jh(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),qh(e)}}function Xh(e,t){return e.replace(/'\/callback'/g,`'/present/${t}/callback'`).replace(/"\/callback"/g,`"/present/${t}/callback"`)}function Zh(e,t){return e.replace(/src="\/viewer"/g,`src="/present/${t}/viewer"`)}async function Qh(e,t){if(Tg(`<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(`
|
|
2934
2934
|
`);return{content:[{type:`text`,text:`[ERROR:VALIDATION] Template "${t.id}" data validation failed:\n${e}\n\nExpected schema: ${JSON.stringify(t.inputSchema,null,2)}`}],structuredContent:{kind:`error`,error:{code:`VIEWER_DATA_INVALID`,message:`Template "${t.id}" data validation failed:\n${e}\n\nExpected schema: ${JSON.stringify(t.inputSchema,null,2)}`}},isError:!0}}}let n=Kh(ym(t.resolveHtml(),e.data??null,t.injectId,t.transformData)),r=Ah(),i=Ie(16).toString(`hex`),a=r.createSession({surfaceId:`viewer`,transport:`viewer`,nonce:i});if(!a.ok)return{content:[{type:`text`,text:`${e.title}\n\nUnable to start local browser transport.`}],structuredContent:{kind:`error`,error:{code:`BROWSER_START_FAILED`,message:a.error.message}},isError:!0};let o=a.session.id,s=dh(`viewer`,e.actions??[],r,o,i),c=Zh(Or({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>`,` ${Gh(i)}`,`</div>`].join(`
|
|
2935
2935
|
`),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(`
|
|
2936
2936
|
`)],islands:[],payload:void 0,nonce:i,generatedAt:new Date().toISOString(),colorScheme:e.colorScheme,lang:e.lang,dir:e.dir,transport:`browser`,exportPolicy:`local-interactive`,footerContentHtml:fh}),o);Dh.set(o,{callbackSession:s,html:c,viewerHtml:n,hasClientConnected:!1,createdAt:Date.now()});let l=``;try{l=`http://127.0.0.1:${await jh()}/present/${o}`}catch(t){return Dh.delete(o),r.removeSession(o),{content:[{type:`text`,text:`${e.title}\n\nUnable to start local browser transport.`}],structuredContent:{kind:`error`,error:{code:`BROWSER_START_FAILED`,message:t instanceof Error?t.message:`Unable to start browser transport`}},isError:!0}}return await Hh(l),setTimeout(()=>{Dh.delete(o),r.removeSession(o)},xh),{content:[{type:`text`,text:Uh(e,l,`Rendered.`)}],structuredContent:{kind:`rendered`,reason:`no-response-required`}}}async function $h(e){Tg(`<html><body style="font-family:system-ui;padding:2rem;color:#888;text-align:center"><p>Content opened in browser window.</p></body></html>`);let t=Ah(),n=Ie(16).toString(`hex`),r=Ir(e,{transport:`browser`,registry:Hm,blockVendorScripts:Km(),nonce:n}),i=t.createSession({surfaceId:r.surfaceId,transport:`browser`,nonce:n});if(!i.ok)return{content:[{type:`text`,text:`${e.title}\n\nUnable to start local browser transport.`}],structuredContent:{kind:`error`,error:{code:`BROWSER_START_FAILED`,message:i.error.message}},isError:!0};let a=i.session.id,o=dh(r.surfaceId,r.actions,t,a,n),s=yh(r.vendorScripts,`browser`);bh();let c=r.actions.length>0?zh(r.actions):``,l=r.actions.length>0?Bh(r.actions,o.nonce):``,u=Xh(Qg(Or({title:e.title,subtitle:e.description,html:[r.html,c,l].filter(Boolean).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-D0Uhpi3k.js";import{createLogger as o,serializeError as s,setDetailedErrorLoggingEnabled as c}from"../../core/dist/index.js";import{randomUUID as l}from"node:crypto";const u=`__pending__:`;function d(e){return e.startsWith(u)}function f(e){let t=e.headers[`mcp-session-id`];return Array.isArray(t)?t[0]:t}function p(e,t,n,r){e.status(t).json({jsonrpc:`2.0`,error:{code:n,message:r},id:null})}var m=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=f(e),i=r?this.runtimes.get(r):void 0;if(r&&!i){p(t,404,-32001,`Session not found`);return}if(!i){if(e.method!==`POST`){p(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`&&!d(r)&&this.options.onSessionActivity?.(r),e.method===`DELETE`&&!d(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&&!d(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){p(e,503,-32003,`Session capacity reached`);return}let t=this.now(),n=await this.options.createServer(),r={id:`${u}${l()}`,transport:void 0,createdAt:t,lastAccessAt:t,server:n,requestChain:Promise.resolve()},i=this.options.createTransport({sessionIdGenerator:()=>l(),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 h(e){let t=e.includes(`T`)?e:`${e.replace(` `,`T`)}Z`;return Date.parse(t)}var g=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=h(n.lastActivity);return Number.isFinite(r)&&e-r>=t}).map(e=>e.sessionId)}};const _=o(`server`);async function v(o,u){let[{default:d},{loadConfig:f,resolveIndexMode:p},{registerDashboardRoutes:h,resolveDashboardDir:v},{registerSettingsRoutes:y,resolveSettingsDir:b},{createSettingsRouter:x},{authMiddleware:S,getOrCreateToken:C}]=await Promise.all([import(`express`),import(`./config-B-wvmMyo.js`),import(`./dashboard-static-Dw7Nsq4f.js`),import(`./settings-static-BpQgaMRs.js`),import(`./routes-C7bDyCOW.js`),import(`./auth-7LFAZQBu.js`).then(e=>e.t)]),w=f();c(w.logging?.errorDetails===!0),w.configError&&_.warn(`Config load failure`,{error:w.configError}),_.info(`Config loaded`,{sourceCount:w.sources.length,storePath:w.store.path});let T=d();T.use(d.json({limit:`1mb`}));let E=Number(u),D=`http://localhost:${E}`,O=process.env.AIKIT_CORS_ORIGIN??D,k=process.env.AIKIT_ALLOW_ANY_ORIGIN===`true`,A=n(`AIKIT_HTTP_MAX_SESSIONS`,8),j=n(`AIKIT_HTTP_SESSION_TIMEOUT_MINUTES`,30),M=n(`AIKIT_HTTP_SESSION_GC_INTERVAL_MINUTES`,5),N=r({limit:100,windowMs:6e4}),P=!1;T.use((t,n,r)=>{let i=Array.isArray(t.headers.origin)?t.headers.origin[0]:t.headers.origin,a=e({requestOrigin:i,configuredOrigin:O,allowAnyOrigin:k,fallbackOrigin:D});if(a.warn&&!P&&(P=!0,_.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 F=C();T.use(S(F)),T.use(`/mcp`,(e,n,r)=>{let i=t(e)??e.ip??e.socket.remoteAddress??`anonymous`;if(N.allow(i)){r();return}let a=Math.max(1,Math.ceil(N.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 I;T.use(`/mcp`,(e,t,n)=>{if(!I){let t=e.headers[`x-workspace-root`];typeof t==`string`&&t.length>0&&(I=t,_.debug(`Captured workspace root from proxy header`,{wsRoot:t}))}n()}),h(T,v(),_);let L=new Date().toISOString();T.use(`/settings/api`,x({log:_,mcpInfo:()=>({transport:`http`,port:E,pid:process.pid,startedAt:L})})),y(T,b(),_),T.get(`/health`,(e,t)=>{t.json({status:`ok`})});let R=!1,z=null,B=null,V=null,H=null,U=null,W=null,G=null,K=null,q=Promise.resolve(),J=async(e,n)=>{if(!R||!V||!H){n.status(503).json({jsonrpc:`2.0`,error:{code:-32603,message:`Server initializing — please retry in a few seconds`},id:null});return}let r=q,i;q=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(()=>{_.warn(`mcpLock timed out waiting for previous request, resetting lock chain`,{method:e.method,timeoutMs:a}),t(!1)},a);n.unref&&n.unref()})])&&(q=Promise.resolve(),i=()=>{},W)){let e=W;W=null,G=null,e.close().catch(()=>{})}try{let r=t(e);if(!W){if(r){n.status(404).json({jsonrpc:`2.0`,error:{code:-32001,message:`Session not found`},id:null});return}let e=new H({sessionIdGenerator:()=>l(),onsessioninitialized:async e=>{G=e,B?.onSessionStart(e,{transport:`http`})},onsessionclosed:async e=>{e&&B?.onSessionEnd(e),G=null}});e.onclose=()=>{W===e&&(W=null),G===e.sessionId&&(G=null)},W=e,await V.connect(e)}let i=W;await i.handleRequest(e,n,e.body),e.method!==`DELETE`&&(!r&&i.sessionId?(G=i.sessionId,B?.onSessionStart(i.sessionId,{transport:`http`}),B?.onSessionActivity(i.sessionId)):r&&B?.onSessionActivity(r))}catch(e){if(_.error(`MCP handler error`,s(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()}},Y=async(e,n)=>{let r=t(e);if(U&&(!W||r!==G)){await U.handleRequest(e,n,e.body);return}await J(e,n)};T.post(`/mcp`,Y),T.get(`/mcp`,Y),T.delete(`/mcp`,Y);let X=T.listen(E,`127.0.0.1`,()=>{_.info(`MCP server listening`,{url:`http://127.0.0.1:${E}/mcp`,port:E}),setTimeout(async()=>{try{typeof I==`string`&&I.length>0&&(w.sources[0]={path:I,excludePatterns:w.sources[0]?.excludePatterns??[]},w.allRoots=[I],_.debug(`Workspace root applied from proxy header`,{wsRoot:I}));let[{createLazyServer:e,createMcpServer:t,ALL_TOOL_NAMES:n},{StreamableHTTPServerTransport:r},{checkForUpdates:c,autoUpgradeScaffold:l}]=await Promise.all([import(`./server-DIJ0L_8t.js`),import(`@modelcontextprotocol/sdk/server/streamableHttp.js`),import(`./version-check-CggUKvv8.js`)]);c(),l(),setInterval(c,1440*60*1e3).unref();let u=!1,d=p(w),f=e(w,d);K=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(()=>{})])},V=f.server,H=r,R=!0,_.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`);B=new g(f.aikit.stateStore,{staleTimeoutMinutes:j,gcIntervalMinutes:M,onBeforeSessionDelete:e=>{if(G===e&&W){let e=W;W=null,G=null,e.close().catch(()=>void 0)}U?.closeSession(e,{notifySessionEnd:!1})},onSessionEndMaintenance:async()=>{if(!f.aikit?.curated||!f.aikit?.stateStore)return;let{pruneLessons:e}=await import(`./evolution-BX_zTSdj.js`).then(e=>e.t),t=await e(f.aikit.curated,f.aikit.stateStore,{dryRun:!1});t.pruned.length>0&&_.info(`Session-end lesson prune`,{pruned:t.pruned.length})}}),U=new m({createServer:()=>{if(!f.aikit)throw Error(`AI Kit components are not available after initialization`);return t(f.aikit,w)},createTransport:e=>new r(e),maxSessions:A,sessionTimeoutMinutes:j,onSessionStart:e=>B?.onSessionStart(e,{transport:`http`}),onSessionActivity:e=>B?.onSessionActivity(e),onSessionEnd:e=>B?.onSessionEnd(e)}),B.startGC(),G&&(B.onSessionStart(G,{transport:`http`}),B.onSessionActivity(G)),_.info(`HTTP session runtime ready`,{maxSessions:A,sessionTimeoutMinutes:j,gcIntervalMinutes:M})}catch(e){_.error(`Failed to start session manager`,s(e)),R=!1,u=!0,V=null,H=null,K=null}}),d===`auto`?f.ready.then(async()=>{try{let e=w.sources.map(e=>e.path).join(`, `);_.info(`Running initial index`,{sourcePaths:e}),await f.runInitialIndex(),_.info(`Initial index complete`)}catch(e){_.error(`Initial index failed; will retry on aikit_reindex`,i(o,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,w,f.aikit.store),n=f.aikit.store;z=t,t.start(),n.onBeforeClose&&n.onBeforeClose(()=>t.stop()),f.setSmartScheduler(t),_.debug(`Smart index scheduler started (HTTP mode)`)}catch(e){_.error(`Failed to start smart index scheduler`,i(o,e))}}):_.info(`Initial full indexing skipped in HTTP mode`,{indexMode:d}),f.ready.catch(e=>{_.error(`AI Kit initialization failed`,i(o,e)),R=!1,u=!0,V=null,H=null,K=null}),a(f.ready,()=>f.aikit?{curated:f.aikit.curated,stateStore:f.aikit.stateStore}:null,o)}catch(e){_.error(`Failed to load server modules`,i(o,e)),R=!1,K=null}},100)}),Z=!1,Q=async e=>{Z||(Z=!0,_.info(`Shutdown signal received`,{signal:e}),z?.stop(),B?.stop(),await import(`../../tools/dist/index.js`).then(({processStopAll:e})=>e()).catch(()=>{}),await U?.closeAll().catch(()=>void 0),G&&B?.onSessionEnd(G),W&&(await W.close().catch(()=>void 0),W=null,G=null),X.close(),V&&await V.close(),await K?.().catch(()=>void 0),process.exit(0))};process.on(`SIGINT`,()=>Q(`SIGINT`)),process.on(`SIGTERM`,()=>Q(`SIGTERM`))}export{v 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-D0Uhpi3k.js";import{createLogger as o,serializeError as s,setDetailedErrorLoggingEnabled as c}from"../../core/dist/index.js";import{randomUUID as l}from"node:crypto";const u=`__pending__:`;function d(e){return e.startsWith(u)}function f(e){let t=e.headers[`mcp-session-id`];return Array.isArray(t)?t[0]:t}function p(e,t,n,r){e.status(t).json({jsonrpc:`2.0`,error:{code:n,message:r},id:null})}var m=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=f(e),i=r?this.runtimes.get(r):void 0;if(r&&!i){p(t,404,-32001,`Session not found`);return}if(!i){if(e.method!==`POST`){p(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`&&!d(r)&&this.options.onSessionActivity?.(r),e.method===`DELETE`&&!d(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&&!d(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){p(e,503,-32003,`Session capacity reached`);return}let t=this.now(),n=await this.options.createServer(),r={id:`${u}${l()}`,transport:void 0,createdAt:t,lastAccessAt:t,server:n,requestChain:Promise.resolve()},i=this.options.createTransport({sessionIdGenerator:()=>l(),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 h(e){let t=e.includes(`T`)?e:`${e.replace(` `,`T`)}Z`;return Date.parse(t)}var g=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=h(n.lastActivity);return Number.isFinite(r)&&e-r>=t}).map(e=>e.sessionId)}};const _=o(`server`);async function v(o,u){let[{default:d},{loadConfig:f,resolveIndexMode:p},{registerDashboardRoutes:h,resolveDashboardDir:v},{registerSettingsRoutes:y,resolveSettingsDir:b},{createSettingsRouter:x},{authMiddleware:S,getOrCreateToken:C}]=await Promise.all([import(`express`),import(`./config-B-wvmMyo.js`),import(`./dashboard-static-Dw7Nsq4f.js`),import(`./settings-static-BpQgaMRs.js`),import(`./routes-C7bDyCOW.js`),import(`./auth-7LFAZQBu.js`).then(e=>e.t)]),w=f();c(w.logging?.errorDetails===!0),w.configError&&_.warn(`Config load failure`,{error:w.configError}),_.info(`Config loaded`,{sourceCount:w.sources.length,storePath:w.store.path});let T=d();T.use(d.json({limit:`1mb`}));let E=Number(u),D=`http://localhost:${E}`,O=process.env.AIKIT_CORS_ORIGIN??D,k=process.env.AIKIT_ALLOW_ANY_ORIGIN===`true`,A=n(`AIKIT_HTTP_MAX_SESSIONS`,8),j=n(`AIKIT_HTTP_SESSION_TIMEOUT_MINUTES`,30),M=n(`AIKIT_HTTP_SESSION_GC_INTERVAL_MINUTES`,5),N=r({limit:100,windowMs:6e4}),P=!1;T.use((t,n,r)=>{let i=Array.isArray(t.headers.origin)?t.headers.origin[0]:t.headers.origin,a=e({requestOrigin:i,configuredOrigin:O,allowAnyOrigin:k,fallbackOrigin:D});if(a.warn&&!P&&(P=!0,_.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 F=C();T.use(S(F)),T.use(`/mcp`,(e,n,r)=>{let i=t(e)??e.ip??e.socket.remoteAddress??`anonymous`;if(N.allow(i)){r();return}let a=Math.max(1,Math.ceil(N.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 I;T.use(`/mcp`,(e,t,n)=>{if(!I){let t=e.headers[`x-workspace-root`];typeof t==`string`&&t.length>0&&(I=t,_.debug(`Captured workspace root from proxy header`,{wsRoot:t}))}n()}),h(T,v(),_);let L=new Date().toISOString();T.use(`/settings/api`,x({log:_,mcpInfo:()=>({transport:`http`,port:E,pid:process.pid,startedAt:L})})),y(T,b(),_),T.get(`/health`,(e,t)=>{t.json({status:`ok`})});let R=!1,z=null,B=null,V=null,H=null,U=null,W=null,G=null,K=null,q=Promise.resolve(),J=async(e,n)=>{if(!R||!V||!H){n.status(503).json({jsonrpc:`2.0`,error:{code:-32603,message:`Server initializing — please retry in a few seconds`},id:null});return}let r=q,i;q=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(()=>{_.warn(`mcpLock timed out waiting for previous request, resetting lock chain`,{method:e.method,timeoutMs:a}),t(!1)},a);n.unref&&n.unref()})])&&(q=Promise.resolve(),i=()=>{},W)){let e=W;W=null,G=null,e.close().catch(()=>{})}try{let r=t(e);if(!W){if(r){n.status(404).json({jsonrpc:`2.0`,error:{code:-32001,message:`Session not found`},id:null});return}let e=new H({sessionIdGenerator:()=>l(),onsessioninitialized:async e=>{G=e,B?.onSessionStart(e,{transport:`http`})},onsessionclosed:async e=>{e&&B?.onSessionEnd(e),G=null}});e.onclose=()=>{W===e&&(W=null),G===e.sessionId&&(G=null)},W=e,await V.connect(e)}let i=W;await i.handleRequest(e,n,e.body),e.method!==`DELETE`&&(!r&&i.sessionId?(G=i.sessionId,B?.onSessionStart(i.sessionId,{transport:`http`}),B?.onSessionActivity(i.sessionId)):r&&B?.onSessionActivity(r))}catch(e){if(_.error(`MCP handler error`,s(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()}},Y=async(e,n)=>{let r=t(e);if(U&&(!W||r!==G)){await U.handleRequest(e,n,e.body);return}await J(e,n)};T.post(`/mcp`,Y),T.get(`/mcp`,Y),T.delete(`/mcp`,Y);let X=T.listen(E,`127.0.0.1`,()=>{_.info(`MCP server listening`,{url:`http://127.0.0.1:${E}/mcp`,port:E}),setTimeout(async()=>{try{typeof I==`string`&&I.length>0&&(w.sources[0]={path:I,excludePatterns:w.sources[0]?.excludePatterns??[]},w.allRoots=[I],_.debug(`Workspace root applied from proxy header`,{wsRoot:I}));let[{createLazyServer:e,createMcpServer:t,ALL_TOOL_NAMES:n},{StreamableHTTPServerTransport:r},{checkForUpdates:c,autoUpgradeScaffold:l}]=await Promise.all([import(`./server-BlN0Hbye.js`),import(`@modelcontextprotocol/sdk/server/streamableHttp.js`),import(`./version-check-CggUKvv8.js`)]);c(),l(),setInterval(c,1440*60*1e3).unref();let u=!1,d=p(w),f=e(w,d);K=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(()=>{})])},V=f.server,H=r,R=!0,_.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`);B=new g(f.aikit.stateStore,{staleTimeoutMinutes:j,gcIntervalMinutes:M,onBeforeSessionDelete:e=>{if(G===e&&W){let e=W;W=null,G=null,e.close().catch(()=>void 0)}U?.closeSession(e,{notifySessionEnd:!1})},onSessionEndMaintenance:async()=>{if(!f.aikit?.curated||!f.aikit?.stateStore)return;let{pruneLessons:e}=await import(`./evolution-BX_zTSdj.js`).then(e=>e.t),t=await e(f.aikit.curated,f.aikit.stateStore,{dryRun:!1});t.pruned.length>0&&_.info(`Session-end lesson prune`,{pruned:t.pruned.length})}}),U=new m({createServer:()=>{if(!f.aikit)throw Error(`AI Kit components are not available after initialization`);return t(f.aikit,w)},createTransport:e=>new r(e),maxSessions:A,sessionTimeoutMinutes:j,onSessionStart:e=>B?.onSessionStart(e,{transport:`http`}),onSessionActivity:e=>B?.onSessionActivity(e),onSessionEnd:e=>B?.onSessionEnd(e)}),B.startGC(),G&&(B.onSessionStart(G,{transport:`http`}),B.onSessionActivity(G)),_.info(`HTTP session runtime ready`,{maxSessions:A,sessionTimeoutMinutes:j,gcIntervalMinutes:M})}catch(e){_.error(`Failed to start session manager`,s(e)),R=!1,u=!0,V=null,H=null,K=null}}),d===`auto`?f.ready.then(async()=>{try{let e=w.sources.map(e=>e.path).join(`, `);_.info(`Running initial index`,{sourcePaths:e}),await f.runInitialIndex(),_.info(`Initial index complete`)}catch(e){_.error(`Initial index failed; will retry on aikit_reindex`,i(o,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,w,f.aikit.store),n=f.aikit.store;z=t,t.start(),n.onBeforeClose&&n.onBeforeClose(()=>t.stop()),f.setSmartScheduler(t),_.debug(`Smart index scheduler started (HTTP mode)`)}catch(e){_.error(`Failed to start smart index scheduler`,i(o,e))}}):_.info(`Initial full indexing skipped in HTTP mode`,{indexMode:d}),f.ready.catch(e=>{_.error(`AI Kit initialization failed`,i(o,e)),R=!1,u=!0,V=null,H=null,K=null}),a(f.ready,()=>f.aikit?{curated:f.aikit.curated,stateStore:f.aikit.stateStore}:null,o)}catch(e){_.error(`Failed to load server modules`,i(o,e)),R=!1,K=null}},100)}),Z=!1,Q=async e=>{Z||(Z=!0,_.info(`Shutdown signal received`,{signal:e}),z?.stop(),B?.stop(),await import(`../../tools/dist/index.js`).then(({processStopAll:e})=>e()).catch(()=>{}),await U?.closeAll().catch(()=>void 0),G&&B?.onSessionEnd(G),W&&(await W.close().catch(()=>void 0),W=null,G=null),X.close(),V&&await V.close(),await K?.().catch(()=>void 0),process.exit(0))};process.on(`SIGINT`,()=>Q(`SIGINT`)),process.on(`SIGTERM`,()=>Q(`SIGTERM`))}export{v as startHttpMode};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{a as e,i as t,o as n,s as r}from"./bin.js";import{n as i,t as a}from"./startup-maintenance-L9NUOBVy.js";import{createLogger as o,serializeError as s,setDetailedErrorLoggingEnabled as c}from"../../core/dist/index.js";import{randomUUID as l}from"node:crypto";const u=`__pending__:`;function d(e){return e.startsWith(u)}function f(e){let t=e.headers[`mcp-session-id`];return Array.isArray(t)?t[0]:t}function p(e,t,n,r){e.status(t).json({jsonrpc:`2.0`,error:{code:n,message:r},id:null})}var m=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=f(e),i=r?this.runtimes.get(r):void 0;if(r&&!i){p(t,404,-32001,`Session not found`);return}if(!i){if(e.method!==`POST`){p(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`&&!d(r)&&this.options.onSessionActivity?.(r),e.method===`DELETE`&&!d(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&&!d(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){p(e,503,-32003,`Session capacity reached`);return}let t=this.now(),n=await this.options.createServer(),r={id:`${u}${l()}`,transport:void 0,createdAt:t,lastAccessAt:t,server:n,requestChain:Promise.resolve()},i=this.options.createTransport({sessionIdGenerator:()=>l(),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 h(e){let t=e.includes(`T`)?e:`${e.replace(` `,`T`)}Z`;return Date.parse(t)}var g=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=h(n.lastActivity);return Number.isFinite(r)&&e-r>=t}).map(e=>e.sessionId)}};const _=o(`server`);async function v(o,u){let[{default:d},{loadConfig:f,resolveIndexMode:p},{registerDashboardRoutes:h,resolveDashboardDir:v},{registerSettingsRoutes:y,resolveSettingsDir:b},{createSettingsRouter:x},{authMiddleware:S,getOrCreateToken:C}]=await Promise.all([import(`express`),import(`./config-Bx85fwRX.js`),import(`./dashboard-static-dPnij4uF.js`),import(`./settings-static-MepJZjer.js`),import(`./routes-CfG5gdSR.js`),import(`./auth-bEP-6uqy.js`)]),w=f();c(w.logging?.errorDetails===!0),w.configError&&_.warn(`Config load failure`,{error:w.configError}),_.info(`Config loaded`,{sourceCount:w.sources.length,storePath:w.store.path});let T=d();T.use(d.json({limit:`1mb`}));let E=Number(u),D=`http://localhost:${E}`,O=process.env.AIKIT_CORS_ORIGIN??D,k=process.env.AIKIT_ALLOW_ANY_ORIGIN===`true`,A=n(`AIKIT_HTTP_MAX_SESSIONS`,8),j=n(`AIKIT_HTTP_SESSION_TIMEOUT_MINUTES`,30),M=n(`AIKIT_HTTP_SESSION_GC_INTERVAL_MINUTES`,5),N=t({limit:100,windowMs:6e4}),P=!1;T.use((e,t,n)=>{let i=Array.isArray(e.headers.origin)?e.headers.origin[0]:e.headers.origin,a=r({requestOrigin:i,configuredOrigin:O,allowAnyOrigin:k,fallbackOrigin:D});if(a.warn&&!P&&(P=!0,_.warn(`Rejected non-local CORS origin while AIKIT_CORS_ORIGIN=*`,{origin:i,allowAnyOriginEnv:`AIKIT_ALLOW_ANY_ORIGIN=true`})),i&&!a.allowOrigin){t.status(403).json({error:`Origin not allowed`});return}if(a.allowOrigin&&t.setHeader(`Access-Control-Allow-Origin`,a.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 F=C();T.use(S(F)),T.use(`/mcp`,(t,n,r)=>{let i=e(t)??t.ip??t.socket.remoteAddress??`anonymous`;if(N.allow(i)){r();return}let a=Math.max(1,Math.ceil(N.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 I;T.use(`/mcp`,(e,t,n)=>{if(!I){let t=e.headers[`x-workspace-root`];typeof t==`string`&&t.length>0&&(I=t,_.debug(`Captured workspace root from proxy header`,{wsRoot:t}))}n()}),h(T,v(),_);let L=new Date().toISOString();T.use(`/settings/api`,x({log:_,mcpInfo:()=>({transport:`http`,port:E,pid:process.pid,startedAt:L})})),y(T,b(),_),T.get(`/health`,(e,t)=>{t.json({status:`ok`})});let R=!1,z=null,B=null,V=null,H=null,U=null,W=null,G=null,K=null,q=Promise.resolve(),J=async(t,n)=>{if(!R||!V||!H){n.status(503).json({jsonrpc:`2.0`,error:{code:-32603,message:`Server initializing — please retry in a few seconds`},id:null});return}let r=q,i;q=new Promise(e=>{i=e});let a={POST:6e4,GET:1e4,DELETE:1e4}[t.method]??3e4;if(!await Promise.race([r.then(()=>!0),new Promise(e=>{let n=setTimeout(()=>{_.warn(`mcpLock timed out waiting for previous request, resetting lock chain`,{method:t.method,timeoutMs:a}),e(!1)},a);n.unref&&n.unref()})])&&(q=Promise.resolve(),i=()=>{},W)){let e=W;W=null,G=null,e.close().catch(()=>{})}try{let r=e(t);if(!W){if(r){n.status(404).json({jsonrpc:`2.0`,error:{code:-32001,message:`Session not found`},id:null});return}let e=new H({sessionIdGenerator:()=>l(),onsessioninitialized:async e=>{G=e,B?.onSessionStart(e,{transport:`http`})},onsessionclosed:async e=>{e&&B?.onSessionEnd(e),G=null}});e.onclose=()=>{W===e&&(W=null),G===e.sessionId&&(G=null)},W=e,await V.connect(e)}let i=W;await i.handleRequest(t,n,t.body),t.method!==`DELETE`&&(!r&&i.sessionId?(G=i.sessionId,B?.onSessionStart(i.sessionId,{transport:`http`}),B?.onSessionActivity(i.sessionId)):r&&B?.onSessionActivity(r))}catch(e){if(_.error(`MCP handler error`,s(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()}},Y=async(t,n)=>{let r=e(t);if(U&&(!W||r!==G)){await U.handleRequest(t,n,t.body);return}await J(t,n)};T.post(`/mcp`,Y),T.get(`/mcp`,Y),T.delete(`/mcp`,Y);let X=T.listen(E,`127.0.0.1`,()=>{_.info(`MCP server listening`,{url:`http://127.0.0.1:${E}/mcp`,port:E}),setTimeout(async()=>{try{typeof I==`string`&&I.length>0&&(w.sources[0]={path:I,excludePatterns:w.sources[0]?.excludePatterns??[]},w.allRoots=[I],_.debug(`Workspace root applied from proxy header`,{wsRoot:I}));let[{createLazyServer:e,createMcpServer:t,ALL_TOOL_NAMES:n},{StreamableHTTPServerTransport:r},{checkForUpdates:c,autoUpgradeScaffold:l}]=await Promise.all([import(`./server-4xcIVuzC.js`),import(`@modelcontextprotocol/sdk/server/streamableHttp.js`),import(`./version-check-CdBHTxtt.js`)]);c(),l(),setInterval(c,1440*60*1e3).unref();let u=!1,d=p(w),f=e(w,d);K=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(()=>{})])},V=f.server,H=r,R=!0,_.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`);B=new g(f.aikit.stateStore,{staleTimeoutMinutes:j,gcIntervalMinutes:M,onBeforeSessionDelete:e=>{if(G===e&&W){let e=W;W=null,G=null,e.close().catch(()=>void 0)}U?.closeSession(e,{notifySessionEnd:!1})},onSessionEndMaintenance:async()=>{if(!f.aikit?.curated||!f.aikit?.stateStore)return;let{pruneLessons:e}=await import(`./evolution-DWaEE6XW.js`).then(e=>e.t),t=await e(f.aikit.curated,f.aikit.stateStore,{dryRun:!1});t.pruned.length>0&&_.info(`Session-end lesson prune`,{pruned:t.pruned.length})}}),U=new m({createServer:()=>{if(!f.aikit)throw Error(`AI Kit components are not available after initialization`);return t(f.aikit,w)},createTransport:e=>new r(e),maxSessions:A,sessionTimeoutMinutes:j,onSessionStart:e=>B?.onSessionStart(e,{transport:`http`}),onSessionActivity:e=>B?.onSessionActivity(e),onSessionEnd:e=>B?.onSessionEnd(e)}),B.startGC(),G&&(B.onSessionStart(G,{transport:`http`}),B.onSessionActivity(G)),_.info(`HTTP session runtime ready`,{maxSessions:A,sessionTimeoutMinutes:j,gcIntervalMinutes:M})}catch(e){_.error(`Failed to start session manager`,s(e)),R=!1,u=!0,V=null,H=null,K=null}}),d===`auto`?f.ready.then(async()=>{try{let e=w.sources.map(e=>e.path).join(`, `);_.info(`Running initial index`,{sourcePaths:e}),await f.runInitialIndex(),_.info(`Initial index complete`)}catch(e){_.error(`Initial index failed; will retry on aikit_reindex`,i(o,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,w,f.aikit.store),n=f.aikit.store;z=t,t.start(),n.onBeforeClose&&n.onBeforeClose(()=>t.stop()),f.setSmartScheduler(t),_.debug(`Smart index scheduler started (HTTP mode)`)}catch(e){_.error(`Failed to start smart index scheduler`,i(o,e))}}):_.info(`Initial full indexing skipped in HTTP mode`,{indexMode:d}),f.ready.catch(e=>{_.error(`AI Kit initialization failed`,i(o,e)),R=!1,u=!0,V=null,H=null,K=null}),a(f.ready,()=>f.aikit?{curated:f.aikit.curated,stateStore:f.aikit.stateStore}:null,o)}catch(e){_.error(`Failed to load server modules`,i(o,e)),R=!1,K=null}},100)}),Z=!1,Q=async e=>{Z||(Z=!0,_.info(`Shutdown signal received`,{signal:e}),z?.stop(),B?.stop(),await import(`../../tools/dist/index.js`).then(({processStopAll:e})=>e()).catch(()=>{}),await U?.closeAll().catch(()=>void 0),G&&B?.onSessionEnd(G),W&&(await W.close().catch(()=>void 0),W=null,G=null),X.close(),V&&await V.close(),await K?.().catch(()=>void 0),process.exit(0))};process.on(`SIGINT`,()=>Q(`SIGINT`)),process.on(`SIGTERM`,()=>Q(`SIGTERM`))}export{v as startHttpMode};
|
|
2
|
+
import{a as e,i as t,o as n,s as r}from"./bin.js";import{n as i,t as a}from"./startup-maintenance-L9NUOBVy.js";import{createLogger as o,serializeError as s,setDetailedErrorLoggingEnabled as c}from"../../core/dist/index.js";import{randomUUID as l}from"node:crypto";const u=`__pending__:`;function d(e){return e.startsWith(u)}function f(e){let t=e.headers[`mcp-session-id`];return Array.isArray(t)?t[0]:t}function p(e,t,n,r){e.status(t).json({jsonrpc:`2.0`,error:{code:n,message:r},id:null})}var m=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=f(e),i=r?this.runtimes.get(r):void 0;if(r&&!i){p(t,404,-32001,`Session not found`);return}if(!i){if(e.method!==`POST`){p(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`&&!d(r)&&this.options.onSessionActivity?.(r),e.method===`DELETE`&&!d(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&&!d(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){p(e,503,-32003,`Session capacity reached`);return}let t=this.now(),n=await this.options.createServer(),r={id:`${u}${l()}`,transport:void 0,createdAt:t,lastAccessAt:t,server:n,requestChain:Promise.resolve()},i=this.options.createTransport({sessionIdGenerator:()=>l(),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 h(e){let t=e.includes(`T`)?e:`${e.replace(` `,`T`)}Z`;return Date.parse(t)}var g=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=h(n.lastActivity);return Number.isFinite(r)&&e-r>=t}).map(e=>e.sessionId)}};const _=o(`server`);async function v(o,u){let[{default:d},{loadConfig:f,resolveIndexMode:p},{registerDashboardRoutes:h,resolveDashboardDir:v},{registerSettingsRoutes:y,resolveSettingsDir:b},{createSettingsRouter:x},{authMiddleware:S,getOrCreateToken:C}]=await Promise.all([import(`express`),import(`./config-Bx85fwRX.js`),import(`./dashboard-static-dPnij4uF.js`),import(`./settings-static-MepJZjer.js`),import(`./routes-CfG5gdSR.js`),import(`./auth-bEP-6uqy.js`)]),w=f();c(w.logging?.errorDetails===!0),w.configError&&_.warn(`Config load failure`,{error:w.configError}),_.info(`Config loaded`,{sourceCount:w.sources.length,storePath:w.store.path});let T=d();T.use(d.json({limit:`1mb`}));let E=Number(u),D=`http://localhost:${E}`,O=process.env.AIKIT_CORS_ORIGIN??D,k=process.env.AIKIT_ALLOW_ANY_ORIGIN===`true`,A=n(`AIKIT_HTTP_MAX_SESSIONS`,8),j=n(`AIKIT_HTTP_SESSION_TIMEOUT_MINUTES`,30),M=n(`AIKIT_HTTP_SESSION_GC_INTERVAL_MINUTES`,5),N=t({limit:100,windowMs:6e4}),P=!1;T.use((e,t,n)=>{let i=Array.isArray(e.headers.origin)?e.headers.origin[0]:e.headers.origin,a=r({requestOrigin:i,configuredOrigin:O,allowAnyOrigin:k,fallbackOrigin:D});if(a.warn&&!P&&(P=!0,_.warn(`Rejected non-local CORS origin while AIKIT_CORS_ORIGIN=*`,{origin:i,allowAnyOriginEnv:`AIKIT_ALLOW_ANY_ORIGIN=true`})),i&&!a.allowOrigin){t.status(403).json({error:`Origin not allowed`});return}if(a.allowOrigin&&t.setHeader(`Access-Control-Allow-Origin`,a.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 F=C();T.use(S(F)),T.use(`/mcp`,(t,n,r)=>{let i=e(t)??t.ip??t.socket.remoteAddress??`anonymous`;if(N.allow(i)){r();return}let a=Math.max(1,Math.ceil(N.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 I;T.use(`/mcp`,(e,t,n)=>{if(!I){let t=e.headers[`x-workspace-root`];typeof t==`string`&&t.length>0&&(I=t,_.debug(`Captured workspace root from proxy header`,{wsRoot:t}))}n()}),h(T,v(),_);let L=new Date().toISOString();T.use(`/settings/api`,x({log:_,mcpInfo:()=>({transport:`http`,port:E,pid:process.pid,startedAt:L})})),y(T,b(),_),T.get(`/health`,(e,t)=>{t.json({status:`ok`})});let R=!1,z=null,B=null,V=null,H=null,U=null,W=null,G=null,K=null,q=Promise.resolve(),J=async(t,n)=>{if(!R||!V||!H){n.status(503).json({jsonrpc:`2.0`,error:{code:-32603,message:`Server initializing — please retry in a few seconds`},id:null});return}let r=q,i;q=new Promise(e=>{i=e});let a={POST:6e4,GET:1e4,DELETE:1e4}[t.method]??3e4;if(!await Promise.race([r.then(()=>!0),new Promise(e=>{let n=setTimeout(()=>{_.warn(`mcpLock timed out waiting for previous request, resetting lock chain`,{method:t.method,timeoutMs:a}),e(!1)},a);n.unref&&n.unref()})])&&(q=Promise.resolve(),i=()=>{},W)){let e=W;W=null,G=null,e.close().catch(()=>{})}try{let r=e(t);if(!W){if(r){n.status(404).json({jsonrpc:`2.0`,error:{code:-32001,message:`Session not found`},id:null});return}let e=new H({sessionIdGenerator:()=>l(),onsessioninitialized:async e=>{G=e,B?.onSessionStart(e,{transport:`http`})},onsessionclosed:async e=>{e&&B?.onSessionEnd(e),G=null}});e.onclose=()=>{W===e&&(W=null),G===e.sessionId&&(G=null)},W=e,await V.connect(e)}let i=W;await i.handleRequest(t,n,t.body),t.method!==`DELETE`&&(!r&&i.sessionId?(G=i.sessionId,B?.onSessionStart(i.sessionId,{transport:`http`}),B?.onSessionActivity(i.sessionId)):r&&B?.onSessionActivity(r))}catch(e){if(_.error(`MCP handler error`,s(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()}},Y=async(t,n)=>{let r=e(t);if(U&&(!W||r!==G)){await U.handleRequest(t,n,t.body);return}await J(t,n)};T.post(`/mcp`,Y),T.get(`/mcp`,Y),T.delete(`/mcp`,Y);let X=T.listen(E,`127.0.0.1`,()=>{_.info(`MCP server listening`,{url:`http://127.0.0.1:${E}/mcp`,port:E}),setTimeout(async()=>{try{typeof I==`string`&&I.length>0&&(w.sources[0]={path:I,excludePatterns:w.sources[0]?.excludePatterns??[]},w.allRoots=[I],_.debug(`Workspace root applied from proxy header`,{wsRoot:I}));let[{createLazyServer:e,createMcpServer:t,ALL_TOOL_NAMES:n},{StreamableHTTPServerTransport:r},{checkForUpdates:c,autoUpgradeScaffold:l}]=await Promise.all([import(`./server-BPpxMa6G.js`),import(`@modelcontextprotocol/sdk/server/streamableHttp.js`),import(`./version-check-CdBHTxtt.js`)]);c(),l(),setInterval(c,1440*60*1e3).unref();let u=!1,d=p(w),f=e(w,d);K=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(()=>{})])},V=f.server,H=r,R=!0,_.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`);B=new g(f.aikit.stateStore,{staleTimeoutMinutes:j,gcIntervalMinutes:M,onBeforeSessionDelete:e=>{if(G===e&&W){let e=W;W=null,G=null,e.close().catch(()=>void 0)}U?.closeSession(e,{notifySessionEnd:!1})},onSessionEndMaintenance:async()=>{if(!f.aikit?.curated||!f.aikit?.stateStore)return;let{pruneLessons:e}=await import(`./evolution-DWaEE6XW.js`).then(e=>e.t),t=await e(f.aikit.curated,f.aikit.stateStore,{dryRun:!1});t.pruned.length>0&&_.info(`Session-end lesson prune`,{pruned:t.pruned.length})}}),U=new m({createServer:()=>{if(!f.aikit)throw Error(`AI Kit components are not available after initialization`);return t(f.aikit,w)},createTransport:e=>new r(e),maxSessions:A,sessionTimeoutMinutes:j,onSessionStart:e=>B?.onSessionStart(e,{transport:`http`}),onSessionActivity:e=>B?.onSessionActivity(e),onSessionEnd:e=>B?.onSessionEnd(e)}),B.startGC(),G&&(B.onSessionStart(G,{transport:`http`}),B.onSessionActivity(G)),_.info(`HTTP session runtime ready`,{maxSessions:A,sessionTimeoutMinutes:j,gcIntervalMinutes:M})}catch(e){_.error(`Failed to start session manager`,s(e)),R=!1,u=!0,V=null,H=null,K=null}}),d===`auto`?f.ready.then(async()=>{try{let e=w.sources.map(e=>e.path).join(`, `);_.info(`Running initial index`,{sourcePaths:e}),await f.runInitialIndex(),_.info(`Initial index complete`)}catch(e){_.error(`Initial index failed; will retry on aikit_reindex`,i(o,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,w,f.aikit.store),n=f.aikit.store;z=t,t.start(),n.onBeforeClose&&n.onBeforeClose(()=>t.stop()),f.setSmartScheduler(t),_.debug(`Smart index scheduler started (HTTP mode)`)}catch(e){_.error(`Failed to start smart index scheduler`,i(o,e))}}):_.info(`Initial full indexing skipped in HTTP mode`,{indexMode:d}),f.ready.catch(e=>{_.error(`AI Kit initialization failed`,i(o,e)),R=!1,u=!0,V=null,H=null,K=null}),a(f.ready,()=>f.aikit?{curated:f.aikit.curated,stateStore:f.aikit.stateStore}:null,o)}catch(e){_.error(`Failed to load server modules`,i(o,e)),R=!1,K=null}},100)}),Z=!1,Q=async e=>{Z||(Z=!0,_.info(`Shutdown signal received`,{signal:e}),z?.stop(),B?.stop(),await import(`../../tools/dist/index.js`).then(({processStopAll:e})=>e()).catch(()=>{}),await U?.closeAll().catch(()=>void 0),G&&B?.onSessionEnd(G),W&&(await W.close().catch(()=>void 0),W=null,G=null),X.close(),V&&await V.close(),await K?.().catch(()=>void 0),process.exit(0))};process.on(`SIGINT`,()=>Q(`SIGINT`)),process.on(`SIGTERM`,()=>Q(`SIGTERM`))}export{v as startHttpMode};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{r as e}from"./bin.js";import{n as t,t as n}from"./startup-maintenance-L9NUOBVy.js";import{t as r}from"./repair-json-D4mft_HA.js";import{createLogger as i,serializeError as a,setDetailedErrorLoggingEnabled as o}from"../../core/dist/index.js";const s=i(`server`);var c=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 s.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 l(r){let[{loadConfig:i,reconfigureForWorkspace:l,resolveIndexMode:u},{createLazyServer:d},{checkForUpdates:f,autoUpgradeScaffold:p},{RootsListChangedNotificationSchema:m}]=await Promise.all([import(`./config-Bx85fwRX.js`),import(`./server-
|
|
2
|
+
import{r as e}from"./bin.js";import{n as t,t as n}from"./startup-maintenance-L9NUOBVy.js";import{t as r}from"./repair-json-D4mft_HA.js";import{createLogger as i,serializeError as a,setDetailedErrorLoggingEnabled as o}from"../../core/dist/index.js";const s=i(`server`);var c=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 s.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 l(r){let[{loadConfig:i,reconfigureForWorkspace:l,resolveIndexMode:u},{createLazyServer:d},{checkForUpdates:f,autoUpgradeScaffold:p},{RootsListChangedNotificationSchema:m}]=await Promise.all([import(`./config-Bx85fwRX.js`),import(`./server-BPpxMa6G.js`),import(`./version-check-CdBHTxtt.js`),import(`@modelcontextprotocol/sdk/types.js`)]),h=i();o(h.logging?.errorDetails===!0),h.configError&&s.warn(`Config load failure`,{error:h.configError}),s.info(`Config loaded`,{sourceCount:h.sources.length,storePath:h.store.path}),p(),setInterval(f,1440*60*1e3).unref();let g=u(h),_=d(h,g),{server:v,startInit:y,ready:b,runInitialIndex:x}=_,{StdioServerTransport:S}=await import(`@modelcontextprotocol/sdk/server/stdio.js`),C=new S;if(typeof C._readBuffer?.readMessage!=`function`)throw Error(`Cannot install JSON repair: StdioServerTransport._readBuffer has unexpected shape`);C._readBuffer=new c,s.debug(`JSON repair installed on stdio transport`),await v.connect(C),s.debug(`MCP server started`,{transport:`stdio`}),await e({config:h,indexMode:g,log:s,rootsChangedNotificationSchema:m,reconfigureForWorkspace:l,runInitialIndex:x,server:v,startInit:y,version:r});let w=null,T=null,E=!1,D=async e=>{E||(E=!0,s.info(`Shutdown signal received`,{signal:e}),w&&=(clearTimeout(w),null),T?.stop(),await import(`../../tools/dist/index.js`).then(({processStopAll:e})=>e()).catch(()=>{}),await C.close().catch(()=>void 0),await v.close().catch(()=>void 0),_.aikit&&await Promise.all([_.aikit.embedder.shutdown?.().catch(()=>{})??Promise.resolve(),_.aikit.graphStore.close().catch(()=>{}),_.aikit.closeStateStore?.().catch(()=>{})??Promise.resolve(),_.aikit.store.close().catch(()=>{})]),process.exit(0))},O=()=>{w&&clearTimeout(w),w=setTimeout(async()=>{s.info(`Auto-shutdown: no activity for 30 minutes — releasing resources`);try{let e=_.aikit;e&&(e.embedder.shutdown?.().catch(()=>{}),e.store.releaseMemory?.(),e.graphStore.releaseMemory?.())}catch(e){s.warn(`Resource release failed during shutdown`,a(e))}},18e5),w.unref&&w.unref()};O(),process.stdin.on(`data`,()=>O()),process.stdin.on(`end`,()=>void D(`stdin-end`)),process.stdin.on(`close`,()=>void D(`stdin-close`)),process.stdin.on(`error`,()=>void D(`stdin-error`)),process.on(`SIGINT`,()=>void D(`SIGINT`)),process.on(`SIGTERM`,()=>void D(`SIGTERM`)),b.catch(e=>{s.error(`Initialization failed — server will continue with limited tools`,t(r,e))}),g===`smart`?b.then(async()=>{try{if(!_.aikit)throw Error(`AI Kit components are not available after initialization`);let{SmartIndexScheduler:e}=await import(`../../indexer/dist/index.js`),t=new e(_.aikit.indexer,h,_.aikit.store);T=t;let n=_.aikit.store;t.start(),n.onBeforeClose&&n.onBeforeClose(()=>t.stop()),_.setSmartScheduler(t),s.debug(`Smart index scheduler started (stdio mode)`)}catch(e){s.error(`Failed to start smart index scheduler`,t(r,e))}}).catch(e=>s.error(`AI Kit init failed for smart scheduler`,t(r,e))):s.warn(`Initial full indexing skipped; use aikit_reindex to index manually`,{indexMode:g}),n(b,()=>_.aikit?{curated:_.aikit.curated,stateStore:_.aikit.stateStore}:null,r)}export{l as startStdioMode};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{n as e}from"./workspace-bootstrap-BJloolzr.js";import{n as t,t as n}from"./startup-maintenance-D0Uhpi3k.js";import{t as r}from"./repair-json-B6Q_HRoP.js";import{createLogger as i,serializeError as a,setDetailedErrorLoggingEnabled as o}from"../../core/dist/index.js";const s=i(`server`);var c=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 s.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 l(r){let[{loadConfig:i,reconfigureForWorkspace:l,resolveIndexMode:u},{createLazyServer:d},{checkForUpdates:f,autoUpgradeScaffold:p},{RootsListChangedNotificationSchema:m}]=await Promise.all([import(`./config-B-wvmMyo.js`),import(`./server-
|
|
1
|
+
import{n as e}from"./workspace-bootstrap-BJloolzr.js";import{n as t,t as n}from"./startup-maintenance-D0Uhpi3k.js";import{t as r}from"./repair-json-B6Q_HRoP.js";import{createLogger as i,serializeError as a,setDetailedErrorLoggingEnabled as o}from"../../core/dist/index.js";const s=i(`server`);var c=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 s.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 l(r){let[{loadConfig:i,reconfigureForWorkspace:l,resolveIndexMode:u},{createLazyServer:d},{checkForUpdates:f,autoUpgradeScaffold:p},{RootsListChangedNotificationSchema:m}]=await Promise.all([import(`./config-B-wvmMyo.js`),import(`./server-BlN0Hbye.js`),import(`./version-check-CggUKvv8.js`),import(`@modelcontextprotocol/sdk/types.js`)]),h=i();o(h.logging?.errorDetails===!0),h.configError&&s.warn(`Config load failure`,{error:h.configError}),s.info(`Config loaded`,{sourceCount:h.sources.length,storePath:h.store.path}),p(),setInterval(f,1440*60*1e3).unref();let g=u(h),_=d(h,g),{server:v,startInit:y,ready:b,runInitialIndex:x}=_,{StdioServerTransport:S}=await import(`@modelcontextprotocol/sdk/server/stdio.js`),C=new S;if(typeof C._readBuffer?.readMessage!=`function`)throw Error(`Cannot install JSON repair: StdioServerTransport._readBuffer has unexpected shape`);C._readBuffer=new c,s.debug(`JSON repair installed on stdio transport`),await v.connect(C),s.debug(`MCP server started`,{transport:`stdio`}),await e({config:h,indexMode:g,log:s,rootsChangedNotificationSchema:m,reconfigureForWorkspace:l,runInitialIndex:x,server:v,startInit:y,version:r});let w=null,T=null,E=!1,D=async e=>{E||(E=!0,s.info(`Shutdown signal received`,{signal:e}),w&&=(clearTimeout(w),null),T?.stop(),await import(`../../tools/dist/index.js`).then(({processStopAll:e})=>e()).catch(()=>{}),await C.close().catch(()=>void 0),await v.close().catch(()=>void 0),_.aikit&&await Promise.all([_.aikit.embedder.shutdown?.().catch(()=>{})??Promise.resolve(),_.aikit.graphStore.close().catch(()=>{}),_.aikit.closeStateStore?.().catch(()=>{})??Promise.resolve(),_.aikit.store.close().catch(()=>{})]),process.exit(0))},O=()=>{w&&clearTimeout(w),w=setTimeout(async()=>{s.info(`Auto-shutdown: no activity for 30 minutes — releasing resources`);try{let e=_.aikit;e&&(e.embedder.shutdown?.().catch(()=>{}),e.store.releaseMemory?.(),e.graphStore.releaseMemory?.())}catch(e){s.warn(`Resource release failed during shutdown`,a(e))}},18e5),w.unref&&w.unref()};O(),process.stdin.on(`data`,()=>O()),process.stdin.on(`end`,()=>void D(`stdin-end`)),process.stdin.on(`close`,()=>void D(`stdin-close`)),process.stdin.on(`error`,()=>void D(`stdin-error`)),process.on(`SIGINT`,()=>void D(`SIGINT`)),process.on(`SIGTERM`,()=>void D(`SIGTERM`)),b.catch(e=>{s.error(`Initialization failed — server will continue with limited tools`,t(r,e))}),g===`smart`?b.then(async()=>{try{if(!_.aikit)throw Error(`AI Kit components are not available after initialization`);let{SmartIndexScheduler:e}=await import(`../../indexer/dist/index.js`),t=new e(_.aikit.indexer,h,_.aikit.store);T=t;let n=_.aikit.store;t.start(),n.onBeforeClose&&n.onBeforeClose(()=>t.stop()),_.setSmartScheduler(t),s.debug(`Smart index scheduler started (stdio mode)`)}catch(e){s.error(`Failed to start smart index scheduler`,t(r,e))}}).catch(e=>s.error(`AI Kit init failed for smart scheduler`,t(r,e))):s.warn(`Initial full indexing skipped; use aikit_reindex to index manually`,{indexMode:g}),n(b,()=>_.aikit?{curated:_.aikit.curated,stateStore:_.aikit.stateStore}:null,r)}export{l as startStdioMode};
|