@vpxa/aikit 0.1.17 → 0.1.19

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.
Files changed (31) hide show
  1. package/package.json +1 -1
  2. package/packages/cli/dist/commands/environment.js +1 -1
  3. package/packages/embeddings/dist/onnx-embedder.js +1 -1
  4. package/packages/server/dist/server.js +1 -1
  5. package/packages/server/dist/tools/flow.tools.js +1 -1
  6. package/packages/server/dist/tools/present/tool.d.ts +1 -1
  7. package/packages/server/dist/tools/present/tool.js +1 -1
  8. package/packages/server/dist/version-check.js +1 -1
  9. package/packages/tools/dist/delegate.js +1 -1
  10. package/packages/tools/dist/web-fetch.js +1 -1
  11. package/scaffold/adapters/copilot.mjs +12 -4
  12. package/scaffold/definitions/bodies.mjs +66 -26
  13. package/scaffold/definitions/models.mjs +32 -17
  14. package/scaffold/general/agents/Architect-Reviewer-Alpha.agent.md +1 -1
  15. package/scaffold/general/agents/Architect-Reviewer-Beta.agent.md +1 -1
  16. package/scaffold/general/agents/Code-Reviewer-Alpha.agent.md +1 -1
  17. package/scaffold/general/agents/Code-Reviewer-Beta.agent.md +1 -1
  18. package/scaffold/general/agents/Debugger.agent.md +1 -1
  19. package/scaffold/general/agents/Documenter.agent.md +1 -1
  20. package/scaffold/general/agents/Explorer.agent.md +1 -1
  21. package/scaffold/general/agents/Frontend.agent.md +1 -1
  22. package/scaffold/general/agents/Implementer.agent.md +1 -1
  23. package/scaffold/general/agents/Orchestrator.agent.md +73 -44
  24. package/scaffold/general/agents/Planner.agent.md +12 -1
  25. package/scaffold/general/agents/README.md +17 -17
  26. package/scaffold/general/agents/Refactor.agent.md +1 -1
  27. package/scaffold/general/agents/Researcher-Alpha.agent.md +1 -1
  28. package/scaffold/general/agents/Researcher-Beta.agent.md +1 -1
  29. package/scaffold/general/agents/Researcher-Delta.agent.md +1 -1
  30. package/scaffold/general/agents/Researcher-Gamma.agent.md +1 -1
  31. package/scaffold/general/agents/Security.agent.md +1 -1
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vpxa/aikit",
3
- "version": "0.1.17",
3
+ "version": "0.1.19",
4
4
  "type": "module",
5
5
  "description": "Local-first AI developer toolkit — knowledge base, code analysis, context management, and developer tools for LLM agents",
6
6
  "license": "MIT",
