@vpxa/aikit 0.1.295 → 0.1.297
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/bin/aikit.mjs +27 -2
- package/package.json +1 -1
- package/packages/blocks-core/dist/index.mjs +54 -36
- package/packages/cli/dist/index.js +18 -18
- package/packages/cli/dist/{init-DWIr_CT8.js → init-WmQoeitD.js} +1 -1
- package/packages/cli/dist/{templates-Cc3Rn_zv.js → templates-BQ1J4HzY.js} +13 -13
- package/packages/present/dist/index.html +39 -22
- package/packages/server/dist/bin.js +3 -3
- package/packages/server/dist/{curated-manager-C5uOPept.js → curated-manager-i5QA4c79.js} +2 -2
- package/packages/server/dist/index.d.ts +30 -3
- package/packages/server/dist/index.js +1 -1
- package/packages/server/dist/promotion-DmwIVl0c.js +2 -0
- package/packages/server/dist/promotion-bQutAIz-.js +3 -0
- package/packages/server/dist/{server-CyERdqK0.js → server-BOvlXO_K.js} +178 -177
- package/packages/server/dist/{server-BRinO5Fx.js → server-fs4l4wco.js} +178 -177
- package/packages/server/viewers/canvas.html +85 -68
- package/packages/server/viewers/report-template.html +21 -4
- package/packages/server/viewers/tour-viewer.html +25 -8
- package/packages/store/dist/index.d.ts +3 -3
- package/packages/store/dist/index.js +35 -35
- package/scaffold/definitions/mcp-entry.json +1 -1
- package/scaffold/dist/definitions/mcp-entry.json +1 -1
- package/scaffold/dist/definitions/skills/c4-architecture.mjs +1 -1
- package/scaffold/dist/definitions/skills/docs.mjs +1 -1
- package/scaffold/dist/definitions/skills/present.mjs +1 -1
- package/packages/server/dist/promotion-CJFYv4Ye.js +0 -3
- package/packages/server/dist/promotion-D9anNXv8.js +0 -2
|
@@ -1,19 +1,19 @@
|
|
|
1
|
-
import{d as e,f as t,i as n,p as r,s as i,u as a}from"./scaffold-BNPHP-QC.js";import{A as o,C as s,D as c,E as l,F as u,I as d,
|
|
2
|
-
Types: structure, deps, symbols, patterns, entry-points, blast-radius, diagram`);let{BlastRadiusAnalyzer:r,DependencyAnalyzer:i,DiagramGenerator:a,EntryPointAnalyzer:o,PatternAnalyzer:s,StructureAnalyzer:c,SymbolAnalyzer:l}=await import(`../../analyzers/dist/index.js`),u=
|
|
3
|
-
`);let s=await t({path:a,mode:r,outDir:i??o.onboardDir});for(let e of s.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: ${s.totalDurationMs}ms`),s.outDir&&console.log(`Output written to: ${s.outDir}`)}}],mn=[{name:`parse-output`,description:`Parse build or tool output from stdin`,usage:`aikit parse-output [--tool tsc|vitest|biome|git-status]`,run:async e=>{let t=
|
|
4
|
-
`;)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 H=class{isPlatformSupported(){return this.platforms.includes(process.platform)}async readConfig(e){let t=this.getConfigPath(e);if(!C(t))return{};let n=await Ve(t,`utf-8`);try{return JSON.parse(wn(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=k(n),i=A(r,`.aikit-tmp-${cn()}.json`);await Be(r,{recursive:!0});try{await Ge(i,`${JSON.stringify(e,null,2)}\n`,`utf-8`),await He(i,n)}catch(e){try{await We(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,hooks:null}}buildInstructionContent(e,t){return`${e}\n---\n\n${t}`}},Tn=class extends H{id=`claude-code`;name=`Claude Code`;family=`claude`;platforms=[`win32`,`darwin`,`linux`];scope=`user`;configKey=`mcpServers`;async detect(){return this.isPlatformSupported()?C(this.getPathModule().resolve(L(),`.claude`)):!1}getConfigPath(){return this.getPathModule().resolve(L(),`.claude`,`mcp.json`)}getScaffoldRoot(){return this.getPathModule().resolve(L(),`.claude`)}getScaffoldPaths(){let e=this.getPathModule(),t=e.resolve(L(),`.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`),hooks:null}}buildInstructionContent(e,t){return`${e}\n---\n\n${t}`}getPathModule(){return process.platform===`win32`?N:j}},En=class extends H{id=`codex-cli`;name=`Codex CLI`;family=`codex`;platforms=[`win32`,`darwin`,`linux`];scope=`user`;configKey=`mcpServers`;async detect(){return this.isPlatformSupported()?C(this.getPathModule().resolve(L(),`.codex`)):!1}getConfigPath(){return this.getPathModule().resolve(L(),`.codex`,`config.json`)}getScaffoldRoot(){return this.getPathModule().resolve(L(),`.codex`)}getScaffoldPaths(){let e=this.getPathModule(),t=e.resolve(L(),`.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`),hooks:null}}getPathModule(){return process.platform===`win32`?N:j}},U=class extends H{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 C(e)||t!==null&&C(t)}return C(e)}getConfigPath(){return this.getPathModule().resolve(this.getConfigDir(),`mcp.json`)}getScaffoldRoot(){return this.getPathModule().resolve(L(),this.scaffoldBase)}getInstructionsRoot(){let e=this.getInstructionFilePath();return e?this.getPathModule().dirname(e):null}getScaffoldPaths(){let e=this.getPathModule(),t=e.resolve(L(),this.scaffoldBase);return{agents:e.resolve(t,`agents`),skills:e.resolve(t,`skills`),prompts:e.resolve(this.getConfigDir(),`prompts`),flows:e.resolve(t,`flows`),hooks:e.resolve(t,`hooks`),commands:null,instructions:this.getInstructionFilePath(),manifest:e.resolve(t,`.aikit-scaffold.json`)}}getConfigDir(){let e=this.getPathModule(),t=L();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`?N:j}},Dn=class extends H{id=`copilot-cli`;name=`Copilot CLI`;family=`copilot`;platforms=[`win32`,`darwin`,`linux`];scope=`user`;configKey=`mcpServers`;async detect(){return this.isPlatformSupported()?C(M(L(),`.copilot`)):!1}getConfigPath(){return M(L(),`.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 M(L(),`.copilot`)}getInstructionsRoot(){return null}getScaffoldPaths(){let e=M(L(),`.copilot`);return{agents:M(e,`agents`),skills:M(e,`skills`),prompts:null,flows:M(e,`flows`),hooks:M(e,`hooks`),commands:null,instructions:M(L(),`.github`,`copilot-instructions.md`),manifest:M(e,`.aikit-scaffold.json`)}}},On=class extends U{id=`cursor`;name=`Cursor`;configKey=`mcpServers`;configDirName=`Cursor`;scaffoldBase=`.cursor`;getMacAppPath(){return`/Applications/Cursor.app`}getInstructionFilePath(){return this.getPathModule().resolve(L(),this.scaffoldBase,`rules`,`aikit.mdc`)}},kn=class extends U{id=`cursor-nightly`;name=`Cursor Nightly`;configKey=`mcpServers`;configDirName=`Cursor Nightly`;scaffoldBase=`.cursor`;getMacAppPath(){return`/Applications/Cursor Nightly.app`}getInstructionFilePath(){return this.getPathModule().resolve(L(),this.scaffoldBase,`rules`,`aikit.mdc`)}},An=class e extends H{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(C(this.getCopilotConfigDir()))return!0;let t=this.getJetBrainsBaseDir();if(!C(t))return!1;try{return E(t,{withFileTypes:!0}).some(t=>t.isDirectory()&&e.PRODUCTS.some(e=>t.name.startsWith(e)))}catch{return!1}}getConfigPath(){return M(this.getCopilotConfigDir(),`mcp.json`)}async registerMcp(e,t,n){let r=this.getCopilotConfigDir();await Be(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=M(r,`${e}-launcher.js`);await Ge(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,hooks:null}}buildInstructionContent(e,t){return t}getCopilotConfigDir(){let e=L();return process.platform===`win32`?M(process.env.LOCALAPPDATA??M(e,`AppData`,`Local`),`github-copilot`,`intellij`):process.platform===`darwin`?M(e,`Library`,`Application Support`,`github-copilot`,`intellij`):M(process.env.XDG_CONFIG_HOME??M(e,`.config`),`github-copilot`,`intellij`)}getJetBrainsBaseDir(){let e=L();return process.platform===`win32`?M(process.env.APPDATA??M(e,`AppData`,`Roaming`),`JetBrains`):process.platform===`darwin`?M(e,`Library`,`Application Support`,`JetBrains`):M(process.env.XDG_CONFIG_HOME??M(e,`.config`),`JetBrains`)}},jn=class extends U{id=`trae`;name=`Trae`;configKey=`servers`;configDirName=`Trae`;scaffoldBase=`.trae`;getMacAppPath(){return`/Applications/Trae.app`}getInstructionFilePath(){return this.getPathModule().resolve(L(),this.scaffoldBase,`rules`,`aikit.md`)}},Mn=class extends U{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(L(),this.scaffoldBase,`instructions`,`copilot-instructions.md`):null}buildInstructionContent(e,t){return`---\napplyTo: "**"\n---\n\n${e}\n---\n\n${t}`}},Nn=class extends U{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(L(),this.scaffoldBase,`instructions`,`copilot-instructions.md`):null}buildInstructionContent(e,t){return`---\napplyTo: "**"\n---\n\n${e}\n---\n\n${t}`}},Pn=class extends U{id=`vscodium`;name=`VSCodium`;configKey=`servers`;configDirName=`VSCodium`;scaffoldBase=`.copilot`;hasInstructions=!0;getMacAppPath(){return`/Applications/VSCodium.app`}getInstructionFilePath(){return this.hasInstructions?this.getPathModule().resolve(L(),this.scaffoldBase,`instructions`,`copilot-instructions.md`):null}buildInstructionContent(e,t){return`---\napplyTo: "**"\n---\n\n${e}\n---\n\n${t}`}},Fn=class extends U{id=`windsurf`;name=`Windsurf`;configKey=`servers`;configDirName=`Windsurf`;scaffoldBase=`.windsurf`;getMacAppPath(){return`/Applications/Windsurf.app`}getInstructionFilePath(){return this.getPathModule().resolve(L(),this.scaffoldBase,`rules`,`aikit.md`)}},In=class extends H{id=`gemini-cli`;name=`Gemini CLI`;family=`gemini`;platforms=[`win32`,`darwin`,`linux`];scope=`user`;configKey=`mcpServers`;async detect(){return this.isPlatformSupported()?C(this.getPathModule().resolve(L(),`.gemini`)):!1}getConfigPath(){return this.getPathModule().resolve(L(),`.gemini`,`settings.json`)}getScaffoldRoot(){return this.getPathModule().resolve(L(),`.gemini`)}getScaffoldPaths(){let e=this.getPathModule(),t=e.resolve(L(),`.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`),hooks:null}}getPathModule(){return process.platform===`win32`?N:j}},Ln=class extends H{id=`opencode`;name=`OpenCode`;family=`opencode`;platforms=[`win32`,`darwin`,`linux`];scope=`user`;configKey=`mcp`;async detect(){if(!this.isPlatformSupported())return!1;let e=this.getPathModule(),t=L();return[e.resolve(t,`.config`,`opencode`),e.resolve(t,`.opencode`)].some(e=>C(e))}getConfigPath(){return this.getPathModule().resolve(L(),`.config`,`opencode`,`opencode.jsonc`)}async registerMcp(e,t){let n=await this.readConfig();n[this.configKey]||(n[this.configKey]={});let r=n[this.configKey];r[e]={type:`local`,command:[t.command,...t.args||[]]},await this.writeConfig(n)}getScaffoldRoot(){return this.getPathModule().resolve(L(),`.config`,`opencode`)}getScaffoldPaths(){let e=this.getPathModule(),t=this.getScaffoldRoot();return t?{agents:e.resolve(t,`agents`),skills:e.resolve(t,`skills`),prompts:null,flows:e.resolve(t,`flows`),commands:null,instructions:e.resolve(t,`OPENCODE.md`),manifest:e.resolve(t,`.aikit-scaffold.json`),hooks:null}:super.getScaffoldPaths()}getPathModule(){return process.platform===`win32`?N:j}},Rn=class extends H{id=`zed`;name=`Zed`;family=`zed`;platforms=[`win32`,`darwin`,`linux`];scope=`user`;configKey=`context_servers`;async detect(){return this.isPlatformSupported()?C(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`),hooks:null}}getConfigDir(){let e=this.getPathModule();return process.platform===`win32`?e.resolve(process.env.APPDATA||L(),`Zed`):e.resolve(L(),`.config`,`zed`)}getPathModule(){return process.platform===`win32`?N:j}};const zn=[new Mn,new Nn,new Pn,new On,new kn,new Fn,new jn,new Dn,new An,new Tn,new In,new En,new Rn,new Ln];async function Bn(e){let t=e?.scope?zn.filter(t=>t.scope===e.scope):zn;return(await Promise.allSettled(t.map(async e=>await e.detect()?e:null))).flatMap(e=>e.status!==`fulfilled`||e.value===null?[]:[e.value])}const Vn={SessionStart:{copilot:`SessionStart`,claude:`PreToolCall`,copilotCli:`sessionStart`},PreToolUse:{copilot:`PreToolUse`,claude:`PreToolCall`,copilotCli:`preToolUse`},PostToolUse:{copilot:`PostToolUse`,claude:`PostToolCall`,copilotCli:`postToolUse`},SubagentStart:{copilot:`SubagentStart`,claude:`PreToolCall`,copilotCli:`subagentStart`},PreCompact:{copilot:`PreCompact`,claude:`PreToolCall`,copilotCli:`preCompact`},Stop:{copilot:`Stop`,claude:`PostToolCall`,copilotCli:`stop`}},Hn={fileRead:{copilot:[`read_file`,`readFile`],claude:[`Read`],copilotCli:[`read_file`]},fileWrite:{copilot:[`editFiles`,`replace_string_in_file`,`create_file`],claude:[`Write`,`Edit`],copilotCli:[`editFiles`,`replace_string_in_file`]},fileSearch:{copilot:[`grep_search`,`semantic_search`,`find`],claude:[`Bash`],copilotCli:[`grep_search`]}},Un={"privacy-guard":{id:`privacy-guard`,event:`PreToolUse`,tier:`safety`,description:`Blocks reads of secret-bearing env files, key material, SSH paths, and credential artifacts.`,script:`privacy-guard.mjs`,matcher:[`fileRead`],scope:`user`,patterns:[`.env`,`*.pem`,`*.key`,`id_rsa*`,`.ssh/*`,`*credentials*`,`*.secret`]},"scout-guard":{id:`scout-guard`,event:`PreToolUse`,tier:`safety`,description:`Blocks reads and searches inside generated, dependency, and git object directories.`,script:`scout-guard.mjs`,matcher:[`fileRead`,`fileSearch`],scope:`user`,patterns:[`node_modules/`,`dist/`,`.git/objects/`,`vendor/`,`build/`]},"subagent-context":{id:`subagent-context`,event:`SubagentStart`,tier:`efficiency`,description:`Injects compact project context into each subagent spawn to reduce repeated discovery.`,script:`subagent-context.mjs`,scope:`user`},"pre-compact-save":{id:`pre-compact-save`,event:`PreCompact`,tier:`efficiency`,description:`Persists critical state before context compaction truncates recent session history.`,script:`pre-compact-save.mjs`,scope:`user`},"post-edit-check":{id:`post-edit-check`,event:`PostToolUse`,tier:`nudge`,description:`After repeated file edits, injects a validation reminder so checks are not skipped.`,script:`post-edit-check.mjs`,matcher:[`fileWrite`],scope:`user`},"session-init":{id:`session-init`,event:`SessionStart`,tier:`nudge`,description:`Detects project stack and injects workspace metadata and environment context at startup.`,script:`session-init.mjs`,scope:`user`},"session-observer":{id:`session-observer`,event:`PostToolUse`,tier:`efficiency`,description:`Captures tool usage patterns for autonomous lesson extraction. Writes to session buffer.`,script:`session-observer.mjs`,scope:`user`},"session-learn":{id:`session-learn`,event:`Stop`,tier:`efficiency`,description:`Nudges final pattern analysis on buffered observations at session end.`,script:`session-learn.mjs`,scope:`user`}},Wn={PreCompact:3e3,PostToolUse:3e3},Gn={copilot:`hooks.json`,claude:`hooks-settings.json`,copilotCli:`hooks.json`};function Kn(e,t){return(e.matcher||[]).flatMap(e=>{let n=Hn[e];if(!n)throw Error(`Unknown hook matcher: ${e}`);return n[t]||[]})}function qn(e,t,n,r){let i=`${n}/${e.script}`;return Kn(e,r),r===`copilot`?{event:t,steps:[{type:`command`,command:`node`,args:[i],timeout:Wn[e.event]||5e3}]}:r===`claude`?{type:`command`,command:`node ${i}`}:{command:`node`,args:[i]}}function Jn(e,t){if(e===`copilot`){let n=Object.values(Un).map(n=>{let r=Vn[n.event]?.[e];if(!r)throw Error(`Unsupported hook event ${n.event} for ${e}`);return qn(n,r,t,e)});return[{path:Gn[e],content:JSON.stringify({hooks:n},null,2)}]}let n={};for(let r of Object.values(Un)){let i=Vn[r.event]?.[e];if(!i)throw Error(`Unsupported hook event ${r.event} for ${e}`);n[i]||=[],n[i].push(qn(r,i,t,e))}return[{path:Gn[e],content:JSON.stringify({hooks:n},null,2)}]}function Yn(){return[`_runtime.mjs`,...Object.values(Un).map(e=>e.script)]}function Xn(){let e={command:y.command,args:y.args?[...y.args]:void 0,type:y.type};if(process.platform!==`win32`){let t=process.env.PATH;t&&(e.env={PATH:t});try{let t=nn(`which`,[`node`],{encoding:`utf-8`,timeout:3e3}).trim();t&&C(t)&&(e.command=t)}catch{}}return e}const Zn=new Set([`VS Code`,`VS Code Insiders`,`VSCodium`]);function Qn(e,t,n){let r=M(L(),`.copilot`,`instructions`,`copilot-instructions.md`);!C(r)||n.has(r)||(w(k(r),{recursive:!0}),O(r,`---\napplyTo: "**"\n---\n\n${e}\n---\n\n${t}`,`utf-8`),n.add(r))}function $n(e,t=!1){if(!Zn.has(e.name))return;let n=M(k(e.getConfigPath()),`settings.json`),r={};if(C(n))try{let e=T(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(fe))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&&(O(n,`${JSON.stringify(r,null,2)}\n`,`utf-8`),console.log(` ${e.name}: updated settings.json`))}async function er(r,o,s,c,l=!1){let u=new Map,d=new Set,f=ce(`aikit`,s),p=pe(`aikit`,s);for(let e of o)e.getScaffoldRoot()!==null&&u.set(e.id,e);if(Qn(f,p,d),u.size===0){d.size>0?console.log(` Instruction files: ${[...d].join(`, `)}`):console.log(` No IDEs with global scaffold support detected.`);return}let ee=await n(r,`copilot`),te=await n(r,`opencode`),ne=e=>{let t=new Map;for(let n of e){let e=n.path.indexOf(`/`);if(e===-1)continue;let r=n.path.substring(0,e);if(r===`agents`||r===`prompts`){let i=t.get(r)??[];i.push({path:n.path.substring(e+1),content:n.content}),t.set(r,i)}else if(r===`.opencode`){let r=n.path.indexOf(`/`,e+1);if(r!==-1&&n.path.substring(e+1,r)===`agents`){let e=t.get(`agents`)??[];e.push({path:n.path.substring(r+1),content:n.content}),t.set(`agents`,e)}}}return t},re=ne(ee),ie=ne(te),m=await n(r,`skills`),ae=new Set;for(let e of m){let t=e.path.indexOf(`/`);t!==-1&&ae.add(e.path.substring(0,t))}let h=await n(r,`flows`),g=new Set;for(let e of h){let t=e.path.indexOf(`/`);t!==-1&&g.add(e.path.substring(0,t))}let _=await n(r,`claude-code`),v=M(r,`scaffold`,`general`,`hooks`,`scripts`),oe=C(v)?v:M(import.meta.dirname,`../../../../../scaffold/general/hooks/scripts`),y=Yn(),b=new Set,se=new Set,x=new Set,S=(n,r,o,s)=>{let u=s.get(o);if(!n||!r||!u||u.length===0)return;let d=`${o}:${r}:${n}`;if(b.has(d))return;b.add(d);let f=e(r)??a(c);f.version=c,i(u,n,f,o,l),t(r,f),x.add(k(r))},le=(n,r,o,s)=>{if(!n||!r||s.length===0)return;let u=`${o}:${r}:${n}`;if(b.has(u))return;if(b.add(u),o===`flows`&&!se.has(n)){for(let e of g){let t=M(n,e,`skills`);C(t)&&(D(t,{recursive:!0,force:!0}),console.log(` ${k(r)}: migrated ${e} flow to steps/ layout`))}se.add(n)}let d=e(r)??a(c);d.version=c,i(s,n,d,o,l),t(r,d),x.add(k(r))},ue=(e,t,n)=>{!e||!t||le(e,t,`hooks`,[...Jn(n,M(e,`scripts`).replace(/\\/g,`/`)),...y.map(e=>({path:`scripts/${e}`,content:T(M(oe,e),`utf-8`)}))])};for(let e of u.values()){let t=e.getScaffoldPaths(),n=e.family===`opencode`?ie:re;S(t.agents,t.manifest,`agents`,n),S(t.prompts,t.manifest,`prompts`,n),le(t.skills,t.manifest,`skills`,m),le(t.flows,t.manifest,`flows`,h),le(t.commands,t.manifest,`commands`,_),ue(t.hooks,t.manifest,e.family===`claude`?`claude`:`copilot`)}for(let e of x)console.log(` ${e}: scaffold updated (${ae.size} skills)`);for(let e of u.values()){let t=e.getScaffoldPaths().instructions;!t||d.has(t)||(w(k(t),{recursive:!0}),O(t,e.buildInstructionContent(f,p),`utf-8`),d.add(t))}d.size>0&&console.log(` Instruction files: ${[...d].join(`, `)}`)}function tr(e){let t=[];for(let n of e){let e=n.getScaffoldRoot();if(e)if(Zn.has(n.name)){let r=n.getInstructionsRoot()??e;t.push(M(r,`kb.instructions.md`)),t.push(M(r,`aikit.instructions.md`))}else n.name===`Cursor`||n.name===`Cursor Nightly`?t.push(M(e,`rules`,`kb.mdc`)):n.name===`Windsurf`&&t.push(M(e,`rules`,`kb.md`))}for(let e of t)C(e)&&(Se(e),console.log(` Removed legacy file: ${e}`))}async function nr(e){let t=m,n=S(),r=JSON.parse(T(M(n,`package.json`),`utf-8`)).version;console.log(`Initializing @vpxa/aikit v${r}...\n`);let i=ke();w(i,{recursive:!0}),console.log(` Global data store: ${i}`),Pe({version:1,workspaces:{}}),console.log(` Created registry.json`);let a=await Bn({scope:`user`});if(a.length===0)console.log(`
|
|
5
|
-
No supported IDEs detected. You can manually add the MCP server config.`);else{console.log(`\n Detected ${a.length} IDE(s):`);let n=Xn();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)
|
|
6
|
-
Installing scaffold files:`),await
|
|
1
|
+
import{d as e,f as t,i as n,p as r,s as i,u as a}from"./scaffold-BNPHP-QC.js";import{A as o,C as s,D as c,E as l,F as u,I as d,L as f,M as p,N as m,O as ee,P as h,S as te,T as ne,_ as re,a as g,b as _,c as v,d as y,f as b,g as ie,h as ae,i as x,j as oe,k as se,l as ce,m as S,n as le,o as ue,p as de,r as fe,s as pe,t as me,u as C,v as he,w as ge,x as _e,y as ve}from"./templates-BQ1J4HzY.js";import{copyFileSync as ye,existsSync as w,mkdirSync as T,readFileSync as E,readdirSync as D,renameSync as be,rmSync as O,statSync as xe,unlinkSync as Se,writeFileSync as k}from"node:fs";import{basename as Ce,dirname as A,join as j,posix as M,relative as we,resolve as N,win32 as P}from"node:path";import{fileURLToPath as Te}from"node:url";import{initializeWasm as Ee}from"../../chunker/dist/index.js";import{AIKIT_PATHS as F,AIKIT_RUNTIME_PATHS as De,EMBEDDING_DEFAULTS as Oe,createLogger as I,getGlobalDataDir as ke,getPartitionDir as Ae,isUserInstalled as je,migrateLegacyWorkspaceLayout as Me,registerWorkspace as Ne,saveRegistry as Pe}from"../../core/dist/index.js";import{OnnxEmbedder as Fe}from"../../embeddings/dist/index.js";import{IncrementalIndexer as Ie}from"../../indexer/dist/index.js";import{SqliteGraphStore as Le,createSqliteAdapter as Re,createStore as ze}from"../../store/dist/index.js";import{mkdir as Be,readFile as Ve,rename as He,rm as Ue,unlink as We,writeFile as Ge}from"node:fs/promises";import{addToWorkset as Ke,audit as qe,check as Je,checkpointLatest as Ye,checkpointList as Xe,checkpointLoad as Ze,checkpointSave as Qe,codemod as $e,compact as et,dataTransform as tt,delegate as nt,delegateListModels as rt,deleteWorkset as it,diffParse as at,evaluate as ot,fileSummary as st,find as ct,findDeadSymbols as lt,findExamples as ut,getWorkset as dt,gitContext as ft,graphQuery as pt,guide as mt,health as ht,laneCreate as gt,laneDiff as _t,laneDiscard as vt,laneList as yt,laneMerge as bt,laneStatus as xt,listWorksets as St,parseOutput as Ct,processList as wt,processLogs as Tt,processStart as Et,processStatus as Dt,processStop as Ot,queueClear as kt,queueCreate as At,queueDelete as jt,queueDone as Mt,queueFail as Nt,queueGet as Pt,queueList as Ft,queueNext as It,queuePush as Lt,removeFromWorkset as Rt,rename as zt,replayClear as Bt,replayList as Vt,replayTrim as Ht,saveWorkset as Ut,scopeMap as Wt,stashClear as Gt,stashDelete as Kt,stashGet as qt,stashList as Jt,stashSet as Yt,symbol as Xt,testRun as Zt,trace as Qt,watchList as $t,watchStart as en,watchStop as tn}from"../../tools/dist/index.js";import{execFileSync as nn,execSync as L,fork as rn,spawn as an}from"node:child_process";import{arch as on,homedir as R,platform as sn}from"node:os";import{randomUUID as cn}from"node:crypto";function ln(){let e=process.env.AIKIT_CONFIG_PATH??(w(N(process.cwd(),`aikit.config.json`))?N(process.cwd(),`aikit.config.json`):null),t=e?A(e):process.cwd();if(Me(t),!e)return un();let n=E(e,`utf-8`),r;try{r=JSON.parse(n)}catch{console.error(`Failed to parse ${e} as JSON. Ensure the file contains valid JSON.`),process.exit(1)}let i=t;return r.sources=r.sources.map(e=>({...e,path:N(i,e.path)})),r.store.path=N(i,r.store.path),r.curated=r.curated??{path:F.aiCurated},r.curated.path=N(i,r.curated.path),r.onboardDir||=F.aiContext,r.onboardDir=N(i,r.onboardDir),r.stateDir||=F.state,r.stateDir=N(i,r.stateDir),dn(r,i),r}function un(){let e=process.env.AIKIT_WORKSPACE_ROOT??process.cwd();Me(e);let t={sources:[{path:e,excludePatterns:[`node_modules/**`,`dist/**`,`.git/**`,`coverage/**`,`*.lock`,`pnpm-lock.yaml`]}],serverName:`aikit`,indexing:{chunkSize:1500,chunkOverlap:200,minChunkSize:100},embedding:{model:Oe.model,dimensions:Oe.dimensions},store:{backend:`sqlite-vec`,path:N(e,F.data)},curated:{path:N(e,F.aiCurated)},onboardDir:N(e,F.aiContext),stateDir:N(e,F.state)};return dn(t,e),t}function dn(e,t){if(!je())return;let n=Ne(t);e.store.path=N(Ae(n.partition),De.data),e.stateDir=N(Ae(n.partition),De.state),e.onboardDir=N(Ae(n.partition),De.onboard),e.curated={path:N(Ae(n.partition),De.curated)}}async function fn(){let e=ln(),t=new Fe({model:e.embedding.model,dimensions:e.embedding.dimensions,interOpNumThreads:e.embedding.interOpNumThreads,intraOpNumThreads:e.embedding.intraOpNumThreads});await t.initialize();let n=null;if(e.store.backend===`sqlite-vec`){let t=N(e.store.path,`aikit.db`),r=A(t);if(!w(r)){let{mkdirSync:e}=await import(`node:fs`);e(r,{recursive:!0})}n=await Re(t)}let r=await ze({backend:e.store.backend,path:e.store.path,embeddingDim:e.embedding.dimensions,adapter:n??void 0});await r.initialize();let i=new Ie(t,r),{CuratedKnowledgeManager:a}=await import(`../../server/dist/index.js`),o=new a(e.curated.path,r,t),s;try{let t=n?new Le({adapter:n}):new Le({path:e.store.path});await t.initialize(),s=t,i.setGraphStore(s)}catch(e){console.error(`[aikit] Graph store init failed (non-fatal): ${e.message}`),s={initialize:async()=>{},upsertNode:async()=>{},upsertEdge:async()=>{},upsertNodes:async()=>{},upsertEdges:async()=>{},getNode:async()=>null,getNeighbors:async()=>({nodes:[],edges:[]}),traverse:async()=>({nodes:[],edges:[]}),findNodes:async()=>[],findEdges:async()=>[],deleteNode:async()=>{},deleteBySourcePath:async()=>0,clear:async()=>{},getStats:async()=>({nodeCount:0,edgeCount:0,nodeTypes:{},edgeTypes:{}}),validate:async()=>({valid:!0,orphanNodes:[],danglingEdges:[],stats:{nodeCount:0,edgeCount:0,nodeTypes:{},edgeTypes:{}}}),setNodeCommunity:async()=>{},detectCommunities:async()=>({}),traceProcess:async()=>({id:``,entryNodeId:``,label:``,properties:{},steps:[]}),getProcesses:async()=>[],deleteProcess:async()=>{},depthGroupedTraversal:async()=>({}),getCohesionScore:async()=>0,getSymbol360:async()=>({node:{id:``,type:``,name:``,properties:{}},incoming:[],outgoing:[],community:null,processes:[]}),close:async()=>{}}}return await Ee().catch(()=>{}),{config:e,embedder:t,store:r,graphStore:s,indexer:i,curated:o,sqliteAdapter:n}}const pn=[{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()??``;if(!t||!n)throw new v(`Usage: aikit analyze <type> <path>
|
|
2
|
+
Types: structure, deps, symbols, patterns, entry-points, blast-radius, diagram`);let{BlastRadiusAnalyzer:r,DependencyAnalyzer:i,DiagramGenerator:a,EntryPointAnalyzer:o,PatternAnalyzer:s,StructureAnalyzer:c,SymbolAnalyzer:l}=await import(`../../analyzers/dist/index.js`),u=N(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:throw new v(`Unknown analyze type: ${t}\nTypes: structure, deps, symbols, patterns, entry-points, blast-radius, diagram`)}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(n),o=ln();console.log(`Onboarding: ${a} (mode: ${r})`),console.log(`Running analyses...
|
|
3
|
+
`);let s=await t({path:a,mode:r,outDir:i??o.onboardDir});for(let e of s.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: ${s.totalDurationMs}ms`),s.outDir&&console.log(`Output written to: ${s.outDir}`)}}],mn=[{name:`parse-output`,description:`Parse build or tool output from stdin`,usage:`aikit parse-output [--tool tsc|vitest|biome|git-status]`,run:async e=>{let t=b(e,`--tool`,``).trim()||void 0,n=await m();n.trim()||(console.error(`Usage: aikit parse-output [--tool tsc|vitest|biome|git-status]`),process.exit(1)),ee(Ct(n,t))}},{name:`git`,description:`Show git branch, status, recent commits, and optional diff stats`,usage:`aikit git [--cwd path] [--commit-count N] [--diff]`,run:async e=>{ne(await ft({cwd:b(e,`--cwd`,``).trim()||void 0,commitCount:y(e,`--commit-count`,5),includeDiff:C(e,`--diff`)}))}},{name:`diff`,description:`Parse unified diff text from stdin into structured file changes`,usage:`git diff | aikit diff`,run:async()=>{let e=await m();e.trim()||(console.error(`Usage: git diff | aikit diff`),process.exit(1)),te(at({diff:e}))}},{name:`summarize`,description:`Show a structural summary of a file`,usage:`aikit summarize <path>`,run:async e=>{let t=e.shift()?.trim();t||(console.error(`Usage: aikit summarize <path>`),process.exit(1)),ge(await st({path:N(t)}))}},{name:`checkpoint`,description:`Save and restore lightweight session checkpoints`,usage:`aikit checkpoint <save|load|list|latest> [label-or-id] [--data json] [--notes text]`,run:async e=>{let t=e.shift()?.trim();t||(console.error(`Usage: aikit checkpoint <save|load|list|latest> [label-or-id] [--data json] [--notes text]`),process.exit(1));let n=await ce();switch(t){case`save`:{let t=e.shift()?.trim(),r=b(e,`--data`,``),i=b(e,`--notes`,``).trim()||void 0,a=r.trim()?``:await m();t||(console.error(`Usage: aikit checkpoint save <label> [--data json] [--notes text]`),process.exit(1)),_(Qe(n,t,he(r||a),{notes:i}));return}case`load`:{let t=e.shift()?.trim();t||(console.error(`Usage: aikit checkpoint load <id>`),process.exit(1));let r=Ze(n,t);if(!r){console.log(`No checkpoint found: ${t}`);return}_(r);return}case`list`:{let e=Xe(n);if(e.length===0){console.log(`No checkpoints saved.`);return}console.log(`Checkpoints (${e.length})`),console.log(`─`.repeat(60));for(let t of e)console.log(`${t.id}`),console.log(` Label: ${t.label}`),console.log(` Created: ${t.createdAt}`);return}case`latest`:{let e=Ye(n);if(!e){console.log(`No checkpoints saved.`);return}_(e);return}default:console.error(`Unknown checkpoint action: ${t}`),console.error(`Actions: save, load, list, latest`),process.exit(1)}}}],hn=j(R(),`.aikit`),z=j(hn,`daemon.json`),gn=3210,B=I(`cli:daemon`);function _n(){if(!w(z))return null;try{return JSON.parse(E(z,`utf-8`))}catch{return null}}function vn(e){w(hn)||T(hn,{recursive:!0});let t=`${z}.tmp`;k(t,JSON.stringify(e,null,2)),be(t,z)}function V(){w(z)&&O(z)}async function H(e){try{return process.kill(e,0),!0}catch{return!1}}async function yn(e){try{return(await fetch(`http://127.0.0.1:${e}/health`,{signal:AbortSignal.timeout(2e3)})).ok}catch{return!1}}async function bn(e,t){let n=Date.now();for(B.debug(`Polling health endpoint on port ${e}...`);Date.now()-n<t;){if(await yn(e))return B.debug(`Daemon health check passed`),!0;await new Promise(e=>setTimeout(e,200))}return!1}async function xn(){let e=_n();if(!e)return B.info(`Daemon is not running`),null;if(!await H(e.pid))return V(),B.debug(`Daemon was not running (stale state cleaned up)`),{pid:e.pid,wasRunning:!1};B.debug(`Sending SIGTERM to daemon...`);try{process.kill(e.pid,`SIGTERM`),await new Promise(e=>setTimeout(e,2e3)),await H(e.pid)&&(B.debug(`Sending SIGKILL to daemon...`),process.kill(e.pid,`SIGKILL`))}catch{}return V(),{pid:e.pid,wasRunning:!0}}async function Sn(e){let t=h();B.debug(`Spawning daemon process...`);let n=an(process.execPath,[t,`--transport`,`http`,`--port`,String(e)],{stdio:`ignore`,detached:!0,env:{...process.env,NODE_OPTIONS:f(process.env.NODE_OPTIONS),AIKIT_TRANSPORT:`http`,AIKIT_PORT:String(e)}});n.unref(),await bn(e,3e4)||(B.error(`Daemon failed to start within 30 seconds`),n.kill(`SIGTERM`),process.exit(1));let r=ae();if(n.pid===void 0)throw Error(`Daemon child process has no PID`);return vn({port:e,pid:n.pid,version:r,startedAt:new Date().toISOString()}),{pid:n.pid,port:e}}const Cn=[{name:`daemon`,description:`Run AI Kit as a background HTTP daemon — survives IDE restarts, shares across windows (start|stop|status|restart)`,usage:`aikit daemon <start|stop|status|restart> [--port <port>]`,run:async e=>{let t=e[0];if(!t){console.error(`Usage: aikit daemon <start|stop|status|restart>`),console.error(``),console.error(`Commands:`),console.error(` start Start the AI Kit daemon`),console.error(` stop Stop the AI Kit daemon`),console.error(` status Show daemon status`),console.error(` restart Restart the AI Kit daemon`);return}switch(t){case`start`:{let t=_n();if(t){if(await H(t.pid)&&await yn(t.port)){B.info(`Daemon already running (PID ${t.pid}, port ${t.port})`);return}B.debug(`Cleaning up stale daemon state...`),V()}let n=e.indexOf(`--port`),r=await Sn(n!==-1&&e[n+1]?Number.parseInt(e[n+1],10):gn);B.info(`Daemon started (PID ${r.pid}, port ${r.port})`);return}case`stop`:{let e=await xn();e?.wasRunning&&B.info(`Daemon stopped (PID ${e.pid})`);return}case`status`:{let e=_n();if(!e){console.log(`Daemon: stopped`);return}if(!(await H(e.pid)&&await yn(e.port))){V(),console.log(`Daemon: stopped (stale state cleaned up)`);return}console.log(`Daemon: running`),console.log(` PID: ${e.pid}`),console.log(` Port: ${e.port}`),console.log(` Version: ${e.version}`),console.log(` Started: ${e.startedAt}`);return}case`restart`:{let t=_n();if(t){if(await H(t.pid)){B.debug(`Sending SIGTERM to daemon...`);try{process.kill(t.pid,`SIGTERM`),await new Promise(e=>setTimeout(e,2e3)),await H(t.pid)&&(B.debug(`Sending SIGKILL to daemon...`),process.kill(t.pid,`SIGKILL`))}catch{}}V(),B.info(`Daemon stopped (PID ${t.pid})`)}else B.info(`Daemon is not running`);let n=e.indexOf(`--port`),r=await Sn(n!==-1&&e[n+1]?Number.parseInt(e[n+1],10):gn);B.info(`Daemon started (PID ${r.pid}, port ${r.port})`);return}default:console.error(`Unknown daemon command: ${t}`),console.error("Use `aikit daemon` for help.")}}}];function wn(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]!==`
|
|
4
|
+
`;)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 U=class{isPlatformSupported(){return this.platforms.includes(process.platform)}async readConfig(e){let t=this.getConfigPath(e);if(!w(t))return{};let n=await Ve(t,`utf-8`);try{return JSON.parse(wn(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=A(n),i=j(r,`.aikit-tmp-${cn()}.json`);await Be(r,{recursive:!0});try{await Ge(i,`${JSON.stringify(e,null,2)}\n`,`utf-8`),await He(i,n)}catch(e){try{await We(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,hooks:null}}buildInstructionContent(e,t){return`${e}\n---\n\n${t}`}},Tn=class extends U{id=`claude-code`;name=`Claude Code`;family=`claude`;platforms=[`win32`,`darwin`,`linux`];scope=`user`;configKey=`mcpServers`;async detect(){return this.isPlatformSupported()?w(this.getPathModule().resolve(R(),`.claude`)):!1}getConfigPath(){return this.getPathModule().resolve(R(),`.claude`,`mcp.json`)}getScaffoldRoot(){return this.getPathModule().resolve(R(),`.claude`)}getScaffoldPaths(){let e=this.getPathModule(),t=e.resolve(R(),`.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`),hooks:null}}buildInstructionContent(e,t){return`${e}\n---\n\n${t}`}getPathModule(){return process.platform===`win32`?P:M}},En=class extends U{id=`codex-cli`;name=`Codex CLI`;family=`codex`;platforms=[`win32`,`darwin`,`linux`];scope=`user`;configKey=`mcpServers`;async detect(){return this.isPlatformSupported()?w(this.getPathModule().resolve(R(),`.codex`)):!1}getConfigPath(){return this.getPathModule().resolve(R(),`.codex`,`config.json`)}getScaffoldRoot(){return this.getPathModule().resolve(R(),`.codex`)}getScaffoldPaths(){let e=this.getPathModule(),t=e.resolve(R(),`.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`),hooks:null}}getPathModule(){return process.platform===`win32`?P:M}},W=class extends U{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 w(e)||t!==null&&w(t)}return w(e)}getConfigPath(){return this.getPathModule().resolve(this.getConfigDir(),`mcp.json`)}getScaffoldRoot(){return this.getPathModule().resolve(R(),this.scaffoldBase)}getInstructionsRoot(){let e=this.getInstructionFilePath();return e?this.getPathModule().dirname(e):null}getScaffoldPaths(){let e=this.getPathModule(),t=e.resolve(R(),this.scaffoldBase);return{agents:e.resolve(t,`agents`),skills:e.resolve(t,`skills`),prompts:e.resolve(this.getConfigDir(),`prompts`),flows:e.resolve(t,`flows`),hooks:e.resolve(t,`hooks`),commands:null,instructions:this.getInstructionFilePath(),manifest:e.resolve(t,`.aikit-scaffold.json`)}}getConfigDir(){let e=this.getPathModule(),t=R();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`?P:M}},Dn=class extends U{id=`copilot-cli`;name=`Copilot CLI`;family=`copilot`;platforms=[`win32`,`darwin`,`linux`];scope=`user`;configKey=`mcpServers`;async detect(){return this.isPlatformSupported()?w(N(R(),`.copilot`)):!1}getConfigPath(){return N(R(),`.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 N(R(),`.copilot`)}getInstructionsRoot(){return null}getScaffoldPaths(){let e=N(R(),`.copilot`);return{agents:N(e,`agents`),skills:N(e,`skills`),prompts:null,flows:N(e,`flows`),hooks:N(e,`hooks`),commands:null,instructions:N(R(),`.github`,`copilot-instructions.md`),manifest:N(e,`.aikit-scaffold.json`)}}},On=class extends W{id=`cursor`;name=`Cursor`;configKey=`mcpServers`;configDirName=`Cursor`;scaffoldBase=`.cursor`;getMacAppPath(){return`/Applications/Cursor.app`}getInstructionFilePath(){return this.getPathModule().resolve(R(),this.scaffoldBase,`rules`,`aikit.mdc`)}},kn=class extends W{id=`cursor-nightly`;name=`Cursor Nightly`;configKey=`mcpServers`;configDirName=`Cursor Nightly`;scaffoldBase=`.cursor`;getMacAppPath(){return`/Applications/Cursor Nightly.app`}getInstructionFilePath(){return this.getPathModule().resolve(R(),this.scaffoldBase,`rules`,`aikit.mdc`)}},An=class e extends U{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(w(this.getCopilotConfigDir()))return!0;let t=this.getJetBrainsBaseDir();if(!w(t))return!1;try{return D(t,{withFileTypes:!0}).some(t=>t.isDirectory()&&e.PRODUCTS.some(e=>t.name.startsWith(e)))}catch{return!1}}getConfigPath(){return N(this.getCopilotConfigDir(),`mcp.json`)}async registerMcp(e,t,n){let r=this.getCopilotConfigDir();await Be(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=N(r,`${e}-launcher.js`);await Ge(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,hooks:null}}buildInstructionContent(e,t){return t}getCopilotConfigDir(){let e=R();return process.platform===`win32`?N(process.env.LOCALAPPDATA??N(e,`AppData`,`Local`),`github-copilot`,`intellij`):process.platform===`darwin`?N(e,`Library`,`Application Support`,`github-copilot`,`intellij`):N(process.env.XDG_CONFIG_HOME??N(e,`.config`),`github-copilot`,`intellij`)}getJetBrainsBaseDir(){let e=R();return process.platform===`win32`?N(process.env.APPDATA??N(e,`AppData`,`Roaming`),`JetBrains`):process.platform===`darwin`?N(e,`Library`,`Application Support`,`JetBrains`):N(process.env.XDG_CONFIG_HOME??N(e,`.config`),`JetBrains`)}},jn=class extends W{id=`trae`;name=`Trae`;configKey=`servers`;configDirName=`Trae`;scaffoldBase=`.trae`;getMacAppPath(){return`/Applications/Trae.app`}getInstructionFilePath(){return this.getPathModule().resolve(R(),this.scaffoldBase,`rules`,`aikit.md`)}},Mn=class extends W{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(R(),this.scaffoldBase,`instructions`,`copilot-instructions.md`):null}buildInstructionContent(e,t){return`---\napplyTo: "**"\n---\n\n${e}\n---\n\n${t}`}},Nn=class extends W{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(R(),this.scaffoldBase,`instructions`,`copilot-instructions.md`):null}buildInstructionContent(e,t){return`---\napplyTo: "**"\n---\n\n${e}\n---\n\n${t}`}},Pn=class extends W{id=`vscodium`;name=`VSCodium`;configKey=`servers`;configDirName=`VSCodium`;scaffoldBase=`.copilot`;hasInstructions=!0;getMacAppPath(){return`/Applications/VSCodium.app`}getInstructionFilePath(){return this.hasInstructions?this.getPathModule().resolve(R(),this.scaffoldBase,`instructions`,`copilot-instructions.md`):null}buildInstructionContent(e,t){return`---\napplyTo: "**"\n---\n\n${e}\n---\n\n${t}`}},Fn=class extends W{id=`windsurf`;name=`Windsurf`;configKey=`servers`;configDirName=`Windsurf`;scaffoldBase=`.windsurf`;getMacAppPath(){return`/Applications/Windsurf.app`}getInstructionFilePath(){return this.getPathModule().resolve(R(),this.scaffoldBase,`rules`,`aikit.md`)}},In=class extends U{id=`gemini-cli`;name=`Gemini CLI`;family=`gemini`;platforms=[`win32`,`darwin`,`linux`];scope=`user`;configKey=`mcpServers`;async detect(){return this.isPlatformSupported()?w(this.getPathModule().resolve(R(),`.gemini`)):!1}getConfigPath(){return this.getPathModule().resolve(R(),`.gemini`,`settings.json`)}getScaffoldRoot(){return this.getPathModule().resolve(R(),`.gemini`)}getScaffoldPaths(){let e=this.getPathModule(),t=e.resolve(R(),`.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`),hooks:null}}getPathModule(){return process.platform===`win32`?P:M}},Ln=class extends U{id=`opencode`;name=`OpenCode`;family=`opencode`;platforms=[`win32`,`darwin`,`linux`];scope=`user`;configKey=`mcp`;async detect(){if(!this.isPlatformSupported())return!1;let e=this.getPathModule(),t=R();return[e.resolve(t,`.config`,`opencode`),e.resolve(t,`.opencode`)].some(e=>w(e))}getConfigPath(){return this.getPathModule().resolve(R(),`.config`,`opencode`,`opencode.jsonc`)}async registerMcp(e,t){let n=await this.readConfig();n[this.configKey]||(n[this.configKey]={});let r=n[this.configKey];r[e]={type:`local`,command:[t.command,...t.args||[]]},await this.writeConfig(n)}getScaffoldRoot(){return this.getPathModule().resolve(R(),`.config`,`opencode`)}getScaffoldPaths(){let e=this.getPathModule(),t=this.getScaffoldRoot();return t?{agents:e.resolve(t,`agents`),skills:e.resolve(t,`skills`),prompts:null,flows:e.resolve(t,`flows`),commands:null,instructions:e.resolve(t,`OPENCODE.md`),manifest:e.resolve(t,`.aikit-scaffold.json`),hooks:null}:super.getScaffoldPaths()}getPathModule(){return process.platform===`win32`?P:M}},Rn=class extends U{id=`zed`;name=`Zed`;family=`zed`;platforms=[`win32`,`darwin`,`linux`];scope=`user`;configKey=`context_servers`;async detect(){return this.isPlatformSupported()?w(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`),hooks:null}}getConfigDir(){let e=this.getPathModule();return process.platform===`win32`?e.resolve(process.env.APPDATA||R(),`Zed`):e.resolve(R(),`.config`,`zed`)}getPathModule(){return process.platform===`win32`?P:M}};const zn=[new Mn,new Nn,new Pn,new On,new kn,new Fn,new jn,new Dn,new An,new Tn,new In,new En,new Rn,new Ln];async function Bn(e){let t=e?.scope?zn.filter(t=>t.scope===e.scope):zn;return(await Promise.allSettled(t.map(async e=>await e.detect()?e:null))).flatMap(e=>e.status!==`fulfilled`||e.value===null?[]:[e.value])}const Vn={SessionStart:{copilot:`SessionStart`,claude:`PreToolCall`,copilotCli:`sessionStart`},PreToolUse:{copilot:`PreToolUse`,claude:`PreToolCall`,copilotCli:`preToolUse`},PostToolUse:{copilot:`PostToolUse`,claude:`PostToolCall`,copilotCli:`postToolUse`},SubagentStart:{copilot:`SubagentStart`,claude:`PreToolCall`,copilotCli:`subagentStart`},PreCompact:{copilot:`PreCompact`,claude:`PreToolCall`,copilotCli:`preCompact`},Stop:{copilot:`Stop`,claude:`PostToolCall`,copilotCli:`stop`}},Hn={fileRead:{copilot:[`read_file`,`readFile`],claude:[`Read`],copilotCli:[`read_file`]},fileWrite:{copilot:[`editFiles`,`replace_string_in_file`,`create_file`],claude:[`Write`,`Edit`],copilotCli:[`editFiles`,`replace_string_in_file`]},fileSearch:{copilot:[`grep_search`,`semantic_search`,`find`],claude:[`Bash`],copilotCli:[`grep_search`]}},Un={"privacy-guard":{id:`privacy-guard`,event:`PreToolUse`,tier:`safety`,description:`Blocks reads of secret-bearing env files, key material, SSH paths, and credential artifacts.`,script:`privacy-guard.mjs`,matcher:[`fileRead`],scope:`user`,patterns:[`.env`,`*.pem`,`*.key`,`id_rsa*`,`.ssh/*`,`*credentials*`,`*.secret`]},"scout-guard":{id:`scout-guard`,event:`PreToolUse`,tier:`safety`,description:`Blocks reads and searches inside generated, dependency, and git object directories.`,script:`scout-guard.mjs`,matcher:[`fileRead`,`fileSearch`],scope:`user`,patterns:[`node_modules/`,`dist/`,`.git/objects/`,`vendor/`,`build/`]},"subagent-context":{id:`subagent-context`,event:`SubagentStart`,tier:`efficiency`,description:`Injects compact project context into each subagent spawn to reduce repeated discovery.`,script:`subagent-context.mjs`,scope:`user`},"pre-compact-save":{id:`pre-compact-save`,event:`PreCompact`,tier:`efficiency`,description:`Persists critical state before context compaction truncates recent session history.`,script:`pre-compact-save.mjs`,scope:`user`},"post-edit-check":{id:`post-edit-check`,event:`PostToolUse`,tier:`nudge`,description:`After repeated file edits, injects a validation reminder so checks are not skipped.`,script:`post-edit-check.mjs`,matcher:[`fileWrite`],scope:`user`},"session-init":{id:`session-init`,event:`SessionStart`,tier:`nudge`,description:`Detects project stack and injects workspace metadata and environment context at startup.`,script:`session-init.mjs`,scope:`user`},"session-observer":{id:`session-observer`,event:`PostToolUse`,tier:`efficiency`,description:`Captures tool usage patterns for autonomous lesson extraction. Writes to session buffer.`,script:`session-observer.mjs`,scope:`user`},"session-learn":{id:`session-learn`,event:`Stop`,tier:`efficiency`,description:`Nudges final pattern analysis on buffered observations at session end.`,script:`session-learn.mjs`,scope:`user`}},Wn={PreCompact:3e3,PostToolUse:3e3},Gn={copilot:`hooks.json`,claude:`hooks-settings.json`,copilotCli:`hooks.json`};function Kn(e,t){return(e.matcher||[]).flatMap(e=>{let n=Hn[e];if(!n)throw Error(`Unknown hook matcher: ${e}`);return n[t]||[]})}function qn(e,t,n,r){let i=`${n}/${e.script}`;return Kn(e,r),r===`copilot`?{event:t,steps:[{type:`command`,command:`node`,args:[i],timeout:Wn[e.event]||5e3}]}:r===`claude`?{type:`command`,command:`node ${i}`}:{command:`node`,args:[i]}}function Jn(e,t){if(e===`copilot`){let n=Object.values(Un).map(n=>{let r=Vn[n.event]?.[e];if(!r)throw Error(`Unsupported hook event ${n.event} for ${e}`);return qn(n,r,t,e)});return[{path:Gn[e],content:JSON.stringify({hooks:n},null,2)}]}let n={};for(let r of Object.values(Un)){let i=Vn[r.event]?.[e];if(!i)throw Error(`Unsupported hook event ${r.event} for ${e}`);n[i]||=[],n[i].push(qn(r,i,t,e))}return[{path:Gn[e],content:JSON.stringify({hooks:n},null,2)}]}function Yn(){return[`_runtime.mjs`,...Object.values(Un).map(e=>e.script)]}function Xn(){let e=Zn();if(e)return e;let t={command:x.command,args:x.args?[...x.args]:void 0,type:x.type};if(process.platform!==`win32`){let e=process.env.PATH;e&&(t.env={PATH:e});try{let e=nn(`which`,[`node`],{encoding:`utf-8`,timeout:3e3}).trim();e&&w(e)&&(t.command=e)}catch{}}return t}function Zn(){let e=j(R(),`.aikit`,`current-version.json`);if(!w(e))return null;try{let t=JSON.parse(E(e,`utf-8`));if(typeof t.version!=`string`||t.version.length===0)return null;let n=j(R(),`.aikit`,`versions`,`v${t.version}`,`packages`,`server`,`dist`,`bin.js`);if(!w(n))return null;let r={command:process.execPath,args:[n,`serve`],type:`stdio`};return process.platform!==`win32`&&process.env.PATH&&(r.env={PATH:process.env.PATH}),r}catch{return null}}const Qn=new Set([`VS Code`,`VS Code Insiders`,`VSCodium`]);function $n(e,t,n){let r=N(R(),`.copilot`,`instructions`,`copilot-instructions.md`);!w(r)||n.has(r)||(T(A(r),{recursive:!0}),k(r,`---\napplyTo: "**"\n---\n\n${e}\n---\n\n${t}`,`utf-8`),n.add(r))}function er(e,t=!1){if(!Qn.has(e.name))return;let n=N(A(e.getConfigPath()),`settings.json`),r={};if(w(n))try{let e=E(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(pe))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&&(k(n,`${JSON.stringify(r,null,2)}\n`,`utf-8`),console.log(` ${e.name}: updated settings.json`))}async function tr(r,o,s,c,l=!1){let u=new Map,d=new Set,f=le(`aikit`,s),p=me(`aikit`,s);for(let e of o)e.getScaffoldRoot()!==null&&u.set(e.id,e);if($n(f,p,d),u.size===0){d.size>0?console.log(` Instruction files: ${[...d].join(`, `)}`):console.log(` No IDEs with global scaffold support detected.`);return}let m=await n(r,`copilot`),ee=await n(r,`opencode`),h=e=>{let t=new Map;for(let n of e){let e=n.path.indexOf(`/`);if(e===-1)continue;let r=n.path.substring(0,e);if(r===`agents`||r===`prompts`){let i=t.get(r)??[];i.push({path:n.path.substring(e+1),content:n.content}),t.set(r,i)}else if(r===`.opencode`){let r=n.path.indexOf(`/`,e+1);if(r!==-1&&n.path.substring(e+1,r)===`agents`){let e=t.get(`agents`)??[];e.push({path:n.path.substring(r+1),content:n.content}),t.set(`agents`,e)}}}return t},te=h(m),ne=h(ee),re=await n(r,`skills`),g=new Set;for(let e of re){let t=e.path.indexOf(`/`);t!==-1&&g.add(e.path.substring(0,t))}let _=await n(r,`flows`),v=new Set;for(let e of _){let t=e.path.indexOf(`/`);t!==-1&&v.add(e.path.substring(0,t))}let y=await n(r,`claude-code`),b=N(r,`scaffold`,`general`,`hooks`,`scripts`),ie=w(b)?b:N(import.meta.dirname,`../../../../../scaffold/general/hooks/scripts`),ae=Yn(),x=new Set,oe=new Set,se=new Set,ce=(n,r,o,s)=>{let u=s.get(o);if(!n||!r||!u||u.length===0)return;let d=`${o}:${r}:${n}`;if(x.has(d))return;x.add(d);let f=e(r)??a(c);f.version=c,i(u,n,f,o,l),t(r,f),se.add(A(r))},S=(n,r,o,s)=>{if(!n||!r||s.length===0)return;let u=`${o}:${r}:${n}`;if(x.has(u))return;if(x.add(u),o===`flows`&&!oe.has(n)){for(let e of v){let t=N(n,e,`skills`);w(t)&&(O(t,{recursive:!0,force:!0}),console.log(` ${A(r)}: migrated ${e} flow to steps/ layout`))}oe.add(n)}let d=e(r)??a(c);d.version=c,i(s,n,d,o,l),t(r,d),se.add(A(r))},ue=(e,t,n)=>{!e||!t||S(e,t,`hooks`,[...Jn(n,N(e,`scripts`).replace(/\\/g,`/`)),...ae.map(e=>({path:`scripts/${e}`,content:E(N(ie,e),`utf-8`)}))])};for(let e of u.values()){let t=e.getScaffoldPaths(),n=e.family===`opencode`?ne:te;ce(t.agents,t.manifest,`agents`,n),ce(t.prompts,t.manifest,`prompts`,n),S(t.skills,t.manifest,`skills`,re),S(t.flows,t.manifest,`flows`,_),S(t.commands,t.manifest,`commands`,y),ue(t.hooks,t.manifest,e.family===`claude`?`claude`:`copilot`)}for(let e of se)console.log(` ${e}: scaffold updated (${g.size} skills)`);for(let e of u.values()){let t=e.getScaffoldPaths().instructions;!t||d.has(t)||(T(A(t),{recursive:!0}),k(t,e.buildInstructionContent(f,p),`utf-8`),d.add(t))}d.size>0&&console.log(` Instruction files: ${[...d].join(`, `)}`)}function nr(e){let t=[];for(let n of e){let e=n.getScaffoldRoot();if(e)if(Qn.has(n.name)){let r=n.getInstructionsRoot()??e;t.push(N(r,`kb.instructions.md`)),t.push(N(r,`aikit.instructions.md`))}else n.name===`Cursor`||n.name===`Cursor Nightly`?t.push(N(e,`rules`,`kb.mdc`)):n.name===`Windsurf`&&t.push(N(e,`rules`,`kb.md`))}for(let e of t)w(e)&&(Se(e),console.log(` Removed legacy file: ${e}`))}async function rr(e){let t=g,n=S(),r=JSON.parse(E(N(n,`package.json`),`utf-8`)).version;console.log(`Initializing @vpxa/aikit v${r}...\n`);let i=ke();T(i,{recursive:!0}),console.log(` Global data store: ${i}`),Pe({version:1,workspaces:{}}),console.log(` Created registry.json`);let a=await Bn({scope:`user`});if(a.length===0)console.log(`
|
|
5
|
+
No supported IDEs detected. You can manually add the MCP server config.`);else{console.log(`\n Detected ${a.length} IDE(s):`);let n=Xn();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)er(t,e.force)}console.log(`
|
|
6
|
+
Installing scaffold files:`),await tr(n,a,t,r,e.force),nr(a),console.log(`
|
|
7
7
|
User-level AI Kit installation complete!`),console.log(`
|
|
8
|
-
Next steps:`),console.log(` 1. Open any workspace in your IDE`),console.log(` 2. The AI Kit server will auto-start and index the workspace`),console.log(` 3. Agents, prompts, skills & instructions are available globally`),console.log(` 4. No per-workspace init needed — just open a project and start coding`)}const
|
|
8
|
+
Next steps:`),console.log(` 1. Open any workspace in your IDE`),console.log(` 2. The AI Kit server will auto-start and index the workspace`),console.log(` 3. Agents, prompts, skills & instructions are available globally`),console.log(` 4. No per-workspace init needed — just open a project and start coding`)}const ir=[{directory:`.github/copilot/agents`,suffix:`.agent.md`},{directory:`.github/copilot/prompts`,suffix:`.prompt.md`},{directory:`.copilot/skills`,suffix:`/SKILL.md`},{directory:`.agents/skills`,suffix:`/SKILL.md`}],ar=[`.copilot/skills`,`.agents/skills`],or=/^(?:mcp_)?aikit_[a-z0-9_]+$/;function sr(e,t){return(we(e,t)||t).split(`\\`).join(`/`)}function cr(e){let t=new Set;for(let n of ir){let r=j(e,n.directory);if(w(r))try{for(let e of D(r,{withFileTypes:!0})){if(n.suffix===`/SKILL.md`){if(e.isDirectory()){let n=j(r,e.name,`SKILL.md`);w(n)&&t.add(n)}continue}e.isFile()&&e.name.endsWith(n.suffix)&&t.add(j(r,e.name))}}catch{}}return[...t].sort()}function lr(e){let t=new Set;for(let n of ar){let r=j(e,n);if(w(r))try{for(let e of D(r,{withFileTypes:!0}))e.isDirectory()&&t.add(e.name.toLowerCase())}catch{}}return t}function ur(e){if(!e.startsWith(`---`))return null;let t=e.match(/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/);return t?t[1]:null}function dr(e){let t=e.trim();if(!t)return[];let n=t.startsWith(`[`)&&t.endsWith(`]`)?t.slice(1,-1):t,r=[],i=``,a=null;for(let e of n){if((e===`"`||e===`'`)&&a===null){a=e,i+=e;continue}if(e===a){a=null,i+=e;continue}if(e===`,`&&a===null){let e=fr(i);e&&r.push(e),i=``;continue}i+=e}let o=fr(i);return o&&r.push(o),r}function fr(e){let t=e.trim();return t.startsWith(`"`)&&t.endsWith(`"`)||t.startsWith(`'`)&&t.endsWith(`'`)?t.slice(1,-1).trim():t}function pr(e){let t=e.trim();if(!t)return;if(t.startsWith(`[`)!==t.endsWith(`]`))return`inline array is missing a closing bracket`;if(!t.startsWith(`[`))return;let n=null;for(let e=1;e<t.length-1;e+=1){let r=t[e];if((r===`"`||r===`'`)&&n===null){n=r;continue}r===n&&(n=null)}if(n!==null)return`inline array has an unterminated quoted value`}function mr(e){if(!e.startsWith(`---`))return;let t=ur(e);if(t===null)return`frontmatter is missing a closing --- delimiter`;let n=!1;for(let e of t.split(/\r?\n/)){let t=e.trim();if(!t||t.startsWith(`#`))continue;if(n){if(/^\s{2,}[A-Za-z0-9_-]+:\s*.*$/.test(e))return pr(e.replace(/^\s{2,}[A-Za-z0-9_-]+:\s*/,``));n=!1}let r=e.match(/^([A-Za-z0-9_-]+):\s*(.*)$/);if(!r)return`unsupported frontmatter line: ${t}`;let[,i,a]=r;if(i===`metadata`&&a.trim()===``){n=!0;continue}let o=pr(a);if(o)return o}}function hr(e,t){try{let n=E(t,`utf8`),i=mr(n);return{filePath:t,displayPath:sr(e,t),content:n,parsed:i?null:r(n),yamlError:i}}catch{return null}}function gr(e){return cr(e).map(t=>hr(e,t)).filter(e=>e!==null)}function _r(e){if(!e.parsed)return[];let t=e.parsed.fields.applyTo;return t?dr(t):[]}function vr(e){let t=e.trim();if(!t)return`glob pattern is empty`;let n=[],r={"[":`]`,"{":`}`,"(":`)`},i=new Set(Object.values(r));for(let e=0;e<t.length;e+=1){let a=t[e];if(t[e-1]!==`\\`){if(a in r){n.push(r[a]);continue}if(i.has(a)&&n.pop()!==a)return`glob pattern has an unexpected '${a}'`}}if(n.length>0)return`glob pattern is missing '${n[n.length-1]}'`}function yr(e){let t=new Set;for(let n of e.matchAll(/<skill>\s*([a-z][a-z0-9-]*)\s*<\/skill>/gi))t.add(n[1].toLowerCase());let n=e.split(/\r?\n/),r=!1;for(let e of n){if(/^#{1,6}\s+skills\b/i.test(e)){r=!0;continue}if(r&&/^#{1,6}\s+/.test(e)&&(r=!1),!r)continue;let n=e.match(/^\|\s*([a-z][a-z0-9-]*)\s*\|/i);if(n){let e=n[1].toLowerCase();e!==`skill`&&t.add(e)}for(let n of e.matchAll(/`([a-z][a-z0-9-]*)`/gi))t.add(n[1].toLowerCase())}return[...t]}const br={name:`yaml-parse`,run:e=>{try{return gr(e).filter(e=>e.yamlError).map(e=>({severity:`error`,file:e.displayPath,message:`invalid YAML frontmatter: ${e.yamlError}`,code:`yaml-parse-error`}))}catch{return[]}}},xr={name:`skill-refs`,run:e=>{try{let t=lr(e);if(t.size===0)return[];let n=[];for(let r of gr(e))if(r.filePath.endsWith(`.agent.md`))for(let e of yr(r.content))t.has(e)||n.push({severity:`warning`,file:r.displayPath,message:`referenced skill '${e}' was not found in .copilot/skills or .agents/skills`,code:`skill-ref-missing`});return n}catch{return[]}}},Sr={name:`tool-names`,run:e=>{try{let t=[];for(let n of gr(e))if(n.parsed)for(let e of n.parsed.tools.map(fr))e&&!or.test(e)&&t.push({severity:`warning`,file:n.displayPath,message:`tool '${e}' should use an aikit-prefixed name`,code:`tool-name-invalid`});return t}catch{return[]}}},Cr={name:`glob-patterns`,run:e=>{try{let t=[];for(let n of gr(e))if(n.parsed)for(let e of _r(n)){let r=vr(e);r&&t.push({severity:`warning`,file:n.displayPath,message:`applyTo pattern '${e}' is invalid: ${r}`,code:`glob-pattern-invalid`})}return t}catch{return[]}}};async function G(e){let t=console.log;console.log=()=>{};try{return await e()}finally{console.log=t}}async function wr(e){let t=e.reset??!1,n=e.silent??!1,r=[],i=0,a=0,o=await Bn({scope:`user`}),s=Xn(),c=S(),l=ae(),u=e=>{r.push(e),a+=1,n||console.log(`- ${e}`)};for(let e of o){let n=e.getConfigPath();if(i+=1,!w(n)){T(A(n),{recursive:!0}),await G(()=>e.registerMcp(g,s)),u(`Fixed: ${e.name} — MCP config was missing, recreated`);continue}try{if(!(await e.readConfig())[e.configKey]?.aikit){T(A(n),{recursive:!0}),await G(()=>e.registerMcp(g,s)),u(`Fixed: ${e.name} — MCP entry was missing, added`);continue}t&&(T(A(n),{recursive:!0}),await G(()=>e.registerMcp(g,s)),u(`Reset: ${e.name} — MCP config restored to factory defaults`))}catch{ye(n,`${n}.bak`),T(A(n),{recursive:!0}),await G(()=>e.registerMcp(g,s)),u(`Fixed: ${e.name} — MCP config was corrupt, backed up and recreated`)}}await G(async()=>{for(let e of o)er(e,t)}),await G(()=>tr(c,o,g,l??`0.0.0`,t));let d=[br,xr,Sr,Cr];for(let e of d)try{let t=e.run(process.cwd());for(let e of t)(e.severity===`error`||e.severity===`warning`)&&(n||console.warn(`[doctor:${e.code}] ${e.file}: ${e.message}`))}catch{}if(n){if(r.length>0)for(let e of r)console.error(`[doctor] ${e}`)}else r.length===0&&console.log(`- No MCP config issues found.`);return{checked:i,fixed:a,issues:r}}const Tr=[{name:`doctor`,description:`Check and repair AI Kit configuration files`,usage:`aikit doctor [--reset]`,run:async e=>{let t=e.includes(`--reset`);console.log(t?`Resetting AI Kit to factory defaults...
|
|
9
9
|
`:`Running AI Kit doctor...
|
|
10
|
-
`);let n=await
|
|
11
|
-
Issues found:`);for(let e of n.issues)console.log(` - ${e}`)}}}],Tr=[{name:`proc`,description:`Manage in-memory child processes`,usage:`aikit proc <start|stop|status|list|logs> ...`,run:async e=>{let t=e.shift()?.trim()??``;switch(t){case`start`:{let t=e.shift()?.trim(),n=e.shift()?.trim();(!t||!n)&&(console.error(`Usage: aikit proc start <id> <command> [args...]`),process.exit(1)),c(Et(t,n,e));return}case`stop`:{let t=e.shift()?.trim();t||(console.error(`Usage: aikit proc stop <id>`),process.exit(1));let n=Ot(t);if(!n){console.log(`No managed process found: ${t}`);return}c(n);return}case`status`:{let t=e.shift()?.trim();t||(console.error(`Usage: aikit proc status <id>`),process.exit(1));let n=Dt(t);if(!n){console.log(`No managed process found: ${t}`);return}c(n);return}case`list`:{let e=wt();if(e.length===0){console.log(`No managed processes.`);return}for(let t of e)c(t),console.log(``);return}case`logs`:{let t=g(e,`--tail`,50),n=e.shift()?.trim();n||(console.error(`Usage: aikit proc logs <id> [--tail N]`),process.exit(1));let r=Tt(n,t);if(r.length===0){console.log(`No logs found for process: ${n}`);return}for(let e of r)console.log(e);return}default:console.error(`Unknown proc action: ${t}`),console.error(`Actions: start, stop, status, list, logs`),process.exit(1)}}},{name:`watch`,description:`Manage in-memory filesystem watchers`,usage:`aikit watch <start|stop|list> ...`,run:async e=>{let t=e.shift()?.trim()??``;switch(t){case`start`:{let t=e.shift()?.trim();t||(console.error(`Usage: aikit watch start <path>`),process.exit(1));let n=en({path:M(t)});console.log(`Started watcher: ${n.id}`),console.log(` Path: ${n.path}`),console.log(` Status: ${n.status}`);return}case`stop`:{let t=e.shift()?.trim();t||(console.error(`Usage: aikit watch stop <id>`),process.exit(1));let n=tn(t);console.log(n?`Stopped watcher: ${t}`:`Watcher not found: ${t}`);return}case`list`:{let e=$t();if(e.length===0){console.log(`No active watchers.`);return}for(let t of e)console.log(`${t.id}`),console.log(` Path: ${t.path}`),console.log(` Status: ${t.status}`),console.log(` Events: ${t.eventCount}`);return}default:console.error(`Unknown watch action: ${t}`),console.error(`Actions: start, stop, list`),process.exit(1)}}},{name:`delegate`,description:`Delegate a task to a local Ollama model`,usage:`aikit delegate [--model name] [--system prompt] [--temp 0.3] <prompt | --stdin>`,run:async e=>{if((e[0]===`models`?e.shift():void 0)===`models`){try{let e=await rt();if(e.length===0){console.log(`No Ollama models available. Pull one with: ollama pull gemma4:e2b`);return}for(let t of e)console.log(t)}catch{console.error(`Ollama is not running. Start it with: ollama serve`),process.exit(1)}return}let t=_(e,`--model`,``),n=_(e,`--system`,``),r=g(e,`--temp`,.3),i=_(e,`--context`,``),a=e.join(` `);a||=await p(),a||(console.error(`Usage: aikit delegate [--model name] <prompt>`),process.exit(1));let o;i&&(o=await Ve(M(i),`utf-8`));let s=await nt({prompt:a,model:t||void 0,system:n||void 0,context:o,temperature:r});s.error&&(console.error(`Error: ${s.error}`),process.exit(1)),console.log(s.response),console.error(`\n(${s.model}, ${s.durationMs}ms, ${s.tokenCount??`?`} tokens)`)}}],Er=[{name:`eval`,description:`Evaluate JavaScript or TypeScript in a constrained VM sandbox`,usage:`aikit eval [code] [--lang js|ts] [--timeout ms]`,run:async e=>{let t=_(e,`--lang`,`js`),n=g(e,`--timeout`,5e3),r=e.join(` `),i=r.trim()?``:await p(),a=r||i;if(!a.trim())throw new h(`Usage: aikit eval [code] [--lang js|ts] [--timeout ms]`);let o=await ot({code:a,lang:t===`ts`?`ts`:`js`,timeout:n});if(!o.success){console.error(`Eval failed in ${o.durationMs}ms: ${o.error}`),process.exitCode=1;return}console.log(`Eval succeeded in ${o.durationMs}ms`),console.log(`─`.repeat(60)),console.log(o.output)}},{name:`proxy`,description:`Run stdio-to-HTTP proxy for IDE MCP integration`,usage:`aikit proxy [--port port] [--no-auto-start]`,run:async e=>{let t=g(e,`--port`,3210),n=!me(e,`--no-auto-start`),{runProxy:r}=await import(`../../server/dist/proxy.js`);await r({port:t,autoStart:n})}},{name:`test`,description:`Run Vitest for all tests or a specific subset`,usage:`aikit test [files...] [--grep pattern] [--cwd path] [--timeout ms]`,run:async e=>{let t=_(e,`--grep`,``).trim()||void 0,n=_(e,`--cwd`,``).trim()||void 0,r=g(e,`--timeout`,6e4),i=e.filter(Boolean),a=await Zt({files:i.length>0?i:void 0,grep:t,cwd:n,timeout:r});o(a),a.passed||(process.exitCode=1)}},{name:`rename`,description:`Rename a symbol across files using whole-word regex matching`,usage:`aikit rename <old> <new> <path> [--dry-run] [--extensions .ts,.tsx] [--exclude dist/**]`,run:async e=>{let t=e.shift()?.trim()??``,n=e.shift()?.trim()??``,r=e.shift()?.trim()??``;if(!t||!n||!r)throw new h(`Usage: aikit rename <old> <new> <path> [--dry-run] [--extensions .ts,.tsx] [--exclude dist/**]`);let i=d(_(e,`--extensions`,``)),a=d(_(e,`--exclude`,``)),o=await zt({oldName:t,newName:n,rootPath:M(r),extensions:i.length>0?i:void 0,exclude:a.length>0?a:void 0,dryRun:me(e,`--dry-run`)});console.log(JSON.stringify(o,null,2))}},{name:`codemod`,description:`Apply regex-based codemod rules from a JSON file across a path`,usage:`aikit codemod <path> --rules <file.json> [--dry-run] [--extensions .ts,.tsx] [--exclude dist/**]`,run:async e=>{let t=e.shift()?.trim()??``,n=_(e,`--rules`,``).trim();if(!t||!n)throw new h(`Usage: aikit codemod <path> --rules <file.json> [--dry-run] [--extensions .ts,.tsx] [--exclude dist/**]`);let r=await Ve(M(n),`utf-8`),i;try{i=JSON.parse(r)}catch{throw Error(`Failed to parse rules file as JSON: ${n}`)}if(!Array.isArray(i))throw Error(`Codemod rules file must contain a JSON array.`);let a=d(_(e,`--extensions`,``)),o=d(_(e,`--exclude`,``)),s=await $e({rootPath:M(t),rules:i,extensions:a.length>0?a:void 0,exclude:o.length>0?o:void 0,dryRun:me(e,`--dry-run`)});console.log(JSON.stringify(s,null,2))}},{name:`transform`,description:`Apply jq-like transforms to JSON from stdin`,usage:`cat data.json | aikit transform <expression>`,run:async e=>{let t=e.join(` `).trim(),n=await p();if(!t||!n.trim())throw new h(`Usage: cat data.json | aikit transform <expression>`);let r=tt({input:n,expression:t});console.log(r.outputString)}}];async function Dr(){let e=await import(`../../flows/dist/index.js`),{FlowLoader:t,FlowRegistryManager:n,FlowStateMachine:r,GitInstaller:i}=e,a=typeof e.getBuiltinFlows==`function`?e.getBuiltinFlows:void 0,o=ln(),s=o.stateDir;if(!s)throw Error(`stateDir not configured`);let c=A(s,`flows`,`installed`),l=A(ke(),`flows`);w(l,{recursive:!0});let u=A(l,`registry.json`),d=o.sources[0].path,f=A(d,`.flows`);return{loader:new t,registry:new n(u),stateMachine:new r(f,{before:[],after:[{id:`_docs-sync`,description:`Synchronize project documentation — update docs/ folder based on changes made during the flow.`,position:`after`,skills:[`docs`]}]}),git:new i(c),getBuiltinFlows:a,cwd:d}}const Or=[e=>A(`skills`,e,`SKILL.md`),e=>A(`skills`,e,`README.md`),e=>A(e,`SKILL.md`),e=>A(e,`README.md`)];function kr(e,t){for(let n of t.steps){let t=A(e,n.instruction);if(C(t))continue;let r=!1;for(let i of Or){let a=A(e,i(n.id));if(C(a)){let e=k(t);C(e)||w(e,{recursive:!0}),ye(a,t),r=!0;break}}r||console.warn(`Warning: instruction file for step "${n.id}" not found.\n Expected: ${n.instruction}\n Searched: ${Or.map(e=>e(n.id)).join(`, `)}`)}}const Ar=[{name:`flow`,description:`Manage pluggable development flows`,usage:`flow <add|remove|list|info|use|update|status|start|reset> [args]`,run:async e=>{let t=e[0];if(!t){console.log(`Usage: aikit flow <add|remove|list|info|use|update|status|start|reset|runs>`),console.log(``),console.log(`Commands:`),console.log(` add <source> Install a flow from git URL or local path`),console.log(` remove <name> Remove an installed flow`),console.log(` list List all installed flows`),console.log(` info <name> Show details of a flow`),console.log(` use <name> Set active flow (start it)`),console.log(` update <name> Update a flow from its source`),console.log(` status Show current flow execution status`),console.log(` start [name] Start a flow (or resume)`),console.log(` reset Reset the active flow`),console.log(` runs List all flow runs`);return}let n=await Dr();switch(t){case`add`:{let t=e[1];if(!t){console.error(`Usage: aikit flow add <source>`),console.error(` source: git URL (https://...) or local path`);return}let r=t.startsWith(`http`)||t.startsWith(`git@`)||t.endsWith(`.git`),i=M(t),a=C(i);if(!r&&!a){console.error(`Source not found: ${t}`),console.error(`Provide a git URL or existing local path.`);return}let o,s;if(r){console.log(`Cloning ${t}...`);let e=n.git.clone(t);if(!e.success||!e.data){console.error(e.error??`Failed to clone flow`);return}o=e.data,s=`git`}else{let r=e[2]||Ce(i);console.log(`Copying local flow from ${t}...`);let a=n.git.copyLocal(i,r);if(!a.success||!a.data){console.error(a.error??`Failed to copy local flow`);return}o=a.data,s=`local`}let c=await n.loader.load(o);if(!c.success||!c.data){console.error(c.error??`Failed to load flow`),n.git.remove(o);return}let{manifest:l,format:u}=c.data;if(kr(o,l),l.install.length>0){console.log(`Installing ${l.install.length} dependencies...`);let e=n.git.runInstallDeps(l.install);if(!e.success){console.error(`Dependency install failed: ${e.error}`),n.git.remove(o);return}}let d=new Date().toISOString(),f=n.registry.register({name:l.name,version:l.version,source:t,sourceType:s,installPath:o,format:u,registeredAt:d,updatedAt:d,manifest:l});if(!f.success){console.error(f.error??`Failed to register flow`),n.git.remove(o);return}console.log(`✓ Flow "${l.name}" v${l.version} installed (${u} format)`),console.log(` Steps: ${l.steps.map(e=>e.id).join(` → `)}`);break}case`remove`:{let t=e[1];if(!t){console.error(`Usage: aikit flow remove <name>`);return}let r=n.registry.get(t);if(!r){console.error(`Flow "${t}" not found`);return}let i=n.git.remove(r.installPath);if(!i.success){console.error(i.error??`Failed to remove flow files`);return}let a=n.registry.unregister(t);if(!a.success){console.error(a.error??`Failed to unregister flow`);return}console.log(`✓ Flow "${t}" removed`);break}case`list`:{let e=n.registry.list();if(e.length===0){console.log("No flows installed. Use `aikit flow add <source>` to install one.");return}console.log(`Installed Flows:`),console.log(`─`.repeat(60));for(let t of e){let e=t.manifest.steps.map(e=>e.id).join(` → `);console.log(` ${t.name} v${t.version} (${t.sourceType}, ${t.format})`),console.log(` Steps: ${e}`)}let t=n.stateMachine.getStatus();t.success&&t.data&&(console.log(``),console.log(`Active: ${t.data.flow} (${t.data.status}, step: ${t.data.currentStep??`done`})`));break}case`info`:{let t=e[1];if(!t){console.error(`Usage: aikit flow info <name>`);return}let r=n.registry.get(t);if(!r){console.error(`Flow "${t}" not found`);return}console.log(`Flow: ${r.name}`),console.log(`Version: ${r.version}`),console.log(`Source: ${r.source} (${r.sourceType})`),console.log(`Format: ${r.format}`),console.log(`Path: ${r.installPath}`),console.log(`Registered: ${r.registeredAt}`),console.log(`Updated: ${r.updatedAt}`),console.log(``),console.log(`Steps:`);for(let e of r.manifest.steps){let t=e.requires.length?` (requires: ${e.requires.join(`, `)})`:``;console.log(` ${e.id}: ${e.name}${t}`),console.log(` Skill: ${e.skill}`),console.log(` Produces: ${e.produces.join(`, `)}`)}if(r.manifest.install.length>0){console.log(``),console.log(`Dependencies:`);for(let e of r.manifest.install)console.log(` ${e}`)}break}case`use`:case`start`:{let r=e[1],i=r?n.registry.get(r):null;if(t===`use`&&!r){console.error(`Usage: aikit flow use <name>`);return}if(t===`start`&&!r){let e=n.stateMachine.getStatus();if(e.success&&e.data&&e.data.status===`active`){console.log(`Resuming flow: ${e.data.flow}`),console.log(`Current step: ${e.data.currentStep}`),console.log(`Completed: ${e.data.completedSteps.join(`, `)||`none`}`);return}console.error("No active flow. Use `aikit flow start <name>` to begin one.");return}if(!i){console.error(`Flow "${r}" not found. Use \`aikit flow list\` to see installed flows.`);return}let a=e[2],o=n.stateMachine.start(i.name,i.manifest,a);if(!o.success||!o.data){console.error(o.error??`Failed to start flow`);return}let s=o.data;console.log(`✓ Flow "${i.name}" started`),console.log(` Topic: ${s.topic}`),console.log(` Run directory: ${s.runDir}`),console.log(` Current step: ${s.currentStep}`),console.log(` Steps: ${i.manifest.steps.map(e=>e.id).join(` → `)}`);break}case`update`:{let t=e[1];if(!t){console.error(`Usage: aikit flow update <name>`);return}let r=n.registry.get(t);if(!r){console.error(`Flow "${t}" not found`);return}if(r.sourceType!==`git`){console.error(`Flow "${t}" is ${r.sourceType}, not updatable via git`);return}console.log(`Updating ${t}...`);let i=n.git.update(r.installPath);if(!i.success){console.error(i.error??`Failed to update flow`);return}let a=await n.loader.load(r.installPath);if(a.success&&a.data){let e=new Date().toISOString(),t=n.registry.register({...r,version:a.data.manifest.version,format:a.data.format,manifest:a.data.manifest,updatedAt:e});if(!t.success){console.error(t.error??`Failed to refresh flow registry entry`);return}}console.log(`✓ Flow "${t}" updated`);break}case`status`:{let e=n.stateMachine.getStatus();if(!e.success||!e.data){console.log(`No active flow.`);return}let t=e.data;if(console.log(`Flow: ${t.flow}`),console.log(`Topic: ${t.topic}`),console.log(`Slug: ${t.slug}`),console.log(`Run Dir: ${t.runDir}`),console.log(`Status: ${t.status}`),console.log(`Current Step: ${t.currentStep??`(completed)`}`),console.log(`Completed: ${t.completedSteps.join(`, `)||`none`}`),t.skippedSteps.length>0&&console.log(`Skipped: ${t.skippedSteps.join(`, `)}`),console.log(`Started: ${t.startedAt}`),console.log(`Updated: ${t.updatedAt}`),Object.keys(t.artifacts).length>0){console.log(`Artifacts:`);for(let[e,n]of Object.entries(t.artifacts))console.log(` ${e}: ${n}`)}break}case`reset`:{let e=n.stateMachine.reset();if(!e.success){console.error(e.error??`Failed to reset flow state`);return}console.log(`✓ Flow abandoned`);break}case`runs`:{let t=e[1],r=e[2],i=n.stateMachine.listRuns({flow:t,status:r});if(i.length===0){console.log(`No flow runs found.`);return}console.log(`Flow Runs:`),console.log(`─`.repeat(80));for(let e of i){let t=e.currentStep?` → ${e.currentStep}`:``;console.log(` ${e.id} [${e.status}] ${e.flow}${t}`),console.log(` Topic: ${e.topic}`),console.log(` Started: ${e.startedAt} | Updated: ${e.updatedAt}`)}break}default:console.error(`Unknown flow command: ${t}`),console.log("Use `aikit flow` for help.")}}}],G=F(`cli:gc`),jr=A(L(),`.aikit`,`versions`),Mr=A(L(),`.aikit`,`current-version.json`);function Nr(e){let t=e.match(/^v(\d+)\.(\d+)\.(\d+)$/);return t?{major:Number.parseInt(t[1],10),minor:Number.parseInt(t[2],10),patch:Number.parseInt(t[3],10)}:null}function Pr(e,t){return e.major===t.major?e.minor===t.minor?t.patch-e.patch:t.minor-e.minor:t.major-e.major}function Fr(){try{return C(Mr)?JSON.parse(T(Mr,`utf-8`)).version??null:null}catch{return null}}const Ir=[{name:`gc`,description:`Free disk space by removing old AI Kit versions (keeps current + last N)`,usage:`aikit gc [--keep N]`,run:async e=>{if(!C(jr)){G.info(`No version directories found.`);return}let t=g(e,`--keep`,2),n=Fr(),r=E(jr,{withFileTypes:!0}),i=new Set(r.filter(e=>e.isDirectory()&&(e.name.includes(`-staging`)||e.name.startsWith(`_offline-detect-`)||e.name.startsWith(`_aikit-tarball-staging-`))).map(e=>e.name));for(let e of i)await Ue(A(jr,e),{recursive:!0,force:!0}),G.debug(`Removed ${e}`);let a=r.filter(e=>e.isDirectory()&&!i.has(e.name)).map(e=>({name:e.name,semver:Nr(e.name)})).filter(e=>e.semver!==null).sort((e,t)=>Pr(e.semver,t.semver));if(a.length===0){G.info(`No version directories found.`);return}let o=new Set;n&&o.add(`v${n}`);for(let e of a){if(o.size>=t+ +!!n)break;o.add(e.name)}let s=a.filter(e=>!o.has(e.name));if(s.length===0){G.info(`No versions to clean`);return}for(let e of s)await Ue(A(jr,e.name),{recursive:!0,force:!0}),G.debug(`Removed ${e.name}`);G.info(`Removed ${s.length} versions`)}}];let Lr=null;async function K(){return Lr||=await fn(),Lr}function Rr(){return Lr}const zr=[{name:`graph`,description:`Query the knowledge graph`,usage:`aikit graph <action> [options]
|
|
10
|
+
`);let n=await wr({reset:t,silent:!1});if(console.log(`\nDone: ${n.checked} checked, ${n.fixed} fixed.`),n.issues.length>0){console.log(`
|
|
11
|
+
Issues found:`);for(let e of n.issues)console.log(` - ${e}`)}}}],Er=[{name:`proc`,description:`Manage in-memory child processes`,usage:`aikit proc <start|stop|status|list|logs> ...`,run:async e=>{let t=e.shift()?.trim()??``;switch(t){case`start`:{let t=e.shift()?.trim(),n=e.shift()?.trim();(!t||!n)&&(console.error(`Usage: aikit proc start <id> <command> [args...]`),process.exit(1)),c(Et(t,n,e));return}case`stop`:{let t=e.shift()?.trim();t||(console.error(`Usage: aikit proc stop <id>`),process.exit(1));let n=Ot(t);if(!n){console.log(`No managed process found: ${t}`);return}c(n);return}case`status`:{let t=e.shift()?.trim();t||(console.error(`Usage: aikit proc status <id>`),process.exit(1));let n=Dt(t);if(!n){console.log(`No managed process found: ${t}`);return}c(n);return}case`list`:{let e=wt();if(e.length===0){console.log(`No managed processes.`);return}for(let t of e)c(t),console.log(``);return}case`logs`:{let t=y(e,`--tail`,50),n=e.shift()?.trim();n||(console.error(`Usage: aikit proc logs <id> [--tail N]`),process.exit(1));let r=Tt(n,t);if(r.length===0){console.log(`No logs found for process: ${n}`);return}for(let e of r)console.log(e);return}default:console.error(`Unknown proc action: ${t}`),console.error(`Actions: start, stop, status, list, logs`),process.exit(1)}}},{name:`watch`,description:`Manage in-memory filesystem watchers`,usage:`aikit watch <start|stop|list> ...`,run:async e=>{let t=e.shift()?.trim()??``;switch(t){case`start`:{let t=e.shift()?.trim();t||(console.error(`Usage: aikit watch start <path>`),process.exit(1));let n=en({path:N(t)});console.log(`Started watcher: ${n.id}`),console.log(` Path: ${n.path}`),console.log(` Status: ${n.status}`);return}case`stop`:{let t=e.shift()?.trim();t||(console.error(`Usage: aikit watch stop <id>`),process.exit(1));let n=tn(t);console.log(n?`Stopped watcher: ${t}`:`Watcher not found: ${t}`);return}case`list`:{let e=$t();if(e.length===0){console.log(`No active watchers.`);return}for(let t of e)console.log(`${t.id}`),console.log(` Path: ${t.path}`),console.log(` Status: ${t.status}`),console.log(` Events: ${t.eventCount}`);return}default:console.error(`Unknown watch action: ${t}`),console.error(`Actions: start, stop, list`),process.exit(1)}}},{name:`delegate`,description:`Delegate a task to a local Ollama model`,usage:`aikit delegate [--model name] [--system prompt] [--temp 0.3] <prompt | --stdin>`,run:async e=>{if((e[0]===`models`?e.shift():void 0)===`models`){try{let e=await rt();if(e.length===0){console.log(`No Ollama models available. Pull one with: ollama pull gemma4:e2b`);return}for(let t of e)console.log(t)}catch{console.error(`Ollama is not running. Start it with: ollama serve`),process.exit(1)}return}let t=b(e,`--model`,``),n=b(e,`--system`,``),r=y(e,`--temp`,.3),i=b(e,`--context`,``),a=e.join(` `);a||=await m(),a||(console.error(`Usage: aikit delegate [--model name] <prompt>`),process.exit(1));let o;i&&(o=await Ve(N(i),`utf-8`));let s=await nt({prompt:a,model:t||void 0,system:n||void 0,context:o,temperature:r});s.error&&(console.error(`Error: ${s.error}`),process.exit(1)),console.log(s.response),console.error(`\n(${s.model}, ${s.durationMs}ms, ${s.tokenCount??`?`} tokens)`)}}],Dr=[{name:`eval`,description:`Evaluate JavaScript or TypeScript in a constrained VM sandbox`,usage:`aikit eval [code] [--lang js|ts] [--timeout ms]`,run:async e=>{let t=b(e,`--lang`,`js`),n=y(e,`--timeout`,5e3),r=e.join(` `),i=r.trim()?``:await m(),a=r||i;if(!a.trim())throw new v(`Usage: aikit eval [code] [--lang js|ts] [--timeout ms]`);let o=await ot({code:a,lang:t===`ts`?`ts`:`js`,timeout:n});if(!o.success){console.error(`Eval failed in ${o.durationMs}ms: ${o.error}`),process.exitCode=1;return}console.log(`Eval succeeded in ${o.durationMs}ms`),console.log(`─`.repeat(60)),console.log(o.output)}},{name:`proxy`,description:`Run stdio-to-HTTP proxy for IDE MCP integration`,usage:`aikit proxy [--port port] [--no-auto-start]`,run:async e=>{let t=y(e,`--port`,3210),n=!C(e,`--no-auto-start`),{runProxy:r}=await import(`../../server/dist/proxy.js`);await r({port:t,autoStart:n})}},{name:`test`,description:`Run Vitest for all tests or a specific subset`,usage:`aikit test [files...] [--grep pattern] [--cwd path] [--timeout ms]`,run:async e=>{let t=b(e,`--grep`,``).trim()||void 0,n=b(e,`--cwd`,``).trim()||void 0,r=y(e,`--timeout`,6e4),i=e.filter(Boolean),a=await Zt({files:i.length>0?i:void 0,grep:t,cwd:n,timeout:r});o(a),a.passed||(process.exitCode=1)}},{name:`rename`,description:`Rename a symbol across files using whole-word regex matching`,usage:`aikit rename <old> <new> <path> [--dry-run] [--extensions .ts,.tsx] [--exclude dist/**]`,run:async e=>{let t=e.shift()?.trim()??``,n=e.shift()?.trim()??``,r=e.shift()?.trim()??``;if(!t||!n||!r)throw new v(`Usage: aikit rename <old> <new> <path> [--dry-run] [--extensions .ts,.tsx] [--exclude dist/**]`);let i=d(b(e,`--extensions`,``)),a=d(b(e,`--exclude`,``)),o=await zt({oldName:t,newName:n,rootPath:N(r),extensions:i.length>0?i:void 0,exclude:a.length>0?a:void 0,dryRun:C(e,`--dry-run`)});console.log(JSON.stringify(o,null,2))}},{name:`codemod`,description:`Apply regex-based codemod rules from a JSON file across a path`,usage:`aikit codemod <path> --rules <file.json> [--dry-run] [--extensions .ts,.tsx] [--exclude dist/**]`,run:async e=>{let t=e.shift()?.trim()??``,n=b(e,`--rules`,``).trim();if(!t||!n)throw new v(`Usage: aikit codemod <path> --rules <file.json> [--dry-run] [--extensions .ts,.tsx] [--exclude dist/**]`);let r=await Ve(N(n),`utf-8`),i;try{i=JSON.parse(r)}catch{throw Error(`Failed to parse rules file as JSON: ${n}`)}if(!Array.isArray(i))throw Error(`Codemod rules file must contain a JSON array.`);let a=d(b(e,`--extensions`,``)),o=d(b(e,`--exclude`,``)),s=await $e({rootPath:N(t),rules:i,extensions:a.length>0?a:void 0,exclude:o.length>0?o:void 0,dryRun:C(e,`--dry-run`)});console.log(JSON.stringify(s,null,2))}},{name:`transform`,description:`Apply jq-like transforms to JSON from stdin`,usage:`cat data.json | aikit transform <expression>`,run:async e=>{let t=e.join(` `).trim(),n=await m();if(!t||!n.trim())throw new v(`Usage: cat data.json | aikit transform <expression>`);let r=tt({input:n,expression:t});console.log(r.outputString)}}];async function Or(){let e=await import(`../../flows/dist/index.js`),{FlowLoader:t,FlowRegistryManager:n,FlowStateMachine:r,GitInstaller:i}=e,a=typeof e.getBuiltinFlows==`function`?e.getBuiltinFlows:void 0,o=ln(),s=o.stateDir;if(!s)throw Error(`stateDir not configured`);let c=j(s,`flows`,`installed`),l=j(ke(),`flows`);T(l,{recursive:!0});let u=j(l,`registry.json`),d=o.sources[0].path,f=j(d,`.flows`);return{loader:new t,registry:new n(u),stateMachine:new r(f,{before:[],after:[{id:`_docs-sync`,description:`Synchronize project documentation — update docs/ folder based on changes made during the flow.`,position:`after`,skills:[`docs`]}]}),git:new i(c),getBuiltinFlows:a,cwd:d}}const kr=[e=>j(`skills`,e,`SKILL.md`),e=>j(`skills`,e,`README.md`),e=>j(e,`SKILL.md`),e=>j(e,`README.md`)];function Ar(e,t){for(let n of t.steps){let t=j(e,n.instruction);if(w(t))continue;let r=!1;for(let i of kr){let a=j(e,i(n.id));if(w(a)){let e=A(t);w(e)||T(e,{recursive:!0}),ye(a,t),r=!0;break}}r||console.warn(`Warning: instruction file for step "${n.id}" not found.\n Expected: ${n.instruction}\n Searched: ${kr.map(e=>e(n.id)).join(`, `)}`)}}const jr=[{name:`flow`,description:`Manage pluggable development flows`,usage:`flow <add|remove|list|info|use|update|status|start|reset> [args]`,run:async e=>{let t=e[0];if(!t){console.log(`Usage: aikit flow <add|remove|list|info|use|update|status|start|reset|runs>`),console.log(``),console.log(`Commands:`),console.log(` add <source> Install a flow from git URL or local path`),console.log(` remove <name> Remove an installed flow`),console.log(` list List all installed flows`),console.log(` info <name> Show details of a flow`),console.log(` use <name> Set active flow (start it)`),console.log(` update <name> Update a flow from its source`),console.log(` status Show current flow execution status`),console.log(` start [name] Start a flow (or resume)`),console.log(` reset Reset the active flow`),console.log(` runs List all flow runs`);return}let n=await Or();switch(t){case`add`:{let t=e[1];if(!t){console.error(`Usage: aikit flow add <source>`),console.error(` source: git URL (https://...) or local path`);return}let r=t.startsWith(`http`)||t.startsWith(`git@`)||t.endsWith(`.git`),i=N(t),a=w(i);if(!r&&!a){console.error(`Source not found: ${t}`),console.error(`Provide a git URL or existing local path.`);return}let o,s;if(r){console.log(`Cloning ${t}...`);let e=n.git.clone(t);if(!e.success||!e.data){console.error(e.error??`Failed to clone flow`);return}o=e.data,s=`git`}else{let r=e[2]||Ce(i);console.log(`Copying local flow from ${t}...`);let a=n.git.copyLocal(i,r);if(!a.success||!a.data){console.error(a.error??`Failed to copy local flow`);return}o=a.data,s=`local`}let c=await n.loader.load(o);if(!c.success||!c.data){console.error(c.error??`Failed to load flow`),n.git.remove(o);return}let{manifest:l,format:u}=c.data;if(Ar(o,l),l.install.length>0){console.log(`Installing ${l.install.length} dependencies...`);let e=n.git.runInstallDeps(l.install);if(!e.success){console.error(`Dependency install failed: ${e.error}`),n.git.remove(o);return}}let d=new Date().toISOString(),f=n.registry.register({name:l.name,version:l.version,source:t,sourceType:s,installPath:o,format:u,registeredAt:d,updatedAt:d,manifest:l});if(!f.success){console.error(f.error??`Failed to register flow`),n.git.remove(o);return}console.log(`✓ Flow "${l.name}" v${l.version} installed (${u} format)`),console.log(` Steps: ${l.steps.map(e=>e.id).join(` → `)}`);break}case`remove`:{let t=e[1];if(!t){console.error(`Usage: aikit flow remove <name>`);return}let r=n.registry.get(t);if(!r){console.error(`Flow "${t}" not found`);return}let i=n.git.remove(r.installPath);if(!i.success){console.error(i.error??`Failed to remove flow files`);return}let a=n.registry.unregister(t);if(!a.success){console.error(a.error??`Failed to unregister flow`);return}console.log(`✓ Flow "${t}" removed`);break}case`list`:{let e=n.registry.list();if(e.length===0){console.log("No flows installed. Use `aikit flow add <source>` to install one.");return}console.log(`Installed Flows:`),console.log(`─`.repeat(60));for(let t of e){let e=t.manifest.steps.map(e=>e.id).join(` → `);console.log(` ${t.name} v${t.version} (${t.sourceType}, ${t.format})`),console.log(` Steps: ${e}`)}let t=n.stateMachine.getStatus();t.success&&t.data&&(console.log(``),console.log(`Active: ${t.data.flow} (${t.data.status}, step: ${t.data.currentStep??`done`})`));break}case`info`:{let t=e[1];if(!t){console.error(`Usage: aikit flow info <name>`);return}let r=n.registry.get(t);if(!r){console.error(`Flow "${t}" not found`);return}console.log(`Flow: ${r.name}`),console.log(`Version: ${r.version}`),console.log(`Source: ${r.source} (${r.sourceType})`),console.log(`Format: ${r.format}`),console.log(`Path: ${r.installPath}`),console.log(`Registered: ${r.registeredAt}`),console.log(`Updated: ${r.updatedAt}`),console.log(``),console.log(`Steps:`);for(let e of r.manifest.steps){let t=e.requires.length?` (requires: ${e.requires.join(`, `)})`:``;console.log(` ${e.id}: ${e.name}${t}`),console.log(` Skill: ${e.skill}`),console.log(` Produces: ${e.produces.join(`, `)}`)}if(r.manifest.install.length>0){console.log(``),console.log(`Dependencies:`);for(let e of r.manifest.install)console.log(` ${e}`)}break}case`use`:case`start`:{let r=e[1],i=r?n.registry.get(r):null;if(t===`use`&&!r){console.error(`Usage: aikit flow use <name>`);return}if(t===`start`&&!r){let e=n.stateMachine.getStatus();if(e.success&&e.data&&e.data.status===`active`){console.log(`Resuming flow: ${e.data.flow}`),console.log(`Current step: ${e.data.currentStep}`),console.log(`Completed: ${e.data.completedSteps.join(`, `)||`none`}`);return}console.error("No active flow. Use `aikit flow start <name>` to begin one.");return}if(!i){console.error(`Flow "${r}" not found. Use \`aikit flow list\` to see installed flows.`);return}let a=e[2],o=n.stateMachine.start(i.name,i.manifest,a);if(!o.success||!o.data){console.error(o.error??`Failed to start flow`);return}let s=o.data;console.log(`✓ Flow "${i.name}" started`),console.log(` Topic: ${s.topic}`),console.log(` Run directory: ${s.runDir}`),console.log(` Current step: ${s.currentStep}`),console.log(` Steps: ${i.manifest.steps.map(e=>e.id).join(` → `)}`);break}case`update`:{let t=e[1];if(!t){console.error(`Usage: aikit flow update <name>`);return}let r=n.registry.get(t);if(!r){console.error(`Flow "${t}" not found`);return}if(r.sourceType!==`git`){console.error(`Flow "${t}" is ${r.sourceType}, not updatable via git`);return}console.log(`Updating ${t}...`);let i=n.git.update(r.installPath);if(!i.success){console.error(i.error??`Failed to update flow`);return}let a=await n.loader.load(r.installPath);if(a.success&&a.data){let e=new Date().toISOString(),t=n.registry.register({...r,version:a.data.manifest.version,format:a.data.format,manifest:a.data.manifest,updatedAt:e});if(!t.success){console.error(t.error??`Failed to refresh flow registry entry`);return}}console.log(`✓ Flow "${t}" updated`);break}case`status`:{let e=n.stateMachine.getStatus();if(!e.success||!e.data){console.log(`No active flow.`);return}let t=e.data;if(console.log(`Flow: ${t.flow}`),console.log(`Topic: ${t.topic}`),console.log(`Slug: ${t.slug}`),console.log(`Run Dir: ${t.runDir}`),console.log(`Status: ${t.status}`),console.log(`Current Step: ${t.currentStep??`(completed)`}`),console.log(`Completed: ${t.completedSteps.join(`, `)||`none`}`),t.skippedSteps.length>0&&console.log(`Skipped: ${t.skippedSteps.join(`, `)}`),console.log(`Started: ${t.startedAt}`),console.log(`Updated: ${t.updatedAt}`),Object.keys(t.artifacts).length>0){console.log(`Artifacts:`);for(let[e,n]of Object.entries(t.artifacts))console.log(` ${e}: ${n}`)}break}case`reset`:{let e=n.stateMachine.reset();if(!e.success){console.error(e.error??`Failed to reset flow state`);return}console.log(`✓ Flow abandoned`);break}case`runs`:{let t=e[1],r=e[2],i=n.stateMachine.listRuns({flow:t,status:r});if(i.length===0){console.log(`No flow runs found.`);return}console.log(`Flow Runs:`),console.log(`─`.repeat(80));for(let e of i){let t=e.currentStep?` → ${e.currentStep}`:``;console.log(` ${e.id} [${e.status}] ${e.flow}${t}`),console.log(` Topic: ${e.topic}`),console.log(` Started: ${e.startedAt} | Updated: ${e.updatedAt}`)}break}default:console.error(`Unknown flow command: ${t}`),console.log("Use `aikit flow` for help.")}}}],K=I(`cli:gc`),Mr=j(R(),`.aikit`,`versions`),Nr=j(R(),`.aikit`,`current-version.json`);function Pr(e){let t=e.match(/^v(\d+)\.(\d+)\.(\d+)$/);return t?{major:Number.parseInt(t[1],10),minor:Number.parseInt(t[2],10),patch:Number.parseInt(t[3],10)}:null}function Fr(e,t){return e.major===t.major?e.minor===t.minor?t.patch-e.patch:t.minor-e.minor:t.major-e.major}function Ir(){try{return w(Nr)?JSON.parse(E(Nr,`utf-8`)).version??null:null}catch{return null}}const Lr=[{name:`gc`,description:`Free disk space by removing old AI Kit versions (keeps current + last N)`,usage:`aikit gc [--keep N]`,run:async e=>{if(!w(Mr)){K.info(`No version directories found.`);return}let t=y(e,`--keep`,2),n=Ir(),r=D(Mr,{withFileTypes:!0}),i=new Set(r.filter(e=>e.isDirectory()&&(e.name.includes(`-staging`)||e.name.startsWith(`_offline-detect-`)||e.name.startsWith(`_aikit-tarball-staging-`))).map(e=>e.name));for(let e of i)await Ue(j(Mr,e),{recursive:!0,force:!0}),K.debug(`Removed ${e}`);let a=r.filter(e=>e.isDirectory()&&!i.has(e.name)).map(e=>({name:e.name,semver:Pr(e.name)})).filter(e=>e.semver!==null).sort((e,t)=>Fr(e.semver,t.semver));if(a.length===0){K.info(`No version directories found.`);return}let o=new Set;n&&o.add(`v${n}`);for(let e of a){if(o.size>=t+ +!!n)break;o.add(e.name)}let s=a.filter(e=>!o.has(e.name));if(s.length===0){K.info(`No versions to clean`);return}for(let e of s)await Ue(j(Mr,e.name),{recursive:!0,force:!0}),K.debug(`Removed ${e.name}`);K.info(`Removed ${s.length} versions`)}}];let Rr=null;async function q(){return Rr||=await fn(),Rr}function zr(){return Rr}const Br=[{name:`graph`,description:`Query the knowledge graph`,usage:`aikit graph <action> [options]
|
|
12
12
|
Actions: stats, find-nodes, find-edges, neighbors, traverse, delete, clear
|
|
13
|
-
Options: --type, --name, --node-id, --edge-type, --direction, --depth, --limit, --source-path`,run:async e=>{let t=e.shift()?.trim()??``;if(!t)throw new
|
|
14
|
-
Actions: stats, find-nodes, find-edges, neighbors, traverse, delete, clear`);let{graphStore:n}=await
|
|
13
|
+
Options: --type, --name, --node-id, --edge-type, --direction, --depth, --limit, --source-path`,run:async e=>{let t=e.shift()?.trim()??``;if(!t)throw new v(`Usage: aikit graph <action>
|
|
14
|
+
Actions: stats, find-nodes, find-edges, neighbors, traverse, delete, clear`);let{graphStore:n}=await q(),r=b(e,`--type`,``),i=b(e,`--name`,``),a=b(e,`--node-id`,``),o=b(e,`--edge-type`,``),s=b(e,`--direction`,`both`),c=y(e,`--depth`,2),l=y(e,`--limit`,50),u=b(e,`--source-path`,``),d={stats:`stats`,"find-nodes":`find_nodes`,"find-edges":`find_edges`,neighbors:`neighbors`,traverse:`traverse`,delete:`delete`,clear:`clear`}[t];if(!d)throw new v(`Unknown graph action: ${t}\nActions: stats, find-nodes, find-edges, neighbors, traverse, delete, clear`);let f=await pt(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(`
|
|
15
15
|
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(`
|
|
16
|
-
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}`)}}],
|
|
16
|
+
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}`)}}],J=I(`cli:install`),Vr=/^\d+\.\d+\.\d+(-[\w.+]+)?(\+[\w.]+)?$/,Y=j(R(),`.aikit`),X=j(Y,`versions`),Hr=j(Y,`current-version.json`),Ur=`@vpxa/aikit`,Wr=`Usage:
|
|
17
17
|
aikit install
|
|
18
18
|
aikit install --version <version>
|
|
19
19
|
aikit install --offline <path-to-tarball>
|
|
@@ -35,12 +35,12 @@ After install, verify with:
|
|
|
35
35
|
Options:
|
|
36
36
|
--version <version> Install a specific version instead of latest
|
|
37
37
|
--offline <path> Install from a local tarball (no network needed)
|
|
38
|
-
--help, -h Show this help`;function Ur(e){if(!Br.test(e))throw Error(`Invalid semver version: ${JSON.stringify(e)}`)}async function Wr(){let e=await fetch(`https://registry.npmjs.org/${X}/latest`,{signal:AbortSignal.timeout(1e4)});if(!e.ok)throw Error(`Failed to fetch latest version from npm registry (HTTP ${e.status})`);let t=await e.json();if(!t.version)throw Error(`npm registry response missing "version" field`);return t.version}function Gr(e){let t=A(e,`packages`,`server`,`dist`,`bin.js`);if(!C(t))throw Error(`Server entry point not found at ${t}. The installation may be incomplete or corrupted.`);let n=A(e,`node_modules`);if(!C(n))throw Error(`node_modules not found at ${n}. Production dependencies may not have been installed.`)}function Kr(e){let t=A(e,`package.json`),n=JSON.parse(T(t,`utf-8`));if(!n.version)throw Error(`No "version" field in ${t}`);return n.version}function qr(e){C(J)||w(J,{recursive:!0});let t=A(J,`current-version.json.tmp`);O(t,`${JSON.stringify({version:e},null,2)}\n`),be(t,Vr)}function Jr(e){let t=E(e).filter(e=>e.endsWith(`.tgz`));return t.length>0?t[0]:null}function Yr(e,t){q.debug(`Extracting...`),I(`tar -xzf "${t}"`,{cwd:e,stdio:`pipe`,timeout:6e4});let n=A(e,`package`);if(!C(n))throw Error(`Expected "package/" directory not found after extraction`);return q.debug(`Installing production dependencies...`),I(`npm install --production --install-strategy=nested --no-audit --no-fund`,{cwd:n,stdio:`pipe`,timeout:3e5}),n}function Xr(e,t){let n=A(Y,`v${t}`);C(Y)||w(Y,{recursive:!0}),C(n)&&(q.debug(`Removing previous installation...`,{target:n}),D(n,{recursive:!0})),be(e,n),qr(t),q.info(`Installation complete`,{package:`${X}@${t}`,target:n})}function Zr(){let e={win32:`win32`,darwin:`darwin`,linux:`linux`},t={x64:`x64`,arm64:`arm64`},n=e[sn()],r=t[on()];return!n||!r?(q.warn(`Unknown platform, falling back to npm pack`,{platform:sn(),arch:on()}),``):`${n}-${r}`}function Qr(e){let t=Zr();if(!t)return null;let n=`aikit-v${e}-${t}.tar.gz`,r=A(A(J,`cache`,`tarballs`),n);return C(r)?r:null}function $r(e,t){let n=A(Y,`v${t}-staging`);C(n)&&D(n,{recursive:!0}),w(n,{recursive:!0});try{q.debug(`Extracting prebuilt tarball...`),I(`tar -xzf "${e}"`,{cwd:n,stdio:`pipe`,timeout:6e4});let r=A(n,`aikit-v${t}-${Zr()}`);if(!C(r)){let e=A(n,`package`);if(C(e)){q.debug(`Validating installation...`),Gr(e),Xr(e,t);return}throw Error(`Expected directory not found after extracting prebuilt tarball`)}q.debug(`Validating installation...`),Gr(r),Xr(r,t)}finally{C(n)&&D(n,{recursive:!0})}}function ei(e){Ur(e);let t=Qr(e);if(t){q.debug(`Found prebuilt tarball`,{path:t}),$r(t,e);return}let n=A(Y,`v${e}-staging`);C(n)&&D(n,{recursive:!0}),w(n,{recursive:!0});try{q.debug(`Downloading...`,{package:`${X}@${e}`}),I(`npm pack ${X}@${e}`,{cwd:n,stdio:`pipe`,timeout:12e4});let t=Jr(n);if(!t)throw Error(`No .tgz file found after npm pack`);let r=Yr(n,t);q.debug(`Validating installation...`),Gr(r),Xr(r,e)}finally{C(n)&&D(n,{recursive:!0})}}function ti(e){if(!C(e))throw Error(`Tarball not found: ${e}`);let t=A(Y,`_offline-detect-${Date.now()}`);w(t,{recursive:!0});let n;try{I(`tar -xzf "${e}"`,{cwd:t,stdio:`pipe`,timeout:6e4}),n=Kr(A(t,`package`))}finally{C(t)&&D(t,{recursive:!0})}q.debug(`Installing from local tarball...`,{package:`${X}@${n}`});let r=A(Y,`v${n}-staging`);C(r)&&D(r,{recursive:!0}),w(r,{recursive:!0});try{ye(e,A(r,`offline-${n}.tgz`));let t=Yr(r,`offline-${n}.tgz`);return q.debug(`Validating installation...`),Gr(t),Xr(t,n),n}finally{C(r)&&D(r,{recursive:!0})}}async function ni(e){try{let t=A(Y,`v${e}`,`packages`,`server`,`dist`,`bin.js`);if(!C(t)){q.warn(`Server entry not found — skipping MCP registration`,{serverPath:t});return}let n={command:process.execPath,args:[t,`serve`],type:`stdio`};if(process.platform!==`win32`){let e=process.env.PATH;e&&(n.env={PATH:e})}let r=await Bn({scope:`user`});if(r.length===0){q.info(`No supported IDEs detected for MCP registration`);return}let i=0;for(let e of r)try{await e.registerMcp(m,n),i++}catch(t){q.warn(`Failed to register MCP for ${e.name}`,{error:t.message})}i>0&&q.info(`MCP server configured for ${i} IDE(s) — using local install path`)}catch(e){q.warn(`MCP registration failed`,{error:e.message})}}const ri=[{name:`install`,description:`Install AI Kit to ~/.aikit/versions/ (one-time setup for fast local startup)`,usage:Hr,run:async e=>{let t=e.indexOf(`--version`),n=e.indexOf(`--offline`),r=t!==-1&&t+1<e.length,i=n!==-1&&n+1<e.length;if(e.includes(`--help`)||e.includes(`-h`)){console.log(Hr);return}if(i){let t=e[n+1];await ni(ti(t)),q.info(`Install complete — restart your IDE to use the new version`);return}let a;r?a=e[t+1]:(q.debug(`Checking npm registry for latest version...`),a=await Wr(),q.info(`Latest version detected`,{version:a})),ei(a),await ni(a),q.info(`Install complete — restart your IDE to use the new version`)}}],ii=[{name:`remember`,description:`Store curated knowledge`,usage:`aikit remember <title> --category <cat> [--tags tag1,tag2]`,run:async e=>{let t=_(e,`--category`,``).trim(),n=d(_(e,`--tags`,``)),r=e.shift()?.trim()??``,i=await p(),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 K(),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=_(e,`--reason`,``).trim(),n=e.shift()?.trim()??``;(!n||!t)&&(console.error(`Usage: aikit forget <path> --reason <reason>`),process.exit(1));let{curated:r}=await K(),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 K(),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=_(e,`--category`,``).trim()||void 0,n=_(e,`--tag`,``).trim()||void 0,{curated:r}=await K(),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=_(e,`--reason`,``).trim(),n=e.shift()?.trim()??``,r=await p();(!n||!t||!r.trim())&&(console.error(`Usage: aikit update <path> --reason <reason>`),process.exit(1));let{curated:i}=await K(),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=g(e,`--max-chars`,3e3),n=_(e,`--path`,``).trim()||void 0,r=_(e,`--segmentation`,`paragraph`),i=e.join(` `).trim(),a=n?void 0:await p();(!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 K(),s=n?await et(o,{path:n,query:i,maxChars:t,segmentation:r}):await et(o,{text:a??``,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)}}],Z=F(`cli:rollback`),ai=A(L(),`.aikit`,`versions`),oi=A(L(),`.aikit`,`current-version.json`),si=[{name:`rollback`,description:`Rollback to a previous AI Kit version (see "aikit versions" for available)`,usage:`aikit rollback <version>`,run:async e=>{let t=e[0];t||(console.error(`Usage: aikit rollback <version>`),console.error(`Example: aikit rollback 0.1.280`),process.exit(1)),Z.debug(`Validating version directory for v${t}...`);let n=A(ai,`v${t}`);C(n)||(Z.warn(`Version v${t} not found`),process.exit(1)),Z.debug(`Validating version dir...`);let r=A(n,`package.json`);C(r)||(Z.error(`Version v${t} is missing package.json`),process.exit(1));try{JSON.parse(T(r,`utf-8`)).version||(Z.error(`Version v${t} has invalid package.json (missing version field)`),process.exit(1))}catch{Z.error(`Version v${t} has invalid package.json`),process.exit(1)}let i=A(ai,`current-version.json.tmp`);await Ge(i,JSON.stringify({version:t},null,2),`utf-8`),await He(i,oi),Z.info(`Switched to v${t}`)}}],ci=[{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=v(e),n=g(e,`--limit`,5),r=_(e,`--mode`,`hybrid`),i=g(e,`--graph-hops`,0),a=e.join(` `).trim();if(!a)throw new h(`Usage: aikit search <query>`);let{embedder:o,store:s,graphStore:c}=await K(),d=await o.embedQuery(a),f;if(r===`keyword`)f=await s.ftsSearch(a,{limit:n});else if(r===`semantic`)f=await s.search(d,{limit:n});else{let[e,t]=await Promise.all([s.search(d,{limit:n*2}),s.ftsSearch(a,{limit:n*2}).catch(()=>[])]);f=u(e,t).slice(0,n)}if(t){l({query:a,results:f,graphHops:i});return}if(f.length===0){console.log(`No results found.`);return}for(let{record:e,score:t}of f){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(`${f.length} result(s) found.`),i>0&&f.length>0)try{let{graphAugmentSearch:e}=await import(`../../tools/dist/index.js`),t=(await e(c,f.map(e=>({recordId:e.record.id,score:e.score,sourcePath:e.record.sourcePath})),{hops:i,maxPerHit:5})).filter(e=>e.graphContext.nodes.length>0);if(t.length>0){console.log(`\nGraph context (${i} hop${i>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=v(e),n=g(e,`--limit`,10),r=_(e,`--glob`,``).trim()||void 0,i=_(e,`--pattern`,``).trim()||void 0,a=e.join(` `).trim()||void 0;if(!a&&!r&&!i)throw new h(`Usage: aikit find [query] [--glob <pattern>] [--pattern <regex>] [--limit N]`);let{embedder:o,store:s}=await K(),c=await ct(o,s,{query:a,glob:r,pattern:i,limit:n});if(t){l(c);return}if(c.results.length===0){console.log(`No matches found.`);return}console.log(`Strategies: ${c.strategies.join(`, `)}`),console.log(`Results: ${c.results.length} shown (${c.totalFound} total)`);for(let e of c.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=g(e,`--max-files`,15),n=e.join(` `).trim();if(!n)throw new h(`Usage: aikit scope-map <task> [--max-files N]`);let{embedder:r,store:i}=await K(),a=await Wt(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: ${ue(t.focusRanges)}`)}},{name:`symbol`,description:`Resolve a symbol definition, imports, and references`,usage:`aikit symbol <name> [--limit N]`,run:async e=>{let t=g(e,`--limit`,20),n=e.join(` `).trim();if(!n)throw new h(`Usage: aikit symbol <name> [--limit N]`);let{embedder:r,store:i}=await K();se(await Xt(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=_(e,`--direction`,`both`).trim()||`both`,n=g(e,`--max-depth`,3),r=e.join(` `).trim();if(!r||![`forward`,`backward`,`both`].includes(t))throw new h(`Usage: aikit trace <start> [--direction forward|backward|both] [--max-depth N]`);let{embedder:i,store:a}=await K();b(await Qt(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=g(e,`--limit`,5),n=_(e,`--content-type`,``).trim()||void 0,r=e.join(` `).trim();if(!r)throw new h(`Usage: aikit examples <query> [--limit N] [--content-type type]`);let{embedder:i,store:a}=await K();s(await ut(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=g(e,`--limit`,100),{embedder:n,store:r}=await K();_e(await lt(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();if(!t)throw new h(`Usage: aikit lookup <id>`);let{store:n}=await K(),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)}}}];async function li(e){let{port:t,noOpen:n,urlPath:r,commandName:i}=e;console.log(`Starting AI Kit server on port ${t}...`);let{spawn:a}=await import(`node:child_process`),{platform:o}=await import(`node:os`),s=te(),c=a(process.execPath,[s,`--transport`,`http`,`--port`,String(t)],{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env,AIKIT_TRANSPORT:`http`,AIKIT_PORT:String(t)}}),l=`http://localhost:${t}${r}`,u=`http://localhost:${t}/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)throw c.kill(),new h(`Server failed to start within 30 seconds.`);let f=i.charAt(0).toUpperCase()+i.slice(1);if(console.log(`AI Kit ${f}: ${l}`),console.log(`Press Ctrl+C to stop.`),!n){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 p=()=>{c.kill(),process.exit(0)};process.on(`SIGINT`,p),process.on(`SIGTERM`,p),await new Promise(e=>{c.on(`exit`,()=>e())})}const ui=[{name:`status`,description:`Show AI Kit index status and statistics`,run:async e=>{let t=v(e),{AIKIT_PATHS:n,computePartitionKey:r,getPartitionDir:i,isUserInstalled:a,listWorkspaces:o}=await import(`../../core/dist/index.js`),{existsSync:s}=await import(`node:fs`),c=process.cwd(),u=a(),d=s(M(c,`.vscode`,`mcp.json`)),f={mode:void 0,dataPath:void 0};if(u&&d)f.mode=`workspace (overrides user-level for this workspace)`,f.dataPath=M(c,n.data);else if(u){let e=r(c);f.mode=s(M(c,`AGENTS.md`))?`user (workspace scaffolded)`:`user (workspace not scaffolded)`,f.dataPath=i(e)}else f.mode=`workspace`,f.dataPath=M(c,n.data);u&&!d&&(f.workspaces=o().length);try{let{store:e}=await K(),t=await e.getStats(),n=await e.listSourcePaths();f.records=t.totalRecords,f.files=t.totalFiles,f.lastIndexed=t.lastIndexedAt??null,f.backend=t.storeBackend,f.model=t.embeddingModel,f.contentTypeBreakdown=t.contentTypeBreakdown,f.sourcePaths=n.slice(0,20),f.sourcePathTotal=n.length}catch{f.indexAvailable=!1}if(t){l(f);return}if(console.log(`AI Kit Status`),console.log(`─`.repeat(40)),console.log(` Mode: ${f.mode}`),console.log(` Data: ${f.dataPath}`),u&&!d){let e=o();console.log(` Registry: ${e.length} workspace(s) enrolled`)}if(f.records!==void 0){console.log(` Records: ${f.records}`),console.log(` Files: ${f.files}`),console.log(` Indexed: ${f.lastIndexed??`Never`}`),console.log(` Backend: ${f.backend}`),console.log(` Model: ${f.model}`),console.log(``),console.log(`Content Types:`);for(let[e,t]of Object.entries(f.contentTypeBreakdown))console.log(` ${e}: ${t}`);let e=f.sourcePaths;if(e.length>0){console.log(``),console.log(`Files (${f.sourcePathTotal} total):`);for(let t of e.slice(0,20))console.log(` ${t}`);f.sourcePathTotal>20&&console.log(` ... and ${f.sourcePathTotal-20} more`)}}else console.log(``),console.log(" Index not available — run `aikit reindex` to index this workspace.");u&&!d&&!s(M(c,`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 K();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(`
|
|
39
|
-
`)},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. Default: direct stdio (one server per workspace). Use --daemon to share a single HTTP daemon across multiple clients.`,usage:`aikit serve [--transport stdio|http] [--port N] [--daemon]`,run:async e=>{let t=
|
|
38
|
+
--help, -h Show this help`;function Gr(e){if(!Vr.test(e))throw Error(`Invalid semver version: ${JSON.stringify(e)}`)}async function Kr(){let e=await fetch(`https://registry.npmjs.org/${Ur}/latest`,{signal:AbortSignal.timeout(1e4)});if(!e.ok)throw Error(`Failed to fetch latest version from npm registry (HTTP ${e.status})`);let t=await e.json();if(!t.version)throw Error(`npm registry response missing "version" field`);return t.version}function qr(e){let t=j(e,`packages`,`server`,`dist`,`bin.js`);if(!w(t))throw Error(`Server entry point not found at ${t}. The installation may be incomplete or corrupted.`);let n=j(e,`node_modules`);if(!w(n))throw Error(`node_modules not found at ${n}. Production dependencies may not have been installed.`)}function Jr(e){let t=j(e,`package.json`),n=JSON.parse(E(t,`utf-8`));if(!n.version)throw Error(`No "version" field in ${t}`);return n.version}function Yr(e){w(Y)||T(Y,{recursive:!0});let t=j(Y,`current-version.json.tmp`);k(t,`${JSON.stringify({version:e},null,2)}\n`),be(t,Hr)}function Xr(e){let t=D(e).filter(e=>e.endsWith(`.tgz`));return t.length>0?t[0]:null}function Zr(e,t){J.debug(`Extracting...`),L(`tar -xzf "${t}"`,{cwd:e,stdio:`pipe`,timeout:6e4});let n=j(e,`package`);if(!w(n))throw Error(`Expected "package/" directory not found after extraction`);return J.debug(`Installing production dependencies...`),L(`npm install --production --install-strategy=nested --no-audit --no-fund`,{cwd:n,stdio:`pipe`,timeout:3e5}),n}function Qr(e,t){let n=j(X,`v${t}`);w(X)||T(X,{recursive:!0}),w(n)&&(J.debug(`Removing previous installation...`,{target:n}),O(n,{recursive:!0})),be(e,n),Yr(t),J.info(`Installation complete`,{package:`${Ur}@${t}`,target:n})}function $r(){let e={win32:`win32`,darwin:`darwin`,linux:`linux`},t={x64:`x64`,arm64:`arm64`},n=e[sn()],r=t[on()];return!n||!r?(J.warn(`Unknown platform, falling back to npm pack`,{platform:sn(),arch:on()}),``):`${n}-${r}`}function ei(e){let t=$r();if(!t)return null;let n=`aikit-v${e}-${t}.tar.gz`,r=j(j(Y,`cache`,`tarballs`),n);return w(r)?r:null}function ti(e,t){let n=j(X,`v${t}-staging`);w(n)&&O(n,{recursive:!0}),T(n,{recursive:!0});try{J.debug(`Extracting prebuilt tarball...`),L(`tar -xzf "${e}"`,{cwd:n,stdio:`pipe`,timeout:6e4});let r=j(n,`aikit-v${t}-${$r()}`);if(!w(r)){let e=j(n,`package`);if(w(e)){J.debug(`Validating installation...`),qr(e),Qr(e,t);return}throw Error(`Expected directory not found after extracting prebuilt tarball`)}J.debug(`Validating installation...`),qr(r),Qr(r,t)}finally{w(n)&&O(n,{recursive:!0})}}function ni(e){Gr(e);let t=ei(e);if(t){J.debug(`Found prebuilt tarball`,{path:t}),ti(t,e);return}let n=j(X,`v${e}-staging`);w(n)&&O(n,{recursive:!0}),T(n,{recursive:!0});try{J.debug(`Downloading...`,{package:`${Ur}@${e}`}),L(`npm pack ${Ur}@${e}`,{cwd:n,stdio:`pipe`,timeout:12e4});let t=Xr(n);if(!t)throw Error(`No .tgz file found after npm pack`);let r=Zr(n,t);J.debug(`Validating installation...`),qr(r),Qr(r,e)}finally{w(n)&&O(n,{recursive:!0})}}function ri(e){if(!w(e))throw Error(`Tarball not found: ${e}`);let t=j(X,`_offline-detect-${Date.now()}`);T(t,{recursive:!0});let n;try{L(`tar -xzf "${e}"`,{cwd:t,stdio:`pipe`,timeout:6e4}),n=Jr(j(t,`package`))}finally{w(t)&&O(t,{recursive:!0})}J.debug(`Installing from local tarball...`,{package:`${Ur}@${n}`});let r=j(X,`v${n}-staging`);w(r)&&O(r,{recursive:!0}),T(r,{recursive:!0});try{ye(e,j(r,`offline-${n}.tgz`));let t=Zr(r,`offline-${n}.tgz`);return J.debug(`Validating installation...`),qr(t),Qr(t,n),n}finally{w(r)&&O(r,{recursive:!0})}}async function ii(e){try{let t=j(X,`v${e}`,`packages`,`server`,`dist`,`bin.js`);if(!w(t)){J.warn(`Server entry not found — skipping MCP registration`,{serverPath:t});return}let n={command:process.execPath,args:[t,`serve`],type:`stdio`};if(process.platform!==`win32`){let e=process.env.PATH;e&&(n.env={PATH:e})}let r=await Bn({scope:`user`});if(r.length===0){J.info(`No supported IDEs detected for MCP registration`);return}let i=0;for(let e of r)try{await e.registerMcp(g,n),i++}catch(t){J.warn(`Failed to register MCP for ${e.name}`,{error:t.message})}i>0&&J.info(`MCP server configured for ${i} IDE(s) — using local install path`)}catch(e){J.warn(`MCP registration failed`,{error:e.message})}}const ai=[{name:`install`,description:`Install AI Kit to ~/.aikit/versions/ (one-time setup for fast local startup)`,usage:Wr,run:async e=>{let t=e.indexOf(`--version`),n=e.indexOf(`--offline`),r=t!==-1&&t+1<e.length,i=n!==-1&&n+1<e.length;if(e.includes(`--help`)||e.includes(`-h`)){console.log(Wr);return}if(i){let t=e[n+1];await ii(ri(t)),J.info(`Install complete — restart your IDE to use the new version`);return}let a;r?a=e[t+1]:(J.debug(`Checking npm registry for latest version...`),a=await Kr(),J.info(`Latest version detected`,{version:a})),ni(a),await ii(a),J.info(`Install complete — restart your IDE to use the new version`)}}],oi=[{name:`remember`,description:`Store curated knowledge`,usage:`aikit remember <title> --category <cat> [--tags tag1,tag2]`,run:async e=>{let t=b(e,`--category`,``).trim(),n=d(b(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 q(),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=b(e,`--reason`,``).trim(),n=e.shift()?.trim()??``;(!n||!t)&&(console.error(`Usage: aikit forget <path> --reason <reason>`),process.exit(1));let{curated:r}=await q(),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 q(),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=b(e,`--category`,``).trim()||void 0,n=b(e,`--tag`,``).trim()||void 0,{curated:r}=await q(),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=b(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 q(),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=y(e,`--max-chars`,3e3),n=b(e,`--path`,``).trim()||void 0,r=b(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 q(),s=n?await et(o,{path:n,query:i,maxChars:t,segmentation:r}):await et(o,{text:a??``,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)}}],Z=I(`cli:rollback`),si=j(R(),`.aikit`,`versions`),ci=j(R(),`.aikit`,`current-version.json`),li=[{name:`rollback`,description:`Rollback to a previous AI Kit version (see "aikit versions" for available)`,usage:`aikit rollback <version>`,run:async e=>{let t=e[0];t||(console.error(`Usage: aikit rollback <version>`),console.error(`Example: aikit rollback 0.1.280`),process.exit(1)),Z.debug(`Validating version directory for v${t}...`);let n=j(si,`v${t}`);w(n)||(Z.warn(`Version v${t} not found`),process.exit(1)),Z.debug(`Validating version dir...`);let r=j(n,`package.json`);w(r)||(Z.error(`Version v${t} is missing package.json`),process.exit(1));try{JSON.parse(E(r,`utf-8`)).version||(Z.error(`Version v${t} has invalid package.json (missing version field)`),process.exit(1))}catch{Z.error(`Version v${t} has invalid package.json`),process.exit(1)}let i=j(si,`current-version.json.tmp`);await Ge(i,JSON.stringify({version:t},null,2),`utf-8`),await He(i,ci),Z.info(`Switched to v${t}`)}}],ui=[{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=ie(e),n=y(e,`--limit`,5),r=b(e,`--mode`,`hybrid`),i=y(e,`--graph-hops`,0),a=e.join(` `).trim();if(!a)throw new v(`Usage: aikit search <query>`);let{embedder:o,store:s,graphStore:c}=await q(),d=await o.embedQuery(a),f;if(r===`keyword`)f=await s.ftsSearch(a,{limit:n});else if(r===`semantic`)f=await s.search(d,{limit:n});else{let[e,t]=await Promise.all([s.search(d,{limit:n*2}),s.ftsSearch(a,{limit:n*2}).catch(()=>[])]);f=u(e,t).slice(0,n)}if(t){l({query:a,results:f,graphHops:i});return}if(f.length===0){console.log(`No results found.`);return}for(let{record:e,score:t}of f){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(`${f.length} result(s) found.`),i>0&&f.length>0)try{let{graphAugmentSearch:e}=await import(`../../tools/dist/index.js`),t=(await e(c,f.map(e=>({recordId:e.record.id,score:e.score,sourcePath:e.record.sourcePath})),{hops:i,maxPerHit:5})).filter(e=>e.graphContext.nodes.length>0);if(t.length>0){console.log(`\nGraph context (${i} hop${i>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=ie(e),n=y(e,`--limit`,10),r=b(e,`--glob`,``).trim()||void 0,i=b(e,`--pattern`,``).trim()||void 0,a=e.join(` `).trim()||void 0;if(!a&&!r&&!i)throw new v(`Usage: aikit find [query] [--glob <pattern>] [--pattern <regex>] [--limit N]`);let{embedder:o,store:s}=await q(),c=await ct(o,s,{query:a,glob:r,pattern:i,limit:n});if(t){l(c);return}if(c.results.length===0){console.log(`No matches found.`);return}console.log(`Strategies: ${c.strategies.join(`, `)}`),console.log(`Results: ${c.results.length} shown (${c.totalFound} total)`);for(let e of c.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=y(e,`--max-files`,15),n=e.join(` `).trim();if(!n)throw new v(`Usage: aikit scope-map <task> [--max-files N]`);let{embedder:r,store:i}=await q(),a=await Wt(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: ${de(t.focusRanges)}`)}},{name:`symbol`,description:`Resolve a symbol definition, imports, and references`,usage:`aikit symbol <name> [--limit N]`,run:async e=>{let t=y(e,`--limit`,20),n=e.join(` `).trim();if(!n)throw new v(`Usage: aikit symbol <name> [--limit N]`);let{embedder:r,store:i}=await q();se(await Xt(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=b(e,`--direction`,`both`).trim()||`both`,n=y(e,`--max-depth`,3),r=e.join(` `).trim();if(!r||![`forward`,`backward`,`both`].includes(t))throw new v(`Usage: aikit trace <start> [--direction forward|backward|both] [--max-depth N]`);let{embedder:i,store:a}=await q();oe(await Qt(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=y(e,`--limit`,5),n=b(e,`--content-type`,``).trim()||void 0,r=e.join(` `).trim();if(!r)throw new v(`Usage: aikit examples <query> [--limit N] [--content-type type]`);let{embedder:i,store:a}=await q();s(await ut(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=y(e,`--limit`,100),{embedder:n,store:r}=await q();_e(await lt(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();if(!t)throw new v(`Usage: aikit lookup <id>`);let{store:n}=await q(),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)}}}];async function di(e){let{port:t,noOpen:n,urlPath:r,commandName:i}=e;console.log(`Starting AI Kit server on port ${t}...`);let{spawn:a}=await import(`node:child_process`),{platform:o}=await import(`node:os`),s=h(),c=a(process.execPath,[s,`--transport`,`http`,`--port`,String(t)],{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env,NODE_OPTIONS:f(process.env.NODE_OPTIONS),AIKIT_TRANSPORT:`http`,AIKIT_PORT:String(t)}}),l=`http://localhost:${t}${r}`,u=`http://localhost:${t}/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)throw c.kill(),new v(`Server failed to start within 30 seconds.`);let p=i.charAt(0).toUpperCase()+i.slice(1);if(console.log(`AI Kit ${p}: ${l}`),console.log(`Press Ctrl+C to stop.`),!n){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 m=()=>{c.kill(),process.exit(0)};process.on(`SIGINT`,m),process.on(`SIGTERM`,m),await new Promise(e=>{c.on(`exit`,()=>e())})}const fi=[{name:`status`,description:`Show AI Kit index status and statistics`,run:async e=>{let t=ie(e),{AIKIT_PATHS:n,computePartitionKey:r,getPartitionDir:i,isUserInstalled:a,listWorkspaces:o}=await import(`../../core/dist/index.js`),{existsSync:s}=await import(`node:fs`),c=process.cwd(),u=a(),d=s(N(c,`.vscode`,`mcp.json`)),f={mode:void 0,dataPath:void 0};if(u&&d)f.mode=`workspace (overrides user-level for this workspace)`,f.dataPath=N(c,n.data);else if(u){let e=r(c);f.mode=s(N(c,`AGENTS.md`))?`user (workspace scaffolded)`:`user (workspace not scaffolded)`,f.dataPath=i(e)}else f.mode=`workspace`,f.dataPath=N(c,n.data);u&&!d&&(f.workspaces=o().length);try{let{store:e}=await q(),t=await e.getStats(),n=await e.listSourcePaths();f.records=t.totalRecords,f.files=t.totalFiles,f.lastIndexed=t.lastIndexedAt??null,f.backend=t.storeBackend,f.model=t.embeddingModel,f.contentTypeBreakdown=t.contentTypeBreakdown,f.sourcePaths=n.slice(0,20),f.sourcePathTotal=n.length}catch{f.indexAvailable=!1}if(t){l(f);return}if(console.log(`AI Kit Status`),console.log(`─`.repeat(40)),console.log(` Mode: ${f.mode}`),console.log(` Data: ${f.dataPath}`),u&&!d){let e=o();console.log(` Registry: ${e.length} workspace(s) enrolled`)}if(f.records!==void 0){console.log(` Records: ${f.records}`),console.log(` Files: ${f.files}`),console.log(` Indexed: ${f.lastIndexed??`Never`}`),console.log(` Backend: ${f.backend}`),console.log(` Model: ${f.model}`),console.log(``),console.log(`Content Types:`);for(let[e,t]of Object.entries(f.contentTypeBreakdown))console.log(` ${e}: ${t}`);let e=f.sourcePaths;if(e.length>0){console.log(``),console.log(`Files (${f.sourcePathTotal} total):`);for(let t of e.slice(0,20))console.log(` ${t}`);f.sourcePathTotal>20&&console.log(` ... and ${f.sourcePathTotal-20} more`)}}else console.log(``),console.log(" Index not available — run `aikit reindex` to index this workspace.");u&&!d&&!s(N(c,`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 q();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(`
|
|
39
|
+
`)},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. Default: direct stdio (one server per workspace). Use --daemon to share a single HTTP daemon across multiple clients.`,usage:`aikit serve [--transport stdio|http] [--port N] [--daemon]`,run:async e=>{let t=b(e,`--transport`,`stdio`),n=b(e,`--port`,`3210`),r=C(e,`--daemon`);try{await wr({silent:!0})}catch{}if(t===`stdio`&&r){let{runProxy:e}=await import(`../../server/dist/proxy.js`);try{let t=`http://127.0.0.1:${n}/health`;if((await fetch(t,{signal:AbortSignal.timeout(2e3)})).ok){await e({port:Number(n),autoStart:!1});return}}catch{}await e({port:Number(n),autoStart:!0});return}let i=rn(h(),[],{stdio:t===`stdio`?[`pipe`,`pipe`,`inherit`,`ipc`]:`inherit`,env:{...process.env,NODE_OPTIONS:f(process.env.NODE_OPTIONS),AIKIT_TRANSPORT:t,AIKIT_PORT:n}});t===`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)throw new v(`Cannot use --user and --workspace together.`);if(i){let{guideProject:e}=await import(`./init-WmQoeitD.js`);await e();return}if(r){let{initSmart:e}=await import(`./init-WmQoeitD.js`);await e({force:a})}else if(t)await rr({force:a});else if(n){let{initProject:e}=await import(`./init-WmQoeitD.js`);await e({force:a})}else await rr({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=b(e,`--cwd`,``).trim()||void 0,n=b(e,`--files`,``),r=b(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 Je({cwd:t,files:i.length>0?i:void 0,skipTypes:a,skipLint:o,detail:r});ve(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=ie(e),n=ht(e.shift());if(t){l(n);return}console.log(`Project Health: ${n.path}`),console.log(`─`.repeat(50));for(let e of n.checks){let t=e.status===`pass`?`+`:e.status===`warn`?`~`:`X`;console.log(` [${t}] ${e.name}: ${e.message}`)}console.log(`─`.repeat(50)),console.log(`Score: ${n.score}% — ${n.summary}`)}},{name:`prune`,description:`Clean up orphaned storage, legacy data, and stale partitions`,usage:`aikit prune [--dry-run] [--max-age-days=90] [--force]`,run:async e=>{let{prune:t,formatBytes:n,markPruneRun:r}=await import(`../../tools/dist/index.js`),i=e.includes(`--dry-run`),a=e.includes(`--force`),o=e.find(e=>e.startsWith(`--max-age-days=`)),s=o?Number.parseInt(o.split(`=`)[1]??``,10):90;if(!i&&!a){console.log(`⚠️ This will permanently delete data. Use --dry-run to preview, or --force to execute.`);return}console.log(i?`🔍 Dry run — no files will be deleted
|
|
40
40
|
`:`🧹 Pruning storage...
|
|
41
41
|
`);let c=await t({dryRun:i,maxAgeDays:s});console.log(`Results:`),console.log(` Forge-ground orphans: ${c.forgeGroundOrphans.count} dirs (${n(c.forgeGroundOrphans.bytesFreed)})`),console.log(` Legacy LanceDB: ${c.legacyLance.count} dirs (${n(c.legacyLance.bytesFreed)})`),console.log(` Empty ephemeral dirs: ${c.emptyEphemeral.count} dirs`),console.log(` Stale partitions: ${c.stalePartitions.count} dirs (${n(c.stalePartitions.bytesFreed)})`),console.log(` Browser profiles: ${c.browserProfiles.count} dirs (${n(c.browserProfiles.bytesFreed)})`),console.log(`\n Total freed: ${n(c.totalBytesFreed)}`),i||(r(),console.log(`
|
|
42
|
-
✅ Cleanup complete.`))}},{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
|
|
43
|
-
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();if(!r)throw new
|
|
44
|
-
Example: aikit guide "audit this project"`);let i=mt(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=Vt({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}`)}Ht().catch(()=>{})}},{name:`replay-clear`,description:`Clear the replay audit trail`,run:async()=>{Bt(),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;await li({port:Number.isFinite(n)?n:3210,noOpen:e.includes(`--no-open`),urlPath:`/_dashboard/`,commandName:`dashboard`})}},{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;await li({port:Number.isFinite(n)?n:3210,noOpen:e.includes(`--no-open`),urlPath:`/settings/`,commandName:`settings`})}}],Q=F(`cli:update`),di=A(L(),`.aikit`),fi=A(di,`versions`),pi=A(di,`current-version.json`);function mi(){if(!C(pi))return null;try{let e=T(pi,`utf-8`);return JSON.parse(e)}catch{return null}}function hi(e){C(di)||w(di,{recursive:!0});let t=`${pi}.tmp`;O(t,`${JSON.stringify({version:e,installedAt:new Date().toISOString()},null,2)}\n`),be(t,pi)}function gi(e,t){let n=e.split(`.`).map(Number),r=t.split(`.`).map(Number);for(let e=0;e<3;e++){let t=n[e]??0,i=r[e]??0;if(t>i)return!0;if(t<i)return!1}return!1}async function _i(){let e=await fetch(`https://registry.npmjs.org/@vpxa%2faikit/latest`);if(!e.ok)throw Error(`npm registry responded ${e.status}: ${e.statusText}`);let t=await e.json(),n=Array.isArray(t)?t[0]:t;return n.version??n[`dist-tags`]?.latest??`0.0.0`}const vi=[{name:`version-update`,description:`Update AI Kit to the latest version from npm (auto-detects and installs newer release)`,usage:`aikit version-update`,run:async()=>{let e=mi();if(!e){Q.debug("No installed version found. Run `aikit install` first.");return}Q.debug(`Current version: ${e.version}`);let t;try{t=await _i()}catch(e){let t=e instanceof Error?e.message:String(e);Q.error(`Failed to check for updates: ${t}`);return}if(Q.debug(`Latest version: ${t}`),!gi(t,e.version)){Q.info(`Already latest version.`);return}Q.debug(`Updating to ${t}...`);try{let e=`https://registry.npmjs.org/@vpxa/aikit/-/aikit-${t}.tgz`,n=await fetch(e);if(!n.ok)throw Error(`Download failed: ${n.status} ${n.statusText}`);let r=Buffer.from(await n.arrayBuffer()),i=A(fi,`v${t}-staging`);C(i)&&D(i,{recursive:!0,force:!0}),w(i,{recursive:!0});try{let e=A(i,`aikit-${t}.tgz`);O(e,r),Q.debug(`Extracting...`),I(`tar -xzf "${e}"`,{cwd:i,stdio:`pipe`,timeout:6e4});let n=A(i,`package`);if(!C(n))throw Error(`Expected "package/" directory not found after extraction`);Q.debug(`Installing production dependencies...`),I(`npm install --production --install-strategy=nested --no-audit --no-fund`,{cwd:n,stdio:`pipe`,timeout:3e5});let a=A(n,`packages`,`server`,`dist`,`bin.js`);if(!C(a))throw Error(`Server entry not found at ${a}`);let o=A(fi,`v${t}`);C(fi)||w(fi,{recursive:!0}),C(o)&&(Q.debug(`Removing previous installation at ${o}...`),D(o,{recursive:!0,force:!0})),be(n,o),hi(t),Q.info(`Updated to ${t}`)}finally{C(i)&&D(i,{recursive:!0,force:!0})}}catch(e){let t=e instanceof Error?e.message:String(e);Q.error(`Update failed: ${t}`)}}}],yi=[{name:`upgrade`,description:`Upgrade AI Kit agents, prompts, and skills to the latest version (user-level and workspace-level)`,usage:`aikit upgrade`,run:async()=>{await nr({force:!0});let e=process.cwd();if(C(M(e,`.github`,`.aikit-scaffold.json`))){let{initScaffoldOnly:e}=await import(`./init-DWIr_CT8.js`);await e({force:!0})}if(C(M(e,`.github`,`skills`))){let{smartCopySkills:t}=await import(`./scaffold-BNPHP-QC.js`).then(e=>e.a),n=S(),r=oe();await t(e,n,[...le],r,!0);let{smartCopyFlows:i}=await import(`./scaffold-BNPHP-QC.js`).then(e=>e.a);await i(e,n,[...de],r,!0)}let{homedir:t}=await import(`node:os`),{rmSync:n}=await import(`node:fs`),r=A(t(),`.aikit`,`cache`,`wasm`);if(C(r))try{n(r,{recursive:!0,force:!0}),console.log(`✓ WASM cache cleared (will re-resolve on next start)`)}catch{console.warn(`⚠ Could not clear WASM cache at`,r)}}}],bi=F(`cli:versions`),xi=A(L(),`.aikit`,`versions`),Si=A(L(),`.aikit`,`current-version.json`);function Ci(){try{return C(Si)?JSON.parse(T(Si,`utf-8`)).version??null:null}catch{return null}}const wi=[{name:`versions`,description:`List installed AI Kit versions (shows current, date, and available rollbacks)`,usage:`aikit versions`,run:async()=>{if(!C(xi)){bi.warn(`No versions installed.`);return}let e=Ci(),t=E(xi,{withFileTypes:!0}).filter(e=>e.isDirectory()&&/^v\d+\.\d+\.\d+$/.test(e.name)).map(e=>{let t=xe(A(xi,e.name));return{name:e.name,ver:e.name.slice(1),mtime:t.mtime}}).sort((e,t)=>t.mtime.getTime()-e.mtime.getTime());if(t.length===0){bi.warn(`No versions installed.`);return}for(let n of t){let t=n.ver===e,r=n.mtime.toISOString().split(`T`)[0],i=t?`(current)`:`(older)`,a=t?` ←`:``;console.log(`${n.name} - ${r} ${i}${a}`)}}}],Ti=[{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=d(_(e,`--files`,``)),r=_(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=Ut(i,n,{description:r});console.log(`Saved workset: ${e.name}`),f(e);return}case`get`:{i||(console.error(`Usage: aikit workset get <name>`),process.exit(1));let e=dt(i);if(!e){console.log(`No workset found: ${i}`);return}f(e);return}case`list`:{let e=St();if(e.length===0){console.log(`No worksets saved.`);return}console.log(`Worksets (${e.length})`),console.log(`─`.repeat(60));for(let t of e)f(t),console.log(``);return}case`delete`:{i||(console.error(`Usage: aikit workset delete <name>`),process.exit(1));let e=it(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=Ke(i,n);console.log(`Updated workset: ${e.name}`),f(e);return}case`remove`:{(!i||n.length===0)&&(console.error(`Usage: aikit workset remove <name> --files f1,f2`),process.exit(1));let e=Rt(i,n);if(!e){console.log(`No workset found: ${i}`);return}console.log(`Updated workset: ${e.name}`),f(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();t||(console.error(`Usage: aikit stash <set|get|list|delete|clear> [key] [value]`),process.exit(1));let r=await x();switch(t){case`set`:{n||(console.error(`Usage: aikit stash set <key> <value>`),process.exit(1));let t=e.join(` `),i=t.trim()?``:await p(),a=Yt(r,n,ie(t||i));console.log(`Stored stash entry: ${a.key}`),console.log(` Type: ${a.type}`),console.log(` Stored: ${a.storedAt}`);return}case`get`:{n||(console.error(`Usage: aikit stash get <key>`),process.exit(1));let e=qt(r,n);if(!e){console.log(`No stash entry found: ${n}`);return}console.log(JSON.stringify(e,null,2));return}case`list`:{let e=Jt(r);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=Kt(r,n);console.log(e?`Deleted stash entry: ${n}`:`No stash entry found: ${n}`);return}case`clear`:{let e=Gt(r);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=yt();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=_(e,`--files`,``);t||(console.error(`Usage: aikit lane create <name> --files file1.ts,file2.ts`),process.exit(1));let r=gt(n,t.split(`,`).map(e=>e.trim()));console.log(`Lane "${r.name}" created with ${r.sourceFiles.length} files.`);break}case`status`:{let e=xt(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=_t(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=bt(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=vt(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=Ft();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=At(n);console.log(`Queue "${e.name}" created.`);break}case`push`:{let t=Lt(n,e.join(` `)||`Untitled task`);console.log(`Pushed "${t.title}" (${t.id}) to queue "${n}".`);break}case`next`:{let e=It(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=Mt(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=Nt(n,t,r);console.log(`Marked "${i.title}" as failed: ${r}`);break}case`get`:{let e=Pt(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=kt(n);console.log(`Cleared ${e} completed/failed items from queue "${n}".`);break}case`delete`:{let e=jt(n);console.log(e?`Queue "${n}" deleted.`:`Queue "${n}" not found.`);break}}}}],$=[...ci,...ii,...pn,...zr,...ri,...ui,...Er,...mn,...Cn,...Ti,...Tr,...vi,...yi,...Ar,...wr,...wi,...si,...Ir];$.push({name:`help`,description:`Show available commands`,run:async()=>{Di()}});async function Ei(e){let t=[...e],n=t.shift();if(!n||n===`--help`||n===`-h`){Di();return}if(n===`--version`||n===`-v`){let e=M(k(Te(import.meta.url)),`..`,`..`,`..`,`package.json`),t=JSON.parse(T(e,`utf-8`));console.log(t.version);return}if(n&&new Set([`--user`,`--workspace`,`--guide`,`--smart`]).has(n)){let e=$.find(e=>e.name===`init`);if(e){await e.run([n,...t]);return}}let r=$.find(e=>e.name===n);r||(console.error(`Unknown command: ${n}`),Di(),process.exit(1));try{await r.run(t)}catch(e){throw e instanceof h&&(console.error(e.message),process.exit(e.exitCode)),e}finally{let e=Rr();e&&await e.store.close()}}function Di(){console.log(`@vpxa/aikit — Local-first AI developer toolkit
|
|
42
|
+
✅ Cleanup complete.`))}},{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 q(),r=b(e,`--detail`,`efficient`)||`efficient`,i=b(e,`--checks`,``),a=i?i.split(`,`).map(e=>e.trim()):void 0,o=await qe(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(`
|
|
43
|
+
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();if(!r)throw new v(`Usage: aikit guide <goal> [--max N]
|
|
44
|
+
Example: aikit guide "audit this project"`);let i=mt(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=Vt({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}`)}Ht().catch(()=>{})}},{name:`replay-clear`,description:`Clear the replay audit trail`,run:async()=>{Bt(),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;await di({port:Number.isFinite(n)?n:3210,noOpen:e.includes(`--no-open`),urlPath:`/_dashboard/`,commandName:`dashboard`})}},{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;await di({port:Number.isFinite(n)?n:3210,noOpen:e.includes(`--no-open`),urlPath:`/settings/`,commandName:`settings`})}}],Q=I(`cli:update`),pi=j(R(),`.aikit`),mi=j(pi,`versions`),hi=j(pi,`current-version.json`);function gi(){if(!w(hi))return null;try{let e=E(hi,`utf-8`);return JSON.parse(e)}catch{return null}}function _i(e){w(pi)||T(pi,{recursive:!0});let t=`${hi}.tmp`;k(t,`${JSON.stringify({version:e,installedAt:new Date().toISOString()},null,2)}\n`),be(t,hi)}function vi(e,t){let n=e.split(`.`).map(Number),r=t.split(`.`).map(Number);for(let e=0;e<3;e++){let t=n[e]??0,i=r[e]??0;if(t>i)return!0;if(t<i)return!1}return!1}async function yi(){let e=await fetch(`https://registry.npmjs.org/@vpxa%2faikit/latest`);if(!e.ok)throw Error(`npm registry responded ${e.status}: ${e.statusText}`);let t=await e.json(),n=Array.isArray(t)?t[0]:t;return n.version??n[`dist-tags`]?.latest??`0.0.0`}const bi=[{name:`version-update`,description:`Update AI Kit to the latest version from npm (auto-detects and installs newer release)`,usage:`aikit version-update`,run:async()=>{let e=gi();if(!e){Q.debug("No installed version found. Run `aikit install` first.");return}Q.debug(`Current version: ${e.version}`);let t;try{t=await yi()}catch(e){let t=e instanceof Error?e.message:String(e);Q.error(`Failed to check for updates: ${t}`);return}if(Q.debug(`Latest version: ${t}`),!vi(t,e.version)){Q.info(`Already latest version.`);return}Q.debug(`Updating to ${t}...`);try{let e=`https://registry.npmjs.org/@vpxa/aikit/-/aikit-${t}.tgz`,n=await fetch(e);if(!n.ok)throw Error(`Download failed: ${n.status} ${n.statusText}`);let r=Buffer.from(await n.arrayBuffer()),i=j(mi,`v${t}-staging`);w(i)&&O(i,{recursive:!0,force:!0}),T(i,{recursive:!0});try{let e=j(i,`aikit-${t}.tgz`);k(e,r),Q.debug(`Extracting...`),L(`tar -xzf "${e}"`,{cwd:i,stdio:`pipe`,timeout:6e4});let n=j(i,`package`);if(!w(n))throw Error(`Expected "package/" directory not found after extraction`);Q.debug(`Installing production dependencies...`),L(`npm install --production --install-strategy=nested --no-audit --no-fund`,{cwd:n,stdio:`pipe`,timeout:3e5});let a=j(n,`packages`,`server`,`dist`,`bin.js`);if(!w(a))throw Error(`Server entry not found at ${a}`);let o=j(mi,`v${t}`);w(mi)||T(mi,{recursive:!0}),w(o)&&(Q.debug(`Removing previous installation at ${o}...`),O(o,{recursive:!0,force:!0})),be(n,o),_i(t),Q.info(`Updated to ${t}`)}finally{w(i)&&O(i,{recursive:!0,force:!0})}}catch(e){let t=e instanceof Error?e.message:String(e);Q.error(`Update failed: ${t}`)}}}],xi=[{name:`upgrade`,description:`Upgrade AI Kit agents, prompts, and skills to the latest version (user-level and workspace-level)`,usage:`aikit upgrade`,run:async()=>{await rr({force:!0});let e=process.cwd();if(w(N(e,`.github`,`.aikit-scaffold.json`))){let{initScaffoldOnly:e}=await import(`./init-WmQoeitD.js`);await e({force:!0})}if(w(N(e,`.github`,`skills`))){let{smartCopySkills:t}=await import(`./scaffold-BNPHP-QC.js`).then(e=>e.a),n=S(),r=ae();await t(e,n,[...ue],r,!0);let{smartCopyFlows:i}=await import(`./scaffold-BNPHP-QC.js`).then(e=>e.a);await i(e,n,[...fe],r,!0)}let{homedir:t}=await import(`node:os`),{rmSync:n}=await import(`node:fs`),r=j(t(),`.aikit`,`cache`,`wasm`);if(w(r))try{n(r,{recursive:!0,force:!0}),console.log(`✓ WASM cache cleared (will re-resolve on next start)`)}catch{console.warn(`⚠ Could not clear WASM cache at`,r)}}}],Si=I(`cli:versions`),Ci=j(R(),`.aikit`,`versions`),wi=j(R(),`.aikit`,`current-version.json`);function Ti(){try{return w(wi)?JSON.parse(E(wi,`utf-8`)).version??null:null}catch{return null}}const Ei=[{name:`versions`,description:`List installed AI Kit versions (shows current, date, and available rollbacks)`,usage:`aikit versions`,run:async()=>{if(!w(Ci)){Si.warn(`No versions installed.`);return}let e=Ti(),t=D(Ci,{withFileTypes:!0}).filter(e=>e.isDirectory()&&/^v\d+\.\d+\.\d+$/.test(e.name)).map(e=>{let t=xe(j(Ci,e.name));return{name:e.name,ver:e.name.slice(1),mtime:t.mtime}}).sort((e,t)=>t.mtime.getTime()-e.mtime.getTime());if(t.length===0){Si.warn(`No versions installed.`);return}for(let n of t){let t=n.ver===e,r=n.mtime.toISOString().split(`T`)[0],i=t?`(current)`:`(older)`,a=t?` ←`:``;console.log(`${n.name} - ${r} ${i}${a}`)}}}],Di=[{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=d(b(e,`--files`,``)),r=b(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=Ut(i,n,{description:r});console.log(`Saved workset: ${e.name}`),p(e);return}case`get`:{i||(console.error(`Usage: aikit workset get <name>`),process.exit(1));let e=dt(i);if(!e){console.log(`No workset found: ${i}`);return}p(e);return}case`list`:{let e=St();if(e.length===0){console.log(`No worksets saved.`);return}console.log(`Worksets (${e.length})`),console.log(`─`.repeat(60));for(let t of e)p(t),console.log(``);return}case`delete`:{i||(console.error(`Usage: aikit workset delete <name>`),process.exit(1));let e=it(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=Ke(i,n);console.log(`Updated workset: ${e.name}`),p(e);return}case`remove`:{(!i||n.length===0)&&(console.error(`Usage: aikit workset remove <name> --files f1,f2`),process.exit(1));let e=Rt(i,n);if(!e){console.log(`No workset found: ${i}`);return}console.log(`Updated workset: ${e.name}`),p(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();t||(console.error(`Usage: aikit stash <set|get|list|delete|clear> [key] [value]`),process.exit(1));let r=await ce();switch(t){case`set`:{n||(console.error(`Usage: aikit stash set <key> <value>`),process.exit(1));let t=e.join(` `),i=t.trim()?``:await m(),a=Yt(r,n,re(t||i));console.log(`Stored stash entry: ${a.key}`),console.log(` Type: ${a.type}`),console.log(` Stored: ${a.storedAt}`);return}case`get`:{n||(console.error(`Usage: aikit stash get <key>`),process.exit(1));let e=qt(r,n);if(!e){console.log(`No stash entry found: ${n}`);return}console.log(JSON.stringify(e,null,2));return}case`list`:{let e=Jt(r);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=Kt(r,n);console.log(e?`Deleted stash entry: ${n}`:`No stash entry found: ${n}`);return}case`clear`:{let e=Gt(r);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=yt();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=b(e,`--files`,``);t||(console.error(`Usage: aikit lane create <name> --files file1.ts,file2.ts`),process.exit(1));let r=gt(n,t.split(`,`).map(e=>e.trim()));console.log(`Lane "${r.name}" created with ${r.sourceFiles.length} files.`);break}case`status`:{let e=xt(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=_t(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=bt(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=vt(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=Ft();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=At(n);console.log(`Queue "${e.name}" created.`);break}case`push`:{let t=Lt(n,e.join(` `)||`Untitled task`);console.log(`Pushed "${t.title}" (${t.id}) to queue "${n}".`);break}case`next`:{let e=It(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=Mt(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=Nt(n,t,r);console.log(`Marked "${i.title}" as failed: ${r}`);break}case`get`:{let e=Pt(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=kt(n);console.log(`Cleared ${e} completed/failed items from queue "${n}".`);break}case`delete`:{let e=jt(n);console.log(e?`Queue "${n}" deleted.`:`Queue "${n}" not found.`);break}}}}],$=[...ui,...oi,...pn,...Br,...ai,...fi,...Dr,...mn,...Cn,...Di,...Er,...bi,...xi,...jr,...Tr,...Ei,...li,...Lr];$.push({name:`help`,description:`Show available commands`,run:async()=>{ki()}});async function Oi(e){let t=[...e],n=t.shift();if(!n||n===`--help`||n===`-h`){ki();return}if(n===`--version`||n===`-v`){let e=N(A(Te(import.meta.url)),`..`,`..`,`..`,`package.json`),t=JSON.parse(E(e,`utf-8`));console.log(t.version);return}if(n&&new Set([`--user`,`--workspace`,`--guide`,`--smart`]).has(n)){let e=$.find(e=>e.name===`init`);if(e){await e.run([n,...t]);return}}let r=$.find(e=>e.name===n);r||(console.error(`Unknown command: ${n}`),ki(),process.exit(1));try{await r.run(t)}catch(e){throw e instanceof v&&(console.error(e.message),process.exit(e.exitCode)),e}finally{let e=zr();e&&await e.store.close()}}function ki(){console.log(`@vpxa/aikit — Local-first AI developer toolkit
|
|
45
45
|
`),console.log(`Usage: aikit <command> [options]
|
|
46
|
-
`),console.log(`Commands:`);let e=Math.max(...$.map(e=>e.name.length));for(let t of $)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{
|
|
46
|
+
`),console.log(`Commands:`);let e=Math.max(...$.map(e=>e.name.length));for(let t of $)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{Oi 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-BNPHP-QC.js";import{a as o,i as s,m as c,n as l,o as u,r as d,t as f}from"./templates-
|
|
1
|
+
import{c as e,l as t,n,o as r,r as i,t as a}from"./scaffold-BNPHP-QC.js";import{a as o,i as s,m as c,n as l,o as u,r as d,t as f}from"./templates-BQ1J4HzY.js";import{appendFileSync as p,existsSync as m,mkdirSync as h,readFileSync as g,unlinkSync as _,writeFileSync as v}from"node:fs";import{basename as y,resolve as b}from"node:path";import{AIKIT_PATHS as x,EMBEDDING_DEFAULTS as S,isUserInstalled as C}from"../../core/dist/index.js";function w(e){return m(b(e,`.cursor`))?`cursor`:m(b(e,`.claude`))?`claude-code`:m(b(e,`.windsurf`))?`windsurf`:m(b(e,`.zed`))?`zed`:m(b(e,`.idea`))?`intellij`:m(b(e,`.opencode`))?`opencode`:`copilot`}function T(e){let t=[];return m(b(e,`.cursor`))&&t.push(`cursor`),(m(b(e,`.claude`))||m(b(e,`CLAUDE.md`)))&&t.push(`claude-code`),m(b(e,`.windsurf`))&&t.push(`windsurf`),m(b(e,`.zed`))&&t.push(`zed`),m(b(e,`.idea`))&&t.push(`intellij`),m(b(e,`.gemini`))&&t.push(`gemini-cli`),(m(b(e,`.codex`))||m(b(e,`codex.md`)))&&t.push(`codex-cli`),(m(b(e,`.opencode`))||m(b(e,`OPENCODE.md`)))&&t.push(`opencode`),t.push(`copilot`),[...new Set(t)]}function E(e){return{servers:{[e]:{...s}}}}function D(e){let{type:t,...n}=s;return{mcpServers:{[e]:n}}}function O(e){let{type:t,...n}=s;return{context_servers:{[e]:{...n}}}}function k(e){let{type:t,...n}=s;return{mcp:{[e]:{type:`local`,command:[n.command,...n.args]}}}}const A={scaffoldDir:`general`,writeMcpConfig(e,t){let n=b(e,`.vscode`),r=b(n,`mcp.json`);m(r)||(h(n,{recursive:!0}),v(r,`${JSON.stringify(E(t),null,2)}\n`,`utf-8`),console.log(` Created .vscode/mcp.json`))},writeInstructions(e,t){let n=b(e,`.github`),r=b(n,`copilot-instructions.md`);h(n,{recursive:!0}),v(r,l(y(e),t),`utf-8`),console.log(` Updated .github/copilot-instructions.md`)},writeAgentsMd(e,t){v(b(e,`AGENTS.md`),f(y(e),t),`utf-8`),console.log(` Updated AGENTS.md`)}},j={scaffoldDir:`general`,writeMcpConfig(e,t){let n=b(e,`.mcp.json`);m(n)||(v(n,`${JSON.stringify(D(t),null,2)}\n`,`utf-8`),console.log(` Created .mcp.json`))},writeInstructions(e,t){let n=b(e,`CLAUDE.md`),r=y(e);v(n,`${l(r,t)}\n---\n\n${f(r,t)}`,`utf-8`),console.log(` Updated CLAUDE.md`)},writeAgentsMd(e,t){}},M={scaffoldDir:`general`,writeMcpConfig(e,t){let n=b(e,`.cursor`),r=b(n,`mcp.json`);m(r)||(h(n,{recursive:!0}),v(r,`${JSON.stringify(D(t),null,2)}\n`,`utf-8`),console.log(` Created .cursor/mcp.json`))},writeInstructions(e,t){let n=b(e,`.cursor`,`rules`),r=b(n,`aikit.mdc`);h(n,{recursive:!0});let i=y(e);v(r,`${l(i,t)}\n---\n\n${f(i,t)}`,`utf-8`),console.log(` Updated .cursor/rules/aikit.mdc`);let a=b(n,`kb.mdc`);m(a)&&a!==r&&(_(a),console.log(` Removed legacy .cursor/rules/kb.mdc`))},writeAgentsMd(e,t){}},N={scaffoldDir:`general`,writeMcpConfig(e,t){let n=b(e,`.vscode`),r=b(n,`mcp.json`);m(r)||(h(n,{recursive:!0}),v(r,`${JSON.stringify(E(t),null,2)}\n`,`utf-8`),console.log(` Created .vscode/mcp.json (Windsurf-compatible)`))},writeInstructions(e,t){let n=b(e,`.windsurfrules`),r=y(e);v(n,`${l(r,t)}\n---\n\n${f(r,t)}`,`utf-8`),console.log(` Updated .windsurfrules`)},writeAgentsMd(e,t){}},P={scaffoldDir:`general`,writeMcpConfig(e,t){let n=b(e,`.zed`),r=b(n,`settings.json`);if(h(n,{recursive:!0}),!m(r))v(r,`${JSON.stringify(O(t),null,2)}\n`,`utf-8`),console.log(` Created .zed/settings.json`);else{let e;try{e=JSON.parse(g(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,...O(t).context_servers},v(r,`${JSON.stringify(e,null,2)}\n`,`utf-8`),console.log(` Updated .zed/settings.json with context_servers`))}},writeInstructions(e,t){let n=b(e,`.rules`),r=y(e);v(n,`${l(r,t)}\n---\n\n${f(r,t)}`,`utf-8`),console.log(` Updated .rules`)},writeAgentsMd(e,t){}},F={scaffoldDir:`general`,writeMcpConfig(e,t){let n=b(e,`mcp.json`);m(n)||(v(n,`${JSON.stringify(D(t),null,2)}\n`,`utf-8`),console.log(` Created mcp.json`))},writeInstructions(e,t){let n=b(e,`.aiassistant`,`rules`),r=b(n,`aikit.md`);h(n,{recursive:!0});let i=y(e);v(r,`${l(i,t)}\n---\n\n${f(i,t)}`,`utf-8`),console.log(` Updated .aiassistant/rules/aikit.md`)},writeAgentsMd(e,t){}},I={scaffoldDir:`general`,writeMcpConfig(e,t){let n=b(e,`.opencode`),r=b(n,`opencode.json`);m(r)||(h(n,{recursive:!0}),v(r,`${JSON.stringify(k(t),null,2)}\n`,`utf-8`),console.log(` Created .opencode/opencode.json`))},writeInstructions(e,t){let n=b(e,`OPENCODE.md`),r=y(e);v(n,`${l(r,t)}\n---\n\n${f(r,t)}`,`utf-8`),console.log(` Updated OPENCODE.md`)},writeAgentsMd(e,t){}};function L(e){switch(e){case`copilot`:return A;case`claude-code`:return j;case`cursor`:return M;case`windsurf`:return N;case`zed`:return P;case`intellij`:return F;case`opencode`:return I;case`gemini-cli`:case`codex-cli`:return A}}const R={serverName:o,sources:[{path:`.`,excludePatterns:[`**/node_modules/**`,`**/dist/**`,`**/build/**`,`**/.git/**`,`**/${x.data}/**`,`**/coverage/**`,`**/*.min.js`,`**/package-lock.json`,`**/pnpm-lock.yaml`]}],indexing:{chunkSize:1500,chunkOverlap:200,minChunkSize:100},embedding:{model:S.model,dimensions:S.dimensions},store:{backend:`sqlite-vec`,path:x.data},curated:{path:x.aiCurated}};function z(e,t){let n=b(e,`aikit.config.json`);return m(n)&&!t?(console.log(`aikit.config.json already exists. Use --force to overwrite.`),!1):(v(n,`${JSON.stringify(R,null,2)}\n`,`utf-8`),console.log(` Created aikit.config.json`),!0)}function B(e){let t=b(e,`.gitignore`),n=[{dir:`.flows/`,label:`AI Kit flow runs`}];if(m(t)){let e=g(t,`utf-8`),r=n.filter(t=>!e.includes(t.dir));r.length>0&&(p(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 v(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=b(e,`.ai`,`curated`);m(t)||(h(t,{recursive:!0}),console.log(` Created .ai/curated/`));for(let e of H){let n=b(t,e);m(n)||h(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`;case`opencode`:return`opencode`;default:return`copilot`}}async function G(n){let i=process.cwd();if(!z(i,n.force))return;B(i);let a=V(),o=L(w(i));o.writeMcpConfig(i,a),o.writeInstructions(i,a),o.writeAgentsMd(i,a);let s=c(),l=JSON.parse(g(b(s,`package.json`),`utf-8`)).version;await t(i,s,[...u],l,n.force),await r(i,s,[...d],l,n.force);let f=T(i),p=new Set;for(let t of f){let r=W(t);p.has(r)||(p.add(r),await e(i,s,r,l,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`),C()&&console.log(`
|