@vpxa/aikit 0.1.367 → 0.1.369

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 (25) 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/index.js +1 -1
  5. package/packages/server/dist/prelude-DqJ2G_gT.js +1 -0
  6. package/packages/server/dist/prelude-JNadYyA-.js +2 -0
  7. package/packages/server/dist/sampling-CD3fmYL9.js +1 -0
  8. package/packages/server/dist/sampling-DF2FdDmy.js +2 -0
  9. package/packages/server/dist/{server-B3Wy5oMX.js → server-Cchjt4r6.js} +180 -180
  10. package/packages/server/dist/{server-DBLXa2HM.js → server-P4KQX_3U.js} +180 -180
  11. package/packages/server/dist/{server-http-Do9kvXVq.js → server-http-BfR-ib_I.js} +1 -1
  12. package/packages/server/dist/{server-http-CytJq5BC.js → server-http-Dbrn1HM0.js} +1 -1
  13. package/packages/server/dist/server-stdio-6kzvYc41.js +1 -0
  14. package/packages/server/dist/server-stdio-ru-R1hO2.js +2 -0
  15. package/packages/server/dist/startup-maintenance-BPrX5-1U.js +2 -0
  16. package/packages/server/dist/startup-maintenance-CT6Z3734.js +1 -0
  17. package/packages/store/dist/index.js +2 -2
  18. package/packages/server/dist/prelude-BT_YGKcG.js +0 -2
  19. package/packages/server/dist/prelude-CHJaVPEe.js +0 -1
  20. package/packages/server/dist/sampling-CC7xHN-4.js +0 -1
  21. package/packages/server/dist/sampling-DRMRPVW6.js +0 -2
  22. package/packages/server/dist/server-stdio-BJ7pjrh7.js +0 -1
  23. package/packages/server/dist/server-stdio-bxxYSAHg.js +0 -2
  24. package/packages/server/dist/startup-maintenance-CBJWiJ7p.js +0 -2
  25. package/packages/server/dist/startup-maintenance-DX1yTfBa.js +0 -1