@@ -1 +1 @@
1
- import{extractNumFlag as e,extractStrFlag as t,printManagedProcess as n,readStdin as r}from"../helpers.js";import{resolve as i}from"node:path";import{readFile as a}from"node:fs/promises";import{delegate as o,delegateListModels as s,processList as c,processLogs as l,processStart as u,processStatus as d,processStop as f,watchList as p,watchStart as m,watchStop as h}from"../../../tools/dist/index.js";const g=[{name:`proc`,description:`Manage in-memory child processes`,usage:`aikit proc <start|stop|status|list|logs> ...`,run:async t=>{let r=t.shift()?.trim()??``;switch(r){case`start`:{let e=t.shift()?.trim(),r=t.shift()?.trim();(!e||!r)&&(console.error(`Usage: aikit proc start <id> <command> [args...]`),process.exit(1)),n(u(e,r,t));return}case`stop`:{let e=t.shift()?.trim();e||(console.error(`Usage: aikit proc stop <id>`),process.exit(1));let r=f(e);if(!r){console.log(`No managed process found: ${e}`);return}n(r);return}case`status`:{let e=t.shift()?.trim();e||(console.error(`Usage: aikit proc status <id>`),process.exit(1));let r=d(e);if(!r){console.log(`No managed process found: ${e}`);return}n(r);return}case`list`:{let e=c();if(e.length===0){console.log(`No managed processes.`);return}for(let t of e)n(t),console.log(``);return}case`logs`:{let n=e(t,`--tail`,50),r=t.shift()?.trim();r||(console.error(`Usage: aikit proc logs <id> [--tail N]`),process.exit(1));let i=l(r,n);if(i.length===0){console.log(`No logs found for process: ${r}`);return}for(let e of i)console.log(e);return}default:console.error(`Unknown proc action: ${r}`),console.error(`Actions: start, stop, status, list, logs`),process.exit(1)}}},{name:`watch`,description:`Manage in-memory filesystem watchers`,usage:`aikit watch <start|stop|list> ...`,run:async e=>{let t=e.shift()?.trim()??``;switch(t){case`start`:{let t=e.shift()?.trim();t||(console.error(`Usage: aikit watch start <path>`),process.exit(1));let n=m({path:i(t)});console.log(`Started watcher: ${n.id}`),console.log(` Path: ${n.path}`),console.log(` Status: ${n.status}`);return}case`stop`:{let t=e.shift()?.trim();t||(console.error(`Usage: aikit watch stop <id>`),process.exit(1));let n=h(t);console.log(n?`Stopped watcher: ${t}`:`Watcher not found: ${t}`);return}case`list`:{let e=p();if(e.length===0){console.log(`No active watchers.`);return}for(let t of e)console.log(`${t.id}`),console.log(` Path: ${t.path}`),console.log(` Status: ${t.status}`),console.log(` Events: ${t.eventCount}`);return}default:console.error(`Unknown watch action: ${t}`),console.error(`Actions: start, stop, list`),process.exit(1)}}},{name:`delegate`,description:`Delegate a task to a local Ollama model`,usage:`aikit delegate [--model name] [--system prompt] [--temp 0.3] <prompt | --stdin>`,run:async n=>{if((n[0]===`models`?n.shift():void 0)===`models`){try{let e=await s();if(e.length===0){console.log(`No Ollama models available. Pull one with: ollama pull qwen2.5-coder:7b`);return}for(let t of e)console.log(t)}catch{console.error(`Ollama is not running. Start it with: ollama serve`),process.exit(1)}return}let c=t(n,`--model`,``),l=t(n,`--system`,``),u=e(n,`--temp`,.3),d=t(n,`--context`,``),f=n.join(` `);f||=await r(),f||(console.error(`Usage: aikit delegate [--model name] <prompt>`),process.exit(1));let p;d&&(p=await a(i(d),`utf-8`));let m=await o({prompt:f,model:c||void 0,system:l||void 0,context:p,temperature:u});m.error&&(console.error(`Error: ${m.error}`),process.exit(1)),console.log(m.response),console.error(`\n(${m.model}, ${m.durationMs}ms, ${m.tokenCount??`?`} tokens)`)}}];export{g as environmentCommands};
1
+ import{extractNumFlag as e,extractStrFlag as t,printManagedProcess as n,readStdin as r}from"../helpers.js";import{resolve as i}from"node:path";import{readFile as a}from"node:fs/promises";import{delegate as o,delegateListModels as s,processList as c,processLogs as l,processStart as u,processStatus as d,processStop as f,watchList as p,watchStart as m,watchStop as h}from"../../../tools/dist/index.js";const g=[{name:`proc`,description:`Manage in-memory child processes`,usage:`aikit proc <start|stop|status|list|logs> ...`,run:async t=>{let r=t.shift()?.trim()??``;switch(r){case`start`:{let e=t.shift()?.trim(),r=t.shift()?.trim();(!e||!r)&&(console.error(`Usage: aikit proc start <id> <command> [args...]`),process.exit(1)),n(u(e,r,t));return}case`stop`:{let e=t.shift()?.trim();e||(console.error(`Usage: aikit proc stop <id>`),process.exit(1));let r=f(e);if(!r){console.log(`No managed process found: ${e}`);return}n(r);return}case`status`:{let e=t.shift()?.trim();e||(console.error(`Usage: aikit proc status <id>`),process.exit(1));let r=d(e);if(!r){console.log(`No managed process found: ${e}`);return}n(r);return}case`list`:{let e=c();if(e.length===0){console.log(`No managed processes.`);return}for(let t of e)n(t),console.log(``);return}case`logs`:{let n=e(t,`--tail`,50),r=t.shift()?.trim();r||(console.error(`Usage: aikit proc logs <id> [--tail N]`),process.exit(1));let i=l(r,n);if(i.length===0){console.log(`No logs found for process: ${r}`);return}for(let e of i)console.log(e);return}default:console.error(`Unknown proc action: ${r}`),console.error(`Actions: start, stop, status, list, logs`),process.exit(1)}}},{name:`watch`,description:`Manage in-memory filesystem watchers`,usage:`aikit watch <start|stop|list> ...`,run:async e=>{let t=e.shift()?.trim()??``;switch(t){case`start`:{let t=e.shift()?.trim();t||(console.error(`Usage: aikit watch start <path>`),process.exit(1));let n=m({path:i(t)});console.log(`Started watcher: ${n.id}`),console.log(` Path: ${n.path}`),console.log(` Status: ${n.status}`);return}case`stop`:{let t=e.shift()?.trim();t||(console.error(`Usage: aikit watch stop <id>`),process.exit(1));let n=h(t);console.log(n?`Stopped watcher: ${t}`:`Watcher not found: ${t}`);return}case`list`:{let e=p();if(e.length===0){console.log(`No active watchers.`);return}for(let t of e)console.log(`${t.id}`),console.log(` Path: ${t.path}`),console.log(` Status: ${t.status}`),console.log(` Events: ${t.eventCount}`);return}default:console.error(`Unknown watch action: ${t}`),console.error(`Actions: start, stop, list`),process.exit(1)}}},{name:`delegate`,description:`Delegate a task to a local Ollama model`,usage:`aikit delegate [--model name] [--system prompt] [--temp 0.3] <prompt | --stdin>`,run:async n=>{if((n[0]===`models`?n.shift():void 0)===`models`){try{let e=await s();if(e.length===0){console.log(`No Ollama models available. Pull one with: ollama pull gemma4:e2b`);return}for(let t of e)console.log(t)}catch{console.error(`Ollama is not running. Start it with: ollama serve`),process.exit(1)}return}let c=t(n,`--model`,``),l=t(n,`--system`,``),u=e(n,`--temp`,.3),d=t(n,`--context`,``),f=n.join(` `);f||=await r(),f||(console.error(`Usage: aikit delegate [--model name] <prompt>`),process.exit(1));let p;d&&(p=await a(i(d),`utf-8`));let m=await o({prompt:f,model:c||void 0,system:l||void 0,context:p,temperature:u});m.error&&(console.error(`Error: ${m.error}`),process.exit(1)),console.log(m.response),console.error(`\n(${m.model}, ${m.durationMs}ms, ${m.tokenCount??`?`} tokens)`)}}];export{g as environmentCommands};
@@ -1 +1 @@
1
- import{homedir as e}from"node:os";import{join as t}from"node:path";import{EMBEDDING_DEFAULTS as n}from"../../core/dist/index.js";import{env as r,pipeline as i}from"@huggingface/transformers";r.cacheDir=t(e(),`.cache`,`huggingface`,`transformers-js`);var a=class{pipe=null;dimensions;modelId;queryPrefix;constructor(e){this.modelId=e?.model??n.model,this.dimensions=e?.dimensions??n.dimensions,this.queryPrefix=e?.queryPrefix??this.detectQueryPrefix(this.modelId)}detectQueryPrefix(e){let t=e.toLowerCase();return t.includes(`bge`)||t.includes(`mxbai-embed`)?`Represent this sentence for searching relevant passages: `:t.includes(`/e5-`)||t.includes(`multilingual-e5`)?`query: `:``}async initialize(){if(!this.pipe)try{this.pipe=await i(`feature-extraction`,this.modelId,{dtype:`fp32`})}catch(e){throw Error(`Failed to initialize embedding model "${this.modelId}": ${e.message}`)}}async shutdown(){this.pipe=null}async embed(e){this.pipe||await this.initialize();let t=await this.pipe?.(e,{pooling:`mean`,normalize:!0});if(!t)throw Error(`Embedding pipeline returned no output`);return new Float32Array(t.data)}async embedQuery(e){return this.embed(this.queryPrefix+e)}async embedBatch(e,t=64){if(e.length===0)return[];this.pipe||await this.initialize();let n=[];for(let r=0;r<e.length;r+=t){let i=e.slice(r,r+t),a=await this.pipe?.(i,{pooling:`mean`,normalize:!0});if(!a)throw Error(`Embedding pipeline returned no output`);if(i.length===1)n.push(new Float32Array(a.data));else for(let e=0;e<i.length;e++){let t=e*this.dimensions,r=a.data.slice(t,t+this.dimensions);n.push(new Float32Array(r))}}return n}};export{a as OnnxEmbedder};
1
+ import{homedir as e}from"node:os";import{join as t}from"node:path";import{EMBEDDING_DEFAULTS as n}from"../../core/dist/index.js";import{env as r,pipeline as i}from"@huggingface/transformers";r.cacheDir=t(e(),`.cache`,`huggingface`,`transformers-js`);var a=class{pipe=null;dimensions;modelId;queryPrefix;constructor(e){this.modelId=e?.model??n.model,this.dimensions=e?.dimensions??n.dimensions,this.queryPrefix=e?.queryPrefix??this.detectQueryPrefix(this.modelId)}detectQueryPrefix(e){let t=e.toLowerCase();return t.includes(`bge`)||t.includes(`mxbai-embed`)?`Represent this sentence for searching relevant passages: `:t.includes(`/e5-`)||t.includes(`multilingual-e5`)?`query: `:``}async initialize(){if(!this.pipe)try{this.pipe=await i(`feature-extraction`,this.modelId,{dtype:`q8`})}catch(e){throw Error(`Failed to initialize embedding model "${this.modelId}": ${e.message}`)}}async shutdown(){this.pipe=null}async embed(e){this.pipe||await this.initialize();let t=await this.pipe?.(e,{pooling:`mean`,normalize:!0});if(!t)throw Error(`Embedding pipeline returned no output`);return new Float32Array(t.data)}async embedQuery(e){return this.embed(this.queryPrefix+e)}async embedBatch(e,t=64){if(e.length===0)return[];this.pipe||await this.initialize();let n=[];for(let r=0;r<e.length;r+=t){let i=e.slice(r,r+t),a=await this.pipe?.(i,{pooling:`mean`,normalize:!0});if(!a)throw Error(`Embedding pipeline returned no output`);if(i.length===1)n.push(new Float32Array(a.data));else for(let e=0;e<i.length;e++){let t=e*this.dimensions,r=a.data.slice(t,t+this.dimensions);n.push(new Float32Array(r))}}return n}};export{a as OnnxEmbedder};
@@ -1,3 +1,3 @@
1
- import{BackgroundTaskScheduler as e}from"./background-task.js";import{clearCompletionCache as t}from"./completions.js";import{installCompressionInterceptor as n}from"./compression-interceptor.js";import{CuratedKnowledgeManager as r}from"./curated-manager.js";import{createElicitor as i,noopElicitor as a}from"./elicitor.js";import{IdleTimer as o}from"./idle-timer.js";import{bridgeMcpLogging as s}from"./mcp-logging.js";import{MemoryMonitor as c}from"./memory-monitor.js";import{registerPrompts as l}from"./prompts.js";import{installReplayInterceptor as u}from"./replay-interceptor.js";import{ResourceNotifier as d}from"./resources/resource-notifier.js";import{registerResources as f}from"./resources/resources.js";import{createSamplingClient as p}from"./sampling.js";import{installStructuredContentGuard as m}from"./structured-content-guard.js";import{getToolMeta as h}from"./tool-metadata.js";import{installToolPrefix as g}from"./tool-prefix.js";import{ToolTimeoutError as _,getToolTimeout as v,withTimeout as ee}from"./tool-timeout.js";import{registerAnalyzeDependenciesTool as y,registerAnalyzeDiagramTool as b,registerAnalyzeEntryPointsTool as x,registerAnalyzePatternsTool as te,registerAnalyzeStructureTool as S,registerAnalyzeSymbolsTool as C,registerBlastRadiusTool as w}from"./tools/analyze.tools.js";import{registerAuditTool as ne}from"./tools/audit.tool.js";import{registerBrainstormTool as T}from"./tools/brainstorm.tool.js";import{initBridgeComponents as E,registerErPullTool as D,registerErPushTool as O,registerErSyncStatusTool as re}from"./tools/bridge.tools.js";import{registerConfigTool as k}from"./tools/config.tool.js";import{registerCompactTool as A,registerDeadSymbolsTool as j,registerFileSummaryTool as M,registerFindTool as ie,registerScopeMapTool as N,registerSymbolTool as P,registerTraceTool as ae}from"./tools/context.tools.js";import{registerErEvolveReviewTool as oe}from"./tools/evolution.tools.js";import{registerBatchTool as se,registerCheckTool as F,registerDelegateTool as I,registerEvalTool as L,registerParseOutputTool as R,registerTestRunTool as z}from"./tools/execution.tools.js";import{registerFlowTools as ce}from"./tools/flow.tools.js";import{registerDigestTool as le,registerEvidenceMapTool as B,registerForgeClassifyTool as V,registerForgeGroundTool as ue,registerStratumCardTool as de}from"./tools/forge.tools.js";import{registerForgetTool as fe}from"./tools/forget.tool.js";import{registerGraphTool as pe}from"./tools/graph.tool.js";import{registerGuideTool as H,registerHealthTool as U,registerProcessTool as W,registerWatchTool as G,registerWebFetchTool as K}from"./tools/infra.tools.js";import{registerListTool as me}from"./tools/list.tool.js";import{registerLookupTool as he}from"./tools/lookup.tool.js";import{registerCodemodTool as ge,registerDataTransformTool as q,registerDiffParseTool as _e,registerGitContextTool as ve,registerRenameTool as ye}from"./tools/manipulation.tools.js";import{registerOnboardTool as be}from"./tools/onboard.tool.js";import{registerCheckpointTool as xe,registerLaneTool as Se,registerQueueTool as Ce,registerStashTool as we,registerWorksetTool as Te}from"./tools/persistence.tools.js";import{registerErUpdatePolicyTool as Ee}from"./tools/policy.tools.js";import{registerPresentTool as De}from"./tools/present/tool.js";import"./tools/present/index.js";import{registerProduceKnowledgeTool as Oe}from"./tools/produce.tool.js";import{registerReadTool as ke}from"./tools/read.tool.js";import{registerReindexTool as Ae}from"./tools/reindex.tool.js";import{registerRememberTool as je}from"./tools/remember.tool.js";import{registerReplayTool as Me}from"./tools/replay.tool.js";import{registerRestoreTool as Ne}from"./tools/restore.tool.js";import{registerSearchTool as Pe}from"./tools/search.tool.js";import{getCurrentVersion as Fe}from"./version-check.js";import{registerEarlyStatusTool as Ie,registerStatusTool as Le}from"./tools/status.tool.js";import{registerUpdateTool as Re}from"./tools/update.tool.js";import{registerChangelogTool as ze,registerEncodeTool as Be,registerEnvTool as Ve,registerHttpTool as He,registerMeasureTool as Ue,registerRegexTestTool as We,registerSchemaValidateTool as Ge,registerSnippetTool as Ke,registerTimeTool as qe,registerWebSearchTool as Je}from"./tools/utility.tools.js";import{existsSync as Ye,statSync as Xe}from"node:fs";import{resolve as Ze}from"node:path";import{AIKIT_PATHS as Qe,createLogger as $e,serializeError as J}from"../../core/dist/index.js";import{initializeWasm as et}from"../../chunker/dist/index.js";import{OnnxEmbedder as tt}from"../../embeddings/dist/index.js";import{EvolutionCollector as nt,PolicyStore as rt}from"../../enterprise-bridge/dist/index.js";import{FileHashCache as it,IncrementalIndexer as at}from"../../indexer/dist/index.js";import{SqliteGraphStore as ot,createStore as st}from"../../store/dist/index.js";import{FileCache as ct}from"../../tools/dist/index.js";import{completable as lt}from"@modelcontextprotocol/sdk/server/completable.js";import{McpServer as ut}from"@modelcontextprotocol/sdk/server/mcp.js";import{z as dt}from"zod";const Y=$e(`server`);async function X(e){Y.info(`Initializing AI Kit components`);let[t,n,i,a]=await Promise.all([(async()=>{let t=new tt({model:e.embedding.model,dimensions:e.embedding.dimensions});return await t.initialize(),Y.info(`Embedder loaded`,{modelId:t.modelId,dimensions:t.dimensions}),t})(),(async()=>{let t=await st({backend:e.store.backend,path:e.store.path});return await t.initialize(),Y.info(`Store initialized`),t})(),(async()=>{let t=new ot({path:e.store.path});return await t.initialize(),Y.info(`Graph store initialized`),t})(),(async()=>{let e=await et();return e?Y.info(`WASM tree-sitter enabled for AST analysis`):Y.warn(`WASM tree-sitter not available; analyzers will use regex fallback`),e})()]),o=new at(t,n),s=new it(e.store.path);s.load(),o.setHashCache(s);let c=e.curated.path,l=new r(c,n,t);o.setGraphStore(i);let u=E(e.er),d=u?new rt(e.curated.path):void 0;d&&Y.info(`Policy store initialized`,{ruleCount:d.getRules().length});let f=u?new nt:void 0,p=Ze(e.sources[0]?.path??process.cwd(),Qe.aiKb),m=Ye(p),h=e.onboardDir?Ye(e.onboardDir):!1,g=m||h,_,v=m?p:e.onboardDir;if(g&&v)try{_=Xe(v).mtime.toISOString()}catch{}return Y.info(`Onboard state detected`,{onboardComplete:g,onboardTimestamp:_,aiKbExists:m,onboardDirExists:h}),{embedder:t,store:n,indexer:o,curated:l,graphStore:i,fileCache:new ct,bridge:u,policyStore:d,evolutionCollector:f,onboardComplete:g,onboardTimestamp:_}}function ft(e,t){let n=new ut({name:t.serverName??`aikit`,version:Fe()},{capabilities:{logging:{},completions:{},prompts:{}}});return s(n),g(n,t.toolPrefix??``),Z(n,e,t,i(n),new d(n),p(n)),l(n,{curated:e.curated,store:e.store,graphStore:e.graphStore},t.indexMode),n}function Z(e,t,r,i,a,o,s,c){u(e),m(e),n(e),Pe(e,t.embedder,t.store,t.graphStore,t.bridge,t.evolutionCollector,o),he(e,t.store),Le(e,t.store,t.graphStore,t.curated,{onboardComplete:t.onboardComplete,onboardTimestamp:t.onboardTimestamp},r,s,c),k(e,r),Ae(e,t.indexer,r,t.curated,t.store,a,s),je(e,t.curated,t.policyStore,t.evolutionCollector,a),Re(e,t.curated,a),fe(e,t.curated,a),ke(e,t.curated),me(e,t.curated),S(e,t.store,t.embedder),y(e,t.store,t.embedder),C(e,t.store,t.embedder),te(e,t.store,t.embedder),x(e,t.store,t.embedder),b(e,t.store,t.embedder),w(e,t.store,t.embedder,t.graphStore),Oe(e,r),be(e,t.store,t.embedder,r),pe(e,t.graphStore),ne(e,t.store,t.embedder);let l=r.sources[0]?.path??process.cwd();A(e,t.embedder,t.fileCache,l),N(e,t.embedder,t.store),ie(e,t.embedder,t.store),R(e),Te(e),F(e),se(e,t.embedder,t.store),P(e,t.embedder,t.store,t.graphStore),L(e),z(e),we(e),ve(e),_e(e),ye(e),ge(e),Ne(e),M(e,t.fileCache,l),xe(e),q(e),ae(e,t.embedder,t.store,t.graphStore),W(e),G(e),j(e,t.embedder,t.store),I(e,o),U(e),Se(e),Ce(e),K(e),H(e,s),B(e),le(e,t.embedder),V(e),de(e,t.embedder,t.fileCache),ue(e,t.embedder,t.store),De(e,i),i&&T(e,i),Je(e),He(e),We(e),Be(e),Ue(e),ze(e),Ge(e),Ke(e),Ve(e),qe(e),ce(e,r),t.bridge&&(O(e,t.bridge,t.evolutionCollector),D(e,t.bridge),re(e,t.bridge)),t.policyStore&&Ee(e,t.policyStore),t.evolutionCollector&&oe(e,t.evolutionCollector),f(e,t.store,t.curated),Me(e)}async function pt(e){let t=await X(e),n=ft(t,e);Y.info(`MCP server configured`,{toolCount:$.length,resourceCount:2});let r=async()=>{try{let n=e.sources.map(e=>e.path).join(`, `);Y.info(`Running initial index`,{sourcePaths:n});let r=await t.indexer.index(e,e=>{e.phase===`crawling`||e.phase===`done`||(e.phase===`chunking`&&e.currentFile&&Y.debug(`Indexing file`,{current:e.filesProcessed+1,total:e.filesTotal,file:e.currentFile}),e.phase===`cleanup`&&Y.debug(`Index cleanup`,{staleEntries:e.filesTotal-e.filesProcessed}))});Y.info(`Initial index complete`,{filesProcessed:r.filesProcessed,filesSkipped:r.filesSkipped,chunksCreated:r.chunksCreated,durationMs:r.durationMs});try{await t.store.createFtsIndex()}catch(e){Y.warn(`FTS index creation failed`,J(e))}try{let e=await t.curated.reindexAll();Y.info(`Curated re-index complete`,{indexed:e.indexed})}catch(e){Y.error(`Curated re-index failed`,J(e))}}catch(e){Y.error(`Initial index failed; will retry on aikit_reindex`,J(e))}},i=async()=>{Y.info(`Shutting down`),await Promise.all([t.embedder.shutdown().catch(()=>{}),t.graphStore.close().catch(()=>{}),t.store.close().catch(()=>{})]),process.exit(0)};process.on(`SIGINT`,i),process.on(`SIGTERM`,i);let a=process.ppid,o=setInterval(()=>{try{process.kill(a,0)}catch{Y.info(`Parent process died; shutting down`,{parentPid:a}),clearInterval(o),i()}},5e3);return o.unref(),{server:n,runInitialIndex:r,shutdown:i}}const mt=new Set(`batch.brainstorm.changelog.check.checkpoint.codemod.compact.config.data_transform.delegate.diff_parse.digest.encode.env.eval.evidence_map.file_summary.forge_classify.git_context.graph.guide.health.http.lane.measure.onboard.parse_output.present.process.produce_knowledge.queue.read.regex_test.reindex.remember.rename.replay.restore.schema_validate.scope_map.snippet.stash.status.stratum_card.test_run.time.update.forget.list.watch.web_fetch.web_search.workset`.split(`.`)),ht=5e3,Q=new Set(`brainstorm.changelog.check.checkpoint.codemod.data_transform.delegate.diff_parse.encode.env.eval.evidence_map.forge_classify.git_context.guide.present.health.http.lane.measure.parse_output.process.produce_knowledge.queue.regex_test.rename.replay.restore.schema_validate.snippet.stash.status.test_run.time.watch.web_fetch.web_search.workset`.split(`.`));function gt(e){F(e),L(e),z(e),R(e),I(e),ve(e),_e(e),ye(e),ge(e),q(e),Te(e),we(e),xe(e),Ne(e),Se(e),Ce(e),U(e),W(e),G(e),K(e),H(e),B(e),V(e),De(e),T(e,a),Oe(e),Me(e),Ie(e),Je(e),He(e),We(e),Be(e),Ue(e),ze(e),Ge(e),Ke(e),Ve(e),qe(e)}const $=`analyze_dependencies.analyze_diagram.analyze_entry_points.analyze_patterns.analyze_structure.analyze_symbols.audit.batch.blast_radius.brainstorm.changelog.check.checkpoint.codemod.compact.config.data_transform.dead_symbols.delegate.diff_parse.digest.encode.env.eval.evidence_map.file_summary.find.flow_info.flow_list.flow_reset.flow_start.flow_status.flow_step.forge_classify.forge_ground.forget.git_context.graph.guide.health.http.lane.list.lookup.measure.onboard.parse_output.present.process.produce_knowledge.queue.read.regex_test.reindex.remember.rename.replay.restore.schema_validate.scope_map.search.snippet.stash.status.stratum_card.symbol.test_run.time.trace.update.watch.web_fetch.web_search.workset`.split(`.`);function _t(n,r){let a=new ut({name:n.serverName??`aikit`,version:Fe()},{capabilities:{logging:{},completions:{},prompts:{}}}),u=`initializing`,f=``,m=!1,y=null,b=null,x=null;function te(e){if(!e||typeof e!=`object`)return[];let t=e,n=[];for(let e of[`path`,`file`,`source_path`,`sourcePath`,`filePath`]){let r=t[e];typeof r==`string`&&r&&n.push(r)}for(let e of[`changed_files`,`paths`,`files`]){let r=t[e];if(Array.isArray(r))for(let e of r){if(typeof e==`string`){n.push(e);continue}e&&typeof e==`object`&&typeof e.path==`string`&&n.push(e.path)}}if(Array.isArray(t.sources))for(let e of t.sources)e&&typeof e==`object`&&typeof e.path==`string`&&n.push(e.path);return n}let S=()=>u===`failed`?[`❌ AI Kit initialization failed — this tool is unavailable.`,``,f?`Error: ${f}`:``,``,`**35 tools are still available** and fully functional:`,`check, eval, test_run, git_context, health, measure, web_fetch, web_search,`,`regex_test, encode, stash, checkpoint, lane, process, time, env, and more.`,``,`Try restarting the MCP server to retry initialization.`].filter(Boolean).join(`
1
+ import{BackgroundTaskScheduler as e}from"./background-task.js";import{clearCompletionCache as t}from"./completions.js";import{installCompressionInterceptor as n}from"./compression-interceptor.js";import{CuratedKnowledgeManager as r}from"./curated-manager.js";import{createElicitor as i,noopElicitor as a}from"./elicitor.js";import{IdleTimer as o}from"./idle-timer.js";import{bridgeMcpLogging as s}from"./mcp-logging.js";import{MemoryMonitor as c}from"./memory-monitor.js";import{registerPrompts as l}from"./prompts.js";import{installReplayInterceptor as u}from"./replay-interceptor.js";import{ResourceNotifier as d}from"./resources/resource-notifier.js";import{registerResources as f}from"./resources/resources.js";import{createSamplingClient as p}from"./sampling.js";import{installStructuredContentGuard as m}from"./structured-content-guard.js";import{getToolMeta as h}from"./tool-metadata.js";import{installToolPrefix as g}from"./tool-prefix.js";import{ToolTimeoutError as _,getToolTimeout as v,withTimeout as ee}from"./tool-timeout.js";import{registerAnalyzeDependenciesTool as y,registerAnalyzeDiagramTool as b,registerAnalyzeEntryPointsTool as x,registerAnalyzePatternsTool as te,registerAnalyzeStructureTool as S,registerAnalyzeSymbolsTool as C,registerBlastRadiusTool as w}from"./tools/analyze.tools.js";import{registerAuditTool as ne}from"./tools/audit.tool.js";import{registerBrainstormTool as T}from"./tools/brainstorm.tool.js";import{initBridgeComponents as E,registerErPullTool as D,registerErPushTool as O,registerErSyncStatusTool as re}from"./tools/bridge.tools.js";import{registerConfigTool as k}from"./tools/config.tool.js";import{registerCompactTool as A,registerDeadSymbolsTool as j,registerFileSummaryTool as M,registerFindTool as ie,registerScopeMapTool as N,registerSymbolTool as P,registerTraceTool as ae}from"./tools/context.tools.js";import{registerErEvolveReviewTool as oe}from"./tools/evolution.tools.js";import{registerBatchTool as se,registerCheckTool as F,registerDelegateTool as I,registerEvalTool as L,registerParseOutputTool as R,registerTestRunTool as z}from"./tools/execution.tools.js";import{registerFlowTools as ce}from"./tools/flow.tools.js";import{registerDigestTool as le,registerEvidenceMapTool as B,registerForgeClassifyTool as V,registerForgeGroundTool as ue,registerStratumCardTool as de}from"./tools/forge.tools.js";import{registerForgetTool as fe}from"./tools/forget.tool.js";import{registerGraphTool as pe}from"./tools/graph.tool.js";import{registerGuideTool as H,registerHealthTool as U,registerProcessTool as W,registerWatchTool as G,registerWebFetchTool as K}from"./tools/infra.tools.js";import{registerListTool as me}from"./tools/list.tool.js";import{registerLookupTool as he}from"./tools/lookup.tool.js";import{registerCodemodTool as ge,registerDataTransformTool as q,registerDiffParseTool as _e,registerGitContextTool as ve,registerRenameTool as ye}from"./tools/manipulation.tools.js";import{registerOnboardTool as be}from"./tools/onboard.tool.js";import{registerCheckpointTool as xe,registerLaneTool as Se,registerQueueTool as Ce,registerStashTool as we,registerWorksetTool as Te}from"./tools/persistence.tools.js";import{registerErUpdatePolicyTool as Ee}from"./tools/policy.tools.js";import{registerPresentTool as De}from"./tools/present/tool.js";import"./tools/present/index.js";import{registerProduceKnowledgeTool as Oe}from"./tools/produce.tool.js";import{registerReadTool as ke}from"./tools/read.tool.js";import{registerReindexTool as Ae}from"./tools/reindex.tool.js";import{registerRememberTool as je}from"./tools/remember.tool.js";import{registerReplayTool as Me}from"./tools/replay.tool.js";import{registerRestoreTool as Ne}from"./tools/restore.tool.js";import{registerSearchTool as Pe}from"./tools/search.tool.js";import{getCurrentVersion as Fe}from"./version-check.js";import{registerEarlyStatusTool as Ie,registerStatusTool as Le}from"./tools/status.tool.js";import{registerUpdateTool as Re}from"./tools/update.tool.js";import{registerChangelogTool as ze,registerEncodeTool as Be,registerEnvTool as Ve,registerHttpTool as He,registerMeasureTool as Ue,registerRegexTestTool as We,registerSchemaValidateTool as Ge,registerSnippetTool as Ke,registerTimeTool as qe,registerWebSearchTool as Je}from"./tools/utility.tools.js";import{existsSync as Ye,statSync as Xe}from"node:fs";import{resolve as Ze}from"node:path";import{AIKIT_PATHS as Qe,createLogger as $e,serializeError as J}from"../../core/dist/index.js";import{initializeWasm as et}from"../../chunker/dist/index.js";import{OnnxEmbedder as tt}from"../../embeddings/dist/index.js";import{EvolutionCollector as nt,PolicyStore as rt}from"../../enterprise-bridge/dist/index.js";import{FileHashCache as it,IncrementalIndexer as at}from"../../indexer/dist/index.js";import{SqliteGraphStore as ot,createStore as st}from"../../store/dist/index.js";import{FileCache as ct}from"../../tools/dist/index.js";import{completable as lt}from"@modelcontextprotocol/sdk/server/completable.js";import{McpServer as ut}from"@modelcontextprotocol/sdk/server/mcp.js";import{z as dt}from"zod";const Y=$e(`server`);async function X(e){Y.info(`Initializing AI Kit components`);let[t,n,i,a]=await Promise.all([(async()=>{let t=new tt({model:e.embedding.model,dimensions:e.embedding.dimensions});return await t.initialize(),Y.info(`Embedder loaded`,{modelId:t.modelId,dimensions:t.dimensions}),t})(),(async()=>{let t=await st({backend:e.store.backend,path:e.store.path});return await t.initialize(),Y.info(`Store initialized`),t})(),(async()=>{let t=new ot({path:e.store.path});return await t.initialize(),Y.info(`Graph store initialized`),t})(),(async()=>{let e=await et();return e?Y.info(`WASM tree-sitter enabled for AST analysis`):Y.warn(`WASM tree-sitter not available; analyzers will use regex fallback`),e})()]),o=new at(t,n),s=new it(e.store.path);s.load(),o.setHashCache(s);let c=e.curated.path,l=new r(c,n,t);o.setGraphStore(i);let u=E(e.er),d=u?new rt(e.curated.path):void 0;d&&Y.info(`Policy store initialized`,{ruleCount:d.getRules().length});let f=u?new nt:void 0,p=Ze(e.sources[0]?.path??process.cwd(),Qe.aiKb),m=Ye(p),h=e.onboardDir?Ye(e.onboardDir):!1,g=m||h,_,v=m?p:e.onboardDir;if(g&&v)try{_=Xe(v).mtime.toISOString()}catch{}return Y.info(`Onboard state detected`,{onboardComplete:g,onboardTimestamp:_,aiKbExists:m,onboardDirExists:h}),{embedder:t,store:n,indexer:o,curated:l,graphStore:i,fileCache:new ct,bridge:u,policyStore:d,evolutionCollector:f,onboardComplete:g,onboardTimestamp:_}}function ft(e,t){let n=new ut({name:t.serverName??`aikit`,version:Fe()},{capabilities:{logging:{},completions:{},prompts:{}}});return s(n),g(n,t.toolPrefix??``),Z(n,e,t,i(n),new d(n),p(n)),l(n,{curated:e.curated,store:e.store,graphStore:e.graphStore},t.indexMode),n}function Z(e,t,r,i,a,o,s,c){u(e),m(e),n(e),Pe(e,t.embedder,t.store,t.graphStore,t.bridge,t.evolutionCollector,o),he(e,t.store),Le(e,t.store,t.graphStore,t.curated,{onboardComplete:t.onboardComplete,onboardTimestamp:t.onboardTimestamp},r,s,c),k(e,r),Ae(e,t.indexer,r,t.curated,t.store,a,s),je(e,t.curated,t.policyStore,t.evolutionCollector,a),Re(e,t.curated,a),fe(e,t.curated,a),ke(e,t.curated),me(e,t.curated),S(e,t.store,t.embedder),y(e,t.store,t.embedder),C(e,t.store,t.embedder),te(e,t.store,t.embedder),x(e,t.store,t.embedder),b(e,t.store,t.embedder),w(e,t.store,t.embedder,t.graphStore),Oe(e,r),be(e,t.store,t.embedder,r),pe(e,t.graphStore),ne(e,t.store,t.embedder);let l=r.sources[0]?.path??process.cwd();A(e,t.embedder,t.fileCache,l),N(e,t.embedder,t.store),ie(e,t.embedder,t.store),R(e),Te(e),F(e),se(e,t.embedder,t.store),P(e,t.embedder,t.store,t.graphStore),L(e),z(e),we(e),ve(e),_e(e),ye(e),ge(e),Ne(e),M(e,t.fileCache,l),xe(e),q(e),ae(e,t.embedder,t.store,t.graphStore),W(e),G(e),j(e,t.embedder,t.store),(process.env.AIKIT_DELEGATE===`1`||process.env.AIKIT_DELEGATE===`true`)&&I(e,o),U(e),Se(e),Ce(e),K(e),H(e,s),B(e),le(e,t.embedder),V(e),de(e,t.embedder,t.fileCache),ue(e,t.embedder,t.store),De(e,i),i&&T(e,i),Je(e),He(e),We(e),Be(e),Ue(e),ze(e),Ge(e),Ke(e),Ve(e),qe(e),ce(e,r),t.bridge&&(O(e,t.bridge,t.evolutionCollector),D(e,t.bridge),re(e,t.bridge)),t.policyStore&&Ee(e,t.policyStore),t.evolutionCollector&&oe(e,t.evolutionCollector),f(e,t.store,t.curated),Me(e)}async function pt(e){let t=await X(e),n=ft(t,e);Y.info(`MCP server configured`,{toolCount:$.length,resourceCount:2});let r=async()=>{try{let n=e.sources.map(e=>e.path).join(`, `);Y.info(`Running initial index`,{sourcePaths:n});let r=await t.indexer.index(e,e=>{e.phase===`crawling`||e.phase===`done`||(e.phase===`chunking`&&e.currentFile&&Y.debug(`Indexing file`,{current:e.filesProcessed+1,total:e.filesTotal,file:e.currentFile}),e.phase===`cleanup`&&Y.debug(`Index cleanup`,{staleEntries:e.filesTotal-e.filesProcessed}))});Y.info(`Initial index complete`,{filesProcessed:r.filesProcessed,filesSkipped:r.filesSkipped,chunksCreated:r.chunksCreated,durationMs:r.durationMs});try{await t.store.createFtsIndex()}catch(e){Y.warn(`FTS index creation failed`,J(e))}try{let e=await t.curated.reindexAll();Y.info(`Curated re-index complete`,{indexed:e.indexed})}catch(e){Y.error(`Curated re-index failed`,J(e))}}catch(e){Y.error(`Initial index failed; will retry on aikit_reindex`,J(e))}},i=async()=>{Y.info(`Shutting down`),await Promise.all([t.embedder.shutdown().catch(()=>{}),t.graphStore.close().catch(()=>{}),t.store.close().catch(()=>{})]),process.exit(0)};process.on(`SIGINT`,i),process.on(`SIGTERM`,i);let a=process.ppid,o=setInterval(()=>{try{process.kill(a,0)}catch{Y.info(`Parent process died; shutting down`,{parentPid:a}),clearInterval(o),i()}},5e3);return o.unref(),{server:n,runInitialIndex:r,shutdown:i}}const mt=new Set(`batch.brainstorm.changelog.check.checkpoint.codemod.compact.config.data_transform.delegate.diff_parse.digest.encode.env.eval.evidence_map.file_summary.forge_classify.git_context.graph.guide.health.http.lane.measure.onboard.parse_output.present.process.produce_knowledge.queue.read.regex_test.reindex.remember.rename.replay.restore.schema_validate.scope_map.snippet.stash.status.stratum_card.test_run.time.update.forget.list.watch.web_fetch.web_search.workset`.split(`.`)),ht=5e3,Q=new Set(`brainstorm.changelog.check.checkpoint.codemod.data_transform.delegate.diff_parse.encode.env.eval.evidence_map.forge_classify.git_context.guide.present.health.http.lane.measure.parse_output.process.produce_knowledge.queue.regex_test.rename.replay.restore.schema_validate.snippet.stash.status.test_run.time.watch.web_fetch.web_search.workset`.split(`.`));function gt(e){F(e),L(e),z(e),R(e),(process.env.AIKIT_DELEGATE===`1`||process.env.AIKIT_DELEGATE===`true`)&&I(e),ve(e),_e(e),ye(e),ge(e),q(e),Te(e),we(e),xe(e),Ne(e),Se(e),Ce(e),U(e),W(e),G(e),K(e),H(e),B(e),V(e),De(e),T(e,a),Oe(e),Me(e),Ie(e),Je(e),He(e),We(e),Be(e),Ue(e),ze(e),Ge(e),Ke(e),Ve(e),qe(e)}const $=`analyze_dependencies.analyze_diagram.analyze_entry_points.analyze_patterns.analyze_structure.analyze_symbols.audit.batch.blast_radius.brainstorm.changelog.check.checkpoint.codemod.compact.config.data_transform.dead_symbols.delegate.diff_parse.digest.encode.env.eval.evidence_map.file_summary.find.flow_info.flow_list.flow_reset.flow_start.flow_status.flow_step.forge_classify.forge_ground.forget.git_context.graph.guide.health.http.lane.list.lookup.measure.onboard.parse_output.present.process.produce_knowledge.queue.read.regex_test.reindex.remember.rename.replay.restore.schema_validate.scope_map.search.snippet.stash.status.stratum_card.symbol.test_run.time.trace.update.watch.web_fetch.web_search.workset`.split(`.`);function _t(n,r){let a=new ut({name:n.serverName??`aikit`,version:Fe()},{capabilities:{logging:{},completions:{},prompts:{}}}),u=`initializing`,f=``,m=!1,y=null,b=null,x=null;function te(e){if(!e||typeof e!=`object`)return[];let t=e,n=[];for(let e of[`path`,`file`,`source_path`,`sourcePath`,`filePath`]){let r=t[e];typeof r==`string`&&r&&n.push(r)}for(let e of[`changed_files`,`paths`,`files`]){let r=t[e];if(Array.isArray(r))for(let e of r){if(typeof e==`string`){n.push(e);continue}e&&typeof e==`object`&&typeof e.path==`string`&&n.push(e.path)}}if(Array.isArray(t.sources))for(let e of t.sources)e&&typeof e==`object`&&typeof e.path==`string`&&n.push(e.path);return n}let S=()=>u===`failed`?[`❌ AI Kit initialization failed — this tool is unavailable.`,``,f?`Error: ${f}`:``,``,`**35 tools are still available** and fully functional:`,`check, eval, test_run, git_context, health, measure, web_fetch, web_search,`,`regex_test, encode, stash, checkpoint, lane, process, time, env, and more.`,``,`Try restarting the MCP server to retry initialization.`].filter(Boolean).join(`
2
2
  `):[`AI Kit is still initializing (loading embeddings model & store).`,``,`**35 tools are already available** while initialization completes — including:`,`check, eval, test_run, git_context, health, measure, web_fetch, web_search,`,`regex_test, encode, stash, checkpoint, lane, process, time, env, and more.`,``,`This tool requires the AI Kit index. Please retry in a few seconds,`,`or use one of the available tools above in the meantime.`].join(`
3
3
  `);s(a),g(a,n.toolPrefix??``);let C=a.sendToolListChanged.bind(a);a.sendToolListChanged=()=>{};let w=[];for(let e of $){let t=h(e),n=a.registerTool(e,{title:t.title,description:`${t.title} — initializing, available shortly`,inputSchema:{},annotations:t.annotations},async()=>({content:[{type:`text`,text:S()}]}));Q.has(e)?n.remove():w.push(n)}gt(a),a.sendToolListChanged=C;let ne=a.registerResource(`aikit-status`,`aikit://status`,{description:`AI Kit status (initializing...)`,mimeType:`text/plain`},async()=>({contents:[{uri:`aikit://status`,text:`AI Kit is initializing...`,mimeType:`text/plain`}]})),T=a.registerPrompt(`_init`,{description:`Initializing AI Kit…`,argsSchema:{_dummy:lt(dt.string(),()=>[])}},async()=>({messages:[]})),E,D=new Promise(e=>{E=e}),O,re=new Promise(e=>{O=e}),k=()=>O?.(),A=(async()=>{await re;let e;try{e=await X(n)}catch(e){u=`failed`,f=e instanceof Error?e.message:String(e),Y.error(`AI Kit initialization failed — server continuing with zero-dep tools only`,{error:f});return}let s=a.sendToolListChanged.bind(a);a.sendToolListChanged=()=>{};let h=a.sendPromptListChanged.bind(a);a.sendPromptListChanged=()=>{};let g=a.sendResourceListChanged.bind(a);a.sendResourceListChanged=()=>{};for(let e of w)e.remove();ne.remove(),T.remove();let S=a._registeredTools??{};for(let e of Q)S[e]?.remove();let C=new d(a),D=p(a);Z(a,e,n,i(a),C,D,r,r===`smart`?(()=>{let e=x;return e?.getState?e.getState():null}):null),l(a,{curated:e.curated,store:e.store,graphStore:e.graphStore},r),a.sendToolListChanged=s,a.sendPromptListChanged=h,a.sendResourceListChanged=g,Promise.resolve(a.sendToolListChanged()).catch(()=>{}),Promise.resolve(a.sendPromptListChanged()).catch(()=>{}),Promise.resolve(a.sendResourceListChanged()).catch(()=>{});let O=a._registeredTools??{};for(let[t,n]of Object.entries(O)){if(mt.has(t))continue;let r=n.handler;n.handler=async(...n)=>{if(!e.indexer.isIndexing)return r(...n);let i=m?`re-indexing`:`running initial index`,a=new Promise(e=>setTimeout(()=>e({content:[{type:`text`,text:`⏳ AI Kit is ${i}. The tool "${t}" timed out waiting for index data (${ht/1e3}s).\n\nThe existing index may be temporarily locked. Please retry shortly — indexing will complete automatically.`}]}),ht));return Promise.race([r(...n),a])}}for(let[e,t]of Object.entries(O)){let n=t.handler,r=v(e);t.handler=async(...t)=>{try{return await ee(()=>n(...t),r,e)}catch(t){if(t instanceof _)return{content:[{type:`text`,text:`⏳ Tool "${e}" timed out after ${r/1e3}s. This may indicate a long-running operation. Please retry or break the task into smaller steps.`}]};throw t}}}let k=Object.keys(O).length;k<$.length&&Y.warn(`ALL_TOOL_NAMES count mismatch`,{expectedToolCount:$.length,registeredToolCount:k}),Y.info(`MCP server configured`,{toolCount:$.length,resourceCount:4});let A=new c;A.onPressure((e,n)=>{e===`warning`&&t(),e===`critical`&&(Y.warn(`Memory pressure critical — consider restarting`,{rssMB:Math.round(n/1024/1024)}),t())}),A.start();let j=new o;b=j,j.onIdle(async()=>{if(M.isRunning||e.indexer.isIndexing){Y.info(`Idle cleanup deferred — background tasks still running`),j.touch();return}Y.info(`Idle cleanup: closing store and graph connections`);try{await Promise.all([e.store.close().catch(()=>{}),e.graphStore.close().catch(()=>{})])}catch{}}),j.touch();for(let e of Object.values(O)){let t=e.handler;e.handler=async(...e)=>{if(j.touch(),x){let t=te(e[0]);t.length>0&&x.prioritize(...t)}return t(...e)}}y=e,E?.(e)})(),j=async()=>{let e=await D;b?.setBusy(!0);try{let t=n.sources.map(e=>e.path).join(`, `);Y.info(`Running initial index`,{sourcePaths:t});let r=await e.indexer.index(n,e=>{e.phase===`crawling`||e.phase===`done`||(e.phase===`chunking`&&e.currentFile&&Y.debug(`Indexing file`,{current:e.filesProcessed+1,total:e.filesTotal,file:e.currentFile}),e.phase===`cleanup`&&Y.debug(`Index cleanup`,{staleEntries:e.filesTotal-e.filesProcessed}))});m=!0,Y.info(`Initial index complete`,{filesProcessed:r.filesProcessed,filesSkipped:r.filesSkipped,chunksCreated:r.chunksCreated,durationMs:r.durationMs});try{await e.store.createFtsIndex()}catch(e){Y.warn(`FTS index creation failed`,J(e))}try{let t=await e.curated.reindexAll();Y.info(`Curated re-index complete`,{indexed:t.indexed})}catch(e){Y.error(`Curated re-index failed`,J(e))}}catch(e){Y.error(`Initial index failed; will retry on aikit_reindex`,J(e))}finally{b?.setBusy(!1)}},M=new e,ie=()=>M.schedule({name:`initial-index`,fn:j}),N=process.ppid,P=setInterval(()=>{try{process.kill(N,0)}catch{Y.info(`Parent process died; shutting down`,{parentPid:N}),clearInterval(P),D.then(async e=>{await Promise.all([e.embedder.shutdown().catch(()=>{}),e.graphStore.close().catch(()=>{}),e.store.close().catch(()=>{})])}).catch(()=>{}).finally(()=>process.exit(0))}},5e3);return P.unref(),{server:a,startInit:k,ready:A,runInitialIndex:ie,get kb(){return y},scheduler:M,setSmartScheduler(e){x=e}}}export{$ as ALL_TOOL_NAMES,_t as createLazyServer,ft as createMcpServer,pt as createServer,X as initializeKnowledgeBase,Z as registerMcpTools};
@@ -1 +1 @@
1
- import{getToolMeta as e}from"../tool-metadata.js";import{basename as t,join as n,resolve as r}from"node:path";import{z as i}from"zod";import{readFile as a}from"node:fs/promises";import{createLogger as o,serializeError as s}from"../../../core/dist/index.js";const c=o(`flow-tools`);function l(e){return{content:[{type:`text`,text:e}]}}function u(e){return e instanceof Error?e.message:String(e)}function d(o,d){let f=d.sources?.[0]?.path??process.cwd(),p=n(d.stateDir??n(d.sources[0].path,`.aikit-state`),`flows`),m=n(p,`registry.json`),h=n(p,`state.json`);function g(e,n){let i;return i=e.sourceType===`builtin`?r(f,`.github`,`flows`,t(e.installPath),n):r(e.installPath,n),i.replaceAll(`\\`,`/`)}function _(e){return e.sourceType===`builtin`?r(f,`.github`,`flows`,t(e.installPath)).replaceAll(`\\`,`/`):e.installPath.replaceAll(`\\`,`/`)}async function v(){let{FlowRegistryManager:e,FlowStateMachine:t}=await import(`../../../flows/dist/index.js`);return{registry:new e(m),stateMachine:new t(h)}}let y=e(`flow_list`);o.registerTool(`flow_list`,{title:y.title,description:`List all installed flows and their steps`,annotations:y.annotations,inputSchema:{}},async()=>{try{let{registry:e,stateMachine:t}=await v(),n=e.list(),r=t.getStatus(),i={flows:n.map(e=>({name:e.name,version:e.version,source:e.source,sourceType:e.sourceType,format:e.format,steps:e.manifest.steps.map(e=>e.id)})),activeFlow:r.success&&r.data?{flow:r.data.flow,status:r.data.status,currentStep:r.data.currentStep}:null};return l(JSON.stringify(i,null,2))}catch(e){return c.error(`flow_list failed`,s(e)),l(`Error: ${u(e)}`)}});let b=e(`flow_info`);o.registerTool(`flow_info`,{title:b.title,description:`Show detailed information about a specific flow`,annotations:b.annotations,inputSchema:{name:i.string().describe(`Flow name to get info for`)}},async({name:e})=>{try{let{registry:t}=await v(),n=t.get(e);if(!n)return l(`Flow "${e}" not found. Use flow_list to see available flows.`);let r={name:n.name,version:n.version,description:n.manifest.description,source:n.source,sourceType:n.sourceType,format:n.format,installPath:_(n),registeredAt:n.registeredAt,updatedAt:n.updatedAt,steps:n.manifest.steps.map(e=>({id:e.id,name:e.name,skill:g(n,e.skill),produces:e.produces,requires:e.requires,description:e.description})),agents:n.manifest.agents,artifactsDir:n.manifest.artifacts_dir,install:n.manifest.install};return l(JSON.stringify(r,null,2))}catch(e){return c.error(`flow_info failed`,s(e)),l(`Error: ${u(e)}`)}});let x=e(`flow_start`);o.registerTool(`flow_start`,{title:x.title,description:`Start a flow. Sets the active flow and positions at the first step.`,annotations:x.annotations,inputSchema:{flow:i.string().describe(`Flow name to start (use flow_list to see options)`)}},async({flow:e})=>{try{let{registry:t,stateMachine:n}=await v(),r=t.get(e);if(!r)return l(`Flow "${e}" not found. Use flow_list to see available flows.`);let i=n.start(r.name,r.manifest);if(!i.success||!i.data)return l(`Cannot start: ${i.error}`);let a=i.data,o=r.manifest.steps.find(e=>e.id===a.currentStep),s={started:!0,flow:a.flow,currentStep:a.currentStep,currentStepSkill:r&&o?g(r,o.skill):null,currentStepDescription:o?.description??null,totalSteps:r.manifest.steps.length,stepSequence:r.manifest.steps.map(e=>e.id),artifactsDir:r.manifest.artifacts_dir};return l(JSON.stringify(s,null,2))}catch(e){return c.error(`flow_start failed`,s(e)),l(`Error: ${u(e)}`)}});let S=e(`flow_step`);o.registerTool(`flow_step`,{title:S.title,description:`Advance the active flow: complete current step and move to next, skip current step, or redo current step.`,annotations:S.annotations,inputSchema:{action:i.enum([`next`,`skip`,`redo`]).describe(`next: mark current step done and advance. skip: skip current step. redo: repeat current step.`)}},async({action:e})=>{try{let{registry:t,stateMachine:n}=await v(),r=n.load();if(!r)return l(`No active flow. Use flow_start first.`);let i=t.get(r.flow);if(!i)return l(`Flow "${r.flow}" not found in registry.`);let a=n.step(e,i.manifest);if(!a.success||!a.data)return l(`Cannot ${e}: ${a.error}`);let o=a.data,s=o.currentStep?i.manifest.steps.find(e=>e.id===o.currentStep):null,c={flow:o.flow,status:o.status,action:e,currentStep:o.currentStep,currentStepSkill:i&&s?g(i,s.skill):null,currentStepDescription:s?.description??null,completedSteps:o.completedSteps,skippedSteps:o.skippedSteps,totalSteps:i.manifest.steps.length,remaining:i.manifest.steps.filter(e=>!o.completedSteps.includes(e.id)&&!o.skippedSteps.includes(e.id)&&e.id!==o.currentStep).map(e=>e.id)};return l(JSON.stringify(c,null,2))}catch(e){return c.error(`flow_step failed`,s(e)),l(`Error: ${u(e)}`)}});let C=e(`flow_status`);o.registerTool(`flow_status`,{title:C.title,description:`Show the current flow execution state — which flow is active, current step, completed steps, and artifacts.`,annotations:C.annotations,inputSchema:{}},async()=>{try{let{registry:e,stateMachine:t}=await v(),n=t.getStatus();if(!n.success||!n.data)return l(`No active flow. Use flow_start to begin one, or flow_list to see available flows.`);let r=n.data,i=e.get(r.flow),a=i?.manifest.steps.find(e=>e.id===r.currentStep),o=i&&a?g(i,a.skill):null,s={flow:r.flow,status:r.status,currentStep:r.currentStep,currentStepSkill:o,skillPath:o,currentStepDescription:a?.description??null,completedSteps:r.completedSteps,skippedSteps:r.skippedSteps,artifacts:r.artifacts,startedAt:r.startedAt,updatedAt:r.updatedAt,totalSteps:i?.manifest.steps.length??0,progress:i?`${r.completedSteps.length+r.skippedSteps.length}/${i.manifest.steps.length}`:`unknown`};return l(JSON.stringify(s,null,2))}catch(e){return c.error(`flow_status failed`,s(e)),l(`Error: ${u(e)}`)}});let w=e(`flow_read_skill`);o.registerTool(`flow_read_skill`,{title:w.title===`flow_read_skill`?`Flow Read Skill`:w.title,description:`Read the skill or instruction content for a flow step. If step is omitted, reads the current step.`,annotations:w.title===`flow_read_skill`?{readOnlyHint:!0,idempotentHint:!0}:w.annotations,inputSchema:{step:i.string().optional().describe(`Step id or name to read. Defaults to the current step.`)}},async({step:e})=>{try{let{registry:t,stateMachine:n}=await v(),r=n.getStatus();if(!r.success||!r.data)return l(`No active flow. Use flow_start to begin one, or flow_list to see available flows.`);let i=r.data,o=t.get(i.flow);if(!o)return l(`Flow "${i.flow}" not found in registry.`);let s=e??i.currentStep;if(!s)return l(`No current step is available for the active flow.`);let c=o.manifest.steps.find(e=>e.id===s||e.name===s);return l(c?await a(g(o,c.skill),`utf-8`):`Step "${s}" not found in flow "${i.flow}".`)}catch(e){return c.error(`flow_read_skill failed`,s(e)),e instanceof Error&&`code`in e&&e.code===`ENOENT`?l(`Could not read skill file: ${e.message}`):l(`Error: ${u(e)}`)}});let T=e(`flow_reset`);o.registerTool(`flow_reset`,{title:T.title,description:`Reset the active flow, clearing all state. Use to start over or switch to a different flow.`,annotations:T.annotations,inputSchema:{}},async()=>{try{let{stateMachine:e}=await v(),t=e.reset();return t.success?l(`Flow state reset. Use flow_start to begin a new flow.`):l(`Reset failed: ${t.error}`)}catch(e){return c.error(`flow_reset failed`,s(e)),l(`Error: ${u(e)}`)}})}export{d as registerFlowTools};
1
+ import{getToolMeta as e}from"../tool-metadata.js";import{existsSync as t}from"node:fs";import{basename as n,join as r,resolve as i}from"node:path";import{z as a}from"zod";import{readFile as o}from"node:fs/promises";import{createLogger as s,serializeError as c}from"../../../core/dist/index.js";import{homedir as l}from"node:os";const u=s(`flow-tools`);function d(e){return{content:[{type:`text`,text:e}]}}function f(e){return e instanceof Error?e.message:String(e)}function p(s,p){let m=p.sources?.[0]?.path??process.cwd(),h=r(p.stateDir??r(p.sources[0].path,`.aikit-state`),`flows`),g=r(h,`registry.json`),_=r(h,`state.json`);function v(e,t){return i(y(e),t).replaceAll(`\\`,`/`)}function y(e){if(e.sourceType===`builtin`){let r=n(e.installPath),a=i(m,`.github`,`flows`,r);if(t(a))return a.replaceAll(`\\`,`/`);let o=i(l(),`.copilot`,`flows`,r);return t(o)?o.replaceAll(`\\`,`/`):a.replaceAll(`\\`,`/`)}return e.installPath.replaceAll(`\\`,`/`)}async function b(){let{FlowRegistryManager:e,FlowStateMachine:t}=await import(`../../../flows/dist/index.js`);return{registry:new e(g),stateMachine:new t(_)}}let x=e(`flow_list`);s.registerTool(`flow_list`,{title:x.title,description:`List all installed flows and their steps`,annotations:x.annotations,inputSchema:{}},async()=>{try{let{registry:e,stateMachine:t}=await b(),n=e.list(),r=t.getStatus(),i={flows:n.map(e=>({name:e.name,version:e.version,source:e.source,sourceType:e.sourceType,format:e.format,steps:e.manifest.steps.map(e=>e.id)})),activeFlow:r.success&&r.data?{flow:r.data.flow,status:r.data.status,currentStep:r.data.currentStep}:null};return d(JSON.stringify(i,null,2))}catch(e){return u.error(`flow_list failed`,c(e)),d(`Error: ${f(e)}`)}});let S=e(`flow_info`);s.registerTool(`flow_info`,{title:S.title,description:`Show detailed information about a specific flow`,annotations:S.annotations,inputSchema:{name:a.string().describe(`Flow name to get info for`)}},async({name:e})=>{try{let{registry:t}=await b(),n=t.get(e);if(!n)return d(`Flow "${e}" not found. Use flow_list to see available flows.`);let r={name:n.name,version:n.version,description:n.manifest.description,source:n.source,sourceType:n.sourceType,format:n.format,installPath:y(n),registeredAt:n.registeredAt,updatedAt:n.updatedAt,steps:n.manifest.steps.map(e=>({id:e.id,name:e.name,skill:v(n,e.skill),produces:e.produces,requires:e.requires,description:e.description})),agents:n.manifest.agents,artifactsDir:n.manifest.artifacts_dir,install:n.manifest.install};return d(JSON.stringify(r,null,2))}catch(e){return u.error(`flow_info failed`,c(e)),d(`Error: ${f(e)}`)}});let C=e(`flow_start`);s.registerTool(`flow_start`,{title:C.title,description:`Start a flow. Sets the active flow and positions at the first step.`,annotations:C.annotations,inputSchema:{flow:a.string().describe(`Flow name to start (use flow_list to see options)`)}},async({flow:e})=>{try{let{registry:t,stateMachine:n}=await b(),r=t.get(e);if(!r)return d(`Flow "${e}" not found. Use flow_list to see available flows.`);let i=n.start(r.name,r.manifest);if(!i.success||!i.data)return d(`Cannot start: ${i.error}`);let a=i.data,o=r.manifest.steps.find(e=>e.id===a.currentStep),s={started:!0,flow:a.flow,currentStep:a.currentStep,currentStepSkill:r&&o?v(r,o.skill):null,currentStepDescription:o?.description??null,totalSteps:r.manifest.steps.length,stepSequence:r.manifest.steps.map(e=>e.id),artifactsDir:r.manifest.artifacts_dir};return d(JSON.stringify(s,null,2))}catch(e){return u.error(`flow_start failed`,c(e)),d(`Error: ${f(e)}`)}});let w=e(`flow_step`);s.registerTool(`flow_step`,{title:w.title,description:`Advance the active flow: complete current step and move to next, skip current step, or redo current step.`,annotations:w.annotations,inputSchema:{action:a.enum([`next`,`skip`,`redo`]).describe(`next: mark current step done and advance. skip: skip current step. redo: repeat current step.`)}},async({action:e})=>{try{let{registry:t,stateMachine:n}=await b(),r=n.load();if(!r)return d(`No active flow. Use flow_start first.`);let i=t.get(r.flow);if(!i)return d(`Flow "${r.flow}" not found in registry.`);let a=n.step(e,i.manifest);if(!a.success||!a.data)return d(`Cannot ${e}: ${a.error}`);let o=a.data,s=o.currentStep?i.manifest.steps.find(e=>e.id===o.currentStep):null,c={flow:o.flow,status:o.status,action:e,currentStep:o.currentStep,currentStepSkill:i&&s?v(i,s.skill):null,currentStepDescription:s?.description??null,completedSteps:o.completedSteps,skippedSteps:o.skippedSteps,totalSteps:i.manifest.steps.length,remaining:i.manifest.steps.filter(e=>!o.completedSteps.includes(e.id)&&!o.skippedSteps.includes(e.id)&&e.id!==o.currentStep).map(e=>e.id)};return d(JSON.stringify(c,null,2))}catch(e){return u.error(`flow_step failed`,c(e)),d(`Error: ${f(e)}`)}});let T=e(`flow_status`);s.registerTool(`flow_status`,{title:T.title,description:`Show the current flow execution state — which flow is active, current step, completed steps, and artifacts.`,annotations:T.annotations,inputSchema:{}},async()=>{try{let{registry:e,stateMachine:t}=await b(),n=t.getStatus();if(!n.success||!n.data)return d(`No active flow. Use flow_start to begin one, or flow_list to see available flows.`);let r=n.data,i=e.get(r.flow),a=i?.manifest.steps.find(e=>e.id===r.currentStep),o=i&&a?v(i,a.skill):null,s={flow:r.flow,status:r.status,currentStep:r.currentStep,currentStepSkill:o,skillPath:o,currentStepDescription:a?.description??null,completedSteps:r.completedSteps,skippedSteps:r.skippedSteps,artifacts:r.artifacts,startedAt:r.startedAt,updatedAt:r.updatedAt,totalSteps:i?.manifest.steps.length??0,progress:i?`${r.completedSteps.length+r.skippedSteps.length}/${i.manifest.steps.length}`:`unknown`};return d(JSON.stringify(s,null,2))}catch(e){return u.error(`flow_status failed`,c(e)),d(`Error: ${f(e)}`)}});let E=e(`flow_read_skill`);s.registerTool(`flow_read_skill`,{title:E.title===`flow_read_skill`?`Flow Read Skill`:E.title,description:`Read the skill or instruction content for a flow step. If step is omitted, reads the current step.`,annotations:E.title===`flow_read_skill`?{readOnlyHint:!0,idempotentHint:!0}:E.annotations,inputSchema:{step:a.string().optional().describe(`Step id or name to read. Defaults to the current step.`)}},async({step:e})=>{try{let{registry:t,stateMachine:n}=await b(),r=n.getStatus();if(!r.success||!r.data)return d(`No active flow. Use flow_start to begin one, or flow_list to see available flows.`);let i=r.data,a=t.get(i.flow);if(!a)return d(`Flow "${i.flow}" not found in registry.`);let s=e??i.currentStep;if(!s)return d(`No current step is available for the active flow.`);let c=a.manifest.steps.find(e=>e.id===s||e.name===s);return d(c?await o(v(a,c.skill),`utf-8`):`Step "${s}" not found in flow "${i.flow}".`)}catch(e){return u.error(`flow_read_skill failed`,c(e)),e instanceof Error&&`code`in e&&e.code===`ENOENT`?d(`Could not read skill file: ${e.message}`):d(`Error: ${f(e)}`)}});let D=e(`flow_reset`);s.registerTool(`flow_reset`,{title:D.title,description:`Reset the active flow, clearing all state. Use to start over or switch to a different flow.`,annotations:D.annotations,inputSchema:{}},async()=>{try{let{stateMachine:e}=await b(),t=e.reset();return t.success?d(`Flow state reset. Use flow_start to begin a new flow.`):d(`Reset failed: ${t.error}`)}catch(e){return u.error(`flow_reset failed`,c(e)),d(`Error: ${f(e)}`)}})}export{p as registerFlowTools};
@@ -17,7 +17,7 @@ declare function formatAsHtml(title: string | undefined, content: unknown, actio
17
17
  type: 'text';
18
18
  text: string;
19
19
  } | UIResource>;
20
- structuredContent: {
20
+ structuredContent?: {
21
21
  title?: string;
22
22
  content?: unknown;
23
23
  actions: Array<Record<string, unknown>>;
@@ -16,4 +16,4 @@ import{getToolMeta as e}from"../../tool-metadata.js";import{buildBrowserHtml as
16
16
  - "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.
17
17
  FORMAT RULE: If no user interaction is needed → use "html". If you need user input back → use "browser".
18
18
  BROWSER WORKFLOW: After calling present with format "browser", you MUST extract the URL from the response and call openBrowserPage({ url }) to open it in VS Code Simple Browser. A system browser fallback also opens automatically, but always call openBrowserPage yourself.`,annotations:r.annotations,inputSchema:_,_meta:{ui:{resourceUri:h}}},async({format:e,title:t,content:r,actions:i,template:a})=>(e??`html`)===`browser`||Array.isArray(i)&&i.length>0?await w(t,r,i,n,a):T(t,r,i,a))}async function w(e,r,i,a,o){let s=n(e,r),c=t(e,r,i,o),l=p({uri:`ui://aikit/present-browser.html`,content:{type:`rawHtml`,htmlString:c},encoding:`text`,adapters:{mcpApps:{enabled:!0}}}),u,m,h=Array.isArray(i)?i:[],g=``,_;try{b&&=(b.close(),null),h.length>0&&(u=new Promise(e=>{m=e}));let e=!1;g=await new Promise((t,n)=>{let r=f((t,n)=>{if(e||(e=!0,_&&clearTimeout(_)),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);m?.(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(c)});r.listen(0,`127.0.0.1`,()=>{let i=r.address();if(typeof i==`object`&&i){b=r;let n=`http://127.0.0.1:${i.port}`;_=setTimeout(()=>{if(!e)try{d(process.platform===`win32`?`start "" "${n}"`:process.platform===`darwin`?`open "${n}"`:`xdg-open "${n}"`)}catch{}},8e3),_.unref(),t(n)}else n(Error(`Failed to start present server`))}),setTimeout(()=>{r.close(),b===r&&(b=null)},300*1e3).unref()})}catch{}let v=g?`${s}\n\n---\n🌐 **Dashboard opened in browser:** ${g}\n\n**IMPORTANT:** You MUST now open this URL using the \`openBrowserPage\` tool (Simple Browser). 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.`:s;if(h.length>0&&a?.available&&u)try{let e=await Promise.race([u,new Promise((e,t)=>setTimeout(()=>t(Error(`timeout`)),300*1e3))]);return{content:[{type:`text`,text:`${v}\n\n✅ **Selected:** ${e.actionId} = \`${e.value}\``},l]}}catch{return{content:[{type:`text`,text:`${v}\n\n⚠️ *No selection received (timed out).*`},l]}}return{content:[{type:`text`,text:v},l]}}function T(e,r,i,a){let o=Array.isArray(i)?i:[],s=n(e,r);if(o.length>0){let e=[``];for(let t=0;t<o.length;t++){let n=o[t],r=typeof n.label==`string`?n.label:`Action ${t+1}`;if(n.type===`select`&&Array.isArray(n.options)){let i=n.options.map(e=>typeof e==`string`?e:e.label).join(`, `);e.push(`${t+1}. **${r}** — choose: ${i}`)}else e.push(`${t+1}. **${r}**`)}s+=`\n${e.join(`
19
- `)}`}let c=p({uri:`ui://aikit/present-static.html`,content:{type:`rawHtml`,htmlString:t(e,r,i,a)},encoding:`text`,adapters:{mcpApps:{enabled:!0}}});return{content:[{type:`text`,text:s},c],structuredContent:{title:e,content:r,actions:o}}}export{w as formatAsBrowser,T as formatAsHtml,S as getPresentHtml,C as registerPresentTool,x as resolvePresentHtml};
19
+ `)}`}let c=p({uri:`ui://aikit/present-static.html`,content:{type:`rawHtml`,htmlString:t(e,r,i,a)},encoding:`text`,adapters:{mcpApps:{enabled:!0}}});return{content:[{type:`text`,text:s},c]}}export{w as formatAsBrowser,T as formatAsHtml,S as getPresentHtml,C as registerPresentTool,x as resolvePresentHtml};
@@ -1 +1 @@
1
- import{existsSync as e,readFileSync as t}from"node:fs";import{dirname as n,resolve as r}from"node:path";import{fileURLToPath as i}from"node:url";import{createLogger as a}from"../../core/dist/index.js";import{execFile as o}from"node:child_process";import{homedir as s}from"node:os";const c=a(`server`);function l(){let e=r(n(i(import.meta.url)),`..`,`..`,`..`,`package.json`);try{return JSON.parse(t(e,`utf-8`)).version??`0.0.0`}catch{return`0.0.0`}}function u(e,t){let n=e.split(`.`).map(Number),r=t.split(`.`).map(Number);for(let e=0;e<3;e++){let t=(n[e]??0)-(r[e]??0);if(t!==0)return t>0?1:-1}return 0}function d(){let e=l();fetch(`https://registry.npmjs.org/@vpxa/aikit/latest`,{signal:AbortSignal.timeout(5e3)}).then(e=>{if(e.ok)return e.json()}).then(t=>{if(!t||typeof t!=`object`)return;let n=t.version;n&&u(e,n)<0&&c.warn(`Update available`,{currentVersion:e,latestVersion:n,updateCommand:`aikit upgrade`})}).catch(()=>{})}function f(){try{let n=r(s(),`.copilot`,`.aikit-scaffold.json`);return e(n)?JSON.parse(t(n,`utf-8`)).version??null:null}catch{return null}}function p(){try{let n=r(process.cwd(),`.github`,`.aikit-scaffold.json`);return e(n)?JSON.parse(t(n,`utf-8`)).version??null:null}catch{return null}}let m=`idle`,h=null;function g(){return{state:m,error:h}}function _(){try{let t=l(),a=f(),s=p();if(!(a!=null&&a!==t)&&!(s!=null&&s!==t)||m===`pending`||m===`success`)return;m=`pending`,h=null,c.info(`Scaffold version mismatch — auto-upgrading`,{serverVersion:t,userScaffoldVersion:a,workspaceScaffoldVersion:s});let u=r(n(i(import.meta.url)),`..`,`..`,`..`,`bin`,`aikit.mjs`);if(!e(u)){m=`failed`,h=`aikit CLI binary not found at ${u}`,c.warn(`Cannot auto-upgrade: aikit CLI binary not found`,{binPath:u});return}o(process.execPath,[u,`upgrade`],{timeout:3e4,windowsHide:!0},(e,t,n)=>{e?(m=`failed`,h=e.message,c.warn(`Auto-upgrade failed`,{error:e.message,stderr:n?.slice(0,500)})):(m=`success`,h=null,c.info(`Auto-upgrade complete`))}).unref()}catch(e){m=`failed`,h=e instanceof Error?e.message:String(e),c.warn(`Auto-upgrade check failed`,{error:h})}}export{_ as autoUpgradeScaffold,d as checkForUpdates,l as getCurrentVersion,g as getUpgradeState};
1
+ import{existsSync as e,readFileSync as t}from"node:fs";import{dirname as n,resolve as r}from"node:path";import{fileURLToPath as i}from"node:url";import{createLogger as a}from"../../core/dist/index.js";import{homedir as o}from"node:os";import{execFile as s}from"node:child_process";const c=a(`server`);function l(){let e=r(n(i(import.meta.url)),`..`,`..`,`..`,`package.json`);try{return JSON.parse(t(e,`utf-8`)).version??`0.0.0`}catch{return`0.0.0`}}function u(e,t){let n=e.split(`.`).map(Number),r=t.split(`.`).map(Number);for(let e=0;e<3;e++){let t=(n[e]??0)-(r[e]??0);if(t!==0)return t>0?1:-1}return 0}function d(){let e=l();fetch(`https://registry.npmjs.org/@vpxa/aikit/latest`,{signal:AbortSignal.timeout(5e3)}).then(e=>{if(e.ok)return e.json()}).then(t=>{if(!t||typeof t!=`object`)return;let n=t.version;n&&u(e,n)<0&&c.warn(`Update available`,{currentVersion:e,latestVersion:n,updateCommand:`aikit upgrade`})}).catch(()=>{})}function f(){try{let n=r(o(),`.copilot`,`.aikit-scaffold.json`);return e(n)?JSON.parse(t(n,`utf-8`)).version??null:null}catch{return null}}function p(){try{let n=r(process.cwd(),`.github`,`.aikit-scaffold.json`);return e(n)?JSON.parse(t(n,`utf-8`)).version??null:null}catch{return null}}let m=`idle`,h=null;function g(){return{state:m,error:h}}function _(){try{let t=l(),a=f(),o=p();if(!(a!=null&&a!==t)&&!(o!=null&&o!==t)||m===`pending`||m===`success`)return;m=`pending`,h=null,c.info(`Scaffold version mismatch — auto-upgrading`,{serverVersion:t,userScaffoldVersion:a,workspaceScaffoldVersion:o});let u=r(n(i(import.meta.url)),`..`,`..`,`..`,`bin`,`aikit.mjs`);if(!e(u)){m=`failed`,h=`aikit CLI binary not found at ${u}`,c.warn(`Cannot auto-upgrade: aikit CLI binary not found`,{binPath:u});return}s(process.execPath,[u,`upgrade`],{timeout:3e4,windowsHide:!0},(e,t,n)=>{e?(m=`failed`,h=e.message,c.warn(`Auto-upgrade failed`,{error:e.message,stderr:n?.slice(0,500)})):(m=`success`,h=null,c.info(`Auto-upgrade complete`))}).unref()}catch(e){m=`failed`,h=e instanceof Error?e.message:String(e),c.warn(`Auto-upgrade check failed`,{error:h})}}export{_ as autoUpgradeScaffold,d as checkForUpdates,l as getCurrentVersion,g as getUpgradeState};
@@ -1 +1 @@
1
- import{request as e}from"node:http";const t=`http://localhost:11434`;async function n(e=t){let n=await i(`${e}/api/tags`),r;try{r=JSON.parse(n)}catch{throw Error(`Ollama returned invalid JSON`)}return(r.models??[]).map(e=>e.name)}async function r(e){let r=e.baseUrl??t,i=e.timeout??12e4,o;try{o=await n(r)}catch{return{model:e.model??`unknown`,response:``,durationMs:0,error:`Ollama is not running at ${r}. Start it with: ollama serve`}}if(o.length===0)return{model:`none`,response:``,durationMs:0,error:`No Ollama models available. Pull one with: ollama pull qwen2.5-coder:7b`};let s=e.model??o[0];if(!o.includes(s))return{model:s,response:``,durationMs:0,error:`Model "${s}" not found. Available: ${o.join(`, `)}`};let c=``;e.context&&(c+=`<context>\n${e.context}\n</context>\n\n`),c+=e.prompt;let l=Date.now(),u=JSON.stringify({model:s,prompt:c,system:e.system,stream:!1,options:{temperature:e.temperature??.3}});try{let e=await a(`${r}/api/generate`,u,i),t=JSON.parse(e);return t.error?{model:s,response:``,durationMs:Date.now()-l,error:t.error}:{model:s,response:(t.response??``).trim(),durationMs:Date.now()-l,tokenCount:t.eval_count}}catch(e){return{model:s,response:``,durationMs:Date.now()-l,error:e instanceof Error?e.message:String(e)}}}function i(t){return new Promise((n,r)=>{let i=new URL(t),a=e({hostname:i.hostname,port:i.port,path:i.pathname,method:`GET`,timeout:5e3},e=>{let t=[];e.on(`data`,e=>t.push(e)),e.on(`end`,()=>n(Buffer.concat(t).toString(`utf-8`)))});a.on(`error`,r),a.on(`timeout`,()=>{a.destroy(),r(Error(`Connection timeout`))}),a.end()})}function a(t,n,r){return new Promise((i,a)=>{let o=new URL(t),s=e({hostname:o.hostname,port:o.port,path:o.pathname,method:`POST`,headers:{"Content-Type":`application/json`,"Content-Length":Buffer.byteLength(n)},timeout:r},e=>{let t=[];e.on(`data`,e=>t.push(e)),e.on(`end`,()=>i(Buffer.concat(t).toString(`utf-8`)))});s.on(`error`,a),s.on(`timeout`,()=>{s.destroy(),a(Error(`Ollama request timed out after ${r}ms`))}),s.write(n),s.end()})}export{r as delegate,n as delegateListModels};
1
+ import{request as e}from"node:http";const t=`http://localhost:11434`;async function n(e=t){let n=await i(`${e}/api/tags`),r;try{r=JSON.parse(n)}catch{throw Error(`Ollama returned invalid JSON`)}return(r.models??[]).map(e=>e.name)}async function r(e){let r=e.baseUrl??t,i=e.timeout??12e4,o;try{o=await n(r)}catch{return{model:e.model??`unknown`,response:``,durationMs:0,error:`Ollama is not running at ${r}. Start it with: ollama serve`}}if(o.length===0)return{model:`none`,response:``,durationMs:0,error:`No Ollama models available. Pull one with: ollama pull gemma4:e2b`};let s=e.model??o[0];if(!o.includes(s))return{model:s,response:``,durationMs:0,error:`Model "${s}" not found. Available: ${o.join(`, `)}`};let c=``;e.context&&(c+=`<context>\n${e.context}\n</context>\n\n`),c+=e.prompt;let l=Date.now(),u=JSON.stringify({model:s,prompt:c,system:e.system,stream:!1,options:{temperature:e.temperature??.3}});try{let e=await a(`${r}/api/generate`,u,i),t=JSON.parse(e);return t.error?{model:s,response:``,durationMs:Date.now()-l,error:t.error}:{model:s,response:(t.response??``).trim(),durationMs:Date.now()-l,tokenCount:t.eval_count}}catch(e){return{model:s,response:``,durationMs:Date.now()-l,error:e instanceof Error?e.message:String(e)}}}function i(t){return new Promise((n,r)=>{let i=new URL(t),a=e({hostname:i.hostname,port:i.port,path:i.pathname,method:`GET`,timeout:5e3},e=>{let t=[];e.on(`data`,e=>t.push(e)),e.on(`end`,()=>n(Buffer.concat(t).toString(`utf-8`)))});a.on(`error`,r),a.on(`timeout`,()=>{a.destroy(),r(Error(`Connection timeout`))}),a.end()})}function a(t,n,r){return new Promise((i,a)=>{let o=new URL(t),s=e({hostname:o.hostname,port:o.port,path:o.pathname,method:`POST`,headers:{"Content-Type":`application/json`,"Content-Length":Buffer.byteLength(n)},timeout:r},e=>{let t=[];e.on(`data`,e=>t.push(e)),e.on(`end`,()=>i(Buffer.concat(t).toString(`utf-8`)))});s.on(`error`,a),s.on(`timeout`,()=>{s.destroy(),a(Error(`Ollama request timed out after ${r}ms`))}),s.write(n),s.end()})}export{r as delegate,n as delegateListModels};
@@ -1,4 +1,4 @@
1
- import{paragraphTruncate as e}from"./truncation.js";import t from"turndown";const n=`script,style,noscript,iframe,svg,nav,footer,header,aside,form,button,input,select,textarea,[role="navigation"],[role="banner"],[role="contentinfo"],[aria-hidden="true"],.sidebar,.nav,.menu,.footer,.header,.ad,.advertisement,.cookie-banner,.popup,.modal`.split(`,`),r=[`article`,`[role="main"]`,`main`,`.post-content`,`.article-content`,`.entry-content`,`.content`,`#content`,`.prose`,`.markdown-body`,`.documentation`,`.doc-content`];async function i(e){let{url:t,mode:i=`markdown`,selector:d,maxLength:f=15e3,includeMetadata:p=!0,includeLinks:m=!1,includeImages:h=!1,timeout:g=15e3}=e,_=new URL(t);if(_.protocol!==`http:`&&_.protocol!==`https:`)throw Error(`Unsupported protocol: ${_.protocol} — only http/https allowed`);let v=new AbortController,y=setTimeout(()=>v.abort(),g),b;try{b=await fetch(t,{signal:v.signal,headers:{"User-Agent":`aikit-web-fetch/1.0 (LLM context tool)`,Accept:`text/html,application/xhtml+xml,text/plain`},redirect:`follow`})}finally{clearTimeout(y)}if(!b.ok)throw Error(`HTTP ${b.status}: ${b.statusText}`);let x=b.headers.get(`content-type`)??``,S=/text\/html|application\/xhtml\+xml/i.test(x),C=await b.text(),w=b.url;if(!S){let e=C,t=w.split(`/`).pop()??``;p&&(e=c(t,``,w)+e);let n=e.length,r=n>f;return r&&(e=u(e,f)),{content:e,title:t,description:``,url:w,originalLength:n,truncated:r}}let{parseHTML:T}=await import(`linkedom`),{document:E}=T(C),D=E.querySelector(`title`)?.textContent?.trim()??E.querySelector(`meta[property="og:title"]`)?.getAttribute(`content`)?.trim()??``,O=E.querySelector(`meta[name="description"]`)?.getAttribute(`content`)?.trim()??E.querySelector(`meta[property="og:description"]`)?.getAttribute(`content`)?.trim()??``;for(let e of n)for(let t of E.querySelectorAll(e))t.remove();if(!h)for(let e of E.querySelectorAll(`img`))e.remove();let k=null;if(d){if(k=E.querySelector(d),!k)throw Error(`Selector "${d}" matched no elements on the page`)}else{for(let e of r)if(k=E.querySelector(e),k)break;k||=E.querySelector(`body`)}if(!k)return{content:`(empty page — no content found)`,title:D,description:O,url:w,originalLength:0,truncated:!1};let A=k.innerHTML,j=[];if(m||i===`links`)for(let e of k.querySelectorAll(`a[href]`)){let t=e.textContent?.trim(),n=e.getAttribute(`href`);t&&n&&!n.startsWith(`#`)&&!n.startsWith(`javascript:`)&&j.push({text:t,href:l(n,w)})}let M;switch(i){case`raw`:M=A;break;case`links`:M=s(j);break;case`outline`:M=o(k);break;default:M=a(A,h);break}p&&i!==`links`&&(M=c(D,O,w)+M),m&&i!==`links`&&j.length>0&&(M+=`\n\n---\n\n## Links\n\n${s(j)}`);let N=M.length,P=N>f;return P&&(M=u(M,f)),{content:M,title:D,description:O,url:w,originalLength:N,truncated:P}}function a(e,n){let r=new t({headingStyle:`atx`,codeBlockStyle:`fenced`,bulletListMarker:`-`});r.addRule(`emptyLinks`,{filter:e=>e.nodeName===`A`&&!e.textContent?.trim(),replacement:()=>``}),n||r.addRule(`removeImages`,{filter:`img`,replacement:()=>``});let i=r.turndown(e);return i=i.replace(/\n{3,}/g,`
1
+ import{paragraphTruncate as e}from"./truncation.js";import t from"turndown";const n=`script,style,noscript,iframe,svg,nav,footer,header,aside,form,button,input,select,textarea,[role="navigation"],[role="banner"],[role="contentinfo"],[aria-hidden="true"],.sidebar,.nav,.menu,.footer,.header,.ad,.advertisement,.cookie-banner,.popup,.modal`.split(`,`),r=[`article`,`[role="main"]`,`main`,`.post-content`,`.article-content`,`.entry-content`,`.content`,`#content`,`.prose`,`.markdown-body`,`.documentation`,`.doc-content`];async function i(e){let{url:t,mode:i=`markdown`,selector:d,maxLength:f=15e3,includeMetadata:p=!0,includeLinks:m=!1,includeImages:h=!1,timeout:g=6e4}=e,_=new URL(t);if(_.protocol!==`http:`&&_.protocol!==`https:`)throw Error(`Unsupported protocol: ${_.protocol} — only http/https allowed`);let v=new AbortController,y=setTimeout(()=>v.abort(),g),b,x,S=``,C=!1,w=``;try{if(b=await fetch(t,{signal:v.signal,headers:{"User-Agent":`aikit-web-fetch/1.0 (LLM context tool)`,Accept:`text/html,application/xhtml+xml,text/plain`},redirect:`follow`}),!b.ok)throw Error(`HTTP ${b.status}: ${b.statusText}`);x=await b.text(),S=b.headers.get(`content-type`)??``,C=/text\/html|application\/xhtml\+xml/i.test(S),w=b.url}finally{clearTimeout(y)}if(!C){let e=x,t=w.split(`/`).pop()??``;p&&(e=c(t,``,w)+e);let n=e.length,r=n>f;return r&&(e=u(e,f)),{content:e,title:t,description:``,url:w,originalLength:n,truncated:r}}let{parseHTML:T}=await import(`linkedom`),{document:E}=T(x),D=E.querySelector(`title`)?.textContent?.trim()??E.querySelector(`meta[property="og:title"]`)?.getAttribute(`content`)?.trim()??``,O=E.querySelector(`meta[name="description"]`)?.getAttribute(`content`)?.trim()??E.querySelector(`meta[property="og:description"]`)?.getAttribute(`content`)?.trim()??``;for(let e of n)for(let t of E.querySelectorAll(e))t.remove();if(!h)for(let e of E.querySelectorAll(`img`))e.remove();let k=null;if(d){if(k=E.querySelector(d),!k)throw Error(`Selector "${d}" matched no elements on the page`)}else{for(let e of r)if(k=E.querySelector(e),k)break;k||=E.querySelector(`body`)}if(!k)return{content:`(empty page — no content found)`,title:D,description:O,url:w,originalLength:0,truncated:!1};let A=k.innerHTML,j=[];if(m||i===`links`)for(let e of k.querySelectorAll(`a[href]`)){let t=e.textContent?.trim(),n=e.getAttribute(`href`);t&&n&&!n.startsWith(`#`)&&!n.startsWith(`javascript:`)&&j.push({text:t,href:l(n,w)})}let M;switch(i){case`raw`:M=A;break;case`links`:M=s(j);break;case`outline`:M=o(k);break;default:M=a(A,h);break}p&&i!==`links`&&(M=c(D,O,w)+M),m&&i!==`links`&&j.length>0&&(M+=`\n\n---\n\n## Links\n\n${s(j)}`);let N=M.length,P=N>f;return P&&(M=u(M,f)),{content:M,title:D,description:O,url:w,originalLength:N,truncated:P}}function a(e,n){let r=new t({headingStyle:`atx`,codeBlockStyle:`fenced`,bulletListMarker:`-`});r.addRule(`emptyLinks`,{filter:e=>e.nodeName===`A`&&!e.textContent?.trim(),replacement:()=>``}),n||r.addRule(`removeImages`,{filter:`img`,replacement:()=>``});let i=r.turndown(e);return i=i.replace(/\n{3,}/g,`
2
2
 
3
3
  `).trim(),i}function o(e){let t=e.querySelectorAll(`h1, h2, h3, h4, h5, h6`),n=[];for(let e of t){let t=Number.parseInt(e.tagName.slice(1),10),r=` `.repeat(t-1),i=e.textContent?.trim()??``;i&&n.push(`${r}- ${i}`)}return n.length>0?n.join(`
4
4
  `):`(no headings found)`}function s(e){if(e.length===0)return`(no links found)`;let t=new Set,n=[];for(let r of e)t.has(r.href)||(t.add(r.href),n.push(r));return n.map(e=>`- [${e.text}](${e.href})`).join(`
@@ -64,8 +64,14 @@ function buildToolsYaml(toolRole) {
64
64
  }
65
65
 
66
66
  function copilotModel(agentName) {
67
- const base = MODELS[agentName];
68
- return base ? `${base} (copilot)` : 'Claude Opus 4.6 (copilot)';
67
+ const models = MODELS[agentName];
68
+ if (!models) return 'Auto (copilot)';
69
+ if (Array.isArray(models)) {
70
+ if (models.length === 0) return 'Auto (copilot)';
71
+ if (models.length === 1) return models[0];
72
+ return `[${models.join(', ')}]`;
73
+ }
74
+ return models;
69
75
  }
70
76
 
71
77
  const FLOWS_SECTION = [
@@ -84,13 +90,15 @@ function buildAgentTable() {
84
90
  if (def.variants) {
85
91
  for (const suffix of VARIANT_GROUPS[name] || []) {
86
92
  const fullName = `${name}-${suffix}`;
87
- const model = MODELS[fullName] || 'Unknown';
93
+ const models = MODELS[fullName] || MODELS[name];
94
+ const model = Array.isArray(models) ? models[0] : models || 'Unknown';
88
95
  const varDef = def.variants[suffix] || {};
89
96
  const desc = varDef.description || def.description;
90
97
  rows.push(`| **${fullName}** | ${desc} | ${model} | ${def.category} |`);
91
98
  }
92
99
  } else {
93
- const model = MODELS[name] || 'Unknown';
100
+ const models = MODELS[name];
101
+ const model = Array.isArray(models) ? models[0] : models || 'Unknown';
94
102
  rows.push(`| **${name}** | ${def.description} | ${model} | ${def.category} |`);
95
103
  }
96
104
  }
@@ -40,26 +40,43 @@ ${agentTable}
40
40
  3. After review: \`evidence_map({ action: "gate", task_id })\` → YIELD/HOLD/HARD_BLOCK
41
41
  4. Auto-upgrade tier if unknowns reveal contract/security issues
42
42
 
43
- ## Workflow
43
+ ## Flow-Driven Development
44
44
 
45
- ### Phase 1: Planning
46
- 1. Read onboard artifacts → parse goal → identify affected subsystems → \`forge_classify\`
47
- 2. Research: <5 files direct, 5-15 Explorer→Researcher, >15 multiple parallel
48
- 3. Draft plan: 3-10 phases, agent assignments, TDD steps, dependency graph
49
- 4. Batch independent phases for parallel execution
50
- 5. **🛑 STOP — user approval required**
45
+ Orchestrator uses the flow system for structured development. Flows define the step sequence — Orchestrator adds multi-agent orchestration, quality gates, and review protocols on top.
51
46
 
52
- ### Phase 2: Implementation Cycle
47
+ ### Flow Selection
53
48
 
54
- **🚨 PRE-DISPATCH GATE complete ALL before ANY \`runSubagent\` call:**
49
+ | Situation | Flow | Steps |
50
+ |-----------|------|-------|
51
+ | Bug fix, small feature, refactoring | \`aikit:basic\` | assess → implement → verify |
52
+ | New feature, major change, multi-file | \`aikit:advanced\` | spec → plan → task → execute → verify |
53
+ | Custom/specialized work | Check \`flow_list\` | Follow flow-specific steps |
55
54
 
56
- 1. \`multi-agents-development\` skill loaded? (Bootstrap step 4 if not, load NOW)
57
- 2. ✅ Task decomposition table produced? (show user: task → files → agent → parallel batch)
58
- 3. ✅ Independence Check passed per pair? (shared files? shared state? ordering dependency? → must be "No" for parallel)
59
- 4. ✅ Each task ≤ 3 files? (if not, split further)
60
- 5. ✅ Parallel batches identified? (tasks with no dependencies MUST be in same batch)
55
+ **If multiple flows could apply and user hasn't specified ask user to choose.**
61
56
 
62
- **Decomposition output format** (show this to user before dispatching):
57
+ ### Session Start Flow Check
58
+
59
+ 1. \`flow_status\` — check for active flow
60
+ 2. If active:
61
+ - Note current step name and skill path
62
+ - Read the current step skill with \`flow_read_skill\`
63
+ - Follow its instructions
64
+ - When complete: \`flow_step({ action: 'next' })\`
65
+ 3. If no active flow:
66
+ - \`flow_list\` — check ALL available flows (builtin + custom)
67
+ - Recommend appropriate flow based on task scope
68
+ - \`flow_start({ flow: '<name>' })\` after user confirms
69
+
70
+ ### Orchestrator Protocols (apply during ALL flow steps)
71
+
72
+ **PRE-DISPATCH GATE — complete ALL before ANY \`runSubagent\` call:**
73
+ 1. ✅ \`multi-agents-development\` skill loaded?
74
+ 2. ✅ Task decomposition table produced?
75
+ 3. ✅ Independence Check passed per pair?
76
+ 4. ✅ Each task ≤ 3 files?
77
+ 5. ✅ Parallel batches identified?
78
+
79
+ **Decomposition output format:**
63
80
 
64
81
  \`\`\`
65
82
  Batch 1 (parallel):
@@ -69,23 +86,35 @@ Batch 2 (after batch 1):
69
86
  Task C: [agent] → [file5] — [goal] (depends on A)
70
87
  \`\`\`
71
88
 
72
- **Prompt every subagent with** (use \`multi-agents-development\` skill templates):
73
- 1. **Scope** — exact files to touch + boundary (do NOT touch)
89
+ **Subagent prompt template:**
90
+ 1. **Scope** — exact files + boundary
74
91
  2. **Goal** — acceptance criteria, testable
75
- 3. **Arch Context** — paste actual code snippets from \`compact()\`/\`digest()\`
76
- 4. **Constraints** — patterns, conventions, anti-patterns
92
+ 3. **Arch Context** — code snippets from \`compact()\`/\`digest()\`
93
+ 4. **Constraints** — patterns, conventions
77
94
  5. **FORGE** — tier + evidence requirements
78
95
  6. **Self-Review** — checklist before declaring status
79
96
 
80
- **Subagent status protocol**: \`DONE\` | \`DONE_WITH_CONCERNS\` | \`NEEDS_CONTEXT\` | \`BLOCKED\`
97
+ **Subagent status protocol:** \`DONE\` | \`DONE_WITH_CONCERNS\` | \`NEEDS_CONTEXT\` | \`BLOCKED\`
81
98
 
82
- **Per-batch flow**: Dispatch (parallel) Spec Review → Code Quality Review (Alpha+Beta parallel) → Arch Review (if boundary changes) → Security (if applicable) → \`evidence_map\` gate → **🛑 STOP — present commit message**
99
+ **Additional Orchestrator requirements during flow execution:**
100
+ - Apply the PRE-DISPATCH GATE before any subagent dispatch, regardless of flow
101
+ - Apply FORGE at classification and verification points; pass tier/evidence expectations into subagents and gate with \`evidence_map\`
102
+ - Enforce delegation rules at all times — Orchestrator never implements code directly
103
+ - Use the subagent prompt template for every dispatch so step-specific flow instructions are grounded in actual code context
83
104
 
84
- ### Phase 3: Completion
85
- 1. Optional: Refactor pass (separate commit)
86
- 2. Documenter for docs updates
87
- 3. \`remember\` all decisions, patterns, gotchas, conventions
88
- 4. \`reindex({})\` + \`produce_knowledge({ path: "." })\`
105
+ **Per-step review cycle:** Dispatch → Code Review (Alpha+Beta) → Arch Review (if boundary changes) → Security (if applicable) → \`evidence_map\` gate → **🛑 STOP — present results**
106
+
107
+ ### Flow MCP Tools
108
+
109
+ | Tool | Purpose |
110
+ |------|---------|
111
+ | \`flow_list\` | List installed flows and active flow |
112
+ | \`flow_info\` | Get detailed flow info including steps |
113
+ | \`flow_start\` | Start a named flow |
114
+ | \`flow_step\` | Advance: next, skip, or redo current step |
115
+ | \`flow_status\` | Check current execution state |
116
+ | \`flow_reset\` | Clear flow state to start over |
117
+ | \`flow_read_skill\` | Read the skill content for the current step |
89
118
 
90
119
  ## Emergency: STOP → ASSESS → CONTAIN → RECOVER → DOCUMENT
91
120
 
@@ -228,6 +257,17 @@ At session start, check for an active flow:
228
257
  5. **Dependency Graph** — For each phase, list dependencies. Group into parallel batches
229
258
  6. **Present** — Show plan with open questions, complexity estimate, parallel batch layout
230
259
 
260
+ ## Flow Integration
261
+
262
+ When activated as part of a flow (e.g., \`aikit:advanced\` plan step or \`aikit:basic\` assess step):
263
+ 1. Check \`flow_status\` for current step context
264
+ 2. Read the step's skill file for specific instructions
265
+ 3. Follow skill instructions while applying Planner methodology
266
+ 4. Produce required artifacts (as specified by the flow step's \`produces\` field)
267
+ 5. When complete, report to Orchestrator (do NOT call \`flow_step\` — let Orchestrator advance)
268
+
269
+ When no flow is active, operate autonomously following normal Planner methodology.
270
+
231
271
  ## Subagent Output Relay
232
272
 
233
273
  When subagents complete, their visual outputs (from \`present\`) are NOT visible to the user.
@@ -11,29 +11,44 @@
11
11
 
12
12
  export const MODELS = {
13
13
  // ─── Single-role agents ───────────────────────────────────────────────
14
- Orchestrator: 'Claude Opus 4.6',
15
- Planner: 'Claude Opus 4.6',
16
- Implementer: 'GPT-5.4',
17
- Frontend: 'Gemini 3.1 Pro (Preview)',
18
- Debugger: 'Claude Opus 4.6',
19
- Refactor: 'GPT-5.4',
20
- Security: 'Claude Opus 4.6',
21
- Documenter: 'GPT-5.4',
22
- Explorer: 'Gemini 3 Flash (Preview)',
14
+ Orchestrator: ['Claude Opus 4.6 (copilot)', 'GPT-5.4 (copilot)', 'Auto (copilot)'],
15
+ Planner: ['Claude Opus 4.6 (copilot)', 'GPT-5.4 (copilot)', 'Auto (copilot)'],
16
+ Implementer: [
17
+ 'GPT-5.4 (copilot)',
18
+ 'Gemini 3.1 Pro (Preview) (copilot)',
19
+ 'GPT-5.3-Codex (copilot)',
20
+ 'Auto (copilot)',
21
+ ],
22
+ Frontend: [
23
+ 'Gemini 3.1 Pro (Preview) (copilot)',
24
+ 'GPT-5.4 (copilot)',
25
+ 'GPT-5.3-Codex (copilot)',
26
+ 'Auto (copilot)',
27
+ ],
28
+ Debugger: [
29
+ 'Claude Opus 4.6 (copilot)',
30
+ 'GPT-5.4 (copilot)',
31
+ 'GPT-5.3-Codex (copilot)',
32
+ 'Auto (copilot)',
33
+ ],
34
+ Refactor: ['GPT-5.4 (copilot)', 'GPT-5.3-Codex (copilot)', 'Auto (copilot)'],
35
+ Security: ['Claude Opus 4.6 (copilot)', 'GPT-5.4 (copilot)', 'Auto (copilot)'],
36
+ Documenter: ['GPT-5.4 (copilot)', 'Gemini 3.1 Pro (Preview) (copilot)', 'Auto (copilot)'],
37
+ Explorer: ['Gemini 3 Flash (Preview) (copilot)', 'Claude Haiku 4.5 (copilot)', 'Auto (copilot)'],
23
38
 
24
39
  // ─── Researcher variants (4 models for multi-model decision protocol) ────────────
25
- 'Researcher-Alpha': 'Claude Opus 4.6',
26
- 'Researcher-Beta': 'Claude Sonnet 4.6',
27
- 'Researcher-Gamma': 'GPT-5.4',
28
- 'Researcher-Delta': 'Gemini 3.1 Pro (Preview)',
40
+ 'Researcher-Alpha': ['Claude Opus 4.6 (copilot)', 'Auto (copilot)'],
41
+ 'Researcher-Beta': ['Claude Sonnet 4.6 (copilot)', 'Auto (copilot)'],
42
+ 'Researcher-Gamma': ['GPT-5.4 (copilot)', 'Auto (copilot)'],
43
+ 'Researcher-Delta': ['Gemini 3.1 Pro (Preview) (copilot)', 'Auto (copilot)'],
29
44
 
30
45
  // ─── Code-Reviewer variants (2 models for dual review) ───────────────
31
- 'Code-Reviewer-Alpha': 'GPT-5.4',
32
- 'Code-Reviewer-Beta': 'Claude Opus 4.6',
46
+ 'Code-Reviewer-Alpha': ['GPT-5.4 (copilot)', 'Auto (copilot)'],
47
+ 'Code-Reviewer-Beta': ['Claude Opus 4.6 (copilot)', 'Auto (copilot)'],
33
48
 
34
49
  // ─── Architect-Reviewer variants (2 models for dual review) ──────────
35
- 'Architect-Reviewer-Alpha': 'GPT-5.4',
36
- 'Architect-Reviewer-Beta': 'Claude Opus 4.6',
50
+ 'Architect-Reviewer-Alpha': ['GPT-5.4 (copilot)', 'Auto (copilot)'],
51
+ 'Architect-Reviewer-Beta': ['Claude Opus 4.6 (copilot)', 'Auto (copilot)'],
37
52
  };
38
53
 
39
54
  /**
@@ -2,7 +2,7 @@
2
2
  description: 'Primary architecture reviewer'
3
3
  argument-hint: Files, PR, or subsystem to architecture-review
4
4
  tools: [execute/runInTerminal, read/problems, read/readFile, read/terminalLastCommand, agent/runSubagent, search/changes, search/codebase, search/usages, web/fetch, web/githubRepo, browser/openBrowserPage, browser/readPage, browser/screenshotPage, browser/navigatePage, browser/clickElement, browser/dragElement, browser/hoverElement, browser/typeInPage, browser/runPlaywrightCode, browser/handleDialog, aikit/*]
5
- model: GPT-5.4 (copilot)
5
+ model: [GPT-5.4 (copilot), Auto (copilot)]
6
6
  ---
7
7
 
8
8
  # Architect-Reviewer-Alpha - The Structural Guardian
@@ -2,7 +2,7 @@
2
2
  description: 'Architecture reviewer variant — different LLM perspective for dual review'
3
3
  argument-hint: Files, PR, or subsystem to architecture-review
4
4
  tools: [execute/runInTerminal, read/problems, read/readFile, read/terminalLastCommand, agent/runSubagent, search/changes, search/codebase, search/usages, web/fetch, web/githubRepo, browser/openBrowserPage, browser/readPage, browser/screenshotPage, browser/navigatePage, browser/clickElement, browser/dragElement, browser/hoverElement, browser/typeInPage, browser/runPlaywrightCode, browser/handleDialog, aikit/*]
5
- model: Claude Opus 4.6 (copilot)
5
+ model: [Claude Opus 4.6 (copilot), Auto (copilot)]
6
6
  ---
7
7
 
8
8
  # Architect-Reviewer-Beta - The Structural Guardian
@@ -2,7 +2,7 @@
2
2
  description: 'Primary code reviewer'
3
3
  argument-hint: File path, PR, or code to review
4
4
  tools: [execute/runInTerminal, read/problems, read/readFile, read/terminalLastCommand, agent/runSubagent, search/changes, search/codebase, search/usages, web/fetch, web/githubRepo, browser/openBrowserPage, browser/readPage, browser/screenshotPage, browser/navigatePage, browser/clickElement, browser/dragElement, browser/hoverElement, browser/typeInPage, browser/runPlaywrightCode, browser/handleDialog, aikit/*]
5
- model: GPT-5.4 (copilot)
5
+ model: [GPT-5.4 (copilot), Auto (copilot)]
6
6
  ---
7
7
 
8
8
  # Code-Reviewer-Alpha - The Quality Guardian
@@ -2,7 +2,7 @@
2
2
  description: 'Code reviewer variant — different LLM perspective for dual review'
3
3
  argument-hint: File path, PR, or code to review
4
4
  tools: [execute/runInTerminal, read/problems, read/readFile, read/terminalLastCommand, agent/runSubagent, search/changes, search/codebase, search/usages, web/fetch, web/githubRepo, browser/openBrowserPage, browser/readPage, browser/screenshotPage, browser/navigatePage, browser/clickElement, browser/dragElement, browser/hoverElement, browser/typeInPage, browser/runPlaywrightCode, browser/handleDialog, aikit/*]
5
- model: Claude Opus 4.6 (copilot)
5
+ model: [Claude Opus 4.6 (copilot), Auto (copilot)]
6
6
  ---
7
7
 
8
8
  # Code-Reviewer-Beta - The Quality Guardian
@@ -2,7 +2,7 @@
2
2
  description: 'Expert debugger that diagnoses issues, traces errors, and provides solutions'
3
3
  argument-hint: Error message, stack trace, or description of issue
4
4
  tools: [execute/runInTerminal, read/problems, read/readFile, read/terminalSelection, read/terminalLastCommand, agent/runSubagent, edit/createFile, edit/editFiles, search/changes, search/codebase, search/usages, browser/openBrowserPage, browser/readPage, browser/screenshotPage, browser/navigatePage, browser/clickElement, browser/dragElement, browser/hoverElement, browser/typeInPage, browser/runPlaywrightCode, browser/handleDialog, aikit/*]
5
- model: Claude Opus 4.6 (copilot)
5
+ model: [Claude Opus 4.6 (copilot), GPT-5.4 (copilot), GPT-5.3-Codex (copilot), Auto (copilot)]
6
6
  ---
7
7
 
8
8
  # Debugger - The Problem Solver
@@ -2,7 +2,7 @@
2
2
  description: 'Documentation specialist that creates and maintains comprehensive project documentation'
3
3
  argument-hint: Component, API, feature, or area to document
4
4
  tools: [execute/runInTerminal, read/problems, read/readFile, read/terminalLastCommand, agent/runSubagent, edit/createFile, edit/editFiles, edit/rename, edit/createDirectory, search/changes, search/codebase, search/usages, web/fetch, web/githubRepo, browser/openBrowserPage, browser/readPage, browser/screenshotPage, browser/navigatePage, browser/clickElement, browser/dragElement, browser/hoverElement, browser/typeInPage, browser/runPlaywrightCode, browser/handleDialog, aikit/*]
5
- model: GPT-5.4 (copilot)
5
+ model: [GPT-5.4 (copilot), Gemini 3.1 Pro (Preview) (copilot), Auto (copilot)]
6
6
  ---
7
7
 
8
8
  # Documenter - The Knowledge Keeper
@@ -2,7 +2,7 @@
2
2
  description: 'Rapid codebase exploration to find files, usages, dependencies, and structural context'
3
3
  argument-hint: Find files, usages, and context related to: {topic or goal}
4
4
  tools: [read/problems, read/readFile, search/changes, search/codebase, search/usages, search/fileSearch, search/listDirectory, search/textSearch, browser/openBrowserPage, browser/readPage, browser/screenshotPage, browser/navigatePage, browser/clickElement, browser/dragElement, browser/hoverElement, browser/typeInPage, browser/runPlaywrightCode, browser/handleDialog, aikit/*]
5
- model: Gemini 3 Flash (Preview) (copilot)
5
+ model: [Gemini 3 Flash (Preview) (copilot), Claude Haiku 4.5 (copilot), Auto (copilot)]
6
6
  ---
7
7
 
8
8
  # Explorer - The Rapid Scout
@@ -2,7 +2,7 @@
2
2
  description: 'UI/UX specialist for React, styling, responsive design, and frontend implementation'
3
3
  argument-hint: UI component, styling task, or frontend feature
4
4
  tools: [execute/createAndRunTask, execute/runInTerminal, read/problems, read/readFile, read/terminalLastCommand, agent/runSubagent, edit/createFile, edit/editFiles, edit/rename, edit/createDirectory, search/changes, search/codebase, search/usages, todo, browser/openBrowserPage, browser/readPage, browser/screenshotPage, browser/navigatePage, browser/clickElement, browser/dragElement, browser/hoverElement, browser/typeInPage, browser/runPlaywrightCode, browser/handleDialog, aikit/*]
5
- model: Gemini 3.1 Pro (Preview) (copilot)
5
+ model: [Gemini 3.1 Pro (Preview) (copilot), GPT-5.4 (copilot), GPT-5.3-Codex (copilot), Auto (copilot)]
6
6
  ---
7
7
 
8
8
  # Frontend - The UI Specialist
@@ -2,7 +2,7 @@
2
2
  description: 'Persistent implementation agent that writes code following TDD practices until all tasks are complete'
3
3
  argument-hint: Implementation task, feature, or phase from plan
4
4
  tools: [execute/createAndRunTask, execute/runInTerminal, read/problems, read/readFile, read/terminalLastCommand, agent/runSubagent, edit/createFile, edit/editFiles, edit/rename, edit/createDirectory, search/changes, search/codebase, search/usages, todo, browser/openBrowserPage, browser/readPage, browser/screenshotPage, browser/navigatePage, browser/clickElement, browser/dragElement, browser/hoverElement, browser/typeInPage, browser/runPlaywrightCode, browser/handleDialog, aikit/*]
5
- model: GPT-5.4 (copilot)
5
+ model: [GPT-5.4 (copilot), Gemini 3.1 Pro (Preview) (copilot), GPT-5.3-Codex (copilot), Auto (copilot)]
6
6
  ---
7
7
 
8
8
  # Implementer - The Code Builder
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  description: 'Master conductor that orchestrates the full development lifecycle: Planning → Implementation → Review → Recovery → Commit'
3
3
  tools: [vscode/memory, vscode/runCommand, vscode/switchAgent, execute/killTerminal, execute/createAndRunTask, execute/runInTerminal, read/terminalSelection, read/terminalLastCommand, read/problems, read/readFile, agent/runSubagent, edit/createFile, edit/editFiles, edit/rename, edit/createDirectory, search/changes, search/codebase, search/usages, web/fetch, web/githubRepo, todo, search/searchSubagent, search/textSearch, browser/openBrowserPage, browser/readPage, browser/screenshotPage, browser/navigatePage, browser/clickElement, browser/dragElement, browser/hoverElement, browser/typeInPage, browser/runPlaywrightCode, browser/handleDialog, vscode/askQuestions, vscode/resolveMemoryFileUri, aikit/*]
4
- model: Claude Opus 4.6 (copilot)
4
+ model: [Claude Opus 4.6 (copilot), GPT-5.4 (copilot), Auto (copilot)]
5
5
  ---
6
6
 
7
7
  # Orchestrator - The Master Conductor
@@ -21,23 +21,23 @@ You orchestrate the full development lifecycle: **planning → implementation
21
21
 
22
22
  | Agent | Purpose | Model | Category |
23
23
  |-------|---------|-------|----------|
24
- | **Orchestrator** | Master conductor that orchestrates the full development lifecycle: Planning → Implementation → Review → Recovery → Commit | Claude Opus 4.6 | orchestration |
25
- | **Planner** | Autonomous planner that researches codebases and writes comprehensive TDD implementation plans | Claude Opus 4.6 | orchestration |
26
- | **Implementer** | Persistent implementation agent that writes code following TDD practices until all tasks are complete | GPT-5.4 | implementation |
27
- | **Frontend** | UI/UX specialist for React, styling, responsive design, and frontend implementation | Gemini 3.1 Pro (Preview) | implementation |
28
- | **Refactor** | Code refactoring specialist that improves structure, readability, and maintainability | GPT-5.4 | implementation |
29
- | **Debugger** | Expert debugger that diagnoses issues, traces errors, and provides solutions | Claude Opus 4.6 | diagnostics |
30
- | **Security** | Security specialist that analyzes code for vulnerabilities and compliance | Claude Opus 4.6 | diagnostics |
31
- | **Documenter** | Documentation specialist that creates and maintains comprehensive project documentation | GPT-5.4 | documentation |
32
- | **Explorer** | Rapid codebase exploration to find files, usages, dependencies, and structural context | Gemini 3 Flash (Preview) | exploration |
33
- | **Researcher-Alpha** | Primary deep research agent — also serves as default Researcher | Claude Opus 4.6 | research |
34
- | **Researcher-Beta** | Research variant — pragmatic analysis with focus on trade-offs and edge cases | Claude Sonnet 4.6 | research |
35
- | **Researcher-Gamma** | Research variant — broad pattern matching across domains and technologies | GPT-5.4 | research |
36
- | **Researcher-Delta** | Research variant — implementation feasibility and performance implications | Gemini 3.1 Pro (Preview) | research |
37
- | **Code-Reviewer-Alpha** | Primary code reviewer | GPT-5.4 | review |
38
- | **Code-Reviewer-Beta** | Code reviewer variant — different LLM perspective for dual review | Claude Opus 4.6 | review |
39
- | **Architect-Reviewer-Alpha** | Primary architecture reviewer | GPT-5.4 | review |
40
- | **Architect-Reviewer-Beta** | Architecture reviewer variant — different LLM perspective for dual review | Claude Opus 4.6 | review |
24
+ | **Orchestrator** | Master conductor that orchestrates the full development lifecycle: Planning → Implementation → Review → Recovery → Commit | Claude Opus 4.6 (copilot) | orchestration |
25
+ | **Planner** | Autonomous planner that researches codebases and writes comprehensive TDD implementation plans | Claude Opus 4.6 (copilot) | orchestration |
26
+ | **Implementer** | Persistent implementation agent that writes code following TDD practices until all tasks are complete | GPT-5.4 (copilot) | implementation |
27
+ | **Frontend** | UI/UX specialist for React, styling, responsive design, and frontend implementation | Gemini 3.1 Pro (Preview) (copilot) | implementation |
28
+ | **Refactor** | Code refactoring specialist that improves structure, readability, and maintainability | GPT-5.4 (copilot) | implementation |
29
+ | **Debugger** | Expert debugger that diagnoses issues, traces errors, and provides solutions | Claude Opus 4.6 (copilot) | diagnostics |
30
+ | **Security** | Security specialist that analyzes code for vulnerabilities and compliance | Claude Opus 4.6 (copilot) | diagnostics |
31
+ | **Documenter** | Documentation specialist that creates and maintains comprehensive project documentation | GPT-5.4 (copilot) | documentation |
32
+ | **Explorer** | Rapid codebase exploration to find files, usages, dependencies, and structural context | Gemini 3 Flash (Preview) (copilot) | exploration |
33
+ | **Researcher-Alpha** | Primary deep research agent — also serves as default Researcher | Claude Opus 4.6 (copilot) | research |
34
+ | **Researcher-Beta** | Research variant — pragmatic analysis with focus on trade-offs and edge cases | Claude Sonnet 4.6 (copilot) | research |
35
+ | **Researcher-Gamma** | Research variant — broad pattern matching across domains and technologies | GPT-5.4 (copilot) | research |
36
+ | **Researcher-Delta** | Research variant — implementation feasibility and performance implications | Gemini 3.1 Pro (Preview) (copilot) | research |
37
+ | **Code-Reviewer-Alpha** | Primary code reviewer | GPT-5.4 (copilot) | review |
38
+ | **Code-Reviewer-Beta** | Code reviewer variant — different LLM perspective for dual review | Claude Opus 4.6 (copilot) | review |
39
+ | **Architect-Reviewer-Alpha** | Primary architecture reviewer | GPT-5.4 (copilot) | review |
40
+ | **Architect-Reviewer-Beta** | Architecture reviewer variant — different LLM perspective for dual review | Claude Opus 4.6 (copilot) | review |
41
41
 
42
42
  **Parallelism**: Read-only agents run in parallel freely. File-modifying agents run in parallel ONLY on completely different files. Max 4 concurrent file-modifying agents.
43
43
 
@@ -57,26 +57,43 @@ You orchestrate the full development lifecycle: **planning → implementation
57
57
  3. After review: `evidence_map({ action: "gate", task_id })` → YIELD/HOLD/HARD_BLOCK
58
58
  4. Auto-upgrade tier if unknowns reveal contract/security issues
59
59
 
60
- ## Workflow
60
+ ## Flow-Driven Development
61
61
 
62
- ### Phase 1: Planning
63
- 1. Read onboard artifacts → parse goal → identify affected subsystems → `forge_classify`
64
- 2. Research: <5 files direct, 5-15 Explorer→Researcher, >15 multiple parallel
65
- 3. Draft plan: 3-10 phases, agent assignments, TDD steps, dependency graph
66
- 4. Batch independent phases for parallel execution
67
- 5. **🛑 STOP — user approval required**
62
+ Orchestrator uses the flow system for structured development. Flows define the step sequence — Orchestrator adds multi-agent orchestration, quality gates, and review protocols on top.
68
63
 
69
- ### Phase 2: Implementation Cycle
64
+ ### Flow Selection
70
65
 
71
- **🚨 PRE-DISPATCH GATE complete ALL before ANY `runSubagent` call:**
66
+ | Situation | Flow | Steps |
67
+ |-----------|------|-------|
68
+ | Bug fix, small feature, refactoring | `aikit:basic` | assess → implement → verify |
69
+ | New feature, major change, multi-file | `aikit:advanced` | spec → plan → task → execute → verify |
70
+ | Custom/specialized work | Check `flow_list` | Follow flow-specific steps |
72
71
 
73
- 1. `multi-agents-development` skill loaded? (Bootstrap step 4 if not, load NOW)
74
- 2. ✅ Task decomposition table produced? (show user: task → files → agent → parallel batch)
75
- 3. ✅ Independence Check passed per pair? (shared files? shared state? ordering dependency? → must be "No" for parallel)
76
- 4. ✅ Each task ≤ 3 files? (if not, split further)
77
- 5. ✅ Parallel batches identified? (tasks with no dependencies MUST be in same batch)
72
+ **If multiple flows could apply and user hasn't specified ask user to choose.**
78
73
 
79
- **Decomposition output format** (show this to user before dispatching):
74
+ ### Session Start Flow Check
75
+
76
+ 1. `flow_status` — check for active flow
77
+ 2. If active:
78
+ - Note current step name and skill path
79
+ - Read the current step skill with `flow_read_skill`
80
+ - Follow its instructions
81
+ - When complete: `flow_step({ action: 'next' })`
82
+ 3. If no active flow:
83
+ - `flow_list` — check ALL available flows (builtin + custom)
84
+ - Recommend appropriate flow based on task scope
85
+ - `flow_start({ flow: '<name>' })` after user confirms
86
+
87
+ ### Orchestrator Protocols (apply during ALL flow steps)
88
+
89
+ **PRE-DISPATCH GATE — complete ALL before ANY `runSubagent` call:**
90
+ 1. ✅ `multi-agents-development` skill loaded?
91
+ 2. ✅ Task decomposition table produced?
92
+ 3. ✅ Independence Check passed per pair?
93
+ 4. ✅ Each task ≤ 3 files?
94
+ 5. ✅ Parallel batches identified?
95
+
96
+ **Decomposition output format:**
80
97
 
81
98
  ```
82
99
  Batch 1 (parallel):
@@ -86,23 +103,35 @@ Batch 2 (after batch 1):
86
103
  Task C: [agent] → [file5] — [goal] (depends on A)
87
104
  ```
88
105
 
89
- **Prompt every subagent with** (use `multi-agents-development` skill templates):
90
- 1. **Scope** — exact files to touch + boundary (do NOT touch)
106
+ **Subagent prompt template:**
107
+ 1. **Scope** — exact files + boundary
91
108
  2. **Goal** — acceptance criteria, testable
92
- 3. **Arch Context** — paste actual code snippets from `compact()`/`digest()`
93
- 4. **Constraints** — patterns, conventions, anti-patterns
109
+ 3. **Arch Context** — code snippets from `compact()`/`digest()`
110
+ 4. **Constraints** — patterns, conventions
94
111
  5. **FORGE** — tier + evidence requirements
95
112
  6. **Self-Review** — checklist before declaring status
96
113
 
97
- **Subagent status protocol**: `DONE` | `DONE_WITH_CONCERNS` | `NEEDS_CONTEXT` | `BLOCKED`
114
+ **Subagent status protocol:** `DONE` | `DONE_WITH_CONCERNS` | `NEEDS_CONTEXT` | `BLOCKED`
115
+
116
+ **Additional Orchestrator requirements during flow execution:**
117
+ - Apply the PRE-DISPATCH GATE before any subagent dispatch, regardless of flow
118
+ - Apply FORGE at classification and verification points; pass tier/evidence expectations into subagents and gate with `evidence_map`
119
+ - Enforce delegation rules at all times — Orchestrator never implements code directly
120
+ - Use the subagent prompt template for every dispatch so step-specific flow instructions are grounded in actual code context
98
121
 
99
- **Per-batch flow**: Dispatch (parallel) Spec Review → Code Quality Review (Alpha+Beta parallel) → Arch Review (if boundary changes) → Security (if applicable) → `evidence_map` gate → **🛑 STOP — present commit message**
122
+ **Per-step review cycle:** Dispatch → Code Review (Alpha+Beta) → Arch Review (if boundary changes) → Security (if applicable) → `evidence_map` gate → **🛑 STOP — present results**
123
+
124
+ ### Flow MCP Tools
100
125
 
101
- ### Phase 3: Completion
102
- 1. Optional: Refactor pass (separate commit)
103
- 2. Documenter for docs updates
104
- 3. `remember` all decisions, patterns, gotchas, conventions
105
- 4. `reindex({})` + `produce_knowledge({ path: "." })`
126
+ | Tool | Purpose |
127
+ |------|---------|
128
+ | `flow_list` | List installed flows and active flow |
129
+ | `flow_info` | Get detailed flow info including steps |
130
+ | `flow_start` | Start a named flow |
131
+ | `flow_step` | Advance: next, skip, or redo current step |
132
+ | `flow_status` | Check current execution state |
133
+ | `flow_reset` | Clear flow state to start over |
134
+ | `flow_read_skill` | Read the skill content for the current step |
106
135
 
107
136
  ## Emergency: STOP → ASSESS → CONTAIN → RECOVER → DOCUMENT
108
137
 
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  description: 'Autonomous planner that researches codebases and writes comprehensive TDD implementation plans'
3
3
  tools: [execute/runInTerminal, read/problems, read/readFile, read/terminalLastCommand, agent/runSubagent, edit/createFile, edit/editFiles, edit/rename, edit/createDirectory, search/changes, search/codebase, search/usages, web/fetch, web/githubRepo, todo, search/searchSubagent, browser/openBrowserPage, browser/readPage, browser/screenshotPage, browser/navigatePage, browser/clickElement, browser/dragElement, browser/hoverElement, browser/typeInPage, browser/runPlaywrightCode, browser/handleDialog, aikit/*]
4
- model: Claude Opus 4.6 (copilot)
4
+ model: [Claude Opus 4.6 (copilot), GPT-5.4 (copilot), Auto (copilot)]
5
5
  ---
6
6
 
7
7
  # Planner - The Strategic Architect
@@ -38,6 +38,17 @@ You are the **Planner**, autonomous planner that researches codebases and writes
38
38
  5. **Dependency Graph** — For each phase, list dependencies. Group into parallel batches
39
39
  6. **Present** — Show plan with open questions, complexity estimate, parallel batch layout
40
40
 
41
+ ## Flow Integration
42
+
43
+ When activated as part of a flow (e.g., `aikit:advanced` plan step or `aikit:basic` assess step):
44
+ 1. Check `flow_status` for current step context
45
+ 2. Read the step's skill file for specific instructions
46
+ 3. Follow skill instructions while applying Planner methodology
47
+ 4. Produce required artifacts (as specified by the flow step's `produces` field)
48
+ 5. When complete, report to Orchestrator (do NOT call `flow_step` — let Orchestrator advance)
49
+
50
+ When no flow is active, operate autonomously following normal Planner methodology.
51
+
41
52
  ## Subagent Output Relay
42
53
 
43
54
  When subagents complete, their visual outputs (from `present`) are NOT visible to the user.
@@ -6,23 +6,23 @@ This directory contains AI agent definitions generated by `@vpxa/aikit init`.
6
6
 
7
7
  | Agent | Purpose | Model | Category |
8
8
  |-------|---------|-------|----------|
9
- | **Orchestrator** | Master conductor that orchestrates the full development lifecycle: Planning → Implementation → Review → Recovery → Commit | Claude Opus 4.6 | orchestration |
10
- | **Planner** | Autonomous planner that researches codebases and writes comprehensive TDD implementation plans | Claude Opus 4.6 | orchestration |
11
- | **Implementer** | Persistent implementation agent that writes code following TDD practices until all tasks are complete | GPT-5.4 | implementation |
12
- | **Frontend** | UI/UX specialist for React, styling, responsive design, and frontend implementation | Gemini 3.1 Pro (Preview) | implementation |
13
- | **Refactor** | Code refactoring specialist that improves structure, readability, and maintainability | GPT-5.4 | implementation |
14
- | **Debugger** | Expert debugger that diagnoses issues, traces errors, and provides solutions | Claude Opus 4.6 | diagnostics |
15
- | **Security** | Security specialist that analyzes code for vulnerabilities and compliance | Claude Opus 4.6 | diagnostics |
16
- | **Documenter** | Documentation specialist that creates and maintains comprehensive project documentation | GPT-5.4 | documentation |
17
- | **Explorer** | Rapid codebase exploration to find files, usages, dependencies, and structural context | Gemini 3 Flash (Preview) | exploration |
18
- | **Researcher-Alpha** | Primary deep research agent — also serves as default Researcher | Claude Opus 4.6 | research |
19
- | **Researcher-Beta** | Research variant — pragmatic analysis with focus on trade-offs and edge cases | Claude Sonnet 4.6 | research |
20
- | **Researcher-Gamma** | Research variant — broad pattern matching across domains and technologies | GPT-5.4 | research |
21
- | **Researcher-Delta** | Research variant — implementation feasibility and performance implications | Gemini 3.1 Pro (Preview) | research |
22
- | **Code-Reviewer-Alpha** | Primary code reviewer | GPT-5.4 | review |
23
- | **Code-Reviewer-Beta** | Code reviewer variant — different LLM perspective for dual review | Claude Opus 4.6 | review |
24
- | **Architect-Reviewer-Alpha** | Primary architecture reviewer | GPT-5.4 | review |
25
- | **Architect-Reviewer-Beta** | Architecture reviewer variant — different LLM perspective for dual review | Claude Opus 4.6 | review |
9
+ | **Orchestrator** | Master conductor that orchestrates the full development lifecycle: Planning → Implementation → Review → Recovery → Commit | Claude Opus 4.6 (copilot) | orchestration |
10
+ | **Planner** | Autonomous planner that researches codebases and writes comprehensive TDD implementation plans | Claude Opus 4.6 (copilot) | orchestration |
11
+ | **Implementer** | Persistent implementation agent that writes code following TDD practices until all tasks are complete | GPT-5.4 (copilot) | implementation |
12
+ | **Frontend** | UI/UX specialist for React, styling, responsive design, and frontend implementation | Gemini 3.1 Pro (Preview) (copilot) | implementation |
13
+ | **Refactor** | Code refactoring specialist that improves structure, readability, and maintainability | GPT-5.4 (copilot) | implementation |
14
+ | **Debugger** | Expert debugger that diagnoses issues, traces errors, and provides solutions | Claude Opus 4.6 (copilot) | diagnostics |
15
+ | **Security** | Security specialist that analyzes code for vulnerabilities and compliance | Claude Opus 4.6 (copilot) | diagnostics |
16
+ | **Documenter** | Documentation specialist that creates and maintains comprehensive project documentation | GPT-5.4 (copilot) | documentation |
17
+ | **Explorer** | Rapid codebase exploration to find files, usages, dependencies, and structural context | Gemini 3 Flash (Preview) (copilot) | exploration |
18
+ | **Researcher-Alpha** | Primary deep research agent — also serves as default Researcher | Claude Opus 4.6 (copilot) | research |
19
+ | **Researcher-Beta** | Research variant — pragmatic analysis with focus on trade-offs and edge cases | Claude Sonnet 4.6 (copilot) | research |
20
+ | **Researcher-Gamma** | Research variant — broad pattern matching across domains and technologies | GPT-5.4 (copilot) | research |
21
+ | **Researcher-Delta** | Research variant — implementation feasibility and performance implications | Gemini 3.1 Pro (Preview) (copilot) | research |
22
+ | **Code-Reviewer-Alpha** | Primary code reviewer | GPT-5.4 (copilot) | review |
23
+ | **Code-Reviewer-Beta** | Code reviewer variant — different LLM perspective for dual review | Claude Opus 4.6 (copilot) | review |
24
+ | **Architect-Reviewer-Alpha** | Primary architecture reviewer | GPT-5.4 (copilot) | review |
25
+ | **Architect-Reviewer-Beta** | Architecture reviewer variant — different LLM perspective for dual review | Claude Opus 4.6 (copilot) | review |
26
26
 
27
27
  ## Multi-Model Pattern
28
28
 
@@ -2,7 +2,7 @@
2
2
  description: 'Code refactoring specialist that improves structure, readability, and maintainability'
3
3
  argument-hint: Code, component, or pattern to refactor
4
4
  tools: [execute/runInTerminal, read/problems, read/readFile, read/terminalLastCommand, agent/runSubagent, edit/createFile, edit/editFiles, edit/rename, edit/createDirectory, search/changes, search/codebase, search/usages, browser/openBrowserPage, browser/readPage, browser/screenshotPage, browser/navigatePage, browser/clickElement, browser/dragElement, browser/hoverElement, browser/typeInPage, browser/runPlaywrightCode, browser/handleDialog, aikit/*]
5
- model: GPT-5.4 (copilot)
5
+ model: [GPT-5.4 (copilot), GPT-5.3-Codex (copilot), Auto (copilot)]
6
6
  ---
7
7
 
8
8
  # Refactor - The Code Sculptor
@@ -2,7 +2,7 @@
2
2
  description: 'Primary deep research agent — also serves as default Researcher'
3
3
  argument-hint: Research question, problem statement, or subsystem to investigate
4
4
  tools: [execute/runInTerminal, read/problems, read/readFile, read/terminalLastCommand, agent/runSubagent, search/changes, search/codebase, search/usages, web/fetch, web/githubRepo, browser/openBrowserPage, browser/readPage, browser/screenshotPage, browser/navigatePage, browser/clickElement, browser/dragElement, browser/hoverElement, browser/typeInPage, browser/runPlaywrightCode, browser/handleDialog, aikit/*]
5
- model: Claude Opus 4.6 (copilot)
5
+ model: [Claude Opus 4.6 (copilot), Auto (copilot)]
6
6
  ---
7
7
 
8
8
  # Researcher-Alpha - The Context Gatherer
@@ -2,7 +2,7 @@
2
2
  description: 'Research variant — pragmatic analysis with focus on trade-offs and edge cases'
3
3
  argument-hint: Research question, problem statement, or subsystem to investigate
4
4
  tools: [execute/runInTerminal, read/problems, read/readFile, read/terminalLastCommand, agent/runSubagent, search/changes, search/codebase, search/usages, web/fetch, web/githubRepo, browser/openBrowserPage, browser/readPage, browser/screenshotPage, browser/navigatePage, browser/clickElement, browser/dragElement, browser/hoverElement, browser/typeInPage, browser/runPlaywrightCode, browser/handleDialog, aikit/*]
5
- model: Claude Sonnet 4.6 (copilot)
5
+ model: [Claude Sonnet 4.6 (copilot), Auto (copilot)]
6
6
  ---
7
7
 
8
8
  # Researcher-Beta - The Context Gatherer
@@ -2,7 +2,7 @@
2
2
  description: 'Research variant — implementation feasibility and performance implications'
3
3
  argument-hint: Research question, problem statement, or subsystem to investigate
4
4
  tools: [execute/runInTerminal, read/problems, read/readFile, read/terminalLastCommand, agent/runSubagent, search/changes, search/codebase, search/usages, web/fetch, web/githubRepo, browser/openBrowserPage, browser/readPage, browser/screenshotPage, browser/navigatePage, browser/clickElement, browser/dragElement, browser/hoverElement, browser/typeInPage, browser/runPlaywrightCode, browser/handleDialog, aikit/*]
5
- model: Gemini 3.1 Pro (Preview) (copilot)
5
+ model: [Gemini 3.1 Pro (Preview) (copilot), Auto (copilot)]
6
6
  ---
7
7
 
8
8
  # Researcher-Delta - The Context Gatherer
@@ -2,7 +2,7 @@
2
2
  description: 'Research variant — broad pattern matching across domains and technologies'
3
3
  argument-hint: Research question, problem statement, or subsystem to investigate
4
4
  tools: [execute/runInTerminal, read/problems, read/readFile, read/terminalLastCommand, agent/runSubagent, search/changes, search/codebase, search/usages, web/fetch, web/githubRepo, browser/openBrowserPage, browser/readPage, browser/screenshotPage, browser/navigatePage, browser/clickElement, browser/dragElement, browser/hoverElement, browser/typeInPage, browser/runPlaywrightCode, browser/handleDialog, aikit/*]
5
- model: GPT-5.4 (copilot)
5
+ model: [GPT-5.4 (copilot), Auto (copilot)]
6
6
  ---
7
7
 
8
8
  # Researcher-Gamma - The Context Gatherer
@@ -2,7 +2,7 @@
2
2
  description: 'Security specialist that analyzes code for vulnerabilities and compliance'
3
3
  argument-hint: Code, feature, or component to security review
4
4
  tools: [execute/runInTerminal, read/problems, read/readFile, agent/runSubagent, search/changes, search/codebase, search/usages, web/fetch, web/githubRepo, browser/openBrowserPage, browser/readPage, browser/screenshotPage, browser/navigatePage, browser/clickElement, browser/dragElement, browser/hoverElement, browser/typeInPage, browser/runPlaywrightCode, browser/handleDialog, aikit/*]
5
- model: Claude Opus 4.6 (copilot)
5
+ model: [Claude Opus 4.6 (copilot), GPT-5.4 (copilot), Auto (copilot)]
6
6
  ---
7
7
 
8
8
  # Security - The Vulnerability Hunter