@vpxa/aikit 0.1.270 → 0.1.272

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vpxa/aikit",
3
- "version": "0.1.270",
3
+ "version": "0.1.272",
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",
@@ -1457,10 +1457,10 @@ ${tt}
1457
1457
  `)].join(`
1458
1458
 
1459
1459
  `)}const j={header:`aikit-header`,brand:`aikit-header-brand`,title:`aikit-header-title`,titleText:`aikit-header-title-text`,subtitle:`aikit-header-subtitle`,actions:`aikit-header-actions`,themeToggle:`aikit-theme-toggle`,themeToggleIcon:`aikit-theme-toggle-icon`,themeToggleIconSun:`aikit-theme-toggle-icon--sun`,themeToggleIconMoon:`aikit-theme-toggle-icon--moon`,toolbox:`aikit-toolbox`,toolboxToggle:`aikit-toolbox-toggle`,toolboxMenu:`aikit-toolbox-menu`,toolboxItem:`aikit-toolbox-item`,footer:`aikit-footer`,footerMeta:`aikit-footer-meta`,footerText:`aikit-footer-text`,footerBrand:`aikit-footer-brand`,footerTimestamp:`aikit-footer-timestamp`,footerSlot:`aikit-footer-slot`,footerBadge:`aikit-footer-badge`},Jt=[{kind:`shared-chrome-action`,id:`copy-image`,label:`Copy as Image`,icon:`<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z"/><circle cx="12" cy="13" r="4"/></svg>`,onclick:`screenshotPage()`}];function Yt(e){let t=e.onclick?` onclick="${n(e.onclick)}"`:``;return[` <button type="button" class="${j.toolboxItem}" role="menuitem" data-shared-chrome-action="${n(e.id)}" aria-label="${n(e.label)}"${t}>`,` <span aria-hidden="true">${e.icon}</span>`,` <span>${n(e.label)}</span>`,` </button>`].join(`
1460
- `)}function Xt(e){if(e!==`browser`&&e!==`mcp-app`)return``;let t=Jt.filter(e=>e.kind===`shared-chrome-action`);return[` <div class="${j.toolbox}">`,` <button type="button" class="${j.toolboxToggle}" aria-label="Open tools menu" aria-haspopup="menu" aria-expanded="false" aria-controls="aikit-toolbox-menu" onclick="toggleToolbox()">`,` <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"/></svg>`,` </button>`,` <div id="aikit-toolbox-menu" class="${j.toolboxMenu}" role="menu" hidden>`,...t.map(e=>Yt(e)),` </div>`,` </div>`].join(`
1461
- `)}function M(e){return e?.trim()?e.trim():``}function Zt(e){if(!e)return null;let t=new Date(e);return Number.isNaN(t.getTime())?{display:e}:{dateTime:t.toISOString(),display:new Intl.DateTimeFormat(void 0,{month:`long`,day:`numeric`,year:`numeric`,hour:`numeric`,minute:`2-digit`}).format(t)}}function N(e){let t=e.brand??`AI KIT`,r=[M(e.actionsHtml),Xt(e.transport),e.showThemeToggle===!1?``:[` <button type="button" class="${j.themeToggle}" aria-label="Switch to dark theme" aria-pressed="false" onclick="toggleTheme()">`,` <span class="${j.themeToggleIcon} ${j.themeToggleIconSun}" aria-hidden="true"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="5"/><line x1="12" y1="1" x2="12" y2="3"/><line x1="12" y1="21" x2="12" y2="23"/><line x1="4.22" y1="4.22" x2="5.64" y2="5.64"/><line x1="18.36" y1="18.36" x2="19.78" y2="19.78"/><line x1="1" y1="12" x2="3" y2="12"/><line x1="21" y1="12" x2="23" y2="12"/><line x1="4.22" y1="19.78" x2="5.64" y2="18.36"/><line x1="18.36" y1="5.64" x2="19.78" y2="4.22"/></svg></span>`,` <span class="${j.themeToggleIcon} ${j.themeToggleIconMoon}" aria-hidden="true"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/></svg></span>`,` </button>`].join(`
1460
+ `)}function Xt(e,t=[]){if(e!==`browser`&&e!==`mcp-app`)return``;let n=t.filter(e=>e.kind===`shared-chrome-action`);return n.length===0?``:[` <div class="${j.toolbox}">`,` <button type="button" class="${j.toolboxToggle}" aria-label="Open tools menu" aria-haspopup="menu" aria-expanded="false" aria-controls="aikit-toolbox-menu" onclick="toggleToolbox()">`,` <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"/></svg>`,` </button>`,` <div id="aikit-toolbox-menu" class="${j.toolboxMenu}" role="menu" hidden>`,...n.map(e=>Yt(e)),` </div>`,` </div>`].join(`
1461
+ `)}function M(e){return e?.trim()?e.trim():``}function Zt(e){if(!e)return null;let t=new Date(e);return Number.isNaN(t.getTime())?{display:e}:{dateTime:t.toISOString(),display:new Intl.DateTimeFormat(void 0,{month:`long`,day:`numeric`,year:`numeric`,hour:`numeric`,minute:`2-digit`}).format(t)}}function N(e){let t=e.brand??`AI KIT`,r=e.sharedChromeActions??(e.transport===`browser`?Jt:[]),i=[M(e.actionsHtml),Xt(e.transport,r),e.showThemeToggle===!1?``:[` <button type="button" class="${j.themeToggle}" aria-label="Switch to dark theme" aria-pressed="false" onclick="toggleTheme()">`,` <span class="${j.themeToggleIcon} ${j.themeToggleIconSun}" aria-hidden="true"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="5"/><line x1="12" y1="1" x2="12" y2="3"/><line x1="12" y1="21" x2="12" y2="23"/><line x1="4.22" y1="4.22" x2="5.64" y2="5.64"/><line x1="18.36" y1="18.36" x2="19.78" y2="19.78"/><line x1="1" y1="12" x2="3" y2="12"/><line x1="21" y1="12" x2="23" y2="12"/><line x1="4.22" y1="19.78" x2="5.64" y2="18.36"/><line x1="18.36" y1="5.64" x2="19.78" y2="4.22"/></svg></span>`,` <span class="${j.themeToggleIcon} ${j.themeToggleIconMoon}" aria-hidden="true"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/></svg></span>`,` </button>`].join(`
1462
1462
  `)].filter(Boolean).join(`
1463
- `);return[` <header class="${j.header}">`,` <div class="${j.brand}">${n(t)}</div>`,` <div class="${j.title}">`,` <span class="${j.titleText}">${n(e.title)}</span>`,...e.subtitle?[` <span class="${j.subtitle}">${n(e.subtitle)}</span>`]:[],` </div>`,` <div class="${j.actions}">`,r,` </div>`,` </header>`].join(`
1463
+ `);return[` <header class="${j.header}">`,` <div class="${j.brand}">${n(t)}</div>`,` <div class="${j.title}">`,` <span class="${j.titleText}">${n(e.title)}</span>`,...e.subtitle?[` <span class="${j.subtitle}">${n(e.subtitle)}</span>`]:[],` </div>`,` <div class="${j.actions}">`,i,` </div>`,` </header>`].join(`
1464
1464
  `)}function P(e={}){let t=Zt(e.generatedAt),r=t?[`Generated by `,`<span class="${j.footerBrand}">AI KIT</span>`,` at `,t.dateTime?`<time class="${j.footerTimestamp}" datetime="${n(t.dateTime)}">${n(t.display)}</time>`:`<span class="${j.footerTimestamp}">${n(t.display)}</span>`].join(``):`Generated by <span class="${j.footerBrand}">AI KIT</span>`,i=M(e.contentHtml);return[` <footer class="${j.footer}">`,` <div class="${j.footerMeta}">`,` <span class="${j.footerText}">${r}</span>`,...i?[` <span class="${j.footerSlot}">${i}</span>`]:[],` </div>`,` </footer>`].join(`
1465
1465
  `)}const F=`
1466
1466
  .aikit-header,