@@ -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-DX1yTfBa.js";import{createLogger as o,serializeError as s,setDetailedErrorLoggingEnabled as c}from"../../core/dist/index.js";import{randomUUID as l}from"node:crypto";const u=`__pending__:`;function d(e){return e.startsWith(u)}function f(e){let t=e.headers[`mcp-session-id`];return Array.isArray(t)?t[0]:t}function p(e,t,n,r){e.status(t).json({jsonrpc:`2.0`,error:{code:n,message:r},id:null})}var m=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=f(e),i=r?this.runtimes.get(r):void 0;if(r&&!i){p(t,404,-32001,`Session not found`);return}if(!i){if(e.method!==`POST`){p(t,400,-32e3,`Session required`);return}if(i=await this.createRuntime(t),!i)return}await this.withRuntimeLock(i,async()=>{await i.transport.handleRequest(e,t,n),i.lastAccessAt=this.now();let r=i.transport.sessionId??i.id;e.method!==`DELETE`&&!d(r)&&this.options.onSessionActivity?.(r),e.method===`DELETE`&&!d(r)&&await this.closeSession(r,{closeTransport:!1})})}async closeExpiredSessions(){let e=[...this.runtimes.values()].filter(e=>this.now()-e.lastAccessAt>=this.sessionTimeoutMs).map(e=>e.id);for(let t of e)await this.closeSession(t);return e.length}async closeSession(e,t={}){let n=this.runtimes.get(e);return n?(this.runtimes.delete(e),t.notifySessionEnd!==!1&&!d(e)&&this.options.onSessionEnd?.(e),t.closeTransport!==!1&&await n.transport.close().catch(()=>void 0),await n.server.close().catch(()=>void 0),!0):!1}async closeAll(){let e=[...this.runtimes.keys()];for(let t of e)await this.closeSession(t)}async createRuntime(e){if(await this.closeExpiredSessions(),this.runtimes.size>=this.maxSessions){p(e,503,-32003,`Session capacity reached`);return}let t=this.now(),n=await this.options.createServer(),r={id:`${u}${l()}`,transport:void 0,createdAt:t,lastAccessAt:t,server:n,requestChain:Promise.resolve()},i=this.options.createTransport({sessionIdGenerator:()=>l(),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 h(e){let t=e.includes(`T`)?e:`${e.replace(` `,`T`)}Z`;return Date.parse(t)}var g=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=h(n.lastActivity);return Number.isFinite(r)&&e-r>=t}).map(e=>e.sessionId)}};const _=o(`server`);async function v(o,u){let[{default:d},{loadConfig:f,resolveIndexMode:p},{registerDashboardRoutes:h,resolveDashboardDir:v},{registerSettingsRoutes:y,resolveSettingsDir:b},{createSettingsRouter:x},{authMiddleware:S,getOrCreateToken:C}]=await Promise.all([import(`express`),import(`./config-D3rRPB9X.js`),import(`./dashboard-static-Dw7Nsq4f.js`),import(`./settings-static-BpQgaMRs.js`),import(`./routes-DsSm9ea0.js`),import(`./auth-7LFAZQBu.js`).then(e=>e.t)]),w=f();c(w.logging?.errorDetails===!0),w.configError&&_.warn(`Config load failure`,{error:w.configError}),_.info(`Config loaded`,{sourceCount:w.sources.length,storePath:w.store.path});let T=d();T.use(d.json({limit:`1mb`}));let E=Number(u),D=`http://localhost:${E}`,O=process.env.AIKIT_CORS_ORIGIN??D,k=process.env.AIKIT_ALLOW_ANY_ORIGIN===`true`,A=n(`AIKIT_HTTP_MAX_SESSIONS`,8),j=n(`AIKIT_HTTP_SESSION_TIMEOUT_MINUTES`,30),M=n(`AIKIT_HTTP_SESSION_GC_INTERVAL_MINUTES`,5),N=r({limit:100,windowMs:6e4}),P=!1;T.use((t,n,r)=>{let i=Array.isArray(t.headers.origin)?t.headers.origin[0]:t.headers.origin,a=e({requestOrigin:i,configuredOrigin:O,allowAnyOrigin:k,fallbackOrigin:D});if(a.warn&&!P&&(P=!0,_.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 F=C();T.use(S(F)),T.use(`/mcp`,(e,n,r)=>{let i=t(e)??e.ip??e.socket.remoteAddress??`anonymous`;if(N.allow(i)){r();return}let a=Math.max(1,Math.ceil(N.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 I;T.use(`/mcp`,(e,t,n)=>{if(!I){let t=e.headers[`x-workspace-root`];typeof t==`string`&&t.length>0&&(I=t,_.debug(`Captured workspace root from proxy header`,{wsRoot:t}))}n()}),h(T,v(),_);let L=new Date().toISOString();T.use(`/settings/api`,x({log:_,mcpInfo:()=>({transport:`http`,port:E,pid:process.pid,startedAt:L})})),y(T,b(),_),T.get(`/health`,(e,t)=>{t.json({status:`ok`})});let R=!1,z=null,B=null,V=null,H=null,U=null,W=null,G=null,K=null,q=Promise.resolve(),J=async(e,n)=>{if(!R||!V||!H){n.status(503).json({jsonrpc:`2.0`,error:{code:-32603,message:`Server initializing — please retry in a few seconds`},id:null});return}let r=q,i;q=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(()=>{_.warn(`mcpLock timed out waiting for previous request, resetting lock chain`,{method:e.method,timeoutMs:a}),t(!1)},a);n.unref&&n.unref()})])&&(q=Promise.resolve(),i=()=>{},W)){let e=W;W=null,G=null,e.close().catch(()=>{})}try{let r=t(e);if(!W){if(r){n.status(404).json({jsonrpc:`2.0`,error:{code:-32001,message:`Session not found`},id:null});return}let e=new H({sessionIdGenerator:()=>l(),onsessioninitialized:async e=>{G=e,B?.onSessionStart(e,{transport:`http`})},onsessionclosed:async e=>{e&&B?.onSessionEnd(e),G=null}});e.onclose=()=>{W===e&&(W=null),G===e.sessionId&&(G=null)},W=e,await V.connect(e)}let i=W;await i.handleRequest(e,n,e.body),e.method!==`DELETE`&&(!r&&i.sessionId?(G=i.sessionId,B?.onSessionStart(i.sessionId,{transport:`http`}),B?.onSessionActivity(i.sessionId)):r&&B?.onSessionActivity(r))}catch(e){if(_.error(`MCP handler error`,s(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()}},Y=async(e,n)=>{let r=t(e);if(U&&(!W||r!==G)){await U.handleRequest(e,n,e.body);return}await J(e,n)};T.post(`/mcp`,Y),T.get(`/mcp`,Y),T.delete(`/mcp`,Y);let X=T.listen(E,`127.0.0.1`,()=>{_.info(`MCP server listening`,{url:`http://127.0.0.1:${E}/mcp`,port:E}),setTimeout(async()=>{try{typeof I==`string`&&I.length>0&&(w.sources[0]={path:I,excludePatterns:w.sources[0]?.excludePatterns??[]},w.allRoots=[I],_.debug(`Workspace root applied from proxy header`,{wsRoot:I}));let[{createLazyServer:e,createMcpServer:t,ALL_TOOL_NAMES:n},{StreamableHTTPServerTransport:r},{checkForUpdates:c,autoUpgradeScaffold:l}]=await Promise.all([import(`./server-DBLXa2HM.js`),import(`@modelcontextprotocol/sdk/server/streamableHttp.js`),import(`./version-check-DNe43rCZ.js`)]);c(),l(),setInterval(c,1440*60*1e3).unref();let u=!1,d=p(w),f=e(w,d);K=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(()=>{})])},V=f.server,H=r,R=!0,_.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`);B=new g(f.aikit.stateStore,{staleTimeoutMinutes:j,gcIntervalMinutes:M,onBeforeSessionDelete:e=>{if(G===e&&W){let e=W;W=null,G=null,e.close().catch(()=>void 0)}U?.closeSession(e,{notifySessionEnd:!1})},onSessionEndMaintenance:async()=>{if(!f.aikit?.curated||!f.aikit?.stateStore)return;let{pruneLessons:e}=await import(`./evolution-BX_zTSdj.js`).then(e=>e.t),t=await e(f.aikit.curated,f.aikit.stateStore,{dryRun:!1});t.pruned.length>0&&_.info(`Session-end lesson prune`,{pruned:t.pruned.length})}}),U=new m({createServer:()=>{if(!f.aikit)throw Error(`AI Kit components are not available after initialization`);return t(f.aikit,w)},createTransport:e=>new r(e),maxSessions:A,sessionTimeoutMinutes:j,onSessionStart:e=>B?.onSessionStart(e,{transport:`http`}),onSessionActivity:e=>B?.onSessionActivity(e),onSessionEnd:e=>B?.onSessionEnd(e)}),B.startGC(),G&&(B.onSessionStart(G,{transport:`http`}),B.onSessionActivity(G)),_.info(`HTTP session runtime ready`,{maxSessions:A,sessionTimeoutMinutes:j,gcIntervalMinutes:M})}catch(e){_.error(`Failed to start session manager`,s(e)),R=!1,u=!0,V=null,H=null,K=null}}),d===`auto`?f.ready.then(async()=>{try{let e=w.sources.map(e=>e.path).join(`, `);_.info(`Running initial index`,{sourcePaths:e}),await f.runInitialIndex(),_.info(`Initial index complete`)}catch(e){_.error(`Initial index failed; will retry on aikit_reindex`,i(o,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,w,f.aikit.store),n=f.aikit.store;z=t,t.start(),n.onBeforeClose&&n.onBeforeClose(()=>t.stop()),f.setSmartScheduler(t),_.debug(`Smart index scheduler started (HTTP mode)`)}catch(e){_.error(`Failed to start smart index scheduler`,i(o,e))}}):_.info(`Initial full indexing skipped in HTTP mode`,{indexMode:d}),f.ready.catch(e=>{_.error(`AI Kit initialization failed`,i(o,e)),R=!1,u=!0,V=null,H=null,K=null}),a(f.ready,()=>f.aikit?{curated:f.aikit.curated,stateStore:f.aikit.stateStore}:null,o)}catch(e){_.error(`Failed to load server modules`,i(o,e)),R=!1,K=null}},100)}),Z=!1,Q=async e=>{Z||(Z=!0,_.info(`Shutdown signal received`,{signal:e}),z?.stop(),B?.stop(),await import(`../../tools/dist/index.js`).then(({processStopAll:e})=>e()).catch(()=>{}),await U?.closeAll().catch(()=>void 0),G&&B?.onSessionEnd(G),W&&(await W.close().catch(()=>void 0),W=null,G=null),X.close(),V&&await V.close(),await K?.().catch(()=>void 0),process.exit(0))};process.on(`SIGINT`,()=>Q(`SIGINT`)),process.on(`SIGTERM`,()=>Q(`SIGTERM`))}export{v 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-CT6Z3734.js";import{createLogger as o,serializeError as s,setDetailedErrorLoggingEnabled as c}from"../../core/dist/index.js";import{randomUUID as l}from"node:crypto";const u=`__pending__:`;function d(e){return e.startsWith(u)}function f(e){let t=e.headers[`mcp-session-id`];return Array.isArray(t)?t[0]:t}function p(e,t,n,r){e.status(t).json({jsonrpc:`2.0`,error:{code:n,message:r},id:null})}var m=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=f(e),i=r?this.runtimes.get(r):void 0;if(r&&!i){p(t,404,-32001,`Session not found`);return}if(!i){if(e.method!==`POST`){p(t,400,-32e3,`Session required`);return}if(i=await this.createRuntime(t),!i)return}await this.withRuntimeLock(i,async()=>{await i.transport.handleRequest(e,t,n),i.lastAccessAt=this.now();let r=i.transport.sessionId??i.id;e.method!==`DELETE`&&!d(r)&&this.options.onSessionActivity?.(r),e.method===`DELETE`&&!d(r)&&await this.closeSession(r,{closeTransport:!1})})}async closeExpiredSessions(){let e=[...this.runtimes.values()].filter(e=>this.now()-e.lastAccessAt>=this.sessionTimeoutMs).map(e=>e.id);for(let t of e)await this.closeSession(t);return e.length}async closeSession(e,t={}){let n=this.runtimes.get(e);return n?(this.runtimes.delete(e),t.notifySessionEnd!==!1&&!d(e)&&this.options.onSessionEnd?.(e),t.closeTransport!==!1&&await n.transport.close().catch(()=>void 0),await n.server.close().catch(()=>void 0),!0):!1}async closeAll(){let e=[...this.runtimes.keys()];for(let t of e)await this.closeSession(t)}async createRuntime(e){if(await this.closeExpiredSessions(),this.runtimes.size>=this.maxSessions){p(e,503,-32003,`Session capacity reached`);return}let t=this.now(),n=await this.options.createServer(),r={id:`${u}${l()}`,transport:void 0,createdAt:t,lastAccessAt:t,server:n,requestChain:Promise.resolve()},i=this.options.createTransport({sessionIdGenerator:()=>l(),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 h(e){let t=e.includes(`T`)?e:`${e.replace(` `,`T`)}Z`;return Date.parse(t)}var g=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=h(n.lastActivity);return Number.isFinite(r)&&e-r>=t}).map(e=>e.sessionId)}};const _=o(`server`);async function v(o,u){let[{default:d},{loadConfig:f,resolveIndexMode:p},{registerDashboardRoutes:h,resolveDashboardDir:v},{registerSettingsRoutes:y,resolveSettingsDir:b},{createSettingsRouter:x},{authMiddleware:S,getOrCreateToken:C}]=await Promise.all([import(`express`),import(`./config-D3rRPB9X.js`),import(`./dashboard-static-Dw7Nsq4f.js`),import(`./settings-static-BpQgaMRs.js`),import(`./routes-DsSm9ea0.js`),import(`./auth-7LFAZQBu.js`).then(e=>e.t)]),w=f();c(w.logging?.errorDetails===!0),w.configError&&_.warn(`Config load failure`,{error:w.configError}),_.info(`Config loaded`,{sourceCount:w.sources.length,storePath:w.store.path});let T=d();T.use(d.json({limit:`1mb`}));let E=Number(u),D=`http://localhost:${E}`,O=process.env.AIKIT_CORS_ORIGIN??D,k=process.env.AIKIT_ALLOW_ANY_ORIGIN===`true`,A=n(`AIKIT_HTTP_MAX_SESSIONS`,8),j=n(`AIKIT_HTTP_SESSION_TIMEOUT_MINUTES`,30),M=n(`AIKIT_HTTP_SESSION_GC_INTERVAL_MINUTES`,5),N=r({limit:100,windowMs:6e4}),P=!1;T.use((t,n,r)=>{let i=Array.isArray(t.headers.origin)?t.headers.origin[0]:t.headers.origin,a=e({requestOrigin:i,configuredOrigin:O,allowAnyOrigin:k,fallbackOrigin:D});if(a.warn&&!P&&(P=!0,_.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 F=C();T.use(S(F)),T.use(`/mcp`,(e,n,r)=>{let i=t(e)??e.ip??e.socket.remoteAddress??`anonymous`;if(N.allow(i)){r();return}let a=Math.max(1,Math.ceil(N.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 I;T.use(`/mcp`,(e,t,n)=>{if(!I){let t=e.headers[`x-workspace-root`];typeof t==`string`&&t.length>0&&(I=t,_.debug(`Captured workspace root from proxy header`,{wsRoot:t}))}n()}),h(T,v(),_);let L=new Date().toISOString();T.use(`/settings/api`,x({log:_,mcpInfo:()=>({transport:`http`,port:E,pid:process.pid,startedAt:L})})),y(T,b(),_),T.get(`/health`,(e,t)=>{t.json({status:`ok`})});let R=!1,z=null,B=null,V=null,H=null,U=null,W=null,G=null,K=null,q=Promise.resolve(),J=async(e,n)=>{if(!R||!V||!H){n.status(503).json({jsonrpc:`2.0`,error:{code:-32603,message:`Server initializing — please retry in a few seconds`},id:null});return}let r=q,i;q=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(()=>{_.warn(`mcpLock timed out waiting for previous request, resetting lock chain`,{method:e.method,timeoutMs:a}),t(!1)},a);n.unref&&n.unref()})])&&(q=Promise.resolve(),i=()=>{},W)){let e=W;W=null,G=null,e.close().catch(()=>{})}try{let r=t(e);if(!W){if(r){n.status(404).json({jsonrpc:`2.0`,error:{code:-32001,message:`Session not found`},id:null});return}let e=new H({sessionIdGenerator:()=>l(),onsessioninitialized:async e=>{G=e,B?.onSessionStart(e,{transport:`http`})},onsessionclosed:async e=>{e&&B?.onSessionEnd(e),G=null}});e.onclose=()=>{W===e&&(W=null),G===e.sessionId&&(G=null)},W=e,await V.connect(e)}let i=W;await i.handleRequest(e,n,e.body),e.method!==`DELETE`&&(!r&&i.sessionId?(G=i.sessionId,B?.onSessionStart(i.sessionId,{transport:`http`}),B?.onSessionActivity(i.sessionId)):r&&B?.onSessionActivity(r))}catch(e){if(_.error(`MCP handler error`,s(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()}},Y=async(e,n)=>{let r=t(e);if(U&&(!W||r!==G)){await U.handleRequest(e,n,e.body);return}await J(e,n)};T.post(`/mcp`,Y),T.get(`/mcp`,Y),T.delete(`/mcp`,Y);let X=T.listen(E,`127.0.0.1`,()=>{_.info(`MCP server listening`,{url:`http://127.0.0.1:${E}/mcp`,port:E}),setTimeout(async()=>{try{typeof I==`string`&&I.length>0&&(w.sources[0]={path:I,excludePatterns:w.sources[0]?.excludePatterns??[]},w.allRoots=[I],_.debug(`Workspace root applied from proxy header`,{wsRoot:I}));let[{createLazyServer:e,createMcpServer:t,ALL_TOOL_NAMES:n},{StreamableHTTPServerTransport:r},{checkForUpdates:c,autoUpgradeScaffold:l}]=await Promise.all([import(`./server-P4KQX_3U.js`),import(`@modelcontextprotocol/sdk/server/streamableHttp.js`),import(`./version-check-DNe43rCZ.js`)]);c(),l(),setInterval(c,1440*60*1e3).unref();let u=!1,d=p(w),f=e(w,d);K=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(()=>{})])},V=f.server,H=r,R=!0,_.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`);B=new g(f.aikit.stateStore,{staleTimeoutMinutes:j,gcIntervalMinutes:M,onBeforeSessionDelete:e=>{if(G===e&&W){let e=W;W=null,G=null,e.close().catch(()=>void 0)}U?.closeSession(e,{notifySessionEnd:!1})},onSessionEndMaintenance:async()=>{if(!f.aikit?.curated||!f.aikit?.stateStore)return;let{pruneLessons:e}=await import(`./evolution-BX_zTSdj.js`).then(e=>e.t),t=await e(f.aikit.curated,f.aikit.stateStore,{dryRun:!1});t.pruned.length>0&&_.info(`Session-end lesson prune`,{pruned:t.pruned.length})}}),U=new m({createServer:()=>{if(!f.aikit)throw Error(`AI Kit components are not available after initialization`);return t(f.aikit,w)},createTransport:e=>new r(e),maxSessions:A,sessionTimeoutMinutes:j,onSessionStart:e=>B?.onSessionStart(e,{transport:`http`}),onSessionActivity:e=>B?.onSessionActivity(e),onSessionEnd:e=>B?.onSessionEnd(e)}),B.startGC(),G&&(B.onSessionStart(G,{transport:`http`}),B.onSessionActivity(G)),_.info(`HTTP session runtime ready`,{maxSessions:A,sessionTimeoutMinutes:j,gcIntervalMinutes:M})}catch(e){_.error(`Failed to start session manager`,s(e)),R=!1,u=!0,V=null,H=null,K=null}}),d===`auto`?f.ready.then(async()=>{try{let e=w.sources.map(e=>e.path).join(`, `);_.info(`Running initial index`,{sourcePaths:e}),await f.runInitialIndex(),_.info(`Initial index complete`)}catch(e){_.error(`Initial index failed; will retry on aikit_reindex`,i(o,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,w,f.aikit.store),n=f.aikit.store;z=t,t.start(),n.onBeforeClose&&n.onBeforeClose(()=>t.stop()),f.setSmartScheduler(t),_.debug(`Smart index scheduler started (HTTP mode)`)}catch(e){_.error(`Failed to start smart index scheduler`,i(o,e))}}):_.info(`Initial full indexing skipped in HTTP mode`,{indexMode:d}),f.ready.catch(e=>{_.error(`AI Kit initialization failed`,i(o,e)),R=!1,u=!0,V=null,H=null,K=null}),a(f.ready,()=>f.aikit?{curated:f.aikit.curated,stateStore:f.aikit.stateStore}:null,o)}catch(e){_.error(`Failed to load server modules`,i(o,e)),R=!1,K=null}},100)}),Z=!1,Q=async e=>{Z||(Z=!0,_.info(`Shutdown signal received`,{signal:e}),z?.stop(),B?.stop(),await import(`../../tools/dist/index.js`).then(({processStopAll:e})=>e()).catch(()=>{}),await U?.closeAll().catch(()=>void 0),G&&B?.onSessionEnd(G),W&&(await W.close().catch(()=>void 0),W=null,G=null),X.close(),V&&await V.close(),await K?.().catch(()=>void 0),process.exit(0))};process.on(`SIGINT`,()=>Q(`SIGINT`)),process.on(`SIGTERM`,()=>Q(`SIGTERM`))}export{v as startHttpMode};
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- import{a as e,i as t,o as n,s as r}from"./bin.js";import{n as i,t as a}from"./startup-maintenance-CBJWiJ7p.js";import{createLogger as o,serializeError as s,setDetailedErrorLoggingEnabled as c}from"../../core/dist/index.js";import{randomUUID as l}from"node:crypto";const u=`__pending__:`;function d(e){return e.startsWith(u)}function f(e){let t=e.headers[`mcp-session-id`];return Array.isArray(t)?t[0]:t}function p(e,t,n,r){e.status(t).json({jsonrpc:`2.0`,error:{code:n,message:r},id:null})}var m=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=f(e),i=r?this.runtimes.get(r):void 0;if(r&&!i){p(t,404,-32001,`Session not found`);return}if(!i){if(e.method!==`POST`){p(t,400,-32e3,`Session required`);return}if(i=await this.createRuntime(t),!i)return}await this.withRuntimeLock(i,async()=>{await i.transport.handleRequest(e,t,n),i.lastAccessAt=this.now();let r=i.transport.sessionId??i.id;e.method!==`DELETE`&&!d(r)&&this.options.onSessionActivity?.(r),e.method===`DELETE`&&!d(r)&&await this.closeSession(r,{closeTransport:!1})})}async closeExpiredSessions(){let e=[...this.runtimes.values()].filter(e=>this.now()-e.lastAccessAt>=this.sessionTimeoutMs).map(e=>e.id);for(let t of e)await this.closeSession(t);return e.length}async closeSession(e,t={}){let n=this.runtimes.get(e);return n?(this.runtimes.delete(e),t.notifySessionEnd!==!1&&!d(e)&&this.options.onSessionEnd?.(e),t.closeTransport!==!1&&await n.transport.close().catch(()=>void 0),await n.server.close().catch(()=>void 0),!0):!1}async closeAll(){let e=[...this.runtimes.keys()];for(let t of e)await this.closeSession(t)}async createRuntime(e){if(await this.closeExpiredSessions(),this.runtimes.size>=this.maxSessions){p(e,503,-32003,`Session capacity reached`);return}let t=this.now(),n=await this.options.createServer(),r={id:`${u}${l()}`,transport:void 0,createdAt:t,lastAccessAt:t,server:n,requestChain:Promise.resolve()},i=this.options.createTransport({sessionIdGenerator:()=>l(),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 h(e){let t=e.includes(`T`)?e:`${e.replace(` `,`T`)}Z`;return Date.parse(t)}var g=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=h(n.lastActivity);return Number.isFinite(r)&&e-r>=t}).map(e=>e.sessionId)}};const _=o(`server`);async function v(o,u){let[{default:d},{loadConfig:f,resolveIndexMode:p},{registerDashboardRoutes:h,resolveDashboardDir:v},{registerSettingsRoutes:y,resolveSettingsDir:b},{createSettingsRouter:x},{authMiddleware:S,getOrCreateToken:C}]=await Promise.all([import(`express`),import(`./config-B4klhHVp.js`),import(`./dashboard-static-dPnij4uF.js`),import(`./settings-static-MepJZjer.js`),import(`./routes-Ct7q5jrL.js`),import(`./auth-bEP-6uqy.js`)]),w=f();c(w.logging?.errorDetails===!0),w.configError&&_.warn(`Config load failure`,{error:w.configError}),_.info(`Config loaded`,{sourceCount:w.sources.length,storePath:w.store.path});let T=d();T.use(d.json({limit:`1mb`}));let E=Number(u),D=`http://localhost:${E}`,O=process.env.AIKIT_CORS_ORIGIN??D,k=process.env.AIKIT_ALLOW_ANY_ORIGIN===`true`,A=n(`AIKIT_HTTP_MAX_SESSIONS`,8),j=n(`AIKIT_HTTP_SESSION_TIMEOUT_MINUTES`,30),M=n(`AIKIT_HTTP_SESSION_GC_INTERVAL_MINUTES`,5),N=t({limit:100,windowMs:6e4}),P=!1;T.use((e,t,n)=>{let i=Array.isArray(e.headers.origin)?e.headers.origin[0]:e.headers.origin,a=r({requestOrigin:i,configuredOrigin:O,allowAnyOrigin:k,fallbackOrigin:D});if(a.warn&&!P&&(P=!0,_.warn(`Rejected non-local CORS origin while AIKIT_CORS_ORIGIN=*`,{origin:i,allowAnyOriginEnv:`AIKIT_ALLOW_ANY_ORIGIN=true`})),i&&!a.allowOrigin){t.status(403).json({error:`Origin not allowed`});return}if(a.allowOrigin&&t.setHeader(`Access-Control-Allow-Origin`,a.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 F=C();T.use(S(F)),T.use(`/mcp`,(t,n,r)=>{let i=e(t)??t.ip??t.socket.remoteAddress??`anonymous`;if(N.allow(i)){r();return}let a=Math.max(1,Math.ceil(N.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 I;T.use(`/mcp`,(e,t,n)=>{if(!I){let t=e.headers[`x-workspace-root`];typeof t==`string`&&t.length>0&&(I=t,_.debug(`Captured workspace root from proxy header`,{wsRoot:t}))}n()}),h(T,v(),_);let L=new Date().toISOString();T.use(`/settings/api`,x({log:_,mcpInfo:()=>({transport:`http`,port:E,pid:process.pid,startedAt:L})})),y(T,b(),_),T.get(`/health`,(e,t)=>{t.json({status:`ok`})});let R=!1,z=null,B=null,V=null,H=null,U=null,W=null,G=null,K=null,q=Promise.resolve(),J=async(t,n)=>{if(!R||!V||!H){n.status(503).json({jsonrpc:`2.0`,error:{code:-32603,message:`Server initializing — please retry in a few seconds`},id:null});return}let r=q,i;q=new Promise(e=>{i=e});let a={POST:6e4,GET:1e4,DELETE:1e4}[t.method]??3e4;if(!await Promise.race([r.then(()=>!0),new Promise(e=>{let n=setTimeout(()=>{_.warn(`mcpLock timed out waiting for previous request, resetting lock chain`,{method:t.method,timeoutMs:a}),e(!1)},a);n.unref&&n.unref()})])&&(q=Promise.resolve(),i=()=>{},W)){let e=W;W=null,G=null,e.close().catch(()=>{})}try{let r=e(t);if(!W){if(r){n.status(404).json({jsonrpc:`2.0`,error:{code:-32001,message:`Session not found`},id:null});return}let e=new H({sessionIdGenerator:()=>l(),onsessioninitialized:async e=>{G=e,B?.onSessionStart(e,{transport:`http`})},onsessionclosed:async e=>{e&&B?.onSessionEnd(e),G=null}});e.onclose=()=>{W===e&&(W=null),G===e.sessionId&&(G=null)},W=e,await V.connect(e)}let i=W;await i.handleRequest(t,n,t.body),t.method!==`DELETE`&&(!r&&i.sessionId?(G=i.sessionId,B?.onSessionStart(i.sessionId,{transport:`http`}),B?.onSessionActivity(i.sessionId)):r&&B?.onSessionActivity(r))}catch(e){if(_.error(`MCP handler error`,s(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()}},Y=async(t,n)=>{let r=e(t);if(U&&(!W||r!==G)){await U.handleRequest(t,n,t.body);return}await J(t,n)};T.post(`/mcp`,Y),T.get(`/mcp`,Y),T.delete(`/mcp`,Y);let X=T.listen(E,`127.0.0.1`,()=>{_.info(`MCP server listening`,{url:`http://127.0.0.1:${E}/mcp`,port:E}),setTimeout(async()=>{try{typeof I==`string`&&I.length>0&&(w.sources[0]={path:I,excludePatterns:w.sources[0]?.excludePatterns??[]},w.allRoots=[I],_.debug(`Workspace root applied from proxy header`,{wsRoot:I}));let[{createLazyServer:e,createMcpServer:t,ALL_TOOL_NAMES:n},{StreamableHTTPServerTransport:r},{checkForUpdates:c,autoUpgradeScaffold:l}]=await Promise.all([import(`./server-B3Wy5oMX.js`),import(`@modelcontextprotocol/sdk/server/streamableHttp.js`),import(`./version-check-CRvtGBDG.js`)]);c(),l(),setInterval(c,1440*60*1e3).unref();let u=!1,d=p(w),f=e(w,d);K=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(()=>{})])},V=f.server,H=r,R=!0,_.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`);B=new g(f.aikit.stateStore,{staleTimeoutMinutes:j,gcIntervalMinutes:M,onBeforeSessionDelete:e=>{if(G===e&&W){let e=W;W=null,G=null,e.close().catch(()=>void 0)}U?.closeSession(e,{notifySessionEnd:!1})},onSessionEndMaintenance:async()=>{if(!f.aikit?.curated||!f.aikit?.stateStore)return;let{pruneLessons:e}=await import(`./evolution-DWaEE6XW.js`).then(e=>e.t),t=await e(f.aikit.curated,f.aikit.stateStore,{dryRun:!1});t.pruned.length>0&&_.info(`Session-end lesson prune`,{pruned:t.pruned.length})}}),U=new m({createServer:()=>{if(!f.aikit)throw Error(`AI Kit components are not available after initialization`);return t(f.aikit,w)},createTransport:e=>new r(e),maxSessions:A,sessionTimeoutMinutes:j,onSessionStart:e=>B?.onSessionStart(e,{transport:`http`}),onSessionActivity:e=>B?.onSessionActivity(e),onSessionEnd:e=>B?.onSessionEnd(e)}),B.startGC(),G&&(B.onSessionStart(G,{transport:`http`}),B.onSessionActivity(G)),_.info(`HTTP session runtime ready`,{maxSessions:A,sessionTimeoutMinutes:j,gcIntervalMinutes:M})}catch(e){_.error(`Failed to start session manager`,s(e)),R=!1,u=!0,V=null,H=null,K=null}}),d===`auto`?f.ready.then(async()=>{try{let e=w.sources.map(e=>e.path).join(`, `);_.info(`Running initial index`,{sourcePaths:e}),await f.runInitialIndex(),_.info(`Initial index complete`)}catch(e){_.error(`Initial index failed; will retry on aikit_reindex`,i(o,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,w,f.aikit.store),n=f.aikit.store;z=t,t.start(),n.onBeforeClose&&n.onBeforeClose(()=>t.stop()),f.setSmartScheduler(t),_.debug(`Smart index scheduler started (HTTP mode)`)}catch(e){_.error(`Failed to start smart index scheduler`,i(o,e))}}):_.info(`Initial full indexing skipped in HTTP mode`,{indexMode:d}),f.ready.catch(e=>{_.error(`AI Kit initialization failed`,i(o,e)),R=!1,u=!0,V=null,H=null,K=null}),a(f.ready,()=>f.aikit?{curated:f.aikit.curated,stateStore:f.aikit.stateStore}:null,o)}catch(e){_.error(`Failed to load server modules`,i(o,e)),R=!1,K=null}},100)}),Z=!1,Q=async e=>{Z||(Z=!0,_.info(`Shutdown signal received`,{signal:e}),z?.stop(),B?.stop(),await import(`../../tools/dist/index.js`).then(({processStopAll:e})=>e()).catch(()=>{}),await U?.closeAll().catch(()=>void 0),G&&B?.onSessionEnd(G),W&&(await W.close().catch(()=>void 0),W=null,G=null),X.close(),V&&await V.close(),await K?.().catch(()=>void 0),process.exit(0))};process.on(`SIGINT`,()=>Q(`SIGINT`)),process.on(`SIGTERM`,()=>Q(`SIGTERM`))}export{v as startHttpMode};
2
+ import{a as e,i as t,o as n,s as r}from"./bin.js";import{n as i,t as a}from"./startup-maintenance-BPrX5-1U.js";import{createLogger as o,serializeError as s,setDetailedErrorLoggingEnabled as c}from"../../core/dist/index.js";import{randomUUID as l}from"node:crypto";const u=`__pending__:`;function d(e){return e.startsWith(u)}function f(e){let t=e.headers[`mcp-session-id`];return Array.isArray(t)?t[0]:t}function p(e,t,n,r){e.status(t).json({jsonrpc:`2.0`,error:{code:n,message:r},id:null})}var m=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=f(e),i=r?this.runtimes.get(r):void 0;if(r&&!i){p(t,404,-32001,`Session not found`);return}if(!i){if(e.method!==`POST`){p(t,400,-32e3,`Session required`);return}if(i=await this.createRuntime(t),!i)return}await this.withRuntimeLock(i,async()=>{await i.transport.handleRequest(e,t,n),i.lastAccessAt=this.now();let r=i.transport.sessionId??i.id;e.method!==`DELETE`&&!d(r)&&this.options.onSessionActivity?.(r),e.method===`DELETE`&&!d(r)&&await this.closeSession(r,{closeTransport:!1})})}async closeExpiredSessions(){let e=[...this.runtimes.values()].filter(e=>this.now()-e.lastAccessAt>=this.sessionTimeoutMs).map(e=>e.id);for(let t of e)await this.closeSession(t);return e.length}async closeSession(e,t={}){let n=this.runtimes.get(e);return n?(this.runtimes.delete(e),t.notifySessionEnd!==!1&&!d(e)&&this.options.onSessionEnd?.(e),t.closeTransport!==!1&&await n.transport.close().catch(()=>void 0),await n.server.close().catch(()=>void 0),!0):!1}async closeAll(){let e=[...this.runtimes.keys()];for(let t of e)await this.closeSession(t)}async createRuntime(e){if(await this.closeExpiredSessions(),this.runtimes.size>=this.maxSessions){p(e,503,-32003,`Session capacity reached`);return}let t=this.now(),n=await this.options.createServer(),r={id:`${u}${l()}`,transport:void 0,createdAt:t,lastAccessAt:t,server:n,requestChain:Promise.resolve()},i=this.options.createTransport({sessionIdGenerator:()=>l(),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 h(e){let t=e.includes(`T`)?e:`${e.replace(` `,`T`)}Z`;return Date.parse(t)}var g=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=h(n.lastActivity);return Number.isFinite(r)&&e-r>=t}).map(e=>e.sessionId)}};const _=o(`server`);async function v(o,u){let[{default:d},{loadConfig:f,resolveIndexMode:p},{registerDashboardRoutes:h,resolveDashboardDir:v},{registerSettingsRoutes:y,resolveSettingsDir:b},{createSettingsRouter:x},{authMiddleware:S,getOrCreateToken:C}]=await Promise.all([import(`express`),import(`./config-B4klhHVp.js`),import(`./dashboard-static-dPnij4uF.js`),import(`./settings-static-MepJZjer.js`),import(`./routes-Ct7q5jrL.js`),import(`./auth-bEP-6uqy.js`)]),w=f();c(w.logging?.errorDetails===!0),w.configError&&_.warn(`Config load failure`,{error:w.configError}),_.info(`Config loaded`,{sourceCount:w.sources.length,storePath:w.store.path});let T=d();T.use(d.json({limit:`1mb`}));let E=Number(u),D=`http://localhost:${E}`,O=process.env.AIKIT_CORS_ORIGIN??D,k=process.env.AIKIT_ALLOW_ANY_ORIGIN===`true`,A=n(`AIKIT_HTTP_MAX_SESSIONS`,8),j=n(`AIKIT_HTTP_SESSION_TIMEOUT_MINUTES`,30),M=n(`AIKIT_HTTP_SESSION_GC_INTERVAL_MINUTES`,5),N=t({limit:100,windowMs:6e4}),P=!1;T.use((e,t,n)=>{let i=Array.isArray(e.headers.origin)?e.headers.origin[0]:e.headers.origin,a=r({requestOrigin:i,configuredOrigin:O,allowAnyOrigin:k,fallbackOrigin:D});if(a.warn&&!P&&(P=!0,_.warn(`Rejected non-local CORS origin while AIKIT_CORS_ORIGIN=*`,{origin:i,allowAnyOriginEnv:`AIKIT_ALLOW_ANY_ORIGIN=true`})),i&&!a.allowOrigin){t.status(403).json({error:`Origin not allowed`});return}if(a.allowOrigin&&t.setHeader(`Access-Control-Allow-Origin`,a.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 F=C();T.use(S(F)),T.use(`/mcp`,(t,n,r)=>{let i=e(t)??t.ip??t.socket.remoteAddress??`anonymous`;if(N.allow(i)){r();return}let a=Math.max(1,Math.ceil(N.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 I;T.use(`/mcp`,(e,t,n)=>{if(!I){let t=e.headers[`x-workspace-root`];typeof t==`string`&&t.length>0&&(I=t,_.debug(`Captured workspace root from proxy header`,{wsRoot:t}))}n()}),h(T,v(),_);let L=new Date().toISOString();T.use(`/settings/api`,x({log:_,mcpInfo:()=>({transport:`http`,port:E,pid:process.pid,startedAt:L})})),y(T,b(),_),T.get(`/health`,(e,t)=>{t.json({status:`ok`})});let R=!1,z=null,B=null,V=null,H=null,U=null,W=null,G=null,K=null,q=Promise.resolve(),J=async(t,n)=>{if(!R||!V||!H){n.status(503).json({jsonrpc:`2.0`,error:{code:-32603,message:`Server initializing — please retry in a few seconds`},id:null});return}let r=q,i;q=new Promise(e=>{i=e});let a={POST:6e4,GET:1e4,DELETE:1e4}[t.method]??3e4;if(!await Promise.race([r.then(()=>!0),new Promise(e=>{let n=setTimeout(()=>{_.warn(`mcpLock timed out waiting for previous request, resetting lock chain`,{method:t.method,timeoutMs:a}),e(!1)},a);n.unref&&n.unref()})])&&(q=Promise.resolve(),i=()=>{},W)){let e=W;W=null,G=null,e.close().catch(()=>{})}try{let r=e(t);if(!W){if(r){n.status(404).json({jsonrpc:`2.0`,error:{code:-32001,message:`Session not found`},id:null});return}let e=new H({sessionIdGenerator:()=>l(),onsessioninitialized:async e=>{G=e,B?.onSessionStart(e,{transport:`http`})},onsessionclosed:async e=>{e&&B?.onSessionEnd(e),G=null}});e.onclose=()=>{W===e&&(W=null),G===e.sessionId&&(G=null)},W=e,await V.connect(e)}let i=W;await i.handleRequest(t,n,t.body),t.method!==`DELETE`&&(!r&&i.sessionId?(G=i.sessionId,B?.onSessionStart(i.sessionId,{transport:`http`}),B?.onSessionActivity(i.sessionId)):r&&B?.onSessionActivity(r))}catch(e){if(_.error(`MCP handler error`,s(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()}},Y=async(t,n)=>{let r=e(t);if(U&&(!W||r!==G)){await U.handleRequest(t,n,t.body);return}await J(t,n)};T.post(`/mcp`,Y),T.get(`/mcp`,Y),T.delete(`/mcp`,Y);let X=T.listen(E,`127.0.0.1`,()=>{_.info(`MCP server listening`,{url:`http://127.0.0.1:${E}/mcp`,port:E}),setTimeout(async()=>{try{typeof I==`string`&&I.length>0&&(w.sources[0]={path:I,excludePatterns:w.sources[0]?.excludePatterns??[]},w.allRoots=[I],_.debug(`Workspace root applied from proxy header`,{wsRoot:I}));let[{createLazyServer:e,createMcpServer:t,ALL_TOOL_NAMES:n},{StreamableHTTPServerTransport:r},{checkForUpdates:c,autoUpgradeScaffold:l}]=await Promise.all([import(`./server-Cchjt4r6.js`),import(`@modelcontextprotocol/sdk/server/streamableHttp.js`),import(`./version-check-CRvtGBDG.js`)]);c(),l(),setInterval(c,1440*60*1e3).unref();let u=!1,d=p(w),f=e(w,d);K=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(()=>{})])},V=f.server,H=r,R=!0,_.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`);B=new g(f.aikit.stateStore,{staleTimeoutMinutes:j,gcIntervalMinutes:M,onBeforeSessionDelete:e=>{if(G===e&&W){let e=W;W=null,G=null,e.close().catch(()=>void 0)}U?.closeSession(e,{notifySessionEnd:!1})},onSessionEndMaintenance:async()=>{if(!f.aikit?.curated||!f.aikit?.stateStore)return;let{pruneLessons:e}=await import(`./evolution-DWaEE6XW.js`).then(e=>e.t),t=await e(f.aikit.curated,f.aikit.stateStore,{dryRun:!1});t.pruned.length>0&&_.info(`Session-end lesson prune`,{pruned:t.pruned.length})}}),U=new m({createServer:()=>{if(!f.aikit)throw Error(`AI Kit components are not available after initialization`);return t(f.aikit,w)},createTransport:e=>new r(e),maxSessions:A,sessionTimeoutMinutes:j,onSessionStart:e=>B?.onSessionStart(e,{transport:`http`}),onSessionActivity:e=>B?.onSessionActivity(e),onSessionEnd:e=>B?.onSessionEnd(e)}),B.startGC(),G&&(B.onSessionStart(G,{transport:`http`}),B.onSessionActivity(G)),_.info(`HTTP session runtime ready`,{maxSessions:A,sessionTimeoutMinutes:j,gcIntervalMinutes:M})}catch(e){_.error(`Failed to start session manager`,s(e)),R=!1,u=!0,V=null,H=null,K=null}}),d===`auto`?f.ready.then(async()=>{try{let e=w.sources.map(e=>e.path).join(`, `);_.info(`Running initial index`,{sourcePaths:e}),await f.runInitialIndex(),_.info(`Initial index complete`)}catch(e){_.error(`Initial index failed; will retry on aikit_reindex`,i(o,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,w,f.aikit.store),n=f.aikit.store;z=t,t.start(),n.onBeforeClose&&n.onBeforeClose(()=>t.stop()),f.setSmartScheduler(t),_.debug(`Smart index scheduler started (HTTP mode)`)}catch(e){_.error(`Failed to start smart index scheduler`,i(o,e))}}):_.info(`Initial full indexing skipped in HTTP mode`,{indexMode:d}),f.ready.catch(e=>{_.error(`AI Kit initialization failed`,i(o,e)),R=!1,u=!0,V=null,H=null,K=null}),a(f.ready,()=>f.aikit?{curated:f.aikit.curated,stateStore:f.aikit.stateStore}:null,o)}catch(e){_.error(`Failed to load server modules`,i(o,e)),R=!1,K=null}},100)}),Z=!1,Q=async e=>{Z||(Z=!0,_.info(`Shutdown signal received`,{signal:e}),z?.stop(),B?.stop(),await import(`../../tools/dist/index.js`).then(({processStopAll:e})=>e()).catch(()=>{}),await U?.closeAll().catch(()=>void 0),G&&B?.onSessionEnd(G),W&&(await W.close().catch(()=>void 0),W=null,G=null),X.close(),V&&await V.close(),await K?.().catch(()=>void 0),process.exit(0))};process.on(`SIGINT`,()=>Q(`SIGINT`)),process.on(`SIGTERM`,()=>Q(`SIGTERM`))}export{v as startHttpMode};
@@ -0,0 +1 @@
1
+ import{n as e}from"./workspace-bootstrap-B57Oz40_.js";import{n as t,t as n}from"./startup-maintenance-CT6Z3734.js";import{t as r}from"./repair-json-B6Q_HRoP.js";import{createLogger as i,serializeError as a,setDetailedErrorLoggingEnabled as o}from"../../core/dist/index.js";const s=i(`server`);var c=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 s.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 l(r){let[{loadConfig:i,reconfigureForWorkspace:l,resolveIndexMode:u},{createLazyServer:d},{checkForUpdates:f,autoUpgradeScaffold:p},{RootsListChangedNotificationSchema:m}]=await Promise.all([import(`./config-D3rRPB9X.js`),import(`./server-P4KQX_3U.js`),import(`./version-check-DNe43rCZ.js`),import(`@modelcontextprotocol/sdk/types.js`)]),h=i();o(h.logging?.errorDetails===!0),h.configError&&s.warn(`Config load failure`,{error:h.configError}),s.info(`Config loaded`,{sourceCount:h.sources.length,storePath:h.store.path}),p(),setInterval(f,1440*60*1e3).unref();let g=u(h),_=d(h,g),{server:v,startInit:y,ready:b,runInitialIndex:x}=_,{StdioServerTransport:S}=await import(`@modelcontextprotocol/sdk/server/stdio.js`),C=new S;if(typeof C._readBuffer?.readMessage!=`function`)throw Error(`Cannot install JSON repair: StdioServerTransport._readBuffer has unexpected shape`);C._readBuffer=new c,s.debug(`JSON repair installed on stdio transport`),await v.connect(C),s.debug(`MCP server started`,{transport:`stdio`}),await e({config:h,indexMode:g,log:s,rootsChangedNotificationSchema:m,reconfigureForWorkspace:l,runInitialIndex:x,server:v,startInit:y,version:r});let w=null,T=null,E=!1,D=async e=>{E||(E=!0,s.info(`Shutdown signal received`,{signal:e}),w&&=(clearTimeout(w),null),T?.stop(),await import(`../../tools/dist/index.js`).then(({processStopAll:e})=>e()).catch(()=>{}),await C.close().catch(()=>void 0),await v.close().catch(()=>void 0),_.aikit&&await Promise.all([_.aikit.embedder.shutdown?.().catch(()=>{})??Promise.resolve(),_.aikit.graphStore.close().catch(()=>{}),_.aikit.closeStateStore?.().catch(()=>{})??Promise.resolve(),_.aikit.store.close().catch(()=>{})]),process.exit(0))},O=()=>{w&&clearTimeout(w),w=setTimeout(async()=>{s.info(`Auto-shutdown: no activity for 30 minutes — releasing resources`);try{let e=_.aikit;e&&(e.embedder.shutdown?.().catch(()=>{}),e.store.releaseMemory?.(),e.graphStore.releaseMemory?.())}catch(e){s.warn(`Resource release failed during shutdown`,a(e))}},18e5),w.unref&&w.unref()};O(),process.stdin.on(`data`,()=>O()),process.stdin.on(`end`,()=>void D(`stdin-end`)),process.stdin.on(`close`,()=>void D(`stdin-close`)),process.stdin.on(`error`,()=>void D(`stdin-error`)),process.on(`SIGINT`,()=>void D(`SIGINT`)),process.on(`SIGTERM`,()=>void D(`SIGTERM`)),b.catch(e=>{s.error(`Initialization failed — server will continue with limited tools`,t(r,e))}),g===`smart`?b.then(async()=>{try{if(!_.aikit)throw Error(`AI Kit components are not available after initialization`);let{SmartIndexScheduler:e}=await import(`../../indexer/dist/index.js`),t=new e(_.aikit.indexer,h,_.aikit.store);T=t;let n=_.aikit.store;t.start(),n.onBeforeClose&&n.onBeforeClose(()=>t.stop()),_.setSmartScheduler(t),s.debug(`Smart index scheduler started (stdio mode)`)}catch(e){s.error(`Failed to start smart index scheduler`,t(r,e))}}).catch(e=>s.error(`AI Kit init failed for smart scheduler`,t(r,e))):s.warn(`Initial full indexing skipped; use aikit_reindex to index manually`,{indexMode:g}),n(b,()=>_.aikit?{curated:_.aikit.curated,stateStore:_.aikit.stateStore}:null,r)}export{l as startStdioMode};
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ import{r as e}from"./bin.js";import{n as t,t as n}from"./startup-maintenance-BPrX5-1U.js";import{t as r}from"./repair-json-D4mft_HA.js";import{createLogger as i,serializeError as a,setDetailedErrorLoggingEnabled as o}from"../../core/dist/index.js";const s=i(`server`);var c=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 s.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 l(r){let[{loadConfig:i,reconfigureForWorkspace:l,resolveIndexMode:u},{createLazyServer:d},{checkForUpdates:f,autoUpgradeScaffold:p},{RootsListChangedNotificationSchema:m}]=await Promise.all([import(`./config-B4klhHVp.js`),import(`./server-Cchjt4r6.js`),import(`./version-check-CRvtGBDG.js`),import(`@modelcontextprotocol/sdk/types.js`)]),h=i();o(h.logging?.errorDetails===!0),h.configError&&s.warn(`Config load failure`,{error:h.configError}),s.info(`Config loaded`,{sourceCount:h.sources.length,storePath:h.store.path}),p(),setInterval(f,1440*60*1e3).unref();let g=u(h),_=d(h,g),{server:v,startInit:y,ready:b,runInitialIndex:x}=_,{StdioServerTransport:S}=await import(`@modelcontextprotocol/sdk/server/stdio.js`),C=new S;if(typeof C._readBuffer?.readMessage!=`function`)throw Error(`Cannot install JSON repair: StdioServerTransport._readBuffer has unexpected shape`);C._readBuffer=new c,s.debug(`JSON repair installed on stdio transport`),await v.connect(C),s.debug(`MCP server started`,{transport:`stdio`}),await e({config:h,indexMode:g,log:s,rootsChangedNotificationSchema:m,reconfigureForWorkspace:l,runInitialIndex:x,server:v,startInit:y,version:r});let w=null,T=null,E=!1,D=async e=>{E||(E=!0,s.info(`Shutdown signal received`,{signal:e}),w&&=(clearTimeout(w),null),T?.stop(),await import(`../../tools/dist/index.js`).then(({processStopAll:e})=>e()).catch(()=>{}),await C.close().catch(()=>void 0),await v.close().catch(()=>void 0),_.aikit&&await Promise.all([_.aikit.embedder.shutdown?.().catch(()=>{})??Promise.resolve(),_.aikit.graphStore.close().catch(()=>{}),_.aikit.closeStateStore?.().catch(()=>{})??Promise.resolve(),_.aikit.store.close().catch(()=>{})]),process.exit(0))},O=()=>{w&&clearTimeout(w),w=setTimeout(async()=>{s.info(`Auto-shutdown: no activity for 30 minutes — releasing resources`);try{let e=_.aikit;e&&(e.embedder.shutdown?.().catch(()=>{}),e.store.releaseMemory?.(),e.graphStore.releaseMemory?.())}catch(e){s.warn(`Resource release failed during shutdown`,a(e))}},18e5),w.unref&&w.unref()};O(),process.stdin.on(`data`,()=>O()),process.stdin.on(`end`,()=>void D(`stdin-end`)),process.stdin.on(`close`,()=>void D(`stdin-close`)),process.stdin.on(`error`,()=>void D(`stdin-error`)),process.on(`SIGINT`,()=>void D(`SIGINT`)),process.on(`SIGTERM`,()=>void D(`SIGTERM`)),b.catch(e=>{s.error(`Initialization failed — server will continue with limited tools`,t(r,e))}),g===`smart`?b.then(async()=>{try{if(!_.aikit)throw Error(`AI Kit components are not available after initialization`);let{SmartIndexScheduler:e}=await import(`../../indexer/dist/index.js`),t=new e(_.aikit.indexer,h,_.aikit.store);T=t;let n=_.aikit.store;t.start(),n.onBeforeClose&&n.onBeforeClose(()=>t.stop()),_.setSmartScheduler(t),s.debug(`Smart index scheduler started (stdio mode)`)}catch(e){s.error(`Failed to start smart index scheduler`,t(r,e))}}).catch(e=>s.error(`AI Kit init failed for smart scheduler`,t(r,e))):s.warn(`Initial full indexing skipped; use aikit_reindex to index manually`,{indexMode:g}),n(b,()=>_.aikit?{curated:_.aikit.curated,stateStore:_.aikit.stateStore}:null,r)}export{l as startStdioMode};
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ import{t as e}from"./bin.js";import{createLogger as t,serializeError as n}from"../../core/dist/index.js";const r=t(`server`);function i(e,t){return t?{version:e,...n(t)}:{version:e}}function a(t,a,o){t.then(async()=>{try{let{markPromoteRun:t,markPruneRun:n,prune:i,shouldRunStartupPrune:o,shouldRunWeeklyPromote:s}=await import(`../../tools/dist/index.js`),c=a();if(!c)return;try{let{readdirSync:e,rmSync:t,statSync:n,existsSync:i}=await import(`node:fs`),{join:a}=await import(`node:path`),{homedir:o}=await import(`node:os`),s=a(o(),`.aikit`,`workspaces`);if(i(s)){let o=Date.now(),c=e(s,{withFileTypes:!0}),l=0;for(let e of c){if(!e.isDirectory())continue;let r=a(s,e.name);try{if(o-n(r).mtimeMs<2592e6)continue;let e=a(r,`store`,`aikit.db`);if(!i(e)){t(r,{recursive:!0,force:!0}),l++;continue}n(e).size<1024&&(t(r,{recursive:!0,force:!0}),l++)}catch{}}l>0&&r.info(`Workspace directory GC complete`,{directoriesRemoved:l,directoriesRemaining:c.length-l})}}catch{}if(o()){let e=await i({});n(),e.totalBytesFreed>0&&r.info(`Storage maintenance complete`,{forgeOrphans:e.forgeGroundOrphans.count,legacyLance:e.legacyLance.count,bytesFreed:e.totalBytesFreed});let{groupLessons:t,pruneLessons:a}=await import(`./evolution-DWaEE6XW.js`).then(e=>e.t),o=await a(c.curated,c.stateStore,{dryRun:!1});o.pruned.length>0&&r.info(`Startup lesson prune complete`,{pruned:o.pruned.length});let s=await t(c.curated,c.stateStore,{dryRun:!1});(s.groupsCreated>0||s.lessonsGrouped>0)&&r.info(`Startup lesson grouping complete`,{groupsCreated:s.groupsCreated,lessonsGrouped:s.lessonsGrouped})}if(s()){let{DEFAULT_PROMOTE_CONFIG:n,collectWorkspaceLessons:i,getGlobalCuratedDir:a,promoteLessons:o,scanForDuplicates:s}=await import(`./promotion-DRnRfteq.js`).then(e=>e.o),l=c.curated,u=new e(a(),l.store,l.embedder),d=await i(),f={...n,dryRun:!1},p=await o(s(d,f),u,f);t(),p.promoted.length>0&&r.info(`Weekly lesson promotion complete`,{promoted:p.promoted.length,candidates:p.candidates.length})}}catch(e){r.warn(`Startup maintenance failed (non-critical)`,i(o,e))}}).catch(e=>r.warn(`Startup maintenance failed`,n(e)))}export{i as n,a as t};
@@ -0,0 +1 @@
1
+ import{t as e}from"./curated-manager-CBKTmAjM.js";import{createLogger as t,serializeError as n}from"../../core/dist/index.js";const r=t(`server`);function i(e,t){return t?{version:e,...n(t)}:{version:e}}function a(t,a,o){t.then(async()=>{try{let{markPromoteRun:t,markPruneRun:n,prune:i,shouldRunStartupPrune:o,shouldRunWeeklyPromote:s}=await import(`../../tools/dist/index.js`),c=a();if(!c)return;try{let{readdirSync:e,rmSync:t,statSync:n,existsSync:i}=await import(`node:fs`),{join:a}=await import(`node:path`),{homedir:o}=await import(`node:os`),s=a(o(),`.aikit`,`workspaces`);if(i(s)){let o=Date.now(),c=e(s,{withFileTypes:!0}),l=0;for(let e of c){if(!e.isDirectory())continue;let r=a(s,e.name);try{if(o-n(r).mtimeMs<2592e6)continue;let e=a(r,`store`,`aikit.db`);if(!i(e)){t(r,{recursive:!0,force:!0}),l++;continue}n(e).size<1024&&(t(r,{recursive:!0,force:!0}),l++)}catch{}}l>0&&r.info(`Workspace directory GC complete`,{directoriesRemoved:l,directoriesRemaining:c.length-l})}}catch{}if(o()){let e=await i({});n(),e.totalBytesFreed>0&&r.info(`Storage maintenance complete`,{forgeOrphans:e.forgeGroundOrphans.count,legacyLance:e.legacyLance.count,bytesFreed:e.totalBytesFreed});let{groupLessons:t,pruneLessons:a}=await import(`./evolution-BX_zTSdj.js`).then(e=>e.t),o=await a(c.curated,c.stateStore,{dryRun:!1});o.pruned.length>0&&r.info(`Startup lesson prune complete`,{pruned:o.pruned.length});let s=await t(c.curated,c.stateStore,{dryRun:!1});(s.groupsCreated>0||s.lessonsGrouped>0)&&r.info(`Startup lesson grouping complete`,{groupsCreated:s.groupsCreated,lessonsGrouped:s.lessonsGrouped})}if(s()){let{DEFAULT_PROMOTE_CONFIG:n,collectWorkspaceLessons:i,getGlobalCuratedDir:a,promoteLessons:o,scanForDuplicates:s}=await import(`./promotion-DzVLWVtx.js`).then(e=>e.o),l=c.curated,u=new e(a(),l.store,l.embedder),d=await i(),f={...n,dryRun:!1},p=await o(s(d,f),u,f);t(),p.promoted.length>0&&r.info(`Weekly lesson promotion complete`,{promoted:p.promoted.length,candidates:p.candidates.length})}}catch(e){r.warn(`Startup maintenance failed (non-critical)`,i(o,e))}}).catch(e=>r.warn(`Startup maintenance failed`,n(e)))}export{i as n,a as t};
@@ -111,7 +111,7 @@ import{createRequire as e}from"node:module";import{AIKIT_PATHS as t,EMBEDDING_DE
111
111
  `)}},{version:4,name:`backfill vec0 embeddings into memory_embeddings`,up(e){let t=e.queryAll(`SELECT COUNT(*) AS cnt FROM memory_embeddings`);if(t[0]?.cnt&&t[0].cnt>0)return;let n=e.queryAll(`SELECT name, sql FROM sqlite_master WHERE type = 'table' AND sql LIKE '%vec0%'`);if(n.length===0)return;let r=Date.now(),i=0;for(let t of n){let n=t.sql.match(/(?:int8|float)\[(\d+)\]/i);if(!n)continue;let a=Number(n[1]),o=e.queryAll(`SELECT COUNT(*) AS cnt FROM memory_embeddings`)[0]?.cnt??0;e.run(`INSERT OR IGNORE INTO memory_embeddings
112
112
  (memory_id, embedding_model, embedding_version, dimensions, element_type, embedding, created_at)
113
113
  SELECT knowledge_id, 'default', '1', ?, 'float32', embedding, ?
114
- FROM ${t.name}`,[a,r]);let s=e.queryAll(`SELECT COUNT(*) AS cnt FROM memory_embeddings`)[0]?.cnt??0;i+=s-o}i>0&&oe.info(`[migration v4] backfilled ${i} embeddings into memory_embeddings`)}}],v=a(`sqlite-adapter`),y=e(import.meta.url),b=`better-sqlite3`;function ce(e){return e.replace(/\\/g,`/`)}function x(){return y.resolve(`@vpxa/aikit/package.json`).replace(/[\\/]package\.json$/,``)}function S(){return x().replace(/[\\/]node_modules[\\/]@vpxa[\\/]aikit$/,``)}function le(e){return ce(e).includes(`/_npx/`)}function C(){try{return JSON.parse(u(h(x(),`package.json`),`utf8`)).optionalDependencies?.[b]??`latest`}catch{return`latest`}}function ue(e){return e.replace(/[^a-zA-Z0-9._-]+/g,`_`)}function de(){let e=`${ue(C())}-${process.platform}-${process.arch}-abi${process.versions.modules}`;return h(re(),`.aikit`,`cache`,`native-modules`,b,e)}function w(e){l(e,{recursive:!0});let t=h(e,`package.json`);c(t)||p(t,`${JSON.stringify({name:`aikit-native-runtime-cache`,private:!0},null,2)}\n`,`utf8`)}function fe(e){let t=D(e);if(!t)return null;try{return JSON.parse(u(h(t,`package.json`),`utf8`)).version??null}catch{return null}}function T(e,t){try{let n={packageName:b,packageSpec:C(),packageVersion:fe(e),platform:process.platform,arch:process.arch,nodeAbi:process.versions.modules,installedAt:new Date().toISOString(),source:t};p(h(e,`.aikit-native-module.json`),`${JSON.stringify(n,null,2)}\n`,`utf8`)}catch(e){v.debug(`Failed to write better-sqlite3 runtime marker`,o(e))}}var E=class{runtimeRoot;type=`better-sqlite3`;kind=`better-sqlite3`;vectorCapable=!1;get capabilities(){return{vectorCapable:this.vectorCapable,persistentFile:!0,concurrentReaders:!0}}db=null;stmtCache=new Map;dbPath=``;DatabaseCtor=null;recovering=!1;constructor(e){this.runtimeRoot=e}async open(t){let n;try{let t=y;this.runtimeRoot!=null&&(w(this.runtimeRoot),t=e(h(this.runtimeRoot,`package.json`))),n=t(b)}catch(e){throw Error(`better-sqlite3 native binding unavailable: ${e instanceof Error?e.message:String(e)}`)}this.db=new n(t),this.dbPath=t,this.DatabaseCtor=n,this.db.pragma(`journal_mode = WAL`),this.db.pragma(`foreign_keys = ON`),this.db.pragma(`synchronous = NORMAL`),this.runIntegrityCheck(t,n)||(this.db?.pragma(`journal_mode = WAL`),this.db?.pragma(`foreign_keys = ON`),this.db?.pragma(`synchronous = NORMAL`));try{y(`sqlite-vec`).load(this.db),this.vectorCapable=!0,v.debug(`sqlite-vec extension loaded`)}catch(e){this.vectorCapable=!1,v.warn(`sqlite-vec extension failed to load; vector search disabled`,o(e))}}exec(e){try{this.getDb().exec(e)}catch(t){if(this.isCorruptionError(t)){this.recover(),this.getDb().exec(e);return}throw t}}pragma(e){this.getDb().pragma(e)}queryAll(e,t=[]){try{let n=this.prepareCached(e);return t.length>0?n.all(...t):n.all()}catch(n){if(this.isCorruptionError(n))return this.recover(),this.queryAll(e,t);throw n}}run(e,t){try{let n=this.prepareCached(e);return t===void 0?n.run():Array.isArray(t)?t.length===0?n.run():n.run(...t):n.run(t)}catch(n){if(this.isCorruptionError(n))return this.recover(),this.run(e,t);throw n}}get(e,t){try{let n=this.prepareCached(e);return t===void 0?n.get():Array.isArray(t)?t.length>0?n.get(...t):n.get():n.get(t)}catch(n){if(this.isCorruptionError(n))return this.recover(),this.get(e,t);throw n}}all(e,t){try{let n=this.prepareCached(e);return t===void 0?n.all():Array.isArray(t)?t.length>0?n.all(...t):n.all():n.all(t)}catch(n){if(this.isCorruptionError(n))return this.recover(),this.all(e,t);throw n}}transaction(e){return this.getDb().transaction(()=>e(this.createTransactionHandle()))()}createTransactionHandle(){return{exec:e=>this.exec(e),get:(e,t)=>this.get(e,t),all:(e,t)=>this.all(e,t),run:(e,t)=>this.run(e,t)}}flush(){}async close(){this.db&&=(this.stmtCache.clear(),this.db.close(),null)}runIntegrityCheck(e,t){try{let t=this.db?.pragma(`integrity_check`);if(t.length===1&&t[0]?.integrity_check===`ok`)return!0;let n=t.map(e=>e.integrity_check).slice(0,5).join(`; `);v.warn(`Database integrity check failed — recreating`,{dbPath:e,issues:n})}catch(t){v.warn(`Integrity check query failed — recreating database`,{dbPath:e,error:o(t)})}try{this.db?.close()}catch{}this.db=null,this.stmtCache.clear();try{f(e)}catch{}try{f(`${e}-wal`)}catch{}try{f(`${e}-shm`)}catch{}return this.db=new t(e),v.info(`Database recreated successfully — full reindex required`,{dbPath:e}),!1}isCorruptionError(e){if(this.recovering)return!1;let t=e instanceof Error?e.message:String(e);return/database disk image is malformed|file is not a database|database or disk is full/.test(t)}recover(){if(this.recovering)throw Error(`BetterSqlite3Adapter: recovery already in progress`);this.recovering=!0;try{v.warn(`Runtime corruption detected — recovering database`,{dbPath:this.dbPath});try{this.db?.close()}catch{}this.db=null,this.stmtCache.clear();try{f(this.dbPath)}catch{}try{f(`${this.dbPath}-wal`)}catch{}try{f(`${this.dbPath}-shm`)}catch{}if(!this.DatabaseCtor)throw Error(`DatabaseCtor is not initialized`);this.db=this.DatabaseCtor(this.dbPath),this.db.pragma(`journal_mode = WAL`),this.db.pragma(`foreign_keys = ON`),this.db.pragma(`synchronous = NORMAL`);try{y(`sqlite-vec`).load(this.db),this.vectorCapable=!0}catch{this.vectorCapable=!1}v.info(`Database recovered — full reindex required`,{dbPath:this.dbPath})}finally{this.recovering=!1}}getDb(){if(!this.db)throw Error(`BetterSqlite3Adapter: database not opened`);return this.db}prepareCached(e){let t=this.stmtCache.get(e);if(t)return t;let n=this.getDb().prepare(e);return this.stmtCache.set(e,n),n}};function D(e){if(e){let t=h(e,`node_modules`,b);return c(h(t,`package.json`))?t:null}try{return y.resolve(`${b}/package.json`).replace(/[\\/]package\.json$/,``)}catch{return null}}function pe(e){let t=D(e);if(!t)return null;let n=h(t,`build`,`Release`,`better_sqlite3.node`);return c(n)?n:null}async function me(e){let t=D(e);if(!t)return`package-missing`;if(!c(h(t,`build`,`Release`,`better_sqlite3.node`)))return`binding-missing`;try{let{execFileSync:t}=await import(`node:child_process`),n=e??S();return e&&w(e),t(process.execPath,[`-e`,`require('${b}')`],{cwd:n,stdio:`pipe`,timeout:15e3,windowsHide:!0}),`ok`}catch(e){let t=e instanceof Error&&`stderr`in e?String(e.stderr):``;return/NODE_MODULE_VERSION/.test(t)?`abi-mismatch`:/Could not locate the bindings file|no native build was found/.test(t)?`binding-missing`:`error`}}async function he(e,t=!1){let n=D(e);if(!n)return v.info(`better-sqlite3 package is not installed — skipping native rebuild`),!1;try{let{execFileSync:r}=await import(`node:child_process`),i=e??n.replace(/[\\/]node_modules[\\/]better-sqlite3$/,``),a=process.platform===`win32`?`npm.cmd`:`npm`;if(e&&w(e),t){let e=h(n,`build`,`Release`,`better_sqlite3.node`);if(c(e))try{f(e),v.info(`Deleted stale native binding before rebuild`,{path:e})}catch(t){v.warn(`Cannot delete stale native binding — file may be locked by another process`,{path:e,error:t instanceof Error?t.message:String(t)})}}return v.info(`Attempting native module rebuild for better-sqlite3`,{cwd:i}),r(a,[`rebuild`,b],{cwd:i,stdio:`pipe`,timeout:6e4,windowsHide:!0}),v.info(`Native module rebuild completed successfully`),T(i,`rebuild`),!0}catch(e){return v.warn(`Native module rebuild failed — continuing with sql.js fallback`,o(e)),!1}}async function ge(e){try{let{execFileSync:t}=await import(`node:child_process`),n=e??S(),r=process.platform===`win32`?`npm.cmd`:`npm`,i=C();return w(n),v.info(`Attempting to install better-sqlite3 for native adapter recovery`,{cwd:n,packageSpec:i}),t(r,[`install`,`--no-save`,`--package-lock=false`,`--no-audit`,`--no-fund`,`--omit=dev`,`${b}@${i}`],{cwd:n,stdio:`pipe`,timeout:12e4,windowsHide:!0}),v.info(`better-sqlite3 install completed successfully`),T(n,`install`),!0}catch(e){return v.warn(`better-sqlite3 install failed — continuing with sql.js fallback`,o(e)),!1}}const O=a(`driver-selector`),k=e(import.meta.url);var _e=class extends Error{code=`STORAGE_INITIALIZATION_FAILED`;failures;constructor(e){let t=e.map(e=>`[${e.code}] ${e.driver}: ${e.message}`).join(`; `);super(`All SQLite drivers failed to initialise (${e.length}): ${t}`),this.name=`StorageInitializationError`,this.failures=e}};function ve(e){let[t,n]=(e??process.versions.node).split(`.`),r=Number.parseInt(t??`0`,10);return r>22||r===22&&Number.parseInt(n??`0`,10)>=13}function ye(e){if(typeof e!=`function`)return!1;let t=e.prototype;return typeof t?.enableLoadExtension==`function`&&typeof t.loadExtension==`function`}function A(e,t,n){return{available:!1,failure:{driver:e,code:t,message:n}}}function j(e){return{available:!0,capabilities:e}}function be(){try{try{let e=k(`sqlite-vec`);if(typeof e.getLoadablePath==`function`){let t=e.getLoadablePath();if(t&&c(t))return t}if(e.loadablePath&&c(e.loadablePath))return e.loadablePath}catch{}let e=m(k.resolve(`sqlite-vec/package.json`)),t={"win32-x64":`sqlite-vec-win32-x64.node`,"win32-arm64":`sqlite-vec-win32-arm64.node`,"darwin-x64":`sqlite-vec-darwin-x64.node`,"darwin-arm64":`sqlite-vec-darwin-arm64.node`,"linux-x64":`sqlite-vec-linux-x64.node`,"linux-arm64":`sqlite-vec-linux-arm64.node`}[`${process.platform}-${process.arch}`];if(t){let n=h(e,t);if(c(n))return n}let n=h(e,`sqlite-vec.node`);if(c(n))return n;let r=h(m(k.resolve(`sqlite-vec`)),`sqlite-vec.node`);return c(r)?r:null}catch{return null}}async function M(){if(!ve())return A(`node-sqlite`,`NODE_VERSION_UNSUPPORTED`,`Node.js ${process.versions.node} < 22.13 — node:sqlite extension loading unavailable`);let e;try{let t=await import(`node:sqlite`);if(!ye(t.DatabaseSync))return A(`node-sqlite`,`EXTENSION_LOADING_DISABLED`,`node:sqlite is available but DatabaseSync extension loading APIs are unavailable`);e=t.DatabaseSync}catch(e){return A(`node-sqlite`,`MODULE_NOT_AVAILABLE`,`node:sqlite not available: ${e instanceof Error?e.message:String(e)}`)}let t=new e(`:memory:`,{allowExtension:!0});try{try{t.enableLoadExtension(!0)}catch(e){return A(`node-sqlite`,`EXTENSION_LOADING_DISABLED`,`enableLoadExtension failed: ${e instanceof Error?e.message:String(e)}`)}let e=be();if(!e)return A(`node-sqlite`,`NATIVE_BINARY_UNAVAILABLE`,`Could not resolve sqlite-vec native binary path`);try{t.loadExtension(e)}catch(e){return A(`node-sqlite`,`SQLITE_VEC_LOAD_FAILED`,`sqlite-vec loadExtension failed: ${e instanceof Error?e.message:String(e)}`)}try{let e=t.prepare(`SELECT vec_version() AS v`).get();if(!e||typeof e.v!=`string`)return A(`node-sqlite`,`SQLITE_VEC_PROBE_FAILED`,`vec_version() returned empty result`);O.debug(`node-sqlite: sqlite-vec ${e.v}`)}catch(e){return A(`node-sqlite`,`SQLITE_VEC_PROBE_FAILED`,`vec_version() failed: ${e instanceof Error?e.message:String(e)}`)}try{let e=new Uint8Array(new Float32Array([1,0,0]).buffer),n=t.prepare(`SELECT vec_distance_cosine(?, ?) AS d`).get(e,e);if(!n||typeof n.d!=`number`)return A(`node-sqlite`,`SQLITE_VEC_PROBE_FAILED`,`Vector smoke test failed: unexpected result ${JSON.stringify(n)}`);O.debug(`node-sqlite: vector smoke test passed`)}catch(e){return A(`node-sqlite`,`SQLITE_VEC_PROBE_FAILED`,`Vector smoke test failed: ${e instanceof Error?e.message:String(e)}`)}}finally{try{t.enableLoadExtension(!1)}catch{}t.close()}return O.debug(`node:sqlite driver ready (sqlite-vec enabled)`),j({vectorCapable:!0,persistentFile:!0,concurrentReaders:!0})}async function N(){let e;try{e=k(`better-sqlite3`)}catch(e){return A(`better-sqlite3`,`MODULE_NOT_AVAILABLE`,`better-sqlite3 not available: ${e instanceof Error?e.message:String(e)}`)}let t;try{t=new e(`:memory:`)}catch(e){return A(`better-sqlite3`,`DATABASE_OPEN_FAILED`,`Failed to open in-memory database: ${e instanceof Error?e.message:String(e)}`)}try{try{k(`sqlite-vec`).load(t)}catch(e){return A(`better-sqlite3`,`SQLITE_VEC_LOAD_FAILED`,`sqlite-vec load failed: ${e instanceof Error?e.message:String(e)}`)}try{let e=t.prepare(`SELECT vec_version() AS v`).get();if(!e||typeof e.v!=`string`)return A(`better-sqlite3`,`SQLITE_VEC_PROBE_FAILED`,`vec_version() returned empty result`);O.debug(`better-sqlite3: sqlite-vec ${e.v}`)}catch(e){return A(`better-sqlite3`,`SQLITE_VEC_PROBE_FAILED`,`vec_version() failed: ${e instanceof Error?e.message:String(e)}`)}try{let e=new Uint8Array(new Float32Array([1,0,0]).buffer),n=t.prepare(`SELECT vec_distance_cosine(?, ?) AS d`).get([e,e]);if(!n||typeof n.d!=`number`)return A(`better-sqlite3`,`SQLITE_VEC_PROBE_FAILED`,`Vector smoke test failed: unexpected result ${JSON.stringify(n)}`);O.debug(`better-sqlite3: vector smoke test passed`)}catch(e){return A(`better-sqlite3`,`SQLITE_VEC_PROBE_FAILED`,`Vector smoke test failed: ${e instanceof Error?e.message:String(e)}`)}}finally{t.close()}return O.debug(`better-sqlite3 driver ready (sqlite-vec enabled)`),j({vectorCapable:!0,persistentFile:!0,concurrentReaders:!0})}async function xe(){let e;try{let t=await import(`sql.js`);e=t.default??t}catch(e){return A(`sqljs`,`MODULE_NOT_AVAILABLE`,`sql.js module not available: ${e instanceof Error?e.message:String(e)}`)}let t;try{let e=m(k.resolve(`sql.js/package.json`)),n=h(e,`dist`,`sql-wasm.wasm`);c(n)&&(t=t=>t.endsWith(`.wasm`)?n:h(e,`dist`,t))}catch{}let n;try{n=await e(t?{locateFile:t}:void 0)}catch(e){let t=e instanceof Error?e.message:String(e);return t.includes(`wasm`)||t.includes(`WASM`)||t.includes(`WebAssembly`)?A(`sqljs`,`WASM_INITIALIZATION_FAILED`,`sql.js WASM initialisation failed: ${t}`):A(`sqljs`,`WASM_ASSET_NOT_FOUND`,`sql.js initialisation failed (WASM asset may be missing): ${t}`)}try{new n.Database().close()}catch(e){return A(`sqljs`,`DATABASE_OPEN_FAILED`,`sql.js in-memory database failed: ${e instanceof Error?e.message:String(e)}`)}return O.debug(`sql.js driver ready (vector search disabled)`),j({vectorCapable:!1,persistentFile:!0,concurrentReaders:!1})}async function P(e){let t=e.driver??`auto`;if(t!==`auto`)return Se(t);let n=[];{let e=await M();if(e.available)return{kind:`node-sqlite`,capabilities:e.capabilities,failures:[]};e.failure&&n.push(e.failure)}{let e=await N();if(e.available)return{kind:`better-sqlite3`,capabilities:e.capabilities,failures:n};e.failure&&n.push(e.failure)}{let e=await xe();if(e.available)return{kind:`sqljs`,capabilities:e.capabilities,failures:n};e.failure&&n.push(e.failure)}throw new _e(n)}async function Se(e){let{kind:t,capabilities:n,failures:r}=await Ce(e);if(!n)throw new _e(r);return{kind:t,capabilities:n,failures:r}}async function Ce(e){let t=e;switch(e){case`node-sqlite`:{let e=await M();if(e.available)return{kind:t,capabilities:e.capabilities,failures:[]};let n=[];return e.failure&&n.push(e.failure),{kind:t,capabilities:null,failures:n}}case`better-sqlite3`:{let e=await N();if(e.available)return{kind:t,capabilities:e.capabilities,failures:[]};let n=[];return e.failure&&n.push(e.failure),{kind:t,capabilities:null,failures:n}}case`sqljs`:{let e=await xe();if(e.available)return{kind:t,capabilities:e.capabilities,failures:[]};let n=[];return e.failure&&n.push(e.failure),{kind:t,capabilities:null,failures:n}}default:throw Error(`Unreachable: unknown driver mode "${e}"`)}}const we=e(import.meta.url),Te=a(`sqljs-adapter`);function Ee(e){return we.resolve(`sql.js/dist/${e}`)}function De(e){return e.match(/^\s*(?:INSERT(?:\s+OR\s+\w+)?\s+INTO|UPDATE)\s+([A-Za-z_][A-Za-z0-9_]*)/i)?.[1]??null}var F=class{type=`sql.js`;kind=`sqljs`;vectorCapable=!1;capabilities={vectorCapable:!1,persistentFile:!0,concurrentReaders:!1};db=null;dbPath=``;dirty=!1;flushTimer=null;DEBOUNCE_MS=1e3;MAX_DB_SIZE_BYTES=500*1024*1024;inTransaction=!1;foreignKeysEnabled=!1;async open(e){this.dbPath=e;let t=(await import(`sql.js`)).default,n=await t({locateFile:e=>Ee(e)});if(c(e)){let t=u(e);this.db=new n.Database(t)}else this.db=new n.Database}exec(e){let t=e.trimStart().toUpperCase();this.getDb().run(e),t.startsWith(`BEGIN`)?this.inTransaction=!0:(t.startsWith(`COMMIT`)||t.startsWith(`ROLLBACK`))&&(this.inTransaction=!1),this.markDirty()}pragma(e){let t=e.trim().toLowerCase();t===`foreign_keys = on`||t===`foreign_keys=on`?this.foreignKeysEnabled=!0:(t===`foreign_keys = off`||t===`foreign_keys=off`)&&(this.foreignKeysEnabled=!1),this.getDb().exec(`PRAGMA ${e}`)}queryAll(e,t=[]){let n=this.getDb().prepare(e);try{t.length>0&&n.bind(t);let e=[];for(;n.step();)e.push(n.getAsObject());return e}finally{n.free()}}execWrite(e,t){let n=this.getDb();if(t===void 0){n.run(e);return}let r=n.prepare(e);try{r.bind(t),r.step()}finally{r.free()}}toBindParams(e){if(e!==void 0)return Array.isArray(e)&&e.length===0?void 0:e}run(e,t){let n=this.getDb(),r=e.trimStart().toUpperCase(),i=De(e),a=this.foreignKeysEnabled&&!this.inTransaction&&i!==null&&(r.startsWith(`INSERT`)||r.startsWith(`UPDATE`));a&&n.run(`SAVEPOINT fk_check`);try{if(this.execWrite(e,this.toBindParams(t)),a){if(n.exec(`PRAGMA foreign_key_check(${i})`).length>0)throw n.run(`ROLLBACK TO fk_check`),n.run(`RELEASE fk_check`),Error(`FOREIGN KEY constraint failed`);n.run(`RELEASE fk_check`)}}catch(e){if(a)try{n.run(`ROLLBACK TO fk_check`),n.run(`RELEASE fk_check`)}catch{}throw e}return this.markDirty(),this.getChangesResult(n)}getChangesResult(e){let t=e.exec(`SELECT changes() AS changes, last_insert_rowid() AS rowid`),n=t[0]?.values[0]?.[0]??0,r=t[0]?.values[0]?.[1];return{changes:Number(n),lastInsertRowid:r===void 0?void 0:Number(r)}}get(e,t){let n=this.getDb().prepare(e);try{return t!==void 0&&(Array.isArray(t)?t.length>0&&n.bind(t):n.bind(t)),n.step()?n.getAsObject():void 0}finally{n.free()}}all(e,t){let n=this.getDb().prepare(e);try{t!==void 0&&(Array.isArray(t)?t.length>0&&n.bind(t):n.bind(t));let e=[];for(;n.step();)e.push(n.getAsObject());return e}finally{n.free()}}transaction(e){this.exec(`BEGIN IMMEDIATE`);try{let t=e(this.createTransactionHandle());return this.exec(`COMMIT`),t}catch(e){throw this.exec(`ROLLBACK`),e}}createTransactionHandle(){return{exec:e=>this.exec(e),get:(e,t)=>this.get(e,t),all:(e,t)=>this.all(e,t),run:(e,t)=>this.run(e,t)}}markDirty(e=!1){this.dirty=!0,e?this.flushImmediate():this.scheduleFlush()}scheduleFlush(){this.flushTimer&&clearTimeout(this.flushTimer),this.flushTimer=setTimeout(()=>{this.flush()},this.DEBOUNCE_MS),this.flushTimer&&typeof this.flushTimer==`object`&&`unref`in this.flushTimer&&this.flushTimer.unref()}flushImmediate(){this.flushTimer&&=(clearTimeout(this.flushTimer),null),this.flush()}notifyCriticalWrite(){this.flushImmediate()}flush(){if(!this.dirty||!this.db)return;let e=this.db.export();e.byteLength>this.MAX_DB_SIZE_BYTES&&Te.warn(`Database size ${e.byteLength} bytes exceeds guardrail ${this.MAX_DB_SIZE_BYTES} bytes`);let t=`${this.dbPath}.tmp`,n=m(this.dbPath);n&&!c(n)&&l(n,{recursive:!0}),p(t,Buffer.from(e));try{f(this.dbPath)}catch{}d(t,this.dbPath),this.dirty=!1}async close(){if(this.flushTimer&&=(clearTimeout(this.flushTimer),null),this.db){let e=this.db,t;if(this.dirty)try{this.flush()}catch(e){t=e;try{f(`${this.dbPath}.tmp`)}catch{}}try{e.close()}finally{this.db=null}if(t)throw t}}getDb(){if(!this.db)throw Error(`SqlJsAdapter: database not opened`);return this.db}};const I=a(`sqlite-adapter`);e(import.meta.url);function Oe(){return!!process.env.VITEST||process.argv.some(e=>e.includes(`vitest`))}async function ke(){let e=R.resolveAikitRuntimeRoot(),t=await R.probeNativeModuleAbi(e);if(t===`ok`)return e;if(R.isNpxRuntimeRoot(e)){let e=R.resolvePersistentNativeRuntimeRoot(),t=await R.probeNativeModuleAbi(e);if(t===`ok`)return I.info(`Using cached better-sqlite3 native runtime`,{runtimeRoot:e,version:R.resolveNativeModuleVersion(e)}),e;let n=!1;if(t===`abi-mismatch`?(I.info(`Persistent better-sqlite3 cache ABI mismatch — rebuilding cached binding`),n=await R.tryRebuildNativeModule(e,!0)):t===`binding-missing`?(I.info(`Persistent better-sqlite3 cache missing binding — rebuilding cache`),n=await R.tryRebuildNativeModule(e,!1)):(I.info(`Persistent better-sqlite3 cache missing — installing cached runtime`,{runtimeRoot:e,packageSpec:R.readAikitPackageSpec()}),n=await R.tryInstallNativeModule(e)),n&&await R.probeNativeModuleAbi(e)===`ok`)return I.info(`Persistent better-sqlite3 cache ready`,{runtimeRoot:e,version:R.resolveNativeModuleVersion(e)}),e}if(t===`abi-mismatch`){if(I.info(`Detected NODE_MODULE_VERSION mismatch via pre-flight probe — rebuilding before load`),await R.tryRebuildNativeModule(e,!0)&&await R.probeNativeModuleAbi(e)===`ok`)return I.info(`Pre-flight rebuild succeeded — proceeding with native adapter`),e}else if(t===`binding-missing`){if(I.info(`No native binding found — attempting rebuild before load`),await R.tryRebuildNativeModule(e,!1)&&await R.probeNativeModuleAbi(e)===`ok`)return e}else if(t===`package-missing`&&(I.info(`better-sqlite3 package is not installed — attempting install before load`),await R.tryInstallNativeModule(e)&&await R.probeNativeModuleAbi(e)===`ok`))return e;return null}async function L(e){let t=await P({driver:process.env.AI_KIT_SQLITE_DRIVER??`auto`,databasePath:e});I.debug(`Storage backend: ${t.kind}`);for(let e of t.failures)I.warn(` ${e.driver}: ${e.code} — ${e.message}`);switch(t.kind){case`node-sqlite`:{let{NodeSqliteAdapter:t}=await Promise.resolve().then(()=>mt),n=new t;return await n.open(e),n}case`better-sqlite3`:{if(!R.isVitestRuntime()){let t=await R.preparePreferredNativeRuntime(),n=R.createNativeAdapter(t??void 0);try{return await n.open(e),n}catch(n){let r=n instanceof Error?n.message:String(n);if(!R.isVitestRuntime()&&/NODE_MODULE_VERSION|Could not locate the bindings file|no native build was found/.test(r)){let n=t??R.resolveAikitRuntimeRoot();if(await R.tryRebuildNativeModule(n,!1)){let t=R.createNativeAdapter(n);try{return await t.open(e),I.info(`better-sqlite3 recovered after native module rebuild`),t}catch{}}}throw n}}let t=R.createNativeAdapter();return await t.open(e),t}case`sqljs`:{let t=R.createFallbackAdapter();return await t.open(e),t}default:{let e=t.kind;throw Error(`Unknown driver kind: ${e}`)}}}async function Ae(e){let t=new F;return await t.open(e),t}const R={BetterSqlite3Adapter:E,SqlJsAdapter:F,isVitestRuntime:Oe,resolveAikitPackageRoot:x,resolveAikitRuntimeRoot:S,isNpxRuntimeRoot:le,readAikitPackageSpec:C,resolvePersistentNativeRuntimeRoot:de,ensureRuntimeRootPackageJson:w,resolveNativeModulePackageDir:D,resolveNativeBindingPath:pe,resolveNativeModuleVersion:fe,probeNativeModuleAbi:me,tryRebuildNativeModule:he,tryInstallNativeModule:ge,preparePreferredNativeRuntime:ke,createNativeAdapter:e=>new E(e),createFallbackAdapter:()=>new F},z=new Set([`sessions`,`stash`,`checkpoints`,`leases`,`signals`,`audit_log`,`replay_entries`,`session_metadata`]);function je(e){let t=ne(e)||`.db`,n=te(e,t);return h(m(e),`${n}-control${t}`)}function Me(e){return z.has(e)?`control`:`content`}function B(e,t={}){let n=t.splitEnabled??!1;return{splitEnabled:n,contentDbPath:t.contentDbPath??e,controlDbPath:t.controlDbPath??(n?je(e):e)}}function Ne(e,t=process.env){let n=t.AIKIT_SPLIT_STATE?.trim().toLowerCase();return B(e,{splitEnabled:n===`1`||n===`true`||n===`yes`||n===`on`})}const Pe=`_state_partition_meta`;function V(e){return`"${e.replaceAll(`"`,`""`)}"`}function Fe(e){let t=m(e);c(t)||l(t,{recursive:!0})}async function H(e){return Fe(e),L(e)}function U(e,t){return e.queryAll(`SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?`,[t]).length>0}function Ie(e,t){return e.queryAll(`SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?`,[t])[0]?.sql??void 0}function Le(e,t){return e.queryAll(`PRAGMA table_info(${V(t)})`).map(e=>e.name)}function Re(e,t){return e.queryAll(`SELECT COUNT(*) AS count FROM ${V(t)}`)[0]?.count??0}function ze(e,t,n){if(!U(e,n))return;if(!U(t,n)){let r=Ie(e,n);if(!r)return;t.exec(r)}let r=Le(t,n);if(r.length===0)return;let i=r.map(V).join(`, `),a=r.map(()=>`?`).join(`, `),o=e.queryAll(`SELECT ${i} FROM ${V(n)}`);if(o.length===0)return;let s=`INSERT OR REPLACE INTO ${V(n)} (${i}) VALUES (${a})`;for(let e of o)t.run(s,r.map(t=>e[t]??null))}function Be(e){e.exec(`
114
+ FROM ${t.name}`,[a,r]);let s=e.queryAll(`SELECT COUNT(*) AS cnt FROM memory_embeddings`)[0]?.cnt??0;i+=s-o}i>0&&oe.info(`[migration v4] backfilled ${i} embeddings into memory_embeddings`)}}],v=a(`sqlite-adapter`),y=e(import.meta.url),b=`better-sqlite3`;function ce(e){return e.replace(/\\/g,`/`)}function x(){return y.resolve(`@vpxa/aikit/package.json`).replace(/[\\/]package\.json$/,``)}function S(){return x().replace(/[\\/]node_modules[\\/]@vpxa[\\/]aikit$/,``)}function le(e){return ce(e).includes(`/_npx/`)}function C(){try{return JSON.parse(u(h(x(),`package.json`),`utf8`)).optionalDependencies?.[b]??`latest`}catch{return`latest`}}function ue(e){return e.replace(/[^a-zA-Z0-9._-]+/g,`_`)}function de(){let e=`${ue(C())}-${process.platform}-${process.arch}-abi${process.versions.modules}`;return h(re(),`.aikit`,`cache`,`native-modules`,b,e)}function w(e){l(e,{recursive:!0});let t=h(e,`package.json`);c(t)||p(t,`${JSON.stringify({name:`aikit-native-runtime-cache`,private:!0},null,2)}\n`,`utf8`)}function fe(e){let t=D(e);if(!t)return null;try{return JSON.parse(u(h(t,`package.json`),`utf8`)).version??null}catch{return null}}function T(e,t){try{let n={packageName:b,packageSpec:C(),packageVersion:fe(e),platform:process.platform,arch:process.arch,nodeAbi:process.versions.modules,installedAt:new Date().toISOString(),source:t};p(h(e,`.aikit-native-module.json`),`${JSON.stringify(n,null,2)}\n`,`utf8`)}catch(e){v.debug(`Failed to write better-sqlite3 runtime marker`,o(e))}}var E=class{runtimeRoot;type=`better-sqlite3`;kind=`better-sqlite3`;vectorCapable=!1;get capabilities(){return{vectorCapable:this.vectorCapable,persistentFile:!0,concurrentReaders:!0}}db=null;stmtCache=new Map;dbPath=``;DatabaseCtor=null;recovering=!1;constructor(e){this.runtimeRoot=e}async open(t){let n;try{let t=y;this.runtimeRoot!=null&&(w(this.runtimeRoot),t=e(h(this.runtimeRoot,`package.json`))),n=t(b)}catch(e){throw Error(`better-sqlite3 native binding unavailable: ${e instanceof Error?e.message:String(e)}`)}this.db=new n(t,{timeout:5e3}),this.dbPath=t,this.DatabaseCtor=n,this.db.pragma(`journal_mode = WAL`),this.db.pragma(`foreign_keys = ON`),this.db.pragma(`synchronous = NORMAL`),this.db.pragma(`busy_timeout = 5000`),this.runIntegrityCheck(t,n)||(this.db?.pragma(`journal_mode = WAL`),this.db?.pragma(`foreign_keys = ON`),this.db?.pragma(`synchronous = NORMAL`));try{y(`sqlite-vec`).load(this.db),this.vectorCapable=!0,v.debug(`sqlite-vec extension loaded`)}catch(e){this.vectorCapable=!1,v.warn(`sqlite-vec extension failed to load; vector search disabled`,o(e))}}exec(e){try{this.getDb().exec(e)}catch(t){if(this.isCorruptionError(t)){this.recover(),this.getDb().exec(e);return}throw t}}pragma(e){this.getDb().pragma(e)}queryAll(e,t=[]){try{let n=this.prepareCached(e);return t.length>0?n.all(...t):n.all()}catch(n){if(this.isCorruptionError(n))return this.recover(),this.queryAll(e,t);throw n}}run(e,t){try{let n=this.prepareCached(e);return t===void 0?n.run():Array.isArray(t)?t.length===0?n.run():n.run(...t):n.run(t)}catch(n){if(this.isCorruptionError(n))return this.recover(),this.run(e,t);throw n}}get(e,t){try{let n=this.prepareCached(e);return t===void 0?n.get():Array.isArray(t)?t.length>0?n.get(...t):n.get():n.get(t)}catch(n){if(this.isCorruptionError(n))return this.recover(),this.get(e,t);throw n}}all(e,t){try{let n=this.prepareCached(e);return t===void 0?n.all():Array.isArray(t)?t.length>0?n.all(...t):n.all():n.all(t)}catch(n){if(this.isCorruptionError(n))return this.recover(),this.all(e,t);throw n}}transaction(e){return this.getDb().transaction(()=>e(this.createTransactionHandle()))()}createTransactionHandle(){return{exec:e=>this.exec(e),get:(e,t)=>this.get(e,t),all:(e,t)=>this.all(e,t),run:(e,t)=>this.run(e,t)}}flush(){}async close(){this.db&&=(this.stmtCache.clear(),this.db.close(),null)}runIntegrityCheck(e,t){try{let t=this.db?.pragma(`integrity_check`);if(t.length===1&&t[0]?.integrity_check===`ok`)return!0;let n=t.map(e=>e.integrity_check).slice(0,5).join(`; `);v.warn(`Database integrity check failed — recreating`,{dbPath:e,issues:n})}catch(t){v.warn(`Integrity check query failed — recreating database`,{dbPath:e,error:o(t)})}try{this.db?.close()}catch{}this.db=null,this.stmtCache.clear();try{f(e)}catch{}try{f(`${e}-wal`)}catch{}try{f(`${e}-shm`)}catch{}return this.db=new t(e,{timeout:5e3}),v.info(`Database recreated successfully — full reindex required`,{dbPath:e}),!1}isCorruptionError(e){if(this.recovering)return!1;let t=e instanceof Error?e.message:String(e);return/database disk image is malformed|file is not a database|database or disk is full/.test(t)}recover(){if(this.recovering)throw Error(`BetterSqlite3Adapter: recovery already in progress`);this.recovering=!0;try{v.warn(`Runtime corruption detected — recovering database`,{dbPath:this.dbPath});try{this.db?.close()}catch{}this.db=null,this.stmtCache.clear();try{f(this.dbPath)}catch{}try{f(`${this.dbPath}-wal`)}catch{}try{f(`${this.dbPath}-shm`)}catch{}if(!this.DatabaseCtor)throw Error(`DatabaseCtor is not initialized`);this.db=this.DatabaseCtor(this.dbPath),this.db.pragma(`journal_mode = WAL`),this.db.pragma(`foreign_keys = ON`),this.db.pragma(`synchronous = NORMAL`);try{y(`sqlite-vec`).load(this.db),this.vectorCapable=!0}catch{this.vectorCapable=!1}v.info(`Database recovered — full reindex required`,{dbPath:this.dbPath})}finally{this.recovering=!1}}getDb(){if(!this.db)throw Error(`BetterSqlite3Adapter: database not opened`);return this.db}prepareCached(e){let t=this.stmtCache.get(e);if(t)return t;let n=this.getDb().prepare(e);return this.stmtCache.set(e,n),n}};function D(e){if(e){let t=h(e,`node_modules`,b);return c(h(t,`package.json`))?t:null}try{return y.resolve(`${b}/package.json`).replace(/[\\/]package\.json$/,``)}catch{return null}}function pe(e){let t=D(e);if(!t)return null;let n=h(t,`build`,`Release`,`better_sqlite3.node`);return c(n)?n:null}async function me(e){let t=D(e);if(!t)return`package-missing`;if(!c(h(t,`build`,`Release`,`better_sqlite3.node`)))return`binding-missing`;try{let{execFileSync:t}=await import(`node:child_process`),n=e??S();return e&&w(e),t(process.execPath,[`-e`,`require('${b}')`],{cwd:n,stdio:`pipe`,timeout:15e3,windowsHide:!0}),`ok`}catch(e){let t=e instanceof Error&&`stderr`in e?String(e.stderr):``;return/NODE_MODULE_VERSION/.test(t)?`abi-mismatch`:/Could not locate the bindings file|no native build was found/.test(t)?`binding-missing`:`error`}}async function he(e,t=!1){let n=D(e);if(!n)return v.info(`better-sqlite3 package is not installed — skipping native rebuild`),!1;try{let{execFileSync:r}=await import(`node:child_process`),i=e??n.replace(/[\\/]node_modules[\\/]better-sqlite3$/,``),a=process.platform===`win32`?`npm.cmd`:`npm`;if(e&&w(e),t){let e=h(n,`build`,`Release`,`better_sqlite3.node`);if(c(e))try{f(e),v.info(`Deleted stale native binding before rebuild`,{path:e})}catch(t){v.warn(`Cannot delete stale native binding — file may be locked by another process`,{path:e,error:t instanceof Error?t.message:String(t)})}}return v.info(`Attempting native module rebuild for better-sqlite3`,{cwd:i}),r(a,[`rebuild`,b],{cwd:i,stdio:`pipe`,timeout:6e4,windowsHide:!0}),v.info(`Native module rebuild completed successfully`),T(i,`rebuild`),!0}catch(e){return v.warn(`Native module rebuild failed — continuing with sql.js fallback`,o(e)),!1}}async function ge(e){try{let{execFileSync:t}=await import(`node:child_process`),n=e??S(),r=process.platform===`win32`?`npm.cmd`:`npm`,i=C();return w(n),v.info(`Attempting to install better-sqlite3 for native adapter recovery`,{cwd:n,packageSpec:i}),t(r,[`install`,`--no-save`,`--package-lock=false`,`--no-audit`,`--no-fund`,`--omit=dev`,`${b}@${i}`],{cwd:n,stdio:`pipe`,timeout:12e4,windowsHide:!0}),v.info(`better-sqlite3 install completed successfully`),T(n,`install`),!0}catch(e){return v.warn(`better-sqlite3 install failed — continuing with sql.js fallback`,o(e)),!1}}const O=a(`driver-selector`),k=e(import.meta.url);var _e=class extends Error{code=`STORAGE_INITIALIZATION_FAILED`;failures;constructor(e){let t=e.map(e=>`[${e.code}] ${e.driver}: ${e.message}`).join(`; `);super(`All SQLite drivers failed to initialise (${e.length}): ${t}`),this.name=`StorageInitializationError`,this.failures=e}};function ve(e){let[t,n]=(e??process.versions.node).split(`.`),r=Number.parseInt(t??`0`,10);return r>22||r===22&&Number.parseInt(n??`0`,10)>=13}function ye(e){if(typeof e!=`function`)return!1;let t=e.prototype;return typeof t?.enableLoadExtension==`function`&&typeof t.loadExtension==`function`}function A(e,t,n){return{available:!1,failure:{driver:e,code:t,message:n}}}function j(e){return{available:!0,capabilities:e}}function be(){try{try{let e=k(`sqlite-vec`);if(typeof e.getLoadablePath==`function`){let t=e.getLoadablePath();if(t&&c(t))return t}if(e.loadablePath&&c(e.loadablePath))return e.loadablePath}catch{}let e=m(k.resolve(`sqlite-vec/package.json`)),t={"win32-x64":`sqlite-vec-win32-x64.node`,"win32-arm64":`sqlite-vec-win32-arm64.node`,"darwin-x64":`sqlite-vec-darwin-x64.node`,"darwin-arm64":`sqlite-vec-darwin-arm64.node`,"linux-x64":`sqlite-vec-linux-x64.node`,"linux-arm64":`sqlite-vec-linux-arm64.node`}[`${process.platform}-${process.arch}`];if(t){let n=h(e,t);if(c(n))return n}let n=h(e,`sqlite-vec.node`);if(c(n))return n;let r=h(m(k.resolve(`sqlite-vec`)),`sqlite-vec.node`);return c(r)?r:null}catch{return null}}async function M(){if(!ve())return A(`node-sqlite`,`NODE_VERSION_UNSUPPORTED`,`Node.js ${process.versions.node} < 22.13 — node:sqlite extension loading unavailable`);let e;try{let t=await import(`node:sqlite`);if(!ye(t.DatabaseSync))return A(`node-sqlite`,`EXTENSION_LOADING_DISABLED`,`node:sqlite is available but DatabaseSync extension loading APIs are unavailable`);e=t.DatabaseSync}catch(e){return A(`node-sqlite`,`MODULE_NOT_AVAILABLE`,`node:sqlite not available: ${e instanceof Error?e.message:String(e)}`)}let t=new e(`:memory:`,{allowExtension:!0});try{try{t.enableLoadExtension(!0)}catch(e){return A(`node-sqlite`,`EXTENSION_LOADING_DISABLED`,`enableLoadExtension failed: ${e instanceof Error?e.message:String(e)}`)}let e=be();if(!e)return A(`node-sqlite`,`NATIVE_BINARY_UNAVAILABLE`,`Could not resolve sqlite-vec native binary path`);try{t.loadExtension(e)}catch(e){return A(`node-sqlite`,`SQLITE_VEC_LOAD_FAILED`,`sqlite-vec loadExtension failed: ${e instanceof Error?e.message:String(e)}`)}try{let e=t.prepare(`SELECT vec_version() AS v`).get();if(!e||typeof e.v!=`string`)return A(`node-sqlite`,`SQLITE_VEC_PROBE_FAILED`,`vec_version() returned empty result`);O.debug(`node-sqlite: sqlite-vec ${e.v}`)}catch(e){return A(`node-sqlite`,`SQLITE_VEC_PROBE_FAILED`,`vec_version() failed: ${e instanceof Error?e.message:String(e)}`)}try{let e=new Uint8Array(new Float32Array([1,0,0]).buffer),n=t.prepare(`SELECT vec_distance_cosine(?, ?) AS d`).get(e,e);if(!n||typeof n.d!=`number`)return A(`node-sqlite`,`SQLITE_VEC_PROBE_FAILED`,`Vector smoke test failed: unexpected result ${JSON.stringify(n)}`);O.debug(`node-sqlite: vector smoke test passed`)}catch(e){return A(`node-sqlite`,`SQLITE_VEC_PROBE_FAILED`,`Vector smoke test failed: ${e instanceof Error?e.message:String(e)}`)}}finally{try{t.enableLoadExtension(!1)}catch{}t.close()}return O.debug(`node:sqlite driver ready (sqlite-vec enabled)`),j({vectorCapable:!0,persistentFile:!0,concurrentReaders:!0})}async function N(){let e;try{e=k(`better-sqlite3`)}catch(e){return A(`better-sqlite3`,`MODULE_NOT_AVAILABLE`,`better-sqlite3 not available: ${e instanceof Error?e.message:String(e)}`)}let t;try{t=new e(`:memory:`)}catch(e){return A(`better-sqlite3`,`DATABASE_OPEN_FAILED`,`Failed to open in-memory database: ${e instanceof Error?e.message:String(e)}`)}try{try{k(`sqlite-vec`).load(t)}catch(e){return A(`better-sqlite3`,`SQLITE_VEC_LOAD_FAILED`,`sqlite-vec load failed: ${e instanceof Error?e.message:String(e)}`)}try{let e=t.prepare(`SELECT vec_version() AS v`).get();if(!e||typeof e.v!=`string`)return A(`better-sqlite3`,`SQLITE_VEC_PROBE_FAILED`,`vec_version() returned empty result`);O.debug(`better-sqlite3: sqlite-vec ${e.v}`)}catch(e){return A(`better-sqlite3`,`SQLITE_VEC_PROBE_FAILED`,`vec_version() failed: ${e instanceof Error?e.message:String(e)}`)}try{let e=new Uint8Array(new Float32Array([1,0,0]).buffer),n=t.prepare(`SELECT vec_distance_cosine(?, ?) AS d`).get([e,e]);if(!n||typeof n.d!=`number`)return A(`better-sqlite3`,`SQLITE_VEC_PROBE_FAILED`,`Vector smoke test failed: unexpected result ${JSON.stringify(n)}`);O.debug(`better-sqlite3: vector smoke test passed`)}catch(e){return A(`better-sqlite3`,`SQLITE_VEC_PROBE_FAILED`,`Vector smoke test failed: ${e instanceof Error?e.message:String(e)}`)}}finally{t.close()}return O.debug(`better-sqlite3 driver ready (sqlite-vec enabled)`),j({vectorCapable:!0,persistentFile:!0,concurrentReaders:!0})}async function xe(){let e;try{let t=await import(`sql.js`);e=t.default??t}catch(e){return A(`sqljs`,`MODULE_NOT_AVAILABLE`,`sql.js module not available: ${e instanceof Error?e.message:String(e)}`)}let t;try{let e=m(k.resolve(`sql.js/package.json`)),n=h(e,`dist`,`sql-wasm.wasm`);c(n)&&(t=t=>t.endsWith(`.wasm`)?n:h(e,`dist`,t))}catch{}let n;try{n=await e(t?{locateFile:t}:void 0)}catch(e){let t=e instanceof Error?e.message:String(e);return t.includes(`wasm`)||t.includes(`WASM`)||t.includes(`WebAssembly`)?A(`sqljs`,`WASM_INITIALIZATION_FAILED`,`sql.js WASM initialisation failed: ${t}`):A(`sqljs`,`WASM_ASSET_NOT_FOUND`,`sql.js initialisation failed (WASM asset may be missing): ${t}`)}try{new n.Database().close()}catch(e){return A(`sqljs`,`DATABASE_OPEN_FAILED`,`sql.js in-memory database failed: ${e instanceof Error?e.message:String(e)}`)}return O.debug(`sql.js driver ready (vector search disabled)`),j({vectorCapable:!1,persistentFile:!0,concurrentReaders:!1})}async function P(e){let t=e.driver??`auto`;if(t!==`auto`)return Se(t);let n=[];{let e=await M();if(e.available)return{kind:`node-sqlite`,capabilities:e.capabilities,failures:[]};e.failure&&n.push(e.failure)}{let e=await N();if(e.available)return{kind:`better-sqlite3`,capabilities:e.capabilities,failures:n};e.failure&&n.push(e.failure)}{let e=await xe();if(e.available)return{kind:`sqljs`,capabilities:e.capabilities,failures:n};e.failure&&n.push(e.failure)}throw new _e(n)}async function Se(e){let{kind:t,capabilities:n,failures:r}=await Ce(e);if(!n)throw new _e(r);return{kind:t,capabilities:n,failures:r}}async function Ce(e){let t=e;switch(e){case`node-sqlite`:{let e=await M();if(e.available)return{kind:t,capabilities:e.capabilities,failures:[]};let n=[];return e.failure&&n.push(e.failure),{kind:t,capabilities:null,failures:n}}case`better-sqlite3`:{let e=await N();if(e.available)return{kind:t,capabilities:e.capabilities,failures:[]};let n=[];return e.failure&&n.push(e.failure),{kind:t,capabilities:null,failures:n}}case`sqljs`:{let e=await xe();if(e.available)return{kind:t,capabilities:e.capabilities,failures:[]};let n=[];return e.failure&&n.push(e.failure),{kind:t,capabilities:null,failures:n}}default:throw Error(`Unreachable: unknown driver mode "${e}"`)}}const we=e(import.meta.url),Te=a(`sqljs-adapter`);function Ee(e){return we.resolve(`sql.js/dist/${e}`)}function De(e){return e.match(/^\s*(?:INSERT(?:\s+OR\s+\w+)?\s+INTO|UPDATE)\s+([A-Za-z_][A-Za-z0-9_]*)/i)?.[1]??null}var F=class{type=`sql.js`;kind=`sqljs`;vectorCapable=!1;capabilities={vectorCapable:!1,persistentFile:!0,concurrentReaders:!1};db=null;dbPath=``;dirty=!1;flushTimer=null;DEBOUNCE_MS=1e3;MAX_DB_SIZE_BYTES=500*1024*1024;inTransaction=!1;foreignKeysEnabled=!1;async open(e){this.dbPath=e;let t=(await import(`sql.js`)).default,n=await t({locateFile:e=>Ee(e)});if(c(e)){let t=u(e);this.db=new n.Database(t)}else this.db=new n.Database}exec(e){let t=e.trimStart().toUpperCase();this.getDb().run(e),t.startsWith(`BEGIN`)?this.inTransaction=!0:(t.startsWith(`COMMIT`)||t.startsWith(`ROLLBACK`))&&(this.inTransaction=!1),this.markDirty()}pragma(e){let t=e.trim().toLowerCase();t===`foreign_keys = on`||t===`foreign_keys=on`?this.foreignKeysEnabled=!0:(t===`foreign_keys = off`||t===`foreign_keys=off`)&&(this.foreignKeysEnabled=!1),this.getDb().exec(`PRAGMA ${e}`)}queryAll(e,t=[]){let n=this.getDb().prepare(e);try{t.length>0&&n.bind(t);let e=[];for(;n.step();)e.push(n.getAsObject());return e}finally{n.free()}}execWrite(e,t){let n=this.getDb();if(t===void 0){n.run(e);return}let r=n.prepare(e);try{r.bind(t),r.step()}finally{r.free()}}toBindParams(e){if(e!==void 0)return Array.isArray(e)&&e.length===0?void 0:e}run(e,t){let n=this.getDb(),r=e.trimStart().toUpperCase(),i=De(e),a=this.foreignKeysEnabled&&!this.inTransaction&&i!==null&&(r.startsWith(`INSERT`)||r.startsWith(`UPDATE`));a&&n.run(`SAVEPOINT fk_check`);try{if(this.execWrite(e,this.toBindParams(t)),a){if(n.exec(`PRAGMA foreign_key_check(${i})`).length>0)throw n.run(`ROLLBACK TO fk_check`),n.run(`RELEASE fk_check`),Error(`FOREIGN KEY constraint failed`);n.run(`RELEASE fk_check`)}}catch(e){if(a)try{n.run(`ROLLBACK TO fk_check`),n.run(`RELEASE fk_check`)}catch{}throw e}return this.markDirty(),this.getChangesResult(n)}getChangesResult(e){let t=e.exec(`SELECT changes() AS changes, last_insert_rowid() AS rowid`),n=t[0]?.values[0]?.[0]??0,r=t[0]?.values[0]?.[1];return{changes:Number(n),lastInsertRowid:r===void 0?void 0:Number(r)}}get(e,t){let n=this.getDb().prepare(e);try{return t!==void 0&&(Array.isArray(t)?t.length>0&&n.bind(t):n.bind(t)),n.step()?n.getAsObject():void 0}finally{n.free()}}all(e,t){let n=this.getDb().prepare(e);try{t!==void 0&&(Array.isArray(t)?t.length>0&&n.bind(t):n.bind(t));let e=[];for(;n.step();)e.push(n.getAsObject());return e}finally{n.free()}}transaction(e){this.exec(`BEGIN IMMEDIATE`);try{let t=e(this.createTransactionHandle());return this.exec(`COMMIT`),t}catch(e){throw this.exec(`ROLLBACK`),e}}createTransactionHandle(){return{exec:e=>this.exec(e),get:(e,t)=>this.get(e,t),all:(e,t)=>this.all(e,t),run:(e,t)=>this.run(e,t)}}markDirty(e=!1){this.dirty=!0,e?this.flushImmediate():this.scheduleFlush()}scheduleFlush(){this.flushTimer&&clearTimeout(this.flushTimer),this.flushTimer=setTimeout(()=>{this.flush()},this.DEBOUNCE_MS),this.flushTimer&&typeof this.flushTimer==`object`&&`unref`in this.flushTimer&&this.flushTimer.unref()}flushImmediate(){this.flushTimer&&=(clearTimeout(this.flushTimer),null),this.flush()}notifyCriticalWrite(){this.flushImmediate()}flush(){if(!this.dirty||!this.db)return;let e=this.db.export();e.byteLength>this.MAX_DB_SIZE_BYTES&&Te.warn(`Database size ${e.byteLength} bytes exceeds guardrail ${this.MAX_DB_SIZE_BYTES} bytes`);let t=`${this.dbPath}.tmp`,n=m(this.dbPath);n&&!c(n)&&l(n,{recursive:!0}),p(t,Buffer.from(e));try{f(this.dbPath)}catch{}d(t,this.dbPath),this.dirty=!1}async close(){if(this.flushTimer&&=(clearTimeout(this.flushTimer),null),this.db){let e=this.db,t;if(this.dirty)try{this.flush()}catch(e){t=e;try{f(`${this.dbPath}.tmp`)}catch{}}try{e.close()}finally{this.db=null}if(t)throw t}}getDb(){if(!this.db)throw Error(`SqlJsAdapter: database not opened`);return this.db}};const I=a(`sqlite-adapter`);e(import.meta.url);function Oe(){return!!process.env.VITEST||process.argv.some(e=>e.includes(`vitest`))}async function ke(){let e=R.resolveAikitRuntimeRoot(),t=await R.probeNativeModuleAbi(e);if(t===`ok`)return e;if(R.isNpxRuntimeRoot(e)){let e=R.resolvePersistentNativeRuntimeRoot(),t=await R.probeNativeModuleAbi(e);if(t===`ok`)return I.info(`Using cached better-sqlite3 native runtime`,{runtimeRoot:e,version:R.resolveNativeModuleVersion(e)}),e;let n=!1;if(t===`abi-mismatch`?(I.info(`Persistent better-sqlite3 cache ABI mismatch — rebuilding cached binding`),n=await R.tryRebuildNativeModule(e,!0)):t===`binding-missing`?(I.info(`Persistent better-sqlite3 cache missing binding — rebuilding cache`),n=await R.tryRebuildNativeModule(e,!1)):(I.info(`Persistent better-sqlite3 cache missing — installing cached runtime`,{runtimeRoot:e,packageSpec:R.readAikitPackageSpec()}),n=await R.tryInstallNativeModule(e)),n&&await R.probeNativeModuleAbi(e)===`ok`)return I.info(`Persistent better-sqlite3 cache ready`,{runtimeRoot:e,version:R.resolveNativeModuleVersion(e)}),e}if(t===`abi-mismatch`){if(I.info(`Detected NODE_MODULE_VERSION mismatch via pre-flight probe — rebuilding before load`),await R.tryRebuildNativeModule(e,!0)&&await R.probeNativeModuleAbi(e)===`ok`)return I.info(`Pre-flight rebuild succeeded — proceeding with native adapter`),e}else if(t===`binding-missing`){if(I.info(`No native binding found — attempting rebuild before load`),await R.tryRebuildNativeModule(e,!1)&&await R.probeNativeModuleAbi(e)===`ok`)return e}else if(t===`package-missing`&&(I.info(`better-sqlite3 package is not installed — attempting install before load`),await R.tryInstallNativeModule(e)&&await R.probeNativeModuleAbi(e)===`ok`))return e;return null}async function L(e){let t=await P({driver:process.env.AI_KIT_SQLITE_DRIVER??`auto`,databasePath:e});I.debug(`Storage backend: ${t.kind}`);for(let e of t.failures)I.warn(` ${e.driver}: ${e.code} — ${e.message}`);switch(t.kind){case`node-sqlite`:{let{NodeSqliteAdapter:t}=await Promise.resolve().then(()=>mt),n=new t;return await n.open(e),n}case`better-sqlite3`:{if(!R.isVitestRuntime()){let t=await R.preparePreferredNativeRuntime(),n=R.createNativeAdapter(t??void 0);try{return await n.open(e),n}catch(n){let r=n instanceof Error?n.message:String(n);if(!R.isVitestRuntime()&&/NODE_MODULE_VERSION|Could not locate the bindings file|no native build was found/.test(r)){let n=t??R.resolveAikitRuntimeRoot();if(await R.tryRebuildNativeModule(n,!1)){let t=R.createNativeAdapter(n);try{return await t.open(e),I.info(`better-sqlite3 recovered after native module rebuild`),t}catch{}}}throw n}}let t=R.createNativeAdapter();return await t.open(e),t}case`sqljs`:{let t=R.createFallbackAdapter();return await t.open(e),t}default:{let e=t.kind;throw Error(`Unknown driver kind: ${e}`)}}}async function Ae(e){let t=new F;return await t.open(e),t}const R={BetterSqlite3Adapter:E,SqlJsAdapter:F,isVitestRuntime:Oe,resolveAikitPackageRoot:x,resolveAikitRuntimeRoot:S,isNpxRuntimeRoot:le,readAikitPackageSpec:C,resolvePersistentNativeRuntimeRoot:de,ensureRuntimeRootPackageJson:w,resolveNativeModulePackageDir:D,resolveNativeBindingPath:pe,resolveNativeModuleVersion:fe,probeNativeModuleAbi:me,tryRebuildNativeModule:he,tryInstallNativeModule:ge,preparePreferredNativeRuntime:ke,createNativeAdapter:e=>new E(e),createFallbackAdapter:()=>new F},z=new Set([`sessions`,`stash`,`checkpoints`,`leases`,`signals`,`audit_log`,`replay_entries`,`session_metadata`]);function je(e){let t=ne(e)||`.db`,n=te(e,t);return h(m(e),`${n}-control${t}`)}function Me(e){return z.has(e)?`control`:`content`}function B(e,t={}){let n=t.splitEnabled??!1;return{splitEnabled:n,contentDbPath:t.contentDbPath??e,controlDbPath:t.controlDbPath??(n?je(e):e)}}function Ne(e,t=process.env){let n=t.AIKIT_SPLIT_STATE?.trim().toLowerCase();return B(e,{splitEnabled:n===`1`||n===`true`||n===`yes`||n===`on`})}const Pe=`_state_partition_meta`;function V(e){return`"${e.replaceAll(`"`,`""`)}"`}function Fe(e){let t=m(e);c(t)||l(t,{recursive:!0})}async function H(e){return Fe(e),L(e)}function U(e,t){return e.queryAll(`SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?`,[t]).length>0}function Ie(e,t){return e.queryAll(`SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?`,[t])[0]?.sql??void 0}function Le(e,t){return e.queryAll(`PRAGMA table_info(${V(t)})`).map(e=>e.name)}function Re(e,t){return e.queryAll(`SELECT COUNT(*) AS count FROM ${V(t)}`)[0]?.count??0}function ze(e,t,n){if(!U(e,n))return;if(!U(t,n)){let r=Ie(e,n);if(!r)return;t.exec(r)}let r=Le(t,n);if(r.length===0)return;let i=r.map(V).join(`, `),a=r.map(()=>`?`).join(`, `),o=e.queryAll(`SELECT ${i} FROM ${V(n)}`);if(o.length===0)return;let s=`INSERT OR REPLACE INTO ${V(n)} (${i}) VALUES (${a})`;for(let e of o)t.run(s,r.map(t=>e[t]??null))}function Be(e){e.exec(`
115
115
  CREATE TABLE IF NOT EXISTS ${Pe} (
116
116
  key TEXT PRIMARY KEY,
117
117
  value TEXT NOT NULL,
@@ -121,7 +121,7 @@ import{createRequire as e}from"node:module";import{AIKIT_PATHS as t,EMBEDDING_DE
121
121
  VALUES (?, ?, datetime('now'))
122
122
  ON CONFLICT(key) DO UPDATE SET
123
123
  value = excluded.value,
124
- updated_at = datetime('now')`,[`split-state`,JSON.stringify({splitEnabled:t.splitEnabled,contentDbPath:t.contentDbPath,controlDbPath:t.controlDbPath,migratedTables:n})])}async function He(e){let t=e.contentDbPath??e.controlDbPath;if(!t)throw Error(`migrateToSplitState requires at least one database path in config`);let n=B(t,e);if(!n.splitEnabled||n.controlDbPath===n.contentDbPath)return;let r=await H(n.contentDbPath),i=await H(n.controlDbPath);try{g(i,_);let e=[];for(let t of z){if(!U(r,t))continue;ze(r,i,t);let n=Re(r,t),a=Re(i,t);if(a<n)throw Error(`Split-state migration verification failed for ${t}: source=${n} target=${a}`);e.push(t)}Ve(i,n,e)}finally{r.close(),i.close()}}var Ue=class{adapter=null;reopenPromise=null;dbPath;externalAdapter;constructor(e={}){if(e.adapter)this.adapter=e.adapter,this.externalAdapter=!0,this.dbPath=``;else{let n=e.path??t.data;this.dbPath=h(n,`graph.db`),this.externalAdapter=!1}}async initialize(){if(this.externalAdapter){let e=this.getAdapter();this.createTables(e),this.migrateSchema(e),e.flush();return}let e=m(this.dbPath);c(e)||l(e,{recursive:!0}),this.adapter=await L(this.dbPath),this.configureAdapter(this.adapter),this.createTables(this.adapter),this.migrateSchema(this.adapter),this.adapter.flush()}configureAdapter(e){e.pragma(`journal_mode = WAL`),e.pragma(`foreign_keys = ON`)}createTables(e){e.exec(`
124
+ updated_at = datetime('now')`,[`split-state`,JSON.stringify({splitEnabled:t.splitEnabled,contentDbPath:t.contentDbPath,controlDbPath:t.controlDbPath,migratedTables:n})])}async function He(e){let t=e.contentDbPath??e.controlDbPath;if(!t)throw Error(`migrateToSplitState requires at least one database path in config`);let n=B(t,e);if(!n.splitEnabled||n.controlDbPath===n.contentDbPath)return;let r=await H(n.contentDbPath),i=await H(n.controlDbPath);try{g(i,_);let e=[];for(let t of z){if(!U(r,t))continue;ze(r,i,t);let n=Re(r,t),a=Re(i,t);if(a<n)throw Error(`Split-state migration verification failed for ${t}: source=${n} target=${a}`);e.push(t)}Ve(i,n,e)}finally{r.close(),i.close()}}var Ue=class{adapter=null;reopenPromise=null;dbPath;externalAdapter;constructor(e={}){if(e.adapter)this.adapter=e.adapter,this.externalAdapter=!0,this.dbPath=``;else{let n=e.path??t.data;this.dbPath=h(n,`graph.db`),this.externalAdapter=!1}}async initialize(){if(this.externalAdapter){let e=this.getAdapter();this.createTables(e),this.migrateSchema(e),e.flush();return}let e=m(this.dbPath);c(e)||l(e,{recursive:!0}),this.adapter=await L(this.dbPath),this.configureAdapter(this.adapter),this.createTables(this.adapter),this.migrateSchema(this.adapter),this.adapter.flush()}configureAdapter(e){e.pragma(`journal_mode = WAL`),e.pragma(`foreign_keys = ON`),e.pragma(`busy_timeout = 5000`)}createTables(e){e.exec(`
125
125
  CREATE TABLE IF NOT EXISTS nodes (
126
126
  id TEXT PRIMARY KEY,
127
127
  type TEXT NOT NULL,
@@ -1,2 +0,0 @@
1
- #!/usr/bin/env node
2
- import{n as e,t}from"./server-B3Wy5oMX.js";export{t as buildPreludeInjection,e as generatePrelude};
@@ -1 +0,0 @@
1
- import{n as e,t}from"./server-DBLXa2HM.js";export{t as buildPreludeInjection,e as generatePrelude};
@@ -1 +0,0 @@
1
- import{r as e}from"./server-DBLXa2HM.js";export{e as createSamplingClient};
@@ -1,2 +0,0 @@
1
- #!/usr/bin/env node
2
- import{r as e}from"./server-B3Wy5oMX.js";export{e as createSamplingClient};
@@ -1 +0,0 @@
1
- import{n as e}from"./workspace-bootstrap-B57Oz40_.js";import{n as t,t as n}from"./startup-maintenance-DX1yTfBa.js";import{t as r}from"./repair-json-B6Q_HRoP.js";import{createLogger as i,serializeError as a,setDetailedErrorLoggingEnabled as o}from"../../core/dist/index.js";const s=i(`server`);var c=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 s.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}};const l=12e3;async function u(r){let[{loadConfig:i,reconfigureForWorkspace:u,resolveIndexMode:d},{createLazyServer:f},{checkForUpdates:p,autoUpgradeScaffold:m},{RootsListChangedNotificationSchema:h}]=await Promise.all([import(`./config-D3rRPB9X.js`),import(`./server-DBLXa2HM.js`),import(`./version-check-DNe43rCZ.js`),import(`@modelcontextprotocol/sdk/types.js`)]),g=i();o(g.logging?.errorDetails===!0),g.configError&&s.warn(`Config load failure`,{error:g.configError}),s.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;b();let C=Date.now()+l,w=!1;try{await Promise.race([x.then(()=>{w=!0}),new Promise(e=>setTimeout(e,l))])}catch{}if(w)s.debug(`Init completed before transport connect — all tools registered`);else{let e=Date.now()-(C-l);s.debug(`Init ${e>=l?`timed out`:`failed`} after ${e}ms — connecting with placeholder tools; tool_list_changed will be sent when init completes`)}let{StdioServerTransport:T}=await import(`@modelcontextprotocol/sdk/server/stdio.js`),E=new T;if(typeof E._readBuffer?.readMessage!=`function`)throw Error(`Cannot install JSON repair: StdioServerTransport._readBuffer has unexpected shape`);E._readBuffer=new c,s.debug(`JSON repair installed on stdio transport`),await y.connect(E),s.debug(`MCP server started`,{transport:`stdio`,initSucceeded:w}),await e({config:g,indexMode:_,log:s,rootsChangedNotificationSchema:h,reconfigureForWorkspace:u,runInitialIndex:S,server:y,startInit:b,version:r});let D=null,O=null,k=!1,A=async e=>{k||(k=!0,s.info(`Shutdown signal received`,{signal:e}),D&&=(clearTimeout(D),null),O?.stop(),await import(`../../tools/dist/index.js`).then(({processStopAll:e})=>e()).catch(()=>{}),await E.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))},j=()=>{D&&clearTimeout(D),D=setTimeout(async()=>{s.info(`Auto-shutdown: no activity for 30 minutes — releasing resources`);try{let e=v.aikit;e&&(e.embedder.shutdown?.().catch(()=>{}),e.store.releaseMemory?.(),e.graphStore.releaseMemory?.())}catch(e){s.warn(`Resource release failed during shutdown`,a(e))}},18e5),D.unref&&D.unref()};j(),process.stdin.on(`data`,()=>j()),process.stdin.on(`end`,()=>void A(`stdin-end`)),process.stdin.on(`close`,()=>void A(`stdin-close`)),process.stdin.on(`error`,()=>void A(`stdin-error`)),process.on(`SIGINT`,()=>void A(`SIGINT`)),process.on(`SIGTERM`,()=>void A(`SIGTERM`)),x.catch(e=>{s.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);O=t;let n=v.aikit.store;t.start(),n.onBeforeClose&&n.onBeforeClose(()=>t.stop()),v.setSmartScheduler(t),s.debug(`Smart index scheduler started (stdio mode)`)}catch(e){s.error(`Failed to start smart index scheduler`,t(r,e))}}).catch(e=>s.error(`AI Kit init failed for smart scheduler`,t(r,e))):s.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,2 +0,0 @@
1
- #!/usr/bin/env node
2
- import{r as e}from"./bin.js";import{n as t,t as n}from"./startup-maintenance-CBJWiJ7p.js";import{t as r}from"./repair-json-D4mft_HA.js";import{createLogger as i,serializeError as a,setDetailedErrorLoggingEnabled as o}from"../../core/dist/index.js";const s=i(`server`);var c=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 s.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}};const l=12e3;async function u(r){let[{loadConfig:i,reconfigureForWorkspace:u,resolveIndexMode:d},{createLazyServer:f},{checkForUpdates:p,autoUpgradeScaffold:m},{RootsListChangedNotificationSchema:h}]=await Promise.all([import(`./config-B4klhHVp.js`),import(`./server-B3Wy5oMX.js`),import(`./version-check-CRvtGBDG.js`),import(`@modelcontextprotocol/sdk/types.js`)]),g=i();o(g.logging?.errorDetails===!0),g.configError&&s.warn(`Config load failure`,{error:g.configError}),s.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;b();let C=Date.now()+l,w=!1;try{await Promise.race([x.then(()=>{w=!0}),new Promise(e=>setTimeout(e,l))])}catch{}if(w)s.debug(`Init completed before transport connect — all tools registered`);else{let e=Date.now()-(C-l);s.debug(`Init ${e>=l?`timed out`:`failed`} after ${e}ms — connecting with placeholder tools; tool_list_changed will be sent when init completes`)}let{StdioServerTransport:T}=await import(`@modelcontextprotocol/sdk/server/stdio.js`),E=new T;if(typeof E._readBuffer?.readMessage!=`function`)throw Error(`Cannot install JSON repair: StdioServerTransport._readBuffer has unexpected shape`);E._readBuffer=new c,s.debug(`JSON repair installed on stdio transport`),await y.connect(E),s.debug(`MCP server started`,{transport:`stdio`,initSucceeded:w}),await e({config:g,indexMode:_,log:s,rootsChangedNotificationSchema:h,reconfigureForWorkspace:u,runInitialIndex:S,server:y,startInit:b,version:r});let D=null,O=null,k=!1,A=async e=>{k||(k=!0,s.info(`Shutdown signal received`,{signal:e}),D&&=(clearTimeout(D),null),O?.stop(),await import(`../../tools/dist/index.js`).then(({processStopAll:e})=>e()).catch(()=>{}),await E.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))},j=()=>{D&&clearTimeout(D),D=setTimeout(async()=>{s.info(`Auto-shutdown: no activity for 30 minutes — releasing resources`);try{let e=v.aikit;e&&(e.embedder.shutdown?.().catch(()=>{}),e.store.releaseMemory?.(),e.graphStore.releaseMemory?.())}catch(e){s.warn(`Resource release failed during shutdown`,a(e))}},18e5),D.unref&&D.unref()};j(),process.stdin.on(`data`,()=>j()),process.stdin.on(`end`,()=>void A(`stdin-end`)),process.stdin.on(`close`,()=>void A(`stdin-close`)),process.stdin.on(`error`,()=>void A(`stdin-error`)),process.on(`SIGINT`,()=>void A(`SIGINT`)),process.on(`SIGTERM`,()=>void A(`SIGTERM`)),x.catch(e=>{s.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);O=t;let n=v.aikit.store;t.start(),n.onBeforeClose&&n.onBeforeClose(()=>t.stop()),v.setSmartScheduler(t),s.debug(`Smart index scheduler started (stdio mode)`)}catch(e){s.error(`Failed to start smart index scheduler`,t(r,e))}}).catch(e=>s.error(`AI Kit init failed for smart scheduler`,t(r,e))):s.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,2 +0,0 @@
1
- #!/usr/bin/env node
2
- import{t as e}from"./bin.js";import{createLogger as t,serializeError as n}from"../../core/dist/index.js";const r=t(`server`);function i(e,t){return t?{version:e,...n(t)}:{version:e}}function a(t,a,o){t.then(async()=>{try{let{markPromoteRun:t,markPruneRun:n,prune:i,shouldRunStartupPrune:o,shouldRunWeeklyPromote:s}=await import(`../../tools/dist/index.js`),c=a();if(!c)return;if(o()){let e=await i({});n(),e.totalBytesFreed>0&&r.info(`Storage maintenance complete`,{forgeOrphans:e.forgeGroundOrphans.count,legacyLance:e.legacyLance.count,bytesFreed:e.totalBytesFreed});let{groupLessons:t,pruneLessons:a}=await import(`./evolution-DWaEE6XW.js`).then(e=>e.t),o=await a(c.curated,c.stateStore,{dryRun:!1});o.pruned.length>0&&r.info(`Startup lesson prune complete`,{pruned:o.pruned.length});let s=await t(c.curated,c.stateStore,{dryRun:!1});(s.groupsCreated>0||s.lessonsGrouped>0)&&r.info(`Startup lesson grouping complete`,{groupsCreated:s.groupsCreated,lessonsGrouped:s.lessonsGrouped})}if(s()){let{DEFAULT_PROMOTE_CONFIG:n,collectWorkspaceLessons:i,getGlobalCuratedDir:a,promoteLessons:o,scanForDuplicates:s}=await import(`./promotion-DRnRfteq.js`).then(e=>e.o),l=c.curated,u=new e(a(),l.store,l.embedder),d=await i(),f={...n,dryRun:!1},p=await o(s(d,f),u,f);t(),p.promoted.length>0&&r.info(`Weekly lesson promotion complete`,{promoted:p.promoted.length,candidates:p.candidates.length})}}catch(e){r.warn(`Startup maintenance failed (non-critical)`,i(o,e))}}).catch(e=>r.warn(`Startup maintenance failed`,n(e)))}export{i as n,a as t};
@@ -1 +0,0 @@
1
- import{t as e}from"./curated-manager-CBKTmAjM.js";import{createLogger as t,serializeError as n}from"../../core/dist/index.js";const r=t(`server`);function i(e,t){return t?{version:e,...n(t)}:{version:e}}function a(t,a,o){t.then(async()=>{try{let{markPromoteRun:t,markPruneRun:n,prune:i,shouldRunStartupPrune:o,shouldRunWeeklyPromote:s}=await import(`../../tools/dist/index.js`),c=a();if(!c)return;if(o()){let e=await i({});n(),e.totalBytesFreed>0&&r.info(`Storage maintenance complete`,{forgeOrphans:e.forgeGroundOrphans.count,legacyLance:e.legacyLance.count,bytesFreed:e.totalBytesFreed});let{groupLessons:t,pruneLessons:a}=await import(`./evolution-BX_zTSdj.js`).then(e=>e.t),o=await a(c.curated,c.stateStore,{dryRun:!1});o.pruned.length>0&&r.info(`Startup lesson prune complete`,{pruned:o.pruned.length});let s=await t(c.curated,c.stateStore,{dryRun:!1});(s.groupsCreated>0||s.lessonsGrouped>0)&&r.info(`Startup lesson grouping complete`,{groupsCreated:s.groupsCreated,lessonsGrouped:s.lessonsGrouped})}if(s()){let{DEFAULT_PROMOTE_CONFIG:n,collectWorkspaceLessons:i,getGlobalCuratedDir:a,promoteLessons:o,scanForDuplicates:s}=await import(`./promotion-DzVLWVtx.js`).then(e=>e.o),l=c.curated,u=new e(a(),l.store,l.embedder),d=await i(),f={...n,dryRun:!1},p=await o(s(d,f),u,f);t(),p.promoted.length>0&&r.info(`Weekly lesson promotion complete`,{promoted:p.promoted.length,candidates:p.candidates.length})}}catch(e){r.warn(`Startup maintenance failed (non-critical)`,i(o,e))}}).catch(e=>r.warn(`Startup maintenance failed`,n(e)))}export{i as n,a as t};