@vpxa/aikit 0.1.144 → 0.1.146
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 +11 -4
- package/packages/cli/dist/index.js +3 -3
- package/packages/cli/dist/{init-CeRqVSQt.js → init-BBmNDjFy.js} +1 -1
- package/packages/cli/dist/{templates-Uuiq1jc_.js → templates-BXyPFub1.js} +9 -4
- package/packages/cli/dist/{user-B6_6Sk9I.js → user-ZDsx66gQ.js} +1 -1
- package/packages/server/dist/index.js +1 -1
- package/packages/server/dist/{server-Mioq3dZQ.js → server-3YlZan29.js} +164 -164
- package/packages/store/dist/index.js +2 -2
- package/packages/store/dist/{sqlite-vec-store-C-GvCcJH.js → sqlite-vec-store-CrvQ06f8.js} +6 -6
- package/scaffold/dist/adapters/claude-code.mjs +10 -6
- package/scaffold/dist/definitions/bodies.mjs +12 -0
- package/scaffold/dist/definitions/flows.mjs +114 -3
- package/scaffold/dist/definitions/hooks.mjs +1 -1
- package/scaffold/dist/definitions/skills/aikit.mjs +1 -1
- package/scaffold/dist/definitions/skills/browser-use.mjs +661 -16
- package/scaffold/dist/definitions/skills/requirements-clarity.mjs +81 -297
- package/scaffold/dist/definitions/skills/session-handoff.mjs +258 -64
- package/scaffold/dist/definitions/tools.mjs +1 -1
package/package.json
CHANGED
|
@@ -1,10 +1,17 @@
|
|
|
1
|
-
import{createRequire as e}from"node:module";import{createHash as t,randomUUID as n}from"node:crypto";import{homedir as r}from"node:os";import{join as i}from"node:path";import{execFileSync as a}from"node:child_process";import{existsSync as o,readdirSync as s}from"node:fs";import{Buffer as c}from"node:buffer";import{z as l}from"zod";const u=e(import.meta.url);function d(e){return typeof e==`string`?e.trim():e instanceof Buffer?e.toString(`utf8`).trim():``}function f(e){process.env.PLAYWRIGHT_BROWSERS_PATH=e}async function p(e){f(e);let{chromium:t}=await import(`playwright-core`),n=t.executablePath();if(!n)throw Error(`Chromium executable not found in ${e}`);return n}function m(){return i(r(),`.aikit`,`browsers`)}function h(e){return e.browsersPath??process.env.PLAYWRIGHT_BROWSERS_PATH??m()}function g(e){return o(e)?s(e,{withFileTypes:!0}).some(e=>e.isDirectory()&&e.name.toLowerCase().startsWith(`chromium-`)):!1}async function _(e,t){let n=h(e);if(f(n),t?.(`Using Chromium cache at ${n}`),g(n))return t?.(`Chromium already installed`),p(n);let r=i(u.resolve(`playwright-core`),`..`,`cli.js`);t?.(`Installing Chromium via playwright-core`);try{a(process.execPath,[r,`install`,`chromium`],{env:{...process.env,PLAYWRIGHT_BROWSERS_PATH:n},encoding:`utf8`,stdio:`pipe`})}catch(e){let t=e,n=d(t.stderr),r=d(t.stdout),i=n||r||t.message||`Unknown playwright install failure`;throw Error(`Failed to install Chromium: ${i}`)}return t?.(`Chromium install complete`),p(n)}function v(){return process.platform===`win32`||process.platform===`darwin`?!0:!!(process.env.DISPLAY||process.env.WAYLAND_DISPLAY)}function y(e){return e===`headless`||!v()?`headless`:e}function b(e){switch(e){case`headless`:return{headless:!0,args:[]};case`panel`:return{headless:!1,args:[`--app=data:text/html,<title>aikit</title>`]};default:return{headless:!1,args:[]}}}var x=class{pages=new Map;registerPage(e,t,r){let i=n();return this.pages.set(i,{page:e,url:t,title:r,createdAt:new Date}),i}getPage(e){let t=this.pages.get(e);if(!t)throw Error(`Page not found: ${e}`);return t.page}getPageInfo(e){let t=this.pages.get(e);if(!t)throw Error(`Page not found: ${e}`);return{pageId:e,url:t.url,title:t.title,createdAt:t.createdAt}}updatePageInfo(e,t,n){let r=this.pages.get(e);if(!r)throw Error(`Page not found: ${e}`);this.pages.set(e,{...r,url:t,title:n})}async removePage(e){let t=this.pages.get(e);t&&(await t.page.close(),this.pages.delete(e))}listPages(){return[...this.pages.entries()].map(([e,t])=>({pageId:e,url:t.url,title:t.title,createdAt:t.createdAt}))}async closeAll(){await Promise.allSettled([...this.pages.keys()].map(async e=>this.removePage(e)))}get size(){return this.pages.size}};const S={defaultMode:`ui`,browsersPath:null,userDataDirRoot:null,idleShutdownMinutes:10,allowInternalSchemes:!1,evalTimeoutMs:1e4,evalMaxResultBytes:262144,redactPasswordFieldsInScreenshots:!0};var C=class{browser=null;context=null;idleTimer=null;launchPromise=null;session=new x;config;constructor(e={}){this.config={...S,...e}}async launch(e,t){if(!this.context){if(this.launchPromise)return this.launchPromise;this.launchPromise=this.doLaunch(e,t);try{await this.launchPromise}finally{this.launchPromise=null}}}async doLaunch(e,n){if(this.browser&&this.context)return;let a=y(e??this.config.defaultMode),o=h(this.config);process.env.PLAYWRIGHT_BROWSERS_PATH=o;let{chromium:s}=await import(`playwright-core`),c=await _(this.config,n),l=b(a),u=t(`sha256`).update(process.cwd()).digest(`hex`).slice(0,12),d=i(this.config.userDataDirRoot??i(r(),`.aikit`,`profiles`),u);if(n?.(`Launching Chromium in ${a} mode`),this.context=await s.launchPersistentContext(d,{headless:l.headless,args:l.args,executablePath:c}),this.browser=this.context.browser(),!this.browser)throw await this.context.close(),this.context=null,Error(`Failed to acquire Chromium browser instance`);this.browser.on(`disconnected`,()=>{this.browser=null,this.context=null,this.session.closeAll().catch(()=>{}),this.stopIdleTimer()}),this.resetIdleTimer()}stopIdleTimer(){this.idleTimer&&=(clearTimeout(this.idleTimer),null)}resetIdleTimer(){this.stopIdleTimer();let e=setTimeout(()=>{this.close()},this.config.idleShutdownMinutes*6e4);e.unref?.(),this.idleTimer=e}async close(){this.stopIdleTimer(),this.launchPromise=null;let e=this.context,t=this.browser;this.context=null,this.browser=null;let n;try{await this.session.closeAll()}catch(e){n=e}try{e&&await e.close()}catch(e){n??=e}finally{try{t&&await t.close()}catch(e){n??=e}}if(n)throw n}getContext(){if(!this.context)throw Error(`Browser not launched. Call launch() first.`);return this.context}getConfig(){return this.config}isLaunched(){return this.browser!==null}};let w=null;function T(e){return w||=new C(e),w}async function ee(){w&&=(await w.close(),null)}const te=[`file:`,`chrome:`,`chrome-extension:`,`data:`,`javascript:`],ne=[`169.254.169.254`,`metadata.google.internal`,`metadata.google.com`],E=[`localhost`,`127.0.0.1`,`::1`,`[::1]`];function re(e){return e.replace(/^\[(.*)\]$/,`$1`).toLowerCase()}function ie(e){let t=new WeakSet,n=JSON.stringify(e,(e,n)=>{if(typeof n==`bigint`)return n.toString();if(typeof n==`function`)return`[Function ${n.name||`anonymous`}]`;if(typeof n==`symbol`)return n.toString();if(n instanceof Error)return{name:n.name,message:n.message,stack:n.stack};if(typeof n==`object`&&n){if(t.has(n))return`[Circular]`;t.add(n)}return n});return n===void 0?e===void 0?`undefined`:String(e):n}function ae(e,t){let n=c.from(e,`utf8`);return n.byteLength<=t?e:n.subarray(0,t).toString(`utf8`)}function D(e,t){let n;try{n=new URL(e)}catch{return{allowed:!1,reason:`Invalid URL: ${e}`}}let r=n.protocol.toLowerCase();if(te.includes(r)&&!t.allowInternalSchemes)return{allowed:!1,reason:`Blocked URL scheme: ${r}`};let i=re(n.hostname);return ne.includes(i)?{allowed:!1,reason:`Blocked host: ${n.hostname}`}:(E.includes(i)||E.includes(n.hostname),{allowed:!0})}function O(e){return e?{allowed:!0}:{allowed:!1,reason:`Cookie access requires explicit confirmation (confirm: true)`}}function k(e,t){if(t<=0)return{valid:!1,reason:`maxBytes must be greater than 0`};try{let n=ie(e);return c.byteLength(n,`utf8`)<=t?{valid:!0,result:n,truncated:!1}:{valid:!0,result:`${ae(n,Math.max(t-3,0))}...`,truncated:!0,reason:`Result exceeded ${t} bytes and was truncated`}}catch(e){return{valid:!1,reason:`Unable to serialize eval result: ${e instanceof Error?e.message:String(e)}`}}}function oe(e){return e.replace(/<input\b[^>]*>/gi,e=>/\btype\s*=\s*(["'])password\1/i.test(e)?/\bvalue\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+)/i.test(e)?e.replace(/\bvalue\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+)/i,`value="***"`):e.replace(/\s*\/?>$/,e=>` value="***"${e}`):e)}const se=[`ui`,`headless`,`panel`];function ce(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`&&se.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 le(e){let t=ce(e.browser)??{};return{...S,defaultMode:N(process.env.AIKIT_BROWSER_DEFAULT_MODE)??N(t.defaultMode)??S.defaultMode,browsersPath:A(process.env.AIKIT_BROWSER_PATH)??A(process.env.AIKIT_BROWSER_BROWSERS_PATH)??A(t.browsersPath)??S.browsersPath,userDataDirRoot:A(t.userDataDirRoot)??S.userDataDirRoot,idleShutdownMinutes:P(`AIKIT_BROWSER_IDLE_MINUTES`)??M(t.idleShutdownMinutes)??S.idleShutdownMinutes,allowInternalSchemes:j(t.allowInternalSchemes)??S.allowInternalSchemes,evalTimeoutMs:P(`AIKIT_BROWSER_EVAL_TIMEOUT_MS`)??M(t.evalTimeoutMs)??S.evalTimeoutMs,evalMaxResultBytes:M(t.evalMaxResultBytes)??S.evalMaxResultBytes,redactPasswordFieldsInScreenshots:j(t.redactPasswordFieldsInScreenshots)??S.redactPasswordFieldsInScreenshots}}function F(e,t){return{content:[{type:`text`,text:e}],structuredContent:t}}function I(e,t){let n=e.selector??e.ref;if(!n)throw Error(`${t} requires selector or ref`);return n}function ue(e){if(!e)return`empty snapshot`;let t=[],n=(e,r)=>{let i=[e.role??`node`];e.name&&i.push(e.name),e.value!==void 0&&i.push(`value=${String(e.value)}`),e.description&&i.push(`description=${e.description}`),t.push(`${` `.repeat(r)}${i.join(`: `)}`);for(let t of e.children??[])n(t,r+1)};return n(e,0),t.join(`
|
|
2
|
-
|
|
1
|
+
import{createRequire as e}from"node:module";import{createHash as t,randomUUID as n}from"node:crypto";import{homedir as r}from"node:os";import{join as i}from"node:path";import{execFileSync as a}from"node:child_process";import{existsSync as o,readdirSync as s}from"node:fs";import{Buffer as c}from"node:buffer";import{z as l}from"zod";const u=e(import.meta.url);function d(e){return typeof e==`string`?e.trim():e instanceof Buffer?e.toString(`utf8`).trim():``}function f(e){process.env.PLAYWRIGHT_BROWSERS_PATH=e}async function p(e){f(e);let{chromium:t}=await import(`playwright-core`),n=t.executablePath();if(!n)throw Error(`Chromium executable not found in ${e}`);return n}function m(){return i(r(),`.aikit`,`browsers`)}function h(e){return e.browsersPath??process.env.PLAYWRIGHT_BROWSERS_PATH??m()}function g(e){return o(e)?s(e,{withFileTypes:!0}).some(e=>e.isDirectory()&&e.name.toLowerCase().startsWith(`chromium-`)):!1}async function _(e,t){let n=h(e);if(f(n),t?.(`Using Chromium cache at ${n}`),g(n))return t?.(`Chromium already installed`),p(n);let r=i(u.resolve(`playwright-core`),`..`,`cli.js`);t?.(`Installing Chromium via playwright-core`);try{a(process.execPath,[r,`install`,`chromium`],{env:{...process.env,PLAYWRIGHT_BROWSERS_PATH:n},encoding:`utf8`,stdio:`pipe`})}catch(e){let t=e,n=d(t.stderr),r=d(t.stdout),i=n||r||t.message||`Unknown playwright install failure`;throw Error(`Failed to install Chromium: ${i}`)}return t?.(`Chromium install complete`),p(n)}function v(){return process.platform===`win32`||process.platform===`darwin`?!0:!!(process.env.DISPLAY||process.env.WAYLAND_DISPLAY)}function y(e){return e===`headless`||!v()?`headless`:e}function b(e){switch(e){case`headless`:return{headless:!0,args:[]};case`panel`:return{headless:!1,args:[`--app=data:text/html,<title>aikit</title>`]};default:return{headless:!1,args:[]}}}var x=class{pages=new Map;registerPage(e,t,r){let i=n();return this.pages.set(i,{page:e,url:t,title:r,createdAt:new Date}),i}getPage(e){let t=this.pages.get(e);if(!t)throw Error(`Page not found: ${e}`);return t.page}getPageInfo(e){let t=this.pages.get(e);if(!t)throw Error(`Page not found: ${e}`);return{pageId:e,url:t.url,title:t.title,createdAt:t.createdAt}}updatePageInfo(e,t,n){let r=this.pages.get(e);if(!r)throw Error(`Page not found: ${e}`);this.pages.set(e,{...r,url:t,title:n})}async removePage(e){let t=this.pages.get(e);t&&(await t.page.close(),this.pages.delete(e))}listPages(){return[...this.pages.entries()].map(([e,t])=>({pageId:e,url:t.url,title:t.title,createdAt:t.createdAt}))}async closeAll(){await Promise.allSettled([...this.pages.keys()].map(async e=>this.removePage(e)))}get size(){return this.pages.size}};const S={defaultMode:`ui`,browsersPath:null,userDataDirRoot:null,idleShutdownMinutes:10,allowInternalSchemes:!1,evalTimeoutMs:1e4,evalMaxResultBytes:262144,redactPasswordFieldsInScreenshots:!0};var C=class{browser=null;context=null;idleTimer=null;launchPromise=null;session=new x;config;constructor(e={}){this.config={...S,...e}}async launch(e,t){if(!this.context){if(this.launchPromise)return this.launchPromise;this.launchPromise=this.doLaunch(e,t);try{await this.launchPromise}finally{this.launchPromise=null}}}async doLaunch(e,n){if(this.browser&&this.context)return;let a=y(e??this.config.defaultMode),o=h(this.config);process.env.PLAYWRIGHT_BROWSERS_PATH=o;let{chromium:s}=await import(`playwright-core`),c=await _(this.config,n),l=b(a),u=t(`sha256`).update(process.cwd()).digest(`hex`).slice(0,12),d=i(this.config.userDataDirRoot??i(r(),`.aikit`,`profiles`),u);if(n?.(`Launching Chromium in ${a} mode`),this.context=await s.launchPersistentContext(d,{headless:l.headless,args:l.args,executablePath:c}),this.browser=this.context.browser(),!this.browser)throw await this.context.close(),this.context=null,Error(`Failed to acquire Chromium browser instance`);this.browser.on(`disconnected`,()=>{this.browser=null,this.context=null,this.session.closeAll().catch(()=>{}),this.stopIdleTimer()}),this.resetIdleTimer()}stopIdleTimer(){this.idleTimer&&=(clearTimeout(this.idleTimer),null)}resetIdleTimer(){this.stopIdleTimer();let e=setTimeout(()=>{this.close()},this.config.idleShutdownMinutes*6e4);e.unref?.(),this.idleTimer=e}async close(){this.stopIdleTimer(),this.launchPromise=null;let e=this.context,t=this.browser;this.context=null,this.browser=null;let n;try{await this.session.closeAll()}catch(e){n=e}try{e&&await e.close()}catch(e){n??=e}finally{try{t&&await t.close()}catch(e){n??=e}}if(n)throw n}getContext(){if(!this.context)throw Error(`Browser not launched. Call launch() first.`);return this.context}getConfig(){return this.config}isLaunched(){return this.browser!==null}};let w=null;function T(e){return w||=new C(e),w}async function ee(){w&&=(await w.close(),null)}const te=[`file:`,`chrome:`,`chrome-extension:`,`data:`,`javascript:`],ne=[`169.254.169.254`,`metadata.google.internal`,`metadata.google.com`],E=[`localhost`,`127.0.0.1`,`::1`,`[::1]`];function re(e){return e.replace(/^\[(.*)\]$/,`$1`).toLowerCase()}function ie(e){let t=new WeakSet,n=JSON.stringify(e,(e,n)=>{if(typeof n==`bigint`)return n.toString();if(typeof n==`function`)return`[Function ${n.name||`anonymous`}]`;if(typeof n==`symbol`)return n.toString();if(n instanceof Error)return{name:n.name,message:n.message,stack:n.stack};if(typeof n==`object`&&n){if(t.has(n))return`[Circular]`;t.add(n)}return n});return n===void 0?e===void 0?`undefined`:String(e):n}function D(e,t){let n=c.from(e,`utf8`);return n.byteLength<=t?e:n.subarray(0,t).toString(`utf8`)}function O(e,t){let n;try{n=new URL(e)}catch{return{allowed:!1,reason:`Invalid URL: ${e}`}}let r=n.protocol.toLowerCase();if(te.includes(r)&&!t.allowInternalSchemes)return{allowed:!1,reason:`Blocked URL scheme: ${r}`};let i=re(n.hostname);return ne.includes(i)?{allowed:!1,reason:`Blocked host: ${n.hostname}`}:(E.includes(i)||E.includes(n.hostname),{allowed:!0})}function k(e){return e?{allowed:!0}:{allowed:!1,reason:`Cookie access requires explicit confirmation (confirm: true)`}}function A(e,t){if(t<=0)return{valid:!1,reason:`maxBytes must be greater than 0`};try{let n=ie(e);return c.byteLength(n,`utf8`)<=t?{valid:!0,result:n,truncated:!1}:{valid:!0,result:`${D(n,Math.max(t-3,0))}...`,truncated:!0,reason:`Result exceeded ${t} bytes and was truncated`}}catch(e){return{valid:!1,reason:`Unable to serialize eval result: ${e instanceof Error?e.message:String(e)}`}}}function ae(e){return e.replace(/<input\b[^>]*>/gi,e=>/\btype\s*=\s*(["'])password\1/i.test(e)?/\bvalue\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+)/i.test(e)?e.replace(/\bvalue\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+)/i,`value="***"`):e.replace(/\s*\/?>$/,e=>` value="***"${e}`):e)}const oe=[`ui`,`headless`,`panel`];function se(e){return typeof e==`object`&&e?e:null}function j(e){return typeof e==`string`&&e.length>0?e:void 0}function M(e){return typeof e==`boolean`?e:void 0}function N(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}function P(e){return typeof e==`string`&&oe.includes(e)?e:void 0}function F(e){let t=process.env[e];if(!t)return;let n=Number(t);return Number.isFinite(n)?n:void 0}function ce(e){let t=se(e.browser)??{};return{...S,defaultMode:P(process.env.AIKIT_BROWSER_DEFAULT_MODE)??P(t.defaultMode)??S.defaultMode,browsersPath:j(process.env.AIKIT_BROWSER_PATH)??j(process.env.AIKIT_BROWSER_BROWSERS_PATH)??j(t.browsersPath)??S.browsersPath,userDataDirRoot:j(t.userDataDirRoot)??S.userDataDirRoot,idleShutdownMinutes:F(`AIKIT_BROWSER_IDLE_MINUTES`)??N(t.idleShutdownMinutes)??S.idleShutdownMinutes,allowInternalSchemes:M(t.allowInternalSchemes)??S.allowInternalSchemes,evalTimeoutMs:F(`AIKIT_BROWSER_EVAL_TIMEOUT_MS`)??N(t.evalTimeoutMs)??S.evalTimeoutMs,evalMaxResultBytes:N(t.evalMaxResultBytes)??S.evalMaxResultBytes,redactPasswordFieldsInScreenshots:M(t.redactPasswordFieldsInScreenshots)??S.redactPasswordFieldsInScreenshots}}function I(e,t){return{content:[{type:`text`,text:e}],structuredContent:t}}function L(e,t){let n=e.selector??e.ref;if(!n)throw Error(`${t} requires selector or ref`);return n}async function le(e,t,n){let r=null;try{return await Promise.race([e,new Promise((e,i)=>{r=setTimeout(()=>{i(Error(`${n} timed out after ${t}ms`))},t)})])}finally{r&&clearTimeout(r)}}l.string().describe(`Tracked browser page identifier`),l.enum([`click`,`type`,`press`,`hover`,`drag`,`select`,`scroll`,`upload`]).describe(`Interaction kind: click, type, press, hover, drag, select, scroll, upload`),l.string().optional().describe(`Target ref alias`),l.string().optional().describe(`Playwright selector`),l.string().optional().describe(`Human-readable element label`),l.string().optional().describe(`Text to type`),l.string().optional().describe(`Key to press`),l.string().optional().describe(`Option value, drag target, scroll spec, or file path(s)`),l.string().optional().describe(`Drag source ref`),l.string().optional().describe(`Drag source selector`),l.string().optional().describe(`Drag target ref`),l.string().optional().describe(`Drag target selector`);function ue(e){return async({pageId:t,kind:n,ref:r,selector:i,text:a,key:o,value:s,fromRef:c,fromSelector:l,toRef:u,toSelector:d})=>{let f=T(e),p=f.session.getPage(t);switch(n){case`click`:{let e=L({ref:r,selector:i},`browser_act(click)`);await p.click(e);break}case`type`:{let e=L({ref:r,selector:i},`browser_act(type)`);await p.fill(e,a??``);break}case`press`:{let e=L({ref:r,selector:i},`browser_act(press)`);if(!o)throw Error(`browser_act(press) requires key`);await p.press(e,o);break}case`hover`:{let e=L({ref:r,selector:i},`browser_act(hover)`);await p.hover(e);break}case`drag`:{let e=L({ref:c??r,selector:l??i},`browser_act(drag) source`),t=L({ref:u,selector:d??s},`browser_act(drag) target`);await p.dragAndDrop(e,t);break}case`select`:{let e=L({ref:r,selector:i},`browser_act(select)`);if(s===void 0)throw Error(`browser_act(select) requires value`);await p.selectOption(e,s);break}case`scroll`:{if(i||r){let e=L({ref:r,selector:i},`browser_act(scroll)`);await p.locator(e).scrollIntoViewIfNeeded();break}let e=s??`down 500`;await p.evaluate(e=>{if(e===`bottom`){window.scrollTo(0,document.body.scrollHeight);return}if(e===`top`){window.scrollTo(0,0);return}let t=e.split(` `),n=t[0]||`down`,r=Number.parseInt(t[1]||`500`,10),i=n===`left`?-r:n===`right`?r:0,a=n===`up`?-r:n===`down`?r:0;window.scrollBy(i,a)},e);break}case`upload`:{let e=L({ref:r,selector:i},`browser_act(upload)`);if(!s)throw Error(`value (file path or JSON array of paths) required for upload`);let t;try{let e=JSON.parse(s);t=Array.isArray(e)?e:[s]}catch{t=[s]}await p.locator(e).setInputFiles(t);break}}return f.resetIdleTimer(),I(`ok`,{ok:!0})}}l.string().describe(`Tracked browser page identifier`),l.boolean().describe(`Whether to accept the next dialog`),l.string().optional().describe(`Text to provide when accepting a prompt dialog`);function de(e){return async({pageId:t,accept:n,promptText:r})=>{let i=T(e);return i.session.getPage(t).once(`dialog`,async e=>{n?await e.accept(r):await e.dismiss()}),i.resetIdleTimer(),I(`ok`,{ok:!0})}}l.string().describe(`Tracked browser page identifier`),l.string().describe(`JavaScript expression or function source evaluated in the page`),l.number().min(1).max(6e4).optional().describe(`Optional evaluation timeout`);function fe(e){return async({pageId:t,code:n,timeoutMs:r})=>{let i=T(e),a=i.session.getPage(t),o=Math.min(r??e.evalTimeoutMs,6e4),s=A(await le(a.evaluate(e=>{let t=Function(`return (${e});`)();return typeof t==`function`?t():t},n),o,`browser_eval`),e.evalMaxResultBytes);if(!s.valid||s.result===void 0)throw Error(s.reason??`browser_eval result validation failed`);return i.resetIdleTimer(),I(s.result,{pageId:t,result:s.result,truncated:s.truncated??!1,reason:s.reason})}}l.string().describe(`Tracked browser page identifier`),l.string().url().optional().describe(`Optional URL to navigate to`),l.enum([`back`,`forward`,`reload`,`waitFor`]).optional().describe(`Navigation helper action`),l.string().optional().describe(`Selector to wait for when type="waitFor"`),l.number().min(1).max(6e4).optional().describe(`Optional wait timeout`);function R(e){return async({pageId:t,url:n,type:r,selector:i,timeoutMs:a})=>{let o=T(e),s=o.session.getPage(t);if(n){let r=O(n,e);if(!r.allowed)return I(`Navigation blocked: ${r.reason}`,{blocked:!0,pageId:t,reason:r.reason});await s.goto(n)}else if(!r)return I(`Navigation requires url or type`,{error:`Navigation requires url or type`,pageId:t});else if(r===`back`)await s.goBack();else if(r===`forward`)await s.goForward();else if(r===`reload`)await s.reload();else if(r===`waitFor`){if(!i)throw Error(`browser_navigate(waitFor) requires selector`);await s.waitForSelector(i,a?{timeout:a}:void 0)}let c=s.url(),l=await s.title();return o.session.updatePageInfo(t,c,l),o.resetIdleTimer(),I(`${l||c}\n${c}`,{pageId:t,url:c,title:l})}}l.string().url().describe(`Absolute URL to open`),l.enum([`ui`,`headless`,`panel`]).optional().describe(`Browser launch mode`),l.boolean().optional().describe(`Reserved for future tab reuse control`),l.enum([`load`,`domcontentloaded`,`networkidle`]).optional().describe(`Navigation readiness event`);function z(e){return async({url:t,mode:n,waitUntil:r})=>{let i=O(t,e);if(!i.allowed)throw Error(i.reason??`Blocked URL: ${t}`);let a=T(e);a.isLaunched()||await a.launch(n??e.defaultMode);let o=await a.getContext().newPage();r?await o.goto(t,{waitUntil:r}):await o.goto(t);let s=await o.title(),c=a.session.registerPage(o,t,s);return a.resetIdleTimer(),I(`Opened ${s||t}\npageId: ${c}`,{pageId:c,url:t,title:s})}}l.string().describe(`Tracked browser page identifier`),l.enum([`snapshot`,`dom`,`markdown`,`text`]).optional().describe(`Extraction mode: snapshot (ARIA tree), dom (HTML), markdown (clean MD), text (plain text)`),l.string().optional().describe(`CSS selector to scope extraction to a specific element`);function B(e){return async({pageId:t,mode:n,selector:r})=>{let i=T(e).session.getPage(t),a=r??`body`,o=n??`snapshot`;switch(o){case`dom`:{let e=r?await i.locator(r).innerHTML():await i.content();return I(e||`empty page`,{pageId:t,mode:o,selector:r,dom:e})}case`markdown`:{let e=await i.evaluate(e=>{let t=globalThis,n=e?t.document?.querySelector(e):t.document?.body;if(!n)return``;function r(e){if(e.nodeType===t.Node?.TEXT_NODE)return e.textContent?.replace(/\s+/g,` `)||``;if(e.nodeType!==t.Node?.ELEMENT_NODE)return``;let n=e,a=n.tagName.toLowerCase(),o=t.window?.getComputedStyle(n);if(o?.display===`none`||o?.visibility===`hidden`)return``;let s=Array.from(n.childNodes).map(r).filter(Boolean).join(``);switch(a){case`h1`:return`# ${s.trim()}\n\n`;case`h2`:return`## ${s.trim()}\n\n`;case`h3`:return`### ${s.trim()}\n\n`;case`h4`:return`#### ${s.trim()}\n\n`;case`h5`:return`##### ${s.trim()}\n\n`;case`h6`:return`###### ${s.trim()}\n\n`;case`p`:return`${s.trim()}\n\n`;case`br`:return`
|
|
2
|
+
`;case`hr`:return`
|
|
3
|
+
---
|
|
4
|
+
|
|
5
|
+
`;case`strong`:case`b`:return`**${s.trim()}**`;case`em`:case`i`:return`*${s.trim()}*`;case`code`:return n.parentElement?.tagName===`PRE`?s:`\`${s.trim()}\``;case`pre`:return`\n\`\`\`\n${n.textContent?.trim()||``}\n\`\`\`\n\n`;case`blockquote`:return`> ${s.trim().replace(/\n/g,`
|
|
6
|
+
> `)}\n\n`;case`a`:return`[${s.trim()}](${n.getAttribute(`href`)||``})`;case`img`:return`||``})`;case`ul`:case`ol`:return`${s}\n`;case`li`:return`${n.parentElement?.tagName===`OL`?`${Array.from(n.parentElement.children).indexOf(n)+1}. `:`- `}${s.trim()}\n`;case`table`:return`${i(n)}\n\n`;case`script`:case`style`:case`noscript`:case`nav`:case`footer`:case`header`:return``;case`div`:case`section`:case`article`:case`main`:case`span`:return s;default:return s}}function i(e){let t=Array.from(e.querySelectorAll(`tr`));if(!t.length)return``;let n=[];return t.forEach((e,t)=>{let r=Array.from(e.querySelectorAll(`th, td`)).map(e=>e.textContent?.trim()||``);n.push(`| ${r.join(` | `)} |`),t===0&&n.push(`| ${r.map(()=>`---`).join(` | `)} |`)}),n.join(`
|
|
7
|
+
`)}return r(n).replace(/\n{3,}/g,`
|
|
8
|
+
|
|
9
|
+
`).trim()},r);return I(e||`empty page`,{pageId:t,mode:o,selector:r,markdown:e})}case`text`:{let e=await i.locator(a).innerText();return I(e||`empty page`,{pageId:t,mode:o,selector:r,text:e})}default:{let e=await i.locator(a).ariaSnapshot();return I(e||`empty page`,{pageId:t,mode:o,selector:r,snapshot:e})}}}}l.string().describe(`Tracked browser page identifier`),l.string().optional().describe(`Optional target ref alias`),l.string().optional().describe(`Optional target selector`),l.boolean().optional().describe(`Capture the full page when no selector is provided`),l.boolean().optional().describe(`Mask password fields before capture`),l.object({x:l.number(),y:l.number(),width:l.number(),height:l.number()}).optional().describe(`Capture a specific page region { x, y, width, height }`),l.enum([`png`,`jpeg`]).optional().describe(`Image format (default: png)`),l.number().min(0).max(100).optional().describe(`JPEG quality 0-100 (only for jpeg format)`);function pe(e){return async({pageId:t,ref:n,selector:r,fullPage:i,redactPasswords:a,clip:o,format:s,quality:c})=>{let l=T(e),u=l.session.getPage(t),d=a??e.redactPasswordFieldsInScreenshots,f=[];d&&(f=await u.evaluate(()=>{let e=globalThis.document;return Array.from(e.querySelectorAll(`input[type="password"]`)).map((e,t)=>{let n=e,r=`data-aikit-password-mask-${t}`;return n.setAttribute(r,n.value),n.value=`***`,r})}));try{let e={};s&&(e.type=s),s===`jpeg`&&c!==void 0&&(e.quality=c);let a=r??n?await u.locator(L({ref:n,selector:r},`browser_screenshot`)).screenshot(e):await u.screenshot({...e,...o?{clip:o}:{fullPage:i??!1}});return l.resetIdleTimer(),I(`Screenshot captured`,{pageId:t,base64:a.toString(`base64`)})}finally{d&&f.length>0&&await u.evaluate(e=>{let t=globalThis.document;for(let n of e){let e=t.querySelector(`input[${n}]`);e&&(e.value=e.getAttribute(n)??``,e.removeAttribute(n))}},f)}}}const me=l.enum([`Lax`,`None`,`Strict`]),he=l.enum([`localStorage`,`sessionStorage`]);l.enum([`list`,`close`,`cookies`,`set-cookie`,`delete-cookie`,`clear-cookies`,`get-storage`,`set-storage`,`clear-storage`]).describe(`Session sub-action`),l.string().optional().describe(`Page ID (required for close, storage actions)`),l.boolean().optional().describe(`Explicit confirmation for cookie operations`),l.array(l.object({name:l.string(),value:l.string(),url:l.string().optional(),domain:l.string().optional(),path:l.string().optional(),expires:l.number().optional(),httpOnly:l.boolean().optional(),secure:l.boolean().optional(),sameSite:me.optional()})).optional().describe(`Cookies to set (for set-cookie action)`),l.string().optional().describe(`Cookie name (for delete-cookie action)`),he.optional().describe(`Storage type for storage actions`),l.string().optional().describe(`Storage key to get/set`),l.string().optional().describe(`Storage value to set`);function ge(e){return async({action:t,pageId:n,confirm:r,cookies:i,name:a,storageType:o,storageKey:s,storageValue:c})=>{let l=T(e);if(t===`list`){let e=l.session.listPages();return I(JSON.stringify(e,null,2),{pages:e})}if(t===`close`){if(!n)throw Error(`browser_session(close) requires pageId`);return await l.session.removePage(n),l.resetIdleTimer(),I(`ok`,{ok:!0,pageId:n})}if(t===`set-cookie`){let e=k(!!r);if(!e.allowed)throw Error(e.reason??`Cookie access denied`);if(!i?.length)throw Error(`cookies array required for set-cookie`);return await l.getContext().addCookies(i),l.resetIdleTimer(),I(`Set ${i.length} cookie(s)`,{ok:!0,count:i.length})}if(t===`delete-cookie`){let e=k(!!r);if(!e.allowed)throw Error(e.reason??`Cookie access denied`);if(!a)throw Error(`name required for delete-cookie`);return await l.getContext().clearCookies({name:a}),l.resetIdleTimer(),I(`Deleted cookie: ${a}`,{ok:!0,name:a})}if(t===`clear-cookies`){let e=k(!!r);if(!e.allowed)throw Error(e.reason??`Cookie access denied`);return await l.getContext().clearCookies(),l.resetIdleTimer(),I(`All cookies cleared`,{ok:!0})}if(t===`get-storage`){if(!n)throw Error(`pageId required for get-storage`);if(!o)throw Error(`storageType required for get-storage`);let e=await l.session.getPage(n).evaluate(({type:e,key:t})=>{let n=e===`localStorage`?localStorage:sessionStorage;if(t)return n.getItem(t);let r={};for(let e=0;e<n.length;e+=1){let t=n.key(e);t&&(r[t]=n.getItem(t)||``)}return r},{type:o,key:s});return l.resetIdleTimer(),I(s?`${o}.${s} = ${String(e)}`:`${o}: ${JSON.stringify(e)}`,{storageType:o,key:s,data:e})}if(t===`set-storage`){if(!n)throw Error(`pageId required for set-storage`);if(!o)throw Error(`storageType required for set-storage`);if(!s)throw Error(`storageKey required for set-storage`);if(c===void 0)throw Error(`storageValue required for set-storage`);return await l.session.getPage(n).evaluate(({type:e,key:t,value:n})=>{(e===`localStorage`?localStorage:sessionStorage).setItem(t,n)},{type:o,key:s,value:c}),l.resetIdleTimer(),I(`Set ${o}.${s}`,{ok:!0,storageType:o,key:s})}if(t===`clear-storage`){if(!n)throw Error(`pageId required for clear-storage`);if(!o)throw Error(`storageType required for clear-storage`);return await l.session.getPage(n).evaluate(e=>{(e===`localStorage`?localStorage:sessionStorage).clear()},o),l.resetIdleTimer(),I(`Cleared ${o}`,{ok:!0,storageType:o})}let u=k(!!r);if(!u.allowed)throw Error(u.reason??`Cookie access denied`);let d=await l.getContext().cookies();return l.resetIdleTimer(),I(JSON.stringify(d,null,2),{cookies:d})}}const V=[`open`,`read`,`act`,`navigate`,`eval`,`screenshot`,`dialog`,`session`],H=[`ui`,`headless`,`panel`],U=[`load`,`domcontentloaded`,`networkidle`],W=[`click`,`type`,`press`,`hover`,`drag`,`select`,`scroll`,`upload`],G=[`back`,`forward`,`reload`,`waitFor`],K=[`list`,`close`,`cookies`,`set-cookie`,`delete-cookie`,`clear-cookies`,`get-storage`,`set-storage`,`clear-storage`],_e={action:l.enum(V).describe(`Browser action to perform`),pageId:l.string().optional().describe(`Tracked browser page identifier`),url:l.string().url().optional().describe(`URL to open or navigate to`),mode:l.enum(H).optional().describe(`Browser launch mode (open only)`),forceNew:l.boolean().optional().describe(`Reserved for future tab reuse`),waitUntil:l.enum(U).optional().describe(`Navigation readiness event`),kind:l.enum(W).optional().describe(`Interaction kind (act only)`),ref:l.string().optional().describe(`Target ref alias`),selector:l.string().optional().describe(`Playwright selector`),element:l.string().optional().describe(`Human-readable element label`),text:l.string().optional().describe(`Text to type`),key:l.string().optional().describe(`Key to press`),value:l.string().optional().describe(`Option value or drag target`),fromRef:l.string().optional().describe(`Drag source ref`),fromSelector:l.string().optional().describe(`Drag source selector`),toRef:l.string().optional().describe(`Drag target ref`),toSelector:l.string().optional().describe(`Drag target selector`),type:l.enum(G).optional().describe(`Navigation type`),code:l.string().optional().describe(`JavaScript to evaluate in the page`),timeoutMs:l.number().min(1).max(6e4).optional().describe(`Timeout in milliseconds`),fullPage:l.boolean().optional().describe(`Capture full page`),redactPasswords:l.boolean().optional().describe(`Mask password fields`),readMode:l.enum([`snapshot`,`dom`,`markdown`,`text`]).optional().describe(`Extraction mode for read action: snapshot (ARIA tree), dom (HTML), markdown (clean MD), text (plain text)`),clip:l.object({x:l.number(),y:l.number(),width:l.number(),height:l.number()}).optional().describe(`Capture a specific page region { x, y, width, height }`),format:l.enum([`png`,`jpeg`]).optional().describe(`Screenshot image format (default: png)`),quality:l.number().min(0).max(100).optional().describe(`JPEG quality 0-100 (only for jpeg format)`),cookies:l.array(l.object({name:l.string(),value:l.string(),url:l.string().optional(),domain:l.string().optional(),path:l.string().optional(),expires:l.number().optional(),httpOnly:l.boolean().optional(),secure:l.boolean().optional(),sameSite:l.enum([`Lax`,`None`,`Strict`]).optional()})).optional().describe(`Cookies to set (for session set-cookie action)`),name:l.string().optional().describe(`Cookie name for delete-cookie action`),storageType:l.enum([`localStorage`,`sessionStorage`]).optional().describe(`Storage type for get/set/clear-storage actions`),storageKey:l.string().optional().describe(`Storage key to get or set`),storageValue:l.string().optional().describe(`Value to set in storage`),accept:l.boolean().optional().describe(`Accept or dismiss dialog`),promptText:l.string().optional().describe(`Text for prompt dialog`),sessionAction:l.enum(K).optional().describe(`Session sub-action (session only)`),confirm:l.boolean().optional().describe(`Explicit confirmation for cookie export`)};function q(e,t){return typeof e==`string`&&t.includes(e)}function J(e,t,n){let r=e[t];if(typeof r!=`string`)throw Error(`${n} requires ${t}`);return r}function ve(e,t,n){let r=e[t];if(typeof r!=`boolean`)throw Error(`${n} requires ${t}`);return r}function Y(e,t){let n=e[t];return typeof n==`string`?n:void 0}function X(e,t){let n=e[t];return typeof n==`boolean`?n:void 0}function Z(e,t){let n=e[t];return typeof n==`number`?n:void 0}function ye(e,t){let n=e[t];return typeof n==`object`&&n?n:void 0}function Q(e,t,n,r){let i=e[t];if(!q(i,n))throw Error(`${r} requires ${t}`);return i}function $(e,t,n,r){let i=e[t];if(i!==void 0){if(!q(i,n))throw Error(`${r} received invalid ${t}`);return i}}function be(e,t){let n=ce(t),r=z(n),i=B(n),a=ue(n),o=R(n),s=fe(n),c=pe(n),l=de(n),u=ge(n);e.registerTool(`browser`,{title:`Browser Automation`,description:`Unified browser automation tool. Actions:
|
|
3
10
|
- open: Launch a browser page (url required, mode/waitUntil optional)
|
|
4
11
|
- read: Get accessibility snapshot of a page (pageId required)
|
|
5
|
-
- act: Interact with elements — click/type/press/hover/drag/select (pageId + kind required)
|
|
12
|
+
- act: Interact with elements — click/type/press/hover/drag/select/scroll/upload (pageId + kind required)
|
|
6
13
|
- navigate: Go to URL, back/forward/reload, or waitFor selector (pageId required)
|
|
7
14
|
- eval: Evaluate JavaScript in page context (pageId + code required)
|
|
8
15
|
- screenshot: Capture page or element screenshot (pageId required)
|
|
9
16
|
- dialog: Accept or dismiss next browser dialog (pageId + accept required)
|
|
10
|
-
- session: List pages, close a page, or export cookies (sessionAction required)`,inputSchema:_e,annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},async e=>{switch(Q(e,`action`,
|
|
17
|
+
- session: List pages, close a page, or export cookies (sessionAction required)`,inputSchema:_e,annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},async e=>{switch(Q(e,`action`,V,`browser`)){case`open`:return r({url:J(e,`url`,`browser(open)`),mode:$(e,`mode`,H,`browser(open)`),forceNew:X(e,`forceNew`),waitUntil:$(e,`waitUntil`,U,`browser(open)`)});case`read`:return i({pageId:J(e,`pageId`,`browser(read)`),mode:$(e,`readMode`,[`snapshot`,`dom`,`markdown`,`text`],`browser(read)`),selector:Y(e,`selector`)});case`act`:return a({pageId:J(e,`pageId`,`browser(act)`),kind:Q(e,`kind`,W,`browser(act)`),ref:Y(e,`ref`),selector:Y(e,`selector`),element:Y(e,`element`),text:Y(e,`text`),key:Y(e,`key`),value:Y(e,`value`),fromRef:Y(e,`fromRef`),fromSelector:Y(e,`fromSelector`),toRef:Y(e,`toRef`),toSelector:Y(e,`toSelector`)});case`navigate`:return o({pageId:J(e,`pageId`,`browser(navigate)`),url:Y(e,`url`),type:$(e,`type`,G,`browser(navigate)`),selector:Y(e,`selector`),timeoutMs:Z(e,`timeoutMs`)});case`eval`:return s({pageId:J(e,`pageId`,`browser(eval)`),code:J(e,`code`,`browser(eval)`),timeoutMs:Z(e,`timeoutMs`)});case`screenshot`:{let t=ye(e,`clip`);return c({pageId:J(e,`pageId`,`browser(screenshot)`),ref:Y(e,`ref`),selector:Y(e,`selector`),fullPage:X(e,`fullPage`),redactPasswords:X(e,`redactPasswords`),clip:t,format:$(e,`format`,[`png`,`jpeg`],`browser(screenshot)`),quality:Z(e,`quality`)})}case`dialog`:return l({pageId:J(e,`pageId`,`browser(dialog)`),accept:ve(e,`accept`,`browser(dialog)`),promptText:Y(e,`promptText`)});case`session`:{let t=e.cookies;return u({action:Q(e,`sessionAction`,K,`browser(session)`),pageId:Y(e,`pageId`),confirm:X(e,`confirm`),cookies:t,name:Y(e,`name`),storageType:$(e,`storageType`,[`localStorage`,`sessionStorage`],`browser(session)`),storageKey:Y(e,`storageKey`),storageValue:Y(e,`storageValue`)})}}})}export{C as BrowserEngine,S as DEFAULT_BROWSER_CONFIG,x as SessionRegistry,y as autoSelectMode,ee as closeEngine,v as detectDisplayAvailable,_ as ensureBrowserInstalled,m as getDefaultBrowsersPath,T as getEngine,b as getLaunchArgs,g as isBrowserInstalled,k as isCookieAccessAllowed,O as isUrlAllowed,ae as redactPasswordFields,be as registerBrowserTools,h as resolveBrowsersPath,A as validateEvalResult};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{p as e}from"./scaffold-BB6OrTuA.js";import{a as t,i as n,n as r,t as i}from"./user-
|
|
1
|
+
import{p as e}from"./scaffold-BB6OrTuA.js";import{a as t,i as n,n as r,t as i}from"./user-ZDsx66gQ.js";import{a,o,r as s}from"./templates-BXyPFub1.js";import{copyFileSync as c,existsSync as l,mkdirSync as u,readFileSync as d,readdirSync as f}from"node:fs";import{basename as p,dirname as m,join as h,relative as g,resolve as _}from"node:path";import{fileURLToPath as v}from"node:url";import{addToWorkset as y,audit as b,check as x,checkpointLatest as S,checkpointList as ee,checkpointLoad as te,checkpointSave as ne,codemod as re,compact as ie,dataTransform as ae,delegate as oe,delegateListModels as se,deleteWorkset as ce,diffParse as le,evaluate as ue,fileSummary as de,find as fe,findDeadSymbols as pe,findExamples as me,getWorkset as he,gitContext as ge,graphQuery as _e,guide as ve,health as ye,laneCreate as be,laneDiff as xe,laneDiscard as Se,laneList as Ce,laneMerge as we,laneStatus as Te,listWorksets as Ee,parseOutput as De,processList as Oe,processLogs as ke,processStart as Ae,processStatus as C,processStop as je,queueClear as Me,queueCreate as Ne,queueDelete as Pe,queueDone as Fe,queueFail as Ie,queueGet as Le,queueList as Re,queueNext as ze,queuePush as Be,removeFromWorkset as Ve,rename as He,replayClear as Ue,replayList as We,replayTrim as Ge,saveWorkset as Ke,scopeMap as qe,stashClear as Je,stashDelete as Ye,stashGet as Xe,stashList as Ze,stashSet as Qe,symbol as $e,testRun as et,trace as tt,watchList as nt,watchStart as rt,watchStop as it}from"../../tools/dist/index.js";import{readFile as w}from"node:fs/promises";import{fork as at}from"node:child_process";import{AIKIT_PATHS as T,EMBEDDING_DEFAULTS as E,getGlobalDataDir as ot,getPartitionDir as D,isUserInstalled as st,registerWorkspace as ct}from"../../core/dist/index.js";import{initializeWasm as lt}from"../../chunker/dist/index.js";import{OnnxEmbedder as ut}from"../../embeddings/dist/index.js";import{IncrementalIndexer as dt}from"../../indexer/dist/index.js";import{SqliteGraphStore as O,createSqliteAdapter as ft,createStore as pt}from"../../store/dist/index.js";const mt=[{name:`analyze`,description:`Run analyzer output for a path`,usage:`aikit analyze <type> <path>`,run:async e=>{let t=e.shift()?.trim()??``,n=e.shift()?.trim()??``;(!t||!n)&&(console.error(`Usage: aikit analyze <type> <path>`),console.error(`Types: structure, deps, symbols, patterns, entry-points, blast-radius, diagram`),process.exit(1));let{BlastRadiusAnalyzer:r,DependencyAnalyzer:i,DiagramGenerator:a,EntryPointAnalyzer:o,PatternAnalyzer:s,StructureAnalyzer:c,SymbolAnalyzer:l}=await import(`../../analyzers/dist/index.js`),u=_(n),d;switch(t){case`structure`:d=await new c().analyze(u,{format:`markdown`});break;case`deps`:case`dependencies`:d=await new i().analyze(u,{format:`markdown`});break;case`symbols`:d=await new l().analyze(u,{format:`markdown`});break;case`patterns`:d=await new s().analyze(u,{format:`markdown`});break;case`entry-points`:d=await new o().analyze(u,{format:`markdown`});break;case`blast-radius`:d=await new r().analyze(process.cwd(),{files:[n],format:`markdown`});break;case`diagram`:d=await new a().analyze(u,{diagramType:`architecture`});break;default:console.error(`Unknown analyze type: ${t}`),console.error(`Types: structure, deps, symbols, patterns, entry-points, blast-radius, diagram`),process.exit(1)}console.log(d.output)}},{name:`onboard`,description:`Run all analyses for first-time codebase onboarding`,usage:`aikit onboard <path> [--generate] [--out-dir <dir>]`,run:async e=>{let{onboard:t}=await import(`../../tools/dist/index.js`),n=``,r=`memory`,i;for(let t=0;t<e.length;t++){let a=e[t].trim();a===`--generate`?r=`generate`:a===`--out-dir`&&t+1<e.length?i=e[++t].trim():a.startsWith(`--`)||(n=a)}n||=process.cwd();let a=_(n);console.log(`Onboarding: ${a} (mode: ${r})`),console.log(`Running analyses...
|
|
2
2
|
`);let o=await t({path:a,mode:r,outDir:i});for(let e of o.steps){let t=e.status===`success`?`✓`:`✗`,n=e.status===`success`?`${e.durationMs}ms, ${e.output.length} chars`:e.error;console.log(` ${t} ${e.name} — ${n}`)}console.log(`\nTotal: ${o.totalDurationMs}ms`),o.outDir&&console.log(`Output written to: ${o.outDir}`)}}];function k(e,t,n){let r=e.indexOf(t);if(r===-1||r+1>=e.length)return n;let i=Number.parseInt(e.splice(r,2)[1],10);return Number.isNaN(i)?n:i}function A(e,t,n){let r=e.indexOf(t);return r===-1||r+1>=e.length?n:e.splice(r,2)[1]}function j(e,t){let n=e.indexOf(t);return n===-1?!1:(e.splice(n,1),!0)}async function M(){if(process.stdin.isTTY)return``;let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString(`utf-8`)}function N(e){return e.split(`,`).map(e=>e.trim()).filter(Boolean)}function ht(e){return e.map(e=>{let t=e.heading?` ${e.heading}`:``;return`${e.start}-${e.end}${t}`}).join(`, `)}function gt(e){switch(e.tool){case`tsc`:case`biome`:console.log(`${e.tool} errors: ${e.errors.length}`);for(let t of e.errors){let e=[t.line,t.column].filter(e=>e!==void 0).join(`:`),n=e?`${t.file}:${e}`:t.file,r=t.code?` ${t.code}`:``;console.log(`- ${n} [${t.severity}${r}] ${t.message}`)}return;case`vitest`:console.log(`Vitest summary`),console.log(` Passed: ${e.summary.passed}`),console.log(` Failed: ${e.summary.failed}`),console.log(` Skipped: ${e.summary.skipped}`),e.summary.duration!==void 0&&console.log(` Duration: ${e.summary.duration}ms`);for(let t of e.summary.tests)t.status===`fail`&&(console.log(`- ${t.name}${t.file?` (${t.file})`:``}`),t.error&&console.log(` ${t.error}`));return;case`git-status`:console.log(`Branch: ${e.status.branch??`unknown`}`),console.log(`Staged: ${e.status.staged.length}`);for(let t of e.status.staged)console.log(` ${t.status} ${t.file}`);console.log(`Unstaged: ${e.status.unstaged.length}`);for(let t of e.status.unstaged)console.log(` ${t.status} ${t.file}`);console.log(`Untracked: ${e.status.untracked.length}`);for(let t of e.status.untracked)console.log(` ?? ${t}`);return}}function _t(e){console.log(`Overall: ${e.passed?`passed`:`failed`}`),P(`tsc`,e.tsc.passed,e.tsc.errors),P(`biome`,e.biome.passed,e.biome.errors)}function P(e,t,n){console.log(`${e}: ${t?`passed`:`${n.length} issue(s)`}`);for(let e of n){let t=[e.line,e.column].filter(e=>e!==void 0).join(`:`),n=t?`${e.file}:${t}`:e.file,r=e.code?` ${e.code}`:``;console.log(` - ${n} [${e.severity}${r}] ${e.message}`)}}function vt(e){console.log(`Vitest: ${e.passed?`passed`:`failed`}`),console.log(` Duration: ${e.durationMs}ms`),console.log(` Passed: ${e.summary.passed}`),console.log(` Failed: ${e.summary.failed}`),console.log(` Skipped: ${e.summary.skipped}`),e.summary.suites!==void 0&&console.log(` Suites: ${e.summary.suites}`);let t=e.summary.tests.filter(e=>e.status===`fail`);if(t.length!==0){console.log(`Failed tests:`);for(let e of t)console.log(` - ${e.name}${e.file?` (${e.file})`:``}`),e.error&&console.log(` ${e.error}`)}}function yt(e){console.log(`Branch: ${e.branch}`),console.log(`Staged: ${e.status.staged.length}`);for(let t of e.status.staged)console.log(` - ${t}`);console.log(`Modified: ${e.status.modified.length}`);for(let t of e.status.modified)console.log(` - ${t}`);console.log(`Untracked: ${e.status.untracked.length}`);for(let t of e.status.untracked)console.log(` - ${t}`);if(console.log(``),console.log(`Recent commits:`),e.recentCommits.length===0)console.log(` none`);else for(let t of e.recentCommits)console.log(` - ${t.hash} ${t.message}`),console.log(` ${t.author} @ ${t.date}`);e.diff&&(console.log(``),console.log(`Diff stat:`),console.log(e.diff))}function bt(e){if(e.length===0){console.log(`No diff files found.`);return}for(let t of e){let e=t.oldPath?` (from ${t.oldPath})`:``;console.log(`${t.path}${e}`),console.log(` Status: ${t.status}`),console.log(` Changes: +${t.additions} -${t.deletions}`),console.log(` Hunks: ${t.hunks.length}`);for(let e of t.hunks){let t=e.header?` ${e.header}`:``;console.log(` @@ -${e.oldStart},${e.oldLines} +${e.newStart},${e.newLines} @@${t}`)}}}function xt(e){if(console.log(`Start: ${e.start}`),console.log(`Direction: ${e.direction}`),console.log(`Depth reached: ${e.depth}`),console.log(`Nodes: ${e.nodes.length}`),e.nodes.length===0){console.log(`No trace nodes found.`);return}for(let t of e.nodes)console.log(` - [${t.relationship}] ${t.path}:${t.line} ${t.symbol}`)}function St(e){if(console.log(`Query: ${e.query}`),console.log(`Examples: ${e.examples.length} shown (${e.totalFound} total)`),e.examples.length===0){console.log(`No matching examples found.`);return}for(let t of e.examples){console.log(``),console.log(`${t.path}:${t.startLine}-${t.endLine}`),console.log(` Context: ${t.context}`),console.log(` Relevance: ${(t.relevance*100).toFixed(1)}%`);for(let e of t.content.split(`
|
|
3
3
|
`))console.log(` ${e}`)}}function F(e){console.log(e.id),console.log(` Command: ${e.command}${e.args.length>0?` ${e.args.join(` `)}`:``}`),console.log(` PID: ${e.pid??`unknown`}`),console.log(` Status: ${e.status}`),console.log(` Started: ${e.startedAt}`),e.exitCode!==void 0&&console.log(` Exit code: ${e.exitCode}`),console.log(` Logs: ${e.logs.length}`)}function Ct(e){if(console.log(`Exports scanned: ${e.totalExports}`),console.log(`Dead in source: ${e.totalDeadSource} (actionable)`),console.log(`Dead in docs: ${e.totalDeadDocs} (informational)`),e.totalDeadSource===0&&e.totalDeadDocs===0){console.log(`No dead symbols found.`);return}if(e.deadInSource.length>0){console.log(`
|
|
4
4
|
Dead in source (actionable):`);for(let t of e.deadInSource)console.log(` - ${t.path}:${t.line} ${t.kind} ${t.name}`)}if(e.deadInDocs.length>0){console.log(`
|
|
@@ -12,7 +12,7 @@ Issues found:`);for(let e of n.issues)console.log(` - ${e}`)}}}],Xt=[{name:`pro
|
|
|
12
12
|
Actions: stats, find-nodes, find-edges, neighbors, traverse, delete, clear`),process.exit(1));let{graphStore:n}=await J(),r=A(e,`--type`,``),i=A(e,`--name`,``),a=A(e,`--node-id`,``),o=A(e,`--edge-type`,``),s=A(e,`--direction`,`both`),c=k(e,`--depth`,2),l=k(e,`--limit`,50),u=A(e,`--source-path`,``),d={stats:`stats`,"find-nodes":`find_nodes`,"find-edges":`find_edges`,neighbors:`neighbors`,traverse:`traverse`,delete:`delete`,clear:`clear`}[t];d||(console.error(`Unknown graph action: ${t}`),console.error(`Actions: stats, find-nodes, find-edges, neighbors, traverse, delete, clear`),process.exit(1));let f=await _e(n,{action:d,nodeType:r||void 0,namePattern:i||void 0,sourcePath:u||void 0,nodeId:a||void 0,edgeType:o||void 0,direction:s,maxDepth:c,limit:l});if(console.log(f.summary),f.nodes&&f.nodes.length>0){console.log(`
|
|
13
13
|
Nodes:`);for(let e of f.nodes){let t=Object.keys(e.properties).length>0?` ${JSON.stringify(e.properties)}`:``;console.log(` ${e.name} (${e.type}, id: ${e.id})${t}`)}}if(f.edges&&f.edges.length>0){console.log(`
|
|
14
14
|
Edges:`);for(let e of f.edges){let t=e.weight===1?``:` (weight: ${e.weight})`;console.log(` ${e.fromId} --[${e.type}]--> ${e.toId}${t}`)}}f.stats&&(console.log(`\nNode types: ${JSON.stringify(f.stats.nodeTypes)}`),console.log(`Edge types: ${JSON.stringify(f.stats.edgeTypes)}`)),f.deleted!==void 0&&console.log(`Deleted: ${f.deleted}`)}}],an=[{name:`remember`,description:`Store curated knowledge`,usage:`aikit remember <title> --category <cat> [--tags tag1,tag2]`,run:async e=>{let t=A(e,`--category`,``).trim(),n=N(A(e,`--tags`,``)),r=e.shift()?.trim()??``,i=await M(),a=i.trim().length>0?i:e.join(` `).trim();(!r||!t||!a.trim())&&(console.error(`Usage: aikit remember <title> --category <cat> [--tags tag1,tag2]`),process.exit(1));let{curated:o}=await J(),s=await o.remember(r,a,t,n);console.log(`Stored curated entry`),console.log(` Path: ${s.path}`),console.log(` Category: ${t}`),n.length>0&&console.log(` Tags: ${n.join(`, `)}`)}},{name:`forget`,description:`Remove a curated entry`,usage:`aikit forget <path> --reason <reason>`,run:async e=>{let t=A(e,`--reason`,``).trim(),n=e.shift()?.trim()??``;(!n||!t)&&(console.error(`Usage: aikit forget <path> --reason <reason>`),process.exit(1));let{curated:r}=await J(),i=await r.forget(n,t);console.log(`Removed curated entry: ${i.path}`)}},{name:`read`,description:`Read a curated entry`,usage:`aikit read <path>`,run:async e=>{let t=e.shift()?.trim()??``;t||(console.error(`Usage: aikit read <path>`),process.exit(1));let{curated:n}=await J(),r=await n.read(t);console.log(r.title),console.log(`─`.repeat(60)),console.log(`Path: ${r.path}`),console.log(`Category: ${r.category}`),console.log(`Version: ${r.version}`),console.log(`Tags: ${r.tags.length>0?r.tags.join(`, `):`None`}`),console.log(``),console.log(r.content)}},{name:`list`,description:`List curated entries`,usage:`aikit list [--category <cat>] [--tag <tag>]`,run:async e=>{let t=A(e,`--category`,``).trim()||void 0,n=A(e,`--tag`,``).trim()||void 0,{curated:r}=await J(),i=await r.list({category:t,tag:n});if(i.length===0){console.log(`No curated entries found.`);return}console.log(`Curated entries (${i.length})`),console.log(`─`.repeat(60));for(let e of i){console.log(e.path),console.log(` ${e.title}`),console.log(` Category: ${e.category} | Version: ${e.version}`),console.log(` Tags: ${e.tags.length>0?e.tags.join(`, `):`None`}`);let t=e.contentPreview.replace(/\s+/g,` `).trim();t&&console.log(` Preview: ${t}`),console.log(``)}}},{name:`update`,description:`Update a curated entry`,usage:`aikit update <path> --reason <reason>`,run:async e=>{let t=A(e,`--reason`,``).trim(),n=e.shift()?.trim()??``,r=await M();(!n||!t||!r.trim())&&(console.error(`Usage: aikit update <path> --reason <reason>`),process.exit(1));let{curated:i}=await J(),a=await i.update(n,r,t);console.log(`Updated curated entry`),console.log(` Path: ${a.path}`),console.log(` Version: ${a.version}`)}},{name:`compact`,description:`Compress text for context`,usage:`aikit compact <query> [--path <file>] [--max-chars N] [--segmentation paragraph|sentence|line]`,run:async e=>{let t=k(e,`--max-chars`,3e3),n=A(e,`--path`,``).trim()||void 0,r=A(e,`--segmentation`,`paragraph`),i=e.join(` `).trim(),a=n?void 0:await M();(!i||!n&&!a?.trim())&&(console.error(`Usage: aikit compact <query> --path <file> OR cat file | aikit compact <query>`),process.exit(1));let{embedder:o}=await J(),s=await ie(o,{text:a,path:n,query:i,maxChars:t,segmentation:r});console.log(`Compressed ${s.originalChars} chars to ${s.compressedChars} chars`),console.log(`Ratio: ${(s.ratio*100).toFixed(1)}% | Segments: ${s.segmentsKept}/${s.segmentsTotal}`),console.log(``),console.log(s.text)}}],on=[{name:`search`,description:`Search the AI Kit index`,usage:`aikit search <query> [--limit N] [--mode hybrid|semantic|keyword] [--graph-hops 0-3]`,run:async e=>{let t=k(e,`--limit`,5),n=A(e,`--mode`,`hybrid`),r=k(e,`--graph-hops`,0),i=e.join(` `).trim();i||(console.error(`Usage: aikit search <query>`),process.exit(1));let{embedder:a,store:o,graphStore:s}=await J(),c=await a.embedQuery(i),l;if(n===`keyword`)l=await o.ftsSearch(i,{limit:t});else if(n===`semantic`)l=await o.search(c,{limit:t});else{let[e,n]=await Promise.all([o.search(c,{limit:t*2}),o.ftsSearch(i,{limit:t*2}).catch(()=>[])]);l=Ot(e,n).slice(0,t)}if(l.length===0){console.log(`No results found.`);return}for(let{record:e,score:t}of l){console.log(`\n${`─`.repeat(60)}`),console.log(`[${(t*100).toFixed(1)}%] ${e.sourcePath}:${e.startLine}-${e.endLine}`),console.log(` Type: ${e.contentType} | Origin: ${e.origin}`),e.tags.length>0&&console.log(` Tags: ${e.tags.join(`, `)}`),console.log(``);let n=e.content.length>500?`${e.content.slice(0,500)}...`:e.content;console.log(n)}if(console.log(`\n${`─`.repeat(60)}`),console.log(`${l.length} result(s) found.`),r>0&&l.length>0)try{let{graphAugmentSearch:e}=await import(`../../tools/dist/index.js`),t=(await e(s,l.map(e=>({recordId:e.record.id,score:e.score,sourcePath:e.record.sourcePath})),{hops:r,maxPerHit:5})).filter(e=>e.graphContext.nodes.length>0);if(t.length>0){console.log(`\nGraph context (${r} hop${r>1?`s`:``}):\n`);for(let e of t){console.log(` ${e.sourcePath}:`);for(let t of e.graphContext.nodes.slice(0,5))console.log(` → ${t.name} (${t.type})`);for(let t of e.graphContext.edges.slice(0,5))console.log(` → ${t.fromId} --[${t.type}]--> ${t.toId}`)}}}catch(e){console.error(`[graph] augmentation failed: ${e.message}`)}}},{name:`find`,description:`Run federated search across indexed content and files`,usage:`aikit find [query] [--glob <pattern>] [--pattern <regex>] [--limit N]`,run:async e=>{let t=k(e,`--limit`,10),n=A(e,`--glob`,``).trim()||void 0,r=A(e,`--pattern`,``).trim()||void 0,i=e.join(` `).trim()||void 0;!i&&!n&&!r&&(console.error(`Usage: aikit find [query] [--glob <pattern>] [--pattern <regex>] [--limit N]`),process.exit(1));let{embedder:a,store:o}=await J(),s=await fe(a,o,{query:i,glob:n,pattern:r,limit:t});if(s.results.length===0){console.log(`No matches found.`);return}console.log(`Strategies: ${s.strategies.join(`, `)}`),console.log(`Results: ${s.results.length} shown (${s.totalFound} total)`);for(let e of s.results){let t=e.lineRange?`:${e.lineRange.start}-${e.lineRange.end}`:``;console.log(`\n[${e.source}] ${e.path}${t}`),console.log(` Score: ${(e.score*100).toFixed(1)}%`),e.preview&&console.log(` ${e.preview.replace(/\s+/g,` `).trim()}`)}}},{name:`scope-map`,description:`Generate a reading plan for a task`,usage:`aikit scope-map <task> [--max-files N]`,run:async e=>{let t=k(e,`--max-files`,15),n=e.join(` `).trim();n||(console.error(`Usage: aikit scope-map <task> [--max-files N]`),process.exit(1));let{embedder:r,store:i}=await J(),a=await qe(r,i,{task:n,maxFiles:t});console.log(`Task: ${a.task}`),console.log(`Files: ${a.files.length}`),console.log(`Estimated tokens: ${a.totalEstimatedTokens}`),console.log(``),console.log(`Reading order:`);for(let e of a.readingOrder)console.log(` ${e}`);for(let[e,t]of a.files.entries())console.log(`\n${e+1}. ${t.path}`),console.log(` Relevance: ${(t.relevance*100).toFixed(1)}% | Tokens: ${t.estimatedTokens}`),console.log(` Why: ${t.reason}`),t.focusRanges.length>0&&console.log(` Focus: ${ht(t.focusRanges)}`)}},{name:`symbol`,description:`Resolve a symbol definition, imports, and references`,usage:`aikit symbol <name> [--limit N]`,run:async e=>{let t=k(e,`--limit`,20),n=e.join(` `).trim();n||(console.error(`Usage: aikit symbol <name> [--limit N]`),process.exit(1));let{embedder:r,store:i}=await J();Tt(await $e(r,i,{name:n,limit:t}))}},{name:`trace`,description:`Trace forward/backward flow for a symbol or file location`,usage:`aikit trace <start> [--direction forward|backward|both] [--max-depth N]`,run:async e=>{let t=A(e,`--direction`,`both`).trim()||`both`,n=k(e,`--max-depth`,3),r=e.join(` `).trim();(!r||![`forward`,`backward`,`both`].includes(t))&&(console.error(`Usage: aikit trace <start> [--direction forward|backward|both] [--max-depth N]`),process.exit(1));let{embedder:i,store:a}=await J();xt(await tt(i,a,{start:r,direction:t,maxDepth:n}))}},{name:`examples`,description:`Find real code examples of a symbol or pattern`,usage:`aikit examples <query> [--limit N] [--content-type type]`,run:async e=>{let t=k(e,`--limit`,5),n=A(e,`--content-type`,``).trim()||void 0,r=e.join(` `).trim();r||(console.error(`Usage: aikit examples <query> [--limit N] [--content-type type]`),process.exit(1));let{embedder:i,store:a}=await J();St(await me(i,a,{query:r,limit:t,contentType:n}))}},{name:`dead-symbols`,description:`Find exported symbols that appear to be unused`,usage:`aikit dead-symbols [--limit N]`,run:async e=>{let t=k(e,`--limit`,100),{embedder:n,store:r}=await J();Ct(await pe(n,r,{limit:t}))}},{name:`lookup`,description:`Look up indexed content by record ID or source path`,usage:`aikit lookup <id>`,run:async e=>{let t=e.join(` `).trim();t||(console.error(`Usage: aikit lookup <id>`),process.exit(1));let{store:n}=await J(),r=await n.getById(t);if(r){console.log(r.id),console.log(`─`.repeat(60)),console.log(`Path: ${r.sourcePath}`),console.log(`Chunk: ${r.chunkIndex+1}/${r.totalChunks}`),console.log(`Lines: ${r.startLine}-${r.endLine}`),console.log(`Type: ${r.contentType} | Origin: ${r.origin}`),r.tags.length>0&&console.log(`Tags: ${r.tags.join(`, `)}`),console.log(``),console.log(r.content);return}let i=await n.getBySourcePath(t);if(i.length===0){console.log(`No indexed content found for: ${t}`);return}i.sort((e,t)=>e.chunkIndex-t.chunkIndex),console.log(t),console.log(`─`.repeat(60)),console.log(`Chunks: ${i.length} | Type: ${i[0].contentType}`);for(let e of i){let t=e.startLine?` (lines ${e.startLine}-${e.endLine})`:``;console.log(`\nChunk ${e.chunkIndex+1}/${e.totalChunks}${t}`),console.log(e.content)}}}],X=m(v(import.meta.url));function Z(e){let t=e;for(let e=0;e<10;e++){try{let e=h(t,`package.json`);if(l(e)&&JSON.parse(d(e,`utf8`)).name===`@vpxa/aikit`)return t}catch{}let e=m(t);if(e===t)break;t=e}return _(e,`..`,`..`,`..`)}const sn=[{name:`status`,description:`Show AI Kit index status and statistics`,run:async()=>{let{isUserInstalled:e,getGlobalDataDir:t,computePartitionKey:n,listWorkspaces:r}=await import(`../../core/dist/index.js`),{existsSync:i}=await import(`node:fs`),a=process.cwd(),o=e(),s=i(_(a,`.vscode`,`mcp.json`)),c,l;if(o&&s)c=`workspace (overrides user-level for this workspace)`,l=_(a,`.aikit-data`);else if(o){let e=n(a);c=i(_(a,`AGENTS.md`))?`user (workspace scaffolded)`:`user (workspace not scaffolded)`,l=_(t(),e)}else c=`workspace`,l=_(a,`.aikit-data`);if(console.log(`AI Kit Status`),console.log(`─`.repeat(40)),console.log(` Mode: ${c}`),console.log(` Data: ${l}`),o&&!s){let e=r();console.log(` Registry: ${e.length} workspace(s) enrolled`)}try{let{store:e}=await J(),t=await e.getStats(),n=await e.listSourcePaths();console.log(` Records: ${t.totalRecords}`),console.log(` Files: ${t.totalFiles}`),console.log(` Indexed: ${t.lastIndexedAt??`Never`}`),console.log(` Backend: ${t.storeBackend}`),console.log(` Model: ${t.embeddingModel}`),console.log(``),console.log(`Content Types:`);for(let[e,n]of Object.entries(t.contentTypeBreakdown))console.log(` ${e}: ${n}`);if(n.length>0){console.log(``),console.log(`Files (${n.length} total):`);for(let e of n.slice(0,20))console.log(` ${e}`);n.length>20&&console.log(` ... and ${n.length-20} more`)}}catch{console.log(``),console.log(" Index not available — run `aikit reindex` to index this workspace.")}o&&!s&&!i(_(a,`AGENTS.md`))&&(console.log(``),console.log(" Action: Run `npx @vpxa/aikit init` to add AGENTS.md and copilot-instructions.md"))}},{name:`reindex`,description:`Re-index the AI Kit index from configured sources`,usage:`aikit reindex [--full]`,run:async e=>{let t=e.includes(`--full`),{store:n,indexer:r,curated:i,config:a}=await J();console.log(`Indexing sources...`);let o=e=>{e.phase===`chunking`&&e.currentFile&&process.stdout.write(`\r [${e.filesProcessed+1}/${e.filesTotal}] ${e.currentFile}`),e.phase===`done`&&process.stdout.write(`
|
|
15
|
-
`)},s;t?(console.log(`Dropping existing index for full reindex...`),s=await r.reindexAll(a,o)):s=await r.index(a,o),console.log(`Done: ${s.filesProcessed} files, ${s.chunksCreated} chunks in ${(s.durationMs/1e3).toFixed(1)}s`),console.log(`Building FTS index...`),await n.createFtsIndex(),console.log(`Re-indexing curated entries...`);let c=await i.reindexAll();console.log(`Curated: ${c.indexed} entries restored`)}},{name:`serve`,description:`Start the MCP server (stdio or HTTP)`,usage:`aikit serve [--transport stdio|http] [--port N]`,run:async e=>{let t=_(Z(X),`packages`,`server`,`dist`,`index.js`),n=A(e,`--transport`,`stdio`),r=A(e,`--port`,`3210`);try{await U({silent:!0})}catch{}let i=at(t,[],{stdio:n===`stdio`?[`pipe`,`pipe`,`inherit`,`ipc`]:`inherit`,env:{...process.env,AIKIT_TRANSPORT:n,AIKIT_PORT:r}});n===`stdio`&&i.stdin&&i.stdout&&(process.stdin.pipe(i.stdin),i.stdout.pipe(process.stdout)),i.on(`exit`,e=>process.exit(e??0)),process.on(`SIGINT`,()=>i.kill(`SIGINT`)),process.on(`SIGTERM`,()=>i.kill(`SIGTERM`)),await new Promise(()=>{})}},{name:`init`,description:`Initialize AI Kit in the current directory`,usage:`aikit init [--workspace] [--smart] [--force] [--guide]`,run:async e=>{let t=e.includes(`--user`),n=e.includes(`--workspace`),r=e.includes(`--smart`),i=e.includes(`--guide`),a=e.includes(`--force`);if(t&&n&&(console.error(`Cannot use --user and --workspace together.`),process.exit(1)),i){let{guideProject:e}=await import(`./init-
|
|
16
|
-
Suggested next steps:`);for(let e of o.next)console.log(` → ${e.tool}: ${e.reason}`)}}else console.error(o.error?.message??`Audit failed`),process.exitCode=1}},{name:`guide`,description:`Tool discovery — recommend AI Kit tools for a given goal`,usage:`aikit guide <goal> [--max N]`,run:async e=>{let t=e.indexOf(`--max`),n=5;t!==-1&&t+1<e.length&&(n=Number.parseInt(e.splice(t,2)[1],10)||5);let r=e.join(` `).trim();r||(console.error(`Usage: aikit guide <goal> [--max N]`),console.error(`Example: aikit guide "audit this project"`),process.exit(1));let i=ve(r,n);console.log(`Workflow: ${i.workflow}`),console.log(` ${i.description}\n`),console.log(`Recommended tools:`);for(let e of i.tools){let t=e.suggestedArgs?` ${JSON.stringify(e.suggestedArgs)}`:``;console.log(` ${e.order}. ${e.tool} — ${e.reason}${t}`)}i.alternativeWorkflows.length>0&&console.log(`\nAlternatives: ${i.alternativeWorkflows.join(`, `)}`)}},{name:`replay`,description:`Show recent tool invocation audit trail`,usage:`aikit replay [--last N] [--tool <name>] [--source mcp|cli]`,run:async e=>{let t=We({last:Number.parseInt(e[e.indexOf(`--last`)+1],10)||20,tool:e.includes(`--tool`)?e[e.indexOf(`--tool`)+1]:void 0,source:e.includes(`--source`)?e[e.indexOf(`--source`)+1]:void 0});if(t.length===0){console.log(`No replay entries. Activity is logged when tools are invoked.`);return}console.log(`Replay Log (${t.length} entries)\n`);for(let e of t){let t=e.ts.split(`T`)[1]?.split(`.`)[0]??e.ts,n=e.status===`ok`?`✓`:`✗`;console.log(`${t} ${n} ${e.tool} (${e.durationMs}ms) [${e.source}]`),console.log(` in: ${e.input}`),console.log(` out: ${e.output}`)}Ge().catch(()=>{})}},{name:`replay-clear`,description:`Clear the replay audit trail`,run:async()=>{Ue(),console.log(`Replay log cleared.`)}},{name:`dashboard`,description:`Launch web dashboard for knowledge graph visualization`,usage:`aikit dashboard [--port <port>] [--no-open]`,run:async e=>{let t=e.indexOf(`--port`),n=t!==-1&&e[t+1]?Number.parseInt(e[t+1],10):3210,r=Number.isFinite(n)?n:3210,i=e.includes(`--no-open`);console.log(`Starting AI Kit server on port ${r}...`);let{spawn:a}=await import(`node:child_process`),{platform:o}=await import(`node:os`),s=_(Z(X),`packages`,`server`,`dist`,`index.js`),c=a(process.execPath,[s,`--transport`,`http`,`--port`,String(r)],{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env,AIKIT_TRANSPORT:`http`,AIKIT_PORT:String(r)}}),l=`http://localhost:${r}/_dashboard/`,u=`http://localhost:${r}/health`,d=!1;for(let e=0;e<30;e+=1){try{if((await fetch(u)).ok){d=!0;break}}catch{}await new Promise(e=>setTimeout(e,1e3))}if(d||(console.error(`Server failed to start within 30 seconds.`),c.kill(),process.exit(1)),console.log(`AI Kit Dashboard: ${l}`),console.log(`Press Ctrl+C to stop.`),!i){let e=o();e===`win32`?a(`cmd`,[`/c`,`start`,``,l],{stdio:`ignore`,detached:!0}).unref():a(e===`darwin`?`open`:`xdg-open`,[l],{stdio:`ignore`,detached:!0}).unref()}let f=()=>{c.kill(),process.exit(0)};process.on(`SIGINT`,f),process.on(`SIGTERM`,f),await new Promise(e=>{c.on(`exit`,()=>e())})}},{name:`settings`,description:`Launch web UI to manage AI Kit configuration and environment variables`,usage:`aikit settings [--port <port>] [--no-open]`,run:async e=>{let t=e.indexOf(`--port`),n=t!==-1&&e[t+1]?Number.parseInt(e[t+1],10):3210,r=Number.isFinite(n)?n:3210,i=e.includes(`--no-open`);console.log(`Starting AI Kit server on port ${r}...`);let{spawn:a}=await import(`node:child_process`),{platform:o}=await import(`node:os`),s=_(Z(X),`packages`,`server`,`dist`,`index.js`),c=a(process.execPath,[s,`--transport`,`http`,`--port`,String(r)],{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env,AIKIT_TRANSPORT:`http`,AIKIT_PORT:String(r)}}),l=`http://localhost:${r}/settings/`,u=`http://localhost:${r}/health`,d=!1;for(let e=0;e<30;e+=1){try{if((await fetch(u)).ok){d=!0;break}}catch{}await new Promise(e=>setTimeout(e,1e3))}if(d||(console.error(`Server failed to start within 30 seconds.`),c.kill(),process.exit(1)),console.log(`AI Kit Settings: ${l}`),console.log(`Press Ctrl+C to stop.`),!i){let e=o();e===`win32`?a(`cmd`,[`/c`,`start`,``,l],{stdio:`ignore`,detached:!0}).unref():a(e===`darwin`?`open`:`xdg-open`,[l],{stdio:`ignore`,detached:!0}).unref()}let f=()=>{c.kill(),process.exit(0)};process.on(`SIGINT`,f),process.on(`SIGTERM`,f),await new Promise(e=>{c.on(`exit`,()=>e())})}}];function cn(e){let t=e;for(let e=0;e<10;e++){try{let e=h(t,`package.json`);if(l(e)&&JSON.parse(d(e,`utf8`)).name===`@vpxa/aikit`)return t}catch{}let e=m(t);if(e===t)break;t=e}return _(e,`..`,`..`,`..`)}const ln=[{name:`upgrade`,description:`Upgrade AI Kit agents, prompts, and skills to the latest version (user-level and workspace-level)`,usage:`aikit upgrade`,run:async()=>{let{initUser:e}=await import(`./user-B6_6Sk9I.js`).then(e=>e.r);await e({force:!0});let t=process.cwd(),n=l(_(t,`.github`,`.aikit-scaffold.json`)),r=l(_(t,`.github`,`agents`)),i=l(_(t,`.github`,`prompts`)),a=l(_(t,`.claude`,`commands`));if(n||r||i||a){let{initScaffoldOnly:e}=await import(`./init-CeRqVSQt.js`);await e({force:!0})}if(l(_(t,`.github`,`skills`))){let{smartCopySkills:e}=await import(`./scaffold-BB6OrTuA.js`).then(e=>e.a),n=cn(m(v(import.meta.url))),r=JSON.parse(d(_(n,`package.json`),`utf-8`)).version;await e(t,n,[...o],r,!0);let{smartCopyFlows:i}=await import(`./scaffold-BB6OrTuA.js`).then(e=>e.a);await i(t,n,[...s],r,!0)}let{homedir:c}=await import(`node:os`),{rmSync:u}=await import(`node:fs`),f=h(c(),`.aikit`,`cache`,`wasm`);if(l(f))try{u(f,{recursive:!0,force:!0}),console.log(`✓ WASM cache cleared (will re-resolve on next start)`)}catch{console.warn(`⚠ Could not clear WASM cache at`,f)}}}],un=[{name:`workset`,description:`Manage saved file sets`,usage:`aikit workset <action> [name] [--files f1,f2] [--description desc]`,run:async e=>{let t=e.shift()?.trim(),n=N(A(e,`--files`,``)),r=A(e,`--description`,``).trim()||void 0,i=e.shift()?.trim();switch(t||(console.error(`Usage: aikit workset <action> [name] [--files f1,f2] [--description desc]`),console.error(`Actions: save, get, list, delete, add, remove`),process.exit(1)),t){case`save`:{(!i||n.length===0)&&(console.error(`Usage: aikit workset save <name> --files f1,f2 [--description desc]`),process.exit(1));let e=Ke(i,n,{description:r});console.log(`Saved workset: ${e.name}`),I(e);return}case`get`:{i||(console.error(`Usage: aikit workset get <name>`),process.exit(1));let e=he(i);if(!e){console.log(`No workset found: ${i}`);return}I(e);return}case`list`:{let e=Ee();if(e.length===0){console.log(`No worksets saved.`);return}console.log(`Worksets (${e.length})`),console.log(`─`.repeat(60));for(let t of e)I(t),console.log(``);return}case`delete`:{i||(console.error(`Usage: aikit workset delete <name>`),process.exit(1));let e=ce(i);console.log(e?`Deleted workset: ${i}`:`No workset found: ${i}`);return}case`add`:{(!i||n.length===0)&&(console.error(`Usage: aikit workset add <name> --files f1,f2`),process.exit(1));let e=y(i,n);console.log(`Updated workset: ${e.name}`),I(e);return}case`remove`:{(!i||n.length===0)&&(console.error(`Usage: aikit workset remove <name> --files f1,f2`),process.exit(1));let e=Ve(i,n);if(!e){console.log(`No workset found: ${i}`);return}console.log(`Updated workset: ${e.name}`),I(e);return}default:console.error(`Unknown workset action: ${t}`),console.error(`Actions: save, get, list, delete, add, remove`),process.exit(1)}}},{name:`stash`,description:`Persist and retrieve named intermediate values`,usage:`aikit stash <set|get|list|delete|clear> [key] [value]`,run:async e=>{let t=e.shift()?.trim(),n=e.shift()?.trim();switch(t||(console.error(`Usage: aikit stash <set|get|list|delete|clear> [key] [value]`),process.exit(1)),t){case`set`:{n||(console.error(`Usage: aikit stash set <key> <value>`),process.exit(1));let t=e.join(` `),r=t.trim()?``:await M(),i=Qe(n,Et(t||r));console.log(`Stored stash entry: ${i.key}`),console.log(` Type: ${i.type}`),console.log(` Stored: ${i.storedAt}`);return}case`get`:{n||(console.error(`Usage: aikit stash get <key>`),process.exit(1));let e=Xe(n);if(!e){console.log(`No stash entry found: ${n}`);return}console.log(JSON.stringify(e,null,2));return}case`list`:{let e=Ze();if(e.length===0){console.log(`No stash entries saved.`);return}console.log(`Stash entries (${e.length})`),console.log(`─`.repeat(60));for(let t of e)console.log(`${t.key} (${t.type})`),console.log(` Stored: ${t.storedAt}`);return}case`delete`:{n||(console.error(`Usage: aikit stash delete <key>`),process.exit(1));let e=Ye(n);console.log(e?`Deleted stash entry: ${n}`:`No stash entry found: ${n}`);return}case`clear`:{let e=Je();console.log(`Cleared ${e} stash entr${e===1?`y`:`ies`}.`);return}default:console.error(`Unknown stash action: ${t}`),console.error(`Actions: set, get, list, delete, clear`),process.exit(1)}}},{name:`lane`,description:`Manage verified lanes — isolated file copies for parallel exploration`,usage:`aikit lane <create|list|status|diff|merge|discard> [name] [--files f1,f2]`,run:async e=>{let t=e.shift();if((!t||![`create`,`list`,`status`,`diff`,`merge`,`discard`].includes(t))&&(console.error(`Usage: aikit lane <create|list|status|diff|merge|discard> [name] [--files f1,f2]`),process.exit(1)),t===`list`){let e=Ce();if(e.length===0){console.log(`No active lanes.`);return}for(let t of e)console.log(`${t.name} (${t.sourceFiles.length} files, created ${t.createdAt})`);return}let n=e.shift();switch(n||(console.error(`Lane name is required for "${t}".`),process.exit(1)),t){case`create`:{let t=A(e,`--files`,``);t||(console.error(`Usage: aikit lane create <name> --files file1.ts,file2.ts`),process.exit(1));let r=be(n,t.split(`,`).map(e=>e.trim()));console.log(`Lane "${r.name}" created with ${r.sourceFiles.length} files.`);break}case`status`:{let e=Te(n);console.log(`Lane: ${e.name}`),console.log(`Modified: ${e.modified} | Added: ${e.added} | Deleted: ${e.deleted}`);for(let t of e.entries)console.log(` ${t.status.padEnd(10)} ${t.file}`);break}case`diff`:{let e=xe(n);console.log(`Lane: ${e.name} — ${e.modified} modified, ${e.added} added, ${e.deleted} deleted`);for(let t of e.entries)t.diff&&(console.log(`\n--- ${t.file} (${t.status})`),console.log(t.diff));break}case`merge`:{let e=we(n);console.log(`Merged ${e.filesMerged} files from lane "${e.name}".`);for(let t of e.files)console.log(` ${t}`);break}case`discard`:{let e=Se(n);console.log(e?`Lane "${n}" discarded.`:`Lane "${n}" not found.`);break}}}},{name:`queue`,description:`Manage task queues for sequential agent operations`,usage:`aikit queue <create|push|next|done|fail|get|list|clear|delete> [name] [args]`,run:async e=>{let t=e.shift();if((!t||![`create`,`push`,`next`,`done`,`fail`,`get`,`list`,`clear`,`delete`].includes(t))&&(console.error(`Usage: aikit queue <create|push|next|done|fail|get|list|clear|delete> [name] [args]`),process.exit(1)),t===`list`){let e=Re();if(e.length===0){console.log(`No queues.`);return}for(let t of e)console.log(`${t.name} pending:${t.pending} done:${t.done} failed:${t.failed} total:${t.total}`);return}let n=e.shift();switch(n||(console.error(`Queue name is required for "${t}".`),process.exit(1)),t){case`create`:{let e=Ne(n);console.log(`Queue "${e.name}" created.`);break}case`push`:{let t=Be(n,e.join(` `)||`Untitled task`);console.log(`Pushed "${t.title}" (${t.id}) to queue "${n}".`);break}case`next`:{let e=ze(n);console.log(e?`Next: ${e.title} (${e.id})`:`No pending items in queue "${n}".`);break}case`done`:{let t=e.shift();t||(console.error(`Usage: aikit queue done <name> <id>`),process.exit(1));let r=Fe(n,t);console.log(`Marked "${r.item.title}" as done.`);break}case`fail`:{let t=e.shift(),r=e.join(` `)||`Unknown error`;t||(console.error(`Usage: aikit queue fail <name> <id> [error message]`),process.exit(1));let i=Ie(n,t,r);console.log(`Marked "${i.title}" as failed: ${r}`);break}case`get`:{let e=Le(n);if(!e){console.log(`Queue "${n}" not found.`);return}console.log(`Queue: ${e.name} (${e.items.length} items)`);for(let t of e.items){let e=t.error?` — ${t.error}`:``;console.log(` ${t.status.padEnd(12)} ${t.id} ${t.title}${e}`)}break}case`clear`:{let e=Me(n);console.log(`Cleared ${e} completed/failed items from queue "${n}".`);break}case`delete`:{let e=Pe(n);console.log(e?`Queue "${n}" deleted.`:`Queue "${n}" not found.`);break}}}}],Q=[...on,...an,...mt,...Y,...sn,...Zt,...kt,...un,...Xt,...ln,...nn,...Yt];Q.push({name:`help`,description:`Show available commands`,run:async()=>{$()}});async function dn(e){let t=[...e],n=t.shift();if(!n||n===`--help`||n===`-h`){$();return}if(n===`--version`||n===`-v`){let e=_(m(v(import.meta.url)),`..`,`..`,`..`,`package.json`),t=JSON.parse(d(e,`utf-8`));console.log(t.version);return}if(n&&new Set([`--user`,`--workspace`,`--guide`,`--smart`]).has(n)){let e=Q.find(e=>e.name===`init`);if(e){await e.run([n,...t]);return}}let r=Q.find(e=>e.name===n);r||(console.error(`Unknown command: ${n}`),$(),process.exit(1));try{await r.run(t)}finally{let e=rn();e&&await e.store.close()}}function $(){console.log(`@vpxa/aikit — Local-first AI developer toolkit
|
|
15
|
+
`)},s;t?(console.log(`Dropping existing index for full reindex...`),s=await r.reindexAll(a,o)):s=await r.index(a,o),console.log(`Done: ${s.filesProcessed} files, ${s.chunksCreated} chunks in ${(s.durationMs/1e3).toFixed(1)}s`),console.log(`Building FTS index...`),await n.createFtsIndex(),console.log(`Re-indexing curated entries...`);let c=await i.reindexAll();console.log(`Curated: ${c.indexed} entries restored`)}},{name:`serve`,description:`Start the MCP server (stdio or HTTP)`,usage:`aikit serve [--transport stdio|http] [--port N]`,run:async e=>{let t=_(Z(X),`packages`,`server`,`dist`,`index.js`),n=A(e,`--transport`,`stdio`),r=A(e,`--port`,`3210`);try{await U({silent:!0})}catch{}let i=at(t,[],{stdio:n===`stdio`?[`pipe`,`pipe`,`inherit`,`ipc`]:`inherit`,env:{...process.env,AIKIT_TRANSPORT:n,AIKIT_PORT:r}});n===`stdio`&&i.stdin&&i.stdout&&(process.stdin.pipe(i.stdin),i.stdout.pipe(process.stdout)),i.on(`exit`,e=>process.exit(e??0)),process.on(`SIGINT`,()=>i.kill(`SIGINT`)),process.on(`SIGTERM`,()=>i.kill(`SIGTERM`)),await new Promise(()=>{})}},{name:`init`,description:`Initialize AI Kit in the current directory`,usage:`aikit init [--workspace] [--smart] [--force] [--guide]`,run:async e=>{let t=e.includes(`--user`),n=e.includes(`--workspace`),r=e.includes(`--smart`),i=e.includes(`--guide`),a=e.includes(`--force`);if(t&&n&&(console.error(`Cannot use --user and --workspace together.`),process.exit(1)),i){let{guideProject:e}=await import(`./init-BBmNDjFy.js`);await e();return}if(r){let{initSmart:e}=await import(`./init-BBmNDjFy.js`);await e({force:a})}else if(t){let{initUser:e}=await import(`./user-ZDsx66gQ.js`).then(e=>e.r);await e({force:a})}else if(n){let{initProject:e}=await import(`./init-BBmNDjFy.js`);await e({force:a})}else{let{initUser:e}=await import(`./user-ZDsx66gQ.js`).then(e=>e.r);await e({force:a})}}},{name:`check`,description:`Run incremental typecheck and lint`,usage:`aikit check [--cwd <dir>] [--files f1,f2] [--skip-types] [--skip-lint] [--detail efficient|normal|full]`,run:async e=>{let t=A(e,`--cwd`,``).trim()||void 0,n=A(e,`--files`,``),r=A(e,`--detail`,`full`)||`full`,i=n.split(`,`).map(e=>e.trim()).filter(Boolean),a=!1;e.includes(`--skip-types`)&&(e.splice(e.indexOf(`--skip-types`),1),a=!0);let o=!1;e.includes(`--skip-lint`)&&(e.splice(e.indexOf(`--skip-lint`),1),o=!0);let s=await x({cwd:t,files:i.length>0?i:void 0,skipTypes:a,skipLint:o,detail:r});_t(s),s.passed||(process.exitCode=1)}},{name:`health`,description:`Run project health checks on the current directory`,usage:`aikit health [path]`,run:async e=>{let t=ye(e.shift());console.log(`Project Health: ${t.path}`),console.log(`─`.repeat(50));for(let e of t.checks){let t=e.status===`pass`?`+`:e.status===`warn`?`~`:`X`;console.log(` [${t}] ${e.name}: ${e.message}`)}console.log(`─`.repeat(50)),console.log(`Score: ${t.score}% — ${t.summary}`)}},{name:`audit`,description:`Run a unified project audit (structure, deps, patterns, health, dead symbols, check)`,usage:`aikit audit [path] [--checks structure,dependencies,patterns,health,dead_symbols,check,entry_points] [--detail efficient|normal|full]`,run:async e=>{let{store:t,embedder:n}=await J(),r=A(e,`--detail`,`efficient`)||`efficient`,i=A(e,`--checks`,``),a=i?i.split(`,`).map(e=>e.trim()):void 0,o=await b(t,n,{path:e.shift()||`.`,checks:a,detail:r});if(o.ok){if(console.log(o.summary),o.next&&o.next.length>0){console.log(`
|
|
16
|
+
Suggested next steps:`);for(let e of o.next)console.log(` → ${e.tool}: ${e.reason}`)}}else console.error(o.error?.message??`Audit failed`),process.exitCode=1}},{name:`guide`,description:`Tool discovery — recommend AI Kit tools for a given goal`,usage:`aikit guide <goal> [--max N]`,run:async e=>{let t=e.indexOf(`--max`),n=5;t!==-1&&t+1<e.length&&(n=Number.parseInt(e.splice(t,2)[1],10)||5);let r=e.join(` `).trim();r||(console.error(`Usage: aikit guide <goal> [--max N]`),console.error(`Example: aikit guide "audit this project"`),process.exit(1));let i=ve(r,n);console.log(`Workflow: ${i.workflow}`),console.log(` ${i.description}\n`),console.log(`Recommended tools:`);for(let e of i.tools){let t=e.suggestedArgs?` ${JSON.stringify(e.suggestedArgs)}`:``;console.log(` ${e.order}. ${e.tool} — ${e.reason}${t}`)}i.alternativeWorkflows.length>0&&console.log(`\nAlternatives: ${i.alternativeWorkflows.join(`, `)}`)}},{name:`replay`,description:`Show recent tool invocation audit trail`,usage:`aikit replay [--last N] [--tool <name>] [--source mcp|cli]`,run:async e=>{let t=We({last:Number.parseInt(e[e.indexOf(`--last`)+1],10)||20,tool:e.includes(`--tool`)?e[e.indexOf(`--tool`)+1]:void 0,source:e.includes(`--source`)?e[e.indexOf(`--source`)+1]:void 0});if(t.length===0){console.log(`No replay entries. Activity is logged when tools are invoked.`);return}console.log(`Replay Log (${t.length} entries)\n`);for(let e of t){let t=e.ts.split(`T`)[1]?.split(`.`)[0]??e.ts,n=e.status===`ok`?`✓`:`✗`;console.log(`${t} ${n} ${e.tool} (${e.durationMs}ms) [${e.source}]`),console.log(` in: ${e.input}`),console.log(` out: ${e.output}`)}Ge().catch(()=>{})}},{name:`replay-clear`,description:`Clear the replay audit trail`,run:async()=>{Ue(),console.log(`Replay log cleared.`)}},{name:`dashboard`,description:`Launch web dashboard for knowledge graph visualization`,usage:`aikit dashboard [--port <port>] [--no-open]`,run:async e=>{let t=e.indexOf(`--port`),n=t!==-1&&e[t+1]?Number.parseInt(e[t+1],10):3210,r=Number.isFinite(n)?n:3210,i=e.includes(`--no-open`);console.log(`Starting AI Kit server on port ${r}...`);let{spawn:a}=await import(`node:child_process`),{platform:o}=await import(`node:os`),s=_(Z(X),`packages`,`server`,`dist`,`index.js`),c=a(process.execPath,[s,`--transport`,`http`,`--port`,String(r)],{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env,AIKIT_TRANSPORT:`http`,AIKIT_PORT:String(r)}}),l=`http://localhost:${r}/_dashboard/`,u=`http://localhost:${r}/health`,d=!1;for(let e=0;e<30;e+=1){try{if((await fetch(u)).ok){d=!0;break}}catch{}await new Promise(e=>setTimeout(e,1e3))}if(d||(console.error(`Server failed to start within 30 seconds.`),c.kill(),process.exit(1)),console.log(`AI Kit Dashboard: ${l}`),console.log(`Press Ctrl+C to stop.`),!i){let e=o();e===`win32`?a(`cmd`,[`/c`,`start`,``,l],{stdio:`ignore`,detached:!0}).unref():a(e===`darwin`?`open`:`xdg-open`,[l],{stdio:`ignore`,detached:!0}).unref()}let f=()=>{c.kill(),process.exit(0)};process.on(`SIGINT`,f),process.on(`SIGTERM`,f),await new Promise(e=>{c.on(`exit`,()=>e())})}},{name:`settings`,description:`Launch web UI to manage AI Kit configuration and environment variables`,usage:`aikit settings [--port <port>] [--no-open]`,run:async e=>{let t=e.indexOf(`--port`),n=t!==-1&&e[t+1]?Number.parseInt(e[t+1],10):3210,r=Number.isFinite(n)?n:3210,i=e.includes(`--no-open`);console.log(`Starting AI Kit server on port ${r}...`);let{spawn:a}=await import(`node:child_process`),{platform:o}=await import(`node:os`),s=_(Z(X),`packages`,`server`,`dist`,`index.js`),c=a(process.execPath,[s,`--transport`,`http`,`--port`,String(r)],{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env,AIKIT_TRANSPORT:`http`,AIKIT_PORT:String(r)}}),l=`http://localhost:${r}/settings/`,u=`http://localhost:${r}/health`,d=!1;for(let e=0;e<30;e+=1){try{if((await fetch(u)).ok){d=!0;break}}catch{}await new Promise(e=>setTimeout(e,1e3))}if(d||(console.error(`Server failed to start within 30 seconds.`),c.kill(),process.exit(1)),console.log(`AI Kit Settings: ${l}`),console.log(`Press Ctrl+C to stop.`),!i){let e=o();e===`win32`?a(`cmd`,[`/c`,`start`,``,l],{stdio:`ignore`,detached:!0}).unref():a(e===`darwin`?`open`:`xdg-open`,[l],{stdio:`ignore`,detached:!0}).unref()}let f=()=>{c.kill(),process.exit(0)};process.on(`SIGINT`,f),process.on(`SIGTERM`,f),await new Promise(e=>{c.on(`exit`,()=>e())})}}];function cn(e){let t=e;for(let e=0;e<10;e++){try{let e=h(t,`package.json`);if(l(e)&&JSON.parse(d(e,`utf8`)).name===`@vpxa/aikit`)return t}catch{}let e=m(t);if(e===t)break;t=e}return _(e,`..`,`..`,`..`)}const ln=[{name:`upgrade`,description:`Upgrade AI Kit agents, prompts, and skills to the latest version (user-level and workspace-level)`,usage:`aikit upgrade`,run:async()=>{let{initUser:e}=await import(`./user-ZDsx66gQ.js`).then(e=>e.r);await e({force:!0});let t=process.cwd(),n=l(_(t,`.github`,`.aikit-scaffold.json`)),r=l(_(t,`.github`,`agents`)),i=l(_(t,`.github`,`prompts`)),a=l(_(t,`.claude`,`commands`));if(n||r||i||a){let{initScaffoldOnly:e}=await import(`./init-BBmNDjFy.js`);await e({force:!0})}if(l(_(t,`.github`,`skills`))){let{smartCopySkills:e}=await import(`./scaffold-BB6OrTuA.js`).then(e=>e.a),n=cn(m(v(import.meta.url))),r=JSON.parse(d(_(n,`package.json`),`utf-8`)).version;await e(t,n,[...o],r,!0);let{smartCopyFlows:i}=await import(`./scaffold-BB6OrTuA.js`).then(e=>e.a);await i(t,n,[...s],r,!0)}let{homedir:c}=await import(`node:os`),{rmSync:u}=await import(`node:fs`),f=h(c(),`.aikit`,`cache`,`wasm`);if(l(f))try{u(f,{recursive:!0,force:!0}),console.log(`✓ WASM cache cleared (will re-resolve on next start)`)}catch{console.warn(`⚠ Could not clear WASM cache at`,f)}}}],un=[{name:`workset`,description:`Manage saved file sets`,usage:`aikit workset <action> [name] [--files f1,f2] [--description desc]`,run:async e=>{let t=e.shift()?.trim(),n=N(A(e,`--files`,``)),r=A(e,`--description`,``).trim()||void 0,i=e.shift()?.trim();switch(t||(console.error(`Usage: aikit workset <action> [name] [--files f1,f2] [--description desc]`),console.error(`Actions: save, get, list, delete, add, remove`),process.exit(1)),t){case`save`:{(!i||n.length===0)&&(console.error(`Usage: aikit workset save <name> --files f1,f2 [--description desc]`),process.exit(1));let e=Ke(i,n,{description:r});console.log(`Saved workset: ${e.name}`),I(e);return}case`get`:{i||(console.error(`Usage: aikit workset get <name>`),process.exit(1));let e=he(i);if(!e){console.log(`No workset found: ${i}`);return}I(e);return}case`list`:{let e=Ee();if(e.length===0){console.log(`No worksets saved.`);return}console.log(`Worksets (${e.length})`),console.log(`─`.repeat(60));for(let t of e)I(t),console.log(``);return}case`delete`:{i||(console.error(`Usage: aikit workset delete <name>`),process.exit(1));let e=ce(i);console.log(e?`Deleted workset: ${i}`:`No workset found: ${i}`);return}case`add`:{(!i||n.length===0)&&(console.error(`Usage: aikit workset add <name> --files f1,f2`),process.exit(1));let e=y(i,n);console.log(`Updated workset: ${e.name}`),I(e);return}case`remove`:{(!i||n.length===0)&&(console.error(`Usage: aikit workset remove <name> --files f1,f2`),process.exit(1));let e=Ve(i,n);if(!e){console.log(`No workset found: ${i}`);return}console.log(`Updated workset: ${e.name}`),I(e);return}default:console.error(`Unknown workset action: ${t}`),console.error(`Actions: save, get, list, delete, add, remove`),process.exit(1)}}},{name:`stash`,description:`Persist and retrieve named intermediate values`,usage:`aikit stash <set|get|list|delete|clear> [key] [value]`,run:async e=>{let t=e.shift()?.trim(),n=e.shift()?.trim();switch(t||(console.error(`Usage: aikit stash <set|get|list|delete|clear> [key] [value]`),process.exit(1)),t){case`set`:{n||(console.error(`Usage: aikit stash set <key> <value>`),process.exit(1));let t=e.join(` `),r=t.trim()?``:await M(),i=Qe(n,Et(t||r));console.log(`Stored stash entry: ${i.key}`),console.log(` Type: ${i.type}`),console.log(` Stored: ${i.storedAt}`);return}case`get`:{n||(console.error(`Usage: aikit stash get <key>`),process.exit(1));let e=Xe(n);if(!e){console.log(`No stash entry found: ${n}`);return}console.log(JSON.stringify(e,null,2));return}case`list`:{let e=Ze();if(e.length===0){console.log(`No stash entries saved.`);return}console.log(`Stash entries (${e.length})`),console.log(`─`.repeat(60));for(let t of e)console.log(`${t.key} (${t.type})`),console.log(` Stored: ${t.storedAt}`);return}case`delete`:{n||(console.error(`Usage: aikit stash delete <key>`),process.exit(1));let e=Ye(n);console.log(e?`Deleted stash entry: ${n}`:`No stash entry found: ${n}`);return}case`clear`:{let e=Je();console.log(`Cleared ${e} stash entr${e===1?`y`:`ies`}.`);return}default:console.error(`Unknown stash action: ${t}`),console.error(`Actions: set, get, list, delete, clear`),process.exit(1)}}},{name:`lane`,description:`Manage verified lanes — isolated file copies for parallel exploration`,usage:`aikit lane <create|list|status|diff|merge|discard> [name] [--files f1,f2]`,run:async e=>{let t=e.shift();if((!t||![`create`,`list`,`status`,`diff`,`merge`,`discard`].includes(t))&&(console.error(`Usage: aikit lane <create|list|status|diff|merge|discard> [name] [--files f1,f2]`),process.exit(1)),t===`list`){let e=Ce();if(e.length===0){console.log(`No active lanes.`);return}for(let t of e)console.log(`${t.name} (${t.sourceFiles.length} files, created ${t.createdAt})`);return}let n=e.shift();switch(n||(console.error(`Lane name is required for "${t}".`),process.exit(1)),t){case`create`:{let t=A(e,`--files`,``);t||(console.error(`Usage: aikit lane create <name> --files file1.ts,file2.ts`),process.exit(1));let r=be(n,t.split(`,`).map(e=>e.trim()));console.log(`Lane "${r.name}" created with ${r.sourceFiles.length} files.`);break}case`status`:{let e=Te(n);console.log(`Lane: ${e.name}`),console.log(`Modified: ${e.modified} | Added: ${e.added} | Deleted: ${e.deleted}`);for(let t of e.entries)console.log(` ${t.status.padEnd(10)} ${t.file}`);break}case`diff`:{let e=xe(n);console.log(`Lane: ${e.name} — ${e.modified} modified, ${e.added} added, ${e.deleted} deleted`);for(let t of e.entries)t.diff&&(console.log(`\n--- ${t.file} (${t.status})`),console.log(t.diff));break}case`merge`:{let e=we(n);console.log(`Merged ${e.filesMerged} files from lane "${e.name}".`);for(let t of e.files)console.log(` ${t}`);break}case`discard`:{let e=Se(n);console.log(e?`Lane "${n}" discarded.`:`Lane "${n}" not found.`);break}}}},{name:`queue`,description:`Manage task queues for sequential agent operations`,usage:`aikit queue <create|push|next|done|fail|get|list|clear|delete> [name] [args]`,run:async e=>{let t=e.shift();if((!t||![`create`,`push`,`next`,`done`,`fail`,`get`,`list`,`clear`,`delete`].includes(t))&&(console.error(`Usage: aikit queue <create|push|next|done|fail|get|list|clear|delete> [name] [args]`),process.exit(1)),t===`list`){let e=Re();if(e.length===0){console.log(`No queues.`);return}for(let t of e)console.log(`${t.name} pending:${t.pending} done:${t.done} failed:${t.failed} total:${t.total}`);return}let n=e.shift();switch(n||(console.error(`Queue name is required for "${t}".`),process.exit(1)),t){case`create`:{let e=Ne(n);console.log(`Queue "${e.name}" created.`);break}case`push`:{let t=Be(n,e.join(` `)||`Untitled task`);console.log(`Pushed "${t.title}" (${t.id}) to queue "${n}".`);break}case`next`:{let e=ze(n);console.log(e?`Next: ${e.title} (${e.id})`:`No pending items in queue "${n}".`);break}case`done`:{let t=e.shift();t||(console.error(`Usage: aikit queue done <name> <id>`),process.exit(1));let r=Fe(n,t);console.log(`Marked "${r.item.title}" as done.`);break}case`fail`:{let t=e.shift(),r=e.join(` `)||`Unknown error`;t||(console.error(`Usage: aikit queue fail <name> <id> [error message]`),process.exit(1));let i=Ie(n,t,r);console.log(`Marked "${i.title}" as failed: ${r}`);break}case`get`:{let e=Le(n);if(!e){console.log(`Queue "${n}" not found.`);return}console.log(`Queue: ${e.name} (${e.items.length} items)`);for(let t of e.items){let e=t.error?` — ${t.error}`:``;console.log(` ${t.status.padEnd(12)} ${t.id} ${t.title}${e}`)}break}case`clear`:{let e=Me(n);console.log(`Cleared ${e} completed/failed items from queue "${n}".`);break}case`delete`:{let e=Pe(n);console.log(e?`Queue "${n}" deleted.`:`Queue "${n}" not found.`);break}}}}],Q=[...on,...an,...mt,...Y,...sn,...Zt,...kt,...un,...Xt,...ln,...nn,...Yt];Q.push({name:`help`,description:`Show available commands`,run:async()=>{$()}});async function dn(e){let t=[...e],n=t.shift();if(!n||n===`--help`||n===`-h`){$();return}if(n===`--version`||n===`-v`){let e=_(m(v(import.meta.url)),`..`,`..`,`..`,`package.json`),t=JSON.parse(d(e,`utf-8`));console.log(t.version);return}if(n&&new Set([`--user`,`--workspace`,`--guide`,`--smart`]).has(n)){let e=Q.find(e=>e.name===`init`);if(e){await e.run([n,...t]);return}}let r=Q.find(e=>e.name===n);r||(console.error(`Unknown command: ${n}`),$(),process.exit(1));try{await r.run(t)}finally{let e=rn();e&&await e.store.close()}}function $(){console.log(`@vpxa/aikit — Local-first AI developer toolkit
|
|
17
17
|
`),console.log(`Usage: aikit <command> [options]
|
|
18
18
|
`),console.log(`Commands:`);let e=Math.max(...Q.map(e=>e.name.length));for(let t of Q)console.log(` ${t.name.padEnd(e+2)}${t.description}`);console.log(``),console.log(`Options:`),console.log(` --help, -h Show this help`),console.log(` --version, -v Show version`)}export{dn as run};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{c as e,l as t,n,o as r,r as i,t as a}from"./scaffold-BB6OrTuA.js";import{a as o,i as s,n as c,o as l,r as u,t as d}from"./templates-
|
|
1
|
+
import{c as e,l as t,n,o as r,r as i,t as a}from"./scaffold-BB6OrTuA.js";import{a as o,i as s,n as c,o as l,r as u,t as d}from"./templates-BXyPFub1.js";import{appendFileSync as f,existsSync as p,mkdirSync as m,readFileSync as h,unlinkSync as g,writeFileSync as _}from"node:fs";import{basename as v,dirname as y,join as b,resolve as x}from"node:path";import{fileURLToPath as S}from"node:url";import{AIKIT_PATHS as C,EMBEDDING_DEFAULTS as w,isUserInstalled as T}from"../../core/dist/index.js";function E(e){return p(x(e,`.cursor`))?`cursor`:p(x(e,`.claude`))?`claude-code`:p(x(e,`.windsurf`))?`windsurf`:p(x(e,`.zed`))?`zed`:p(x(e,`.idea`))?`intellij`:`copilot`}function D(e){let t=[];return p(x(e,`.cursor`))&&t.push(`cursor`),(p(x(e,`.claude`))||p(x(e,`CLAUDE.md`)))&&t.push(`claude-code`),p(x(e,`.windsurf`))&&t.push(`windsurf`),p(x(e,`.zed`))&&t.push(`zed`),p(x(e,`.idea`))&&t.push(`intellij`),p(x(e,`.gemini`))&&t.push(`gemini-cli`),(p(x(e,`.codex`))||p(x(e,`codex.md`)))&&t.push(`codex-cli`),t.push(`copilot`),[...new Set(t)]}function O(e){return{servers:{[e]:{...s}}}}function k(e){let{type:t,...n}=s;return{mcpServers:{[e]:n}}}function A(e){let{type:t,...n}=s;return{context_servers:{[e]:{...n}}}}const j={scaffoldDir:`general`,writeMcpConfig(e,t){let n=x(e,`.vscode`),r=x(n,`mcp.json`);p(r)||(m(n,{recursive:!0}),_(r,`${JSON.stringify(O(t),null,2)}\n`,`utf-8`),console.log(` Created .vscode/mcp.json`))},writeInstructions(e,t){let n=x(e,`.github`),r=x(n,`copilot-instructions.md`);m(n,{recursive:!0}),_(r,c(v(e),t),`utf-8`),console.log(` Updated .github/copilot-instructions.md`)},writeAgentsMd(e,t){_(x(e,`AGENTS.md`),d(v(e),t),`utf-8`),console.log(` Updated AGENTS.md`)}},M={scaffoldDir:`general`,writeMcpConfig(e,t){let n=x(e,`.mcp.json`);p(n)||(_(n,`${JSON.stringify(k(t),null,2)}\n`,`utf-8`),console.log(` Created .mcp.json`))},writeInstructions(e,t){let n=x(e,`CLAUDE.md`),r=v(e);_(n,`${c(r,t)}\n---\n\n${d(r,t)}`,`utf-8`),console.log(` Updated CLAUDE.md`)},writeAgentsMd(e,t){}},N={scaffoldDir:`general`,writeMcpConfig(e,t){let n=x(e,`.cursor`),r=x(n,`mcp.json`);p(r)||(m(n,{recursive:!0}),_(r,`${JSON.stringify(k(t),null,2)}\n`,`utf-8`),console.log(` Created .cursor/mcp.json`))},writeInstructions(e,t){let n=x(e,`.cursor`,`rules`),r=x(n,`aikit.mdc`);m(n,{recursive:!0});let i=v(e);_(r,`${c(i,t)}\n---\n\n${d(i,t)}`,`utf-8`),console.log(` Updated .cursor/rules/aikit.mdc`);let a=x(n,`kb.mdc`);p(a)&&a!==r&&(g(a),console.log(` Removed legacy .cursor/rules/kb.mdc`))},writeAgentsMd(e,t){}},P={scaffoldDir:`general`,writeMcpConfig(e,t){let n=x(e,`.vscode`),r=x(n,`mcp.json`);p(r)||(m(n,{recursive:!0}),_(r,`${JSON.stringify(O(t),null,2)}\n`,`utf-8`),console.log(` Created .vscode/mcp.json (Windsurf-compatible)`))},writeInstructions(e,t){let n=x(e,`.windsurfrules`),r=v(e);_(n,`${c(r,t)}\n---\n\n${d(r,t)}`,`utf-8`),console.log(` Updated .windsurfrules`)},writeAgentsMd(e,t){}},F={scaffoldDir:`general`,writeMcpConfig(e,t){let n=x(e,`.zed`),r=x(n,`settings.json`);if(m(n,{recursive:!0}),!p(r))_(r,`${JSON.stringify(A(t),null,2)}\n`,`utf-8`),console.log(` Created .zed/settings.json`);else{let e;try{e=JSON.parse(h(r,`utf-8`))}catch{console.warn(` ⚠ .zed/settings.json contains invalid JSON — skipping MCP config merge`);return}e.context_servers?.[t]||(e.context_servers={...e.context_servers,...A(t).context_servers},_(r,`${JSON.stringify(e,null,2)}\n`,`utf-8`),console.log(` Updated .zed/settings.json with context_servers`))}},writeInstructions(e,t){let n=x(e,`.rules`),r=v(e);_(n,`${c(r,t)}\n---\n\n${d(r,t)}`,`utf-8`),console.log(` Updated .rules`)},writeAgentsMd(e,t){}},I={scaffoldDir:`general`,writeMcpConfig(e,t){let n=x(e,`mcp.json`);p(n)||(_(n,`${JSON.stringify(k(t),null,2)}\n`,`utf-8`),console.log(` Created mcp.json`))},writeInstructions(e,t){let n=x(e,`.aiassistant`,`rules`),r=x(n,`aikit.md`);m(n,{recursive:!0});let i=v(e);_(r,`${c(i,t)}\n---\n\n${d(i,t)}`,`utf-8`),console.log(` Updated .aiassistant/rules/aikit.md`)},writeAgentsMd(e,t){}};function L(e){switch(e){case`copilot`:return j;case`claude-code`:return M;case`cursor`:return N;case`windsurf`:return P;case`zed`:return F;case`intellij`:return I;case`gemini-cli`:case`codex-cli`:return j}}const R={serverName:o,sources:[{path:`.`,excludePatterns:[`**/node_modules/**`,`**/dist/**`,`**/build/**`,`**/.git/**`,`**/${C.data}/**`,`**/coverage/**`,`**/*.min.js`,`**/package-lock.json`,`**/pnpm-lock.yaml`]}],indexing:{chunkSize:1500,chunkOverlap:200,minChunkSize:100},embedding:{model:w.model,dimensions:w.dimensions},store:{backend:`sqlite-vec`,path:C.data},curated:{path:C.aiCurated}};function z(e,t){let n=x(e,`aikit.config.json`);return p(n)&&!t?(console.log(`aikit.config.json already exists. Use --force to overwrite.`),!1):(_(n,`${JSON.stringify(R,null,2)}\n`,`utf-8`),console.log(` Created aikit.config.json`),!0)}function B(e){let t=x(e,`.gitignore`),n=[{dir:`${C.data}/`,label:`AI Kit vector store`},{dir:`${C.state}/`,label:`AI Kit session state`},{dir:`${C.restorePoints}/`,label:`Restore points (codemod/rename undo snapshots)`},{dir:`${C.brainstorm}/`,label:`Brainstorming sessions`},{dir:`${C.handoffs}/`,label:`Handoff documents`}];if(p(t)){let e=h(t,`utf-8`),r=n.filter(t=>!e.includes(t.dir));r.length>0&&(f(t,`\n${r.map(e=>`# ${e.label}\n${e.dir}`).join(`
|
|
2
2
|
`)}\n`,`utf-8`),console.log(` Added ${r.map(e=>e.dir).join(`, `)} to .gitignore`))}else _(t,`${n.map(e=>`# ${e.label}\n${e.dir}`).join(`
|
|
3
3
|
`)}\n`,`utf-8`),console.log(` Created .gitignore with AI Kit entries`)}function V(){return R.serverName}const H=[`decisions`,`patterns`,`conventions`,`troubleshooting`];function U(e){let t=x(e,`.ai`,`curated`);p(t)||(m(t,{recursive:!0}),console.log(` Created .ai/curated/`));for(let e of H){let n=x(t,e);p(n)||m(n,{recursive:!0})}console.log(` Created .ai/curated/{${H.join(`,`)}}/`)}function W(e){switch(e){case`zed`:return`zed`;case`intellij`:return`intellij`;case`claude-code`:return`claude-code`;case`gemini-cli`:return`gemini`;case`codex-cli`:return`codex`;default:return`copilot`}}function G(e){let t=e;for(let e=0;e<10;e++){try{let e=b(t,`package.json`);if(p(e)&&JSON.parse(h(e,`utf8`)).name===`@vpxa/aikit`)return t}catch{}let e=y(t);if(e===t)break;t=e}return x(e,`..`,`..`,`..`)}async function K(n){let i=process.cwd();if(!z(i,n.force))return;B(i);let a=V(),o=L(E(i));o.writeMcpConfig(i,a),o.writeInstructions(i,a),o.writeAgentsMd(i,a);let s=G(y(S(import.meta.url))),c=JSON.parse(h(x(s,`package.json`),`utf-8`)).version;await t(i,s,[...l],c,n.force),await r(i,s,[...u],c,n.force);let d=D(i),f=new Set;for(let t of d){let r=W(t);f.has(r)||(f.add(r),await e(i,s,r,c,n.force))}U(i),console.log(`
|
|
4
4
|
AI Kit initialized! Next steps:`),console.log(` aikit reindex Index your codebase`),console.log(` aikit search Search indexed content`),console.log(` aikit serve Start MCP server for IDE integration`),T()&&console.log(`
|
|
@@ -8,7 +8,7 @@ These capabilities are intentionally NOT provided by aikit. Each decision follow
|
|
|
8
8
|
${g().map(({name:e,rationale:t})=>`| ${_(e)} | ${_(t)} |`).join(`
|
|
9
9
|
`)}`}function y(e,t){return`# ${e} — Copilot Instructions
|
|
10
10
|
|
|
11
|
-
This project has an MCP server (\`${t}\`) providing
|
|
11
|
+
This project has an MCP server (\`${t}\`) providing 62 tools for search, analysis, memory, and validation.
|
|
12
12
|
**These tools REPLACE most native IDE tools.** You MUST use them.
|
|
13
13
|
|
|
14
14
|
## Step 0: Load AI Kit Tools
|
|
@@ -16,7 +16,7 @@ This project has an MCP server (\`${t}\`) providing 61 tools for search, analysi
|
|
|
16
16
|
Before doing ANYTHING else, load the AI Kit MCP tools. They are deferred — you must load them first.
|
|
17
17
|
Search for tools matching the server name (e.g. \`aikit\`):
|
|
18
18
|
\`\`\`
|
|
19
|
-
tool_search_tool_regex({ pattern: "aikit" }) // loads all
|
|
19
|
+
tool_search_tool_regex({ pattern: "aikit" }) // loads all 62 AI Kit tools
|
|
20
20
|
\`\`\`
|
|
21
21
|
Once loaded, AI Kit tools appear as \`mcp_<server>_<tool>\` (e.g. \`mcp_aikit_search\`).
|
|
22
22
|
|
|
@@ -36,7 +36,8 @@ Once loaded, AI Kit tools appear as \`mcp_<server>_<tool>\` (e.g. \`mcp_aikit_se
|
|
|
36
36
|
| Manual import/dependency tracing | \`graph({ action: 'neighbors' })\` | Module import graph with cross-package edges |
|
|
37
37
|
| Line counting / wc | \`measure({ path })\` | Lines, functions, cognitive complexity |
|
|
38
38
|
| \`fetch_webpage\` | \`web_fetch({ url })\` | Readability extract + token budget — richer output |
|
|
39
|
-
| Web research / browsing | \`web_search({ query })\` |
|
|
39
|
+
| Web research / browsing | \`web_search({ query })\` | Multi-provider web search — no browser needed |
|
|
40
|
+
| Manual browser automation | \`browser({ action, ... })\` | Owned Chromium with read modes, screenshots, cookies, storage management |
|
|
40
41
|
|
|
41
42
|
**\`read_file\` is ONLY acceptable when you need exact line content FOR EDITING (before \`replace_string_in_file\`).**
|
|
42
43
|
Even then, use \`file_summary\` first to identify which lines to read.
|
|
@@ -157,6 +158,9 @@ Load them: \`tool_search_tool_regex({ pattern: "aikit" })\`
|
|
|
157
158
|
| React patterns | \`react\` | Before React work — component architecture, React 19 APIs, Server Components. |
|
|
158
159
|
| Frontend design | \`frontend-design\` | Before UI/UX work — visual design, typography, color, layout, accessibility. |
|
|
159
160
|
| Multi-agent orchestration | \`multi-agents-development\` | Before delegating to multiple agents — task decomposition, dispatch, review pipelines. |
|
|
161
|
+
| Living documentation | \`docs\` | When creating or updating project documentation — Diátaxis framework, staleness detection. |
|
|
162
|
+
| Repository access recovery | \`repo-access\` | When encountering git auth failures or accessing private/enterprise repos. |
|
|
163
|
+
| Browser automation & auth | \`browser-use\` | When needing browser interaction — login flows, SAML SSO, cookie extraction, form filling, web scraping. Pairs with \`repo-access\`. |
|
|
160
164
|
|
|
161
165
|
### Skills-First Rule (MANDATORY)
|
|
162
166
|
|
|
@@ -189,6 +193,7 @@ Load them: \`tool_search_tool_regex({ pattern: "aikit" })\`
|
|
|
189
193
|
| FORGE | \`forge_ground\`, \`forge_classify\`, \`evidence_map\` | Quality gates for complex tasks |
|
|
190
194
|
| Code Manipulation | \`rename\`, \`codemod\`, \`diff_parse\`, \`data_transform\` | Safe renames, transforms |
|
|
191
195
|
| Web & API | \`web_fetch\`, \`web_search\`, \`http\` | Fetch pages, search web |
|
|
196
|
+
| Browser | \`browser\` | Owned Chromium — page automation, screenshots, cookies, storage |
|
|
192
197
|
| Lanes | \`lane\` | Isolated file copies for parallel exploration |
|
|
193
198
|
| Git & Environment | \`git_context\`, \`process\`, \`watch\`, \`delegate\` | Git info, process management |
|
|
194
199
|
| Utilities | \`regex_test\`, \`encode\`, \`measure\`, \`changelog\`, \`schema_validate\`, \`parse_output\`, \`env\`, \`time\` | Regex, encoding, metrics, output parsing |
|
|
@@ -234,5 +239,5 @@ Both ReactFlow viewers include an **AI Kit** attribution badge (bottom-right). A
|
|
|
234
239
|
|
|
235
240
|
## Full Documentation
|
|
236
241
|
|
|
237
|
-
For complete tool documentation (
|
|
242
|
+
For complete tool documentation (62 tools), workflow chains, search strategies, session protocol, and persistent memory patterns, load the \`aikit\` skill at session start.
|
|
238
243
|
`}export{s as a,c as i,y as n,l as o,u as r,d as s,b as t};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{d as e,f as t,i as n,m as r,s as i,u as a}from"./scaffold-BB6OrTuA.js";import{a as o,i as s,n as c,s as l,t as u}from"./templates-
|
|
1
|
+
import{d as e,f as t,i as n,m as r,s as i,u as a}from"./scaffold-BB6OrTuA.js";import{a as o,i as s,n as c,s as l,t as u}from"./templates-BXyPFub1.js";import{existsSync as d,mkdirSync as f,readFileSync as p,readdirSync as m,rmSync as h,unlinkSync as g,writeFileSync as _}from"node:fs";import{dirname as v,join as y,posix as b,resolve as x,win32 as S}from"node:path";import{fileURLToPath as C}from"node:url";import{mkdir as w,readFile as T,rename as E,unlink as D,writeFile as O}from"node:fs/promises";import{randomUUID as k}from"node:crypto";import{homedir as A}from"node:os";import{execFileSync as j}from"node:child_process";import{getGlobalDataDir as M,saveRegistry as N}from"../../core/dist/index.js";function ee(e){let t=``,n=0,r=e.length;for(;n<r;)if(e[n]===`"`){for(t+=`"`,n++;n<r&&e[n]!==`"`;)e[n]===`\\`&&(t+=e[n++]),n<r&&(t+=e[n++]);n<r&&(t+=e[n++])}else if(e[n]===`/`&&n+1<r&&e[n+1]===`/`)for(n+=2;n<r&&e[n]!==`
|
|
2
2
|
`;)n++;else if(e[n]===`/`&&n+1<r&&e[n+1]===`*`){for(n+=2;n+1<r&&!(e[n]===`*`&&e[n+1]===`/`);)n++;n+=2}else t+=e[n++];return t.replace(/,(\s*[}\]])/g,`$1`)}var P=class{isPlatformSupported(){return this.platforms.includes(process.platform)}async readConfig(e){let t=this.getConfigPath(e);if(!d(t))return{};let n=await T(t,`utf-8`);try{return JSON.parse(ee(n))}catch{throw Error(`Invalid JSON in ${t}. Please fix or remove the file before retrying.`)}}async writeConfig(e,t){let n=this.getConfigPath(t),r=v(n),i=y(r,`.aikit-tmp-${k()}.json`);await w(r,{recursive:!0});try{await O(i,`${JSON.stringify(e,null,2)}\n`,`utf-8`),await E(i,n)}catch(e){try{await D(i)}catch{}throw e}}async registerMcp(e,t,n){let r=await this.readConfig(n);r[this.configKey]||(r[this.configKey]={}),r[this.configKey][e]=t,await this.writeConfig(r,n)}async unregisterMcp(e,t){let n=await this.readConfig(t);n[this.configKey]&&(delete n[this.configKey][e],await this.writeConfig(n,t))}getScaffoldRoot(e){return null}getInstructionsRoot(e){return null}getScaffoldPaths(e){return{agents:null,skills:null,prompts:null,flows:null,commands:null,instructions:null,manifest:null}}buildInstructionContent(e,t){return`${e}\n---\n\n${t}`}},F=class extends P{id=`claude-code`;name=`Claude Code`;family=`claude`;platforms=[`win32`,`darwin`,`linux`];scope=`user`;configKey=`mcpServers`;async detect(){return this.isPlatformSupported()?d(this.getPathModule().resolve(A(),`.claude`)):!1}getConfigPath(){return this.getPathModule().resolve(A(),`.claude`,`mcp.json`)}getScaffoldRoot(){return this.getPathModule().resolve(A(),`.claude`)}getScaffoldPaths(){let e=this.getPathModule(),t=e.resolve(A(),`.claude`);return{agents:e.resolve(t,`agents`),skills:e.resolve(t,`skills`),prompts:null,flows:e.resolve(t,`flows`),commands:e.resolve(t,`commands`),instructions:e.resolve(t,`CLAUDE.md`),manifest:e.resolve(t,`.aikit-scaffold.json`)}}buildInstructionContent(e,t){return`${e}\n---\n\n${t}`}getPathModule(){return process.platform===`win32`?S:b}},te=class extends P{id=`codex-cli`;name=`Codex CLI`;family=`codex`;platforms=[`win32`,`darwin`,`linux`];scope=`user`;configKey=`mcpServers`;async detect(){return this.isPlatformSupported()?d(this.getPathModule().resolve(A(),`.codex`)):!1}getConfigPath(){return this.getPathModule().resolve(A(),`.codex`,`config.json`)}getScaffoldRoot(){return this.getPathModule().resolve(A(),`.codex`)}getScaffoldPaths(){let e=this.getPathModule(),t=e.resolve(A(),`.codex`);return{agents:e.resolve(t,`agents`),skills:e.resolve(t,`skills`),prompts:null,flows:e.resolve(t,`flows`),commands:null,instructions:e.resolve(t,`AGENTS.md`),manifest:e.resolve(t,`.aikit-scaffold.json`)}}getPathModule(){return process.platform===`win32`?S:b}},I=class extends P{family=`copilot`;platforms=[`win32`,`darwin`,`linux`];scope=`user`;hasInstructions=!1;async detect(){if(!this.isPlatformSupported())return!1;let e=this.getConfigDir();if(process.platform===`darwin`){let t=this.getMacAppPath();return d(e)||t!==null&&d(t)}return d(e)}getConfigPath(){return this.getPathModule().resolve(this.getConfigDir(),`mcp.json`)}getScaffoldRoot(){return this.getPathModule().resolve(A(),this.scaffoldBase)}getInstructionsRoot(){let e=this.getInstructionFilePath();return e?this.getPathModule().dirname(e):null}getScaffoldPaths(){let e=this.getPathModule(),t=e.resolve(A(),this.scaffoldBase);return{agents:e.resolve(t,`agents`),skills:e.resolve(t,`skills`),prompts:e.resolve(this.getConfigDir(),`prompts`),flows:e.resolve(t,`flows`),commands:null,instructions:this.getInstructionFilePath(),manifest:e.resolve(t,`.aikit-scaffold.json`)}}getConfigDir(){let e=this.getPathModule(),t=A();if(process.platform===`win32`){let n=process.env.APPDATA??e.resolve(t,`AppData`,`Roaming`);return e.resolve(n,this.configDirName,`User`)}if(process.platform===`darwin`)return e.resolve(t,`Library`,`Application Support`,this.configDirName,`User`);let n=process.env.XDG_CONFIG_HOME??e.resolve(t,`.config`);return e.resolve(n,this.configDirName,`User`)}getMacAppPath(){return null}getInstructionFilePath(){return null}getPathModule(){return process.platform===`win32`?S:b}},ne=class extends P{id=`copilot-cli`;name=`Copilot CLI`;family=`copilot`;platforms=[`win32`,`darwin`,`linux`];scope=`user`;configKey=`mcpServers`;async detect(){return this.isPlatformSupported()?d(x(A(),`.copilot`)):!1}getConfigPath(){return x(A(),`.copilot`,`mcp-config.json`)}async registerMcp(e,t,n){let r={...t,tools:[`*`]},i=await this.readConfig(n);i[this.configKey]||(i[this.configKey]={}),i[this.configKey][e]=r,await this.writeConfig(i,n)}getScaffoldRoot(){return x(A(),`.copilot`)}getInstructionsRoot(){return null}getScaffoldPaths(){let e=x(A(),`.copilot`);return{agents:x(e,`agents`),skills:x(e,`skills`),prompts:null,flows:x(e,`flows`),commands:null,instructions:x(A(),`.github`,`copilot-instructions.md`),manifest:x(e,`.aikit-scaffold.json`)}}},re=class extends I{id=`cursor`;name=`Cursor`;configKey=`mcpServers`;configDirName=`Cursor`;scaffoldBase=`.cursor`;getMacAppPath(){return`/Applications/Cursor.app`}getInstructionFilePath(){return this.getPathModule().resolve(A(),this.scaffoldBase,`rules`,`aikit.mdc`)}},ie=class extends I{id=`cursor-nightly`;name=`Cursor Nightly`;configKey=`mcpServers`;configDirName=`Cursor Nightly`;scaffoldBase=`.cursor`;getMacAppPath(){return`/Applications/Cursor Nightly.app`}getInstructionFilePath(){return this.getPathModule().resolve(A(),this.scaffoldBase,`rules`,`aikit.mdc`)}},L=class e extends P{id=`intellij`;name=`IntelliJ IDEA`;family=`copilot`;platforms=[`win32`,`darwin`,`linux`];scope=`user`;configKey=`servers`;static PRODUCTS=[`IntelliJIdea`,`IdeaIC`,`WebStorm`,`PyCharm`,`PyCharmCE`,`GoLand`,`PhpStorm`,`CLion`,`Rider`,`RubyMine`,`RustRover`,`DataGrip`];async detect(){if(!this.isPlatformSupported())return!1;if(d(this.getCopilotConfigDir()))return!0;let t=this.getJetBrainsBaseDir();if(!d(t))return!1;try{return m(t,{withFileTypes:!0}).some(t=>t.isDirectory()&&e.PRODUCTS.some(e=>t.name.startsWith(e)))}catch{return!1}}getConfigPath(){return x(this.getCopilotConfigDir(),`mcp.json`)}async registerMcp(e,t,n){let r=this.getCopilotConfigDir();await w(r,{recursive:!0});let i=t.args??[],a=i.indexOf(`-e`),o;if(a!==-1&&a+1<i.length){let t=i[a+1],n=x(r,`${e}-launcher.js`);await O(n,t,`utf-8`),o=[...i.slice(0,a),n,...i.slice(a+2)]}else o=[...i];let s={type:`stdio`,...t,args:o};await super.registerMcp(e,s,n)}getScaffoldRoot(e){return null}getInstructionsRoot(e){return null}getScaffoldPaths(e){return{agents:null,skills:null,prompts:null,flows:null,commands:null,instructions:null,manifest:null}}buildInstructionContent(e,t){return t}getCopilotConfigDir(){let e=A();return process.platform===`win32`?x(process.env.LOCALAPPDATA??x(e,`AppData`,`Local`),`github-copilot`,`intellij`):process.platform===`darwin`?x(e,`Library`,`Application Support`,`github-copilot`,`intellij`):x(process.env.XDG_CONFIG_HOME??x(e,`.config`),`github-copilot`,`intellij`)}getJetBrainsBaseDir(){let e=A();return process.platform===`win32`?x(process.env.APPDATA??x(e,`AppData`,`Roaming`),`JetBrains`):process.platform===`darwin`?x(e,`Library`,`Application Support`,`JetBrains`):x(process.env.XDG_CONFIG_HOME??x(e,`.config`),`JetBrains`)}},R=class extends I{id=`trae`;name=`Trae`;configKey=`servers`;configDirName=`Trae`;scaffoldBase=`.trae`;getMacAppPath(){return`/Applications/Trae.app`}getInstructionFilePath(){return this.getPathModule().resolve(A(),this.scaffoldBase,`rules`,`aikit.md`)}},z=class extends I{id=`vscode`;name=`VS Code`;configKey=`servers`;configDirName=`Code`;scaffoldBase=`.copilot`;hasInstructions=!0;getMacAppPath(){return`/Applications/Visual Studio Code.app`}getInstructionFilePath(){return this.hasInstructions?this.getPathModule().resolve(A(),this.scaffoldBase,`instructions`,`copilot-instructions.md`):null}buildInstructionContent(e,t){return`---\napplyTo: "**"\n---\n\n${e}\n---\n\n${t}`}},B=class extends I{id=`vscode-insiders`;name=`VS Code Insiders`;configKey=`servers`;configDirName=`Code - Insiders`;scaffoldBase=`.copilot`;hasInstructions=!0;getMacAppPath(){return`/Applications/Visual Studio Code - Insiders.app`}getInstructionFilePath(){return this.hasInstructions?this.getPathModule().resolve(A(),this.scaffoldBase,`instructions`,`copilot-instructions.md`):null}buildInstructionContent(e,t){return`---\napplyTo: "**"\n---\n\n${e}\n---\n\n${t}`}},V=class extends I{id=`vscodium`;name=`VSCodium`;configKey=`servers`;configDirName=`VSCodium`;scaffoldBase=`.copilot`;hasInstructions=!0;getMacAppPath(){return`/Applications/VSCodium.app`}getInstructionFilePath(){return this.hasInstructions?this.getPathModule().resolve(A(),this.scaffoldBase,`instructions`,`copilot-instructions.md`):null}buildInstructionContent(e,t){return`---\napplyTo: "**"\n---\n\n${e}\n---\n\n${t}`}},H=class extends I{id=`windsurf`;name=`Windsurf`;configKey=`servers`;configDirName=`Windsurf`;scaffoldBase=`.windsurf`;getMacAppPath(){return`/Applications/Windsurf.app`}getInstructionFilePath(){return this.getPathModule().resolve(A(),this.scaffoldBase,`rules`,`aikit.md`)}},U=class extends P{id=`gemini-cli`;name=`Gemini CLI`;family=`gemini`;platforms=[`win32`,`darwin`,`linux`];scope=`user`;configKey=`mcpServers`;async detect(){return this.isPlatformSupported()?d(this.getPathModule().resolve(A(),`.gemini`)):!1}getConfigPath(){return this.getPathModule().resolve(A(),`.gemini`,`settings.json`)}getScaffoldRoot(){return this.getPathModule().resolve(A(),`.gemini`)}getScaffoldPaths(){let e=this.getPathModule(),t=e.resolve(A(),`.gemini`);return{agents:e.resolve(t,`agents`),skills:e.resolve(t,`skills`),prompts:null,flows:e.resolve(t,`flows`),commands:null,instructions:e.resolve(t,`AGENTS.md`),manifest:e.resolve(t,`.aikit-scaffold.json`)}}getPathModule(){return process.platform===`win32`?S:b}},W=class extends P{id=`zed`;name=`Zed`;family=`zed`;platforms=[`win32`,`darwin`,`linux`];scope=`user`;configKey=`context_servers`;async detect(){return this.isPlatformSupported()?d(this.getConfigDir()):!1}getConfigPath(){return this.getPathModule().resolve(this.getConfigDir(),`settings.json`)}async registerMcp(e,t){let{type:n,...r}=t,i={...r,env:r.env??{}};await super.registerMcp(e,i)}getScaffoldRoot(){return this.getConfigDir()}getScaffoldPaths(){let e=this.getPathModule(),t=this.getConfigDir();return{agents:e.resolve(t,`prompts`),skills:null,prompts:e.resolve(t,`prompts`),flows:null,commands:null,instructions:null,manifest:e.resolve(t,`.aikit-scaffold.json`)}}getConfigDir(){let e=this.getPathModule();return process.platform===`win32`?e.resolve(process.env.APPDATA||A(),`Zed`):e.resolve(A(),`.config`,`zed`)}getPathModule(){return process.platform===`win32`?S:b}};const G=[new z,new B,new V,new re,new ie,new H,new R,new ne,new L,new F,new U,new te,new W];function K(){return[...G]}async function q(e){let t=e?.scope?G.filter(t=>t.scope===e.scope):G;return(await Promise.allSettled(t.map(async e=>await e.detect()?e:null))).flatMap(e=>e.status!==`fulfilled`||e.value===null?[]:[e.value])}var J=r({initUser:()=>oe,installGlobalScaffold:()=>$,resolveMcpServerEntry:()=>X,writeVscodeSettings:()=>Q});function Y(e){let t=e;for(let e=0;e<10;e++){try{let e=y(t,`package.json`);if(d(e)&&JSON.parse(p(e,`utf8`)).name===`@vpxa/aikit`)return t}catch{}let e=v(t);if(e===t)break;t=e}return x(e,`..`,`..`,`..`)}function X(){let e={command:s.command,args:s.args?[...s.args]:void 0,type:s.type};if(process.platform!==`win32`){let t=process.env.PATH;t&&(e.env={PATH:t});try{let t=j(`which`,[`node`],{encoding:`utf-8`,timeout:3e3}).trim();t&&d(t)&&(e.command=t)}catch{}}return e}const Z=new Set([`VS Code`,`VS Code Insiders`,`VSCodium`]);function Q(e,t=!1){if(!Z.has(e.name))return;let n=x(v(e.getConfigPath()),`settings.json`),r={};if(d(n))try{let e=p(n,`utf-8`);r=JSON.parse(e)}catch{console.log(` ${e.name}: skipped settings.json (invalid JSON)`);return}let i=!1;for(let[e,n]of Object.entries(l))if(typeof n==`object`&&n){let t=typeof r[e]==`object`&&r[e]!==null?r[e]:{},a={...t,...n};JSON.stringify(a)!==JSON.stringify(t)&&(r[e]=a,i=!0)}else (t||!(e in r))&&(r[e]=n,i=!0);i&&(_(n,`${JSON.stringify(r,null,2)}\n`,`utf-8`),console.log(` ${e.name}: updated settings.json`))}async function $(r,o,s,l,p=!1){let m=new Map;for(let e of o)e.getScaffoldRoot()!==null&&m.set(e.id,e);if(o.some(e=>Z.has(e.name))){let e=K().find(e=>e.id===`copilot-cli`);e&&m.set(e.id,e)}if(m.size===0){console.log(` No IDEs with global scaffold support detected.`);return}let g=await n(r,`copilot`),y=new Map;for(let e of g){let t=e.path.indexOf(`/`);if(t===-1)continue;let n=e.path.substring(0,t);if(n!==`agents`&&n!==`prompts`)continue;let r=y.get(n)??[];r.push({path:e.path.substring(t+1),content:e.content}),y.set(n,r)}let b=await n(r,`skills`),S=new Set;for(let e of b){let t=e.path.indexOf(`/`);t!==-1&&S.add(e.path.substring(0,t))}let C=await n(r,`flows`),w=new Set;for(let e of C){let t=e.path.indexOf(`/`);t!==-1&&w.add(e.path.substring(0,t))}let T=await n(r,`claude-code`),E=new Set,D=new Set,O=new Set,k=(n,r,o)=>{let s=y.get(o);if(!n||!r||!s||s.length===0)return;let c=`${o}:${r}:${n}`;if(E.has(c))return;E.add(c);let u=e(r)??a(l);u.version=l,i(s,n,u,o,p),t(r,u),O.add(v(r))},A=(n,r,o,s)=>{if(!n||!r||s.length===0)return;let c=`${o}:${r}:${n}`;if(E.has(c))return;if(E.add(c),o===`flows`&&!D.has(n)){for(let e of w){let t=x(n,e,`skills`);d(t)&&(h(t,{recursive:!0,force:!0}),console.log(` ${v(r)}: migrated ${e} flow to steps/ layout`))}D.add(n)}let u=e(r)??a(l);u.version=l,i(s,n,u,o,p),t(r,u),O.add(v(r))};for(let e of m.values()){let t=e.getScaffoldPaths();k(t.agents,t.manifest,`agents`),k(t.prompts,t.manifest,`prompts`),A(t.skills,t.manifest,`skills`,b),A(t.flows,t.manifest,`flows`,C),A(t.commands,t.manifest,`commands`,T)}for(let e of O)console.log(` ${e}: scaffold updated (${S.size} skills)`);let j=new Set,M=c(`aikit`,s),N=u(`aikit`,s);for(let e of m.values()){let t=e.getScaffoldPaths().instructions;!t||j.has(t)||(f(v(t),{recursive:!0}),_(t,e.buildInstructionContent(M,N),`utf-8`),j.add(t))}j.size>0&&console.log(` Instruction files: ${[...j].join(`, `)}`)}function ae(e){let t=[];for(let n of e){let e=n.getScaffoldRoot();if(e)if(Z.has(n.name)){let r=n.getInstructionsRoot()??e;t.push(x(r,`kb.instructions.md`)),t.push(x(r,`aikit.instructions.md`))}else n.name===`Cursor`||n.name===`Cursor Nightly`?t.push(x(e,`rules`,`kb.mdc`)):n.name===`Windsurf`&&t.push(x(e,`rules`,`kb.md`))}for(let e of t)d(e)&&(g(e),console.log(` Removed legacy file: ${e}`))}async function oe(e){let t=o,n=Y(v(C(import.meta.url))),r=JSON.parse(p(x(n,`package.json`),`utf-8`)).version;console.log(`Initializing @vpxa/aikit v${r}...\n`);let i=M();f(i,{recursive:!0}),console.log(` Global data store: ${i}`),N({version:1,workspaces:{}}),console.log(` Created registry.json`);let a=await q({scope:`user`});if(a.length===0)console.log(`
|
|
3
3
|
No supported IDEs detected. You can manually add the MCP server config.`);else{console.log(`\n Detected ${a.length} IDE(s):`);let n=X();for(let e of a)try{await e.registerMcp(t,n),console.log(` ${e.name}: configured ${t}`)}catch(t){console.log(` ${e.name}: failed to configure (${t.message})`)}for(let t of a)Q(t,e.force)}console.log(`
|
|
4
4
|
Installing scaffold files:`),await $(n,a,t,r,e.force),ae(a),console.log(`
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{t as e}from"./curated-manager-BkSgtNC2.js";import{readFileSync as t}from"node:fs";import{dirname as n,resolve as r}from"node:path";import{fileURLToPath as i,pathToFileURL as a}from"node:url";import{parseArgs as o}from"node:util";import{createLogger as s,serializeError as c}from"../../core/dist/index.js";const l=n(i(import.meta.url)),u=(()=>{try{let e=r(l,`..`,`..`,`..`,`package.json`);return JSON.parse(t(e,`utf-8`)).version??`0.0.0`}catch{return`0.0.0`}})(),d=s(`server`);function f(){return process.env.AIKIT_TRANSPORT?process.env.AIKIT_TRANSPORT:process.stdin.isTTY?`http`:`stdio`}const{values:p}=(()=>{let e=process.argv[1];if(!e)return!1;try{return import.meta.url===a(e).href}catch{return!1}})()?o({allowPositionals:!0,options:{transport:{type:`string`,default:f()},port:{type:`string`,default:process.env.AIKIT_PORT??`3210`}}}):{values:{transport:f(),port:process.env.AIKIT_PORT??`3210`}};async function m(){if(process.on(`unhandledRejection`,e=>{d.error(`Unhandled rejection`,c(e))}),process.on(`uncaughtException`,e=>{d.error(`Uncaught exception — exiting`,c(e)),process.exit(1)}),d.info(`Starting MCP AI Kit server`,{version:u}),p.transport===`http`){let[{default:e},{loadConfig:t,resolveIndexMode:n},{registerDashboardRoutes:r,resolveDashboardDir:i},{registerSettingsRoutes:a,resolveSettingsDir:o},{createSettingsRouter:s}]=await Promise.all([import(`express`),import(`./config-D4z6-EcI.js`),import(`./dashboard-static-BfIe0Si1.js`),import(`./settings-static-BosGZSPf.js`),import(`./routes-gbC5Wmr9.js`)]),l=t();d.info(`Config loaded`,{sourceCount:l.sources.length,storePath:l.store.path});let u=e();u.use(e.json());let f=Number(p.port);u.use((e,t,n)=>{if(t.setHeader(`Access-Control-Allow-Origin`,process.env.AIKIT_CORS_ORIGIN??`http://localhost:${f}`),t.setHeader(`Access-Control-Allow-Methods`,`GET, POST, PUT, PATCH, DELETE, OPTIONS`),t.setHeader(`Access-Control-Allow-Headers`,`Content-Type, Authorization`),e.method===`OPTIONS`){t.status(204).end();return}n()}),r(u,i(),d);let m=new Date().toISOString();u.use(`/settings/api`,s({log:d,mcpInfo:()=>({transport:`http`,port:f,pid:process.pid,startedAt:m})})),a(u,o(),d),u.get(`/health`,(e,t)=>{t.json({status:`ok`})});let h=!1,g=null,_=null,v=null,y=Promise.resolve();u.post(`/mcp`,async(e,t)=>{if(!h||!_||!v){t.status(503).json({jsonrpc:`2.0`,error:{code:-32603,message:`Server initializing — please retry in a few seconds`},id:null});return}let n=y,r;y=new Promise(e=>{r=e}),await n;try{let n=new v({sessionIdGenerator:void 0});await _.connect(n),await n.handleRequest(e,t,e.body),n.close()}catch(e){if(d.error(`MCP handler error`,c(e)),!t.headersSent){let n=e instanceof Error?e.message:String(e),r=n.includes(`Not Acceptable`);t.status(r?406:500).json({jsonrpc:`2.0`,error:{code:r?-32e3:-32603,message:r?n:`Internal server error`},id:null})}}finally{r()}}),u.get(`/mcp`,(e,t)=>{t.writeHead(405).end(JSON.stringify({jsonrpc:`2.0`,error:{code:-32e3,message:`Method not allowed.`},id:null}))}),u.delete(`/mcp`,(e,t)=>{t.writeHead(405).end(JSON.stringify({jsonrpc:`2.0`,error:{code:-32e3,message:`Method not allowed.`},id:null}))});let b=u.listen(f,`127.0.0.1`,()=>{d.info(`MCP server listening`,{url:`http://127.0.0.1:${f}/mcp`,port:f}),setTimeout(async()=>{try{let[{createLazyServer:e,ALL_TOOL_NAMES:t},{StreamableHTTPServerTransport:r},{checkForUpdates:i,autoUpgradeScaffold:a}]=await Promise.all([import(`./server-
|
|
1
|
+
import{t as e}from"./curated-manager-BkSgtNC2.js";import{readFileSync as t}from"node:fs";import{dirname as n,resolve as r}from"node:path";import{fileURLToPath as i,pathToFileURL as a}from"node:url";import{parseArgs as o}from"node:util";import{createLogger as s,serializeError as c}from"../../core/dist/index.js";const l=n(i(import.meta.url)),u=(()=>{try{let e=r(l,`..`,`..`,`..`,`package.json`);return JSON.parse(t(e,`utf-8`)).version??`0.0.0`}catch{return`0.0.0`}})(),d=s(`server`);function f(){return process.env.AIKIT_TRANSPORT?process.env.AIKIT_TRANSPORT:process.stdin.isTTY?`http`:`stdio`}const{values:p}=(()=>{let e=process.argv[1];if(!e)return!1;try{return import.meta.url===a(e).href}catch{return!1}})()?o({allowPositionals:!0,options:{transport:{type:`string`,default:f()},port:{type:`string`,default:process.env.AIKIT_PORT??`3210`}}}):{values:{transport:f(),port:process.env.AIKIT_PORT??`3210`}};async function m(){if(process.on(`unhandledRejection`,e=>{d.error(`Unhandled rejection`,c(e))}),process.on(`uncaughtException`,e=>{d.error(`Uncaught exception — exiting`,c(e)),process.exit(1)}),d.info(`Starting MCP AI Kit server`,{version:u}),p.transport===`http`){let[{default:e},{loadConfig:t,resolveIndexMode:n},{registerDashboardRoutes:r,resolveDashboardDir:i},{registerSettingsRoutes:a,resolveSettingsDir:o},{createSettingsRouter:s}]=await Promise.all([import(`express`),import(`./config-D4z6-EcI.js`),import(`./dashboard-static-BfIe0Si1.js`),import(`./settings-static-BosGZSPf.js`),import(`./routes-gbC5Wmr9.js`)]),l=t();d.info(`Config loaded`,{sourceCount:l.sources.length,storePath:l.store.path});let u=e();u.use(e.json());let f=Number(p.port);u.use((e,t,n)=>{if(t.setHeader(`Access-Control-Allow-Origin`,process.env.AIKIT_CORS_ORIGIN??`http://localhost:${f}`),t.setHeader(`Access-Control-Allow-Methods`,`GET, POST, PUT, PATCH, DELETE, OPTIONS`),t.setHeader(`Access-Control-Allow-Headers`,`Content-Type, Authorization`),e.method===`OPTIONS`){t.status(204).end();return}n()}),r(u,i(),d);let m=new Date().toISOString();u.use(`/settings/api`,s({log:d,mcpInfo:()=>({transport:`http`,port:f,pid:process.pid,startedAt:m})})),a(u,o(),d),u.get(`/health`,(e,t)=>{t.json({status:`ok`})});let h=!1,g=null,_=null,v=null,y=Promise.resolve();u.post(`/mcp`,async(e,t)=>{if(!h||!_||!v){t.status(503).json({jsonrpc:`2.0`,error:{code:-32603,message:`Server initializing — please retry in a few seconds`},id:null});return}let n=y,r;y=new Promise(e=>{r=e}),await n;try{let n=new v({sessionIdGenerator:void 0});await _.connect(n),await n.handleRequest(e,t,e.body),n.close()}catch(e){if(d.error(`MCP handler error`,c(e)),!t.headersSent){let n=e instanceof Error?e.message:String(e),r=n.includes(`Not Acceptable`);t.status(r?406:500).json({jsonrpc:`2.0`,error:{code:r?-32e3:-32603,message:r?n:`Internal server error`},id:null})}}finally{r()}}),u.get(`/mcp`,(e,t)=>{t.writeHead(405).end(JSON.stringify({jsonrpc:`2.0`,error:{code:-32e3,message:`Method not allowed.`},id:null}))}),u.delete(`/mcp`,(e,t)=>{t.writeHead(405).end(JSON.stringify({jsonrpc:`2.0`,error:{code:-32e3,message:`Method not allowed.`},id:null}))});let b=u.listen(f,`127.0.0.1`,()=>{d.info(`MCP server listening`,{url:`http://127.0.0.1:${f}/mcp`,port:f}),setTimeout(async()=>{try{let[{createLazyServer:e,ALL_TOOL_NAMES:t},{StreamableHTTPServerTransport:r},{checkForUpdates:i,autoUpgradeScaffold:a}]=await Promise.all([import(`./server-3YlZan29.js`),import(`@modelcontextprotocol/sdk/server/streamableHttp.js`),import(`./version-check-Bj07vc5x.js`)]);i(),a();let o=n(l),s=e(l,o);_=s.server,v=r,h=!0,d.info(`MCP server configured (lazy — AI Kit initializing in background)`,{toolCount:t.length,resourceCount:2}),s.startInit(),o===`auto`?s.ready.then(async()=>{try{let e=l.sources.map(e=>e.path).join(`, `);d.info(`Running initial index`,{sourcePaths:e}),await s.runInitialIndex(),d.info(`Initial index complete`)}catch(e){d.error(`Initial index failed; will retry on aikit_reindex`,c(e))}}).catch(e=>d.error(`AI Kit init or indexing failed`,c(e))):o===`smart`?s.ready.then(async()=>{try{if(!s.aikit)throw Error(`AI Kit components are not available after initialization`);let{SmartIndexScheduler:e}=await import(`../../indexer/dist/index.js`),t=new e(s.aikit.indexer,l,s.aikit.store),n=s.aikit.store;g=t,t.start(),n.onBeforeClose&&n.onBeforeClose(()=>t.stop()),s.setSmartScheduler(t),d.info(`Smart index scheduler started (HTTP mode)`)}catch(e){d.error(`Failed to start smart index scheduler`,c(e))}}).catch(e=>d.error(`AI Kit initialization failed`,c(e))):(s.ready.catch(e=>d.error(`AI Kit initialization failed`,c(e))),d.info(`Initial full indexing skipped in HTTP mode`,{indexMode:o}))}catch(e){d.error(`Failed to load server modules`,c(e))}},100)}),x=async e=>{d.info(`Shutdown signal received`,{signal:e}),g?.stop(),b.close(),_&&await _.close(),process.exit(0)};process.on(`SIGINT`,()=>x(`SIGINT`)),process.on(`SIGTERM`,()=>x(`SIGTERM`))}else{let[{loadConfig:e,reconfigureForWorkspace:t,resolveIndexMode:n},{createLazyServer:r},{checkForUpdates:a,autoUpgradeScaffold:o},{RootsListChangedNotificationSchema:s}]=await Promise.all([import(`./config-D4z6-EcI.js`),import(`./server-3YlZan29.js`),import(`./version-check-Bj07vc5x.js`),import(`@modelcontextprotocol/sdk/types.js`)]),l=e();d.info(`Config loaded`,{sourceCount:l.sources.length,storePath:l.store.path}),a(),o();let u=n(l),f=r(l,u),{server:p,startInit:m,ready:h,runInitialIndex:g}=f,{StdioServerTransport:_}=await import(`@modelcontextprotocol/sdk/server/stdio.js`),v=new _;await p.connect(v),d.info(`MCP server started`,{transport:`stdio`});let y=e=>{if(e.length===0)return!1;let n=e[0].uri,r=n.startsWith(`file://`)?i(n):n;return d.info(`MCP roots resolved`,{rootUri:n,rootPath:r,rootCount:e.length}),t(l,r),l.allRoots=e.map(e=>{let t=e.uri;return t.startsWith(`file://`)?i(t):t}),!0},b=!1;try{b=y((await p.server.listRoots()).roots),b||d.info(`No MCP roots yet; waiting for roots/list_changed notification`)}catch(e){d.warn(`MCP roots/list not supported by client; using cwd fallback`,{cwd:process.cwd(),...c(e)}),b=!0}b||=await new Promise(e=>{let t=setTimeout(()=>{d.warn(`Timed out waiting for MCP roots/list_changed; using cwd fallback`,{cwd:process.cwd()}),e(!1)},5e3);p.server.setNotificationHandler(s,async()=>{clearTimeout(t);try{e(y((await p.server.listRoots()).roots))}catch(t){d.warn(`roots/list retry failed after notification`,c(t)),e(!1)}})}),m();let x=null,S=()=>{x&&clearTimeout(x),x=setTimeout(async()=>{d.info(`Auto-shutdown: no activity for 30 minutes — shutting down gracefully`);try{let e=f.aikit;e&&await Promise.all([e.embedder.shutdown?.().catch(()=>{})??Promise.resolve(),e.graphStore.close().catch(()=>{}),e.store.close().catch(()=>{})])}catch{}process.exit(0)},18e5),x.unref&&x.unref()};S(),process.stdin.on(`data`,()=>S()),h.catch(e=>{d.error(`Initialization failed — server will continue with limited tools`,c(e))}),u===`auto`?g().catch(e=>d.error(`Initial index failed`,c(e))):u===`smart`?h.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,l,f.aikit.store),n=f.aikit.store;t.start(),n.onBeforeClose&&n.onBeforeClose(()=>t.stop()),f.setSmartScheduler(t),d.info(`Smart index scheduler started (stdio mode)`)}catch(e){d.error(`Failed to start smart index scheduler`,c(e))}}).catch(e=>d.error(`AI Kit init failed for smart scheduler`,c(e))):d.warn(`Initial full indexing skipped; use aikit_reindex to index manually`,{indexMode:u})}}m().catch(e=>{d.error(`Fatal error`,c(e)),process.exit(1)});export{e as CuratedKnowledgeManager};
|