@vpxa/aikit 0.1.344 → 0.1.346
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/packages/cli/dist/index.js +19 -19
- package/packages/cli/dist/{init-DgYgDXBw.js → init-BZHwK5rv.js} +1 -1
- package/packages/cli/dist/{templates-DEHhml1n.js → templates-DxyYPlMl.js} +48 -16
- package/packages/core/dist/index.d.ts +273 -2
- package/packages/core/dist/index.js +1 -1
- package/packages/flows/dist/index.d.ts +141 -4
- package/packages/flows/dist/index.js +6 -6
- package/packages/server/dist/bin.js +1 -1
- package/packages/server/dist/config-BsS-77rp.js +2 -0
- package/packages/server/dist/config-Ds28Hvip.js +1 -0
- package/packages/server/dist/index.js +1 -1
- package/packages/server/dist/prelude-BZ8GJ-XM.js +2 -0
- package/packages/server/dist/prelude-n6bQqN8I.js +1 -0
- package/packages/server/dist/promotion-DRnRfteq.js +3 -0
- package/packages/server/dist/promotion-DzVLWVtx.js +2 -0
- package/packages/server/dist/sampling-BPyxG8R9.js +2 -0
- package/packages/server/dist/sampling-Du72dbFV.js +1 -0
- package/packages/server/dist/{server-2ntNwLtr.js → server-BemxePvq.js} +173 -169
- package/packages/server/dist/{server-qVK37TfU.js → server-DrADmSsL.js} +173 -169
- package/packages/server/dist/{server-http-BwaQWT2R.js → server-http-Bqpd6YFe.js} +1 -1
- package/packages/server/dist/{server-http-BXF275jD.js → server-http-Dxm0ojXH.js} +1 -1
- package/packages/server/dist/{server-stdio-DVjY0Ebj.js → server-stdio-BKsekmb0.js} +1 -1
- package/packages/server/dist/{server-stdio-By2Kx_7Y.js → server-stdio-G0HKuOkb.js} +1 -1
- package/packages/server/dist/{startup-maintenance-L9NUOBVy.js → startup-maintenance-CBJWiJ7p.js} +1 -1
- package/packages/server/dist/{startup-maintenance-DYmXBVTV.js → startup-maintenance-DX1yTfBa.js} +1 -1
- package/packages/server/dist/version-check-BjFqR01r.js +1 -0
- package/packages/server/dist/version-check-_2wmedTl.js +2 -0
- package/packages/tools/dist/index.d.ts +145 -1
- package/packages/tools/dist/index.js +87 -82
- package/scaffold/dist/adapters/_shared.mjs +9 -9
- package/scaffold/dist/definitions/agents.mjs +2 -2
- package/scaffold/dist/definitions/bodies.mjs +22 -13
- package/scaffold/dist/definitions/flows.mjs +28 -12
- package/scaffold/dist/definitions/protocols.mjs +38 -8
- package/scaffold/dist/definitions/skills/aikit.mjs +80 -17
- package/scaffold/dist/definitions/skills/docs.mjs +9 -0
- package/scaffold/dist/definitions/skills/lesson-learned.mjs +9 -0
- package/scaffold/dist/definitions/skills/multi-agents-development.mjs +10 -5
- package/packages/server/dist/config-B-wvmMyo.js +0 -1
- package/packages/server/dist/config-Bx85fwRX.js +0 -2
- package/packages/server/dist/prelude-DOxnDMN4.js +0 -2
- package/packages/server/dist/prelude-Dzih_AGV.js +0 -1
- package/packages/server/dist/promotion-RbjKfC88.js +0 -3
- package/packages/server/dist/promotion-l1L8Vf7U.js +0 -2
- package/packages/server/dist/version-check-2-tfmCnt.js +0 -2
- package/packages/server/dist/version-check-BKtLrLhw.js +0 -1
|
@@ -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-L9NUOBVy.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-Bx85fwRX.js`),import(`./dashboard-static-dPnij4uF.js`),import(`./settings-static-MepJZjer.js`),import(`./routes-CfG5gdSR.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-2ntNwLtr.js`),import(`@modelcontextprotocol/sdk/server/streamableHttp.js`),import(`./version-check-2-tfmCnt.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-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-BsS-77rp.js`),import(`./dashboard-static-dPnij4uF.js`),import(`./settings-static-MepJZjer.js`),import(`./routes-CfG5gdSR.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-BemxePvq.js`),import(`@modelcontextprotocol/sdk/server/streamableHttp.js`),import(`./version-check-_2wmedTl.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};
|
|
@@ -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-DYmXBVTV.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-B-wvmMyo.js`),import(`./dashboard-static-Dw7Nsq4f.js`),import(`./settings-static-BpQgaMRs.js`),import(`./routes-C7bDyCOW.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-qVK37TfU.js`),import(`@modelcontextprotocol/sdk/server/streamableHttp.js`),import(`./version-check-BKtLrLhw.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-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-Ds28Hvip.js`),import(`./dashboard-static-Dw7Nsq4f.js`),import(`./settings-static-BpQgaMRs.js`),import(`./routes-C7bDyCOW.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-DrADmSsL.js`),import(`@modelcontextprotocol/sdk/server/streamableHttp.js`),import(`./version-check-BjFqR01r.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 +1 @@
|
|
|
1
|
-
import{n as e}from"./workspace-bootstrap-BJloolzr.js";import{n as t,t as n}from"./startup-maintenance-
|
|
1
|
+
import{n as e}from"./workspace-bootstrap-BJloolzr.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}};async function l(r){let[{loadConfig:i,reconfigureForWorkspace:l,resolveIndexMode:u},{createLazyServer:d},{checkForUpdates:f,autoUpgradeScaffold:p},{RootsListChangedNotificationSchema:m}]=await Promise.all([import(`./config-Ds28Hvip.js`),import(`./server-DrADmSsL.js`),import(`./version-check-BjFqR01r.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};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{r as e}from"./bin.js";import{n as t,t as n}from"./startup-maintenance-
|
|
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}};async function l(r){let[{loadConfig:i,reconfigureForWorkspace:l,resolveIndexMode:u},{createLazyServer:d},{checkForUpdates:f,autoUpgradeScaffold:p},{RootsListChangedNotificationSchema:m}]=await Promise.all([import(`./config-BsS-77rp.js`),import(`./server-BemxePvq.js`),import(`./version-check-_2wmedTl.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};
|
package/packages/server/dist/{startup-maintenance-L9NUOBVy.js → startup-maintenance-CBJWiJ7p.js}
RENAMED
|
@@ -1,2 +1,2 @@
|
|
|
1
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-
|
|
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};
|
package/packages/server/dist/{startup-maintenance-DYmXBVTV.js → startup-maintenance-DX1yTfBa.js}
RENAMED
|
@@ -1 +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;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-
|
|
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};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{fileURLToPath as e}from"node:url";import{INSTALL_ARGS as t,cleanupOldVersions as n,createLogger as r}from"../../core/dist/index.js";import{existsSync as i,mkdirSync as a,readFileSync as o,renameSync as s,rmSync as c,writeFileSync as l}from"node:fs";import{dirname as u,join as d,resolve as f}from"node:path";import{execFile as p,execSync as m,spawn as h}from"node:child_process";import{homedir as g}from"node:os";const _=`@vpxa/aikit`,v=`https://registry.npmjs.org/${_}/latest`,y=r(`server`);function b(){let t=u(e(import.meta.url));return[f(t,`..`,`..`,`..`,`bin`,`aikit.mjs`),f(t,`..`,`bin`,`aikit.mjs`),...process.argv[1]?[f(u(process.argv[1]),`aikit.mjs`)]:[]].find(e=>i(e))??null}const x=d(g(),`.aikit`),S=d(x,`current-version.json`),C=d(x,`versions`),w=/^\d+\.\d+\.\d+(-[\w.+]+)?(\+[\w.]+)?$/;function T(e){if(!w.test(e))throw Error(`Invalid semver version: ${JSON.stringify(e)}`)}function E(){let t=f(u(e(import.meta.url)),`..`,`..`,`..`,`package.json`);try{return JSON.parse(o(t,`utf-8`)).version??`0.0.0`}catch{return`0.0.0`}}function D(e,t){let n=e.split(`.`).map(Number),r=t.split(`.`).map(Number);for(let e=0;e<3;e++){let t=(n[e]??0)-(r[e]??0);if(t!==0)return t>0?1:-1}return 0}function O(e,t){let n=e.split(`.`).map(Number),r=t.split(`.`).map(Number);for(let e=0;e<3;e++){if((n[e]??0)>(r[e]??0))return!0;if((n[e]??0)<(r[e]??0))return!1}return!1}async function k(e){T(e);let n=`v${e}`,r=d(C,`${n}-staging`),o=d(C,n);try{i(r)&&c(r,{recursive:!0,force:!0}),a(r,{recursive:!0}),m(`tar -xzf "${m(`npm pack ${_}@${e} 2>${process.platform===`win32`?`NUL`:`/dev/null`}`,{cwd:r,encoding:`utf-8`,timeout:6e4,windowsHide:!0}).trim()}"`,{cwd:r,encoding:`utf-8`,stdio:`pipe`,timeout:3e4,windowsHide:!0});let n=d(r,`package`);m(`npm ${t.join(` `)}`,{cwd:n,encoding:`utf-8`,stdio:`pipe`,timeout:12e4,windowsHide:!0});let u=d(n,`packages`,`server`,`dist`,`bin.js`);if(!i(u))throw Error(`Server entry not found at ${u}`);if(!i(d(n,`node_modules`)))throw Error(`node_modules not found — npm install may have failed`);i(o)&&c(o,{recursive:!0,force:!0}),s(n,o);let f=`${S}.tmp`;l(f,JSON.stringify({version:e,installedAt:new Date().toISOString()},null,2)),s(f,S),j(e)}finally{i(r)&&c(r,{recursive:!0,force:!0})}}function A(e){y.debug(`Updated to v${e}. Restarting server...`),setTimeout(()=>{process.exit(0)},300).unref()}function j(e){n(C,e??E())}async function M(){try{let e=o(S,`utf-8`),{version:t}=JSON.parse(e),n=await fetch(v,{signal:AbortSignal.timeout(1e4)});if(!n.ok)return;let r=(await n.json()).version;if(!r||r===t||!O(r,t))return;if(i(d(C,`v${r}`))){let e=`${S}.tmp`;l(e,JSON.stringify({version:r,installedAt:new Date().toISOString()},null,2)),s(e,S),y.debug(`Re-activated existing version v${r} — no download needed`),A(r);return}y.debug(`New version available: ${r}. Installing...`),await k(r),A(r)}catch(e){y.error(`Background update check failed: ${e instanceof Error?e.message:String(e)}`)}}let N=null;function P(){return N||(N=F().finally(()=>{N=null}),N)}async function F(){if(i(S)){await M();return}let e=E();try{let t=await fetch(v,{signal:AbortSignal.timeout(1e4)});if(!t.ok)return;let n=(await t.json()).version;if(!n)return;if(D(e,n)<0){y.debug(`Newer version available — installing`,{currentVersion:e,latestVersion:n});try{await k(n),A(n)}catch(e){y.warn(`Auto-install failed`,{error:e instanceof Error?e.message:String(e),latestVersion:n})}}}catch{}}function I(){try{let e=f(g(),`.copilot`,`.aikit-scaffold.json`);return i(e)?JSON.parse(o(e,`utf-8`)).version??null:null}catch{return null}}function L(){try{let e=f(process.cwd(),`.github`,`.aikit-scaffold.json`);return i(e)?JSON.parse(o(e,`utf-8`)).version??null:null}catch{return null}}let R=`idle`,z=null,B=null,V=!1;function H(){return{state:R,error:z}}function U(){R=`idle`,z=null}function W(){try{let e=E();if(P(),!V){V=!0;try{let e=b();e&&h(process.execPath,[e,`migrate-launcher`],{stdio:`ignore`,timeout:15e3,windowsHide:!0}).unref()}catch{}}let t=I(),n=L();if(!(t!=null&&t!==e)&&!(n!=null&&n!==e)||(B!==e&&(U(),B=e),R!==`idle`))return;R=`pending`,z=null,y.debug(`Scaffold version mismatch — auto-upgrading`,{serverVersion:e,userScaffoldVersion:t,workspaceScaffoldVersion:n});let r=b();if(!r){R=`failed`,z=`aikit CLI binary not found`,y.warn(`Cannot auto-upgrade: aikit CLI binary not found`);return}p(process.execPath,[r,`upgrade`],{timeout:3e4,windowsHide:!0},(t,n,i)=>{t?(R=`failed`,z=t.message,y.warn(`Auto-upgrade failed`,{error:t.message,stderr:i?.slice(0,500),binPath:r,platform:process.platform})):(R=`success`,z=null,y.debug(`Auto-upgrade completed to version ${e}`))}).unref()}catch(e){R=`failed`,z=e instanceof Error?e.message:String(e),y.warn(`Auto-upgrade check failed`,{error:z})}}export{W as autoUpgradeScaffold,P as checkForUpdates,j as cleanupOldVersions,E as getCurrentVersion,H as getUpgradeState};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import{fileURLToPath as e}from"node:url";import{INSTALL_ARGS as t,cleanupOldVersions as n,createLogger as r}from"../../core/dist/index.js";import{existsSync as i,mkdirSync as a,readFileSync as o,renameSync as s,rmSync as c,writeFileSync as l}from"node:fs";import{dirname as u,join as d,resolve as f}from"node:path";import{homedir as p}from"node:os";import{execFile as m,execSync as h,spawn as g}from"node:child_process";const _=`@vpxa/aikit`,v=`https://registry.npmjs.org/${_}/latest`,y=r(`server`);function b(){let t=u(e(import.meta.url));return[f(t,`..`,`..`,`..`,`bin`,`aikit.mjs`),f(t,`..`,`bin`,`aikit.mjs`),...process.argv[1]?[f(u(process.argv[1]),`aikit.mjs`)]:[]].find(e=>i(e))??null}const x=d(p(),`.aikit`),S=d(x,`current-version.json`),C=d(x,`versions`),w=/^\d+\.\d+\.\d+(-[\w.+]+)?(\+[\w.]+)?$/;function T(e){if(!w.test(e))throw Error(`Invalid semver version: ${JSON.stringify(e)}`)}function E(){let t=f(u(e(import.meta.url)),`..`,`..`,`..`,`package.json`);try{return JSON.parse(o(t,`utf-8`)).version??`0.0.0`}catch{return`0.0.0`}}function D(e,t){let n=e.split(`.`).map(Number),r=t.split(`.`).map(Number);for(let e=0;e<3;e++){let t=(n[e]??0)-(r[e]??0);if(t!==0)return t>0?1:-1}return 0}function O(e,t){let n=e.split(`.`).map(Number),r=t.split(`.`).map(Number);for(let e=0;e<3;e++){if((n[e]??0)>(r[e]??0))return!0;if((n[e]??0)<(r[e]??0))return!1}return!1}async function k(e){T(e);let n=`v${e}`,r=d(C,`${n}-staging`),o=d(C,n);try{i(r)&&c(r,{recursive:!0,force:!0}),a(r,{recursive:!0}),h(`tar -xzf "${h(`npm pack ${_}@${e} 2>${process.platform===`win32`?`NUL`:`/dev/null`}`,{cwd:r,encoding:`utf-8`,timeout:6e4,windowsHide:!0}).trim()}"`,{cwd:r,encoding:`utf-8`,stdio:`pipe`,timeout:3e4,windowsHide:!0});let n=d(r,`package`);h(`npm ${t.join(` `)}`,{cwd:n,encoding:`utf-8`,stdio:`pipe`,timeout:12e4,windowsHide:!0});let u=d(n,`packages`,`server`,`dist`,`bin.js`);if(!i(u))throw Error(`Server entry not found at ${u}`);if(!i(d(n,`node_modules`)))throw Error(`node_modules not found — npm install may have failed`);i(o)&&c(o,{recursive:!0,force:!0}),s(n,o);let f=`${S}.tmp`;l(f,JSON.stringify({version:e,installedAt:new Date().toISOString()},null,2)),s(f,S),j(e)}finally{i(r)&&c(r,{recursive:!0,force:!0})}}function A(e){y.debug(`Updated to v${e}. Restarting server...`),setTimeout(()=>{process.exit(0)},300).unref()}function j(e){n(C,e??E())}async function M(){try{let e=o(S,`utf-8`),{version:t}=JSON.parse(e),n=await fetch(v,{signal:AbortSignal.timeout(1e4)});if(!n.ok)return;let r=(await n.json()).version;if(!r||r===t||!O(r,t))return;if(i(d(C,`v${r}`))){let e=`${S}.tmp`;l(e,JSON.stringify({version:r,installedAt:new Date().toISOString()},null,2)),s(e,S),y.debug(`Re-activated existing version v${r} — no download needed`),A(r);return}y.debug(`New version available: ${r}. Installing...`),await k(r),A(r)}catch(e){y.error(`Background update check failed: ${e instanceof Error?e.message:String(e)}`)}}let N=null;function P(){return N||(N=F().finally(()=>{N=null}),N)}async function F(){if(i(S)){await M();return}let e=E();try{let t=await fetch(v,{signal:AbortSignal.timeout(1e4)});if(!t.ok)return;let n=(await t.json()).version;if(!n)return;if(D(e,n)<0){y.debug(`Newer version available — installing`,{currentVersion:e,latestVersion:n});try{await k(n),A(n)}catch(e){y.warn(`Auto-install failed`,{error:e instanceof Error?e.message:String(e),latestVersion:n})}}}catch{}}function I(){try{let e=f(p(),`.copilot`,`.aikit-scaffold.json`);return i(e)?JSON.parse(o(e,`utf-8`)).version??null:null}catch{return null}}function L(){try{let e=f(process.cwd(),`.github`,`.aikit-scaffold.json`);return i(e)?JSON.parse(o(e,`utf-8`)).version??null:null}catch{return null}}let R=`idle`,z=null,B=null,V=!1;function H(){return{state:R,error:z}}function U(){R=`idle`,z=null}function W(){try{let e=E();if(P(),!V){V=!0;try{let e=b();e&&g(process.execPath,[e,`migrate-launcher`],{stdio:`ignore`,timeout:15e3,windowsHide:!0}).unref()}catch{}}let t=I(),n=L();if(!(t!=null&&t!==e)&&!(n!=null&&n!==e)||(B!==e&&(U(),B=e),R!==`idle`))return;R=`pending`,z=null,y.debug(`Scaffold version mismatch — auto-upgrading`,{serverVersion:e,userScaffoldVersion:t,workspaceScaffoldVersion:n});let r=b();if(!r){R=`failed`,z=`aikit CLI binary not found`,y.warn(`Cannot auto-upgrade: aikit CLI binary not found`);return}m(process.execPath,[r,`upgrade`],{timeout:3e4,windowsHide:!0},(t,n,i)=>{t?(R=`failed`,z=t.message,y.warn(`Auto-upgrade failed`,{error:t.message,stderr:i?.slice(0,500),binPath:r,platform:process.platform})):(R=`success`,z=null,y.debug(`Auto-upgrade completed to version ${e}`))}).unref()}catch(e){R=`failed`,z=e instanceof Error?e.message:String(e),y.warn(`Auto-upgrade check failed`,{error:z})}}export{W as autoUpgradeScaffold,P as checkForUpdates,j as cleanupOldVersions,E as getCurrentVersion,H as getUpgradeState};
|
|
@@ -100,6 +100,145 @@ interface AuditData {
|
|
|
100
100
|
}
|
|
101
101
|
declare function audit(store: IKnowledgeStore, embedder: IEmbedder, options?: AuditOptions): Promise<AikitResponse<AuditData>>;
|
|
102
102
|
//#endregion
|
|
103
|
+
//#region packages/tools/src/briefing-card-compiler.d.ts
|
|
104
|
+
/**
|
|
105
|
+
* Briefing Card Compiler — L0 card management utility.
|
|
106
|
+
*
|
|
107
|
+
* This module provides runtime path resolution and card metadata for L0
|
|
108
|
+
* generated briefing cards. It is an INTERNAL tool (not an MCP tool) —
|
|
109
|
+
* agents access L0 cards through enhanced existing tools (stratum_card,
|
|
110
|
+
* compact, status).
|
|
111
|
+
*
|
|
112
|
+
* Card storage path is resolved from server config (AikitConfig.l0CardDir)
|
|
113
|
+
* which defaults to AIKIT_RUNTIME_PATHS.l0Cards ('memories') under the
|
|
114
|
+
* workspace partition root (~/.aikit/workspaces/<partition>/).
|
|
115
|
+
*
|
|
116
|
+
* Scaffold instructions reference the TOOLS that serve L0 cards (stratum_card,
|
|
117
|
+
* compact, status), not the raw filesystem path.
|
|
118
|
+
*
|
|
119
|
+
* @module
|
|
120
|
+
*/
|
|
121
|
+
/**
|
|
122
|
+
* Known L0 briefing card families. Each family covers a specific workspace
|
|
123
|
+
* knowledge domain and has an associated token budget range.
|
|
124
|
+
*/
|
|
125
|
+
declare const BRIEFING_CARD_FAMILIES: readonly [{
|
|
126
|
+
readonly type: "workspace-core";
|
|
127
|
+
readonly description: "Durable repo facts, tool surfaces, and session rules";
|
|
128
|
+
readonly minTokens: 800;
|
|
129
|
+
readonly maxTokens: 1200;
|
|
130
|
+
readonly loadAtSessionStart: true;
|
|
131
|
+
}, {
|
|
132
|
+
readonly type: "architecture";
|
|
133
|
+
readonly description: "Package boundaries and major data flows";
|
|
134
|
+
readonly minTokens: 600;
|
|
135
|
+
readonly maxTokens: 900;
|
|
136
|
+
readonly loadAtSessionStart: false;
|
|
137
|
+
}, {
|
|
138
|
+
readonly type: "testing-release";
|
|
139
|
+
readonly description: "Release gates and high-value verification steps";
|
|
140
|
+
readonly minTokens: 600;
|
|
141
|
+
readonly maxTokens: 900;
|
|
142
|
+
readonly loadAtSessionStart: false;
|
|
143
|
+
}, {
|
|
144
|
+
readonly type: "known-issues";
|
|
145
|
+
readonly description: "Verified failures and recurring hazards";
|
|
146
|
+
readonly minTokens: 400;
|
|
147
|
+
readonly maxTokens: 700;
|
|
148
|
+
readonly loadAtSessionStart: false;
|
|
149
|
+
}, {
|
|
150
|
+
readonly type: "workflow:*";
|
|
151
|
+
readonly description: "Active flow lineage and current task context";
|
|
152
|
+
readonly minTokens: 500;
|
|
153
|
+
readonly maxTokens: 900;
|
|
154
|
+
readonly loadAtSessionStart: false;
|
|
155
|
+
}];
|
|
156
|
+
/**
|
|
157
|
+
* Resolve the L0 card storage directory for a workspace partition.
|
|
158
|
+
*
|
|
159
|
+
* At runtime, the server resolves `AikitConfig.l0CardDir` via
|
|
160
|
+
* `applyPartitionRuntimeLayout()`. This function provides the same
|
|
161
|
+
* resolution for tool-level consumers.
|
|
162
|
+
*
|
|
163
|
+
* @param partitionRoot - Absolute path to the workspace partition root
|
|
164
|
+
* @param l0CardDir - Config override, or default subdirectory name
|
|
165
|
+
* @returns Absolute path to the L0 card storage directory
|
|
166
|
+
*/
|
|
167
|
+
declare function resolveL0CardDir(partitionRoot: string, l0CardDir?: string): string;
|
|
168
|
+
/**
|
|
169
|
+
* Describe the available card families and token budgets.
|
|
170
|
+
* Returns a structured descriptor that the MCP layer can render into
|
|
171
|
+
* tool responses or status prelude output.
|
|
172
|
+
*/
|
|
173
|
+
declare function describeBriefingCards(): {
|
|
174
|
+
families: Array<{
|
|
175
|
+
type: string;
|
|
176
|
+
description: string;
|
|
177
|
+
minTokens: number;
|
|
178
|
+
maxTokens: number;
|
|
179
|
+
loadAtSessionStart: boolean;
|
|
180
|
+
}>;
|
|
181
|
+
sessionBudget: number;
|
|
182
|
+
storageHint: string;
|
|
183
|
+
};
|
|
184
|
+
/**
|
|
185
|
+
* Card selection result for session start.
|
|
186
|
+
*
|
|
187
|
+
* Per layered knowledge protocol:
|
|
188
|
+
* - \`workspace-core\` is ALWAYS loaded.
|
|
189
|
+
* - If a flow is active → load \`workflow:<flow>\` as the second card (NOT a task card).
|
|
190
|
+
* - If NO flow → optionally load one task-dependent card (architecture, testing-release,
|
|
191
|
+
* or known-issues). The second slot is null when the caller should determine based
|
|
192
|
+
* on the current task.
|
|
193
|
+
* - Never load both a task card and a flow card.
|
|
194
|
+
* - Total budget ≤ 2,100 tokens.
|
|
195
|
+
*/
|
|
196
|
+
interface SessionStartSelection {
|
|
197
|
+
/** Always \`workspace-core\` */
|
|
198
|
+
cards: string[];
|
|
199
|
+
/** Human-readable rationale for the selection */
|
|
200
|
+
rationale: string;
|
|
201
|
+
}
|
|
202
|
+
/**
|
|
203
|
+
* Get the recommended card selection for session start.
|
|
204
|
+
*
|
|
205
|
+
* @param activeFlowSlug - Active flow slug (if any). When set, workflow card replaces task card.
|
|
206
|
+
* @returns Selection with primary + optional secondary card
|
|
207
|
+
*/
|
|
208
|
+
declare function getSessionStartCards(activeFlowSlug?: string): SessionStartSelection;
|
|
209
|
+
/**
|
|
210
|
+
* Estimate token budget for a session start card set.
|
|
211
|
+
* Returns null if the set exceeds 2,100 tokens.
|
|
212
|
+
*/
|
|
213
|
+
/** Name of the workspace-core L0 card file. */
|
|
214
|
+
declare const WORKSPACE_CORE_FILENAME = "workspace-core.md";
|
|
215
|
+
/** Maximum characters for a generated L0 card (≈1,200 tokens × 4 chars/token). */
|
|
216
|
+
declare const MAX_CARD_CHARS = 4800;
|
|
217
|
+
/**
|
|
218
|
+
* Input data for generating a workspace-core L0 briefing card.
|
|
219
|
+
*/
|
|
220
|
+
interface L0CardInput {
|
|
221
|
+
/** Workspace root path or name */
|
|
222
|
+
workspaceName: string;
|
|
223
|
+
/** Structure analysis output (compact) */
|
|
224
|
+
structure?: string;
|
|
225
|
+
/** Entry points analysis output */
|
|
226
|
+
entryPoints?: string;
|
|
227
|
+
/** Dependencies analysis output */
|
|
228
|
+
dependencies?: string;
|
|
229
|
+
/** Key symbols (comma-separated) */
|
|
230
|
+
symbols?: string;
|
|
231
|
+
}
|
|
232
|
+
/**
|
|
233
|
+
* Generate a workspace-core L0 briefing card from analysis baselines.
|
|
234
|
+
* Card is compact markdown ≤1,200 tokens.
|
|
235
|
+
*
|
|
236
|
+
* @param input - Analysis data to compress into the card
|
|
237
|
+
* @returns Card content as markdown string
|
|
238
|
+
*/
|
|
239
|
+
declare function generateL0WorkspaceCoreCard(input: L0CardInput): string;
|
|
240
|
+
declare function estimateSessionTokenBudget(cards: string[]): number | null;
|
|
241
|
+
//#endregion
|
|
103
242
|
//#region packages/tools/src/changelog.d.ts
|
|
104
243
|
/**
|
|
105
244
|
* aikit_changelog — Generate a changelog from git history.
|
|
@@ -2424,6 +2563,11 @@ interface OnboardOptions {
|
|
|
2424
2563
|
/** Callback function for LLM text generation (provided by server layer via MCP sampling). */
|
|
2425
2564
|
llmCall?: (prompt: string, system?: string) => Promise<string>;
|
|
2426
2565
|
}
|
|
2566
|
+
/**
|
|
2567
|
+
* Resolve the workspace directory for a given project path.
|
|
2568
|
+
* All output goes here — never inside the project itself.
|
|
2569
|
+
*/
|
|
2570
|
+
declare function resolveWorkspaceDir(rootPath: string): string;
|
|
2427
2571
|
interface OnboardStepResult {
|
|
2428
2572
|
name: string;
|
|
2429
2573
|
status: 'success' | 'failed';
|
|
@@ -3437,4 +3581,4 @@ declare function addToWorkset(name: string, files: string[], cwd?: string): Work
|
|
|
3437
3581
|
*/
|
|
3438
3582
|
declare function removeFromWorkset(name: string, files: string[], cwd?: string): Workset | null;
|
|
3439
3583
|
//#endregion
|
|
3440
|
-
export { type AikitNextHint, type AikitResponse, type AikitResponseMeta, type AikitToolError, type AikitToolErrorCode, type AuditCheck, type AuditData, type AuditOptions, type AuditRecommendation, type BenchmarkReport, type BlastNode, type ChangelogEntry, type ChangelogFormat, type ChangelogOptions, type ChangelogResult, type CheckOptions, type CheckResult, type CheckSummaryResult, type Checkpoint, type CheckpointSummary, type ClassifyTrigger, type CodemodChange, type CodemodOptions, type CodemodResult, type CodemodRule, type CompactOptions, type CompactResult, type ComplianceReport, type ComplianceRule, type ComplianceScoreOptions, type ComplianceViolation, type CompressOutputOptions, type CompressionContext, type CompressionMode, type CompressionResult, type CompressionRule, type ConstraintRef, type CorpusStats, type DeadSymbol, type DeadSymbolOptions, type DeadSymbolResult, type Definition, type DelegateOptions, type DelegateResult, type DetectedRoute, type DiffChange, type DiffFile, type DiffHunk, type DiffParseOptions, type DiffReport, type DigestFieldEntry, type DigestOptions, type DigestResult, type DigestSource, type DogfoodLogEntry, type DogfoodLogGroupedEntry, type DogfoodLogOptions, type DogfoodLogResult, type Domain, type DomainAnalysisInput, type DomainClassification, type DomainType, type EncodeOperation, type EncodeOptions, type EncodeResult, type EnrichOptions, type EnrichStructureEntry, type EnrichSymbolEntry, type EnvInfoOptions, type EnvInfoResult, type EvalOptions, type EvalResult, type EvidenceEntry, type EvidenceMapAction, type EvidenceMapResult, type EvidenceMapState, type EvidenceStatus, type Example, type ExportMap, ExtractionCache, type ExtractionCacheEntry, FileCache, type FileCacheEntry, type FileCacheStats, type FileChange, type FileMetrics, type FileSummaryOptions, type FileSummaryResult, type FindExamplesOptions, type FindExamplesResult, type FindOptions, type FindResult, type FindResults, type Finding, type FindingSeverity, type ForgeClassifyCeremony, type ForgeClassifyOptions, type ForgeClassifyResult, type ForgeGroundOptions, type ForgeGroundResult, type ForgeTier, GIT_REF_SLUG_PATTERN, type GateConfig, type GateDecision, type GateResult, type GitContextOptions, type GitContextResult, type GraphAugmentOptions, type GraphAugmentedResult, type GraphQueryOptions, type GraphQueryResult, type GraphReviewReport, type GraphStats, type GuideRecommendation, type GuideResult, type GuidedTour, type GuidedTourOptions, type HealthCheck, type HealthResult, type HotspotEntry, type HttpMethod, type HttpRequestOptions, type HttpRequestResult, type ImportGraph, type ImportMap, type KnowledgeGraph, LLMEnricher, type LaneDiffEntry, type LaneDiffResult, type LaneMergeResult, type LaneMeta, type LayerDetectionInput, type LayerType, type Lease, type LeaseConflict, type LegacyStashOptions, type ManagedProcess, type MeasureOptions, type MeasureResult, type ModuleInsight, type OnboardMode, type OnboardOptions, type OnboardResult, type OnboardStepResult, type ParsedError, type ParsedGitStatus, type ParsedOutput, type ParsedTestResult, type ParsedTestSummary, type PipelineResult, type PruneOptions, type PruneResult, type QueueItem, type QueueState, type Reference, type RegexTestOptions, type RegexTestResult, type RenameChange, type RenameOptions, type RenameResult, type ReplayEntry, type ReplayOptions, type Resolution, type ResolutionMethod, type ResolutionOptions, type ResolvedImport, type RestorePoint, type ReverseGraph, type RouteDetectionResult, type SafetyGate, type SafetyGateResult, type ScanResult, type ScannedFile, type SchemaValidateOptions, type SchemaValidateResult, type ScopeMapEntry, type ScopeMapOptions, type ScopeMapResult, type SearchResponseData, type SearchResponseItem, type SearchSuccessResponseOptions, type SessionDigestOptions, type SessionDigestResult, type SkillMatch, type SkillTriggerExamples, type SkillTriggerMeta, type StashEntry, type StashStore, type StratumCard, type StratumCardOptions, type StratumCardResult, type SymbolGraphContext, type SymbolInfo, type SymbolOptions, type TestRunOptions, type TestRunResult, type TimeOptions, type TimeResult, type TimeoutAction, type TourStep, type TraceNode, type TraceOptions, type TraceResult, type TransformOptions, type TransformResult, type TypedUnknownSeed, type UnknownType, type ValidationError, type WatchEvent, type WatchHandle, type WatchOptions, type WebFetchMode, type WebFetchOptions, type WebFetchResult, type WebSearchOptions, type WebSearchResult, type WebSearchResultItem, type Workset, type WorksetStore, acquireLease, addToWorkset, analyzeDiff, analyzeDomain, analyzeDomains, analyzeFile, audit, autoClaimTestFailures, benchmarkFiles, benchmarkTokenReduction, bookendReorder, bpeSurprise, buildExportMap, buildImportGraph, buildImportMap, buildReverseGraph, callId, changelog, check, checkEmptyGraph, checkMissingFields, checkSchemaVersion, checkpointDiff, checkpointGC, checkpointHistory, checkpointLatest, checkpointList, checkpointLoad, checkpointSave, classifyDomain, classifyDomains, classifyExitCode, codemod, compact, compressOutput, compressTerminalOutput, cosineSimilarity, createRestorePoint, createSearchErrorResponse, createSearchSuccessResponse, dataTransform, delegate, delegateListModels, deleteWorkset, detectLayer, detectLayers, detectOutputTool, detectRoutes, diffParse, digest, dogfoodLog, edgeId, encode, ensureLegacyStashImported, envInfo, errorResponse, escapeRegExp, estimateGraphTokens, estimateTokens, evaluate, evidenceMap, extractImports, extractRoutesFromFile, fileId, fileSummary, find, findDanglingEdges, findDeadSymbols, findDuplicateIds, findExamples, findOrphanNodes, findSelfLoops, findTour, forgeClassify, forgeGround, formatBytes, formatChangelog, formatDomainReport, formatTour, formatToursIndex, generateGuidedTours, getRegisteredRules, getWorkset, gitAvailable, gitCommitToRef, gitContext, gitExec, graphAugmentSearch, graphQuery, groupByDomain, guide, headTailTruncate, health, httpRequest, inferNextjsRoutes, laneCreate, laneDiff, laneDiscard, laneList, laneMerge, laneStatus, listActiveLeases, listRestorePoints, listWorksets, markPromoteRun, markPruneRun, matchSkills, measure, measureCorpus, normalizePath, okResponse, onboard, orderByDependency, paragraphTruncate, parseBiome, parseGitStatus, parseOutput, parseSearchResults, parseTsc, parseVitest, processList, processLogs, processStart, processStatus, processStop, processStopAll, prune, queueClear, queueCreate, queueDag, queueDelete, queueDone, queueFail, queueGet, queueList, queueNext, queuePush, regexTest, registerRule, registerRules, releaseLease, removeFromWorkset, rename, replayAppend, replayCapture, replayClear, replayList, replayTrim, resetGitCache, resolveImportPath, resolvePath, resolveSymbol, resolveSymbols, restoreFromPoint, reviewGraph, runPipeline, saveWorkset, scanCodebase, schemaValidate, scopeMap, scoreCompliance, scoreLine, scoreLines, segment, sessionDigest, sessionDigestSampling, shannonEntropy, shouldRunStartupPrune, shouldRunWeeklyPromote, slugForRef, stashClear, stashDelete, stashGet, stashList, stashSet, storeReversibleContext, stratumCard, summarizeCheckResult, symbol, symbolId, testRun, timeUtils, trace, traverseBlastRadius, truncateToTokenBudget, watchList, watchStart, watchStop, webFetch, webSearch, workspacePath };
|
|
3584
|
+
export { type AikitNextHint, type AikitResponse, type AikitResponseMeta, type AikitToolError, type AikitToolErrorCode, type AuditCheck, type AuditData, type AuditOptions, type AuditRecommendation, BRIEFING_CARD_FAMILIES, type BenchmarkReport, type BlastNode, type ChangelogEntry, type ChangelogFormat, type ChangelogOptions, type ChangelogResult, type CheckOptions, type CheckResult, type CheckSummaryResult, type Checkpoint, type CheckpointSummary, type ClassifyTrigger, type CodemodChange, type CodemodOptions, type CodemodResult, type CodemodRule, type CompactOptions, type CompactResult, type ComplianceReport, type ComplianceRule, type ComplianceScoreOptions, type ComplianceViolation, type CompressOutputOptions, type CompressionContext, type CompressionMode, type CompressionResult, type CompressionRule, type ConstraintRef, type CorpusStats, type DeadSymbol, type DeadSymbolOptions, type DeadSymbolResult, type Definition, type DelegateOptions, type DelegateResult, type DetectedRoute, type DiffChange, type DiffFile, type DiffHunk, type DiffParseOptions, type DiffReport, type DigestFieldEntry, type DigestOptions, type DigestResult, type DigestSource, type DogfoodLogEntry, type DogfoodLogGroupedEntry, type DogfoodLogOptions, type DogfoodLogResult, type Domain, type DomainAnalysisInput, type DomainClassification, type DomainType, type EncodeOperation, type EncodeOptions, type EncodeResult, type EnrichOptions, type EnrichStructureEntry, type EnrichSymbolEntry, type EnvInfoOptions, type EnvInfoResult, type EvalOptions, type EvalResult, type EvidenceEntry, type EvidenceMapAction, type EvidenceMapResult, type EvidenceMapState, type EvidenceStatus, type Example, type ExportMap, ExtractionCache, type ExtractionCacheEntry, FileCache, type FileCacheEntry, type FileCacheStats, type FileChange, type FileMetrics, type FileSummaryOptions, type FileSummaryResult, type FindExamplesOptions, type FindExamplesResult, type FindOptions, type FindResult, type FindResults, type Finding, type FindingSeverity, type ForgeClassifyCeremony, type ForgeClassifyOptions, type ForgeClassifyResult, type ForgeGroundOptions, type ForgeGroundResult, type ForgeTier, GIT_REF_SLUG_PATTERN, type GateConfig, type GateDecision, type GateResult, type GitContextOptions, type GitContextResult, type GraphAugmentOptions, type GraphAugmentedResult, type GraphQueryOptions, type GraphQueryResult, type GraphReviewReport, type GraphStats, type GuideRecommendation, type GuideResult, type GuidedTour, type GuidedTourOptions, type HealthCheck, type HealthResult, type HotspotEntry, type HttpMethod, type HttpRequestOptions, type HttpRequestResult, type ImportGraph, type ImportMap, type KnowledgeGraph, type L0CardInput, LLMEnricher, type LaneDiffEntry, type LaneDiffResult, type LaneMergeResult, type LaneMeta, type LayerDetectionInput, type LayerType, type Lease, type LeaseConflict, type LegacyStashOptions, MAX_CARD_CHARS, type ManagedProcess, type MeasureOptions, type MeasureResult, type ModuleInsight, type OnboardMode, type OnboardOptions, type OnboardResult, type OnboardStepResult, type ParsedError, type ParsedGitStatus, type ParsedOutput, type ParsedTestResult, type ParsedTestSummary, type PipelineResult, type PruneOptions, type PruneResult, type QueueItem, type QueueState, type Reference, type RegexTestOptions, type RegexTestResult, type RenameChange, type RenameOptions, type RenameResult, type ReplayEntry, type ReplayOptions, type Resolution, type ResolutionMethod, type ResolutionOptions, type ResolvedImport, type RestorePoint, type ReverseGraph, type RouteDetectionResult, type SafetyGate, type SafetyGateResult, type ScanResult, type ScannedFile, type SchemaValidateOptions, type SchemaValidateResult, type ScopeMapEntry, type ScopeMapOptions, type ScopeMapResult, type SearchResponseData, type SearchResponseItem, type SearchSuccessResponseOptions, type SessionDigestOptions, type SessionDigestResult, type SessionStartSelection, type SkillMatch, type SkillTriggerExamples, type SkillTriggerMeta, type StashEntry, type StashStore, type StratumCard, type StratumCardOptions, type StratumCardResult, type SymbolGraphContext, type SymbolInfo, type SymbolOptions, type TestRunOptions, type TestRunResult, type TimeOptions, type TimeResult, type TimeoutAction, type TourStep, type TraceNode, type TraceOptions, type TraceResult, type TransformOptions, type TransformResult, type TypedUnknownSeed, type UnknownType, type ValidationError, WORKSPACE_CORE_FILENAME, type WatchEvent, type WatchHandle, type WatchOptions, type WebFetchMode, type WebFetchOptions, type WebFetchResult, type WebSearchOptions, type WebSearchResult, type WebSearchResultItem, type Workset, type WorksetStore, acquireLease, addToWorkset, analyzeDiff, analyzeDomain, analyzeDomains, analyzeFile, audit, autoClaimTestFailures, benchmarkFiles, benchmarkTokenReduction, bookendReorder, bpeSurprise, buildExportMap, buildImportGraph, buildImportMap, buildReverseGraph, callId, changelog, check, checkEmptyGraph, checkMissingFields, checkSchemaVersion, checkpointDiff, checkpointGC, checkpointHistory, checkpointLatest, checkpointList, checkpointLoad, checkpointSave, classifyDomain, classifyDomains, classifyExitCode, codemod, compact, compressOutput, compressTerminalOutput, cosineSimilarity, createRestorePoint, createSearchErrorResponse, createSearchSuccessResponse, dataTransform, delegate, delegateListModels, deleteWorkset, describeBriefingCards, detectLayer, detectLayers, detectOutputTool, detectRoutes, diffParse, digest, dogfoodLog, edgeId, encode, ensureLegacyStashImported, envInfo, errorResponse, escapeRegExp, estimateGraphTokens, estimateSessionTokenBudget, estimateTokens, evaluate, evidenceMap, extractImports, extractRoutesFromFile, fileId, fileSummary, find, findDanglingEdges, findDeadSymbols, findDuplicateIds, findExamples, findOrphanNodes, findSelfLoops, findTour, forgeClassify, forgeGround, formatBytes, formatChangelog, formatDomainReport, formatTour, formatToursIndex, generateGuidedTours, generateL0WorkspaceCoreCard, getRegisteredRules, getSessionStartCards, getWorkset, gitAvailable, gitCommitToRef, gitContext, gitExec, graphAugmentSearch, graphQuery, groupByDomain, guide, headTailTruncate, health, httpRequest, inferNextjsRoutes, laneCreate, laneDiff, laneDiscard, laneList, laneMerge, laneStatus, listActiveLeases, listRestorePoints, listWorksets, markPromoteRun, markPruneRun, matchSkills, measure, measureCorpus, normalizePath, okResponse, onboard, orderByDependency, paragraphTruncate, parseBiome, parseGitStatus, parseOutput, parseSearchResults, parseTsc, parseVitest, processList, processLogs, processStart, processStatus, processStop, processStopAll, prune, queueClear, queueCreate, queueDag, queueDelete, queueDone, queueFail, queueGet, queueList, queueNext, queuePush, regexTest, registerRule, registerRules, releaseLease, removeFromWorkset, rename, replayAppend, replayCapture, replayClear, replayList, replayTrim, resetGitCache, resolveImportPath, resolveL0CardDir, resolvePath, resolveSymbol, resolveSymbols, resolveWorkspaceDir, restoreFromPoint, reviewGraph, runPipeline, saveWorkset, scanCodebase, schemaValidate, scopeMap, scoreCompliance, scoreLine, scoreLines, segment, sessionDigest, sessionDigestSampling, shannonEntropy, shouldRunStartupPrune, shouldRunWeeklyPromote, slugForRef, stashClear, stashDelete, stashGet, stashList, stashSet, storeReversibleContext, stratumCard, summarizeCheckResult, symbol, symbolId, testRun, timeUtils, trace, traverseBlastRadius, truncateToTokenBudget, watchList, watchStart, watchStop, webFetch, webSearch, workspacePath };
|