@vpxa/aikit 0.1.84 → 0.1.86
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 +2 -2
- package/packages/cli/dist/user-C2c_eBDB.js +5 -0
- package/packages/server/dist/index.js +1 -1
- package/packages/server/dist/{server-CRBcgUPU.js → server-DG5jasWR.js} +1 -1
- package/scaffold/dist/definitions/agents.mjs +58 -2
- package/scaffold/dist/definitions/bodies.mjs +16 -1
- package/scaffold/dist/definitions/flows.mjs +18 -13
- package/scaffold/dist/definitions/prompts.mjs +1 -1
- package/scaffold/dist/definitions/protocols.mjs +83 -2
- package/scaffold/dist/definitions/skills.mjs +33 -16
- package/packages/cli/dist/user-C05ypatU.js +0 -5
package/package.json
CHANGED
|
@@ -9,7 +9,7 @@ Dead in docs (informational):`);for(let t of e.deadInDocs)console.log(` - ${t.p
|
|
|
9
9
|
Actions: stats, find-nodes, find-edges, neighbors, traverse, delete, clear`),process.exit(1));let{graphStore:n}=await Y(),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 ge(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(`
|
|
10
10
|
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(`
|
|
11
11
|
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}`)}}],Ot=[{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 Y(),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 Y(),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 Y(),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 Y(),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 Y(),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 Y(),s=await ie(o,{text:a,path:n,query:i,maxChars:t,segmentation:r});console.log(`Compressed ${s.originalChars} chars to ${s.compressedChars} chars`),console.log(`Ratio: ${(s.ratio*100).toFixed(1)}% | Segments: ${s.segmentsKept}/${s.segmentsTotal}`),console.log(``),console.log(s.text)}}],kt=[{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 Y(),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=U(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 Y(),s=await g(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 Y(),a=await Fe(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 Y();ht(await Ve(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 Y();dt(await Ue(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 Y();ft(await pe(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 Y();pt(await fe(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 Y(),r=await n.getById(t);if(r){console.log(r.id),console.log(`─`.repeat(60)),console.log(`Path: ${r.sourcePath}`),console.log(`Chunk: ${r.chunkIndex+1}/${r.totalChunks}`),console.log(`Lines: ${r.startLine}-${r.endLine}`),console.log(`Type: ${r.contentType} | Origin: ${r.origin}`),r.tags.length>0&&console.log(`Tags: ${r.tags.join(`, `)}`),console.log(``),console.log(r.content);return}let i=await n.getBySourcePath(t);if(i.length===0){console.log(`No indexed content found for: ${t}`);return}i.sort((e,t)=>e.chunkIndex-t.chunkIndex),console.log(t),console.log(`─`.repeat(60)),console.log(`Chunks: ${i.length} | Type: ${i[0].contentType}`);for(let e of i){let t=e.startLine?` (lines ${e.startLine}-${e.endLine})`:``;console.log(`\nChunk ${e.chunkIndex+1}/${e.totalChunks}${t}`),console.log(e.content)}}}],X=s(u(import.meta.url));function Z(e){let t=e;for(let e=0;e<10;e++){try{let e=c(t,`package.json`);if(r(e)&&JSON.parse(a(e,`utf8`)).name===`@vpxa/aikit`)return t}catch{}let e=s(t);if(e===t)break;t=e}return l(e,`..`,`..`,`..`)}const At=[{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(l(a,`.vscode`,`mcp.json`)),c,u;if(o&&s)c=`workspace (overrides user-level for this workspace)`,u=l(a,`.aikit-data`);else if(o){let e=n(a);c=i(l(a,`AGENTS.md`))?`user (workspace scaffolded)`:`user (workspace not scaffolded)`,u=l(t(),e)}else c=`workspace`,u=l(a,`.aikit-data`);if(console.log(`AI Kit Status`),console.log(`─`.repeat(40)),console.log(` Mode: ${c}`),console.log(` Data: ${u}`),o&&!s){let e=r();console.log(` Registry: ${e.length} workspace(s) enrolled`)}try{let{store:e}=await Y(),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(l(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 Y();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(`
|
|
12
|
-
`)},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=l(Z(X),`packages`,`server`,`dist`,`index.js`),n=N(e,`--transport`,`stdio`),r=N(e,`--port`,`3210`),i=tt(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 [--user|--workspace] [--force] [--guide]`,run:async e=>{let t=e.includes(`--user`),n=e.includes(`--workspace`),r=e.includes(`--guide`),i=e.includes(`--force`);if(t&&n&&(console.error(`Cannot use --user and --workspace together.`),process.exit(1)),r){let{guideProject:e}=await import(`./init-CuRXmyD9.js`);await e();return}if(t){let{initUser:e}=await import(`./user-
|
|
13
|
-
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=_e(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=Me({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}`)}Ne().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=l(Z(X),`packages`,`server`,`dist`,`index.js`),c=a(process.execPath,[s,`--transport`,`http`,`--port`,String(r)],{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env,AIKIT_TRANSPORT:`http`,AIKIT_PORT:String(r)}}),u=`http://localhost:${r}/_dashboard/`,d=`http://localhost:${r}/health`,f=!1;for(let e=0;e<30;e+=1){try{if((await fetch(d)).ok){f=!0;break}}catch{}await new Promise(e=>setTimeout(e,1e3))}if(f||(console.error(`Server failed to start within 30 seconds.`),c.kill(),process.exit(1)),console.log(`AI Kit Dashboard: ${u}`),console.log(`Press Ctrl+C to stop.`),!i){let e=o();e===`win32`?a(`cmd`,[`/c`,`start`,``,u],{stdio:`ignore`,detached:!0}).unref():a(e===`darwin`?`open`:`xdg-open`,[u],{stdio:`ignore`,detached:!0}).unref()}let p=()=>{c.kill(),process.exit(0)};process.on(`SIGINT`,p),process.on(`SIGTERM`,p),await new Promise(e=>{c.on(`exit`,()=>e())})}},{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=l(Z(X),`packages`,`server`,`dist`,`index.js`),c=a(process.execPath,[s,`--transport`,`http`,`--port`,String(r)],{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env,AIKIT_TRANSPORT:`http`,AIKIT_PORT:String(r)}}),u=`http://localhost:${r}/settings/`,d=`http://localhost:${r}/health`,f=!1;for(let e=0;e<30;e+=1){try{if((await fetch(d)).ok){f=!0;break}}catch{}await new Promise(e=>setTimeout(e,1e3))}if(f||(console.error(`Server failed to start within 30 seconds.`),c.kill(),process.exit(1)),console.log(`AI Kit Settings: ${u}`),console.log(`Press Ctrl+C to stop.`),!i){let e=o();e===`win32`?a(`cmd`,[`/c`,`start`,``,u],{stdio:`ignore`,detached:!0}).unref():a(e===`darwin`?`open`:`xdg-open`,[u],{stdio:`ignore`,detached:!0}).unref()}let p=()=>{c.kill(),process.exit(0)};process.on(`SIGINT`,p),process.on(`SIGTERM`,p),await new Promise(e=>{c.on(`exit`,()=>e())})}}];function jt(e){let t=e;for(let e=0;e<10;e++){try{let e=c(t,`package.json`);if(r(e)&&JSON.parse(a(e,`utf8`)).name===`@vpxa/aikit`)return t}catch{}let e=s(t);if(e===t)break;t=e}return l(e,`..`,`..`,`..`)}const Mt=[{name:`upgrade`,description:`Upgrade AI Kit agents, prompts, and skills to the latest version (user-level and workspace-level)`,usage:`aikit upgrade`,run:async()=>{let{initUser:n}=await import(`./user-C05ypatU.js`);await n({force:!0});let i=process.cwd(),o=r(l(i,`.github`,`.aikit-scaffold.json`)),c=r(l(i,`.github`,`agents`)),d=r(l(i,`.github`,`prompts`)),f=r(l(i,`.claude`,`commands`));if(o||c||d||f){let{initScaffoldOnly:e}=await import(`./init-CuRXmyD9.js`);await e({force:!0})}if(r(l(i,`.github`,`skills`))){let{smartCopySkills:n}=await import(`./scaffold-WMQ2uQ48.js`),r=jt(s(u(import.meta.url))),o=JSON.parse(a(l(r,`package.json`),`utf-8`)).version;await n(i,r,[...e],o,!0);let{smartCopyFlows:c}=await import(`./scaffold-WMQ2uQ48.js`);await c(i,r,[...t],o,!0)}}}],Nt=[{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=Pe(i,n,{description:r});console.log(`Saved workset: ${e.name}`),B(e);return}case`get`:{i||(console.error(`Usage: aikit workset get <name>`),process.exit(1));let e=me(i);if(!e){console.log(`No workset found: ${i}`);return}B(e);return}case`list`:{let e=Te();if(e.length===0){console.log(`No worksets saved.`);return}console.log(`Worksets (${e.length})`),console.log(`─`.repeat(60));for(let t of e)B(t),console.log(``);return}case`delete`:{i||(console.error(`Usage: aikit workset delete <name>`),process.exit(1));let e=ce(i);console.log(e?`Deleted workset: ${i}`:`No workset found: ${i}`);return}case`add`:{(!i||n.length===0)&&(console.error(`Usage: aikit workset add <name> --files f1,f2`),process.exit(1));let e=d(i,n);console.log(`Updated workset: ${e.name}`),B(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}`),B(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=Be(n,gt(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=Re(n);if(!e){console.log(`No stash entry found: ${n}`);return}console.log(JSON.stringify(e,null,2));return}case`list`:{let e=ze();if(e.length===0){console.log(`No stash entries saved.`);return}console.log(`Stash entries (${e.length})`),console.log(`─`.repeat(60));for(let t of e)console.log(`${t.key} (${t.type})`),console.log(` Stored: ${t.storedAt}`);return}case`delete`:{n||(console.error(`Usage: aikit stash delete <key>`),process.exit(1));let e=Le(n);console.log(e?`Deleted stash entry: ${n}`:`No stash entry found: ${n}`);return}case`clear`:{let e=Ie();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=Se();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=ye(n,t.split(`,`).map(e=>e.trim()));console.log(`Lane "${r.name}" created with ${r.sourceFiles.length} files.`);break}case`status`:{let e=we(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=be(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=Ce(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=xe(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=Ee();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=w(n);console.log(`Queue "${e.name}" created.`);break}case`push`:{let t=Oe(n,e.join(` `)||`Untitled task`);console.log(`Pushed "${t.title}" (${t.id}) to queue "${n}".`);break}case`next`:{let e=De(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=E(n,t);console.log(`Marked "${r.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=D(n,t,r);console.log(`Marked "${i.title}" as failed: ${r}`);break}case`get`:{let e=O(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=C(n);console.log(`Cleared ${e} completed/failed items from queue "${n}".`);break}case`delete`:{let e=T(n);console.log(e?`Queue "${n}" deleted.`:`Queue "${n}" not found.`);break}}}}],Q=[...kt,...Ot,...nt,...Dt,...At,...xt,...yt,...Nt,...bt,...Mt,...q];Q.push({name:`help`,description:`Show available commands`,run:async()=>{$()}});async function Pt(e){let t=[...e],n=t.shift();if(!n||n===`--help`||n===`-h`){$();return}if(n===`--version`||n===`-v`){let e=l(s(u(import.meta.url)),`..`,`..`,`..`,`package.json`),t=JSON.parse(a(e,`utf-8`));console.log(t.version);return}if(n&&new Set([`--user`,`--workspace`,`--guide`,`--smart`]).has(n)){let e=Q.find(e=>e.name===`init`);if(e){await e.run([n,...t]);return}}let r=Q.find(e=>e.name===n);r||(console.error(`Unknown command: ${n}`),$(),process.exit(1));try{await r.run(t)}finally{let e=Et();e&&await e.store.close()}}function $(){console.log(`@vpxa/aikit — Local-first AI developer toolkit
|
|
12
|
+
`)},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=l(Z(X),`packages`,`server`,`dist`,`index.js`),n=N(e,`--transport`,`stdio`),r=N(e,`--port`,`3210`),i=tt(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 [--user|--workspace] [--force] [--guide]`,run:async e=>{let t=e.includes(`--user`),n=e.includes(`--workspace`),r=e.includes(`--guide`),i=e.includes(`--force`);if(t&&n&&(console.error(`Cannot use --user and --workspace together.`),process.exit(1)),r){let{guideProject:e}=await import(`./init-CuRXmyD9.js`);await e();return}if(t){let{initUser:e}=await import(`./user-C2c_eBDB.js`);await e({force:i})}else if(n){let{initProject:e}=await import(`./init-CuRXmyD9.js`);await e({force:i})}else{let{initSmart:e}=await import(`./init-CuRXmyD9.js`);await e({force:i})}}},{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 m({cwd:t,files:i.length>0?i:void 0,skipTypes:a,skipLint:o,detail:r});st(s),s.passed||(process.exitCode=1)}},{name:`batch`,description:`Execute built-in operations from JSON input`,usage:`aikit batch [--file path] [--concurrency N]`,run:async e=>{let t=N(e,`--file`,``).trim()||void 0,n=(()=>{let t=e.indexOf(`--concurrency`);if(t===-1||t+1>=e.length)return 0;let n=Number.parseInt(e.splice(t,2)[1],10);return Number.isNaN(n)?0:n})(),r=await rt(t);r.trim()||(console.error(`Usage: aikit batch [--file path] [--concurrency N]`),process.exit(1));let i=it(r),a=n>0?n:i.concurrency,o=i.operations.some(e=>e.type!==`check`)?await Y():null,s=await p(i.operations,async e=>vt(e,o),{concurrency:a});console.log(JSON.stringify(s,null,2)),s.some(e=>e.status===`error`)&&(process.exitCode=1)}},{name:`health`,description:`Run project health checks on the current directory`,usage:`aikit health [path]`,run:async e=>{let t=ve(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 Y(),r=N(e,`--detail`,`efficient`)||`efficient`,i=N(e,`--checks`,``),a=i?i.split(`,`).map(e=>e.trim()):void 0,o=await f(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(`
|
|
13
|
+
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=_e(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=Me({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}`)}Ne().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=l(Z(X),`packages`,`server`,`dist`,`index.js`),c=a(process.execPath,[s,`--transport`,`http`,`--port`,String(r)],{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env,AIKIT_TRANSPORT:`http`,AIKIT_PORT:String(r)}}),u=`http://localhost:${r}/_dashboard/`,d=`http://localhost:${r}/health`,f=!1;for(let e=0;e<30;e+=1){try{if((await fetch(d)).ok){f=!0;break}}catch{}await new Promise(e=>setTimeout(e,1e3))}if(f||(console.error(`Server failed to start within 30 seconds.`),c.kill(),process.exit(1)),console.log(`AI Kit Dashboard: ${u}`),console.log(`Press Ctrl+C to stop.`),!i){let e=o();e===`win32`?a(`cmd`,[`/c`,`start`,``,u],{stdio:`ignore`,detached:!0}).unref():a(e===`darwin`?`open`:`xdg-open`,[u],{stdio:`ignore`,detached:!0}).unref()}let p=()=>{c.kill(),process.exit(0)};process.on(`SIGINT`,p),process.on(`SIGTERM`,p),await new Promise(e=>{c.on(`exit`,()=>e())})}},{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=l(Z(X),`packages`,`server`,`dist`,`index.js`),c=a(process.execPath,[s,`--transport`,`http`,`--port`,String(r)],{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env,AIKIT_TRANSPORT:`http`,AIKIT_PORT:String(r)}}),u=`http://localhost:${r}/settings/`,d=`http://localhost:${r}/health`,f=!1;for(let e=0;e<30;e+=1){try{if((await fetch(d)).ok){f=!0;break}}catch{}await new Promise(e=>setTimeout(e,1e3))}if(f||(console.error(`Server failed to start within 30 seconds.`),c.kill(),process.exit(1)),console.log(`AI Kit Settings: ${u}`),console.log(`Press Ctrl+C to stop.`),!i){let e=o();e===`win32`?a(`cmd`,[`/c`,`start`,``,u],{stdio:`ignore`,detached:!0}).unref():a(e===`darwin`?`open`:`xdg-open`,[u],{stdio:`ignore`,detached:!0}).unref()}let p=()=>{c.kill(),process.exit(0)};process.on(`SIGINT`,p),process.on(`SIGTERM`,p),await new Promise(e=>{c.on(`exit`,()=>e())})}}];function jt(e){let t=e;for(let e=0;e<10;e++){try{let e=c(t,`package.json`);if(r(e)&&JSON.parse(a(e,`utf8`)).name===`@vpxa/aikit`)return t}catch{}let e=s(t);if(e===t)break;t=e}return l(e,`..`,`..`,`..`)}const Mt=[{name:`upgrade`,description:`Upgrade AI Kit agents, prompts, and skills to the latest version (user-level and workspace-level)`,usage:`aikit upgrade`,run:async()=>{let{initUser:n}=await import(`./user-C2c_eBDB.js`);await n({force:!0});let i=process.cwd(),o=r(l(i,`.github`,`.aikit-scaffold.json`)),c=r(l(i,`.github`,`agents`)),d=r(l(i,`.github`,`prompts`)),f=r(l(i,`.claude`,`commands`));if(o||c||d||f){let{initScaffoldOnly:e}=await import(`./init-CuRXmyD9.js`);await e({force:!0})}if(r(l(i,`.github`,`skills`))){let{smartCopySkills:n}=await import(`./scaffold-WMQ2uQ48.js`),r=jt(s(u(import.meta.url))),o=JSON.parse(a(l(r,`package.json`),`utf-8`)).version;await n(i,r,[...e],o,!0);let{smartCopyFlows:c}=await import(`./scaffold-WMQ2uQ48.js`);await c(i,r,[...t],o,!0)}}}],Nt=[{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=Pe(i,n,{description:r});console.log(`Saved workset: ${e.name}`),B(e);return}case`get`:{i||(console.error(`Usage: aikit workset get <name>`),process.exit(1));let e=me(i);if(!e){console.log(`No workset found: ${i}`);return}B(e);return}case`list`:{let e=Te();if(e.length===0){console.log(`No worksets saved.`);return}console.log(`Worksets (${e.length})`),console.log(`─`.repeat(60));for(let t of e)B(t),console.log(``);return}case`delete`:{i||(console.error(`Usage: aikit workset delete <name>`),process.exit(1));let e=ce(i);console.log(e?`Deleted workset: ${i}`:`No workset found: ${i}`);return}case`add`:{(!i||n.length===0)&&(console.error(`Usage: aikit workset add <name> --files f1,f2`),process.exit(1));let e=d(i,n);console.log(`Updated workset: ${e.name}`),B(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}`),B(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=Be(n,gt(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=Re(n);if(!e){console.log(`No stash entry found: ${n}`);return}console.log(JSON.stringify(e,null,2));return}case`list`:{let e=ze();if(e.length===0){console.log(`No stash entries saved.`);return}console.log(`Stash entries (${e.length})`),console.log(`─`.repeat(60));for(let t of e)console.log(`${t.key} (${t.type})`),console.log(` Stored: ${t.storedAt}`);return}case`delete`:{n||(console.error(`Usage: aikit stash delete <key>`),process.exit(1));let e=Le(n);console.log(e?`Deleted stash entry: ${n}`:`No stash entry found: ${n}`);return}case`clear`:{let e=Ie();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=Se();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=ye(n,t.split(`,`).map(e=>e.trim()));console.log(`Lane "${r.name}" created with ${r.sourceFiles.length} files.`);break}case`status`:{let e=we(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=be(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=Ce(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=xe(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=Ee();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=w(n);console.log(`Queue "${e.name}" created.`);break}case`push`:{let t=Oe(n,e.join(` `)||`Untitled task`);console.log(`Pushed "${t.title}" (${t.id}) to queue "${n}".`);break}case`next`:{let e=De(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=E(n,t);console.log(`Marked "${r.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=D(n,t,r);console.log(`Marked "${i.title}" as failed: ${r}`);break}case`get`:{let e=O(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=C(n);console.log(`Cleared ${e} completed/failed items from queue "${n}".`);break}case`delete`:{let e=T(n);console.log(e?`Queue "${n}" deleted.`:`Queue "${n}" not found.`);break}}}}],Q=[...kt,...Ot,...nt,...Dt,...At,...xt,...yt,...Nt,...bt,...Mt,...q];Q.push({name:`help`,description:`Show available commands`,run:async()=>{$()}});async function Pt(e){let t=[...e],n=t.shift();if(!n||n===`--help`||n===`-h`){$();return}if(n===`--version`||n===`-v`){let e=l(s(u(import.meta.url)),`..`,`..`,`..`,`package.json`),t=JSON.parse(a(e,`utf-8`));console.log(t.version);return}if(n&&new Set([`--user`,`--workspace`,`--guide`,`--smart`]).has(n)){let e=Q.find(e=>e.name===`init`);if(e){await e.run([n,...t]);return}}let r=Q.find(e=>e.name===n);r||(console.error(`Unknown command: ${n}`),$(),process.exit(1));try{await r.run(t)}finally{let e=Et();e&&await e.store.close()}}function $(){console.log(`@vpxa/aikit — Local-first AI developer toolkit
|
|
14
14
|
`),console.log(`Usage: aikit <command> [options]
|
|
15
15
|
`),console.log(`Commands:`);let e=Math.max(...Q.map(e=>e.name.length));for(let t of Q)console.log(` ${t.name.padEnd(e+2)}${t.description}`);console.log(``),console.log(`Options:`),console.log(` --help, -h Show this help`),console.log(` --version, -v Show version`)}export{Pt as run};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import{a as e,n as t,r as n}from"./constants-B8_CApx0.js";import{n as r,t as i}from"./templates-ArdAVWoY.js";import{loadAdapter as a,n as o,r as s,smartCopyFromMemory as c,t as l}from"./scaffold-WMQ2uQ48.js";import{existsSync as u,mkdirSync as d,readFileSync as f,readdirSync as p,rmSync as m,unlinkSync as h,writeFileSync as g}from"node:fs";import{dirname as _,join as v,posix as y,resolve as b,win32 as x}from"node:path";import{fileURLToPath as S}from"node:url";import{mkdir as C,readFile as w,rename as T,unlink as E,writeFile as D}from"node:fs/promises";import{getGlobalDataDir as O,saveRegistry as k}from"../../core/dist/index.js";import{execFileSync as A}from"node:child_process";import{randomUUID as j}from"node:crypto";import{homedir as M}from"node:os";var N=class{isPlatformSupported(){return this.platforms.includes(process.platform)}async readConfig(e){let t=this.getConfigPath(e);if(!u(t))return{};let n=await w(t,`utf-8`);try{return JSON.parse(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=_(n),i=v(r,`.aikit-tmp-${j()}.json`);await C(r,{recursive:!0});try{await D(i,`${JSON.stringify(e,null,2)}\n`,`utf-8`),await T(i,n)}catch(e){try{await E(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,instructions:null,manifest:null}}buildInstructionContent(e,t){return`${e}\n---\n\n${t}`}},P=class extends N{id=`claude-code`;name=`Claude Code`;family=`claude`;platforms=[`win32`,`darwin`,`linux`];scope=`user`;configKey=`mcpServers`;async detect(){return this.isPlatformSupported()?u(this.getPathModule().resolve(M(),`.claude`)):!1}getConfigPath(){return this.getPathModule().resolve(M(),`.claude`,`mcp.json`)}getScaffoldRoot(){return this.getPathModule().resolve(M(),`.claude`)}getScaffoldPaths(){let e=this.getPathModule(),t=e.resolve(M(),`.claude`);return{agents:e.resolve(t,`agents`),skills:e.resolve(t,`skills`),prompts:null,flows:e.resolve(t,`flows`),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`?x:y}},F=class extends N{id=`codex-cli`;name=`Codex CLI`;family=`codex`;platforms=[`win32`,`darwin`,`linux`];scope=`user`;configKey=`mcpServers`;async detect(){return this.isPlatformSupported()?u(this.getPathModule().resolve(M(),`.codex`)):!1}getConfigPath(){return this.getPathModule().resolve(M(),`.codex`,`config.json`)}getScaffoldRoot(){return this.getPathModule().resolve(M(),`.codex`)}getScaffoldPaths(){let e=this.getPathModule(),t=e.resolve(M(),`.codex`);return{agents:e.resolve(t,`agents`),skills:e.resolve(t,`skills`),prompts:null,flows:e.resolve(t,`flows`),instructions:e.resolve(t,`AGENTS.md`),manifest:e.resolve(t,`.aikit-scaffold.json`)}}getPathModule(){return process.platform===`win32`?x:y}},I=class extends N{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 u(e)||t!==null&&u(t)}return u(e)}getConfigPath(){return this.getPathModule().resolve(this.getConfigDir(),`mcp.json`)}getScaffoldRoot(){return this.getPathModule().resolve(M(),this.scaffoldBase)}getInstructionsRoot(){let e=this.getInstructionFilePath();return e?this.getPathModule().dirname(e):null}getScaffoldPaths(){let e=this.getPathModule(),t=e.resolve(M(),this.scaffoldBase);return{agents:e.resolve(t,`agents`),skills:e.resolve(t,`skills`),prompts:e.resolve(this.getConfigDir(),`prompts`),flows:e.resolve(t,`flows`),instructions:this.getInstructionFilePath(),manifest:e.resolve(t,`.aikit-scaffold.json`)}}getConfigDir(){let e=this.getPathModule(),t=M();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`?x:y}},L=class extends N{id=`copilot-cli`;name=`Copilot CLI`;family=`copilot`;platforms=[`win32`,`darwin`,`linux`];scope=`user`;configKey=`mcpServers`;async detect(){return this.isPlatformSupported()?u(b(M(),`.copilot`)):!1}getConfigPath(){return b(M(),`.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 b(M(),`.copilot`)}getInstructionsRoot(){return null}getScaffoldPaths(){let e=b(M(),`.copilot`);return{agents:b(e,`agents`),skills:b(e,`skills`),prompts:null,flows:b(e,`flows`),instructions:b(M(),`.github`,`copilot-instructions.md`),manifest:b(e,`.aikit-scaffold.json`)}}},R=class extends I{id=`cursor`;name=`Cursor`;configKey=`mcpServers`;configDirName=`Cursor`;scaffoldBase=`.cursor`;getMacAppPath(){return`/Applications/Cursor.app`}getInstructionFilePath(){return this.getPathModule().resolve(M(),this.scaffoldBase,`rules`,`aikit.mdc`)}},z=class extends I{id=`cursor-nightly`;name=`Cursor Nightly`;configKey=`mcpServers`;configDirName=`Cursor Nightly`;scaffoldBase=`.cursor`;getMacAppPath(){return`/Applications/Cursor Nightly.app`}getInstructionFilePath(){return this.getPathModule().resolve(M(),this.scaffoldBase,`rules`,`aikit.mdc`)}},B=class e extends N{id=`intellij`;name=`IntelliJ IDEA`;family=`copilot`;platforms=[`win32`,`darwin`,`linux`];scope=`workspace`;configKey=`servers`;static PRODUCTS=[`IntelliJIdea`,`IdeaIC`,`WebStorm`,`PyCharm`,`PyCharmCE`,`GoLand`,`PhpStorm`,`CLion`,`Rider`,`RubyMine`,`RustRover`,`DataGrip`];async detect(){if(!this.isPlatformSupported())return!1;let t=this.getJetBrainsBaseDir();if(!u(t))return!1;try{return p(t,{withFileTypes:!0}).some(t=>t.isDirectory()&&e.PRODUCTS.some(e=>t.name.startsWith(e)))}catch{return!1}}getConfigPath(e){if(!e)throw Error(`IntelliJ adapter requires projectRoot (scope: workspace)`);return b(e,`mcp.json`)}async registerMcp(e,t,n){let r={type:`stdio`,...t};await super.registerMcp(e,r,n)}getScaffoldRoot(e){return e?b(e,`.github`,`agents`):null}getInstructionsRoot(e){return null}getScaffoldPaths(e){return e?{agents:b(e,`.github`,`agents`),skills:null,prompts:null,flows:null,instructions:b(e,`AGENTS.md`),manifest:null}:{agents:null,skills:null,prompts:null,flows:null,instructions:null,manifest:null}}buildInstructionContent(e,t){return t}getJetBrainsBaseDir(){let e=M();return process.platform===`win32`?b(process.env.APPDATA??b(e,`AppData`,`Roaming`),`JetBrains`):process.platform===`darwin`?b(e,`Library`,`Application Support`,`JetBrains`):b(process.env.XDG_CONFIG_HOME??b(e,`.config`),`JetBrains`)}},V=class extends I{id=`trae`;name=`Trae`;configKey=`servers`;configDirName=`Trae`;scaffoldBase=`.trae`;getMacAppPath(){return`/Applications/Trae.app`}getInstructionFilePath(){return this.getPathModule().resolve(M(),this.scaffoldBase,`rules`,`aikit.md`)}},H=class extends I{id=`vscode`;name=`VS Code`;configKey=`servers`;configDirName=`Code`;scaffoldBase=`.copilot`;hasInstructions=!0;getMacAppPath(){return`/Applications/Visual Studio Code.app`}getInstructionFilePath(){return this.hasInstructions?this.getPathModule().resolve(M(),this.scaffoldBase,`instructions`,`copilot-instructions.md`):null}buildInstructionContent(e,t){return`---\napplyTo: "**"\n---\n\n${e}\n---\n\n${t}`}},U=class extends I{id=`vscode-insiders`;name=`VS Code Insiders`;configKey=`servers`;configDirName=`Code - Insiders`;scaffoldBase=`.copilot`;hasInstructions=!0;getMacAppPath(){return`/Applications/Visual Studio Code - Insiders.app`}getInstructionFilePath(){return this.hasInstructions?this.getPathModule().resolve(M(),this.scaffoldBase,`instructions`,`copilot-instructions.md`):null}buildInstructionContent(e,t){return`---\napplyTo: "**"\n---\n\n${e}\n---\n\n${t}`}},W=class extends I{id=`vscodium`;name=`VSCodium`;configKey=`servers`;configDirName=`VSCodium`;scaffoldBase=`.copilot`;hasInstructions=!0;getMacAppPath(){return`/Applications/VSCodium.app`}getInstructionFilePath(){return this.hasInstructions?this.getPathModule().resolve(M(),this.scaffoldBase,`instructions`,`copilot-instructions.md`):null}buildInstructionContent(e,t){return`---\napplyTo: "**"\n---\n\n${e}\n---\n\n${t}`}},G=class extends I{id=`windsurf`;name=`Windsurf`;configKey=`servers`;configDirName=`Windsurf`;scaffoldBase=`.windsurf`;getMacAppPath(){return`/Applications/Windsurf.app`}getInstructionFilePath(){return this.getPathModule().resolve(M(),this.scaffoldBase,`rules`,`aikit.md`)}},K=class extends N{id=`gemini-cli`;name=`Gemini CLI`;family=`gemini`;platforms=[`win32`,`darwin`,`linux`];scope=`user`;configKey=`mcpServers`;async detect(){return this.isPlatformSupported()?u(this.getPathModule().resolve(M(),`.gemini`)):!1}getConfigPath(){return this.getPathModule().resolve(M(),`.gemini`,`settings.json`)}getScaffoldRoot(){return this.getPathModule().resolve(M(),`.gemini`)}getScaffoldPaths(){let e=this.getPathModule(),t=e.resolve(M(),`.gemini`);return{agents:e.resolve(t,`agents`),skills:e.resolve(t,`skills`),prompts:null,flows:e.resolve(t,`flows`),instructions:e.resolve(t,`AGENTS.md`),manifest:e.resolve(t,`.aikit-scaffold.json`)}}getPathModule(){return process.platform===`win32`?x:y}};const q=[new H,new U,new W,new R,new z,new G,new V,new L,new B,new P,new K,new F];function J(){return[...q]}async function Y(e){let t=e?.scope?q.filter(t=>t.scope===e.scope):q;return(await Promise.allSettled(t.map(async e=>await e.detect()?e:null))).flatMap(e=>e.status!==`fulfilled`||e.value===null?[]:[e.value])}function X(e){let t=e;for(let e=0;e<10;e++){try{let e=v(t,`package.json`);if(u(e)&&JSON.parse(f(e,`utf8`)).name===`@vpxa/aikit`)return t}catch{}let e=_(t);if(e===t)break;t=e}return b(e,`..`,`..`,`..`)}function Z(){let e={command:t.command,args:t.args?[...t.args]:void 0,type:t.type};if(process.platform!==`win32`){let t=process.env.PATH;t&&(e.env={PATH:t});try{let t=A(`which`,[`npx`],{encoding:`utf-8`,timeout:3e3}).trim();t&&u(t)&&(e.command=t)}catch{}}return e}const Q=new Set([`VS Code`,`VS Code Insiders`,`VSCodium`]);function $(t,n=!1){if(!Q.has(t.name))return;let r=b(_(t.getConfigPath()),`settings.json`),i={};if(u(r))try{let e=f(r,`utf-8`);i=JSON.parse(e)}catch{console.log(` ${t.name}: skipped settings.json (invalid JSON)`);return}let a=!1;for(let[t,r]of Object.entries(e))if(typeof r==`object`&&r){let e=typeof i[t]==`object`&&i[t]!==null?i[t]:{},n={...e,...r};JSON.stringify(n)!==JSON.stringify(e)&&(i[t]=n,a=!0)}else (n||!(t in i))&&(i[t]=r,a=!0);a&&(g(r,`${JSON.stringify(i,null,2)}\n`,`utf-8`),console.log(` ${t.name}: updated settings.json`))}async function ee(e,t,n,f,p=!1){let h=new Map;for(let e of t)e.getScaffoldRoot()!==null&&h.set(e.id,e);if(t.some(e=>Q.has(e.name))){let e=J().find(e=>e.id===`copilot-cli`);e&&h.set(e.id,e)}if(h.size===0){console.log(` No IDEs with global scaffold support detected.`);return}let v=await a(e,`copilot`),y=new Map;for(let e of v){let t=e.path.indexOf(`/`);if(t===-1)continue;let n=e.path.substring(0,t);if(n!==`agents`&&n!==`prompts`)continue;let r=y.get(n)??[];r.push({path:e.path.substring(t+1),content:e.content}),y.set(n,r)}let x=await a(e,`skills`),S=new Set;for(let e of x){let t=e.path.indexOf(`/`);t!==-1&&S.add(e.path.substring(0,t))}let C=await a(e,`flows`),w=new Set;for(let e of C){let t=e.path.indexOf(`/`);t!==-1&&w.add(e.path.substring(0,t))}let T=new Set,E=new Set,D=new Set,O=(e,t,n)=>{let r=y.get(n);if(!e||!t||!r||r.length===0)return;let i=`${n}:${t}:${e}`;if(T.has(i))return;T.add(i);let a=o(t)??l(f);a.version=f,c(r,e,a,n,p),s(t,a),D.add(_(t))},k=(e,t,n,r)=>{if(!e||!t||r.length===0)return;let i=`${n}:${t}:${e}`;if(T.has(i))return;if(T.add(i),n===`flows`&&!E.has(e)){for(let n of w){let r=b(e,n,`skills`);u(r)&&(m(r,{recursive:!0,force:!0}),console.log(` ${_(t)}: migrated ${n} flow to steps/ layout`))}E.add(e)}let a=o(t)??l(f);a.version=f,c(r,e,a,n,p),s(t,a),D.add(_(t))};for(let e of h.values()){let t=e.getScaffoldPaths();O(t.agents,t.manifest,`agents`),O(t.prompts,t.manifest,`prompts`),k(t.skills,t.manifest,`skills`,x),k(t.flows,t.manifest,`flows`,C)}for(let e of D)console.log(` ${e}: scaffold updated (${S.size} skills)`);let A=new Set,j=r(`aikit`,n),M=i(`aikit`,n);for(let e of h.values()){let t=e.getScaffoldPaths().instructions;!t||A.has(t)||(d(_(t),{recursive:!0}),g(t,e.buildInstructionContent(j,M),`utf-8`),A.add(t))}A.size>0&&console.log(` Instruction files: ${[...A].join(`, `)}`)}function te(e){let t=[];for(let n of e){let e=n.getScaffoldRoot();if(e)if(Q.has(n.name)){let r=n.getInstructionsRoot()??e;t.push(b(r,`kb.instructions.md`)),t.push(b(r,`aikit.instructions.md`))}else n.name===`Cursor`||n.name===`Cursor Nightly`?t.push(b(e,`rules`,`kb.mdc`)):n.name===`Windsurf`&&t.push(b(e,`rules`,`kb.md`))}for(let e of t)u(e)&&(h(e),console.log(` Removed legacy file: ${e}`))}async function ne(e){let t=n,r=X(_(S(import.meta.url))),i=JSON.parse(f(b(r,`package.json`),`utf-8`)).version;console.log(`Initializing @vpxa/aikit v${i}...\n`);let a=O();d(a,{recursive:!0}),console.log(` Global data store: ${a}`),k({version:1,workspaces:{}}),console.log(` Created registry.json`);let o=await Y({scope:`user`});if(o.length===0)console.log(`
|
|
2
|
+
No supported IDEs detected. You can manually add the MCP server config.`);else{console.log(`\n Detected ${o.length} IDE(s):`);let n=Z();for(let e of o)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 o)$(t,e.force)}console.log(`
|
|
3
|
+
Installing scaffold files:`),await ee(r,o,t,i,e.force),te(o),console.log(`
|
|
4
|
+
User-level AI Kit installation complete!`),console.log(`
|
|
5
|
+
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`)}export{ne as initUser};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{t as e}from"./curated-manager-DX-_oJg0.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))}),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-C5IU9Lau.js`),import(`./dashboard-static-BfIe0Si1.js`),import(`./settings-static-BosGZSPf.js`),import(`./routes-0OCkdgRe.js`)]),l=t();d.info(`Config loaded`,{sourceCount:l.sources.length,storePath:l.store.path});let u=e();u.use(e.json());let f=Number(p.port);u.use((e,t,n)=>{if(t.setHeader(`Access-Control-Allow-Origin`,process.env.AIKIT_CORS_ORIGIN??`http://localhost:${f}`),t.setHeader(`Access-Control-Allow-Methods`,`GET, POST, PUT, PATCH, DELETE, OPTIONS`),t.setHeader(`Access-Control-Allow-Headers`,`Content-Type, Authorization`),e.method===`OPTIONS`){t.status(204).end();return}n()}),r(u,i(),d);let m=new Date().toISOString();u.use(`/settings/api`,s({log:d,mcpInfo:()=>({transport:`http`,port:f,pid:process.pid,startedAt:m})})),a(u,o(),d),u.get(`/health`,(e,t)=>{t.json({status:`ok`})});let h=!1,g=null,_=null,v=null,y=Promise.resolve();u.post(`/mcp`,async(e,t)=>{if(!h||!_||!v){t.status(503).json({jsonrpc:`2.0`,error:{code:-32603,message:`Server initializing — please retry in a few seconds`},id:null});return}let n=y,r;y=new Promise(e=>{r=e}),await n;try{let n=new v({sessionIdGenerator:void 0});await _.connect(n),await n.handleRequest(e,t,e.body),n.close()}catch(e){if(d.error(`MCP handler error`,c(e)),!t.headersSent){let n=e instanceof Error?e.message:String(e),r=n.includes(`Not Acceptable`);t.status(r?406:500).json({jsonrpc:`2.0`,error:{code:r?-32e3:-32603,message:r?n:`Internal server error`},id:null})}}finally{r()}}),u.get(`/mcp`,(e,t)=>{t.writeHead(405).end(JSON.stringify({jsonrpc:`2.0`,error:{code:-32e3,message:`Method not allowed.`},id:null}))}),u.delete(`/mcp`,(e,t)=>{t.writeHead(405).end(JSON.stringify({jsonrpc:`2.0`,error:{code:-32e3,message:`Method not allowed.`},id:null}))});let b=u.listen(f,`127.0.0.1`,()=>{d.info(`MCP server listening`,{url:`http://127.0.0.1:${f}/mcp`,port:f}),setTimeout(async()=>{try{let[{createLazyServer:e,ALL_TOOL_NAMES:t},{StreamableHTTPServerTransport:r},{checkForUpdates:i,autoUpgradeScaffold:a}]=await Promise.all([import(`./server-
|
|
1
|
+
import{t as e}from"./curated-manager-DX-_oJg0.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))}),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-C5IU9Lau.js`),import(`./dashboard-static-BfIe0Si1.js`),import(`./settings-static-BosGZSPf.js`),import(`./routes-0OCkdgRe.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-DG5jasWR.js`),import(`@modelcontextprotocol/sdk/server/streamableHttp.js`),import(`./version-check-AMfxaZUw.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.kb)throw Error(`AI Kit components are not available after initialization`);let{SmartIndexScheduler:e}=await import(`../../indexer/dist/index.js`);g=new e(s.kb.indexer,l,s.kb.store),g.start(),s.setSmartScheduler(g),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-C5IU9Lau.js`),import(`./server-DG5jasWR.js`),import(`./version-check-AMfxaZUw.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(()=>{d.info(`Auto-shutdown: no activity for 30 minutes — exiting`),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.kb)throw Error(`AI Kit components are not available after initialization`);let{SmartIndexScheduler:e}=await import(`../../indexer/dist/index.js`),t=new e(f.kb.indexer,l,f.kb.store);t.start(),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};
|
|
@@ -1230,7 +1230,7 @@ IMPORTANT: For charts, use the ChartValue format above. Do NOT use Chart.js form
|
|
|
1230
1230
|
- "browser": Serves a themed dashboard on a local URL. Use ONLY when you need user interaction back (confirmations, selections, form input). The tool blocks until user clicks an action button, then returns their selection.
|
|
1231
1231
|
FORMAT RULE: If no user interaction is needed → use "html". If you need user input back → use "browser".
|
|
1232
1232
|
CONTENT GUIDE: Pass typed blocks [{ type, title?, value }] for structured content. See the \`content\` parameter description for all supported block types and their value shapes. For charts: use {chartType, data:Record[], xKey, yKeys} — NOT Chart.js format.
|
|
1233
|
-
BROWSER WORKFLOW: After calling present with format "browser", you MUST extract the URL from the response and call openBrowserPage({ url }) tool - PlayWright MCP to open it in VS Code Simple Browser. A system browser fallback also opens automatically, but always call openBrowserPage tool - PlayWright MCP yourself.`,a=async({format:e,title:n,content:r,actions:i,template:a})=>{let o=lc(r);return(e??`html`)===`browser`||Array.isArray(i)&&i.length>0?await Kc(n,o,i,t,a):qc(n,o,i,a)};if(r){Vc||=(yn(e,`AI Kit Present App`,Lc,{description:`Rich interactive content viewer for AI Kit tools`},async()=>({contents:[{uri:Lc,mimeType:vn,text:r}]})),!0),bn(e,`present`,{title:n.title,description:i,annotations:n.annotations,inputSchema:zc,_meta:{ui:{resourceUri:Lc}}},a);return}e.tool(`present`,i,zc,n.annotations,a)}async function Kc(e,t,n,r,i){let a=Dc(e,t,{compactTables:!0}),o=Ec(e,t,n,i),s=wn({uri:`ui://aikit/present-browser.html`,content:{type:`rawHtml`,htmlString:o},encoding:`text`,adapters:{mcpApps:{enabled:!0}}}),c,l,u=Array.isArray(n)?n:[],d=``,f;try{Hc&&=(Hc.close(),null),u.length>0&&(c=new Promise(e=>{l=e}));let e=!1;d=await new Promise((t,n)=>{let r=Cn((t,n)=>{if(e||(e=!0,f&&clearTimeout(f)),t.method===`POST`&&t.url===`/callback`){let e=``;t.on(`data`,t=>{e+=t.toString()}),t.on(`end`,()=>{n.writeHead(200,{"Content-Type":`application/json`,"Access-Control-Allow-Origin":`*`}),n.end(`{"ok":true}`);try{let t=JSON.parse(e);l?.(t)}catch{}});return}if(t.method===`OPTIONS`){n.writeHead(204,{"Access-Control-Allow-Origin":`*`,"Access-Control-Allow-Methods":`POST`,"Access-Control-Allow-Headers":`Content-Type`}),n.end();return}n.writeHead(200,{"Content-Type":`text/html; charset=utf-8`}),n.end(o)});r.listen(0,`127.0.0.1`,()=>{let i=r.address();if(typeof i==`object`&&i){Hc=r;let n=`http://127.0.0.1:${i.port}`;f=setTimeout(()=>{if(!e)try{xn(process.platform===`win32`?`start "" "${n}"`:process.platform===`darwin`?`open "${n}"`:`xdg-open "${n}"`)}catch{}},8e3),f.unref(),t(n)}else n(Error(`Failed to start present server`))}),setTimeout(()=>{r.close(),Hc===r&&(Hc=null)},300*1e3).unref()})}catch{}let p=d?`${a}\n\n---\n🌐 **Dashboard opened in browser:** ${d}\n\n**IMPORTANT:** You MUST now open this URL using the \`openBrowserPage\` tool - PlayWright MCP. If that tool is unavailable, open the URL in the system browser as a fallback. If neither works, ask the user to open the URL manually.`:a;if(u.length>0&&r?.available&&c)try{let e=await Promise.race([c,new Promise((e,t)=>setTimeout(()=>t(Error(`timeout`)),300*1e3))]);return{content:[{type:`text`,text:`${p}\n\n✅ **Selected:** ${e.actionId} = \`${e.value}\``},s]}}catch{return{content:[{type:`text`,text:`${p}\n\n⚠️ *No selection received (timed out).*`},s]}}return{content:[{type:`text`,text:p},s]}}function qc(e,t,n,r){let i=Array.isArray(n)?n:[],a=Dc(e,t,{compactTables:!0}),o=wn({uri
|
|
1233
|
+
BROWSER WORKFLOW: After calling present with format "browser", you MUST extract the URL from the response and call openBrowserPage({ url }) tool - PlayWright MCP to open it in VS Code Simple Browser. A system browser fallback also opens automatically, but always call openBrowserPage tool - PlayWright MCP yourself.`,a=async({format:e,title:n,content:r,actions:i,template:a})=>{let o=lc(r);return(e??`html`)===`browser`||Array.isArray(i)&&i.length>0?await Kc(n,o,i,t,a):qc(n,o,i,a)};if(r){Vc||=(yn(e,`AI Kit Present App`,Lc,{description:`Rich interactive content viewer for AI Kit tools`},async()=>({contents:[{uri:Lc,mimeType:vn,text:r}]})),!0),bn(e,`present`,{title:n.title,description:i,annotations:n.annotations,inputSchema:zc,_meta:{ui:{resourceUri:Lc}}},a);return}e.tool(`present`,i,zc,n.annotations,a)}async function Kc(e,t,n,r,i){let a=Dc(e,t,{compactTables:!0}),o=Ec(e,t,n,i),s=wn({uri:`ui://aikit/present-browser.html`,content:{type:`rawHtml`,htmlString:o},encoding:`text`,adapters:{mcpApps:{enabled:!0}}}),c,l,u=Array.isArray(n)?n:[],d=``,f;try{Hc&&=(Hc.close(),null),u.length>0&&(c=new Promise(e=>{l=e}));let e=!1;d=await new Promise((t,n)=>{let r=Cn((t,n)=>{if(e||(e=!0,f&&clearTimeout(f)),t.method===`POST`&&t.url===`/callback`){let e=``;t.on(`data`,t=>{e+=t.toString()}),t.on(`end`,()=>{n.writeHead(200,{"Content-Type":`application/json`,"Access-Control-Allow-Origin":`*`}),n.end(`{"ok":true}`);try{let t=JSON.parse(e);l?.(t)}catch{}});return}if(t.method===`OPTIONS`){n.writeHead(204,{"Access-Control-Allow-Origin":`*`,"Access-Control-Allow-Methods":`POST`,"Access-Control-Allow-Headers":`Content-Type`}),n.end();return}n.writeHead(200,{"Content-Type":`text/html; charset=utf-8`}),n.end(o)});r.listen(0,`127.0.0.1`,()=>{let i=r.address();if(typeof i==`object`&&i){Hc=r;let n=`http://127.0.0.1:${i.port}`;f=setTimeout(()=>{if(!e)try{xn(process.platform===`win32`?`start "" "${n}"`:process.platform===`darwin`?`open "${n}"`:`xdg-open "${n}"`)}catch{}},8e3),f.unref(),t(n)}else n(Error(`Failed to start present server`))}),setTimeout(()=>{r.close(),Hc===r&&(Hc=null)},300*1e3).unref()})}catch{}let p=d?`${a}\n\n---\n🌐 **Dashboard opened in browser:** ${d}\n\n**IMPORTANT:** You MUST now open this URL using the \`openBrowserPage\` tool - PlayWright MCP. If that tool is unavailable, open the URL in the system browser as a fallback. If neither works, ask the user to open the URL manually.`:a;if(u.length>0&&r?.available&&c)try{let e=await Promise.race([c,new Promise((e,t)=>setTimeout(()=>t(Error(`timeout`)),300*1e3))]);return{content:[{type:`text`,text:`${p}\n\n✅ **Selected:** ${e.actionId} = \`${e.value}\``},s]}}catch{return{content:[{type:`text`,text:`${p}\n\n⚠️ *No selection received (timed out).*`},s]}}return{content:[{type:`text`,text:p},s]}}function qc(e,t,n,r){let i=Array.isArray(n)?n:[],a=Dc(e,t,{compactTables:!0}),o=wn({uri:Lc,content:{type:`rawHtml`,htmlString:Ec(e,t,n,r)},encoding:`text`,adapters:{mcpApps:{enabled:!0}}});return{content:[{type:`text`,text:a},o],structuredContent:{title:e,content:hc(t),actions:i}}}const Jc=D(`tools`);function Yc(e,t){let n=new mn({structure:new gn,dependencies:new dn,symbols:new _n,patterns:new hn,entryPoints:new pn,diagrams:new fn}),r=L(`produce_knowledge`);e.registerTool(`produce_knowledge`,{title:r.title,description:`Run automated codebase analysis and produce synthesis instructions. Executes Tier 1 deterministic analyzers, then returns structured baselines and instructions for you to synthesize knowledge using remember.`,inputSchema:{scope:P.string().optional().describe(`Root path to analyze (defaults to workspace root)`),aspects:P.array(P.enum([`all`,`structure`,`dependencies`,`symbols`,`patterns`,`entry-points`,`diagrams`])).default([`all`]).describe(`Which analysis aspects to run`)},annotations:r.annotations},async({scope:e,aspects:r})=>{try{let i=e??`.`;Jc.info(`Running knowledge production`,{rootPath:i,aspects:r});let a=await n.runExtraction(i,r);try{let e=t?.onboardDir??g(i,`.ai`,`context`);o(e,{recursive:!0});let n=`<!-- Generated by produce_knowledge at ${new Date().toISOString()} -->\n\n`;for(let[t,r]of Object.entries(a))r&&typeof r==`string`&&f(g(e,`${t}.md`),n+r,`utf-8`);Jc.info(`Knowledge persisted to .ai/context/`,{files:Object.keys(a).length})}catch(e){Jc.warn(`Failed to persist knowledge to .ai/context/`,{error:A(e)})}return{content:[{type:`text`,text:n.buildSynthesisInstructions(a,r)+`
|
|
1234
1234
|
|
|
1235
1235
|
---
|
|
1236
1236
|
_Next: Review the baselines above and use \`remember\` to store synthesized knowledge entries._`}]}}catch(e){return Jc.error(`Knowledge production failed`,A(e)),B(`INTERNAL`,`Knowledge production failed: ${e instanceof Error?e.message:String(e)}`)}})}const Xc=D(`tools`);function Zc(e,t){let n=L(`read`);e.registerTool(`read`,{title:n.title,description:`Read the full content of a specific curated knowledge entry by its path. Use list first to discover available entries.`,inputSchema:{path:P.string().describe(`Relative path within .ai/curated/ (e.g., "decisions/use-lancedb.md")`)},annotations:n.annotations},async({path:e})=>{try{let n=await t.read(e),r=[`## ${n.title}`,`- **Path**: .ai/curated/${e}`,`- **Category**: ${n.category}`,n.tags.length?`- **Tags**: ${n.tags.join(`, `)}`:null,`- **Version**: ${n.version}`,`- **Created**: ${n.created}`,n.updated===n.created?null:`- **Updated**: ${n.updated}`,``].filter(e=>e!==null).join(`
|
|
@@ -1,9 +1,65 @@
|
|
|
1
|
-
const e={Orchestrator:{title:`The Master Conductor`,description:`Master conductor that orchestrates the full development lifecycle: Planning → Implementation → Review → Recovery → Commit`,argumentHint:null,toolRole:`orchestrator`,sharedBase:null,sharedProtocols:[`decision-protocol`,`forge-protocol`],category:`orchestration`,skills:[]},Planner:{title:`The Strategic Architect`,description:`Autonomous planner that researches codebases and writes comprehensive TDD implementation plans`,argumentHint:null,toolRole:`planner`,sharedBase:`code-agent-base`,category:`orchestration`},Implementer:{title:`The Code Builder`,description:`Persistent implementation agent that writes code following TDD practices until all tasks are complete`,argumentHint:`Implementation task, feature, or phase from plan`,toolRole:`codeAgent`,sharedBase:`code-agent-base`,category:`implementation`,skills:[[`aikit`,`**Always** — AI Kit tool signatures, search, analysis`],[`typescript`,`When writing TypeScript code — type patterns, generics, utility types`]]},Frontend:{title:`The UI Specialist`,description:`UI/UX specialist for React, styling, responsive design, and frontend implementation`,argumentHint:`UI component, styling task, or frontend feature`,toolRole:`codeAgent`,sharedBase:`code-agent-base`,category:`implementation`,skills:[[`aikit`,`**Always** — AI Kit tool signatures, search, analysis`],[`react`,`When building React components — hooks, patterns, Server Components`],[`typescript`,`When writing TypeScript code — type patterns, generics, utility types`],[`frontend-design`,`When implementing UI/UX — design systems, accessibility, responsive patterns`]]},Refactor:{title:`The Code Sculptor`,description:`Code refactoring specialist that improves structure, readability, and maintainability`,argumentHint:`Code, component, or pattern to refactor`,toolRole:`refactor`,sharedBase:`code-agent-base`,category:`implementation`,skills:[[`aikit`,`**Always** — AI Kit tool signatures, search, analysis`]]},Debugger:{title:`The Problem Solver`,description:`Expert debugger that diagnoses issues, traces errors, and provides solutions`,argumentHint:`Error message, stack trace, or description of issue`,toolRole:`debugger`,sharedBase:`code-agent-base`,category:`diagnostics`,skills:[[`aikit`,`**Always** — AI Kit tool signatures, search, analysis`],[`typescript`,`When writing TypeScript code — type patterns, generics, utility types`]]},Security:{title:`The Vulnerability Hunter`,description:`Security specialist that analyzes code for vulnerabilities and compliance`,argumentHint:`Code, feature, or component to security review`,toolRole:`security`,sharedBase:`code-agent-base`,category:`diagnostics`,skills:[[`aikit`,`**Always** — AI Kit tool signatures, search, analysis`],[`typescript`,`When reviewing code — security patterns, type safety`]]},Documenter:{title:`The Knowledge Keeper`,description:`Documentation specialist that creates and maintains comprehensive project documentation`,argumentHint:`Component, API, feature, or area to document`,toolRole:`documenter`,sharedBase:`code-agent-base`,category:`documentation`,skills:[[`aikit`,`**Always** — AI Kit tool signatures, search, analysis`],[`present`,`When presenting documentation previews or architecture visuals to the user`],[`docs`,`When creating or updating project documentation — docs/ convention, architecture blueprints, Diátaxis framework`]]},Explorer:{title:`The Rapid Scout`,description:`Rapid codebase exploration to find files, usages, dependencies, and structural context`,argumentHint:`Find files, usages, and context related to: {topic or goal}`,toolRole:`explorer`,sharedBase:null,category:`exploration`,skills:[[`aikit`,`**Always** — AI Kit tool signatures, search, analysis`]]},Researcher:{title:`The Context Gatherer`,description:`Deep analysis, architecture review, and multi-model decision protocol participant`,argumentHint:`Research question, problem statement, or subsystem to investigate`,toolRole:`researcher`,sharedBase:`researcher-base`,category:`research`,skills:[[`aikit`,`**Always** — AI Kit tool signatures, search, analysis`],[`lesson-learned`,`When analyzing past changes to extract engineering principles`],[`c4-architecture`,`When researching system architecture — produce C4 diagrams`],[`adr-skill`,`When the research involves a technical decision — draft an ADR`]],variants:{Alpha:{description:`Primary deep research agent — also serves as default Researcher`,identity:`, the primary deep research agent. During multi-model decision sessions, you provide deep reasoning and nuanced system design.`,bodyAddendum:`## Required Output Section — \`## Depth Analysis\`
|
|
1
|
+
const e={Orchestrator:{title:`The Master Conductor`,description:`Master conductor that orchestrates the full development lifecycle: Planning → Implementation → Review → Recovery → Commit`,argumentHint:null,toolRole:`orchestrator`,sharedBase:null,sharedProtocols:[`decision-protocol`,`forge-protocol`],category:`orchestration`,skills:[]},Planner:{title:`The Strategic Architect`,description:`Autonomous planner that researches codebases and writes comprehensive TDD implementation plans`,argumentHint:null,toolRole:`planner`,sharedBase:`code-agent-base`,category:`orchestration`},Implementer:{title:`The Code Builder`,description:`Persistent implementation agent that writes code following TDD practices until all tasks are complete`,argumentHint:`Implementation task, feature, or phase from plan`,toolRole:`codeAgent`,sharedBase:`code-agent-base`,category:`implementation`,skills:[[`aikit`,`**Always** — AI Kit tool signatures, search, analysis`],[`typescript`,`When writing TypeScript code — type patterns, generics, utility types`]]},Frontend:{title:`The UI Specialist`,description:`UI/UX specialist for React, styling, responsive design, and frontend implementation`,argumentHint:`UI component, styling task, or frontend feature`,toolRole:`codeAgent`,sharedBase:`code-agent-base`,category:`implementation`,skills:[[`aikit`,`**Always** — AI Kit tool signatures, search, analysis`],[`react`,`When building React components — hooks, patterns, Server Components`],[`typescript`,`When writing TypeScript code — type patterns, generics, utility types`],[`frontend-design`,`When implementing UI/UX — design systems, accessibility, responsive patterns`]]},Refactor:{title:`The Code Sculptor`,description:`Code refactoring specialist that improves structure, readability, and maintainability`,argumentHint:`Code, component, or pattern to refactor`,toolRole:`refactor`,sharedBase:`code-agent-base`,category:`implementation`,skills:[[`aikit`,`**Always** — AI Kit tool signatures, search, analysis`]]},Debugger:{title:`The Problem Solver`,description:`Expert debugger that diagnoses issues, traces errors, and provides solutions`,argumentHint:`Error message, stack trace, or description of issue`,toolRole:`debugger`,sharedBase:`code-agent-base`,category:`diagnostics`,skills:[[`aikit`,`**Always** — AI Kit tool signatures, search, analysis`],[`typescript`,`When writing TypeScript code — type patterns, generics, utility types`]]},Security:{title:`The Vulnerability Hunter`,description:`Security specialist that analyzes code for vulnerabilities and compliance`,argumentHint:`Code, feature, or component to security review`,toolRole:`security`,sharedBase:`code-agent-base`,category:`diagnostics`,skills:[[`aikit`,`**Always** — AI Kit tool signatures, search, analysis`],[`typescript`,`When reviewing code — security patterns, type safety`]]},Documenter:{title:`The Knowledge Keeper`,description:`Documentation specialist that creates and maintains comprehensive project documentation`,argumentHint:`Component, API, feature, or area to document`,toolRole:`documenter`,sharedBase:`code-agent-base`,category:`documentation`,skills:[[`aikit`,`**Always** — AI Kit tool signatures, search, analysis`],[`present`,`When presenting documentation previews or architecture visuals to the user`],[`docs`,`When creating or updating project documentation — docs/ convention, architecture blueprints, Diátaxis framework`]]},Explorer:{title:`The Rapid Scout`,description:`Rapid codebase exploration to find files, usages, dependencies, and structural context`,argumentHint:`Find files, usages, and context related to: {topic or goal}`,toolRole:`explorer`,sharedBase:null,category:`exploration`,skills:[[`aikit`,`**Always** — AI Kit tool signatures, search, analysis`]]},Researcher:{title:`The Context Gatherer`,description:`Deep analysis, architecture review, and multi-model decision protocol participant`,argumentHint:`Research question, problem statement, or subsystem to investigate`,toolRole:`researcher`,sharedBase:`researcher-base`,category:`research`,skills:[[`aikit`,`**Always** — AI Kit tool signatures, search, analysis`],[`lesson-learned`,`When analyzing past changes to extract engineering principles`],[`c4-architecture`,`When researching system architecture — produce C4 diagrams`],[`adr-skill`,`When the research involves a technical decision — draft an ADR`]],variants:{Alpha:{description:`Primary deep research agent — also serves as default Researcher`,identity:`, the primary deep research agent. During multi-model decision sessions, you provide deep reasoning and nuanced system design. Your thinking style is **Contrarian** — actively look for flaws, fatal assumptions, and hidden risks in every approach. The best ideas survive adversarial pressure.`,bodyAddendum:`## Required Output Section — \`## Depth Analysis\`
|
|
2
2
|
|
|
3
3
|
Your final report MUST contain a \`## Depth Analysis\` section with:
|
|
4
4
|
- Deep-dive into ONE chosen subsystem (most structurally central to the question)
|
|
5
5
|
- Full evidence chain: file:line citations for every structural claim
|
|
6
6
|
- At least 2 \`compact\`/\`file_summary\` extracts woven into the narrative
|
|
7
7
|
|
|
8
|
+
## Thinking Style: Contrarian
|
|
9
|
+
|
|
10
|
+
During multi-model decision sessions, apply the **Contrarian** lens:
|
|
11
|
+
- For every proposed approach, actively seek the fatal flaw or hidden assumption
|
|
12
|
+
- Ask: "Under what conditions does this approach fail catastrophically?"
|
|
13
|
+
- Prefer uncomfortable truths over comfortable consensus
|
|
14
|
+
|
|
8
15
|
You are the DEFAULT researcher. When the Orchestrator needs breadth + depth, they
|
|
9
|
-
dispatch you alone. Your lens: thorough, evidence-first, exhaustive.`},Beta:{description:`Research variant — pragmatic analysis with focus on trade-offs and edge cases`,identity:`, a variant of the Researcher agent optimized for **pragmatic analysis**. Focus on trade-offs, edge cases, and practical constraints. Challenge assumptions and highlight risks the primary researcher may overlook
|
|
16
|
+
dispatch you alone. Your lens: thorough, evidence-first, exhaustive + contrarian.`},Beta:{description:`Research variant — pragmatic analysis with focus on trade-offs and edge cases`,identity:`, a variant of the Researcher agent optimized for **pragmatic analysis**. Focus on trade-offs, edge cases, and practical constraints. Challenge assumptions and highlight risks the primary researcher may overlook. Your thinking style is **First Principles** — strip away assumptions, decompose to ground truths, and rebuild reasoning from scratch.`,bodyAddendum:`## Required Output Section — \`## Failure Modes & Counter-Evidence\`
|
|
17
|
+
|
|
18
|
+
Your final report MUST contain a \`## Failure Modes & Counter-Evidence\` section with:
|
|
19
|
+
- At least 3 adversarial claims challenging your own primary finding
|
|
20
|
+
- For each counter-claim: the condition under which it would be TRUE, and the
|
|
21
|
+
evidence (file:line or search receipt) that currently falsifies it
|
|
22
|
+
- Any unresolved counter-evidence flagged as \`⚠ UNRESOLVED\`
|
|
23
|
+
|
|
24
|
+
## Thinking Style: First Principles
|
|
25
|
+
|
|
26
|
+
During multi-model decision sessions, apply the **First Principles** lens:
|
|
27
|
+
- Strip every assumption: "Is this truly required, or just inherited convention?"
|
|
28
|
+
- Decompose to ground truths, then rebuild the reasoning from scratch
|
|
29
|
+
- If the current approach exists only because "that's how it's always been done", flag it
|
|
30
|
+
|
|
31
|
+
Your lens: pragmatic skepticism + first principles. Mark competing claims as \`A\` (Assumed)
|
|
32
|
+
by default; challenge before promoting to \`V\`.`},Gamma:{description:`Research variant — broad pattern matching across domains and technologies`,identity:`, a variant of the Researcher agent optimized for **cross-domain pattern matching**. Draw connections from other domains, frameworks, and industries. Bring breadth where Alpha brings depth. Your thinking style is **Expansionist** — look for the bigger opportunity, find what's undervalued, and identify patterns others dismiss.`,bodyAddendum:`## Required Output Section — \`## Cross-Domain Analogies\`
|
|
33
|
+
|
|
34
|
+
Your final report MUST contain a \`## Cross-Domain Analogies\` section with:
|
|
35
|
+
- At least 2 patterns from other tools/frameworks/domains that apply to the question
|
|
36
|
+
- For each: the external source (cite via \`web_search\` or \`web_fetch\` receipt) and
|
|
37
|
+
how it maps to our codebase
|
|
38
|
+
- One "missing pattern we should adopt" recommendation
|
|
39
|
+
|
|
40
|
+
## Thinking Style: Expansionist
|
|
41
|
+
|
|
42
|
+
During multi-model decision sessions, apply the **Expansionist** lens:
|
|
43
|
+
- Ask: "What's the bigger opportunity everyone else is ignoring?"
|
|
44
|
+
- Seek undervalued approaches and non-obvious connections across domains
|
|
45
|
+
- Challenge narrow framing: "Is this really just an X problem, or is it also a Y problem?"
|
|
46
|
+
|
|
47
|
+
Your lens: cross-domain pattern matching + expansionist. Weight \`web_search\` + \`web_fetch\`
|
|
48
|
+
higher than peers. Assume the LLM's training data is stale — verify with fresh searches.`},Delta:{description:`Research variant — implementation feasibility and performance implications`,identity:`, a variant of the Researcher agent optimized for **implementation feasibility**. Focus on performance implications, scaling concerns, and concrete implementation paths. Ground theoretical proposals in practical reality. Your thinking style is **Executor** — focus on what can actually be built, the fastest path to value, and real-world constraints.`,bodyAddendum:`## Required Output Section — \`## Implementation Cost & Feasibility\`
|
|
49
|
+
|
|
50
|
+
Your final report MUST contain a \`## Implementation Cost & Feasibility\` section with:
|
|
51
|
+
- Complexity snapshot: you MUST call \`measure({ path })\` on any file ≥ 50 LOC in the
|
|
52
|
+
target subsystem at least once and quote the \`cognitiveComplexity\` result
|
|
53
|
+
- Blast radius estimate: \`blast_radius({ changed_files })\` on the proposed edits
|
|
54
|
+
- Time/risk table: | Change | Lines | Risk | Effort |
|
|
55
|
+
- Feasibility verdict: SAFE / RISKY / INFEASIBLE with one-line justification
|
|
56
|
+
|
|
57
|
+
## Thinking Style: Executor
|
|
58
|
+
|
|
59
|
+
During multi-model decision sessions, apply the **Executor** lens:
|
|
60
|
+
- Ask: "Can this actually be built? What's the fastest path to a working version?"
|
|
61
|
+
- Ground every proposal in concrete effort: lines of code, files changed, risk
|
|
62
|
+
- Reject elegant theory that can't survive contact with the codebase
|
|
63
|
+
|
|
64
|
+
Your lens: implementation feasibility + executor. Prefer \`measure\` + \`blast_radius\` +
|
|
65
|
+
\`analyze_patterns\` over abstract reasoning.`}}},"Code-Reviewer":{title:`The Quality Guardian`,description:`Code review specialist analyzing code for quality, security, performance, and maintainability`,argumentHint:`File path, PR, or code to review`,toolRole:`reviewer`,sharedBase:`code-reviewer-base`,category:`review`,skills:[[`aikit`,`**Always** — AI Kit tool signatures, search, analysis`],[`typescript`,`When reviewing TypeScript code — type patterns, best practices`]],variants:{Alpha:{description:`Primary code reviewer`},Beta:{description:`Code reviewer variant — different LLM perspective for dual review`}}},"Architect-Reviewer":{title:`The Structural Guardian`,description:`Reviews architecture for pattern adherence, SOLID compliance, dependency direction, and structural integrity`,argumentHint:`Files, PR, or subsystem to architecture-review`,toolRole:`reviewer`,sharedBase:`architect-reviewer-base`,category:`review`,skills:[[`aikit`,`**Always** — AI Kit tool signatures, search, analysis`],[`c4-architecture`,`When reviewing architectural diagrams or boundary changes`],[`adr-skill`,`When the review involves architecture decisions — reference or create ADRs`]],extraBody:`You are **not** the Code-Reviewer agent. Code-Reviewer handles correctness, testing, security, and code quality. You handle the big picture: service boundaries, dependency direction, pattern adherence, and structural health.`,variants:{Alpha:{description:`Primary architecture reviewer`},Beta:{description:`Architecture reviewer variant — different LLM perspective for dual review`}}}};export{e as AGENTS};
|
|
@@ -67,6 +67,21 @@ For EACH step in the active flow:
|
|
|
67
67
|
|
|
68
68
|
**Custom flows work identically** — \`flow_list\` returns them alongside builtins. The execution loop is the same for ALL flows.
|
|
69
69
|
|
|
70
|
+
### Design & Decision Detection (applies to ALL flows including custom)
|
|
71
|
+
|
|
72
|
+
When executing ANY flow step (builtin or custom), detect if the step involves design or decision work:
|
|
73
|
+
|
|
74
|
+
**Detection signals** (in step name, description, or instruction content):
|
|
75
|
+
- Keywords: design, brainstorm, architecture, decision, approach, strategy, RFC, ADR, trade-off, alternatives, options
|
|
76
|
+
- Step asks to "choose between", "evaluate options", "propose approaches", or "make a decision"
|
|
77
|
+
|
|
78
|
+
**When detected, ALWAYS:**
|
|
79
|
+
1. Load the \`brainstorming\` skill — use it for requirements discovery and creative exploration
|
|
80
|
+
2. Apply the **Multi-Model Decision Protocol** (inlined below under "Multi-Model Decision Protocol") for any non-trivial technical decisions
|
|
81
|
+
3. This applies equally to builtin flows, custom flows, and any future flow — no exceptions
|
|
82
|
+
|
|
83
|
+
Custom flows are NOT expected to reference these protocols in their step instructions. The Orchestrator injects them automatically based on step content detection.
|
|
84
|
+
|
|
70
85
|
### Flow Completion & Cleanup
|
|
71
86
|
|
|
72
87
|
Flows MUST be driven to completion. A flow left active forever blocks future work.
|
|
@@ -287,7 +302,7 @@ Before every tool call, verify:
|
|
|
287
302
|
|-------|--------------|
|
|
288
303
|
| \`multi-agents-development\` | **Before any delegation** — task decomposition, dispatch templates, review pipeline, recovery patterns |
|
|
289
304
|
| \`present\` | When presenting plans, findings, or visual content to the user — dashboards, tables, charts, timelines |
|
|
290
|
-
| \`brainstorming\` | When
|
|
305
|
+
| \`brainstorming\` | When ANY flow step (builtin or custom) involves design, brainstorming, or creative work — auto-detected by Orchestrator. Pairs with the Multi-Model Decision Protocol for technical decisions |
|
|
291
306
|
| \`session-handoff\` | Context filling up, session ending, or major milestone |
|
|
292
307
|
| \`lesson-learned\` | After completing work — extract engineering principles |
|
|
293
308
|
| \`docs\` | During \`_docs-sync\` epilogue — living documentation convention, templates, change-to-doc mapping |
|
|
@@ -117,7 +117,7 @@ If the flow's changes don't warrant doc updates (e.g., pure bug fix with no reve
|
|
|
117
117
|
- [ ] \`docs/\` bootstrapped with tool outputs if it didn't exist
|
|
118
118
|
- [ ] Relevant docs created or updated (or skipped with reason)
|
|
119
119
|
- [ ] \`docs/README.md\` index is current
|
|
120
|
-
- [ ] No placeholder/empty docs created — all content tool-generated or hand-written with purpose`}],"aikit-advanced":[{file:`README.md`,content:"# aikit:advanced — Full Development Flow\n\nFull development flow for **new features, API design, and architecture changes**.\n\n## Steps\n\n| # | Step | Skill | Produces | Requires | Agents |\n|---|------|-------|----------|----------|--------|\n| 1 | **Design Gate** | `steps/design/README.md` | `design-decisions.md` | — | Researcher-Alpha/Beta/Gamma/Delta |\n| 2 | **Specification** | `steps/spec/README.md` | `spec.md` | `design-decisions.md` | Researcher-Alpha |\n| 3 | **Planning** | `steps/plan/README.md` | `plan.md` | `spec.md` | Planner, Explorer |\n| 4 | **Task Breakdown** | `steps/task/README.md` | `tasks.md` | `plan.md` | Planner, Architect-Reviewer-Alpha |\n| 5 | **Execution** | `steps/execute/README.md` | `progress.md` | `tasks.md` | Orchestrator, Implementer, Frontend, Refactor |\n| 6 | **Verification** | `steps/verify/README.md` | `verify-report.md` | `progress.md` | Code-Reviewer-Alpha/Beta, Architect-Reviewer-Alpha/Beta, Security |\n\n## How It Works\n\nEach step has a **README.md** file that contains the detailed instructions for the agent(s) executing that step. The Orchestrator reads the README.md via `flow_read_instruction` and delegates work accordingly.\n\n### Step 1: Design Gate\n- Full brainstorming session for new features and architectural changes\n- FORGE classification (`forge_classify`) + grounding (`forge_ground`) for complex tasks\n-
|
|
120
|
+
- [ ] No placeholder/empty docs created — all content tool-generated or hand-written with purpose`}],"aikit-advanced":[{file:`README.md`,content:"# aikit:advanced — Full Development Flow\n\nFull development flow for **new features, API design, and architecture changes**.\n\n## Steps\n\n| # | Step | Skill | Produces | Requires | Agents |\n|---|------|-------|----------|----------|--------|\n| 1 | **Design Gate** | `steps/design/README.md` | `design-decisions.md` | — | Researcher-Alpha/Beta/Gamma/Delta |\n| 2 | **Specification** | `steps/spec/README.md` | `spec.md` | `design-decisions.md` | Researcher-Alpha |\n| 3 | **Planning** | `steps/plan/README.md` | `plan.md` | `spec.md` | Planner, Explorer |\n| 4 | **Task Breakdown** | `steps/task/README.md` | `tasks.md` | `plan.md` | Planner, Architect-Reviewer-Alpha |\n| 5 | **Execution** | `steps/execute/README.md` | `progress.md` | `tasks.md` | Orchestrator, Implementer, Frontend, Refactor |\n| 6 | **Verification** | `steps/verify/README.md` | `verify-report.md` | `progress.md` | Code-Reviewer-Alpha/Beta, Architect-Reviewer-Alpha/Beta, Security |\n\n## How It Works\n\nEach step has a **README.md** file that contains the detailed instructions for the agent(s) executing that step. The Orchestrator reads the README.md via `flow_read_instruction` and delegates work accordingly.\n\n### Step 1: Design Gate\n- Full brainstorming session for new features and architectural changes\n- FORGE classification (`forge_classify`) + grounding (`forge_ground`) for complex tasks\n- Full 3-phase multi-model decision protocol for non-trivial technical decisions (see Orchestrator's inlined Multi-Model Decision Protocol)\n- ADR generation for critical-tier tasks\n- **Mandatory user stop** before proceeding — design decisions must be approved\n- Read `steps/design/README.md` for the full protocol\n\n### Step 2: Specification\n- Elicit requirements from the user, clarify scope\n- Define acceptance criteria and constraints\n- Build on design decisions from the previous step\n\n### Step 3: Planning\n- Deep codebase analysis using `search`, `scope_map`, `trace`, `analyze_*`\n- Design architecture based on spec and design decisions\n- Create comprehensive implementation plan with file-level changes\n\n### Step 4: Task Breakdown\n- Break the plan into ordered, atomic implementation tasks\n- Define dependencies between tasks\n- Identify parallel batches for multi-agent execution\n- Architecture review of the task structure\n\n### Step 5: Execution\n- Orchestrator dispatches agents in parallel batches per the task breakdown\n- Each agent gets a scoped task (1-3 files) with clear acceptance criteria\n- TDD: write tests first, then implement\n- Per-batch review cycle: Code Review (dual) → Arch Review → Security → Evidence Gate\n\n### Step 6: Verification\n- Dual code review (Code-Reviewer-Alpha + Beta)\n- Architecture review (Architect-Reviewer-Alpha + Beta)\n- Security review\n- Run `check({})` + `test_run({})` + `blast_radius({})`\n- `evidence_map({ action: \"gate\" })` for final quality gate\n\n## Using Skills Inside Steps\n\nWhen the Orchestrator activates a step:\n\n1. **Read the instruction first** — `flow_read_instruction` returns the README.md for the current step\n2. **Follow step instructions** — the README.md is the primary guide for what to do\n3. **Delegate to listed agents** — each step lists which agents are appropriate\n4. **Produce the required artifact** — the step's `produces` field specifies what file to create in the artifacts directory\n5. **Check dependencies** — the step's `requires` field lists artifacts from previous steps that must exist\n6. **Report status** — agents report `DONE` | `DONE_WITH_CONCERNS` | `NEEDS_CONTEXT` | `BLOCKED` to the Orchestrator\n\n## Artifacts\n\nAll artifacts are stored in the run directory under `.flows/{topic}/`. The template variable `{{artifacts_path}}` resolves to the actual path at runtime.\n"},{file:`steps/design/README.md`,content:`# Design Gate — Advanced Flow
|
|
121
121
|
|
|
122
122
|
Full design gate for new features, API design, and architecture changes. Runs brainstorming, decision protocol, and FORGE classification before specification begins.
|
|
123
123
|
|
|
@@ -164,16 +164,19 @@ For **Critical** tier tasks, also explore:
|
|
|
164
164
|
|
|
165
165
|
### 4. Decision Protocol (Standard & Critical tiers)
|
|
166
166
|
|
|
167
|
-
When technical decisions need resolution
|
|
167
|
+
When technical decisions need resolution, follow the **3-phase multi-model decision protocol**:
|
|
168
168
|
|
|
169
169
|
1. **Identify decisions** — List each decision point with 2+ viable options
|
|
170
|
-
2. **
|
|
171
|
-
- Researcher-Alpha: Deep analysis
|
|
172
|
-
- Researcher-Beta: Trade-offs and edge cases
|
|
173
|
-
- Researcher-Gamma: Cross-domain patterns
|
|
174
|
-
- Researcher-Delta: Feasibility
|
|
175
|
-
3. **
|
|
176
|
-
4. **
|
|
170
|
+
2. **Phase 1 — Independent Research** — Launch ALL 4 Researcher variants in parallel:
|
|
171
|
+
- Researcher-Alpha (Contrarian): Deep analysis, actively seeks fatal flaws
|
|
172
|
+
- Researcher-Beta (First Principles): Trade-offs and edge cases, strips assumptions
|
|
173
|
+
- Researcher-Gamma (Expansionist): Cross-domain patterns, undervalued opportunities
|
|
174
|
+
- Researcher-Delta (Executor): Feasibility, performance, fastest implementation path
|
|
175
|
+
3. **Phase 2 — Peer Review** — Anonymize outputs as Perspective A/B/C/D, launch 4 reviewers in parallel asking: strongest argument, biggest blind spot, consensus gap, verdict
|
|
176
|
+
4. **Phase 3 — Structured Verdict** — Synthesize into: Where Agrees / Where Clashes / Blind Spots Caught / Recommendation (with confidence) / First Step
|
|
177
|
+
5. **Present & Record** — Render verdict with \`present\`, produce ADR via \`adr-skill\`
|
|
178
|
+
|
|
179
|
+
**Floor tier shortcut**: Skip Phase 2 (peer review), go straight from research to verdict.
|
|
177
180
|
|
|
178
181
|
### 5. FORGE Ground (Standard & Critical tiers)
|
|
179
182
|
|
|
@@ -951,7 +954,7 @@ Before completing this step, persist important findings using \`remember()\`:
|
|
|
951
954
|
- **Session checkpoint**: Summarize what was accomplished, decisions made, and any remaining work
|
|
952
955
|
|
|
953
956
|
**Every step produces knowledge worth preserving.** If you discovered something that would help a future session, call \`remember()\` now.
|
|
954
|
-
`}],"aikit-basic":[{file:`README.md`,content:"# aikit:basic — Quick Development Flow\n\nQuick development flow for **bug fixes, small features, and refactoring**.\n\n## Steps\n\n| # | Step | Skill | Produces | Requires | Agents |\n|---|------|-------|----------|----------|--------|\n| 1 | **Design Gate** | `steps/design/README.md` | `design-decisions.md` | — | Researcher-Alpha/Beta/Gamma/Delta |\n| 2 | **Assessment** | `steps/assess/README.md` | `assessment.md` | `design-decisions.md` | Explorer, Researcher-Alpha |\n| 3 | **Implementation** | `steps/implement/README.md` | `progress.md` | `assessment.md` | Implementer, Frontend |\n| 4 | **Verification** | `steps/verify/README.md` | `verify-report.md` | `progress.md` | Code-Reviewer-Alpha, Security |\n\n## How It Works\n\nEach step has a **README.md** file that contains the detailed instructions for the agent(s) executing that step. The Orchestrator reads the README.md via `flow_read_instruction` and delegates work accordingly.\n\n### Step 1: Design Gate\n- **Auto-skips** for bug fixes and refactors (produces a minimal `design-decisions.md` noting it was skipped)\n- For small features: runs quick brainstorming, FORGE classification, and optional decision protocol\n- Read `steps/design/README.md` for the full decision tree\n\n### Step 2: Assessment\n- Explore the codebase to understand scope and impact\n- Use `search`, `scope_map`, `file_summary`, `compact` to gather context\n- Identify the approach and produce `assessment.md`\n\n### Step 3: Implementation\n- Write code following the assessment plan\n- The Orchestrator dispatches Implementer/Frontend agents with specific file scopes\n- Follow TDD practices where applicable\n\n### Step 4: Verification\n- Code review, test execution, security check\n- Run `check({})` + `test_run({})` + `blast_radius({})`\n- Produce `verify-report.md` with findings\n\n## Using Skills Inside Steps\n\nWhen the Orchestrator activates a step:\n\n1. **Read the instruction first** — `flow_read_instruction` returns the README.md for the current step\n2. **Follow step instructions** — the README.md is the primary guide for what to do\n3. **Delegate to listed agents** — each step lists which agents are appropriate\n4. **Produce the required artifact** — the step's `produces` field specifies what file to create in the artifacts directory\n5. **Check dependencies** — the step's `requires` field lists artifacts from previous steps that must exist\n6. **Report status** — agents report `DONE` | `DONE_WITH_CONCERNS` | `NEEDS_CONTEXT` | `BLOCKED` to the Orchestrator\n\n## Artifacts\n\nAll artifacts are stored in the run directory under `.flows/{topic}/`. The template variable `{{artifacts_path}}` resolves to the actual path at runtime.\n"},{file:`steps/assess/README.md`,content:`---
|
|
957
|
+
`}],"aikit-basic":[{file:`README.md`,content:"# aikit:basic — Quick Development Flow\n\nQuick development flow for **bug fixes, small features, and refactoring**.\n\n## Steps\n\n| # | Step | Skill | Produces | Requires | Agents |\n|---|------|-------|----------|----------|--------|\n| 1 | **Design Gate** | `steps/design/README.md` | `design-decisions.md` | — | Researcher-Alpha/Beta/Gamma/Delta |\n| 2 | **Assessment** | `steps/assess/README.md` | `assessment.md` | `design-decisions.md` | Explorer, Researcher-Alpha |\n| 3 | **Implementation** | `steps/implement/README.md` | `progress.md` | `assessment.md` | Implementer, Frontend |\n| 4 | **Verification** | `steps/verify/README.md` | `verify-report.md` | `progress.md` | Code-Reviewer-Alpha, Security |\n\n## How It Works\n\nEach step has a **README.md** file that contains the detailed instructions for the agent(s) executing that step. The Orchestrator reads the README.md via `flow_read_instruction` and delegates work accordingly.\n\n### Step 1: Design Gate\n- **Auto-skips** for bug fixes and refactors (produces a minimal `design-decisions.md` noting it was skipped)\n- For small features: runs quick brainstorming, FORGE classification, and optional decision protocol (see Orchestrator's inlined Multi-Model Decision Protocol for the full 3-phase process)\n- Read `steps/design/README.md` for the full decision tree\n\n### Step 2: Assessment\n- Explore the codebase to understand scope and impact\n- Use `search`, `scope_map`, `file_summary`, `compact` to gather context\n- Identify the approach and produce `assessment.md`\n\n### Step 3: Implementation\n- Write code following the assessment plan\n- The Orchestrator dispatches Implementer/Frontend agents with specific file scopes\n- Follow TDD practices where applicable\n\n### Step 4: Verification\n- Code review, test execution, security check\n- Run `check({})` + `test_run({})` + `blast_radius({})`\n- Produce `verify-report.md` with findings\n\n## Using Skills Inside Steps\n\nWhen the Orchestrator activates a step:\n\n1. **Read the instruction first** — `flow_read_instruction` returns the README.md for the current step\n2. **Follow step instructions** — the README.md is the primary guide for what to do\n3. **Delegate to listed agents** — each step lists which agents are appropriate\n4. **Produce the required artifact** — the step's `produces` field specifies what file to create in the artifacts directory\n5. **Check dependencies** — the step's `requires` field lists artifacts from previous steps that must exist\n6. **Report status** — agents report `DONE` | `DONE_WITH_CONCERNS` | `NEEDS_CONTEXT` | `BLOCKED` to the Orchestrator\n\n## Artifacts\n\nAll artifacts are stored in the run directory under `.flows/{topic}/`. The template variable `{{artifacts_path}}` resolves to the actual path at runtime.\n"},{file:`steps/assess/README.md`,content:`---
|
|
955
958
|
name: assess
|
|
956
959
|
description: Understand scope, analyze the codebase, and identify the implementation approach.
|
|
957
960
|
---
|
|
@@ -1099,9 +1102,11 @@ For small features that need minimal design:
|
|
|
1099
1102
|
- What is the user trying to achieve?
|
|
1100
1103
|
- What are the constraints?
|
|
1101
1104
|
- What is the simplest approach?
|
|
1102
|
-
3. **Decision Protocol** (if technical decisions exist) —
|
|
1103
|
-
-
|
|
1104
|
-
-
|
|
1105
|
+
3. **Decision Protocol** (if technical decisions exist) — Follow the full 3-phase multi-model decision protocol:
|
|
1106
|
+
- **Phase 1**: Launch ALL 4 Researcher variants in parallel (Alpha/Beta/Gamma/Delta)
|
|
1107
|
+
- **Phase 2**: Anonymize outputs as A/B/C/D, run peer review round (4 reviewers in parallel)
|
|
1108
|
+
- **Phase 3**: Synthesize into structured verdict (Agrees / Clashes / Blind Spots / Recommendation / First Step)
|
|
1109
|
+
- Present verdict visually using \`present\`, produce ADR for Standard+ tiers
|
|
1105
1110
|
4. **Write \`{{artifacts_path}}/design-decisions.md\`** to disk:
|
|
1106
1111
|
|
|
1107
1112
|
\`\`\`markdown
|
|
@@ -31,7 +31,7 @@ Enter Phase 0 (Design Gate) directly — the user is requesting a design session
|
|
|
31
31
|
|
|
32
32
|
1. **Invoke the brainstorming skill** — interactive design dialogue with user
|
|
33
33
|
2. Follow the skill's full process (auto-selects Simple or Advanced mode)
|
|
34
|
-
3. If Advanced Mode, use Decision Protocol for unresolved technical choices
|
|
34
|
+
3. If Advanced Mode, use the full Multi-Model Decision Protocol (3-phase: research → peer review → verdict, defined in Orchestrator instructions) for unresolved technical choices
|
|
35
35
|
4. Terminal state: brainstorming skill invokes writing-plans skill
|
|
36
36
|
|
|
37
37
|
**🛑 HARD GATE** — Do NOT skip brainstorming. Do NOT write code. Design first.`},review:{description:`Dual-model code + architecture review pipeline`,agent:`Orchestrator`,tools:[`search`,`blast_radius`,`check`,`test_run`,`analyze_dependencies`,`remember`,`present`],content:`## Review Pipeline
|
|
@@ -669,9 +669,80 @@ or repeated \`neighbors\` calls.
|
|
|
669
669
|
|
|
670
670
|
The Orchestrator uses **multi-model decision analysis** to resolve non-trivial technical choices. This is the autonomous decision-making process — distinct from the interactive brainstorming skill.
|
|
671
671
|
|
|
672
|
-
## How It Works
|
|
672
|
+
## How It Works (3 Phases)
|
|
673
673
|
|
|
674
|
-
|
|
674
|
+
### Phase 1 — Independent Research (parallel)
|
|
675
|
+
|
|
676
|
+
Launch ALL available Researcher variants **in parallel** with the same question. Each returns an independent recommendation grounded in their thinking style:
|
|
677
|
+
|
|
678
|
+
| Variant | Thinking Style | Lens |
|
|
679
|
+
|---------|---------------|------|
|
|
680
|
+
| **Alpha** | Contrarian | Actively seeks flaws, fatal assumptions, hidden risks |
|
|
681
|
+
| **Beta** | First Principles | Strips assumptions, rebuilds reasoning from ground truth |
|
|
682
|
+
| **Gamma** | Expansionist | Finds undervalued opportunities, cross-domain patterns |
|
|
683
|
+
| **Delta** | Executor | Focuses on fastest path, implementation cost, feasibility |
|
|
684
|
+
|
|
685
|
+
### Phase 2 — Peer Review (parallel)
|
|
686
|
+
|
|
687
|
+
After all researchers return, **anonymize** their responses as Perspective A / B / C / D (strip agent names). Then launch a **second parallel batch** of 4 review sub-agents:
|
|
688
|
+
|
|
689
|
+
**Peer Review Prompt Template:**
|
|
690
|
+
\`\`\`
|
|
691
|
+
You are reviewing 4 independent analyses of the same technical decision.
|
|
692
|
+
Each perspective was produced independently — they have NOT seen each other's work.
|
|
693
|
+
|
|
694
|
+
[Perspective A]
|
|
695
|
+
{Alpha's full response}
|
|
696
|
+
|
|
697
|
+
[Perspective B]
|
|
698
|
+
{Beta's full response}
|
|
699
|
+
|
|
700
|
+
[Perspective C]
|
|
701
|
+
{Gamma's full response}
|
|
702
|
+
|
|
703
|
+
[Perspective D]
|
|
704
|
+
{Delta's full response}
|
|
705
|
+
|
|
706
|
+
Evaluate ALL perspectives. Your review MUST include:
|
|
707
|
+
1. **Strongest argument** — which perspective and why (cite specific evidence)
|
|
708
|
+
2. **Critical blind spot** — what did the STRONGEST perspective miss?
|
|
709
|
+
3. **Consensus gap** — one thing ALL perspectives overlooked or assumed
|
|
710
|
+
4. **Your verdict** — which approach to adopt (may combine elements)
|
|
711
|
+
\`\`\`
|
|
712
|
+
|
|
713
|
+
Use the same 4 Researcher variants for peer review — each model reviews from its own thinking style, catching different blind spots.
|
|
714
|
+
|
|
715
|
+
### Phase 3 — Synthesis & Verdict
|
|
716
|
+
|
|
717
|
+
The Orchestrator synthesizes BOTH layers (original research + peer reviews) into a structured verdict.
|
|
718
|
+
|
|
719
|
+
**Verdict Format (MANDATORY):**
|
|
720
|
+
|
|
721
|
+
\`\`\`markdown
|
|
722
|
+
## Decision Verdict: {title}
|
|
723
|
+
|
|
724
|
+
### Where They Agree
|
|
725
|
+
{Points of consensus across researchers — high confidence items}
|
|
726
|
+
|
|
727
|
+
### Where They Clash
|
|
728
|
+
{Key disagreements with the strongest argument for each side}
|
|
729
|
+
|
|
730
|
+
### Blind Spots Caught (by peer review)
|
|
731
|
+
{Issues found in Phase 2 that no researcher identified in Phase 1}
|
|
732
|
+
|
|
733
|
+
### Recommendation
|
|
734
|
+
{The chosen approach — may combine elements from multiple perspectives}
|
|
735
|
+
**Confidence:** HIGH / MEDIUM / LOW
|
|
736
|
+
**Rationale:** {one paragraph}
|
|
737
|
+
|
|
738
|
+
### First Step
|
|
739
|
+
{The single most concrete next action to begin implementation}
|
|
740
|
+
\`\`\`
|
|
741
|
+
|
|
742
|
+
Then:
|
|
743
|
+
1. **Present** the verdict using \`present({ format: "html" })\` with comparison blocks
|
|
744
|
+
2. **Produce an ADR** via the \`adr-skill\`
|
|
745
|
+
3. **\`remember\`** the decision for future recall
|
|
675
746
|
|
|
676
747
|
## When to Use (Auto-Trigger Rules)
|
|
677
748
|
|
|
@@ -688,9 +759,19 @@ Trigger the decision protocol when there is an **unresolved non-trivial technica
|
|
|
688
759
|
|
|
689
760
|
- Always launch in **parallel**, minimum 4 variants
|
|
690
761
|
- Use exact case-sensitive agent names — never rename or alias
|
|
762
|
+
- **Anonymize** researcher outputs before peer review (A/B/C/D, not agent names)
|
|
763
|
+
- Peer review is a SEPARATE parallel batch — never skip it
|
|
691
764
|
- Never make a non-trivial technical decision without multi-model analysis
|
|
765
|
+
- Always present the verdict visually using \`present\`
|
|
692
766
|
- **Produce an ADR** after every decision resolution
|
|
693
767
|
- \`remember\` the decision for future recall
|
|
768
|
+
|
|
769
|
+
## Shortcut: Floor-Tier Decisions
|
|
770
|
+
|
|
771
|
+
For decisions classified as **Floor tier** (blast_radius ≤ 2, single concern):
|
|
772
|
+
- Skip Phase 2 (peer review) — synthesis directly from Phase 1
|
|
773
|
+
- Verdict format still required but can be abbreviated
|
|
774
|
+
- ADR is optional (use \`remember\` at minimum)
|
|
694
775
|
`,"forge-protocol":`# FORGE Protocol — Quality Overlay
|
|
695
776
|
|
|
696
777
|
> Follow the FORGE (Fact-Oriented Reasoning with Graduated Evidence) protocol for all code generation and modification tasks.
|
|
@@ -1806,7 +1806,7 @@ digraph brainstorming_simple {
|
|
|
1806
1806
|
2. **Assess scope** — if multiple independent subsystems, decompose before detailing (see below)
|
|
1807
1807
|
3. **Offer visual presentation support** (if topic will involve visual questions) — this is its own message, not combined with a clarifying question. Use \`present({ format: "html" })\` to display brainstorming results as a rich visual dashboard.
|
|
1808
1808
|
4. **Ask clarifying questions** — one at a time, understand purpose/constraints/success criteria
|
|
1809
|
-
5. **Propose 2-3 approaches via Decision Protocol** —
|
|
1809
|
+
5. **Propose 2-3 approaches via Decision Protocol** — run the full 3-phase multi-model decision protocol: Phase 1 (4 Researchers in parallel), Phase 2 (peer review with anonymized outputs), Phase 3 (structured verdict). Present the verdict visually using \`present\`. *(See "Decision Protocol Integration" below.)*
|
|
1810
1810
|
6. **Present design** — in sections scaled to their complexity, get user approval after each section
|
|
1811
1811
|
7. **Write design doc** — save to \`docs/plans/YYYY-MM-DD-<topic>-design.md\` and commit
|
|
1812
1812
|
8. **Spec review loop** — review the spec for completeness, consistency, clarity, scope, and YAGNI. Fix issues. Max 3 iterations, then surface to user.
|
|
@@ -1815,18 +1815,33 @@ digraph brainstorming_simple {
|
|
|
1815
1815
|
|
|
1816
1816
|
### Decision Protocol Integration (Advanced Mode Only)
|
|
1817
1817
|
|
|
1818
|
-
When Advanced Mode reaches step 5 ("Propose approaches"), invoke the **multi-model decision protocol**:
|
|
1818
|
+
When Advanced Mode reaches step 5 ("Propose approaches"), invoke the **full 3-phase multi-model decision protocol**:
|
|
1819
1819
|
|
|
1820
|
+
**Phase 1 — Independent Research:**
|
|
1820
1821
|
1. Frame the design question with full context gathered from steps 1-4
|
|
1821
|
-
2. Launch ALL 4 Researcher variants **in parallel** with identical framing:
|
|
1822
|
-
|
|
1823
|
-
|
|
1824
|
-
- **
|
|
1825
|
-
- **
|
|
1826
|
-
|
|
1827
|
-
|
|
1828
|
-
|
|
1829
|
-
|
|
1822
|
+
2. Launch ALL 4 Researcher variants **in parallel** with identical framing — each applies its thinking style:
|
|
1823
|
+
- **Alpha (Contrarian)**: Actively seeks flaws and fatal assumptions
|
|
1824
|
+
- **Beta (First Principles)**: Strips assumptions, rebuilds from ground truth
|
|
1825
|
+
- **Gamma (Expansionist)**: Finds undervalued opportunities, cross-domain patterns
|
|
1826
|
+
- **Delta (Executor)**: Focuses on fastest path, implementation cost, feasibility
|
|
1827
|
+
|
|
1828
|
+
**Phase 2 — Peer Review:**
|
|
1829
|
+
3. **Anonymize** Phase 1 outputs as Perspective A / B / C / D (strip agent names)
|
|
1830
|
+
4. Launch a **second parallel batch** of 4 reviewers, each evaluating ALL perspectives:
|
|
1831
|
+
- Strongest argument — which perspective and why?
|
|
1832
|
+
- Critical blind spot — what did the strongest miss?
|
|
1833
|
+
- Consensus gap — what did ALL overlook?
|
|
1834
|
+
- Verdict — which approach to adopt?
|
|
1835
|
+
|
|
1836
|
+
**Phase 3 — Structured Verdict:**
|
|
1837
|
+
5. Synthesize BOTH layers into the structured verdict format:
|
|
1838
|
+
- **Where Agrees** / **Where Clashes** / **Blind Spots Caught** / **Recommendation** (with confidence) / **First Step**
|
|
1839
|
+
6. Present verdict visually using \`present({ format: "html" })\`
|
|
1840
|
+
7. If a decision produces an ADR, write it to \`docs/decisions/\`
|
|
1841
|
+
|
|
1842
|
+
**Floor-tier shortcut**: Skip Phase 2 (peer review), synthesize directly from Phase 1.
|
|
1843
|
+
|
|
1844
|
+
This replaces the single-agent "propose approaches" step with 8 independent evaluations (4 research + 4 review), producing significantly higher-quality decisions.
|
|
1830
1845
|
|
|
1831
1846
|
### Process Flow
|
|
1832
1847
|
|
|
@@ -1838,8 +1853,9 @@ digraph brainstorming_advanced {
|
|
|
1838
1853
|
"Visual questions ahead?" [shape=diamond];
|
|
1839
1854
|
"Offer Visual Presentation\\n(own message)" [shape=box];
|
|
1840
1855
|
"Ask clarifying questions" [shape=box];
|
|
1841
|
-
"
|
|
1842
|
-
"
|
|
1856
|
+
"Phase 1: 4 Researchers\\nin parallel" [shape=box, style=bold];
|
|
1857
|
+
"Phase 2: Peer Review\\n(anonymized, 4 reviewers)" [shape=box, style=bold];
|
|
1858
|
+
"Phase 3: Structured Verdict" [shape=box];
|
|
1843
1859
|
"Present design sections" [shape=box];
|
|
1844
1860
|
"User approves design?" [shape=diamond];
|
|
1845
1861
|
"Write design doc" [shape=box];
|
|
@@ -1855,9 +1871,10 @@ digraph brainstorming_advanced {
|
|
|
1855
1871
|
"Visual questions ahead?" -> "Offer Visual Presentation\\n(own message)" [label="yes"];
|
|
1856
1872
|
"Visual questions ahead?" -> "Ask clarifying questions" [label="no"];
|
|
1857
1873
|
"Offer Visual Presentation\\n(own message)" -> "Ask clarifying questions";
|
|
1858
|
-
"Ask clarifying questions" -> "
|
|
1859
|
-
"
|
|
1860
|
-
"
|
|
1874
|
+
"Ask clarifying questions" -> "Phase 1: 4 Researchers\\nin parallel";
|
|
1875
|
+
"Phase 1: 4 Researchers\\nin parallel" -> "Phase 2: Peer Review\\n(anonymized, 4 reviewers)";
|
|
1876
|
+
"Phase 2: Peer Review\\n(anonymized, 4 reviewers)" -> "Phase 3: Structured Verdict";
|
|
1877
|
+
"Phase 3: Structured Verdict" -> "Present design sections";
|
|
1861
1878
|
"Present design sections" -> "User approves design?";
|
|
1862
1879
|
"User approves design?" -> "Present design sections" [label="no, revise"];
|
|
1863
1880
|
"User approves design?" -> "Write design doc" [label="yes"];
|
|
@@ -1,5 +0,0 @@
|
|
|
1
|
-
import{a as e,n as t,r as n}from"./constants-B8_CApx0.js";import{n as r,t as i}from"./templates-ArdAVWoY.js";import{loadAdapter as a,n as o,r as s,smartCopyFromMemory as c,t as l}from"./scaffold-WMQ2uQ48.js";import{existsSync as u,mkdirSync as d,readFileSync as f,rmSync as p,unlinkSync as m,writeFileSync as h}from"node:fs";import{dirname as g,join as _,resolve as v}from"node:path";import{fileURLToPath as y}from"node:url";import{getGlobalDataDir as b,saveRegistry as x}from"../../core/dist/index.js";import{execFileSync as S}from"node:child_process";import{homedir as C}from"node:os";function w(e){let t=e;for(let e=0;e<10;e++){try{let e=_(t,`package.json`);if(u(e)&&JSON.parse(f(e,`utf8`)).name===`@vpxa/aikit`)return t}catch{}let e=g(t);if(e===t)break;t=e}return v(e,`..`,`..`,`..`)}function T(){let e={...t};if(process.platform!==`win32`){let t=process.env.PATH;t&&(e.env={PATH:t});try{let t=S(`which`,[`npx`],{encoding:`utf-8`,timeout:3e3}).trim();t&&u(t)&&(e.command=t)}catch{}}return e}function E(){let e=C(),t=process.platform,n=[],r=v(e,`.copilot`),i=v(r,`instructions`),a=v(e,`.claude`),o=v(e,`.cursor`),s=v(e,`.windsurf`);if(t===`win32`){let t=process.env.APPDATA??v(e,`AppData`,`Roaming`);n.push({ide:`VS Code`,configDir:v(t,`Code`,`User`),mcpConfigPath:v(t,`Code`,`User`,`mcp.json`),globalScaffoldRoot:r,instructionsRoot:i},{ide:`VS Code Insiders`,configDir:v(t,`Code - Insiders`,`User`),mcpConfigPath:v(t,`Code - Insiders`,`User`,`mcp.json`),globalScaffoldRoot:r,instructionsRoot:i},{ide:`VSCodium`,configDir:v(t,`VSCodium`,`User`),mcpConfigPath:v(t,`VSCodium`,`User`,`mcp.json`),globalScaffoldRoot:r,instructionsRoot:i},{ide:`Cursor`,configDir:v(t,`Cursor`,`User`),mcpConfigPath:v(t,`Cursor`,`User`,`mcp.json`),globalScaffoldRoot:o,instructionsRoot:null},{ide:`Cursor Nightly`,configDir:v(t,`Cursor Nightly`,`User`),mcpConfigPath:v(t,`Cursor Nightly`,`User`,`mcp.json`),globalScaffoldRoot:o,instructionsRoot:null},{ide:`Windsurf`,configDir:v(t,`Windsurf`,`User`),mcpConfigPath:v(t,`Windsurf`,`User`,`mcp.json`),globalScaffoldRoot:s,instructionsRoot:null})}else if(t===`darwin`){let t=v(e,`Library`,`Application Support`);n.push({ide:`VS Code`,configDir:v(t,`Code`,`User`),mcpConfigPath:v(t,`Code`,`User`,`mcp.json`),globalScaffoldRoot:r,instructionsRoot:i},{ide:`VS Code Insiders`,configDir:v(t,`Code - Insiders`,`User`),mcpConfigPath:v(t,`Code - Insiders`,`User`,`mcp.json`),globalScaffoldRoot:r,instructionsRoot:i},{ide:`VSCodium`,configDir:v(t,`VSCodium`,`User`),mcpConfigPath:v(t,`VSCodium`,`User`,`mcp.json`),globalScaffoldRoot:r,instructionsRoot:i},{ide:`Cursor`,configDir:v(t,`Cursor`,`User`),mcpConfigPath:v(t,`Cursor`,`User`,`mcp.json`),globalScaffoldRoot:o,instructionsRoot:null},{ide:`Cursor Nightly`,configDir:v(t,`Cursor Nightly`,`User`),mcpConfigPath:v(t,`Cursor Nightly`,`User`,`mcp.json`),globalScaffoldRoot:o,instructionsRoot:null},{ide:`Windsurf`,configDir:v(t,`Windsurf`,`User`),mcpConfigPath:v(t,`Windsurf`,`User`,`mcp.json`),globalScaffoldRoot:s,instructionsRoot:null})}else{let t=process.env.XDG_CONFIG_HOME??v(e,`.config`);n.push({ide:`VS Code`,configDir:v(t,`Code`,`User`),mcpConfigPath:v(t,`Code`,`User`,`mcp.json`),globalScaffoldRoot:r,instructionsRoot:i},{ide:`VS Code Insiders`,configDir:v(t,`Code - Insiders`,`User`),mcpConfigPath:v(t,`Code - Insiders`,`User`,`mcp.json`),globalScaffoldRoot:r,instructionsRoot:i},{ide:`VSCodium`,configDir:v(t,`VSCodium`,`User`),mcpConfigPath:v(t,`VSCodium`,`User`,`mcp.json`),globalScaffoldRoot:r,instructionsRoot:i},{ide:`Cursor`,configDir:v(t,`Cursor`,`User`),mcpConfigPath:v(t,`Cursor`,`User`,`mcp.json`),globalScaffoldRoot:o,instructionsRoot:null},{ide:`Cursor Nightly`,configDir:v(t,`Cursor Nightly`,`User`),mcpConfigPath:v(t,`Cursor Nightly`,`User`,`mcp.json`),globalScaffoldRoot:o,instructionsRoot:null},{ide:`Windsurf`,configDir:v(t,`Windsurf`,`User`),mcpConfigPath:v(t,`Windsurf`,`User`,`mcp.json`),globalScaffoldRoot:s,instructionsRoot:null})}if(n.push({ide:`Claude Code`,configDir:v(e,`.claude`),mcpConfigPath:v(e,`.claude`,`mcp.json`),globalScaffoldRoot:a,instructionsRoot:null}),n.push({ide:`Copilot CLI`,configDir:r,mcpConfigPath:v(r,`mcp-config.json`),globalScaffoldRoot:null,instructionsRoot:null}),t===`darwin`){let e={"VS Code":`/Applications/Visual Studio Code.app`,"VS Code Insiders":`/Applications/Visual Studio Code - Insiders.app`,VSCodium:`/Applications/VSCodium.app`,Cursor:`/Applications/Cursor.app`,"Cursor Nightly":`/Applications/Cursor Nightly.app`,Windsurf:`/Applications/Windsurf.app`};return n.filter(t=>u(t.configDir)||e[t.ide]&&u(e[t.ide]))}return n.filter(e=>u(e.configDir))}function D(e,t,n=!1){let{mcpConfigPath:r,configDir:i}=e,a=T(),o={};if(u(r)){try{let e=f(r,`utf-8`);o=JSON.parse(e)}catch{let e=`${r}.bak`;h(e,f(r,`utf-8`),`utf-8`),console.log(` Backed up invalid ${r} to ${e}`),o={}}if((o.servers??o.mcpServers??{})[t]&&!n){console.log(` ${e.ide}: ${t} already configured (use --force to update)`);return}}let s=new Set([`VS Code`,`VS Code Insiders`,`VSCodium`,`Windsurf`]).has(e.ide)?`servers`:`mcpServers`,c=o[s]??{};e.ide===`Copilot CLI`?c[t]={...a,tools:[`*`]}:c[t]=a,o[s]=c,d(i,{recursive:!0}),h(r,`${JSON.stringify(o,null,2)}\n`,`utf-8`),console.log(` ${e.ide}: configured ${t} in ${r}`)}const O=new Set([`VS Code`,`VS Code Insiders`,`VSCodium`]);function k(t,n=!1){if(!O.has(t.ide))return;let r=v(t.configDir,`settings.json`),i={};if(u(r))try{let e=f(r,`utf-8`);i=JSON.parse(e)}catch{console.log(` ${t.ide}: skipped settings.json (invalid JSON)`);return}let a=!1;for(let[t,r]of Object.entries(e))if(typeof r==`object`&&r){let e=typeof i[t]==`object`&&i[t]!==null?i[t]:{},n={...e,...r};JSON.stringify(n)!==JSON.stringify(e)&&(i[t]=n,a=!0)}else (n||!(t in i))&&(i[t]=r,a=!0);a&&(h(r,`${JSON.stringify(i,null,2)}\n`,`utf-8`),console.log(` ${t.ide}: updated settings.json`))}async function A(e,t,n,f,m=!1){let g=new Set;for(let e of t)e.globalScaffoldRoot&&g.add(e.globalScaffoldRoot);if(g.size===0){console.log(` No IDEs with global scaffold support detected.`);return}let _=await a(e,`copilot`),y=new Map;for(let e of _){let t=e.path.indexOf(`/`);if(t===-1)continue;let n=e.path.substring(0,t);if(n!==`agents`&&n!==`prompts`)continue;let r=y.get(n)??[];r.push({path:e.path.substring(t+1),content:e.content}),y.set(n,r)}let b=await a(e,`skills`),x=new Map;for(let e of b){let t=e.path.indexOf(`/`);if(t===-1)continue;let n=e.path.substring(0,t),r=x.get(n)??[];r.push({path:e.path.substring(t+1),content:e.content}),x.set(n,r)}let S=await a(e,`flows`),w=new Map;for(let e of S){let t=e.path.indexOf(`/`);if(t===-1)continue;let n=e.path.substring(0,t),r=w.get(n)??[];r.push({path:e.path.substring(t+1),content:e.content}),w.set(n,r)}let T=(e,t)=>{let n=y.get(t);if(!n||n.length===0)return;let r=v(e,`.aikit-scaffold.json`),i=o(r)??l(f);i.version=f,c(n,v(e,t),i,t,m),s(r,i)};for(let e of g){T(e,`agents`),T(e,`prompts`);{let t=v(e,`.aikit-scaffold.json`),n=o(t)??l(f);n.version=f;for(let[t,r]of x)c(r,v(e,`skills`,t),n,`skills/${t}`,m);s(t,n)}{let t=v(e,`.aikit-scaffold.json`),n=o(t)??l(f);n.version=f;for(let t of w.keys()){let n=v(e,`flows`,t,`skills`);u(n)&&(p(n,{recursive:!0,force:!0}),console.log(` ${e}: migrated ${t} flow to steps/ layout`))}for(let[t,r]of w)c(r,v(e,`flows`,t),n,`flows/${t}`,m);s(t,n)}console.log(` ${e}: scaffold updated (${x.size} skills)`)}let E=new Set,D=r(`aikit`,n),O=i(`aikit`,n);for(let e of t){if(!e.globalScaffoldRoot)continue;let t=e.globalScaffoldRoot;if(e.ide===`Claude Code`){let e=v(t,`CLAUDE.md`);h(e,`${D}\n---\n\n${O}`,`utf-8`),E.add(e)}else if(e.ide===`VS Code`||e.ide===`VS Code Insiders`||e.ide===`VSCodium`){let n=e.instructionsRoot??t;d(n,{recursive:!0});let r=v(n,`copilot-instructions.md`);E.has(r)||(h(r,`---\napplyTo: "**"\n---\n\n${D}\n---\n\n${O}`,`utf-8`),E.add(r));let i=v(C(),`.github`),a=v(i,`copilot-instructions.md`);E.has(a)||(d(i,{recursive:!0}),h(a,`${D}\n---\n\n${O}`,`utf-8`),E.add(a)),T(e.configDir,`prompts`)}else if(e.ide===`Cursor`||e.ide===`Cursor Nightly`){let e=v(t,`rules`);d(e,{recursive:!0});let n=v(e,`aikit.mdc`);E.has(n)||(h(n,`${D}\n---\n\n${O}`,`utf-8`),E.add(n))}else if(e.ide===`Windsurf`){let e=v(t,`rules`);d(e,{recursive:!0});let n=v(e,`aikit.md`);E.has(n)||(h(n,`${D}\n---\n\n${O}`,`utf-8`),E.add(n))}}E.size>0&&console.log(` Instruction files: ${[...E].join(`, `)}`)}function j(e){let t=[];for(let n of e){if(!n.globalScaffoldRoot)continue;let e=n.globalScaffoldRoot;if(n.ide===`VS Code`||n.ide===`VS Code Insiders`||n.ide===`VSCodium`){let r=n.instructionsRoot??e;t.push(v(r,`kb.instructions.md`)),t.push(v(r,`aikit.instructions.md`))}else n.ide===`Cursor`||n.ide===`Cursor Nightly`?t.push(v(e,`rules`,`kb.mdc`)):n.ide===`Windsurf`&&t.push(v(e,`rules`,`kb.md`))}for(let e of t)u(e)&&(m(e),console.log(` Removed legacy file: ${e}`))}async function M(e){let t=n,r=w(g(y(import.meta.url))),i=JSON.parse(f(v(r,`package.json`),`utf-8`)).version;console.log(`Initializing @vpxa/aikit v${i}...\n`);let a=b();d(a,{recursive:!0}),console.log(` Global data store: ${a}`),x({version:1,workspaces:{}}),console.log(` Created registry.json`);let o=E();if(o.length===0)console.log(`
|
|
2
|
-
No supported IDEs detected. You can manually add the MCP server config.`);else{console.log(`\n Detected ${o.length} IDE(s):`);for(let n of o)D(n,t,e.force),k(n,e.force)}console.log(`
|
|
3
|
-
Installing scaffold files:`),await A(r,o,t,i,e.force),j(o),console.log(`
|
|
4
|
-
User-level AI Kit installation complete!`),console.log(`
|
|
5
|
-
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`)}export{M as initUser};
|