@vpxa/aikit 0.1.250 → 0.1.251
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/blocks-interactive/dist/index.mjs +2 -2
- package/packages/present/dist/index.html +9 -9
- package/packages/server/dist/bin.js +1 -1
- package/packages/server/dist/index.js +1 -1
- package/packages/server/dist/{server-CBs_q9S9.js → server-CzPRmJtW.js} +146 -146
- package/packages/server/dist/{server-0JRtGGti.js → server-D-PQVQ3u.js} +146 -146
- package/packages/tools/dist/index.d.ts +34 -5
- package/packages/tools/dist/index.js +61 -61
- package/scaffold/dist/definitions/bodies.mjs +3 -3
- package/scaffold/dist/definitions/flows.mjs +1 -1
- package/scaffold/dist/definitions/protocols.mjs +2 -0
- package/scaffold/dist/definitions/skills/aikit.mjs +2 -2
package/package.json
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as e,i as t,n,r}from"./payload-DyKkZIOX.mjs";
|
|
1
|
+
import{a as e,i as t,n,r}from"./payload-DyKkZIOX.mjs";function i(e,t){let n=[];for(let r of Array.from(e.querySelectorAll(`[data-action-id]`))){let e=r.getAttribute(`data-action-id`);if(!e)continue;if(r.tagName===`SELECT`){let i=r,a=()=>{t(e,i.value)};i.addEventListener(`change`,a),n.push(()=>{i.removeEventListener(`change`,a)});continue}let i=()=>{t(e)};r.addEventListener(`click`,i),n.push(()=>{r.removeEventListener(`click`,i)})}return()=>{for(let e of n)e()}}function a(e){let t=e.createElement(`style`);return t.textContent=`
|
|
2
2
|
.bk-checklist-progress {
|
|
3
3
|
margin-bottom: var(--dt-space-3);
|
|
4
4
|
color: var(--dt-text-secondary);
|
|
@@ -12,4 +12,4 @@ import{a as e,i as t,n,r}from"./payload-DyKkZIOX.mjs";var i=Object.definePropert
|
|
|
12
12
|
margin: 0;
|
|
13
13
|
accent-color: var(--dt-accent-fg);
|
|
14
14
|
}
|
|
15
|
-
`,t}function
|
|
15
|
+
`,t}function o(e,t){let n=t.filter(e=>e.getAttribute(`data-checked`)===`true`).length,r=t.length;return e.textContent=`${n}/${r} complete`,{complete:n,total:r}}function s(e,t={}){let n=Array.from(e.querySelectorAll(`.bk-checklist-item`));if(n.length===0)return()=>{};let r=e.ownerDocument,i=a(r),s=r.createElement(`div`);s.className=`bk-checklist-progress`,e.parentElement?.insertBefore(s,e),r.head?.appendChild(i);let c=[];for(let[e,i]of n.entries()){let a=i.querySelector(`.bk-checklist-icon`),l=i.querySelector(`.bk-checklist-label`)?.textContent?.trim()??``,u=r.createElement(`input`);u.type=`checkbox`,u.className=`bk-checklist-box`,u.checked=i.getAttribute(`data-checked`)===`true`;let d=()=>{i.setAttribute(`data-checked`,String(u.checked));let r=o(s,n);t.onAction?.(`checklist`,JSON.stringify({index:e,label:l,checked:u.checked,complete:r.complete,total:r.total}))};u.addEventListener(`change`,d),c.push(()=>{u.removeEventListener(`change`,d)}),a?a.replaceWith(u):i.insertBefore(u,i.firstChild)}return o(s,n),()=>{for(let e of c)e();s.remove(),i.remove();for(let e of n){let t=e.querySelector(`.bk-checklist-box`);if(!t)continue;let n=r.createElement(`span`);n.className=`bk-checklist-icon`,n.textContent=e.getAttribute(`data-checked`)===`true`?`✓`:`×`,t.replaceWith(n)}}}const c=`data-sort-label`,l=`data-sort-dir`,u=new Intl.Collator(void 0,{numeric:!0,sensitivity:`base`});function d(e){let t=e.getAttribute(c);if(t!==null)return t;let n=e.textContent?.trim()??``;return e.setAttribute(c,n),n}function f(e,t,n){for(let[r,i]of e.entries())i.textContent=d(i),r===t?(i.setAttribute(l,n),i.append(` ${n===`asc`?`▲`:`▼`}`)):i.removeAttribute(l)}function p(e,t){return e.querySelectorAll(`td`)[t]?.textContent?.trim()??``}function m(e){let t=Array.from(e.querySelectorAll(`thead th`)),n=e.querySelector(`tbody`);if(!n||t.length===0)return()=>{};let r=Array.from(n.querySelectorAll(`tr`)),i=e.parentElement,a=null,o=`asc`,s=``,m=null,h=[],g=()=>{let e=[...r];if(a!==null){let t=a;e.sort((e,n)=>{let r=u.compare(p(e,t),p(n,t));return o===`asc`?r:-r})}for(let t of e){n.appendChild(t);let e=t.textContent?.toLowerCase()??``;t.hidden=s.length>0&&!e.includes(s)}f(t,a,o)};for(let[e,n]of t.entries()){d(n);let t=()=>{a===e?o=o===`asc`?`desc`:`asc`:(a=e,o=`asc`),g()};n.style.cursor=`pointer`,n.addEventListener(`click`,t),h.push(()=>{n.removeEventListener(`click`,t)})}if(r.length>5&&i){m=i.ownerDocument.createElement(`input`),m.className=`bk-table-filter`,m.placeholder=`Filter...`;let t=()=>{s=m?.value.toLowerCase().trim()??``,g()};i.insertBefore(m,e),m.addEventListener(`input`,t),h.push(()=>{m?.removeEventListener(`input`,t),m?.remove(),m=null})}return g(),()=>{for(let e of h)e();for(let e of t)e.textContent=d(e),e.removeAttribute(l),e.removeAttribute(c),e.style.removeProperty(`cursor`);for(let e of r)e.hidden=!1}}function h(e){for(let t of Array.from(e.children))if(t.tagName===`SUMMARY`)return t;return null}function g(e){let t=e.closest(`details`);if(!t)return null;let n=t.parentElement;for(;n;){if(n.tagName===`DETAILS`)return h(n);n=n.parentElement}return null}function _(e){return Array.from(e.querySelectorAll(`summary`))}function v(e){return e.open||e.hasAttribute(`open`)}function y(e,t){e.open=t,t?e.setAttribute(`open`,``):e.removeAttribute(`open`)}function b(e,t){e.textContent=t.every(e=>v(e))?`Collapse all`:`Expand all`}function x(e){let t=Array.from(e.querySelectorAll(`details`));if(t.length===0)return()=>{};let n=e.ownerDocument.createElement(`button`);n.type=`button`,n.className=`bk-tree-toggle-all`,e.insertBefore(n,e.firstChild);let r=()=>{let e=t.some(e=>!v(e));for(let n of t)y(n,e);b(n,t)},i=()=>{r()};n.addEventListener(`click`,i);let a=t.map(e=>{let r=()=>{b(n,t)};return e.addEventListener(`toggle`,r),()=>{e.removeEventListener(`toggle`,r)}}),o=_(e).map(t=>{t.tabIndex=0;let n=n=>{let r=_(e),i=r.indexOf(t);if(i===-1)return;let a=t.closest(`details`);if(n.key===`ArrowDown`){r[i+1]?.focus(),n.preventDefault();return}if(n.key===`ArrowUp`){r[i-1]?.focus(),n.preventDefault();return}if(n.key===`ArrowRight`){if(a&&!v(a))y(a,!0);else{let e=r[i+1];e&&a?.contains(e)&&e.focus()}n.preventDefault();return}n.key===`ArrowLeft`&&(a&&v(a)?y(a,!1):g(t)?.focus(),n.preventDefault())};return t.addEventListener(`keydown`,n),()=>{t.removeEventListener(`keydown`,n)}});return b(n,t),()=>{n.removeEventListener(`click`,i);for(let e of a)e();for(let e of o)e();n.remove()}}const S=[{selector:`.bk-table`,matches:e=>!r(e.ownerDocument),load:async()=>({hydrate:e=>m(e)})},{selector:`.bk-table`,matches:(t,n)=>r(t.ownerDocument)&&e(t,`.bk-table`,n),load:()=>import(`./form-SyIoFeT1.mjs`).then(e=>({hydrate:(t,n)=>e.hydrateForm(t,n)}))},{selector:`.bk-tree`,matches:e=>!n(e.ownerDocument),load:async()=>({hydrate:e=>x(e)})},{selector:`.bk-tree`,matches:e=>n(e.ownerDocument),load:()=>import(`./flame-graph-CV8KCLKu.mjs`).then(e=>({hydrate:(t,n)=>e.hydrateFlameGraph(t,n)}))},{selector:`.bk-actions`,load:async()=>({hydrate:(e,t)=>t?.onAction?i(e,t.onAction):()=>{}})},{selector:`.bk-checklist`,load:async()=>({hydrate:(e,t)=>s(e,t)})},{selector:`.bk-cards`,matches:(n,r)=>t(n.ownerDocument)&&e(n,`.bk-cards`,r),load:()=>import(`./picker-CZJricO9.mjs`).then(e=>({hydrate:(t,n)=>e.hydratePicker(t,n)}))}],C=`data-hydrated`;function w(e,t){let n=[];return e.matches(t)&&n.push(e),n.push(...Array.from(e.querySelectorAll(t))),n}function T(e,t,n){e.push(()=>{n(),t.removeAttribute(C)})}function E(e={}){let t=e.container??document.body,n=[];for(let e of w(t,`.bk-table`))e.hasAttribute(C)||(e.setAttribute(C,``),T(n,e,m(e)));for(let e of w(t,`.bk-tree`))e.hasAttribute(C)||(e.setAttribute(C,``),T(n,e,x(e)));for(let r of w(t,`.bk-checklist`))r.hasAttribute(C)||(r.setAttribute(C,``),T(n,r,s(r,e)));for(let r of w(t,`.bk-actions`))if(!r.hasAttribute(C)){if(r.setAttribute(C,``),e.onAction){T(n,r,i(r,e.onAction));continue}n.push(()=>{r.removeAttribute(C)})}return()=>{for(let e of n)e();n.length=0}}async function D(e={}){let t=e.container??document.body,n={...e,container:t},r=[],i=S.map(e=>({definition:e,elements:w(t,e.selector).filter(t=>!t.hasAttribute(C)&&(e.matches?.(t,n)??!0))})).filter(({elements:e})=>e.length>0);if(i.length===0)return()=>{};let a=await Promise.all(i.map(async({definition:e,elements:t})=>({island:await e.load(),elements:t})));for(let{island:e,elements:t}of a)for(let i of t)i.hasAttribute(C)||(i.setAttribute(C,``),T(r,i,e.hydrate(i,n)));return()=>{for(let e of r)e();r.length=0}}export{S as ISLAND_REGISTRY,E as hydrate,i as hydrateActions,D as hydrateAsync,m as hydrateTable,x as hydrateTree};
|
|
@@ -1954,7 +1954,7 @@ Boolean requesting whether a visible border and background is provided by the ho
|
|
|
1954
1954
|
- omitted: host decides border`)}),I({method:V(`ui/request-display-mode`),params:I({mode:IS.describe(`The display mode being requested.`)})});var QS=I({mode:IS.describe(`The display mode that was actually set. May differ from requested if not supported.`)}).passthrough(),$S=R([V(`model`),V(`app`)]).describe(`Tool visibility scope - who can access the tool.`);I({resourceUri:j().optional(),visibility:F($S).optional().describe(`Who can access this tool. Default: ["model", "app"]
|
|
1955
1955
|
- "model": Tool visible to and callable by the agent
|
|
1956
1956
|
- "app": Tool callable by the app from this server only`),csp:h_().optional(),permissions:h_().optional()}),I({mimeTypes:F(j()).optional().describe('Array of supported MIME types for UI resources.\nMust include `"text/html;profile=mcp-app"` for MCP Apps support.')}),I({method:V(`ui/download-file`),params:I({contents:F(R([Tx,Ex])).describe(`Resource contents to download — embedded (inline data) or linked (host fetches). Uses standard MCP resource types.`)})}),I({method:V(`ui/message`),params:I({role:V(`user`).describe(`Message role, currently only "user" is supported.`),content:F(Dx).describe(`Message content blocks (text, image, etc.).`)})}),I({method:V(`ui/notifications/sandbox-resource-ready`),params:I({html:j().describe(`HTML content to load into the inner iframe.`),sandbox:j().optional().describe(`Optional override for the inner iframe's sandbox attribute.`),csp:VS.optional().describe(`CSP configuration from resource metadata.`),permissions:HS.optional().describe(`Sandbox permissions from resource metadata.`)})});var eC=I({method:V(`ui/notifications/tool-result`),params:Ix.describe(`Standard MCP tool execution result.`)}),tC=I({toolInfo:I({id:nb.optional().describe(`JSON-RPC id of the tools/call request.`),tool:Nx.describe(`Tool definition including name, inputSchema, etc.`)}).optional().describe(`Metadata of the tool call that instantiated this App.`),theme:FS.optional().describe(`Current color theme preference.`),styles:qS.optional().describe(`Style configuration for theming the app.`),displayMode:IS.optional().describe(`How the UI is currently displayed.`),availableDisplayModes:F(IS).optional().describe(`Display modes the host supports.`),containerDimensions:R([I({height:M().describe(`Fixed container height in pixels.`)}),I({maxHeight:R([M(),f_()]).optional().describe(`Maximum container height in pixels.`)})]).and(R([I({width:M().describe(`Fixed container width in pixels.`)}),I({maxWidth:R([M(),f_()]).optional().describe(`Maximum container width in pixels.`)})])).optional().describe(`Container dimensions. Represents the dimensions of the iframe or other
|
|
1957
|
-
container holding the app. Specify either width or maxWidth, and either height or maxHeight.`),locale:j().optional().describe(`User's language and region preference in BCP 47 format.`),timeZone:j().optional().describe(`User's timezone in IANA format.`),userAgent:j().optional().describe(`Host application identifier.`),platform:R([V(`web`),V(`desktop`),V(`mobile`)]).optional().describe(`Platform type for responsive design decisions.`),deviceCapabilities:I({touch:N().optional().describe(`Whether the device supports touch input.`),hover:N().optional().describe(`Whether the device supports hover interactions.`)}).optional().describe(`Device input capabilities.`),safeAreaInsets:I({top:M().describe(`Top safe area inset in pixels.`),right:M().describe(`Right safe area inset in pixels.`),bottom:M().describe(`Bottom safe area inset in pixels.`),left:M().describe(`Left safe area inset in pixels.`)}).optional().describe(`Mobile safe area boundaries in pixels.`)}).passthrough(),nC=I({method:V(`ui/notifications/host-context-changed`),params:tC.describe(`Partial context update containing only changed fields.`)});I({method:V(`ui/update-model-context`),params:I({content:F(Dx).optional().describe(`Context content blocks (text, image, etc.).`),structuredContent:z(j(),P().describe(`Structured content for machine-readable context data.`)).optional().describe(`Structured content for machine-readable context data.`)})}),I({method:V(`ui/initialize`),params:I({appInfo:_b.describe(`App identification (name and version).`),appCapabilities:ZS.describe(`Features and capabilities this app provides.`),protocolVersion:j().describe(`Protocol version this app supports.`)})});var rC=I({protocolVersion:j().describe(`Negotiated protocol version string (e.g., "2025-11-21").`),hostInfo:_b.describe(`Host application identification and version.`),hostCapabilities:XS.describe(`Features and capabilities provided by the host.`),hostContext:tC.describe(`Rich context about the host environment.`)}).passthrough(),iC={target:`draft-2020-12`};async function aC(e,t){let n=e[`~standard`];if(n.jsonSchema)return n.jsonSchema[t](iC);if(n.vendor===`zod`){let{z:n}=await jS(async()=>{let{z:e}=await Promise.resolve().then(()=>(Wy(),Hy));return{z:e}},void 0,import.meta.url);return n.toJSONSchema(e,{io:t})}throw Error(`Schema (vendor: ${n.vendor}) does not implement Standard JSON Schema (~standard.jsonSchema). Use a library that does (zod v4, ArkType, Valibot) or wrap your schema accordingly.`)}async function oC(e,t,n=``){let r=await e[`~standard`].validate(t);if(r.issues){let e=r.issues.map(e=>{let t=e.path?.map(e=>typeof e==`object`?e.key:e).join(`.`);return t?`${t}: ${e.message}`:e.message}).join(`; `);throw Error(n+e)}return r.value}function sC(){let e=document.documentElement.getAttribute(`data-theme`);return e===`dark`||e===`light`?e:document.documentElement.classList.contains(`dark`)?`dark`:`light`}function cC(e){let t=document.documentElement;t.setAttribute(`data-theme`,e),t.style.colorScheme=e}function lC(e,t=document.documentElement){for(let[n,r]of Object.entries(e))r!==void 0&&t.style.setProperty(n,r)}var uC=class e extends MS{_appInfo;_capabilities;options;_hostCapabilities;_hostInfo;_hostContext;_registeredTools={};_initializedSent=!1;_assertInitialized(e){if(this._initializedSent)return;let t=`[ext-apps] App.${e}() called before connect() completed the ui/initialize handshake. Await app.connect() before calling this method, or move data loading to an ontoolresult handler.`;if(this.options?.strict)throw Error(t);console.warn(`${t}. This will throw in a future release.`)}eventSchemas={toolinput:US,toolinputpartial:WS,toolresult:eC,toolcancelled:GS,hostcontextchanged:nC};static ONE_SHOT_EVENTS=new Set([`toolinput`,`toolinputpartial`,`toolresult`,`toolcancelled`]);_everHadListener=new Set;_assertHandlerTiming(t){if(!e.ONE_SHOT_EVENTS.has(t)||this._everHadListener.has(t)||(this._everHadListener.add(t),!this._initializedSent))return;let n=`[ext-apps] "${String(t)}" handler registered after connect() completed the ui/initialize handshake. The host may have already sent this notification. Register handlers before calling app.connect().`;if(this.options?.strict)throw Error(n);console.warn(n)}setEventHandler(e,t){t&&this._assertHandlerTiming(e),super.setEventHandler(e,t)}addEventListener(e,t){this._assertHandlerTiming(e),super.addEventListener(e,t)}onEventDispatch(e,t){e===`hostcontextchanged`&&(this._hostContext={...this._hostContext,...t})}constructor(e,t={},n={autoResize:!0}){super(n),this._appInfo=e,this._capabilities=t,this.options=n,n.allowUnsafeEval||h({jitless:!0}),this.setRequestHandler(Db,e=>(console.log(`Received ping:`,e.params),{})),this.setEventHandler(`hostcontextchanged`,void 0)}registerCapabilities(e){if(this.transport)throw Error(`Cannot register capabilities after transport is established`);this._capabilities=DS(this._capabilities,e)}registerTool(e,t,n){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let r=this,i=()=>{r._initializedSent&&r._capabilities.tools?.listChanged&&r.sendToolListChanged()},a=t.inputSchema!==void 0,o={title:t.title,description:t.description,inputSchema:t.inputSchema,outputSchema:t.outputSchema,annotations:t.annotations,_meta:t._meta,enabled:!0,enable(){this.enabled=!0,i()},disable(){this.enabled=!1,i()},update(e){Object.assign(this,e),i()},remove(){r._registeredTools[e]===o&&(delete r._registeredTools[e],i())},handler:async(t,r)=>{if(!o.enabled)throw Error(`Tool ${e} is disabled`);let i;if(a){let a=o.inputSchema;i=await n(a?await oC(a,t??{},`Invalid input for tool ${e}: `):t??{},r)}else i=await n(r);return o.outputSchema&&!i.isError&&(i.structuredContent=await oC(o.outputSchema,i.structuredContent,`Invalid output for tool ${e}: `)),i}};return this._registeredTools[e]=o,!this._capabilities.tools&&!this.transport&&this.registerCapabilities({tools:{listChanged:!0}}),this.ensureToolHandlersInitialized(),i(),o}_toolHandlersInitialized=!1;ensureToolHandlersInitialized(){this._toolHandlersInitialized||(this._toolHandlersInitialized=!0,this.oncalltool=async(e,t)=>{let n=this._registeredTools[e.name];if(!n)throw Error(`Tool ${e.name} not found`);return n.handler(e.arguments,t)},this.onlisttools=async(e,t)=>({tools:await Promise.all(Object.entries(this._registeredTools).filter(([e,t])=>t.enabled).map(async([e,t])=>{let n={name:e,title:t.title,description:t.description,inputSchema:t.inputSchema?await aC(t.inputSchema,`input`):{type:`object`,properties:{}}};return t.outputSchema&&(n.outputSchema=await aC(t.outputSchema,`output`)),t.annotations&&(n.annotations=t.annotations),t._meta&&(n._meta=t._meta),n}))}))}async sendToolListChanged(e={}){this._assertInitialized(`sendToolListChanged`),await this.notification({method:`notifications/tools/list_changed`,params:e})}getHostCapabilities(){return this._hostCapabilities}getHostVersion(){return this._hostInfo}getHostContext(){return this._hostContext}get ontoolinput(){return this.getEventHandler(`toolinput`)}set ontoolinput(e){this.setEventHandler(`toolinput`,e)}get ontoolinputpartial(){return this.getEventHandler(`toolinputpartial`)}set ontoolinputpartial(e){this.setEventHandler(`toolinputpartial`,e)}get ontoolresult(){return this.getEventHandler(`toolresult`)}set ontoolresult(e){this.setEventHandler(`toolresult`,e)}get ontoolcancelled(){return this.getEventHandler(`toolcancelled`)}set ontoolcancelled(e){this.setEventHandler(`toolcancelled`,e)}get onhostcontextchanged(){return this.getEventHandler(`hostcontextchanged`)}set onhostcontextchanged(e){this.setEventHandler(`hostcontextchanged`,e)}_onteardown;get onteardown(){return this._onteardown}set onteardown(e){this.warnIfRequestHandlerReplaced(`onteardown`,this._onteardown,e),this._onteardown=e,this.replaceRequestHandler(JS,(e,t)=>{if(!this._onteardown)throw Error(`No onteardown handler set`);return this._onteardown(e.params,t)})}_oncalltool;get oncalltool(){return this._oncalltool}set oncalltool(e){this.warnIfRequestHandlerReplaced(`oncalltool`,this._oncalltool,e),this._oncalltool=e,this.replaceRequestHandler(Rx,(e,t)=>{if(!this._oncalltool)throw Error(`No oncalltool handler set`);return this._oncalltool(e.params,t)})}_onlisttools;get onlisttools(){return this._onlisttools}set onlisttools(e){this.warnIfRequestHandlerReplaced(`onlisttools`,this._onlisttools,e),this._onlisttools=e,this.replaceRequestHandler(Px,(e,t)=>{if(!this._onlisttools)throw Error(`No onlisttools handler set`);return this._onlisttools(e.params,t)})}assertCapabilityForMethod(e){switch(e){case`sampling/createMessage`:if(!this._hostCapabilities?.sampling)throw Error(`Host does not support sampling (required for ${e})`);break}}assertRequestHandlerCapability(e){switch(e){case`tools/call`:case`tools/list`:if(!this._capabilities.tools)throw Error(`Client does not support tool capability (required for ${e})`);return;case`ping`:case`ui/resource-teardown`:return;default:throw Error(`No handler for method ${e} registered`)}}assertNotificationCapability(e){}assertTaskCapability(e){throw Error(`Tasks are not supported in MCP Apps`)}assertTaskHandlerCapability(e){throw Error(`Task handlers are not supported in MCP Apps`)}async callServerTool(e,t){if(this._assertInitialized(`callServerTool`),typeof e==`string`)throw Error(`callServerTool() expects an object as its first argument, but received a string ("${e}"). Did you mean: callServerTool({ name: "${e}", arguments: { ... } })?`);return await this.request({method:`tools/call`,params:e},Ix,{onprogress:()=>{},resetTimeoutOnProgress:!0,...t})}async readServerResource(e,t){return this._assertInitialized(`readServerResource`),await this.request({method:`resources/read`,params:e},sx,t)}async listServerResources(e,t){return this._assertInitialized(`listServerResources`),await this.request({method:`resources/list`,params:e},tx,t)}async createSamplingMessage(e,t){this._assertInitialized(`createSamplingMessage`);let n=e.tools?eS:$x;return await this.request({method:`sampling/createMessage`,params:e},n,t)}sendMessage(e,t){return this._assertInitialized(`sendMessage`),this.request({method:`ui/message`,params:e},BS,t)}sendLog(e){return this.notification({method:`notifications/message`,params:e})}updateModelContext(e,t){return this._assertInitialized(`updateModelContext`),this.request({method:`ui/update-model-context`,params:e},fb,t)}openLink(e,t){return this._assertInitialized(`openLink`),this.request({method:`ui/open-link`,params:e},RS,t)}sendOpenLink=this.openLink;downloadFile(e,t){return this._assertInitialized(`downloadFile`),this.request({method:`ui/download-file`,params:e},zS,t)}requestTeardown(e={}){return this.notification({method:`ui/notifications/request-teardown`,params:e})}requestDisplayMode(e,t){return this._assertInitialized(`requestDisplayMode`),this.request({method:`ui/request-display-mode`,params:e},QS,t)}sendSizeChanged(e){return this.notification({method:`ui/notifications/size-changed`,params:e})}setupSizeChangedNotifications(){let e=!1,t=0,n=0,r=()=>{e||(e=!0,requestAnimationFrame(()=>{e=!1;let r=document.documentElement,i=r.style.height;r.style.height=`max-content`;let a=Math.ceil(r.getBoundingClientRect().height);r.style.height=i;let o=Math.ceil(window.innerWidth);(o!==t||a!==n)&&(t=o,n=a,this.sendSizeChanged({width:o,height:a}))}))};r();let i=new ResizeObserver(r);return i.observe(document.documentElement),i.observe(document.body),()=>i.disconnect()}async connect(e=new PS(window.parent,window.parent),t){if(this.transport)throw Error(`App is already connected. Call close() before connecting again.`);this._initializedSent=!1,await super.connect(e);try{let e=await this.request({method:`ui/initialize`,params:{appCapabilities:this._capabilities,appInfo:this._appInfo,protocolVersion:NS}},rC,t);if(e===void 0)throw Error(`Server sent invalid initialize result: ${e}`);this._hostCapabilities=e.hostCapabilities,this._hostInfo=e.hostInfo,this._hostContext=e.hostContext,await this.notification({method:`ui/notifications/initialized`}),this._initializedSent=!0,this.options?.autoResize&&this.setupSizeChangedNotifications()}catch(e){throw this.close(),e}}};function dC(e){let t=e.getAttribute(hC);if(t!==null)return t;let n=e.textContent?.trim()??``;return e.setAttribute(hC,n),n}function fC(e,t,n){for(let[r,i]of e.entries())i.textContent=dC(i),r===t?(i.setAttribute(gC,n),i.append(` ${n===`asc`?`▲`:`▼`}`)):i.removeAttribute(gC)}function pC(e,t){return e.querySelectorAll(`td`)[t]?.textContent?.trim()??``}function mC(e){let t=Array.from(e.querySelectorAll(`thead th`)),n=e.querySelector(`tbody`);if(!n||t.length===0)return()=>{};let r=Array.from(n.querySelectorAll(`tr`)),i=e.parentElement,a=null,o=`asc`,s=``,c=null,l=[],u=()=>{let e=[...r];if(a!==null){let t=a;e.sort((e,n)=>{let r=_C.compare(pC(e,t),pC(n,t));return o===`asc`?r:-r})}for(let t of e){n.appendChild(t);let e=t.textContent?.toLowerCase()??``;t.hidden=s.length>0&&!e.includes(s)}fC(t,a,o)};for(let[e,n]of t.entries()){dC(n);let t=()=>{a===e?o=o===`asc`?`desc`:`asc`:(a=e,o=`asc`),u()};n.style.cursor=`pointer`,n.addEventListener(`click`,t),l.push(()=>{n.removeEventListener(`click`,t)})}if(r.length>5&&i){c=i.ownerDocument.createElement(`input`),c.className=`bk-table-filter`,c.placeholder=`Filter...`;let t=()=>{s=c?.value.toLowerCase().trim()??``,u()};i.insertBefore(c,e),c.addEventListener(`input`,t),l.push(()=>{c?.removeEventListener(`input`,t),c?.remove(),c=null})}return u(),()=>{for(let e of l)e();for(let e of t)e.textContent=dC(e),e.removeAttribute(gC),e.removeAttribute(hC),e.style.removeProperty(`cursor`);for(let e of r)e.hidden=!1}}var hC,gC,_C,vC=t((()=>{hC=`data-sort-label`,gC=`data-sort-dir`,_C=new Intl.Collator(void 0,{numeric:!0,sensitivity:`base`})}));function yC(e){for(let t of Array.from(e.children))if(t.tagName===`SUMMARY`)return t;return null}function bC(e){let t=e.closest(`details`);if(!t)return null;let n=t.parentElement;for(;n;){if(n.tagName===`DETAILS`)return yC(n);n=n.parentElement}return null}function xC(e){return Array.from(e.querySelectorAll(`summary`))}function SC(e){return e.open||e.hasAttribute(`open`)}function CC(e,t){e.open=t,t?e.setAttribute(`open`,``):e.removeAttribute(`open`)}function wC(e,t){e.textContent=t.every(e=>SC(e))?`Collapse all`:`Expand all`}function TC(e){let t=Array.from(e.querySelectorAll(`details`));if(t.length===0)return()=>{};let n=e.ownerDocument.createElement(`button`);n.type=`button`,n.className=`bk-tree-toggle-all`,e.insertBefore(n,e.firstChild);let r=()=>{let e=t.some(e=>!SC(e));for(let n of t)CC(n,e);wC(n,t)},i=()=>{r()};n.addEventListener(`click`,i);let a=t.map(e=>{let r=()=>{wC(n,t)};return e.addEventListener(`toggle`,r),()=>{e.removeEventListener(`toggle`,r)}}),o=xC(e).map(t=>{t.tabIndex=0;let n=n=>{let r=xC(e),i=r.indexOf(t);if(i===-1)return;let a=t.closest(`details`);if(n.key===`ArrowDown`){r[i+1]?.focus(),n.preventDefault();return}if(n.key===`ArrowUp`){r[i-1]?.focus(),n.preventDefault();return}if(n.key===`ArrowRight`){if(a&&!SC(a))CC(a,!0);else{let e=r[i+1];e&&a?.contains(e)&&e.focus()}n.preventDefault();return}n.key===`ArrowLeft`&&(a&&SC(a)?CC(a,!1):bC(t)?.focus(),n.preventDefault())};return t.addEventListener(`keydown`,n),()=>{t.removeEventListener(`keydown`,n)}});return wC(n,t),()=>{n.removeEventListener(`click`,i);for(let e of a)e();for(let e of o)e();n.remove()}}var EC=t((()=>{}));function DC(e,t){let n=[];for(let r of Array.from(e.querySelectorAll(`[data-action-id]`))){let e=r.getAttribute(`data-action-id`);if(!e)continue;if(r.tagName===`SELECT`){let i=r,a=()=>{t(e,i.value)};i.addEventListener(`change`,a),n.push(()=>{i.removeEventListener(`change`,a)});continue}let i=()=>{t(e)};r.addEventListener(`click`,i),n.push(()=>{r.removeEventListener(`click`,i)})}return()=>{for(let e of n)e()}}var OC=t((()=>{}));function kC(e){let t=e.createElement(`style`);return t.textContent=MC,t}function AC(e,t){let n=t.filter(e=>e.getAttribute(`data-checked`)===`true`).length,r=t.length;return e.textContent=`${n}/${r} complete`,{complete:n,total:r}}function jC(e,t={}){let n=Array.from(e.querySelectorAll(`.bk-checklist-item`));if(n.length===0)return()=>{};let r=e.ownerDocument,i=kC(r),a=r.createElement(`div`);a.className=`bk-checklist-progress`,e.parentElement?.insertBefore(a,e),r.head?.appendChild(i);let o=[];for(let[e,i]of n.entries()){let s=i.querySelector(`.bk-checklist-icon`),c=i.querySelector(`.bk-checklist-label`)?.textContent?.trim()??``,l=r.createElement(`input`);l.type=`checkbox`,l.className=`bk-checklist-box`,l.checked=i.getAttribute(`data-checked`)===`true`;let u=()=>{i.setAttribute(`data-checked`,String(l.checked));let r=AC(a,n);t.onAction?.(`checklist`,JSON.stringify({index:e,label:c,checked:l.checked,complete:r.complete,total:r.total}))};l.addEventListener(`change`,u),o.push(()=>{l.removeEventListener(`change`,u)}),s?s.replaceWith(l):i.insertBefore(l,i.firstChild)}return AC(a,n),()=>{for(let e of o)e();a.remove(),i.remove();for(let e of n){let t=e.querySelector(`.bk-checklist-box`);if(!t)continue;let n=r.createElement(`span`);n.className=`bk-checklist-icon`,n.textContent=e.getAttribute(`data-checked`)===`true`?`✓`:`×`,t.replaceWith(n)}}}var MC,NC=t((()=>{MC=`
|
|
1957
|
+
container holding the app. Specify either width or maxWidth, and either height or maxHeight.`),locale:j().optional().describe(`User's language and region preference in BCP 47 format.`),timeZone:j().optional().describe(`User's timezone in IANA format.`),userAgent:j().optional().describe(`Host application identifier.`),platform:R([V(`web`),V(`desktop`),V(`mobile`)]).optional().describe(`Platform type for responsive design decisions.`),deviceCapabilities:I({touch:N().optional().describe(`Whether the device supports touch input.`),hover:N().optional().describe(`Whether the device supports hover interactions.`)}).optional().describe(`Device input capabilities.`),safeAreaInsets:I({top:M().describe(`Top safe area inset in pixels.`),right:M().describe(`Right safe area inset in pixels.`),bottom:M().describe(`Bottom safe area inset in pixels.`),left:M().describe(`Left safe area inset in pixels.`)}).optional().describe(`Mobile safe area boundaries in pixels.`)}).passthrough(),nC=I({method:V(`ui/notifications/host-context-changed`),params:tC.describe(`Partial context update containing only changed fields.`)});I({method:V(`ui/update-model-context`),params:I({content:F(Dx).optional().describe(`Context content blocks (text, image, etc.).`),structuredContent:z(j(),P().describe(`Structured content for machine-readable context data.`)).optional().describe(`Structured content for machine-readable context data.`)})}),I({method:V(`ui/initialize`),params:I({appInfo:_b.describe(`App identification (name and version).`),appCapabilities:ZS.describe(`Features and capabilities this app provides.`),protocolVersion:j().describe(`Protocol version this app supports.`)})});var rC=I({protocolVersion:j().describe(`Negotiated protocol version string (e.g., "2025-11-21").`),hostInfo:_b.describe(`Host application identification and version.`),hostCapabilities:XS.describe(`Features and capabilities provided by the host.`),hostContext:tC.describe(`Rich context about the host environment.`)}).passthrough(),iC={target:`draft-2020-12`};async function aC(e,t){let n=e[`~standard`];if(n.jsonSchema)return n.jsonSchema[t](iC);if(n.vendor===`zod`){let{z:n}=await jS(async()=>{let{z:e}=await Promise.resolve().then(()=>(Wy(),Hy));return{z:e}},void 0,import.meta.url);return n.toJSONSchema(e,{io:t})}throw Error(`Schema (vendor: ${n.vendor}) does not implement Standard JSON Schema (~standard.jsonSchema). Use a library that does (zod v4, ArkType, Valibot) or wrap your schema accordingly.`)}async function oC(e,t,n=``){let r=await e[`~standard`].validate(t);if(r.issues){let e=r.issues.map(e=>{let t=e.path?.map(e=>typeof e==`object`?e.key:e).join(`.`);return t?`${t}: ${e.message}`:e.message}).join(`; `);throw Error(n+e)}return r.value}function sC(){let e=document.documentElement.getAttribute(`data-theme`);return e===`dark`||e===`light`?e:document.documentElement.classList.contains(`dark`)?`dark`:`light`}function cC(e){let t=document.documentElement;t.setAttribute(`data-theme`,e),t.style.colorScheme=e}function lC(e,t=document.documentElement){for(let[n,r]of Object.entries(e))r!==void 0&&t.style.setProperty(n,r)}var uC=class e extends MS{_appInfo;_capabilities;options;_hostCapabilities;_hostInfo;_hostContext;_registeredTools={};_initializedSent=!1;_assertInitialized(e){if(this._initializedSent)return;let t=`[ext-apps] App.${e}() called before connect() completed the ui/initialize handshake. Await app.connect() before calling this method, or move data loading to an ontoolresult handler.`;if(this.options?.strict)throw Error(t);console.warn(`${t}. This will throw in a future release.`)}eventSchemas={toolinput:US,toolinputpartial:WS,toolresult:eC,toolcancelled:GS,hostcontextchanged:nC};static ONE_SHOT_EVENTS=new Set([`toolinput`,`toolinputpartial`,`toolresult`,`toolcancelled`]);_everHadListener=new Set;_assertHandlerTiming(t){if(!e.ONE_SHOT_EVENTS.has(t)||this._everHadListener.has(t)||(this._everHadListener.add(t),!this._initializedSent))return;let n=`[ext-apps] "${String(t)}" handler registered after connect() completed the ui/initialize handshake. The host may have already sent this notification. Register handlers before calling app.connect().`;if(this.options?.strict)throw Error(n);console.warn(n)}setEventHandler(e,t){t&&this._assertHandlerTiming(e),super.setEventHandler(e,t)}addEventListener(e,t){this._assertHandlerTiming(e),super.addEventListener(e,t)}onEventDispatch(e,t){e===`hostcontextchanged`&&(this._hostContext={...this._hostContext,...t})}constructor(e,t={},n={autoResize:!0}){super(n),this._appInfo=e,this._capabilities=t,this.options=n,n.allowUnsafeEval||h({jitless:!0}),this.setRequestHandler(Db,e=>(console.log(`Received ping:`,e.params),{})),this.setEventHandler(`hostcontextchanged`,void 0)}registerCapabilities(e){if(this.transport)throw Error(`Cannot register capabilities after transport is established`);this._capabilities=DS(this._capabilities,e)}registerTool(e,t,n){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let r=this,i=()=>{r._initializedSent&&r._capabilities.tools?.listChanged&&r.sendToolListChanged()},a=t.inputSchema!==void 0,o={title:t.title,description:t.description,inputSchema:t.inputSchema,outputSchema:t.outputSchema,annotations:t.annotations,_meta:t._meta,enabled:!0,enable(){this.enabled=!0,i()},disable(){this.enabled=!1,i()},update(e){Object.assign(this,e),i()},remove(){r._registeredTools[e]===o&&(delete r._registeredTools[e],i())},handler:async(t,r)=>{if(!o.enabled)throw Error(`Tool ${e} is disabled`);let i;if(a){let a=o.inputSchema;i=await n(a?await oC(a,t??{},`Invalid input for tool ${e}: `):t??{},r)}else i=await n(r);return o.outputSchema&&!i.isError&&(i.structuredContent=await oC(o.outputSchema,i.structuredContent,`Invalid output for tool ${e}: `)),i}};return this._registeredTools[e]=o,!this._capabilities.tools&&!this.transport&&this.registerCapabilities({tools:{listChanged:!0}}),this.ensureToolHandlersInitialized(),i(),o}_toolHandlersInitialized=!1;ensureToolHandlersInitialized(){this._toolHandlersInitialized||(this._toolHandlersInitialized=!0,this.oncalltool=async(e,t)=>{let n=this._registeredTools[e.name];if(!n)throw Error(`Tool ${e.name} not found`);return n.handler(e.arguments,t)},this.onlisttools=async(e,t)=>({tools:await Promise.all(Object.entries(this._registeredTools).filter(([e,t])=>t.enabled).map(async([e,t])=>{let n={name:e,title:t.title,description:t.description,inputSchema:t.inputSchema?await aC(t.inputSchema,`input`):{type:`object`,properties:{}}};return t.outputSchema&&(n.outputSchema=await aC(t.outputSchema,`output`)),t.annotations&&(n.annotations=t.annotations),t._meta&&(n._meta=t._meta),n}))}))}async sendToolListChanged(e={}){this._assertInitialized(`sendToolListChanged`),await this.notification({method:`notifications/tools/list_changed`,params:e})}getHostCapabilities(){return this._hostCapabilities}getHostVersion(){return this._hostInfo}getHostContext(){return this._hostContext}get ontoolinput(){return this.getEventHandler(`toolinput`)}set ontoolinput(e){this.setEventHandler(`toolinput`,e)}get ontoolinputpartial(){return this.getEventHandler(`toolinputpartial`)}set ontoolinputpartial(e){this.setEventHandler(`toolinputpartial`,e)}get ontoolresult(){return this.getEventHandler(`toolresult`)}set ontoolresult(e){this.setEventHandler(`toolresult`,e)}get ontoolcancelled(){return this.getEventHandler(`toolcancelled`)}set ontoolcancelled(e){this.setEventHandler(`toolcancelled`,e)}get onhostcontextchanged(){return this.getEventHandler(`hostcontextchanged`)}set onhostcontextchanged(e){this.setEventHandler(`hostcontextchanged`,e)}_onteardown;get onteardown(){return this._onteardown}set onteardown(e){this.warnIfRequestHandlerReplaced(`onteardown`,this._onteardown,e),this._onteardown=e,this.replaceRequestHandler(JS,(e,t)=>{if(!this._onteardown)throw Error(`No onteardown handler set`);return this._onteardown(e.params,t)})}_oncalltool;get oncalltool(){return this._oncalltool}set oncalltool(e){this.warnIfRequestHandlerReplaced(`oncalltool`,this._oncalltool,e),this._oncalltool=e,this.replaceRequestHandler(Rx,(e,t)=>{if(!this._oncalltool)throw Error(`No oncalltool handler set`);return this._oncalltool(e.params,t)})}_onlisttools;get onlisttools(){return this._onlisttools}set onlisttools(e){this.warnIfRequestHandlerReplaced(`onlisttools`,this._onlisttools,e),this._onlisttools=e,this.replaceRequestHandler(Px,(e,t)=>{if(!this._onlisttools)throw Error(`No onlisttools handler set`);return this._onlisttools(e.params,t)})}assertCapabilityForMethod(e){switch(e){case`sampling/createMessage`:if(!this._hostCapabilities?.sampling)throw Error(`Host does not support sampling (required for ${e})`);break}}assertRequestHandlerCapability(e){switch(e){case`tools/call`:case`tools/list`:if(!this._capabilities.tools)throw Error(`Client does not support tool capability (required for ${e})`);return;case`ping`:case`ui/resource-teardown`:return;default:throw Error(`No handler for method ${e} registered`)}}assertNotificationCapability(e){}assertTaskCapability(e){throw Error(`Tasks are not supported in MCP Apps`)}assertTaskHandlerCapability(e){throw Error(`Task handlers are not supported in MCP Apps`)}async callServerTool(e,t){if(this._assertInitialized(`callServerTool`),typeof e==`string`)throw Error(`callServerTool() expects an object as its first argument, but received a string ("${e}"). Did you mean: callServerTool({ name: "${e}", arguments: { ... } })?`);return await this.request({method:`tools/call`,params:e},Ix,{onprogress:()=>{},resetTimeoutOnProgress:!0,...t})}async readServerResource(e,t){return this._assertInitialized(`readServerResource`),await this.request({method:`resources/read`,params:e},sx,t)}async listServerResources(e,t){return this._assertInitialized(`listServerResources`),await this.request({method:`resources/list`,params:e},tx,t)}async createSamplingMessage(e,t){this._assertInitialized(`createSamplingMessage`);let n=e.tools?eS:$x;return await this.request({method:`sampling/createMessage`,params:e},n,t)}sendMessage(e,t){return this._assertInitialized(`sendMessage`),this.request({method:`ui/message`,params:e},BS,t)}sendLog(e){return this.notification({method:`notifications/message`,params:e})}updateModelContext(e,t){return this._assertInitialized(`updateModelContext`),this.request({method:`ui/update-model-context`,params:e},fb,t)}openLink(e,t){return this._assertInitialized(`openLink`),this.request({method:`ui/open-link`,params:e},RS,t)}sendOpenLink=this.openLink;downloadFile(e,t){return this._assertInitialized(`downloadFile`),this.request({method:`ui/download-file`,params:e},zS,t)}requestTeardown(e={}){return this.notification({method:`ui/notifications/request-teardown`,params:e})}requestDisplayMode(e,t){return this._assertInitialized(`requestDisplayMode`),this.request({method:`ui/request-display-mode`,params:e},QS,t)}sendSizeChanged(e){return this.notification({method:`ui/notifications/size-changed`,params:e})}setupSizeChangedNotifications(){let e=!1,t=0,n=0,r=()=>{e||(e=!0,requestAnimationFrame(()=>{e=!1;let r=document.documentElement,i=r.style.height;r.style.height=`max-content`;let a=Math.ceil(r.getBoundingClientRect().height);r.style.height=i;let o=Math.ceil(window.innerWidth);(o!==t||a!==n)&&(t=o,n=a,this.sendSizeChanged({width:o,height:a}))}))};r();let i=new ResizeObserver(r);return i.observe(document.documentElement),i.observe(document.body),()=>i.disconnect()}async connect(e=new PS(window.parent,window.parent),t){if(this.transport)throw Error(`App is already connected. Call close() before connecting again.`);this._initializedSent=!1,await super.connect(e);try{let e=await this.request({method:`ui/initialize`,params:{appCapabilities:this._capabilities,appInfo:this._appInfo,protocolVersion:NS}},rC,t);if(e===void 0)throw Error(`Server sent invalid initialize result: ${e}`);this._hostCapabilities=e.hostCapabilities,this._hostInfo=e.hostInfo,this._hostContext=e.hostContext,await this.notification({method:`ui/notifications/initialized`}),this._initializedSent=!0,this.options?.autoResize&&this.setupSizeChangedNotifications()}catch(e){throw this.close(),e}}};function dC(e,t){let n=[];for(let r of Array.from(e.querySelectorAll(`[data-action-id]`))){let e=r.getAttribute(`data-action-id`);if(!e)continue;if(r.tagName===`SELECT`){let i=r,a=()=>{t(e,i.value)};i.addEventListener(`change`,a),n.push(()=>{i.removeEventListener(`change`,a)});continue}let i=()=>{t(e)};r.addEventListener(`click`,i),n.push(()=>{r.removeEventListener(`click`,i)})}return()=>{for(let e of n)e()}}var fC=`
|
|
1958
1958
|
.bk-checklist-progress {
|
|
1959
1959
|
margin-bottom: var(--dt-space-3);
|
|
1960
1960
|
color: var(--dt-text-secondary);
|
|
@@ -1968,9 +1968,9 @@ container holding the app. Specify either width or maxWidth, and either height o
|
|
|
1968
1968
|
margin: 0;
|
|
1969
1969
|
accent-color: var(--dt-accent-fg);
|
|
1970
1970
|
}
|
|
1971
|
-
`}));
|
|
1972
|
-
`)}function
|
|
1973
|
-
`)}];if(typeof e==`string`)return[{type:`markdown`,value:e}];if(typeof e==`object`&&e){let t=e;return Array.isArray(t.nodes)&&Array.isArray(t.edges)?[{type:`graph`,value:t}]:Array.isArray(t.metrics)?[{type:`metrics`,value:t.metrics}]:[{type:`json`,value:t}]}return[{type:`text`,value:String(e??``)}]}function
|
|
1971
|
+
`;function pC(e){let t=e.createElement(`style`);return t.textContent=fC,t}function mC(e,t){let n=t.filter(e=>e.getAttribute(`data-checked`)===`true`).length,r=t.length;return e.textContent=`${n}/${r} complete`,{complete:n,total:r}}function hC(e,t={}){let n=Array.from(e.querySelectorAll(`.bk-checklist-item`));if(n.length===0)return()=>{};let r=e.ownerDocument,i=pC(r),a=r.createElement(`div`);a.className=`bk-checklist-progress`,e.parentElement?.insertBefore(a,e),r.head?.appendChild(i);let o=[];for(let[e,i]of n.entries()){let s=i.querySelector(`.bk-checklist-icon`),c=i.querySelector(`.bk-checklist-label`)?.textContent?.trim()??``,l=r.createElement(`input`);l.type=`checkbox`,l.className=`bk-checklist-box`,l.checked=i.getAttribute(`data-checked`)===`true`;let u=()=>{i.setAttribute(`data-checked`,String(l.checked));let r=mC(a,n);t.onAction?.(`checklist`,JSON.stringify({index:e,label:c,checked:l.checked,complete:r.complete,total:r.total}))};l.addEventListener(`change`,u),o.push(()=>{l.removeEventListener(`change`,u)}),s?s.replaceWith(l):i.insertBefore(l,i.firstChild)}return mC(a,n),()=>{for(let e of o)e();a.remove(),i.remove();for(let e of n){let t=e.querySelector(`.bk-checklist-box`);if(!t)continue;let n=r.createElement(`span`);n.className=`bk-checklist-icon`,n.textContent=e.getAttribute(`data-checked`)===`true`?`✓`:`×`,t.replaceWith(n)}}}var gC=`data-sort-label`,_C=`data-sort-dir`,vC=new Intl.Collator(void 0,{numeric:!0,sensitivity:`base`});function yC(e){let t=e.getAttribute(gC);if(t!==null)return t;let n=e.textContent?.trim()??``;return e.setAttribute(gC,n),n}function bC(e,t,n){for(let[r,i]of e.entries())i.textContent=yC(i),r===t?(i.setAttribute(_C,n),i.append(` ${n===`asc`?`▲`:`▼`}`)):i.removeAttribute(_C)}function xC(e,t){return e.querySelectorAll(`td`)[t]?.textContent?.trim()??``}function SC(e){let t=Array.from(e.querySelectorAll(`thead th`)),n=e.querySelector(`tbody`);if(!n||t.length===0)return()=>{};let r=Array.from(n.querySelectorAll(`tr`)),i=e.parentElement,a=null,o=`asc`,s=``,c=null,l=[],u=()=>{let e=[...r];if(a!==null){let t=a;e.sort((e,n)=>{let r=vC.compare(xC(e,t),xC(n,t));return o===`asc`?r:-r})}for(let t of e){n.appendChild(t);let e=t.textContent?.toLowerCase()??``;t.hidden=s.length>0&&!e.includes(s)}bC(t,a,o)};for(let[e,n]of t.entries()){yC(n);let t=()=>{a===e?o=o===`asc`?`desc`:`asc`:(a=e,o=`asc`),u()};n.style.cursor=`pointer`,n.addEventListener(`click`,t),l.push(()=>{n.removeEventListener(`click`,t)})}if(r.length>5&&i){c=i.ownerDocument.createElement(`input`),c.className=`bk-table-filter`,c.placeholder=`Filter...`;let t=()=>{s=c?.value.toLowerCase().trim()??``,u()};i.insertBefore(c,e),c.addEventListener(`input`,t),l.push(()=>{c?.removeEventListener(`input`,t),c?.remove(),c=null})}return u(),()=>{for(let e of l)e();for(let e of t)e.textContent=yC(e),e.removeAttribute(_C),e.removeAttribute(gC),e.style.removeProperty(`cursor`);for(let e of r)e.hidden=!1}}function CC(e){for(let t of Array.from(e.children))if(t.tagName===`SUMMARY`)return t;return null}function wC(e){let t=e.closest(`details`);if(!t)return null;let n=t.parentElement;for(;n;){if(n.tagName===`DETAILS`)return CC(n);n=n.parentElement}return null}function TC(e){return Array.from(e.querySelectorAll(`summary`))}function EC(e){return e.open||e.hasAttribute(`open`)}function DC(e,t){e.open=t,t?e.setAttribute(`open`,``):e.removeAttribute(`open`)}function OC(e,t){e.textContent=t.every(e=>EC(e))?`Collapse all`:`Expand all`}function kC(e){let t=Array.from(e.querySelectorAll(`details`));if(t.length===0)return()=>{};let n=e.ownerDocument.createElement(`button`);n.type=`button`,n.className=`bk-tree-toggle-all`,e.insertBefore(n,e.firstChild);let r=()=>{let e=t.some(e=>!EC(e));for(let n of t)DC(n,e);OC(n,t)},i=()=>{r()};n.addEventListener(`click`,i);let a=t.map(e=>{let r=()=>{OC(n,t)};return e.addEventListener(`toggle`,r),()=>{e.removeEventListener(`toggle`,r)}}),o=TC(e).map(t=>{t.tabIndex=0;let n=n=>{let r=TC(e),i=r.indexOf(t);if(i===-1)return;let a=t.closest(`details`);if(n.key===`ArrowDown`){r[i+1]?.focus(),n.preventDefault();return}if(n.key===`ArrowUp`){r[i-1]?.focus(),n.preventDefault();return}if(n.key===`ArrowRight`){if(a&&!EC(a))DC(a,!0);else{let e=r[i+1];e&&a?.contains(e)&&e.focus()}n.preventDefault();return}n.key===`ArrowLeft`&&(a&&EC(a)?DC(a,!1):wC(t)?.focus(),n.preventDefault())};return t.addEventListener(`keydown`,n),()=>{t.removeEventListener(`keydown`,n)}});return OC(n,t),()=>{n.removeEventListener(`click`,i);for(let e of a)e();for(let e of o)e();n.remove()}}var AC=`data-hydrated`;function jC(e,t){let n=[];return e.matches(t)&&n.push(e),n.push(...Array.from(e.querySelectorAll(t))),n}function MC(e,t,n){e.push(()=>{n(),t.removeAttribute(AC)})}function NC(e={}){let t=e.container??document.body,n=[];for(let e of jC(t,`.bk-table`))e.hasAttribute(AC)||(e.setAttribute(AC,``),MC(n,e,SC(e)));for(let e of jC(t,`.bk-tree`))e.hasAttribute(AC)||(e.setAttribute(AC,``),MC(n,e,kC(e)));for(let r of jC(t,`.bk-checklist`))r.hasAttribute(AC)||(r.setAttribute(AC,``),MC(n,r,hC(r,e)));for(let r of jC(t,`.bk-actions`))if(!r.hasAttribute(AC)){if(r.setAttribute(AC,``),e.onAction){MC(n,r,dC(r,e.onAction));continue}n.push(()=>{r.removeAttribute(AC)})}return()=>{for(let e of n)e();n.length=0}}var PC=`bk-styles`,FC=new Set;function IC(e){for(let t of e.css)t.trim().length>0&&FC.add(t);return[...FC].join(`
|
|
1972
|
+
`)}function LC(e){return di(e,{transport:`browser`})}function RC(e,t=document){let n=IC(e),r=t.getElementById(PC);r||(r=t.createElement(`style`),r.id=PC,t.head.appendChild(r)),r.textContent=n}function zC(e,t){let n=LC(t);return RC(n,e.ownerDocument),e.innerHTML=n.html,n}function BC(e,t,n){return zC(e,{schemaVersion:1,title:`AI Kit Present`,blocks:t}),NC({container:e,onAction:n})}function VC(e){return function(t,n){let r=n??t.label;if(!e){fetch(`/callback`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({actionId:t.id,value:r})});return}e.updateModelContext({content:[{type:`text`,text:`Latest UI action: ${t.label}${n?` → ${n}`:``}`}],structuredContent:{actionId:t.id,actionType:t.type,label:t.label,value:r,timestamp:new Date().toISOString()}}),e.sendMessage({role:`user`,content:[{type:`text`,text:`User selected: ${t.label}${n?` → ${n}`:``}`}]})}}function HC(e){return typeof e==`object`&&!!e}function UC(e,t){let n=e.id.split(`@`)[0];return n===`timeline`&&HC(t)&&Array.isArray(t.events)?t.events:n===`tree`&&Array.isArray(t)?{root:{label:`Root`,children:t}}:t}function WC(e,t,n){let r=oi.get(e);if(!r?.supportedTransports.includes(`browser`))return null;let i=UC(r,t);return{blocks:r.blocksFromData(i,{colorScheme:n.colorScheme,transport:`browser`,lang:n.lang,dir:n.dir}),actions:r.actionsFromData?.(i)??[]}}var GC=`present-data`;function KC(e=document,t=GC){let n=e.getElementById(t);return n?.textContent?JSON.parse(n.textContent):null}function qC(e){return e?{callTool:(t,n)=>e.callServerTool({name:t,arguments:n}),sendMessage:async t=>{await e.sendMessage({role:`user`,content:[{type:`text`,text:t}]})},updateContext:async t=>{await e.updateModelContext({content:[{type:`text`,text:t}]})}}:{callTool:async()=>{throw Error(`callTool is not available in browser mode`)},sendMessage:async()=>{},updateContext:async()=>{}}}var JC=class{app;currentMode=`inline`;availableModes=[];toolbar=null;constructor(e){this.app=e}apply(e){e.displayMode&&(this.currentMode=e.displayMode),e.availableDisplayModes&&(this.availableModes=e.availableDisplayModes),this.updateToolbar()}async requestMode(e){try{let t=await this.app.requestDisplayMode({mode:e});return this.currentMode=t.mode,document.documentElement.dataset.display=t.mode,this.updateToolbar(),t.mode}catch{return this.currentMode}}updateToolbar(){if(this.availableModes.length<=1){this.toolbar?.remove(),this.toolbar=null;return}this.toolbar||=this.createToolbar(),this.renderButtons()}createToolbar(){let e=document.createElement(`div`);return e.className=`display-mode-toolbar`,document.body.appendChild(e),e}renderButtons(){if(!this.toolbar)return;this.toolbar.innerHTML=``;let e={inline:`▣`,fullscreen:`⛶`,pip:`◱`};for(let t of this.availableModes){let n=document.createElement(`button`);n.className=`dm-btn${t===this.currentMode?` dm-active`:``}`,n.textContent=e[t]??t,n.title=t,n.addEventListener(`click`,()=>this.requestMode(t)),this.toolbar.appendChild(n)}}},YC=new Set;function XC(e,t){if(YC.has(e))return;YC.add(e);let n=document.createElement(`style`);n.textContent=t,document.head.appendChild(n)}function Q(e,t,n){let r=document.createElement(e);return t&&(r.className=t),n&&(r.textContent=n),r}function ZC(e){return e==null?`null`:Array.isArray(e)?`[${e.map(ZC).join(`, `)}]`:String(e)}function QC(e){return typeof e==`object`&&!!e&&`type`in e}var $C=[[400,`compact`],[800,`comfortable`]],ew=class{root;displayMode=`inline`;sizeClass=`comfortable`;constructor(e){this.root=e??document.documentElement}apply(e){this.applyDisplayMode(e),this.applyContainerDimensions(e),this.applySafeArea(e),this.applyPlatform(e),this.applyDeviceCapabilities(e)}getDisplayMode(){return this.displayMode}getSize(){return this.sizeClass}applyDisplayMode(e){e.displayMode&&(this.displayMode=e.displayMode,this.root.dataset.display=e.displayMode)}applyContainerDimensions(e){let t=e.containerDimensions;if(!t)return;let n=this.root.style,r=`width`in t?t.width:`maxWidth`in t?t.maxWidth:void 0,i=`height`in t?t.height:`maxHeight`in t?t.maxHeight:void 0;r!==void 0&&(n.setProperty(`--aikit-container-w`,`${r}px`),this.sizeClass=this.deriveSizeClass(r),this.root.dataset.size=this.sizeClass,n.setProperty(`--aikit-content-max-width`,this.deriveMaxWidth(r)),n.setProperty(`--aikit-body-pad-x`,this.derivePadX()),n.setProperty(`--aikit-grid-cols`,this.deriveGridCols()),n.setProperty(`--aikit-card-min`,this.deriveCardMin()),n.setProperty(`--aikit-metric-min`,this.deriveMetricMin())),i!==void 0&&(n.setProperty(`--aikit-container-h`,`${i}px`),n.setProperty(`--aikit-body-pad-y`,this.derivePadY()))}applySafeArea(e){let t=e.safeAreaInsets;if(!t)return;let n=this.root.style;n.setProperty(`--aikit-safe-top`,`${t.top}px`),n.setProperty(`--aikit-safe-right`,`${t.right}px`),n.setProperty(`--aikit-safe-bottom`,`${t.bottom}px`),n.setProperty(`--aikit-safe-left`,`${t.left}px`)}applyPlatform(e){e.platform&&(this.root.dataset.platform=e.platform)}applyDeviceCapabilities(e){let t=e.deviceCapabilities;t&&(t.touch!==void 0&&(this.root.dataset.touch=String(t.touch)),t.hover!==void 0&&(this.root.dataset.hover=String(t.hover)))}deriveSizeClass(e){for(let[t,n]of $C)if(e<t)return n;return`full`}deriveMaxWidth(e){return this.displayMode===`pip`?`100%`:this.displayMode===`fullscreen`?`none`:e<960?`100%`:`900px`}derivePadX(){return this.sizeClass===`compact`?`8px`:`16px`}derivePadY(){return this.sizeClass===`compact`?`8px`:`16px`}deriveGridCols(){switch(this.sizeClass){case`compact`:return`1`;case`comfortable`:return`2`;case`full`:return`3`}}deriveCardMin(){return this.sizeClass===`compact`?`100%`:`250px`}deriveMetricMin(){return this.sizeClass===`compact`?`100px`:`150px`}},tw=`AI Kit Present`;function nw(e){if(!Array.isArray(e)&&typeof e==`object`&&e){let t=e;if(Array.isArray(t.blocks)&&t.blocks.length>0)return t.blocks}return e}function rw(e){if(Array.isArray(e))return e.length===0?[{type:`markdown`,value:`*Empty array*`}]:QC(e[0])?e.filter(QC):typeof e[0]==`object`&&e[0]!==null?[{type:`table`,value:e}]:[{type:`markdown`,value:e.map(e=>`- ${String(e)}`).join(`
|
|
1973
|
+
`)}];if(typeof e==`string`)return[{type:`markdown`,value:e}];if(typeof e==`object`&&e){let t=e;return Array.isArray(t.nodes)&&Array.isArray(t.edges)?[{type:`graph`,value:t}]:Array.isArray(t.metrics)?[{type:`metrics`,value:t.metrics}]:[{type:`json`,value:t}]}return[{type:`text`,value:String(e??``)}]}function iw(e){return{...e,options:e.options?.map(e=>typeof e==`string`?{label:e,value:e}:e)}}function aw(e){let t=nw(e.content);return{schemaVersion:1,title:e.title??tw,template:e.template,data:t,blocks:rw(t),actions:e.actions?.map(iw)}}var ow=class{templates=new Map;register(e){this.templates.set(e.name,e)}get(e){return this.templates.get(e)}detect(e){let t,n=0;for(let r of this.templates.values()){let i=r.detect(e);i>n&&(n=i,t=r)}return n>0?t:void 0}getAll(){return[...this.templates.values()]}},sw={"--color-background-primary":`--aikit-bg`,"--color-background-secondary":`--aikit-surface`,"--color-background-tertiary":`--aikit-surface2`,"--color-text-primary":`--aikit-text`,"--color-text-secondary":`--aikit-muted`,"--color-border-primary":`--aikit-border`,"--color-ring-primary":`--aikit-accent`,"--color-text-success":`--aikit-success`,"--color-text-danger":`--aikit-error`,"--color-text-warning":`--aikit-warning`,"--color-text-info":`--aikit-info`,"--font-sans":`--aikit-font-sans`,"--font-mono":`--aikit-font-mono`,"--border-radius-md":`--aikit-radius`,"--shadow-sm":`--aikit-shadow`},cw={"--aikit-bg":`--bg`,"--aikit-text":`--fg`,"--aikit-surface":`--surface`,"--aikit-border":`--border`,"--aikit-accent":`--accent`,"--aikit-success":`--success`,"--aikit-warning":`--warning`,"--aikit-error":`--error`,"--aikit-font-sans":`--font-sans`,"--aikit-font-mono":`--font-mono`,"--aikit-radius":`--radius`,"--aikit-shadow":`--shadow`},lw=`aikit-design-token-bridge`,uw={light:{"--bg":`#ffffff`,"--fg":`rgb(26 26 46)`,"--surface":`#f8f9fa`,"--border":`#e2e8f0`,"--accent":`#58a6ff`,"--accent-light":`#79c0ff`,"--success":`#22c55e`,"--warning":`#f59e0b`,"--error":`#ef4444`,"--code-bg":`#1e1e2e`,"--code-fg":`#cdd6f4`,"--radius":`8px`,"--shadow":`0 1px 3px rgba(0,0,0,0.08), 0 1px 2px rgba(0,0,0,0.06)`,"--font-sans":`-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif`,"--font-mono":`'Cascadia Code', 'Fira Code', 'JetBrains Mono', Consolas, monospace`,"--aikit-bg":`#ffffff`,"--aikit-surface":`#f8f9fa`,"--aikit-surface2":`#f8f9fa`,"--aikit-text":`rgb(26 26 46)`,"--aikit-muted":`#94a3b8`,"--aikit-border":`#e2e8f0`,"--aikit-accent":`#58a6ff`,"--aikit-accent-light":`#79c0ff`,"--aikit-success":`#22c55e`,"--aikit-warning":`#f59e0b`,"--aikit-error":`#ef4444`,"--aikit-info":`#58a6ff`,"--aikit-code-bg":`#1e1e2e`,"--aikit-code-fg":`#cdd6f4`,"--aikit-font-sans":`-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif`,"--aikit-font-mono":`'Cascadia Code', 'Fira Code', 'JetBrains Mono', Consolas, monospace`,"--aikit-radius":`8px`,"--aikit-shadow":`0 1px 3px rgba(0,0,0,0.08), 0 1px 2px rgba(0,0,0,0.06)`,"--aikit-hover-bg":`color-mix(in srgb, #58a6ff 10%, transparent)`},dark:{"--bg":`#0d1117`,"--fg":`#e6edf3`,"--surface":`#161b22`,"--border":`#30363d`,"--accent":`#58a6ff`,"--accent-light":`#79c0ff`,"--success":`#22c55e`,"--warning":`#f59e0b`,"--error":`#ef4444`,"--code-bg":`#161b22`,"--code-fg":`#cdd6f4`,"--radius":`8px`,"--shadow":`0 1px 3px rgba(0,0,0,0.3)`,"--font-sans":`-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif`,"--font-mono":`'Cascadia Code', 'Fira Code', 'JetBrains Mono', Consolas, monospace`,"--aikit-bg":`#0d1117`,"--aikit-surface":`#161b22`,"--aikit-surface2":`#161b22`,"--aikit-text":`#e6edf3`,"--aikit-muted":`#94a3b8`,"--aikit-border":`#30363d`,"--aikit-accent":`#58a6ff`,"--aikit-accent-light":`#79c0ff`,"--aikit-success":`#22c55e`,"--aikit-warning":`#f59e0b`,"--aikit-error":`#ef4444`,"--aikit-info":`#58a6ff`,"--aikit-code-bg":`#161b22`,"--aikit-code-fg":`#cdd6f4`,"--aikit-font-sans":`-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif`,"--aikit-font-mono":`'Cascadia Code', 'Fira Code', 'JetBrains Mono', Consolas, monospace`,"--aikit-radius":`8px`,"--aikit-shadow":`0 1px 3px rgba(0,0,0,0.3)`,"--aikit-hover-bg":`color-mix(in srgb, #58a6ff 10%, transparent)`}},dw={"--chart-1":`#79c0ff`,"--chart-2":`#38bdf8`,"--chart-3":`#34d399`,"--chart-4":`#fbbf24`,"--chart-5":`#f87171`,"--chart-6":`#a78bfa`,"--chart-7":`#f472b6`,"--chart-8":`#2dd4bf`,"--chart-9":`#fb923c`,"--chart-10":`#22d3ee`,"--chart-11":`#c084fc`,"--chart-12":`#a3e635`,"--chart-others":`#a8a29e`},fw=`
|
|
1974
1974
|
:root {
|
|
1975
1975
|
--dt-bg-primary: var(--aikit-bg, #0d1117);
|
|
1976
1976
|
--dt-bg-secondary: var(--aikit-surface, #161b22);
|
|
@@ -2039,7 +2039,7 @@ container holding the app. Specify either width or maxWidth, and either height o
|
|
|
2039
2039
|
[data-theme='light'] {
|
|
2040
2040
|
color-scheme: light;
|
|
2041
2041
|
}
|
|
2042
|
-
`,
|
|
2042
|
+
`,pw=class{root;constructor(e){this.root=e??document.documentElement,this.applyFallbackVariables(),this.ensureDesignTokenBridge()}apply(e){e.theme&&cC(e.theme),this.applyFallbackVariables(e.theme),e.styles?.variables&&(lC(e.styles.variables),this.mapTokens(e.styles.variables)),e.styles?.css?.fonts&&this.injectFonts(e.styles.css.fonts)}getTheme(){return sC()}resolveFallbackTheme(e){if(e)return e;let t=this.root.dataset.theme;return t===`light`||t===`dark`?t:window.matchMedia(`(prefers-color-scheme: dark)`).matches?`dark`:`light`}applyFallbackVariables(e){let t=this.resolveFallbackTheme(e),n=this.root.style;for(let[e,r]of Object.entries(uw[t]))n.setProperty(e,r);for(let[e,t]of Object.entries(dw))n.setProperty(e,t);n.colorScheme=t}mapTokens(e){let t=this.root.style;for(let[n,r]of Object.entries(sw)){let i=e[n];if(i){t.setProperty(r,i);let e=cw[r];e&&t.setProperty(e,i)}}this.getTheme()===`dark`?(t.setProperty(`--code-bg`,e[`--color-background-tertiary`]??`#0f0f1a`),t.setProperty(`--code-fg`,`#cdd6f4`)):(t.setProperty(`--code-bg`,`#f0f0f5`),t.setProperty(`--code-fg`,`#1a1a2e`)),t.setProperty(`--aikit-code-bg`,t.getPropertyValue(`--code-bg`)),t.setProperty(`--aikit-code-fg`,t.getPropertyValue(`--code-fg`));let n=e[`--color-ring-primary`];n&&(t.setProperty(`--aikit-accent-light`,n),t.setProperty(`--accent-light`,n),t.setProperty(`--aikit-hover-bg`,`color-mix(in srgb, ${n} 10%, transparent)`))}injectFonts(e){let t=`aikit-host-fonts`;if(document.getElementById(t))return;let n=document.createElement(`style`);n.id=t,n.textContent=e,document.head.appendChild(n)}ensureDesignTokenBridge(){if(document.getElementById(lw))return;let e=document.createElement(`style`);e.id=lw,e.textContent=fw,document.head.appendChild(e)}},mw=`
|
|
2043
2043
|
.tpl-dashboard { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 14px; }
|
|
2044
2044
|
.db-card { min-height: 136px; padding: 14px; border: 1px solid var(--aikit-border, #3c3c3c);
|
|
2045
2045
|
border-left-width: 4px; border-radius: var(--aikit-radius, 10px); background: var(--aikit-surface, #252526);
|
|
@@ -2065,7 +2065,7 @@ container holding the app. Specify either width or maxWidth, and either height o
|
|
|
2065
2065
|
.db-list-item { display: flex; align-items: center; justify-content: space-between; gap: 12px; color: var(--aikit-text, #e5e7eb);
|
|
2066
2066
|
font: 500 13px var(--aikit-font-sans, Inter, sans-serif); }
|
|
2067
2067
|
.db-list-item span:last-child { color: var(--aikit-muted, #9ca3af); font-family: var(--aikit-font-mono, Consolas, monospace); }
|
|
2068
|
-
`,
|
|
2068
|
+
`,hw={name:`dashboard`,label:`Dashboard`,detect(e){if(typeof e!=`object`||!e||Array.isArray(e))return 0;let t=e,n=Array.isArray(t.metrics)?t.metrics[0]:void 0;return n&&typeof n.label==`string`&&`value`in n?.85:0},render(e,t,n){XC(`tpl-dashboard`,mw);let r=t,i=Q(`div`,`block tpl-dashboard`);for(let e of r.metrics){let t=Q(`article`,`db-card status-${e.status??`info`}`),n=Q(`div`,`db-header`);if(n.appendChild(Q(`div`,`db-label`,e.label)),e.trend){let t=e.trend.direction===`up`?`▲`:e.trend.direction===`down`?`▼`:`—`;n.appendChild(Q(`div`,`db-trend ${e.trend.direction}`,`${t} ${e.trend.value}`))}if(t.appendChild(n),t.appendChild(Q(`div`,`db-value`,ZC(e.value))),e.type===`progress`){let n=Q(`div`,`db-progress-track`),r=Q(`div`,`db-progress-fill`);r.style.width=`${Math.max(0,Math.min(100,e.progress??0))}%`,n.appendChild(r),t.appendChild(n),t.appendChild(Q(`div`,`db-progress-meta`,`${Math.max(0,Math.min(100,e.progress??0))}% complete`))}if(e.type===`list`&&e.items?.length){let n=Q(`ul`,`db-list`);for(let t of e.items){let e=Q(`li`,`db-list-item`);e.appendChild(Q(`span`,``,t.label)),e.appendChild(Q(`span`,``,t.value)),n.appendChild(e)}t.appendChild(n)}i.appendChild(t)}e.appendChild(i)},styles(){return mw}},gw=`
|
|
2069
2069
|
.fg-breadcrumb { display: flex; align-items: center; gap: 4px; padding: 8px 0; flex-wrap: wrap; }
|
|
2070
2070
|
.fg-crumb { background: var(--aikit-surface, #252526); border: 1px solid var(--aikit-border, #3c3c3c);
|
|
2071
2071
|
color: var(--aikit-text, #ccc); padding: 3px 10px; border-radius: 4px; cursor: pointer; font-size: 12px; }
|
|
@@ -2080,7 +2080,7 @@ container holding the app. Specify either width or maxWidth, and either height o
|
|
|
2080
2080
|
text-overflow: ellipsis; font-weight: 500; }
|
|
2081
2081
|
.fg-info { font-size: 12px; color: var(--aikit-muted, #858585); padding: 8px 0;
|
|
2082
2082
|
border-top: 1px solid var(--aikit-border, #3c3c3c); margin-top: 8px; }
|
|
2083
|
-
`;function
|
|
2083
|
+
`;function _w(e){return{name:String(e.name??``),total:typeof e.total==`number`?e.total:typeof e.value==`number`?e.value:0,self:typeof e.self==`number`?e.self:void 0,children:Array.isArray(e.children)?e.children.map(e=>_w(e)):void 0}}var vw={name:`flame-graph`,label:`Flame Graph`,detect(e){if(typeof e!=`object`||!e||Array.isArray(e))return 0;let t=e.profile;return t&&typeof t==`object`&&t.children?.9:0},render(e,t,n){let r=t,i=Q(`div`,`block tpl-flame-graph`),a=_w(r.profile),o=a,s=[a],c=Q(`div`,`fg-breadcrumb`);i.appendChild(c);let l=Q(`div`,`fg-canvas`);i.appendChild(l);let u=Q(`div`,`fg-info`);i.appendChild(u);function d(){c.innerHTML=``;for(let e=0;e<s.length;e++){let t=s[e],n=document.createElement(`button`);n.className=`fg-crumb`,n.textContent=t.name,n.addEventListener(`click`,()=>{s.splice(e+1),o=t,d()}),c.appendChild(n),e<s.length-1&&c.appendChild(Q(`span`,`fg-sep`,`›`))}l.innerHTML=``,f(l,o,0,o.total),u.textContent=`${o.name} — total: ${o.total}${o.self==null?``:`, self: ${o.self}`}`}function f(e,t,r,i){let a=Q(`div`,`fg-row`);a.style.paddingLeft=`${r*2}px`;let c=Q(`div`,`fg-bar`),l=Math.max(2,t.total/i*100);c.style.width=`${l}%`,c.style.background=ee(r),c.title=`${t.name}: ${t.total}${t.self==null?``:` (self: ${t.self})`}`;let te=Q(`span`,`fg-bar-label`,`${t.name} (${t.total})`);if(c.appendChild(te),t.children?.length&&(c.style.cursor=`pointer`,c.addEventListener(`click`,()=>{o=t,s.push(t),d(),n.emitAction({type:`button`,id:`zoom`,label:`Zoom`},JSON.stringify({name:t.name,total:t.total}))})),c.addEventListener(`mouseenter`,()=>{u.textContent=`${t.name} — total: ${t.total}${t.self==null?``:`, self: ${t.self}`}`}),a.appendChild(c),e.appendChild(a),t.children)for(let n of t.children)f(e,n,r+1,i)}function ee(e){let t=getComputedStyle(document.documentElement),n=[t.getPropertyValue(`--chart-5`).trim()||`#e24d28`,t.getPropertyValue(`--chart-9`).trim()||`#e8602a`,t.getPropertyValue(`--chart-4`).trim()||`#edad2a`,t.getPropertyValue(`--chart-1`).trim()||`#f5c842`,t.getPropertyValue(`--chart-3`).trim()||`#fce94f`,t.getPropertyValue(`--chart-6`).trim()||`#c4a000`,t.getPropertyValue(`--chart-7`).trim()||`#e07028`,t.getPropertyValue(`--chart-8`).trim()||`#d45500`];return n[e%n.length]}d(),XC(`tpl-flame-graph`,gw),e.appendChild(i)},styles(){return gw}},yw=`
|
|
2084
2084
|
.tpl-kanban { overflow-x: auto; }
|
|
2085
2085
|
.kbn-board { display: flex; gap: 14px; align-items: flex-start; min-width: min-content; padding-bottom: 4px; }
|
|
2086
2086
|
.kbn-column { width: 280px; flex: 0 0 280px; border: 1px solid var(--aikit-border, #3c3c3c); border-radius: var(--aikit-radius, 10px);
|
|
@@ -2106,7 +2106,7 @@ container holding the app. Specify either width or maxWidth, and either height o
|
|
|
2106
2106
|
.kbn-tags { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 10px; }
|
|
2107
2107
|
.kbn-tag { padding: 2px 8px; border-radius: 999px; background: var(--aikit-surface, #252526); color: var(--aikit-muted, #9ca3af);
|
|
2108
2108
|
font: 500 11px var(--aikit-font-sans, Inter, sans-serif); }
|
|
2109
|
-
`,
|
|
2109
|
+
`,bw={name:`kanban`,label:`Kanban`,detect(e){if(typeof e!=`object`||!e||Array.isArray(e))return 0;let t=e,n=Array.isArray(t.cards)?t.cards[0]:void 0;return Array.isArray(t.columns)&&Array.isArray(t.cards)&&typeof n?.column==`string`?.85:0},render(e,t,n){XC(`tpl-kanban`,yw);let r=t,i=r.cards.map(e=>({...e,tags:e.tags?[...e.tags]:void 0})),a=new Set,o=``,s=Q(`div`,`block tpl-kanban`),c=Q(`div`,`kbn-board`);s.appendChild(c);let l=()=>{c.innerHTML=``;for(let e of r.columns){let t=Q(`section`,`kbn-column`),r=Q(`div`,`kbn-column-header`),s=Q(`div`,`kbn-column-title`),u=Q(`span`,`kbn-column-swatch`);e.color&&(u.style.background=e.color),s.appendChild(u),s.appendChild(Q(`span`,``,e.label)),r.appendChild(s);let d=i.filter(t=>t.column===e.id);r.appendChild(Q(`span`,`kbn-column-count`,String(d.length))),t.appendChild(r);let f=Q(`div`,`kbn-cards`);t.addEventListener(`dragover`,e=>{e.preventDefault(),t.classList.add(`drop-target`)}),t.addEventListener(`dragleave`,()=>{t.classList.remove(`drop-target`)}),t.addEventListener(`drop`,r=>{if(r.preventDefault(),t.classList.remove(`drop-target`),!o)return;let a=i.find(e=>e.id===o);!a||a.column===e.id||(a.column=e.id,l(),n.emitAction({type:`button`,id:`move-card`,label:`Move Card`},JSON.stringify({id:a.id,column:e.id})))});for(let e of d){let t=Q(`article`,`kbn-card priority-${e.priority??`low`}`);if(t.draggable=!0,t.appendChild(Q(`div`,`kbn-card-title`,e.title)),e.description){let n=Q(`div`,`kbn-card-description`,e.description);n.hidden=!a.has(e.id),t.appendChild(n),t.addEventListener(`click`,()=>{a.has(e.id)?a.delete(e.id):a.add(e.id),n.hidden=!a.has(e.id)})}else t.addEventListener(`click`,()=>{a.has(e.id)?a.delete(e.id):a.add(e.id)});if(e.tags?.length){let n=Q(`div`,`kbn-tags`);for(let t of e.tags)n.appendChild(Q(`span`,`kbn-tag`,t));t.appendChild(n)}t.addEventListener(`dragstart`,()=>{o=e.id,t.classList.add(`dragging`)}),t.addEventListener(`dragend`,()=>{t.classList.remove(`dragging`),o=``}),f.appendChild(t)}t.appendChild(f),c.appendChild(t)}};l(),e.appendChild(s)},styles(){return yw}},xw=`
|
|
2110
2110
|
.sort-list { list-style: none; padding: 0; margin: 0; }
|
|
2111
2111
|
.sort-item { display: flex; align-items: center; gap: 10px; padding: 10px 14px; margin: 4px 0;
|
|
2112
2112
|
background: var(--aikit-surface, #252526); border: 1px solid var(--aikit-border, #3c3c3c);
|
|
@@ -2117,7 +2117,7 @@ container holding the app. Specify either width or maxWidth, and either height o
|
|
|
2117
2117
|
.drag-handle { font-size: 18px; color: var(--aikit-muted, #858585); cursor: grab; user-select: none; }
|
|
2118
2118
|
.sort-label { flex: 1; color: var(--aikit-text, #ccc); }
|
|
2119
2119
|
.sort-pos { font-size: 12px; color: var(--aikit-muted, #858585); font-variant-numeric: tabular-nums; }
|
|
2120
|
-
`,
|
|
2120
|
+
`,Sw={name:`list-sort`,label:`Sortable List`,detect(e){if(typeof e!=`object`||!e||Array.isArray(e))return 0;let t=e;return t.items&&Array.isArray(t.items)&&!t.categories?.8:0},render(e,t,n){let r=t,i=Q(`div`,`block tpl-list-sort`);XC(`tpl-list-sort`,xw);function a(e){i.innerHTML=``;let t=Q(`ul`,`sort-list`),r=-1;for(let i=0;i<e.length;i++){let o=e[i],s=document.createElement(`li`);s.className=`sort-item`,s.draggable=!0,s.dataset.idx=String(i);let c=Q(`span`,`drag-handle`,`⠿`),l=Q(`span`,`sort-label`,o.label),u=Q(`span`,`sort-pos`,`#${i+1}`);s.appendChild(c),s.appendChild(l),s.appendChild(u),s.addEventListener(`dragstart`,()=>{r=Number(s.dataset.idx),s.classList.add(`dragging`)}),s.addEventListener(`dragend`,()=>{s.classList.remove(`dragging`)}),s.addEventListener(`dragenter`,e=>{e.preventDefault()}),s.addEventListener(`dragover`,e=>{e.preventDefault(),s.classList.add(`drag-over`)}),s.addEventListener(`dragleave`,()=>{s.classList.remove(`drag-over`)}),s.addEventListener(`drop`,t=>{t.preventDefault(),s.classList.remove(`drag-over`);let i=Number(s.dataset.idx);if(r>=0&&r!==i){let t=[...e],[o]=t.splice(r,1);t.splice(i,0,o),a(t),n.emitAction({type:`button`,id:`reorder`,label:`Reorder`},JSON.stringify(t.map(e=>e.id)))}}),t.appendChild(s)}i.appendChild(t)}a([...r.items??[]]),e.appendChild(i)},styles(){return xw}},Cw=document.getElementById(`app`);if(!Cw)throw Error(`Missing #app element`);var $=Cw,ww=KC(),Tw=ww?void 0:new uC({name:`AI Kit Present`,version:`1.0.0`}),Ew=new ow;Ew.register(Sw),Ew.register(vw),Ew.register(hw),Ew.register(bw);var Dw=VC(Tw),Ow={app:Tw,data:qC(Tw),emitAction:Dw},kw=new pw,Aw=new ew,jw=Tw?new JC(Tw):void 0,Mw=null;function Nw(){Mw?.(),Mw=null,zw?.destroy&&zw.destroy(),zw=null}function Pw(e,t){let n=new Map,r=e=>{n.set(o(e.id),e)};for(let e of t??[])r(e);for(let t of e)if(!(t.type!==`actions`||!Array.isArray(t.value)))for(let e of t.value)e&&typeof e==`object`&&`id`in e&&r(e);return n}function Fw(e,t,n){let r=Pw(t,n);Mw=BC(e,t,(e,t)=>{Dw(r.get(e)??{type:t===void 0?`button`:`select`,id:e,label:e},t)})}function Iw(e,t,n){let r=document.documentElement.dir,i=WC(e,t,{colorScheme:kw.getTheme(),lang:document.documentElement.lang||void 0,dir:r===`ltr`||r===`rtl`||r===`auto`?r:void 0});return i?{blocks:i.blocks,actions:n.actions}:null}var Lw;function Rw(e){Nw(),$.innerHTML=``;let t=aw(e);if(e.title){let t=Q(`div`,`header`);t.appendChild(Q(`h1`,``,e.title)),t.appendChild(Q(`span`,`badge streaming`,`⟳`)),$.appendChild(t)}let n=Q(`div`,`content`);Fw(n,t.blocks??[]),$.appendChild(n)}var zw=null;function Bw(e,t){$.innerHTML=``;let n=Q(`div`,`error-panel`);n.appendChild(Q(`h3`,``,`⚠ ${e}`)),n.appendChild(Q(`pre`,``,t instanceof Error?t.message:String(t))),$.appendChild(n)}function Vw(e){Nw(),$.innerHTML=``;let t=aw(e),n=t.data;if(!n){$.innerHTML=`<p class="no-data">No content data received.</p>`;return}if(e.title){let t=Q(`div`,`header`);t.appendChild(Q(`h1`,``,e.title)),t.appendChild(Q(`span`,`badge`,`AI KIT`)),$.appendChild(t)}let r=t.template?Ew.get(t.template):Ew.detect(n),i=Q(`div`,`content`);if(r)zw=r,r.render(i,n,Ow);else if(t.template){let r=Iw(t.template,n,e);r?Fw(i,r.blocks,r.actions):Fw(i,t.blocks??[],e.actions)}else Fw(i,t.blocks??[],e.actions);if($.appendChild(i),e.actions?.length){let t=Q(`div`,`actions-shell`),n=BC(t,[{type:`actions`,value:e.actions}],(t,n)=>{Dw(e.actions?.find(e=>o(e.id)===t)??{type:n===void 0?`button`:`select`,id:t,label:t},n)}),r=Mw;Mw=()=>{r?.(),n()},$.appendChild(t)}let a=Q(`div`,`footer`);a.innerHTML=`<span class="footer-brand">Powered by <strong>AI Kit</strong></span>`,$.appendChild(a)}Tw?(Tw.connect().then(()=>{let e=Tw.getHostContext();e&&(kw.apply(e),Aw.apply(e),jw?.apply(e))}),Tw.onhostcontextchanged=e=>{kw.apply(e),Aw.apply(e),jw?.apply(e),zw?.onThemeChange&&zw.onThemeChange(kw.getTheme())},Tw.ontoolinputpartial=e=>{let t=e.arguments;t&&($.dataset.streaming=`true`,clearTimeout(Lw),Lw=setTimeout(()=>{try{let e=t.content;if(!e)return;Rw({title:t.title,template:t.template,content:e})}catch{}},80))},Tw.ontoolinput=()=>{clearTimeout(Lw),delete $.dataset.streaming},Tw.ontoolresult=e=>{if(clearTimeout(Lw),delete $.dataset.streaming,e.structuredContent)try{Vw(e.structuredContent);return}catch(e){Bw(`Render error`,e);return}let t=e.content?.find(e=>e.type===`text`)?.text;if(!t){$.innerHTML=`<p>No data received.</p>`;return}try{Vw(JSON.parse(t))}catch{Vw({content:t})}}):ww&&(document.documentElement.dataset.theme=`dark`,Vw(ww));</script>
|
|
2121
2121
|
</head>
|
|
2122
2122
|
<body>
|
|
2123
2123
|
<div id="app">
|
|
@@ -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-CBs_q9S9.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-CBs_q9S9.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-CzPRmJtW.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-CzPRmJtW.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-0JRtGGti.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-0JRtGGti.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-D-PQVQ3u.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-D-PQVQ3u.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};
|