@vpxa/aikit 0.1.172 → 0.1.173
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/packages/cli/dist/index.js +16 -16
- package/packages/cli/dist/{init-BWhqiOl_.js → init-BVU1RVy5.js} +1 -1
- package/packages/cli/dist/{scaffold-DwQDdiCJ.js → scaffold-BB6OrTuA.js} +1 -1
- package/packages/server/dist/{config-D4z6-EcI.js → config-Dsu2Kd3U.js} +1 -1
- package/packages/server/dist/index.js +1 -1
- package/packages/server/dist/{server-Chxe6Ips.js → server-CqEB0MaC.js} +12 -12
package/package.json
CHANGED
|
@@ -1,23 +1,23 @@
|
|
|
1
|
-
import{d as e,f as t,i as n,
|
|
2
|
-
`);let
|
|
3
|
-
`))console.log(` ${e}`)}}function L(e){console.log(e.id),console.log(` Command: ${e.command}${e.args.length>0?` ${e.args.join(` `)}`:``}`),console.log(` PID: ${e.pid??`unknown`}`),console.log(` Status: ${e.status}`),console.log(` Started: ${e.startedAt}`),e.exitCode!==void 0&&console.log(` Exit code: ${e.exitCode}`),console.log(` Logs: ${e.logs.length}`)}function
|
|
1
|
+
import{d as e,f as t,i as n,m as r,p as i,s as a,u as o}from"./scaffold-BB6OrTuA.js";import{a as s,i as c,n as l,o as u,r as d,s as f,t as ee}from"./templates-D-eA4QVK.js";import{copyFileSync as p,existsSync as m,mkdirSync as h,readFileSync as g,readdirSync as _,rmSync as te,unlinkSync as ne,writeFileSync as re}from"node:fs";import{basename as v,dirname as y,join as b,posix as x,relative as S,resolve as C,win32 as w}from"node:path";import{fileURLToPath as T}from"node:url";import{addToWorkset as E,audit as D,check as ie,checkpointLatest as ae,checkpointList as oe,checkpointLoad as se,checkpointSave as ce,codemod as le,compact as ue,dataTransform as de,delegate as fe,delegateListModels as pe,deleteWorkset as me,diffParse as he,evaluate as ge,fileSummary as _e,find as ve,findDeadSymbols as ye,findExamples as be,getWorkset as xe,gitContext as Se,graphQuery as Ce,guide as we,health as Te,laneCreate as Ee,laneDiff as De,laneDiscard as Oe,laneList as ke,laneMerge as Ae,laneStatus as je,listWorksets as Me,parseOutput as Ne,processList as Pe,processLogs as Fe,processStart as Ie,processStatus as Le,processStop as Re,queueClear as ze,queueCreate as Be,queueDelete as Ve,queueDone as He,queueFail as Ue,queueGet as We,queueList as Ge,queueNext as Ke,queuePush as qe,removeFromWorkset as Je,rename as Ye,replayClear as Xe,replayList as Ze,replayTrim as Qe,saveWorkset as $e,scopeMap as et,stashClear as tt,stashDelete as nt,stashGet as rt,stashList as it,stashSet as at,symbol as ot,testRun as st,trace as ct,watchList as lt,watchStart as ut,watchStop as dt}from"../../tools/dist/index.js";import{mkdir as ft,readFile as O,rename as pt,unlink as mt,writeFile as ht}from"node:fs/promises";import{randomUUID as gt}from"node:crypto";import{homedir as k}from"node:os";import{execFileSync as _t,fork as vt}from"node:child_process";import{AIKIT_PATHS as A,EMBEDDING_DEFAULTS as yt,getGlobalDataDir as bt,getPartitionDir as j,isUserInstalled as xt,registerWorkspace as St,saveRegistry as Ct}from"../../core/dist/index.js";import{initializeWasm as wt}from"../../chunker/dist/index.js";import{OnnxEmbedder as Tt}from"../../embeddings/dist/index.js";import{IncrementalIndexer as Et}from"../../indexer/dist/index.js";import{SqliteGraphStore as Dt,createSqliteAdapter as Ot,createStore as kt}from"../../store/dist/index.js";const At=[{name:`analyze`,description:`Run analyzer output for a path`,usage:`aikit analyze <type> <path>`,run:async e=>{let t=e.shift()?.trim()??``,n=e.shift()?.trim()??``;(!t||!n)&&(console.error(`Usage: aikit analyze <type> <path>`),console.error(`Types: structure, deps, symbols, patterns, entry-points, blast-radius, diagram`),process.exit(1));let{BlastRadiusAnalyzer:r,DependencyAnalyzer:i,DiagramGenerator:a,EntryPointAnalyzer:o,PatternAnalyzer:s,StructureAnalyzer:c,SymbolAnalyzer:l}=await import(`../../analyzers/dist/index.js`),u=C(n),d;switch(t){case`structure`:d=await new c().analyze(u,{format:`markdown`});break;case`deps`:case`dependencies`:d=await new i().analyze(u,{format:`markdown`});break;case`symbols`:d=await new l().analyze(u,{format:`markdown`});break;case`patterns`:d=await new s().analyze(u,{format:`markdown`});break;case`entry-points`:d=await new o().analyze(u,{format:`markdown`});break;case`blast-radius`:d=await new r().analyze(process.cwd(),{files:[n],format:`markdown`});break;case`diagram`:d=await new a().analyze(u,{diagramType:`architecture`});break;default:console.error(`Unknown analyze type: ${t}`),console.error(`Types: structure, deps, symbols, patterns, entry-points, blast-radius, diagram`),process.exit(1)}console.log(d.output)}},{name:`onboard`,description:`Run all analyses for first-time codebase onboarding`,usage:`aikit onboard <path> [--generate] [--out-dir <dir>]`,run:async e=>{let{onboard:t}=await import(`../../tools/dist/index.js`),{loadConfig:n}=await Promise.resolve().then(()=>zn),r=``,i=`memory`,a;for(let t=0;t<e.length;t++){let n=e[t].trim();n===`--generate`?i=`generate`:n===`--out-dir`&&t+1<e.length?a=e[++t].trim():n.startsWith(`--`)||(r=n)}r||=process.cwd();let o=C(r),s=n();console.log(`Onboarding: ${o} (mode: ${i})`),console.log(`Running analyses...
|
|
2
|
+
`);let c=await t({path:o,mode:i,outDir:a??s.onboardDir});for(let e of c.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: ${c.totalDurationMs}ms`),c.outDir&&console.log(`Output written to: ${c.outDir}`)}}];function M(e,t,n){let r=e.indexOf(t);if(r===-1||r+1>=e.length)return n;let i=Number.parseInt(e.splice(r,2)[1],10);return Number.isNaN(i)?n:i}function N(e,t,n){let r=e.indexOf(t);return r===-1||r+1>=e.length?n:e.splice(r,2)[1]}function P(e,t){let n=e.indexOf(t);return n===-1?!1:(e.splice(n,1),!0)}async function F(){if(process.stdin.isTTY)return``;let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString(`utf-8`)}function I(e){return e.split(`,`).map(e=>e.trim()).filter(Boolean)}function jt(e){return e.map(e=>{let t=e.heading?` ${e.heading}`:``;return`${e.start}-${e.end}${t}`}).join(`, `)}function Mt(e){switch(e.tool){case`tsc`:case`biome`:console.log(`${e.tool} errors: ${e.errors.length}`);for(let t of e.errors){let e=[t.line,t.column].filter(e=>e!==void 0).join(`:`),n=e?`${t.file}:${e}`:t.file,r=t.code?` ${t.code}`:``;console.log(`- ${n} [${t.severity}${r}] ${t.message}`)}return;case`vitest`:console.log(`Vitest summary`),console.log(` Passed: ${e.summary.passed}`),console.log(` Failed: ${e.summary.failed}`),console.log(` Skipped: ${e.summary.skipped}`),e.summary.duration!==void 0&&console.log(` Duration: ${e.summary.duration}ms`);for(let t of e.summary.tests)t.status===`fail`&&(console.log(`- ${t.name}${t.file?` (${t.file})`:``}`),t.error&&console.log(` ${t.error}`));return;case`git-status`:console.log(`Branch: ${e.status.branch??`unknown`}`),console.log(`Staged: ${e.status.staged.length}`);for(let t of e.status.staged)console.log(` ${t.status} ${t.file}`);console.log(`Unstaged: ${e.status.unstaged.length}`);for(let t of e.status.unstaged)console.log(` ${t.status} ${t.file}`);console.log(`Untracked: ${e.status.untracked.length}`);for(let t of e.status.untracked)console.log(` ?? ${t}`);return}}function Nt(e){console.log(`Overall: ${e.passed?`passed`:`failed`}`),Pt(`tsc`,e.tsc.passed,e.tsc.errors),Pt(`biome`,e.biome.passed,e.biome.errors)}function Pt(e,t,n){console.log(`${e}: ${t?`passed`:`${n.length} issue(s)`}`);for(let e of n){let t=[e.line,e.column].filter(e=>e!==void 0).join(`:`),n=t?`${e.file}:${t}`:e.file,r=e.code?` ${e.code}`:``;console.log(` - ${n} [${e.severity}${r}] ${e.message}`)}}function Ft(e){console.log(`Vitest: ${e.passed?`passed`:`failed`}`),console.log(` Duration: ${e.durationMs}ms`),console.log(` Passed: ${e.summary.passed}`),console.log(` Failed: ${e.summary.failed}`),console.log(` Skipped: ${e.summary.skipped}`),e.summary.suites!==void 0&&console.log(` Suites: ${e.summary.suites}`);let t=e.summary.tests.filter(e=>e.status===`fail`);if(t.length!==0){console.log(`Failed tests:`);for(let e of t)console.log(` - ${e.name}${e.file?` (${e.file})`:``}`),e.error&&console.log(` ${e.error}`)}}function It(e){console.log(`Branch: ${e.branch}`),console.log(`Staged: ${e.status.staged.length}`);for(let t of e.status.staged)console.log(` - ${t}`);console.log(`Modified: ${e.status.modified.length}`);for(let t of e.status.modified)console.log(` - ${t}`);console.log(`Untracked: ${e.status.untracked.length}`);for(let t of e.status.untracked)console.log(` - ${t}`);if(console.log(``),console.log(`Recent commits:`),e.recentCommits.length===0)console.log(` none`);else for(let t of e.recentCommits)console.log(` - ${t.hash} ${t.message}`),console.log(` ${t.author} @ ${t.date}`);e.diff&&(console.log(``),console.log(`Diff stat:`),console.log(e.diff))}function Lt(e){if(e.length===0){console.log(`No diff files found.`);return}for(let t of e){let e=t.oldPath?` (from ${t.oldPath})`:``;console.log(`${t.path}${e}`),console.log(` Status: ${t.status}`),console.log(` Changes: +${t.additions} -${t.deletions}`),console.log(` Hunks: ${t.hunks.length}`);for(let e of t.hunks){let t=e.header?` ${e.header}`:``;console.log(` @@ -${e.oldStart},${e.oldLines} +${e.newStart},${e.newLines} @@${t}`)}}}function Rt(e){if(console.log(`Start: ${e.start}`),console.log(`Direction: ${e.direction}`),console.log(`Depth reached: ${e.depth}`),console.log(`Nodes: ${e.nodes.length}`),e.nodes.length===0){console.log(`No trace nodes found.`);return}for(let t of e.nodes)console.log(` - [${t.relationship}] ${t.path}:${t.line} ${t.symbol}`)}function zt(e){if(console.log(`Query: ${e.query}`),console.log(`Examples: ${e.examples.length} shown (${e.totalFound} total)`),e.examples.length===0){console.log(`No matching examples found.`);return}for(let t of e.examples){console.log(``),console.log(`${t.path}:${t.startLine}-${t.endLine}`),console.log(` Context: ${t.context}`),console.log(` Relevance: ${(t.relevance*100).toFixed(1)}%`);for(let e of t.content.split(`
|
|
3
|
+
`))console.log(` ${e}`)}}function L(e){console.log(e.id),console.log(` Command: ${e.command}${e.args.length>0?` ${e.args.join(` `)}`:``}`),console.log(` PID: ${e.pid??`unknown`}`),console.log(` Status: ${e.status}`),console.log(` Started: ${e.startedAt}`),e.exitCode!==void 0&&console.log(` Exit code: ${e.exitCode}`),console.log(` Logs: ${e.logs.length}`)}function Bt(e){if(console.log(`Exports scanned: ${e.totalExports}`),console.log(`Dead in source: ${e.totalDeadSource} (actionable)`),console.log(`Dead in docs: ${e.totalDeadDocs} (informational)`),e.totalDeadSource===0&&e.totalDeadDocs===0){console.log(`No dead symbols found.`);return}if(e.deadInSource.length>0){console.log(`
|
|
4
4
|
Dead in source (actionable):`);for(let t of e.deadInSource)console.log(` - ${t.path}:${t.line} ${t.kind} ${t.name}`)}if(e.deadInDocs.length>0){console.log(`
|
|
5
|
-
Dead in docs (informational):`);for(let t of e.deadInDocs)console.log(` - ${t.path}:${t.line} ${t.kind} ${t.name}`)}}function
|
|
6
|
-
`))console.log(` ${t}`)}function B(e,t){if(console.log(`${e}:`),t.length===0){console.log(` none`),console.log(``);return}for(let e of t)console.log(` - ${e}`);console.log(``)}function
|
|
7
|
-
`;)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 V=class{isPlatformSupported(){return this.platforms.includes(process.platform)}async readConfig(e){let t=this.getConfigPath(e);if(!m(t))return{};let n=await k(t,`utf-8`);try{return JSON.parse(Kt(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=b(n),i=x(r,`.aikit-tmp-${mt()}.json`);await ut(r,{recursive:!0});try{await pt(i,`${JSON.stringify(e,null,2)}\n`,`utf-8`),await dt(i,n)}catch(e){try{await ft(i)}catch{}throw e}}async registerMcp(e,t,n){let r=await this.readConfig(n);r[this.configKey]||(r[this.configKey]={}),r[this.configKey][e]=t,await this.writeConfig(r,n)}async unregisterMcp(e,t){let n=await this.readConfig(t);n[this.configKey]&&(delete n[this.configKey][e],await this.writeConfig(n,t))}getScaffoldRoot(e){return null}getInstructionsRoot(e){return null}getScaffoldPaths(e){return{agents:null,skills:null,prompts:null,flows:null,commands:null,instructions:null,manifest:null}}buildInstructionContent(e,t){return`${e}\n---\n\n${t}`}},qt=class extends V{id=`claude-code`;name=`Claude Code`;family=`claude`;platforms=[`win32`,`darwin`,`linux`];scope=`user`;configKey=`mcpServers`;async detect(){return this.isPlatformSupported()?m(this.getPathModule().resolve(A(),`.claude`)):!1}getConfigPath(){return this.getPathModule().resolve(A(),`.claude`,`mcp.json`)}getScaffoldRoot(){return this.getPathModule().resolve(A(),`.claude`)}getScaffoldPaths(){let e=this.getPathModule(),t=e.resolve(A(),`.claude`);return{agents:e.resolve(t,`agents`),skills:e.resolve(t,`skills`),prompts:null,flows:e.resolve(t,`flows`),commands:e.resolve(t,`commands`),instructions:e.resolve(t,`CLAUDE.md`),manifest:e.resolve(t,`.aikit-scaffold.json`)}}buildInstructionContent(e,t){return`${e}\n---\n\n${t}`}getPathModule(){return process.platform===`win32`?T:S}},Jt=class extends V{id=`codex-cli`;name=`Codex CLI`;family=`codex`;platforms=[`win32`,`darwin`,`linux`];scope=`user`;configKey=`mcpServers`;async detect(){return this.isPlatformSupported()?m(this.getPathModule().resolve(A(),`.codex`)):!1}getConfigPath(){return this.getPathModule().resolve(A(),`.codex`,`config.json`)}getScaffoldRoot(){return this.getPathModule().resolve(A(),`.codex`)}getScaffoldPaths(){let e=this.getPathModule(),t=e.resolve(A(),`.codex`);return{agents:e.resolve(t,`agents`),skills:e.resolve(t,`skills`),prompts:null,flows:e.resolve(t,`flows`),commands:null,instructions:e.resolve(t,`AGENTS.md`),manifest:e.resolve(t,`.aikit-scaffold.json`)}}getPathModule(){return process.platform===`win32`?T:S}},H=class extends V{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 m(e)||t!==null&&m(t)}return m(e)}getConfigPath(){return this.getPathModule().resolve(this.getConfigDir(),`mcp.json`)}getScaffoldRoot(){return this.getPathModule().resolve(A(),this.scaffoldBase)}getInstructionsRoot(){let e=this.getInstructionFilePath();return e?this.getPathModule().dirname(e):null}getScaffoldPaths(){let e=this.getPathModule(),t=e.resolve(A(),this.scaffoldBase);return{agents:e.resolve(t,`agents`),skills:e.resolve(t,`skills`),prompts:e.resolve(this.getConfigDir(),`prompts`),flows:e.resolve(t,`flows`),commands:null,instructions:this.getInstructionFilePath(),manifest:e.resolve(t,`.aikit-scaffold.json`)}}getConfigDir(){let e=this.getPathModule(),t=A();if(process.platform===`win32`){let n=process.env.APPDATA??e.resolve(t,`AppData`,`Roaming`);return e.resolve(n,this.configDirName,`User`)}if(process.platform===`darwin`)return e.resolve(t,`Library`,`Application Support`,this.configDirName,`User`);let n=process.env.XDG_CONFIG_HOME??e.resolve(t,`.config`);return e.resolve(n,this.configDirName,`User`)}getMacAppPath(){return null}getInstructionFilePath(){return null}getPathModule(){return process.platform===`win32`?T:S}},Yt=class extends V{id=`copilot-cli`;name=`Copilot CLI`;family=`copilot`;platforms=[`win32`,`darwin`,`linux`];scope=`user`;configKey=`mcpServers`;async detect(){return this.isPlatformSupported()?m(w(A(),`.copilot`)):!1}getConfigPath(){return w(A(),`.copilot`,`mcp-config.json`)}async registerMcp(e,t,n){let r={...t,tools:[`*`]},i=await this.readConfig(n);i[this.configKey]||(i[this.configKey]={}),i[this.configKey][e]=r,await this.writeConfig(i,n)}getScaffoldRoot(){return w(A(),`.copilot`)}getInstructionsRoot(){return null}getScaffoldPaths(){let e=w(A(),`.copilot`);return{agents:w(e,`agents`),skills:w(e,`skills`),prompts:null,flows:w(e,`flows`),commands:null,instructions:w(A(),`.github`,`copilot-instructions.md`),manifest:w(e,`.aikit-scaffold.json`)}}},Xt=class extends H{id=`cursor`;name=`Cursor`;configKey=`mcpServers`;configDirName=`Cursor`;scaffoldBase=`.cursor`;getMacAppPath(){return`/Applications/Cursor.app`}getInstructionFilePath(){return this.getPathModule().resolve(A(),this.scaffoldBase,`rules`,`aikit.mdc`)}},Zt=class extends H{id=`cursor-nightly`;name=`Cursor Nightly`;configKey=`mcpServers`;configDirName=`Cursor Nightly`;scaffoldBase=`.cursor`;getMacAppPath(){return`/Applications/Cursor Nightly.app`}getInstructionFilePath(){return this.getPathModule().resolve(A(),this.scaffoldBase,`rules`,`aikit.mdc`)}},Qt=class e extends V{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(m(this.getCopilotConfigDir()))return!0;let t=this.getJetBrainsBaseDir();if(!m(t))return!1;try{return _(t,{withFileTypes:!0}).some(t=>t.isDirectory()&&e.PRODUCTS.some(e=>t.name.startsWith(e)))}catch{return!1}}getConfigPath(){return w(this.getCopilotConfigDir(),`mcp.json`)}async registerMcp(e,t,n){let r=this.getCopilotConfigDir();await ut(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=w(r,`${e}-launcher.js`);await pt(n,t,`utf-8`),o=[...i.slice(0,a),n,...i.slice(a+2)]}else o=[...i];let s={type:`stdio`,...t,args:o};await super.registerMcp(e,s,n)}getScaffoldRoot(e){return null}getInstructionsRoot(e){return null}getScaffoldPaths(e){return{agents:null,skills:null,prompts:null,flows:null,commands:null,instructions:null,manifest:null}}buildInstructionContent(e,t){return t}getCopilotConfigDir(){let e=A();return process.platform===`win32`?w(process.env.LOCALAPPDATA??w(e,`AppData`,`Local`),`github-copilot`,`intellij`):process.platform===`darwin`?w(e,`Library`,`Application Support`,`github-copilot`,`intellij`):w(process.env.XDG_CONFIG_HOME??w(e,`.config`),`github-copilot`,`intellij`)}getJetBrainsBaseDir(){let e=A();return process.platform===`win32`?w(process.env.APPDATA??w(e,`AppData`,`Roaming`),`JetBrains`):process.platform===`darwin`?w(e,`Library`,`Application Support`,`JetBrains`):w(process.env.XDG_CONFIG_HOME??w(e,`.config`),`JetBrains`)}},$t=class extends H{id=`trae`;name=`Trae`;configKey=`servers`;configDirName=`Trae`;scaffoldBase=`.trae`;getMacAppPath(){return`/Applications/Trae.app`}getInstructionFilePath(){return this.getPathModule().resolve(A(),this.scaffoldBase,`rules`,`aikit.md`)}},en=class extends H{id=`vscode`;name=`VS Code`;configKey=`servers`;configDirName=`Code`;scaffoldBase=`.copilot`;hasInstructions=!0;getMacAppPath(){return`/Applications/Visual Studio Code.app`}getInstructionFilePath(){return this.hasInstructions?this.getPathModule().resolve(A(),this.scaffoldBase,`instructions`,`copilot-instructions.md`):null}buildInstructionContent(e,t){return`---\napplyTo: "**"\n---\n\n${e}\n---\n\n${t}`}},tn=class extends H{id=`vscode-insiders`;name=`VS Code Insiders`;configKey=`servers`;configDirName=`Code - Insiders`;scaffoldBase=`.copilot`;hasInstructions=!0;getMacAppPath(){return`/Applications/Visual Studio Code - Insiders.app`}getInstructionFilePath(){return this.hasInstructions?this.getPathModule().resolve(A(),this.scaffoldBase,`instructions`,`copilot-instructions.md`):null}buildInstructionContent(e,t){return`---\napplyTo: "**"\n---\n\n${e}\n---\n\n${t}`}},nn=class extends H{id=`vscodium`;name=`VSCodium`;configKey=`servers`;configDirName=`VSCodium`;scaffoldBase=`.copilot`;hasInstructions=!0;getMacAppPath(){return`/Applications/VSCodium.app`}getInstructionFilePath(){return this.hasInstructions?this.getPathModule().resolve(A(),this.scaffoldBase,`instructions`,`copilot-instructions.md`):null}buildInstructionContent(e,t){return`---\napplyTo: "**"\n---\n\n${e}\n---\n\n${t}`}},rn=class extends H{id=`windsurf`;name=`Windsurf`;configKey=`servers`;configDirName=`Windsurf`;scaffoldBase=`.windsurf`;getMacAppPath(){return`/Applications/Windsurf.app`}getInstructionFilePath(){return this.getPathModule().resolve(A(),this.scaffoldBase,`rules`,`aikit.md`)}},an=class extends V{id=`gemini-cli`;name=`Gemini CLI`;family=`gemini`;platforms=[`win32`,`darwin`,`linux`];scope=`user`;configKey=`mcpServers`;async detect(){return this.isPlatformSupported()?m(this.getPathModule().resolve(A(),`.gemini`)):!1}getConfigPath(){return this.getPathModule().resolve(A(),`.gemini`,`settings.json`)}getScaffoldRoot(){return this.getPathModule().resolve(A(),`.gemini`)}getScaffoldPaths(){let e=this.getPathModule(),t=e.resolve(A(),`.gemini`);return{agents:e.resolve(t,`agents`),skills:e.resolve(t,`skills`),prompts:null,flows:e.resolve(t,`flows`),commands:null,instructions:e.resolve(t,`AGENTS.md`),manifest:e.resolve(t,`.aikit-scaffold.json`)}}getPathModule(){return process.platform===`win32`?T:S}},on=class extends V{id=`zed`;name=`Zed`;family=`zed`;platforms=[`win32`,`darwin`,`linux`];scope=`user`;configKey=`context_servers`;async detect(){return this.isPlatformSupported()?m(this.getConfigDir()):!1}getConfigPath(){return this.getPathModule().resolve(this.getConfigDir(),`settings.json`)}async registerMcp(e,t){let{type:n,...r}=t,i={...r,env:r.env??{}};await super.registerMcp(e,i)}getScaffoldRoot(){return this.getConfigDir()}getScaffoldPaths(){let e=this.getPathModule(),t=this.getConfigDir();return{agents:e.resolve(t,`prompts`),skills:null,prompts:e.resolve(t,`prompts`),flows:null,commands:null,instructions:null,manifest:e.resolve(t,`.aikit-scaffold.json`)}}getConfigDir(){let e=this.getPathModule();return process.platform===`win32`?e.resolve(process.env.APPDATA||A(),`Zed`):e.resolve(A(),`.config`,`zed`)}getPathModule(){return process.platform===`win32`?T:S}};const U=[new en,new tn,new nn,new Xt,new Zt,new rn,new $t,new Yt,new Qt,new qt,new an,new Jt,new on];function sn(){return[...U]}async function cn(e){let t=e?.scope?U.filter(t=>t.scope===e.scope):U;return(await Promise.allSettled(t.map(async e=>await e.detect()?e:null))).flatMap(e=>e.status!==`fulfilled`||e.value===null?[]:[e.value])}function ln(e){let t=e;for(let e=0;e<10;e++){try{let e=x(t,`package.json`);if(m(e)&&JSON.parse(g(e,`utf8`)).name===`@vpxa/aikit`)return t}catch{}let e=b(t);if(e===t)break;t=e}return w(e,`..`,`..`,`..`)}function un(){let e={command:s.command,args:s.args?[...s.args]:void 0,type:s.type};if(process.platform!==`win32`){let t=process.env.PATH;t&&(e.env={PATH:t});try{let t=ht(`which`,[`node`],{encoding:`utf-8`,timeout:3e3}).trim();t&&m(t)&&(e.command=t)}catch{}}return e}const W=new Set([`VS Code`,`VS Code Insiders`,`VSCodium`]);function dn(e,t=!1){if(!W.has(e.name))return;let n=w(b(e.getConfigPath()),`settings.json`),r={};if(m(n))try{let e=g(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(d))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&&(te(n,`${JSON.stringify(r,null,2)}\n`,`utf-8`),console.log(` ${e.name}: updated settings.json`))}async function fn(r,o,s,l,u=!1){let d=new Map;for(let e of o)e.getScaffoldRoot()!==null&&d.set(e.id,e);if(o.some(e=>W.has(e.name))){let e=sn().find(e=>e.id===`copilot-cli`);e&&d.set(e.id,e)}if(d.size===0){console.log(` No IDEs with global scaffold support detected.`);return}let p=await n(r,`copilot`),g=new Map;for(let e of p){let t=e.path.indexOf(`/`);if(t===-1)continue;let n=e.path.substring(0,t);if(n!==`agents`&&n!==`prompts`)continue;let r=g.get(n)??[];r.push({path:e.path.substring(t+1),content:e.content}),g.set(n,r)}let _=await n(r,`skills`),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,`flows`),x=new Set;for(let e of y){let t=e.path.indexOf(`/`);t!==-1&&x.add(e.path.substring(0,t))}let S=await n(r,`claude-code`),C=new Set,T=new Set,E=new Set,ne=(n,r,o)=>{let s=g.get(o);if(!n||!r||!s||s.length===0)return;let c=`${o}:${r}:${n}`;if(C.has(c))return;C.add(c);let d=e(r)??a(l);d.version=l,i(s,n,d,o,u),t(r,d),E.add(b(r))},D=(n,r,o,s)=>{if(!n||!r||s.length===0)return;let c=`${o}:${r}:${n}`;if(C.has(c))return;if(C.add(c),o===`flows`&&!T.has(n)){for(let e of x){let t=w(n,e,`skills`);m(t)&&(ee(t,{recursive:!0,force:!0}),console.log(` ${b(r)}: migrated ${e} flow to steps/ layout`))}T.add(n)}let d=e(r)??a(l);d.version=l,i(s,n,d,o,u),t(r,d),E.add(b(r))};for(let e of d.values()){let t=e.getScaffoldPaths();ne(t.agents,t.manifest,`agents`),ne(t.prompts,t.manifest,`prompts`),D(t.skills,t.manifest,`skills`,_),D(t.flows,t.manifest,`flows`,y),D(t.commands,t.manifest,`commands`,S)}for(let e of E)console.log(` ${e}: scaffold updated (${v.size} skills)`);let O=new Set,re=c(`aikit`,s),ie=f(`aikit`,s);for(let e of d.values()){let t=e.getScaffoldPaths().instructions;!t||O.has(t)||(h(b(t),{recursive:!0}),te(t,e.buildInstructionContent(re,ie),`utf-8`),O.add(t))}O.size>0&&console.log(` Instruction files: ${[...O].join(`, `)}`)}function pn(e){let t=[];for(let n of e){let e=n.getScaffoldRoot();if(e)if(W.has(n.name)){let r=n.getInstructionsRoot()??e;t.push(w(r,`kb.instructions.md`)),t.push(w(r,`aikit.instructions.md`))}else n.name===`Cursor`||n.name===`Cursor Nightly`?t.push(w(e,`rules`,`kb.mdc`)):n.name===`Windsurf`&&t.push(w(e,`rules`,`kb.md`))}for(let e of t)m(e)&&(v(e),console.log(` Removed legacy file: ${e}`))}async function G(e){let t=o,n=ln(b(E(import.meta.url))),r=JSON.parse(g(w(n,`package.json`),`utf-8`)).version;console.log(`Initializing @vpxa/aikit v${r}...\n`);let i=vt();h(i,{recursive:!0}),console.log(` Global data store: ${i}`),St({version:1,workspaces:{}}),console.log(` Created registry.json`);let a=await cn({scope:`user`});if(a.length===0)console.log(`
|
|
8
|
-
No supported IDEs detected. You can manually add the MCP server config.`);else{console.log(`\n Detected ${a.length} IDE(s):`);let n=
|
|
9
|
-
Installing scaffold files:`),await
|
|
5
|
+
Dead in docs (informational):`);for(let t of e.deadInDocs)console.log(` - ${t.path}:${t.line} ${t.kind} ${t.name}`)}}function Vt(e){console.log(e.path),console.log(` Language: ${e.language}`),console.log(` Lines: ${e.lines}`),console.log(` Estimated tokens: ~${e.estimatedTokens}`),console.log(``),B(`Imports`,e.imports),B(`Exports`,e.exports),B(`Functions`,e.functions.map(e=>`${e.name} @ line ${e.line}${e.exported?` [exported]`:``}`)),B(`Classes`,e.classes.map(e=>`${e.name} @ line ${e.line}${e.exported?` [exported]`:``}`)),B(`Interfaces`,e.interfaces.map(e=>`${e.name} @ line ${e.line}`)),B(`Types`,e.types.map(e=>`${e.name} @ line ${e.line}`))}function Ht(e){if(console.log(`Symbol: ${e.name}`),e.definedIn?console.log(`Defined in: ${e.definedIn.path}:${e.definedIn.line} (${e.definedIn.kind})`):console.log(`Defined in: not found`),console.log(``),console.log(`Imported by:`),e.importedBy.length===0)console.log(` none`);else for(let t of e.importedBy)console.log(` - ${t.path}:${t.line} ${t.importStatement}`);if(console.log(``),console.log(`Referenced in:`),e.referencedIn.length===0)console.log(` none`);else for(let t of e.referencedIn)console.log(` - ${t.path}:${t.line} ${t.context}`)}function R(e){console.log(e.name),console.log(` Files: ${e.files.length}`),console.log(` Updated: ${e.updated}`),e.description&&console.log(` Description: ${e.description}`);for(let t of e.files)console.log(` - ${t}`)}function z(e){if(console.log(e.id),console.log(` Label: ${e.label}`),console.log(` Created: ${e.createdAt}`),e.notes&&console.log(` Notes: ${e.notes}`),e.files?.length){console.log(` Files: ${e.files.length}`);for(let t of e.files)console.log(` - ${t}`)}console.log(` Data:`);for(let t of JSON.stringify(e.data,null,2).split(`
|
|
6
|
+
`))console.log(` ${t}`)}function B(e,t){if(console.log(`${e}:`),t.length===0){console.log(` none`),console.log(``);return}for(let e of t)console.log(` - ${e}`);console.log(``)}function Ut(e){let t=e.trim();if(!t)return``;try{return JSON.parse(t)}catch{return e}}function Wt(e){let t=e.trim();if(!t)return{};let n=JSON.parse(t);if(!n||typeof n!=`object`||Array.isArray(n))throw Error(`Checkpoint data must be a JSON object.`);return n}function Gt(e,t,n=60){let r=new Map;for(let t=0;t<e.length;t++){let i=e[t];r.set(i.record.id,{record:i.record,score:1/(n+t+1)})}for(let e=0;e<t.length;e++){let i=t[e],a=r.get(i.record.id);a?a.score+=1/(n+e+1):r.set(i.record.id,{record:i.record,score:1/(n+e+1)})}return[...r.values()].sort((e,t)=>t.score-e.score)}const Kt=[{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=N(e,`--tool`,``).trim()||void 0,n=await F();n.trim()||(console.error(`Usage: aikit parse-output [--tool tsc|vitest|biome|git-status]`),process.exit(1)),Mt(Ne(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=>{It(await Se({cwd:N(e,`--cwd`,``).trim()||void 0,commitCount:M(e,`--commit-count`,5),includeDiff:P(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 F();e.trim()||(console.error(`Usage: git diff | aikit diff`),process.exit(1)),Lt(he({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)),Vt(await _e({path:C(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();switch(t||(console.error(`Usage: aikit checkpoint <save|load|list|latest> [label-or-id] [--data json] [--notes text]`),process.exit(1)),t){case`save`:{let t=e.shift()?.trim(),n=N(e,`--data`,``),r=N(e,`--notes`,``).trim()||void 0,i=n.trim()?``:await F();t||(console.error(`Usage: aikit checkpoint save <label> [--data json] [--notes text]`),process.exit(1)),z(ce(t,Wt(n||i),{notes:r}));return}case`load`:{let t=e.shift()?.trim();t||(console.error(`Usage: aikit checkpoint load <id>`),process.exit(1));let n=se(t);if(!n){console.log(`No checkpoint found: ${t}`);return}z(n);return}case`list`:{let e=oe();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=ae();if(!e){console.log(`No checkpoints saved.`);return}z(e);return}default:console.error(`Unknown checkpoint action: ${t}`),console.error(`Actions: save, load, list, latest`),process.exit(1)}}}];function qt(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]!==`
|
|
7
|
+
`;)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 V=class{isPlatformSupported(){return this.platforms.includes(process.platform)}async readConfig(e){let t=this.getConfigPath(e);if(!m(t))return{};let n=await O(t,`utf-8`);try{return JSON.parse(qt(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=y(n),i=b(r,`.aikit-tmp-${gt()}.json`);await ft(r,{recursive:!0});try{await ht(i,`${JSON.stringify(e,null,2)}\n`,`utf-8`),await pt(i,n)}catch(e){try{await mt(i)}catch{}throw e}}async registerMcp(e,t,n){let r=await this.readConfig(n);r[this.configKey]||(r[this.configKey]={}),r[this.configKey][e]=t,await this.writeConfig(r,n)}async unregisterMcp(e,t){let n=await this.readConfig(t);n[this.configKey]&&(delete n[this.configKey][e],await this.writeConfig(n,t))}getScaffoldRoot(e){return null}getInstructionsRoot(e){return null}getScaffoldPaths(e){return{agents:null,skills:null,prompts:null,flows:null,commands:null,instructions:null,manifest:null}}buildInstructionContent(e,t){return`${e}\n---\n\n${t}`}},Jt=class extends V{id=`claude-code`;name=`Claude Code`;family=`claude`;platforms=[`win32`,`darwin`,`linux`];scope=`user`;configKey=`mcpServers`;async detect(){return this.isPlatformSupported()?m(this.getPathModule().resolve(k(),`.claude`)):!1}getConfigPath(){return this.getPathModule().resolve(k(),`.claude`,`mcp.json`)}getScaffoldRoot(){return this.getPathModule().resolve(k(),`.claude`)}getScaffoldPaths(){let e=this.getPathModule(),t=e.resolve(k(),`.claude`);return{agents:e.resolve(t,`agents`),skills:e.resolve(t,`skills`),prompts:null,flows:e.resolve(t,`flows`),commands:e.resolve(t,`commands`),instructions:e.resolve(t,`CLAUDE.md`),manifest:e.resolve(t,`.aikit-scaffold.json`)}}buildInstructionContent(e,t){return`${e}\n---\n\n${t}`}getPathModule(){return process.platform===`win32`?w:x}},Yt=class extends V{id=`codex-cli`;name=`Codex CLI`;family=`codex`;platforms=[`win32`,`darwin`,`linux`];scope=`user`;configKey=`mcpServers`;async detect(){return this.isPlatformSupported()?m(this.getPathModule().resolve(k(),`.codex`)):!1}getConfigPath(){return this.getPathModule().resolve(k(),`.codex`,`config.json`)}getScaffoldRoot(){return this.getPathModule().resolve(k(),`.codex`)}getScaffoldPaths(){let e=this.getPathModule(),t=e.resolve(k(),`.codex`);return{agents:e.resolve(t,`agents`),skills:e.resolve(t,`skills`),prompts:null,flows:e.resolve(t,`flows`),commands:null,instructions:e.resolve(t,`AGENTS.md`),manifest:e.resolve(t,`.aikit-scaffold.json`)}}getPathModule(){return process.platform===`win32`?w:x}},H=class extends V{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 m(e)||t!==null&&m(t)}return m(e)}getConfigPath(){return this.getPathModule().resolve(this.getConfigDir(),`mcp.json`)}getScaffoldRoot(){return this.getPathModule().resolve(k(),this.scaffoldBase)}getInstructionsRoot(){let e=this.getInstructionFilePath();return e?this.getPathModule().dirname(e):null}getScaffoldPaths(){let e=this.getPathModule(),t=e.resolve(k(),this.scaffoldBase);return{agents:e.resolve(t,`agents`),skills:e.resolve(t,`skills`),prompts:e.resolve(this.getConfigDir(),`prompts`),flows:e.resolve(t,`flows`),commands:null,instructions:this.getInstructionFilePath(),manifest:e.resolve(t,`.aikit-scaffold.json`)}}getConfigDir(){let e=this.getPathModule(),t=k();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`?w:x}},Xt=class extends V{id=`copilot-cli`;name=`Copilot CLI`;family=`copilot`;platforms=[`win32`,`darwin`,`linux`];scope=`user`;configKey=`mcpServers`;async detect(){return this.isPlatformSupported()?m(C(k(),`.copilot`)):!1}getConfigPath(){return C(k(),`.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 C(k(),`.copilot`)}getInstructionsRoot(){return null}getScaffoldPaths(){let e=C(k(),`.copilot`);return{agents:C(e,`agents`),skills:C(e,`skills`),prompts:null,flows:C(e,`flows`),commands:null,instructions:C(k(),`.github`,`copilot-instructions.md`),manifest:C(e,`.aikit-scaffold.json`)}}},Zt=class extends H{id=`cursor`;name=`Cursor`;configKey=`mcpServers`;configDirName=`Cursor`;scaffoldBase=`.cursor`;getMacAppPath(){return`/Applications/Cursor.app`}getInstructionFilePath(){return this.getPathModule().resolve(k(),this.scaffoldBase,`rules`,`aikit.mdc`)}},Qt=class extends H{id=`cursor-nightly`;name=`Cursor Nightly`;configKey=`mcpServers`;configDirName=`Cursor Nightly`;scaffoldBase=`.cursor`;getMacAppPath(){return`/Applications/Cursor Nightly.app`}getInstructionFilePath(){return this.getPathModule().resolve(k(),this.scaffoldBase,`rules`,`aikit.mdc`)}},$t=class e extends V{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(m(this.getCopilotConfigDir()))return!0;let t=this.getJetBrainsBaseDir();if(!m(t))return!1;try{return _(t,{withFileTypes:!0}).some(t=>t.isDirectory()&&e.PRODUCTS.some(e=>t.name.startsWith(e)))}catch{return!1}}getConfigPath(){return C(this.getCopilotConfigDir(),`mcp.json`)}async registerMcp(e,t,n){let r=this.getCopilotConfigDir();await ft(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=C(r,`${e}-launcher.js`);await ht(n,t,`utf-8`),o=[...i.slice(0,a),n,...i.slice(a+2)]}else o=[...i];let s={type:`stdio`,...t,args:o};await super.registerMcp(e,s,n)}getScaffoldRoot(e){return null}getInstructionsRoot(e){return null}getScaffoldPaths(e){return{agents:null,skills:null,prompts:null,flows:null,commands:null,instructions:null,manifest:null}}buildInstructionContent(e,t){return t}getCopilotConfigDir(){let e=k();return process.platform===`win32`?C(process.env.LOCALAPPDATA??C(e,`AppData`,`Local`),`github-copilot`,`intellij`):process.platform===`darwin`?C(e,`Library`,`Application Support`,`github-copilot`,`intellij`):C(process.env.XDG_CONFIG_HOME??C(e,`.config`),`github-copilot`,`intellij`)}getJetBrainsBaseDir(){let e=k();return process.platform===`win32`?C(process.env.APPDATA??C(e,`AppData`,`Roaming`),`JetBrains`):process.platform===`darwin`?C(e,`Library`,`Application Support`,`JetBrains`):C(process.env.XDG_CONFIG_HOME??C(e,`.config`),`JetBrains`)}},en=class extends H{id=`trae`;name=`Trae`;configKey=`servers`;configDirName=`Trae`;scaffoldBase=`.trae`;getMacAppPath(){return`/Applications/Trae.app`}getInstructionFilePath(){return this.getPathModule().resolve(k(),this.scaffoldBase,`rules`,`aikit.md`)}},tn=class extends H{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(k(),this.scaffoldBase,`instructions`,`copilot-instructions.md`):null}buildInstructionContent(e,t){return`---\napplyTo: "**"\n---\n\n${e}\n---\n\n${t}`}},nn=class extends H{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(k(),this.scaffoldBase,`instructions`,`copilot-instructions.md`):null}buildInstructionContent(e,t){return`---\napplyTo: "**"\n---\n\n${e}\n---\n\n${t}`}},rn=class extends H{id=`vscodium`;name=`VSCodium`;configKey=`servers`;configDirName=`VSCodium`;scaffoldBase=`.copilot`;hasInstructions=!0;getMacAppPath(){return`/Applications/VSCodium.app`}getInstructionFilePath(){return this.hasInstructions?this.getPathModule().resolve(k(),this.scaffoldBase,`instructions`,`copilot-instructions.md`):null}buildInstructionContent(e,t){return`---\napplyTo: "**"\n---\n\n${e}\n---\n\n${t}`}},an=class extends H{id=`windsurf`;name=`Windsurf`;configKey=`servers`;configDirName=`Windsurf`;scaffoldBase=`.windsurf`;getMacAppPath(){return`/Applications/Windsurf.app`}getInstructionFilePath(){return this.getPathModule().resolve(k(),this.scaffoldBase,`rules`,`aikit.md`)}},on=class extends V{id=`gemini-cli`;name=`Gemini CLI`;family=`gemini`;platforms=[`win32`,`darwin`,`linux`];scope=`user`;configKey=`mcpServers`;async detect(){return this.isPlatformSupported()?m(this.getPathModule().resolve(k(),`.gemini`)):!1}getConfigPath(){return this.getPathModule().resolve(k(),`.gemini`,`settings.json`)}getScaffoldRoot(){return this.getPathModule().resolve(k(),`.gemini`)}getScaffoldPaths(){let e=this.getPathModule(),t=e.resolve(k(),`.gemini`);return{agents:e.resolve(t,`agents`),skills:e.resolve(t,`skills`),prompts:null,flows:e.resolve(t,`flows`),commands:null,instructions:e.resolve(t,`AGENTS.md`),manifest:e.resolve(t,`.aikit-scaffold.json`)}}getPathModule(){return process.platform===`win32`?w:x}},sn=class extends V{id=`zed`;name=`Zed`;family=`zed`;platforms=[`win32`,`darwin`,`linux`];scope=`user`;configKey=`context_servers`;async detect(){return this.isPlatformSupported()?m(this.getConfigDir()):!1}getConfigPath(){return this.getPathModule().resolve(this.getConfigDir(),`settings.json`)}async registerMcp(e,t){let{type:n,...r}=t,i={...r,env:r.env??{}};await super.registerMcp(e,i)}getScaffoldRoot(){return this.getConfigDir()}getScaffoldPaths(){let e=this.getPathModule(),t=this.getConfigDir();return{agents:e.resolve(t,`prompts`),skills:null,prompts:e.resolve(t,`prompts`),flows:null,commands:null,instructions:null,manifest:e.resolve(t,`.aikit-scaffold.json`)}}getConfigDir(){let e=this.getPathModule();return process.platform===`win32`?e.resolve(process.env.APPDATA||k(),`Zed`):e.resolve(k(),`.config`,`zed`)}getPathModule(){return process.platform===`win32`?w:x}};const U=[new tn,new nn,new rn,new Zt,new Qt,new an,new en,new Xt,new $t,new Jt,new on,new Yt,new sn];function cn(){return[...U]}async function ln(e){let t=e?.scope?U.filter(t=>t.scope===e.scope):U;return(await Promise.allSettled(t.map(async e=>await e.detect()?e:null))).flatMap(e=>e.status!==`fulfilled`||e.value===null?[]:[e.value])}function un(e){let t=e;for(let e=0;e<10;e++){try{let e=b(t,`package.json`);if(m(e)&&JSON.parse(g(e,`utf8`)).name===`@vpxa/aikit`)return t}catch{}let e=y(t);if(e===t)break;t=e}return C(e,`..`,`..`,`..`)}function dn(){let e={command:c.command,args:c.args?[...c.args]:void 0,type:c.type};if(process.platform!==`win32`){let t=process.env.PATH;t&&(e.env={PATH:t});try{let t=_t(`which`,[`node`],{encoding:`utf-8`,timeout:3e3}).trim();t&&m(t)&&(e.command=t)}catch{}}return e}const W=new Set([`VS Code`,`VS Code Insiders`,`VSCodium`]);function fn(e,t=!1){if(!W.has(e.name))return;let n=C(y(e.getConfigPath()),`settings.json`),r={};if(m(n))try{let e=g(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(f))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&&(re(n,`${JSON.stringify(r,null,2)}\n`,`utf-8`),console.log(` ${e.name}: updated settings.json`))}async function pn(r,i,s,c,u=!1){let d=new Map;for(let e of i)e.getScaffoldRoot()!==null&&d.set(e.id,e);if(i.some(e=>W.has(e.name))){let e=cn().find(e=>e.id===`copilot-cli`);e&&d.set(e.id,e)}if(d.size===0){console.log(` No IDEs with global scaffold support detected.`);return}let f=await n(r,`copilot`),p=new Map;for(let e of f){let t=e.path.indexOf(`/`);if(t===-1)continue;let n=e.path.substring(0,t);if(n!==`agents`&&n!==`prompts`)continue;let r=p.get(n)??[];r.push({path:e.path.substring(t+1),content:e.content}),p.set(n,r)}let g=await n(r,`skills`),_=new Set;for(let e of g){let t=e.path.indexOf(`/`);t!==-1&&_.add(e.path.substring(0,t))}let ne=await n(r,`flows`),v=new Set;for(let e of ne){let t=e.path.indexOf(`/`);t!==-1&&v.add(e.path.substring(0,t))}let b=await n(r,`claude-code`),x=new Set,S=new Set,w=new Set,T=(n,r,i)=>{let s=p.get(i);if(!n||!r||!s||s.length===0)return;let l=`${i}:${r}:${n}`;if(x.has(l))return;x.add(l);let d=e(r)??o(c);d.version=c,a(s,n,d,i,u),t(r,d),w.add(y(r))},E=(n,r,i,s)=>{if(!n||!r||s.length===0)return;let l=`${i}:${r}:${n}`;if(x.has(l))return;if(x.add(l),i===`flows`&&!S.has(n)){for(let e of v){let t=C(n,e,`skills`);m(t)&&(te(t,{recursive:!0,force:!0}),console.log(` ${y(r)}: migrated ${e} flow to steps/ layout`))}S.add(n)}let d=e(r)??o(c);d.version=c,a(s,n,d,i,u),t(r,d),w.add(y(r))};for(let e of d.values()){let t=e.getScaffoldPaths();T(t.agents,t.manifest,`agents`),T(t.prompts,t.manifest,`prompts`),E(t.skills,t.manifest,`skills`,g),E(t.flows,t.manifest,`flows`,ne),E(t.commands,t.manifest,`commands`,b)}for(let e of w)console.log(` ${e}: scaffold updated (${_.size} skills)`);let D=new Set,ie=l(`aikit`,s),ae=ee(`aikit`,s);for(let e of d.values()){let t=e.getScaffoldPaths().instructions;!t||D.has(t)||(h(y(t),{recursive:!0}),re(t,e.buildInstructionContent(ie,ae),`utf-8`),D.add(t))}D.size>0&&console.log(` Instruction files: ${[...D].join(`, `)}`)}function mn(e){let t=[];for(let n of e){let e=n.getScaffoldRoot();if(e)if(W.has(n.name)){let r=n.getInstructionsRoot()??e;t.push(C(r,`kb.instructions.md`)),t.push(C(r,`aikit.instructions.md`))}else n.name===`Cursor`||n.name===`Cursor Nightly`?t.push(C(e,`rules`,`kb.mdc`)):n.name===`Windsurf`&&t.push(C(e,`rules`,`kb.md`))}for(let e of t)m(e)&&(ne(e),console.log(` Removed legacy file: ${e}`))}async function G(e){let t=s,n=un(y(T(import.meta.url))),r=JSON.parse(g(C(n,`package.json`),`utf-8`)).version;console.log(`Initializing @vpxa/aikit v${r}...\n`);let i=bt();h(i,{recursive:!0}),console.log(` Global data store: ${i}`),Ct({version:1,workspaces:{}}),console.log(` Created registry.json`);let a=await ln({scope:`user`});if(a.length===0)console.log(`
|
|
8
|
+
No supported IDEs detected. You can manually add the MCP server config.`);else{console.log(`\n Detected ${a.length} IDE(s):`);let n=dn();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)fn(t,e.force)}console.log(`
|
|
9
|
+
Installing scaffold files:`),await pn(n,a,t,r,e.force),mn(a),console.log(`
|
|
10
10
|
User-level AI Kit installation complete!`),console.log(`
|
|
11
|
-
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
|
|
11
|
+
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 hn=[{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`}],gn=[`.copilot/skills`,`.agents/skills`],_n=/^(?:mcp_)?aikit_[a-z0-9_]+$/,vn=y(T(import.meta.url));function yn(e,t){return(S(e,t)||t).split(`\\`).join(`/`)}function bn(e){let t=new Set;for(let n of hn){let r=b(e,n.directory);if(m(r))try{for(let e of _(r,{withFileTypes:!0})){if(n.suffix===`/SKILL.md`){if(e.isDirectory()){let n=b(r,e.name,`SKILL.md`);m(n)&&t.add(n)}continue}e.isFile()&&e.name.endsWith(n.suffix)&&t.add(b(r,e.name))}}catch{}}return[...t].sort()}function xn(e){let t=new Set;for(let n of gn){let r=b(e,n);if(m(r))try{for(let e of _(r,{withFileTypes:!0}))e.isDirectory()&&t.add(e.name.toLowerCase())}catch{}}return t}function Sn(e){if(!e.startsWith(`---`))return null;let t=e.match(/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/);return t?t[1]:null}function Cn(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=K(i);e&&r.push(e),i=``;continue}i+=e}let o=K(i);return o&&r.push(o),r}function K(e){let t=e.trim();return t.startsWith(`"`)&&t.endsWith(`"`)||t.startsWith(`'`)&&t.endsWith(`'`)?t.slice(1,-1).trim():t}function wn(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 Tn(e){if(!e.startsWith(`---`))return;let t=Sn(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 wn(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=wn(a);if(o)return o}}function En(e,t){try{let n=g(t,`utf8`),r=Tn(n);return{filePath:t,displayPath:yn(e,t),content:n,parsed:r?null:i(n),yamlError:r}}catch{return null}}function q(e){return bn(e).map(t=>En(e,t)).filter(e=>e!==null)}function Dn(e){if(!e.parsed)return[];let t=e.parsed.fields.applyTo;return t?Cn(t):[]}function On(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 kn(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 An={name:`yaml-parse`,run:e=>{try{return q(e).filter(e=>e.yamlError).map(e=>({severity:`error`,file:e.displayPath,message:`invalid YAML frontmatter: ${e.yamlError}`,code:`yaml-parse-error`}))}catch{return[]}}},jn={name:`skill-refs`,run:e=>{try{let t=xn(e);if(t.size===0)return[];let n=[];for(let r of q(e))if(r.filePath.endsWith(`.agent.md`))for(let e of kn(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[]}}},Mn={name:`tool-names`,run:e=>{try{let t=[];for(let n of q(e))if(n.parsed)for(let e of n.parsed.tools.map(K))e&&!_n.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[]}}},Nn={name:`glob-patterns`,run:e=>{try{let t=[];for(let n of q(e))if(n.parsed)for(let e of Dn(n)){let r=On(e);r&&t.push({severity:`warning`,file:n.displayPath,message:`applyTo pattern '${e}' is invalid: ${r}`,code:`glob-pattern-invalid`})}return t}catch{return[]}}};function Pn(e){let t=e;for(let e=0;e<10;e++){try{let e=b(t,`package.json`);if(m(e)&&JSON.parse(g(e,`utf8`)).name===`@vpxa/aikit`)return t}catch{}let e=y(t);if(e===t)break;t=e}return C(e,`..`,`..`,`..`)}async function J(e){let t=console.log;console.log=()=>{};try{return await e()}finally{console.log=t}}async function Fn(e){let t=e.reset??!1,n=e.silent??!1,r=[],i=0,a=0,o=await ln({scope:`user`}),c=dn(),l=Pn(vn),u=JSON.parse(g(b(l,`package.json`),`utf-8`)).version,d=e=>{r.push(e),a+=1,n||console.log(`- ${e}`)};for(let e of o){let n=e.getConfigPath();if(i+=1,!m(n)){h(y(n),{recursive:!0}),await J(()=>e.registerMcp(s,c)),d(`Fixed: ${e.name} — MCP config was missing, recreated`);continue}try{if(!(await e.readConfig())[e.configKey]?.aikit){h(y(n),{recursive:!0}),await J(()=>e.registerMcp(s,c)),d(`Fixed: ${e.name} — MCP entry was missing, added`);continue}t&&(h(y(n),{recursive:!0}),await J(()=>e.registerMcp(s,c)),d(`Reset: ${e.name} — MCP config restored to factory defaults`))}catch{p(n,`${n}.bak`),h(y(n),{recursive:!0}),await J(()=>e.registerMcp(s,c)),d(`Fixed: ${e.name} — MCP config was corrupt, backed up and recreated`)}}await J(async()=>{for(let e of o)fn(e,t)}),await J(()=>pn(l,o,s,u??`0.0.0`,t));let f=[An,jn,Mn,Nn];for(let e of f)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 In=[{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...
|
|
12
12
|
`:`Running AI Kit doctor...
|
|
13
|
-
`);let n=await
|
|
14
|
-
Issues found:`);for(let e of n.issues)console.log(` - ${e}`)}}}],In=[{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)),L(Pe(t,n,e));return}case`stop`:{let t=e.shift()?.trim();t||(console.error(`Usage: aikit proc stop <id>`),process.exit(1));let n=Ie(t);if(!n){console.log(`No managed process found: ${t}`);return}L(n);return}case`status`:{let t=e.shift()?.trim();t||(console.error(`Usage: aikit proc status <id>`),process.exit(1));let n=Fe(t);if(!n){console.log(`No managed process found: ${t}`);return}L(n);return}case`list`:{let e=Me();if(e.length===0){console.log(`No managed processes.`);return}for(let t of e)L(t),console.log(``);return}case`logs`:{let t=M(e,`--tail`,50),n=e.shift()?.trim();n||(console.error(`Usage: aikit proc logs <id> [--tail N]`),process.exit(1));let r=Ne(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=ct({path:w(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=lt(t);console.log(n?`Stopped watcher: ${t}`:`Watcher not found: ${t}`);return}case`list`:{let e=st();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 de();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=N(e,`--model`,``),n=N(e,`--system`,``),r=M(e,`--temp`,.3),i=N(e,`--context`,``),a=e.join(` `);a||=await F(),a||(console.error(`Usage: aikit delegate [--model name] <prompt>`),process.exit(1));let o;i&&(o=await k(w(i),`utf-8`));let s=await ue({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)`)}}],Ln=[{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=N(e,`--lang`,`js`),n=M(e,`--timeout`,5e3),r=e.join(` `),i=r.trim()?``:await F(),a=r||i;a.trim()||(console.error(`Usage: aikit eval [code] [--lang js|ts] [--timeout ms]`),process.exit(1));let o=me({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:`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=N(e,`--grep`,``).trim()||void 0,n=N(e,`--cwd`,``).trim()||void 0,r=M(e,`--timeout`,6e4),i=e.filter(Boolean),a=await at({files:i.length>0?i:void 0,grep:t,cwd:n,timeout:r});Pt(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()??``;(!t||!n||!r)&&(console.error(`Usage: aikit rename <old> <new> <path> [--dry-run] [--extensions .ts,.tsx] [--exclude dist/**]`),process.exit(1));let i=I(N(e,`--extensions`,``)),a=I(N(e,`--exclude`,``)),o=await qe({oldName:t,newName:n,rootPath:w(r),extensions:i.length>0?i:void 0,exclude:a.length>0?a:void 0,dryRun:P(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=N(e,`--rules`,``).trim();(!t||!n)&&(console.error(`Usage: aikit codemod <path> --rules <file.json> [--dry-run] [--extensions .ts,.tsx] [--exclude dist/**]`),process.exit(1));let r=await k(w(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=I(N(e,`--extensions`,``)),o=I(N(e,`--exclude`,``)),s=await se({rootPath:w(t),rules:i,extensions:a.length>0?a:void 0,exclude:o.length>0?o:void 0,dryRun:P(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 F();(!t||!n.trim())&&(console.error(`Usage: cat data.json | aikit transform <expression>`),process.exit(1));let r=le({input:n,expression:t});console.log(r.outputString)}}];function Rn(){let e=process.env.AIKIT_CONFIG_PATH??(m(w(process.cwd(),`aikit.config.json`))?w(process.cwd(),`aikit.config.json`):null);if(!e)return zn();let t=g(e,`utf-8`),n;try{n=JSON.parse(t)}catch{console.error(`Failed to parse ${e} as JSON. Ensure the file contains valid JSON.`),process.exit(1)}let r=b(e);return n.sources=n.sources.map(e=>({...e,path:w(r,e.path)})),n.store.path=w(r,n.store.path),n.curated=n.curated??{path:`curated`},n.curated.path=w(r,n.curated.path),Bn(n,r),n}function zn(){let e=process.env.AIKIT_WORKSPACE_ROOT??process.cwd(),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:_t.model,dimensions:_t.dimensions},store:{backend:`sqlite-vec`,path:w(e,j.data)},curated:{path:w(e,j.aiCurated)},stateDir:w(e,j.state)};return Bn(t,e),t}function Bn(e,t){if(!bt())return;let n=xt(t);e.store.path=w(yt(n.partition)),e.stateDir=w(yt(n.partition),`state`),e.curated||={path:w(t,j.aiCurated)}}async function Vn(){let e=Rn(),t=new wt({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=w(e.store.path,`aikit.db`),r=b(t);if(!m(r)){let{mkdirSync:e}=await import(`node:fs`);e(r,{recursive:!0})}n=await Dt(t)}let r=await Ot({backend:e.store.backend,path:e.store.path,embeddingDim:e.embedding.dimensions,adapter:n??void 0});await r.initialize();let i=new Tt(t,r),{CuratedKnowledgeManager:a}=await import(`../../server/dist/index.js`),o=new a(e.curated.path,r,t),s;try{let t=n?new Et({adapter:n}):new Et({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 Ct().catch(()=>{}),{config:e,embedder:t,store:r,graphStore:s,indexer:i,curated:o,sqliteAdapter:n}}async function Hn(){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=Rn(),s=x(o.stateDir??x(o.sources[0].path,`.aikit-state`),`flows`,`installed`),c=x(vt(),`flows`);h(c,{recursive:!0});let l=x(c,`registry.json`),u=o.sources[0].path,d=x(u,`.flows`);return{loader:new t,registry:new n(l),stateMachine:new r(d,{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(s),getBuiltinFlows:a,cwd:u}}const Un=[e=>x(`skills`,e,`SKILL.md`),e=>x(`skills`,e,`README.md`),e=>x(e,`SKILL.md`),e=>x(e,`README.md`)];function Wn(e,t){for(let n of t.steps){let t=x(e,n.instruction);if(m(t))continue;let r=!1;for(let i of Un){let a=x(e,i(n.id));if(m(a)){let e=b(t);m(e)||h(e,{recursive:!0}),p(a,t),r=!0;break}}r||console.warn(`Warning: instruction file for step "${n.id}" not found.\n Expected: ${n.instruction}\n Searched: ${Un.map(e=>e(n.id)).join(`, `)}`)}}const Gn=[{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 Hn();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=w(t),a=m(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]||y(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(Wn(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.")}}}];let Y=null;async function X(){return Y||=await Vn(),Y}function Kn(){return Y}const qn=[{name:`graph`,description:`Query the knowledge graph`,usage:`aikit graph <action> [options]
|
|
13
|
+
`);let n=await Fn({reset:t,silent:!1});if(console.log(`\nDone: ${n.checked} checked, ${n.fixed} fixed.`),n.issues.length>0){console.log(`
|
|
14
|
+
Issues found:`);for(let e of n.issues)console.log(` - ${e}`)}}}],Ln=[{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)),L(Ie(t,n,e));return}case`stop`:{let t=e.shift()?.trim();t||(console.error(`Usage: aikit proc stop <id>`),process.exit(1));let n=Re(t);if(!n){console.log(`No managed process found: ${t}`);return}L(n);return}case`status`:{let t=e.shift()?.trim();t||(console.error(`Usage: aikit proc status <id>`),process.exit(1));let n=Le(t);if(!n){console.log(`No managed process found: ${t}`);return}L(n);return}case`list`:{let e=Pe();if(e.length===0){console.log(`No managed processes.`);return}for(let t of e)L(t),console.log(``);return}case`logs`:{let t=M(e,`--tail`,50),n=e.shift()?.trim();n||(console.error(`Usage: aikit proc logs <id> [--tail N]`),process.exit(1));let r=Fe(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=ut({path:C(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=dt(t);console.log(n?`Stopped watcher: ${t}`:`Watcher not found: ${t}`);return}case`list`:{let e=lt();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 pe();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=N(e,`--model`,``),n=N(e,`--system`,``),r=M(e,`--temp`,.3),i=N(e,`--context`,``),a=e.join(` `);a||=await F(),a||(console.error(`Usage: aikit delegate [--model name] <prompt>`),process.exit(1));let o;i&&(o=await O(C(i),`utf-8`));let s=await fe({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)`)}}],Rn=[{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=N(e,`--lang`,`js`),n=M(e,`--timeout`,5e3),r=e.join(` `),i=r.trim()?``:await F(),a=r||i;a.trim()||(console.error(`Usage: aikit eval [code] [--lang js|ts] [--timeout ms]`),process.exit(1));let o=ge({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:`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=N(e,`--grep`,``).trim()||void 0,n=N(e,`--cwd`,``).trim()||void 0,r=M(e,`--timeout`,6e4),i=e.filter(Boolean),a=await st({files:i.length>0?i:void 0,grep:t,cwd:n,timeout:r});Ft(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()??``;(!t||!n||!r)&&(console.error(`Usage: aikit rename <old> <new> <path> [--dry-run] [--extensions .ts,.tsx] [--exclude dist/**]`),process.exit(1));let i=I(N(e,`--extensions`,``)),a=I(N(e,`--exclude`,``)),o=await Ye({oldName:t,newName:n,rootPath:C(r),extensions:i.length>0?i:void 0,exclude:a.length>0?a:void 0,dryRun:P(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=N(e,`--rules`,``).trim();(!t||!n)&&(console.error(`Usage: aikit codemod <path> --rules <file.json> [--dry-run] [--extensions .ts,.tsx] [--exclude dist/**]`),process.exit(1));let r=await O(C(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=I(N(e,`--extensions`,``)),o=I(N(e,`--exclude`,``)),s=await le({rootPath:C(t),rules:i,extensions:a.length>0?a:void 0,exclude:o.length>0?o:void 0,dryRun:P(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 F();(!t||!n.trim())&&(console.error(`Usage: cat data.json | aikit transform <expression>`),process.exit(1));let r=de({input:n,expression:t});console.log(r.outputString)}}];var zn=r({initAikit:()=>Hn,loadConfig:()=>Y});function Y(){let e=process.env.AIKIT_CONFIG_PATH??(m(C(process.cwd(),`aikit.config.json`))?C(process.cwd(),`aikit.config.json`):null);if(!e)return Bn();let t=g(e,`utf-8`),n;try{n=JSON.parse(t)}catch{console.error(`Failed to parse ${e} as JSON. Ensure the file contains valid JSON.`),process.exit(1)}let r=y(e);return n.sources=n.sources.map(e=>({...e,path:C(r,e.path)})),n.store.path=C(r,n.store.path),n.curated=n.curated??{path:A.aiCurated},n.curated.path=C(r,n.curated.path),n.onboardDir||=A.aiContext,n.onboardDir=C(r,n.onboardDir),n.stateDir||=A.state,n.stateDir=C(r,n.stateDir),Vn(n,r),n}function Bn(){let e=process.env.AIKIT_WORKSPACE_ROOT??process.cwd(),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:yt.model,dimensions:yt.dimensions},store:{backend:`sqlite-vec`,path:C(e,A.data)},curated:{path:C(e,A.aiCurated)},onboardDir:C(e,A.aiContext),stateDir:C(e,A.state)};return Vn(t,e),t}function Vn(e,t){if(!xt())return;let n=St(t);e.store.path=C(j(n.partition)),e.stateDir=C(j(n.partition),`state`),e.onboardDir=C(j(n.partition),`onboard`),e.curated={path:C(j(n.partition),`curated`)}}async function Hn(){let e=Y(),t=new Tt({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=C(e.store.path,`aikit.db`),r=y(t);if(!m(r)){let{mkdirSync:e}=await import(`node:fs`);e(r,{recursive:!0})}n=await Ot(t)}let r=await kt({backend:e.store.backend,path:e.store.path,embeddingDim:e.embedding.dimensions,adapter:n??void 0});await r.initialize();let i=new Et(t,r),{CuratedKnowledgeManager:a}=await import(`../../server/dist/index.js`),o=new a(e.curated.path,r,t),s;try{let t=n?new Dt({adapter:n}):new Dt({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 wt().catch(()=>{}),{config:e,embedder:t,store:r,graphStore:s,indexer:i,curated:o,sqliteAdapter:n}}async function Un(){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=Y(),s=o.stateDir;if(!s)throw Error(`stateDir not configured`);let c=b(s,`flows`,`installed`),l=b(bt(),`flows`);h(l,{recursive:!0});let u=b(l,`registry.json`),d=o.sources[0].path,f=b(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 Wn=[e=>b(`skills`,e,`SKILL.md`),e=>b(`skills`,e,`README.md`),e=>b(e,`SKILL.md`),e=>b(e,`README.md`)];function Gn(e,t){for(let n of t.steps){let t=b(e,n.instruction);if(m(t))continue;let r=!1;for(let i of Wn){let a=b(e,i(n.id));if(m(a)){let e=y(t);m(e)||h(e,{recursive:!0}),p(a,t),r=!0;break}}r||console.warn(`Warning: instruction file for step "${n.id}" not found.\n Expected: ${n.instruction}\n Searched: ${Wn.map(e=>e(n.id)).join(`, `)}`)}}const Kn=[{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 Un();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=C(t),a=m(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]||v(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(Gn(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.")}}}];let X=null;async function Z(){return X||=await Hn(),X}function qn(){return X}const Jn=[{name:`graph`,description:`Query the knowledge graph`,usage:`aikit graph <action> [options]
|
|
15
15
|
Actions: stats, find-nodes, find-edges, neighbors, traverse, delete, clear
|
|
16
16
|
Options: --type, --name, --node-id, --edge-type, --direction, --depth, --limit, --source-path`,run:async e=>{let t=e.shift()?.trim()??``;t||(console.error(`Usage: aikit graph <action>
|
|
17
|
-
Actions: stats, find-nodes, find-edges, neighbors, traverse, delete, clear`),process.exit(1));let{graphStore:n}=await
|
|
17
|
+
Actions: stats, find-nodes, find-edges, neighbors, traverse, delete, clear`),process.exit(1));let{graphStore:n}=await Z(),r=N(e,`--type`,``),i=N(e,`--name`,``),a=N(e,`--node-id`,``),o=N(e,`--edge-type`,``),s=N(e,`--direction`,`both`),c=M(e,`--depth`,2),l=M(e,`--limit`,50),u=N(e,`--source-path`,``),d={stats:`stats`,"find-nodes":`find_nodes`,"find-edges":`find_edges`,neighbors:`neighbors`,traverse:`traverse`,delete:`delete`,clear:`clear`}[t];d||(console.error(`Unknown graph action: ${t}`),console.error(`Actions: stats, find-nodes, find-edges, neighbors, traverse, delete, clear`),process.exit(1));let f=await Ce(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(`
|
|
18
18
|
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(`
|
|
19
|
-
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}`)}}],Jn=[{name:`remember`,description:`Store curated knowledge`,usage:`aikit remember <title> --category <cat> [--tags tag1,tag2]`,run:async e=>{let t=N(e,`--category`,``).trim(),n=I(N(e,`--tags`,``)),r=e.shift()?.trim()??``,i=await F(),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 X(),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=N(e,`--reason`,``).trim(),n=e.shift()?.trim()??``;(!n||!t)&&(console.error(`Usage: aikit forget <path> --reason <reason>`),process.exit(1));let{curated:r}=await X(),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 X(),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=N(e,`--category`,``).trim()||void 0,n=N(e,`--tag`,``).trim()||void 0,{curated:r}=await X(),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=N(e,`--reason`,``).trim(),n=e.shift()?.trim()??``,r=await F();(!n||!t||!r.trim())&&(console.error(`Usage: aikit update <path> --reason <reason>`),process.exit(1));let{curated:i}=await X(),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=M(e,`--max-chars`,3e3),n=N(e,`--path`,``).trim()||void 0,r=N(e,`--segmentation`,`paragraph`),i=e.join(` `).trim(),a=n?void 0:await F();(!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 X(),s=await ce(o,{text:a,path:n,query:i,maxChars:t,segmentation:r});console.log(`Compressed ${s.originalChars} chars to ${s.compressedChars} chars`),console.log(`Ratio: ${(s.ratio*100).toFixed(1)}% | Segments: ${s.segmentsKept}/${s.segmentsTotal}`),console.log(``),console.log(s.text)}}],Yn=[{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=M(e,`--limit`,5),n=N(e,`--mode`,`hybrid`),r=M(e,`--graph-hops`,0),i=e.join(` `).trim();i||(console.error(`Usage: aikit search <query>`),process.exit(1));let{embedder:a,store:o,graphStore:s}=await X(),c=await a.embedQuery(i),l;if(n===`keyword`)l=await o.ftsSearch(i,{limit:t});else if(n===`semantic`)l=await o.search(c,{limit:t});else{let[e,n]=await Promise.all([o.search(c,{limit:t*2}),o.ftsSearch(i,{limit:t*2}).catch(()=>[])]);l=Wt(e,n).slice(0,t)}if(l.length===0){console.log(`No results found.`);return}for(let{record:e,score:t}of l){console.log(`\n${`─`.repeat(60)}`),console.log(`[${(t*100).toFixed(1)}%] ${e.sourcePath}:${e.startLine}-${e.endLine}`),console.log(` Type: ${e.contentType} | Origin: ${e.origin}`),e.tags.length>0&&console.log(` Tags: ${e.tags.join(`, `)}`),console.log(``);let n=e.content.length>500?`${e.content.slice(0,500)}...`:e.content;console.log(n)}if(console.log(`\n${`─`.repeat(60)}`),console.log(`${l.length} result(s) found.`),r>0&&l.length>0)try{let{graphAugmentSearch:e}=await import(`../../tools/dist/index.js`),t=(await e(s,l.map(e=>({recordId:e.record.id,score:e.score,sourcePath:e.record.sourcePath})),{hops:r,maxPerHit:5})).filter(e=>e.graphContext.nodes.length>0);if(t.length>0){console.log(`\nGraph context (${r} hop${r>1?`s`:``}):\n`);for(let e of t){console.log(` ${e.sourcePath}:`);for(let t of e.graphContext.nodes.slice(0,5))console.log(` → ${t.name} (${t.type})`);for(let t of e.graphContext.edges.slice(0,5))console.log(` → ${t.fromId} --[${t.type}]--> ${t.toId}`)}}}catch(e){console.error(`[graph] augmentation failed: ${e.message}`)}}},{name:`find`,description:`Run federated search across indexed content and files`,usage:`aikit find [query] [--glob <pattern>] [--pattern <regex>] [--limit N]`,run:async e=>{let t=M(e,`--limit`,10),n=N(e,`--glob`,``).trim()||void 0,r=N(e,`--pattern`,``).trim()||void 0,i=e.join(` `).trim()||void 0;!i&&!n&&!r&&(console.error(`Usage: aikit find [query] [--glob <pattern>] [--pattern <regex>] [--limit N]`),process.exit(1));let{embedder:a,store:o}=await X(),s=await ge(a,o,{query:i,glob:n,pattern:r,limit:t});if(s.results.length===0){console.log(`No matches found.`);return}console.log(`Strategies: ${s.strategies.join(`, `)}`),console.log(`Results: ${s.results.length} shown (${s.totalFound} total)`);for(let e of s.results){let t=e.lineRange?`:${e.lineRange.start}-${e.lineRange.end}`:``;console.log(`\n[${e.source}] ${e.path}${t}`),console.log(` Score: ${(e.score*100).toFixed(1)}%`),e.preview&&console.log(` ${e.preview.replace(/\s+/g,` `).trim()}`)}}},{name:`scope-map`,description:`Generate a reading plan for a task`,usage:`aikit scope-map <task> [--max-files N]`,run:async e=>{let t=M(e,`--max-files`,15),n=e.join(` `).trim();n||(console.error(`Usage: aikit scope-map <task> [--max-files N]`),process.exit(1));let{embedder:r,store:i}=await X(),a=await Qe(r,i,{task:n,maxFiles:t});console.log(`Task: ${a.task}`),console.log(`Files: ${a.files.length}`),console.log(`Estimated tokens: ${a.totalEstimatedTokens}`),console.log(``),console.log(`Reading order:`);for(let e of a.readingOrder)console.log(` ${e}`);for(let[e,t]of a.files.entries())console.log(`\n${e+1}. ${t.path}`),console.log(` Relevance: ${(t.relevance*100).toFixed(1)}% | Tokens: ${t.estimatedTokens}`),console.log(` Why: ${t.reason}`),t.focusRanges.length>0&&console.log(` Focus: ${At(t.focusRanges)}`)}},{name:`symbol`,description:`Resolve a symbol definition, imports, and references`,usage:`aikit symbol <name> [--limit N]`,run:async e=>{let t=M(e,`--limit`,20),n=e.join(` `).trim();n||(console.error(`Usage: aikit symbol <name> [--limit N]`),process.exit(1));let{embedder:r,store:i}=await X();Vt(await it(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=N(e,`--direction`,`both`).trim()||`both`,n=M(e,`--max-depth`,3),r=e.join(` `).trim();(!r||![`forward`,`backward`,`both`].includes(t))&&(console.error(`Usage: aikit trace <start> [--direction forward|backward|both] [--max-depth N]`),process.exit(1));let{embedder:i,store:a}=await X();Lt(await ot(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=M(e,`--limit`,5),n=N(e,`--content-type`,``).trim()||void 0,r=e.join(` `).trim();r||(console.error(`Usage: aikit examples <query> [--limit N] [--content-type type]`),process.exit(1));let{embedder:i,store:a}=await X();Rt(await ve(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=M(e,`--limit`,100),{embedder:n,store:r}=await X();zt(await _e(n,r,{limit:t}))}},{name:`lookup`,description:`Look up indexed content by record ID or source path`,usage:`aikit lookup <id>`,run:async e=>{let t=e.join(` `).trim();t||(console.error(`Usage: aikit lookup <id>`),process.exit(1));let{store:n}=await X(),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)}}}],Z=b(E(import.meta.url));function Q(e){let t=e;for(let e=0;e<10;e++){try{let e=x(t,`package.json`);if(m(e)&&JSON.parse(g(e,`utf8`)).name===`@vpxa/aikit`)return t}catch{}let e=b(t);if(e===t)break;t=e}return w(e,`..`,`..`,`..`)}const Xn=[{name:`status`,description:`Show AI Kit index status and statistics`,run:async()=>{let{isUserInstalled:e,getGlobalDataDir:t,computePartitionKey:n,listWorkspaces:r}=await import(`../../core/dist/index.js`),{existsSync:i}=await import(`node:fs`),a=process.cwd(),o=e(),s=i(w(a,`.vscode`,`mcp.json`)),c,l;if(o&&s)c=`workspace (overrides user-level for this workspace)`,l=w(a,`.aikit-data`);else if(o){let e=n(a);c=i(w(a,`AGENTS.md`))?`user (workspace scaffolded)`:`user (workspace not scaffolded)`,l=w(t(),e)}else c=`workspace`,l=w(a,`.aikit-data`);if(console.log(`AI Kit Status`),console.log(`─`.repeat(40)),console.log(` Mode: ${c}`),console.log(` Data: ${l}`),o&&!s){let e=r();console.log(` Registry: ${e.length} workspace(s) enrolled`)}try{let{store:e}=await X(),t=await e.getStats(),n=await e.listSourcePaths();console.log(` Records: ${t.totalRecords}`),console.log(` Files: ${t.totalFiles}`),console.log(` Indexed: ${t.lastIndexedAt??`Never`}`),console.log(` Backend: ${t.storeBackend}`),console.log(` Model: ${t.embeddingModel}`),console.log(``),console.log(`Content Types:`);for(let[e,n]of Object.entries(t.contentTypeBreakdown))console.log(` ${e}: ${n}`);if(n.length>0){console.log(``),console.log(`Files (${n.length} total):`);for(let e of n.slice(0,20))console.log(` ${e}`);n.length>20&&console.log(` ... and ${n.length-20} more`)}}catch{console.log(``),console.log(" Index not available — run `aikit reindex` to index this workspace.")}o&&!s&&!i(w(a,`AGENTS.md`))&&(console.log(``),console.log(" Action: Run `npx @vpxa/aikit init` to add AGENTS.md and copilot-instructions.md"))}},{name:`reindex`,description:`Re-index the AI Kit index from configured sources`,usage:`aikit reindex [--full]`,run:async e=>{let t=e.includes(`--full`),{store:n,indexer:r,curated:i,config:a}=await X();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(`
|
|
20
|
-
`)},s;t?(console.log(`Dropping existing index for full reindex...`),s=await r.reindexAll(a,o)):s=await r.index(a,o),console.log(`Done: ${s.filesProcessed} files, ${s.chunksCreated} chunks in ${(s.durationMs/1e3).toFixed(1)}s`),console.log(`Building FTS index...`),await n.createFtsIndex(),console.log(`Re-indexing curated entries...`);let c=await i.reindexAll();console.log(`Curated: ${c.indexed} entries restored`)}},{name:`serve`,description:`Start the MCP server (stdio or HTTP)`,usage:`aikit serve [--transport stdio|http] [--port N]`,run:async e=>{let t=
|
|
21
|
-
Suggested next steps:`);for(let e of o.next)console.log(` → ${e.tool}: ${e.reason}`)}}else console.error(o.error?.message??`Audit failed`),process.exitCode=1}},{name:`guide`,description:`Tool discovery — recommend AI Kit tools for a given goal`,usage:`aikit guide <goal> [--max N]`,run:async e=>{let t=e.indexOf(`--max`),n=5;t!==-1&&t+1<e.length&&(n=Number.parseInt(e.splice(t,2)[1],10)||5);let r=e.join(` `).trim();r||(console.error(`Usage: aikit guide <goal> [--max N]`),console.error(`Example: aikit guide "audit this project"`),process.exit(1));let i=Se(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=Ye({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}`)}Xe().catch(()=>{})}},{name:`replay-clear`,description:`Clear the replay audit trail`,run:async()=>{Je(),console.log(`Replay log cleared.`)}},{name:`dashboard`,description:`Launch web dashboard for knowledge graph visualization`,usage:`aikit dashboard [--port <port>] [--no-open]`,run:async e=>{let t=e.indexOf(`--port`),n=t!==-1&&e[t+1]?Number.parseInt(e[t+1],10):3210,r=Number.isFinite(n)?n:3210,i=e.includes(`--no-open`);console.log(`Starting AI Kit server on port ${r}...`);let{spawn:a}=await import(`node:child_process`),{platform:o}=await import(`node:os`),s=w(Q(Z),`packages`,`server`,`dist`,`index.js`),c=a(process.execPath,[s,`--transport`,`http`,`--port`,String(r)],{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env,AIKIT_TRANSPORT:`http`,AIKIT_PORT:String(r)}}),l=`http://localhost:${r}/_dashboard/`,u=`http://localhost:${r}/health`,d=!1;for(let e=0;e<30;e+=1){try{if((await fetch(u)).ok){d=!0;break}}catch{}await new Promise(e=>setTimeout(e,1e3))}if(d||(console.error(`Server failed to start within 30 seconds.`),c.kill(),process.exit(1)),console.log(`AI Kit Dashboard: ${l}`),console.log(`Press Ctrl+C to stop.`),!i){let e=o();e===`win32`?a(`cmd`,[`/c`,`start`,``,l],{stdio:`ignore`,detached:!0}).unref():a(e===`darwin`?`open`:`xdg-open`,[l],{stdio:`ignore`,detached:!0}).unref()}let f=()=>{c.kill(),process.exit(0)};process.on(`SIGINT`,f),process.on(`SIGTERM`,f),await new Promise(e=>{c.on(`exit`,()=>e())})}},{name:`settings`,description:`Launch web UI to manage AI Kit configuration and environment variables`,usage:`aikit settings [--port <port>] [--no-open]`,run:async e=>{let t=e.indexOf(`--port`),n=t!==-1&&e[t+1]?Number.parseInt(e[t+1],10):3210,r=Number.isFinite(n)?n:3210,i=e.includes(`--no-open`);console.log(`Starting AI Kit server on port ${r}...`);let{spawn:a}=await import(`node:child_process`),{platform:o}=await import(`node:os`),s=w(Q(Z),`packages`,`server`,`dist`,`index.js`),c=a(process.execPath,[s,`--transport`,`http`,`--port`,String(r)],{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env,AIKIT_TRANSPORT:`http`,AIKIT_PORT:String(r)}}),l=`http://localhost:${r}/settings/`,u=`http://localhost:${r}/health`,d=!1;for(let e=0;e<30;e+=1){try{if((await fetch(u)).ok){d=!0;break}}catch{}await new Promise(e=>setTimeout(e,1e3))}if(d||(console.error(`Server failed to start within 30 seconds.`),c.kill(),process.exit(1)),console.log(`AI Kit Settings: ${l}`),console.log(`Press Ctrl+C to stop.`),!i){let e=o();e===`win32`?a(`cmd`,[`/c`,`start`,``,l],{stdio:`ignore`,detached:!0}).unref():a(e===`darwin`?`open`:`xdg-open`,[l],{stdio:`ignore`,detached:!0}).unref()}let f=()=>{c.kill(),process.exit(0)};process.on(`SIGINT`,f),process.on(`SIGTERM`,f),await new Promise(e=>{c.on(`exit`,()=>e())})}}];function Zn(e){let t=e;for(let e=0;e<10;e++){try{let e=x(t,`package.json`);if(m(e)&&JSON.parse(g(e,`utf8`)).name===`@vpxa/aikit`)return t}catch{}let e=b(t);if(e===t)break;t=e}return w(e,`..`,`..`,`..`)}const Qn=[{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 G({force:!0});let e=process.cwd(),t=m(w(e,`.github`,`.aikit-scaffold.json`)),n=m(w(e,`.github`,`agents`)),r=m(w(e,`.github`,`prompts`)),i=m(w(e,`.claude`,`commands`));if(t||n||r||i){let{initScaffoldOnly:e}=await import(`./init-BWhqiOl_.js`);await e({force:!0})}if(m(w(e,`.github`,`skills`))){let{smartCopySkills:t}=await import(`./scaffold-DwQDdiCJ.js`).then(e=>e.a),n=Zn(b(E(import.meta.url))),r=JSON.parse(g(w(n,`package.json`),`utf-8`)).version;await t(e,n,[...l],r,!0);let{smartCopyFlows:i}=await import(`./scaffold-DwQDdiCJ.js`).then(e=>e.a);await i(e,n,[...u],r,!0)}let{homedir:a}=await import(`node:os`),{rmSync:o}=await import(`node:fs`),s=x(a(),`.aikit`,`cache`,`wasm`);if(m(s))try{o(s,{recursive:!0,force:!0}),console.log(`✓ WASM cache cleared (will re-resolve on next start)`)}catch{console.warn(`⚠ Could not clear WASM cache at`,s)}}}],$n=[{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=I(N(e,`--files`,``)),r=N(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=Ze(i,n,{description:r});console.log(`Saved workset: ${e.name}`),R(e);return}case`get`:{i||(console.error(`Usage: aikit workset get <name>`),process.exit(1));let e=ye(i);if(!e){console.log(`No workset found: ${i}`);return}R(e);return}case`list`:{let e=Ae();if(e.length===0){console.log(`No worksets saved.`);return}console.log(`Worksets (${e.length})`),console.log(`─`.repeat(60));for(let t of e)R(t),console.log(``);return}case`delete`:{i||(console.error(`Usage: aikit workset delete <name>`),process.exit(1));let e=fe(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=ne(i,n);console.log(`Updated workset: ${e.name}`),R(e);return}case`remove`:{(!i||n.length===0)&&(console.error(`Usage: aikit workset remove <name> --files f1,f2`),process.exit(1));let e=Ke(i,n);if(!e){console.log(`No workset found: ${i}`);return}console.log(`Updated workset: ${e.name}`),R(e);return}default:console.error(`Unknown workset action: ${t}`),console.error(`Actions: save, get, list, delete, add, remove`),process.exit(1)}}},{name:`stash`,description:`Persist and retrieve named intermediate values`,usage:`aikit stash <set|get|list|delete|clear> [key] [value]`,run:async e=>{let t=e.shift()?.trim(),n=e.shift()?.trim();switch(t||(console.error(`Usage: aikit stash <set|get|list|delete|clear> [key] [value]`),process.exit(1)),t){case`set`:{n||(console.error(`Usage: aikit stash set <key> <value>`),process.exit(1));let t=e.join(` `),r=t.trim()?``:await F(),i=rt(n,Ht(t||r));console.log(`Stored stash entry: ${i.key}`),console.log(` Type: ${i.type}`),console.log(` Stored: ${i.storedAt}`);return}case`get`:{n||(console.error(`Usage: aikit stash get <key>`),process.exit(1));let e=tt(n);if(!e){console.log(`No stash entry found: ${n}`);return}console.log(JSON.stringify(e,null,2));return}case`list`:{let e=nt();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=et(n);console.log(e?`Deleted stash entry: ${n}`:`No stash entry found: ${n}`);return}case`clear`:{let e=$e();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=De();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=N(e,`--files`,``);t||(console.error(`Usage: aikit lane create <name> --files file1.ts,file2.ts`),process.exit(1));let r=we(n,t.split(`,`).map(e=>e.trim()));console.log(`Lane "${r.name}" created with ${r.sourceFiles.length} files.`);break}case`status`:{let e=ke(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=Te(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=Oe(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=Ee(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=Ue();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=Re(n);console.log(`Queue "${e.name}" created.`);break}case`push`:{let t=Ge(n,e.join(` `)||`Untitled task`);console.log(`Pushed "${t.title}" (${t.id}) to queue "${n}".`);break}case`next`:{let e=We(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=Be(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=Ve(n,t,r);console.log(`Marked "${i.title}" as failed: ${r}`);break}case`get`:{let e=He(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=Le(n);console.log(`Cleared ${e} completed/failed items from queue "${n}".`);break}case`delete`:{let e=ze(n);console.log(e?`Queue "${n}" deleted.`:`Queue "${n}" not found.`);break}}}}],$=[...Yn,...Jn,...kt,...qn,...Xn,...Ln,...Gt,...$n,...In,...Qn,...Gn,...Fn];$.push({name:`help`,description:`Show available commands`,run:async()=>{tr()}});async function er(e){let t=[...e],n=t.shift();if(!n||n===`--help`||n===`-h`){tr();return}if(n===`--version`||n===`-v`){let e=w(b(E(import.meta.url)),`..`,`..`,`..`,`package.json`),t=JSON.parse(g(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}`),tr(),process.exit(1));try{await r.run(t)}finally{let e=Kn();e&&await e.store.close()}}function tr(){console.log(`@vpxa/aikit — Local-first AI developer toolkit
|
|
19
|
+
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}`)}}],Yn=[{name:`remember`,description:`Store curated knowledge`,usage:`aikit remember <title> --category <cat> [--tags tag1,tag2]`,run:async e=>{let t=N(e,`--category`,``).trim(),n=I(N(e,`--tags`,``)),r=e.shift()?.trim()??``,i=await F(),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 Z(),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=N(e,`--reason`,``).trim(),n=e.shift()?.trim()??``;(!n||!t)&&(console.error(`Usage: aikit forget <path> --reason <reason>`),process.exit(1));let{curated:r}=await Z(),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 Z(),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=N(e,`--category`,``).trim()||void 0,n=N(e,`--tag`,``).trim()||void 0,{curated:r}=await Z(),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=N(e,`--reason`,``).trim(),n=e.shift()?.trim()??``,r=await F();(!n||!t||!r.trim())&&(console.error(`Usage: aikit update <path> --reason <reason>`),process.exit(1));let{curated:i}=await Z(),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=M(e,`--max-chars`,3e3),n=N(e,`--path`,``).trim()||void 0,r=N(e,`--segmentation`,`paragraph`),i=e.join(` `).trim(),a=n?void 0:await F();(!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 Z(),s=await ue(o,{text:a,path:n,query:i,maxChars:t,segmentation:r});console.log(`Compressed ${s.originalChars} chars to ${s.compressedChars} chars`),console.log(`Ratio: ${(s.ratio*100).toFixed(1)}% | Segments: ${s.segmentsKept}/${s.segmentsTotal}`),console.log(``),console.log(s.text)}}],Xn=[{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=M(e,`--limit`,5),n=N(e,`--mode`,`hybrid`),r=M(e,`--graph-hops`,0),i=e.join(` `).trim();i||(console.error(`Usage: aikit search <query>`),process.exit(1));let{embedder:a,store:o,graphStore:s}=await Z(),c=await a.embedQuery(i),l;if(n===`keyword`)l=await o.ftsSearch(i,{limit:t});else if(n===`semantic`)l=await o.search(c,{limit:t});else{let[e,n]=await Promise.all([o.search(c,{limit:t*2}),o.ftsSearch(i,{limit:t*2}).catch(()=>[])]);l=Gt(e,n).slice(0,t)}if(l.length===0){console.log(`No results found.`);return}for(let{record:e,score:t}of l){console.log(`\n${`─`.repeat(60)}`),console.log(`[${(t*100).toFixed(1)}%] ${e.sourcePath}:${e.startLine}-${e.endLine}`),console.log(` Type: ${e.contentType} | Origin: ${e.origin}`),e.tags.length>0&&console.log(` Tags: ${e.tags.join(`, `)}`),console.log(``);let n=e.content.length>500?`${e.content.slice(0,500)}...`:e.content;console.log(n)}if(console.log(`\n${`─`.repeat(60)}`),console.log(`${l.length} result(s) found.`),r>0&&l.length>0)try{let{graphAugmentSearch:e}=await import(`../../tools/dist/index.js`),t=(await e(s,l.map(e=>({recordId:e.record.id,score:e.score,sourcePath:e.record.sourcePath})),{hops:r,maxPerHit:5})).filter(e=>e.graphContext.nodes.length>0);if(t.length>0){console.log(`\nGraph context (${r} hop${r>1?`s`:``}):\n`);for(let e of t){console.log(` ${e.sourcePath}:`);for(let t of e.graphContext.nodes.slice(0,5))console.log(` → ${t.name} (${t.type})`);for(let t of e.graphContext.edges.slice(0,5))console.log(` → ${t.fromId} --[${t.type}]--> ${t.toId}`)}}}catch(e){console.error(`[graph] augmentation failed: ${e.message}`)}}},{name:`find`,description:`Run federated search across indexed content and files`,usage:`aikit find [query] [--glob <pattern>] [--pattern <regex>] [--limit N]`,run:async e=>{let t=M(e,`--limit`,10),n=N(e,`--glob`,``).trim()||void 0,r=N(e,`--pattern`,``).trim()||void 0,i=e.join(` `).trim()||void 0;!i&&!n&&!r&&(console.error(`Usage: aikit find [query] [--glob <pattern>] [--pattern <regex>] [--limit N]`),process.exit(1));let{embedder:a,store:o}=await Z(),s=await ve(a,o,{query:i,glob:n,pattern:r,limit:t});if(s.results.length===0){console.log(`No matches found.`);return}console.log(`Strategies: ${s.strategies.join(`, `)}`),console.log(`Results: ${s.results.length} shown (${s.totalFound} total)`);for(let e of s.results){let t=e.lineRange?`:${e.lineRange.start}-${e.lineRange.end}`:``;console.log(`\n[${e.source}] ${e.path}${t}`),console.log(` Score: ${(e.score*100).toFixed(1)}%`),e.preview&&console.log(` ${e.preview.replace(/\s+/g,` `).trim()}`)}}},{name:`scope-map`,description:`Generate a reading plan for a task`,usage:`aikit scope-map <task> [--max-files N]`,run:async e=>{let t=M(e,`--max-files`,15),n=e.join(` `).trim();n||(console.error(`Usage: aikit scope-map <task> [--max-files N]`),process.exit(1));let{embedder:r,store:i}=await Z(),a=await et(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: ${jt(t.focusRanges)}`)}},{name:`symbol`,description:`Resolve a symbol definition, imports, and references`,usage:`aikit symbol <name> [--limit N]`,run:async e=>{let t=M(e,`--limit`,20),n=e.join(` `).trim();n||(console.error(`Usage: aikit symbol <name> [--limit N]`),process.exit(1));let{embedder:r,store:i}=await Z();Ht(await ot(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=N(e,`--direction`,`both`).trim()||`both`,n=M(e,`--max-depth`,3),r=e.join(` `).trim();(!r||![`forward`,`backward`,`both`].includes(t))&&(console.error(`Usage: aikit trace <start> [--direction forward|backward|both] [--max-depth N]`),process.exit(1));let{embedder:i,store:a}=await Z();Rt(await ct(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=M(e,`--limit`,5),n=N(e,`--content-type`,``).trim()||void 0,r=e.join(` `).trim();r||(console.error(`Usage: aikit examples <query> [--limit N] [--content-type type]`),process.exit(1));let{embedder:i,store:a}=await Z();zt(await be(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=M(e,`--limit`,100),{embedder:n,store:r}=await Z();Bt(await ye(n,r,{limit:t}))}},{name:`lookup`,description:`Look up indexed content by record ID or source path`,usage:`aikit lookup <id>`,run:async e=>{let t=e.join(` `).trim();t||(console.error(`Usage: aikit lookup <id>`),process.exit(1));let{store:n}=await Z(),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)}}}],Q=y(T(import.meta.url));function Zn(e){let t=e;for(let e=0;e<10;e++){try{let e=b(t,`package.json`);if(m(e)&&JSON.parse(g(e,`utf8`)).name===`@vpxa/aikit`)return t}catch{}let e=y(t);if(e===t)break;t=e}return C(e,`..`,`..`,`..`)}const Qn=[{name:`status`,description:`Show AI Kit index status and statistics`,run:async()=>{let{isUserInstalled:e,getGlobalDataDir:t,computePartitionKey:n,listWorkspaces:r}=await import(`../../core/dist/index.js`),{existsSync:i}=await import(`node:fs`),a=process.cwd(),o=e(),s=i(C(a,`.vscode`,`mcp.json`)),c,l;if(o&&s)c=`workspace (overrides user-level for this workspace)`,l=C(a,`.aikit-data`);else if(o){let e=n(a);c=i(C(a,`AGENTS.md`))?`user (workspace scaffolded)`:`user (workspace not scaffolded)`,l=C(t(),e)}else c=`workspace`,l=C(a,`.aikit-data`);if(console.log(`AI Kit Status`),console.log(`─`.repeat(40)),console.log(` Mode: ${c}`),console.log(` Data: ${l}`),o&&!s){let e=r();console.log(` Registry: ${e.length} workspace(s) enrolled`)}try{let{store:e}=await Z(),t=await e.getStats(),n=await e.listSourcePaths();console.log(` Records: ${t.totalRecords}`),console.log(` Files: ${t.totalFiles}`),console.log(` Indexed: ${t.lastIndexedAt??`Never`}`),console.log(` Backend: ${t.storeBackend}`),console.log(` Model: ${t.embeddingModel}`),console.log(``),console.log(`Content Types:`);for(let[e,n]of Object.entries(t.contentTypeBreakdown))console.log(` ${e}: ${n}`);if(n.length>0){console.log(``),console.log(`Files (${n.length} total):`);for(let e of n.slice(0,20))console.log(` ${e}`);n.length>20&&console.log(` ... and ${n.length-20} more`)}}catch{console.log(``),console.log(" Index not available — run `aikit reindex` to index this workspace.")}o&&!s&&!i(C(a,`AGENTS.md`))&&(console.log(``),console.log(" Action: Run `npx @vpxa/aikit init` to add AGENTS.md and copilot-instructions.md"))}},{name:`reindex`,description:`Re-index the AI Kit index from configured sources`,usage:`aikit reindex [--full]`,run:async e=>{let t=e.includes(`--full`),{store:n,indexer:r,curated:i,config:a}=await Z();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(`
|
|
20
|
+
`)},s;t?(console.log(`Dropping existing index for full reindex...`),s=await r.reindexAll(a,o)):s=await r.index(a,o),console.log(`Done: ${s.filesProcessed} files, ${s.chunksCreated} chunks in ${(s.durationMs/1e3).toFixed(1)}s`),console.log(`Building FTS index...`),await n.createFtsIndex(),console.log(`Re-indexing curated entries...`);let c=await i.reindexAll();console.log(`Curated: ${c.indexed} entries restored`)}},{name:`serve`,description:`Start the MCP server (stdio or HTTP)`,usage:`aikit serve [--transport stdio|http] [--port N]`,run:async e=>{let t=C(Zn(Q),`packages`,`server`,`dist`,`index.js`),n=N(e,`--transport`,`stdio`),r=N(e,`--port`,`3210`);try{await Fn({silent:!0})}catch{}let i=vt(t,[],{stdio:n===`stdio`?[`pipe`,`pipe`,`inherit`,`ipc`]:`inherit`,env:{...process.env,AIKIT_TRANSPORT:n,AIKIT_PORT:r}});n===`stdio`&&i.stdin&&i.stdout&&(process.stdin.pipe(i.stdin),i.stdout.pipe(process.stdout)),i.on(`exit`,e=>process.exit(e??0)),process.on(`SIGINT`,()=>i.kill(`SIGINT`)),process.on(`SIGTERM`,()=>i.kill(`SIGTERM`)),await new Promise(()=>{})}},{name:`init`,description:`Initialize AI Kit in the current directory`,usage:`aikit init [--workspace] [--smart] [--force] [--guide]`,run:async e=>{let t=e.includes(`--user`),n=e.includes(`--workspace`),r=e.includes(`--smart`),i=e.includes(`--guide`),a=e.includes(`--force`);if(t&&n&&(console.error(`Cannot use --user and --workspace together.`),process.exit(1)),i){let{guideProject:e}=await import(`./init-BVU1RVy5.js`);await e();return}if(r){let{initSmart:e}=await import(`./init-BVU1RVy5.js`);await e({force:a})}else if(t)await G({force:a});else if(n){let{initProject:e}=await import(`./init-BVU1RVy5.js`);await e({force:a})}else await G({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=N(e,`--cwd`,``).trim()||void 0,n=N(e,`--files`,``),r=N(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 ie({cwd:t,files:i.length>0?i:void 0,skipTypes:a,skipLint:o,detail:r});Nt(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=Te(e.shift());console.log(`Project Health: ${t.path}`),console.log(`─`.repeat(50));for(let e of t.checks){let t=e.status===`pass`?`+`:e.status===`warn`?`~`:`X`;console.log(` [${t}] ${e.name}: ${e.message}`)}console.log(`─`.repeat(50)),console.log(`Score: ${t.score}% — ${t.summary}`)}},{name:`audit`,description:`Run a unified project audit (structure, deps, patterns, health, dead symbols, check)`,usage:`aikit audit [path] [--checks structure,dependencies,patterns,health,dead_symbols,check,entry_points] [--detail efficient|normal|full]`,run:async e=>{let{store:t,embedder:n}=await Z(),r=N(e,`--detail`,`efficient`)||`efficient`,i=N(e,`--checks`,``),a=i?i.split(`,`).map(e=>e.trim()):void 0,o=await D(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(`
|
|
21
|
+
Suggested next steps:`);for(let e of o.next)console.log(` → ${e.tool}: ${e.reason}`)}}else console.error(o.error?.message??`Audit failed`),process.exitCode=1}},{name:`guide`,description:`Tool discovery — recommend AI Kit tools for a given goal`,usage:`aikit guide <goal> [--max N]`,run:async e=>{let t=e.indexOf(`--max`),n=5;t!==-1&&t+1<e.length&&(n=Number.parseInt(e.splice(t,2)[1],10)||5);let r=e.join(` `).trim();r||(console.error(`Usage: aikit guide <goal> [--max N]`),console.error(`Example: aikit guide "audit this project"`),process.exit(1));let i=we(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=Ze({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}`)}Qe().catch(()=>{})}},{name:`replay-clear`,description:`Clear the replay audit trail`,run:async()=>{Xe(),console.log(`Replay log cleared.`)}},{name:`dashboard`,description:`Launch web dashboard for knowledge graph visualization`,usage:`aikit dashboard [--port <port>] [--no-open]`,run:async e=>{let t=e.indexOf(`--port`),n=t!==-1&&e[t+1]?Number.parseInt(e[t+1],10):3210,r=Number.isFinite(n)?n:3210,i=e.includes(`--no-open`);console.log(`Starting AI Kit server on port ${r}...`);let{spawn:a}=await import(`node:child_process`),{platform:o}=await import(`node:os`),s=C(Zn(Q),`packages`,`server`,`dist`,`index.js`),c=a(process.execPath,[s,`--transport`,`http`,`--port`,String(r)],{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env,AIKIT_TRANSPORT:`http`,AIKIT_PORT:String(r)}}),l=`http://localhost:${r}/_dashboard/`,u=`http://localhost:${r}/health`,d=!1;for(let e=0;e<30;e+=1){try{if((await fetch(u)).ok){d=!0;break}}catch{}await new Promise(e=>setTimeout(e,1e3))}if(d||(console.error(`Server failed to start within 30 seconds.`),c.kill(),process.exit(1)),console.log(`AI Kit Dashboard: ${l}`),console.log(`Press Ctrl+C to stop.`),!i){let e=o();e===`win32`?a(`cmd`,[`/c`,`start`,``,l],{stdio:`ignore`,detached:!0}).unref():a(e===`darwin`?`open`:`xdg-open`,[l],{stdio:`ignore`,detached:!0}).unref()}let f=()=>{c.kill(),process.exit(0)};process.on(`SIGINT`,f),process.on(`SIGTERM`,f),await new Promise(e=>{c.on(`exit`,()=>e())})}},{name:`settings`,description:`Launch web UI to manage AI Kit configuration and environment variables`,usage:`aikit settings [--port <port>] [--no-open]`,run:async e=>{let t=e.indexOf(`--port`),n=t!==-1&&e[t+1]?Number.parseInt(e[t+1],10):3210,r=Number.isFinite(n)?n:3210,i=e.includes(`--no-open`);console.log(`Starting AI Kit server on port ${r}...`);let{spawn:a}=await import(`node:child_process`),{platform:o}=await import(`node:os`),s=C(Zn(Q),`packages`,`server`,`dist`,`index.js`),c=a(process.execPath,[s,`--transport`,`http`,`--port`,String(r)],{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env,AIKIT_TRANSPORT:`http`,AIKIT_PORT:String(r)}}),l=`http://localhost:${r}/settings/`,u=`http://localhost:${r}/health`,d=!1;for(let e=0;e<30;e+=1){try{if((await fetch(u)).ok){d=!0;break}}catch{}await new Promise(e=>setTimeout(e,1e3))}if(d||(console.error(`Server failed to start within 30 seconds.`),c.kill(),process.exit(1)),console.log(`AI Kit Settings: ${l}`),console.log(`Press Ctrl+C to stop.`),!i){let e=o();e===`win32`?a(`cmd`,[`/c`,`start`,``,l],{stdio:`ignore`,detached:!0}).unref():a(e===`darwin`?`open`:`xdg-open`,[l],{stdio:`ignore`,detached:!0}).unref()}let f=()=>{c.kill(),process.exit(0)};process.on(`SIGINT`,f),process.on(`SIGTERM`,f),await new Promise(e=>{c.on(`exit`,()=>e())})}}];function $n(e){let t=e;for(let e=0;e<10;e++){try{let e=b(t,`package.json`);if(m(e)&&JSON.parse(g(e,`utf8`)).name===`@vpxa/aikit`)return t}catch{}let e=y(t);if(e===t)break;t=e}return C(e,`..`,`..`,`..`)}const er=[{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 G({force:!0});let e=process.cwd(),t=m(C(e,`.github`,`.aikit-scaffold.json`)),n=m(C(e,`.github`,`agents`)),r=m(C(e,`.github`,`prompts`)),i=m(C(e,`.claude`,`commands`));if(t||n||r||i){let{initScaffoldOnly:e}=await import(`./init-BVU1RVy5.js`);await e({force:!0})}if(m(C(e,`.github`,`skills`))){let{smartCopySkills:t}=await import(`./scaffold-BB6OrTuA.js`).then(e=>e.a),n=$n(y(T(import.meta.url))),r=JSON.parse(g(C(n,`package.json`),`utf-8`)).version;await t(e,n,[...u],r,!0);let{smartCopyFlows:i}=await import(`./scaffold-BB6OrTuA.js`).then(e=>e.a);await i(e,n,[...d],r,!0)}let{homedir:a}=await import(`node:os`),{rmSync:o}=await import(`node:fs`),s=b(a(),`.aikit`,`cache`,`wasm`);if(m(s))try{o(s,{recursive:!0,force:!0}),console.log(`✓ WASM cache cleared (will re-resolve on next start)`)}catch{console.warn(`⚠ Could not clear WASM cache at`,s)}}}],tr=[{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=I(N(e,`--files`,``)),r=N(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=$e(i,n,{description:r});console.log(`Saved workset: ${e.name}`),R(e);return}case`get`:{i||(console.error(`Usage: aikit workset get <name>`),process.exit(1));let e=xe(i);if(!e){console.log(`No workset found: ${i}`);return}R(e);return}case`list`:{let e=Me();if(e.length===0){console.log(`No worksets saved.`);return}console.log(`Worksets (${e.length})`),console.log(`─`.repeat(60));for(let t of e)R(t),console.log(``);return}case`delete`:{i||(console.error(`Usage: aikit workset delete <name>`),process.exit(1));let e=me(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=E(i,n);console.log(`Updated workset: ${e.name}`),R(e);return}case`remove`:{(!i||n.length===0)&&(console.error(`Usage: aikit workset remove <name> --files f1,f2`),process.exit(1));let e=Je(i,n);if(!e){console.log(`No workset found: ${i}`);return}console.log(`Updated workset: ${e.name}`),R(e);return}default:console.error(`Unknown workset action: ${t}`),console.error(`Actions: save, get, list, delete, add, remove`),process.exit(1)}}},{name:`stash`,description:`Persist and retrieve named intermediate values`,usage:`aikit stash <set|get|list|delete|clear> [key] [value]`,run:async e=>{let t=e.shift()?.trim(),n=e.shift()?.trim();switch(t||(console.error(`Usage: aikit stash <set|get|list|delete|clear> [key] [value]`),process.exit(1)),t){case`set`:{n||(console.error(`Usage: aikit stash set <key> <value>`),process.exit(1));let t=e.join(` `),r=t.trim()?``:await F(),i=at(n,Ut(t||r));console.log(`Stored stash entry: ${i.key}`),console.log(` Type: ${i.type}`),console.log(` Stored: ${i.storedAt}`);return}case`get`:{n||(console.error(`Usage: aikit stash get <key>`),process.exit(1));let e=rt(n);if(!e){console.log(`No stash entry found: ${n}`);return}console.log(JSON.stringify(e,null,2));return}case`list`:{let e=it();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=nt(n);console.log(e?`Deleted stash entry: ${n}`:`No stash entry found: ${n}`);return}case`clear`:{let e=tt();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=ke();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=N(e,`--files`,``);t||(console.error(`Usage: aikit lane create <name> --files file1.ts,file2.ts`),process.exit(1));let r=Ee(n,t.split(`,`).map(e=>e.trim()));console.log(`Lane "${r.name}" created with ${r.sourceFiles.length} files.`);break}case`status`:{let e=je(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=De(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=Ae(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=Oe(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=Ge();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=Be(n);console.log(`Queue "${e.name}" created.`);break}case`push`:{let t=qe(n,e.join(` `)||`Untitled task`);console.log(`Pushed "${t.title}" (${t.id}) to queue "${n}".`);break}case`next`:{let e=Ke(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=He(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=Ue(n,t,r);console.log(`Marked "${i.title}" as failed: ${r}`);break}case`get`:{let e=We(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=ze(n);console.log(`Cleared ${e} completed/failed items from queue "${n}".`);break}case`delete`:{let e=Ve(n);console.log(e?`Queue "${n}" deleted.`:`Queue "${n}" not found.`);break}}}}],$=[...Xn,...Yn,...At,...Jn,...Qn,...Rn,...Kt,...tr,...Ln,...er,...Kn,...In];$.push({name:`help`,description:`Show available commands`,run:async()=>{rr()}});async function nr(e){let t=[...e],n=t.shift();if(!n||n===`--help`||n===`-h`){rr();return}if(n===`--version`||n===`-v`){let e=C(y(T(import.meta.url)),`..`,`..`,`..`,`package.json`),t=JSON.parse(g(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}`),rr(),process.exit(1));try{await r.run(t)}finally{let e=qn();e&&await e.store.close()}}function rr(){console.log(`@vpxa/aikit — Local-first AI developer toolkit
|
|
22
22
|
`),console.log(`Usage: aikit <command> [options]
|
|
23
|
-
`),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{
|
|
23
|
+
`),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{nr 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-
|
|
1
|
+
import{c as e,l as t,n,o as r,r as i,t as a}from"./scaffold-BB6OrTuA.js";import{a as o,i as s,n as c,o as l,r as u,t as d}from"./templates-D-eA4QVK.js";import{appendFileSync as f,existsSync as p,mkdirSync as m,readFileSync as h,unlinkSync as g,writeFileSync as _}from"node:fs";import{basename as v,dirname as y,join as b,resolve as x}from"node:path";import{fileURLToPath as S}from"node:url";import{AIKIT_PATHS as C,EMBEDDING_DEFAULTS as w,isUserInstalled as T}from"../../core/dist/index.js";function E(e){return p(x(e,`.cursor`))?`cursor`:p(x(e,`.claude`))?`claude-code`:p(x(e,`.windsurf`))?`windsurf`:p(x(e,`.zed`))?`zed`:p(x(e,`.idea`))?`intellij`:`copilot`}function D(e){let t=[];return p(x(e,`.cursor`))&&t.push(`cursor`),(p(x(e,`.claude`))||p(x(e,`CLAUDE.md`)))&&t.push(`claude-code`),p(x(e,`.windsurf`))&&t.push(`windsurf`),p(x(e,`.zed`))&&t.push(`zed`),p(x(e,`.idea`))&&t.push(`intellij`),p(x(e,`.gemini`))&&t.push(`gemini-cli`),(p(x(e,`.codex`))||p(x(e,`codex.md`)))&&t.push(`codex-cli`),t.push(`copilot`),[...new Set(t)]}function O(e){return{servers:{[e]:{...s}}}}function k(e){let{type:t,...n}=s;return{mcpServers:{[e]:n}}}function A(e){let{type:t,...n}=s;return{context_servers:{[e]:{...n}}}}const j={scaffoldDir:`general`,writeMcpConfig(e,t){let n=x(e,`.vscode`),r=x(n,`mcp.json`);p(r)||(m(n,{recursive:!0}),_(r,`${JSON.stringify(O(t),null,2)}\n`,`utf-8`),console.log(` Created .vscode/mcp.json`))},writeInstructions(e,t){let n=x(e,`.github`),r=x(n,`copilot-instructions.md`);m(n,{recursive:!0}),_(r,c(v(e),t),`utf-8`),console.log(` Updated .github/copilot-instructions.md`)},writeAgentsMd(e,t){_(x(e,`AGENTS.md`),d(v(e),t),`utf-8`),console.log(` Updated AGENTS.md`)}},M={scaffoldDir:`general`,writeMcpConfig(e,t){let n=x(e,`.mcp.json`);p(n)||(_(n,`${JSON.stringify(k(t),null,2)}\n`,`utf-8`),console.log(` Created .mcp.json`))},writeInstructions(e,t){let n=x(e,`CLAUDE.md`),r=v(e);_(n,`${c(r,t)}\n---\n\n${d(r,t)}`,`utf-8`),console.log(` Updated CLAUDE.md`)},writeAgentsMd(e,t){}},N={scaffoldDir:`general`,writeMcpConfig(e,t){let n=x(e,`.cursor`),r=x(n,`mcp.json`);p(r)||(m(n,{recursive:!0}),_(r,`${JSON.stringify(k(t),null,2)}\n`,`utf-8`),console.log(` Created .cursor/mcp.json`))},writeInstructions(e,t){let n=x(e,`.cursor`,`rules`),r=x(n,`aikit.mdc`);m(n,{recursive:!0});let i=v(e);_(r,`${c(i,t)}\n---\n\n${d(i,t)}`,`utf-8`),console.log(` Updated .cursor/rules/aikit.mdc`);let a=x(n,`kb.mdc`);p(a)&&a!==r&&(g(a),console.log(` Removed legacy .cursor/rules/kb.mdc`))},writeAgentsMd(e,t){}},P={scaffoldDir:`general`,writeMcpConfig(e,t){let n=x(e,`.vscode`),r=x(n,`mcp.json`);p(r)||(m(n,{recursive:!0}),_(r,`${JSON.stringify(O(t),null,2)}\n`,`utf-8`),console.log(` Created .vscode/mcp.json (Windsurf-compatible)`))},writeInstructions(e,t){let n=x(e,`.windsurfrules`),r=v(e);_(n,`${c(r,t)}\n---\n\n${d(r,t)}`,`utf-8`),console.log(` Updated .windsurfrules`)},writeAgentsMd(e,t){}},F={scaffoldDir:`general`,writeMcpConfig(e,t){let n=x(e,`.zed`),r=x(n,`settings.json`);if(m(n,{recursive:!0}),!p(r))_(r,`${JSON.stringify(A(t),null,2)}\n`,`utf-8`),console.log(` Created .zed/settings.json`);else{let e;try{e=JSON.parse(h(r,`utf-8`))}catch{console.warn(` ⚠ .zed/settings.json contains invalid JSON — skipping MCP config merge`);return}e.context_servers?.[t]||(e.context_servers={...e.context_servers,...A(t).context_servers},_(r,`${JSON.stringify(e,null,2)}\n`,`utf-8`),console.log(` Updated .zed/settings.json with context_servers`))}},writeInstructions(e,t){let n=x(e,`.rules`),r=v(e);_(n,`${c(r,t)}\n---\n\n${d(r,t)}`,`utf-8`),console.log(` Updated .rules`)},writeAgentsMd(e,t){}},I={scaffoldDir:`general`,writeMcpConfig(e,t){let n=x(e,`mcp.json`);p(n)||(_(n,`${JSON.stringify(k(t),null,2)}\n`,`utf-8`),console.log(` Created mcp.json`))},writeInstructions(e,t){let n=x(e,`.aiassistant`,`rules`),r=x(n,`aikit.md`);m(n,{recursive:!0});let i=v(e);_(r,`${c(i,t)}\n---\n\n${d(i,t)}`,`utf-8`),console.log(` Updated .aiassistant/rules/aikit.md`)},writeAgentsMd(e,t){}};function L(e){switch(e){case`copilot`:return j;case`claude-code`:return M;case`cursor`:return N;case`windsurf`:return P;case`zed`:return F;case`intellij`:return I;case`gemini-cli`:case`codex-cli`:return j}}const R={serverName:o,sources:[{path:`.`,excludePatterns:[`**/node_modules/**`,`**/dist/**`,`**/build/**`,`**/.git/**`,`**/${C.data}/**`,`**/coverage/**`,`**/*.min.js`,`**/package-lock.json`,`**/pnpm-lock.yaml`]}],indexing:{chunkSize:1500,chunkOverlap:200,minChunkSize:100},embedding:{model:w.model,dimensions:w.dimensions},store:{backend:`sqlite-vec`,path:C.data},curated:{path:C.aiCurated}};function z(e,t){let n=x(e,`aikit.config.json`);return p(n)&&!t?(console.log(`aikit.config.json already exists. Use --force to overwrite.`),!1):(_(n,`${JSON.stringify(R,null,2)}\n`,`utf-8`),console.log(` Created aikit.config.json`),!0)}function B(e){let t=x(e,`.gitignore`),n=[{dir:`${C.data}/`,label:`AI Kit vector store`},{dir:`${C.state}/`,label:`AI Kit session state`},{dir:`${C.restorePoints}/`,label:`Restore points (codemod/rename undo snapshots)`},{dir:`${C.brainstorm}/`,label:`Brainstorming sessions`},{dir:`${C.handoffs}/`,label:`Handoff documents`}];if(p(t)){let e=h(t,`utf-8`),r=n.filter(t=>!e.includes(t.dir));r.length>0&&(f(t,`\n${r.map(e=>`# ${e.label}\n${e.dir}`).join(`
|
|
2
2
|
`)}\n`,`utf-8`),console.log(` Added ${r.map(e=>e.dir).join(`, `)} to .gitignore`))}else _(t,`${n.map(e=>`# ${e.label}\n${e.dir}`).join(`
|
|
3
3
|
`)}\n`,`utf-8`),console.log(` Created .gitignore with AI Kit entries`)}function V(){return R.serverName}const H=[`decisions`,`patterns`,`conventions`,`troubleshooting`];function U(e){let t=x(e,`.ai`,`curated`);p(t)||(m(t,{recursive:!0}),console.log(` Created .ai/curated/`));for(let e of H){let n=x(t,e);p(n)||m(n,{recursive:!0})}console.log(` Created .ai/curated/{${H.join(`,`)}}/`)}function W(e){switch(e){case`zed`:return`zed`;case`intellij`:return`intellij`;case`claude-code`:return`claude-code`;case`gemini-cli`:return`gemini`;case`codex-cli`:return`codex`;default:return`copilot`}}function G(e){let t=e;for(let e=0;e<10;e++){try{let e=b(t,`package.json`);if(p(e)&&JSON.parse(h(e,`utf8`)).name===`@vpxa/aikit`)return t}catch{}let e=y(t);if(e===t)break;t=e}return x(e,`..`,`..`,`..`)}async function K(n){let i=process.cwd();if(!z(i,n.force))return;B(i);let a=V(),o=L(E(i));o.writeMcpConfig(i,a),o.writeInstructions(i,a),o.writeAgentsMd(i,a);let s=G(y(S(import.meta.url))),c=JSON.parse(h(x(s,`package.json`),`utf-8`)).version;await t(i,s,[...l],c,n.force),await r(i,s,[...u],c,n.force);let d=D(i),f=new Set;for(let t of d){let r=W(t);f.has(r)||(f.add(r),await e(i,s,r,c,n.force))}U(i),console.log(`
|
|
4
4
|
AI Kit initialized! Next steps:`),console.log(` aikit reindex Index your codebase`),console.log(` aikit search Search indexed content`),console.log(` aikit serve Start MCP server for IDE integration`),T()&&console.log(`
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import{existsSync as e,mkdirSync as t,readFileSync as n,rmSync as r,unlinkSync as i,writeFileSync as a}from"node:fs";import{dirname as o,resolve as s}from"node:path";import{pathToFileURL as c}from"node:url";import{createHash as l}from"node:crypto";var u=Object.defineProperty,d=(e,t)=>{let n={};for(var r in e)u(n,r,{get:e[r],enumerable:!0});return t||u(n,Symbol.toStringTag,{value:`Module`}),n};const f=[`inputs`,`outputs`,`requires`,`relatedSkills`],p=[`model`],m=[`category`,`domain`,`applicability`],h=new Set([`__proto__`,`constructor`,`prototype`]);function g(e,t){return e.metadata[t]??e.fields[t]}function _(e,t){let n=g(e,t);return n?y(n):[]}function v(e){let t=Object.create(null),n=Object.create(null),r=[],i=e,a=e.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);if(!a)return{fields:t,metadata:n,tools:r,body:i};let o=a[1];i=a[2];let s=!1;for(let e of o.split(/\r?\n/)){if(s){if(e.trim()===``)continue;let t=e.match(/^\s{2,}(\S+?):\s*(.*)$/);if(t){let[,e,r]=t;if(h.has(e))continue;n[e]=r;continue}s=!1}let i=e.match(/^(\S+?):\s*(.*)$/);if(!i)continue;let[,a,o]=i;if(a===`metadata`&&o.trim()===``){s=!0;continue}h.has(a)||(t[a]=o,a===`tools`&&(r=y(o)))}return{fields:t,metadata:n,tools:r,body:i}}function y(e){let t=e.trim();if(!t.startsWith(`[`)||!t.endsWith(`]`))return[];let n=t.slice(1,-1).trim();return n?n.split(`,`).map(e=>e.trim()).filter(Boolean):[]}function b(e){return`[${e.join(`, `)}]`}function x(e,t){let n=v(e),r=v(t),i={...n.fields},a={...n.metadata};for(let[e,t]of Object.entries(r.metadata))e in a||(a[e]=t);for(let e of p)r.fields[e]&&(i[e]=r.fields[e]);for(let e of m){let t=g(r,e);t&&(a[e]=t)}for(let e of[...m,...f])delete i[e];delete i.metadata;let o=n.tools,s=r.tools,c=new Set(o),l=s.filter(e=>!c.has(e)),u=[...o,...l];u.length>0&&(i.tools=b(u));for(let e of f){let t=_(n,e),i=_(r,e),o=new Set(t),s=i.filter(e=>!o.has(e)),c=[...t,...s];c.length>0?a[e]=b(c):delete a[e]}let d=[`---`],h=[`name`,`description`,`argument-hint`,`tools`,`model`],y=[`category`,`domain`,`applicability`,`inputs`,`outputs`,`requires`,`relatedSkills`],x=new Set;for(let e of h)e in i&&(d.push(`${e}: ${i[e]}`),x.add(e));for(let[e,t]of Object.entries(i))x.has(e)||d.push(`${e}: ${t}`);let S=[],C=new Set;for(let e of y){let t=a[e];t&&(S.push(` ${e}: ${t}`),C.add(e))}for(let[e,t]of Object.entries(a))!C.has(e)&&t&&S.push(` ${e}: ${t}`);return S.length>0&&(d.push(`metadata:`),d.push(...S)),d.push(`---`),`${d.join(`
|
|
2
|
-
`)}\n${n.body}`}function S(e){return l(`sha256`).update(e).digest(`hex`).slice(0,16)}function C(t){if(!e(t))return null;try{let e=n(t,`utf-8`),r=JSON.parse(e);return!r.version||!r.files?null:r}catch{return null}}function w(e,t){a(e,`${JSON.stringify(t,null,2)}\n`,`utf-8`)}function T(e){return e.endsWith(`.agent.md`)&&!e.startsWith(`_shared/`)&&!e.startsWith(`agents/_shared/`)&&!e.startsWith(`templates/`)||e.endsWith(`SKILL.md`)&&!e.startsWith(`_shared/`)&&!e.startsWith(`templates/`)?`merge-frontmatter`:`overwrite`}function E(e,t,n){if(!e)return`new`;let r=e.files[t];return r?r.sourceHash===S(n)?`current`:`outdated`:`new`}function D(e,t,n,r){e.files[t]={sourceHash:S(n),strategy:r??T(t),updatedAt:new Date().toISOString()}}function O(e){return{version:e,generatedAt:new Date().toISOString(),files:{}}}var k=d({guideFlows:()=>R,guideScaffold:()=>F,guideSkills:()=>I,loadAdapter:()=>A,smartCopyFlows:()=>L,smartCopyFromMemory:()=>j,smartCopyScaffold:()=>N,smartCopySkills:()=>P});async function A(e,t){let n=await import(c(s(e,`scaffold`,`dist`,`adapters`,`${t}.mjs`)).href),r=n[`generate${t.split(`-`).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(``)}`]??n.generate??n.default;if(typeof r!=`function`)throw Error(`Adapter ${t} does not export a generate function`);return r()}function j(r,i,c,l,u=!1){t(i,{recursive:!0});for(let d of r){let r=l?`${l}/${d.path}`:d.path,f=s(i,d.path);if(u){t(o(f),{recursive:!0}),a(f,d.content,`utf-8`),D(c,r,d.content);continue}let p=E(c,r,d.content);if(p!==`current`){if(p===`new`&&!e(f)){t(o(f),{recursive:!0}),a(f,d.content,`utf-8`),D(c,r,d.content);continue}if(p===`new`&&e(f)){D(c,r,d.content);continue}if(T(r)===`merge-frontmatter`&&e(f)){let e=n(f,`utf-8`);a(f,x(d.content,e),`utf-8`)}else t(o(f),{recursive:!0}),a(f,d.content,`utf-8`);D(c,r,d.content)}}u&&M(i,c,l,new Set(r.map(e=>l?`${l}/${e.path}`:e.path)))}function M(t,n,r,a){let o=[];for(let c of Object.keys(n.files)){if(!c.startsWith(`${r}/`)||a.has(c))continue;let l=s(t,c.slice(r.length+1));e(l)&&(i(l),o.push(c)),delete n.files[c]}return o}async function N(e,t,n=`copilot`,r,i=!1){let a=await A(t,n),o=a.some(e=>e.path.startsWith(`.`)),c=o?e:s(e,`.github`),l=s(c,`.aikit-scaffold.json`),u=C(l)??O(r);u.version=r;let d=new Map;for(let e of a){let t=e.path.indexOf(`/`);if(t===-1){let t=d.get(``)??[];t.push({path:e.path,content:e.content}),d.set(``,t);continue}let n=e.path.substring(0,t),r=e.path.substring(t+1),i=d.get(n)??[];i.push({path:r,content:e.content}),d.set(n,i)}for(let[e,t]of d)j(t,e?s(c,e):c,u,o?`${n}/${e||`.`}`:e||`.`,i);w(l,u)}async function P(e,t,n,r,i=!1){let a=s(e,`.github`),o=s(a,`.aikit-scaffold.json`),c=C(o)??O(r);c.version=r;let l=await A(t,`skills`),u=new Map;for(let e of l){let t=e.path.indexOf(`/`);if(t===-1)continue;let n=e.path.substring(0,t),r=e.path.substring(t+1),i=u.get(n)??[];i.push({path:r,content:e.content}),u.set(n,i)}for(let[e,t]of u)j(t,s(a,`skills`,e),c,`skills/${e}`,i);w(o,c)}async function F(t,r,i=`copilot`){let a=[],o=await A(r,i),c=o.some(e=>e.path.startsWith(`.`))?t:s(t,`.github`);for(let t of o){let r=s(c,t.path);if(!e(r))a.push({status:`new`,relativePath:t.path,sourcePath:``,content:t.content});else{let e=n(r,`utf-8`);t.content===e?a.push({status:`current`,relativePath:t.path,sourcePath:``}):a.push({status:`outdated`,relativePath:t.path,sourcePath:``,content:t.content})}}return a}async function I(t,r,i){let a=[],o=await A(r,`skills`),c=s(t,`.github`);for(let t of o){let r=`skills/${t.path}`,i=s(c,`skills`,t.path);if(!e(i))a.push({status:`new`,relativePath:r,sourcePath:``,content:t.content});else{let e=n(i,`utf-8`);t.content===e?a.push({status:`current`,relativePath:r,sourcePath:``}):a.push({status:`outdated`,relativePath:r,sourcePath:``,content:t.content})}}return a}async function L(t,n,i,a,o=!1){let c=s(t,`.github`),l=s(c,`.aikit-scaffold.json`),u=C(l)??O(a);u.version=a;let d=await A(n,`flows`),f=new Set,p=new Map;for(let e of d){let t=e.path.indexOf(`/`);if(t===-1)continue;let n=e.path.substring(0,t);f.add(n);let r=e.path.substring(t+1),i=p.get(n)??[];i.push({path:r,content:e.content}),p.set(n,i)}for(let t of f){let n=s(c,`flows`,t,`skills`);e(n)&&r(n,{recursive:!0,force:!0})}for(let[e,t]of p)j(t,s(c,`flows`,e),u,`flows/${e}`,o);w(l,u)}async function R(t,r,i){let a=[],o=await A(r,`flows`),c=s(t,`.github`);for(let t of o){let r=`flows/${t.path}`,i=s(c,`flows`,t.path);if(!e(i))a.push({status:`new`,relativePath:r,sourcePath:``,content:t.content});else{let e=n(i,`utf-8`);t.content===e?a.push({status:`current`,relativePath:r,sourcePath:``}):a.push({status:`outdated`,relativePath:r,sourcePath:``,content:t.content})}}return a}export{k as a,N as c,C as d,w as f,A as i,P as l,F as n,L as o,v as p,I as r,j as s,R as t,O as u};
|
|
2
|
+
`)}\n${n.body}`}function S(e){return l(`sha256`).update(e).digest(`hex`).slice(0,16)}function C(t){if(!e(t))return null;try{let e=n(t,`utf-8`),r=JSON.parse(e);return!r.version||!r.files?null:r}catch{return null}}function w(e,t){a(e,`${JSON.stringify(t,null,2)}\n`,`utf-8`)}function T(e){return e.endsWith(`.agent.md`)&&!e.startsWith(`_shared/`)&&!e.startsWith(`agents/_shared/`)&&!e.startsWith(`templates/`)||e.endsWith(`SKILL.md`)&&!e.startsWith(`_shared/`)&&!e.startsWith(`templates/`)?`merge-frontmatter`:`overwrite`}function E(e,t,n){if(!e)return`new`;let r=e.files[t];return r?r.sourceHash===S(n)?`current`:`outdated`:`new`}function D(e,t,n,r){e.files[t]={sourceHash:S(n),strategy:r??T(t),updatedAt:new Date().toISOString()}}function O(e){return{version:e,generatedAt:new Date().toISOString(),files:{}}}var k=d({guideFlows:()=>R,guideScaffold:()=>F,guideSkills:()=>I,loadAdapter:()=>A,smartCopyFlows:()=>L,smartCopyFromMemory:()=>j,smartCopyScaffold:()=>N,smartCopySkills:()=>P});async function A(e,t){let n=await import(c(s(e,`scaffold`,`dist`,`adapters`,`${t}.mjs`)).href),r=n[`generate${t.split(`-`).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(``)}`]??n.generate??n.default;if(typeof r!=`function`)throw Error(`Adapter ${t} does not export a generate function`);return r()}function j(r,i,c,l,u=!1){t(i,{recursive:!0});for(let d of r){let r=l?`${l}/${d.path}`:d.path,f=s(i,d.path);if(u){t(o(f),{recursive:!0}),a(f,d.content,`utf-8`),D(c,r,d.content);continue}let p=E(c,r,d.content);if(p!==`current`){if(p===`new`&&!e(f)){t(o(f),{recursive:!0}),a(f,d.content,`utf-8`),D(c,r,d.content);continue}if(p===`new`&&e(f)){D(c,r,d.content);continue}if(T(r)===`merge-frontmatter`&&e(f)){let e=n(f,`utf-8`);a(f,x(d.content,e),`utf-8`)}else t(o(f),{recursive:!0}),a(f,d.content,`utf-8`);D(c,r,d.content)}}u&&M(i,c,l,new Set(r.map(e=>l?`${l}/${e.path}`:e.path)))}function M(t,n,r,a){let o=[];for(let c of Object.keys(n.files)){if(!c.startsWith(`${r}/`)||a.has(c))continue;let l=s(t,c.slice(r.length+1));e(l)&&(i(l),o.push(c)),delete n.files[c]}return o}async function N(e,t,n=`copilot`,r,i=!1){let a=await A(t,n),o=a.some(e=>e.path.startsWith(`.`)),c=o?e:s(e,`.github`),l=s(c,`.aikit-scaffold.json`),u=C(l)??O(r);u.version=r;let d=new Map;for(let e of a){let t=e.path.indexOf(`/`);if(t===-1){let t=d.get(``)??[];t.push({path:e.path,content:e.content}),d.set(``,t);continue}let n=e.path.substring(0,t),r=e.path.substring(t+1),i=d.get(n)??[];i.push({path:r,content:e.content}),d.set(n,i)}for(let[e,t]of d)j(t,e?s(c,e):c,u,o?`${n}/${e||`.`}`:e||`.`,i);w(l,u)}async function P(e,t,n,r,i=!1){let a=s(e,`.github`),o=s(a,`.aikit-scaffold.json`),c=C(o)??O(r);c.version=r;let l=await A(t,`skills`),u=new Map;for(let e of l){let t=e.path.indexOf(`/`);if(t===-1)continue;let n=e.path.substring(0,t),r=e.path.substring(t+1),i=u.get(n)??[];i.push({path:r,content:e.content}),u.set(n,i)}for(let[e,t]of u)j(t,s(a,`skills`,e),c,`skills/${e}`,i);w(o,c)}async function F(t,r,i=`copilot`){let a=[],o=await A(r,i),c=o.some(e=>e.path.startsWith(`.`))?t:s(t,`.github`);for(let t of o){let r=s(c,t.path);if(!e(r))a.push({status:`new`,relativePath:t.path,sourcePath:``,content:t.content});else{let e=n(r,`utf-8`);t.content===e?a.push({status:`current`,relativePath:t.path,sourcePath:``}):a.push({status:`outdated`,relativePath:t.path,sourcePath:``,content:t.content})}}return a}async function I(t,r,i){let a=[],o=await A(r,`skills`),c=s(t,`.github`);for(let t of o){let r=`skills/${t.path}`,i=s(c,`skills`,t.path);if(!e(i))a.push({status:`new`,relativePath:r,sourcePath:``,content:t.content});else{let e=n(i,`utf-8`);t.content===e?a.push({status:`current`,relativePath:r,sourcePath:``}):a.push({status:`outdated`,relativePath:r,sourcePath:``,content:t.content})}}return a}async function L(t,n,i,a,o=!1){let c=s(t,`.github`),l=s(c,`.aikit-scaffold.json`),u=C(l)??O(a);u.version=a;let d=await A(n,`flows`),f=new Set,p=new Map;for(let e of d){let t=e.path.indexOf(`/`);if(t===-1)continue;let n=e.path.substring(0,t);f.add(n);let r=e.path.substring(t+1),i=p.get(n)??[];i.push({path:r,content:e.content}),p.set(n,i)}for(let t of f){let n=s(c,`flows`,t,`skills`);e(n)&&r(n,{recursive:!0,force:!0})}for(let[e,t]of p)j(t,s(c,`flows`,e),u,`flows/${e}`,o);w(l,u)}async function R(t,r,i){let a=[],o=await A(r,`flows`),c=s(t,`.github`);for(let t of o){let r=`flows/${t.path}`,i=s(c,`flows`,t.path);if(!e(i))a.push({status:`new`,relativePath:r,sourcePath:``,content:t.content});else{let e=n(i,`utf-8`);t.content===e?a.push({status:`current`,relativePath:r,sourcePath:``}):a.push({status:`outdated`,relativePath:r,sourcePath:``,content:t.content})}}return a}export{k as a,N as c,C as d,w as f,A as i,P as l,d as m,F as n,L as o,v as p,I as r,j as s,R as t,O as u};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{existsSync as e,readFileSync as t}from"node:fs";import{dirname as n,resolve as r}from"node:path";import{fileURLToPath as i}from"node:url";import{AIKIT_PATHS as a,EMBEDDING_DEFAULTS as o,createLogger as s,getPartitionDir as c,isUserInstalled as l,registerWorkspace as u,serializeError as d}from"../../core/dist/index.js";const f=n(i(import.meta.url)),p=s(`server`),m=[`auto`,`manual`,`smart`],h={model:o.model,dimensions:o.dimensions,childProcess:!0,idleTimeoutMs:6e4};function g(e){return typeof e==`string`&&m.includes(e)}function _(e,t,n){let i=r(e),a=r(t);if(!i.startsWith(a))throw Error(`Config ${n} path escapes workspace root: ${e} is not under ${t}`);return i}function v(e){let t=process.env.AIKIT_INDEX_MODE;if(g(t))return t;if(e.indexMode)return e.indexMode;let n=process.env.AIKIT_AUTO_INDEX;return n===void 0?e.autoIndex===void 0?`smart`:e.autoIndex?`auto`:`manual`:n===`true`?`auto`:`manual`}function y(){let i=process.env.AIKIT_CONFIG_PATH??(e(r(process.cwd(),`aikit.config.json`))?r(process.cwd(),`aikit.config.json`):r(f,`..`,`..`,`..`,`aikit.config.json`));try{if(!e(i))return p.info(`No config file found, using defaults`,{configPath:i}),b();let o=t(i,`utf-8`),s=JSON.parse(o);if(s.embedding={...h,...s.embedding},!s.sources||!Array.isArray(s.sources)||s.sources.length===0)throw Error(`Config must have at least one source`);if(!s.store?.path)throw Error(`Config must specify store.path`);if(s.autoIndex!==void 0&&typeof s.autoIndex!=`boolean`)throw Error(`Config autoIndex must be a boolean`);if(s.indexMode!==void 0&&!g(s.indexMode))throw Error(`Config indexMode must be one of: ${m.join(`, `)}`);let c=n(i);return s.sources=s.sources.map(e=>({...e,path:_(r(c,e.path),c,`source`)})),s.store.path=_(r(c,s.store.path),c,`store`),s.curated=s.curated??{path:a.aiCurated},s.curated.path=_(r(c,s.curated.path),c,`curated`),x(s,c),s.indexMode=v(s),s}catch(e){return p.error(`Failed to load config`,{configPath:i,...d(e)}),p.warn(`Falling back to default configuration`,{configPath:i}),b()}}function b(){let e=process.env.AIKIT_WORKSPACE_ROOT??process.cwd(),t={sources:[{path:e,excludePatterns:[`node_modules/**`,`dist/**`,`.git/**`,`coverage/**`,`*.lock`,`pnpm-lock.yaml`]}],serverName:`aikit`,indexing:{chunkSize:1500,chunkOverlap:200,minChunkSize:100},embedding:{...h},store:{backend:`sqlite-vec`,path:r(e,a.data)},curated:{path:r(e,a.aiCurated)},onboardDir:r(e,a.aiContext),stateDir:r(e,a.state)};return x(t,e),t.indexMode=v(t),t}function x(e,t){if(!l())return;let n=
|
|
1
|
+
import{existsSync as e,readFileSync as t}from"node:fs";import{dirname as n,resolve as r}from"node:path";import{fileURLToPath as i}from"node:url";import{AIKIT_PATHS as a,EMBEDDING_DEFAULTS as o,createLogger as s,getPartitionDir as c,isUserInstalled as l,registerWorkspace as u,serializeError as d}from"../../core/dist/index.js";const f=n(i(import.meta.url)),p=s(`server`),m=[`auto`,`manual`,`smart`],h={model:o.model,dimensions:o.dimensions,childProcess:!0,idleTimeoutMs:6e4};function g(e){return typeof e==`string`&&m.includes(e)}function _(e,t,n){let i=r(e),a=r(t);if(!i.startsWith(a))throw Error(`Config ${n} path escapes workspace root: ${e} is not under ${t}`);return i}function v(e){let t=process.env.AIKIT_INDEX_MODE;if(g(t))return t;if(e.indexMode)return e.indexMode;let n=process.env.AIKIT_AUTO_INDEX;return n===void 0?e.autoIndex===void 0?`smart`:e.autoIndex?`auto`:`manual`:n===`true`?`auto`:`manual`}function y(){let i=process.env.AIKIT_CONFIG_PATH??(e(r(process.cwd(),`aikit.config.json`))?r(process.cwd(),`aikit.config.json`):r(f,`..`,`..`,`..`,`aikit.config.json`));try{if(!e(i))return p.info(`No config file found, using defaults`,{configPath:i}),b();let o=t(i,`utf-8`),s=JSON.parse(o);if(s.embedding={...h,...s.embedding},!s.sources||!Array.isArray(s.sources)||s.sources.length===0)throw Error(`Config must have at least one source`);if(!s.store?.path)throw Error(`Config must specify store.path`);if(s.autoIndex!==void 0&&typeof s.autoIndex!=`boolean`)throw Error(`Config autoIndex must be a boolean`);if(s.indexMode!==void 0&&!g(s.indexMode))throw Error(`Config indexMode must be one of: ${m.join(`, `)}`);let c=n(i);return s.sources=s.sources.map(e=>({...e,path:_(r(c,e.path),c,`source`)})),s.store.path=_(r(c,s.store.path),c,`store`),s.curated=s.curated??{path:a.aiCurated},s.curated.path=_(r(c,s.curated.path),c,`curated`),x(s,c),s.indexMode=v(s),s}catch(e){return p.error(`Failed to load config`,{configPath:i,...d(e)}),p.warn(`Falling back to default configuration`,{configPath:i}),b()}}function b(){let e=process.env.AIKIT_WORKSPACE_ROOT??process.cwd(),t={sources:[{path:e,excludePatterns:[`node_modules/**`,`dist/**`,`.git/**`,`coverage/**`,`*.lock`,`pnpm-lock.yaml`]}],serverName:`aikit`,indexing:{chunkSize:1500,chunkOverlap:200,minChunkSize:100},embedding:{...h},store:{backend:`sqlite-vec`,path:r(e,a.data)},curated:{path:r(e,a.aiCurated)},onboardDir:r(e,a.aiContext),stateDir:r(e,a.state)};return x(t,e),t.indexMode=v(t),t}function x(e,t){if(!l())return;let n=u(t);e.store.path=r(c(n.partition)),e.onboardDir=r(c(n.partition),`onboard`),e.stateDir=r(c(n.partition),`state`),e.curated={path:r(c(n.partition),`curated`)}}function S(t,n){if(!e(n))throw Error(`Workspace root does not exist: ${n}`);p.info(`Reconfiguring for workspace root`,{workspaceRoot:n});try{process.chdir(n),p.info(`Changed process cwd to workspace root`,{cwd:process.cwd()})}catch(e){p.warn(`Failed to chdir to workspace root`,{workspaceRoot:n,...d(e)})}t.sources=[{path:n,excludePatterns:t.sources[0]?.excludePatterns??[`node_modules/**`,`dist/**`,`.git/**`,`coverage/**`,`*.lock`,`pnpm-lock.yaml`]}],t.store.path=r(n,a.data),t.curated={path:r(n,a.aiCurated)},t.onboardDir=r(n,a.aiContext),t.stateDir=r(n,a.state),x(t,n)}export{y as loadConfig,S as reconfigureForWorkspace,v as resolveIndexMode};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{t as e}from"./curated-manager-BkSgtNC2.js";import{readFileSync as t}from"node:fs";import{dirname as n,resolve as r}from"node:path";import{fileURLToPath as i,pathToFileURL as a}from"node:url";import{parseArgs as o}from"node:util";import{createLogger as s,serializeError as c}from"../../core/dist/index.js";const l=n(i(import.meta.url)),u=(()=>{try{let e=r(l,`..`,`..`,`..`,`package.json`);return JSON.parse(t(e,`utf-8`)).version??`0.0.0`}catch{return`0.0.0`}})(),d=s(`server`);function f(){return process.env.AIKIT_TRANSPORT?process.env.AIKIT_TRANSPORT:process.stdin.isTTY?`http`:`stdio`}const{values:p}=(()=>{let e=process.argv[1];if(!e)return!1;try{return import.meta.url===a(e).href}catch{return!1}})()?o({allowPositionals:!0,options:{transport:{type:`string`,default:f()},port:{type:`string`,default:process.env.AIKIT_PORT??`3210`}}}):{values:{transport:f(),port:process.env.AIKIT_PORT??`3210`}};async function m(){if(process.on(`unhandledRejection`,e=>{d.error(`Unhandled rejection`,c(e))}),process.on(`uncaughtException`,e=>{d.error(`Uncaught exception — exiting`,c(e)),process.exit(1)}),d.info(`Starting MCP AI Kit server`,{version:u}),p.transport===`http`){let[{default:e},{loadConfig:t,resolveIndexMode:n},{registerDashboardRoutes:r,resolveDashboardDir:i},{registerSettingsRoutes:a,resolveSettingsDir:o},{createSettingsRouter:s}]=await Promise.all([import(`express`),import(`./config-
|
|
1
|
+
import{t as e}from"./curated-manager-BkSgtNC2.js";import{readFileSync as t}from"node:fs";import{dirname as n,resolve as r}from"node:path";import{fileURLToPath as i,pathToFileURL as a}from"node:url";import{parseArgs as o}from"node:util";import{createLogger as s,serializeError as c}from"../../core/dist/index.js";const l=n(i(import.meta.url)),u=(()=>{try{let e=r(l,`..`,`..`,`..`,`package.json`);return JSON.parse(t(e,`utf-8`)).version??`0.0.0`}catch{return`0.0.0`}})(),d=s(`server`);function f(){return process.env.AIKIT_TRANSPORT?process.env.AIKIT_TRANSPORT:process.stdin.isTTY?`http`:`stdio`}const{values:p}=(()=>{let e=process.argv[1];if(!e)return!1;try{return import.meta.url===a(e).href}catch{return!1}})()?o({allowPositionals:!0,options:{transport:{type:`string`,default:f()},port:{type:`string`,default:process.env.AIKIT_PORT??`3210`}}}):{values:{transport:f(),port:process.env.AIKIT_PORT??`3210`}};async function m(){if(process.on(`unhandledRejection`,e=>{d.error(`Unhandled rejection`,c(e))}),process.on(`uncaughtException`,e=>{d.error(`Uncaught exception — exiting`,c(e)),process.exit(1)}),d.info(`Starting MCP AI Kit server`,{version:u}),p.transport===`http`){let[{default:e},{loadConfig:t,resolveIndexMode:n},{registerDashboardRoutes:r,resolveDashboardDir:i},{registerSettingsRoutes:a,resolveSettingsDir:o},{createSettingsRouter:s}]=await Promise.all([import(`express`),import(`./config-Dsu2Kd3U.js`),import(`./dashboard-static-BfIe0Si1.js`),import(`./settings-static-BosGZSPf.js`),import(`./routes-gbC5Wmr9.js`)]),l=t();d.info(`Config loaded`,{sourceCount:l.sources.length,storePath:l.store.path});let u=e();u.use(e.json());let f=Number(p.port);u.use((e,t,n)=>{if(t.setHeader(`Access-Control-Allow-Origin`,process.env.AIKIT_CORS_ORIGIN??`http://localhost:${f}`),t.setHeader(`Access-Control-Allow-Methods`,`GET, POST, PUT, PATCH, DELETE, OPTIONS`),t.setHeader(`Access-Control-Allow-Headers`,`Content-Type, Authorization`),e.method===`OPTIONS`){t.status(204).end();return}n()}),r(u,i(),d);let m=new Date().toISOString();u.use(`/settings/api`,s({log:d,mcpInfo:()=>({transport:`http`,port:f,pid:process.pid,startedAt:m})})),a(u,o(),d),u.get(`/health`,(e,t)=>{t.json({status:`ok`})});let h=!1,g=null,_=null,v=null,y=Promise.resolve();u.post(`/mcp`,async(e,t)=>{if(!h||!_||!v){t.status(503).json({jsonrpc:`2.0`,error:{code:-32603,message:`Server initializing — please retry in a few seconds`},id:null});return}let n=y,r;y=new Promise(e=>{r=e}),await n;try{let n=new v({sessionIdGenerator:void 0});await _.connect(n),await n.handleRequest(e,t,e.body),n.close()}catch(e){if(d.error(`MCP handler error`,c(e)),!t.headersSent){let n=e instanceof Error?e.message:String(e),r=n.includes(`Not Acceptable`);t.status(r?406:500).json({jsonrpc:`2.0`,error:{code:r?-32e3:-32603,message:r?n:`Internal server error`},id:null})}}finally{r()}}),u.get(`/mcp`,(e,t)=>{t.writeHead(405).end(JSON.stringify({jsonrpc:`2.0`,error:{code:-32e3,message:`Method not allowed.`},id:null}))}),u.delete(`/mcp`,(e,t)=>{t.writeHead(405).end(JSON.stringify({jsonrpc:`2.0`,error:{code:-32e3,message:`Method not allowed.`},id:null}))});let b=u.listen(f,`127.0.0.1`,()=>{d.info(`MCP server listening`,{url:`http://127.0.0.1:${f}/mcp`,port:f}),setTimeout(async()=>{try{let[{createLazyServer:e,ALL_TOOL_NAMES:t},{StreamableHTTPServerTransport:r},{checkForUpdates:i,autoUpgradeScaffold:a}]=await Promise.all([import(`./server-CqEB0MaC.js`),import(`@modelcontextprotocol/sdk/server/streamableHttp.js`),import(`./version-check-Bj07vc5x.js`)]);i(),a();let o=n(l),s=e(l,o);_=s.server,v=r,h=!0,d.info(`MCP server configured (lazy — AI Kit initializing in background)`,{toolCount:t.length,resourceCount:2}),s.startInit(),o===`auto`?s.ready.then(async()=>{try{let e=l.sources.map(e=>e.path).join(`, `);d.info(`Running initial index`,{sourcePaths:e}),await s.runInitialIndex(),d.info(`Initial index complete`)}catch(e){d.error(`Initial index failed; will retry on aikit_reindex`,c(e))}}).catch(e=>d.error(`AI Kit init or indexing failed`,c(e))):o===`smart`?s.ready.then(async()=>{try{if(!s.aikit)throw Error(`AI Kit components are not available after initialization`);let{SmartIndexScheduler:e}=await import(`../../indexer/dist/index.js`),t=new e(s.aikit.indexer,l,s.aikit.store),n=s.aikit.store;g=t,t.start(),n.onBeforeClose&&n.onBeforeClose(()=>t.stop()),s.setSmartScheduler(t),d.info(`Smart index scheduler started (HTTP mode)`)}catch(e){d.error(`Failed to start smart index scheduler`,c(e))}}).catch(e=>d.error(`AI Kit initialization failed`,c(e))):(s.ready.catch(e=>d.error(`AI Kit initialization failed`,c(e))),d.info(`Initial full indexing skipped in HTTP mode`,{indexMode:o}))}catch(e){d.error(`Failed to load server modules`,c(e))}},100)}),x=async e=>{d.info(`Shutdown signal received`,{signal:e}),g?.stop(),b.close(),_&&await _.close(),process.exit(0)};process.on(`SIGINT`,()=>x(`SIGINT`)),process.on(`SIGTERM`,()=>x(`SIGTERM`))}else{let[{loadConfig:e,reconfigureForWorkspace:t,resolveIndexMode:n},{createLazyServer:r},{checkForUpdates:a,autoUpgradeScaffold:o},{RootsListChangedNotificationSchema:s}]=await Promise.all([import(`./config-Dsu2Kd3U.js`),import(`./server-CqEB0MaC.js`),import(`./version-check-Bj07vc5x.js`),import(`@modelcontextprotocol/sdk/types.js`)]),l=e();d.info(`Config loaded`,{sourceCount:l.sources.length,storePath:l.store.path}),a(),o();let u=n(l),f=r(l,u),{server:p,startInit:m,ready:h,runInitialIndex:g}=f,{StdioServerTransport:_}=await import(`@modelcontextprotocol/sdk/server/stdio.js`),v=new _;await p.connect(v),d.info(`MCP server started`,{transport:`stdio`});let y=e=>{if(e.length===0)return!1;let n=e[0].uri,r=n.startsWith(`file://`)?i(n):n;return d.info(`MCP roots resolved`,{rootUri:n,rootPath:r,rootCount:e.length}),t(l,r),l.allRoots=e.map(e=>{let t=e.uri;return t.startsWith(`file://`)?i(t):t}),!0},b=!1;try{b=y((await p.server.listRoots()).roots),b||d.info(`No MCP roots yet; waiting for roots/list_changed notification`)}catch(e){d.warn(`MCP roots/list not supported by client; using cwd fallback`,{cwd:process.cwd(),...c(e)}),b=!0}b||=await new Promise(e=>{let t=setTimeout(()=>{d.warn(`Timed out waiting for MCP roots/list_changed; using cwd fallback`,{cwd:process.cwd()}),e(!1)},5e3);p.server.setNotificationHandler(s,async()=>{clearTimeout(t);try{e(y((await p.server.listRoots()).roots))}catch(t){d.warn(`roots/list retry failed after notification`,c(t)),e(!1)}})}),m();let x=null,S=()=>{x&&clearTimeout(x),x=setTimeout(async()=>{d.info(`Auto-shutdown: no activity for 30 minutes — shutting down gracefully`);try{let e=f.aikit;e&&await Promise.all([e.embedder.shutdown?.().catch(()=>{})??Promise.resolve(),e.graphStore.close().catch(()=>{}),e.store.close().catch(()=>{})])}catch{}process.exit(0)},18e5),x.unref&&x.unref()};S(),process.stdin.on(`data`,()=>S()),h.catch(e=>{d.error(`Initialization failed — server will continue with limited tools`,c(e))}),u===`auto`?g().catch(e=>d.error(`Initial index failed`,c(e))):u===`smart`?h.then(async()=>{try{if(!f.aikit)throw Error(`AI Kit components are not available after initialization`);let{SmartIndexScheduler:e}=await import(`../../indexer/dist/index.js`),t=new e(f.aikit.indexer,l,f.aikit.store),n=f.aikit.store;t.start(),n.onBeforeClose&&n.onBeforeClose(()=>t.stop()),f.setSmartScheduler(t),d.info(`Smart index scheduler started (stdio mode)`)}catch(e){d.error(`Failed to start smart index scheduler`,c(e))}}).catch(e=>d.error(`AI Kit init failed for smart scheduler`,c(e))):d.warn(`Initial full indexing skipped; use aikit_reindex to index manually`,{indexMode:u})}}m().catch(e=>{d.error(`Fatal error`,c(e)),process.exit(1)});export{e as CuratedKnowledgeManager};
|