@vpxa/aikit 0.1.327 → 0.1.329
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.d.ts +6 -1
- package/packages/browser/dist/index.js +1 -1
- package/packages/server/dist/bin.js +2 -2
- package/packages/server/dist/index.d.ts +2 -6
- package/packages/server/dist/index.js +1 -1
- package/packages/server/dist/{server-DMPbgOpF.js → server-4xcIVuzC.js} +162 -162
- package/packages/server/dist/{server-CBJi-ji8.js → server-DIJ0L_8t.js} +162 -162
- package/packages/server/dist/{server-http-Cj5g8ohL.js → server-http-Cda_MYnv.js} +1 -1
- package/packages/server/dist/{server-http-BLRFgvkK.js → server-http-o8cfhQys.js} +1 -1
- package/packages/server/dist/{server-stdio-BfNBdIL8.js → server-stdio-Bnw6B9K9.js} +1 -1
- package/packages/server/dist/{server-stdio-t2WEVq-g.js → server-stdio-CmfhInUV.js} +1 -1
- package/packages/server/dist/{workspace-bootstrap-DupGrGox.js → workspace-bootstrap-BJloolzr.js} +1 -1
package/package.json
CHANGED
|
@@ -149,6 +149,10 @@ declare class BrowserEngine {
|
|
|
149
149
|
* Returns stdout/stderr/exitCode.
|
|
150
150
|
*/
|
|
151
151
|
exec(command: string, ...args: string[]): Promise<AgentBrowserResult>;
|
|
152
|
+
/** Run a command via execFile (no shell). */
|
|
153
|
+
private execViaExecFile;
|
|
154
|
+
/** Run a command via exec() (goes through cmd.exe shell). */
|
|
155
|
+
private execViaShell;
|
|
152
156
|
/**
|
|
153
157
|
* Execute a command scoped to a specific tab.
|
|
154
158
|
* Prepends "tab <tabId>" to the command automatically.
|
|
@@ -162,7 +166,8 @@ declare class BrowserEngine {
|
|
|
162
166
|
/**
|
|
163
167
|
* Take a screenshot of the active tab and return the base64-encoded PNG.
|
|
164
168
|
* screenshot is a TOP-LEVEL command in agent-browser (not under `tab`).
|
|
165
|
-
*
|
|
169
|
+
* It captures whatever tab is currently active.
|
|
170
|
+
* exec() handles .cmd wrappers via shell on Windows automatically.
|
|
166
171
|
*/
|
|
167
172
|
screenshot(_tabId: string, options?: {
|
|
168
173
|
fullPage?: boolean;
|
|
@@ -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,...n){if(!this.binaryPath)throw Error(`agent-browser not launched. Call launch() first, or use getEngine() singleton.`);let r=this.binaryPath;u()===`win32`&&!r.endsWith(`.cmd`)&&!r.endsWith(`.bat`)&&!r.endsWith(`.exe`)&&i(`${r}.cmd`)&&(r=`${r}.cmd`);let a=[e,...n];return new Promise((e,n)=>{t(r,a,{timeout:this.config.evalTimeoutMs},(t,r,i)=>{if(t&&t.code===`ENOENT`){n(Error(`agent-browser binary not found at ${this.binaryPath}`));return}e({stdout:r??``,stderr:i??``,exitCode:t?.code?Number(t.code):0})}).stdin?.end()})}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(t,n){let r=n?.format??`png`,i=r===`jpeg`?`image/jpeg`:`image/png`,a=r===`jpeg`?`jpg`:`png`,c=f(d(),`aikit-screenshot-${Date.now()}.${a}`),l=this.binaryPath?`"${this.binaryPath}" screenshot "${c}"${n?.fullPage?` --full`:``}`:``;if(u()===`win32`&&l)await new Promise((t,n)=>{e(l,{timeout:this.config.evalTimeoutMs},e=>{e?n(e):t()}).stdin?.end()});else{let e=[c];n?.fullPage&&e.push(`--full`),n?.format===`jpeg`&&e.push(`--screenshot-format`,`jpeg`),n?.quality&&e.push(`--screenshot-quality`,String(n.quality)),await this.exec(`screenshot`,...e)}let p=o(c),m=p.toString(`base64`);try{s(c)}catch{}return this.resetIdleTimer(),{base64:m,mimeType:i,bytes:p.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){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 => {
|
|
2
2
|
const text = await r.text();
|
|
3
3
|
const headers = {};
|
|
4
4
|
r.headers.forEach((v, k) => { headers[k] = v; });
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{fileURLToPath as e,pathToFileURL as t}from"node:url";import{parseArgs as n}from"node:util";import{HealthBus as r,createLogger as i,serializeError as a}from"../../core/dist/index.js";import{readFileSync as o}from"node:fs";import{dirname as s,isAbsolute as c,join as l,resolve as u}from"node:path";import{createHash as d}from"node:crypto";import{GIT_REF_SLUG_PATTERN as f,gitAvailable as p,gitCommitToRef as m,gitExec as h,slugForRef as g}from"../../tools/dist/index.js";import{mkdir as _,readFile as v,readdir as y,stat as b,unlink as x,writeFile as S}from"node:fs/promises";function C(){try{let t=u(s(e(import.meta.url)),`..`,`..`,`..`,`package.json`);return JSON.parse(o(t,`utf-8`)).version??`0.0.0`}catch{return`0.0.0`}}function w(e){let t=e.headers[`mcp-session-id`];return Array.isArray(t)?t[0]:t}function T(e,t){let n=process.env[e];if(!n)return t;let r=Number.parseInt(n,10);return Number.isFinite(r)&&r>0?r:t}const E=/^https?:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/i;function D({requestOrigin:e,configuredOrigin:t,allowAnyOrigin:n,fallbackOrigin:r}){let i=t??r;return i===`*`?n?{allowOrigin:`*`,warn:!1}:e?E.test(e)?{allowOrigin:e,warn:!1}:{allowOrigin:null,warn:!0}:{allowOrigin:r,warn:!1}:{allowOrigin:i,warn:!1}}function O({limit:e,windowMs:t}){let n=new Map,r=(e,r)=>{let i=r-t,a=n.get(e)?.filter(e=>e>i)??[];return a.length===0?(n.delete(e),[]):(n.set(e,a),a)};return{allow(t,i=Date.now()){let a=r(t,i);return a.length>=e?!1:(a.push(i),n.set(t,a),!0)},getRetryAfterMs(n,i=Date.now()){let a=r(n,i);return a.length<e?0:Math.max(0,a[0]+t-i)}}}function k(t){return t.startsWith(`file://`)?e(t):t}function A(e){let t=u(e);return process.platform===`win32`?t.toLowerCase():t}function j(e){let t=new Map;for(let n of e){let e=k(n.uri);t.set(A(e),e)}return[...t.values()].sort((e,t)=>A(e).localeCompare(A(t)))}function M({config:e,roots:t}){let n=j(t);if(n.length===0)return null;let r=e.sources?.[0]?.path;if(r){let e=A(r),t=n.find(t=>A(t)===e);if(t)return t}return n[0]}function N({config:e,log:t,reconfigureForWorkspace:n,roots:r}){let i=j(r);if(i.length===0)return!1;let a=M({config:e,roots:i.map(e=>({uri:e}))});if(!a)return!1;let o=e.sources?.[0]?.path;return t.debug(`MCP roots resolved`,{rootPath:a,rootCount:i.length,selectedBy:o&&A(o)===A(a)?`configured-source`:`stable-sorted-root`}),n(e,a),e.allRoots=i,!0}async function P({config:e,indexMode:t,log:n,rootsChangedNotificationSchema:r,reconfigureForWorkspace:i,runInitialIndex:o,server:s,startInit:c,timeoutMs:l=5e3,getCwd:u=()=>process.env.AIKIT_WORKSPACE_ROOT??process.cwd(),version:d=`0.0.0`}){let f=!1,p=!1,m,h=s.server,g=e=>{let t=a(e),n=`${String(e)} ${String(t.message??``)}`.toLowerCase();return n.includes(`method not found`)||n.includes(`not supported`)||n.includes(`unsupported`)||n.includes(`unknown method`)||n.includes(`roots/list`)||n.includes(`timed out`)},_=()=>{f||(f=!0,c())},v=()=>{p||t!==`auto`||(p=!0,(async()=>{try{await o()}catch(e){n.error(`Initial index failed`,{version:d,...a(e)})}})())},y=t=>t.length===0||(m&&=(clearTimeout(m),void 0),!N({config:e,log:n,reconfigureForWorkspace:i,roots:t}))?!1:(_(),v(),!0);try{if(y((await h.listRoots()).roots))return;n.debug(`No MCP roots yet; waiting for roots/list_changed notification`)}catch(t){if(g(t)){n.warn(`MCP roots/list not supported by client; using cwd fallback`,{version:d,cwd:u(),...a(t)}),N({config:e,log:n,reconfigureForWorkspace:i,roots:[{uri:u()}]})&&(_(),v());return}n.warn(`MCP roots/list failed; waiting for roots/list_changed notification`,{version:d,cwd:u(),...a(t)})}h.setNotificationHandler(r,async()=>{try{y((await h.listRoots()).roots)}catch(e){n.warn(`roots/list retry failed after notification`,{version:d,...a(e)})}}),m=setTimeout(()=>{let t=u();n.debug(`Timed out waiting for roots/list_changed; falling back to cwd workspace`,{cwd:t}),N({config:e,log:n,reconfigureForWorkspace:i,roots:[{uri:t}]})&&(_(),v())},l)}var F=class{baseDir;constructor(e){this.baseDir=e}async initialize(){await _(this.baseDir,{recursive:!0})}async read(e){let t=l(this.baseDir,e);try{return await v(t,`utf-8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}async write(e,t,n){let r=l(this.baseDir,e);await _(s(r),{recursive:!0}),await S(r,t,{encoding:`utf-8`,flag:n?.exclusive?`wx`:`w`})}async delete(e){let t=l(this.baseDir,e);try{return await x(t),!0}catch(e){if(e.code===`ENOENT`)return!1;throw e}}async list(e){let t=[],n=e?[e]:await this.listDirectories();for(let e of n){let n=l(this.baseDir,e),r;try{r=await y(n)}catch{continue}for(let n of r){if(!n.endsWith(`.md`))continue;let r=`${e}/${n}`,i=l(this.baseDir,r);try{let e=await b(i);t.push({path:r,size:e.size,mtimeMs:e.mtimeMs})}catch{}}}return t}async exists(e){let t=l(this.baseDir,e);try{return await b(t),!0}catch{return!1}}async listDirectories(){try{return(await y(this.baseDir,{withFileTypes:!0})).filter(e=>e.isDirectory()&&/^[a-z][a-z0-9-]*$/.test(e.name)).map(e=>e.name)}catch{return[]}}async close(){}};const I=50*1024,L=`refs/aikit/knowledge`,R=i(`server`);var z=class{curatedDir;store;embedder;adapter;constructor(e,t,n,r=new F(e)){this.curatedDir=e,this.store=t,this.embedder=n,this.adapter=r}async remember(e,t,n,r=[]){this.validateCategoryName(n),this.validateContentSize(t);let i=this.normalizeTags(r),a=this.slugify(e),o=await this.uniqueRelativePath(n,a),s=new Date().toISOString(),c={title:e,category:n,tags:i,created:s,updated:s,version:1,origin:`curated`,changelog:[{version:1,date:s,reason:`Initial creation`}]},l=this.serializeFile(t,c);try{await this.adapter.write(o,l,{exclusive:!0})}catch(e){throw e.code===`EEXIST`?Error(`Concurrent write collision for "${o}" — retry the operation`):e}return this.gitCommitKnowledge(o,l,`remember: ${e}\n\nCategory: ${n}\nTags: ${i.join(`, `)}`),await this.indexCuratedFileBestEffort(o,t,c,`remember`),{path:o}}async upsertAutoKnowledge(e,t,n,r,i=[],a=`Auto-knowledge refresh`){e=this.guardPath(e),this.validateCategoryName(r),this.validateContentSize(n),this.ensureCategoryPath(e,r);let o=this.normalizeTags(i),s=await this.adapter.read(e);if(s==null){let i=new Date().toISOString(),a={title:t,category:r,tags:o,created:i,updated:i,version:1,origin:`curated`,changelog:[{version:1,date:i,reason:`Initial creation`}]},s=this.serializeFile(n,a);try{await this.adapter.write(e,s,{exclusive:!0})}catch(t){throw t.code===`EEXIST`?Error(`Concurrent write collision for "${e}" — retry the operation`):t}return this.gitCommitKnowledge(e,s,`remember: ${t}\n\nCategory: ${r}\nTags: ${o.join(`, `)}`),await this.indexCuratedFileBestEffort(e,n,a,`remember`),{path:e,status:`created`,version:1}}let{frontmatter:c,content:l}=this.parseFile(s),u=this.normalizeTags(c.tags??[]),d=t.trim()||c.title;if(l===n&&c.category===r&&c.title===d&&this.sameTags(u,o))return{path:e,status:`unchanged`,version:c.version??1};let f=(c.version??1)+1,p=new Date().toISOString();c.title=d,c.category=r,c.tags=o,c.version=f,c.updated=p,c.changelog=[...c.changelog??[],{version:f,date:p,reason:a}];let m=this.serializeFile(n,c);return await this.adapter.write(e,m),this.gitCommitKnowledge(e,m,`update(v${f}): ${c.title}\n\nReason: ${a}\nVersion: ${f}`),await this.indexCuratedFileBestEffort(e,n,c,`update`),{path:e,status:`updated`,version:f}}async update(e,t,n){e=this.guardPath(e),this.validateContentSize(t);let r=await this.adapter.read(e);if(r==null)throw Error(`Curated entry not found: ${e}`);let{frontmatter:i}=this.parseFile(r),a=(i.version??1)+1,o=new Date().toISOString();i.version=a,i.updated=o,i.changelog=[...i.changelog??[],{version:a,date:o,reason:n}];let s=this.serializeFile(t,i);return await this.adapter.write(e,s),this.gitCommitKnowledge(e,s,`update(v${a}): ${i.title}\n\nReason: ${n}\nVersion: ${a}`),await this.indexCuratedFileBestEffort(e,t,i,`update`),{path:e,version:a}}async forget(e,t){if(e=this.guardPath(e),!await this.adapter.delete(e))throw Error(`Curated entry not found: ${e}`);let n=`.ai/curated/${e}`;return await this.store.deleteBySourcePath(n).catch(e=>{R.warn(`File deleted but vector cleanup failed`,{sourcePath:n,...a(e)})}),this.gitDeleteKnowledgeRef(e),{path:e}}async history(e,t=20){if(e=this.guardPath(e),!p(this.curatedDir))return[];let n=this.knowledgeRefForPath(e);if(!n)return[];let r=h([`log`,`--format=%H|%aI|%s`,n,`-n`,String(t)],this.curatedDir);return r?r.split(`
|
|
2
|
+
import{fileURLToPath as e,pathToFileURL as t}from"node:url";import{parseArgs as n}from"node:util";import{HealthBus as r,createLogger as i,serializeError as a}from"../../core/dist/index.js";import{readFileSync as o}from"node:fs";import{dirname as s,isAbsolute as c,join as l,resolve as u}from"node:path";import{createHash as d}from"node:crypto";import{GIT_REF_SLUG_PATTERN as f,gitAvailable as p,gitCommitToRef as m,gitExec as h,slugForRef as g}from"../../tools/dist/index.js";import{mkdir as _,readFile as v,readdir as y,stat as b,unlink as x,writeFile as S}from"node:fs/promises";function C(){try{let t=u(s(e(import.meta.url)),`..`,`..`,`..`,`package.json`);return JSON.parse(o(t,`utf-8`)).version??`0.0.0`}catch{return`0.0.0`}}function w(e){let t=e.headers[`mcp-session-id`];return Array.isArray(t)?t[0]:t}function T(e,t){let n=process.env[e];if(!n)return t;let r=Number.parseInt(n,10);return Number.isFinite(r)&&r>0?r:t}const E=/^https?:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/i;function D({requestOrigin:e,configuredOrigin:t,allowAnyOrigin:n,fallbackOrigin:r}){let i=t??r;return i===`*`?n?{allowOrigin:`*`,warn:!1}:e?E.test(e)?{allowOrigin:e,warn:!1}:{allowOrigin:null,warn:!0}:{allowOrigin:r,warn:!1}:{allowOrigin:i,warn:!1}}function O({limit:e,windowMs:t}){let n=new Map,r=(e,r)=>{let i=r-t,a=n.get(e)?.filter(e=>e>i)??[];return a.length===0?(n.delete(e),[]):(n.set(e,a),a)};return{allow(t,i=Date.now()){let a=r(t,i);return a.length>=e?!1:(a.push(i),n.set(t,a),!0)},getRetryAfterMs(n,i=Date.now()){let a=r(n,i);return a.length<e?0:Math.max(0,a[0]+t-i)}}}function k(t){return t.startsWith(`file://`)?e(t):t}function A(e){let t=u(e);return process.platform===`win32`?t.toLowerCase():t}function j(e){let t=new Map;for(let n of e){let e=k(n.uri);t.set(A(e),e)}return[...t.values()].sort((e,t)=>A(e).localeCompare(A(t)))}function M({config:e,roots:t}){let n=j(t);if(n.length===0)return null;let r=e.sources?.[0]?.path;if(r){let e=A(r),t=n.find(t=>A(t)===e);if(t)return t}return n[0]}function N({config:e,log:t,reconfigureForWorkspace:n,roots:r}){let i=j(r);if(i.length===0)return!1;let a=M({config:e,roots:i.map(e=>({uri:e}))});if(!a)return!1;let o=e.sources?.[0]?.path;return t.debug(`MCP roots resolved`,{rootPath:a,rootCount:i.length,selectedBy:o&&A(o)===A(a)?`configured-source`:`stable-sorted-root`}),n(e,a),e.allRoots=i,!0}async function P({config:e,indexMode:t,log:n,rootsChangedNotificationSchema:r,reconfigureForWorkspace:i,runInitialIndex:o,server:s,startInit:c,timeoutMs:l=5e3,getCwd:u=()=>process.env.AIKIT_WORKSPACE_ROOT??process.cwd(),version:d=`0.0.0`}){let f=!1,p=!1,m,h=s.server,g=e=>{let t=a(e),n=`${String(e)} ${String(t.message??``)}`.toLowerCase();return n.includes(`method not found`)||n.includes(`not supported`)||n.includes(`unsupported`)||n.includes(`unknown method`)||n.includes(`roots/list`)||n.includes(`timed out`)},_=()=>{f||(f=!0,c())},v=()=>{p||t!==`auto`||(p=!0,(async()=>{try{await o()}catch(e){n.error(`Initial index failed`,{version:d,...a(e)})}})())},y=t=>t.length===0||(m&&=(clearTimeout(m),void 0),!N({config:e,log:n,reconfigureForWorkspace:i,roots:t}))?!1:(_(),v(),!0);try{if(y((await h.listRoots()).roots))return;n.debug(`No MCP roots yet; waiting for roots/list_changed notification`)}catch(t){if(g(t)){let r=e.sources?.[0]?.path;r?(n.debug(`MCP roots/list not supported; using configured source path`,{version:d,configuredRoot:r,cwd:u(),...a(t)}),_(),v()):(n.warn(`MCP roots/list not supported by client; using cwd fallback`,{version:d,cwd:u(),...a(t)}),N({config:e,log:n,reconfigureForWorkspace:i,roots:[{uri:u()}]})&&(_(),v()));return}n.warn(`MCP roots/list failed; waiting for roots/list_changed notification`,{version:d,cwd:u(),...a(t)})}h.setNotificationHandler(r,async()=>{try{y((await h.listRoots()).roots)}catch(e){n.warn(`roots/list retry failed after notification`,{version:d,...a(e)})}}),m=setTimeout(()=>{let t=e.sources?.[0]?.path;if(t)n.debug(`Timed out waiting for roots/list_changed; using configured source path`,{configuredRoot:t}),_(),v();else{let t=u();n.debug(`Timed out waiting for roots/list_changed; falling back to cwd workspace`,{cwd:t}),N({config:e,log:n,reconfigureForWorkspace:i,roots:[{uri:t}]})&&(_(),v())}},l)}var F=class{baseDir;constructor(e){this.baseDir=e}async initialize(){await _(this.baseDir,{recursive:!0})}async read(e){let t=l(this.baseDir,e);try{return await v(t,`utf-8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}async write(e,t,n){let r=l(this.baseDir,e);await _(s(r),{recursive:!0}),await S(r,t,{encoding:`utf-8`,flag:n?.exclusive?`wx`:`w`})}async delete(e){let t=l(this.baseDir,e);try{return await x(t),!0}catch(e){if(e.code===`ENOENT`)return!1;throw e}}async list(e){let t=[],n=e?[e]:await this.listDirectories();for(let e of n){let n=l(this.baseDir,e),r;try{r=await y(n)}catch{continue}for(let n of r){if(!n.endsWith(`.md`))continue;let r=`${e}/${n}`,i=l(this.baseDir,r);try{let e=await b(i);t.push({path:r,size:e.size,mtimeMs:e.mtimeMs})}catch{}}}return t}async exists(e){let t=l(this.baseDir,e);try{return await b(t),!0}catch{return!1}}async listDirectories(){try{return(await y(this.baseDir,{withFileTypes:!0})).filter(e=>e.isDirectory()&&/^[a-z][a-z0-9-]*$/.test(e.name)).map(e=>e.name)}catch{return[]}}async close(){}};const I=50*1024,L=`refs/aikit/knowledge`,R=i(`server`);var z=class{curatedDir;store;embedder;adapter;constructor(e,t,n,r=new F(e)){this.curatedDir=e,this.store=t,this.embedder=n,this.adapter=r}async remember(e,t,n,r=[]){this.validateCategoryName(n),this.validateContentSize(t);let i=this.normalizeTags(r),a=this.slugify(e),o=await this.uniqueRelativePath(n,a),s=new Date().toISOString(),c={title:e,category:n,tags:i,created:s,updated:s,version:1,origin:`curated`,changelog:[{version:1,date:s,reason:`Initial creation`}]},l=this.serializeFile(t,c);try{await this.adapter.write(o,l,{exclusive:!0})}catch(e){throw e.code===`EEXIST`?Error(`Concurrent write collision for "${o}" — retry the operation`):e}return this.gitCommitKnowledge(o,l,`remember: ${e}\n\nCategory: ${n}\nTags: ${i.join(`, `)}`),await this.indexCuratedFileBestEffort(o,t,c,`remember`),{path:o}}async upsertAutoKnowledge(e,t,n,r,i=[],a=`Auto-knowledge refresh`){e=this.guardPath(e),this.validateCategoryName(r),this.validateContentSize(n),this.ensureCategoryPath(e,r);let o=this.normalizeTags(i),s=await this.adapter.read(e);if(s==null){let i=new Date().toISOString(),a={title:t,category:r,tags:o,created:i,updated:i,version:1,origin:`curated`,changelog:[{version:1,date:i,reason:`Initial creation`}]},s=this.serializeFile(n,a);try{await this.adapter.write(e,s,{exclusive:!0})}catch(t){throw t.code===`EEXIST`?Error(`Concurrent write collision for "${e}" — retry the operation`):t}return this.gitCommitKnowledge(e,s,`remember: ${t}\n\nCategory: ${r}\nTags: ${o.join(`, `)}`),await this.indexCuratedFileBestEffort(e,n,a,`remember`),{path:e,status:`created`,version:1}}let{frontmatter:c,content:l}=this.parseFile(s),u=this.normalizeTags(c.tags??[]),d=t.trim()||c.title;if(l===n&&c.category===r&&c.title===d&&this.sameTags(u,o))return{path:e,status:`unchanged`,version:c.version??1};let f=(c.version??1)+1,p=new Date().toISOString();c.title=d,c.category=r,c.tags=o,c.version=f,c.updated=p,c.changelog=[...c.changelog??[],{version:f,date:p,reason:a}];let m=this.serializeFile(n,c);return await this.adapter.write(e,m),this.gitCommitKnowledge(e,m,`update(v${f}): ${c.title}\n\nReason: ${a}\nVersion: ${f}`),await this.indexCuratedFileBestEffort(e,n,c,`update`),{path:e,status:`updated`,version:f}}async update(e,t,n){e=this.guardPath(e),this.validateContentSize(t);let r=await this.adapter.read(e);if(r==null)throw Error(`Curated entry not found: ${e}`);let{frontmatter:i}=this.parseFile(r),a=(i.version??1)+1,o=new Date().toISOString();i.version=a,i.updated=o,i.changelog=[...i.changelog??[],{version:a,date:o,reason:n}];let s=this.serializeFile(t,i);return await this.adapter.write(e,s),this.gitCommitKnowledge(e,s,`update(v${a}): ${i.title}\n\nReason: ${n}\nVersion: ${a}`),await this.indexCuratedFileBestEffort(e,t,i,`update`),{path:e,version:a}}async forget(e,t){if(e=this.guardPath(e),!await this.adapter.delete(e))throw Error(`Curated entry not found: ${e}`);let n=`.ai/curated/${e}`;return await this.store.deleteBySourcePath(n).catch(e=>{R.warn(`File deleted but vector cleanup failed`,{sourcePath:n,...a(e)})}),this.gitDeleteKnowledgeRef(e),{path:e}}async history(e,t=20){if(e=this.guardPath(e),!p(this.curatedDir))return[];let n=this.knowledgeRefForPath(e);if(!n)return[];let r=h([`log`,`--format=%H|%aI|%s`,n,`-n`,String(t)],this.curatedDir);return r?r.split(`
|
|
3
3
|
`).filter(Boolean).map(e=>{let[t,n,...r]=e.split(`|`);return{sha:t,date:n,message:r.join(`|`)}}):[]}async diff(e,t,n){if(e=this.guardPath(e),!p(this.curatedDir))return``;if(!n){let r=await this.history(e,2);if(r.length===0)return``;n=r[0].sha,r.length>1&&!t&&(t=r[1].sha)}return t&&n?h([`diff`,`${t}:entry.md`,`${n}:entry.md`],this.curatedDir)??``:n?h([`show`,`${n}:entry.md`],this.curatedDir)??``:``}async recover(e){if(e=this.guardPath(e),await this.adapter.exists(e))throw Error(`Entry already exists on filesystem: ${e}. Use update() instead.`);if(!p(this.curatedDir))return null;let t=this.knowledgeRefForPath(e);if(!t)return null;let n=h([`show`,`${t}:entry.md`],this.curatedDir);if(!n)return null;await this.adapter.write(e,n);let{frontmatter:r,content:i}=this.parseFile(n);return await this.indexCuratedFile(e,i,r),{path:e,version:r.version??1}}async listOrphaned(){if(!p(this.curatedDir))return[];let e=h([`for-each-ref`,`--format=%(refname)|%(subject)`,`${L}/`],this.curatedDir);if(!e)return[];let t=[];for(let n of e.split(`
|
|
4
4
|
`).filter(Boolean)){let[e,...r]=n.split(`|`),i=r.join(`|`),a=`${e.replace(`${L}/`,``)}.md`;await this.adapter.exists(a)||t.push({ref:e,path:a,lastMessage:i})}return t}async read(e){e=this.guardPath(e);let t=await this.adapter.read(e);if(t==null)throw Error(`Curated entry not found: ${e}`);let{frontmatter:n,content:r}=this.parseFile(t),i=e.split(`/`)[0];return{path:e,title:n.title??e,category:i,tags:n.tags??[],version:n.version??1,created:n.created??``,updated:n.updated??``,contentPreview:r.slice(0,200),content:r}}async list(e){return(await this.listPage(e)).entries}async listPage(e){let t=e?.category?[e.category]:await this.discoverCategories(),n=[];for(let e of t){let t=await this.adapter.list(e);for(let r of t)n.push({path:r.path,category:e,mtimeMs:r.mtimeMs??0})}let r=Math.max(0,e?.offset??0),i=e?.limit==null?null:Math.max(1,e.limit),a=(e?.order??`asc`)===`desc`?-1:1,o=e?.orderBy??`path`;if(o===`path`||o===`updated`){let t=this.sortCandidateMetadata(n,o,a);if(e?.tag){let n=i==null?void 0:r+i+1,{entries:a,scannedAll:o}=await this.readCandidateEntries(t,{tag:e.tag,maxMatches:n}),s=i==null?a.slice(r):a.slice(r,r+i),c=i!=null&&(a.length>r+s.length||!o);return{entries:s,totalCount:o?a.length:r+s.length+ +!!c,totalCountIsExact:o,limit:i,offset:r,hasMore:c}}let s=i==null?t.slice(r):t.slice(r,r+i),{entries:c}=await this.readCandidateEntries(s);return{entries:c,totalCount:t.length,totalCountIsExact:!0,limit:i,offset:r,hasMore:i!=null&&r+c.length<t.length}}let{entries:s}=await this.readCandidateEntries(n,{tag:e?.tag}),c=s.sort((e,t)=>{switch(o){case`created`:return(Date.parse(e.created)-Date.parse(t.created))*a;case`updated`:return(Date.parse(e.updated)-Date.parse(t.updated))*a;case`path`:return e.path.localeCompare(t.path)*a;default:return 0}}),l=i==null?c.slice(r):c.slice(r,r+i);return{entries:l,totalCount:c.length,totalCountIsExact:!0,limit:i,offset:r,hasMore:i!=null&&r+l.length<c.length}}async count(e){if(e?.tag)return(await this.listPage({...e,limit:void 0})).totalCount;let t=e?.category?[e.category]:await this.discoverCategories(),n=0;for(let e of t)n+=(await this.adapter.list(e)).length;return n}async listPaths(e){let t=e?.category?[e.category]:await this.discoverCategories(),n=[];for(let e of t){let t=await this.adapter.list(e);n.push(...t.map(e=>e.path))}n.sort((e,t)=>e.localeCompare(t));let r=Math.max(0,e?.offset??0),i=e?.limit==null?null:Math.max(1,e.limit);return i==null?n.slice(r):n.slice(r,r+i)}sortCandidateMetadata(e,t,n){return[...e].sort((e,r)=>t===`updated`?(e.mtimeMs-r.mtimeMs)*n:e.path.localeCompare(r.path)*n)}async readCandidateEntries(e,t){let n=[];for(let r of e){let e=await this.adapter.read(r.path);if(e==null)continue;let{frontmatter:i,content:a}=this.parseFile(e),o=i.tags??[];if(!(t?.tag&&!o.includes(t.tag))&&(n.push({path:r.path,title:i.title??r.path,category:r.category,tags:o,version:i.version??1,created:i.created??``,updated:i.updated??``,contentPreview:a.slice(0,200)}),t?.maxMatches!=null&&n.length>=t.maxMatches))return{entries:n,scannedAll:!1}}return{entries:n,scannedAll:!0}}async reindexAll(){let e=await this.discoverCategories(),t=[],n=[];for(let r of e){let e=await this.adapter.list(r);for(let r of e){let e=r.path;try{let r=await this.adapter.read(e);if(r==null){t.push(`${e}: read failed`);continue}let{frontmatter:i,content:a}=this.parseFile(r);n.push({relativePath:e,content:a,frontmatter:i})}catch(n){R.error(`Failed to read curated file`,{relativePath:e,...a(n)}),t.push(`${e}: read failed`)}}}if(n.length===0)return{indexed:0,errors:t};let r=new Date().toISOString(),i=0;for(let e=0;e<n.length;e+=16){let a=n.slice(e,e+16);i+=await this.embedAndUpsertBatch(a,r,t)}return{indexed:i,errors:t}}async embedAndUpsertBatch(e,t,n){try{let r=await this.embedder.embedBatch(e.map(e=>e.content)),i=e.map(e=>{let n=`.ai/curated/${e.relativePath}`;return{id:this.hashId(n,0),content:e.content,sourcePath:n,contentType:`curated-knowledge`,headingPath:e.frontmatter.title,chunkIndex:0,totalChunks:1,startLine:1,endLine:e.content.split(`
|
|
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-o8cfhQys.js`);await n(e,t.port)}else{let{startStdioMode:t}=await import(`./server-stdio-CmfhInUV.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};
|
|
@@ -54,9 +54,7 @@ type WorkspaceRootApplyDeps<Config extends WorkspaceRootConfig> = {
|
|
|
54
54
|
uri: string;
|
|
55
55
|
}>;
|
|
56
56
|
};
|
|
57
|
-
type WorkspaceRootBootstrapDeps<Config extends {
|
|
58
|
-
allRoots?: string[];
|
|
59
|
-
}> = {
|
|
57
|
+
type WorkspaceRootBootstrapDeps<Config extends WorkspaceRootConfig> = {
|
|
60
58
|
config: Config;
|
|
61
59
|
indexMode: string;
|
|
62
60
|
log: WorkspaceLogger;
|
|
@@ -81,9 +79,7 @@ declare function applyWorkspaceRoots<Config extends WorkspaceRootConfig>({
|
|
|
81
79
|
reconfigureForWorkspace,
|
|
82
80
|
roots
|
|
83
81
|
}: WorkspaceRootApplyDeps<Config>): boolean;
|
|
84
|
-
declare function bootstrapWorkspaceRoots<Config extends {
|
|
85
|
-
allRoots?: string[];
|
|
86
|
-
}>({
|
|
82
|
+
declare function bootstrapWorkspaceRoots<Config extends WorkspaceRootConfig>({
|
|
87
83
|
config,
|
|
88
84
|
indexMode,
|
|
89
85
|
log,
|
|
@@ -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-
|
|
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-Cda_MYnv.js`);await t(e,n.port)}else{let{startStdioMode:t}=await import(`./server-stdio-Bnw6B9K9.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};
|