@@ -1,4 +1,4 @@
1
- import{d as e,f as t,i as n,m as r,p as i,s as a,u as o}from"./scaffold-BnhmnBfn.js";import{A as s,C as c,D as l,E as u,M as d,N as f,O as p,S as ee,T as m,_ as h,a as g,b as _,c as v,d as y,f as b,g as te,h as ne,i as x,j as S,k as C,l as w,m as T,n as re,o as ie,p as ae,r as oe,s as se,t as ce,u as E,v as D,w as O,x as le,y as ue}from"./templates-guQ2153Z.js";import{copyFileSync as de,existsSync as k,mkdirSync as A,readFileSync as j,readdirSync as M,rmSync as fe,unlinkSync as pe,writeFileSync as N}from"node:fs";import{basename as me,dirname as P,join as F,posix as I,relative as he,resolve as L,win32 as R}from"node:path";import{fileURLToPath as ge}from"node:url";import{addToWorkset as _e,audit as ve,check as ye,checkpointLatest as be,checkpointList as xe,checkpointLoad as Se,checkpointSave as Ce,codemod as we,compact as Te,dataTransform as Ee,delegate as De,delegateListModels as Oe,deleteWorkset as ke,diffParse as Ae,evaluate as je,fileSummary as Me,find as Ne,findDeadSymbols as Pe,findExamples as Fe,getWorkset as Ie,gitContext as Le,graphQuery as Re,guide as ze,health as Be,laneCreate as Ve,laneDiff as He,laneDiscard as Ue,laneList as We,laneMerge as Ge,laneStatus as Ke,listWorksets as qe,parseOutput as Je,processList as Ye,processLogs as Xe,processStart as Ze,processStatus as Qe,processStop as $e,queueClear as et,queueCreate as tt,queueDelete as nt,queueDone as rt,queueFail as it,queueGet as at,queueList as ot,queueNext as st,queuePush as ct,removeFromWorkset as lt,rename as ut,replayClear as dt,replayList as ft,replayTrim as pt,saveWorkset as mt,scopeMap as ht,stashClear as gt,stashDelete as _t,stashGet as vt,stashList as yt,stashSet as bt,symbol as xt,testRun as St,trace as Ct,watchList as wt,watchStart as Tt,watchStop as Et}from"../../tools/dist/index.js";import{mkdir as Dt,readFile as z,rename as Ot,unlink as kt,writeFile as At}from"node:fs/promises";import{SqliteGraphStore as jt,createSqliteAdapter as Mt,createStore as Nt}from"../../store/dist/index.js";import{randomUUID as Pt}from"node:crypto";import{homedir as B}from"node:os";import{execFileSync as Ft,fork as It}from"node:child_process";import{AIKIT_PATHS as V,EMBEDDING_DEFAULTS as Lt,getGlobalDataDir as Rt,getPartitionDir as H,isUserInstalled as zt,registerWorkspace as Bt,saveRegistry as Vt}from"../../core/dist/index.js";import{initializeWasm as Ht}from"../../chunker/dist/index.js";import{OnnxEmbedder as Ut}from"../../embeddings/dist/index.js";import{IncrementalIndexer as Wt}from"../../indexer/dist/index.js";const Gt=[{name:`analyze`,description:`Run analyzer output for a path`,usage:`aikit analyze <type> <path>`,run:async e=>{let t=e.shift()?.trim()??``,n=e.shift()?.trim()??``;(!t||!n)&&(console.error(`Usage: aikit analyze <type> <path>`),console.error(`Types: structure, deps, symbols, patterns, entry-points, blast-radius, diagram`),process.exit(1));let{BlastRadiusAnalyzer:r,DependencyAnalyzer:i,DiagramGenerator:a,EntryPointAnalyzer:o,PatternAnalyzer:s,StructureAnalyzer:c,SymbolAnalyzer:l}=await import(`../../analyzers/dist/index.js`),u=L(n),d;switch(t){case`structure`:d=await new c().analyze(u,{format:`markdown`});break;case`deps`:case`dependencies`:d=await new i().analyze(u,{format:`markdown`});break;case`symbols`:d=await new l().analyze(u,{format:`markdown`});break;case`patterns`:d=await new s().analyze(u,{format:`markdown`});break;case`entry-points`:d=await new o().analyze(u,{format:`markdown`});break;case`blast-radius`:d=await new r().analyze(process.cwd(),{files:[n],format:`markdown`});break;case`diagram`:d=await new a().analyze(u,{diagramType:`architecture`});break;default:console.error(`Unknown analyze type: ${t}`),console.error(`Types: structure, deps, symbols, patterns, entry-points, blast-radius, diagram`),process.exit(1)}console.log(d.output)}},{name:`onboard`,description:`Run all analyses for first-time codebase onboarding`,usage:`aikit onboard <path> [--generate] [--out-dir <dir>]`,run:async e=>{let{onboard:t}=await import(`../../tools/dist/index.js`),{loadConfig:n}=await Promise.resolve().then(()=>Kn),r=``,i=`memory`,a;for(let t=0;t<e.length;t++){let n=e[t].trim();n===`--generate`?i=`generate`:n===`--out-dir`&&t+1<e.length?a=e[++t].trim():n.startsWith(`--`)||(r=n)}r||=process.cwd();let o=L(r),s=n();console.log(`Onboarding: ${o} (mode: ${i})`),console.log(`Running analyses...
1
+ import{d as e,f as t,i as n,m as r,p as i,s as a,u as o}from"./scaffold-BnhmnBfn.js";import{A as s,C as c,D as l,E as u,M as d,N as f,O as p,S as ee,T as m,_ as h,a as g,b as _,c as v,d as y,f as b,g as te,h as ne,i as x,j as S,k as C,l as w,m as T,n as re,o as ie,p as ae,r as oe,s as se,t as ce,u as E,v as D,w as O,x as le,y as ue}from"./templates-C92mODRl.js";import{copyFileSync as de,existsSync as k,mkdirSync as A,readFileSync as j,readdirSync as M,rmSync as fe,unlinkSync as pe,writeFileSync as N}from"node:fs";import{basename as me,dirname as P,join as F,posix as I,relative as he,resolve as L,win32 as R}from"node:path";import{fileURLToPath as ge}from"node:url";import{addToWorkset as _e,audit as ve,check as ye,checkpointLatest as be,checkpointList as xe,checkpointLoad as Se,checkpointSave as Ce,codemod as we,compact as Te,dataTransform as Ee,delegate as De,delegateListModels as Oe,deleteWorkset as ke,diffParse as Ae,evaluate as je,fileSummary as Me,find as Ne,findDeadSymbols as Pe,findExamples as Fe,getWorkset as Ie,gitContext as Le,graphQuery as Re,guide as ze,health as Be,laneCreate as Ve,laneDiff as He,laneDiscard as Ue,laneList as We,laneMerge as Ge,laneStatus as Ke,listWorksets as qe,parseOutput as Je,processList as Ye,processLogs as Xe,processStart as Ze,processStatus as Qe,processStop as $e,queueClear as et,queueCreate as tt,queueDelete as nt,queueDone as rt,queueFail as it,queueGet as at,queueList as ot,queueNext as st,queuePush as ct,removeFromWorkset as lt,rename as ut,replayClear as dt,replayList as ft,replayTrim as pt,saveWorkset as mt,scopeMap as ht,stashClear as gt,stashDelete as _t,stashGet as vt,stashList as yt,stashSet as bt,symbol as xt,testRun as St,trace as Ct,watchList as wt,watchStart as Tt,watchStop as Et}from"../../tools/dist/index.js";import{mkdir as Dt,readFile as z,rename as Ot,unlink as kt,writeFile as At}from"node:fs/promises";import{SqliteGraphStore as jt,createSqliteAdapter as Mt,createStore as Nt}from"../../store/dist/index.js";import{randomUUID as Pt}from"node:crypto";import{homedir as B}from"node:os";import{execFileSync as Ft,fork as It}from"node:child_process";import{AIKIT_PATHS as V,EMBEDDING_DEFAULTS as Lt,getGlobalDataDir as Rt,getPartitionDir as H,isUserInstalled as zt,registerWorkspace as Bt,saveRegistry as Vt}from"../../core/dist/index.js";import{initializeWasm as Ht}from"../../chunker/dist/index.js";import{OnnxEmbedder as Ut}from"../../embeddings/dist/index.js";import{IncrementalIndexer as Wt}from"../../indexer/dist/index.js";const Gt=[{name:`analyze`,description:`Run analyzer output for a path`,usage:`aikit analyze <type> <path>`,run:async e=>{let t=e.shift()?.trim()??``,n=e.shift()?.trim()??``;(!t||!n)&&(console.error(`Usage: aikit analyze <type> <path>`),console.error(`Types: structure, deps, symbols, patterns, entry-points, blast-radius, diagram`),process.exit(1));let{BlastRadiusAnalyzer:r,DependencyAnalyzer:i,DiagramGenerator:a,EntryPointAnalyzer:o,PatternAnalyzer:s,StructureAnalyzer:c,SymbolAnalyzer:l}=await import(`../../analyzers/dist/index.js`),u=L(n),d;switch(t){case`structure`:d=await new c().analyze(u,{format:`markdown`});break;case`deps`:case`dependencies`:d=await new i().analyze(u,{format:`markdown`});break;case`symbols`:d=await new l().analyze(u,{format:`markdown`});break;case`patterns`:d=await new s().analyze(u,{format:`markdown`});break;case`entry-points`:d=await new o().analyze(u,{format:`markdown`});break;case`blast-radius`:d=await new r().analyze(process.cwd(),{files:[n],format:`markdown`});break;case`diagram`:d=await new a().analyze(u,{diagramType:`architecture`});break;default:console.error(`Unknown analyze type: ${t}`),console.error(`Types: structure, deps, symbols, patterns, entry-points, blast-radius, diagram`),process.exit(1)}console.log(d.output)}},{name:`onboard`,description:`Run all analyses for first-time codebase onboarding`,usage:`aikit onboard <path> [--generate] [--out-dir <dir>]`,run:async e=>{let{onboard:t}=await import(`../../tools/dist/index.js`),{loadConfig:n}=await Promise.resolve().then(()=>Kn),r=``,i=`memory`,a;for(let t=0;t<e.length;t++){let n=e[t].trim();n===`--generate`?i=`generate`:n===`--out-dir`&&t+1<e.length?a=e[++t].trim():n.startsWith(`--`)||(r=n)}r||=process.cwd();let o=L(r),s=n();console.log(`Onboarding: ${o} (mode: ${i})`),console.log(`Running analyses...
2
2
  `);let c=await t({path:o,mode:i,outDir:a??s.onboardDir});for(let e of c.steps){let t=e.status===`success`?`✓`:`✗`,n=e.status===`success`?`${e.durationMs}ms, ${e.output.length} chars`:e.error;console.log(` ${t} ${e.name} — ${n}`)}console.log(`\nTotal: ${c.totalDurationMs}ms`),c.outDir&&console.log(`Output written to: ${c.outDir}`)}}],Kt=[{name:`parse-output`,description:`Parse build or tool output from stdin`,usage:`aikit parse-output [--tool tsc|vitest|biome|git-status]`,run:async e=>{let t=y(e,`--tool`,``).trim()||void 0,n=await s();n.trim()||(console.error(`Usage: aikit parse-output [--tool tsc|vitest|biome|git-status]`),process.exit(1)),m(Je(n,t))}},{name:`git`,description:`Show git branch, status, recent commits, and optional diff stats`,usage:`aikit git [--cwd path] [--commit-count N] [--diff]`,run:async e=>{c(await Le({cwd:y(e,`--cwd`,``).trim()||void 0,commitCount:E(e,`--commit-count`,5),includeDiff:w(e,`--diff`)}))}},{name:`diff`,description:`Parse unified diff text from stdin into structured file changes`,usage:`git diff | aikit diff`,run:async()=>{let e=await s();e.trim()||(console.error(`Usage: git diff | aikit diff`),process.exit(1)),_(Ae({diff:e}))}},{name:`summarize`,description:`Show a structural summary of a file`,usage:`aikit summarize <path>`,run:async e=>{let t=e.shift()?.trim();t||(console.error(`Usage: aikit summarize <path>`),process.exit(1)),ee(await Me({path:L(t)}))}},{name:`checkpoint`,description:`Save and restore lightweight session checkpoints`,usage:`aikit checkpoint <save|load|list|latest> [label-or-id] [--data json] [--notes text]`,run:async e=>{let t=e.shift()?.trim();t||(console.error(`Usage: aikit checkpoint <save|load|list|latest> [label-or-id] [--data json] [--notes text]`),process.exit(1));let n=await v();switch(t){case`save`:{let t=e.shift()?.trim(),r=y(e,`--data`,``),i=y(e,`--notes`,``).trim()||void 0,a=r.trim()?``:await s();t||(console.error(`Usage: aikit checkpoint save <label> [--data json] [--notes text]`),process.exit(1)),D(Ce(n,t,te(r||a),{notes:i}));return}case`load`:{let t=e.shift()?.trim();t||(console.error(`Usage: aikit checkpoint load <id>`),process.exit(1));let r=Se(n,t);if(!r){console.log(`No checkpoint found: ${t}`);return}D(r);return}case`list`:{let e=xe(n);if(e.length===0){console.log(`No checkpoints saved.`);return}console.log(`Checkpoints (${e.length})`),console.log(`─`.repeat(60));for(let t of e)console.log(`${t.id}`),console.log(` Label: ${t.label}`),console.log(` Created: ${t.createdAt}`);return}case`latest`:{let e=be(n);if(!e){console.log(`No checkpoints saved.`);return}D(e);return}default:console.error(`Unknown checkpoint action: ${t}`),console.error(`Actions: save, load, list, latest`),process.exit(1)}}}];function qt(e){let t=``,n=0,r=e.length;for(;n<r;)if(e[n]===`"`){for(t+=`"`,n++;n<r&&e[n]!==`"`;)e[n]===`\\`&&(t+=e[n++]),n<r&&(t+=e[n++]);n<r&&(t+=e[n++])}else if(e[n]===`/`&&n+1<r&&e[n+1]===`/`)for(n+=2;n<r&&e[n]!==`
3
3
  `;)n++;else if(e[n]===`/`&&n+1<r&&e[n+1]===`*`){for(n+=2;n+1<r&&!(e[n]===`*`&&e[n+1]===`/`);)n++;n+=2}else t+=e[n++];return t.replace(/,(\s*[}\]])/g,`$1`)}var U=class{isPlatformSupported(){return this.platforms.includes(process.platform)}async readConfig(e){let t=this.getConfigPath(e);if(!k(t))return{};let n=await z(t,`utf-8`);try{return JSON.parse(qt(n))}catch{throw Error(`Invalid JSON in ${t}. Please fix or remove the file before retrying.`)}}async writeConfig(e,t){let n=this.getConfigPath(t),r=P(n),i=F(r,`.aikit-tmp-${Pt()}.json`);await Dt(r,{recursive:!0});try{await At(i,`${JSON.stringify(e,null,2)}\n`,`utf-8`),await Ot(i,n)}catch(e){try{await kt(i)}catch{}throw e}}async registerMcp(e,t,n){let r=await this.readConfig(n);r[this.configKey]||(r[this.configKey]={}),r[this.configKey][e]=t,await this.writeConfig(r,n)}async unregisterMcp(e,t){let n=await this.readConfig(t);n[this.configKey]&&(delete n[this.configKey][e],await this.writeConfig(n,t))}getScaffoldRoot(e){return null}getInstructionsRoot(e){return null}getScaffoldPaths(e){return{agents:null,skills:null,prompts:null,flows:null,commands:null,instructions:null,manifest:null,hooks:null}}buildInstructionContent(e,t){return`${e}\n---\n\n${t}`}},Jt=class extends U{id=`claude-code`;name=`Claude Code`;family=`claude`;platforms=[`win32`,`darwin`,`linux`];scope=`user`;configKey=`mcpServers`;async detect(){return this.isPlatformSupported()?k(this.getPathModule().resolve(B(),`.claude`)):!1}getConfigPath(){return this.getPathModule().resolve(B(),`.claude`,`mcp.json`)}getScaffoldRoot(){return this.getPathModule().resolve(B(),`.claude`)}getScaffoldPaths(){let e=this.getPathModule(),t=e.resolve(B(),`.claude`);return{agents:e.resolve(t,`agents`),skills:e.resolve(t,`skills`),prompts:null,flows:e.resolve(t,`flows`),commands:e.resolve(t,`commands`),instructions:e.resolve(t,`CLAUDE.md`),manifest:e.resolve(t,`.aikit-scaffold.json`),hooks:null}}buildInstructionContent(e,t){return`${e}\n---\n\n${t}`}getPathModule(){return process.platform===`win32`?R:I}},Yt=class extends U{id=`codex-cli`;name=`Codex CLI`;family=`codex`;platforms=[`win32`,`darwin`,`linux`];scope=`user`;configKey=`mcpServers`;async detect(){return this.isPlatformSupported()?k(this.getPathModule().resolve(B(),`.codex`)):!1}getConfigPath(){return this.getPathModule().resolve(B(),`.codex`,`config.json`)}getScaffoldRoot(){return this.getPathModule().resolve(B(),`.codex`)}getScaffoldPaths(){let e=this.getPathModule(),t=e.resolve(B(),`.codex`);return{agents:e.resolve(t,`agents`),skills:e.resolve(t,`skills`),prompts:null,flows:e.resolve(t,`flows`),commands:null,instructions:e.resolve(t,`AGENTS.md`),manifest:e.resolve(t,`.aikit-scaffold.json`),hooks:null}}getPathModule(){return process.platform===`win32`?R:I}},W=class extends U{family=`copilot`;platforms=[`win32`,`darwin`,`linux`];scope=`user`;hasInstructions=!1;async detect(){if(!this.isPlatformSupported())return!1;let e=this.getConfigDir();if(process.platform===`darwin`){let t=this.getMacAppPath();return k(e)||t!==null&&k(t)}return k(e)}getConfigPath(){return this.getPathModule().resolve(this.getConfigDir(),`mcp.json`)}getScaffoldRoot(){return this.getPathModule().resolve(B(),this.scaffoldBase)}getInstructionsRoot(){let e=this.getInstructionFilePath();return e?this.getPathModule().dirname(e):null}getScaffoldPaths(){let e=this.getPathModule(),t=e.resolve(B(),this.scaffoldBase);return{agents:e.resolve(t,`agents`),skills:e.resolve(t,`skills`),prompts:e.resolve(this.getConfigDir(),`prompts`),flows:e.resolve(t,`flows`),hooks:e.resolve(t,`hooks`),commands:null,instructions:this.getInstructionFilePath(),manifest:e.resolve(t,`.aikit-scaffold.json`)}}getConfigDir(){let e=this.getPathModule(),t=B();if(process.platform===`win32`){let n=process.env.APPDATA??e.resolve(t,`AppData`,`Roaming`);return e.resolve(n,this.configDirName,`User`)}if(process.platform===`darwin`)return e.resolve(t,`Library`,`Application Support`,this.configDirName,`User`);let n=process.env.XDG_CONFIG_HOME??e.resolve(t,`.config`);return e.resolve(n,this.configDirName,`User`)}getMacAppPath(){return null}getInstructionFilePath(){return null}getPathModule(){return process.platform===`win32`?R:I}},Xt=class extends U{id=`copilot-cli`;name=`Copilot CLI`;family=`copilot`;platforms=[`win32`,`darwin`,`linux`];scope=`user`;configKey=`mcpServers`;async detect(){return this.isPlatformSupported()?k(L(B(),`.copilot`)):!1}getConfigPath(){return L(B(),`.copilot`,`mcp-config.json`)}async registerMcp(e,t,n){let r={...t,tools:[`*`]},i=await this.readConfig(n);i[this.configKey]||(i[this.configKey]={}),i[this.configKey][e]=r,await this.writeConfig(i,n)}getScaffoldRoot(){return L(B(),`.copilot`)}getInstructionsRoot(){return null}getScaffoldPaths(){let e=L(B(),`.copilot`);return{agents:L(e,`agents`),skills:L(e,`skills`),prompts:null,flows:L(e,`flows`),hooks:L(e,`hooks`),commands:null,instructions:L(B(),`.github`,`copilot-instructions.md`),manifest:L(e,`.aikit-scaffold.json`)}}},Zt=class extends W{id=`cursor`;name=`Cursor`;configKey=`mcpServers`;configDirName=`Cursor`;scaffoldBase=`.cursor`;getMacAppPath(){return`/Applications/Cursor.app`}getInstructionFilePath(){return this.getPathModule().resolve(B(),this.scaffoldBase,`rules`,`aikit.mdc`)}},Qt=class extends W{id=`cursor-nightly`;name=`Cursor Nightly`;configKey=`mcpServers`;configDirName=`Cursor Nightly`;scaffoldBase=`.cursor`;getMacAppPath(){return`/Applications/Cursor Nightly.app`}getInstructionFilePath(){return this.getPathModule().resolve(B(),this.scaffoldBase,`rules`,`aikit.mdc`)}},$t=class e extends U{id=`intellij`;name=`IntelliJ IDEA`;family=`copilot`;platforms=[`win32`,`darwin`,`linux`];scope=`user`;configKey=`servers`;static PRODUCTS=[`IntelliJIdea`,`IdeaIC`,`WebStorm`,`PyCharm`,`PyCharmCE`,`GoLand`,`PhpStorm`,`CLion`,`Rider`,`RubyMine`,`RustRover`,`DataGrip`];async detect(){if(!this.isPlatformSupported())return!1;if(k(this.getCopilotConfigDir()))return!0;let t=this.getJetBrainsBaseDir();if(!k(t))return!1;try{return M(t,{withFileTypes:!0}).some(t=>t.isDirectory()&&e.PRODUCTS.some(e=>t.name.startsWith(e)))}catch{return!1}}getConfigPath(){return L(this.getCopilotConfigDir(),`mcp.json`)}async registerMcp(e,t,n){let r=this.getCopilotConfigDir();await Dt(r,{recursive:!0});let i=t.args??[],a=i.indexOf(`-e`),o;if(a!==-1&&a+1<i.length){let t=i[a+1],n=L(r,`${e}-launcher.js`);await At(n,t,`utf-8`),o=[...i.slice(0,a),n,...i.slice(a+2)]}else o=[...i];let s={type:`stdio`,...t,args:o};await super.registerMcp(e,s,n)}getScaffoldRoot(e){return null}getInstructionsRoot(e){return null}getScaffoldPaths(e){return{agents:null,skills:null,prompts:null,flows:null,commands:null,instructions:null,manifest:null,hooks:null}}buildInstructionContent(e,t){return t}getCopilotConfigDir(){let e=B();return process.platform===`win32`?L(process.env.LOCALAPPDATA??L(e,`AppData`,`Local`),`github-copilot`,`intellij`):process.platform===`darwin`?L(e,`Library`,`Application Support`,`github-copilot`,`intellij`):L(process.env.XDG_CONFIG_HOME??L(e,`.config`),`github-copilot`,`intellij`)}getJetBrainsBaseDir(){let e=B();return process.platform===`win32`?L(process.env.APPDATA??L(e,`AppData`,`Roaming`),`JetBrains`):process.platform===`darwin`?L(e,`Library`,`Application Support`,`JetBrains`):L(process.env.XDG_CONFIG_HOME??L(e,`.config`),`JetBrains`)}},en=class extends W{id=`trae`;name=`Trae`;configKey=`servers`;configDirName=`Trae`;scaffoldBase=`.trae`;getMacAppPath(){return`/Applications/Trae.app`}getInstructionFilePath(){return this.getPathModule().resolve(B(),this.scaffoldBase,`rules`,`aikit.md`)}},tn=class extends W{id=`vscode`;name=`VS Code`;configKey=`servers`;configDirName=`Code`;scaffoldBase=`.copilot`;hasInstructions=!0;getMacAppPath(){return`/Applications/Visual Studio Code.app`}getInstructionFilePath(){return this.hasInstructions?this.getPathModule().resolve(B(),this.scaffoldBase,`instructions`,`copilot-instructions.md`):null}buildInstructionContent(e,t){return`---\napplyTo: "**"\n---\n\n${e}\n---\n\n${t}`}},nn=class extends W{id=`vscode-insiders`;name=`VS Code Insiders`;configKey=`servers`;configDirName=`Code - Insiders`;scaffoldBase=`.copilot`;hasInstructions=!0;getMacAppPath(){return`/Applications/Visual Studio Code - Insiders.app`}getInstructionFilePath(){return this.hasInstructions?this.getPathModule().resolve(B(),this.scaffoldBase,`instructions`,`copilot-instructions.md`):null}buildInstructionContent(e,t){return`---\napplyTo: "**"\n---\n\n${e}\n---\n\n${t}`}},rn=class extends W{id=`vscodium`;name=`VSCodium`;configKey=`servers`;configDirName=`VSCodium`;scaffoldBase=`.copilot`;hasInstructions=!0;getMacAppPath(){return`/Applications/VSCodium.app`}getInstructionFilePath(){return this.hasInstructions?this.getPathModule().resolve(B(),this.scaffoldBase,`instructions`,`copilot-instructions.md`):null}buildInstructionContent(e,t){return`---\napplyTo: "**"\n---\n\n${e}\n---\n\n${t}`}},an=class extends W{id=`windsurf`;name=`Windsurf`;configKey=`servers`;configDirName=`Windsurf`;scaffoldBase=`.windsurf`;getMacAppPath(){return`/Applications/Windsurf.app`}getInstructionFilePath(){return this.getPathModule().resolve(B(),this.scaffoldBase,`rules`,`aikit.md`)}},on=class extends U{id=`gemini-cli`;name=`Gemini CLI`;family=`gemini`;platforms=[`win32`,`darwin`,`linux`];scope=`user`;configKey=`mcpServers`;async detect(){return this.isPlatformSupported()?k(this.getPathModule().resolve(B(),`.gemini`)):!1}getConfigPath(){return this.getPathModule().resolve(B(),`.gemini`,`settings.json`)}getScaffoldRoot(){return this.getPathModule().resolve(B(),`.gemini`)}getScaffoldPaths(){let e=this.getPathModule(),t=e.resolve(B(),`.gemini`);return{agents:e.resolve(t,`agents`),skills:e.resolve(t,`skills`),prompts:null,flows:e.resolve(t,`flows`),commands:null,instructions:e.resolve(t,`AGENTS.md`),manifest:e.resolve(t,`.aikit-scaffold.json`),hooks:null}}getPathModule(){return process.platform===`win32`?R:I}},sn=class extends U{id=`zed`;name=`Zed`;family=`zed`;platforms=[`win32`,`darwin`,`linux`];scope=`user`;configKey=`context_servers`;async detect(){return this.isPlatformSupported()?k(this.getConfigDir()):!1}getConfigPath(){return this.getPathModule().resolve(this.getConfigDir(),`settings.json`)}async registerMcp(e,t){let{type:n,...r}=t,i={...r,env:r.env??{}};await super.registerMcp(e,i)}getScaffoldRoot(){return this.getConfigDir()}getScaffoldPaths(){let e=this.getPathModule(),t=this.getConfigDir();return{agents:e.resolve(t,`prompts`),skills:null,prompts:e.resolve(t,`prompts`),flows:null,commands:null,instructions:null,manifest:e.resolve(t,`.aikit-scaffold.json`),hooks:null}}getConfigDir(){let e=this.getPathModule();return process.platform===`win32`?e.resolve(process.env.APPDATA||B(),`Zed`):e.resolve(B(),`.config`,`zed`)}getPathModule(){return process.platform===`win32`?R:I}};const cn=[new tn,new nn,new rn,new Zt,new Qt,new an,new en,new Xt,new $t,new Jt,new on,new Yt,new sn];async function ln(e){let t=e?.scope?cn.filter(t=>t.scope===e.scope):cn;return(await Promise.allSettled(t.map(async e=>await e.detect()?e:null))).flatMap(e=>e.status!==`fulfilled`||e.value===null?[]:[e.value])}const un={SessionStart:{copilot:`SessionStart`,claude:`PreToolCall`,copilotCli:`sessionStart`},PreToolUse:{copilot:`PreToolUse`,claude:`PreToolCall`,copilotCli:`preToolUse`},PostToolUse:{copilot:`PostToolUse`,claude:`PostToolCall`,copilotCli:`postToolUse`},SubagentStart:{copilot:`SubagentStart`,claude:`PreToolCall`,copilotCli:`subagentStart`},PreCompact:{copilot:`PreCompact`,claude:`PreToolCall`,copilotCli:`preCompact`},Stop:{copilot:`Stop`,claude:`PostToolCall`,copilotCli:`stop`}},dn={fileRead:{copilot:[`read_file`,`readFile`],claude:[`Read`],copilotCli:[`read_file`]},fileWrite:{copilot:[`editFiles`,`replace_string_in_file`,`create_file`],claude:[`Write`,`Edit`],copilotCli:[`editFiles`,`replace_string_in_file`]},fileSearch:{copilot:[`grep_search`,`semantic_search`,`find`],claude:[`Bash`],copilotCli:[`grep_search`]}},G={"privacy-guard":{id:`privacy-guard`,event:`PreToolUse`,tier:`safety`,description:`Blocks reads of secret-bearing env files, key material, SSH paths, and credential artifacts.`,script:`privacy-guard.mjs`,matcher:[`fileRead`],scope:`user`,patterns:[`.env`,`*.pem`,`*.key`,`id_rsa*`,`.ssh/*`,`*credentials*`,`*.secret`]},"scout-guard":{id:`scout-guard`,event:`PreToolUse`,tier:`safety`,description:`Blocks reads and searches inside generated, dependency, and git object directories.`,script:`scout-guard.mjs`,matcher:[`fileRead`,`fileSearch`],scope:`user`,patterns:[`node_modules/`,`dist/`,`.git/objects/`,`vendor/`,`build/`]},"subagent-context":{id:`subagent-context`,event:`SubagentStart`,tier:`efficiency`,description:`Injects compact project context into each subagent spawn to reduce repeated discovery.`,script:`subagent-context.mjs`,scope:`user`},"pre-compact-save":{id:`pre-compact-save`,event:`PreCompact`,tier:`efficiency`,description:`Persists critical state before context compaction truncates recent session history.`,script:`pre-compact-save.mjs`,scope:`user`},"post-edit-check":{id:`post-edit-check`,event:`PostToolUse`,tier:`nudge`,description:`After repeated file edits, injects a validation reminder so checks are not skipped.`,script:`post-edit-check.mjs`,matcher:[`fileWrite`],scope:`user`},"session-init":{id:`session-init`,event:`SessionStart`,tier:`nudge`,description:`Detects project stack and injects workspace metadata and environment context at startup.`,script:`session-init.mjs`,scope:`user`},"session-observer":{id:`session-observer`,event:`PostToolUse`,tier:`efficiency`,description:`Captures tool usage patterns for autonomous lesson extraction. Writes to session buffer.`,script:`session-observer.mjs`,scope:`user`},"session-learn":{id:`session-learn`,event:`Stop`,tier:`efficiency`,description:`Nudges final pattern analysis on buffered observations at session end.`,script:`session-learn.mjs`,scope:`user`}},fn={PreCompact:3e3,PostToolUse:3e3},pn={copilot:`hooks.json`,claude:`hooks-settings.json`,copilotCli:`hooks.json`};function mn(e,t){return(e.matcher||[]).flatMap(e=>{let n=dn[e];if(!n)throw Error(`Unknown hook matcher: ${e}`);return n[t]||[]})}function hn(e,t,n,r){let i=`${n}/${e.script}`;return mn(e,r),r===`copilot`?{event:t,steps:[{type:`command`,command:`node`,args:[i],timeout:fn[e.event]||5e3}]}:r===`claude`?{type:`command`,command:`node ${i}`}:{command:`node`,args:[i]}}function gn(e,t){if(e===`copilot`){let n=Object.values(G).map(n=>{let r=un[n.event]?.[e];if(!r)throw Error(`Unsupported hook event ${n.event} for ${e}`);return hn(n,r,t,e)});return[{path:pn[e],content:JSON.stringify({hooks:n},null,2)}]}let n={};for(let r of Object.values(G)){let i=un[r.event]?.[e];if(!i)throw Error(`Unsupported hook event ${r.event} for ${e}`);n[i]||=[],n[i].push(hn(r,i,t,e))}return[{path:pn[e],content:JSON.stringify({hooks:n},null,2)}]}function _n(){return[`_runtime.mjs`,...Object.values(G).map(e=>e.script)]}function vn(){let e={command:x.command,args:x.args?[...x.args]:void 0,type:x.type};if(process.platform!==`win32`){let t=process.env.PATH;t&&(e.env={PATH:t});try{let t=Ft(`which`,[`node`],{encoding:`utf-8`,timeout:3e3}).trim();t&&k(t)&&(e.command=t)}catch{}}return e}const yn=new Set([`VS Code`,`VS Code Insiders`,`VSCodium`]);function bn(e,t,n){let r=L(B(),`.copilot`,`instructions`,`copilot-instructions.md`);!k(r)||n.has(r)||(A(P(r),{recursive:!0}),N(r,`---\napplyTo: "**"\n---\n\n${e}\n---\n\n${t}`,`utf-8`),n.add(r))}function xn(e,t=!1){if(!yn.has(e.name))return;let n=L(P(e.getConfigPath()),`settings.json`),r={};if(k(n))try{let e=j(n,`utf-8`);r=JSON.parse(e)}catch{console.log(` ${e.name}: skipped settings.json (invalid JSON)`);return}let i=!1;for(let[e,n]of Object.entries(se))if(typeof n==`object`&&n){let t=typeof r[e]==`object`&&r[e]!==null?r[e]:{},a={...t,...n};JSON.stringify(a)!==JSON.stringify(t)&&(r[e]=a,i=!0)}else (t||!(e in r))&&(r[e]=n,i=!0);i&&(N(n,`${JSON.stringify(r,null,2)}\n`,`utf-8`),console.log(` ${e.name}: updated settings.json`))}async function Sn(r,i,s,c,l=!1){let u=new Map,d=new Set,f=re(`aikit`,s),p=ce(`aikit`,s);for(let e of i)e.getScaffoldRoot()!==null&&u.set(e.id,e);if(bn(f,p,d),u.size===0){d.size>0?console.log(` Instruction files: ${[...d].join(`, `)}`):console.log(` No IDEs with global scaffold support detected.`);return}let ee=await n(r,`copilot`),m=new Map;for(let e of ee){let t=e.path.indexOf(`/`);if(t===-1)continue;let n=e.path.substring(0,t);if(n!==`agents`&&n!==`prompts`)continue;let r=m.get(n)??[];r.push({path:e.path.substring(t+1),content:e.content}),m.set(n,r)}let h=await n(r,`skills`),g=new Set;for(let e of h){let t=e.path.indexOf(`/`);t!==-1&&g.add(e.path.substring(0,t))}let _=await n(r,`flows`),v=new Set;for(let e of _){let t=e.path.indexOf(`/`);t!==-1&&v.add(e.path.substring(0,t))}let y=await n(r,`claude-code`),b=L(r,`scaffold`,`general`,`hooks`,`scripts`),te=k(b)?b:L(import.meta.dirname,`../../../../../scaffold/general/hooks/scripts`),ne=_n(),x=new Set,S=new Set,C=new Set,w=(n,r,i)=>{let s=m.get(i);if(!n||!r||!s||s.length===0)return;let u=`${i}:${r}:${n}`;if(x.has(u))return;x.add(u);let d=e(r)??o(c);d.version=c,a(s,n,d,i,l),t(r,d),C.add(P(r))},T=(n,r,i,s)=>{if(!n||!r||s.length===0)return;let u=`${i}:${r}:${n}`;if(x.has(u))return;if(x.add(u),i===`flows`&&!S.has(n)){for(let e of v){let t=L(n,e,`skills`);k(t)&&(fe(t,{recursive:!0,force:!0}),console.log(` ${P(r)}: migrated ${e} flow to steps/ layout`))}S.add(n)}let d=e(r)??o(c);d.version=c,a(s,n,d,i,l),t(r,d),C.add(P(r))},ie=(e,t,n)=>{!e||!t||T(e,t,`hooks`,[...gn(n,L(e,`scripts`).replace(/\\/g,`/`)),...ne.map(e=>({path:`scripts/${e}`,content:j(L(te,e),`utf-8`)}))])};for(let e of u.values()){let t=e.getScaffoldPaths();w(t.agents,t.manifest,`agents`),w(t.prompts,t.manifest,`prompts`),T(t.skills,t.manifest,`skills`,h),T(t.flows,t.manifest,`flows`,_),T(t.commands,t.manifest,`commands`,y),ie(t.hooks,t.manifest,e.family===`claude`?`claude`:`copilot`)}for(let e of C)console.log(` ${e}: scaffold updated (${g.size} skills)`);for(let e of u.values()){let t=e.getScaffoldPaths().instructions;!t||d.has(t)||(A(P(t),{recursive:!0}),N(t,e.buildInstructionContent(f,p),`utf-8`),d.add(t))}d.size>0&&console.log(` Instruction files: ${[...d].join(`, `)}`)}function Cn(e){let t=[];for(let n of e){let e=n.getScaffoldRoot();if(e)if(yn.has(n.name)){let r=n.getInstructionsRoot()??e;t.push(L(r,`kb.instructions.md`)),t.push(L(r,`aikit.instructions.md`))}else n.name===`Cursor`||n.name===`Cursor Nightly`?t.push(L(e,`rules`,`kb.mdc`)):n.name===`Windsurf`&&t.push(L(e,`rules`,`kb.md`))}for(let e of t)k(e)&&(pe(e),console.log(` Removed legacy file: ${e}`))}async function K(e){let t=g,n=ae(),r=JSON.parse(j(L(n,`package.json`),`utf-8`)).version;console.log(`Initializing @vpxa/aikit v${r}...\n`);let i=Rt();A(i,{recursive:!0}),console.log(` Global data store: ${i}`),Vt({version:1,workspaces:{}}),console.log(` Created registry.json`);let a=await ln({scope:`user`});if(a.length===0)console.log(`
4
4
  No supported IDEs detected. You can manually add the MCP server config.`);else{console.log(`\n Detected ${a.length} IDE(s):`);let n=vn();for(let e of a)try{await e.registerMcp(t,n),console.log(` ${e.name}: configured ${t}`)}catch(t){console.log(` ${e.name}: failed to configure (${t.message})`)}for(let t of a)xn(t,e.force)}console.log(`
@@ -13,10 +13,10 @@ Issues found:`);for(let e of n.issues)console.log(` - ${e}`)}}}],Wn=[{name:`pro
13
13
  Actions: stats, find-nodes, find-edges, neighbors, traverse, delete, clear`),process.exit(1));let{graphStore:n}=await Q(),r=y(e,`--type`,``),i=y(e,`--name`,``),a=y(e,`--node-id`,``),o=y(e,`--edge-type`,``),s=y(e,`--direction`,`both`),c=E(e,`--depth`,2),l=E(e,`--limit`,50),u=y(e,`--source-path`,``),d={stats:`stats`,"find-nodes":`find_nodes`,"find-edges":`find_edges`,neighbors:`neighbors`,traverse:`traverse`,delete:`delete`,clear:`clear`}[t];d||(console.error(`Unknown graph action: ${t}`),console.error(`Actions: stats, find-nodes, find-edges, neighbors, traverse, delete, clear`),process.exit(1));let f=await Re(n,{action:d,nodeType:r||void 0,namePattern:i||void 0,sourcePath:u||void 0,nodeId:a||void 0,edgeType:o||void 0,direction:s,maxDepth:c,limit:l});if(console.log(f.summary),f.nodes&&f.nodes.length>0){console.log(`
14
14
  Nodes:`);for(let e of f.nodes){let t=Object.keys(e.properties).length>0?` ${JSON.stringify(e.properties)}`:``;console.log(` ${e.name} (${e.type}, id: ${e.id})${t}`)}}if(f.edges&&f.edges.length>0){console.log(`
15
15
  Edges:`);for(let e of f.edges){let t=e.weight===1?``:` (weight: ${e.weight})`;console.log(` ${e.fromId} --[${e.type}]--> ${e.toId}${t}`)}}f.stats&&(console.log(`\nNode types: ${JSON.stringify(f.stats.nodeTypes)}`),console.log(`Edge types: ${JSON.stringify(f.stats.edgeTypes)}`)),f.deleted!==void 0&&console.log(`Deleted: ${f.deleted}`)}}],nr=[{name:`remember`,description:`Store curated knowledge`,usage:`aikit remember <title> --category <cat> [--tags tag1,tag2]`,run:async e=>{let t=y(e,`--category`,``).trim(),n=f(y(e,`--tags`,``)),r=e.shift()?.trim()??``,i=await s(),a=i.trim().length>0?i:e.join(` `).trim();(!r||!t||!a.trim())&&(console.error(`Usage: aikit remember <title> --category <cat> [--tags tag1,tag2]`),process.exit(1));let{curated:o}=await Q(),c=await o.remember(r,a,t,n);console.log(`Stored curated entry`),console.log(` Path: ${c.path}`),console.log(` Category: ${t}`),n.length>0&&console.log(` Tags: ${n.join(`, `)}`)}},{name:`forget`,description:`Remove a curated entry`,usage:`aikit forget <path> --reason <reason>`,run:async e=>{let t=y(e,`--reason`,``).trim(),n=e.shift()?.trim()??``;(!n||!t)&&(console.error(`Usage: aikit forget <path> --reason <reason>`),process.exit(1));let{curated:r}=await Q(),i=await r.forget(n,t);console.log(`Removed curated entry: ${i.path}`)}},{name:`read`,description:`Read a curated entry`,usage:`aikit read <path>`,run:async e=>{let t=e.shift()?.trim()??``;t||(console.error(`Usage: aikit read <path>`),process.exit(1));let{curated:n}=await Q(),r=await n.read(t);console.log(r.title),console.log(`─`.repeat(60)),console.log(`Path: ${r.path}`),console.log(`Category: ${r.category}`),console.log(`Version: ${r.version}`),console.log(`Tags: ${r.tags.length>0?r.tags.join(`, `):`None`}`),console.log(``),console.log(r.content)}},{name:`list`,description:`List curated entries`,usage:`aikit list [--category <cat>] [--tag <tag>]`,run:async e=>{let t=y(e,`--category`,``).trim()||void 0,n=y(e,`--tag`,``).trim()||void 0,{curated:r}=await Q(),i=await r.list({category:t,tag:n});if(i.length===0){console.log(`No curated entries found.`);return}console.log(`Curated entries (${i.length})`),console.log(`─`.repeat(60));for(let e of i){console.log(e.path),console.log(` ${e.title}`),console.log(` Category: ${e.category} | Version: ${e.version}`),console.log(` Tags: ${e.tags.length>0?e.tags.join(`, `):`None`}`);let t=e.contentPreview.replace(/\s+/g,` `).trim();t&&console.log(` Preview: ${t}`),console.log(``)}}},{name:`update`,description:`Update a curated entry`,usage:`aikit update <path> --reason <reason>`,run:async e=>{let t=y(e,`--reason`,``).trim(),n=e.shift()?.trim()??``,r=await s();(!n||!t||!r.trim())&&(console.error(`Usage: aikit update <path> --reason <reason>`),process.exit(1));let{curated:i}=await Q(),a=await i.update(n,r,t);console.log(`Updated curated entry`),console.log(` Path: ${a.path}`),console.log(` Version: ${a.version}`)}},{name:`compact`,description:`Compress text for context`,usage:`aikit compact <query> [--path <file>] [--max-chars N] [--segmentation paragraph|sentence|line]`,run:async e=>{let t=E(e,`--max-chars`,3e3),n=y(e,`--path`,``).trim()||void 0,r=y(e,`--segmentation`,`paragraph`),i=e.join(` `).trim(),a=n?void 0:await s();(!i||!n&&!a?.trim())&&(console.error(`Usage: aikit compact <query> --path <file> OR cat file | aikit compact <query>`),process.exit(1));let{embedder:o}=await Q(),c=n?await Te(o,{path:n,query:i,maxChars:t,segmentation:r}):await Te(o,{text:a??``,query:i,maxChars:t,segmentation:r});console.log(`Compressed ${c.originalChars} chars to ${c.compressedChars} chars`),console.log(`Ratio: ${(c.ratio*100).toFixed(1)}% | Segments: ${c.segmentsKept}/${c.segmentsTotal}`),console.log(``),console.log(c.text)}}],rr=[{name:`search`,description:`Search the AI Kit index`,usage:`aikit search <query> [--limit N] [--mode hybrid|semantic|keyword] [--graph-hops 0-3]`,run:async e=>{let t=E(e,`--limit`,5),n=y(e,`--mode`,`hybrid`),r=E(e,`--graph-hops`,0),i=e.join(` `).trim();i||(console.error(`Usage: aikit search <query>`),process.exit(1));let{embedder:a,store:o,graphStore:s}=await Q(),c=await a.embedQuery(i),l;if(n===`keyword`)l=await o.ftsSearch(i,{limit:t});else if(n===`semantic`)l=await o.search(c,{limit:t});else{let[e,n]=await Promise.all([o.search(c,{limit:t*2}),o.ftsSearch(i,{limit:t*2}).catch(()=>[])]);l=d(e,n).slice(0,t)}if(l.length===0){console.log(`No results found.`);return}for(let{record:e,score:t}of l){console.log(`\n${`─`.repeat(60)}`),console.log(`[${(t*100).toFixed(1)}%] ${e.sourcePath}:${e.startLine}-${e.endLine}`),console.log(` Type: ${e.contentType} | Origin: ${e.origin}`),e.tags.length>0&&console.log(` Tags: ${e.tags.join(`, `)}`),console.log(``);let n=e.content.length>500?`${e.content.slice(0,500)}...`:e.content;console.log(n)}if(console.log(`\n${`─`.repeat(60)}`),console.log(`${l.length} result(s) found.`),r>0&&l.length>0)try{let{graphAugmentSearch:e}=await import(`../../tools/dist/index.js`),t=(await e(s,l.map(e=>({recordId:e.record.id,score:e.score,sourcePath:e.record.sourcePath})),{hops:r,maxPerHit:5})).filter(e=>e.graphContext.nodes.length>0);if(t.length>0){console.log(`\nGraph context (${r} hop${r>1?`s`:``}):\n`);for(let e of t){console.log(` ${e.sourcePath}:`);for(let t of e.graphContext.nodes.slice(0,5))console.log(` → ${t.name} (${t.type})`);for(let t of e.graphContext.edges.slice(0,5))console.log(` → ${t.fromId} --[${t.type}]--> ${t.toId}`)}}}catch(e){console.error(`[graph] augmentation failed: ${e.message}`)}}},{name:`find`,description:`Run federated search across indexed content and files`,usage:`aikit find [query] [--glob <pattern>] [--pattern <regex>] [--limit N]`,run:async e=>{let t=E(e,`--limit`,10),n=y(e,`--glob`,``).trim()||void 0,r=y(e,`--pattern`,``).trim()||void 0,i=e.join(` `).trim()||void 0;!i&&!n&&!r&&(console.error(`Usage: aikit find [query] [--glob <pattern>] [--pattern <regex>] [--limit N]`),process.exit(1));let{embedder:a,store:o}=await Q(),s=await Ne(a,o,{query:i,glob:n,pattern:r,limit:t});if(s.results.length===0){console.log(`No matches found.`);return}console.log(`Strategies: ${s.strategies.join(`, `)}`),console.log(`Results: ${s.results.length} shown (${s.totalFound} total)`);for(let e of s.results){let t=e.lineRange?`:${e.lineRange.start}-${e.lineRange.end}`:``;console.log(`\n[${e.source}] ${e.path}${t}`),console.log(` Score: ${(e.score*100).toFixed(1)}%`),e.preview&&console.log(` ${e.preview.replace(/\s+/g,` `).trim()}`)}}},{name:`scope-map`,description:`Generate a reading plan for a task`,usage:`aikit scope-map <task> [--max-files N]`,run:async e=>{let t=E(e,`--max-files`,15),n=e.join(` `).trim();n||(console.error(`Usage: aikit scope-map <task> [--max-files N]`),process.exit(1));let{embedder:r,store:i}=await Q(),a=await ht(r,i,{task:n,maxFiles:t});console.log(`Task: ${a.task}`),console.log(`Files: ${a.files.length}`),console.log(`Estimated tokens: ${a.totalEstimatedTokens}`),console.log(``),console.log(`Reading order:`);for(let e of a.readingOrder)console.log(` ${e}`);for(let[e,t]of a.files.entries())console.log(`\n${e+1}. ${t.path}`),console.log(` Relevance: ${(t.relevance*100).toFixed(1)}% | Tokens: ${t.estimatedTokens}`),console.log(` Why: ${t.reason}`),t.focusRanges.length>0&&console.log(` Focus: ${b(t.focusRanges)}`)}},{name:`symbol`,description:`Resolve a symbol definition, imports, and references`,usage:`aikit symbol <name> [--limit N]`,run:async e=>{let t=E(e,`--limit`,20),n=e.join(` `).trim();n||(console.error(`Usage: aikit symbol <name> [--limit N]`),process.exit(1));let{embedder:r,store:i}=await Q();u(await xt(r,i,{name:n,limit:t}))}},{name:`trace`,description:`Trace forward/backward flow for a symbol or file location`,usage:`aikit trace <start> [--direction forward|backward|both] [--max-depth N]`,run:async e=>{let t=y(e,`--direction`,`both`).trim()||`both`,n=E(e,`--max-depth`,3),r=e.join(` `).trim();(!r||![`forward`,`backward`,`both`].includes(t))&&(console.error(`Usage: aikit trace <start> [--direction forward|backward|both] [--max-depth N]`),process.exit(1));let{embedder:i,store:a}=await Q();p(await Ct(i,a,{start:r,direction:t,maxDepth:n}))}},{name:`examples`,description:`Find real code examples of a symbol or pattern`,usage:`aikit examples <query> [--limit N] [--content-type type]`,run:async e=>{let t=E(e,`--limit`,5),n=y(e,`--content-type`,``).trim()||void 0,r=e.join(` `).trim();r||(console.error(`Usage: aikit examples <query> [--limit N] [--content-type type]`),process.exit(1));let{embedder:i,store:a}=await Q();le(await Fe(i,a,{query:r,limit:t,contentType:n}))}},{name:`dead-symbols`,description:`Find exported symbols that appear to be unused`,usage:`aikit dead-symbols [--limit N]`,run:async e=>{let t=E(e,`--limit`,100),{embedder:n,store:r}=await Q();ue(await Pe(n,r,{limit:t}))}},{name:`lookup`,description:`Look up indexed content by record ID or source path`,usage:`aikit lookup <id>`,run:async e=>{let t=e.join(` `).trim();t||(console.error(`Usage: aikit lookup <id>`),process.exit(1));let{store:n}=await Q(),r=await n.getById(t);if(r){console.log(r.id),console.log(`─`.repeat(60)),console.log(`Path: ${r.sourcePath}`),console.log(`Chunk: ${r.chunkIndex+1}/${r.totalChunks}`),console.log(`Lines: ${r.startLine}-${r.endLine}`),console.log(`Type: ${r.contentType} | Origin: ${r.origin}`),r.tags.length>0&&console.log(`Tags: ${r.tags.join(`, `)}`),console.log(``),console.log(r.content);return}let i=await n.getBySourcePath(t);if(i.length===0){console.log(`No indexed content found for: ${t}`);return}i.sort((e,t)=>e.chunkIndex-t.chunkIndex),console.log(t),console.log(`─`.repeat(60)),console.log(`Chunks: ${i.length} | Type: ${i[0].contentType}`);for(let e of i){let t=e.startLine?` (lines ${e.startLine}-${e.endLine})`:``;console.log(`\nChunk ${e.chunkIndex+1}/${e.totalChunks}${t}`),console.log(e.content)}}}],ir=[{name:`status`,description:`Show AI Kit index status and statistics`,run:async()=>{let{isUserInstalled:e,getGlobalDataDir:t,computePartitionKey:n,listWorkspaces:r}=await import(`../../core/dist/index.js`),{existsSync:i}=await import(`node:fs`),a=process.cwd(),o=e(),s=i(L(a,`.vscode`,`mcp.json`)),c,l;if(o&&s)c=`workspace (overrides user-level for this workspace)`,l=L(a,`.aikit-data`);else if(o){let e=n(a);c=i(L(a,`AGENTS.md`))?`user (workspace scaffolded)`:`user (workspace not scaffolded)`,l=L(t(),e)}else c=`workspace`,l=L(a,`.aikit-data`);if(console.log(`AI Kit Status`),console.log(`─`.repeat(40)),console.log(` Mode: ${c}`),console.log(` Data: ${l}`),o&&!s){let e=r();console.log(` Registry: ${e.length} workspace(s) enrolled`)}try{let{store:e}=await Q(),t=await e.getStats(),n=await e.listSourcePaths();console.log(` Records: ${t.totalRecords}`),console.log(` Files: ${t.totalFiles}`),console.log(` Indexed: ${t.lastIndexedAt??`Never`}`),console.log(` Backend: ${t.storeBackend}`),console.log(` Model: ${t.embeddingModel}`),console.log(``),console.log(`Content Types:`);for(let[e,n]of Object.entries(t.contentTypeBreakdown))console.log(` ${e}: ${n}`);if(n.length>0){console.log(``),console.log(`Files (${n.length} total):`);for(let e of n.slice(0,20))console.log(` ${e}`);n.length>20&&console.log(` ... and ${n.length-20} more`)}}catch{console.log(``),console.log(" Index not available — run `aikit reindex` to index this workspace.")}o&&!s&&!i(L(a,`AGENTS.md`))&&(console.log(``),console.log(" Action: Run `npx @vpxa/aikit init` to add AGENTS.md and copilot-instructions.md"))}},{name:`reindex`,description:`Re-index the AI Kit index from configured sources`,usage:`aikit reindex [--full]`,run:async e=>{let t=e.includes(`--full`),{store:n,indexer:r,curated:i,config:a}=await Q();console.log(`Indexing sources...`);let o=e=>{e.phase===`chunking`&&e.currentFile&&process.stdout.write(`\r [${e.filesProcessed+1}/${e.filesTotal}] ${e.currentFile}`),e.phase===`done`&&process.stdout.write(`
16
- `)},s;t?(console.log(`Dropping existing index for full reindex...`),s=await r.reindexAll(a,o)):s=await r.index(a,o),console.log(`Done: ${s.filesProcessed} files, ${s.chunksCreated} chunks in ${(s.durationMs/1e3).toFixed(1)}s`),console.log(`Building FTS index...`),await n.createFtsIndex(),console.log(`Re-indexing curated entries...`);let c=await i.reindexAll();console.log(`Curated: ${c.indexed} entries restored`)}},{name:`serve`,description:`Start the MCP server (stdio or HTTP)`,usage:`aikit serve [--transport stdio|http] [--port N]`,run:async e=>{let t=S(),n=y(e,`--transport`,`stdio`),r=y(e,`--port`,`3210`);try{await Hn({silent:!0})}catch{}let i=It(t,[],{stdio:n===`stdio`?[`pipe`,`pipe`,`inherit`,`ipc`]:`inherit`,env:{...process.env,AIKIT_TRANSPORT:n,AIKIT_PORT:r}});n===`stdio`&&i.stdin&&i.stdout&&(process.stdin.pipe(i.stdin),i.stdout.pipe(process.stdout)),i.on(`exit`,e=>process.exit(e??0)),process.on(`SIGINT`,()=>i.kill(`SIGINT`)),process.on(`SIGTERM`,()=>i.kill(`SIGTERM`)),await new Promise(()=>{})}},{name:`init`,description:`Initialize AI Kit in the current directory`,usage:`aikit init [--workspace] [--smart] [--force] [--guide]`,run:async e=>{let t=e.includes(`--user`),n=e.includes(`--workspace`),r=e.includes(`--smart`),i=e.includes(`--guide`),a=e.includes(`--force`);if(t&&n&&(console.error(`Cannot use --user and --workspace together.`),process.exit(1)),i){let{guideProject:e}=await import(`./init-o6szsZIP.js`);await e();return}if(r){let{initSmart:e}=await import(`./init-o6szsZIP.js`);await e({force:a})}else if(t)await K({force:a});else if(n){let{initProject:e}=await import(`./init-o6szsZIP.js`);await e({force:a})}else await K({force:a})}},{name:`check`,description:`Run incremental typecheck and lint`,usage:`aikit check [--cwd <dir>] [--files f1,f2] [--skip-types] [--skip-lint] [--detail efficient|normal|full]`,run:async e=>{let t=y(e,`--cwd`,``).trim()||void 0,n=y(e,`--files`,``),r=y(e,`--detail`,`full`)||`full`,i=n.split(`,`).map(e=>e.trim()).filter(Boolean),a=!1;e.includes(`--skip-types`)&&(e.splice(e.indexOf(`--skip-types`),1),a=!0);let o=!1;e.includes(`--skip-lint`)&&(e.splice(e.indexOf(`--skip-lint`),1),o=!0);let s=await ye({cwd:t,files:i.length>0?i:void 0,skipTypes:a,skipLint:o,detail:r});h(s),s.passed||(process.exitCode=1)}},{name:`health`,description:`Run project health checks on the current directory`,usage:`aikit health [path]`,run:async e=>{let t=Be(e.shift());console.log(`Project Health: ${t.path}`),console.log(`─`.repeat(50));for(let e of t.checks){let t=e.status===`pass`?`+`:e.status===`warn`?`~`:`X`;console.log(` [${t}] ${e.name}: ${e.message}`)}console.log(`─`.repeat(50)),console.log(`Score: ${t.score}% — ${t.summary}`)}},{name:`prune`,description:`Clean up orphaned storage, legacy data, and stale partitions`,usage:`aikit prune [--dry-run] [--max-age-days=90] [--force]`,run:async e=>{let{prune:t,formatBytes:n,markPruneRun:r}=await import(`../../tools/dist/index.js`),i=e.includes(`--dry-run`),a=e.includes(`--force`),o=e.find(e=>e.startsWith(`--max-age-days=`)),s=o?Number.parseInt(o.split(`=`)[1]??``,10):90;if(!i&&!a){console.log(`⚠️ This will permanently delete data. Use --dry-run to preview, or --force to execute.`);return}console.log(i?`🔍 Dry run — no files will be deleted
16
+ `)},s;t?(console.log(`Dropping existing index for full reindex...`),s=await r.reindexAll(a,o)):s=await r.index(a,o),console.log(`Done: ${s.filesProcessed} files, ${s.chunksCreated} chunks in ${(s.durationMs/1e3).toFixed(1)}s`),console.log(`Building FTS index...`),await n.createFtsIndex(),console.log(`Re-indexing curated entries...`);let c=await i.reindexAll();console.log(`Curated: ${c.indexed} entries restored`)}},{name:`serve`,description:`Start the MCP server (stdio or HTTP)`,usage:`aikit serve [--transport stdio|http] [--port N]`,run:async e=>{let t=S(),n=y(e,`--transport`,`stdio`),r=y(e,`--port`,`3210`);try{await Hn({silent:!0})}catch{}let i=It(t,[],{stdio:n===`stdio`?[`pipe`,`pipe`,`inherit`,`ipc`]:`inherit`,env:{...process.env,AIKIT_TRANSPORT:n,AIKIT_PORT:r}});n===`stdio`&&i.stdin&&i.stdout&&(process.stdin.pipe(i.stdin),i.stdout.pipe(process.stdout)),i.on(`exit`,e=>process.exit(e??0)),process.on(`SIGINT`,()=>i.kill(`SIGINT`)),process.on(`SIGTERM`,()=>i.kill(`SIGTERM`)),await new Promise(()=>{})}},{name:`init`,description:`Initialize AI Kit in the current directory`,usage:`aikit init [--workspace] [--smart] [--force] [--guide]`,run:async e=>{let t=e.includes(`--user`),n=e.includes(`--workspace`),r=e.includes(`--smart`),i=e.includes(`--guide`),a=e.includes(`--force`);if(t&&n&&(console.error(`Cannot use --user and --workspace together.`),process.exit(1)),i){let{guideProject:e}=await import(`./init-DCs4TWh6.js`);await e();return}if(r){let{initSmart:e}=await import(`./init-DCs4TWh6.js`);await e({force:a})}else if(t)await K({force:a});else if(n){let{initProject:e}=await import(`./init-DCs4TWh6.js`);await e({force:a})}else await K({force:a})}},{name:`check`,description:`Run incremental typecheck and lint`,usage:`aikit check [--cwd <dir>] [--files f1,f2] [--skip-types] [--skip-lint] [--detail efficient|normal|full]`,run:async e=>{let t=y(e,`--cwd`,``).trim()||void 0,n=y(e,`--files`,``),r=y(e,`--detail`,`full`)||`full`,i=n.split(`,`).map(e=>e.trim()).filter(Boolean),a=!1;e.includes(`--skip-types`)&&(e.splice(e.indexOf(`--skip-types`),1),a=!0);let o=!1;e.includes(`--skip-lint`)&&(e.splice(e.indexOf(`--skip-lint`),1),o=!0);let s=await ye({cwd:t,files:i.length>0?i:void 0,skipTypes:a,skipLint:o,detail:r});h(s),s.passed||(process.exitCode=1)}},{name:`health`,description:`Run project health checks on the current directory`,usage:`aikit health [path]`,run:async e=>{let t=Be(e.shift());console.log(`Project Health: ${t.path}`),console.log(`─`.repeat(50));for(let e of t.checks){let t=e.status===`pass`?`+`:e.status===`warn`?`~`:`X`;console.log(` [${t}] ${e.name}: ${e.message}`)}console.log(`─`.repeat(50)),console.log(`Score: ${t.score}% — ${t.summary}`)}},{name:`prune`,description:`Clean up orphaned storage, legacy data, and stale partitions`,usage:`aikit prune [--dry-run] [--max-age-days=90] [--force]`,run:async e=>{let{prune:t,formatBytes:n,markPruneRun:r}=await import(`../../tools/dist/index.js`),i=e.includes(`--dry-run`),a=e.includes(`--force`),o=e.find(e=>e.startsWith(`--max-age-days=`)),s=o?Number.parseInt(o.split(`=`)[1]??``,10):90;if(!i&&!a){console.log(`⚠️ This will permanently delete data. Use --dry-run to preview, or --force to execute.`);return}console.log(i?`🔍 Dry run — no files will be deleted
17
17
  `:`🧹 Pruning storage...
18
18
  `);let c=await t({dryRun:i,maxAgeDays:s});console.log(`Results:`),console.log(` Forge-ground orphans: ${c.forgeGroundOrphans.count} dirs (${n(c.forgeGroundOrphans.bytesFreed)})`),console.log(` Legacy LanceDB: ${c.legacyLance.count} dirs (${n(c.legacyLance.bytesFreed)})`),console.log(` Empty ephemeral dirs: ${c.emptyEphemeral.count} dirs`),console.log(` Stale partitions: ${c.stalePartitions.count} dirs (${n(c.stalePartitions.bytesFreed)})`),console.log(` Browser profiles: ${c.browserProfiles.count} dirs (${n(c.browserProfiles.bytesFreed)})`),console.log(`\n Total freed: ${n(c.totalBytesFreed)}`),i||(r(),console.log(`
19
19
  ✅ Cleanup complete.`))}},{name:`audit`,description:`Run a unified project audit (structure, deps, patterns, health, dead symbols, check)`,usage:`aikit audit [path] [--checks structure,dependencies,patterns,health,dead_symbols,check,entry_points] [--detail efficient|normal|full]`,run:async e=>{let{store:t,embedder:n}=await Q(),r=y(e,`--detail`,`efficient`)||`efficient`,i=y(e,`--checks`,``),a=i?i.split(`,`).map(e=>e.trim()):void 0,o=await ve(t,n,{path:e.shift()||`.`,checks:a,detail:r});if(o.ok){if(console.log(o.summary),o.next&&o.next.length>0){console.log(`
20
- Suggested next steps:`);for(let e of o.next)console.log(` → ${e.tool}: ${e.reason}`)}}else console.error(o.error?.message??`Audit failed`),process.exitCode=1}},{name:`guide`,description:`Tool discovery — recommend AI Kit tools for a given goal`,usage:`aikit guide <goal> [--max N]`,run:async e=>{let t=e.indexOf(`--max`),n=5;t!==-1&&t+1<e.length&&(n=Number.parseInt(e.splice(t,2)[1],10)||5);let r=e.join(` `).trim();r||(console.error(`Usage: aikit guide <goal> [--max N]`),console.error(`Example: aikit guide "audit this project"`),process.exit(1));let i=ze(r,n);console.log(`Workflow: ${i.workflow}`),console.log(` ${i.description}\n`),console.log(`Recommended tools:`);for(let e of i.tools){let t=e.suggestedArgs?` ${JSON.stringify(e.suggestedArgs)}`:``;console.log(` ${e.order}. ${e.tool} — ${e.reason}${t}`)}i.alternativeWorkflows.length>0&&console.log(`\nAlternatives: ${i.alternativeWorkflows.join(`, `)}`)}},{name:`replay`,description:`Show recent tool invocation audit trail`,usage:`aikit replay [--last N] [--tool <name>] [--source mcp|cli]`,run:async e=>{let t=ft({last:Number.parseInt(e[e.indexOf(`--last`)+1],10)||20,tool:e.includes(`--tool`)?e[e.indexOf(`--tool`)+1]:void 0,source:e.includes(`--source`)?e[e.indexOf(`--source`)+1]:void 0});if(t.length===0){console.log(`No replay entries. Activity is logged when tools are invoked.`);return}console.log(`Replay Log (${t.length} entries)\n`);for(let e of t){let t=e.ts.split(`T`)[1]?.split(`.`)[0]??e.ts,n=e.status===`ok`?`✓`:`✗`;console.log(`${t} ${n} ${e.tool} (${e.durationMs}ms) [${e.source}]`),console.log(` in: ${e.input}`),console.log(` out: ${e.output}`)}pt().catch(()=>{})}},{name:`replay-clear`,description:`Clear the replay audit trail`,run:async()=>{dt(),console.log(`Replay log cleared.`)}},{name:`dashboard`,description:`Launch web dashboard for knowledge graph visualization`,usage:`aikit dashboard [--port <port>] [--no-open]`,run:async e=>{let t=e.indexOf(`--port`),n=t!==-1&&e[t+1]?Number.parseInt(e[t+1],10):3210,r=Number.isFinite(n)?n:3210,i=e.includes(`--no-open`);console.log(`Starting AI Kit server on port ${r}...`);let{spawn:a}=await import(`node:child_process`),{platform:o}=await import(`node:os`),s=S(),c=a(process.execPath,[s,`--transport`,`http`,`--port`,String(r)],{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env,AIKIT_TRANSPORT:`http`,AIKIT_PORT:String(r)}}),l=`http://localhost:${r}/_dashboard/`,u=`http://localhost:${r}/health`,d=!1;for(let e=0;e<30;e+=1){try{if((await fetch(u)).ok){d=!0;break}}catch{}await new Promise(e=>setTimeout(e,1e3))}if(d||(console.error(`Server failed to start within 30 seconds.`),c.kill(),process.exit(1)),console.log(`AI Kit Dashboard: ${l}`),console.log(`Press Ctrl+C to stop.`),!i){let e=o();e===`win32`?a(`cmd`,[`/c`,`start`,``,l],{stdio:`ignore`,detached:!0}).unref():a(e===`darwin`?`open`:`xdg-open`,[l],{stdio:`ignore`,detached:!0}).unref()}let f=()=>{c.kill(),process.exit(0)};process.on(`SIGINT`,f),process.on(`SIGTERM`,f),await new Promise(e=>{c.on(`exit`,()=>e())})}},{name:`settings`,description:`Launch web UI to manage AI Kit configuration and environment variables`,usage:`aikit settings [--port <port>] [--no-open]`,run:async e=>{let t=e.indexOf(`--port`),n=t!==-1&&e[t+1]?Number.parseInt(e[t+1],10):3210,r=Number.isFinite(n)?n:3210,i=e.includes(`--no-open`);console.log(`Starting AI Kit server on port ${r}...`);let{spawn:a}=await import(`node:child_process`),{platform:o}=await import(`node:os`),s=S(),c=a(process.execPath,[s,`--transport`,`http`,`--port`,String(r)],{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env,AIKIT_TRANSPORT:`http`,AIKIT_PORT:String(r)}}),l=`http://localhost:${r}/settings/`,u=`http://localhost:${r}/health`,d=!1;for(let e=0;e<30;e+=1){try{if((await fetch(u)).ok){d=!0;break}}catch{}await new Promise(e=>setTimeout(e,1e3))}if(d||(console.error(`Server failed to start within 30 seconds.`),c.kill(),process.exit(1)),console.log(`AI Kit Settings: ${l}`),console.log(`Press Ctrl+C to stop.`),!i){let e=o();e===`win32`?a(`cmd`,[`/c`,`start`,``,l],{stdio:`ignore`,detached:!0}).unref():a(e===`darwin`?`open`:`xdg-open`,[l],{stdio:`ignore`,detached:!0}).unref()}let f=()=>{c.kill(),process.exit(0)};process.on(`SIGINT`,f),process.on(`SIGTERM`,f),await new Promise(e=>{c.on(`exit`,()=>e())})}}],ar=[{name:`upgrade`,description:`Upgrade AI Kit agents, prompts, and skills to the latest version (user-level and workspace-level)`,usage:`aikit upgrade`,run:async()=>{await K({force:!0});let e=process.cwd();if(k(L(e,`.github`,`.aikit-scaffold.json`))){let{initScaffoldOnly:e}=await import(`./init-o6szsZIP.js`);await e({force:!0})}if(k(L(e,`.github`,`skills`))){let{smartCopySkills:t}=await import(`./scaffold-BnhmnBfn.js`).then(e=>e.a),n=ae(),r=T();await t(e,n,[...ie],r,!0);let{smartCopyFlows:i}=await import(`./scaffold-BnhmnBfn.js`).then(e=>e.a);await i(e,n,[...oe],r,!0)}let{homedir:t}=await import(`node:os`),{rmSync:n}=await import(`node:fs`),r=F(t(),`.aikit`,`cache`,`wasm`);if(k(r))try{n(r,{recursive:!0,force:!0}),console.log(`✓ WASM cache cleared (will re-resolve on next start)`)}catch{console.warn(`⚠ Could not clear WASM cache at`,r)}}}],or=[{name:`workset`,description:`Manage saved file sets`,usage:`aikit workset <action> [name] [--files f1,f2] [--description desc]`,run:async e=>{let t=e.shift()?.trim(),n=f(y(e,`--files`,``)),r=y(e,`--description`,``).trim()||void 0,i=e.shift()?.trim();switch(t||(console.error(`Usage: aikit workset <action> [name] [--files f1,f2] [--description desc]`),console.error(`Actions: save, get, list, delete, add, remove`),process.exit(1)),t){case`save`:{(!i||n.length===0)&&(console.error(`Usage: aikit workset save <name> --files f1,f2 [--description desc]`),process.exit(1));let e=mt(i,n,{description:r});console.log(`Saved workset: ${e.name}`),C(e);return}case`get`:{i||(console.error(`Usage: aikit workset get <name>`),process.exit(1));let e=Ie(i);if(!e){console.log(`No workset found: ${i}`);return}C(e);return}case`list`:{let e=qe();if(e.length===0){console.log(`No worksets saved.`);return}console.log(`Worksets (${e.length})`),console.log(`─`.repeat(60));for(let t of e)C(t),console.log(``);return}case`delete`:{i||(console.error(`Usage: aikit workset delete <name>`),process.exit(1));let e=ke(i);console.log(e?`Deleted workset: ${i}`:`No workset found: ${i}`);return}case`add`:{(!i||n.length===0)&&(console.error(`Usage: aikit workset add <name> --files f1,f2`),process.exit(1));let e=_e(i,n);console.log(`Updated workset: ${e.name}`),C(e);return}case`remove`:{(!i||n.length===0)&&(console.error(`Usage: aikit workset remove <name> --files f1,f2`),process.exit(1));let e=lt(i,n);if(!e){console.log(`No workset found: ${i}`);return}console.log(`Updated workset: ${e.name}`),C(e);return}default:console.error(`Unknown workset action: ${t}`),console.error(`Actions: save, get, list, delete, add, remove`),process.exit(1)}}},{name:`stash`,description:`Persist and retrieve named intermediate values`,usage:`aikit stash <set|get|list|delete|clear> [key] [value]`,run:async e=>{let t=e.shift()?.trim(),n=e.shift()?.trim();t||(console.error(`Usage: aikit stash <set|get|list|delete|clear> [key] [value]`),process.exit(1));let r=await v();switch(t){case`set`:{n||(console.error(`Usage: aikit stash set <key> <value>`),process.exit(1));let t=e.join(` `),i=t.trim()?``:await s(),a=bt(r,n,ne(t||i));console.log(`Stored stash entry: ${a.key}`),console.log(` Type: ${a.type}`),console.log(` Stored: ${a.storedAt}`);return}case`get`:{n||(console.error(`Usage: aikit stash get <key>`),process.exit(1));let e=vt(r,n);if(!e){console.log(`No stash entry found: ${n}`);return}console.log(JSON.stringify(e,null,2));return}case`list`:{let e=yt(r);if(e.length===0){console.log(`No stash entries saved.`);return}console.log(`Stash entries (${e.length})`),console.log(`─`.repeat(60));for(let t of e)console.log(`${t.key} (${t.type})`),console.log(` Stored: ${t.storedAt}`);return}case`delete`:{n||(console.error(`Usage: aikit stash delete <key>`),process.exit(1));let e=_t(r,n);console.log(e?`Deleted stash entry: ${n}`:`No stash entry found: ${n}`);return}case`clear`:{let e=gt(r);console.log(`Cleared ${e} stash entr${e===1?`y`:`ies`}.`);return}default:console.error(`Unknown stash action: ${t}`),console.error(`Actions: set, get, list, delete, clear`),process.exit(1)}}},{name:`lane`,description:`Manage verified lanes — isolated file copies for parallel exploration`,usage:`aikit lane <create|list|status|diff|merge|discard> [name] [--files f1,f2]`,run:async e=>{let t=e.shift();if((!t||![`create`,`list`,`status`,`diff`,`merge`,`discard`].includes(t))&&(console.error(`Usage: aikit lane <create|list|status|diff|merge|discard> [name] [--files f1,f2]`),process.exit(1)),t===`list`){let e=We();if(e.length===0){console.log(`No active lanes.`);return}for(let t of e)console.log(`${t.name} (${t.sourceFiles.length} files, created ${t.createdAt})`);return}let n=e.shift();switch(n||(console.error(`Lane name is required for "${t}".`),process.exit(1)),t){case`create`:{let t=y(e,`--files`,``);t||(console.error(`Usage: aikit lane create <name> --files file1.ts,file2.ts`),process.exit(1));let r=Ve(n,t.split(`,`).map(e=>e.trim()));console.log(`Lane "${r.name}" created with ${r.sourceFiles.length} files.`);break}case`status`:{let e=Ke(n);console.log(`Lane: ${e.name}`),console.log(`Modified: ${e.modified} | Added: ${e.added} | Deleted: ${e.deleted}`);for(let t of e.entries)console.log(` ${t.status.padEnd(10)} ${t.file}`);break}case`diff`:{let e=He(n);console.log(`Lane: ${e.name} — ${e.modified} modified, ${e.added} added, ${e.deleted} deleted`);for(let t of e.entries)t.diff&&(console.log(`\n--- ${t.file} (${t.status})`),console.log(t.diff));break}case`merge`:{let e=Ge(n);console.log(`Merged ${e.filesMerged} files from lane "${e.name}".`);for(let t of e.files)console.log(` ${t}`);break}case`discard`:{let e=Ue(n);console.log(e?`Lane "${n}" discarded.`:`Lane "${n}" not found.`);break}}}},{name:`queue`,description:`Manage task queues for sequential agent operations`,usage:`aikit queue <create|push|next|done|fail|get|list|clear|delete> [name] [args]`,run:async e=>{let t=e.shift();if((!t||![`create`,`push`,`next`,`done`,`fail`,`get`,`list`,`clear`,`delete`].includes(t))&&(console.error(`Usage: aikit queue <create|push|next|done|fail|get|list|clear|delete> [name] [args]`),process.exit(1)),t===`list`){let e=ot();if(e.length===0){console.log(`No queues.`);return}for(let t of e)console.log(`${t.name} pending:${t.pending} done:${t.done} failed:${t.failed} total:${t.total}`);return}let n=e.shift();switch(n||(console.error(`Queue name is required for "${t}".`),process.exit(1)),t){case`create`:{let e=tt(n);console.log(`Queue "${e.name}" created.`);break}case`push`:{let t=ct(n,e.join(` `)||`Untitled task`);console.log(`Pushed "${t.title}" (${t.id}) to queue "${n}".`);break}case`next`:{let e=st(n);console.log(e?`Next: ${e.title} (${e.id})`:`No pending items in queue "${n}".`);break}case`done`:{let t=e.shift();t||(console.error(`Usage: aikit queue done <name> <id>`),process.exit(1));let r=rt(n,t);console.log(`Marked "${r.item.title}" as done.`);break}case`fail`:{let t=e.shift(),r=e.join(` `)||`Unknown error`;t||(console.error(`Usage: aikit queue fail <name> <id> [error message]`),process.exit(1));let i=it(n,t,r);console.log(`Marked "${i.title}" as failed: ${r}`);break}case`get`:{let e=at(n);if(!e){console.log(`Queue "${n}" not found.`);return}console.log(`Queue: ${e.name} (${e.items.length} items)`);for(let t of e.items){let e=t.error?` — ${t.error}`:``;console.log(` ${t.status.padEnd(12)} ${t.id} ${t.title}${e}`)}break}case`clear`:{let e=et(n);console.log(`Cleared ${e} completed/failed items from queue "${n}".`);break}case`delete`:{let e=nt(n);console.log(e?`Queue "${n}" deleted.`:`Queue "${n}" not found.`);break}}}}],$=[...rr,...nr,...Gt,...tr,...ir,...Gn,...Kt,...or,...Wn,...ar,...$n,...Un];$.push({name:`help`,description:`Show available commands`,run:async()=>{cr()}});async function sr(e){let t=[...e],n=t.shift();if(!n||n===`--help`||n===`-h`){cr();return}if(n===`--version`||n===`-v`){let e=L(P(ge(import.meta.url)),`..`,`..`,`..`,`package.json`),t=JSON.parse(j(e,`utf-8`));console.log(t.version);return}if(n&&new Set([`--user`,`--workspace`,`--guide`,`--smart`]).has(n)){let e=$.find(e=>e.name===`init`);if(e){await e.run([n,...t]);return}}let r=$.find(e=>e.name===n);r||(console.error(`Unknown command: ${n}`),cr(),process.exit(1));try{await r.run(t)}finally{let e=er();e&&await e.store.close()}}function cr(){console.log(`@vpxa/aikit — Local-first AI developer toolkit
20
+ Suggested next steps:`);for(let e of o.next)console.log(` → ${e.tool}: ${e.reason}`)}}else console.error(o.error?.message??`Audit failed`),process.exitCode=1}},{name:`guide`,description:`Tool discovery — recommend AI Kit tools for a given goal`,usage:`aikit guide <goal> [--max N]`,run:async e=>{let t=e.indexOf(`--max`),n=5;t!==-1&&t+1<e.length&&(n=Number.parseInt(e.splice(t,2)[1],10)||5);let r=e.join(` `).trim();r||(console.error(`Usage: aikit guide <goal> [--max N]`),console.error(`Example: aikit guide "audit this project"`),process.exit(1));let i=ze(r,n);console.log(`Workflow: ${i.workflow}`),console.log(` ${i.description}\n`),console.log(`Recommended tools:`);for(let e of i.tools){let t=e.suggestedArgs?` ${JSON.stringify(e.suggestedArgs)}`:``;console.log(` ${e.order}. ${e.tool} — ${e.reason}${t}`)}i.alternativeWorkflows.length>0&&console.log(`\nAlternatives: ${i.alternativeWorkflows.join(`, `)}`)}},{name:`replay`,description:`Show recent tool invocation audit trail`,usage:`aikit replay [--last N] [--tool <name>] [--source mcp|cli]`,run:async e=>{let t=ft({last:Number.parseInt(e[e.indexOf(`--last`)+1],10)||20,tool:e.includes(`--tool`)?e[e.indexOf(`--tool`)+1]:void 0,source:e.includes(`--source`)?e[e.indexOf(`--source`)+1]:void 0});if(t.length===0){console.log(`No replay entries. Activity is logged when tools are invoked.`);return}console.log(`Replay Log (${t.length} entries)\n`);for(let e of t){let t=e.ts.split(`T`)[1]?.split(`.`)[0]??e.ts,n=e.status===`ok`?`✓`:`✗`;console.log(`${t} ${n} ${e.tool} (${e.durationMs}ms) [${e.source}]`),console.log(` in: ${e.input}`),console.log(` out: ${e.output}`)}pt().catch(()=>{})}},{name:`replay-clear`,description:`Clear the replay audit trail`,run:async()=>{dt(),console.log(`Replay log cleared.`)}},{name:`dashboard`,description:`Launch web dashboard for knowledge graph visualization`,usage:`aikit dashboard [--port <port>] [--no-open]`,run:async e=>{let t=e.indexOf(`--port`),n=t!==-1&&e[t+1]?Number.parseInt(e[t+1],10):3210,r=Number.isFinite(n)?n:3210,i=e.includes(`--no-open`);console.log(`Starting AI Kit server on port ${r}...`);let{spawn:a}=await import(`node:child_process`),{platform:o}=await import(`node:os`),s=S(),c=a(process.execPath,[s,`--transport`,`http`,`--port`,String(r)],{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env,AIKIT_TRANSPORT:`http`,AIKIT_PORT:String(r)}}),l=`http://localhost:${r}/_dashboard/`,u=`http://localhost:${r}/health`,d=!1;for(let e=0;e<30;e+=1){try{if((await fetch(u)).ok){d=!0;break}}catch{}await new Promise(e=>setTimeout(e,1e3))}if(d||(console.error(`Server failed to start within 30 seconds.`),c.kill(),process.exit(1)),console.log(`AI Kit Dashboard: ${l}`),console.log(`Press Ctrl+C to stop.`),!i){let e=o();e===`win32`?a(`cmd`,[`/c`,`start`,``,l],{stdio:`ignore`,detached:!0}).unref():a(e===`darwin`?`open`:`xdg-open`,[l],{stdio:`ignore`,detached:!0}).unref()}let f=()=>{c.kill(),process.exit(0)};process.on(`SIGINT`,f),process.on(`SIGTERM`,f),await new Promise(e=>{c.on(`exit`,()=>e())})}},{name:`settings`,description:`Launch web UI to manage AI Kit configuration and environment variables`,usage:`aikit settings [--port <port>] [--no-open]`,run:async e=>{let t=e.indexOf(`--port`),n=t!==-1&&e[t+1]?Number.parseInt(e[t+1],10):3210,r=Number.isFinite(n)?n:3210,i=e.includes(`--no-open`);console.log(`Starting AI Kit server on port ${r}...`);let{spawn:a}=await import(`node:child_process`),{platform:o}=await import(`node:os`),s=S(),c=a(process.execPath,[s,`--transport`,`http`,`--port`,String(r)],{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env,AIKIT_TRANSPORT:`http`,AIKIT_PORT:String(r)}}),l=`http://localhost:${r}/settings/`,u=`http://localhost:${r}/health`,d=!1;for(let e=0;e<30;e+=1){try{if((await fetch(u)).ok){d=!0;break}}catch{}await new Promise(e=>setTimeout(e,1e3))}if(d||(console.error(`Server failed to start within 30 seconds.`),c.kill(),process.exit(1)),console.log(`AI Kit Settings: ${l}`),console.log(`Press Ctrl+C to stop.`),!i){let e=o();e===`win32`?a(`cmd`,[`/c`,`start`,``,l],{stdio:`ignore`,detached:!0}).unref():a(e===`darwin`?`open`:`xdg-open`,[l],{stdio:`ignore`,detached:!0}).unref()}let f=()=>{c.kill(),process.exit(0)};process.on(`SIGINT`,f),process.on(`SIGTERM`,f),await new Promise(e=>{c.on(`exit`,()=>e())})}}],ar=[{name:`upgrade`,description:`Upgrade AI Kit agents, prompts, and skills to the latest version (user-level and workspace-level)`,usage:`aikit upgrade`,run:async()=>{await K({force:!0});let e=process.cwd();if(k(L(e,`.github`,`.aikit-scaffold.json`))){let{initScaffoldOnly:e}=await import(`./init-DCs4TWh6.js`);await e({force:!0})}if(k(L(e,`.github`,`skills`))){let{smartCopySkills:t}=await import(`./scaffold-BnhmnBfn.js`).then(e=>e.a),n=ae(),r=T();await t(e,n,[...ie],r,!0);let{smartCopyFlows:i}=await import(`./scaffold-BnhmnBfn.js`).then(e=>e.a);await i(e,n,[...oe],r,!0)}let{homedir:t}=await import(`node:os`),{rmSync:n}=await import(`node:fs`),r=F(t(),`.aikit`,`cache`,`wasm`);if(k(r))try{n(r,{recursive:!0,force:!0}),console.log(`✓ WASM cache cleared (will re-resolve on next start)`)}catch{console.warn(`⚠ Could not clear WASM cache at`,r)}}}],or=[{name:`workset`,description:`Manage saved file sets`,usage:`aikit workset <action> [name] [--files f1,f2] [--description desc]`,run:async e=>{let t=e.shift()?.trim(),n=f(y(e,`--files`,``)),r=y(e,`--description`,``).trim()||void 0,i=e.shift()?.trim();switch(t||(console.error(`Usage: aikit workset <action> [name] [--files f1,f2] [--description desc]`),console.error(`Actions: save, get, list, delete, add, remove`),process.exit(1)),t){case`save`:{(!i||n.length===0)&&(console.error(`Usage: aikit workset save <name> --files f1,f2 [--description desc]`),process.exit(1));let e=mt(i,n,{description:r});console.log(`Saved workset: ${e.name}`),C(e);return}case`get`:{i||(console.error(`Usage: aikit workset get <name>`),process.exit(1));let e=Ie(i);if(!e){console.log(`No workset found: ${i}`);return}C(e);return}case`list`:{let e=qe();if(e.length===0){console.log(`No worksets saved.`);return}console.log(`Worksets (${e.length})`),console.log(`─`.repeat(60));for(let t of e)C(t),console.log(``);return}case`delete`:{i||(console.error(`Usage: aikit workset delete <name>`),process.exit(1));let e=ke(i);console.log(e?`Deleted workset: ${i}`:`No workset found: ${i}`);return}case`add`:{(!i||n.length===0)&&(console.error(`Usage: aikit workset add <name> --files f1,f2`),process.exit(1));let e=_e(i,n);console.log(`Updated workset: ${e.name}`),C(e);return}case`remove`:{(!i||n.length===0)&&(console.error(`Usage: aikit workset remove <name> --files f1,f2`),process.exit(1));let e=lt(i,n);if(!e){console.log(`No workset found: ${i}`);return}console.log(`Updated workset: ${e.name}`),C(e);return}default:console.error(`Unknown workset action: ${t}`),console.error(`Actions: save, get, list, delete, add, remove`),process.exit(1)}}},{name:`stash`,description:`Persist and retrieve named intermediate values`,usage:`aikit stash <set|get|list|delete|clear> [key] [value]`,run:async e=>{let t=e.shift()?.trim(),n=e.shift()?.trim();t||(console.error(`Usage: aikit stash <set|get|list|delete|clear> [key] [value]`),process.exit(1));let r=await v();switch(t){case`set`:{n||(console.error(`Usage: aikit stash set <key> <value>`),process.exit(1));let t=e.join(` `),i=t.trim()?``:await s(),a=bt(r,n,ne(t||i));console.log(`Stored stash entry: ${a.key}`),console.log(` Type: ${a.type}`),console.log(` Stored: ${a.storedAt}`);return}case`get`:{n||(console.error(`Usage: aikit stash get <key>`),process.exit(1));let e=vt(r,n);if(!e){console.log(`No stash entry found: ${n}`);return}console.log(JSON.stringify(e,null,2));return}case`list`:{let e=yt(r);if(e.length===0){console.log(`No stash entries saved.`);return}console.log(`Stash entries (${e.length})`),console.log(`─`.repeat(60));for(let t of e)console.log(`${t.key} (${t.type})`),console.log(` Stored: ${t.storedAt}`);return}case`delete`:{n||(console.error(`Usage: aikit stash delete <key>`),process.exit(1));let e=_t(r,n);console.log(e?`Deleted stash entry: ${n}`:`No stash entry found: ${n}`);return}case`clear`:{let e=gt(r);console.log(`Cleared ${e} stash entr${e===1?`y`:`ies`}.`);return}default:console.error(`Unknown stash action: ${t}`),console.error(`Actions: set, get, list, delete, clear`),process.exit(1)}}},{name:`lane`,description:`Manage verified lanes — isolated file copies for parallel exploration`,usage:`aikit lane <create|list|status|diff|merge|discard> [name] [--files f1,f2]`,run:async e=>{let t=e.shift();if((!t||![`create`,`list`,`status`,`diff`,`merge`,`discard`].includes(t))&&(console.error(`Usage: aikit lane <create|list|status|diff|merge|discard> [name] [--files f1,f2]`),process.exit(1)),t===`list`){let e=We();if(e.length===0){console.log(`No active lanes.`);return}for(let t of e)console.log(`${t.name} (${t.sourceFiles.length} files, created ${t.createdAt})`);return}let n=e.shift();switch(n||(console.error(`Lane name is required for "${t}".`),process.exit(1)),t){case`create`:{let t=y(e,`--files`,``);t||(console.error(`Usage: aikit lane create <name> --files file1.ts,file2.ts`),process.exit(1));let r=Ve(n,t.split(`,`).map(e=>e.trim()));console.log(`Lane "${r.name}" created with ${r.sourceFiles.length} files.`);break}case`status`:{let e=Ke(n);console.log(`Lane: ${e.name}`),console.log(`Modified: ${e.modified} | Added: ${e.added} | Deleted: ${e.deleted}`);for(let t of e.entries)console.log(` ${t.status.padEnd(10)} ${t.file}`);break}case`diff`:{let e=He(n);console.log(`Lane: ${e.name} — ${e.modified} modified, ${e.added} added, ${e.deleted} deleted`);for(let t of e.entries)t.diff&&(console.log(`\n--- ${t.file} (${t.status})`),console.log(t.diff));break}case`merge`:{let e=Ge(n);console.log(`Merged ${e.filesMerged} files from lane "${e.name}".`);for(let t of e.files)console.log(` ${t}`);break}case`discard`:{let e=Ue(n);console.log(e?`Lane "${n}" discarded.`:`Lane "${n}" not found.`);break}}}},{name:`queue`,description:`Manage task queues for sequential agent operations`,usage:`aikit queue <create|push|next|done|fail|get|list|clear|delete> [name] [args]`,run:async e=>{let t=e.shift();if((!t||![`create`,`push`,`next`,`done`,`fail`,`get`,`list`,`clear`,`delete`].includes(t))&&(console.error(`Usage: aikit queue <create|push|next|done|fail|get|list|clear|delete> [name] [args]`),process.exit(1)),t===`list`){let e=ot();if(e.length===0){console.log(`No queues.`);return}for(let t of e)console.log(`${t.name} pending:${t.pending} done:${t.done} failed:${t.failed} total:${t.total}`);return}let n=e.shift();switch(n||(console.error(`Queue name is required for "${t}".`),process.exit(1)),t){case`create`:{let e=tt(n);console.log(`Queue "${e.name}" created.`);break}case`push`:{let t=ct(n,e.join(` `)||`Untitled task`);console.log(`Pushed "${t.title}" (${t.id}) to queue "${n}".`);break}case`next`:{let e=st(n);console.log(e?`Next: ${e.title} (${e.id})`:`No pending items in queue "${n}".`);break}case`done`:{let t=e.shift();t||(console.error(`Usage: aikit queue done <name> <id>`),process.exit(1));let r=rt(n,t);console.log(`Marked "${r.item.title}" as done.`);break}case`fail`:{let t=e.shift(),r=e.join(` `)||`Unknown error`;t||(console.error(`Usage: aikit queue fail <name> <id> [error message]`),process.exit(1));let i=it(n,t,r);console.log(`Marked "${i.title}" as failed: ${r}`);break}case`get`:{let e=at(n);if(!e){console.log(`Queue "${n}" not found.`);return}console.log(`Queue: ${e.name} (${e.items.length} items)`);for(let t of e.items){let e=t.error?` — ${t.error}`:``;console.log(` ${t.status.padEnd(12)} ${t.id} ${t.title}${e}`)}break}case`clear`:{let e=et(n);console.log(`Cleared ${e} completed/failed items from queue "${n}".`);break}case`delete`:{let e=nt(n);console.log(e?`Queue "${n}" deleted.`:`Queue "${n}" not found.`);break}}}}],$=[...rr,...nr,...Gt,...tr,...ir,...Gn,...Kt,...or,...Wn,...ar,...$n,...Un];$.push({name:`help`,description:`Show available commands`,run:async()=>{cr()}});async function sr(e){let t=[...e],n=t.shift();if(!n||n===`--help`||n===`-h`){cr();return}if(n===`--version`||n===`-v`){let e=L(P(ge(import.meta.url)),`..`,`..`,`..`,`package.json`),t=JSON.parse(j(e,`utf-8`));console.log(t.version);return}if(n&&new Set([`--user`,`--workspace`,`--guide`,`--smart`]).has(n)){let e=$.find(e=>e.name===`init`);if(e){await e.run([n,...t]);return}}let r=$.find(e=>e.name===n);r||(console.error(`Unknown command: ${n}`),cr(),process.exit(1));try{await r.run(t)}finally{let e=er();e&&await e.store.close()}}function cr(){console.log(`@vpxa/aikit — Local-first AI developer toolkit
21
21
  `),console.log(`Usage: aikit <command> [options]
22
22
  `),console.log(`Commands:`);let e=Math.max(...$.map(e=>e.name.length));for(let t of $)console.log(` ${t.name.padEnd(e+2)}${t.description}`);console.log(``),console.log(`Options:`),console.log(` --help, -h Show this help`),console.log(` --version, -v Show version`)}export{sr as run};
@@ -1,4 +1,4 @@
1
- import{c as e,l as t,n,o as r,r as i,t as a}from"./scaffold-BnhmnBfn.js";import{a as o,i as s,n as c,o as l,p as u,r as d,t as f}from"./templates-guQ2153Z.js";import{appendFileSync as p,existsSync as m,mkdirSync as h,readFileSync as g,unlinkSync as _,writeFileSync as v}from"node:fs";import{basename as y,resolve as b}from"node:path";import{AIKIT_PATHS as x,EMBEDDING_DEFAULTS as S,isUserInstalled as C}from"../../core/dist/index.js";function w(e){return m(b(e,`.cursor`))?`cursor`:m(b(e,`.claude`))?`claude-code`:m(b(e,`.windsurf`))?`windsurf`:m(b(e,`.zed`))?`zed`:m(b(e,`.idea`))?`intellij`:`copilot`}function T(e){let t=[];return m(b(e,`.cursor`))&&t.push(`cursor`),(m(b(e,`.claude`))||m(b(e,`CLAUDE.md`)))&&t.push(`claude-code`),m(b(e,`.windsurf`))&&t.push(`windsurf`),m(b(e,`.zed`))&&t.push(`zed`),m(b(e,`.idea`))&&t.push(`intellij`),m(b(e,`.gemini`))&&t.push(`gemini-cli`),(m(b(e,`.codex`))||m(b(e,`codex.md`)))&&t.push(`codex-cli`),t.push(`copilot`),[...new Set(t)]}function E(e){return{servers:{[e]:{...s}}}}function D(e){let{type:t,...n}=s;return{mcpServers:{[e]:n}}}function O(e){let{type:t,...n}=s;return{context_servers:{[e]:{...n}}}}const k={scaffoldDir:`general`,writeMcpConfig(e,t){let n=b(e,`.vscode`),r=b(n,`mcp.json`);m(r)||(h(n,{recursive:!0}),v(r,`${JSON.stringify(E(t),null,2)}\n`,`utf-8`),console.log(` Created .vscode/mcp.json`))},writeInstructions(e,t){let n=b(e,`.github`),r=b(n,`copilot-instructions.md`);h(n,{recursive:!0}),v(r,c(y(e),t),`utf-8`),console.log(` Updated .github/copilot-instructions.md`)},writeAgentsMd(e,t){v(b(e,`AGENTS.md`),f(y(e),t),`utf-8`),console.log(` Updated AGENTS.md`)}},A={scaffoldDir:`general`,writeMcpConfig(e,t){let n=b(e,`.mcp.json`);m(n)||(v(n,`${JSON.stringify(D(t),null,2)}\n`,`utf-8`),console.log(` Created .mcp.json`))},writeInstructions(e,t){let n=b(e,`CLAUDE.md`),r=y(e);v(n,`${c(r,t)}\n---\n\n${f(r,t)}`,`utf-8`),console.log(` Updated CLAUDE.md`)},writeAgentsMd(e,t){}},j={scaffoldDir:`general`,writeMcpConfig(e,t){let n=b(e,`.cursor`),r=b(n,`mcp.json`);m(r)||(h(n,{recursive:!0}),v(r,`${JSON.stringify(D(t),null,2)}\n`,`utf-8`),console.log(` Created .cursor/mcp.json`))},writeInstructions(e,t){let n=b(e,`.cursor`,`rules`),r=b(n,`aikit.mdc`);h(n,{recursive:!0});let i=y(e);v(r,`${c(i,t)}\n---\n\n${f(i,t)}`,`utf-8`),console.log(` Updated .cursor/rules/aikit.mdc`);let a=b(n,`kb.mdc`);m(a)&&a!==r&&(_(a),console.log(` Removed legacy .cursor/rules/kb.mdc`))},writeAgentsMd(e,t){}},M={scaffoldDir:`general`,writeMcpConfig(e,t){let n=b(e,`.vscode`),r=b(n,`mcp.json`);m(r)||(h(n,{recursive:!0}),v(r,`${JSON.stringify(E(t),null,2)}\n`,`utf-8`),console.log(` Created .vscode/mcp.json (Windsurf-compatible)`))},writeInstructions(e,t){let n=b(e,`.windsurfrules`),r=y(e);v(n,`${c(r,t)}\n---\n\n${f(r,t)}`,`utf-8`),console.log(` Updated .windsurfrules`)},writeAgentsMd(e,t){}},N={scaffoldDir:`general`,writeMcpConfig(e,t){let n=b(e,`.zed`),r=b(n,`settings.json`);if(h(n,{recursive:!0}),!m(r))v(r,`${JSON.stringify(O(t),null,2)}\n`,`utf-8`),console.log(` Created .zed/settings.json`);else{let e;try{e=JSON.parse(g(r,`utf-8`))}catch{console.warn(` ⚠ .zed/settings.json contains invalid JSON — skipping MCP config merge`);return}e.context_servers?.[t]||(e.context_servers={...e.context_servers,...O(t).context_servers},v(r,`${JSON.stringify(e,null,2)}\n`,`utf-8`),console.log(` Updated .zed/settings.json with context_servers`))}},writeInstructions(e,t){let n=b(e,`.rules`),r=y(e);v(n,`${c(r,t)}\n---\n\n${f(r,t)}`,`utf-8`),console.log(` Updated .rules`)},writeAgentsMd(e,t){}},P={scaffoldDir:`general`,writeMcpConfig(e,t){let n=b(e,`mcp.json`);m(n)||(v(n,`${JSON.stringify(D(t),null,2)}\n`,`utf-8`),console.log(` Created mcp.json`))},writeInstructions(e,t){let n=b(e,`.aiassistant`,`rules`),r=b(n,`aikit.md`);h(n,{recursive:!0});let i=y(e);v(r,`${c(i,t)}\n---\n\n${f(i,t)}`,`utf-8`),console.log(` Updated .aiassistant/rules/aikit.md`)},writeAgentsMd(e,t){}};function F(e){switch(e){case`copilot`:return k;case`claude-code`:return A;case`cursor`:return j;case`windsurf`:return M;case`zed`:return N;case`intellij`:return P;case`gemini-cli`:case`codex-cli`:return k}}const I={serverName:o,sources:[{path:`.`,excludePatterns:[`**/node_modules/**`,`**/dist/**`,`**/build/**`,`**/.git/**`,`**/${x.data}/**`,`**/coverage/**`,`**/*.min.js`,`**/package-lock.json`,`**/pnpm-lock.yaml`]}],indexing:{chunkSize:1500,chunkOverlap:200,minChunkSize:100},embedding:{model:S.model,dimensions:S.dimensions},store:{backend:`sqlite-vec`,path:x.data},curated:{path:x.aiCurated}};function L(e,t){let n=b(e,`aikit.config.json`);return m(n)&&!t?(console.log(`aikit.config.json already exists. Use --force to overwrite.`),!1):(v(n,`${JSON.stringify(I,null,2)}\n`,`utf-8`),console.log(` Created aikit.config.json`),!0)}function R(e){let t=b(e,`.gitignore`),n=[{dir:`${x.data}/`,label:`AI Kit vector store`},{dir:`${x.state}/`,label:`AI Kit session state`},{dir:`${x.restorePoints}/`,label:`Restore points (codemod/rename undo snapshots)`},{dir:`${x.brainstorm}/`,label:`Brainstorming sessions`},{dir:`${x.handoffs}/`,label:`Handoff documents`}];if(m(t)){let e=g(t,`utf-8`),r=n.filter(t=>!e.includes(t.dir));r.length>0&&(p(t,`\n${r.map(e=>`# ${e.label}\n${e.dir}`).join(`
1
+ import{c as e,l as t,n,o as r,r as i,t as a}from"./scaffold-BnhmnBfn.js";import{a as o,i as s,n as c,o as l,p as u,r as d,t as f}from"./templates-C92mODRl.js";import{appendFileSync as p,existsSync as m,mkdirSync as h,readFileSync as g,unlinkSync as _,writeFileSync as v}from"node:fs";import{basename as y,resolve as b}from"node:path";import{AIKIT_PATHS as x,EMBEDDING_DEFAULTS as S,isUserInstalled as C}from"../../core/dist/index.js";function w(e){return m(b(e,`.cursor`))?`cursor`:m(b(e,`.claude`))?`claude-code`:m(b(e,`.windsurf`))?`windsurf`:m(b(e,`.zed`))?`zed`:m(b(e,`.idea`))?`intellij`:`copilot`}function T(e){let t=[];return m(b(e,`.cursor`))&&t.push(`cursor`),(m(b(e,`.claude`))||m(b(e,`CLAUDE.md`)))&&t.push(`claude-code`),m(b(e,`.windsurf`))&&t.push(`windsurf`),m(b(e,`.zed`))&&t.push(`zed`),m(b(e,`.idea`))&&t.push(`intellij`),m(b(e,`.gemini`))&&t.push(`gemini-cli`),(m(b(e,`.codex`))||m(b(e,`codex.md`)))&&t.push(`codex-cli`),t.push(`copilot`),[...new Set(t)]}function E(e){return{servers:{[e]:{...s}}}}function D(e){let{type:t,...n}=s;return{mcpServers:{[e]:n}}}function O(e){let{type:t,...n}=s;return{context_servers:{[e]:{...n}}}}const k={scaffoldDir:`general`,writeMcpConfig(e,t){let n=b(e,`.vscode`),r=b(n,`mcp.json`);m(r)||(h(n,{recursive:!0}),v(r,`${JSON.stringify(E(t),null,2)}\n`,`utf-8`),console.log(` Created .vscode/mcp.json`))},writeInstructions(e,t){let n=b(e,`.github`),r=b(n,`copilot-instructions.md`);h(n,{recursive:!0}),v(r,c(y(e),t),`utf-8`),console.log(` Updated .github/copilot-instructions.md`)},writeAgentsMd(e,t){v(b(e,`AGENTS.md`),f(y(e),t),`utf-8`),console.log(` Updated AGENTS.md`)}},A={scaffoldDir:`general`,writeMcpConfig(e,t){let n=b(e,`.mcp.json`);m(n)||(v(n,`${JSON.stringify(D(t),null,2)}\n`,`utf-8`),console.log(` Created .mcp.json`))},writeInstructions(e,t){let n=b(e,`CLAUDE.md`),r=y(e);v(n,`${c(r,t)}\n---\n\n${f(r,t)}`,`utf-8`),console.log(` Updated CLAUDE.md`)},writeAgentsMd(e,t){}},j={scaffoldDir:`general`,writeMcpConfig(e,t){let n=b(e,`.cursor`),r=b(n,`mcp.json`);m(r)||(h(n,{recursive:!0}),v(r,`${JSON.stringify(D(t),null,2)}\n`,`utf-8`),console.log(` Created .cursor/mcp.json`))},writeInstructions(e,t){let n=b(e,`.cursor`,`rules`),r=b(n,`aikit.mdc`);h(n,{recursive:!0});let i=y(e);v(r,`${c(i,t)}\n---\n\n${f(i,t)}`,`utf-8`),console.log(` Updated .cursor/rules/aikit.mdc`);let a=b(n,`kb.mdc`);m(a)&&a!==r&&(_(a),console.log(` Removed legacy .cursor/rules/kb.mdc`))},writeAgentsMd(e,t){}},M={scaffoldDir:`general`,writeMcpConfig(e,t){let n=b(e,`.vscode`),r=b(n,`mcp.json`);m(r)||(h(n,{recursive:!0}),v(r,`${JSON.stringify(E(t),null,2)}\n`,`utf-8`),console.log(` Created .vscode/mcp.json (Windsurf-compatible)`))},writeInstructions(e,t){let n=b(e,`.windsurfrules`),r=y(e);v(n,`${c(r,t)}\n---\n\n${f(r,t)}`,`utf-8`),console.log(` Updated .windsurfrules`)},writeAgentsMd(e,t){}},N={scaffoldDir:`general`,writeMcpConfig(e,t){let n=b(e,`.zed`),r=b(n,`settings.json`);if(h(n,{recursive:!0}),!m(r))v(r,`${JSON.stringify(O(t),null,2)}\n`,`utf-8`),console.log(` Created .zed/settings.json`);else{let e;try{e=JSON.parse(g(r,`utf-8`))}catch{console.warn(` ⚠ .zed/settings.json contains invalid JSON — skipping MCP config merge`);return}e.context_servers?.[t]||(e.context_servers={...e.context_servers,...O(t).context_servers},v(r,`${JSON.stringify(e,null,2)}\n`,`utf-8`),console.log(` Updated .zed/settings.json with context_servers`))}},writeInstructions(e,t){let n=b(e,`.rules`),r=y(e);v(n,`${c(r,t)}\n---\n\n${f(r,t)}`,`utf-8`),console.log(` Updated .rules`)},writeAgentsMd(e,t){}},P={scaffoldDir:`general`,writeMcpConfig(e,t){let n=b(e,`mcp.json`);m(n)||(v(n,`${JSON.stringify(D(t),null,2)}\n`,`utf-8`),console.log(` Created mcp.json`))},writeInstructions(e,t){let n=b(e,`.aiassistant`,`rules`),r=b(n,`aikit.md`);h(n,{recursive:!0});let i=y(e);v(r,`${c(i,t)}\n---\n\n${f(i,t)}`,`utf-8`),console.log(` Updated .aiassistant/rules/aikit.md`)},writeAgentsMd(e,t){}};function F(e){switch(e){case`copilot`:return k;case`claude-code`:return A;case`cursor`:return j;case`windsurf`:return M;case`zed`:return N;case`intellij`:return P;case`gemini-cli`:case`codex-cli`:return k}}const I={serverName:o,sources:[{path:`.`,excludePatterns:[`**/node_modules/**`,`**/dist/**`,`**/build/**`,`**/.git/**`,`**/${x.data}/**`,`**/coverage/**`,`**/*.min.js`,`**/package-lock.json`,`**/pnpm-lock.yaml`]}],indexing:{chunkSize:1500,chunkOverlap:200,minChunkSize:100},embedding:{model:S.model,dimensions:S.dimensions},store:{backend:`sqlite-vec`,path:x.data},curated:{path:x.aiCurated}};function L(e,t){let n=b(e,`aikit.config.json`);return m(n)&&!t?(console.log(`aikit.config.json already exists. Use --force to overwrite.`),!1):(v(n,`${JSON.stringify(I,null,2)}\n`,`utf-8`),console.log(` Created aikit.config.json`),!0)}function R(e){let t=b(e,`.gitignore`),n=[{dir:`${x.data}/`,label:`AI Kit vector store`},{dir:`${x.state}/`,label:`AI Kit session state`},{dir:`${x.restorePoints}/`,label:`Restore points (codemod/rename undo snapshots)`},{dir:`${x.brainstorm}/`,label:`Brainstorming sessions`},{dir:`${x.handoffs}/`,label:`Handoff documents`}];if(m(t)){let e=g(t,`utf-8`),r=n.filter(t=>!e.includes(t.dir));r.length>0&&(p(t,`\n${r.map(e=>`# ${e.label}\n${e.dir}`).join(`
2
2
  `)}\n`,`utf-8`),console.log(` Added ${r.map(e=>e.dir).join(`, `)} to .gitignore`))}else v(t,`${n.map(e=>`# ${e.label}\n${e.dir}`).join(`
3
3
  `)}\n`,`utf-8`),console.log(` Created .gitignore with AI Kit entries`)}function z(){return I.serverName}const B=[`decisions`,`patterns`,`conventions`,`troubleshooting`];function V(e){let t=b(e,`.ai`,`curated`);m(t)||(h(t,{recursive:!0}),console.log(` Created .ai/curated/`));for(let e of B){let n=b(t,e);m(n)||h(n,{recursive:!0})}console.log(` Created .ai/curated/{${B.join(`,`)}}/`)}function H(e){switch(e){case`zed`:return`zed`;case`intellij`:return`intellij`;case`claude-code`:return`claude-code`;case`gemini-cli`:return`gemini`;case`codex-cli`:return`codex`;default:return`copilot`}}async function U(n){let i=process.cwd();if(!L(i,n.force))return;R(i);let a=z(),o=F(w(i));o.writeMcpConfig(i,a),o.writeInstructions(i,a),o.writeAgentsMd(i,a);let s=u(),c=JSON.parse(g(b(s,`package.json`),`utf-8`)).version;await t(i,s,[...l],c,n.force),await r(i,s,[...d],c,n.force);let f=T(i),p=new Set;for(let t of f){let r=H(t);p.has(r)||(p.add(r),await e(i,s,r,c,n.force))}V(i),console.log(`
4
4
  AI Kit initialized! Next steps:`),console.log(` aikit reindex Index your codebase`),console.log(` aikit search Search indexed content`),console.log(` aikit serve Start MCP server for IDE integration`),C()&&console.log(`
@@ -2,7 +2,7 @@ import{createRequire as e}from"node:module";import{readFileSync as t}from"node:f
2
2
  `))console.log(` ${e}`)}}function E(e){console.log(e.id),console.log(` Command: ${e.command}${e.args.length>0?` ${e.args.join(` `)}`:``}`),console.log(` PID: ${e.pid??`unknown`}`),console.log(` Status: ${e.status}`),console.log(` Started: ${e.startedAt}`),e.exitCode!==void 0&&console.log(` Exit code: ${e.exitCode}`),console.log(` Logs: ${e.logs.length}`)}function D(e){if(console.log(`Exports scanned: ${e.totalExports}`),console.log(`Dead in source: ${e.totalDeadSource} (actionable)`),console.log(`Dead in docs: ${e.totalDeadDocs} (informational)`),e.totalDeadSource===0&&e.totalDeadDocs===0){console.log(`No dead symbols found.`);return}if(e.deadInSource.length>0){console.log(`
3
3
  Dead in source (actionable):`);for(let t of e.deadInSource)console.log(` - ${t.path}:${t.line} ${t.kind} ${t.name}`)}if(e.deadInDocs.length>0){console.log(`
4
4
  Dead in docs (informational):`);for(let t of e.deadInDocs)console.log(` - ${t.path}:${t.line} ${t.kind} ${t.name}`)}}function O(e){console.log(e.path),console.log(` Language: ${e.language}`),console.log(` Lines: ${e.lines}`),console.log(` Estimated tokens: ~${e.estimatedTokens}`),console.log(``),M(`Imports`,e.imports),M(`Exports`,e.exports),M(`Functions`,e.functions.map(e=>`${e.name} @ line ${e.line}${e.exported?` [exported]`:``}`)),M(`Classes`,e.classes.map(e=>`${e.name} @ line ${e.line}${e.exported?` [exported]`:``}`)),M(`Interfaces`,e.interfaces.map(e=>`${e.name} @ line ${e.line}`)),M(`Types`,e.types.map(e=>`${e.name} @ line ${e.line}`))}function k(e){if(console.log(`Symbol: ${e.name}`),e.definedIn?console.log(`Defined in: ${e.definedIn.path}:${e.definedIn.line} (${e.definedIn.kind})`):console.log(`Defined in: not found`),console.log(``),console.log(`Imported by:`),e.importedBy.length===0)console.log(` none`);else for(let t of e.importedBy)console.log(` - ${t.path}:${t.line} ${t.importStatement}`);if(console.log(``),console.log(`Referenced in:`),e.referencedIn.length===0)console.log(` none`);else for(let t of e.referencedIn)console.log(` - ${t.path}:${t.line} ${t.context}`)}function A(e){console.log(e.name),console.log(` Files: ${e.files.length}`),console.log(` Updated: ${e.updated}`),e.description&&console.log(` Description: ${e.description}`);for(let t of e.files)console.log(` - ${t}`)}function j(e){let t=Array.isArray(e.data.files)?e.data.files.filter(e=>typeof e==`string`):[];if(console.log(e.id),console.log(` Label: ${e.label}`),console.log(` Created: ${e.createdAt}`),e.notes&&console.log(` Notes: ${e.notes}`),t.length>0){console.log(` Files: ${t.length}`);for(let e of t)console.log(` - ${e}`)}console.log(` Data:`);for(let t of JSON.stringify(e.data,null,2).split(`
5
- `))console.log(` ${t}`)}function M(e,t){if(console.log(`${e}:`),t.length===0){console.log(` none`),console.log(``);return}for(let e of t)console.log(` - ${e}`);console.log(``)}function N(e){let t=e.trim();if(!t)return``;try{return JSON.parse(t)}catch{return e}}function P(e){let t=e.trim();if(!t)return{};let n=JSON.parse(t);if(!n||typeof n!=`object`||Array.isArray(n))throw Error(`Checkpoint data must be a JSON object.`);return n}function F(e,t,n=60){let r=new Map;for(let t=0;t<e.length;t++){let i=e[t];r.set(i.record.id,{record:i.record,score:1/(n+t+1)})}for(let e=0;e<t.length;e++){let i=t[e],a=r.get(i.record.id);a?a.score+=1/(n+e+1):r.set(i.record.id,{record:i.record,score:1/(n+e+1)})}return[...r.values()].sort((e,t)=>t.score-e.score)}const I=[`const{execSync:x}=require('child_process')`,`const{readdirSync:r,renameSync:m}=require('fs')`,`const{join:j}=require('path')`,`const c=j(process.env.LOCALAPPDATA||process.env.HOME||'','npm-cache')`,`const s={stdio:'inherit'}`,`try{x('npx -y @vpxa/aikit@latest serve',s)}catch{try{r(c).filter(d=>d.startsWith('_npx')).forEach(d=>{try{m(j(c,d),j(c,d+'_'+Date.now()))}catch{}})}catch{};try{x('npm cache verify',{stdio:'ignore',timeout:30000})}catch{};try{x('npx -y @vpxa/aikit@latest serve',s)}catch(e){process.stderr.write('aikit: all recovery attempts failed. Run: npm cache clean --force && npx -y @vpxa/aikit@latest serve');process.exit(1)}}`].join(`;`),L=`aikit`,R={type:`stdio`,command:`node`,args:[`-e`,I]},z=[`aikit`,`brainstorming`,`multi-agents-development`,`session-handoff`,`requirements-clarity`,`lesson-learned`,`c4-architecture`,`adr-skill`,`present`,`frontend-design`,`react`,`typescript`,`docs`,`repo-access`],B=[`aikit-basic`,`aikit-advanced`,`_epilogue`],V={"chat.agentFilesLocations":{"~/.claude/agents":!1},"chat.useClaudeMdFile":!1,"github.copilot.chat.copilotMemory.enabled":!0,"chat.customAgentInSubagent.enabled":!0,"chat.useNestedAgentsMdFiles":!0,"chat.useAgentSkills":!0,"github.copilot.chat.switchAgent.enabled":!0,"workbench.browser.enableChatTools":!0,"chat.mcp.apps.enabled":!0,"chat.instructionsFilesLocations":{"~/.copilot/instructions":!0,".github/instructions":!0,".claude/rules":!1,"~/.claude/rules":!1}};function H(e){return`
5
+ `))console.log(` ${t}`)}function M(e,t){if(console.log(`${e}:`),t.length===0){console.log(` none`),console.log(``);return}for(let e of t)console.log(` - ${e}`);console.log(``)}function N(e){let t=e.trim();if(!t)return``;try{return JSON.parse(t)}catch{return e}}function P(e){let t=e.trim();if(!t)return{};let n=JSON.parse(t);if(!n||typeof n!=`object`||Array.isArray(n))throw Error(`Checkpoint data must be a JSON object.`);return n}function F(e,t,n=60){let r=new Map;for(let t=0;t<e.length;t++){let i=e[t];r.set(i.record.id,{record:i.record,score:1/(n+t+1)})}for(let e=0;e<t.length;e++){let i=t[e],a=r.get(i.record.id);a?a.score+=1/(n+e+1):r.set(i.record.id,{record:i.record,score:1/(n+e+1)})}return[...r.values()].sort((e,t)=>t.score-e.score)}const I=[`const{execSync:x}=require('child_process')`,`const{existsSync:e,renameSync:m}=require('fs')`,`const{join:j}=require('path')`,`const c=j(process.env.LOCALAPPDATA||process.env.HOME||'','npm-cache')`,`const s={stdio:'inherit'}`,`try{x('npx -y @vpxa/aikit@latest serve',s)}catch{try{const d=j(c,'_npx');if(e(d))m(d,j(c,'_npx_'+Date.now()))}catch{};try{x('npm cache verify',{stdio:'ignore',timeout:30000})}catch{};try{x('npx -y @vpxa/aikit@latest serve',s)}catch(e){process.stderr.write('aikit: all recovery attempts failed. Run: npm cache clean --force && npx -y @vpxa/aikit@latest serve');process.exit(1)}}`].join(`;`),L=`aikit`,R={type:`stdio`,command:`node`,args:[`-e`,I]},z=[`aikit`,`brainstorming`,`multi-agents-development`,`session-handoff`,`requirements-clarity`,`lesson-learned`,`c4-architecture`,`adr-skill`,`present`,`frontend-design`,`react`,`typescript`,`docs`,`repo-access`],B=[`aikit-basic`,`aikit-advanced`,`_epilogue`],V={"chat.agentFilesLocations":{"~/.claude/agents":!1},"chat.useClaudeMdFile":!1,"github.copilot.chat.copilotMemory.enabled":!0,"chat.customAgentInSubagent.enabled":!0,"chat.useNestedAgentsMdFiles":!0,"chat.useAgentSkills":!0,"github.copilot.chat.switchAgent.enabled":!0,"workbench.browser.enableChatTools":!0,"chat.mcp.apps.enabled":!0,"chat.instructionsFilesLocations":{"~/.copilot/instructions":!0,".github/instructions":!0,".claude/rules":!1,"~/.claude/rules":!1}};function H(e){return`
6
6
  ## Flow Context Bootstrap
7
7
 
8
8
  When dispatched as a subagent within an active flow:
@@ -82,7 +82,7 @@ Even then, use \`file_summary\` first to identify which lines to read.
82
82
 
83
83
  1. **Recall before acting** — \`search({ query })\` for past decisions/conventions about the area you're changing. If a prior decision exists, **follow it** — don't silently override. Then \`scope_map({ task })\` for a reading plan.
84
84
  2. **Compress, don't read** — \`file_summary\` → \`compact\` → \`digest\`. NEVER raw-read a file to "understand" it.
85
- 3. **Remember** — \`search({ query: "SESSION CHECKPOINT", origin: "curated" })\` at session start. \`remember()\` decisions at session end. Auto-knowledge captures conventions and patterns from tool outputs automatically.
85
+ 3. **Remember** — \`search({ query: "SESSION CHECKPOINT", origin: "curated" })\` at session start. \`remember()\` decisions at session end. Auto-knowledge captures conventions and patterns from tool outputs automatically and should refresh stable facts instead of multiplying duplicates.
86
86
  4. **Validate** — \`check({})\` + \`test_run({})\` before presenting changes. \`blast_radius({ changed_files })\` for impact.
87
87
  5. **Lifecycle** — Check \`status({})\` first. If onboard not run, run \`onboard({ path: "." })\`. After implementation, \`reindex({})\` + \`produce_knowledge({})\`. At session end, \`remember()\` checkpoint.
88
88
 
@@ -143,6 +143,8 @@ AI Kit provides cross-session persistent memory. **Use it actively** — decisio
143
143
 
144
144
  Auto-knowledge also captures facts automatically from tool outputs (conventions detected, errors encountered, test results, research findings). These are searchable alongside manually stored entries.
145
145
 
146
+ **Retrieval-first rule:** before you re-run \`file_summary\`, \`scope_map\`, \`digest\`, or similar context tools, search the exact file path or topic first. If a response includes \`ctxc_...\`, reuse it via \`compact({ ref })\` or \`compact({ ref, query? })\`. Prefer \`enrich: true\` on follow-up retrieval after the first pass.
147
+
146
148
  | Action | Tool | Example |
147
149
  |--------|------|---------|
148
150
  | Store | \`remember\` | \`knowledge({ action: "remember", title: "Auth uses JWT RS256", content: "...", category: "decisions" })\` |
@@ -159,6 +161,7 @@ Auto-knowledge also captures facts automatically from tool outputs (conventions
159
161
  **Task-level recall** (do BEFORE implementing any feature):
160
162
  \`\`\`
161
163
  search({ query: "keywords about what you're building" }) // check past decisions
164
+ search({ query: "exact-file-path-or-topic" }) // reuse refreshed auto-knowledge before rereading
162
165
  knowledge({ action: "list", category: "decisions" }) // scan recent decisions
163
166
  // If results exist → read and follow them
164
167
  // If no results → proceed, then remember() your decisions
@@ -2452,7 +2452,7 @@ container holding the app. Specify either width or maxWidth, and either height o
2452
2452
  .drag-handle { font-size: 18px; color: var(--aikit-muted, #858585); cursor: grab; user-select: none; }
2453
2453
  .sort-label { flex: 1; color: var(--aikit-text, #ccc); }
2454
2454
  .sort-pos { font-size: 12px; color: var(--aikit-muted, #858585); font-variant-numeric: tabular-nums; }
2455
- `,Dw={name:`list-sort`,label:`Sortable List`,detect(e){if(typeof e!=`object`||!e||Array.isArray(e))return 0;let t=e;return t.items&&Array.isArray(t.items)&&!t.categories?.8:0},render(e,t,n){let r=t,i=Q(`div`,`block tpl-list-sort`);ew(`tpl-list-sort`,Ew);function a(e){i.innerHTML=``;let t=Q(`ul`,`sort-list`),r=-1;for(let i=0;i<e.length;i++){let o=e[i],s=document.createElement(`li`);s.className=`sort-item`,s.draggable=!0,s.dataset.idx=String(i);let c=Q(`span`,`drag-handle`,`⠿`),l=Q(`span`,`sort-label`,o.label),u=Q(`span`,`sort-pos`,`#${i+1}`);s.appendChild(c),s.appendChild(l),s.appendChild(u),s.addEventListener(`dragstart`,()=>{r=Number(s.dataset.idx),s.classList.add(`dragging`)}),s.addEventListener(`dragend`,()=>{s.classList.remove(`dragging`)}),s.addEventListener(`dragenter`,e=>{e.preventDefault()}),s.addEventListener(`dragover`,e=>{e.preventDefault(),s.classList.add(`drag-over`)}),s.addEventListener(`dragleave`,()=>{s.classList.remove(`drag-over`)}),s.addEventListener(`drop`,t=>{t.preventDefault(),s.classList.remove(`drag-over`);let i=Number(s.dataset.idx);if(r>=0&&r!==i){let t=[...e],[o]=t.splice(r,1);t.splice(i,0,o),a(t),n.emitAction({type:`button`,id:`reorder`,label:`Reorder`},JSON.stringify(t.map(e=>e.id)))}}),t.appendChild(s)}i.appendChild(t)}a([...r.items??[]]),e.appendChild(i)},styles(){return Ew}},Ow=document.getElementById(`app`);if(!Ow)throw Error(`Missing #app element`);var $=Ow,kw=XC(),Aw=kw?void 0:new mC({name:`AI Kit Present`,version:`1.0.0`}),jw=new dw;jw.register(Dw),jw.register(Cw),jw.register(bw),jw.register(Tw);var Mw=GC(Aw),Nw={app:Aw,data:ZC(Aw),emitAction:Mw},Pw=new vw,Fw=new iw,Iw=Aw?new QC(Aw):void 0,Lw=null,Rw=!!kw,zw;ew(`aikit-shared-header`,Vn);var Bw=`<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z"/><circle cx="12" cy="13" r="4"/></svg>`,Vw=`<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"/></svg>`,Hw=mi(),Uw=null,Ww=!1;function Gw(e,t={}){if(!Uw)return;let{button:n,menu:r}=Uw;r.hidden=!e,n.setAttribute(`aria-expanded`,String(e)),e&&t.focusItem?r.querySelector(`.${Bn.toolboxItem}`)?.focus():!e&&t.restoreFocus&&n.focus()}function Kw(){Ww||(Ww=!0,document.addEventListener(`click`,e=>{if(!Uw)return;let t=e.target;t instanceof Node&&Uw.container.contains(t)||Gw(!1)}),document.addEventListener(`keydown`,e=>{if(Uw){if(e.key===`Escape`){Gw(!1,{restoreFocus:!0});return}(e.key===`ArrowDown`||e.key===`Enter`||e.key===` `)&&e.target===Uw.button&&(e.preventDefault(),Gw(!0,{focusItem:!0}))}}))}function qw(){Kw();let e=Q(`div`,Bn.toolbox),t=Q(`button`,Bn.toolboxToggle),n=Q(`div`,Bn.toolboxMenu),r=Q(`button`,Bn.toolboxItem);return t.type=`button`,t.setAttribute(`aria-label`,`Open tools menu`),t.setAttribute(`aria-haspopup`,`menu`),t.setAttribute(`aria-expanded`,`false`),t.setAttribute(`aria-controls`,`aikit-toolbox-menu`),t.innerHTML=Vw,t.addEventListener(`click`,()=>{Gw(!!n.hidden,{focusItem:!!n.hidden})}),n.id=`aikit-toolbox-menu`,n.setAttribute(`role`,`menu`),n.hidden=!0,r.type=`button`,r.setAttribute(`role`,`menuitem`),r.setAttribute(`aria-label`,`Copy as Image`),r.dataset.sharedChromeAction=`copy-image`,r.innerHTML=`<span aria-hidden="true">${Bw}</span><span>Copy as Image</span>`,r.addEventListener(`click`,()=>{Gw(!1),tT()}),n.appendChild(r),e.appendChild(t),e.appendChild(n),Uw={button:t,container:e,menu:n},e}function Jw(e,t){let n=Q(`header`,Bn.header);n.appendChild(Q(`div`,Bn.brand,`AI KIT`));let r=Q(`div`,Bn.title);r.appendChild(Q(`span`,Bn.titleText,e)),t&&r.appendChild(Q(`span`,Bn.subtitle,t));let i=Q(`div`,Bn.actions);i.appendChild(qw()),n.appendChild(r),n.appendChild(i),$.appendChild(n)}function Yw(){Lw?.(),Lw=null,fT?.destroy&&fT.destroy(),fT=null}function Xw(e,t){let n=new Map,r=e=>{n.set(o(e.id),e)};for(let e of t??[])r(e);for(let t of e)if(!(t.type!==`actions`||!Array.isArray(t.value)))for(let e of t.value)e&&typeof e==`object`&&`id`in e&&r(e);return n}function Zw(e,t,n){let r=Xw(t,n);Lw=WC(e,t,(e,t)=>{Mw(r.get(e)??{type:t===void 0?`button`:`select`,id:e,label:e},t)})}function Qw(e,t,n){let r=document.documentElement.dir,i=JC(e,t,{colorScheme:Pw.getTheme(),lang:document.documentElement.lang||void 0,dir:r===`ltr`||r===`rtl`||r===`auto`?r:void 0});return i?{blocks:i.blocks,actions:n.actions}:null}var $w;function eT(e){Yw(),$.innerHTML=``;let t=uw(e);e.title&&Jw(e.title,`Streaming`);let n=Q(`div`,`content`);Zw(n,t.blocks??[]),$.appendChild(n)}async function tT(){let e;try{e=await cT()}catch(e){console.warn(Hw.fallbackToServerCaptureMessage,e),uT(Hw.blockedClipboardMessage,`error`);return}try{await iT(e),uT(Hw.clipboardSuccessMessage)}catch(t){console.warn(`Async Clipboard image write failed`,t);try{await rT(e),uT(`Async clipboard write blocked. Copied via legacy clipboard path.`)}catch(t){console.warn(`Legacy clipboard image write failed`,t);try{await aT(e),uT(`${Hw.blockedClipboardMessage} Downloading PNG instead.`)}catch(e){console.warn(`Copy as Image download fallback failed`,e),uT(Hw.blockedClipboardMessage,`error`)}}}}function nT(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>t(String(r.result)),r.onerror=()=>n(r.error||Error(`Image conversion failed`)),r.readAsDataURL(e)})}async function rT(e){let t=await nT(e),n=!1,r=r=>{let i=r.clipboardData;if(i){r.preventDefault();try{i.items&&typeof File<`u`&&(i.items.add(new File([e],`aikit-present.png`,{type:`image/png`})),n=!0)}catch{}i.setData(`text/html`,`<img alt="AI Kit Present" src="${t}">`),i.setData(`text/plain`,`AI Kit Present image`),n=!0}};document.addEventListener(`copy`,r,{once:!0});try{n=document.execCommand(`copy`)||n}finally{document.removeEventListener(`copy`,r)}if(!n)throw Error(`Legacy clipboard copy unavailable`)}async function iT(e){if(!navigator.clipboard?.write||!(`ClipboardItem`in window))throw Error(`Async image clipboard is unavailable in this host.`);await navigator.clipboard.write([new ClipboardItem({"image/png":e})])}async function aT(e){let t=URL.createObjectURL(e),n=document.createElement(`a`);n.href=t,n.download=`aikit-present.png`,n.rel=`noopener`,document.body.appendChild(n);try{n.click()}finally{n.remove(),URL.revokeObjectURL(t)}}async function oT(){let e=Math.max(document.documentElement.scrollWidth,document.documentElement.clientWidth,document.body?document.body.scrollWidth:0),t=Math.max(document.documentElement.scrollHeight,document.documentElement.clientHeight,document.body?document.body.scrollHeight:0),n=window.devicePixelRatio||1,r=document.createElement(`canvas`);r.width=Math.max(1,Math.ceil(e*n)),r.height=Math.max(1,Math.ceil(t*n));let i=r.getContext(`2d`);if(!i)throw Error(`Canvas context unavailable`);i.scale(n,n);let a=document.documentElement.cloneNode(!0);if(!(a instanceof Element))throw Error(`Document clone failed`);a.setAttribute(`xmlns`,`http://www.w3.org/1999/xhtml`),a.querySelectorAll(`script`).forEach(e=>{e.remove()}),lT(document.documentElement,a);let o=[`<svg xmlns="http://www.w3.org/2000/svg" width="${e}" height="${t}" viewBox="0 0 ${e} ${t}">`,`<foreignObject width="100%" height="100%">${new XMLSerializer().serializeToString(a)}</foreignObject>`,`</svg>`].join(``),s=new Blob([o],{type:`image/svg+xml;charset=utf-8`}),c=URL.createObjectURL(s);try{await new Promise((n,r)=>{let a=new Image;a.onload=()=>{i.drawImage(a,0,0,e,t),n(void 0)},a.onerror=()=>r(Error(`ForeignObject render failed`)),a.src=c})}finally{URL.revokeObjectURL(c)}let l=await new Promise(e=>r.toBlob(e,`image/png`));if(l?.type!==`image/png`)throw Error(`PNG export failed`);return l}async function sT(){let e=await fetch(`/__aikit_screenshot.png`,{cache:`no-store`});if(!e.ok)throw Error(`Server PNG capture unavailable`);let t=await e.blob();if(t?.type!==`image/png`)throw Error(`Server PNG capture failed`);return t}async function cT(){try{return await sT()}catch{return oT()}}function lT(e,t){let n=window.getComputedStyle(e),r=Array.from(n).map(e=>`${e}:${n.getPropertyValue(e)}${n.getPropertyPriority(e)?` !important`:``};`).join(``);t.setAttribute(`style`,r);for(let n=0;n<e.children.length;n+=1){let r=e.children[n],i=t.children[n];r&&i&&lT(r,i)}}function uT(e,t=`info`){let n=$.querySelector(`.host-message`);n||(n=Q(`div`,`host-message`),$.prepend(n)),n.dataset.tone=t,n.replaceChildren(),n.appendChild(Q(`span`,``,e)),clearTimeout(zw),zw=setTimeout(()=>{n?.remove()},4e3)}function dT(){if(!Rw)return;let e=window;e.toggleToolbox=()=>{if(Uw){Gw(!!Uw.menu.hidden);return}let e=document.getElementById(`aikit-toolbox-menu`);e&&(e.hidden=!e.hidden)},e.screenshotPage||=tT}var fT=null;function pT(e,t){$.innerHTML=``;let n=Q(`div`,`error-panel`);n.appendChild(Q(`h3`,``,`⚠ ${e}`)),n.appendChild(Q(`pre`,``,t instanceof Error?t.message:String(t))),$.appendChild(n)}function mT(e){Yw(),$.innerHTML=``;let t=uw(e),n=t.data;if(n==null){$.innerHTML=`<p class="no-data">No content data received.</p>`;return}e.title&&!Rw&&Jw(e.title);let r=t.template?jw.get(t.template):jw.detect(n),i=Q(`div`,`content`);if(r)fT=r,r.render(i,n,Nw);else if(t.template){let r=Qw(t.template,n,e);r?Zw(i,r.blocks,r.actions):Zw(i,t.blocks??[],e.actions)}else Zw(i,t.blocks??[],e.actions);if($.appendChild(i),e.actions?.length){let t=Q(`div`,`actions-shell`),n=WC(t,[{type:`actions`,value:e.actions}],(t,n)=>{Mw(e.actions?.find(e=>o(e.id)===t)??{type:n===void 0?`button`:`select`,id:t,label:t},n)}),r=Lw;Lw=()=>{r?.(),n()},$.appendChild(t)}let a=Q(`div`,`footer`);a.innerHTML=`<span class="footer-brand">Powered by <strong>AI Kit</strong></span>`,$.appendChild(a)}Aw?(Aw.connect().then(()=>{let e=Aw.getHostContext();e&&(Pw.apply(e),Fw.apply(e),Iw?.apply(e))}),Aw.onhostcontextchanged=e=>{Pw.apply(e),Fw.apply(e),Iw?.apply(e),fT?.onThemeChange&&fT.onThemeChange(Pw.getTheme())},Aw.ontoolinputpartial=e=>{let t=e.arguments;t&&($.dataset.streaming=`true`,clearTimeout($w),$w=setTimeout(()=>{try{let e=t.content??t.data??t.blocks;if(e==null)return;eT({schemaVersion:t.schemaVersion===1?1:void 0,title:t.title,template:t.template,content:e,data:t.data,blocks:Array.isArray(t.blocks)?t.blocks:void 0})}catch{}},80))},Aw.ontoolinput=()=>{clearTimeout($w),delete $.dataset.streaming},Aw.ontoolresult=e=>{if(clearTimeout($w),delete $.dataset.streaming,e.structuredContent)try{mT(e.structuredContent);return}catch(e){pT(`Render error`,e);return}let t=e.content?.find(e=>e.type===`text`)?.text;if(!t){$.innerHTML=`<p>No data received.</p>`;return}try{mT(JSON.parse(t))}catch{mT({content:t})}}):kw&&(document.documentElement.dataset.theme=`dark`,dT(),mT(kw));</script>
2455
+ `,Dw={name:`list-sort`,label:`Sortable List`,detect(e){if(typeof e!=`object`||!e||Array.isArray(e))return 0;let t=e;return t.items&&Array.isArray(t.items)&&!t.categories?.8:0},render(e,t,n){let r=t,i=Q(`div`,`block tpl-list-sort`);ew(`tpl-list-sort`,Ew);function a(e){i.innerHTML=``;let t=Q(`ul`,`sort-list`),r=-1;for(let i=0;i<e.length;i++){let o=e[i],s=document.createElement(`li`);s.className=`sort-item`,s.draggable=!0,s.dataset.idx=String(i);let c=Q(`span`,`drag-handle`,`⠿`),l=Q(`span`,`sort-label`,o.label),u=Q(`span`,`sort-pos`,`#${i+1}`);s.appendChild(c),s.appendChild(l),s.appendChild(u),s.addEventListener(`dragstart`,()=>{r=Number(s.dataset.idx),s.classList.add(`dragging`)}),s.addEventListener(`dragend`,()=>{s.classList.remove(`dragging`)}),s.addEventListener(`dragenter`,e=>{e.preventDefault()}),s.addEventListener(`dragover`,e=>{e.preventDefault(),s.classList.add(`drag-over`)}),s.addEventListener(`dragleave`,()=>{s.classList.remove(`drag-over`)}),s.addEventListener(`drop`,t=>{t.preventDefault(),s.classList.remove(`drag-over`);let i=Number(s.dataset.idx);if(r>=0&&r!==i){let t=[...e],[o]=t.splice(r,1);t.splice(i,0,o),a(t),n.emitAction({type:`button`,id:`reorder`,label:`Reorder`},JSON.stringify(t.map(e=>e.id)))}}),t.appendChild(s)}i.appendChild(t)}a([...r.items??[]]),e.appendChild(i)},styles(){return Ew}},Ow=document.getElementById(`app`);if(!Ow)throw Error(`Missing #app element`);var $=Ow,kw=XC(),Aw=kw?void 0:new mC({name:`AI Kit Present`,version:`1.0.0`}),jw=new dw;jw.register(Dw),jw.register(Cw),jw.register(bw),jw.register(Tw);var Mw=GC(Aw),Nw={app:Aw,data:ZC(Aw),emitAction:Mw},Pw=new vw,Fw=new iw,Iw=Aw?new QC(Aw):void 0,Lw=null,Rw=!!kw,zw;ew(`aikit-shared-header`,Vn);var Bw=`<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z"/><circle cx="12" cy="13" r="4"/></svg>`,Vw=`<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"/></svg>`,Hw=mi(),Uw={kind:`shared-chrome-action`,id:`copy-image`,label:`Copy as Image`,icon:Bw,onclick:`screenshotPage()`};function Ww(){return typeof navigator<`u`&&typeof document<`u`&&!!navigator.clipboard?.write&&typeof window<`u`&&`ClipboardItem`in window}function Gw(){return Ww()?[Uw]:[]}var Kw=null,qw=!1;function Jw(e,t={}){if(!Kw)return;let{button:n,menu:r}=Kw;r.hidden=!e,n.setAttribute(`aria-expanded`,String(e)),e&&t.focusItem?r.querySelector(`.${Bn.toolboxItem}`)?.focus():!e&&t.restoreFocus&&n.focus()}function Yw(){qw||(qw=!0,document.addEventListener(`click`,e=>{if(!Kw)return;let t=e.target;t instanceof Node&&Kw.container.contains(t)||Jw(!1)}),document.addEventListener(`keydown`,e=>{if(Kw){if(e.key===`Escape`){Jw(!1,{restoreFocus:!0});return}(e.key===`ArrowDown`||e.key===`Enter`||e.key===` `)&&e.target===Kw.button&&(e.preventDefault(),Jw(!0,{focusItem:!0}))}}))}function Xw(e){if(Yw(),e.length===0)return null;let t=Q(`div`,Bn.toolbox),n=Q(`button`,Bn.toolboxToggle),r=Q(`div`,Bn.toolboxMenu);n.type=`button`,n.setAttribute(`aria-label`,`Open tools menu`),n.setAttribute(`aria-haspopup`,`menu`),n.setAttribute(`aria-expanded`,`false`),n.setAttribute(`aria-controls`,`aikit-toolbox-menu`),n.innerHTML=Vw,n.addEventListener(`click`,()=>{Jw(!!r.hidden,{focusItem:!!r.hidden})}),r.id=`aikit-toolbox-menu`,r.setAttribute(`role`,`menu`),r.hidden=!0;for(let t of e){if(t.id!==`copy-image`)continue;let e=Q(`button`,Bn.toolboxItem);e.type=`button`,e.setAttribute(`role`,`menuitem`),e.setAttribute(`aria-label`,t.label),e.dataset.sharedChromeAction=t.id,e.innerHTML=`<span aria-hidden="true">${t.icon}</span><span>${t.label}</span>`,e.addEventListener(`click`,()=>{Jw(!1),iT()}),r.appendChild(e)}return r.childElementCount===0?null:(t.appendChild(n),t.appendChild(r),Kw={button:n,container:t,menu:r},t)}function Zw(e,t){let n=Q(`header`,Bn.header);n.appendChild(Q(`div`,Bn.brand,`AI KIT`));let r=Q(`div`,Bn.title);r.appendChild(Q(`span`,Bn.titleText,e)),t&&r.appendChild(Q(`span`,Bn.subtitle,t));let i=Q(`div`,Bn.actions),a=Xw(Gw());a&&i.appendChild(a),n.appendChild(r),n.appendChild(i),$.appendChild(n)}function Qw(){Lw?.(),Lw=null,hT?.destroy&&hT.destroy(),hT=null}function $w(e,t){let n=new Map,r=e=>{n.set(o(e.id),e)};for(let e of t??[])r(e);for(let t of e)if(!(t.type!==`actions`||!Array.isArray(t.value)))for(let e of t.value)e&&typeof e==`object`&&`id`in e&&r(e);return n}function eT(e,t,n){let r=$w(t,n);Lw=WC(e,t,(e,t)=>{Mw(r.get(e)??{type:t===void 0?`button`:`select`,id:e,label:e},t)})}function tT(e,t,n){let r=document.documentElement.dir,i=JC(e,t,{colorScheme:Pw.getTheme(),lang:document.documentElement.lang||void 0,dir:r===`ltr`||r===`rtl`||r===`auto`?r:void 0});return i?{blocks:i.blocks,actions:n.actions}:null}var nT;function rT(e){Qw(),$.innerHTML=``;let t=uw(e);e.title&&Zw(e.title,`Streaming`);let n=Q(`div`,`content`);eT(n,t.blocks??[]),$.appendChild(n)}async function iT(){let e;try{e=await dT()}catch(e){console.warn(Hw.fallbackToServerCaptureMessage,e),pT(Hw.blockedClipboardMessage,`error`);return}try{await sT(e),pT(Hw.clipboardSuccessMessage)}catch(t){console.warn(`Async Clipboard image write failed`,t);try{await oT(e),pT(`Async clipboard write blocked. Copied via legacy clipboard path.`)}catch(t){console.warn(`Legacy clipboard image write failed`,t);try{await cT(e),pT(`${Hw.blockedClipboardMessage} Downloading PNG instead.`)}catch(e){console.warn(`Copy as Image download fallback failed`,e),pT(Hw.blockedClipboardMessage,`error`)}}}}function aT(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>t(String(r.result)),r.onerror=()=>n(r.error||Error(`Image conversion failed`)),r.readAsDataURL(e)})}async function oT(e){let t=await aT(e),n=!1,r=r=>{let i=r.clipboardData;if(i){r.preventDefault();try{i.items&&typeof File<`u`&&(i.items.add(new File([e],`aikit-present.png`,{type:`image/png`})),n=!0)}catch{}i.setData(`text/html`,`<img alt="AI Kit Present" src="${t}">`),i.setData(`text/plain`,`AI Kit Present image`),n=!0}};document.addEventListener(`copy`,r,{once:!0});try{n=document.execCommand(`copy`)||n}finally{document.removeEventListener(`copy`,r)}if(!n)throw Error(`Legacy clipboard copy unavailable`)}async function sT(e){if(!navigator.clipboard?.write||!(`ClipboardItem`in window))throw Error(`Async image clipboard is unavailable in this host.`);await navigator.clipboard.write([new ClipboardItem({"image/png":e})])}async function cT(e){let t=URL.createObjectURL(e),n=document.createElement(`a`);n.href=t,n.download=`aikit-present.png`,n.rel=`noopener`,document.body.appendChild(n);try{n.click()}finally{n.remove(),URL.revokeObjectURL(t)}}async function lT(){let e=Math.max(document.documentElement.scrollWidth,document.documentElement.clientWidth,document.body?document.body.scrollWidth:0),t=Math.max(document.documentElement.scrollHeight,document.documentElement.clientHeight,document.body?document.body.scrollHeight:0),n=window.devicePixelRatio||1,r=document.createElement(`canvas`);r.width=Math.max(1,Math.ceil(e*n)),r.height=Math.max(1,Math.ceil(t*n));let i=r.getContext(`2d`);if(!i)throw Error(`Canvas context unavailable`);i.scale(n,n);let a=document.documentElement.cloneNode(!0);if(!(a instanceof Element))throw Error(`Document clone failed`);a.setAttribute(`xmlns`,`http://www.w3.org/1999/xhtml`),a.querySelectorAll(`script`).forEach(e=>{e.remove()}),fT(document.documentElement,a);let o=[`<svg xmlns="http://www.w3.org/2000/svg" width="${e}" height="${t}" viewBox="0 0 ${e} ${t}">`,`<foreignObject width="100%" height="100%">${new XMLSerializer().serializeToString(a)}</foreignObject>`,`</svg>`].join(``),s=new Blob([o],{type:`image/svg+xml;charset=utf-8`}),c=URL.createObjectURL(s);try{await new Promise((n,r)=>{let a=new Image;a.onload=()=>{i.drawImage(a,0,0,e,t),n(void 0)},a.onerror=()=>r(Error(`ForeignObject render failed`)),a.src=c})}finally{URL.revokeObjectURL(c)}let l=await new Promise(e=>r.toBlob(e,`image/png`));if(l?.type!==`image/png`)throw Error(`PNG export failed`);return l}async function uT(){let e=await fetch(`/__aikit_screenshot.png`,{cache:`no-store`});if(!e.ok)throw Error(`Server PNG capture unavailable`);let t=await e.blob();if(t?.type!==`image/png`)throw Error(`Server PNG capture failed`);return t}async function dT(){try{return await uT()}catch{return lT()}}function fT(e,t){let n=window.getComputedStyle(e),r=Array.from(n).map(e=>`${e}:${n.getPropertyValue(e)}${n.getPropertyPriority(e)?` !important`:``};`).join(``);t.setAttribute(`style`,r);for(let n=0;n<e.children.length;n+=1){let r=e.children[n],i=t.children[n];r&&i&&fT(r,i)}}function pT(e,t=`info`){let n=$.querySelector(`.host-message`);n||(n=Q(`div`,`host-message`),$.prepend(n)),n.dataset.tone=t,n.replaceChildren(),n.appendChild(Q(`span`,``,e)),clearTimeout(zw),zw=setTimeout(()=>{n?.remove()},4e3)}function mT(){if(!Rw)return;let e=window;e.toggleToolbox=()=>{if(Kw){Jw(!!Kw.menu.hidden);return}let e=document.getElementById(`aikit-toolbox-menu`);e&&(e.hidden=!e.hidden)},e.screenshotPage||=iT}var hT=null;function gT(e,t){$.innerHTML=``;let n=Q(`div`,`error-panel`);n.appendChild(Q(`h3`,``,`⚠ ${e}`)),n.appendChild(Q(`pre`,``,t instanceof Error?t.message:String(t))),$.appendChild(n)}function _T(e){Qw(),$.innerHTML=``;let t=uw(e),n=t.data;if(n==null){$.innerHTML=`<p class="no-data">No content data received.</p>`;return}e.title&&!Rw&&Zw(e.title);let r=t.template?jw.get(t.template):jw.detect(n),i=Q(`div`,`content`);if(r)hT=r,r.render(i,n,Nw);else if(t.template){let r=tT(t.template,n,e);r?eT(i,r.blocks,r.actions):eT(i,t.blocks??[],e.actions)}else eT(i,t.blocks??[],e.actions);if($.appendChild(i),e.actions?.length){let t=Q(`div`,`actions-shell`),n=WC(t,[{type:`actions`,value:e.actions}],(t,n)=>{Mw(e.actions?.find(e=>o(e.id)===t)??{type:n===void 0?`button`:`select`,id:t,label:t},n)}),r=Lw;Lw=()=>{r?.(),n()},$.appendChild(t)}let a=Q(`div`,`footer`);a.innerHTML=`<span class="footer-brand">Powered by <strong>AI Kit</strong></span>`,$.appendChild(a)}Aw?(Aw.connect().then(()=>{let e=Aw.getHostContext();e&&(Pw.apply(e),Fw.apply(e),Iw?.apply(e))}),Aw.onhostcontextchanged=e=>{Pw.apply(e),Fw.apply(e),Iw?.apply(e),hT?.onThemeChange&&hT.onThemeChange(Pw.getTheme())},Aw.ontoolinputpartial=e=>{let t=e.arguments;t&&($.dataset.streaming=`true`,clearTimeout(nT),nT=setTimeout(()=>{try{let e=t.content??t.data??t.blocks;if(e==null)return;rT({schemaVersion:t.schemaVersion===1?1:void 0,title:t.title,template:t.template,content:e,data:t.data,blocks:Array.isArray(t.blocks)?t.blocks:void 0})}catch{}},80))},Aw.ontoolinput=()=>{clearTimeout(nT),delete $.dataset.streaming},Aw.ontoolresult=e=>{if(clearTimeout(nT),delete $.dataset.streaming,e.structuredContent)try{_T(e.structuredContent);return}catch(e){gT(`Render error`,e);return}let t=e.content?.find(e=>e.type===`text`)?.text;if(!t){$.innerHTML=`<p>No data received.</p>`;return}try{_T(JSON.parse(t))}catch{_T({content:t})}}):kw&&(document.documentElement.dataset.theme=`dark`,mT(),_T(kw));</script>
2456
2456
  </head>
2457
2457
  <body>
2458
2458
  <div id="app">
@@ -1,8 +1,8 @@
1
1
  #!/usr/bin/env node
2
- import{t as e}from"./rolldown-runtime-yuFVEuWy.js";import{createHash as t,randomUUID as n}from"node:crypto";import{readFileSync as r}from"node:fs";import{dirname as i,isAbsolute as a,join as o,resolve as s}from"node:path";import{fileURLToPath as c,pathToFileURL as l}from"node:url";import{parseArgs as u}from"node:util";import{HealthBus as d,createLogger as f,serializeError as p,setDetailedErrorLoggingEnabled as m}from"../../core/dist/index.js";import{GIT_REF_SLUG_PATTERN as h,gitAvailable as g,gitCommitToRef as _,gitExec as v,slugForRef as y}from"../../tools/dist/index.js";import{mkdir as b,readFile as x,readdir as S,stat as C,unlink as w,writeFile as T}from"node:fs/promises";const E=`__pending__:`;function D(e){return e.startsWith(E)}function O(e){let t=e.headers[`mcp-session-id`];return Array.isArray(t)?t[0]:t}function k(e,t,n,r){e.status(t).json({jsonrpc:`2.0`,error:{code:n,message:r},id:null})}var A=class{options;runtimes=new Map;maxSessions;sessionTimeoutMs;now;constructor(e){this.options=e,this.maxSessions=e.maxSessions??8,this.sessionTimeoutMs=(e.sessionTimeoutMinutes??30)*60*1e3,this.now=e.now??(()=>Date.now())}hasSession(e){return this.runtimes.has(e)}getSessionCount(){return this.runtimes.size}async handleRequest(e,t,n=e.body){let r=O(e),i=r?this.runtimes.get(r):void 0;if(r&&!i){k(t,404,-32001,`Session not found`);return}if(!i){if(e.method!==`POST`){k(t,400,-32e3,`Session required`);return}if(i=await this.createRuntime(t),!i)return}await this.withRuntimeLock(i,async()=>{await i.transport.handleRequest(e,t,n),i.lastAccessAt=this.now();let r=i.transport.sessionId??i.id;e.method!==`DELETE`&&!D(r)&&this.options.onSessionActivity?.(r),e.method===`DELETE`&&!D(r)&&await this.closeSession(r,{closeTransport:!1})})}async closeExpiredSessions(){let e=[...this.runtimes.values()].filter(e=>this.now()-e.lastAccessAt>=this.sessionTimeoutMs).map(e=>e.id);for(let t of e)await this.closeSession(t);return e.length}async closeSession(e,t={}){let n=this.runtimes.get(e);return n?(this.runtimes.delete(e),t.notifySessionEnd!==!1&&!D(e)&&this.options.onSessionEnd?.(e),t.closeTransport!==!1&&await n.transport.close().catch(()=>void 0),await n.server.close().catch(()=>void 0),!0):!1}async closeAll(){let e=[...this.runtimes.keys()];for(let t of e)await this.closeSession(t)}async createRuntime(e){if(await this.closeExpiredSessions(),this.runtimes.size>=this.maxSessions){k(e,503,-32003,`Session capacity reached`);return}let t=this.now(),r=await this.options.createServer(),i={id:`${E}${n()}`,transport:void 0,createdAt:t,lastAccessAt:t,server:r,requestChain:Promise.resolve()},a=this.options.createTransport({sessionIdGenerator:()=>n(),onsessioninitialized:async e=>{this.runtimes.delete(i.id),i.id=e,this.runtimes.set(e,i),this.options.onSessionStart?.(e)},onsessionclosed:async e=>{e&&await this.closeSession(e,{closeTransport:!1})}});return i.transport=a,a.onclose=()=>{let e=i.transport.sessionId??i.id;this.closeSession(e,{closeTransport:!1})},this.runtimes.set(i.id,i),await r.connect(a),i}async withRuntimeLock(e,t){let n=e.requestChain,r;e.requestChain=new Promise(e=>{r=e}),await n;try{await t()}finally{r()}}};function j(e){let t=e.includes(`T`)?e:`${e.replace(` `,`T`)}Z`;return Date.parse(t)}var M=class{stateStore;options;gcTimer=null;constructor(e,t={}){this.stateStore=e,this.options=t}onSessionStart(e,t){this.stateStore.sessionCreate(e,t)}onSessionActivity(e){this.stateStore.sessionTouch(e)}onSessionEnd(e){this.stateStore.sessionDelete(e),Promise.resolve(this.options.onSessionEndMaintenance?.(e)).catch(()=>{})}startGC(){if(this.gcTimer)return;let e=(this.options.gcIntervalMinutes??5)*60*1e3;this.gcTimer=setInterval(()=>{this.runGC()},e),this.gcTimer.unref()}runGC(){let e=this.getStaleSessionIds();for(let t of e)this.options.onBeforeSessionDelete?.(t),Promise.resolve(this.options.onSessionEndMaintenance?.(t)).catch(()=>{}),this.stateStore.sessionDelete(t);return e.length}stop(){this.gcTimer&&=(clearInterval(this.gcTimer),null)}getActiveSessions(){return this.stateStore.sessionList().length}listSessions(){return this.stateStore.sessionList()}getStaleSessionIds(e=Date.now()){let t=(this.options.staleTimeoutMinutes??30)*60*1e3;return this.stateStore.sessionList().filter(n=>{let r=j(n.lastActivity);return Number.isFinite(r)&&e-r>=t}).map(e=>e.sessionId)}},N=class{baseDir;constructor(e){this.baseDir=e}async initialize(){await b(this.baseDir,{recursive:!0})}async read(e){let t=o(this.baseDir,e);try{return await x(t,`utf-8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}async write(e,t,n){let r=o(this.baseDir,e);await b(i(r),{recursive:!0}),await T(r,t,{encoding:`utf-8`,flag:n?.exclusive?`wx`:`w`})}async delete(e){let t=o(this.baseDir,e);try{return await w(t),!0}catch(e){if(e.code===`ENOENT`)return!1;throw e}}async list(e){let t=[],n=e?[e]:await this.listDirectories();for(let e of n){let n=o(this.baseDir,e),r;try{r=await S(n)}catch{continue}for(let n of r){if(!n.endsWith(`.md`))continue;let r=`${e}/${n}`,i=o(this.baseDir,r);try{let e=await C(i);t.push({path:r,size:e.size})}catch{}}}return t}async exists(e){let t=o(this.baseDir,e);try{return await C(t),!0}catch{return!1}}async listDirectories(){try{return(await S(this.baseDir,{withFileTypes:!0})).filter(e=>e.isDirectory()&&/^[a-z][a-z0-9-]*$/.test(e.name)).map(e=>e.name)}catch{return[]}}async close(){}},P=e({CuratedKnowledgeManager:()=>R});const F=50*1024,I=`refs/aikit/knowledge`,L=f(`server`);var R=class{curatedDir;store;embedder;adapter;constructor(e,t,n,r=new N(e)){this.curatedDir=e,this.store=t,this.embedder=n,this.adapter=r}async remember(e,t,n,r=[]){this.validateCategoryName(n),this.validateContentSize(t);let i=this.slugify(e),a=await this.uniqueRelativePath(n,i),o=new Date().toISOString(),s={title:e,category:n,tags:r,created:o,updated:o,version:1,origin:`curated`,changelog:[{version:1,date:o,reason:`Initial creation`}]},c=this.serializeFile(t,s);try{await this.adapter.write(a,c,{exclusive:!0})}catch(e){throw e.code===`EEXIST`?Error(`Concurrent write collision for "${a}" — retry the operation`):e}return this.gitCommitKnowledge(a,c,`remember: ${e}\n\nCategory: ${n}\nTags: ${r.join(`, `)}`),await this.indexCuratedFileBestEffort(a,t,s,`remember`),{path:a}}async update(e,t,n){e=this.guardPath(e),this.validateContentSize(t);let r=await this.adapter.read(e);if(r==null)throw Error(`Curated entry not found: ${e}`);let{frontmatter:i}=this.parseFile(r),a=(i.version??1)+1,o=new Date().toISOString();i.version=a,i.updated=o,i.changelog=[...i.changelog??[],{version:a,date:o,reason:n}];let s=this.serializeFile(t,i);return await this.adapter.write(e,s),this.gitCommitKnowledge(e,s,`update(v${a}): ${i.title}\n\nReason: ${n}\nVersion: ${a}`),await this.indexCuratedFileBestEffort(e,t,i,`update`),{path:e,version:a}}async forget(e,t){if(e=this.guardPath(e),!await this.adapter.delete(e))throw Error(`Curated entry not found: ${e}`);let n=`.ai/curated/${e}`;return await this.store.deleteBySourcePath(n).catch(e=>{L.warn(`File deleted but vector cleanup failed`,{sourcePath:n,...p(e)})}),this.gitDeleteKnowledgeRef(e),{path:e}}async history(e,t=20){if(e=this.guardPath(e),!g(this.curatedDir))return[];let n=this.knowledgeRefForPath(e);if(!n)return[];let r=v([`log`,`--format=%H|%aI|%s`,n,`-n`,String(t)],this.curatedDir);return r?r.split(`
2
+ import{t as e}from"./rolldown-runtime-yuFVEuWy.js";import{createHash as t,randomUUID as n}from"node:crypto";import{readFileSync as r}from"node:fs";import{dirname as i,isAbsolute as a,join as o,resolve as s}from"node:path";import{fileURLToPath as c,pathToFileURL as l}from"node:url";import{parseArgs as u}from"node:util";import{HealthBus as d,createLogger as f,serializeError as p,setDetailedErrorLoggingEnabled as m}from"../../core/dist/index.js";import{GIT_REF_SLUG_PATTERN as h,gitAvailable as g,gitCommitToRef as _,gitExec as v,slugForRef as y}from"../../tools/dist/index.js";import{mkdir as b,readFile as x,readdir as S,stat as C,unlink as w,writeFile as T}from"node:fs/promises";const E=`__pending__:`;function D(e){return e.startsWith(E)}function O(e){let t=e.headers[`mcp-session-id`];return Array.isArray(t)?t[0]:t}function k(e,t,n,r){e.status(t).json({jsonrpc:`2.0`,error:{code:n,message:r},id:null})}var A=class{options;runtimes=new Map;maxSessions;sessionTimeoutMs;now;constructor(e){this.options=e,this.maxSessions=e.maxSessions??8,this.sessionTimeoutMs=(e.sessionTimeoutMinutes??30)*60*1e3,this.now=e.now??(()=>Date.now())}hasSession(e){return this.runtimes.has(e)}getSessionCount(){return this.runtimes.size}async handleRequest(e,t,n=e.body){let r=O(e),i=r?this.runtimes.get(r):void 0;if(r&&!i){k(t,404,-32001,`Session not found`);return}if(!i){if(e.method!==`POST`){k(t,400,-32e3,`Session required`);return}if(i=await this.createRuntime(t),!i)return}await this.withRuntimeLock(i,async()=>{await i.transport.handleRequest(e,t,n),i.lastAccessAt=this.now();let r=i.transport.sessionId??i.id;e.method!==`DELETE`&&!D(r)&&this.options.onSessionActivity?.(r),e.method===`DELETE`&&!D(r)&&await this.closeSession(r,{closeTransport:!1})})}async closeExpiredSessions(){let e=[...this.runtimes.values()].filter(e=>this.now()-e.lastAccessAt>=this.sessionTimeoutMs).map(e=>e.id);for(let t of e)await this.closeSession(t);return e.length}async closeSession(e,t={}){let n=this.runtimes.get(e);return n?(this.runtimes.delete(e),t.notifySessionEnd!==!1&&!D(e)&&this.options.onSessionEnd?.(e),t.closeTransport!==!1&&await n.transport.close().catch(()=>void 0),await n.server.close().catch(()=>void 0),!0):!1}async closeAll(){let e=[...this.runtimes.keys()];for(let t of e)await this.closeSession(t)}async createRuntime(e){if(await this.closeExpiredSessions(),this.runtimes.size>=this.maxSessions){k(e,503,-32003,`Session capacity reached`);return}let t=this.now(),r=await this.options.createServer(),i={id:`${E}${n()}`,transport:void 0,createdAt:t,lastAccessAt:t,server:r,requestChain:Promise.resolve()},a=this.options.createTransport({sessionIdGenerator:()=>n(),onsessioninitialized:async e=>{this.runtimes.delete(i.id),i.id=e,this.runtimes.set(e,i),this.options.onSessionStart?.(e)},onsessionclosed:async e=>{e&&await this.closeSession(e,{closeTransport:!1})}});return i.transport=a,a.onclose=()=>{let e=i.transport.sessionId??i.id;this.closeSession(e,{closeTransport:!1})},this.runtimes.set(i.id,i),await r.connect(a),i}async withRuntimeLock(e,t){let n=e.requestChain,r;e.requestChain=new Promise(e=>{r=e}),await n;try{await t()}finally{r()}}};function j(e){let t=e.includes(`T`)?e:`${e.replace(` `,`T`)}Z`;return Date.parse(t)}var M=class{stateStore;options;gcTimer=null;constructor(e,t={}){this.stateStore=e,this.options=t}onSessionStart(e,t){this.stateStore.sessionCreate(e,t)}onSessionActivity(e){this.stateStore.sessionTouch(e)}onSessionEnd(e){this.stateStore.sessionDelete(e),Promise.resolve(this.options.onSessionEndMaintenance?.(e)).catch(()=>{})}startGC(){if(this.gcTimer)return;let e=(this.options.gcIntervalMinutes??5)*60*1e3;this.gcTimer=setInterval(()=>{this.runGC()},e),this.gcTimer.unref()}runGC(){let e=this.getStaleSessionIds();for(let t of e)this.options.onBeforeSessionDelete?.(t),Promise.resolve(this.options.onSessionEndMaintenance?.(t)).catch(()=>{}),this.stateStore.sessionDelete(t);return e.length}stop(){this.gcTimer&&=(clearInterval(this.gcTimer),null)}getActiveSessions(){return this.stateStore.sessionList().length}listSessions(){return this.stateStore.sessionList()}getStaleSessionIds(e=Date.now()){let t=(this.options.staleTimeoutMinutes??30)*60*1e3;return this.stateStore.sessionList().filter(n=>{let r=j(n.lastActivity);return Number.isFinite(r)&&e-r>=t}).map(e=>e.sessionId)}},N=class{baseDir;constructor(e){this.baseDir=e}async initialize(){await b(this.baseDir,{recursive:!0})}async read(e){let t=o(this.baseDir,e);try{return await x(t,`utf-8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}async write(e,t,n){let r=o(this.baseDir,e);await b(i(r),{recursive:!0}),await T(r,t,{encoding:`utf-8`,flag:n?.exclusive?`wx`:`w`})}async delete(e){let t=o(this.baseDir,e);try{return await w(t),!0}catch(e){if(e.code===`ENOENT`)return!1;throw e}}async list(e){let t=[],n=e?[e]:await this.listDirectories();for(let e of n){let n=o(this.baseDir,e),r;try{r=await S(n)}catch{continue}for(let n of r){if(!n.endsWith(`.md`))continue;let r=`${e}/${n}`,i=o(this.baseDir,r);try{let e=await C(i);t.push({path:r,size:e.size})}catch{}}}return t}async exists(e){let t=o(this.baseDir,e);try{return await C(t),!0}catch{return!1}}async listDirectories(){try{return(await S(this.baseDir,{withFileTypes:!0})).filter(e=>e.isDirectory()&&/^[a-z][a-z0-9-]*$/.test(e.name)).map(e=>e.name)}catch{return[]}}async close(){}},P=e({CuratedKnowledgeManager:()=>R});const F=50*1024,I=`refs/aikit/knowledge`,L=f(`server`);var R=class{curatedDir;store;embedder;adapter;constructor(e,t,n,r=new N(e)){this.curatedDir=e,this.store=t,this.embedder=n,this.adapter=r}async remember(e,t,n,r=[]){this.validateCategoryName(n),this.validateContentSize(t);let i=this.normalizeTags(r),a=this.slugify(e),o=await this.uniqueRelativePath(n,a),s=new Date().toISOString(),c={title:e,category:n,tags:i,created:s,updated:s,version:1,origin:`curated`,changelog:[{version:1,date:s,reason:`Initial creation`}]},l=this.serializeFile(t,c);try{await this.adapter.write(o,l,{exclusive:!0})}catch(e){throw e.code===`EEXIST`?Error(`Concurrent write collision for "${o}" — retry the operation`):e}return this.gitCommitKnowledge(o,l,`remember: ${e}\n\nCategory: ${n}\nTags: ${i.join(`, `)}`),await this.indexCuratedFileBestEffort(o,t,c,`remember`),{path:o}}async upsertAutoKnowledge(e,t,n,r,i=[],a=`Auto-knowledge refresh`){e=this.guardPath(e),this.validateCategoryName(r),this.validateContentSize(n),this.ensureCategoryPath(e,r);let o=this.normalizeTags(i),s=await this.adapter.read(e);if(s==null){let i=new Date().toISOString(),a={title:t,category:r,tags:o,created:i,updated:i,version:1,origin:`curated`,changelog:[{version:1,date:i,reason:`Initial creation`}]},s=this.serializeFile(n,a);try{await this.adapter.write(e,s,{exclusive:!0})}catch(t){throw t.code===`EEXIST`?Error(`Concurrent write collision for "${e}" — retry the operation`):t}return this.gitCommitKnowledge(e,s,`remember: ${t}\n\nCategory: ${r}\nTags: ${o.join(`, `)}`),await this.indexCuratedFileBestEffort(e,n,a,`remember`),{path:e,status:`created`,version:1}}let{frontmatter:c,content:l}=this.parseFile(s),u=this.normalizeTags(c.tags??[]),d=t.trim()||c.title;if(l===n&&c.category===r&&c.title===d&&this.sameTags(u,o))return{path:e,status:`unchanged`,version:c.version??1};let f=(c.version??1)+1,p=new Date().toISOString();c.title=d,c.category=r,c.tags=o,c.version=f,c.updated=p,c.changelog=[...c.changelog??[],{version:f,date:p,reason:a}];let m=this.serializeFile(n,c);return await this.adapter.write(e,m),this.gitCommitKnowledge(e,m,`update(v${f}): ${c.title}\n\nReason: ${a}\nVersion: ${f}`),await this.indexCuratedFileBestEffort(e,n,c,`update`),{path:e,status:`updated`,version:f}}async update(e,t,n){e=this.guardPath(e),this.validateContentSize(t);let r=await this.adapter.read(e);if(r==null)throw Error(`Curated entry not found: ${e}`);let{frontmatter:i}=this.parseFile(r),a=(i.version??1)+1,o=new Date().toISOString();i.version=a,i.updated=o,i.changelog=[...i.changelog??[],{version:a,date:o,reason:n}];let s=this.serializeFile(t,i);return await this.adapter.write(e,s),this.gitCommitKnowledge(e,s,`update(v${a}): ${i.title}\n\nReason: ${n}\nVersion: ${a}`),await this.indexCuratedFileBestEffort(e,t,i,`update`),{path:e,version:a}}async forget(e,t){if(e=this.guardPath(e),!await this.adapter.delete(e))throw Error(`Curated entry not found: ${e}`);let n=`.ai/curated/${e}`;return await this.store.deleteBySourcePath(n).catch(e=>{L.warn(`File deleted but vector cleanup failed`,{sourcePath:n,...p(e)})}),this.gitDeleteKnowledgeRef(e),{path:e}}async history(e,t=20){if(e=this.guardPath(e),!g(this.curatedDir))return[];let n=this.knowledgeRefForPath(e);if(!n)return[];let r=v([`log`,`--format=%H|%aI|%s`,n,`-n`,String(t)],this.curatedDir);return r?r.split(`
3
3
  `).filter(Boolean).map(e=>{let[t,n,...r]=e.split(`|`);return{sha:t,date:n,message:r.join(`|`)}}):[]}async diff(e,t,n){if(e=this.guardPath(e),!g(this.curatedDir))return``;if(!n){let r=await this.history(e,2);if(r.length===0)return``;n=r[0].sha,r.length>1&&!t&&(t=r[1].sha)}return t&&n?v([`diff`,`${t}:entry.md`,`${n}:entry.md`],this.curatedDir)??``:n?v([`show`,`${n}:entry.md`],this.curatedDir)??``:``}async recover(e){if(e=this.guardPath(e),await this.adapter.exists(e))throw Error(`Entry already exists on filesystem: ${e}. Use update() instead.`);if(!g(this.curatedDir))return null;let t=this.knowledgeRefForPath(e);if(!t)return null;let n=v([`show`,`${t}:entry.md`],this.curatedDir);if(!n)return null;await this.adapter.write(e,n);let{frontmatter:r,content:i}=this.parseFile(n);return await this.indexCuratedFile(e,i,r),{path:e,version:r.version??1}}async listOrphaned(){if(!g(this.curatedDir))return[];let e=v([`for-each-ref`,`--format=%(refname)|%(subject)`,`${I}/`],this.curatedDir);if(!e)return[];let t=[];for(let n of e.split(`
4
4
  `).filter(Boolean)){let[e,...r]=n.split(`|`),i=r.join(`|`),a=`${e.replace(`${I}/`,``)}.md`;await this.adapter.exists(a)||t.push({ref:e,path:a,lastMessage:i})}return t}async read(e){e=this.guardPath(e);let t=await this.adapter.read(e);if(t==null)throw Error(`Curated entry not found: ${e}`);let{frontmatter:n,content:r}=this.parseFile(t),i=e.split(`/`)[0];return{path:e,title:n.title??e,category:i,tags:n.tags??[],version:n.version??1,created:n.created??``,updated:n.updated??``,contentPreview:r.slice(0,200),content:r}}async list(e){let t=[],n=e?.category?[e.category]:await this.discoverCategories();for(let r of n){let n=await this.adapter.list(r);for(let i of n){let n=await this.adapter.read(i.path);if(n==null)continue;let{frontmatter:a,content:o}=this.parseFile(n);e?.tag&&!(a.tags??[]).includes(e.tag)||t.push({path:i.path,title:a.title??i.path,category:r,tags:a.tags??[],version:a.version??1,created:a.created??``,updated:a.updated??``,contentPreview:o.slice(0,200)})}}return t}async reindexAll(){let e=await this.discoverCategories(),t=[],n=[];for(let r of e){let e=await this.adapter.list(r);for(let r of e){let e=r.path;try{let r=await this.adapter.read(e);if(r==null){t.push(`${e}: read failed`);continue}let{frontmatter:i,content:a}=this.parseFile(r);n.push({relativePath:e,content:a,frontmatter:i})}catch(n){L.error(`Failed to read curated file`,{relativePath:e,...p(n)}),t.push(`${e}: read failed`)}}}if(n.length===0)return{indexed:0,errors:t};let r=new Date().toISOString(),i=0;for(let e=0;e<n.length;e+=16){let a=n.slice(e,e+16);i+=await this.embedAndUpsertBatch(a,r,t)}return{indexed:i,errors:t}}async embedAndUpsertBatch(e,t,n){try{let r=await this.embedder.embedBatch(e.map(e=>e.content)),i=e.map(e=>{let n=`.ai/curated/${e.relativePath}`;return{id:this.hashId(n,0),content:e.content,sourcePath:n,contentType:`curated-knowledge`,headingPath:e.frontmatter.title,chunkIndex:0,totalChunks:1,startLine:1,endLine:e.content.split(`
5
5
  `).length,fileHash:this.hash(e.content),indexedAt:t,origin:`curated`,tags:e.frontmatter.tags,category:e.frontmatter.category,version:e.frontmatter.version}});try{return await this.store.upsert(i,r),e.length}catch(t){L.error(`Failed to upsert curated batch`,{batchSize:e.length,...p(t)});for(let t of e)n.push(`${t.relativePath}: upsert failed`);return 0}}catch(r){if(e.length===1)return L.error(`Failed to embed curated item`,{relativePath:e[0].relativePath,...p(r)}),n.push(`${e[0].relativePath}: reindex failed`),0;L.warn(`Curated embed batch failed, retrying with smaller chunks`,{batchSize:e.length,...p(r)});let i=Math.ceil(e.length/2),a=e.slice(0,i),o=e.slice(i);return await this.embedAndUpsertBatch(a,t,n)+await this.embedAndUpsertBatch(o,t,n)}}gitCommitKnowledge(e,t,n){try{if(!g(this.curatedDir))return;let r=this.knowledgeRefForPath(e);if(!r)return;_(r,`entry.md`,t,n,this.curatedDir)}catch{}}gitDeleteKnowledgeRef(e){try{if(!g(this.curatedDir))return;let t=this.knowledgeRefForPath(e);if(!t)return;v([`update-ref`,`-d`,t],this.curatedDir)}catch{}}knowledgeRefForPath(e){let t=e.replace(/\.md$/,``).split(`/`).map(e=>y(e)).join(`/`);return t.split(`/`).every(e=>h.test(e))?`${I}/${t}`:null}async indexCuratedFile(e,t,n){let r=await this.embedder.embed(t),i=`.ai/curated/${e}`,a=new Date().toISOString(),o={id:this.hashId(i,0),content:t,sourcePath:i,contentType:`curated-knowledge`,headingPath:n.title,chunkIndex:0,totalChunks:1,startLine:1,endLine:t.split(`
6
- `).length,fileHash:this.hash(t),indexedAt:a,origin:`curated`,tags:n.tags,category:n.category,version:n.version};await this.store.upsert([o],[r])}async indexCuratedFileBestEffort(e,t,n,r){if(d.instance().isDegraded(`embedder`)){L.debug(`Skipping vector indexing — embedder degraded`,{relativePath:e,operation:r,subsystem:`embedder`});return}try{await this.indexCuratedFile(e,t,n)}catch(t){L.warn(`Curated file persisted but vector indexing deferred`,{relativePath:e,operation:r,...p(t)})}}async discoverCategories(){return this.adapter.listDirectories()}guardPath(e){let t=e.replace(/^\.ai\/curated\//,``);if(t.endsWith(`.md`)||(t+=`.md`),t.includes(`..`)||a(t))throw Error(`Invalid path: ${t}. Must be relative within .ai/curated/ directory.`);let n=t.split(`/`)[0];return this.validateCategoryName(n),t}validateCategoryName(e){if(!/^[a-z][a-z0-9-]*$/.test(e))throw Error(`Invalid category name: "${e}". Must be lowercase kebab-case (e.g., "decisions", "api-contracts").`)}validateContentSize(e){if(Buffer.byteLength(e,`utf-8`)>F)throw Error(`Content exceeds maximum size of ${F/1024}KB`)}slugify(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-|-$/g,``).slice(0,80)}async uniqueRelativePath(e,t){let n=`${e}/${t}.md`;if(!await this.adapter.exists(n))return n;for(let n=2;n<=100;n++){let r=`${e}/${t}-${n}.md`;if(!await this.adapter.exists(r))return r}throw Error(`Too many entries with slug "${t}" in category "${e}"`)}hash(e){return t(`sha256`).update(e).digest(`hex`).slice(0,16)}hashId(e,t){return this.hash(`${e}::${t}`)}serializeFile(e,t){return`${[`---`,`title: "${t.title.replace(/"/g,`\\"`)}"`,`category: ${t.category}`,`tags: [${t.tags.map(e=>`"${e}"`).join(`, `)}]`,`created: ${t.created}`,`updated: ${t.updated}`,`version: ${t.version}`,`origin: ${t.origin}`,`changelog:`,...t.changelog.map(e=>` - version: ${e.version}\n date: ${e.date}\n reason: "${e.reason.replace(/"/g,`\\"`)}"`),`---`].join(`
6
+ `).length,fileHash:this.hash(t),indexedAt:a,origin:`curated`,tags:n.tags,category:n.category,version:n.version};await this.store.upsert([o],[r])}async indexCuratedFileBestEffort(e,t,n,r){if(d.instance().isDegraded(`embedder`)){L.debug(`Skipping vector indexing — embedder degraded`,{relativePath:e,operation:r,subsystem:`embedder`});return}try{await this.indexCuratedFile(e,t,n)}catch(t){L.warn(`Curated file persisted but vector indexing deferred`,{relativePath:e,operation:r,...p(t)})}}async discoverCategories(){return this.adapter.listDirectories()}guardPath(e){let t=e.replace(/^\.ai\/curated\//,``);if(t.endsWith(`.md`)||(t+=`.md`),t.includes(`..`)||a(t))throw Error(`Invalid path: ${t}. Must be relative within .ai/curated/ directory.`);let n=t.split(`/`)[0];return this.validateCategoryName(n),t}validateCategoryName(e){if(!/^[a-z][a-z0-9-]*$/.test(e))throw Error(`Invalid category name: "${e}". Must be lowercase kebab-case (e.g., "decisions", "api-contracts").`)}validateContentSize(e){if(Buffer.byteLength(e,`utf-8`)>F)throw Error(`Content exceeds maximum size of ${F/1024}KB`)}slugify(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-|-$/g,``).slice(0,80)}normalizeTags(e){return[...new Set(e.map(e=>e.trim()).filter(Boolean))]}sameTags(e,t){if(e.length!==t.length)return!1;let n=new Set(e);return t.every(e=>n.has(e))}ensureCategoryPath(e,t){if(!e.startsWith(`${t}/`))throw Error(`Curated path "${e}" must stay within category "${t}"`)}async uniqueRelativePath(e,t){let n=`${e}/${t}.md`;if(!await this.adapter.exists(n))return n;for(let n=2;n<=100;n++){let r=`${e}/${t}-${n}.md`;if(!await this.adapter.exists(r))return r}throw Error(`Too many entries with slug "${t}" in category "${e}"`)}hash(e){return t(`sha256`).update(e).digest(`hex`).slice(0,16)}hashId(e,t){return this.hash(`${e}::${t}`)}serializeFile(e,t){return`${[`---`,`title: "${t.title.replace(/"/g,`\\"`)}"`,`category: ${t.category}`,`tags: [${t.tags.map(e=>`"${e}"`).join(`, `)}]`,`created: ${t.created}`,`updated: ${t.updated}`,`version: ${t.version}`,`origin: ${t.origin}`,`changelog:`,...t.changelog.map(e=>` - version: ${e.version}\n date: ${e.date}\n reason: "${e.reason.replace(/"/g,`\\"`)}"`),`---`].join(`
7
7
  `)}\n\n${e}\n`}parseFile(e){let t=e.match(/^---\n([\s\S]*?)\n---\n\n?([\s\S]*)$/);if(!t)return{frontmatter:{title:`Untitled`,category:`notes`,tags:[],created:``,updated:``,version:1,origin:`curated`,changelog:[]},content:e};let n=t[1],r=t[2].trim(),i={},a=[],o=n.split(`
8
- `),s=!1,c={};for(let e of o){if(/^changelog:\s*$/.test(e)){s=!0;continue}if(s){let t=e.match(/^\s+-\s+version:\s*(\d+)$/);if(t){c.version!=null&&a.push(c),c={version:parseInt(t[1],10)};continue}let n=e.match(/^\s+date:\s*(.+)$/);if(n){c.date=n[1].trim();continue}let r=e.match(/^\s+reason:\s*"?(.*?)"?\s*$/);if(r){c.reason=r[1];continue}/^\w/.test(e)&&(s=!1,c.version!=null&&a.push(c),c={});continue}let t=e.match(/^(\w+):\s*(.*)$/);if(t){let e=t[1],n=t[2];typeof n==`string`&&n.startsWith(`[`)&&n.endsWith(`]`)?n=n.slice(1,-1).split(`,`).map(e=>e.trim().replace(/^"|"$/g,``)).filter(e=>e.length>0):typeof n==`string`&&/^\d+$/.test(n)?n=parseInt(n,10):typeof n==`string`&&n.startsWith(`"`)&&n.endsWith(`"`)&&(n=n.slice(1,-1)),i[e]=n}}return c.version!=null&&a.push(c),{frontmatter:{title:i.title??`Untitled`,category:i.category??`notes`,tags:i.tags??[],created:i.created??``,updated:i.updated??``,version:i.version??1,origin:`curated`,changelog:a},content:r}}};function z(){try{let e=s(i(c(import.meta.url)),`..`,`..`,`..`,`package.json`);return JSON.parse(r(e,`utf-8`)).version??`0.0.0`}catch{return`0.0.0`}}const B=f(`server`);function V(e,t){return t?{version:e,...p(t)}:{version:e}}const H=/^https?:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/i;function ee({requestOrigin:e,configuredOrigin:t,allowAnyOrigin:n,fallbackOrigin:r}){let i=t??r;return i===`*`?n?{allowOrigin:`*`,warn:!1}:e?H.test(e)?{allowOrigin:e,warn:!1}:{allowOrigin:null,warn:!0}:{allowOrigin:r,warn:!1}:{allowOrigin:i,warn:!1}}function U({limit:e,windowMs:t}){let n=new Map,r=(e,r)=>{let i=r-t,a=n.get(e)?.filter(e=>e>i)??[];return a.length===0?(n.delete(e),[]):(n.set(e,a),a)};return{allow(t,i=Date.now()){let a=r(t,i);return a.length>=e?!1:(a.push(i),n.set(t,a),!0)},getRetryAfterMs(n,i=Date.now()){let a=r(n,i);return a.length<e?0:Math.max(0,a[0]+t-i)}}}function W(e){return e.startsWith(`file://`)?c(e):e}function G(e){let t=s(e);return process.platform===`win32`?t.toLowerCase():t}function K(e){let t=new Map;for(let n of e){let e=W(n.uri);t.set(G(e),e)}return[...t.values()].sort((e,t)=>G(e).localeCompare(G(t)))}function q({config:e,roots:t}){let n=K(t);if(n.length===0)return null;let r=e.sources?.[0]?.path;if(r){let e=G(r),t=n.find(t=>G(t)===e);if(t)return t}return n[0]}function J({config:e,log:t,reconfigureForWorkspace:n,roots:r}){let i=K(r);if(i.length===0)return!1;let a=q({config:e,roots:i.map(e=>({uri:e}))});if(!a)return!1;let o=e.sources?.[0]?.path,s=o&&G(o)===G(a)?`configured-source`:`stable-sorted-root`;return t.debug(`MCP roots resolved`,{rootPath:a,rootCount:i.length,selectedBy:s}),n(e,a),e.allRoots=i,!0}async function Y({config:e,indexMode:t,log:n,rootsChangedNotificationSchema:r,reconfigureForWorkspace:i,runInitialIndex:a,server:o,startInit:s,timeoutMs:c=5e3,getCwd:l=()=>process.cwd()}){let u=z(),d=!1,f=!1,m,h=o.server,g=e=>{let t=p(e),n=`${String(e)} ${String(t.message??``)}`.toLowerCase();return n.includes(`method not found`)||n.includes(`not supported`)||n.includes(`unsupported`)||n.includes(`unknown method`)||n.includes(`roots/list`)},_=()=>{d||(d=!0,s())},v=()=>{f||t!==`auto`||(f=!0,(async()=>{try{await a()}catch(e){n.error(`Initial index failed`,V(u,e))}})())},y=t=>t.length===0||(m&&=(clearTimeout(m),void 0),!J({config:e,log:n,reconfigureForWorkspace:i,roots:t}))?!1:(_(),v(),!0);try{if(y((await h.listRoots()).roots))return;n.debug(`No MCP roots yet; waiting for roots/list_changed notification`)}catch(e){if(g(e)){n.warn(`MCP roots/list not supported by client; using cwd fallback`,{version:u,cwd:l(),...p(e)}),_(),v();return}n.warn(`MCP roots/list failed during bootstrap; waiting for roots/list_changed notification`,{version:u,cwd:l(),...p(e)})}h.setNotificationHandler(r,async()=>{try{y((await h.listRoots()).roots)}catch(e){n.warn(`roots/list retry failed after notification`,V(u,e))}}),m=setTimeout(()=>{let t=l();n.debug(`Timed out waiting for MCP roots/list_changed; falling back to cwd workspace`,{cwd:t}),J({config:e,log:n,reconfigureForWorkspace:i,roots:[{uri:t}]})&&(_(),v())},c)}function X(){return process.env.AIKIT_TRANSPORT?process.env.AIKIT_TRANSPORT:process.stdin.isTTY?`http`:`stdio`}function Z(){let e=process.argv[1];if(!e)return!1;try{return import.meta.url===l(e).href}catch{return!1}}function Q(e){let t=e.headers[`mcp-session-id`];return Array.isArray(t)?t[0]:t}function $(e,t){let n=process.env[e];if(!n)return t;let r=Number.parseInt(n,10);return Number.isFinite(r)&&r>0?r:t}function te(){return Z()?u({allowPositionals:!0,options:{transport:{type:`string`,default:X()},port:{type:`string`,default:process.env.AIKIT_PORT??`3210`}}}).values:{transport:X(),port:process.env.AIKIT_PORT??`3210`}}async function ne(){let e=z(),t=te();process.on(`unhandledRejection`,t=>{B.error(`Unhandled rejection`,V(e,t))}),process.on(`uncaughtException`,t=>{B.error(`Uncaught exception — exiting`,V(e,t)),process.exit(1)});let r=(t,n)=>{t.then(async()=>{try{let{markPromoteRun:e,markPruneRun:t,prune:r,shouldRunStartupPrune:i,shouldRunWeeklyPromote:a}=await import(`../../tools/dist/index.js`),o=n();if(!o)return;if(i()){let e=await r({});t(),e.totalBytesFreed>0&&B.info(`Storage maintenance complete`,{forgeOrphans:e.forgeGroundOrphans.count,legacyLance:e.legacyLance.count,bytesFreed:e.totalBytesFreed});let{groupLessons:n,pruneLessons:i}=await import(`./evolution-DWaEE6XW.js`).then(e=>e.t),a=await i(o.curated,o.stateStore,{dryRun:!1});a.pruned.length>0&&B.info(`Startup lesson prune complete`,{pruned:a.pruned.length});let s=await n(o.curated,o.stateStore,{dryRun:!1});(s.groupsCreated>0||s.lessonsGrouped>0)&&B.info(`Startup lesson grouping complete`,{groupsCreated:s.groupsCreated,lessonsGrouped:s.lessonsGrouped})}if(a()){let{DEFAULT_PROMOTE_CONFIG:t,collectWorkspaceLessons:n,getGlobalCuratedDir:r,promoteLessons:i,scanForDuplicates:a}=await import(`./promotion-CJFYv4Ye.js`).then(e=>e.o),{CuratedKnowledgeManager:s}=await Promise.resolve().then(()=>P),c=o.curated,l=new s(r(),c.store,c.embedder),u=await n(),d={...t,dryRun:!1},f=await i(a(u,d),l,d);e(),f.promoted.length>0&&B.info(`Weekly lesson promotion complete`,{promoted:f.promoted.length,candidates:f.candidates.length})}}catch(t){B.warn(`Startup maintenance failed (non-critical)`,V(e,t))}}).catch(()=>{})};if(B.info(`Starting MCP AI Kit server`,{version:e}),t.transport===`http`){let[{default:i},{loadConfig:a,resolveIndexMode:o},{registerDashboardRoutes:s,resolveDashboardDir:c},{registerSettingsRoutes:l,resolveSettingsDir:u},{createSettingsRouter:d},{authMiddleware:f,getOrCreateToken:h}]=await Promise.all([import(`express`),import(`./config-WpN5CWM7.js`),import(`./dashboard-static-CRfR1yKU.js`),import(`./settings-static-B3lnYvcb.js`),import(`./routes-Afg7J7xK.js`),import(`./auth-lzZKfxlV.js`)]),g=a();m(g.logging?.errorDetails===!0),B.info(`Config loaded`,{sourceCount:g.sources.length,storePath:g.store.path});let _=i();_.use(i.json({limit:`1mb`}));let v=Number(t.port),y=`http://localhost:${v}`,b=process.env.AIKIT_CORS_ORIGIN??y,x=process.env.AIKIT_ALLOW_ANY_ORIGIN===`true`,S=$(`AIKIT_HTTP_MAX_SESSIONS`,8),C=$(`AIKIT_HTTP_SESSION_TIMEOUT_MINUTES`,30),w=$(`AIKIT_HTTP_SESSION_GC_INTERVAL_MINUTES`,5),T=U({limit:100,windowMs:6e4}),E=!1;_.use((e,t,n)=>{let r=Array.isArray(e.headers.origin)?e.headers.origin[0]:e.headers.origin,i=ee({requestOrigin:r,configuredOrigin:b,allowAnyOrigin:x,fallbackOrigin:y});if(i.warn&&!E&&(E=!0,B.warn(`Rejected non-local CORS origin while AIKIT_CORS_ORIGIN=*`,{origin:r,allowAnyOriginEnv:`AIKIT_ALLOW_ANY_ORIGIN=true`})),r&&!i.allowOrigin){t.status(403).json({error:`Origin not allowed`});return}if(i.allowOrigin&&t.setHeader(`Access-Control-Allow-Origin`,i.allowOrigin),t.setHeader(`Access-Control-Allow-Methods`,`GET, POST, PUT, PATCH, DELETE, OPTIONS`),t.setHeader(`Access-Control-Allow-Headers`,`Content-Type, Authorization, Mcp-Session-Id, Mcp-Protocol-Version, Last-Event-ID`),t.setHeader(`Access-Control-Expose-Headers`,`Mcp-Session-Id`),e.method===`OPTIONS`){t.status(204).end();return}n()});let D=h();console.error(`[aikit] Auth token: ~/.aikit/token`),_.use(f(D)),_.use(`/mcp`,(e,t,n)=>{let r=Q(e)??e.ip??e.socket.remoteAddress??`anonymous`;if(T.allow(r)){n();return}let i=Math.max(1,Math.ceil(T.getRetryAfterMs(r)/1e3));t.setHeader(`Retry-After`,String(i)),t.status(429).json({jsonrpc:`2.0`,error:{code:-32003,message:`Rate limit exceeded`},id:null})}),s(_,c(),B);let O=new Date().toISOString();_.use(`/settings/api`,d({log:B,mcpInfo:()=>({transport:`http`,port:v,pid:process.pid,startedAt:O})})),l(_,u(),B),_.get(`/health`,(e,t)=>{t.json({status:`ok`})});let k=!1,j=null,N=null,P=null,F=null,I=null,L=null,R=null,z=Promise.resolve(),H=async(e,t)=>{if(!k||!P||!F){t.status(503).json({jsonrpc:`2.0`,error:{code:-32603,message:`Server initializing — please retry in a few seconds`},id:null});return}let r=z,i;z=new Promise(e=>{i=e}),await r;try{let r=Q(e);if(!L){if(r){t.status(404).json({jsonrpc:`2.0`,error:{code:-32001,message:`Session not found`},id:null});return}let e=new F({sessionIdGenerator:()=>n(),onsessioninitialized:async e=>{R=e,N?.onSessionStart(e,{transport:`http`})},onsessionclosed:async e=>{e&&N?.onSessionEnd(e),R=null}});e.onclose=()=>{L===e&&(L=null),R===e.sessionId&&(R=null)},L=e,await P.connect(e)}let i=L;await i.handleRequest(e,t,e.body),e.method!==`DELETE`&&(!r&&i.sessionId?(R=i.sessionId,N?.onSessionStart(i.sessionId,{transport:`http`}),N?.onSessionActivity(i.sessionId)):r&&N?.onSessionActivity(r))}catch(e){if(B.error(`MCP handler error`,p(e)),!t.headersSent){let n=e instanceof Error?e.message:String(e),r=n.includes(`Not Acceptable`);t.status(r?406:500).json({jsonrpc:`2.0`,error:{code:r?-32e3:-32603,message:r?n:`Internal server error`},id:null})}}finally{i()}},W=async(e,t)=>{let n=Q(e);if(I&&(!L||n!==R)){await I.handleRequest(e,t,e.body);return}await H(e,t)};_.post(`/mcp`,W),_.get(`/mcp`,W),_.delete(`/mcp`,W);let G=_.listen(v,`127.0.0.1`,()=>{B.info(`MCP server listening`,{url:`http://127.0.0.1:${v}/mcp`,port:v}),setTimeout(async()=>{try{let[{createLazyServer:t,createMcpServer:n,ALL_TOOL_NAMES:i},{StreamableHTTPServerTransport:a},{checkForUpdates:s,autoUpgradeScaffold:c}]=await Promise.all([import(`./server-CIPdEf8F.js`),import(`@modelcontextprotocol/sdk/server/streamableHttp.js`),import(`./version-check-gazMo-D4.js`)]);s(),c();let l=o(g),u=t(g,l);P=u.server,F=a,k=!0,B.debug(`MCP server configured (lazy — AI Kit initializing in background)`,{toolCount:i.length,resourceCount:2}),u.startInit(),u.ready.then(()=>{if(!u.aikit)throw Error(`AI Kit components are not available after initialization`);N=new M(u.aikit.stateStore,{staleTimeoutMinutes:C,gcIntervalMinutes:w,onBeforeSessionDelete:e=>{if(R===e&&L){let e=L;L=null,R=null,e.close().catch(()=>void 0)}I?.closeSession(e,{notifySessionEnd:!1})},onSessionEndMaintenance:async()=>{if(!u.aikit?.curated||!u.aikit?.stateStore)return;let{pruneLessons:e}=await import(`./evolution-DWaEE6XW.js`).then(e=>e.t),t=await e(u.aikit.curated,u.aikit.stateStore,{dryRun:!1});t.pruned.length>0&&B.info(`Session-end lesson prune`,{pruned:t.pruned.length})}}),I=new A({createServer:()=>{if(!u.aikit)throw Error(`AI Kit components are not available after initialization`);return n(u.aikit,g)},createTransport:e=>new a(e),maxSessions:S,sessionTimeoutMinutes:C,onSessionStart:e=>N?.onSessionStart(e,{transport:`http`}),onSessionActivity:e=>N?.onSessionActivity(e),onSessionEnd:e=>N?.onSessionEnd(e)}),N.startGC(),R&&(N.onSessionStart(R,{transport:`http`}),N.onSessionActivity(R)),B.info(`HTTP session runtime ready`,{maxSessions:S,sessionTimeoutMinutes:C,gcIntervalMinutes:w})}).catch(e=>B.error(`Failed to start session manager`,p(e))),l===`auto`?u.ready.then(async()=>{try{let e=g.sources.map(e=>e.path).join(`, `);B.info(`Running initial index`,{sourcePaths:e}),await u.runInitialIndex(),B.info(`Initial index complete`)}catch(t){B.error(`Initial index failed; will retry on aikit_reindex`,V(e,t))}}).catch(t=>B.error(`AI Kit init or indexing failed`,V(e,t))):l===`smart`?u.ready.then(async()=>{try{if(!u.aikit)throw Error(`AI Kit components are not available after initialization`);let{SmartIndexScheduler:e}=await import(`../../indexer/dist/index.js`),t=new e(u.aikit.indexer,g,u.aikit.store),n=u.aikit.store;j=t,t.start(),n.onBeforeClose&&n.onBeforeClose(()=>t.stop()),u.setSmartScheduler(t),B.debug(`Smart index scheduler started (HTTP mode)`)}catch(t){B.error(`Failed to start smart index scheduler`,V(e,t))}}).catch(t=>B.error(`AI Kit initialization failed`,V(e,t))):(u.ready.catch(t=>B.error(`AI Kit initialization failed`,V(e,t))),B.info(`Initial full indexing skipped in HTTP mode`,{indexMode:l})),r(u.ready,()=>u.aikit?{curated:u.aikit.curated,stateStore:u.aikit.stateStore}:null)}catch(t){B.error(`Failed to load server modules`,V(e,t))}},100)}),K=async e=>{B.info(`Shutdown signal received`,{signal:e}),j?.stop(),N?.stop(),await I?.closeAll().catch(()=>void 0),R&&N?.onSessionEnd(R),L&&(await L.close().catch(()=>void 0),L=null,R=null),G.close(),P&&await P.close(),process.exit(0)};process.on(`SIGINT`,()=>K(`SIGINT`)),process.on(`SIGTERM`,()=>K(`SIGTERM`))}else{let[{loadConfig:t,reconfigureForWorkspace:n,resolveIndexMode:i},{createLazyServer:a},{checkForUpdates:o,autoUpgradeScaffold:s},{RootsListChangedNotificationSchema:c}]=await Promise.all([import(`./config-WpN5CWM7.js`),import(`./server-CIPdEf8F.js`),import(`./version-check-gazMo-D4.js`),import(`@modelcontextprotocol/sdk/types.js`)]),l=t();m(l.logging?.errorDetails===!0),B.info(`Config loaded`,{sourceCount:l.sources.length,storePath:l.store.path}),o(),s();let u=i(l),d=a(l,u),{server:f,startInit:p,ready:h,runInitialIndex:g}=d,{StdioServerTransport:_}=await import(`@modelcontextprotocol/sdk/server/stdio.js`),v=new _;await f.connect(v),B.debug(`MCP server started`,{transport:`stdio`}),await Y({config:l,indexMode:u,log:B,rootsChangedNotificationSchema:c,reconfigureForWorkspace:n,runInitialIndex:g,server:f,startInit:p});let y=null,b=()=>{y&&clearTimeout(y),y=setTimeout(async()=>{B.info(`Auto-shutdown: no activity for 30 minutes — shutting down gracefully`);try{let e=d.aikit;e&&await Promise.all([e.embedder.shutdown?.().catch(()=>{})??Promise.resolve(),e.graphStore.close().catch(()=>{}),e.store.close().catch(()=>{})])}catch{}process.exit(0)},18e5),y.unref&&y.unref()};b(),process.stdin.on(`data`,()=>b()),h.catch(t=>{B.error(`Initialization failed — server will continue with limited tools`,V(e,t))}),u===`smart`?h.then(async()=>{try{if(!d.aikit)throw Error(`AI Kit components are not available after initialization`);let{SmartIndexScheduler:e}=await import(`../../indexer/dist/index.js`),t=new e(d.aikit.indexer,l,d.aikit.store),n=d.aikit.store;t.start(),n.onBeforeClose&&n.onBeforeClose(()=>t.stop()),d.setSmartScheduler(t),B.debug(`Smart index scheduler started (stdio mode)`)}catch(t){B.error(`Failed to start smart index scheduler`,V(e,t))}}).catch(t=>B.error(`AI Kit init failed for smart scheduler`,V(e,t))):B.warn(`Initial full indexing skipped; use aikit_reindex to index manually`,{indexMode:u}),r(h,()=>d.aikit?{curated:d.aikit.curated,stateStore:d.aikit.stateStore}:null)}}ne();export{N as n,R as t};
8
+ `),s=!1,c={};for(let e of o){if(/^changelog:\s*$/.test(e)){s=!0;continue}if(s){let t=e.match(/^\s+-\s+version:\s*(\d+)$/);if(t){c.version!=null&&a.push(c),c={version:parseInt(t[1],10)};continue}let n=e.match(/^\s+date:\s*(.+)$/);if(n){c.date=n[1].trim();continue}let r=e.match(/^\s+reason:\s*"?(.*?)"?\s*$/);if(r){c.reason=r[1];continue}/^\w/.test(e)&&(s=!1,c.version!=null&&a.push(c),c={});continue}let t=e.match(/^(\w+):\s*(.*)$/);if(t){let e=t[1],n=t[2];typeof n==`string`&&n.startsWith(`[`)&&n.endsWith(`]`)?n=n.slice(1,-1).split(`,`).map(e=>e.trim().replace(/^"|"$/g,``)).filter(e=>e.length>0):typeof n==`string`&&/^\d+$/.test(n)?n=parseInt(n,10):typeof n==`string`&&n.startsWith(`"`)&&n.endsWith(`"`)&&(n=n.slice(1,-1)),i[e]=n}}return c.version!=null&&a.push(c),{frontmatter:{title:i.title??`Untitled`,category:i.category??`notes`,tags:i.tags??[],created:i.created??``,updated:i.updated??``,version:i.version??1,origin:`curated`,changelog:a},content:r}}};function z(){try{let e=s(i(c(import.meta.url)),`..`,`..`,`..`,`package.json`);return JSON.parse(r(e,`utf-8`)).version??`0.0.0`}catch{return`0.0.0`}}const B=f(`server`);function V(e,t){return t?{version:e,...p(t)}:{version:e}}const H=/^https?:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/i;function ee({requestOrigin:e,configuredOrigin:t,allowAnyOrigin:n,fallbackOrigin:r}){let i=t??r;return i===`*`?n?{allowOrigin:`*`,warn:!1}:e?H.test(e)?{allowOrigin:e,warn:!1}:{allowOrigin:null,warn:!0}:{allowOrigin:r,warn:!1}:{allowOrigin:i,warn:!1}}function U({limit:e,windowMs:t}){let n=new Map,r=(e,r)=>{let i=r-t,a=n.get(e)?.filter(e=>e>i)??[];return a.length===0?(n.delete(e),[]):(n.set(e,a),a)};return{allow(t,i=Date.now()){let a=r(t,i);return a.length>=e?!1:(a.push(i),n.set(t,a),!0)},getRetryAfterMs(n,i=Date.now()){let a=r(n,i);return a.length<e?0:Math.max(0,a[0]+t-i)}}}function W(e){return e.startsWith(`file://`)?c(e):e}function G(e){let t=s(e);return process.platform===`win32`?t.toLowerCase():t}function K(e){let t=new Map;for(let n of e){let e=W(n.uri);t.set(G(e),e)}return[...t.values()].sort((e,t)=>G(e).localeCompare(G(t)))}function q({config:e,roots:t}){let n=K(t);if(n.length===0)return null;let r=e.sources?.[0]?.path;if(r){let e=G(r),t=n.find(t=>G(t)===e);if(t)return t}return n[0]}function J({config:e,log:t,reconfigureForWorkspace:n,roots:r}){let i=K(r);if(i.length===0)return!1;let a=q({config:e,roots:i.map(e=>({uri:e}))});if(!a)return!1;let o=e.sources?.[0]?.path,s=o&&G(o)===G(a)?`configured-source`:`stable-sorted-root`;return t.debug(`MCP roots resolved`,{rootPath:a,rootCount:i.length,selectedBy:s}),n(e,a),e.allRoots=i,!0}async function Y({config:e,indexMode:t,log:n,rootsChangedNotificationSchema:r,reconfigureForWorkspace:i,runInitialIndex:a,server:o,startInit:s,timeoutMs:c=5e3,getCwd:l=()=>process.cwd()}){let u=z(),d=!1,f=!1,m,h=o.server,g=e=>{let t=p(e),n=`${String(e)} ${String(t.message??``)}`.toLowerCase();return n.includes(`method not found`)||n.includes(`not supported`)||n.includes(`unsupported`)||n.includes(`unknown method`)||n.includes(`roots/list`)},_=()=>{d||(d=!0,s())},v=()=>{f||t!==`auto`||(f=!0,(async()=>{try{await a()}catch(e){n.error(`Initial index failed`,V(u,e))}})())},y=t=>t.length===0||(m&&=(clearTimeout(m),void 0),!J({config:e,log:n,reconfigureForWorkspace:i,roots:t}))?!1:(_(),v(),!0);try{if(y((await h.listRoots()).roots))return;n.debug(`No MCP roots yet; waiting for roots/list_changed notification`)}catch(e){if(g(e)){n.warn(`MCP roots/list not supported by client; using cwd fallback`,{version:u,cwd:l(),...p(e)}),_(),v();return}n.warn(`MCP roots/list failed during bootstrap; waiting for roots/list_changed notification`,{version:u,cwd:l(),...p(e)})}h.setNotificationHandler(r,async()=>{try{y((await h.listRoots()).roots)}catch(e){n.warn(`roots/list retry failed after notification`,V(u,e))}}),m=setTimeout(()=>{let t=l();n.debug(`Timed out waiting for MCP roots/list_changed; falling back to cwd workspace`,{cwd:t}),J({config:e,log:n,reconfigureForWorkspace:i,roots:[{uri:t}]})&&(_(),v())},c)}function X(){return process.env.AIKIT_TRANSPORT?process.env.AIKIT_TRANSPORT:process.stdin.isTTY?`http`:`stdio`}function Z(){let e=process.argv[1];if(!e)return!1;try{return import.meta.url===l(e).href}catch{return!1}}function Q(e){let t=e.headers[`mcp-session-id`];return Array.isArray(t)?t[0]:t}function $(e,t){let n=process.env[e];if(!n)return t;let r=Number.parseInt(n,10);return Number.isFinite(r)&&r>0?r:t}function te(){return Z()?u({allowPositionals:!0,options:{transport:{type:`string`,default:X()},port:{type:`string`,default:process.env.AIKIT_PORT??`3210`}}}).values:{transport:X(),port:process.env.AIKIT_PORT??`3210`}}async function ne(){let e=z(),t=te();process.on(`unhandledRejection`,t=>{B.error(`Unhandled rejection`,V(e,t))}),process.on(`uncaughtException`,t=>{B.error(`Uncaught exception — exiting`,V(e,t)),process.exit(1)});let r=(t,n)=>{t.then(async()=>{try{let{markPromoteRun:e,markPruneRun:t,prune:r,shouldRunStartupPrune:i,shouldRunWeeklyPromote:a}=await import(`../../tools/dist/index.js`),o=n();if(!o)return;if(i()){let e=await r({});t(),e.totalBytesFreed>0&&B.info(`Storage maintenance complete`,{forgeOrphans:e.forgeGroundOrphans.count,legacyLance:e.legacyLance.count,bytesFreed:e.totalBytesFreed});let{groupLessons:n,pruneLessons:i}=await import(`./evolution-DWaEE6XW.js`).then(e=>e.t),a=await i(o.curated,o.stateStore,{dryRun:!1});a.pruned.length>0&&B.info(`Startup lesson prune complete`,{pruned:a.pruned.length});let s=await n(o.curated,o.stateStore,{dryRun:!1});(s.groupsCreated>0||s.lessonsGrouped>0)&&B.info(`Startup lesson grouping complete`,{groupsCreated:s.groupsCreated,lessonsGrouped:s.lessonsGrouped})}if(a()){let{DEFAULT_PROMOTE_CONFIG:t,collectWorkspaceLessons:n,getGlobalCuratedDir:r,promoteLessons:i,scanForDuplicates:a}=await import(`./promotion-CJFYv4Ye.js`).then(e=>e.o),{CuratedKnowledgeManager:s}=await Promise.resolve().then(()=>P),c=o.curated,l=new s(r(),c.store,c.embedder),u=await n(),d={...t,dryRun:!1},f=await i(a(u,d),l,d);e(),f.promoted.length>0&&B.info(`Weekly lesson promotion complete`,{promoted:f.promoted.length,candidates:f.candidates.length})}}catch(t){B.warn(`Startup maintenance failed (non-critical)`,V(e,t))}}).catch(()=>{})};if(B.info(`Starting MCP AI Kit server`,{version:e}),t.transport===`http`){let[{default:i},{loadConfig:a,resolveIndexMode:o},{registerDashboardRoutes:s,resolveDashboardDir:c},{registerSettingsRoutes:l,resolveSettingsDir:u},{createSettingsRouter:d},{authMiddleware:f,getOrCreateToken:h}]=await Promise.all([import(`express`),import(`./config-WpN5CWM7.js`),import(`./dashboard-static-CRfR1yKU.js`),import(`./settings-static-B3lnYvcb.js`),import(`./routes-Afg7J7xK.js`),import(`./auth-lzZKfxlV.js`)]),g=a();m(g.logging?.errorDetails===!0),B.info(`Config loaded`,{sourceCount:g.sources.length,storePath:g.store.path});let _=i();_.use(i.json({limit:`1mb`}));let v=Number(t.port),y=`http://localhost:${v}`,b=process.env.AIKIT_CORS_ORIGIN??y,x=process.env.AIKIT_ALLOW_ANY_ORIGIN===`true`,S=$(`AIKIT_HTTP_MAX_SESSIONS`,8),C=$(`AIKIT_HTTP_SESSION_TIMEOUT_MINUTES`,30),w=$(`AIKIT_HTTP_SESSION_GC_INTERVAL_MINUTES`,5),T=U({limit:100,windowMs:6e4}),E=!1;_.use((e,t,n)=>{let r=Array.isArray(e.headers.origin)?e.headers.origin[0]:e.headers.origin,i=ee({requestOrigin:r,configuredOrigin:b,allowAnyOrigin:x,fallbackOrigin:y});if(i.warn&&!E&&(E=!0,B.warn(`Rejected non-local CORS origin while AIKIT_CORS_ORIGIN=*`,{origin:r,allowAnyOriginEnv:`AIKIT_ALLOW_ANY_ORIGIN=true`})),r&&!i.allowOrigin){t.status(403).json({error:`Origin not allowed`});return}if(i.allowOrigin&&t.setHeader(`Access-Control-Allow-Origin`,i.allowOrigin),t.setHeader(`Access-Control-Allow-Methods`,`GET, POST, PUT, PATCH, DELETE, OPTIONS`),t.setHeader(`Access-Control-Allow-Headers`,`Content-Type, Authorization, Mcp-Session-Id, Mcp-Protocol-Version, Last-Event-ID`),t.setHeader(`Access-Control-Expose-Headers`,`Mcp-Session-Id`),e.method===`OPTIONS`){t.status(204).end();return}n()});let D=h();console.error(`[aikit] Auth token: ~/.aikit/token`),_.use(f(D)),_.use(`/mcp`,(e,t,n)=>{let r=Q(e)??e.ip??e.socket.remoteAddress??`anonymous`;if(T.allow(r)){n();return}let i=Math.max(1,Math.ceil(T.getRetryAfterMs(r)/1e3));t.setHeader(`Retry-After`,String(i)),t.status(429).json({jsonrpc:`2.0`,error:{code:-32003,message:`Rate limit exceeded`},id:null})}),s(_,c(),B);let O=new Date().toISOString();_.use(`/settings/api`,d({log:B,mcpInfo:()=>({transport:`http`,port:v,pid:process.pid,startedAt:O})})),l(_,u(),B),_.get(`/health`,(e,t)=>{t.json({status:`ok`})});let k=!1,j=null,N=null,P=null,F=null,I=null,L=null,R=null,z=Promise.resolve(),H=async(e,t)=>{if(!k||!P||!F){t.status(503).json({jsonrpc:`2.0`,error:{code:-32603,message:`Server initializing — please retry in a few seconds`},id:null});return}let r=z,i;z=new Promise(e=>{i=e}),await r;try{let r=Q(e);if(!L){if(r){t.status(404).json({jsonrpc:`2.0`,error:{code:-32001,message:`Session not found`},id:null});return}let e=new F({sessionIdGenerator:()=>n(),onsessioninitialized:async e=>{R=e,N?.onSessionStart(e,{transport:`http`})},onsessionclosed:async e=>{e&&N?.onSessionEnd(e),R=null}});e.onclose=()=>{L===e&&(L=null),R===e.sessionId&&(R=null)},L=e,await P.connect(e)}let i=L;await i.handleRequest(e,t,e.body),e.method!==`DELETE`&&(!r&&i.sessionId?(R=i.sessionId,N?.onSessionStart(i.sessionId,{transport:`http`}),N?.onSessionActivity(i.sessionId)):r&&N?.onSessionActivity(r))}catch(e){if(B.error(`MCP handler error`,p(e)),!t.headersSent){let n=e instanceof Error?e.message:String(e),r=n.includes(`Not Acceptable`);t.status(r?406:500).json({jsonrpc:`2.0`,error:{code:r?-32e3:-32603,message:r?n:`Internal server error`},id:null})}}finally{i()}},W=async(e,t)=>{let n=Q(e);if(I&&(!L||n!==R)){await I.handleRequest(e,t,e.body);return}await H(e,t)};_.post(`/mcp`,W),_.get(`/mcp`,W),_.delete(`/mcp`,W);let G=_.listen(v,`127.0.0.1`,()=>{B.info(`MCP server listening`,{url:`http://127.0.0.1:${v}/mcp`,port:v}),setTimeout(async()=>{try{let[{createLazyServer:t,createMcpServer:n,ALL_TOOL_NAMES:i},{StreamableHTTPServerTransport:a},{checkForUpdates:s,autoUpgradeScaffold:c}]=await Promise.all([import(`./server-4h0Cclv3.js`),import(`@modelcontextprotocol/sdk/server/streamableHttp.js`),import(`./version-check-gazMo-D4.js`)]);s(),c();let l=o(g),u=t(g,l);P=u.server,F=a,k=!0,B.debug(`MCP server configured (lazy — AI Kit initializing in background)`,{toolCount:i.length,resourceCount:2}),u.startInit(),u.ready.then(()=>{if(!u.aikit)throw Error(`AI Kit components are not available after initialization`);N=new M(u.aikit.stateStore,{staleTimeoutMinutes:C,gcIntervalMinutes:w,onBeforeSessionDelete:e=>{if(R===e&&L){let e=L;L=null,R=null,e.close().catch(()=>void 0)}I?.closeSession(e,{notifySessionEnd:!1})},onSessionEndMaintenance:async()=>{if(!u.aikit?.curated||!u.aikit?.stateStore)return;let{pruneLessons:e}=await import(`./evolution-DWaEE6XW.js`).then(e=>e.t),t=await e(u.aikit.curated,u.aikit.stateStore,{dryRun:!1});t.pruned.length>0&&B.info(`Session-end lesson prune`,{pruned:t.pruned.length})}}),I=new A({createServer:()=>{if(!u.aikit)throw Error(`AI Kit components are not available after initialization`);return n(u.aikit,g)},createTransport:e=>new a(e),maxSessions:S,sessionTimeoutMinutes:C,onSessionStart:e=>N?.onSessionStart(e,{transport:`http`}),onSessionActivity:e=>N?.onSessionActivity(e),onSessionEnd:e=>N?.onSessionEnd(e)}),N.startGC(),R&&(N.onSessionStart(R,{transport:`http`}),N.onSessionActivity(R)),B.info(`HTTP session runtime ready`,{maxSessions:S,sessionTimeoutMinutes:C,gcIntervalMinutes:w})}).catch(e=>B.error(`Failed to start session manager`,p(e))),l===`auto`?u.ready.then(async()=>{try{let e=g.sources.map(e=>e.path).join(`, `);B.info(`Running initial index`,{sourcePaths:e}),await u.runInitialIndex(),B.info(`Initial index complete`)}catch(t){B.error(`Initial index failed; will retry on aikit_reindex`,V(e,t))}}).catch(t=>B.error(`AI Kit init or indexing failed`,V(e,t))):l===`smart`?u.ready.then(async()=>{try{if(!u.aikit)throw Error(`AI Kit components are not available after initialization`);let{SmartIndexScheduler:e}=await import(`../../indexer/dist/index.js`),t=new e(u.aikit.indexer,g,u.aikit.store),n=u.aikit.store;j=t,t.start(),n.onBeforeClose&&n.onBeforeClose(()=>t.stop()),u.setSmartScheduler(t),B.debug(`Smart index scheduler started (HTTP mode)`)}catch(t){B.error(`Failed to start smart index scheduler`,V(e,t))}}).catch(t=>B.error(`AI Kit initialization failed`,V(e,t))):(u.ready.catch(t=>B.error(`AI Kit initialization failed`,V(e,t))),B.info(`Initial full indexing skipped in HTTP mode`,{indexMode:l})),r(u.ready,()=>u.aikit?{curated:u.aikit.curated,stateStore:u.aikit.stateStore}:null)}catch(t){B.error(`Failed to load server modules`,V(e,t))}},100)}),K=async e=>{B.info(`Shutdown signal received`,{signal:e}),j?.stop(),N?.stop(),await I?.closeAll().catch(()=>void 0),R&&N?.onSessionEnd(R),L&&(await L.close().catch(()=>void 0),L=null,R=null),G.close(),P&&await P.close(),process.exit(0)};process.on(`SIGINT`,()=>K(`SIGINT`)),process.on(`SIGTERM`,()=>K(`SIGTERM`))}else{let[{loadConfig:t,reconfigureForWorkspace:n,resolveIndexMode:i},{createLazyServer:a},{checkForUpdates:o,autoUpgradeScaffold:s},{RootsListChangedNotificationSchema:c}]=await Promise.all([import(`./config-WpN5CWM7.js`),import(`./server-4h0Cclv3.js`),import(`./version-check-gazMo-D4.js`),import(`@modelcontextprotocol/sdk/types.js`)]),l=t();m(l.logging?.errorDetails===!0),B.info(`Config loaded`,{sourceCount:l.sources.length,storePath:l.store.path}),o(),s();let u=i(l),d=a(l,u),{server:f,startInit:p,ready:h,runInitialIndex:g}=d,{StdioServerTransport:_}=await import(`@modelcontextprotocol/sdk/server/stdio.js`),v=new _;await f.connect(v),B.debug(`MCP server started`,{transport:`stdio`}),await Y({config:l,indexMode:u,log:B,rootsChangedNotificationSchema:c,reconfigureForWorkspace:n,runInitialIndex:g,server:f,startInit:p});let y=null,b=()=>{y&&clearTimeout(y),y=setTimeout(async()=>{B.info(`Auto-shutdown: no activity for 30 minutes — shutting down gracefully`);try{let e=d.aikit;e&&await Promise.all([e.embedder.shutdown?.().catch(()=>{})??Promise.resolve(),e.graphStore.close().catch(()=>{}),e.store.close().catch(()=>{})])}catch{}process.exit(0)},18e5),y.unref&&y.unref()};b(),process.stdin.on(`data`,()=>b()),h.catch(t=>{B.error(`Initialization failed — server will continue with limited tools`,V(e,t))}),u===`smart`?h.then(async()=>{try{if(!d.aikit)throw Error(`AI Kit components are not available after initialization`);let{SmartIndexScheduler:e}=await import(`../../indexer/dist/index.js`),t=new e(d.aikit.indexer,l,d.aikit.store),n=d.aikit.store;t.start(),n.onBeforeClose&&n.onBeforeClose(()=>t.stop()),d.setSmartScheduler(t),B.debug(`Smart index scheduler started (stdio mode)`)}catch(t){B.error(`Failed to start smart index scheduler`,V(e,t))}}).catch(t=>B.error(`AI Kit init failed for smart scheduler`,V(e,t))):B.warn(`Initial full indexing skipped; use aikit_reindex to index manually`,{indexMode:u}),r(h,()=>d.aikit?{curated:d.aikit.curated,stateStore:d.aikit.stateStore}:null)}}ne();export{N as n,R as t};