@vpxa/aikit 0.1.382 → 0.1.384

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (23) hide show
  1. package/package.json +1 -1
  2. package/packages/claude-desktop/dist/manifest.json +1 -1
  3. package/packages/server/dist/bin.js +1 -1
  4. package/packages/server/dist/{config-CQKoGfwD.js → config-BS9mkd50.js} +1 -1
  5. package/packages/server/dist/{config-DX1KYSbN.js → config-CkXCQx7E.js} +1 -1
  6. package/packages/server/dist/{dashboard-static-DdsIJd-u.js → dashboard-static-CVRj5Cbv.js} +1 -1
  7. package/packages/server/dist/{dashboard-static-C6RP0VA7.js → dashboard-static-q97RHnd3.js} +1 -1
  8. package/packages/server/dist/index.js +1 -1
  9. package/packages/server/dist/{register-tools-C49Lkpvq.js → register-tools-CCDtIMgE.js} +149 -149
  10. package/packages/server/dist/{register-tools-i_1kjBhi.js → register-tools-DLj1eMq3.js} +144 -144
  11. package/packages/server/dist/{server-CTUxU4KX.js → server-B6YroA9y.js} +2 -2
  12. package/packages/server/dist/{server-Dm2u4PSm.js → server-QCZQCfjf.js} +2 -2
  13. package/packages/server/dist/{server-http-DcgFpWra.js → server-http-agZcmQoQ.js} +1 -1
  14. package/packages/server/dist/{server-http-D8Wemu8Y.js → server-http-tJ-qTrTX.js} +1 -1
  15. package/packages/server/dist/{server-stdio-Bpoo8KOT.js → server-stdio-B0CPUULy.js} +1 -1
  16. package/packages/server/dist/{server-stdio-CskpvBew.js → server-stdio-BpzUm6FP.js} +1 -1
  17. package/packages/server/dist/{settings-static-C0oT3Ctk.js → settings-static-HY0egyKG.js} +1 -1
  18. package/packages/server/dist/{settings-static-DVMG47Oh.js → settings-static-VnUkp9iU.js} +1 -1
  19. package/packages/server/dist/startup-maintenance-D7tKqECM.js +21 -0
  20. package/packages/server/dist/{startup-maintenance-kHH8tjds.js → startup-maintenance-QrloHssd.js} +6 -6
  21. package/packages/tools/dist/index.d.ts +41 -2
  22. package/packages/tools/dist/index.js +105 -106
  23. package/packages/server/dist/startup-maintenance-cbRSFMY5.js +0 -21
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{c as e,f as t,p as n,s as r}from"./startup-maintenance-cbRSFMY5.js";import{n as i,t as a}from"./bin.js";import{reconfigureForWorkspace as o}from"./config-DX1KYSbN.js";import{S as s,_ as c,b as l,c as u,d,f,g as p,h as m,i as h,l as g,m as _,n as ee,o as v,p as te,r as y,s as b,t as x,u as S,v as C,x as w,y as ne}from"./register-tools-C49Lkpvq.js";import{fileURLToPath as T}from"node:url";import{AIKIT_PATHS as re,DISPLAY_SERVER_NAME as E,EMBEDDING_DEFAULTS as D,MODEL_REGISTRY as O,addLogListener as k,computePartitionKey as A,createLogger as j,safeCwdOrHome as M,serializeError as N}from"../../core/dist/index.js";import{existsSync as P,mkdirSync as F,statSync as ie}from"node:fs";import{join as I,resolve as ae}from"node:path";import{FileCache as oe,checkpointList as L,checkpointSave as se,listWorksets as R,stashList as ce}from"../../tools/dist/index.js";import{homedir as z}from"node:os";import{McpServer as le}from"@modelcontextprotocol/sdk/server/mcp.js";import{WasmDiagnostics as B,initializeWasm as ue}from"../../chunker/dist/index.js";import{z as V}from"zod";import{EvolutionCollector as de,PolicyStore as fe}from"../../enterprise-bridge/dist/index.js";import{SqliteGraphStore as pe,allMigrations as me,createSqliteAdapter as H,createStateStore as he,createStore as ge,runMigrations as _e}from"../../store/dist/index.js";import{RootsListChangedNotificationSchema as ve}from"@modelcontextprotocol/sdk/types.js";import{buildFormSchema as U,field as W,normalizeResponse as ye}from"../../elicitation/dist/index.js";import{completable as G}from"@modelcontextprotocol/sdk/server/completable.js";import{EmbedderProxy as be}from"../../embeddings/dist/index.js";import{FileHashCache as xe,IncrementalIndexer as Se}from"../../indexer/dist/index.js";import{AsyncLocalStorage as Ce}from"node:async_hooks";function we(e){function t(){return!!e.server?.getClientCapabilities?.()?.elicitation}async function n(n,r){if(t())try{let t=await e.server.elicitInput({message:n,requestedSchema:r});return ye(t?{action:t.action,content:t.content}:void 0)}catch{return}}return{get available(){return t()},async ask(e){return await n(e.message,e.schema)||{action:`decline`}},async confirm(e){let t=await n(e,U({confirmed:W.confirm(e)}));return t?.action===`accept`&&t.content?.confirmed===!0},async selectOne(e,t){let r=await n(e,U({selection:W.select(`Choose one`,t)}));if(r?.action!==`accept`)return null;let i=r.content?.selection;return typeof i==`string`?i:null},async selectMany(e,t){let r=await n(e,U({selections:W.multi(`Choose one or more`,t)}));if(r?.action!==`accept`)return[];let i=r.content?.selections;return Array.isArray(i)?i:[]},async promptText(e,t){let r=await n(e,U({text:W.text(e,{description:t})}));if(r?.action!==`accept`)return null;let i=r.content?.text;return typeof i==`string`?i:null}}}const Te={debug:`debug`,info:`info`,warn:`warning`,error:`error`};function Ee(e){return k(({level:t,component:n,message:r,data:i})=>{try{Promise.resolve(e.sendLoggingMessage({level:Te[t],logger:n,data:i?{message:r,...i}:r})).catch(()=>{})}catch{}})}const K=3e4,q=new Map;function De(e,t,n){let r=q.get(e);if(r&&Date.now()<r.expires)return Promise.resolve(r.data);let i=n();return Promise.resolve(i).then(n=>(q.set(e,{data:n,expires:Date.now()+t}),n))}function Oe(){q.clear()}function ke(e,t){return De(`curated-paths`,K,async()=>e.listPaths({limit:5e3})).then(e=>e.filter(e=>e.toLowerCase().includes(t.toLowerCase())).slice(0,20))}function Ae(e,t){return De(`file-paths`,K,()=>e.listSourcePaths()).then(e=>e.filter(e=>e.toLowerCase().includes(t.toLowerCase())).slice(0,20))}function je(e,t){return De(`symbol-names`,K,async()=>(await e.findNodes({type:`symbol`,limit:500})).map(e=>e.name)).then(e=>e.filter(e=>e.toLowerCase().includes(t.toLowerCase())).slice(0,20))}function Me(e,t){return t?ce(t).map(e=>e.key).filter(t=>t.toLowerCase().includes(e.toLowerCase())).slice(0,20):[]}function Ne(e){return R().map(e=>e.name).filter(t=>t.toLowerCase().includes(e.toLowerCase())).slice(0,20)}function Pe(e,t){return t?L(t).map(e=>e.label).filter(t=>t.toLowerCase().includes(e.toLowerCase())).slice(0,20):[]}function Fe(e,t,n){if(e.registerPrompt(`ready`,{title:`AI Kit Ready`,description:`AI Kit is ready — quick-start guide for search, onboard, and workflows`},async()=>({messages:[{role:`user`,content:{type:`text`,text:[`AI Kit is ready. Quick start:`,``,'• **New project?** → `onboard({ path: "." })` for full codebase analysis','• **Returning?** → `status({})` then `search({ query: "SESSION CHECKPOINT", origin: "curated" })`','• **Exploring?** → `guide({ goal: "your task" })` for workflow recommendations','• **Quick lookup?** → `search({ query: "your question" })`'].join(`
2
+ import{c as e,f as t,p as n,s as r}from"./startup-maintenance-D7tKqECM.js";import{n as i,t as a}from"./bin.js";import{reconfigureForWorkspace as o}from"./config-CkXCQx7E.js";import{S as s,_ as c,b as l,c as u,d,f,g as p,h as m,i as h,l as g,m as _,n as ee,o as v,p as te,r as y,s as b,t as x,u as S,v as C,x as w,y as ne}from"./register-tools-CCDtIMgE.js";import{fileURLToPath as T}from"node:url";import{AIKIT_PATHS as re,DISPLAY_SERVER_NAME as E,EMBEDDING_DEFAULTS as D,MODEL_REGISTRY as O,addLogListener as k,computePartitionKey as A,createLogger as j,safeCwdOrHome as M,serializeError as N}from"../../core/dist/index.js";import{existsSync as P,mkdirSync as F,statSync as ie}from"node:fs";import{join as I,resolve as ae}from"node:path";import{FileCache as oe,checkpointList as L,checkpointSave as se,listWorksets as R,stashList as ce}from"../../tools/dist/index.js";import{homedir as z}from"node:os";import{McpServer as le}from"@modelcontextprotocol/sdk/server/mcp.js";import{WasmDiagnostics as B,initializeWasm as ue}from"../../chunker/dist/index.js";import{z as V}from"zod";import{EvolutionCollector as de,PolicyStore as fe}from"../../enterprise-bridge/dist/index.js";import{SqliteGraphStore as pe,allMigrations as me,createSqliteAdapter as H,createStateStore as he,createStore as ge,runMigrations as _e}from"../../store/dist/index.js";import{RootsListChangedNotificationSchema as ve}from"@modelcontextprotocol/sdk/types.js";import{buildFormSchema as U,field as W,normalizeResponse as ye}from"../../elicitation/dist/index.js";import{completable as G}from"@modelcontextprotocol/sdk/server/completable.js";import{EmbedderProxy as be}from"../../embeddings/dist/index.js";import{FileHashCache as xe,IncrementalIndexer as Se}from"../../indexer/dist/index.js";import{AsyncLocalStorage as Ce}from"node:async_hooks";function we(e){function t(){return!!e.server?.getClientCapabilities?.()?.elicitation}async function n(n,r){if(t())try{let t=await e.server.elicitInput({message:n,requestedSchema:r});return ye(t?{action:t.action,content:t.content}:void 0)}catch{return}}return{get available(){return t()},async ask(e){return await n(e.message,e.schema)||{action:`decline`}},async confirm(e){let t=await n(e,U({confirmed:W.confirm(e)}));return t?.action===`accept`&&t.content?.confirmed===!0},async selectOne(e,t){let r=await n(e,U({selection:W.select(`Choose one`,t)}));if(r?.action!==`accept`)return null;let i=r.content?.selection;return typeof i==`string`?i:null},async selectMany(e,t){let r=await n(e,U({selections:W.multi(`Choose one or more`,t)}));if(r?.action!==`accept`)return[];let i=r.content?.selections;return Array.isArray(i)?i:[]},async promptText(e,t){let r=await n(e,U({text:W.text(e,{description:t})}));if(r?.action!==`accept`)return null;let i=r.content?.text;return typeof i==`string`?i:null}}}const Te={debug:`debug`,info:`info`,warn:`warning`,error:`error`};function Ee(e){return k(({level:t,component:n,message:r,data:i})=>{try{Promise.resolve(e.sendLoggingMessage({level:Te[t],logger:n,data:i?{message:r,...i}:r})).catch(()=>{})}catch{}})}const K=3e4,q=new Map;function De(e,t,n){let r=q.get(e);if(r&&Date.now()<r.expires)return Promise.resolve(r.data);let i=n();return Promise.resolve(i).then(n=>(q.set(e,{data:n,expires:Date.now()+t}),n))}function Oe(){q.clear()}function ke(e,t){return De(`curated-paths`,K,async()=>e.listPaths({limit:5e3})).then(e=>e.filter(e=>e.toLowerCase().includes(t.toLowerCase())).slice(0,20))}function Ae(e,t){return De(`file-paths`,K,()=>e.listSourcePaths()).then(e=>e.filter(e=>e.toLowerCase().includes(t.toLowerCase())).slice(0,20))}function je(e,t){return De(`symbol-names`,K,async()=>(await e.findNodes({type:`symbol`,limit:500})).map(e=>e.name)).then(e=>e.filter(e=>e.toLowerCase().includes(t.toLowerCase())).slice(0,20))}function Me(e,t){return t?ce(t).map(e=>e.key).filter(t=>t.toLowerCase().includes(e.toLowerCase())).slice(0,20):[]}function Ne(e){return R().map(e=>e.name).filter(t=>t.toLowerCase().includes(e.toLowerCase())).slice(0,20)}function Pe(e,t){return t?L(t).map(e=>e.label).filter(t=>t.toLowerCase().includes(e.toLowerCase())).slice(0,20):[]}function Fe(e,t,n){if(e.registerPrompt(`ready`,{title:`AI Kit Ready`,description:`AI Kit is ready — quick-start guide for search, onboard, and workflows`},async()=>({messages:[{role:`user`,content:{type:`text`,text:[`AI Kit is ready. Quick start:`,``,'• **New project?** → `onboard({ path: "." })` for full codebase analysis','• **Returning?** → `status({})` then `search({ query: "SESSION CHECKPOINT", origin: "curated" })`','• **Exploring?** → `guide({ goal: "your task" })` for workflow recommendations','• **Quick lookup?** → `search({ query: "your question" })`'].join(`
3
3
  `)}}]})),e.registerPrompt(`onboard`,{title:`Onboard Codebase`,description:`Analyze the codebase for first-time onboarding — runs all analyzers and produces a knowledge summary`,argsSchema:{path:V.string().optional().describe(`Path to analyze (default: workspace root)`)}},async({path:e})=>({messages:[{role:`user`,content:{type:`text`,text:[`Run the full onboarding workflow for "${e??`.`}"`,``,`1. \`onboard({ path: "${e??`.`}" })\` — full codebase analysis`,`2. \`produce_knowledge({ path: "${e??`.`}" })\` — generate synthesis`,'3. `knowledge({ action: "remember", ... })` for key curated entries',"4. `status` to verify index health"].join(`
4
4
  `)}}]})),e.registerPrompt(`sessionStart`,{title:`Start AI Kit Session`,description:`Initialize an AI Kit session — check status, list knowledge, and resume from last checkpoint`},async()=>({messages:[{role:`user`,content:{type:`text`,text:[`Run the session start protocol:`,``,"1. `status({})` — check AI Kit health and onboard state",'2. `knowledge({ action: "list" })` — see stored knowledge entries','3. `search({ query: "SESSION CHECKPOINT", origin: "curated" })` — resume prior work'].join(`
5
5
  `)}}]})),e.registerPrompt(`sessionEnd`,{title:`End AI Kit Session`,description:`Persist decisions and create a session checkpoint before ending`,argsSchema:{summary:V.string().describe(`Brief summary of decisions made, blockers encountered, and next steps`)}},async({summary:e})=>({messages:[{role:`user`,content:{type:`text`,text:[`Run the session end protocol:`,``,'1. `knowledge({ action: "remember", title: "Session checkpoint: '+e.slice(0,60)+`...", content: "`+e.replace(/"/g,`\\"`)+'", category: "session" })` — persist findings',n===`smart`?`2. Smart indexing is active — index refreshes automatically`:"2. `reindex({})` — refresh search index if files changed",`3. Confirm session data saved`].join(`
@@ -16,7 +16,7 @@ import{c as e,f as t,p as n,s as r}from"./startup-maintenance-cbRSFMY5.js";impor
16
16
  │ Vector search is disabled. Hybrid search returns FTS only. │
17
17
  │ To enable: install/rebuild better-sqlite3 (native module). │
18
18
  └──────────────────────────────────────────────────────────────────┘`);let t=I(s,`lance`);P(t)&&J.info(`Old LanceDB data found at ${t} — ignored. Safe to delete after verifying sqlite-vec works.`)}let m;if(p)if(f.splitEnabled&&f.controlDbPath!==f.contentDbPath){let{migrateToSplitState:e}=await import(`../../store/dist/index.js`);await e(f),m=await H(f.controlDbPath),_e(m,me),J.info(`State store adapter ready`,{type:m.type,dbPath:f.controlDbPath,splitEnabled:!0})}else m=p;else{let e=I(s,`aikit-state.db`);P(s)||F(s,{recursive:!0}),m=await H(e),_e(m,me),J.info(`State store adapter ready`,{type:m.type,dbPath:e})}let[h,g,_,ee]=await Promise.all([(async()=>{try{if(e.embedding.childProcess!==!1){let e=new be({model:o.model,dimensions:o.dimensions,nativeDim:o.nativeDim,queryPrefix:o.queryPrefix,pooling:o.pooling,interOpNumThreads:n.interOpNumThreads,intraOpNumThreads:n.intraOpNumThreads,idleTimeoutMs:n.idleTimeoutMs});return await e.initialize(),J.debug(`Embedder loaded (child process)`,{modelId:e.modelId,dimensions:e.dimensions}),e}let{OnnxEmbedder:t}=await import(`../../embeddings/dist/index.js`),r=new t({model:o.model,dimensions:o.dimensions,nativeDim:o.nativeDim,queryPrefix:o.queryPrefix,pooling:o.pooling,interOpNumThreads:n.interOpNumThreads,intraOpNumThreads:n.intraOpNumThreads});return await r.initialize(),J.debug(`Embedder loaded (in-process)`,{modelId:r.modelId,dimensions:r.dimensions}),r}catch(e){return J.warn(`Embedder initialization failed — vector search degraded to FTS-only`,{error:N(e)}),{dimensions:0,modelId:`unavailable`,initialize:async()=>{},embed:async()=>{throw Error(`Embedder unavailable`)},embedQuery:async()=>{throw Error(`Embedder unavailable`)},embedBatch:async()=>{throw Error(`Embedder unavailable`)}}}})(),(async()=>{let e=t===`sqlite-vec`?await ge({backend:t,path:s,adapter:p??void 0,embeddingDim:o.dimensions,embeddingProfile:o,partition:f}):await ge({backend:t,path:s,adapter:p??void 0,embeddingDim:o.dimensions,partition:void 0});return await e.initialize(),J.debug(`Store initialized`,{backend:t}),e})(),(async()=>{let e=p?new pe({adapter:p}):new pe({path:s});return await e.initialize(),J.debug(`Graph store initialized`,{shared:!!p}),e})(),(async()=>{let e=await ue();if(e){let e=B.get();J.debug(`WASM tree-sitter enabled`,{grammars:e.grammarCount,dir:e.wasmDir})}else{let e=B.get();J.warn(`WASM tree-sitter not available; analyzers will use regex fallback`,{reason:e.reason,os:e.os,arch:e.arch,healAttempted:e.healAttempted,healSuccess:e.healSuccess,healError:e.healError,pathsChecked:e.pathsChecked.map(e=>`${e.path} (${e.exists?`found`:`missing`})`)})}return e})()]),v=new Se(h,g),te=he(m),y=new xe(e.store.path);y.load(),v.setHashCache(y);let b=e.curated.path,x=new i(b);await x.initialize();let S=new a(b,g,h,x);v.setGraphStore(_);let C=u(e.er),w=C?new fe(e.curated.path):void 0;w&&J.debug(`Policy store initialized`,{ruleCount:w.getRules().length});let ne=C?new de:void 0,T=ae(e.sources[0]?.path??M(),re.aiContext),E=P(T),k=e.onboardDir?P(e.onboardDir):!1,A=E||k,j,L=E?T:e.onboardDir;if(A&&L)try{j=ie(L).mtime.toISOString()}catch{}return J.debug(`Onboard state detected`,{onboardComplete:A,onboardTimestamp:j,aiKbExists:E,onboardDirExists:k}),{embedder:h,store:g,stateStore:te,closeStateStore:m===p?void 0:async()=>m.close(),indexer:v,curated:S,graphStore:_,fileCache:new oe,bridge:C,policyStore:w,evolutionCollector:ne,onboardComplete:A,onboardTimestamp:j,eventBus:new c}}function ze(e,t,n){if(e.serverInstructions)return e.serverInstructions;let r=new Set;for(let e of t){let t=n[e];if(t?.category)for(let e of t.category)r.add(e)}let i=[`This server provides ${t.size} tools across ${r.size} categories: ${[...r].sort().join(`, `)}.`,`TOOL ROUTING:`,`- Understand a file -> file_summary (T1=structure, T2=content)`,`- Find code/symbols -> search (hybrid) or symbol (definition + refs)`,`- Validate changes -> check (typecheck+lint) or test_run (tests)`,`- Read file for editing -> read_file (only for exact lines before edits)`,`FORBIDDEN: DO NOT USE native equivalents when AI Kit provides same:`,`- grep/find -> search or find tool`,`- cat/read_file (for understanding) -> file_summary`,`- terminal tsc/lint -> check tool`,`- terminal test -> test_run tool`];return e.readOnly&&i.push(`Server is in read-only mode. Mutating operations are disabled.`),e.features?.length&&i.push(`Active feature groups: ${e.features.join(`, `)}.`),i.join(`
19
- `)}const Be=j(`background-task`);var Ve=class{queue=[];running=null;get isRunning(){return this.running!==null}get currentTask(){return this.running}get pendingCount(){return this.queue.length}schedule(e){return new Promise((t,n)=>{this.queue.push({...e,resolve:t,reject:n}),this.running||this.processQueue()})}async processQueue(){for(;this.queue.length>0;){let e=this.queue.shift();if(!e)break;this.running=e.name,Be.info(`Background task started`,{task:e.name,pending:this.queue.length});let t=Date.now();try{await e.fn();let n=Date.now()-t;Be.info(`Background task completed`,{task:e.name,durationMs:n}),e.resolve()}catch(n){let r=Date.now()-t;Be.error(`Background task failed`,{task:e.name,durationMs:r,err:n}),e.reject(n instanceof Error?n:Error(String(n)))}}this.running=null}};const X=j(`idle-timer`);var He=class{timer=null;cleanupFns=[];idleMs;disposed=!1;sessionActive=!1;_busy=!1;constructor(e){this.idleMs=e?.idleMs??3e5}setBusy(e){this._busy=e,e?this.cancel():this.touch()}onIdle(e){this.cleanupFns.push(e)}markSessionActive(){this.sessionActive=!0}touch(){this.disposed||this._busy||(this.cancel(),this.timer=setTimeout(()=>{this.runCleanup()},this.idleMs),this.timer.unref&&this.timer.unref())}cancel(){this.timer&&=(clearTimeout(this.timer),null)}dispose(){this.cancel(),this.cleanupFns.length=0,this.disposed=!0}async runCleanup(){if(!this.sessionActive){X.info(`Idle timeout reached with no active session — skipping cleanup (waiting for first tool call)`);return}if(this._busy){X.info(`Skipping idle cleanup — background work in progress`);return}X.info(`Idle for ${this.idleMs/1e3}s — running cleanup`);let e=await Promise.allSettled(this.cleanupFns.map(e=>e()));for(let t of e)t.status===`rejected`&&X.warn(`Idle cleanup callback failed`,{error:String(t.reason)})}};const Z=j(`memory-monitor`);var Ue=class{timer=null;warningBytes;criticalBytes;intervalMs;pressureFns=[];memoryPressureFns=[];lastLevel=`normal`;constructor(e){this.warningBytes=e?.warningBytes??3221225472,this.criticalBytes=e?.criticalBytes??6442450944,this.intervalMs=e?.intervalMs??3e4}onPressure(e){this.pressureFns.push(e)}registerMemoryPressureCallback(e){this.memoryPressureFns.push(e)}start(){this.timer||(this.timer=setInterval(()=>this.check(),this.intervalMs),this.timer.unref&&this.timer.unref(),Z.debug(`Memory monitor started`,{warningMB:Math.round(this.warningBytes/1024/1024),criticalMB:Math.round(this.criticalBytes/1024/1024),intervalSec:Math.round(this.intervalMs/1e3)}))}stop(){this.timer&&=(clearInterval(this.timer),null)}getRssBytes(){return process.memoryUsage.rss()}check(){let e=this.getRssBytes(),t=`normal`;if(e>=this.criticalBytes?t=`critical`:e>=this.warningBytes&&(t=`warning`),t!==this.lastLevel||t===`critical`){let n=Math.round(e/1024/1024);t===`critical`?Z.warn(`Memory CRITICAL: ${n}MB RSS — consider restarting the server`):t===`warning`?Z.warn(`Memory WARNING: ${n}MB RSS`):this.lastLevel!==`normal`&&Z.info(`Memory returned to normal: ${n}MB RSS`),this.lastLevel=t}if(t!==`normal`)for(let n of this.pressureFns)try{n(t,e)}catch{}if(t===`critical`)for(let e of this.memoryPressureFns)try{let t=e();t&&typeof t.catch==`function`&&t.catch(()=>{})}catch{}return t===`critical`&&typeof globalThis.gc==`function`&&globalThis.gc(),t}};const We=new Ce;function Ge(e,t){return We.run(e,async()=>{try{return await t()}finally{}})}j(`tool-timeout`);const Ke=new Set([`onboard`,`reindex`,`produce_knowledge`,`analyze`,`codemod`,`audit`]);var qe=class extends Error{toolName;timeoutMs;constructor(e,t){super(`Tool "${e}" timed out after ${t}ms`),this.toolName=e,this.timeoutMs=t,this.name=`ToolTimeoutError`}};function Je(e){return Ke.has(e)?6e5:12e4}function Ye(e,t,n){let r=new AbortController,i=r.signal;return new Promise((a,o)=>{let s=setTimeout(()=>{let e=new qe(n,t);i.aborted||r.abort(e),o(e)},t);s.unref();try{e(i).then(a,o).finally(()=>clearTimeout(s))}catch(e){clearTimeout(s),o(e instanceof Error?e:Error(String(e)))}})}const Q=j(`server`),Xe=new Set([`status`,`list_tools`,`describe_tool`,`config`,`env`,`present`]);function Ze(e,t=28){let n=e.replace(/\s+/g,` `).trim();return n.length<=t?n:`${n.slice(0,t-3)}...`}function Qe(e){let t=[`query`,`path`,`task`,`name`,`start`,`symbol`,`file`,`pattern`],n=[];for(let r of t){let t=e[r];typeof t==`string`&&t.length>0&&t.length<200&&n.push(t)}return n.join(` `).slice(0,200)}async function $e(e,t,n,r){let i=[];if(n){let t=await et(e,n);t&&i.push(t)}try{if(t.statePath){let{ensureLegacyStashImported:n}=await import(`../../tools/dist/index.js`);n(e.stateStore,{stateDir:t.statePath})}let r=e.stateStore.stashList().map(e=>e.key);if(r.length>0){let e=n?n.toLowerCase().split(/\s+/).filter(e=>e.length>2):[];if(e.length===0)i.push(`📦 stash: ${r.length} entries`);else{let t=r.filter(t=>e.some(e=>t.toLowerCase().includes(e))).slice(0,3);t.length>0&&i.push(`📦 stash: ${t.map(e=>`"${Ze(e)}"`).join(`, `)}${r.length>t.length?` (+${r.length-t.length})`:``}`)}}}catch{}if(i.length===0&&!r)return null;if(r){let n=e,r=n.curated;if(r?.list&&n.stateStore)try{let{buildPreludeInjection:e,generatePrelude:a}=await import(`./startup-maintenance-cbRSFMY5.js`).then(e=>e.a),o=e(await a(r,n.stateStore,void 0,t.skillDir),500);o.lines.length>0&&i.push(o.lines.join(`
19
+ `)}const Be=j(`background-task`);var Ve=class{queue=[];running=null;get isRunning(){return this.running!==null}get currentTask(){return this.running}get pendingCount(){return this.queue.length}schedule(e){return new Promise((t,n)=>{this.queue.push({...e,resolve:t,reject:n}),this.running||this.processQueue()})}async processQueue(){for(;this.queue.length>0;){let e=this.queue.shift();if(!e)break;this.running=e.name,Be.info(`Background task started`,{task:e.name,pending:this.queue.length});let t=Date.now();try{await e.fn();let n=Date.now()-t;Be.info(`Background task completed`,{task:e.name,durationMs:n}),e.resolve()}catch(n){let r=Date.now()-t;Be.error(`Background task failed`,{task:e.name,durationMs:r,err:n}),e.reject(n instanceof Error?n:Error(String(n)))}}this.running=null}};const X=j(`idle-timer`);var He=class{timer=null;cleanupFns=[];idleMs;disposed=!1;sessionActive=!1;_busy=!1;constructor(e){this.idleMs=e?.idleMs??3e5}setBusy(e){this._busy=e,e?this.cancel():this.touch()}onIdle(e){this.cleanupFns.push(e)}markSessionActive(){this.sessionActive=!0}touch(){this.disposed||this._busy||(this.cancel(),this.timer=setTimeout(()=>{this.runCleanup()},this.idleMs),this.timer.unref&&this.timer.unref())}cancel(){this.timer&&=(clearTimeout(this.timer),null)}dispose(){this.cancel(),this.cleanupFns.length=0,this.disposed=!0}async runCleanup(){if(!this.sessionActive){X.info(`Idle timeout reached with no active session — skipping cleanup (waiting for first tool call)`);return}if(this._busy){X.info(`Skipping idle cleanup — background work in progress`);return}X.info(`Idle for ${this.idleMs/1e3}s — running cleanup`);let e=await Promise.allSettled(this.cleanupFns.map(e=>e()));for(let t of e)t.status===`rejected`&&X.warn(`Idle cleanup callback failed`,{error:String(t.reason)})}};const Z=j(`memory-monitor`);var Ue=class{timer=null;warningBytes;criticalBytes;intervalMs;pressureFns=[];memoryPressureFns=[];lastLevel=`normal`;constructor(e){this.warningBytes=e?.warningBytes??3221225472,this.criticalBytes=e?.criticalBytes??6442450944,this.intervalMs=e?.intervalMs??3e4}onPressure(e){this.pressureFns.push(e)}registerMemoryPressureCallback(e){this.memoryPressureFns.push(e)}start(){this.timer||(this.timer=setInterval(()=>this.check(),this.intervalMs),this.timer.unref&&this.timer.unref(),Z.debug(`Memory monitor started`,{warningMB:Math.round(this.warningBytes/1024/1024),criticalMB:Math.round(this.criticalBytes/1024/1024),intervalSec:Math.round(this.intervalMs/1e3)}))}stop(){this.timer&&=(clearInterval(this.timer),null)}getRssBytes(){return process.memoryUsage.rss()}check(){let e=this.getRssBytes(),t=`normal`;if(e>=this.criticalBytes?t=`critical`:e>=this.warningBytes&&(t=`warning`),t!==this.lastLevel||t===`critical`){let n=Math.round(e/1024/1024);t===`critical`?Z.warn(`Memory CRITICAL: ${n}MB RSS — consider restarting the server`):t===`warning`?Z.warn(`Memory WARNING: ${n}MB RSS`):this.lastLevel!==`normal`&&Z.info(`Memory returned to normal: ${n}MB RSS`),this.lastLevel=t}if(t!==`normal`)for(let n of this.pressureFns)try{n(t,e)}catch{}if(t===`critical`)for(let e of this.memoryPressureFns)try{let t=e();t&&typeof t.catch==`function`&&t.catch(()=>{})}catch{}return t===`critical`&&typeof globalThis.gc==`function`&&globalThis.gc(),t}};const We=new Ce;function Ge(e,t){return We.run(e,async()=>{try{return await t()}finally{}})}j(`tool-timeout`);const Ke=new Set([`onboard`,`reindex`,`produce_knowledge`,`analyze`,`codemod`,`audit`]);var qe=class extends Error{toolName;timeoutMs;constructor(e,t){super(`Tool "${e}" timed out after ${t}ms`),this.toolName=e,this.timeoutMs=t,this.name=`ToolTimeoutError`}};function Je(e){return Ke.has(e)?6e5:12e4}function Ye(e,t,n){let r=new AbortController,i=r.signal;return new Promise((a,o)=>{let s=setTimeout(()=>{let e=new qe(n,t);i.aborted||r.abort(e),o(e)},t);s.unref();try{e(i).then(a,o).finally(()=>clearTimeout(s))}catch(e){clearTimeout(s),o(e instanceof Error?e:Error(String(e)))}})}const Q=j(`server`),Xe=new Set([`status`,`list_tools`,`describe_tool`,`config`,`env`,`present`]);function Ze(e,t=28){let n=e.replace(/\s+/g,` `).trim();return n.length<=t?n:`${n.slice(0,t-3)}...`}function Qe(e){let t=[`query`,`path`,`task`,`name`,`start`,`symbol`,`file`,`pattern`],n=[];for(let r of t){let t=e[r];typeof t==`string`&&t.length>0&&t.length<200&&n.push(t)}return n.join(` `).slice(0,200)}async function $e(e,t,n,r){let i=[];if(n){let t=await et(e,n);t&&i.push(t)}try{if(t.statePath){let{ensureLegacyStashImported:n}=await import(`../../tools/dist/index.js`);n(e.stateStore,{stateDir:t.statePath})}let r=e.stateStore.stashList().map(e=>e.key);if(r.length>0){let e=n?n.toLowerCase().split(/\s+/).filter(e=>e.length>2):[];if(e.length===0)i.push(`📦 stash: ${r.length} entries`);else{let t=r.filter(t=>e.some(e=>t.toLowerCase().includes(e))).slice(0,3);t.length>0&&i.push(`📦 stash: ${t.map(e=>`"${Ze(e)}"`).join(`, `)}${r.length>t.length?` (+${r.length-t.length})`:``}`)}}}catch{}if(i.length===0&&!r)return null;if(r){let n=e,r=n.curated;if(r?.list&&n.stateStore)try{let{buildPreludeInjection:e,generatePrelude:a}=await import(`./startup-maintenance-D7tKqECM.js`).then(e=>e.a),o=e(await a(r,n.stateStore,void 0,t.skillDir),500);o.lines.length>0&&i.push(o.lines.join(`
20
20
  `))}catch(e){Q.debug?.(`Periodic prelude injection failed`,{error:String(e)})}}return i.length===0?null:`\n${i.join(`
21
21
  `)}`}async function et(e,n){try{let r=await Promise.race([e.store.ftsSearch(n,{limit:3}),new Promise(e=>{let t=setTimeout(()=>e(null),1e3);t.unref&&t.unref()})]);if(!Array.isArray(r)||r.length===0)return null;let i=[];for(let e of r){if(!e||typeof e!=`object`)continue;let n=e.record;if(!n)continue;let r=n.origin;if(r!==`curated`&&r!==`produced`)continue;let a=n.content??``;if(!(!a||a.length<20)){if(a.length<=400){let e=n.headingPath?.trim()||``,t=a.slice(0,400),r=e?`📚 ${e}: ${t}`:`📚 ${t}`;i.push(r)}else{let e=t(a,400),r=n.headingPath?.trim()||``,o=r?`📚 ${r}: ${e}`:`📚 ${e}`;i.push(o)}if(i.length>=2)break}}return i.length===0?null:i.join(`
22
22
  `)}catch{return null}}function tt(e,t,n){let r=5,i=0;for(let[a,o]of Object.entries(e)){let e=o.handler;o.handler=async(...o)=>{let s=await e(...o);if(!s||typeof s!=`object`||r<=0||s.isError||Xe.has(a))return s;try{r--,i++;let e=o[0],a=await $e(t,n,Qe(e&&typeof e==`object`?e:{}),i%5==0);a&&(s.content=Array.isArray(s.content)?s.content:[],s.content.push({type:`text`,text:a}))}catch{}return s}}}function nt(e){let t=e.toLowerCase();return[`protobuf`,`invalid model`,`invalid onnx`,`unexpected end`,`unexpected token`,`failed to load`,`failed to initialize embedding`,`checksum`,`corrupt`,`malformed`,`could not load`,`onnx`,`database is locked`,`database disk image is malformed`,`file is not a database`,`lance`,`cannot find module`,`cannot find package`,`module not found`,`operation not permitted`,`permission denied`].some(e=>t.includes(e))}function rt(e){return v(e)?[`Auto-heal tried to repair missing runtime dependency files in the npx install.`,`If this persists, clear the broken npx cache and restart:`,` npm cache clean --force`,` npx -y @vpxa/aikit@latest serve`].join(`
@@ -1,4 +1,4 @@
1
- import{n as e,t}from"./curated-manager-D4MOFQ-t.js";import{c as n,f as r,p as i,s as a}from"./startup-maintenance-kHH8tjds.js";import{reconfigureForWorkspace as o}from"./config-CQKoGfwD.js";import{S as s,_ as c,b as l,c as u,d,f,g as p,h as m,i as h,l as g,m as _,n as ee,o as v,p as te,r as y,s as b,t as x,u as S,v as C,x as w,y as ne}from"./register-tools-i_1kjBhi.js";import{fileURLToPath as T}from"node:url";import{AIKIT_PATHS as re,DISPLAY_SERVER_NAME as E,EMBEDDING_DEFAULTS as D,MODEL_REGISTRY as O,addLogListener as k,computePartitionKey as A,createLogger as j,safeCwdOrHome as M,serializeError as N}from"../../core/dist/index.js";import{existsSync as P,mkdirSync as F,statSync as ie}from"node:fs";import{join as I,resolve as ae}from"node:path";import{FileCache as oe,checkpointList as L,checkpointSave as se,listWorksets as R,stashList as ce}from"../../tools/dist/index.js";import{homedir as z}from"node:os";import{McpServer as le}from"@modelcontextprotocol/sdk/server/mcp.js";import{WasmDiagnostics as B,initializeWasm as ue}from"../../chunker/dist/index.js";import{z as V}from"zod";import{EvolutionCollector as de,PolicyStore as fe}from"../../enterprise-bridge/dist/index.js";import{SqliteGraphStore as pe,allMigrations as me,createSqliteAdapter as H,createStateStore as he,createStore as ge,runMigrations as _e}from"../../store/dist/index.js";import{RootsListChangedNotificationSchema as ve}from"@modelcontextprotocol/sdk/types.js";import{buildFormSchema as U,field as W,normalizeResponse as ye}from"../../elicitation/dist/index.js";import{completable as G}from"@modelcontextprotocol/sdk/server/completable.js";import{EmbedderProxy as be}from"../../embeddings/dist/index.js";import{FileHashCache as xe,IncrementalIndexer as Se}from"../../indexer/dist/index.js";import{AsyncLocalStorage as Ce}from"node:async_hooks";function we(e){function t(){return!!e.server?.getClientCapabilities?.()?.elicitation}async function n(n,r){if(t())try{let t=await e.server.elicitInput({message:n,requestedSchema:r});return ye(t?{action:t.action,content:t.content}:void 0)}catch{return}}return{get available(){return t()},async ask(e){return await n(e.message,e.schema)||{action:`decline`}},async confirm(e){let t=await n(e,U({confirmed:W.confirm(e)}));return t?.action===`accept`&&t.content?.confirmed===!0},async selectOne(e,t){let r=await n(e,U({selection:W.select(`Choose one`,t)}));if(r?.action!==`accept`)return null;let i=r.content?.selection;return typeof i==`string`?i:null},async selectMany(e,t){let r=await n(e,U({selections:W.multi(`Choose one or more`,t)}));if(r?.action!==`accept`)return[];let i=r.content?.selections;return Array.isArray(i)?i:[]},async promptText(e,t){let r=await n(e,U({text:W.text(e,{description:t})}));if(r?.action!==`accept`)return null;let i=r.content?.text;return typeof i==`string`?i:null}}}const Te={debug:`debug`,info:`info`,warn:`warning`,error:`error`};function Ee(e){return k(({level:t,component:n,message:r,data:i})=>{try{Promise.resolve(e.sendLoggingMessage({level:Te[t],logger:n,data:i?{message:r,...i}:r})).catch(()=>{})}catch{}})}const K=3e4,q=new Map;function De(e,t,n){let r=q.get(e);if(r&&Date.now()<r.expires)return Promise.resolve(r.data);let i=n();return Promise.resolve(i).then(n=>(q.set(e,{data:n,expires:Date.now()+t}),n))}function Oe(){q.clear()}function ke(e,t){return De(`curated-paths`,K,async()=>e.listPaths({limit:5e3})).then(e=>e.filter(e=>e.toLowerCase().includes(t.toLowerCase())).slice(0,20))}function Ae(e,t){return De(`file-paths`,K,()=>e.listSourcePaths()).then(e=>e.filter(e=>e.toLowerCase().includes(t.toLowerCase())).slice(0,20))}function je(e,t){return De(`symbol-names`,K,async()=>(await e.findNodes({type:`symbol`,limit:500})).map(e=>e.name)).then(e=>e.filter(e=>e.toLowerCase().includes(t.toLowerCase())).slice(0,20))}function Me(e,t){return t?ce(t).map(e=>e.key).filter(t=>t.toLowerCase().includes(e.toLowerCase())).slice(0,20):[]}function Ne(e){return R().map(e=>e.name).filter(t=>t.toLowerCase().includes(e.toLowerCase())).slice(0,20)}function Pe(e,t){return t?L(t).map(e=>e.label).filter(t=>t.toLowerCase().includes(e.toLowerCase())).slice(0,20):[]}function Fe(e,t,n){if(e.registerPrompt(`ready`,{title:`AI Kit Ready`,description:`AI Kit is ready — quick-start guide for search, onboard, and workflows`},async()=>({messages:[{role:`user`,content:{type:`text`,text:[`AI Kit is ready. Quick start:`,``,'• **New project?** → `onboard({ path: "." })` for full codebase analysis','• **Returning?** → `status({})` then `search({ query: "SESSION CHECKPOINT", origin: "curated" })`','• **Exploring?** → `guide({ goal: "your task" })` for workflow recommendations','• **Quick lookup?** → `search({ query: "your question" })`'].join(`
1
+ import{n as e,t}from"./curated-manager-D4MOFQ-t.js";import{c as n,f as r,p as i,s as a}from"./startup-maintenance-QrloHssd.js";import{reconfigureForWorkspace as o}from"./config-BS9mkd50.js";import{S as s,_ as c,b as l,c as u,d,f,g as p,h as m,i as h,l as g,m as _,n as ee,o as v,p as te,r as y,s as b,t as x,u as S,v as C,x as w,y as ne}from"./register-tools-DLj1eMq3.js";import{fileURLToPath as T}from"node:url";import{AIKIT_PATHS as re,DISPLAY_SERVER_NAME as E,EMBEDDING_DEFAULTS as D,MODEL_REGISTRY as O,addLogListener as k,computePartitionKey as A,createLogger as j,safeCwdOrHome as M,serializeError as N}from"../../core/dist/index.js";import{existsSync as P,mkdirSync as F,statSync as ie}from"node:fs";import{join as I,resolve as ae}from"node:path";import{FileCache as oe,checkpointList as L,checkpointSave as se,listWorksets as R,stashList as ce}from"../../tools/dist/index.js";import{homedir as z}from"node:os";import{McpServer as le}from"@modelcontextprotocol/sdk/server/mcp.js";import{WasmDiagnostics as B,initializeWasm as ue}from"../../chunker/dist/index.js";import{z as V}from"zod";import{EvolutionCollector as de,PolicyStore as fe}from"../../enterprise-bridge/dist/index.js";import{SqliteGraphStore as pe,allMigrations as me,createSqliteAdapter as H,createStateStore as he,createStore as ge,runMigrations as _e}from"../../store/dist/index.js";import{RootsListChangedNotificationSchema as ve}from"@modelcontextprotocol/sdk/types.js";import{buildFormSchema as U,field as W,normalizeResponse as ye}from"../../elicitation/dist/index.js";import{completable as G}from"@modelcontextprotocol/sdk/server/completable.js";import{EmbedderProxy as be}from"../../embeddings/dist/index.js";import{FileHashCache as xe,IncrementalIndexer as Se}from"../../indexer/dist/index.js";import{AsyncLocalStorage as Ce}from"node:async_hooks";function we(e){function t(){return!!e.server?.getClientCapabilities?.()?.elicitation}async function n(n,r){if(t())try{let t=await e.server.elicitInput({message:n,requestedSchema:r});return ye(t?{action:t.action,content:t.content}:void 0)}catch{return}}return{get available(){return t()},async ask(e){return await n(e.message,e.schema)||{action:`decline`}},async confirm(e){let t=await n(e,U({confirmed:W.confirm(e)}));return t?.action===`accept`&&t.content?.confirmed===!0},async selectOne(e,t){let r=await n(e,U({selection:W.select(`Choose one`,t)}));if(r?.action!==`accept`)return null;let i=r.content?.selection;return typeof i==`string`?i:null},async selectMany(e,t){let r=await n(e,U({selections:W.multi(`Choose one or more`,t)}));if(r?.action!==`accept`)return[];let i=r.content?.selections;return Array.isArray(i)?i:[]},async promptText(e,t){let r=await n(e,U({text:W.text(e,{description:t})}));if(r?.action!==`accept`)return null;let i=r.content?.text;return typeof i==`string`?i:null}}}const Te={debug:`debug`,info:`info`,warn:`warning`,error:`error`};function Ee(e){return k(({level:t,component:n,message:r,data:i})=>{try{Promise.resolve(e.sendLoggingMessage({level:Te[t],logger:n,data:i?{message:r,...i}:r})).catch(()=>{})}catch{}})}const K=3e4,q=new Map;function De(e,t,n){let r=q.get(e);if(r&&Date.now()<r.expires)return Promise.resolve(r.data);let i=n();return Promise.resolve(i).then(n=>(q.set(e,{data:n,expires:Date.now()+t}),n))}function Oe(){q.clear()}function ke(e,t){return De(`curated-paths`,K,async()=>e.listPaths({limit:5e3})).then(e=>e.filter(e=>e.toLowerCase().includes(t.toLowerCase())).slice(0,20))}function Ae(e,t){return De(`file-paths`,K,()=>e.listSourcePaths()).then(e=>e.filter(e=>e.toLowerCase().includes(t.toLowerCase())).slice(0,20))}function je(e,t){return De(`symbol-names`,K,async()=>(await e.findNodes({type:`symbol`,limit:500})).map(e=>e.name)).then(e=>e.filter(e=>e.toLowerCase().includes(t.toLowerCase())).slice(0,20))}function Me(e,t){return t?ce(t).map(e=>e.key).filter(t=>t.toLowerCase().includes(e.toLowerCase())).slice(0,20):[]}function Ne(e){return R().map(e=>e.name).filter(t=>t.toLowerCase().includes(e.toLowerCase())).slice(0,20)}function Pe(e,t){return t?L(t).map(e=>e.label).filter(t=>t.toLowerCase().includes(e.toLowerCase())).slice(0,20):[]}function Fe(e,t,n){if(e.registerPrompt(`ready`,{title:`AI Kit Ready`,description:`AI Kit is ready — quick-start guide for search, onboard, and workflows`},async()=>({messages:[{role:`user`,content:{type:`text`,text:[`AI Kit is ready. Quick start:`,``,'• **New project?** → `onboard({ path: "." })` for full codebase analysis','• **Returning?** → `status({})` then `search({ query: "SESSION CHECKPOINT", origin: "curated" })`','• **Exploring?** → `guide({ goal: "your task" })` for workflow recommendations','• **Quick lookup?** → `search({ query: "your question" })`'].join(`
2
2
  `)}}]})),e.registerPrompt(`onboard`,{title:`Onboard Codebase`,description:`Analyze the codebase for first-time onboarding — runs all analyzers and produces a knowledge summary`,argsSchema:{path:V.string().optional().describe(`Path to analyze (default: workspace root)`)}},async({path:e})=>({messages:[{role:`user`,content:{type:`text`,text:[`Run the full onboarding workflow for "${e??`.`}"`,``,`1. \`onboard({ path: "${e??`.`}" })\` — full codebase analysis`,`2. \`produce_knowledge({ path: "${e??`.`}" })\` — generate synthesis`,'3. `knowledge({ action: "remember", ... })` for key curated entries',"4. `status` to verify index health"].join(`
3
3
  `)}}]})),e.registerPrompt(`sessionStart`,{title:`Start AI Kit Session`,description:`Initialize an AI Kit session — check status, list knowledge, and resume from last checkpoint`},async()=>({messages:[{role:`user`,content:{type:`text`,text:[`Run the session start protocol:`,``,"1. `status({})` — check AI Kit health and onboard state",'2. `knowledge({ action: "list" })` — see stored knowledge entries','3. `search({ query: "SESSION CHECKPOINT", origin: "curated" })` — resume prior work'].join(`
4
4
  `)}}]})),e.registerPrompt(`sessionEnd`,{title:`End AI Kit Session`,description:`Persist decisions and create a session checkpoint before ending`,argsSchema:{summary:V.string().describe(`Brief summary of decisions made, blockers encountered, and next steps`)}},async({summary:e})=>({messages:[{role:`user`,content:{type:`text`,text:[`Run the session end protocol:`,``,'1. `knowledge({ action: "remember", title: "Session checkpoint: '+e.slice(0,60)+`...", content: "`+e.replace(/"/g,`\\"`)+'", category: "session" })` — persist findings',n===`smart`?`2. Smart indexing is active — index refreshes automatically`:"2. `reindex({})` — refresh search index if files changed",`3. Confirm session data saved`].join(`
@@ -15,7 +15,7 @@ import{n as e,t}from"./curated-manager-D4MOFQ-t.js";import{c as n,f as r,p as i,
15
15
  │ Vector search is disabled. Hybrid search returns FTS only. │
16
16
  │ To enable: install/rebuild better-sqlite3 (native module). │
17
17
  └──────────────────────────────────────────────────────────────────┘`);let t=I(s,`lance`);P(t)&&J.info(`Old LanceDB data found at ${t} — ignored. Safe to delete after verifying sqlite-vec works.`)}let m;if(p)if(f.splitEnabled&&f.controlDbPath!==f.contentDbPath){let{migrateToSplitState:e}=await import(`../../store/dist/index.js`);await e(f),m=await H(f.controlDbPath),_e(m,me),J.info(`State store adapter ready`,{type:m.type,dbPath:f.controlDbPath,splitEnabled:!0})}else m=p;else{let e=I(s,`aikit-state.db`);P(s)||F(s,{recursive:!0}),m=await H(e),_e(m,me),J.info(`State store adapter ready`,{type:m.type,dbPath:e})}let[h,g,_,ee]=await Promise.all([(async()=>{try{if(n.embedding.childProcess!==!1){let e=new be({model:o.model,dimensions:o.dimensions,nativeDim:o.nativeDim,queryPrefix:o.queryPrefix,pooling:o.pooling,interOpNumThreads:i.interOpNumThreads,intraOpNumThreads:i.intraOpNumThreads,idleTimeoutMs:i.idleTimeoutMs});return await e.initialize(),J.debug(`Embedder loaded (child process)`,{modelId:e.modelId,dimensions:e.dimensions}),e}let{OnnxEmbedder:e}=await import(`../../embeddings/dist/index.js`),t=new e({model:o.model,dimensions:o.dimensions,nativeDim:o.nativeDim,queryPrefix:o.queryPrefix,pooling:o.pooling,interOpNumThreads:i.interOpNumThreads,intraOpNumThreads:i.intraOpNumThreads});return await t.initialize(),J.debug(`Embedder loaded (in-process)`,{modelId:t.modelId,dimensions:t.dimensions}),t}catch(e){return J.warn(`Embedder initialization failed — vector search degraded to FTS-only`,{error:N(e)}),{dimensions:0,modelId:`unavailable`,initialize:async()=>{},embed:async()=>{throw Error(`Embedder unavailable`)},embedQuery:async()=>{throw Error(`Embedder unavailable`)},embedBatch:async()=>{throw Error(`Embedder unavailable`)}}}})(),(async()=>{let e=r===`sqlite-vec`?await ge({backend:r,path:s,adapter:p??void 0,embeddingDim:o.dimensions,embeddingProfile:o,partition:f}):await ge({backend:r,path:s,adapter:p??void 0,embeddingDim:o.dimensions,partition:void 0});return await e.initialize(),J.debug(`Store initialized`,{backend:r}),e})(),(async()=>{let e=p?new pe({adapter:p}):new pe({path:s});return await e.initialize(),J.debug(`Graph store initialized`,{shared:!!p}),e})(),(async()=>{let e=await ue();if(e){let e=B.get();J.debug(`WASM tree-sitter enabled`,{grammars:e.grammarCount,dir:e.wasmDir})}else{let e=B.get();J.warn(`WASM tree-sitter not available; analyzers will use regex fallback`,{reason:e.reason,os:e.os,arch:e.arch,healAttempted:e.healAttempted,healSuccess:e.healSuccess,healError:e.healError,pathsChecked:e.pathsChecked.map(e=>`${e.path} (${e.exists?`found`:`missing`})`)})}return e})()]),v=new Se(h,g),te=he(m),y=new xe(n.store.path);y.load(),v.setHashCache(y);let b=n.curated.path,x=new e(b);await x.initialize();let S=new t(b,g,h,x);v.setGraphStore(_);let C=u(n.er),w=C?new fe(n.curated.path):void 0;w&&J.debug(`Policy store initialized`,{ruleCount:w.getRules().length});let ne=C?new de:void 0,T=ae(n.sources[0]?.path??M(),re.aiContext),E=P(T),k=n.onboardDir?P(n.onboardDir):!1,A=E||k,j,L=E?T:n.onboardDir;if(A&&L)try{j=ie(L).mtime.toISOString()}catch{}return J.debug(`Onboard state detected`,{onboardComplete:A,onboardTimestamp:j,aiKbExists:E,onboardDirExists:k}),{embedder:h,store:g,stateStore:te,closeStateStore:m===p?void 0:async()=>m.close(),indexer:v,curated:S,graphStore:_,fileCache:new oe,bridge:C,policyStore:w,evolutionCollector:ne,onboardComplete:A,onboardTimestamp:j,eventBus:new c}}function ze(e,t,n){if(e.serverInstructions)return e.serverInstructions;let r=new Set;for(let e of t){let t=n[e];if(t?.category)for(let e of t.category)r.add(e)}let i=[`This server provides ${t.size} tools across ${r.size} categories: ${[...r].sort().join(`, `)}.`,`TOOL ROUTING:`,`- Understand a file -> file_summary (T1=structure, T2=content)`,`- Find code/symbols -> search (hybrid) or symbol (definition + refs)`,`- Validate changes -> check (typecheck+lint) or test_run (tests)`,`- Read file for editing -> read_file (only for exact lines before edits)`,`FORBIDDEN: DO NOT USE native equivalents when AI Kit provides same:`,`- grep/find -> search or find tool`,`- cat/read_file (for understanding) -> file_summary`,`- terminal tsc/lint -> check tool`,`- terminal test -> test_run tool`];return e.readOnly&&i.push(`Server is in read-only mode. Mutating operations are disabled.`),e.features?.length&&i.push(`Active feature groups: ${e.features.join(`, `)}.`),i.join(`
18
- `)}const Be=j(`background-task`);var Ve=class{queue=[];running=null;get isRunning(){return this.running!==null}get currentTask(){return this.running}get pendingCount(){return this.queue.length}schedule(e){return new Promise((t,n)=>{this.queue.push({...e,resolve:t,reject:n}),this.running||this.processQueue()})}async processQueue(){for(;this.queue.length>0;){let e=this.queue.shift();if(!e)break;this.running=e.name,Be.info(`Background task started`,{task:e.name,pending:this.queue.length});let t=Date.now();try{await e.fn();let n=Date.now()-t;Be.info(`Background task completed`,{task:e.name,durationMs:n}),e.resolve()}catch(n){let r=Date.now()-t;Be.error(`Background task failed`,{task:e.name,durationMs:r,err:n}),e.reject(n instanceof Error?n:Error(String(n)))}}this.running=null}};const X=j(`idle-timer`);var He=class{timer=null;cleanupFns=[];idleMs;disposed=!1;sessionActive=!1;_busy=!1;constructor(e){this.idleMs=e?.idleMs??3e5}setBusy(e){this._busy=e,e?this.cancel():this.touch()}onIdle(e){this.cleanupFns.push(e)}markSessionActive(){this.sessionActive=!0}touch(){this.disposed||this._busy||(this.cancel(),this.timer=setTimeout(()=>{this.runCleanup()},this.idleMs),this.timer.unref&&this.timer.unref())}cancel(){this.timer&&=(clearTimeout(this.timer),null)}dispose(){this.cancel(),this.cleanupFns.length=0,this.disposed=!0}async runCleanup(){if(!this.sessionActive){X.info(`Idle timeout reached with no active session — skipping cleanup (waiting for first tool call)`);return}if(this._busy){X.info(`Skipping idle cleanup — background work in progress`);return}X.info(`Idle for ${this.idleMs/1e3}s — running cleanup`);let e=await Promise.allSettled(this.cleanupFns.map(e=>e()));for(let t of e)t.status===`rejected`&&X.warn(`Idle cleanup callback failed`,{error:String(t.reason)})}};const Z=j(`memory-monitor`);var Ue=class{timer=null;warningBytes;criticalBytes;intervalMs;pressureFns=[];memoryPressureFns=[];lastLevel=`normal`;constructor(e){this.warningBytes=e?.warningBytes??3221225472,this.criticalBytes=e?.criticalBytes??6442450944,this.intervalMs=e?.intervalMs??3e4}onPressure(e){this.pressureFns.push(e)}registerMemoryPressureCallback(e){this.memoryPressureFns.push(e)}start(){this.timer||(this.timer=setInterval(()=>this.check(),this.intervalMs),this.timer.unref&&this.timer.unref(),Z.debug(`Memory monitor started`,{warningMB:Math.round(this.warningBytes/1024/1024),criticalMB:Math.round(this.criticalBytes/1024/1024),intervalSec:Math.round(this.intervalMs/1e3)}))}stop(){this.timer&&=(clearInterval(this.timer),null)}getRssBytes(){return process.memoryUsage.rss()}check(){let e=this.getRssBytes(),t=`normal`;if(e>=this.criticalBytes?t=`critical`:e>=this.warningBytes&&(t=`warning`),t!==this.lastLevel||t===`critical`){let n=Math.round(e/1024/1024);t===`critical`?Z.warn(`Memory CRITICAL: ${n}MB RSS — consider restarting the server`):t===`warning`?Z.warn(`Memory WARNING: ${n}MB RSS`):this.lastLevel!==`normal`&&Z.info(`Memory returned to normal: ${n}MB RSS`),this.lastLevel=t}if(t!==`normal`)for(let n of this.pressureFns)try{n(t,e)}catch{}if(t===`critical`)for(let e of this.memoryPressureFns)try{let t=e();t&&typeof t.catch==`function`&&t.catch(()=>{})}catch{}return t===`critical`&&typeof globalThis.gc==`function`&&globalThis.gc(),t}};const We=new Ce;function Ge(e,t){return We.run(e,async()=>{try{return await t()}finally{}})}j(`tool-timeout`);const Ke=new Set([`onboard`,`reindex`,`produce_knowledge`,`analyze`,`codemod`,`audit`]);var qe=class extends Error{toolName;timeoutMs;constructor(e,t){super(`Tool "${e}" timed out after ${t}ms`),this.toolName=e,this.timeoutMs=t,this.name=`ToolTimeoutError`}};function Je(e){return Ke.has(e)?6e5:12e4}function Ye(e,t,n){let r=new AbortController,i=r.signal;return new Promise((a,o)=>{let s=setTimeout(()=>{let e=new qe(n,t);i.aborted||r.abort(e),o(e)},t);s.unref();try{e(i).then(a,o).finally(()=>clearTimeout(s))}catch(e){clearTimeout(s),o(e instanceof Error?e:Error(String(e)))}})}const Q=j(`server`),Xe=new Set([`status`,`list_tools`,`describe_tool`,`config`,`env`,`present`]);function Ze(e,t=28){let n=e.replace(/\s+/g,` `).trim();return n.length<=t?n:`${n.slice(0,t-3)}...`}function Qe(e){let t=[`query`,`path`,`task`,`name`,`start`,`symbol`,`file`,`pattern`],n=[];for(let r of t){let t=e[r];typeof t==`string`&&t.length>0&&t.length<200&&n.push(t)}return n.join(` `).slice(0,200)}async function $e(e,t,n,r){let i=[];if(n){let t=await et(e,n);t&&i.push(t)}try{if(t.statePath){let{ensureLegacyStashImported:n}=await import(`../../tools/dist/index.js`);n(e.stateStore,{stateDir:t.statePath})}let r=e.stateStore.stashList().map(e=>e.key);if(r.length>0){let e=n?n.toLowerCase().split(/\s+/).filter(e=>e.length>2):[];if(e.length===0)i.push(`📦 stash: ${r.length} entries`);else{let t=r.filter(t=>e.some(e=>t.toLowerCase().includes(e))).slice(0,3);t.length>0&&i.push(`📦 stash: ${t.map(e=>`"${Ze(e)}"`).join(`, `)}${r.length>t.length?` (+${r.length-t.length})`:``}`)}}}catch{}if(i.length===0&&!r)return null;if(r){let n=e,r=n.curated;if(r?.list&&n.stateStore)try{let{buildPreludeInjection:e,generatePrelude:a}=await import(`./startup-maintenance-kHH8tjds.js`).then(e=>e.a),o=e(await a(r,n.stateStore,void 0,t.skillDir),500);o.lines.length>0&&i.push(o.lines.join(`
18
+ `)}const Be=j(`background-task`);var Ve=class{queue=[];running=null;get isRunning(){return this.running!==null}get currentTask(){return this.running}get pendingCount(){return this.queue.length}schedule(e){return new Promise((t,n)=>{this.queue.push({...e,resolve:t,reject:n}),this.running||this.processQueue()})}async processQueue(){for(;this.queue.length>0;){let e=this.queue.shift();if(!e)break;this.running=e.name,Be.info(`Background task started`,{task:e.name,pending:this.queue.length});let t=Date.now();try{await e.fn();let n=Date.now()-t;Be.info(`Background task completed`,{task:e.name,durationMs:n}),e.resolve()}catch(n){let r=Date.now()-t;Be.error(`Background task failed`,{task:e.name,durationMs:r,err:n}),e.reject(n instanceof Error?n:Error(String(n)))}}this.running=null}};const X=j(`idle-timer`);var He=class{timer=null;cleanupFns=[];idleMs;disposed=!1;sessionActive=!1;_busy=!1;constructor(e){this.idleMs=e?.idleMs??3e5}setBusy(e){this._busy=e,e?this.cancel():this.touch()}onIdle(e){this.cleanupFns.push(e)}markSessionActive(){this.sessionActive=!0}touch(){this.disposed||this._busy||(this.cancel(),this.timer=setTimeout(()=>{this.runCleanup()},this.idleMs),this.timer.unref&&this.timer.unref())}cancel(){this.timer&&=(clearTimeout(this.timer),null)}dispose(){this.cancel(),this.cleanupFns.length=0,this.disposed=!0}async runCleanup(){if(!this.sessionActive){X.info(`Idle timeout reached with no active session — skipping cleanup (waiting for first tool call)`);return}if(this._busy){X.info(`Skipping idle cleanup — background work in progress`);return}X.info(`Idle for ${this.idleMs/1e3}s — running cleanup`);let e=await Promise.allSettled(this.cleanupFns.map(e=>e()));for(let t of e)t.status===`rejected`&&X.warn(`Idle cleanup callback failed`,{error:String(t.reason)})}};const Z=j(`memory-monitor`);var Ue=class{timer=null;warningBytes;criticalBytes;intervalMs;pressureFns=[];memoryPressureFns=[];lastLevel=`normal`;constructor(e){this.warningBytes=e?.warningBytes??3221225472,this.criticalBytes=e?.criticalBytes??6442450944,this.intervalMs=e?.intervalMs??3e4}onPressure(e){this.pressureFns.push(e)}registerMemoryPressureCallback(e){this.memoryPressureFns.push(e)}start(){this.timer||(this.timer=setInterval(()=>this.check(),this.intervalMs),this.timer.unref&&this.timer.unref(),Z.debug(`Memory monitor started`,{warningMB:Math.round(this.warningBytes/1024/1024),criticalMB:Math.round(this.criticalBytes/1024/1024),intervalSec:Math.round(this.intervalMs/1e3)}))}stop(){this.timer&&=(clearInterval(this.timer),null)}getRssBytes(){return process.memoryUsage.rss()}check(){let e=this.getRssBytes(),t=`normal`;if(e>=this.criticalBytes?t=`critical`:e>=this.warningBytes&&(t=`warning`),t!==this.lastLevel||t===`critical`){let n=Math.round(e/1024/1024);t===`critical`?Z.warn(`Memory CRITICAL: ${n}MB RSS — consider restarting the server`):t===`warning`?Z.warn(`Memory WARNING: ${n}MB RSS`):this.lastLevel!==`normal`&&Z.info(`Memory returned to normal: ${n}MB RSS`),this.lastLevel=t}if(t!==`normal`)for(let n of this.pressureFns)try{n(t,e)}catch{}if(t===`critical`)for(let e of this.memoryPressureFns)try{let t=e();t&&typeof t.catch==`function`&&t.catch(()=>{})}catch{}return t===`critical`&&typeof globalThis.gc==`function`&&globalThis.gc(),t}};const We=new Ce;function Ge(e,t){return We.run(e,async()=>{try{return await t()}finally{}})}j(`tool-timeout`);const Ke=new Set([`onboard`,`reindex`,`produce_knowledge`,`analyze`,`codemod`,`audit`]);var qe=class extends Error{toolName;timeoutMs;constructor(e,t){super(`Tool "${e}" timed out after ${t}ms`),this.toolName=e,this.timeoutMs=t,this.name=`ToolTimeoutError`}};function Je(e){return Ke.has(e)?6e5:12e4}function Ye(e,t,n){let r=new AbortController,i=r.signal;return new Promise((a,o)=>{let s=setTimeout(()=>{let e=new qe(n,t);i.aborted||r.abort(e),o(e)},t);s.unref();try{e(i).then(a,o).finally(()=>clearTimeout(s))}catch(e){clearTimeout(s),o(e instanceof Error?e:Error(String(e)))}})}const Q=j(`server`),Xe=new Set([`status`,`list_tools`,`describe_tool`,`config`,`env`,`present`]);function Ze(e,t=28){let n=e.replace(/\s+/g,` `).trim();return n.length<=t?n:`${n.slice(0,t-3)}...`}function Qe(e){let t=[`query`,`path`,`task`,`name`,`start`,`symbol`,`file`,`pattern`],n=[];for(let r of t){let t=e[r];typeof t==`string`&&t.length>0&&t.length<200&&n.push(t)}return n.join(` `).slice(0,200)}async function $e(e,t,n,r){let i=[];if(n){let t=await et(e,n);t&&i.push(t)}try{if(t.statePath){let{ensureLegacyStashImported:n}=await import(`../../tools/dist/index.js`);n(e.stateStore,{stateDir:t.statePath})}let r=e.stateStore.stashList().map(e=>e.key);if(r.length>0){let e=n?n.toLowerCase().split(/\s+/).filter(e=>e.length>2):[];if(e.length===0)i.push(`📦 stash: ${r.length} entries`);else{let t=r.filter(t=>e.some(e=>t.toLowerCase().includes(e))).slice(0,3);t.length>0&&i.push(`📦 stash: ${t.map(e=>`"${Ze(e)}"`).join(`, `)}${r.length>t.length?` (+${r.length-t.length})`:``}`)}}}catch{}if(i.length===0&&!r)return null;if(r){let n=e,r=n.curated;if(r?.list&&n.stateStore)try{let{buildPreludeInjection:e,generatePrelude:a}=await import(`./startup-maintenance-QrloHssd.js`).then(e=>e.a),o=e(await a(r,n.stateStore,void 0,t.skillDir),500);o.lines.length>0&&i.push(o.lines.join(`
19
19
  `))}catch(e){Q.debug?.(`Periodic prelude injection failed`,{error:String(e)})}}return i.length===0?null:`\n${i.join(`
20
20
  `)}`}async function et(e,t){try{let n=await Promise.race([e.store.ftsSearch(t,{limit:3}),new Promise(e=>{let t=setTimeout(()=>e(null),1e3);t.unref&&t.unref()})]);if(!Array.isArray(n)||n.length===0)return null;let i=[];for(let e of n){if(!e||typeof e!=`object`)continue;let t=e.record;if(!t)continue;let n=t.origin;if(n!==`curated`&&n!==`produced`)continue;let a=t.content??``;if(!(!a||a.length<20)){if(a.length<=400){let e=t.headingPath?.trim()||``,n=a.slice(0,400),r=e?`📚 ${e}: ${n}`:`📚 ${n}`;i.push(r)}else{let e=r(a,400),n=t.headingPath?.trim()||``,o=n?`📚 ${n}: ${e}`:`📚 ${e}`;i.push(o)}if(i.length>=2)break}}return i.length===0?null:i.join(`
21
21
  `)}catch{return null}}function tt(e,t,n){let r=5,i=0;for(let[a,o]of Object.entries(e)){let e=o.handler;o.handler=async(...o)=>{let s=await e(...o);if(!s||typeof s!=`object`||r<=0||s.isError||Xe.has(a))return s;try{r--,i++;let e=o[0],a=await $e(t,n,Qe(e&&typeof e==`object`?e:{}),i%5==0);a&&(s.content=Array.isArray(s.content)?s.content:[],s.content.push({type:`text`,text:a}))}catch{}return s}}}function nt(e){let t=e.toLowerCase();return[`protobuf`,`invalid model`,`invalid onnx`,`unexpected end`,`unexpected token`,`failed to load`,`failed to initialize embedding`,`checksum`,`corrupt`,`malformed`,`could not load`,`onnx`,`database is locked`,`database disk image is malformed`,`file is not a database`,`lance`,`cannot find module`,`cannot find package`,`module not found`,`operation not permitted`,`permission denied`].some(e=>t.includes(e))}function rt(e){return v(e)?[`Auto-heal tried to repair missing runtime dependency files in the npx install.`,`If this persists, clear the broken npx cache and restart:`,` npm cache clean --force`,` npx -y @vpxa/aikit@latest serve`].join(`
@@ -1 +1 @@
1
- import{a as e,n as t,r as n,t as r}from"./server-utils-De-aZNQa.js";import{n as i,t as a}from"./startup-maintenance-kHH8tjds.js";import{t as o}from"./register-tools-i_1kjBhi.js";import{createLogger as s,serializeError as c,setDetailedErrorLoggingEnabled as l}from"../../core/dist/index.js";import{randomUUID as u}from"node:crypto";const d=`__pending__:`;function f(e){return e.startsWith(d)}function p(e){let t=e.headers[`mcp-session-id`];return Array.isArray(t)?t[0]:t}function m(e,t,n,r){e.status(t).json({jsonrpc:`2.0`,error:{code:n,message:r},id:null})}var h=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=p(e),i=r?this.runtimes.get(r):void 0;if(r&&!i){m(t,404,-32001,`Session not found`);return}if(!i){if(e.method!==`POST`){m(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`&&!f(r)&&this.options.onSessionActivity?.(r),e.method===`DELETE`&&!f(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&&!f(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){m(e,503,-32003,`Session capacity reached`);return}let t=this.now(),n=await this.options.createServer(),r={id:`${d}${u()}`,transport:void 0,createdAt:t,lastAccessAt:t,server:n,requestChain:Promise.resolve()},i=this.options.createTransport({sessionIdGenerator:()=>u(),onsessioninitialized:async e=>{this.runtimes.delete(r.id),r.id=e,this.runtimes.set(e,r),this.options.onSessionStart?.(e)},onsessionclosed:async e=>{e&&await this.closeSession(e,{closeTransport:!1})}});return r.transport=i,i.onclose=()=>{let e=r.transport.sessionId??r.id;this.closeSession(e,{closeTransport:!1})},this.runtimes.set(r.id,r),await n.connect(i),r}async withRuntimeLock(e,t){let n=e.requestChain,r;e.requestChain=new Promise(e=>{r=e}),await n;try{await t()}finally{r()}}};function g(e){let t=e.includes(`T`)?e:`${e.replace(` `,`T`)}Z`;return Date.parse(t)}var _=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=g(n.lastActivity);return Number.isFinite(r)&&e-r>=t}).map(e=>e.sessionId)}};const v=s(`server`);async function y(s,d){let[{default:f},{loadConfig:p,resolveIndexMode:m},{registerDashboardRoutes:g,resolveDashboardDir:y},{registerSettingsRoutes:b,resolveSettingsDir:x},{createSettingsRouter:S},{authMiddleware:C,getOrCreateToken:w}]=await Promise.all([import(`express`),import(`./config-CQKoGfwD.js`),import(`./dashboard-static-C6RP0VA7.js`),import(`./settings-static-C0oT3Ctk.js`),import(`./routes-DsSm9ea0.js`),import(`./auth-7LFAZQBu.js`).then(e=>e.t)]),T=p();l(T.logging?.errorDetails===!0),T.configError&&v.warn(`Config load failure`,{error:T.configError}),v.info(`Config loaded`,{sourceCount:T.sources.length,storePath:T.store.path});let E=f();E.use(f.json({limit:`1mb`}));let D=Number(d),O=`http://localhost:${D}`,k=process.env.AIKIT_CORS_ORIGIN??O,A=process.env.AIKIT_ALLOW_ANY_ORIGIN===`true`,j=n(`AIKIT_HTTP_MAX_SESSIONS`,8),M=n(`AIKIT_HTTP_SESSION_TIMEOUT_MINUTES`,30),N=n(`AIKIT_HTTP_SESSION_GC_INTERVAL_MINUTES`,5),P=r({limit:100,windowMs:6e4}),F=!1;E.use((t,n,r)=>{let i=Array.isArray(t.headers.origin)?t.headers.origin[0]:t.headers.origin,a=e({requestOrigin:i,configuredOrigin:k,allowAnyOrigin:A,fallbackOrigin:O});if(a.warn&&!F&&(F=!0,v.warn(`Rejected non-local CORS origin while AIKIT_CORS_ORIGIN=*`,{origin:i,allowAnyOriginEnv:`AIKIT_ALLOW_ANY_ORIGIN=true`})),i&&!a.allowOrigin){n.status(403).json({error:`Origin not allowed`});return}if(a.allowOrigin&&n.setHeader(`Access-Control-Allow-Origin`,a.allowOrigin),n.setHeader(`Access-Control-Allow-Methods`,`GET, POST, PUT, PATCH, DELETE, OPTIONS`),n.setHeader(`Access-Control-Allow-Headers`,`Content-Type, Authorization, Mcp-Session-Id, Mcp-Protocol-Version, Last-Event-ID`),n.setHeader(`Access-Control-Expose-Headers`,`Mcp-Session-Id`),t.method===`OPTIONS`){n.status(204).end();return}r()});let I=w();E.use(C(I)),E.use(`/mcp`,(e,n,r)=>{let i=t(e)??e.ip??e.socket.remoteAddress??`anonymous`;if(P.allow(i)){r();return}let a=Math.max(1,Math.ceil(P.getRetryAfterMs(i)/1e3));n.setHeader(`Retry-After`,String(a)),n.status(429).json({jsonrpc:`2.0`,error:{code:-32003,message:`Rate limit exceeded`},id:null})});let L;E.use(`/mcp`,(e,t,n)=>{if(!L){let t=e.headers[`x-workspace-root`];typeof t==`string`&&t.length>0&&(L=t,v.debug(`Captured workspace root from proxy header`,{wsRoot:t}))}n()}),g(E,y(),v);let R=new Date().toISOString();E.use(`/settings/api`,S({log:v,mcpInfo:()=>({transport:`http`,port:D,pid:process.pid,startedAt:R})})),b(E,x(),v),E.get(`/health`,(e,t)=>{t.json({status:`ok`})});let z=!1,B=null,V=null,H=null,U=null,W=null,G=null,K=null,q=null,J=Promise.resolve(),Y=async(e,n)=>{if(!z||!H||!U){n.status(503).json({jsonrpc:`2.0`,error:{code:-32603,message:`Server initializing — please retry in a few seconds`},id:null});return}let r=J,i;J=new Promise(e=>{i=e});let a={POST:6e4,GET:1e4,DELETE:1e4}[e.method]??3e4;if(!await Promise.race([r.then(()=>!0),new Promise(t=>{let n=setTimeout(()=>{v.warn(`mcpLock timed out waiting for previous request, resetting lock chain`,{method:e.method,timeoutMs:a}),t(!1)},a);n.unref&&n.unref()})])&&(J=Promise.resolve(),i=()=>{},G)){let e=G;G=null,K=null,e.close().catch(()=>{})}try{let r=t(e);if(!G){if(r){n.status(404).json({jsonrpc:`2.0`,error:{code:-32001,message:`Session not found`},id:null});return}let e=new U({sessionIdGenerator:()=>u(),onsessioninitialized:async e=>{K=e,V?.onSessionStart(e,{transport:`http`})},onsessionclosed:async e=>{e&&V?.onSessionEnd(e),K=null}});e.onclose=()=>{G===e&&(G=null),K===e.sessionId&&(K=null)},G=e,await H.connect(e)}let i=G;await i.handleRequest(e,n,e.body),e.method!==`DELETE`&&(!r&&i.sessionId?(K=i.sessionId,V?.onSessionStart(i.sessionId,{transport:`http`}),V?.onSessionActivity(i.sessionId)):r&&V?.onSessionActivity(r))}catch(e){if(v.error(`MCP handler error`,c(e)),!n.headersSent){let t=e instanceof Error?e.message:String(e),r=t.includes(`Not Acceptable`);n.status(r?406:500).json({jsonrpc:`2.0`,error:{code:r?-32e3:-32603,message:r?t:`Internal server error`},id:null})}}finally{i()}},X=async(e,n)=>{let r=t(e);if(W&&(!G||r!==K)){await W.handleRequest(e,n,e.body);return}await Y(e,n)};E.post(`/mcp`,X),E.get(`/mcp`,X),E.delete(`/mcp`,X);let Z=E.listen(D,`127.0.0.1`,()=>{v.info(`MCP server listening`,{url:`http://127.0.0.1:${D}/mcp`,port:D}),setTimeout(async()=>{try{typeof L==`string`&&L.length>0&&(T.sources[0]={path:L,excludePatterns:T.sources[0]?.excludePatterns??[]},T.allRoots=[L],v.debug(`Workspace root applied from proxy header`,{wsRoot:L}));let[{createLazyServer:e,createMcpServer:t,ALL_TOOL_NAMES:n},{StreamableHTTPServerTransport:r},{checkForUpdates:o,autoUpgradeScaffold:l}]=await Promise.all([import(`./server-Dm2u4PSm.js`),import(`@modelcontextprotocol/sdk/server/streamableHttp.js`),import(`./startup-maintenance-kHH8tjds.js`).then(e=>e.u)]);o(),l(),setInterval(o,1440*60*1e3).unref();let u=!1,d=m(T),f=e(T,d);q=async()=>{f.aikit&&await Promise.all([f.aikit.embedder.shutdown?.().catch(()=>{})??Promise.resolve(),f.aikit.graphStore.close().catch(()=>{}),f.aikit.closeStateStore?.().catch(()=>{})??Promise.resolve(),f.aikit.store.close().catch(()=>{})])},H=f.server,U=r,z=!0,v.debug(`MCP server configured (lazy — AI Kit initializing in background)`,{toolCount:n.length,resourceCount:2}),f.startInit(),f.ready.then(async()=>{try{if(!f.aikit)throw Error(`AI Kit components are not available after initialization`);V=new _(f.aikit.stateStore,{staleTimeoutMinutes:M,gcIntervalMinutes:N,onBeforeSessionDelete:e=>{if(K===e&&G){let e=G;G=null,K=null,e.close().catch(()=>void 0)}W?.closeSession(e,{notifySessionEnd:!1})},onSessionEndMaintenance:async()=>{if(!f.aikit?.curated||!f.aikit?.stateStore)return;let{pruneLessons:e}=await import(`./startup-maintenance-kHH8tjds.js`).then(e=>e.x),t=await e(f.aikit.curated,f.aikit.stateStore,{dryRun:!1});t.pruned.length>0&&v.info(`Session-end lesson prune`,{pruned:t.pruned.length})}}),W=new h({createServer:()=>{if(!f.aikit)throw Error(`AI Kit components are not available after initialization`);return t(f.aikit,T)},createTransport:e=>new r(e),maxSessions:j,sessionTimeoutMinutes:M,onSessionStart:e=>V?.onSessionStart(e,{transport:`http`}),onSessionActivity:e=>V?.onSessionActivity(e),onSessionEnd:e=>V?.onSessionEnd(e)}),V.startGC(),K&&(V.onSessionStart(K,{transport:`http`}),V.onSessionActivity(K)),v.info(`HTTP session runtime ready`,{maxSessions:j,sessionTimeoutMinutes:M,gcIntervalMinutes:N})}catch(e){v.error(`Failed to start session manager`,c(e)),z=!1,u=!0,H=null,U=null,q=null}}),d===`auto`?f.ready.then(async()=>{try{let e=T.sources.map(e=>e.path).join(`, `);v.info(`Running initial index`,{sourcePaths:e}),await f.runInitialIndex(),v.info(`Initial index complete`)}catch(e){v.error(`Initial index failed; will retry on aikit_reindex`,i(s,e))}}):d===`smart`?u||f.ready.then(async()=>{try{if(!f.aikit)throw Error(`AI Kit components are not available after initialization`);let{SmartIndexScheduler:e}=await import(`../../indexer/dist/index.js`),t=new e(f.aikit.indexer,T,f.aikit.store),n=f.aikit.store;B=t,t.start(),n.onBeforeClose&&n.onBeforeClose(()=>t.stop()),f.setSmartScheduler(t),v.debug(`Smart index scheduler started (HTTP mode)`)}catch(e){v.error(`Failed to start smart index scheduler`,i(s,e))}}):v.info(`Initial full indexing skipped in HTTP mode`,{indexMode:d}),f.ready.catch(e=>{v.error(`AI Kit initialization failed`,i(s,e)),z=!1,u=!0,H=null,U=null,q=null}),a(f.ready,()=>f.aikit?{curated:f.aikit.curated,stateStore:f.aikit.stateStore}:null,s)}catch(e){v.error(`Failed to load server modules`,i(s,e)),z=!1,q=null}},100)}),Q=!1,$=async e=>{Q||(Q=!0,v.info(`Shutdown signal received`,{signal:e}),o(),B?.stop(),V?.stop(),await import(`../../tools/dist/index.js`).then(({processStopAll:e})=>e()).catch(()=>{}),await W?.closeAll().catch(()=>void 0),K&&V?.onSessionEnd(K),G&&(await G.close().catch(()=>void 0),G=null,K=null),Z.close(),H&&await H.close(),await q?.().catch(()=>void 0),process.exit(0))};process.on(`SIGINT`,()=>$(`SIGINT`)),process.on(`SIGTERM`,()=>$(`SIGTERM`))}export{y as startHttpMode};
1
+ import{a as e,n as t,r as n,t as r}from"./server-utils-De-aZNQa.js";import{n as i,t as a}from"./startup-maintenance-QrloHssd.js";import{t as o}from"./register-tools-DLj1eMq3.js";import{createLogger as s,serializeError as c,setDetailedErrorLoggingEnabled as l}from"../../core/dist/index.js";import{randomUUID as u}from"node:crypto";const d=`__pending__:`;function f(e){return e.startsWith(d)}function p(e){let t=e.headers[`mcp-session-id`];return Array.isArray(t)?t[0]:t}function m(e,t,n,r){e.status(t).json({jsonrpc:`2.0`,error:{code:n,message:r},id:null})}var h=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=p(e),i=r?this.runtimes.get(r):void 0;if(r&&!i){m(t,404,-32001,`Session not found`);return}if(!i){if(e.method!==`POST`){m(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`&&!f(r)&&this.options.onSessionActivity?.(r),e.method===`DELETE`&&!f(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&&!f(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){m(e,503,-32003,`Session capacity reached`);return}let t=this.now(),n=await this.options.createServer(),r={id:`${d}${u()}`,transport:void 0,createdAt:t,lastAccessAt:t,server:n,requestChain:Promise.resolve()},i=this.options.createTransport({sessionIdGenerator:()=>u(),onsessioninitialized:async e=>{this.runtimes.delete(r.id),r.id=e,this.runtimes.set(e,r),this.options.onSessionStart?.(e)},onsessionclosed:async e=>{e&&await this.closeSession(e,{closeTransport:!1})}});return r.transport=i,i.onclose=()=>{let e=r.transport.sessionId??r.id;this.closeSession(e,{closeTransport:!1})},this.runtimes.set(r.id,r),await n.connect(i),r}async withRuntimeLock(e,t){let n=e.requestChain,r;e.requestChain=new Promise(e=>{r=e}),await n;try{await t()}finally{r()}}};function g(e){let t=e.includes(`T`)?e:`${e.replace(` `,`T`)}Z`;return Date.parse(t)}var _=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=g(n.lastActivity);return Number.isFinite(r)&&e-r>=t}).map(e=>e.sessionId)}};const v=s(`server`);async function y(s,d){let[{default:f},{loadConfig:p,resolveIndexMode:m},{registerDashboardRoutes:g,resolveDashboardDir:y},{registerSettingsRoutes:b,resolveSettingsDir:x},{createSettingsRouter:S},{authMiddleware:C,getOrCreateToken:w}]=await Promise.all([import(`express`),import(`./config-BS9mkd50.js`),import(`./dashboard-static-q97RHnd3.js`),import(`./settings-static-HY0egyKG.js`),import(`./routes-DsSm9ea0.js`),import(`./auth-7LFAZQBu.js`).then(e=>e.t)]),T=p();l(T.logging?.errorDetails===!0),T.configError&&v.warn(`Config load failure`,{error:T.configError}),v.info(`Config loaded`,{sourceCount:T.sources.length,storePath:T.store.path});let E=f();E.use(f.json({limit:`1mb`}));let D=Number(d),O=`http://localhost:${D}`,k=process.env.AIKIT_CORS_ORIGIN??O,A=process.env.AIKIT_ALLOW_ANY_ORIGIN===`true`,j=n(`AIKIT_HTTP_MAX_SESSIONS`,8),M=n(`AIKIT_HTTP_SESSION_TIMEOUT_MINUTES`,30),N=n(`AIKIT_HTTP_SESSION_GC_INTERVAL_MINUTES`,5),P=r({limit:100,windowMs:6e4}),F=!1;E.use((t,n,r)=>{let i=Array.isArray(t.headers.origin)?t.headers.origin[0]:t.headers.origin,a=e({requestOrigin:i,configuredOrigin:k,allowAnyOrigin:A,fallbackOrigin:O});if(a.warn&&!F&&(F=!0,v.warn(`Rejected non-local CORS origin while AIKIT_CORS_ORIGIN=*`,{origin:i,allowAnyOriginEnv:`AIKIT_ALLOW_ANY_ORIGIN=true`})),i&&!a.allowOrigin){n.status(403).json({error:`Origin not allowed`});return}if(a.allowOrigin&&n.setHeader(`Access-Control-Allow-Origin`,a.allowOrigin),n.setHeader(`Access-Control-Allow-Methods`,`GET, POST, PUT, PATCH, DELETE, OPTIONS`),n.setHeader(`Access-Control-Allow-Headers`,`Content-Type, Authorization, Mcp-Session-Id, Mcp-Protocol-Version, Last-Event-ID`),n.setHeader(`Access-Control-Expose-Headers`,`Mcp-Session-Id`),t.method===`OPTIONS`){n.status(204).end();return}r()});let I=w();E.use(C(I)),E.use(`/mcp`,(e,n,r)=>{let i=t(e)??e.ip??e.socket.remoteAddress??`anonymous`;if(P.allow(i)){r();return}let a=Math.max(1,Math.ceil(P.getRetryAfterMs(i)/1e3));n.setHeader(`Retry-After`,String(a)),n.status(429).json({jsonrpc:`2.0`,error:{code:-32003,message:`Rate limit exceeded`},id:null})});let L;E.use(`/mcp`,(e,t,n)=>{if(!L){let t=e.headers[`x-workspace-root`];typeof t==`string`&&t.length>0&&(L=t,v.debug(`Captured workspace root from proxy header`,{wsRoot:t}))}n()}),g(E,y(),v);let R=new Date().toISOString();E.use(`/settings/api`,S({log:v,mcpInfo:()=>({transport:`http`,port:D,pid:process.pid,startedAt:R})})),b(E,x(),v),E.get(`/health`,(e,t)=>{t.json({status:`ok`})});let z=!1,B=null,V=null,H=null,U=null,W=null,G=null,K=null,q=null,J=Promise.resolve(),Y=async(e,n)=>{if(!z||!H||!U){n.status(503).json({jsonrpc:`2.0`,error:{code:-32603,message:`Server initializing — please retry in a few seconds`},id:null});return}let r=J,i;J=new Promise(e=>{i=e});let a={POST:6e4,GET:1e4,DELETE:1e4}[e.method]??3e4;if(!await Promise.race([r.then(()=>!0),new Promise(t=>{let n=setTimeout(()=>{v.warn(`mcpLock timed out waiting for previous request, resetting lock chain`,{method:e.method,timeoutMs:a}),t(!1)},a);n.unref&&n.unref()})])&&(J=Promise.resolve(),i=()=>{},G)){let e=G;G=null,K=null,e.close().catch(()=>{})}try{let r=t(e);if(!G){if(r){n.status(404).json({jsonrpc:`2.0`,error:{code:-32001,message:`Session not found`},id:null});return}let e=new U({sessionIdGenerator:()=>u(),onsessioninitialized:async e=>{K=e,V?.onSessionStart(e,{transport:`http`})},onsessionclosed:async e=>{e&&V?.onSessionEnd(e),K=null}});e.onclose=()=>{G===e&&(G=null),K===e.sessionId&&(K=null)},G=e,await H.connect(e)}let i=G;await i.handleRequest(e,n,e.body),e.method!==`DELETE`&&(!r&&i.sessionId?(K=i.sessionId,V?.onSessionStart(i.sessionId,{transport:`http`}),V?.onSessionActivity(i.sessionId)):r&&V?.onSessionActivity(r))}catch(e){if(v.error(`MCP handler error`,c(e)),!n.headersSent){let t=e instanceof Error?e.message:String(e),r=t.includes(`Not Acceptable`);n.status(r?406:500).json({jsonrpc:`2.0`,error:{code:r?-32e3:-32603,message:r?t:`Internal server error`},id:null})}}finally{i()}},X=async(e,n)=>{let r=t(e);if(W&&(!G||r!==K)){await W.handleRequest(e,n,e.body);return}await Y(e,n)};E.post(`/mcp`,X),E.get(`/mcp`,X),E.delete(`/mcp`,X);let Z=E.listen(D,`127.0.0.1`,()=>{v.info(`MCP server listening`,{url:`http://127.0.0.1:${D}/mcp`,port:D}),setTimeout(async()=>{try{typeof L==`string`&&L.length>0&&(T.sources[0]={path:L,excludePatterns:T.sources[0]?.excludePatterns??[]},T.allRoots=[L],v.debug(`Workspace root applied from proxy header`,{wsRoot:L}));let[{createLazyServer:e,createMcpServer:t,ALL_TOOL_NAMES:n},{StreamableHTTPServerTransport:r},{checkForUpdates:o,autoUpgradeScaffold:l}]=await Promise.all([import(`./server-QCZQCfjf.js`),import(`@modelcontextprotocol/sdk/server/streamableHttp.js`),import(`./startup-maintenance-QrloHssd.js`).then(e=>e.u)]);o(),l(),setInterval(o,1440*60*1e3).unref();let u=!1,d=m(T),f=e(T,d);q=async()=>{f.aikit&&await Promise.all([f.aikit.embedder.shutdown?.().catch(()=>{})??Promise.resolve(),f.aikit.graphStore.close().catch(()=>{}),f.aikit.closeStateStore?.().catch(()=>{})??Promise.resolve(),f.aikit.store.close().catch(()=>{})])},H=f.server,U=r,z=!0,v.debug(`MCP server configured (lazy — AI Kit initializing in background)`,{toolCount:n.length,resourceCount:2}),f.startInit(),f.ready.then(async()=>{try{if(!f.aikit)throw Error(`AI Kit components are not available after initialization`);V=new _(f.aikit.stateStore,{staleTimeoutMinutes:M,gcIntervalMinutes:N,onBeforeSessionDelete:e=>{if(K===e&&G){let e=G;G=null,K=null,e.close().catch(()=>void 0)}W?.closeSession(e,{notifySessionEnd:!1})},onSessionEndMaintenance:async()=>{if(!f.aikit?.curated||!f.aikit?.stateStore)return;let{pruneLessons:e}=await import(`./startup-maintenance-QrloHssd.js`).then(e=>e.x),t=await e(f.aikit.curated,f.aikit.stateStore,{dryRun:!1});t.pruned.length>0&&v.info(`Session-end lesson prune`,{pruned:t.pruned.length})}}),W=new h({createServer:()=>{if(!f.aikit)throw Error(`AI Kit components are not available after initialization`);return t(f.aikit,T)},createTransport:e=>new r(e),maxSessions:j,sessionTimeoutMinutes:M,onSessionStart:e=>V?.onSessionStart(e,{transport:`http`}),onSessionActivity:e=>V?.onSessionActivity(e),onSessionEnd:e=>V?.onSessionEnd(e)}),V.startGC(),K&&(V.onSessionStart(K,{transport:`http`}),V.onSessionActivity(K)),v.info(`HTTP session runtime ready`,{maxSessions:j,sessionTimeoutMinutes:M,gcIntervalMinutes:N})}catch(e){v.error(`Failed to start session manager`,c(e)),z=!1,u=!0,H=null,U=null,q=null}}),d===`auto`?f.ready.then(async()=>{try{let e=T.sources.map(e=>e.path).join(`, `);v.info(`Running initial index`,{sourcePaths:e}),await f.runInitialIndex(),v.info(`Initial index complete`)}catch(e){v.error(`Initial index failed; will retry on aikit_reindex`,i(s,e))}}):d===`smart`?u||f.ready.then(async()=>{try{if(!f.aikit)throw Error(`AI Kit components are not available after initialization`);let{SmartIndexScheduler:e}=await import(`../../indexer/dist/index.js`),t=new e(f.aikit.indexer,T,f.aikit.store),n=f.aikit.store;B=t,t.start(),n.onBeforeClose&&n.onBeforeClose(()=>t.stop()),f.setSmartScheduler(t),v.debug(`Smart index scheduler started (HTTP mode)`)}catch(e){v.error(`Failed to start smart index scheduler`,i(s,e))}}):v.info(`Initial full indexing skipped in HTTP mode`,{indexMode:d}),f.ready.catch(e=>{v.error(`AI Kit initialization failed`,i(s,e)),z=!1,u=!0,H=null,U=null,q=null}),a(f.ready,()=>f.aikit?{curated:f.aikit.curated,stateStore:f.aikit.stateStore}:null,s)}catch(e){v.error(`Failed to load server modules`,i(s,e)),z=!1,q=null}},100)}),Q=!1,$=async e=>{Q||(Q=!0,v.info(`Shutdown signal received`,{signal:e}),o(),B?.stop(),V?.stop(),await import(`../../tools/dist/index.js`).then(({processStopAll:e})=>e()).catch(()=>{}),await W?.closeAll().catch(()=>void 0),K&&V?.onSessionEnd(K),G&&(await G.close().catch(()=>void 0),G=null,K=null),Z.close(),H&&await H.close(),await q?.().catch(()=>void 0),process.exit(0))};process.on(`SIGINT`,()=>$(`SIGINT`)),process.on(`SIGTERM`,()=>$(`SIGTERM`))}export{y as startHttpMode};
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- import{n as e,t}from"./startup-maintenance-cbRSFMY5.js";import{a as n,i as r,o as i,s as a}from"./bin.js";import{t as o}from"./register-tools-C49Lkpvq.js";import{createLogger as s,serializeError as c,setDetailedErrorLoggingEnabled as l}from"../../core/dist/index.js";import{randomUUID as u}from"node:crypto";const d=`__pending__:`;function f(e){return e.startsWith(d)}function p(e){let t=e.headers[`mcp-session-id`];return Array.isArray(t)?t[0]:t}function m(e,t,n,r){e.status(t).json({jsonrpc:`2.0`,error:{code:n,message:r},id:null})}var h=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=p(e),i=r?this.runtimes.get(r):void 0;if(r&&!i){m(t,404,-32001,`Session not found`);return}if(!i){if(e.method!==`POST`){m(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`&&!f(r)&&this.options.onSessionActivity?.(r),e.method===`DELETE`&&!f(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&&!f(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){m(e,503,-32003,`Session capacity reached`);return}let t=this.now(),n=await this.options.createServer(),r={id:`${d}${u()}`,transport:void 0,createdAt:t,lastAccessAt:t,server:n,requestChain:Promise.resolve()},i=this.options.createTransport({sessionIdGenerator:()=>u(),onsessioninitialized:async e=>{this.runtimes.delete(r.id),r.id=e,this.runtimes.set(e,r),this.options.onSessionStart?.(e)},onsessionclosed:async e=>{e&&await this.closeSession(e,{closeTransport:!1})}});return r.transport=i,i.onclose=()=>{let e=r.transport.sessionId??r.id;this.closeSession(e,{closeTransport:!1})},this.runtimes.set(r.id,r),await n.connect(i),r}async withRuntimeLock(e,t){let n=e.requestChain,r;e.requestChain=new Promise(e=>{r=e}),await n;try{await t()}finally{r()}}};function g(e){let t=e.includes(`T`)?e:`${e.replace(` `,`T`)}Z`;return Date.parse(t)}var _=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=g(n.lastActivity);return Number.isFinite(r)&&e-r>=t}).map(e=>e.sessionId)}};const v=s(`server`);async function y(s,d){let[{default:f},{loadConfig:p,resolveIndexMode:m},{registerDashboardRoutes:g,resolveDashboardDir:y},{registerSettingsRoutes:b,resolveSettingsDir:x},{createSettingsRouter:S},{authMiddleware:C,getOrCreateToken:w}]=await Promise.all([import(`express`),import(`./config-DX1KYSbN.js`),import(`./dashboard-static-DdsIJd-u.js`),import(`./settings-static-DVMG47Oh.js`),import(`./routes-Ct7q5jrL.js`),import(`./auth-bEP-6uqy.js`)]),T=p();l(T.logging?.errorDetails===!0),T.configError&&v.warn(`Config load failure`,{error:T.configError}),v.info(`Config loaded`,{sourceCount:T.sources.length,storePath:T.store.path});let E=f();E.use(f.json({limit:`1mb`}));let D=Number(d),O=`http://localhost:${D}`,k=process.env.AIKIT_CORS_ORIGIN??O,A=process.env.AIKIT_ALLOW_ANY_ORIGIN===`true`,j=i(`AIKIT_HTTP_MAX_SESSIONS`,8),M=i(`AIKIT_HTTP_SESSION_TIMEOUT_MINUTES`,30),N=i(`AIKIT_HTTP_SESSION_GC_INTERVAL_MINUTES`,5),P=r({limit:100,windowMs:6e4}),F=!1;E.use((e,t,n)=>{let r=Array.isArray(e.headers.origin)?e.headers.origin[0]:e.headers.origin,i=a({requestOrigin:r,configuredOrigin:k,allowAnyOrigin:A,fallbackOrigin:O});if(i.warn&&!F&&(F=!0,v.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 I=w();E.use(C(I)),E.use(`/mcp`,(e,t,r)=>{let i=n(e)??e.ip??e.socket.remoteAddress??`anonymous`;if(P.allow(i)){r();return}let a=Math.max(1,Math.ceil(P.getRetryAfterMs(i)/1e3));t.setHeader(`Retry-After`,String(a)),t.status(429).json({jsonrpc:`2.0`,error:{code:-32003,message:`Rate limit exceeded`},id:null})});let L;E.use(`/mcp`,(e,t,n)=>{if(!L){let t=e.headers[`x-workspace-root`];typeof t==`string`&&t.length>0&&(L=t,v.debug(`Captured workspace root from proxy header`,{wsRoot:t}))}n()}),g(E,y(),v);let R=new Date().toISOString();E.use(`/settings/api`,S({log:v,mcpInfo:()=>({transport:`http`,port:D,pid:process.pid,startedAt:R})})),b(E,x(),v),E.get(`/health`,(e,t)=>{t.json({status:`ok`})});let z=!1,B=null,V=null,H=null,U=null,W=null,G=null,K=null,q=null,J=Promise.resolve(),Y=async(e,t)=>{if(!z||!H||!U){t.status(503).json({jsonrpc:`2.0`,error:{code:-32603,message:`Server initializing — please retry in a few seconds`},id:null});return}let r=J,i;J=new Promise(e=>{i=e});let a={POST:6e4,GET:1e4,DELETE:1e4}[e.method]??3e4;if(!await Promise.race([r.then(()=>!0),new Promise(t=>{let n=setTimeout(()=>{v.warn(`mcpLock timed out waiting for previous request, resetting lock chain`,{method:e.method,timeoutMs:a}),t(!1)},a);n.unref&&n.unref()})])&&(J=Promise.resolve(),i=()=>{},G)){let e=G;G=null,K=null,e.close().catch(()=>{})}try{let r=n(e);if(!G){if(r){t.status(404).json({jsonrpc:`2.0`,error:{code:-32001,message:`Session not found`},id:null});return}let e=new U({sessionIdGenerator:()=>u(),onsessioninitialized:async e=>{K=e,V?.onSessionStart(e,{transport:`http`})},onsessionclosed:async e=>{e&&V?.onSessionEnd(e),K=null}});e.onclose=()=>{G===e&&(G=null),K===e.sessionId&&(K=null)},G=e,await H.connect(e)}let i=G;await i.handleRequest(e,t,e.body),e.method!==`DELETE`&&(!r&&i.sessionId?(K=i.sessionId,V?.onSessionStart(i.sessionId,{transport:`http`}),V?.onSessionActivity(i.sessionId)):r&&V?.onSessionActivity(r))}catch(e){if(v.error(`MCP handler error`,c(e)),!t.headersSent){let n=e instanceof Error?e.message:String(e),r=n.includes(`Not Acceptable`);t.status(r?406:500).json({jsonrpc:`2.0`,error:{code:r?-32e3:-32603,message:r?n:`Internal server error`},id:null})}}finally{i()}},X=async(e,t)=>{let r=n(e);if(W&&(!G||r!==K)){await W.handleRequest(e,t,e.body);return}await Y(e,t)};E.post(`/mcp`,X),E.get(`/mcp`,X),E.delete(`/mcp`,X);let Z=E.listen(D,`127.0.0.1`,()=>{v.info(`MCP server listening`,{url:`http://127.0.0.1:${D}/mcp`,port:D}),setTimeout(async()=>{try{typeof L==`string`&&L.length>0&&(T.sources[0]={path:L,excludePatterns:T.sources[0]?.excludePatterns??[]},T.allRoots=[L],v.debug(`Workspace root applied from proxy header`,{wsRoot:L}));let[{createLazyServer:n,createMcpServer:r,ALL_TOOL_NAMES:i},{StreamableHTTPServerTransport:a},{checkForUpdates:o,autoUpgradeScaffold:l}]=await Promise.all([import(`./server-CTUxU4KX.js`),import(`@modelcontextprotocol/sdk/server/streamableHttp.js`),import(`./startup-maintenance-cbRSFMY5.js`).then(e=>e.u)]);o(),l(),setInterval(o,1440*60*1e3).unref();let u=!1,d=m(T),f=n(T,d);q=async()=>{f.aikit&&await Promise.all([f.aikit.embedder.shutdown?.().catch(()=>{})??Promise.resolve(),f.aikit.graphStore.close().catch(()=>{}),f.aikit.closeStateStore?.().catch(()=>{})??Promise.resolve(),f.aikit.store.close().catch(()=>{})])},H=f.server,U=a,z=!0,v.debug(`MCP server configured (lazy — AI Kit initializing in background)`,{toolCount:i.length,resourceCount:2}),f.startInit(),f.ready.then(async()=>{try{if(!f.aikit)throw Error(`AI Kit components are not available after initialization`);V=new _(f.aikit.stateStore,{staleTimeoutMinutes:M,gcIntervalMinutes:N,onBeforeSessionDelete:e=>{if(K===e&&G){let e=G;G=null,K=null,e.close().catch(()=>void 0)}W?.closeSession(e,{notifySessionEnd:!1})},onSessionEndMaintenance:async()=>{if(!f.aikit?.curated||!f.aikit?.stateStore)return;let{pruneLessons:e}=await import(`./startup-maintenance-cbRSFMY5.js`).then(e=>e.x),t=await e(f.aikit.curated,f.aikit.stateStore,{dryRun:!1});t.pruned.length>0&&v.info(`Session-end lesson prune`,{pruned:t.pruned.length})}}),W=new h({createServer:()=>{if(!f.aikit)throw Error(`AI Kit components are not available after initialization`);return r(f.aikit,T)},createTransport:e=>new a(e),maxSessions:j,sessionTimeoutMinutes:M,onSessionStart:e=>V?.onSessionStart(e,{transport:`http`}),onSessionActivity:e=>V?.onSessionActivity(e),onSessionEnd:e=>V?.onSessionEnd(e)}),V.startGC(),K&&(V.onSessionStart(K,{transport:`http`}),V.onSessionActivity(K)),v.info(`HTTP session runtime ready`,{maxSessions:j,sessionTimeoutMinutes:M,gcIntervalMinutes:N})}catch(e){v.error(`Failed to start session manager`,c(e)),z=!1,u=!0,H=null,U=null,q=null}}),d===`auto`?f.ready.then(async()=>{try{let e=T.sources.map(e=>e.path).join(`, `);v.info(`Running initial index`,{sourcePaths:e}),await f.runInitialIndex(),v.info(`Initial index complete`)}catch(t){v.error(`Initial index failed; will retry on aikit_reindex`,e(s,t))}}):d===`smart`?u||f.ready.then(async()=>{try{if(!f.aikit)throw Error(`AI Kit components are not available after initialization`);let{SmartIndexScheduler:e}=await import(`../../indexer/dist/index.js`),t=new e(f.aikit.indexer,T,f.aikit.store),n=f.aikit.store;B=t,t.start(),n.onBeforeClose&&n.onBeforeClose(()=>t.stop()),f.setSmartScheduler(t),v.debug(`Smart index scheduler started (HTTP mode)`)}catch(t){v.error(`Failed to start smart index scheduler`,e(s,t))}}):v.info(`Initial full indexing skipped in HTTP mode`,{indexMode:d}),f.ready.catch(t=>{v.error(`AI Kit initialization failed`,e(s,t)),z=!1,u=!0,H=null,U=null,q=null}),t(f.ready,()=>f.aikit?{curated:f.aikit.curated,stateStore:f.aikit.stateStore}:null,s)}catch(t){v.error(`Failed to load server modules`,e(s,t)),z=!1,q=null}},100)}),Q=!1,$=async e=>{Q||(Q=!0,v.info(`Shutdown signal received`,{signal:e}),o(),B?.stop(),V?.stop(),await import(`../../tools/dist/index.js`).then(({processStopAll:e})=>e()).catch(()=>{}),await W?.closeAll().catch(()=>void 0),K&&V?.onSessionEnd(K),G&&(await G.close().catch(()=>void 0),G=null,K=null),Z.close(),H&&await H.close(),await q?.().catch(()=>void 0),process.exit(0))};process.on(`SIGINT`,()=>$(`SIGINT`)),process.on(`SIGTERM`,()=>$(`SIGTERM`))}export{y as startHttpMode};
2
+ import{n as e,t}from"./startup-maintenance-D7tKqECM.js";import{a as n,i as r,o as i,s as a}from"./bin.js";import{t as o}from"./register-tools-CCDtIMgE.js";import{createLogger as s,serializeError as c,setDetailedErrorLoggingEnabled as l}from"../../core/dist/index.js";import{randomUUID as u}from"node:crypto";const d=`__pending__:`;function f(e){return e.startsWith(d)}function p(e){let t=e.headers[`mcp-session-id`];return Array.isArray(t)?t[0]:t}function m(e,t,n,r){e.status(t).json({jsonrpc:`2.0`,error:{code:n,message:r},id:null})}var h=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=p(e),i=r?this.runtimes.get(r):void 0;if(r&&!i){m(t,404,-32001,`Session not found`);return}if(!i){if(e.method!==`POST`){m(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`&&!f(r)&&this.options.onSessionActivity?.(r),e.method===`DELETE`&&!f(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&&!f(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){m(e,503,-32003,`Session capacity reached`);return}let t=this.now(),n=await this.options.createServer(),r={id:`${d}${u()}`,transport:void 0,createdAt:t,lastAccessAt:t,server:n,requestChain:Promise.resolve()},i=this.options.createTransport({sessionIdGenerator:()=>u(),onsessioninitialized:async e=>{this.runtimes.delete(r.id),r.id=e,this.runtimes.set(e,r),this.options.onSessionStart?.(e)},onsessionclosed:async e=>{e&&await this.closeSession(e,{closeTransport:!1})}});return r.transport=i,i.onclose=()=>{let e=r.transport.sessionId??r.id;this.closeSession(e,{closeTransport:!1})},this.runtimes.set(r.id,r),await n.connect(i),r}async withRuntimeLock(e,t){let n=e.requestChain,r;e.requestChain=new Promise(e=>{r=e}),await n;try{await t()}finally{r()}}};function g(e){let t=e.includes(`T`)?e:`${e.replace(` `,`T`)}Z`;return Date.parse(t)}var _=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=g(n.lastActivity);return Number.isFinite(r)&&e-r>=t}).map(e=>e.sessionId)}};const v=s(`server`);async function y(s,d){let[{default:f},{loadConfig:p,resolveIndexMode:m},{registerDashboardRoutes:g,resolveDashboardDir:y},{registerSettingsRoutes:b,resolveSettingsDir:x},{createSettingsRouter:S},{authMiddleware:C,getOrCreateToken:w}]=await Promise.all([import(`express`),import(`./config-CkXCQx7E.js`),import(`./dashboard-static-CVRj5Cbv.js`),import(`./settings-static-VnUkp9iU.js`),import(`./routes-Ct7q5jrL.js`),import(`./auth-bEP-6uqy.js`)]),T=p();l(T.logging?.errorDetails===!0),T.configError&&v.warn(`Config load failure`,{error:T.configError}),v.info(`Config loaded`,{sourceCount:T.sources.length,storePath:T.store.path});let E=f();E.use(f.json({limit:`1mb`}));let D=Number(d),O=`http://localhost:${D}`,k=process.env.AIKIT_CORS_ORIGIN??O,A=process.env.AIKIT_ALLOW_ANY_ORIGIN===`true`,j=i(`AIKIT_HTTP_MAX_SESSIONS`,8),M=i(`AIKIT_HTTP_SESSION_TIMEOUT_MINUTES`,30),N=i(`AIKIT_HTTP_SESSION_GC_INTERVAL_MINUTES`,5),P=r({limit:100,windowMs:6e4}),F=!1;E.use((e,t,n)=>{let r=Array.isArray(e.headers.origin)?e.headers.origin[0]:e.headers.origin,i=a({requestOrigin:r,configuredOrigin:k,allowAnyOrigin:A,fallbackOrigin:O});if(i.warn&&!F&&(F=!0,v.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 I=w();E.use(C(I)),E.use(`/mcp`,(e,t,r)=>{let i=n(e)??e.ip??e.socket.remoteAddress??`anonymous`;if(P.allow(i)){r();return}let a=Math.max(1,Math.ceil(P.getRetryAfterMs(i)/1e3));t.setHeader(`Retry-After`,String(a)),t.status(429).json({jsonrpc:`2.0`,error:{code:-32003,message:`Rate limit exceeded`},id:null})});let L;E.use(`/mcp`,(e,t,n)=>{if(!L){let t=e.headers[`x-workspace-root`];typeof t==`string`&&t.length>0&&(L=t,v.debug(`Captured workspace root from proxy header`,{wsRoot:t}))}n()}),g(E,y(),v);let R=new Date().toISOString();E.use(`/settings/api`,S({log:v,mcpInfo:()=>({transport:`http`,port:D,pid:process.pid,startedAt:R})})),b(E,x(),v),E.get(`/health`,(e,t)=>{t.json({status:`ok`})});let z=!1,B=null,V=null,H=null,U=null,W=null,G=null,K=null,q=null,J=Promise.resolve(),Y=async(e,t)=>{if(!z||!H||!U){t.status(503).json({jsonrpc:`2.0`,error:{code:-32603,message:`Server initializing — please retry in a few seconds`},id:null});return}let r=J,i;J=new Promise(e=>{i=e});let a={POST:6e4,GET:1e4,DELETE:1e4}[e.method]??3e4;if(!await Promise.race([r.then(()=>!0),new Promise(t=>{let n=setTimeout(()=>{v.warn(`mcpLock timed out waiting for previous request, resetting lock chain`,{method:e.method,timeoutMs:a}),t(!1)},a);n.unref&&n.unref()})])&&(J=Promise.resolve(),i=()=>{},G)){let e=G;G=null,K=null,e.close().catch(()=>{})}try{let r=n(e);if(!G){if(r){t.status(404).json({jsonrpc:`2.0`,error:{code:-32001,message:`Session not found`},id:null});return}let e=new U({sessionIdGenerator:()=>u(),onsessioninitialized:async e=>{K=e,V?.onSessionStart(e,{transport:`http`})},onsessionclosed:async e=>{e&&V?.onSessionEnd(e),K=null}});e.onclose=()=>{G===e&&(G=null),K===e.sessionId&&(K=null)},G=e,await H.connect(e)}let i=G;await i.handleRequest(e,t,e.body),e.method!==`DELETE`&&(!r&&i.sessionId?(K=i.sessionId,V?.onSessionStart(i.sessionId,{transport:`http`}),V?.onSessionActivity(i.sessionId)):r&&V?.onSessionActivity(r))}catch(e){if(v.error(`MCP handler error`,c(e)),!t.headersSent){let n=e instanceof Error?e.message:String(e),r=n.includes(`Not Acceptable`);t.status(r?406:500).json({jsonrpc:`2.0`,error:{code:r?-32e3:-32603,message:r?n:`Internal server error`},id:null})}}finally{i()}},X=async(e,t)=>{let r=n(e);if(W&&(!G||r!==K)){await W.handleRequest(e,t,e.body);return}await Y(e,t)};E.post(`/mcp`,X),E.get(`/mcp`,X),E.delete(`/mcp`,X);let Z=E.listen(D,`127.0.0.1`,()=>{v.info(`MCP server listening`,{url:`http://127.0.0.1:${D}/mcp`,port:D}),setTimeout(async()=>{try{typeof L==`string`&&L.length>0&&(T.sources[0]={path:L,excludePatterns:T.sources[0]?.excludePatterns??[]},T.allRoots=[L],v.debug(`Workspace root applied from proxy header`,{wsRoot:L}));let[{createLazyServer:n,createMcpServer:r,ALL_TOOL_NAMES:i},{StreamableHTTPServerTransport:a},{checkForUpdates:o,autoUpgradeScaffold:l}]=await Promise.all([import(`./server-B6YroA9y.js`),import(`@modelcontextprotocol/sdk/server/streamableHttp.js`),import(`./startup-maintenance-D7tKqECM.js`).then(e=>e.u)]);o(),l(),setInterval(o,1440*60*1e3).unref();let u=!1,d=m(T),f=n(T,d);q=async()=>{f.aikit&&await Promise.all([f.aikit.embedder.shutdown?.().catch(()=>{})??Promise.resolve(),f.aikit.graphStore.close().catch(()=>{}),f.aikit.closeStateStore?.().catch(()=>{})??Promise.resolve(),f.aikit.store.close().catch(()=>{})])},H=f.server,U=a,z=!0,v.debug(`MCP server configured (lazy — AI Kit initializing in background)`,{toolCount:i.length,resourceCount:2}),f.startInit(),f.ready.then(async()=>{try{if(!f.aikit)throw Error(`AI Kit components are not available after initialization`);V=new _(f.aikit.stateStore,{staleTimeoutMinutes:M,gcIntervalMinutes:N,onBeforeSessionDelete:e=>{if(K===e&&G){let e=G;G=null,K=null,e.close().catch(()=>void 0)}W?.closeSession(e,{notifySessionEnd:!1})},onSessionEndMaintenance:async()=>{if(!f.aikit?.curated||!f.aikit?.stateStore)return;let{pruneLessons:e}=await import(`./startup-maintenance-D7tKqECM.js`).then(e=>e.x),t=await e(f.aikit.curated,f.aikit.stateStore,{dryRun:!1});t.pruned.length>0&&v.info(`Session-end lesson prune`,{pruned:t.pruned.length})}}),W=new h({createServer:()=>{if(!f.aikit)throw Error(`AI Kit components are not available after initialization`);return r(f.aikit,T)},createTransport:e=>new a(e),maxSessions:j,sessionTimeoutMinutes:M,onSessionStart:e=>V?.onSessionStart(e,{transport:`http`}),onSessionActivity:e=>V?.onSessionActivity(e),onSessionEnd:e=>V?.onSessionEnd(e)}),V.startGC(),K&&(V.onSessionStart(K,{transport:`http`}),V.onSessionActivity(K)),v.info(`HTTP session runtime ready`,{maxSessions:j,sessionTimeoutMinutes:M,gcIntervalMinutes:N})}catch(e){v.error(`Failed to start session manager`,c(e)),z=!1,u=!0,H=null,U=null,q=null}}),d===`auto`?f.ready.then(async()=>{try{let e=T.sources.map(e=>e.path).join(`, `);v.info(`Running initial index`,{sourcePaths:e}),await f.runInitialIndex(),v.info(`Initial index complete`)}catch(t){v.error(`Initial index failed; will retry on aikit_reindex`,e(s,t))}}):d===`smart`?u||f.ready.then(async()=>{try{if(!f.aikit)throw Error(`AI Kit components are not available after initialization`);let{SmartIndexScheduler:e}=await import(`../../indexer/dist/index.js`),t=new e(f.aikit.indexer,T,f.aikit.store),n=f.aikit.store;B=t,t.start(),n.onBeforeClose&&n.onBeforeClose(()=>t.stop()),f.setSmartScheduler(t),v.debug(`Smart index scheduler started (HTTP mode)`)}catch(t){v.error(`Failed to start smart index scheduler`,e(s,t))}}):v.info(`Initial full indexing skipped in HTTP mode`,{indexMode:d}),f.ready.catch(t=>{v.error(`AI Kit initialization failed`,e(s,t)),z=!1,u=!0,H=null,U=null,q=null}),t(f.ready,()=>f.aikit?{curated:f.aikit.curated,stateStore:f.aikit.stateStore}:null,s)}catch(t){v.error(`Failed to load server modules`,e(s,t)),z=!1,q=null}},100)}),Q=!1,$=async e=>{Q||(Q=!0,v.info(`Shutdown signal received`,{signal:e}),o(),B?.stop(),V?.stop(),await import(`../../tools/dist/index.js`).then(({processStopAll:e})=>e()).catch(()=>{}),await W?.closeAll().catch(()=>void 0),K&&V?.onSessionEnd(K),G&&(await G.close().catch(()=>void 0),G=null,K=null),Z.close(),H&&await H.close(),await q?.().catch(()=>void 0),process.exit(0))};process.on(`SIGINT`,()=>$(`SIGINT`)),process.on(`SIGTERM`,()=>$(`SIGTERM`))}export{y as startHttpMode};
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- import{n as e,t}from"./startup-maintenance-cbRSFMY5.js";import{r as n}from"./bin.js";import{a as r,t as i}from"./register-tools-C49Lkpvq.js";import{createLogger as a,serializeError as o,setDetailedErrorLoggingEnabled as s}from"../../core/dist/index.js";const c=a(`server`);var l=class{buffer;append(e){this.buffer=this.buffer?Buffer.concat([this.buffer,e]):e}readMessage(){if(!this.buffer)return null;for(let e=0;e<this.buffer.length;e++){if(this.buffer[e]!==10)continue;let t=this.buffer.toString(`utf8`,0,e).replace(/\r$/,``),n=e+1;try{let e=JSON.parse(t);return this.buffer=this.buffer.subarray(n),e}catch{try{let e=r(t);return c.warn(`JSON parse failed on MCP message — repair succeeded`,{preview:t.slice(0,80)}),this.buffer=this.buffer.subarray(n),e}catch{}}}return null}clear(){this.buffer=void 0}};async function u(r){let[{loadConfig:a,reconfigureForWorkspace:u,resolveIndexMode:d},{createLazyServer:f},{checkForUpdates:p,autoUpgradeScaffold:m},{RootsListChangedNotificationSchema:h}]=await Promise.all([import(`./config-DX1KYSbN.js`),import(`./server-CTUxU4KX.js`),import(`./startup-maintenance-cbRSFMY5.js`).then(e=>e.u),import(`@modelcontextprotocol/sdk/types.js`)]),g=a();s(g.logging?.errorDetails===!0),g.configError&&c.warn(`Config load failure`,{error:g.configError}),c.info(`Config loaded`,{sourceCount:g.sources.length,storePath:g.store.path}),m(),setInterval(p,1440*60*1e3).unref();let _=d(g),v=f(g,_),{server:y,startInit:b,ready:x,runInitialIndex:S}=v,{StdioServerTransport:C}=await import(`@modelcontextprotocol/sdk/server/stdio.js`),w=new C;if(typeof w._readBuffer?.readMessage!=`function`)throw Error(`Cannot install JSON repair: StdioServerTransport._readBuffer has unexpected shape`);w._readBuffer=new l,c.debug(`JSON repair installed on stdio transport`),await y.connect(w),c.debug(`MCP server started`,{transport:`stdio`}),await n({config:g,indexMode:_,log:c,rootsChangedNotificationSchema:h,reconfigureForWorkspace:u,runInitialIndex:S,server:y,startInit:b,version:r});let T=null,E=null,D=!1,O=async e=>{D||(D=!0,c.info(`Shutdown signal received`,{signal:e}),i(),T&&=(clearTimeout(T),null),E?.stop(),await import(`../../tools/dist/index.js`).then(({processStopAll:e})=>e()).catch(()=>{}),await w.close().catch(()=>void 0),await y.close().catch(()=>void 0),v.aikit&&await Promise.all([v.aikit.embedder.shutdown?.().catch(()=>{})??Promise.resolve(),v.aikit.graphStore.close().catch(()=>{}),v.aikit.closeStateStore?.().catch(()=>{})??Promise.resolve(),v.aikit.store.close().catch(()=>{})]),process.exit(0))},k=()=>{T&&clearTimeout(T),T=setTimeout(async()=>{c.info(`Auto-shutdown: no activity for 30 minutes — releasing resources`),i();try{let e=v.aikit;e&&(e.embedder.shutdown?.().catch(()=>{}),e.store.releaseMemory?.(),e.graphStore.releaseMemory?.())}catch(e){c.warn(`Resource release failed during shutdown`,o(e))}},18e5),T.unref&&T.unref()};k(),process.stdin.on(`data`,()=>k()),process.stdin.on(`end`,()=>void O(`stdin-end`)),process.stdin.on(`close`,()=>void O(`stdin-close`)),process.stdin.on(`error`,()=>void O(`stdin-error`)),process.on(`SIGINT`,()=>void O(`SIGINT`)),process.on(`SIGTERM`,()=>void O(`SIGTERM`)),x.catch(t=>{c.error(`Initialization failed — server will continue with limited tools`,e(r,t))}),_===`smart`?x.then(async()=>{try{if(!v.aikit)throw Error(`AI Kit components are not available after initialization`);let{SmartIndexScheduler:e}=await import(`../../indexer/dist/index.js`),t=new e(v.aikit.indexer,g,v.aikit.store);E=t;let n=v.aikit.store;t.start(),n.onBeforeClose&&n.onBeforeClose(()=>t.stop()),v.setSmartScheduler(t),c.debug(`Smart index scheduler started (stdio mode)`)}catch(t){c.error(`Failed to start smart index scheduler`,e(r,t))}}).catch(t=>c.error(`AI Kit init failed for smart scheduler`,e(r,t))):c.warn(`Initial full indexing skipped; use aikit_reindex to index manually`,{indexMode:_}),t(x,()=>v.aikit?{curated:v.aikit.curated,stateStore:v.aikit.stateStore}:null,r)}export{u as startStdioMode};
2
+ import{n as e,t}from"./startup-maintenance-D7tKqECM.js";import{r as n}from"./bin.js";import{a as r,t as i}from"./register-tools-CCDtIMgE.js";import{createLogger as a,serializeError as o,setDetailedErrorLoggingEnabled as s}from"../../core/dist/index.js";const c=a(`server`);var l=class{buffer;append(e){this.buffer=this.buffer?Buffer.concat([this.buffer,e]):e}readMessage(){if(!this.buffer)return null;for(let e=0;e<this.buffer.length;e++){if(this.buffer[e]!==10)continue;let t=this.buffer.toString(`utf8`,0,e).replace(/\r$/,``),n=e+1;try{let e=JSON.parse(t);return this.buffer=this.buffer.subarray(n),e}catch{try{let e=r(t);return c.warn(`JSON parse failed on MCP message — repair succeeded`,{preview:t.slice(0,80)}),this.buffer=this.buffer.subarray(n),e}catch{}}}return null}clear(){this.buffer=void 0}};async function u(r){let[{loadConfig:a,reconfigureForWorkspace:u,resolveIndexMode:d},{createLazyServer:f},{checkForUpdates:p,autoUpgradeScaffold:m},{RootsListChangedNotificationSchema:h}]=await Promise.all([import(`./config-CkXCQx7E.js`),import(`./server-B6YroA9y.js`),import(`./startup-maintenance-D7tKqECM.js`).then(e=>e.u),import(`@modelcontextprotocol/sdk/types.js`)]),g=a();s(g.logging?.errorDetails===!0),g.configError&&c.warn(`Config load failure`,{error:g.configError}),c.info(`Config loaded`,{sourceCount:g.sources.length,storePath:g.store.path}),m(),setInterval(p,1440*60*1e3).unref();let _=d(g),v=f(g,_),{server:y,startInit:b,ready:x,runInitialIndex:S}=v,{StdioServerTransport:C}=await import(`@modelcontextprotocol/sdk/server/stdio.js`),w=new C;if(typeof w._readBuffer?.readMessage!=`function`)throw Error(`Cannot install JSON repair: StdioServerTransport._readBuffer has unexpected shape`);w._readBuffer=new l,c.debug(`JSON repair installed on stdio transport`),await y.connect(w),c.debug(`MCP server started`,{transport:`stdio`}),await n({config:g,indexMode:_,log:c,rootsChangedNotificationSchema:h,reconfigureForWorkspace:u,runInitialIndex:S,server:y,startInit:b,version:r});let T=null,E=null,D=!1,O=async e=>{D||(D=!0,c.info(`Shutdown signal received`,{signal:e}),i(),T&&=(clearTimeout(T),null),E?.stop(),await import(`../../tools/dist/index.js`).then(({processStopAll:e})=>e()).catch(()=>{}),await w.close().catch(()=>void 0),await y.close().catch(()=>void 0),v.aikit&&await Promise.all([v.aikit.embedder.shutdown?.().catch(()=>{})??Promise.resolve(),v.aikit.graphStore.close().catch(()=>{}),v.aikit.closeStateStore?.().catch(()=>{})??Promise.resolve(),v.aikit.store.close().catch(()=>{})]),process.exit(0))},k=()=>{T&&clearTimeout(T),T=setTimeout(async()=>{c.info(`Auto-shutdown: no activity for 30 minutes — releasing resources`),i();try{let e=v.aikit;e&&(e.embedder.shutdown?.().catch(()=>{}),e.store.releaseMemory?.(),e.graphStore.releaseMemory?.())}catch(e){c.warn(`Resource release failed during shutdown`,o(e))}},18e5),T.unref&&T.unref()};k(),process.stdin.on(`data`,()=>k()),process.stdin.on(`end`,()=>void O(`stdin-end`)),process.stdin.on(`close`,()=>void O(`stdin-close`)),process.stdin.on(`error`,()=>void O(`stdin-error`)),process.on(`SIGINT`,()=>void O(`SIGINT`)),process.on(`SIGTERM`,()=>void O(`SIGTERM`)),x.catch(t=>{c.error(`Initialization failed — server will continue with limited tools`,e(r,t))}),_===`smart`?x.then(async()=>{try{if(!v.aikit)throw Error(`AI Kit components are not available after initialization`);let{SmartIndexScheduler:e}=await import(`../../indexer/dist/index.js`),t=new e(v.aikit.indexer,g,v.aikit.store);E=t;let n=v.aikit.store;t.start(),n.onBeforeClose&&n.onBeforeClose(()=>t.stop()),v.setSmartScheduler(t),c.debug(`Smart index scheduler started (stdio mode)`)}catch(t){c.error(`Failed to start smart index scheduler`,e(r,t))}}).catch(t=>c.error(`AI Kit init failed for smart scheduler`,e(r,t))):c.warn(`Initial full indexing skipped; use aikit_reindex to index manually`,{indexMode:_}),t(x,()=>v.aikit?{curated:v.aikit.curated,stateStore:v.aikit.stateStore}:null,r)}export{u as startStdioMode};
@@ -1 +1 @@
1
- import{n as e}from"./workspace-bootstrap-DTnTU8p2.js";import{n as t,t as n}from"./startup-maintenance-kHH8tjds.js";import{a as r,t as i}from"./register-tools-i_1kjBhi.js";import{createLogger as a,serializeError as o,setDetailedErrorLoggingEnabled as s}from"../../core/dist/index.js";const c=a(`server`);var l=class{buffer;append(e){this.buffer=this.buffer?Buffer.concat([this.buffer,e]):e}readMessage(){if(!this.buffer)return null;for(let e=0;e<this.buffer.length;e++){if(this.buffer[e]!==10)continue;let t=this.buffer.toString(`utf8`,0,e).replace(/\r$/,``),n=e+1;try{let e=JSON.parse(t);return this.buffer=this.buffer.subarray(n),e}catch{try{let e=r(t);return c.warn(`JSON parse failed on MCP message — repair succeeded`,{preview:t.slice(0,80)}),this.buffer=this.buffer.subarray(n),e}catch{}}}return null}clear(){this.buffer=void 0}};async function u(r){let[{loadConfig:a,reconfigureForWorkspace:u,resolveIndexMode:d},{createLazyServer:f},{checkForUpdates:p,autoUpgradeScaffold:m},{RootsListChangedNotificationSchema:h}]=await Promise.all([import(`./config-CQKoGfwD.js`),import(`./server-Dm2u4PSm.js`),import(`./startup-maintenance-kHH8tjds.js`).then(e=>e.u),import(`@modelcontextprotocol/sdk/types.js`)]),g=a();s(g.logging?.errorDetails===!0),g.configError&&c.warn(`Config load failure`,{error:g.configError}),c.info(`Config loaded`,{sourceCount:g.sources.length,storePath:g.store.path}),m(),setInterval(p,1440*60*1e3).unref();let _=d(g),v=f(g,_),{server:y,startInit:b,ready:x,runInitialIndex:S}=v,{StdioServerTransport:C}=await import(`@modelcontextprotocol/sdk/server/stdio.js`),w=new C;if(typeof w._readBuffer?.readMessage!=`function`)throw Error(`Cannot install JSON repair: StdioServerTransport._readBuffer has unexpected shape`);w._readBuffer=new l,c.debug(`JSON repair installed on stdio transport`),await y.connect(w),c.debug(`MCP server started`,{transport:`stdio`}),await e({config:g,indexMode:_,log:c,rootsChangedNotificationSchema:h,reconfigureForWorkspace:u,runInitialIndex:S,server:y,startInit:b,version:r});let T=null,E=null,D=!1,O=async e=>{D||(D=!0,c.info(`Shutdown signal received`,{signal:e}),i(),T&&=(clearTimeout(T),null),E?.stop(),await import(`../../tools/dist/index.js`).then(({processStopAll:e})=>e()).catch(()=>{}),await w.close().catch(()=>void 0),await y.close().catch(()=>void 0),v.aikit&&await Promise.all([v.aikit.embedder.shutdown?.().catch(()=>{})??Promise.resolve(),v.aikit.graphStore.close().catch(()=>{}),v.aikit.closeStateStore?.().catch(()=>{})??Promise.resolve(),v.aikit.store.close().catch(()=>{})]),process.exit(0))},k=()=>{T&&clearTimeout(T),T=setTimeout(async()=>{c.info(`Auto-shutdown: no activity for 30 minutes — releasing resources`),i();try{let e=v.aikit;e&&(e.embedder.shutdown?.().catch(()=>{}),e.store.releaseMemory?.(),e.graphStore.releaseMemory?.())}catch(e){c.warn(`Resource release failed during shutdown`,o(e))}},18e5),T.unref&&T.unref()};k(),process.stdin.on(`data`,()=>k()),process.stdin.on(`end`,()=>void O(`stdin-end`)),process.stdin.on(`close`,()=>void O(`stdin-close`)),process.stdin.on(`error`,()=>void O(`stdin-error`)),process.on(`SIGINT`,()=>void O(`SIGINT`)),process.on(`SIGTERM`,()=>void O(`SIGTERM`)),x.catch(e=>{c.error(`Initialization failed — server will continue with limited tools`,t(r,e))}),_===`smart`?x.then(async()=>{try{if(!v.aikit)throw Error(`AI Kit components are not available after initialization`);let{SmartIndexScheduler:e}=await import(`../../indexer/dist/index.js`),t=new e(v.aikit.indexer,g,v.aikit.store);E=t;let n=v.aikit.store;t.start(),n.onBeforeClose&&n.onBeforeClose(()=>t.stop()),v.setSmartScheduler(t),c.debug(`Smart index scheduler started (stdio mode)`)}catch(e){c.error(`Failed to start smart index scheduler`,t(r,e))}}).catch(e=>c.error(`AI Kit init failed for smart scheduler`,t(r,e))):c.warn(`Initial full indexing skipped; use aikit_reindex to index manually`,{indexMode:_}),n(x,()=>v.aikit?{curated:v.aikit.curated,stateStore:v.aikit.stateStore}:null,r)}export{u as startStdioMode};
1
+ import{n as e}from"./workspace-bootstrap-DTnTU8p2.js";import{n as t,t as n}from"./startup-maintenance-QrloHssd.js";import{a as r,t as i}from"./register-tools-DLj1eMq3.js";import{createLogger as a,serializeError as o,setDetailedErrorLoggingEnabled as s}from"../../core/dist/index.js";const c=a(`server`);var l=class{buffer;append(e){this.buffer=this.buffer?Buffer.concat([this.buffer,e]):e}readMessage(){if(!this.buffer)return null;for(let e=0;e<this.buffer.length;e++){if(this.buffer[e]!==10)continue;let t=this.buffer.toString(`utf8`,0,e).replace(/\r$/,``),n=e+1;try{let e=JSON.parse(t);return this.buffer=this.buffer.subarray(n),e}catch{try{let e=r(t);return c.warn(`JSON parse failed on MCP message — repair succeeded`,{preview:t.slice(0,80)}),this.buffer=this.buffer.subarray(n),e}catch{}}}return null}clear(){this.buffer=void 0}};async function u(r){let[{loadConfig:a,reconfigureForWorkspace:u,resolveIndexMode:d},{createLazyServer:f},{checkForUpdates:p,autoUpgradeScaffold:m},{RootsListChangedNotificationSchema:h}]=await Promise.all([import(`./config-BS9mkd50.js`),import(`./server-QCZQCfjf.js`),import(`./startup-maintenance-QrloHssd.js`).then(e=>e.u),import(`@modelcontextprotocol/sdk/types.js`)]),g=a();s(g.logging?.errorDetails===!0),g.configError&&c.warn(`Config load failure`,{error:g.configError}),c.info(`Config loaded`,{sourceCount:g.sources.length,storePath:g.store.path}),m(),setInterval(p,1440*60*1e3).unref();let _=d(g),v=f(g,_),{server:y,startInit:b,ready:x,runInitialIndex:S}=v,{StdioServerTransport:C}=await import(`@modelcontextprotocol/sdk/server/stdio.js`),w=new C;if(typeof w._readBuffer?.readMessage!=`function`)throw Error(`Cannot install JSON repair: StdioServerTransport._readBuffer has unexpected shape`);w._readBuffer=new l,c.debug(`JSON repair installed on stdio transport`),await y.connect(w),c.debug(`MCP server started`,{transport:`stdio`}),await e({config:g,indexMode:_,log:c,rootsChangedNotificationSchema:h,reconfigureForWorkspace:u,runInitialIndex:S,server:y,startInit:b,version:r});let T=null,E=null,D=!1,O=async e=>{D||(D=!0,c.info(`Shutdown signal received`,{signal:e}),i(),T&&=(clearTimeout(T),null),E?.stop(),await import(`../../tools/dist/index.js`).then(({processStopAll:e})=>e()).catch(()=>{}),await w.close().catch(()=>void 0),await y.close().catch(()=>void 0),v.aikit&&await Promise.all([v.aikit.embedder.shutdown?.().catch(()=>{})??Promise.resolve(),v.aikit.graphStore.close().catch(()=>{}),v.aikit.closeStateStore?.().catch(()=>{})??Promise.resolve(),v.aikit.store.close().catch(()=>{})]),process.exit(0))},k=()=>{T&&clearTimeout(T),T=setTimeout(async()=>{c.info(`Auto-shutdown: no activity for 30 minutes — releasing resources`),i();try{let e=v.aikit;e&&(e.embedder.shutdown?.().catch(()=>{}),e.store.releaseMemory?.(),e.graphStore.releaseMemory?.())}catch(e){c.warn(`Resource release failed during shutdown`,o(e))}},18e5),T.unref&&T.unref()};k(),process.stdin.on(`data`,()=>k()),process.stdin.on(`end`,()=>void O(`stdin-end`)),process.stdin.on(`close`,()=>void O(`stdin-close`)),process.stdin.on(`error`,()=>void O(`stdin-error`)),process.on(`SIGINT`,()=>void O(`SIGINT`)),process.on(`SIGTERM`,()=>void O(`SIGTERM`)),x.catch(e=>{c.error(`Initialization failed — server will continue with limited tools`,t(r,e))}),_===`smart`?x.then(async()=>{try{if(!v.aikit)throw Error(`AI Kit components are not available after initialization`);let{SmartIndexScheduler:e}=await import(`../../indexer/dist/index.js`),t=new e(v.aikit.indexer,g,v.aikit.store);E=t;let n=v.aikit.store;t.start(),n.onBeforeClose&&n.onBeforeClose(()=>t.stop()),v.setSmartScheduler(t),c.debug(`Smart index scheduler started (stdio mode)`)}catch(e){c.error(`Failed to start smart index scheduler`,t(r,e))}}).catch(e=>c.error(`AI Kit init failed for smart scheduler`,t(r,e))):c.warn(`Initial full indexing skipped; use aikit_reindex to index manually`,{indexMode:_}),n(x,()=>v.aikit?{curated:v.aikit.curated,stateStore:v.aikit.stateStore}:null,r)}export{u as startStdioMode};
@@ -1 +1 @@
1
- import{w as e}from"./startup-maintenance-kHH8tjds.js";import{fileURLToPath as t}from"node:url";import{createReadStream as n,existsSync as r,statSync as i}from"node:fs";import{dirname as a,extname as o,join as s,resolve as c,sep as l}from"node:path";const u=import.meta.dirname??a(t(import.meta.url)),d={".html":`text/html`,".js":`application/javascript`,".css":`text/css`,".json":`application/json`,".png":`image/png`,".svg":`image/svg+xml`,".ico":`image/x-icon`,".woff":`font/woff`,".woff2":`font/woff2`};function f(t){return t?s(t,`..`,`..`,`settings-ui`,`dist`):e(`settings-ui`)??s(u,`..`,`..`,`settings-ui`,`dist`)}function p(e,t){let n=t.replace(/^\/settings\/?/,``)||`index.html`;if(n.startsWith(`api/`)||n===`api`)return{kind:`not-found`};try{n=decodeURIComponent(n)}catch{}let a=c(e,n);if(!(a===e||a.startsWith(`${e}${l}`)))return{kind:`forbidden`};try{if(i(a).isFile())return{kind:`file`,path:a,contentType:d[o(a)]??`application/octet-stream`}}catch{}let u=s(e,`index.html`);return r(u)?{kind:`spa`,path:u,contentType:`text/html`}:{kind:`not-found`}}function m(e,t,i){return r(t)?(e.get(`/settings{/*path}`,(e,r)=>{let i=p(t,e.path);if(i.kind===`forbidden`){r.status(403).end(`Forbidden`);return}if(i.kind===`not-found`){r.status(404).end(`Not found`);return}r.setHeader(`Content-Type`,i.contentType),i.kind===`file`&&/\.[a-f0-9]{8,}\.(js|css)$/i.test(i.path)?r.setHeader(`Cache-Control`,`public, max-age=31536000, immutable`):r.setHeader(`Cache-Control`,`no-cache`),n(i.path).pipe(r)}),i.info(`Settings UI available`,{url:`/settings/`,dir:t}),!0):!1}export{m as registerSettingsRoutes,f as resolveSettingsDir,p as resolveSettingsRequest};
1
+ import{w as e}from"./startup-maintenance-QrloHssd.js";import{fileURLToPath as t}from"node:url";import{createReadStream as n,existsSync as r,statSync as i}from"node:fs";import{dirname as a,extname as o,join as s,resolve as c,sep as l}from"node:path";const u=import.meta.dirname??a(t(import.meta.url)),d={".html":`text/html`,".js":`application/javascript`,".css":`text/css`,".json":`application/json`,".png":`image/png`,".svg":`image/svg+xml`,".ico":`image/x-icon`,".woff":`font/woff`,".woff2":`font/woff2`};function f(t){return t?s(t,`..`,`..`,`settings-ui`,`dist`):e(`settings-ui`)??s(u,`..`,`..`,`settings-ui`,`dist`)}function p(e,t){let n=t.replace(/^\/settings\/?/,``)||`index.html`;if(n.startsWith(`api/`)||n===`api`)return{kind:`not-found`};try{n=decodeURIComponent(n)}catch{}let a=c(e,n);if(!(a===e||a.startsWith(`${e}${l}`)))return{kind:`forbidden`};try{if(i(a).isFile())return{kind:`file`,path:a,contentType:d[o(a)]??`application/octet-stream`}}catch{}let u=s(e,`index.html`);return r(u)?{kind:`spa`,path:u,contentType:`text/html`}:{kind:`not-found`}}function m(e,t,i){return r(t)?(e.get(`/settings{/*path}`,(e,r)=>{let i=p(t,e.path);if(i.kind===`forbidden`){r.status(403).end(`Forbidden`);return}if(i.kind===`not-found`){r.status(404).end(`Not found`);return}r.setHeader(`Content-Type`,i.contentType),i.kind===`file`&&/\.[a-f0-9]{8,}\.(js|css)$/i.test(i.path)?r.setHeader(`Cache-Control`,`public, max-age=31536000, immutable`):r.setHeader(`Cache-Control`,`no-cache`),n(i.path).pipe(r)}),i.info(`Settings UI available`,{url:`/settings/`,dir:t}),!0):!1}export{m as registerSettingsRoutes,f as resolveSettingsDir,p as resolveSettingsRequest};
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- import{w as e}from"./startup-maintenance-cbRSFMY5.js";import{fileURLToPath as t}from"node:url";import{createReadStream as n,existsSync as r,statSync as i}from"node:fs";import{dirname as a,extname as o,join as s,resolve as c,sep as l}from"node:path";const u=import.meta.dirname??a(t(import.meta.url)),d={".html":`text/html`,".js":`application/javascript`,".css":`text/css`,".json":`application/json`,".png":`image/png`,".svg":`image/svg+xml`,".ico":`image/x-icon`,".woff":`font/woff`,".woff2":`font/woff2`};function f(t){return t?s(t,`..`,`..`,`settings-ui`,`dist`):e(`settings-ui`)??s(u,`..`,`..`,`settings-ui`,`dist`)}function p(e,t){let n=t.replace(/^\/settings\/?/,``)||`index.html`;if(n.startsWith(`api/`)||n===`api`)return{kind:`not-found`};try{n=decodeURIComponent(n)}catch{}let a=c(e,n);if(!(a===e||a.startsWith(`${e}${l}`)))return{kind:`forbidden`};try{if(i(a).isFile())return{kind:`file`,path:a,contentType:d[o(a)]??`application/octet-stream`}}catch{}let u=s(e,`index.html`);return r(u)?{kind:`spa`,path:u,contentType:`text/html`}:{kind:`not-found`}}function m(e,t,i){return r(t)?(e.get(`/settings{/*path}`,(e,r)=>{let i=p(t,e.path);if(i.kind===`forbidden`){r.status(403).end(`Forbidden`);return}if(i.kind===`not-found`){r.status(404).end(`Not found`);return}r.setHeader(`Content-Type`,i.contentType),i.kind===`file`&&/\.[a-f0-9]{8,}\.(js|css)$/i.test(i.path)?r.setHeader(`Cache-Control`,`public, max-age=31536000, immutable`):r.setHeader(`Cache-Control`,`no-cache`),n(i.path).pipe(r)}),i.info(`Settings UI available`,{url:`/settings/`,dir:t}),!0):!1}export{m as registerSettingsRoutes,f as resolveSettingsDir,p as resolveSettingsRequest};
2
+ import{w as e}from"./startup-maintenance-D7tKqECM.js";import{fileURLToPath as t}from"node:url";import{createReadStream as n,existsSync as r,statSync as i}from"node:fs";import{dirname as a,extname as o,join as s,resolve as c,sep as l}from"node:path";const u=import.meta.dirname??a(t(import.meta.url)),d={".html":`text/html`,".js":`application/javascript`,".css":`text/css`,".json":`application/json`,".png":`image/png`,".svg":`image/svg+xml`,".ico":`image/x-icon`,".woff":`font/woff`,".woff2":`font/woff2`};function f(t){return t?s(t,`..`,`..`,`settings-ui`,`dist`):e(`settings-ui`)??s(u,`..`,`..`,`settings-ui`,`dist`)}function p(e,t){let n=t.replace(/^\/settings\/?/,``)||`index.html`;if(n.startsWith(`api/`)||n===`api`)return{kind:`not-found`};try{n=decodeURIComponent(n)}catch{}let a=c(e,n);if(!(a===e||a.startsWith(`${e}${l}`)))return{kind:`forbidden`};try{if(i(a).isFile())return{kind:`file`,path:a,contentType:d[o(a)]??`application/octet-stream`}}catch{}let u=s(e,`index.html`);return r(u)?{kind:`spa`,path:u,contentType:`text/html`}:{kind:`not-found`}}function m(e,t,i){return r(t)?(e.get(`/settings{/*path}`,(e,r)=>{let i=p(t,e.path);if(i.kind===`forbidden`){r.status(403).end(`Forbidden`);return}if(i.kind===`not-found`){r.status(404).end(`Not found`);return}r.setHeader(`Content-Type`,i.contentType),i.kind===`file`&&/\.[a-f0-9]{8,}\.(js|css)$/i.test(i.path)?r.setHeader(`Cache-Control`,`public, max-age=31536000, immutable`):r.setHeader(`Cache-Control`,`no-cache`),n(i.path).pipe(r)}),i.info(`Settings UI available`,{url:`/settings/`,dir:t}),!0):!1}export{m as registerSettingsRoutes,f as resolveSettingsDir,p as resolveSettingsRequest};
@@ -0,0 +1,21 @@
1
+ #!/usr/bin/env node
2
+ import{t as e}from"./bin.js";import{createRequire as t}from"node:module";import{fileURLToPath as n}from"node:url";import{INSTALL_ARGS as r,cleanupOldVersions as i,createLogger as a,getGlobalDataDir as o,isUserInstalled as s,listWorkspaces as c,safeCwd as l,serializeError as u}from"../../core/dist/index.js";import{existsSync as d,mkdirSync as f,readFileSync as p,renameSync as m,rmSync as h,statSync as ee,unlinkSync as te,writeFileSync as g}from"node:fs";import{dirname as _,join as v,resolve as y}from"node:path";import{readFile as ne,writeFile as re}from"node:fs/promises";import{homedir as b}from"node:os";import{execFile as ie,execSync as x,spawn as ae}from"node:child_process";var oe=Object.defineProperty,S=(e,t)=>{let n={};for(var r in e)oe(n,r,{get:e[r],enumerable:!0});return t||oe(n,Symbol.toStringTag,{value:`Module`}),n};const C={workingToEpisodicAccesses:2,episodicToSemanticReferences:3,semanticToProceduralVerifications:5},se={working:1,episodic:2,semantic:4,procedural:12};function ce(e,t=C){switch(e.tier){case`working`:if(e.accessCount>=t.workingToEpisodicAccesses)return`episodic`;break;case`episodic`:if(e.accessCount>=t.workingToEpisodicAccesses+t.episodicToSemanticReferences)return`semantic`;break;case`semantic`:if(e.accessCount>=t.workingToEpisodicAccesses+t.episodicToSemanticReferences+t.semanticToProceduralVerifications)return`procedural`;break;case`procedural`:break;default:break}}function le(e,t,n){e.memoryMetaUpdateTier(t,n)}const w={confirmIncrement:10,contradictDecrement:20,weeklyDecay:2,implicitUseIncrement:3,staleThreshold:30,staleDays:21,decayFloor:10,autoArchiveDays:30,archiveThreshold:20},ue=`lesson:auto-archive`;function T(e){return{confirmIncrement:Math.max(0,Math.trunc(e?.confirmIncrement??w.confirmIncrement)),contradictDecrement:Math.max(0,Math.trunc(e?.contradictDecrement??w.contradictDecrement)),weeklyDecay:Math.max(0,Math.trunc(e?.weeklyDecay??w.weeklyDecay)),implicitUseIncrement:Math.max(0,Math.trunc(e?.implicitUseIncrement??w.implicitUseIncrement)),staleThreshold:Math.min(100,Math.max(0,Math.trunc(e?.staleThreshold??w.staleThreshold))),staleDays:Math.max(1,Math.trunc(e?.staleDays??w.staleDays)),decayFloor:Math.min(100,Math.max(0,Math.trunc(e?.decayFloor??w.decayFloor))),autoArchiveDays:Math.max(1,Math.trunc(e?.autoArchiveDays??w.autoArchiveDays)),archiveThreshold:Math.min(100,Math.max(0,Math.trunc(e?.archiveThreshold??w.archiveThreshold)))}}function de(e){return[`## Lesson: ${e.title}`,``,`**Confidence:** ${e.confidence}/100`,``,`### Context`,e.context,``,`### Insight`,e.insight,``,`### Evidence`,e.evidence].join(`
3
+ `)}function E(e){let t=e.match(/^## Lesson:\s+(.+)$/m),n=e.match(/\*\*Confidence:\*\*\s+(\d+)\/100/),r=e.match(/### Context\r?\n([\s\S]*?)(?=\r?\n### |$)/),i=e.match(/### Insight\r?\n([\s\S]*?)(?=\r?\n### |$)/),a=e.match(/### Evidence\r?\n([\s\S]*?)(?=\r?\n### |$)/);return{title:t?.[1]?.trim(),confidence:n?Number(n[1]):void 0,context:r?.[1]?.trim(),insight:i?.[1]?.trim(),evidence:a?.[1]?.trim()}}function fe(e,t){let n=Math.min(100,Math.max(0,Math.trunc(t)));return/\*\*Confidence:\*\*/.test(e)?e.replace(/\*\*Confidence:\*\*\s+\d+\/100/,`**Confidence:** ${n}/100`):e.match(/^(## Lesson:[^\r\n]*)(\r?\n)/)?e.replace(/^(## Lesson:[^\r\n]*)(\r?\n)/,`$1$2$2**Confidence:** ${n}/100$2$2`):`**Confidence:** ${n}/100\n\n${e}`}function pe(e,t,n=w){let r=T(n);return t===`confirm`?Math.min(100,e+r.confirmIncrement):Math.max(0,e-r.contradictDecrement)}function D(e,t,n,r=w,i=Date.now()){let a=T(r),o=!!t,s=t?new Date(t):new Date(n),c=Math.max(0,i-s.getTime());o||(c=Math.min(c,336*60*60*1e3));let l=c/(10080*60*1e3),u=Math.floor(l)*a.weeklyDecay;return Math.max(a.decayFloor,e-u)}function me(e,t=w,n=Date.now()){let r=T(t);if(D(e.confidence,e.lastAccessedAt,e.createdAt,t,n)>=r.staleThreshold)return!1;let i=e.lastAccessedAt?new Date(e.lastAccessedAt):new Date(e.createdAt);return Math.max(0,n-i.getTime())/(1e3*60*60*24)>=r.staleDays}function he(e,t=w,n=Date.now()){let r=T(t);if(D(e.confidence,e.lastAccessedAt,e.createdAt,t,n)>=r.archiveThreshold)return!1;let i=e.lastAccessedAt?new Date(e.lastAccessedAt):new Date(e.createdAt);return Math.max(0,n-i.getTime())/(1e3*60*60*24)>=r.autoArchiveDays}const O={stabilityHours:168,accessMultiplier:1.5,flagThreshold:.1,maxStabilityHours:8760};function ge(e){return{...O,...e}}function _e(e,t){if(!e)return t;let n=Date.parse(e);return Number.isNaN(n)?t:n}function ve(e){return e&&e in se?e:`working`}function ye(e,t,n,r=O,i){let a=typeof r==`string`?ve(r):`working`,o=ge(typeof r==`string`?i:r),s=_e(e,_e(n,Date.now())),c=Math.max(0,Date.now()-s)/(1e3*60*60),l=Math.min(o.stabilityHours*se[a]*o.accessMultiplier**Math.max(0,t),o.maxStabilityHours);return Math.exp(-c/l)}function be(e,t,n){let r=e.memoryMetaGet(t);if(!r)return;let i=ye(r.lastAccessedAt,r.accessCount,r.createdAt,r.tier,n);return r.retentionScore!==i&&e.memoryMetaUpdateScore(t,i),e.memoryMetaGet(t)??{...r,retentionScore:i}}function xe(e,t,n){e.memoryMetaGet(t)||e.memoryMetaCreate(t),e.memoryMetaTouch(t);let r=e.memoryMetaGet(t);if(!r)return 1;let i=ye(r.lastAccessedAt,r.accessCount,r.createdAt,r.tier,n);return e.memoryMetaUpdateScore(t,i),i}function Se(e,t){let n=ge(t);return e.memoryMetaList().map(t=>be(e,t.entryId,n)??t).filter(e=>e.retentionScore<n.flagThreshold).sort((e,t)=>e.retentionScore-t.retentionScore)}const k={threshold:.7,maxCompare:50,autoThreshold:.95};function Ce(e){let t=Math.min(1,Math.max(0,e?.threshold??k.threshold)),n=Math.min(1,Math.max(t,e?.autoThreshold??k.autoThreshold));return{threshold:t,maxCompare:Math.max(1,Math.trunc(e?.maxCompare??k.maxCompare)),autoThreshold:n}}function we(e){let t=e.toLowerCase().match(/[a-z0-9]{2,}/g)??[];return new Set(t)}function A(e,t){let n=we(e),r=we(t);if(n.size===0&&r.size===0)return 1;if(n.size===0||r.size===0)return 0;let i=new Set([...n].filter(e=>r.has(e))),a=new Set([...n,...r]);return i.size/a.size}function Te(e,t,n=k){let r=Ce(n);return t.slice(0,r.maxCompare).map(t=>({entryId:t.id,title:t.title,similarity:A(e,t.content),path:t.path})).filter(e=>e.similarity>=r.threshold).sort((e,t)=>t.similarity-e.similarity)}function Ee(e,t,n){e.memoryMetaCreate(t),e.memoryMetaSetSuperseded(t,n)}const De=t(import.meta.url),Oe=import.meta.dirname??_(n(import.meta.url)),j=new Map;function M(e){let t=j.get(e);if(t!==void 0)return t;let n=v(Oe,`..`,`..`,e);if(d(v(n,`package.json`)))return j.set(e,n),n;try{let t=_(De.resolve(`@aikit/${e}/package.json`));return j.set(e,t),t}catch{}let r=Oe;for(let t=0;t<6;t++){let t=v(r,`packages`,e);if(d(v(t,`package.json`)))return j.set(e,t),t;let n=_(r);if(n===r)break;r=n}return j.set(e,null),null}function ke(e,t=`dist`){let n=M(e);if(!n)return null;let r=v(n,t);return d(r)?r:null}function Ae(e,t){let n=M(e);if(!n)return null;for(let e of t){let t=v(n,e);if(d(t))return t}return null}var je=S({DEFAULT_GROUP_CONFIG:()=>P,DEFAULT_PRUNE_CONFIG:()=>N,groupLessons:()=>Ge,pruneLessons:()=>We});const N={maxConfidence:15,minIdleDays:30,safetyDays:7,maxPrune:20,dryRun:!0},P={similarityThreshold:.7,minGroupSize:2,maxGroups:10,dryRun:!0},Me=new Set([`the`,`a`,`to`,`for`,`in`,`of`,`and`,`is`,`use`]);function Ne(e){return{maxConfidence:Math.min(100,Math.max(0,Math.trunc(e?.maxConfidence??N.maxConfidence))),minIdleDays:Math.max(1,Math.trunc(e?.minIdleDays??N.minIdleDays)),safetyDays:Math.max(0,Math.trunc(e?.safetyDays??N.safetyDays)),maxPrune:Math.max(1,Math.trunc(e?.maxPrune??N.maxPrune)),dryRun:e?.dryRun??N.dryRun}}function Pe(e){return{similarityThreshold:Math.min(1,Math.max(0,e?.similarityThreshold??P.similarityThreshold)),minGroupSize:Math.max(2,Math.trunc(e?.minGroupSize??P.minGroupSize)),maxGroups:Math.max(1,Math.trunc(e?.maxGroups??P.maxGroups)),dryRun:e?.dryRun??P.dryRun}}function Fe(e){if(!e)return 0;let t=Date.parse(e);return Number.isNaN(t)?0:t}function Ie(e,t){let n=Math.max(Fe(e),Fe(t));return n===0?1/0:Math.max(0,Date.now()-n)/864e5}function Le(e){return e.toLowerCase().match(/[a-z0-9]{2,}/g)??[]}function Re(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``).slice(0,60)}function ze(e,t){return`${[`---`,`title: "${e.title.replace(/"/g,`\\"`)}"`,`category: ${e.category}`,`tags: [${e.tags.map(e=>`"${e}"`).join(`, `)}]`,`created: ${e.created}`,`updated: ${e.updated}`,`version: ${e.version}`,`origin: ${e.origin}`,`changelog:`,...e.changelog.map(e=>` - version: ${e.version}\n date: ${e.date}\n reason: "${e.reason.replace(/"/g,`\\"`)}"`),`---`].join(`
4
+ `)}\n\n${t}\n`}function Be(e,t){let n=e.map(()=>[]);for(let r=0;r<e.length;r+=1)for(let i=r+1;i<e.length;i+=1)A(e[r],e[i])>=t&&(n[r].push(i),n[i].push(r));return n}function Ve(e){let t=new Set,n=[];for(let r=0;r<e.length;r+=1){if(t.has(r))continue;let i=[r],a=[];for(t.add(r);i.length>0;){let n=i.pop();if(n!==void 0){a.push(n);for(let r of e[n])t.has(r)||(t.add(r),i.push(r))}}n.push(a)}return n}function He(e){let t=new Map,n=new Map,r=0;for(let i of e)for(let e of Le(i))Me.has(e)||(t.set(e,(t.get(e)??0)+1),n.has(e)||(n.set(e,r),r+=1));let i=[...t.entries()].sort((e,t)=>t[1]-e[1]||(n.get(e[0])??0)-(n.get(t[0])??0))[0];return i&&i[1]>1?Re(i[0]):Re(e.flatMap(e=>Le(e)).find(e=>!Me.has(e))??`lesson-group`)}async function Ue(e,t,n){let r=v(e.curatedDir,t),i=await ne(r,`utf8`),{frontmatter:a,content:o}=e.parseFile(i),s=`group:${n}`;if(a.tags.includes(s))return;let c=new Date().toISOString(),l=(a.version??1)+1;await re(r,ze({...a,tags:[...new Set([...a.tags,s])],updated:c,version:l,changelog:[...a.changelog??[],{version:l,date:c,reason:`Grouped lesson under ${n}`}]},o),`utf8`)}async function We(e,t,n,r){let i=Ne(n),a=T(r??w),o=(await e.list({category:`lessons`})).filter(e=>e.tags.includes(`lesson`)),s=o.map(e=>{let n=t.memoryMetaGet(e.path);if(!n||n.supersededBy!=null)return null;let r=Ie(n.lastAccessedAt,n.createdAt??e.created);if(r<i.safetyDays)return null;let o=D(n.confidence,n.lastAccessedAt,n.createdAt,a);return o>=i.maxConfidence||r<i.minIdleDays?null:{path:e.path,effectiveConfidence:o}}).filter(e=>e!==null).sort((e,t)=>e.effectiveConfidence-t.effectiveConfidence||e.path.localeCompare(t.path)).slice(0,i.maxPrune);if(!i.dryRun)for(let e of s)t.memoryMetaSetSuperseded(e.path,`lesson:auto-prune`);return{pruned:s.map(e=>e.path),skipped:o.length-s.length,dryRun:i.dryRun}}async function Ge(e,t,n){let r=Pe(n),i=(await e.list({category:`lessons`})).filter(e=>{if(!e.tags.includes(`lesson`)||e.tags.some(e=>e.startsWith(`group:`)))return!1;let n=t.memoryMetaGet(e.path);return n?.supersededBy==null||n===void 0});if(i.length<r.minGroupSize)return{groupsCreated:0,lessonsGrouped:0,groups:[],dryRun:r.dryRun};let a=Ve(Be(i.map(e=>e.title),r.similarityThreshold)).filter(e=>e.length>=r.minGroupSize).map(e=>{let t=e.map(e=>i[e]).sort((e,t)=>e.path.localeCompare(t.path));return{label:He(t.map(e=>e.title)),members:t.map(e=>e.path)}}).sort((e,t)=>t.members.length-e.members.length||e.members[0].localeCompare(t.members[0])).slice(0,r.maxGroups);if(!r.dryRun&&a.length>0){for(let t of a)for(let n of t.members)await Ue(e,n,t.label);await e.reindexAll()}return{groupsCreated:a.length,lessonsGrouped:a.reduce((e,t)=>e+t.members.length,0),groups:a,dryRun:r.dryRun}}var Ke=S({DEFAULT_PROMOTE_CONFIG:()=>F,adjudicateCandidate:()=>at,checkPromotionGates:()=>rt,collectWorkspaceLessons:()=>ut,demoteLesson:()=>pt,getGlobalCuratedDir:()=>lt,promoteLessons:()=>ft,scanForDuplicates:()=>dt,scorePromotionCandidate:()=>it});const F={minWorkspaces:2,minAvgConfidence:80,similarityThreshold:.7,dryRun:!0};function qe(e){return{minWorkspaces:Math.max(2,Math.trunc(e?.minWorkspaces??F.minWorkspaces)),minAvgConfidence:Math.min(100,Math.max(0,Math.trunc(e?.minAvgConfidence??F.minAvgConfidence))),similarityThreshold:Math.min(1,Math.max(0,e?.similarityThreshold??F.similarityThreshold)),dryRun:e?.dryRun??F.dryRun,layeredKnowledge:e?.layeredKnowledge??F.layeredKnowledge}}function Je(e,t){let n=e.map(()=>[]);for(let r=0;r<e.length;r+=1)for(let i=r+1;i<e.length;i+=1)A(e[r].insight,e[i].insight)>=t&&(n[r].push(i),n[i].push(r));return n}function Ye(e){let t=new Set,n=[];for(let r=0;r<e.length;r+=1){if(t.has(r))continue;let i=[r],a=[];for(t.add(r);i.length>0;){let n=i.pop();if(n!==void 0){a.push(n);for(let r of e[n])t.has(r)||(t.add(r),i.push(r))}}n.push(a)}return n}function Xe(t){return new e(t,null,null)}function Ze(e){return(e??``).replace(/\s+/g,` `).trim()}function Qe(e){let t=Ze(e);return t.length<=80?t:`${t.slice(0,77).replace(/\s+\S*$/,``)}...`}function $e(e){return de({title:Qe(e.insight),context:`Observed across ${e.foundIn.length} workspaces: ${e.foundIn.join(`, `)}`,insight:e.insight,evidence:[`Promoted from workspaces: ${e.foundIn.join(`, `)}`,`Average confidence: ${e.avgConfidence}/100`,`Reason: ${e.reason}`].join(`
5
+ `),confidence:e.avgConfidence,tags:[`lesson`,`promoted`,`global`]})}function I(e,t,n){return Math.max(t,Math.min(n,Math.round(e)))}function et(e){let t=(Date.now()-e.getTime())/(1440*60*1e3);return t<=1?10:t<=7?8:t<=14?6:t<=21?4:t<=30?2:1}function tt(e){switch(e){case`high`:return 10;case`medium`:return 6;case`low`:return 2}}function nt(e){let t=e.length/4;return t<=10?10:t<=25?8:t<=50?6:t<=100?4:t<=200?2:1}function rt(e,t){let n=[],r=!!t?.topicKey;n.push({name:`canonical-topic-key`,passed:r,reason:r?void 0:`No canonical topic key provided`});let i=!!(t?.evidenceRefs&&t.evidenceRefs.length>0);n.push({name:`evidence-attached`,passed:i,reason:i?void 0:`No evidence refs attached`});let a=!0,o;if(t?.observedAt){let e=Date.now()-new Date(t.observedAt).getTime();a=e<2592e6,o=a?void 0:`Observation older than 30 days (${Math.round(e/(1440*60*1e3))}d)`}n.push({name:`freshness`,passed:a,reason:o});let s=!t?.hasConflict;n.push({name:`no-unresolved-conflict`,passed:s,reason:s?void 0:`Has unresolved conflict`});let c=!0,l;t?.scope&&t?.targetScope&&(c=t.scope===t.targetScope,l=c?void 0:`Scope "${t.scope}" does not match target "${t.targetScope}"`),n.push({name:`scope-matches`,passed:c,reason:l});let u=!1;t?.actionability&&(u=t.actionability===`high`||t.actionability===`medium`),n.push({name:`actionability-clear`,passed:u,reason:u?void 0:`Actionability is "${t?.actionability??`not set`}"`});let d=!0,f;t?.tokenBudgetRemaining!==void 0&&t?.minTokenBudget!==void 0&&(d=t.tokenBudgetRemaining>=t.minTokenBudget,f=d?void 0:`Token budget ${t.tokenBudgetRemaining} < required ${t.minTokenBudget}`),n.push({name:`token-budget-available`,passed:d,reason:f});let p=n.filter(e=>!e.passed).map(e=>e.name);return{passed:p.length===0,gates:n,failedGates:p}}function it(e,t){let n=I(t?.recurrence??1,1,10),r=I(t?.impact??5,1,10),i=I(e.foundIn.length,1,10),a=t?.observedAt?et(new Date(t.observedAt)):5,o=tt(t?.actionability??`medium`),s=nt(e.insight);return{signals:{recurrence:n,impact:r,sourceDiversity:i,freshness:a,actionability:o,tokenCost:s},totalScore:n+r+i+a+o+s}}function at(e,t,n,r,i){return t.passed?n&&r&&i&&n.some(e=>A(e,i.insight)>=r)?{decision:`supersede`,score:e.totalScore,reason:`Similar candidate already exists at L2`}:e.totalScore<20?{decision:`supersede`,score:e.totalScore,reason:`Score ${e.totalScore}/60 insufficient for promotion`}:e.totalScore<35?{decision:`hold-l3`,score:e.totalScore,reason:`Moderate score ${e.totalScore}/60, needs more evidence or recurrence`}:e.signals.recurrence<3&&e.signals.impact<8?{decision:`hold-l3`,score:e.totalScore,reason:`Low-impact repetition: recurrence=${e.signals.recurrence} < 3 despite score ${e.totalScore}/60`}:e.signals.recurrence<3&&e.signals.impact>=8?{decision:`promote`,score:e.totalScore,reason:`High-impact exception: impact=${e.signals.impact}, score=${e.totalScore}/60`}:{decision:`promote`,score:e.totalScore,reason:`Strong multi-signal score: ${e.totalScore}/60, recurrence=${e.signals.recurrence}, impact=${e.signals.impact}`}:{decision:`reject`,score:e.totalScore,reason:`Hard gates failed: ${t.failedGates.join(`, `)}`}}async function ot(e,t){let n=await e.list({category:`lessons`,limit:1e3,orderBy:`updated`,order:`desc`});return(await Promise.all(n.map(async n=>{let r=await e.read(n.path),i=E(r.content),a=Ze(i.insight);return a?{workspace:t,path:n.path,title:i.title??r.title??n.title,insight:a,confidence:i.confidence??0}:null}))).filter(e=>e!==null)}async function st(e){return(await ot(e,`global`)).map(e=>e.insight)}function ct(e,t,n){return t.some(t=>A(t,e)>=n)}function lt(){let e=v(o(),`global-knowledge`,`.ai`,`curated`);return d(e)||f(e,{recursive:!0}),e}async function ut(e){let t=new Map;if(!s())return t;for(let e of c()){let n=v(e.workspacePath,`.ai`,`curated`);if(!d(n))continue;let r=await ot(Xe(n),e.partition);r.length>0&&t.set(e.partition,r)}return t}function dt(e,t=F,n){let r=qe(t),i=[...e.values()].flat();if(i.length===0)return[];let a=Ye(Je(i,r.similarityThreshold)),o=[];for(let e of a){let t=e.map(e=>i[e]),a=[...new Set(t.map(e=>e.workspace))].sort();if(a.length<r.minWorkspaces)continue;let s=Math.round(t.reduce((e,t)=>e+t.confidence,0)/t.length),c={insight:[...t].sort((e,t)=>t.confidence-e.confidence||e.title.localeCompare(t.title)||e.path.localeCompare(t.path))[0].insight,foundIn:a,avgConfidence:s,action:`skip`,reason:``};if(r.layeredKnowledge){let e=n?.get(c.insight),t=rt(c,e),r=it(c,e),i=at(r,t,void 0,void 0,c);c.gateResult=t,c.scoringResult=r,c.adjudication=i,c.action=i.decision===`promote`?`promote`:`skip`,c.reason=i.reason}else c.action=s>=r.minAvgConfidence?`promote`:`skip`,c.reason=s>=r.minAvgConfidence?`Shared across ${a.length} workspaces`:`Below confidence threshold`;o.push(c)}return o.sort((e,t)=>Number(t.action===`promote`)-Number(e.action===`promote`)||t.foundIn.length-e.foundIn.length||t.avgConfidence-e.avgConfidence||e.insight.localeCompare(t.insight))}async function ft(e,t,n=F){let r=qe(n),i=[],a=await st(t);for(let n of e){if(!(r.layeredKnowledge?n.adjudication?.decision===`promote`:n.action===`promote`)||ct(n.insight,a,r.similarityThreshold)||r.dryRun)continue;let e=await t.remember(Qe(n.insight),$e(n),`lessons`,[`lesson`,`promoted`,`global`]);i.push(e.path),a.push(n.insight)}return{candidates:e,promoted:i}}async function pt(e,t){try{return await e.forget(t,`Demoted from global knowledge partition`),{removed:!0,path:t}}catch(e){if(e instanceof Error&&/not found/i.test(e.message))return{removed:!1,path:t};throw e}}var mt=S({createSamplingClient:()=>vt});const ht=a(`sampling`);function gt(e){if(!e.modelPreferences)return;let t={...e.modelPreferences.costPriority===void 0?{}:{costPriority:e.modelPreferences.costPriority},...e.modelPreferences.speedPriority===void 0?{}:{speedPriority:e.modelPreferences.speedPriority},...e.modelPreferences.intelligencePriority===void 0?{}:{intelligencePriority:e.modelPreferences.intelligencePriority}};return Object.keys(t).length>0?t:void 0}function _t(e){if(Array.isArray(e))return e.map(e=>_t(e)).filter(e=>e.length>0).join(`
6
+ `);if(e&&typeof e==`object`&&`type`in e){let t=e;if(t.type===`text`&&typeof t.text==`string`)return t.text}return JSON.stringify(e)}function vt(e){let t=e.server,n=typeof t?.createMessage==`function`;return{get available(){return n},async createMessage(e){if(!n)throw Error(`Sampling not available: client does not support createMessage`);let r=e.context?`${e.context}\n\n---\n\n${e.prompt}`:e.prompt;try{let n=t.createMessage({messages:[{role:`user`,content:{type:`text`,text:r}}],systemPrompt:e.systemPrompt,modelPreferences:gt(e),maxTokens:e.maxTokens??4e3}),i;if(e.timeoutMs&&e.timeoutMs>0){let t=new Promise((t,n)=>setTimeout(()=>n(Error(`Sampling createMessage timed out after ${e.timeoutMs}ms`)),e.timeoutMs));i=await Promise.race([n,t])}else i=await n;return{text:_t(i.content),model:i.model,stopReason:i.stopReason}}catch(e){throw ht.warn(`Sampling createMessage failed`,{error:String(e)}),e}}}}const yt=/^(export|import|function|class|interface|type|const|let|var|→|├|└|─|##)/,bt=/^(decision|rationale|status|context|consequence)/i,xt=/finding|recommendation|warning|error|issue/i,St=/status|done|decision|blocker|next|file|created|modified/i,Ct=/(score|relevance)/i,wt=/[/.]|\\.(ts|js)$/i;function L(e){return e.split(/\r?\n/u).map(e=>e.replace(/[ \t]+$/u,``)).join(`
7
+ `).replace(/\n{3,}/gu,`
8
+
9
+ `).trim()}function Tt(e,t){if(e.length<=t)return e;let n=e.split(`
10
+ `),r=[],i=0;for(let e of n){let n=r.length===0?e.length:e.length+1;if(i+n>t)break;r.push(e),i+=n}return r.length>0?r.join(`
11
+ `):e.slice(0,t).trimEnd()}function R(e,t,n){return Tt(e,Math.max(1,Math.floor(n*t)))}function z(e,t){if(e.length<50)return e;let n=L(t);return!n||n.length<e.length*.2?e:n}function Et(e,t,n){let r=new Set;for(let n=0;n<Math.min(t,e.length);n+=1)r.add(n);return e.forEach((e,t)=>{n(e,t)&&r.add(t)}),e.filter((e,t)=>r.has(t)).join(`
12
+ `)}function Dt(e,t){e.includes(t)||e.push(t)}function Ot(e){return z(e,R(Et(e.split(/\r?\n/u),3,e=>yt.test(e)||e.startsWith(`- `)),.6,e.length))}function kt(e){let t=e.split(/\r?\n/u),n=[];return t.forEach((e,t)=>{if(t<5||Ct.test(e)||wt.test(e)||/^Content:/i.test(e)){if(/^Content:/i.test(e)){Dt(n,`Content: ${e.replace(/^Content:\s*/i,``).trim().slice(0,200)}`);return}Dt(n,e)}}),z(e,n.join(`
13
+ `))}function At(e){let t=e.split(/\r?\n/u),n=new Set;for(let e=0;e<t.length&&t[e].trim()!==``;e+=1)n.add(e);return t.forEach((e,t)=>{(e.startsWith(`- `)||e.startsWith(`* `)||bt.test(e))&&n.add(t)}),z(e,R(t.filter((e,t)=>n.has(t)).join(`
14
+ `),.7,e.length))}function jt(e){let t=e.split(/\r?\n/u),n=new Set,r=!1;for(let e=0;e<Math.min(2,t.length);e+=1)n.add(e);return t.forEach((e,t)=>{if(e.startsWith("```")){n.add(t),r=!r;return}(r||e.startsWith(`##`)||e.startsWith(`- `)||e.startsWith(`* `))&&n.add(t)}),z(e,R(t.filter((e,t)=>n.has(t)).join(`
15
+ `),.65,e.length))}function Mt(e){return z(e,R(e.split(/\r?\n/u).filter(e=>e.startsWith(`#`)||e.startsWith(`- `)||/\d/.test(e)||/\d+%/.test(e)||xt.test(e)).join(`
16
+ `),.6,e.length))}function Nt(e){return z(e,R(e.split(/\r?\n/u).filter(e=>e.startsWith(`- `)||e.startsWith(`* `)||St.test(e)).join(`
17
+ `),.5,e.length))}function Pt(e,t){switch(e){case`file-card`:return Ot(t);case`search-result`:return kt(t);case`decision`:return At(t);case`pattern`:return jt(t);case`analysis`:return Mt(t);case`step-summary`:return Nt(t)}}const Ft=/^### (Context|Insight|Evidence|Key|Finding|Result|Decision)/imu;function It(e,t){let n=e.trim();if(!n||n.length<=t)return n;let r=n.split(/\\r?\\n/u),i=new Set;for(let e=0;e<r.length;e++)if(/^#{1,3}\s/mu.test(r[e])&&i.size===0){i.add(e);for(let t=e+1;t<r.length;t++)if(r[t].trim().length>0){i.add(t);break}}r.forEach((e,t)=>{if((/^\s*[-*]\s/mu.test(e)||/^\d+\.\s/mu.test(e))&&i.add(t),Ft.test(e)){i.add(t);let e=r[t+1]?.trim();e&&!/^[#>-]/.test(e)&&i.add(t+1)}/^(Confidence|Source|Tags?):/imu.test(e)&&i.add(t)}),n.length>t&&r.forEach((e,t)=>{i.has(t)||/\b(always|never|prefer|use|should|must|requires?|detected|confirmed|verified)\b/im.test(e)&&i.add(t)});let a=r.filter((e,t)=>i.has(t)).join(`
18
+ `).trim();return a.length<=t?L(a):Tt(L(a),t)}function Lt(e,t,n,r){let i=t?.trim()??``,a=`(confidence: ${n}/100)`,o=`**${e}** ${a} — ${i}`.trim();if(o.length<=r)return o;let s=`**${e}** ${a}`;if(s.length<=r)return s;let c=r-a.length-8;return`**${e.length>c?`${e.slice(0,Math.max(0,c-3))}...`:e}** ${a}`}var Rt=S({autoUpgradeScaffold:()=>an,checkForUpdates:()=>Xt,cleanupOldVersions:()=>G,getCurrentVersion:()=>U,getUpgradeState:()=>nn});const zt=`@vpxa/aikit`,Bt=`https://registry.npmjs.org/${zt}/latest`,B=a(`server`);function Vt(){let e=_(n(import.meta.url));return[y(e,`..`,`..`,`..`,`bin`,`aikit.mjs`),y(e,`..`,`bin`,`aikit.mjs`),...process.argv[1]?[y(_(process.argv[1]),`aikit.mjs`)]:[]].find(e=>d(e))??null}const Ht=v(b(),`.aikit`),V=v(Ht,`current-version.json`),H=v(Ht,`versions`),Ut=/^\d+\.\d+\.\d+(-[\w.+]+)?(\+[\w.]+)?$/;function Wt(e){if(!Ut.test(e))throw Error(`Invalid semver version: ${JSON.stringify(e)}`)}function U(){let e=y(_(n(import.meta.url)),`..`,`..`,`..`,`package.json`);try{return JSON.parse(p(e,`utf-8`)).version??`0.0.0`}catch{return`0.0.0`}}function Gt(e,t){let n=e.split(`.`).map(Number),r=t.split(`.`).map(Number);for(let e=0;e<3;e++){let t=(n[e]??0)-(r[e]??0);if(t!==0)return t>0?1:-1}return 0}function Kt(e,t){let n=e.split(`.`).map(Number),r=t.split(`.`).map(Number);for(let e=0;e<3;e++){if((n[e]??0)>(r[e]??0))return!0;if((n[e]??0)<(r[e]??0))return!1}return!1}function qt(e){if(!d(e))return;for(let t=1;t<=2;t++)try{h(e,{recursive:!0,force:!0});return}catch(n){if(!(n.code===`EPERM`||n.code===`EBUSY`||/EPERM|permission denied/i.test(String(n)))){B.debug(`Failed to remove directory`,{path:e,error:n instanceof Error?n.message:String(n),attempt:t});return}}let t=`${e}.orphaned.${Date.now()}`;try{m(e,t),B.debug(`Renamed locked directory to ${t} — deferred cleanup`);try{h(t,{recursive:!0,force:!0})}catch{}}catch(t){B.debug(`Failed to rename locked directory`,{path:e,error:t instanceof Error?t.message:String(t)})}}async function Jt(e){Wt(e);let t=`v${e}`,n=v(H,`${t}-staging`),i=v(H,t);try{qt(n),f(n,{recursive:!0}),x(`tar -xzf "${x(`npm pack ${zt}@${e} 2>${process.platform===`win32`?`NUL`:`/dev/null`}`,{cwd:n,encoding:`utf-8`,timeout:6e4,windowsHide:!0}).trim()}"`,{cwd:n,encoding:`utf-8`,stdio:`pipe`,timeout:3e4,windowsHide:!0});let t=v(n,`package`);x(`npm ${r.join(` `)}`,{cwd:t,encoding:`utf-8`,stdio:`pipe`,timeout:12e4,windowsHide:!0});let a=v(t,`packages`,`server`,`dist`,`bin.js`);if(!d(a))throw Error(`Server entry not found at ${a}`);if(!d(v(t,`node_modules`)))throw Error(`node_modules not found — npm install may have failed`);d(i)&&h(i,{recursive:!0,force:!0}),m(t,i);let o=`${V}.tmp`;g(o,JSON.stringify({version:e,installedAt:new Date().toISOString()},null,2)),m(o,V),G(e)}finally{qt(n)}}function W(e){B.debug(`Updated to v${e}. Restarting server...`),setTimeout(()=>{process.exit(0)},300).unref()}function G(e){i(H,e??U())}async function Yt(){try{let e=p(V,`utf-8`),{version:t}=JSON.parse(e),n=await fetch(Bt,{signal:AbortSignal.timeout(1e4)});if(!n.ok)return;let r=(await n.json()).version;if(!r||r===t||!Kt(r,t))return;if(d(v(H,`v${r}`))){let e=`${V}.tmp`;g(e,JSON.stringify({version:r,installedAt:new Date().toISOString()},null,2)),m(e,V),B.debug(`Re-activated existing version v${r} — no download needed`),W(r);return}B.debug(`New version available: ${r}. Installing...`),await Jt(r),W(r)}catch(e){B.error(`Background update check failed: ${e instanceof Error?e.message:String(e)}`)}}let K=null;function Xt(){return K||(K=Zt().finally(()=>{K=null}),K)}async function Zt(){if(d(V)){await Yt();return}let e=U();try{let t=await fetch(Bt,{signal:AbortSignal.timeout(1e4)});if(!t.ok)return;let n=(await t.json()).version;if(!n)return;if(Gt(e,n)<0){B.debug(`Newer version available — installing`,{currentVersion:e,latestVersion:n});try{await Jt(n),W(n)}catch(e){B.warn(`Auto-install failed`,{error:e instanceof Error?e.message:String(e),latestVersion:n})}}}catch{}}function Qt(){try{let e=y(b(),`.copilot`,`.aikit-scaffold.json`);return d(e)?JSON.parse(p(e,`utf-8`)).version??null:null}catch{return null}}function $t(){try{let e=l();if(!e)return null;let t=y(e,`.github`,`.aikit-scaffold.json`);return d(t)?JSON.parse(p(t,`utf-8`)).version??null:null}catch{return null}}let q=`idle`,J=null,en=null,tn=!1;function nn(){return{state:q,error:J}}function rn(){q=`idle`,J=null}function an(){try{let e=U();if(Xt(),!tn){tn=!0;try{let e=Vt();e&&ae(process.execPath,[e,`migrate-launcher`],{cwd:b(),stdio:`ignore`,timeout:15e3,windowsHide:!0}).unref()}catch{}try{let e=y(b(),`.claude`,`mcp.json`);d(e)&&JSON.parse(p(e,`utf-8`))?.mcpServers?.[`AI Kit`]&&te(e)}catch{}}let t=Qt(),n=$t();if(!(t!=null&&t!==e)&&!(n!=null&&n!==e)||(en!==e&&(rn(),en=e),q!==`idle`))return;q=`pending`,J=null,B.debug(`Scaffold version mismatch — auto-upgrading`,{serverVersion:e,userScaffoldVersion:t,workspaceScaffoldVersion:n});let r=Vt();if(!r){q=`failed`,J=`aikit CLI binary not found`,B.warn(`Cannot auto-upgrade: aikit CLI binary not found`);return}let i=b();ie(process.execPath,[r,`upgrade`],{cwd:i,timeout:3e4,windowsHide:!0},(t,n,a)=>{t?(q=`failed`,J=t.message,B.warn(`Auto-upgrade failed`,{error:t.message,stack:t.stack,code:t.code,stdout:n?.slice(0,500),stderr:a?.slice(0,500),cwd:i,binPath:r,platform:process.platform})):(q=`success`,J=null,B.debug(`Auto-upgrade completed to version ${e}`))}).unref()}catch(e){q=`failed`,J=e instanceof Error?e.message:String(e),B.warn(`Auto-upgrade check failed`,{error:J})}}var on=S({buildOnboardContext:()=>vn,buildPreludeInjection:()=>xn,generatePrelude:()=>bn});function Y(e,t){return e.length<=t?e:e.slice(0,t)}function X(e){if(!e)return 0;let t=Date.parse(e);return Number.isNaN(t)?0:t}const sn=2400,cn=new Set([`synthesis-guide.md`,`structure.md`,`dependencies.md`,`diagram.md`,`domains.md`,`entry-points.md`,`code-map.md`]),ln=[{id:`synthesis-guide`,file:`synthesis-guide.md`,title:`Synthesis Guide`,useFor:`project profile, recommended reading order, analysis index`,priority:1},{id:`structure`,file:`structure.md`,title:`Project Structure`,useFor:`package map, file layout, repo shape`,priority:2},{id:`dependencies`,file:`dependencies.md`,title:`Dependencies`,useFor:`external packages, internal import density, dependency hotspots`,priority:3},{id:`diagram`,file:`diagram.md`,title:`Architecture Diagram`,useFor:`C4 containers, package boundaries, architecture overview`,priority:4},{id:`domains`,file:`domains.md`,title:`Domains`,useFor:`service boundaries, domain clusters, ownership hints`,priority:5},{id:`entry-points`,file:`entry-points.md`,title:`Entry Points`,useFor:`CLI/server/API entry points before tracing code`,priority:6},{id:`code-map`,file:`code-map.md`,title:`Code Map`,useFor:`module graph, cross-package call edges, impact orientation`,priority:7},{id:`layers`,file:`layers.md`,title:`Layers`,useFor:`architectural layer classification`,priority:8},{id:`api-surface`,file:`api-surface.md`,title:`API Surface`,useFor:`public exports and API boundaries`,priority:9},{id:`type-inventory`,file:`type-inventory.md`,title:`Type Inventory`,useFor:`shared types and type-heavy modules`,priority:10}];function un(e){return e.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/,``).trimStart()}function dn(e,t){return e.length<=t?e:`${e.slice(0,t).trimEnd()}\n...`}function Z(e,t=12e3){try{return d(e)?p(e,`utf-8`).slice(0,t):null}catch{return null}}function fn(e){let t=Z(y(e,`.aikit-generated.json`),4e3);if(!t)return{exists:!1,valid:!1,generatedAt:null,schemaVersion:null};try{let e=JSON.parse(t);return{exists:!0,valid:!0,generatedAt:typeof e.generated_at==`string`?e.generated_at:null,schemaVersion:typeof e.schema_version==`number`?e.schema_version:null}}catch{return{exists:!0,valid:!1,generatedAt:null,schemaVersion:null}}}function Q(e,t){return e===`fresh`?{kind:`use`,command:null,reason:t}:{kind:`update_onboard`,command:`onboard({ path: ".", update: true })`,reason:t}}function pn(e){let t=new Date().toISOString(),n={generatedAt:e.generatedAt,lastIndexedAt:e.lastIndexedAt,manifestSchemaVersion:e.manifest.schemaVersion,missingResources:e.missingResources,checkedAt:t};if(e.missingResources.length>0)return{...n,status:`stale`,reason:`missing_required_files`,recommendedAction:Q(`stale`,`Required onboard files are missing; refresh onboard context before relying on it.`)};if(!e.manifest.exists)return{...n,status:`unknown`,reason:`missing_manifest`,recommendedAction:Q(`unknown`,`Onboard manifest is missing; update onboard context to restore freshness metadata.`)};if(!e.manifest.valid)return{...n,status:`unknown`,reason:`invalid_manifest`,recommendedAction:Q(`unknown`,`Onboard manifest is invalid; update onboard context before trusting it.`)};if(e.manifest.schemaVersion!==1)return{...n,status:`unknown`,reason:`legacy_manifest`,recommendedAction:Q(`unknown`,`Onboard manifest is from an older schema; update onboard context once.`)};if(!e.generatedAt||X(e.generatedAt)===0)return{...n,status:`unknown`,reason:`missing_generated_at`,recommendedAction:Q(`unknown`,`Onboard generation time is unavailable; update onboard context before trusting it.`)};let r=X(e.generatedAt);return X(e.lastIndexedAt)>r+3e5?{...n,status:`stale`,reason:`generated_before_index`,recommendedAction:Q(`stale`,`Repository index changed after onboard generation; update onboard context.`)}:{...n,status:`fresh`,reason:`fresh`,recommendedAction:Q(`fresh`,`Onboard context matches current freshness checks.`)}}function mn(e){if(!e)return[];let t=e.split(/\r?\n/),n=t.findIndex(e=>e.trim()===`### Project Profile`);if(n<0)return[];let r=[];for(let e of t.slice(n+1)){if(e.startsWith(`### `))break;let t=e.trim();t.startsWith(`- `)&&r.push(t)}return r.slice(0,6)}function hn(e){if(!e)return[];let t=new Set;for(let n of e.matchAll(/Container\([^,\n]+,\s*"([^"]+)"/g)){let e=n[1]?.trim();e&&t.add(e)}return[...t]}function gn(e){if(!e)return[];let t=new Set,n=!1,r=!1,i=null;for(let a of e.split(/\r?\n/)){if(a.trim().startsWith("```")){n=!n;continue}if(!n)continue;let e=a.match(/^([A-Za-z0-9_.@-][^/\\]*)\/\s*$/);if(!r&&e?.[1]){i=e[1].trim(),r=!0;continue}if(!r)continue;let o=a.match(/^(?:│ {3}| {4})([A-Za-z0-9_.@-][^/\\]*?)\/\s*$/)?.[1]?.trim();o&&o!==i&&t.add(o)}return[...t]}function _n(e){if(!e)return null;let{resources:t,...n}=e;return{...n,resourceCount:t.length,resourceIds:t.map(e=>e.id)}}function vn(e,t={}){if(!e||!d(e))return null;let n=ln.flatMap(t=>{let n=y(e,t.file);return d(n)?[{id:t.id,title:t.title,path:n,sizeBytes:ee(n).size,useFor:t.useFor,priority:t.priority}]:[]}),r=y(e,`synthesis-guide.md`),i=y(e,`structure.md`),a=y(e,`diagram.md`),o=fn(e),s=o.generatedAt,c=[...cn].filter(t=>!d(y(e,t))),l=pn({generatedAt:s,lastIndexedAt:t.lastIndexedAt??null,manifest:o,missingResources:c}),u=Z(r),f=Z(i),p=hn(Z(a)),m=p.length>0?[]:gn(f),h=p.length>0?p:m,te=p.length>0?a:m.length>0?i:null,g=h.slice(0,40),_=h.length>g.length,v=p.slice(0,40),ne=p.length>v.length;return{dir:y(e),generatedAt:s,fresh:l.status===`fresh`,freshness:l,projectProfile:mn(u),recommendedReadOrder:[`synthesis-guide.md`,`structure.md`,`dependencies.md`,`diagram.md`,`domains.md`,`entry-points.md`,`code-map.md`],readInstruction:l.status===`fresh`?`Use fresh onboard context before broad source reads: start with synthesis-guide.md, use structure.md/dependencies.md for package map, diagram.md/domains.md for architecture, and code-map.md for module graph.`:`Update onboard context first with \`${l.recommendedAction.command}\`, then use synthesis-guide.md, structure.md/dependencies.md, diagram.md/domains.md, and code-map.md before broad source reads.`,resources:n,packageMap:{sourcePath:te,packages:g,totalPackages:h.length,truncated:_},architecture:{sourcePath:d(a)?a:null,summary:p.length>0?`C4 container diagram with ${p.length} package/container nodes.`:`Read diagram.md and domains.md for architecture boundaries.`,containers:v,totalContainers:p.length,truncated:ne}}}function yn(e){let t=Array.isArray(e)?e:[e];for(let e of t){if(!e)continue;let t=y(e,`SKILL.md`);if(d(t))try{let e=p(t,`utf-8`),n=un(e)||e,r=dn(n,sn);return{preview:r,resource:{uri:`aikit://skill/SKILL.md`,path:t,sizeBytes:ee(t).size,previewChars:r.length,truncated:n.length>sn}}}catch{}}return null}async function bn(e,t,n=w,r,i){let a=yn(r),o={lessons:[],conventions:[],checkpoint:null,workspaceSkill:a?.preview??null,workspaceSkillResource:a?.resource??null,onboardContext:_n(i)};if(!e||!t)return o;try{let[r,i,a]=await Promise.all([e.list({category:`lessons`,limit:200,orderBy:`updated`,order:`desc`}),e.list({category:`conventions`,limit:200,orderBy:`updated`,order:`desc`}),e.list({category:`session`,limit:200,orderBy:`updated`,order:`desc`})]),s=r.filter(e=>e.tags.includes(`lesson`)).map(e=>{let r=t.memoryMetaGet(e.path);return!r||r.supersededBy!=null?null:{entry:e,confidence:D(r.confidence,r.lastAccessedAt,r.createdAt,n)}}).filter(e=>e!==null).sort((e,t)=>t.confidence-e.confidence).slice(0,3),c=await Promise.all(s.map(async({entry:t,confidence:n})=>{let r=E((await e.read(t.path)).content);return{title:t.title,insight:Y(r.insight??``,150),confidence:n}})),l=i.map(e=>({entry:e,lastAccessedAt:t.memoryMetaGet(e.path)?.lastAccessedAt??null})).filter(({entry:e})=>(e.contentPreview?.trim()??``).length>5).sort((e,t)=>X(t.lastAccessedAt)-X(e.lastAccessedAt)).slice(0,2).map(({entry:e})=>({title:e.title,preview:e.contentPreview})),u=a.map(e=>({entry:e,lastAccessedAt:t.memoryMetaGet(e.path)?.lastAccessedAt??null})).sort((e,t)=>X(t.lastAccessedAt)-X(e.lastAccessedAt)).map(({entry:e})=>Y(e.contentPreview,200))[0]??null;return{...o,lessons:c,conventions:l,checkpoint:u}}catch{return o}}function xn(e,t=600){if(!e)return{lines:[],totalChars:0,autoInjectCount:0};let n=[],r=0;for(let t of e.lessons){if(t.confidence<45)continue;let e=Lt(t.title,t.insight,t.confidence,200);n.push(`• ${e}`),r++}if(e.workspaceSkillResource?(n.push(`• Workspace skill: read ${e.workspaceSkillResource.uri} before repo work (${e.workspaceSkillResource.sizeBytes} bytes; status preview included).`),r++):e.workspaceSkill&&(n.push(`• Workspace skill preview: ${e.workspaceSkill.split(`
19
+ `)[0]??``}`),r++),e.onboardContext){let t=e.onboardContext.packageMap.totalPackages>0?` package map has ${e.onboardContext.packageMap.totalPackages} packages/containers;`:``;n.push(`• Onboard context:${t} ${e.onboardContext.readInstruction}`),r++}for(let t of e.conventions){let e=t.preview?.trim()||``;if(e){let r=e.length>120?`${e.slice(0,117)}...`:e;n.push(`• ${t.title}: ${r}`)}else n.push(`• ${t.title}`)}if(n.length===0)return{lines:[],totalChars:0,autoInjectCount:0};let i=[`━━ Knowledge ━━`,...n,`───`],a=i.join(`
20
+ `);if(a.length>t)for(;i.length>3&&a.length>t;)i.splice(1,1)[0]?.startsWith(`•`)&&r--;return{lines:i,totalChars:i.join(`
21
+ `).length,autoInjectCount:r}}const $=a(`server`);function Sn(e,t){return t?{version:e,...u(t)}:{version:e}}function Cn(t,n,r){t.then(async()=>{try{let{markPromoteRun:t,markPruneRun:r,prune:i,shouldRunStartupPrune:a,shouldRunWeeklyPromote:o}=await import(`../../tools/dist/index.js`),s=n();if(!s)return;try{let{readdirSync:e,rmSync:t,statSync:n,existsSync:r}=await import(`node:fs`),{join:i}=await import(`node:path`),{homedir:a}=await import(`node:os`),o=i(a(),`.aikit`,`workspaces`);if(r(o)){let a=Date.now(),s=e(o,{withFileTypes:!0}),c=0;for(let e of s){if(!e.isDirectory())continue;let s=i(o,e.name);try{if(a-n(s).mtimeMs<2592e6)continue;let e=i(s,`store`,`aikit.db`);if(!r(e)){t(s,{recursive:!0,force:!0}),c++;continue}n(e).size<1024&&(t(s,{recursive:!0,force:!0}),c++)}catch{}}c>0&&$.info(`Workspace directory GC complete`,{directoriesRemoved:c,directoriesRemaining:s.length-c})}}catch{}if(a()){let e=await i({});r(),e.totalBytesFreed>0&&$.info(`Storage maintenance complete`,{forgeOrphans:e.forgeGroundOrphans.count,legacyLance:e.legacyLance.count,bytesFreed:e.totalBytesFreed});let{groupLessons:t,pruneLessons:n}=await Promise.resolve().then(()=>je),a=await n(s.curated,s.stateStore,{dryRun:!1});a.pruned.length>0&&$.info(`Startup lesson prune complete`,{pruned:a.pruned.length});let o=await t(s.curated,s.stateStore,{dryRun:!1});(o.groupsCreated>0||o.lessonsGrouped>0)&&$.info(`Startup lesson grouping complete`,{groupsCreated:o.groupsCreated,lessonsGrouped:o.lessonsGrouped})}if(o()){let{DEFAULT_PROMOTE_CONFIG:n,collectWorkspaceLessons:r,getGlobalCuratedDir:i,promoteLessons:a,scanForDuplicates:o}=await Promise.resolve().then(()=>Ke),c=s.curated,l=new e(i(),c.store,c.embedder),u=await r(),d={...n,dryRun:!1},f=await a(o(u,d),l,d);t(),f.promoted.length>0&&$.info(`Weekly lesson promotion complete`,{promoted:f.promoted.length,candidates:f.candidates.length})}}catch(e){$.warn(`Startup maintenance failed (non-critical)`,Sn(r,e))}}).catch(e=>$.warn(`Startup maintenance failed`,u(e)))}export{Ee as A,de as B,We as C,k as D,M as E,xe as F,he as G,E as H,w as I,le as J,C as K,ue as L,O as M,Se as N,Te as O,be as P,pe as R,Ge as S,Ae as T,T as U,me as V,fe as W,pt as _,on as a,dt as b,U as c,Pt as d,It as f,ut as g,F as h,bn as i,Ce as j,A as k,nn as l,mt as m,Sn as n,an as o,vt as p,ce as q,vn as r,G as s,Cn as t,Rt as u,lt as v,ke as w,je as x,ft as y,D as z};