@vpxa/aikit 0.1.265 → 0.1.267
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/server/dist/bin.js +1 -1
- package/packages/server/dist/index.js +1 -1
- package/packages/server/dist/{server-foPKRLfz.js → server-BMVFCB-8.js} +15 -15
- package/packages/server/dist/{server-Bvyactic.js → server-kAiz3riV.js} +15 -15
- package/scaffold/dist/definitions/skills/c4-architecture.mjs +1 -1
package/package.json
CHANGED
|
@@ -5,4 +5,4 @@ import{t as e}from"./rolldown-runtime-yuFVEuWy.js";import{createHash as t,random
|
|
|
5
5
|
`).length,fileHash:this.hash(e.content),indexedAt:t,origin:`curated`,tags:e.frontmatter.tags,category:e.frontmatter.category,version:e.frontmatter.version}});try{return await this.store.upsert(i,r),e.length}catch(t){I.error(`Failed to upsert curated batch`,{batchSize:e.length,...p(t)});for(let t of e)n.push(`${t.relativePath}: upsert failed`);return 0}}catch(r){if(e.length===1)return I.error(`Failed to embed curated item`,{relativePath:e[0].relativePath,...p(r)}),n.push(`${e[0].relativePath}: reindex failed`),0;I.warn(`Curated embed batch failed, retrying with smaller chunks`,{batchSize:e.length,...p(r)});let i=Math.ceil(e.length/2),a=e.slice(0,i),o=e.slice(i);return await this.embedAndUpsertBatch(a,t,n)+await this.embedAndUpsertBatch(o,t,n)}}gitCommitKnowledge(e,t,n){try{if(!h(this.curatedDir))return;let r=this.knowledgeRefForPath(e);if(!r)return;g(r,`entry.md`,t,n,this.curatedDir)}catch{}}gitDeleteKnowledgeRef(e){try{if(!h(this.curatedDir))return;let t=this.knowledgeRefForPath(e);if(!t)return;_([`update-ref`,`-d`,t],this.curatedDir)}catch{}}knowledgeRefForPath(e){let t=e.replace(/\.md$/,``).split(`/`).map(e=>v(e)).join(`/`);return t.split(`/`).every(e=>m.test(e))?`${F}/${t}`:null}async indexCuratedFile(e,t,n){let r=await this.embedder.embed(t),i=`.ai/curated/${e}`,a=new Date().toISOString(),o={id:this.hashId(i,0),content:t,sourcePath:i,contentType:`curated-knowledge`,headingPath:n.title,chunkIndex:0,totalChunks:1,startLine:1,endLine:t.split(`
|
|
6
6
|
`).length,fileHash:this.hash(t),indexedAt:a,origin:`curated`,tags:n.tags,category:n.category,version:n.version};await this.store.upsert([o],[r])}async indexCuratedFileBestEffort(e,t,n,r){if(d.instance().isDegraded(`embedder`)){I.debug(`Skipping vector indexing — embedder degraded`,{relativePath:e,operation:r,subsystem:`embedder`});return}try{await this.indexCuratedFile(e,t,n)}catch(t){I.warn(`Curated file persisted but vector indexing deferred`,{relativePath:e,operation:r,...p(t)})}}async discoverCategories(){return this.adapter.listDirectories()}guardPath(e){let t=e.replace(/^\.ai\/curated\//,``);if(t.endsWith(`.md`)||(t+=`.md`),t.includes(`..`)||a(t))throw Error(`Invalid path: ${t}. Must be relative within .ai/curated/ directory.`);let n=t.split(`/`)[0];return this.validateCategoryName(n),t}validateCategoryName(e){if(!/^[a-z][a-z0-9-]*$/.test(e))throw Error(`Invalid category name: "${e}". Must be lowercase kebab-case (e.g., "decisions", "api-contracts").`)}validateContentSize(e){if(Buffer.byteLength(e,`utf-8`)>P)throw Error(`Content exceeds maximum size of ${P/1024}KB`)}slugify(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-|-$/g,``).slice(0,80)}async uniqueRelativePath(e,t){let n=`${e}/${t}.md`;if(!await this.adapter.exists(n))return n;for(let n=2;n<=100;n++){let r=`${e}/${t}-${n}.md`;if(!await this.adapter.exists(r))return r}throw Error(`Too many entries with slug "${t}" in category "${e}"`)}hash(e){return t(`sha256`).update(e).digest(`hex`).slice(0,16)}hashId(e,t){return this.hash(`${e}::${t}`)}serializeFile(e,t){return`${[`---`,`title: "${t.title.replace(/"/g,`\\"`)}"`,`category: ${t.category}`,`tags: [${t.tags.map(e=>`"${e}"`).join(`, `)}]`,`created: ${t.created}`,`updated: ${t.updated}`,`version: ${t.version}`,`origin: ${t.origin}`,`changelog:`,...t.changelog.map(e=>` - version: ${e.version}\n date: ${e.date}\n reason: "${e.reason.replace(/"/g,`\\"`)}"`),`---`].join(`
|
|
7
7
|
`)}\n\n${e}\n`}parseFile(e){let t=e.match(/^---\n([\s\S]*?)\n---\n\n?([\s\S]*)$/);if(!t)return{frontmatter:{title:`Untitled`,category:`notes`,tags:[],created:``,updated:``,version:1,origin:`curated`,changelog:[]},content:e};let n=t[1],r=t[2].trim(),i={},a=[],o=n.split(`
|
|
8
|
-
`),s=!1,c={};for(let e of o){if(/^changelog:\s*$/.test(e)){s=!0;continue}if(s){let t=e.match(/^\s+-\s+version:\s*(\d+)$/);if(t){c.version!=null&&a.push(c),c={version:parseInt(t[1],10)};continue}let n=e.match(/^\s+date:\s*(.+)$/);if(n){c.date=n[1].trim();continue}let r=e.match(/^\s+reason:\s*"?(.*?)"?\s*$/);if(r){c.reason=r[1];continue}/^\w/.test(e)&&(s=!1,c.version!=null&&a.push(c),c={});continue}let t=e.match(/^(\w+):\s*(.*)$/);if(t){let e=t[1],n=t[2];typeof n==`string`&&n.startsWith(`[`)&&n.endsWith(`]`)?n=n.slice(1,-1).split(`,`).map(e=>e.trim().replace(/^"|"$/g,``)).filter(e=>e.length>0):typeof n==`string`&&/^\d+$/.test(n)?n=parseInt(n,10):typeof n==`string`&&n.startsWith(`"`)&&n.endsWith(`"`)&&(n=n.slice(1,-1)),i[e]=n}}return c.version!=null&&a.push(c),{frontmatter:{title:i.title??`Untitled`,category:i.category??`notes`,tags:i.tags??[],created:i.created??``,updated:i.updated??``,version:i.version??1,origin:`curated`,changelog:a},content:r}}};function R(){try{let e=s(i(c(import.meta.url)),`..`,`..`,`..`,`package.json`);return JSON.parse(r(e,`utf-8`)).version??`0.0.0`}catch{return`0.0.0`}}const z=f(`server`),B=/^https?:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/i;function V({requestOrigin:e,configuredOrigin:t,allowAnyOrigin:n,fallbackOrigin:r}){let i=t??r;return i===`*`?n?{allowOrigin:`*`,warn:!1}:e?B.test(e)?{allowOrigin:e,warn:!1}:{allowOrigin:null,warn:!0}:{allowOrigin:r,warn:!1}:{allowOrigin:i,warn:!1}}function H({limit:e,windowMs:t}){let n=new Map,r=(e,r)=>{let i=r-t,a=n.get(e)?.filter(e=>e>i)??[];return a.length===0?(n.delete(e),[]):(n.set(e,a),a)};return{allow(t,i=Date.now()){let a=r(t,i);return a.length>=e?!1:(a.push(i),n.set(t,a),!0)},getRetryAfterMs(n,i=Date.now()){let a=r(n,i);return a.length<e?0:Math.max(0,a[0]+t-i)}}}function U(e){return e.startsWith(`file://`)?c(e):e}function W(e){let t=s(e);return process.platform===`win32`?t.toLowerCase():t}function G(e){let t=new Map;for(let n of e){let e=U(n.uri);t.set(W(e),e)}return[...t.values()].sort((e,t)=>W(e).localeCompare(W(t)))}function K({config:e,roots:t}){let n=G(t);if(n.length===0)return null;let r=e.sources?.[0]?.path;if(r){let e=W(r),t=n.find(t=>W(t)===e);if(t)return t}return n[0]}function q({config:e,log:t,reconfigureForWorkspace:n,roots:r}){let i=G(r);if(i.length===0)return!1;let a=K({config:e,roots:i.map(e=>({uri:e}))});if(!a)return!1;let o=e.sources?.[0]?.path,s=o&&W(o)===W(a)?`configured-source`:`stable-sorted-root`;return t.debug(`MCP roots resolved`,{rootPath:a,rootCount:i.length,selectedBy:s}),n(e,a),e.allRoots=i,!0}async function J({config:e,indexMode:t,log:n,rootsChangedNotificationSchema:r,reconfigureForWorkspace:i,runInitialIndex:a,server:o,startInit:s,timeoutMs:c=5e3,getCwd:l=()=>process.cwd()}){let u=!1,d=!1,f,m=o.server,h=e=>{let t=p(e),n=`${String(e)} ${String(t.message??``)}`.toLowerCase();return n.includes(`method not found`)||n.includes(`not supported`)||n.includes(`unsupported`)||n.includes(`unknown method`)||n.includes(`roots/list`)},g=()=>{u||(u=!0,s())},_=()=>{d||t!==`auto`||(d=!0,(async()=>{try{await a()}catch(e){n.error(`Initial index failed`,p(e))}})())},v=t=>t.length===0||(f&&=(clearTimeout(f),void 0),!q({config:e,log:n,reconfigureForWorkspace:i,roots:t}))?!1:(g(),_(),!0);try{if(v((await m.listRoots()).roots))return;n.debug(`No MCP roots yet; waiting for roots/list_changed notification`)}catch(e){if(h(e)){n.warn(`MCP roots/list not supported by client; using cwd fallback`,{cwd:l(),...p(e)}),g(),_();return}n.warn(`MCP roots/list failed during bootstrap; waiting for roots/list_changed notification`,{cwd:l(),...p(e)})}m.setNotificationHandler(r,async()=>{try{v((await m.listRoots()).roots)}catch(e){n.warn(`roots/list retry failed after notification`,p(e))}}),f=setTimeout(()=>{let t=l();n.debug(`Timed out waiting for MCP roots/list_changed; falling back to cwd workspace`,{cwd:t}),q({config:e,log:n,reconfigureForWorkspace:i,roots:[{uri:t}]})&&(g(),_())},c)}function Y(){return process.env.AIKIT_TRANSPORT?process.env.AIKIT_TRANSPORT:process.stdin.isTTY?`http`:`stdio`}function X(){let e=process.argv[1];if(!e)return!1;try{return import.meta.url===l(e).href}catch{return!1}}function Z(e){let t=e.headers[`mcp-session-id`];return Array.isArray(t)?t[0]:t}function Q(e,t){let n=process.env[e];if(!n)return t;let r=Number.parseInt(n,10);return Number.isFinite(r)&&r>0?r:t}function $(){return X()?u({allowPositionals:!0,options:{transport:{type:`string`,default:Y()},port:{type:`string`,default:process.env.AIKIT_PORT??`3210`}}}).values:{transport:Y(),port:process.env.AIKIT_PORT??`3210`}}async function ee(){let e=R(),t=$();process.on(`unhandledRejection`,e=>{z.error(`Unhandled rejection`,p(e))}),process.on(`uncaughtException`,e=>{z.error(`Uncaught exception — exiting`,p(e)),process.exit(1)});let r=(e,t)=>{e.then(async()=>{try{let{markPromoteRun:e,markPruneRun:n,prune:r,shouldRunStartupPrune:i,shouldRunWeeklyPromote:a}=await import(`../../tools/dist/index.js`),o=t();if(!o)return;if(i()){let e=await r({});n(),e.totalBytesFreed>0&&z.info(`Storage maintenance complete`,{forgeOrphans:e.forgeGroundOrphans.count,legacyLance:e.legacyLance.count,bytesFreed:e.totalBytesFreed});let{groupLessons:t,pruneLessons:i}=await import(`./evolution-DWaEE6XW.js`).then(e=>e.t),a=await i(o.curated,o.stateStore,{dryRun:!1});a.pruned.length>0&&z.info(`Startup lesson prune complete`,{pruned:a.pruned.length});let s=await t(o.curated,o.stateStore,{dryRun:!1});(s.groupsCreated>0||s.lessonsGrouped>0)&&z.info(`Startup lesson grouping complete`,{groupsCreated:s.groupsCreated,lessonsGrouped:s.lessonsGrouped})}if(a()){let{DEFAULT_PROMOTE_CONFIG:t,collectWorkspaceLessons:n,getGlobalCuratedDir:r,promoteLessons:i,scanForDuplicates:a}=await import(`./promotion-CJFYv4Ye.js`).then(e=>e.o),{CuratedKnowledgeManager:s}=await Promise.resolve().then(()=>N),c=o.curated,l=new s(r(),c.store,c.embedder),u=await n(),d={...t,dryRun:!1},f=await i(a(u,d),l,d);e(),f.promoted.length>0&&z.info(`Weekly lesson promotion complete`,{promoted:f.promoted.length,candidates:f.candidates.length})}}catch(e){z.warn(`Startup maintenance failed (non-critical)`,p(e))}}).catch(()=>{})};if(z.info(`Starting MCP AI Kit server`,{version:e}),t.transport===`http`){let[{default:e},{loadConfig:i,resolveIndexMode:a},{registerDashboardRoutes:o,resolveDashboardDir:s},{registerSettingsRoutes:c,resolveSettingsDir:l},{createSettingsRouter:u},{authMiddleware:d,getOrCreateToken:f}]=await Promise.all([import(`express`),import(`./config-CCrLxwqC.js`),import(`./dashboard-static-CRfR1yKU.js`),import(`./settings-static-B3lnYvcb.js`),import(`./routes-Afg7J7xK.js`),import(`./auth-lzZKfxlV.js`)]),m=i();z.info(`Config loaded`,{sourceCount:m.sources.length,storePath:m.store.path});let h=e();h.use(e.json({limit:`1mb`}));let g=Number(t.port),_=`http://localhost:${g}`,v=process.env.AIKIT_CORS_ORIGIN??_,y=process.env.AIKIT_ALLOW_ANY_ORIGIN===`true`,b=Q(`AIKIT_HTTP_MAX_SESSIONS`,8),x=Q(`AIKIT_HTTP_SESSION_TIMEOUT_MINUTES`,30),S=Q(`AIKIT_HTTP_SESSION_GC_INTERVAL_MINUTES`,5),C=H({limit:100,windowMs:6e4}),w=!1;h.use((e,t,n)=>{let r=Array.isArray(e.headers.origin)?e.headers.origin[0]:e.headers.origin,i=V({requestOrigin:r,configuredOrigin:v,allowAnyOrigin:y,fallbackOrigin:_});if(i.warn&&!w&&(w=!0,z.warn(`Rejected non-local CORS origin while AIKIT_CORS_ORIGIN=*`,{origin:r,allowAnyOriginEnv:`AIKIT_ALLOW_ANY_ORIGIN=true`})),r&&!i.allowOrigin){t.status(403).json({error:`Origin not allowed`});return}if(i.allowOrigin&&t.setHeader(`Access-Control-Allow-Origin`,i.allowOrigin),t.setHeader(`Access-Control-Allow-Methods`,`GET, POST, PUT, PATCH, DELETE, OPTIONS`),t.setHeader(`Access-Control-Allow-Headers`,`Content-Type, Authorization, Mcp-Session-Id, Mcp-Protocol-Version, Last-Event-ID`),t.setHeader(`Access-Control-Expose-Headers`,`Mcp-Session-Id`),e.method===`OPTIONS`){t.status(204).end();return}n()});let T=f();console.error(`[aikit] Auth token: ~/.aikit/token`),h.use(d(T)),h.use(`/mcp`,(e,t,n)=>{let r=Z(e)??e.ip??e.socket.remoteAddress??`anonymous`;if(C.allow(r)){n();return}let i=Math.max(1,Math.ceil(C.getRetryAfterMs(r)/1e3));t.setHeader(`Retry-After`,String(i)),t.status(429).json({jsonrpc:`2.0`,error:{code:-32003,message:`Rate limit exceeded`},id:null})}),o(h,s(),z);let E=new Date().toISOString();h.use(`/settings/api`,u({log:z,mcpInfo:()=>({transport:`http`,port:g,pid:process.pid,startedAt:E})})),c(h,l(),z),h.get(`/health`,(e,t)=>{t.json({status:`ok`})});let D=!1,O=null,A=null,M=null,N=null,P=null,F=null,I=null,L=Promise.resolve(),R=async(e,t)=>{if(!D||!M||!N){t.status(503).json({jsonrpc:`2.0`,error:{code:-32603,message:`Server initializing — please retry in a few seconds`},id:null});return}let r=L,i;L=new Promise(e=>{i=e}),await r;try{let r=Z(e);if(!F){if(r){t.status(404).json({jsonrpc:`2.0`,error:{code:-32001,message:`Session not found`},id:null});return}let e=new N({sessionIdGenerator:()=>n(),onsessioninitialized:async e=>{I=e,A?.onSessionStart(e,{transport:`http`})},onsessionclosed:async e=>{e&&A?.onSessionEnd(e),I=null}});e.onclose=()=>{F===e&&(F=null),I===e.sessionId&&(I=null)},F=e,await M.connect(e)}let i=F;await i.handleRequest(e,t,e.body),e.method!==`DELETE`&&(!r&&i.sessionId?(I=i.sessionId,A?.onSessionStart(i.sessionId,{transport:`http`}),A?.onSessionActivity(i.sessionId)):r&&A?.onSessionActivity(r))}catch(e){if(z.error(`MCP handler error`,p(e)),!t.headersSent){let n=e instanceof Error?e.message:String(e),r=n.includes(`Not Acceptable`);t.status(r?406:500).json({jsonrpc:`2.0`,error:{code:r?-32e3:-32603,message:r?n:`Internal server error`},id:null})}}finally{i()}},B=async(e,t)=>{let n=Z(e);if(P&&(!F||n!==I)){await P.handleRequest(e,t,e.body);return}await R(e,t)};h.post(`/mcp`,B),h.get(`/mcp`,B),h.delete(`/mcp`,B);let U=h.listen(g,`127.0.0.1`,()=>{z.info(`MCP server listening`,{url:`http://127.0.0.1:${g}/mcp`,port:g}),setTimeout(async()=>{try{let[{createLazyServer:e,createMcpServer:t,ALL_TOOL_NAMES:n},{StreamableHTTPServerTransport:i},{checkForUpdates:o,autoUpgradeScaffold:s}]=await Promise.all([import(`./server-Bvyactic.js`),import(`@modelcontextprotocol/sdk/server/streamableHttp.js`),import(`./version-check-gazMo-D4.js`)]);o(),s();let c=a(m),l=e(m,c);M=l.server,N=i,D=!0,z.debug(`MCP server configured (lazy — AI Kit initializing in background)`,{toolCount:n.length,resourceCount:2}),l.startInit(),l.ready.then(()=>{if(!l.aikit)throw Error(`AI Kit components are not available after initialization`);A=new j(l.aikit.stateStore,{staleTimeoutMinutes:x,gcIntervalMinutes:S,onBeforeSessionDelete:e=>{if(I===e&&F){let e=F;F=null,I=null,e.close().catch(()=>void 0)}P?.closeSession(e,{notifySessionEnd:!1})},onSessionEndMaintenance:async()=>{if(!l.aikit?.curated||!l.aikit?.stateStore)return;let{pruneLessons:e}=await import(`./evolution-DWaEE6XW.js`).then(e=>e.t),t=await e(l.aikit.curated,l.aikit.stateStore,{dryRun:!1});t.pruned.length>0&&z.info(`Session-end lesson prune`,{pruned:t.pruned.length})}}),P=new k({createServer:()=>{if(!l.aikit)throw Error(`AI Kit components are not available after initialization`);return t(l.aikit,m)},createTransport:e=>new i(e),maxSessions:b,sessionTimeoutMinutes:x,onSessionStart:e=>A?.onSessionStart(e,{transport:`http`}),onSessionActivity:e=>A?.onSessionActivity(e),onSessionEnd:e=>A?.onSessionEnd(e)}),A.startGC(),I&&(A.onSessionStart(I,{transport:`http`}),A.onSessionActivity(I)),z.info(`HTTP session runtime ready`,{maxSessions:b,sessionTimeoutMinutes:x,gcIntervalMinutes:S})}).catch(e=>z.error(`Failed to start session manager`,p(e))),c===`auto`?l.ready.then(async()=>{try{let e=m.sources.map(e=>e.path).join(`, `);z.info(`Running initial index`,{sourcePaths:e}),await l.runInitialIndex(),z.info(`Initial index complete`)}catch(e){z.error(`Initial index failed; will retry on aikit_reindex`,p(e))}}).catch(e=>z.error(`AI Kit init or indexing failed`,p(e))):c===`smart`?l.ready.then(async()=>{try{if(!l.aikit)throw Error(`AI Kit components are not available after initialization`);let{SmartIndexScheduler:e}=await import(`../../indexer/dist/index.js`),t=new e(l.aikit.indexer,m,l.aikit.store),n=l.aikit.store;O=t,t.start(),n.onBeforeClose&&n.onBeforeClose(()=>t.stop()),l.setSmartScheduler(t),z.debug(`Smart index scheduler started (HTTP mode)`)}catch(e){z.error(`Failed to start smart index scheduler`,p(e))}}).catch(e=>z.error(`AI Kit initialization failed`,p(e))):(l.ready.catch(e=>z.error(`AI Kit initialization failed`,p(e))),z.info(`Initial full indexing skipped in HTTP mode`,{indexMode:c})),r(l.ready,()=>l.aikit?{curated:l.aikit.curated,stateStore:l.aikit.stateStore}:null)}catch(e){z.error(`Failed to load server modules`,p(e))}},100)}),W=async e=>{z.info(`Shutdown signal received`,{signal:e}),O?.stop(),A?.stop(),await P?.closeAll().catch(()=>void 0),I&&A?.onSessionEnd(I),F&&(await F.close().catch(()=>void 0),F=null,I=null),U.close(),M&&await M.close(),process.exit(0)};process.on(`SIGINT`,()=>W(`SIGINT`)),process.on(`SIGTERM`,()=>W(`SIGTERM`))}else{let[{loadConfig:e,reconfigureForWorkspace:t,resolveIndexMode:n},{createLazyServer:i},{checkForUpdates:a,autoUpgradeScaffold:o},{RootsListChangedNotificationSchema:s}]=await Promise.all([import(`./config-CCrLxwqC.js`),import(`./server-Bvyactic.js`),import(`./version-check-gazMo-D4.js`),import(`@modelcontextprotocol/sdk/types.js`)]),c=e();z.info(`Config loaded`,{sourceCount:c.sources.length,storePath:c.store.path}),a(),o();let l=n(c),u=i(c,l),{server:d,startInit:f,ready:m,runInitialIndex:h}=u,{StdioServerTransport:g}=await import(`@modelcontextprotocol/sdk/server/stdio.js`),_=new g;await d.connect(_),z.debug(`MCP server started`,{transport:`stdio`}),await J({config:c,indexMode:l,log:z,rootsChangedNotificationSchema:s,reconfigureForWorkspace:t,runInitialIndex:h,server:d,startInit:f});let v=null,y=()=>{v&&clearTimeout(v),v=setTimeout(async()=>{z.info(`Auto-shutdown: no activity for 30 minutes — shutting down gracefully`);try{let e=u.aikit;e&&await Promise.all([e.embedder.shutdown?.().catch(()=>{})??Promise.resolve(),e.graphStore.close().catch(()=>{}),e.store.close().catch(()=>{})])}catch{}process.exit(0)},18e5),v.unref&&v.unref()};y(),process.stdin.on(`data`,()=>y()),m.catch(e=>{z.error(`Initialization failed — server will continue with limited tools`,p(e))}),l===`smart`?m.then(async()=>{try{if(!u.aikit)throw Error(`AI Kit components are not available after initialization`);let{SmartIndexScheduler:e}=await import(`../../indexer/dist/index.js`),t=new e(u.aikit.indexer,c,u.aikit.store),n=u.aikit.store;t.start(),n.onBeforeClose&&n.onBeforeClose(()=>t.stop()),u.setSmartScheduler(t),z.debug(`Smart index scheduler started (stdio mode)`)}catch(e){z.error(`Failed to start smart index scheduler`,p(e))}}).catch(e=>z.error(`AI Kit init failed for smart scheduler`,p(e))):z.warn(`Initial full indexing skipped; use aikit_reindex to index manually`,{indexMode:l}),r(m,()=>u.aikit?{curated:u.aikit.curated,stateStore:u.aikit.stateStore}:null)}}ee();export{M as n,L as t};
|
|
8
|
+
`),s=!1,c={};for(let e of o){if(/^changelog:\s*$/.test(e)){s=!0;continue}if(s){let t=e.match(/^\s+-\s+version:\s*(\d+)$/);if(t){c.version!=null&&a.push(c),c={version:parseInt(t[1],10)};continue}let n=e.match(/^\s+date:\s*(.+)$/);if(n){c.date=n[1].trim();continue}let r=e.match(/^\s+reason:\s*"?(.*?)"?\s*$/);if(r){c.reason=r[1];continue}/^\w/.test(e)&&(s=!1,c.version!=null&&a.push(c),c={});continue}let t=e.match(/^(\w+):\s*(.*)$/);if(t){let e=t[1],n=t[2];typeof n==`string`&&n.startsWith(`[`)&&n.endsWith(`]`)?n=n.slice(1,-1).split(`,`).map(e=>e.trim().replace(/^"|"$/g,``)).filter(e=>e.length>0):typeof n==`string`&&/^\d+$/.test(n)?n=parseInt(n,10):typeof n==`string`&&n.startsWith(`"`)&&n.endsWith(`"`)&&(n=n.slice(1,-1)),i[e]=n}}return c.version!=null&&a.push(c),{frontmatter:{title:i.title??`Untitled`,category:i.category??`notes`,tags:i.tags??[],created:i.created??``,updated:i.updated??``,version:i.version??1,origin:`curated`,changelog:a},content:r}}};function R(){try{let e=s(i(c(import.meta.url)),`..`,`..`,`..`,`package.json`);return JSON.parse(r(e,`utf-8`)).version??`0.0.0`}catch{return`0.0.0`}}const z=f(`server`),B=/^https?:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/i;function V({requestOrigin:e,configuredOrigin:t,allowAnyOrigin:n,fallbackOrigin:r}){let i=t??r;return i===`*`?n?{allowOrigin:`*`,warn:!1}:e?B.test(e)?{allowOrigin:e,warn:!1}:{allowOrigin:null,warn:!0}:{allowOrigin:r,warn:!1}:{allowOrigin:i,warn:!1}}function H({limit:e,windowMs:t}){let n=new Map,r=(e,r)=>{let i=r-t,a=n.get(e)?.filter(e=>e>i)??[];return a.length===0?(n.delete(e),[]):(n.set(e,a),a)};return{allow(t,i=Date.now()){let a=r(t,i);return a.length>=e?!1:(a.push(i),n.set(t,a),!0)},getRetryAfterMs(n,i=Date.now()){let a=r(n,i);return a.length<e?0:Math.max(0,a[0]+t-i)}}}function U(e){return e.startsWith(`file://`)?c(e):e}function W(e){let t=s(e);return process.platform===`win32`?t.toLowerCase():t}function G(e){let t=new Map;for(let n of e){let e=U(n.uri);t.set(W(e),e)}return[...t.values()].sort((e,t)=>W(e).localeCompare(W(t)))}function K({config:e,roots:t}){let n=G(t);if(n.length===0)return null;let r=e.sources?.[0]?.path;if(r){let e=W(r),t=n.find(t=>W(t)===e);if(t)return t}return n[0]}function q({config:e,log:t,reconfigureForWorkspace:n,roots:r}){let i=G(r);if(i.length===0)return!1;let a=K({config:e,roots:i.map(e=>({uri:e}))});if(!a)return!1;let o=e.sources?.[0]?.path,s=o&&W(o)===W(a)?`configured-source`:`stable-sorted-root`;return t.debug(`MCP roots resolved`,{rootPath:a,rootCount:i.length,selectedBy:s}),n(e,a),e.allRoots=i,!0}async function J({config:e,indexMode:t,log:n,rootsChangedNotificationSchema:r,reconfigureForWorkspace:i,runInitialIndex:a,server:o,startInit:s,timeoutMs:c=5e3,getCwd:l=()=>process.cwd()}){let u=!1,d=!1,f,m=o.server,h=e=>{let t=p(e),n=`${String(e)} ${String(t.message??``)}`.toLowerCase();return n.includes(`method not found`)||n.includes(`not supported`)||n.includes(`unsupported`)||n.includes(`unknown method`)||n.includes(`roots/list`)},g=()=>{u||(u=!0,s())},_=()=>{d||t!==`auto`||(d=!0,(async()=>{try{await a()}catch(e){n.error(`Initial index failed`,p(e))}})())},v=t=>t.length===0||(f&&=(clearTimeout(f),void 0),!q({config:e,log:n,reconfigureForWorkspace:i,roots:t}))?!1:(g(),_(),!0);try{if(v((await m.listRoots()).roots))return;n.debug(`No MCP roots yet; waiting for roots/list_changed notification`)}catch(e){if(h(e)){n.warn(`MCP roots/list not supported by client; using cwd fallback`,{cwd:l(),...p(e)}),g(),_();return}n.warn(`MCP roots/list failed during bootstrap; waiting for roots/list_changed notification`,{cwd:l(),...p(e)})}m.setNotificationHandler(r,async()=>{try{v((await m.listRoots()).roots)}catch(e){n.warn(`roots/list retry failed after notification`,p(e))}}),f=setTimeout(()=>{let t=l();n.debug(`Timed out waiting for MCP roots/list_changed; falling back to cwd workspace`,{cwd:t}),q({config:e,log:n,reconfigureForWorkspace:i,roots:[{uri:t}]})&&(g(),_())},c)}function Y(){return process.env.AIKIT_TRANSPORT?process.env.AIKIT_TRANSPORT:process.stdin.isTTY?`http`:`stdio`}function X(){let e=process.argv[1];if(!e)return!1;try{return import.meta.url===l(e).href}catch{return!1}}function Z(e){let t=e.headers[`mcp-session-id`];return Array.isArray(t)?t[0]:t}function Q(e,t){let n=process.env[e];if(!n)return t;let r=Number.parseInt(n,10);return Number.isFinite(r)&&r>0?r:t}function $(){return X()?u({allowPositionals:!0,options:{transport:{type:`string`,default:Y()},port:{type:`string`,default:process.env.AIKIT_PORT??`3210`}}}).values:{transport:Y(),port:process.env.AIKIT_PORT??`3210`}}async function ee(){let e=R(),t=$();process.on(`unhandledRejection`,e=>{z.error(`Unhandled rejection`,p(e))}),process.on(`uncaughtException`,e=>{z.error(`Uncaught exception — exiting`,p(e)),process.exit(1)});let r=(e,t)=>{e.then(async()=>{try{let{markPromoteRun:e,markPruneRun:n,prune:r,shouldRunStartupPrune:i,shouldRunWeeklyPromote:a}=await import(`../../tools/dist/index.js`),o=t();if(!o)return;if(i()){let e=await r({});n(),e.totalBytesFreed>0&&z.info(`Storage maintenance complete`,{forgeOrphans:e.forgeGroundOrphans.count,legacyLance:e.legacyLance.count,bytesFreed:e.totalBytesFreed});let{groupLessons:t,pruneLessons:i}=await import(`./evolution-DWaEE6XW.js`).then(e=>e.t),a=await i(o.curated,o.stateStore,{dryRun:!1});a.pruned.length>0&&z.info(`Startup lesson prune complete`,{pruned:a.pruned.length});let s=await t(o.curated,o.stateStore,{dryRun:!1});(s.groupsCreated>0||s.lessonsGrouped>0)&&z.info(`Startup lesson grouping complete`,{groupsCreated:s.groupsCreated,lessonsGrouped:s.lessonsGrouped})}if(a()){let{DEFAULT_PROMOTE_CONFIG:t,collectWorkspaceLessons:n,getGlobalCuratedDir:r,promoteLessons:i,scanForDuplicates:a}=await import(`./promotion-CJFYv4Ye.js`).then(e=>e.o),{CuratedKnowledgeManager:s}=await Promise.resolve().then(()=>N),c=o.curated,l=new s(r(),c.store,c.embedder),u=await n(),d={...t,dryRun:!1},f=await i(a(u,d),l,d);e(),f.promoted.length>0&&z.info(`Weekly lesson promotion complete`,{promoted:f.promoted.length,candidates:f.candidates.length})}}catch(e){z.warn(`Startup maintenance failed (non-critical)`,p(e))}}).catch(()=>{})};if(z.info(`Starting MCP AI Kit server`,{version:e}),t.transport===`http`){let[{default:e},{loadConfig:i,resolveIndexMode:a},{registerDashboardRoutes:o,resolveDashboardDir:s},{registerSettingsRoutes:c,resolveSettingsDir:l},{createSettingsRouter:u},{authMiddleware:d,getOrCreateToken:f}]=await Promise.all([import(`express`),import(`./config-CCrLxwqC.js`),import(`./dashboard-static-CRfR1yKU.js`),import(`./settings-static-B3lnYvcb.js`),import(`./routes-Afg7J7xK.js`),import(`./auth-lzZKfxlV.js`)]),m=i();z.info(`Config loaded`,{sourceCount:m.sources.length,storePath:m.store.path});let h=e();h.use(e.json({limit:`1mb`}));let g=Number(t.port),_=`http://localhost:${g}`,v=process.env.AIKIT_CORS_ORIGIN??_,y=process.env.AIKIT_ALLOW_ANY_ORIGIN===`true`,b=Q(`AIKIT_HTTP_MAX_SESSIONS`,8),x=Q(`AIKIT_HTTP_SESSION_TIMEOUT_MINUTES`,30),S=Q(`AIKIT_HTTP_SESSION_GC_INTERVAL_MINUTES`,5),C=H({limit:100,windowMs:6e4}),w=!1;h.use((e,t,n)=>{let r=Array.isArray(e.headers.origin)?e.headers.origin[0]:e.headers.origin,i=V({requestOrigin:r,configuredOrigin:v,allowAnyOrigin:y,fallbackOrigin:_});if(i.warn&&!w&&(w=!0,z.warn(`Rejected non-local CORS origin while AIKIT_CORS_ORIGIN=*`,{origin:r,allowAnyOriginEnv:`AIKIT_ALLOW_ANY_ORIGIN=true`})),r&&!i.allowOrigin){t.status(403).json({error:`Origin not allowed`});return}if(i.allowOrigin&&t.setHeader(`Access-Control-Allow-Origin`,i.allowOrigin),t.setHeader(`Access-Control-Allow-Methods`,`GET, POST, PUT, PATCH, DELETE, OPTIONS`),t.setHeader(`Access-Control-Allow-Headers`,`Content-Type, Authorization, Mcp-Session-Id, Mcp-Protocol-Version, Last-Event-ID`),t.setHeader(`Access-Control-Expose-Headers`,`Mcp-Session-Id`),e.method===`OPTIONS`){t.status(204).end();return}n()});let T=f();console.error(`[aikit] Auth token: ~/.aikit/token`),h.use(d(T)),h.use(`/mcp`,(e,t,n)=>{let r=Z(e)??e.ip??e.socket.remoteAddress??`anonymous`;if(C.allow(r)){n();return}let i=Math.max(1,Math.ceil(C.getRetryAfterMs(r)/1e3));t.setHeader(`Retry-After`,String(i)),t.status(429).json({jsonrpc:`2.0`,error:{code:-32003,message:`Rate limit exceeded`},id:null})}),o(h,s(),z);let E=new Date().toISOString();h.use(`/settings/api`,u({log:z,mcpInfo:()=>({transport:`http`,port:g,pid:process.pid,startedAt:E})})),c(h,l(),z),h.get(`/health`,(e,t)=>{t.json({status:`ok`})});let D=!1,O=null,A=null,M=null,N=null,P=null,F=null,I=null,L=Promise.resolve(),R=async(e,t)=>{if(!D||!M||!N){t.status(503).json({jsonrpc:`2.0`,error:{code:-32603,message:`Server initializing — please retry in a few seconds`},id:null});return}let r=L,i;L=new Promise(e=>{i=e}),await r;try{let r=Z(e);if(!F){if(r){t.status(404).json({jsonrpc:`2.0`,error:{code:-32001,message:`Session not found`},id:null});return}let e=new N({sessionIdGenerator:()=>n(),onsessioninitialized:async e=>{I=e,A?.onSessionStart(e,{transport:`http`})},onsessionclosed:async e=>{e&&A?.onSessionEnd(e),I=null}});e.onclose=()=>{F===e&&(F=null),I===e.sessionId&&(I=null)},F=e,await M.connect(e)}let i=F;await i.handleRequest(e,t,e.body),e.method!==`DELETE`&&(!r&&i.sessionId?(I=i.sessionId,A?.onSessionStart(i.sessionId,{transport:`http`}),A?.onSessionActivity(i.sessionId)):r&&A?.onSessionActivity(r))}catch(e){if(z.error(`MCP handler error`,p(e)),!t.headersSent){let n=e instanceof Error?e.message:String(e),r=n.includes(`Not Acceptable`);t.status(r?406:500).json({jsonrpc:`2.0`,error:{code:r?-32e3:-32603,message:r?n:`Internal server error`},id:null})}}finally{i()}},B=async(e,t)=>{let n=Z(e);if(P&&(!F||n!==I)){await P.handleRequest(e,t,e.body);return}await R(e,t)};h.post(`/mcp`,B),h.get(`/mcp`,B),h.delete(`/mcp`,B);let U=h.listen(g,`127.0.0.1`,()=>{z.info(`MCP server listening`,{url:`http://127.0.0.1:${g}/mcp`,port:g}),setTimeout(async()=>{try{let[{createLazyServer:e,createMcpServer:t,ALL_TOOL_NAMES:n},{StreamableHTTPServerTransport:i},{checkForUpdates:o,autoUpgradeScaffold:s}]=await Promise.all([import(`./server-kAiz3riV.js`),import(`@modelcontextprotocol/sdk/server/streamableHttp.js`),import(`./version-check-gazMo-D4.js`)]);o(),s();let c=a(m),l=e(m,c);M=l.server,N=i,D=!0,z.debug(`MCP server configured (lazy — AI Kit initializing in background)`,{toolCount:n.length,resourceCount:2}),l.startInit(),l.ready.then(()=>{if(!l.aikit)throw Error(`AI Kit components are not available after initialization`);A=new j(l.aikit.stateStore,{staleTimeoutMinutes:x,gcIntervalMinutes:S,onBeforeSessionDelete:e=>{if(I===e&&F){let e=F;F=null,I=null,e.close().catch(()=>void 0)}P?.closeSession(e,{notifySessionEnd:!1})},onSessionEndMaintenance:async()=>{if(!l.aikit?.curated||!l.aikit?.stateStore)return;let{pruneLessons:e}=await import(`./evolution-DWaEE6XW.js`).then(e=>e.t),t=await e(l.aikit.curated,l.aikit.stateStore,{dryRun:!1});t.pruned.length>0&&z.info(`Session-end lesson prune`,{pruned:t.pruned.length})}}),P=new k({createServer:()=>{if(!l.aikit)throw Error(`AI Kit components are not available after initialization`);return t(l.aikit,m)},createTransport:e=>new i(e),maxSessions:b,sessionTimeoutMinutes:x,onSessionStart:e=>A?.onSessionStart(e,{transport:`http`}),onSessionActivity:e=>A?.onSessionActivity(e),onSessionEnd:e=>A?.onSessionEnd(e)}),A.startGC(),I&&(A.onSessionStart(I,{transport:`http`}),A.onSessionActivity(I)),z.info(`HTTP session runtime ready`,{maxSessions:b,sessionTimeoutMinutes:x,gcIntervalMinutes:S})}).catch(e=>z.error(`Failed to start session manager`,p(e))),c===`auto`?l.ready.then(async()=>{try{let e=m.sources.map(e=>e.path).join(`, `);z.info(`Running initial index`,{sourcePaths:e}),await l.runInitialIndex(),z.info(`Initial index complete`)}catch(e){z.error(`Initial index failed; will retry on aikit_reindex`,p(e))}}).catch(e=>z.error(`AI Kit init or indexing failed`,p(e))):c===`smart`?l.ready.then(async()=>{try{if(!l.aikit)throw Error(`AI Kit components are not available after initialization`);let{SmartIndexScheduler:e}=await import(`../../indexer/dist/index.js`),t=new e(l.aikit.indexer,m,l.aikit.store),n=l.aikit.store;O=t,t.start(),n.onBeforeClose&&n.onBeforeClose(()=>t.stop()),l.setSmartScheduler(t),z.debug(`Smart index scheduler started (HTTP mode)`)}catch(e){z.error(`Failed to start smart index scheduler`,p(e))}}).catch(e=>z.error(`AI Kit initialization failed`,p(e))):(l.ready.catch(e=>z.error(`AI Kit initialization failed`,p(e))),z.info(`Initial full indexing skipped in HTTP mode`,{indexMode:c})),r(l.ready,()=>l.aikit?{curated:l.aikit.curated,stateStore:l.aikit.stateStore}:null)}catch(e){z.error(`Failed to load server modules`,p(e))}},100)}),W=async e=>{z.info(`Shutdown signal received`,{signal:e}),O?.stop(),A?.stop(),await P?.closeAll().catch(()=>void 0),I&&A?.onSessionEnd(I),F&&(await F.close().catch(()=>void 0),F=null,I=null),U.close(),M&&await M.close(),process.exit(0)};process.on(`SIGINT`,()=>W(`SIGINT`)),process.on(`SIGTERM`,()=>W(`SIGTERM`))}else{let[{loadConfig:e,reconfigureForWorkspace:t,resolveIndexMode:n},{createLazyServer:i},{checkForUpdates:a,autoUpgradeScaffold:o},{RootsListChangedNotificationSchema:s}]=await Promise.all([import(`./config-CCrLxwqC.js`),import(`./server-kAiz3riV.js`),import(`./version-check-gazMo-D4.js`),import(`@modelcontextprotocol/sdk/types.js`)]),c=e();z.info(`Config loaded`,{sourceCount:c.sources.length,storePath:c.store.path}),a(),o();let l=n(c),u=i(c,l),{server:d,startInit:f,ready:m,runInitialIndex:h}=u,{StdioServerTransport:g}=await import(`@modelcontextprotocol/sdk/server/stdio.js`),_=new g;await d.connect(_),z.debug(`MCP server started`,{transport:`stdio`}),await J({config:c,indexMode:l,log:z,rootsChangedNotificationSchema:s,reconfigureForWorkspace:t,runInitialIndex:h,server:d,startInit:f});let v=null,y=()=>{v&&clearTimeout(v),v=setTimeout(async()=>{z.info(`Auto-shutdown: no activity for 30 minutes — shutting down gracefully`);try{let e=u.aikit;e&&await Promise.all([e.embedder.shutdown?.().catch(()=>{})??Promise.resolve(),e.graphStore.close().catch(()=>{}),e.store.close().catch(()=>{})])}catch{}process.exit(0)},18e5),v.unref&&v.unref()};y(),process.stdin.on(`data`,()=>y()),m.catch(e=>{z.error(`Initialization failed — server will continue with limited tools`,p(e))}),l===`smart`?m.then(async()=>{try{if(!u.aikit)throw Error(`AI Kit components are not available after initialization`);let{SmartIndexScheduler:e}=await import(`../../indexer/dist/index.js`),t=new e(u.aikit.indexer,c,u.aikit.store),n=u.aikit.store;t.start(),n.onBeforeClose&&n.onBeforeClose(()=>t.stop()),u.setSmartScheduler(t),z.debug(`Smart index scheduler started (stdio mode)`)}catch(e){z.error(`Failed to start smart index scheduler`,p(e))}}).catch(e=>z.error(`AI Kit init failed for smart scheduler`,p(e))):z.warn(`Initial full indexing skipped; use aikit_reindex to index manually`,{indexMode:l}),r(m,()=>u.aikit?{curated:u.aikit.curated,stateStore:u.aikit.stateStore}:null)}}ee();export{M as n,L as t};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{t as e}from"./curated-manager-xTfPLFMR.js";import{randomUUID as t}from"node:crypto";import{readFileSync as n}from"node:fs";import{dirname as r,resolve as i}from"node:path";import{fileURLToPath as a,pathToFileURL as o}from"node:url";import{parseArgs as s}from"node:util";import{createLogger as c,serializeError as l}from"../../core/dist/index.js";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 n=this.now(),r=await this.options.createServer(),i={id:`${u}${t()}`,transport:void 0,createdAt:n,lastAccessAt:n,server:r,requestChain:Promise.resolve()},a=this.options.createTransport({sessionIdGenerator:()=>t(),onsessioninitialized:async e=>{this.runtimes.delete(i.id),i.id=e,this.runtimes.set(e,i),this.options.onSessionStart?.(e)},onsessionclosed:async e=>{e&&await this.closeSession(e,{closeTransport:!1})}});return i.transport=a,a.onclose=()=>{let e=i.transport.sessionId??i.id;this.closeSession(e,{closeTransport:!1})},this.runtimes.set(i.id,i),await r.connect(a),i}async withRuntimeLock(e,t){let n=e.requestChain,r;e.requestChain=new Promise(e=>{r=e}),await n;try{await t()}finally{r()}}};function 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)}};function _(){try{let e=i(r(a(import.meta.url)),`..`,`..`,`..`,`package.json`);return JSON.parse(n(e,`utf-8`)).version??`0.0.0`}catch{return`0.0.0`}}const v=c(`server`),y=/^https?:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/i;function b({requestOrigin:e,configuredOrigin:t,allowAnyOrigin:n,fallbackOrigin:r}){let i=t??r;return i===`*`?n?{allowOrigin:`*`,warn:!1}:e?y.test(e)?{allowOrigin:e,warn:!1}:{allowOrigin:null,warn:!0}:{allowOrigin:r,warn:!1}:{allowOrigin:i,warn:!1}}function x({limit:e,windowMs:t}){let n=new Map,r=(e,r)=>{let i=r-t,a=n.get(e)?.filter(e=>e>i)??[];return a.length===0?(n.delete(e),[]):(n.set(e,a),a)};return{allow(t,i=Date.now()){let a=r(t,i);return a.length>=e?!1:(a.push(i),n.set(t,a),!0)},getRetryAfterMs(n,i=Date.now()){let a=r(n,i);return a.length<e?0:Math.max(0,a[0]+t-i)}}}function S(e){return e.startsWith(`file://`)?a(e):e}function C(e){let t=i(e);return process.platform===`win32`?t.toLowerCase():t}function w(e){let t=new Map;for(let n of e){let e=S(n.uri);t.set(C(e),e)}return[...t.values()].sort((e,t)=>C(e).localeCompare(C(t)))}function T({config:e,roots:t}){let n=w(t);if(n.length===0)return null;let r=e.sources?.[0]?.path;if(r){let e=C(r),t=n.find(t=>C(t)===e);if(t)return t}return n[0]}function E({config:e,log:t,reconfigureForWorkspace:n,roots:r}){let i=w(r);if(i.length===0)return!1;let a=T({config:e,roots:i.map(e=>({uri:e}))});if(!a)return!1;let o=e.sources?.[0]?.path,s=o&&C(o)===C(a)?`configured-source`:`stable-sorted-root`;return t.debug(`MCP roots resolved`,{rootPath:a,rootCount:i.length,selectedBy:s}),n(e,a),e.allRoots=i,!0}async function D({config:e,indexMode:t,log:n,rootsChangedNotificationSchema:r,reconfigureForWorkspace:i,runInitialIndex:a,server:o,startInit:s,timeoutMs:c=5e3,getCwd:u=()=>process.cwd()}){let d=!1,f=!1,p,m=o.server,h=e=>{let t=l(e),n=`${String(e)} ${String(t.message??``)}`.toLowerCase();return n.includes(`method not found`)||n.includes(`not supported`)||n.includes(`unsupported`)||n.includes(`unknown method`)||n.includes(`roots/list`)},g=()=>{d||(d=!0,s())},_=()=>{f||t!==`auto`||(f=!0,(async()=>{try{await a()}catch(e){n.error(`Initial index failed`,l(e))}})())},v=t=>t.length===0||(p&&=(clearTimeout(p),void 0),!E({config:e,log:n,reconfigureForWorkspace:i,roots:t}))?!1:(g(),_(),!0);try{if(v((await m.listRoots()).roots))return;n.debug(`No MCP roots yet; waiting for roots/list_changed notification`)}catch(e){if(h(e)){n.warn(`MCP roots/list not supported by client; using cwd fallback`,{cwd:u(),...l(e)}),g(),_();return}n.warn(`MCP roots/list failed during bootstrap; waiting for roots/list_changed notification`,{cwd:u(),...l(e)})}m.setNotificationHandler(r,async()=>{try{v((await m.listRoots()).roots)}catch(e){n.warn(`roots/list retry failed after notification`,l(e))}}),p=setTimeout(()=>{let t=u();n.debug(`Timed out waiting for MCP roots/list_changed; falling back to cwd workspace`,{cwd:t}),E({config:e,log:n,reconfigureForWorkspace:i,roots:[{uri:t}]})&&(g(),_())},c)}function O(){return process.env.AIKIT_TRANSPORT?process.env.AIKIT_TRANSPORT:process.stdin.isTTY?`http`:`stdio`}function k(){let e=process.argv[1];if(!e)return!1;try{return import.meta.url===o(e).href}catch{return!1}}function A(e){let t=e.headers[`mcp-session-id`];return Array.isArray(t)?t[0]:t}function j(e,t){let n=process.env[e];if(!n)return t;let r=Number.parseInt(n,10);return Number.isFinite(r)&&r>0?r:t}function M(){return k()?s({allowPositionals:!0,options:{transport:{type:`string`,default:O()},port:{type:`string`,default:process.env.AIKIT_PORT??`3210`}}}).values:{transport:O(),port:process.env.AIKIT_PORT??`3210`}}async function N(){let e=_(),n=M();process.on(`unhandledRejection`,e=>{v.error(`Unhandled rejection`,l(e))}),process.on(`uncaughtException`,e=>{v.error(`Uncaught exception — exiting`,l(e)),process.exit(1)});let r=(e,t)=>{e.then(async()=>{try{let{markPromoteRun:e,markPruneRun:n,prune:r,shouldRunStartupPrune:i,shouldRunWeeklyPromote:a}=await import(`../../tools/dist/index.js`),o=t();if(!o)return;if(i()){let e=await r({});n(),e.totalBytesFreed>0&&v.info(`Storage maintenance complete`,{forgeOrphans:e.forgeGroundOrphans.count,legacyLance:e.legacyLance.count,bytesFreed:e.totalBytesFreed});let{groupLessons:t,pruneLessons:i}=await import(`./evolution-BX_zTSdj.js`).then(e=>e.t),a=await i(o.curated,o.stateStore,{dryRun:!1});a.pruned.length>0&&v.info(`Startup lesson prune complete`,{pruned:a.pruned.length});let s=await t(o.curated,o.stateStore,{dryRun:!1});(s.groupsCreated>0||s.lessonsGrouped>0)&&v.info(`Startup lesson grouping complete`,{groupsCreated:s.groupsCreated,lessonsGrouped:s.lessonsGrouped})}if(a()){let{DEFAULT_PROMOTE_CONFIG:t,collectWorkspaceLessons:n,getGlobalCuratedDir:r,promoteLessons:i,scanForDuplicates:a}=await import(`./promotion-PdKQQktE.js`).then(e=>e.o),{CuratedKnowledgeManager:s}=await import(`./curated-manager-xTfPLFMR.js`).then(e=>e.n),c=o.curated,l=new s(r(),c.store,c.embedder),u=await n(),d={...t,dryRun:!1},f=await i(a(u,d),l,d);e(),f.promoted.length>0&&v.info(`Weekly lesson promotion complete`,{promoted:f.promoted.length,candidates:f.candidates.length})}}catch(e){v.warn(`Startup maintenance failed (non-critical)`,l(e))}}).catch(()=>{})};if(v.info(`Starting MCP AI Kit server`,{version:e}),n.transport===`http`){let[{default:e},{loadConfig:i,resolveIndexMode:a},{registerDashboardRoutes:o,resolveDashboardDir:s},{registerSettingsRoutes:c,resolveSettingsDir:u},{createSettingsRouter:d},{authMiddleware:f,getOrCreateToken:p}]=await Promise.all([import(`express`),import(`./config-D_MQ_9Q7.js`),import(`./dashboard-static-FmfoS46e.js`),import(`./settings-static-BtvyIrza.js`),import(`./routes-CR3fI-HJ.js`),import(`./auth-Bz5dmZgR.js`).then(e=>e.t)]),h=i();v.info(`Config loaded`,{sourceCount:h.sources.length,storePath:h.store.path});let _=e();_.use(e.json({limit:`1mb`}));let y=Number(n.port),S=`http://localhost:${y}`,C=process.env.AIKIT_CORS_ORIGIN??S,w=process.env.AIKIT_ALLOW_ANY_ORIGIN===`true`,T=j(`AIKIT_HTTP_MAX_SESSIONS`,8),E=j(`AIKIT_HTTP_SESSION_TIMEOUT_MINUTES`,30),D=j(`AIKIT_HTTP_SESSION_GC_INTERVAL_MINUTES`,5),O=x({limit:100,windowMs:6e4}),k=!1;_.use((e,t,n)=>{let r=Array.isArray(e.headers.origin)?e.headers.origin[0]:e.headers.origin,i=b({requestOrigin:r,configuredOrigin:C,allowAnyOrigin:w,fallbackOrigin:S});if(i.warn&&!k&&(k=!0,v.warn(`Rejected non-local CORS origin while AIKIT_CORS_ORIGIN=*`,{origin:r,allowAnyOriginEnv:`AIKIT_ALLOW_ANY_ORIGIN=true`})),r&&!i.allowOrigin){t.status(403).json({error:`Origin not allowed`});return}if(i.allowOrigin&&t.setHeader(`Access-Control-Allow-Origin`,i.allowOrigin),t.setHeader(`Access-Control-Allow-Methods`,`GET, POST, PUT, PATCH, DELETE, OPTIONS`),t.setHeader(`Access-Control-Allow-Headers`,`Content-Type, Authorization, Mcp-Session-Id, Mcp-Protocol-Version, Last-Event-ID`),t.setHeader(`Access-Control-Expose-Headers`,`Mcp-Session-Id`),e.method===`OPTIONS`){t.status(204).end();return}n()});let M=p();console.error(`[aikit] Auth token: ~/.aikit/token`),_.use(f(M)),_.use(`/mcp`,(e,t,n)=>{let r=A(e)??e.ip??e.socket.remoteAddress??`anonymous`;if(O.allow(r)){n();return}let i=Math.max(1,Math.ceil(O.getRetryAfterMs(r)/1e3));t.setHeader(`Retry-After`,String(i)),t.status(429).json({jsonrpc:`2.0`,error:{code:-32003,message:`Rate limit exceeded`},id:null})}),o(_,s(),v);let N=new Date().toISOString();_.use(`/settings/api`,d({log:v,mcpInfo:()=>({transport:`http`,port:y,pid:process.pid,startedAt:N})})),c(_,u(),v),_.get(`/health`,(e,t)=>{t.json({status:`ok`})});let P=!1,F=null,I=null,L=null,R=null,z=null,B=null,V=null,H=Promise.resolve(),U=async(e,n)=>{if(!P||!L||!R){n.status(503).json({jsonrpc:`2.0`,error:{code:-32603,message:`Server initializing — please retry in a few seconds`},id:null});return}let r=H,i;H=new Promise(e=>{i=e}),await r;try{let r=A(e);if(!B){if(r){n.status(404).json({jsonrpc:`2.0`,error:{code:-32001,message:`Session not found`},id:null});return}let e=new R({sessionIdGenerator:()=>t(),onsessioninitialized:async e=>{V=e,I?.onSessionStart(e,{transport:`http`})},onsessionclosed:async e=>{e&&I?.onSessionEnd(e),V=null}});e.onclose=()=>{B===e&&(B=null),V===e.sessionId&&(V=null)},B=e,await L.connect(e)}let i=B;await i.handleRequest(e,n,e.body),e.method!==`DELETE`&&(!r&&i.sessionId?(V=i.sessionId,I?.onSessionStart(i.sessionId,{transport:`http`}),I?.onSessionActivity(i.sessionId)):r&&I?.onSessionActivity(r))}catch(e){if(v.error(`MCP handler error`,l(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()}},W=async(e,t)=>{let n=A(e);if(z&&(!B||n!==V)){await z.handleRequest(e,t,e.body);return}await U(e,t)};_.post(`/mcp`,W),_.get(`/mcp`,W),_.delete(`/mcp`,W);let G=_.listen(y,`127.0.0.1`,()=>{v.info(`MCP server listening`,{url:`http://127.0.0.1:${y}/mcp`,port:y}),setTimeout(async()=>{try{let[{createLazyServer:e,createMcpServer:t,ALL_TOOL_NAMES:n},{StreamableHTTPServerTransport:i},{checkForUpdates:o,autoUpgradeScaffold:s}]=await Promise.all([import(`./server-foPKRLfz.js`),import(`@modelcontextprotocol/sdk/server/streamableHttp.js`),import(`./version-check-BgHzxxCW.js`)]);o(),s();let c=a(h),u=e(h,c);L=u.server,R=i,P=!0,v.debug(`MCP server configured (lazy — AI Kit initializing in background)`,{toolCount:n.length,resourceCount:2}),u.startInit(),u.ready.then(()=>{if(!u.aikit)throw Error(`AI Kit components are not available after initialization`);I=new g(u.aikit.stateStore,{staleTimeoutMinutes:E,gcIntervalMinutes:D,onBeforeSessionDelete:e=>{if(V===e&&B){let e=B;B=null,V=null,e.close().catch(()=>void 0)}z?.closeSession(e,{notifySessionEnd:!1})},onSessionEndMaintenance:async()=>{if(!u.aikit?.curated||!u.aikit?.stateStore)return;let{pruneLessons:e}=await import(`./evolution-BX_zTSdj.js`).then(e=>e.t),t=await e(u.aikit.curated,u.aikit.stateStore,{dryRun:!1});t.pruned.length>0&&v.info(`Session-end lesson prune`,{pruned:t.pruned.length})}}),z=new m({createServer:()=>{if(!u.aikit)throw Error(`AI Kit components are not available after initialization`);return t(u.aikit,h)},createTransport:e=>new i(e),maxSessions:T,sessionTimeoutMinutes:E,onSessionStart:e=>I?.onSessionStart(e,{transport:`http`}),onSessionActivity:e=>I?.onSessionActivity(e),onSessionEnd:e=>I?.onSessionEnd(e)}),I.startGC(),V&&(I.onSessionStart(V,{transport:`http`}),I.onSessionActivity(V)),v.info(`HTTP session runtime ready`,{maxSessions:T,sessionTimeoutMinutes:E,gcIntervalMinutes:D})}).catch(e=>v.error(`Failed to start session manager`,l(e))),c===`auto`?u.ready.then(async()=>{try{let e=h.sources.map(e=>e.path).join(`, `);v.info(`Running initial index`,{sourcePaths:e}),await u.runInitialIndex(),v.info(`Initial index complete`)}catch(e){v.error(`Initial index failed; will retry on aikit_reindex`,l(e))}}).catch(e=>v.error(`AI Kit init or indexing failed`,l(e))):c===`smart`?u.ready.then(async()=>{try{if(!u.aikit)throw Error(`AI Kit components are not available after initialization`);let{SmartIndexScheduler:e}=await import(`../../indexer/dist/index.js`),t=new e(u.aikit.indexer,h,u.aikit.store),n=u.aikit.store;F=t,t.start(),n.onBeforeClose&&n.onBeforeClose(()=>t.stop()),u.setSmartScheduler(t),v.debug(`Smart index scheduler started (HTTP mode)`)}catch(e){v.error(`Failed to start smart index scheduler`,l(e))}}).catch(e=>v.error(`AI Kit initialization failed`,l(e))):(u.ready.catch(e=>v.error(`AI Kit initialization failed`,l(e))),v.info(`Initial full indexing skipped in HTTP mode`,{indexMode:c})),r(u.ready,()=>u.aikit?{curated:u.aikit.curated,stateStore:u.aikit.stateStore}:null)}catch(e){v.error(`Failed to load server modules`,l(e))}},100)}),K=async e=>{v.info(`Shutdown signal received`,{signal:e}),F?.stop(),I?.stop(),await z?.closeAll().catch(()=>void 0),V&&I?.onSessionEnd(V),B&&(await B.close().catch(()=>void 0),B=null,V=null),G.close(),L&&await L.close(),process.exit(0)};process.on(`SIGINT`,()=>K(`SIGINT`)),process.on(`SIGTERM`,()=>K(`SIGTERM`))}else{let[{loadConfig:e,reconfigureForWorkspace:t,resolveIndexMode:n},{createLazyServer:i},{checkForUpdates:a,autoUpgradeScaffold:o},{RootsListChangedNotificationSchema:s}]=await Promise.all([import(`./config-D_MQ_9Q7.js`),import(`./server-foPKRLfz.js`),import(`./version-check-BgHzxxCW.js`),import(`@modelcontextprotocol/sdk/types.js`)]),c=e();v.info(`Config loaded`,{sourceCount:c.sources.length,storePath:c.store.path}),a(),o();let u=n(c),d=i(c,u),{server:f,startInit:p,ready:m,runInitialIndex:h}=d,{StdioServerTransport:g}=await import(`@modelcontextprotocol/sdk/server/stdio.js`),_=new g;await f.connect(_),v.debug(`MCP server started`,{transport:`stdio`}),await D({config:c,indexMode:u,log:v,rootsChangedNotificationSchema:s,reconfigureForWorkspace:t,runInitialIndex:h,server:f,startInit:p});let y=null,b=()=>{y&&clearTimeout(y),y=setTimeout(async()=>{v.info(`Auto-shutdown: no activity for 30 minutes — shutting down gracefully`);try{let e=d.aikit;e&&await Promise.all([e.embedder.shutdown?.().catch(()=>{})??Promise.resolve(),e.graphStore.close().catch(()=>{}),e.store.close().catch(()=>{})])}catch{}process.exit(0)},18e5),y.unref&&y.unref()};b(),process.stdin.on(`data`,()=>b()),m.catch(e=>{v.error(`Initialization failed — server will continue with limited tools`,l(e))}),u===`smart`?m.then(async()=>{try{if(!d.aikit)throw Error(`AI Kit components are not available after initialization`);let{SmartIndexScheduler:e}=await import(`../../indexer/dist/index.js`),t=new e(d.aikit.indexer,c,d.aikit.store),n=d.aikit.store;t.start(),n.onBeforeClose&&n.onBeforeClose(()=>t.stop()),d.setSmartScheduler(t),v.debug(`Smart index scheduler started (stdio mode)`)}catch(e){v.error(`Failed to start smart index scheduler`,l(e))}}).catch(e=>v.error(`AI Kit init failed for smart scheduler`,l(e))):v.warn(`Initial full indexing skipped; use aikit_reindex to index manually`,{indexMode:u}),r(m,()=>d.aikit?{curated:d.aikit.curated,stateStore:d.aikit.stateStore}:null)}}export{e as CuratedKnowledgeManager,E as applyWorkspaceRoots,D as bootstrapWorkspaceRoots,x as createSlidingWindowRateLimiter,N as main,b as resolveCorsOrigin,T as selectWorkspaceRoot};
|
|
1
|
+
import{t as e}from"./curated-manager-xTfPLFMR.js";import{randomUUID as t}from"node:crypto";import{readFileSync as n}from"node:fs";import{dirname as r,resolve as i}from"node:path";import{fileURLToPath as a,pathToFileURL as o}from"node:url";import{parseArgs as s}from"node:util";import{createLogger as c,serializeError as l}from"../../core/dist/index.js";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 n=this.now(),r=await this.options.createServer(),i={id:`${u}${t()}`,transport:void 0,createdAt:n,lastAccessAt:n,server:r,requestChain:Promise.resolve()},a=this.options.createTransport({sessionIdGenerator:()=>t(),onsessioninitialized:async e=>{this.runtimes.delete(i.id),i.id=e,this.runtimes.set(e,i),this.options.onSessionStart?.(e)},onsessionclosed:async e=>{e&&await this.closeSession(e,{closeTransport:!1})}});return i.transport=a,a.onclose=()=>{let e=i.transport.sessionId??i.id;this.closeSession(e,{closeTransport:!1})},this.runtimes.set(i.id,i),await r.connect(a),i}async withRuntimeLock(e,t){let n=e.requestChain,r;e.requestChain=new Promise(e=>{r=e}),await n;try{await t()}finally{r()}}};function 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)}};function _(){try{let e=i(r(a(import.meta.url)),`..`,`..`,`..`,`package.json`);return JSON.parse(n(e,`utf-8`)).version??`0.0.0`}catch{return`0.0.0`}}const v=c(`server`),y=/^https?:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/i;function b({requestOrigin:e,configuredOrigin:t,allowAnyOrigin:n,fallbackOrigin:r}){let i=t??r;return i===`*`?n?{allowOrigin:`*`,warn:!1}:e?y.test(e)?{allowOrigin:e,warn:!1}:{allowOrigin:null,warn:!0}:{allowOrigin:r,warn:!1}:{allowOrigin:i,warn:!1}}function x({limit:e,windowMs:t}){let n=new Map,r=(e,r)=>{let i=r-t,a=n.get(e)?.filter(e=>e>i)??[];return a.length===0?(n.delete(e),[]):(n.set(e,a),a)};return{allow(t,i=Date.now()){let a=r(t,i);return a.length>=e?!1:(a.push(i),n.set(t,a),!0)},getRetryAfterMs(n,i=Date.now()){let a=r(n,i);return a.length<e?0:Math.max(0,a[0]+t-i)}}}function S(e){return e.startsWith(`file://`)?a(e):e}function C(e){let t=i(e);return process.platform===`win32`?t.toLowerCase():t}function w(e){let t=new Map;for(let n of e){let e=S(n.uri);t.set(C(e),e)}return[...t.values()].sort((e,t)=>C(e).localeCompare(C(t)))}function T({config:e,roots:t}){let n=w(t);if(n.length===0)return null;let r=e.sources?.[0]?.path;if(r){let e=C(r),t=n.find(t=>C(t)===e);if(t)return t}return n[0]}function E({config:e,log:t,reconfigureForWorkspace:n,roots:r}){let i=w(r);if(i.length===0)return!1;let a=T({config:e,roots:i.map(e=>({uri:e}))});if(!a)return!1;let o=e.sources?.[0]?.path,s=o&&C(o)===C(a)?`configured-source`:`stable-sorted-root`;return t.debug(`MCP roots resolved`,{rootPath:a,rootCount:i.length,selectedBy:s}),n(e,a),e.allRoots=i,!0}async function D({config:e,indexMode:t,log:n,rootsChangedNotificationSchema:r,reconfigureForWorkspace:i,runInitialIndex:a,server:o,startInit:s,timeoutMs:c=5e3,getCwd:u=()=>process.cwd()}){let d=!1,f=!1,p,m=o.server,h=e=>{let t=l(e),n=`${String(e)} ${String(t.message??``)}`.toLowerCase();return n.includes(`method not found`)||n.includes(`not supported`)||n.includes(`unsupported`)||n.includes(`unknown method`)||n.includes(`roots/list`)},g=()=>{d||(d=!0,s())},_=()=>{f||t!==`auto`||(f=!0,(async()=>{try{await a()}catch(e){n.error(`Initial index failed`,l(e))}})())},v=t=>t.length===0||(p&&=(clearTimeout(p),void 0),!E({config:e,log:n,reconfigureForWorkspace:i,roots:t}))?!1:(g(),_(),!0);try{if(v((await m.listRoots()).roots))return;n.debug(`No MCP roots yet; waiting for roots/list_changed notification`)}catch(e){if(h(e)){n.warn(`MCP roots/list not supported by client; using cwd fallback`,{cwd:u(),...l(e)}),g(),_();return}n.warn(`MCP roots/list failed during bootstrap; waiting for roots/list_changed notification`,{cwd:u(),...l(e)})}m.setNotificationHandler(r,async()=>{try{v((await m.listRoots()).roots)}catch(e){n.warn(`roots/list retry failed after notification`,l(e))}}),p=setTimeout(()=>{let t=u();n.debug(`Timed out waiting for MCP roots/list_changed; falling back to cwd workspace`,{cwd:t}),E({config:e,log:n,reconfigureForWorkspace:i,roots:[{uri:t}]})&&(g(),_())},c)}function O(){return process.env.AIKIT_TRANSPORT?process.env.AIKIT_TRANSPORT:process.stdin.isTTY?`http`:`stdio`}function k(){let e=process.argv[1];if(!e)return!1;try{return import.meta.url===o(e).href}catch{return!1}}function A(e){let t=e.headers[`mcp-session-id`];return Array.isArray(t)?t[0]:t}function j(e,t){let n=process.env[e];if(!n)return t;let r=Number.parseInt(n,10);return Number.isFinite(r)&&r>0?r:t}function M(){return k()?s({allowPositionals:!0,options:{transport:{type:`string`,default:O()},port:{type:`string`,default:process.env.AIKIT_PORT??`3210`}}}).values:{transport:O(),port:process.env.AIKIT_PORT??`3210`}}async function N(){let e=_(),n=M();process.on(`unhandledRejection`,e=>{v.error(`Unhandled rejection`,l(e))}),process.on(`uncaughtException`,e=>{v.error(`Uncaught exception — exiting`,l(e)),process.exit(1)});let r=(e,t)=>{e.then(async()=>{try{let{markPromoteRun:e,markPruneRun:n,prune:r,shouldRunStartupPrune:i,shouldRunWeeklyPromote:a}=await import(`../../tools/dist/index.js`),o=t();if(!o)return;if(i()){let e=await r({});n(),e.totalBytesFreed>0&&v.info(`Storage maintenance complete`,{forgeOrphans:e.forgeGroundOrphans.count,legacyLance:e.legacyLance.count,bytesFreed:e.totalBytesFreed});let{groupLessons:t,pruneLessons:i}=await import(`./evolution-BX_zTSdj.js`).then(e=>e.t),a=await i(o.curated,o.stateStore,{dryRun:!1});a.pruned.length>0&&v.info(`Startup lesson prune complete`,{pruned:a.pruned.length});let s=await t(o.curated,o.stateStore,{dryRun:!1});(s.groupsCreated>0||s.lessonsGrouped>0)&&v.info(`Startup lesson grouping complete`,{groupsCreated:s.groupsCreated,lessonsGrouped:s.lessonsGrouped})}if(a()){let{DEFAULT_PROMOTE_CONFIG:t,collectWorkspaceLessons:n,getGlobalCuratedDir:r,promoteLessons:i,scanForDuplicates:a}=await import(`./promotion-PdKQQktE.js`).then(e=>e.o),{CuratedKnowledgeManager:s}=await import(`./curated-manager-xTfPLFMR.js`).then(e=>e.n),c=o.curated,l=new s(r(),c.store,c.embedder),u=await n(),d={...t,dryRun:!1},f=await i(a(u,d),l,d);e(),f.promoted.length>0&&v.info(`Weekly lesson promotion complete`,{promoted:f.promoted.length,candidates:f.candidates.length})}}catch(e){v.warn(`Startup maintenance failed (non-critical)`,l(e))}}).catch(()=>{})};if(v.info(`Starting MCP AI Kit server`,{version:e}),n.transport===`http`){let[{default:e},{loadConfig:i,resolveIndexMode:a},{registerDashboardRoutes:o,resolveDashboardDir:s},{registerSettingsRoutes:c,resolveSettingsDir:u},{createSettingsRouter:d},{authMiddleware:f,getOrCreateToken:p}]=await Promise.all([import(`express`),import(`./config-D_MQ_9Q7.js`),import(`./dashboard-static-FmfoS46e.js`),import(`./settings-static-BtvyIrza.js`),import(`./routes-CR3fI-HJ.js`),import(`./auth-Bz5dmZgR.js`).then(e=>e.t)]),h=i();v.info(`Config loaded`,{sourceCount:h.sources.length,storePath:h.store.path});let _=e();_.use(e.json({limit:`1mb`}));let y=Number(n.port),S=`http://localhost:${y}`,C=process.env.AIKIT_CORS_ORIGIN??S,w=process.env.AIKIT_ALLOW_ANY_ORIGIN===`true`,T=j(`AIKIT_HTTP_MAX_SESSIONS`,8),E=j(`AIKIT_HTTP_SESSION_TIMEOUT_MINUTES`,30),D=j(`AIKIT_HTTP_SESSION_GC_INTERVAL_MINUTES`,5),O=x({limit:100,windowMs:6e4}),k=!1;_.use((e,t,n)=>{let r=Array.isArray(e.headers.origin)?e.headers.origin[0]:e.headers.origin,i=b({requestOrigin:r,configuredOrigin:C,allowAnyOrigin:w,fallbackOrigin:S});if(i.warn&&!k&&(k=!0,v.warn(`Rejected non-local CORS origin while AIKIT_CORS_ORIGIN=*`,{origin:r,allowAnyOriginEnv:`AIKIT_ALLOW_ANY_ORIGIN=true`})),r&&!i.allowOrigin){t.status(403).json({error:`Origin not allowed`});return}if(i.allowOrigin&&t.setHeader(`Access-Control-Allow-Origin`,i.allowOrigin),t.setHeader(`Access-Control-Allow-Methods`,`GET, POST, PUT, PATCH, DELETE, OPTIONS`),t.setHeader(`Access-Control-Allow-Headers`,`Content-Type, Authorization, Mcp-Session-Id, Mcp-Protocol-Version, Last-Event-ID`),t.setHeader(`Access-Control-Expose-Headers`,`Mcp-Session-Id`),e.method===`OPTIONS`){t.status(204).end();return}n()});let M=p();console.error(`[aikit] Auth token: ~/.aikit/token`),_.use(f(M)),_.use(`/mcp`,(e,t,n)=>{let r=A(e)??e.ip??e.socket.remoteAddress??`anonymous`;if(O.allow(r)){n();return}let i=Math.max(1,Math.ceil(O.getRetryAfterMs(r)/1e3));t.setHeader(`Retry-After`,String(i)),t.status(429).json({jsonrpc:`2.0`,error:{code:-32003,message:`Rate limit exceeded`},id:null})}),o(_,s(),v);let N=new Date().toISOString();_.use(`/settings/api`,d({log:v,mcpInfo:()=>({transport:`http`,port:y,pid:process.pid,startedAt:N})})),c(_,u(),v),_.get(`/health`,(e,t)=>{t.json({status:`ok`})});let P=!1,F=null,I=null,L=null,R=null,z=null,B=null,V=null,H=Promise.resolve(),U=async(e,n)=>{if(!P||!L||!R){n.status(503).json({jsonrpc:`2.0`,error:{code:-32603,message:`Server initializing — please retry in a few seconds`},id:null});return}let r=H,i;H=new Promise(e=>{i=e}),await r;try{let r=A(e);if(!B){if(r){n.status(404).json({jsonrpc:`2.0`,error:{code:-32001,message:`Session not found`},id:null});return}let e=new R({sessionIdGenerator:()=>t(),onsessioninitialized:async e=>{V=e,I?.onSessionStart(e,{transport:`http`})},onsessionclosed:async e=>{e&&I?.onSessionEnd(e),V=null}});e.onclose=()=>{B===e&&(B=null),V===e.sessionId&&(V=null)},B=e,await L.connect(e)}let i=B;await i.handleRequest(e,n,e.body),e.method!==`DELETE`&&(!r&&i.sessionId?(V=i.sessionId,I?.onSessionStart(i.sessionId,{transport:`http`}),I?.onSessionActivity(i.sessionId)):r&&I?.onSessionActivity(r))}catch(e){if(v.error(`MCP handler error`,l(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()}},W=async(e,t)=>{let n=A(e);if(z&&(!B||n!==V)){await z.handleRequest(e,t,e.body);return}await U(e,t)};_.post(`/mcp`,W),_.get(`/mcp`,W),_.delete(`/mcp`,W);let G=_.listen(y,`127.0.0.1`,()=>{v.info(`MCP server listening`,{url:`http://127.0.0.1:${y}/mcp`,port:y}),setTimeout(async()=>{try{let[{createLazyServer:e,createMcpServer:t,ALL_TOOL_NAMES:n},{StreamableHTTPServerTransport:i},{checkForUpdates:o,autoUpgradeScaffold:s}]=await Promise.all([import(`./server-BMVFCB-8.js`),import(`@modelcontextprotocol/sdk/server/streamableHttp.js`),import(`./version-check-BgHzxxCW.js`)]);o(),s();let c=a(h),u=e(h,c);L=u.server,R=i,P=!0,v.debug(`MCP server configured (lazy — AI Kit initializing in background)`,{toolCount:n.length,resourceCount:2}),u.startInit(),u.ready.then(()=>{if(!u.aikit)throw Error(`AI Kit components are not available after initialization`);I=new g(u.aikit.stateStore,{staleTimeoutMinutes:E,gcIntervalMinutes:D,onBeforeSessionDelete:e=>{if(V===e&&B){let e=B;B=null,V=null,e.close().catch(()=>void 0)}z?.closeSession(e,{notifySessionEnd:!1})},onSessionEndMaintenance:async()=>{if(!u.aikit?.curated||!u.aikit?.stateStore)return;let{pruneLessons:e}=await import(`./evolution-BX_zTSdj.js`).then(e=>e.t),t=await e(u.aikit.curated,u.aikit.stateStore,{dryRun:!1});t.pruned.length>0&&v.info(`Session-end lesson prune`,{pruned:t.pruned.length})}}),z=new m({createServer:()=>{if(!u.aikit)throw Error(`AI Kit components are not available after initialization`);return t(u.aikit,h)},createTransport:e=>new i(e),maxSessions:T,sessionTimeoutMinutes:E,onSessionStart:e=>I?.onSessionStart(e,{transport:`http`}),onSessionActivity:e=>I?.onSessionActivity(e),onSessionEnd:e=>I?.onSessionEnd(e)}),I.startGC(),V&&(I.onSessionStart(V,{transport:`http`}),I.onSessionActivity(V)),v.info(`HTTP session runtime ready`,{maxSessions:T,sessionTimeoutMinutes:E,gcIntervalMinutes:D})}).catch(e=>v.error(`Failed to start session manager`,l(e))),c===`auto`?u.ready.then(async()=>{try{let e=h.sources.map(e=>e.path).join(`, `);v.info(`Running initial index`,{sourcePaths:e}),await u.runInitialIndex(),v.info(`Initial index complete`)}catch(e){v.error(`Initial index failed; will retry on aikit_reindex`,l(e))}}).catch(e=>v.error(`AI Kit init or indexing failed`,l(e))):c===`smart`?u.ready.then(async()=>{try{if(!u.aikit)throw Error(`AI Kit components are not available after initialization`);let{SmartIndexScheduler:e}=await import(`../../indexer/dist/index.js`),t=new e(u.aikit.indexer,h,u.aikit.store),n=u.aikit.store;F=t,t.start(),n.onBeforeClose&&n.onBeforeClose(()=>t.stop()),u.setSmartScheduler(t),v.debug(`Smart index scheduler started (HTTP mode)`)}catch(e){v.error(`Failed to start smart index scheduler`,l(e))}}).catch(e=>v.error(`AI Kit initialization failed`,l(e))):(u.ready.catch(e=>v.error(`AI Kit initialization failed`,l(e))),v.info(`Initial full indexing skipped in HTTP mode`,{indexMode:c})),r(u.ready,()=>u.aikit?{curated:u.aikit.curated,stateStore:u.aikit.stateStore}:null)}catch(e){v.error(`Failed to load server modules`,l(e))}},100)}),K=async e=>{v.info(`Shutdown signal received`,{signal:e}),F?.stop(),I?.stop(),await z?.closeAll().catch(()=>void 0),V&&I?.onSessionEnd(V),B&&(await B.close().catch(()=>void 0),B=null,V=null),G.close(),L&&await L.close(),process.exit(0)};process.on(`SIGINT`,()=>K(`SIGINT`)),process.on(`SIGTERM`,()=>K(`SIGTERM`))}else{let[{loadConfig:e,reconfigureForWorkspace:t,resolveIndexMode:n},{createLazyServer:i},{checkForUpdates:a,autoUpgradeScaffold:o},{RootsListChangedNotificationSchema:s}]=await Promise.all([import(`./config-D_MQ_9Q7.js`),import(`./server-BMVFCB-8.js`),import(`./version-check-BgHzxxCW.js`),import(`@modelcontextprotocol/sdk/types.js`)]),c=e();v.info(`Config loaded`,{sourceCount:c.sources.length,storePath:c.store.path}),a(),o();let u=n(c),d=i(c,u),{server:f,startInit:p,ready:m,runInitialIndex:h}=d,{StdioServerTransport:g}=await import(`@modelcontextprotocol/sdk/server/stdio.js`),_=new g;await f.connect(_),v.debug(`MCP server started`,{transport:`stdio`}),await D({config:c,indexMode:u,log:v,rootsChangedNotificationSchema:s,reconfigureForWorkspace:t,runInitialIndex:h,server:f,startInit:p});let y=null,b=()=>{y&&clearTimeout(y),y=setTimeout(async()=>{v.info(`Auto-shutdown: no activity for 30 minutes — shutting down gracefully`);try{let e=d.aikit;e&&await Promise.all([e.embedder.shutdown?.().catch(()=>{})??Promise.resolve(),e.graphStore.close().catch(()=>{}),e.store.close().catch(()=>{})])}catch{}process.exit(0)},18e5),y.unref&&y.unref()};b(),process.stdin.on(`data`,()=>b()),m.catch(e=>{v.error(`Initialization failed — server will continue with limited tools`,l(e))}),u===`smart`?m.then(async()=>{try{if(!d.aikit)throw Error(`AI Kit components are not available after initialization`);let{SmartIndexScheduler:e}=await import(`../../indexer/dist/index.js`),t=new e(d.aikit.indexer,c,d.aikit.store),n=d.aikit.store;t.start(),n.onBeforeClose&&n.onBeforeClose(()=>t.stop()),d.setSmartScheduler(t),v.debug(`Smart index scheduler started (stdio mode)`)}catch(e){v.error(`Failed to start smart index scheduler`,l(e))}}).catch(e=>v.error(`AI Kit init failed for smart scheduler`,l(e))):v.warn(`Initial full indexing skipped; use aikit_reindex to index manually`,{indexMode:u}),r(m,()=>d.aikit?{curated:d.aikit.curated,stateStore:d.aikit.stateStore}:null)}}export{e as CuratedKnowledgeManager,E as applyWorkspaceRoots,D as bootstrapWorkspaceRoots,x as createSlidingWindowRateLimiter,N as main,b as resolveCorsOrigin,T as selectWorkspaceRoot};
|
|
@@ -281,7 +281,7 @@ None.`:`### Stale Lessons\n${l.map(e=>`- **${e.title}** (\`${e.path}\`) — effe
|
|
|
281
281
|
{ path: 'docs/api.md', title: 'API Reference', status: 'stale' },
|
|
282
282
|
],
|
|
283
283
|
},
|
|
284
|
-
}`},{type:`text`,category:`content`,description:`Plain text content rendered through the markdown parser.`,valueShape:`string`},{type:`heading`,category:`content`,description:`Single heading with configurable level from h1 to h6.`,valueShape:`string`},{type:`paragraph`,category:`content`,description:`Single paragraph rendered inside a p tag.`,valueShape:`string`},{type:`separator`,category:`layout`,description:`Horizontal rule used to separate adjacent blocks.`,valueShape:`undefined`},{type:`actions`,category:`layout`,description:`Action bar containing button and select action definitions.`,valueShape:`Array<{ type: string; id: string; label: string; variant?: string; options?: Array<string | { label: string; value: string }> }>`}].map(e=>[e.type,{...e}]));function Yp(){let e={};for(let[t,n]of Jp)n.vendorScripts?.length&&(e[t]=n.vendorScripts);return e}const Xp=1024,Zp=new Set([`user-closed`,`host-dismissed`,`replaced`]);function Qp(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function $p(e,t,n){let r={code:e,message:t};return n!==void 0&&(r.details=n),{kind:`error`,error:r}}function em(e,t,n,r){e.writeHead(t,{"Content-Type":`application/json`,"Access-Control-Allow-Origin":r??`null`}),e.end(JSON.stringify(n))}async function tm(e){return await new Promise((t,n)=>{let r=[],i=0;e.on(`data`,t=>{if(i+=t.length,i>65536){n(Error(`Callback payload exceeds 64KB limit`)),e.destroy();return}r.push(t)}),e.on(`end`,()=>t(Buffer.concat(r).toString(`utf8`))),e.on(`error`,n)})}function nm(e,t){if(typeof e!=`string`||e.length!==t.length)return!1;let n=Buffer.from(e,`utf8`),r=Buffer.from(t,`utf8`);return n.length===r.length?ce(n,r):!1}function rm(e,t){let n=e.headers.origin;if(n!=null)return n===t;let r=e.headers.referer;return r==null?!1:r.startsWith(t)}function im(e){return(e.headers[`content-type`]??``).startsWith(`application/json`)}function am(e){for(let[t,n]of Object.entries(e)){let e=typeof n==`string`?n:JSON.stringify(n);if(Buffer.byteLength(e,`utf8`)>8192)return`Form field "${t}" exceeds 8KB limit`}return null}function om(e){return Array.isArray(e)&&e.length>Xp?`Selection exceeds ${Xp} items (got ${e.length})`:null}function sm(e,t,n){let r=typeof e.actionId==`string`?e.actionId:``,i=n.find(e=>e.id===r);if(!i)return $p(`INVALID_ACTION`,`Unknown actionId: ${r||`(missing)`}`);let a=typeof e.selection==`string`||Array.isArray(e.selection)?e.selection:void 0,o=Qp(e.formData)?e.formData:void 0,s={surfaceId:t,actionId:i.id,actionType:i.type,timestamp:typeof e.timestamp==`string`?e.timestamp:new Date().toISOString(),sourceTransport:`browser`};return e.value!==void 0&&(s.value=e.value),a!==void 0&&(s.selection=a),o!==void 0&&(s.formData=o),typeof e.label==`string`?s.label=e.label:i.label&&(s.label=i.label),{kind:`result`,result:s}}function cm(e,t){let n=oe(16).toString(`hex`),r=!1,i=!1,a,o,s=new Promise(e=>{o=e}),c=e=>r?a??e:(r=!0,a=e,o?.(e),e);return{nonce:n,promise:s,settleTimeout(e){return c({kind:`timeout`,waitedMs:e})},settleCancelled(e){return c({kind:`cancelled`,reason:e})},settleError(e,t,n){return c($p(e,t,n))},async handle(r,a,o){if(!im(r)){let e=c($p(`INVALID_CONTENT_TYPE`,`Content-Type must be application/json`));return em(a,415,{ok:!1,error:`unsupported-media-type`},o),e}if(!rm(r,o)){let e=c($p(`INVALID_ORIGIN`,`Unexpected callback origin: ${r.headers.origin??r.headers.referer??`(missing)`}`));return em(a,403,{ok:!1,error:`invalid-origin`},o),e}let s=``;try{s=await tm(r)}catch(e){let t=c($p(`INVALID_PAYLOAD`,e instanceof Error?e.message:`Unable to read callback payload`));return em(a,413,{ok:!1,error:`payload-too-large`},o),t}let l;try{let e=JSON.parse(s);if(!Qp(e))throw Error(`Callback payload must be an object`);l=e}catch(e){let t=c($p(`INVALID_PAYLOAD`,e instanceof Error?e.message:`Malformed callback payload`));return em(a,400,{ok:!1,error:`invalid-json`},o),t}if(i){let e=$p(`NONCE_CONSUMED`,`Nonce has already been used`);return em(a,403,{ok:!1,error:`nonce-consumed`},o),e}if(!nm(typeof l.nonce==`string`?l.nonce:``,n)){let e=c($p(`INVALID_NONCE`,`Callback nonce did not match`));return em(a,403,{ok:!1,error:`invalid-nonce`},o),e}i=!0;let u=om(l.selection);if(u){let e=c($p(`SELECTION_TOO_LARGE`,u));return em(a,413,{ok:!1,error:`selection-too-large`},o),e}if(Qp(l.formData)){let e=am(l.formData);if(e){let t=c($p(`PAYLOAD_FIELD_TOO_LARGE`,e));return em(a,413,{ok:!1,error:`field-too-large`},o),t}}if(l.kind===`cancelled`){let e=typeof l.reason==`string`?l.reason:``;if(!Zp.has(e)){let t=c($p(`INVALID_CANCEL_REASON`,`Unsupported cancel reason: ${e||`(missing)`}`));return em(a,400,{ok:!1,error:`invalid-cancel-reason`},o),t}let t=c({kind:`cancelled`,reason:e});return em(a,200,{ok:!0,kind:`cancelled`},o),t}let d=c(sm(l,e,t));return em(a,d.kind===`error`?400:200,{ok:d.kind!==`error`,kind:d.kind},o),d}}}const lm=new Map;function um(e){return e.replace(/[|\\{}()[\]^$+*?.]/g,`\\$&`)}function dm(e){let t=`(?=[^>]*\\bid=['"]${um(e)}['"])`;return RegExp(`(<script\\b(?=[^>]*\\btype=['"]application\\/json['"])${t}[^>]*>)[\\s\\S]*?(<\/script>)`,`i`)}function fm(e){lm.has(e.id)&&console.warn(`[viewer-registry] Overwriting viewer template "${e.id}"`),lm.set(e.id,e)}function pm(e){return lm.get(e)}function mm(e){return typeof e==`string`&&lm.has(e)}function hm(){return[...lm.values()]}function gm(e,t,n,r){let i=dm(n);if(!i.test(e))throw Error(`No <script type="application/json" id="${n}"> found in template`);let a=r?r(t):t,o=JSON.stringify(a??null).replace(/<\/script/gi,`<\\/script`).replace(/<script/gi,`\\u003Cscript`).replace(/-->/g,`--\\u003E`).replace(/<!--/g,`\\u003C!--`);return e.replace(i,`$1\n${o}\n$2`)}const _m=import.meta.dirname??ge(be(import.meta.url)),vm={type:`object`,properties:{title:{type:`string`},description:{type:`string`},layout:{type:`object`,properties:{direction:{type:`string`},spacing:{type:`number`},layerSpacing:{type:`number`}}},nodes:{type:`array`,items:{type:`object`,properties:{id:{type:`string`},type:{type:`string`,enum:[`person`,`system`,`container`,`component`,`database`,`queue`,`external`,`boundary`]},label:{type:`string`},technology:{type:`string`},icon:{type:`string`},description:{type:`string`}},required:[`id`,`type`,`label`]}},edges:{type:`array`,items:{type:`object`,properties:{source:{type:`string`},target:{type:`string`},label:{type:`string`},style:{type:`string`,enum:[`sync`,`async`,`dashed`,`dotted`,`solid`]}},required:[`source`,`target`]},default:[]}},required:[`nodes`]},ym={type:`object`,properties:{nodes:{type:`array`,items:{type:`object`,properties:{id:{type:`string`},label:{type:`string`},type:{type:`string`,enum:[`start-end`,`manual`,`automated`,`integration`,`decision`,`prerequisite`]},description:{type:`string`}},required:[`id`,`label`]}},edges:{type:`array`,items:{type:`object`,properties:{source:{type:`string`},target:{type:`string`},label:{type:`string`},type:{type:`string`,enum:[`standard`,`loop-back`,`exception`]}},required:[`source`,`target`]}}},required:[`nodes`]},bm={type:`object`,properties:{title:{type:`string`},description:{type:`string`},phases:{type:`array`,items:{type:`object`,properties:{id:{type:`string`},label:{type:`string`},outcome:{type:`string`},batches:{type:`array`,items:{type:`object`,properties:{id:{type:`string`},order:{type:`number`},parallel:{type:`boolean`},label:{type:`string`},tasks:{type:`array`,items:{type:`object`,properties:{id:{type:`string`},title:{type:`string`},agent:{type:`string`},files:{type:`array`,items:{type:`string`},default:[]},status:{type:`string`,enum:[`pending`,`in-progress`,`done`,`blocked`]},dependsOn:{type:`array`,items:{type:`string`},default:[]}},required:[`id`,`title`]},default:[]}},required:[`id`,`tasks`]},default:[]}},required:[`id`,`label`,`batches`]}}},required:[`phases`]};function xm(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Sm(e,t){return xm(t)?{...t,kind:e}:{kind:e}}function Cm(e){let t=e===`canvas.html`?[P(_m,`..`,`..`,`..`,`..`,`..`,`scaffold`,`general`,`viewers`,`src`,`canvas`,`index.html`),P(_m,`..`,`..`,`scaffold`,`general`,`viewers`,`src`,`canvas`,`index.html`)]:[],n=S(`server`,[P(`viewers`,`dist`,e),P(`viewers`,e)]),r=[...t,...n?[n]:[],P(_m,`..`,`..`,`..`,`viewers`,e),P(_m,`..`,`..`,`..`,`..`,`..`,`scaffold`,`general`,`viewers`,`src`,`static`,e),P(_m,`..`,`..`,`..`,`..`,`..`,`scaffold`,`general`,`viewers`,`dist`,e),P(_m,`..`,`..`,`..`,`..`,`..`,`scaffold`,`general`,`viewers`,e),P(_m,`..`,`..`,`scaffold`,`general`,`viewers`,`dist`,e),P(_m,`..`,`..`,`scaffold`,`general`,`viewers`,e),P(_m,`..`,`viewers`,`dist`,e),P(_m,`..`,`viewers`,e)];for(let e of r)try{return N(e,`utf8`)}catch{}throw Error(`Viewer HTML not found: ${e}. Searched: ${r.join(`, `)}`)}let wm,Tm,Em,Dm,Om,km;function Am(){return wm??=Cm(`c4-viewer.html`),wm}function jm(){return Tm??=Cm(`tour-viewer.html`),Tm}function Mm(){return Em??=Cm(`canvas.html`),Em}function Nm(){return Dm??=Cm(`architecture-static.html`),Dm}function Pm(){return Om??=Cm(`process-flow-static.html`),Om}function Fm(){return km??=Cm(`task-plan-static.html`),km}function Im(){fm({id:`c4@1`,label:`C4 Architecture Diagram`,description:`Interactive C4 architecture diagram with zoom, pan, and ELK auto-layout`,inputSchema:vm,injectId:`diagram-data`,supportedTransports:[`browser`],resolveHtml:Am}),fm({id:`c4-static@1`,label:`C4 Architecture Diagram (Static)`,description:`Static SVG architecture diagram for inline rendering`,inputSchema:vm,injectId:`diagram-data`,supportedTransports:[`mcp-app`],resolveHtml:Nm}),fm({id:`tour@1`,label:`Code Tour Viewer`,description:`Interactive code tour with step navigation and dependency graph`,inputSchema:{type:`object`,properties:{title:{type:`string`},description:{type:`string`},estimatedTime:{type:`string`},steps:{type:`array`,items:{type:`object`,properties:{stepNumber:{type:`number`},id:{type:`string`},title:{type:`string`},file:{type:`string`},explanation:{type:`string`},description:{type:`string`},learnsConcept:{type:`string`},duration:{type:`string`},line:{type:`number`},code:{type:`string`}},required:[`id`,`title`]}},dependencies:{type:`array`,items:{type:`object`,properties:{source:{type:`string`},target:{type:`string`}},required:[`source`,`target`]},default:[]}},required:[`steps`]},injectId:`tour-data`,supportedTransports:[`browser`],resolveHtml:jm}),fm({id:`process-flow-static@1`,label:`Process Flow Diagram (Static)`,description:`Static SVG process flow diagram for inline rendering`,inputSchema:ym,injectId:`diagram-data`,supportedTransports:[`mcp-app`],resolveHtml:Pm}),fm({id:`task-plan-static@1`,label:`Task Execution Plan (Static)`,description:`Static SVG task execution plan for inline rendering`,inputSchema:bm,injectId:`diagram-data`,supportedTransports:[`mcp-app`],resolveHtml:Fm}),fm({id:`task-plan@1`,label:`Task Execution Plan (Interactive)`,description:`Interactive task execution plan with ReactFlow, phase grouping, and dependency edges`,inputSchema:bm,injectId:`diagram-data`,supportedTransports:[`browser`],resolveHtml:Mm,transformData:e=>Sm(`task-plan`,e)}),fm({id:`process-flow@1`,label:`Process Flow Diagram (Interactive)`,description:`Interactive process flow diagram with ReactFlow`,inputSchema:ym,injectId:`diagram-data`,supportedTransports:[`browser`],resolveHtml:Mm,transformData:e=>Sm(`process-flow`,e)})}function Lm(){let e=new Cr;for(let t of Er.list())e.register(t);return e.register(Tr),e.register(Ar),e.register(jr),e.register(Dr),e}function Rm(e,t){return e?.supportedTransports.includes(t)??!1}const zm=Lm();function Bm(e){if(e.template)return zm.get(e.template)}function Vm(e){if((e.actions?.length??0)>0)return!0;if(e.template&&mm(e.template)){let t=pm(e.template);return t?.supportedTransports.includes(`browser`)===!0&&!t.supportedTransports.includes(`mcp-app`)}let t=Bm(e);return Rm(t,`browser`)&&!Rm(t,`mcp-app`)}Im();const Hm=String.raw`(function(){
|
|
284
|
+
}`},{type:`text`,category:`content`,description:`Plain text content rendered through the markdown parser.`,valueShape:`string`},{type:`heading`,category:`content`,description:`Single heading with configurable level from h1 to h6.`,valueShape:`string`},{type:`paragraph`,category:`content`,description:`Single paragraph rendered inside a p tag.`,valueShape:`string`},{type:`separator`,category:`layout`,description:`Horizontal rule used to separate adjacent blocks.`,valueShape:`undefined`},{type:`actions`,category:`layout`,description:`Action bar containing button and select action definitions.`,valueShape:`Array<{ type: string; id: string; label: string; variant?: string; options?: Array<string | { label: string; value: string }> }>`}].map(e=>[e.type,{...e}]));function Yp(){let e={};for(let[t,n]of Jp)n.vendorScripts?.length&&(e[t]=n.vendorScripts);return e}const Xp=1024,Zp=new Set([`user-closed`,`host-dismissed`,`replaced`]);function Qp(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function $p(e,t,n){let r={code:e,message:t};return n!==void 0&&(r.details=n),{kind:`error`,error:r}}function em(e,t,n,r){e.writeHead(t,{"Content-Type":`application/json`,"Access-Control-Allow-Origin":r??`null`}),e.end(JSON.stringify(n))}async function tm(e){return await new Promise((t,n)=>{let r=[],i=0;e.on(`data`,t=>{if(i+=t.length,i>65536){n(Error(`Callback payload exceeds 64KB limit`)),e.destroy();return}r.push(t)}),e.on(`end`,()=>t(Buffer.concat(r).toString(`utf8`))),e.on(`error`,n)})}function nm(e,t){if(typeof e!=`string`||e.length!==t.length)return!1;let n=Buffer.from(e,`utf8`),r=Buffer.from(t,`utf8`);return n.length===r.length?ce(n,r):!1}function rm(e,t){let n=e.headers.origin;if(n!=null)return n===t;let r=e.headers.referer;return r==null?!1:r.startsWith(t)}function im(e){return(e.headers[`content-type`]??``).startsWith(`application/json`)}function am(e){for(let[t,n]of Object.entries(e)){let e=typeof n==`string`?n:JSON.stringify(n);if(Buffer.byteLength(e,`utf8`)>8192)return`Form field "${t}" exceeds 8KB limit`}return null}function om(e){return Array.isArray(e)&&e.length>Xp?`Selection exceeds ${Xp} items (got ${e.length})`:null}function sm(e,t,n){let r=typeof e.actionId==`string`?e.actionId:``,i=n.find(e=>e.id===r);if(!i)return $p(`INVALID_ACTION`,`Unknown actionId: ${r||`(missing)`}`);let a=typeof e.selection==`string`||Array.isArray(e.selection)?e.selection:void 0,o=Qp(e.formData)?e.formData:void 0,s={surfaceId:t,actionId:i.id,actionType:i.type,timestamp:typeof e.timestamp==`string`?e.timestamp:new Date().toISOString(),sourceTransport:`browser`};return e.value!==void 0&&(s.value=e.value),a!==void 0&&(s.selection=a),o!==void 0&&(s.formData=o),typeof e.label==`string`?s.label=e.label:i.label&&(s.label=i.label),{kind:`result`,result:s}}function cm(e,t){let n=oe(16).toString(`hex`),r=!1,i=!1,a,o,s=new Promise(e=>{o=e}),c=e=>r?a??e:(r=!0,a=e,o?.(e),e);return{nonce:n,promise:s,settleTimeout(e){return c({kind:`timeout`,waitedMs:e})},settleCancelled(e){return c({kind:`cancelled`,reason:e})},settleError(e,t,n){return c($p(e,t,n))},async handle(r,a,o){if(!im(r)){let e=c($p(`INVALID_CONTENT_TYPE`,`Content-Type must be application/json`));return em(a,415,{ok:!1,error:`unsupported-media-type`},o),e}if(!rm(r,o)){let e=c($p(`INVALID_ORIGIN`,`Unexpected callback origin: ${r.headers.origin??r.headers.referer??`(missing)`}`));return em(a,403,{ok:!1,error:`invalid-origin`},o),e}let s=``;try{s=await tm(r)}catch(e){let t=c($p(`INVALID_PAYLOAD`,e instanceof Error?e.message:`Unable to read callback payload`));return em(a,413,{ok:!1,error:`payload-too-large`},o),t}let l;try{let e=JSON.parse(s);if(!Qp(e))throw Error(`Callback payload must be an object`);l=e}catch(e){let t=c($p(`INVALID_PAYLOAD`,e instanceof Error?e.message:`Malformed callback payload`));return em(a,400,{ok:!1,error:`invalid-json`},o),t}if(i){let e=$p(`NONCE_CONSUMED`,`Nonce has already been used`);return em(a,403,{ok:!1,error:`nonce-consumed`},o),e}if(!nm(typeof l.nonce==`string`?l.nonce:``,n)){let e=c($p(`INVALID_NONCE`,`Callback nonce did not match`));return em(a,403,{ok:!1,error:`invalid-nonce`},o),e}i=!0;let u=om(l.selection);if(u){let e=c($p(`SELECTION_TOO_LARGE`,u));return em(a,413,{ok:!1,error:`selection-too-large`},o),e}if(Qp(l.formData)){let e=am(l.formData);if(e){let t=c($p(`PAYLOAD_FIELD_TOO_LARGE`,e));return em(a,413,{ok:!1,error:`field-too-large`},o),t}}if(l.kind===`cancelled`){let e=typeof l.reason==`string`?l.reason:``;if(!Zp.has(e)){let t=c($p(`INVALID_CANCEL_REASON`,`Unsupported cancel reason: ${e||`(missing)`}`));return em(a,400,{ok:!1,error:`invalid-cancel-reason`},o),t}let t=c({kind:`cancelled`,reason:e});return em(a,200,{ok:!0,kind:`cancelled`},o),t}let d=c(sm(l,e,t));return em(a,d.kind===`error`?400:200,{ok:d.kind!==`error`,kind:d.kind},o),d}}}const lm=`Install AI Kit with <code>${Y(`npx -y @vpxa/aikit@latest init --user`)}</code>.`,um=new Map;function dm(e){return e.replace(/[|\\{}()[\]^$+*?.]/g,`\\$&`)}function fm(e){let t=`(?=[^>]*\\bid=['"]${dm(e)}['"])`;return RegExp(`(<script\\b(?=[^>]*\\btype=['"]application\\/json['"])${t}[^>]*>)[\\s\\S]*?(<\/script>)`,`i`)}function pm(e){um.has(e.id)&&console.warn(`[viewer-registry] Overwriting viewer template "${e.id}"`),um.set(e.id,e)}function mm(e){return um.get(e)}function hm(e){return typeof e==`string`&&um.has(e)}function gm(){return[...um.values()]}function _m(e,t,n,r){let i=fm(n);if(!i.test(e))throw Error(`No <script type="application/json" id="${n}"> found in template`);let a=r?r(t):t,o=JSON.stringify(a??null).replace(/<\/script/gi,`<\\/script`).replace(/<script/gi,`\\u003Cscript`).replace(/-->/g,`--\\u003E`).replace(/<!--/g,`\\u003C!--`);return e.replace(i,`$1\n${o}\n$2`)}const vm=import.meta.dirname??ge(be(import.meta.url)),ym={type:`object`,properties:{title:{type:`string`},description:{type:`string`},layout:{type:`object`,properties:{direction:{type:`string`},spacing:{type:`number`},layerSpacing:{type:`number`}}},nodes:{type:`array`,items:{type:`object`,properties:{id:{type:`string`},type:{type:`string`,enum:[`person`,`system`,`container`,`component`,`database`,`queue`,`external`,`boundary`]},label:{type:`string`},technology:{type:`string`},icon:{type:`string`},description:{type:`string`}},required:[`id`,`type`,`label`]}},edges:{type:`array`,items:{type:`object`,properties:{source:{type:`string`},target:{type:`string`},label:{type:`string`},style:{type:`string`,enum:[`sync`,`async`,`dashed`,`dotted`,`solid`]}},required:[`source`,`target`]},default:[]}},required:[`nodes`]},bm={type:`object`,properties:{nodes:{type:`array`,items:{type:`object`,properties:{id:{type:`string`},label:{type:`string`},type:{type:`string`,enum:[`start-end`,`manual`,`automated`,`integration`,`decision`,`prerequisite`]},description:{type:`string`}},required:[`id`,`label`]}},edges:{type:`array`,items:{type:`object`,properties:{source:{type:`string`},target:{type:`string`},label:{type:`string`},type:{type:`string`,enum:[`standard`,`loop-back`,`exception`]}},required:[`source`,`target`]}}},required:[`nodes`]},xm={type:`object`,properties:{title:{type:`string`},description:{type:`string`},phases:{type:`array`,items:{type:`object`,properties:{id:{type:`string`},label:{type:`string`},outcome:{type:`string`},batches:{type:`array`,items:{type:`object`,properties:{id:{type:`string`},order:{type:`number`},parallel:{type:`boolean`},label:{type:`string`},tasks:{type:`array`,items:{type:`object`,properties:{id:{type:`string`},title:{type:`string`},agent:{type:`string`},files:{type:`array`,items:{type:`string`},default:[]},status:{type:`string`,enum:[`pending`,`in-progress`,`done`,`blocked`]},dependsOn:{type:`array`,items:{type:`string`},default:[]}},required:[`id`,`title`]},default:[]}},required:[`id`,`tasks`]},default:[]}},required:[`id`,`label`,`batches`]}}},required:[`phases`]};function Sm(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Cm(e,t){return Sm(t)?{...t,kind:e}:{kind:e}}function wm(e){let t=e===`canvas.html`?[P(vm,`..`,`..`,`..`,`..`,`..`,`scaffold`,`general`,`viewers`,`src`,`canvas`,`index.html`),P(vm,`..`,`..`,`scaffold`,`general`,`viewers`,`src`,`canvas`,`index.html`)]:[],n=S(`server`,[P(`viewers`,`dist`,e),P(`viewers`,e)]),r=[...t,...n?[n]:[],P(vm,`..`,`..`,`..`,`viewers`,e),P(vm,`..`,`..`,`..`,`..`,`..`,`scaffold`,`general`,`viewers`,`src`,`static`,e),P(vm,`..`,`..`,`..`,`..`,`..`,`scaffold`,`general`,`viewers`,`dist`,e),P(vm,`..`,`..`,`..`,`..`,`..`,`scaffold`,`general`,`viewers`,e),P(vm,`..`,`..`,`scaffold`,`general`,`viewers`,`dist`,e),P(vm,`..`,`..`,`scaffold`,`general`,`viewers`,e),P(vm,`..`,`viewers`,`dist`,e),P(vm,`..`,`viewers`,e)];for(let e of r)try{return N(e,`utf8`)}catch{}throw Error(`Viewer HTML not found: ${e}. Searched: ${r.join(`, `)}`)}let Tm,Em,Dm,Om,km,Am;function jm(){return Tm??=wm(`c4-viewer.html`),Tm}function Mm(){return Em??=wm(`tour-viewer.html`),Em}function Nm(){return Dm??=wm(`canvas.html`),Dm}function Pm(){return Om??=wm(`architecture-static.html`),Om}function Fm(){return km??=wm(`process-flow-static.html`),km}function Im(){return Am??=wm(`task-plan-static.html`),Am}function Lm(){pm({id:`c4@1`,label:`C4 Architecture Diagram`,description:`Interactive C4 architecture diagram with zoom, pan, and ELK auto-layout`,inputSchema:ym,injectId:`diagram-data`,supportedTransports:[`browser`],resolveHtml:jm}),pm({id:`c4-static@1`,label:`C4 Architecture Diagram (Static)`,description:`Static SVG architecture diagram for inline rendering`,inputSchema:ym,injectId:`diagram-data`,supportedTransports:[`mcp-app`],resolveHtml:Pm}),pm({id:`tour@1`,label:`Code Tour Viewer`,description:`Interactive code tour with step navigation and dependency graph`,inputSchema:{type:`object`,properties:{title:{type:`string`},description:{type:`string`},estimatedTime:{type:`string`},steps:{type:`array`,items:{type:`object`,properties:{stepNumber:{type:`number`},id:{type:`string`},title:{type:`string`},file:{type:`string`},explanation:{type:`string`},description:{type:`string`},learnsConcept:{type:`string`},duration:{type:`string`},line:{type:`number`},code:{type:`string`}},required:[`id`,`title`]}},dependencies:{type:`array`,items:{type:`object`,properties:{source:{type:`string`},target:{type:`string`}},required:[`source`,`target`]},default:[]}},required:[`steps`]},injectId:`tour-data`,supportedTransports:[`browser`],resolveHtml:Mm}),pm({id:`process-flow-static@1`,label:`Process Flow Diagram (Static)`,description:`Static SVG process flow diagram for inline rendering`,inputSchema:bm,injectId:`diagram-data`,supportedTransports:[`mcp-app`],resolveHtml:Fm}),pm({id:`task-plan-static@1`,label:`Task Execution Plan (Static)`,description:`Static SVG task execution plan for inline rendering`,inputSchema:xm,injectId:`diagram-data`,supportedTransports:[`mcp-app`],resolveHtml:Im}),pm({id:`task-plan@1`,label:`Task Execution Plan (Interactive)`,description:`Interactive task execution plan with ReactFlow, phase grouping, and dependency edges`,inputSchema:xm,injectId:`diagram-data`,supportedTransports:[`browser`],resolveHtml:Nm,transformData:e=>Cm(`task-plan`,e)}),pm({id:`process-flow@1`,label:`Process Flow Diagram (Interactive)`,description:`Interactive process flow diagram with ReactFlow`,inputSchema:bm,injectId:`diagram-data`,supportedTransports:[`browser`],resolveHtml:Nm,transformData:e=>Cm(`process-flow`,e)})}function Rm(){let e=new Cr;for(let t of Er.list())e.register(t);return e.register(Tr),e.register(Ar),e.register(jr),e.register(Dr),e}function zm(e,t){return e?.supportedTransports.includes(t)??!1}const Bm=Rm();function Vm(e){if(e.template)return Bm.get(e.template)}function Hm(e){if((e.actions?.length??0)>0)return!0;if(e.template&&hm(e.template)){let t=mm(e.template);return t?.supportedTransports.includes(`browser`)===!0&&!t.supportedTransports.includes(`mcp-app`)}let t=Vm(e);return zm(t,`browser`)&&!zm(t,`mcp-app`)}Lm();const Um=String.raw`(function(){
|
|
285
285
|
'use strict';
|
|
286
286
|
|
|
287
287
|
var SVG_NS = 'http://www.w3.org/2000/svg';
|
|
@@ -2657,7 +2657,7 @@ None.`:`### Stale Lessons\n${l.map(e=>`- **${e.title}** (\`${e.path}\`) — effe
|
|
|
2657
2657
|
};
|
|
2658
2658
|
|
|
2659
2659
|
init();
|
|
2660
|
-
})();`;function
|
|
2660
|
+
})();`;function Wm(){let e;return()=>{if(e!==void 0)return e;try{e=N(ae(import.meta.url).resolve(`mermaid/dist/mermaid.min.js`),`utf-8`)}catch{e=``}return e}}const Gm={id:`mermaid`,cdn:`https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.min.js`,inlineSource:Um,initScript:`window.__aikit_initMermaid = function() {
|
|
2661
2661
|
if (typeof mermaid === 'undefined') return;
|
|
2662
2662
|
if (document.readyState === 'loading') {
|
|
2663
2663
|
document.addEventListener('DOMContentLoaded', window.__aikit_initMermaid);
|
|
@@ -2670,7 +2670,7 @@ None.`:`### Stale Lessons\n${l.map(e=>`- **${e.title}** (\`${e.path}\`) — effe
|
|
|
2670
2670
|
}
|
|
2671
2671
|
mermaid.initialize({ startOnLoad: false, theme: theme });
|
|
2672
2672
|
mermaid.run();
|
|
2673
|
-
};`,onload:`window.__aikit_initMermaid&&window.__aikit_initMermaid()`,local:{route:`/vendor/mermaid.min.js`,getSource:
|
|
2673
|
+
};`,onload:`window.__aikit_initMermaid&&window.__aikit_initMermaid()`,local:{route:`/vendor/mermaid.min.js`,getSource:Wm()}},Km=new Map([[`mermaid`,Gm]]);function qm(e,t){if(!e?.length)return;let n=[];for(let r of e){let e=Km.get(r);if(e){if(t===`browser`){n.push({inlineSource:e.inlineSource,onload:e.onload});continue}if(t===`mcp-app`){n.push({inlineSource:e.inlineSource,onload:e.onload});continue}n.push({src:e.cdn,initScript:e.initScript,onload:e.onload})}}return n.length>0?n:void 0}function Jm(){let e=[];for(let t of Km.values())t.local&&e.push({route:t.local.route,getSource:t.local.getSource,cdn:t.cdn});return e}const Ym=300*1e3,Xm=15*1e3;let X=null,Zm;process.on(`exit`,()=>{let e=X;if(e){try{e.close()}catch{}X=null}});function Qm(e,t){return e.length===0?``:`
|
|
2674
2674
|
<section class="present-surface-actions">
|
|
2675
2675
|
<div class="present-action-bar">${e.map(e=>{let t=Y(e.id),n=Y(e.label);if(e.type===`select`||e.type===`multi-select`)return`<label class="present-action-field"><span>${n}</span><select data-action-id="${t}"${e.type===`multi-select`?` multiple`:``}>${(e.options??[]).map(e=>`<option value="${Y(e.value)}">${Y(e.label)}</option>`).join(``)}</select></label>`;if(e.type===`text-submit`)return`<label class="present-action-field"><span>${n}</span><div class="present-text-submit"><input type="text" class="present-text-input" data-action-id="${t}" data-action-label="${n}" placeholder="${n}" /><button type="button" class="present-action-btn present-action-primary present-submit-btn" data-submit-for="${t}">Send</button></div></label>`;if(e.type===`form-submit`){let r=e.schema;if(r)return`<form class="present-form" data-action-id="${t}" data-action-label="${n}">${Object.entries(r).map(([e,t])=>{let n=Y(t.description??e);return`<label class="present-action-field"><span>${n}</span><input type="${t.type===`number`?`number`:t.type===`boolean`?`checkbox`:`text`}" class="present-text-input" name="${Y(e)}" placeholder="${n}" /></label>`}).join(``)}<button type="submit" class="present-action-btn present-action-primary">${n}</button></form>`}return`<button type="button" class="present-action-btn present-action-${Y(e.variant??`default`)}" data-action-id="${t}" data-action-label="${n}">${n}</button>`}).join(``)}</div>
|
|
2676
2676
|
<p id="present-action-status" class="present-action-status" aria-live="polite"></p>
|
|
@@ -2875,8 +2875,8 @@ None.`:`### Stale Lessons\n${l.map(e=>`- **${e.title}** (\`${e.path}\`) — effe
|
|
|
2875
2875
|
navigator.sendBeacon('/callback', new Blob([body], { type: 'application/json' }));
|
|
2876
2876
|
});
|
|
2877
2877
|
})();
|
|
2878
|
-
<\/script>`}function
|
|
2879
|
-
`)}function
|
|
2878
|
+
<\/script>`}function $m(e){try{if(process.platform===`win32`){Rn(`cmd`,[`/c`,`start`,``,e],{windowsHide:!0});return}if(process.platform===`darwin`){Rn(`open`,[e]);return}Rn(`xdg-open`,[e])}catch{}}async function eh(e){try{let t=Jn();return await t.launch(`ui`),t.resetIdleTimer(),await(await t.getContext().newPage()).goto(e,{waitUntil:`domcontentloaded`}),!0}catch{return $m(e),!1}}function th(e,t,n){let r=[e.title];return e.description&&r.push(e.description),r.push(``,`Opened in browser at ${t}`,n),r.join(`
|
|
2879
|
+
`)}function nh(e){return e.some(e=>e.id!==`__dismiss`)}function rh(){return Zm===void 0&&(Zm=C(`blocks-interactive`)),Zm}function ih(e){let t=e?.split(`?`)[0];if(!t?.startsWith(`/@aikit/blocks-interactive/dist/`))return;let n=rh();if(n)return P(n,`dist`,t.slice(32))}function ah(e){return e.replace(`</head>`,`<style>
|
|
2880
2880
|
.toolbar, .badge, body > header, body > footer { display: none !important; }
|
|
2881
2881
|
body { padding-top: 0 !important; margin-top: 0 !important; }
|
|
2882
2882
|
</style>
|
|
@@ -2887,8 +2887,8 @@ window.addEventListener('message', function(e) {
|
|
|
2887
2887
|
}
|
|
2888
2888
|
});
|
|
2889
2889
|
<\/script>
|
|
2890
|
-
</body>`)}function
|
|
2891
|
-
`);return{content:[{type:`text`,text:`[ERROR:VALIDATION] Template "${t.id}" data validation failed:\n${e}\n\nExpected schema: ${JSON.stringify(t.inputSchema,null,2)}`}],structuredContent:{kind:`error`,error:{code:`VIEWER_DATA_INVALID`,message:`Template "${t.id}" data validation failed:\n${e}\n\nExpected schema: ${JSON.stringify(t.inputSchema,null,2)}`}},isError:!0}}}let n=
|
|
2890
|
+
</body>`)}function oh(){let e=X;e&&(X=null,setTimeout(()=>{try{e.close()}catch{}},2e3))}function sh(e){if(!e.headersSent)try{e.writeHead(500,{"Content-Type":`text/plain`}),e.end(`Internal Server Error`)}catch{try{e.end()}catch{}}}async function ch(e){let t=Jn();t.isLaunched()||await t.launch(`headless`),t.resetIdleTimer();let n=await t.getContext().newPage();try{return await n.goto(e,{waitUntil:`domcontentloaded`}),await n.waitForLoadState(`networkidle`,{timeout:2e3}).catch(()=>{}),await n.screenshot({fullPage:!0,type:`png`})}finally{await n.close().catch(()=>{})}}async function lh(e,t){if(!t){e.writeHead(503,{"Content-Type":`text/plain; charset=utf-8`}),e.end(`Screenshot target is not ready.`);return}try{let n=await ch(t);e.writeHead(200,{"Content-Type":`image/png`,"Cache-Control":`no-store`}),e.end(n)}catch{sh(e)}}async function uh(e,t){if(Ch(`<html><body style="font-family:system-ui;padding:2rem;color:#888;text-align:center"><p>Content opened in browser window.</p></body></html>`),e.data!=null&&t.inputSchema){let n=ln({data:e.data,schema:t.inputSchema});if(!n.valid){let e=n.errors.map(e=>` ${e.path}: ${e.message}${e.expected?` (expected: ${e.expected}, got: ${e.received})`:``}`).join(`
|
|
2891
|
+
`);return{content:[{type:`text`,text:`[ERROR:VALIDATION] Template "${t.id}" data validation failed:\n${e}\n\nExpected schema: ${JSON.stringify(t.inputSchema,null,2)}`}],structuredContent:{kind:`error`,error:{code:`VIEWER_DATA_INVALID`,message:`Template "${t.id}" data validation failed:\n${e}\n\nExpected schema: ${JSON.stringify(t.inputSchema,null,2)}`}},isError:!0}}}let n=ah(_m(t.resolveHtml(),e.data??null,t.injectId,t.transformData)),r=wr({title:e.title,subtitle:e.description,html:[`<div class="present-viewer-container">`,` <iframe class="present-viewer-iframe" src="/viewer" sandbox="allow-scripts allow-same-origin"></iframe>`,` <script>
|
|
2892
2892
|
(function() {
|
|
2893
2893
|
const iframe = document.querySelector('.present-viewer-iframe');
|
|
2894
2894
|
if (!iframe) return;
|
|
@@ -2904,10 +2904,10 @@ window.addEventListener('message', function(e) {
|
|
|
2904
2904
|
})();
|
|
2905
2905
|
<\/script>`,`</div>`].join(`
|
|
2906
2906
|
`),css:[[`.present-viewer-container {`,` flex: 1;`,` min-height: calc(100vh - 12rem);`,` position: relative;`,` border-radius: 0.75rem;`,` overflow: hidden;`,` border: none;`,`}`,`.present-viewer-iframe {`,` border: none;`,` width: 100%;`,` height: 100%;`,` position: absolute;`,` inset: 0;`,` border-radius: inherit;`,`}`].join(`
|
|
2907
|
-
`)],islands:[],payload:void 0,nonce:``,generatedAt:new Date().toISOString(),colorScheme:e.colorScheme,lang:e.lang,dir:e.dir,transport:`browser`,exportPolicy:`local-interactive
|
|
2908
|
-
`),css:t.css,islands:t.islands,payload:t.payload,nonce:t.nonce,generatedAt:new Date().toISOString(),colorScheme:e.colorScheme,lang:e.lang,dir:e.dir,transport:`browser`,exportPolicy:t.exportPolicy,headScripts:r}),o=``,s=``,c=!1;try{let e=X;e&&(e.close(),X=null),o=await new Promise((e,t)=>{let r=Nr((e,t)=>{try{if(c=!0,e.method===`OPTIONS`){t.writeHead(204,{"Access-Control-Allow-Origin":s||`*`,"Access-Control-Allow-Methods":`POST`,"Access-Control-Allow-Headers":`Content-Type`}),t.end();return}if(e.method===`POST`&&e.url===`/callback`){n.handle(e,t,s).catch(()=>{
|
|
2909
|
-
`)}),r.length=0)},a=0;for(;a<t.length;){let e=t[a],o=t[a+1];if(o!==void 0&&Eh.test(e)&&Dh.test(o)){let r=jh(e),o=[];i();let s=a+2;for(;s<t.length&&Mh(t[s],r.length);)o.push(jh(t[s])),s+=1;n.push({type:`table`,headers:r,rows:o}),a=s;continue}r.push(e),a+=1}return i(),n}function Ph(e){let t=kh(e);return!t||!Ah(t)?[e]:Nh(t).flatMap(e=>{if(e.type===`text`){let t=e.content.trim();return t.length>0?[{type:`markdown`,value:t}]:[]}return[{type:`table`,value:{headers:e.headers,rows:e.rows}}]})}function Fh(e){if(typeof e==`string`)return Oh.test(e);if(Array.isArray(e))return e.some(e=>Fh(e));if(!wh(e))return!1;let t=[`client`,`clientInfo`,`host`,`source`,`mode`,`name`,`title`,`channel`];return Object.entries(e).some(([e,n])=>t.includes(e)?Fh(n):!1)}function Ih(e,t){return{preferBrowser:[t,e._meta,wh(e.metadata)?e.metadata.source:void 0].some(e=>Fh(e))}}function Lh(e){if(!e.template)return!0;let t=
|
|
2910
|
-
`)}const zh={id:`__dismiss`,type:`button`,label:`Done`,variant:`default`};function Bh(e){if((e.actions?.length??0)>0||!e.template)return e;let t=
|
|
2907
|
+
`)],islands:[],payload:void 0,nonce:``,generatedAt:new Date().toISOString(),colorScheme:e.colorScheme,lang:e.lang,dir:e.dir,transport:`browser`,exportPolicy:`local-interactive`,footerContentHtml:lm}),i=``;try{oh(),i=await new Promise((e,t)=>{let a=Nr((e,t)=>{try{if(e.url?.startsWith(`/__aikit_screenshot.png`)){lh(t,i);return}if(e.url===`/viewer`){t.writeHead(200,{"Content-Type":`text/html; charset=utf-8`}),t.end(n);return}t.writeHead(200,{"Content-Type":`text/html; charset=utf-8`}),t.end(r)}catch{sh(t)}});a.listen(0,`127.0.0.1`,()=>{let n=a.address();if(typeof n!=`object`||!n){t(Error(`Failed to resolve local browser address`));return}X=a,e(`http://127.0.0.1:${n.port}`)})})}catch(t){return{content:[{type:`text`,text:`${e.title}\n\nUnable to start local browser transport.`}],structuredContent:{kind:`error`,error:{code:`BROWSER_START_FAILED`,message:t instanceof Error?t.message:`Unable to start browser transport`}},isError:!0}}await eh(i);let a=X;return a&&setTimeout(()=>{X===a&&(a.close(),X=null)},Ym),{content:[{type:`text`,text:th(e,i,`Rendered.`)}],structuredContent:{kind:`rendered`,reason:`no-response-required`}}}async function dh(e){Ch(`<html><body style="font-family:system-ui;padding:2rem;color:#888;text-align:center"><p>Content opened in browser window.</p></body></html>`);let t=Mr(e,{transport:`browser`,registry:Bm,blockVendorScripts:Yp()}),n=cm(t.surfaceId,t.actions),r=qm(t.vendorScripts,`browser`),i=Jm(),a=wr({title:e.title,subtitle:e.description,html:[t.html,Qm(t.actions,n.nonce)].filter(Boolean).join(`
|
|
2908
|
+
`),css:t.css,islands:t.islands,payload:t.payload,nonce:t.nonce,generatedAt:new Date().toISOString(),colorScheme:e.colorScheme,lang:e.lang,dir:e.dir,transport:`browser`,exportPolicy:t.exportPolicy,footerContentHtml:lm,headScripts:r}),o=``,s=``,c=!1;try{let e=X;e&&(e.close(),X=null),o=await new Promise((e,t)=>{let r=Nr((e,t)=>{try{if(c=!0,e.method===`OPTIONS`){t.writeHead(204,{"Access-Control-Allow-Origin":s||`*`,"Access-Control-Allow-Methods":`POST`,"Access-Control-Allow-Headers":`Content-Type`}),t.end();return}if(e.method===`POST`&&e.url===`/callback`){n.handle(e,t,s).catch(()=>{sh(t)});return}if(e.url?.startsWith(`/__aikit_screenshot.png`)){lh(t,o||s);return}let r=i.find(t=>e.url===t.route);if(r){let e=r.getSource();if(e){t.writeHead(200,{"Content-Type":`application/javascript; charset=utf-8`,"Cache-Control":`public, max-age=86400`}),t.end(e);return}t.writeHead(302,{Location:r.cdn}),t.end();return}let l=ih(e.url);if(l)try{let e=N(l,`utf8`);t.writeHead(200,{"Content-Type":`application/javascript; charset=utf-8`}),t.end(e);return}catch{}t.writeHead(200,{"Content-Type":`text/html; charset=utf-8`}),t.end(a)}catch{sh(t)}});r.listen(0,`127.0.0.1`,()=>{let n=r.address();if(typeof n!=`object`||!n){t(Error(`Failed to resolve local browser address`));return}X=r,s=`http://127.0.0.1:${n.port}`,e(s)})})}catch(t){return{content:[{type:`text`,text:`${e.title}\n\nUnable to start local browser transport.`}],structuredContent:n.settleError(`BROWSER_START_FAILED`,t instanceof Error?t.message:`Unable to start browser transport`),isError:!0}}let l=await eh(o);if(!nh(t.actions)){let t=X;return t&&(n.promise.finally(()=>{X===t&&(t.close(),X=null)}),setTimeout(()=>{X===t&&(t.close(),X=null)},Ym)),{content:[{type:`text`,text:th(e,o,`Rendered.`)}],structuredContent:{kind:`rendered`,reason:`no-response-required`}}}let u=await Promise.race([n.promise,new Promise(e=>{setTimeout(()=>{c||(oh(),e(n.settleError(`BROWSER_CONNECT_TIMEOUT`,l?`No browser client connected within ${Xm}ms.`:`Fell back to system browser, but no browser client connected within ${Xm}ms.`)))},Xm)}),new Promise(e=>{setTimeout(()=>e(n.settleTimeout(Ym)),Ym)})]),d=X;d&&setTimeout(()=>{X===d&&(d.close(),X=null)},Ym);let f=u.kind===`result`?`Selected action: ${u.result.actionId}`:u.kind===`timeout`?`Timed out after ${u.waitedMs}ms.`:u.kind===`cancelled`?`Cancelled: ${u.reason}.`:u.kind===`error`?`Error: ${u.error.message}`:`Rendered.`;return{content:[{type:`text`,text:th(e,o,f)}],structuredContent:u,isError:u.kind===`error`}}const fh=`openai/outputTemplate`,ph=`ui/resourceUri`,mh={connectDomains:[],resourceDomains:[]},hh={connect_domains:[],resource_domains:[]};function gh(e){return{ui:{resourceUri:e,visibility:[`model`,`app`]},[ph]:e,[fh]:e,"openai/widgetAccessible":!0}}function _h(){return{ui:{prefersBorder:!1,csp:mh},"openai/widgetDescription":`AI Kit renders structured visual surfaces such as dashboards, charts, reports, and diagrams.`,"openai/widgetPrefersBorder":!1,"openai/widgetCSP":hh}}function vh(e){return{ui:{resourceUri:e},[ph]:e,[fh]:e}}function yh(e){return{...e,schemaVersion:1}}const bh=`ui://aikit/present.html`;let xh=``;function Sh(){return xh}function Ch(e){xh=e}function wh(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const Th=/\\u[0-9a-fA-F]{4}/,Eh=/^\s*\|(?:[^|\r\n]+\|){2,}\s*$/,Dh=/^\s*\|?(?:\s*:?-{3,}:?\s*\|){2,}\s*$/,Oh=/\b(cli|terminal|tty|console|command(?:-|\s)?line)\b/i;function kh(e){let t=[e.value,e.markdown,e.text,e.content];for(let e of t)if(typeof e==`string`&&e.trim().length>0)return e}function Ah(e){let t=e.split(/\r?\n/);for(let e=0;e<t.length-1;e+=1)if(Eh.test(t[e])&&Dh.test(t[e+1]))return!0;return!1}function jh(e){let t=e.trim().split(`|`),n=+(t[0]?.trim()===``),r=t.at(-1)?.trim()===``?t.length-1:t.length;return t.slice(n,r).map(e=>e.trim())}function Mh(e,t){if(t<2)return!1;let n=e.trim();return n.startsWith(`|`)?jh(n).length===t:!1}function Nh(e){let t=e.split(/\r?\n/),n=[],r=[],i=()=>{r.length!==0&&(n.push({type:`text`,content:r.join(`
|
|
2909
|
+
`)}),r.length=0)},a=0;for(;a<t.length;){let e=t[a],o=t[a+1];if(o!==void 0&&Eh.test(e)&&Dh.test(o)){let r=jh(e),o=[];i();let s=a+2;for(;s<t.length&&Mh(t[s],r.length);)o.push(jh(t[s])),s+=1;n.push({type:`table`,headers:r,rows:o}),a=s;continue}r.push(e),a+=1}return i(),n}function Ph(e){let t=kh(e);return!t||!Ah(t)?[e]:Nh(t).flatMap(e=>{if(e.type===`text`){let t=e.content.trim();return t.length>0?[{type:`markdown`,value:t}]:[]}return[{type:`table`,value:{headers:e.headers,rows:e.rows}}]})}function Fh(e){if(typeof e==`string`)return Oh.test(e);if(Array.isArray(e))return e.some(e=>Fh(e));if(!wh(e))return!1;let t=[`client`,`clientInfo`,`host`,`source`,`mode`,`name`,`title`,`channel`];return Object.entries(e).some(([e,n])=>t.includes(e)?Fh(n):!1)}function Ih(e,t){return{preferBrowser:[t,e._meta,wh(e.metadata)?e.metadata.source:void 0].some(e=>Fh(e))}}function Lh(e){if(!e.template)return!0;let t=mm(e.template);return t?t.supportedTransports.includes(`browser`):Vm(e)?.supportedTransports.includes(`browser`)??!1}function Rh(e,t,n={}){let r=n.includeSurfaceHeader??!0,i=r?[e.title]:[];return r&&e.description&&i.push(e.description),kr(t)?i.push(``,`Selected action: ${t.result.actionId}`):Or(t)?i.push(``,`Error: ${t.error.message}`):t.kind===`timeout`?i.push(``,`Timed out after ${t.waitedMs}ms.`):t.kind===`cancelled`?i.push(``,`Cancelled: ${t.reason}.`):r||i.push(`Rendered inline.`),i.join(`
|
|
2910
|
+
`)}const zh={id:`__dismiss`,type:`button`,label:`Done`,variant:`default`};function Bh(e){if((e.actions?.length??0)>0||!e.template)return e;let t=Vm(e);return t?.supportedTransports.includes(`browser`)===!0&&!t.supportedTransports.includes(`mcp-app`)?{...e,actions:[zh]}:e}function Vh(e){return e.replace(`</head>`,`<style>
|
|
2911
2911
|
.toolbar, .badge, body > header, body > footer { display: none !important; }
|
|
2912
2912
|
body { padding-top: 0 !important; margin-top: 0 !important; }
|
|
2913
2913
|
</style>
|
|
@@ -2941,8 +2941,8 @@ window.addEventListener('message', function(e) {
|
|
|
2941
2941
|
else{setInterval(notify,500)}
|
|
2942
2942
|
})();
|
|
2943
2943
|
<\/script>`;return e.includes(`</body>`)?e.replace(`</body>`,`${t}</body>`):`${e}${t}`}function Uh(e,t){return[`<!DOCTYPE html>`,`<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">`,`<title>Error — ${Y(e)}</title>`,`<style>`,` * { box-sizing: border-box; margin: 0; padding: 0; }`,` body { font-family: system-ui, -apple-system, sans-serif; min-height: 100vh; display: flex; align-items: center; justify-content: center; padding: 2rem; background: #fafafa; color: #333; }`,` .error-card { max-width: 560px; width: 100%; padding: 2.5rem; border-radius: 1rem; background: #fff; border: 1px solid #e5e7eb; box-shadow: 0 1px 3px rgba(0,0,0,0.06); }`,` .error-badge { display: inline-block; font-size: 0.75rem; font-weight: 600; text-transform: uppercase; letter-spacing: 0.05em; color: #dc2626; background: #fef2f2; border: 1px solid #fecaca; border-radius: 0.375rem; padding: 0.25rem 0.625rem; margin-bottom: 1rem; }`,` .error-title { font-size: 1.25rem; font-weight: 600; margin-bottom: 0.75rem; color: #111; }`,` .error-message { font-size: 0.875rem; line-height: 1.6; color: #6b7280; white-space: pre-wrap; word-break: break-word; }`,`</style></head><body>`,`<div class="error-card">`,` <span class="error-badge">Render Error</span>`,` <h1 class="error-title">${Y(e)}</h1>`,` <p class="error-message">${Y(t)}</p>`,`</div>`,`</body></html>`].join(`
|
|
2944
|
-
`)}function Wh(e,t,n,r){return Ch(Uh(r??`Present`,t)),{content:[{type:`text`,text:`[ERROR:VALIDATION] ${t}`}],isError:!0}}function Gh(e,t){if(!wh(e)||!(`schemaVersion`in e))return{ok:!1,response:Wh(`INVALID_CHANNEL_SURFACE`,`present expects a ChannelSurface object with schemaVersion: 1`)};if(e.schemaVersion!==1)return{ok:!1,response:Wh(`UNSUPPORTED_SCHEMA_VERSION`,`Unsupported ChannelSurface schemaVersion: ${String(e.schemaVersion)}`)};if(typeof e.title==`string`&&Th.test(e.title))return{ok:!1,response:Wh(`TITLE_UNICODE_ESCAPE_NOT_ALLOWED`,`Use actual Unicode characters in title, not escape sequences.`)};let n=Array.isArray(e.blocks)?{...e,blocks:e.blocks.flatMap(e=>{if(!wh(e)||e.type!==`markdown`)return[e];let t=kh(e);return!t||!Ah(t)?[e]:Ph(e)})}:e;return{ok:!0,surface:n,options:Ih(n,t)}}async function Kh(e,t={}){let n=Bh(e);if(e.template){let r=
|
|
2945
|
-
`);return Wh(`VIEWER_DATA_INVALID`,`Template "${t.id}" data validation failed:\n${r}\n\nExpected schema: ${JSON.stringify(t.inputSchema,null,2)}`,void 0,e.title)}}let r=t.supportedTransports.includes(`browser`),i=t.supportedTransports.includes(`mcp-app`);if(n.preferBrowser&&r||r&&!i)return await
|
|
2944
|
+
`)}function Wh(e,t,n,r){return Ch(Uh(r??`Present`,t)),{content:[{type:`text`,text:`[ERROR:VALIDATION] ${t}`}],isError:!0}}function Gh(e,t){if(!wh(e)||!(`schemaVersion`in e))return{ok:!1,response:Wh(`INVALID_CHANNEL_SURFACE`,`present expects a ChannelSurface object with schemaVersion: 1`)};if(e.schemaVersion!==1)return{ok:!1,response:Wh(`UNSUPPORTED_SCHEMA_VERSION`,`Unsupported ChannelSurface schemaVersion: ${String(e.schemaVersion)}`)};if(typeof e.title==`string`&&Th.test(e.title))return{ok:!1,response:Wh(`TITLE_UNICODE_ESCAPE_NOT_ALLOWED`,`Use actual Unicode characters in title, not escape sequences.`)};let n=Array.isArray(e.blocks)?{...e,blocks:e.blocks.flatMap(e=>{if(!wh(e)||e.type!==`markdown`)return[e];let t=kh(e);return!t||!Ah(t)?[e]:Ph(e)})}:e;return{ok:!0,surface:n,options:Ih(n,t)}}async function Kh(e,t={}){let n=Bh(e);if(e.template){let r=mm(e.template);if(r)return await qh(n,r,t)}return Hm(n)||t.preferBrowser&&Lh(n)?await dh(n):Jh(n)}async function qh(e,t,n={}){if(e.data!=null&&t.inputSchema){let n=ln({data:e.data,schema:t.inputSchema});if(!n.valid){let r=n.errors.map(e=>` ${e.path}: ${e.message}${e.expected?` (expected: ${e.expected}, got: ${e.received})`:``}`).join(`
|
|
2945
|
+
`);return Wh(`VIEWER_DATA_INVALID`,`Template "${t.id}" data validation failed:\n${r}\n\nExpected schema: ${JSON.stringify(t.inputSchema,null,2)}`,void 0,e.title)}}let r=t.supportedTransports.includes(`browser`),i=t.supportedTransports.includes(`mcp-app`);if(n.preferBrowser&&r||r&&!i)return await uh(e,t);if(!i)return Wh(`VIEWER_TRANSPORT_UNSUPPORTED`,`Viewer template "${t.id}" does not support an available transport`,void 0,e.title);try{let n=Vh(_m(t.resolveHtml(),e.data??null,t.injectId,t.transformData)).replace(/&/g,`&`).replace(/"/g,`"`);return Ch(Hh(wr({title:e.title,subtitle:e.description,html:[`<div class="present-viewer-container">`,` <iframe class="present-viewer-iframe" srcdoc="${n}" sandbox="allow-scripts allow-same-origin"></iframe>`,` <script>
|
|
2946
2946
|
(function() {
|
|
2947
2947
|
const iframe = document.querySelector('.present-viewer-iframe');
|
|
2948
2948
|
if (!iframe) return;
|
|
@@ -2965,8 +2965,8 @@ window.addEventListener('message', function(e) {
|
|
|
2965
2965
|
});
|
|
2966
2966
|
<\/script>`,`</div>`].join(`
|
|
2967
2967
|
`),css:[[`.present-viewer-container {`,` flex: 1;`,` min-height: 640px;`,` position: relative;`,` border-radius: 0.75rem;`,` overflow: hidden;`,` border: none;`,`}`,`.present-viewer-iframe {`,` border: none;`,` width: 100%;`,` height: 100%;`,` position: absolute;`,` inset: 0;`,` border-radius: inherit;`,`}`].join(`
|
|
2968
|
-
`)],islands:[],payload:void 0,nonce:``,generatedAt:new Date().toISOString(),footerContentHtml:
|
|
2969
|
-
`);gr(e,`present`,{title:n.title,description:r,inputSchema:Qh,annotations:n.annotations,_meta:
|
|
2968
|
+
`)],islands:[],payload:void 0,nonce:``,generatedAt:new Date().toISOString(),footerContentHtml:lm,colorScheme:e.colorScheme,lang:e.lang,dir:e.dir,transport:`mcp-app`,exportPolicy:`local-interactive`}))),{content:[{type:`text`,text:Rh(e,{kind:`rendered`,reason:`no-response-required`},{includeSurfaceHeader:!1})}],structuredContent:yh(e),_meta:vh(bh),ui:{type:`resource`,uri:bh}}}catch(t){return Wh(`VIEWER_RENDER_FAILED`,t instanceof Error?t.message:`Failed to render viewer template`,void 0,e.title)}}function Jh(e){try{let t=Mr(e,{transport:`mcp-app`,registry:Bm,blockVendorScripts:Yp()}),n=qm(t.vendorScripts,`mcp-app`);return xh=Hh(wr({title:e.title,subtitle:e.description,html:t.html,css:t.css,islands:t.islands,payload:t.payload,nonce:t.nonce,colorScheme:e.colorScheme,lang:e.lang,dir:e.dir,transport:`mcp-app`,exportPolicy:t.exportPolicy,footerContentHtml:lm,headScripts:n})),{content:[{type:`text`,text:Rh(e,{kind:`rendered`,reason:`no-response-required`},{includeSurfaceHeader:!1})}],structuredContent:yh(e),_meta:vh(bh),ui:{type:`resource`,uri:bh}}}catch(t){return Wh(`RENDER_FAILED`,t instanceof Error?t.message:`Failed to render ChannelSurface`,void 0,e.title)}}const Yh=z.object({label:z.string(),value:z.string(),description:z.string().optional()}),Xh=z.object({id:z.string().describe(`Unique action identifier`),type:z.enum([`button`,`select`,`multi-select`,`form-submit`,`text-submit`,`confirm`,`custom`]).describe(`Interactive action type`),label:z.string().describe(`Visible action label`),variant:z.enum([`primary`,`danger`,`default`]).optional(),options:z.array(Yh).optional(),schema:z.record(z.string(),z.unknown()).optional()}),Zh=z.object({type:z.string(),title:z.string().optional(),value:z.unknown().optional(),language:z.string().optional()}).catchall(z.unknown()),Qh={schemaVersion:z.literal(1).describe(`ChannelSurface schema version. Must be 1.`),title:z.string().describe(`Surface title shown to the user.`),description:z.string().optional().describe(`Optional supporting copy for the surface.`),template:z.string().optional().describe(`Optional template id such as report@1.`),layout:z.object({maxWidth:z.string().optional(),padding:z.string().optional(),columns:z.number().optional()}).optional(),blocks:z.array(Zh).optional().describe(`Typed block content for the surface.`),data:z.unknown().optional().describe(`Template data payload, if the template expands data.`),actions:z.array(Xh).optional().describe(`Interactive actions. Presence triggers browser transport.`),response:z.object({timeout:z.number().optional(),required:z.boolean().optional()}).optional(),metadata:z.object({surfaceId:z.string().optional(),createdAt:z.string().optional(),source:z.string().optional()}).optional(),colorScheme:z.enum([`light`,`dark`,`auto`]).optional(),lang:z.string().optional(),dir:z.enum([`ltr`,`rtl`,`auto`]).optional()};z.object({surfaceId:z.string(),actionId:z.string(),actionType:z.enum([`button`,`select`,`multi-select`,`form-submit`,`text-submit`,`confirm`,`custom`]),value:z.unknown().optional(),formData:z.record(z.string(),z.unknown()).optional(),selection:z.union([z.string(),z.array(z.string())]).optional(),label:z.string().optional(),timestamp:z.string(),sourceTransport:z.enum([`mcp-app`,`browser`,`export`])});function $h(e){let t=e.server?.getClientCapabilities?.();if(!t)return`unknown`;let n=mr(t);return!n||Array.isArray(n.mimeTypes)&&n.mimeTypes.length>0&&!n.mimeTypes.includes(pr)?`unsupported`:`supported`}function eg(e,t){let n=W(`present`),r=[`Render a ChannelSurface for the user.`,`Quick ref:`,`- Full schema: aikit://schemas/channel-surface`,`- Required: schemaVersion: 1, title`,`- Content: blocks[] for direct rendering, or template + data for registry-backed rendering`,`- Actions: actions[] of SurfaceAction; interactive surfaces use browser transport and return ChannelOutcome`,`- Optional fields: description, layout, response, metadata, colorScheme, lang, dir`,`- Transports: mcp-app, browser, export`,`- Use schema resource for block enums and action details.`].join(`
|
|
2969
|
+
`);gr(e,`present`,{title:n.title,description:r,inputSchema:Qh,annotations:n.annotations,_meta:gh(bh)},J(`present`,async(t,n)=>{let r=Gh(t,n);if(!r.ok)return r.response;let i=$h(e);return await Kh(r.surface,{...r.options,preferBrowser:r.options.preferBrowser||i===`unsupported`})}));try{hr(e,`Present View`,bh,{description:`AI Kit present tool viewer`,_meta:_h()},async()=>({contents:[{uri:bh,mimeType:pr,_meta:_h(),text:Sh()||`<html><body><p>No content generated yet. Call the present tool first.</p></body></html>`}]}))}catch{}try{e.registerResource(`present-templates`,`aikit://present/templates`,{description:`List all registered present viewer templates with their input schemas`},async()=>{let e=gm().map(e=>({id:e.id,label:e.label,description:e.description,transports:e.supportedTransports,inputSchema:e.inputSchema}));return{contents:[{uri:`aikit://present/templates`,mimeType:`application/json`,text:JSON.stringify(e,null,2)}]}})}catch{}}const tg=I(`tools`);function ng(e,t){let n=new er({structure:new nr,dependencies:new Zn,symbols:new rr,patterns:new tr,entryPoints:new $n,diagrams:new Qn}),r=W(`produce_knowledge`);e.registerTool(`produce_knowledge`,{title:r.title,description:`Run automated codebase analysis and produce synthesis instructions. Executes Tier 1 deterministic analyzers, then returns structured baselines and instructions for you to synthesize knowledge using remember.`,inputSchema:{scope:z.string().optional().describe(`Root path to analyze (defaults to workspace root)`),aspects:z.array(z.enum([`all`,`structure`,`dependencies`,`symbols`,`patterns`,`entry-points`,`diagrams`])).default([`all`]).describe(`Which analysis aspects to run`)},annotations:r.annotations},J(`produce_knowledge`,async({scope:e,aspects:r},i)=>{let a;try{a=zc(i).createTask(`Produce Knowledge`,3),a.progress(0,`Running analyzers`);let o=e??`.`;tg.info(`Running knowledge production`,{rootPath:o,aspects:r});let s=await n.runExtraction(o,r);try{let e=t?.onboardDir??``;if(!e)throw tg.warn(`onboardDir not configured — skipping artifact persistence.`),Error(`skip`);M(e,{recursive:!0});let n=`<!-- Generated by produce_knowledge at ${new Date().toISOString()} -->\n\n`;for(let[t,r]of Object.entries(s))r&&typeof r==`string`&&me(P(e,`${t}.md`),n+r,`utf-8`);tg.info(`Knowledge persisted to .ai/context/`,{files:Object.keys(s).length})}catch(e){tg.warn(`Failed to persist knowledge to .ai/context/`,{error:L(e)})}a.progress(1,`Synthesizing results`);let c=n.buildSynthesisInstructions(s,r);return a.complete(`Knowledge production complete`),{content:[{type:`text`,text:c+`
|
|
2970
2970
|
|
|
2971
2971
|
---
|
|
2972
2972
|
_Next: Review the baselines above and use \`remember\` to store synthesized knowledge entries._`}]}}catch(e){return a?.fail?.(`Production failed`),tg.error(`Knowledge production failed`,L(e)),q(`INTERNAL`,`Knowledge production failed: ${e instanceof Error?e.message:String(e)}`)}}))}const rg=I(`tools`);function ig(e,t,n,r,i,a,o){let s=W(`reindex`);e.registerTool(`reindex`,{title:s.title,description:`Trigger re-indexing of the AI Kit index. Can do incremental (only changed files) or full re-index. When smart indexing is active, use force: true to override the automatic trickle indexer.`,inputSchema:{full:z.boolean().default(!1).describe(`If true, force full re-index ignoring file hashes`),force:z.boolean().default(!1).describe(`If true, override smart indexing guard and run reindex anyway`)},annotations:s.annotations},J(`reindex`,async({full:e,force:s},c)=>{try{if(t.isIndexing)return{content:[{type:`text`,text:`## Reindex Already in Progress
|