@juspay/neurolink 12.51.2 → 12.51.3

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/CHANGELOG.md CHANGED
@@ -1,8 +1,8 @@
1
- ## [12.51.2](https://github.com/juspay/neurolink/compare/v12.51.1...v12.51.2) (2026-10-12)
1
+ ## [12.51.3](https://github.com/juspay/neurolink/compare/v12.51.2...v12.51.3) (2026-10-12)
2
2
 
3
3
  ### Bug Fixes
4
4
 
5
- - **(cli):** harden Azure, Vertex and SageMaker setup prompts ([51b8892](https://github.com/juspay/neurolink/commit/51b8892764aa060337e2aff44f0f08fffd8864e5))
5
+ - **(server):** rate-limit file routes, confine demo paths, linearise auth patterns ([af649c6](https://github.com/juspay/neurolink/commit/af649c634ca6f6fc8719680a4b29312856bfdcdc))
6
6
 
7
7
  ## [11.2.3](https://github.com/juspay/neurolink/compare/v11.2.2...v11.2.3) (2026-08-19)
8
8
 
@@ -2297,7 +2297,7 @@ To:
2297
2297
  Import Zod with: import { z } from 'zod'`);if(!o){const i=typeof n.parse=="function"||"_def"in n?`Tool '${e}' has a Zod-like schema but validation failed. Ensure it's a valid Zod schema: z.object({ ... })`:typeof n.validate=="function"?`Tool '${e}' has a validate method but it may not be callable. Ensure: { parameters: { validate: (data) => { ... } } }`:`Tool '${e}' parameters must be a schema object with validation. Supported formats:
2298
2298
  \u2022 Zod schema: { parameters: z.object({ value: z.string() }) }
2299
2299
  \u2022 Custom schema: { parameters: { validate: (data) => { ... } } }
2300
- \u2022 Custom schema: { parameters: { parse: (data) => { ... } } }`;throw new Error(i)}}if(t.metadata){if(typeof t.metadata!="object"||Array.isArray(t.metadata))throw new Error(`Tool '${e}' metadata must be an object. Received: ${typeof t.metadata}. Example: { category: "data", version: "1.0.0", author: "team@company.com" }`);if(t.metadata.version&&typeof t.metadata.version!="string")throw new Error(`Tool '${e}' metadata.version must be a string. Received: ${typeof t.metadata.version}. Example: "1.0.0", "2.1.3-beta"`);if(t.metadata.category&&typeof t.metadata.category!="string")throw new Error(`Tool '${e}' metadata.category must be a string. Received: ${typeof t.metadata.category}. Example: "data", "communication", "utility"`);if(t.metadata.tags&&!Array.isArray(t.metadata.tags))throw new Error(`Tool '${e}' metadata.tags must be an array of strings. Received: ${typeof t.metadata.tags}. Example: ["api", "external", "web"]`)}h.debug(`Tool '${e}' validation passed`,{nameLength:e.length,descriptionLength:t.description.length,hasParameters:!!t.parameters,hasMetadata:!!t.metadata})}Rer(),Ser(),wer(),ber(),Per(),yQt(),ut(),tt(),dl(),gh(),pl(),pl(),dJ(),Jm(),Jm(),_h(),_h(),Cp(),Cp(),Rg(),xf(),ext(),Sce(),qm(),Zle(),rce(),Z0r(),MQ(),tt(),ut(),ob();var dEn=class{config;neurolinkInstance=null;instanceId;constructor(e){this.config={...L8,...e},this.instanceId=`ImageGenService-${Date.now()}-${Math.random().toString(36).substring(2,11)}`}async getNeuroLink(){if(!this.neurolinkInstance){const{NeuroLink:e}=await au().then(()=>Fce);this.neurolinkInstance=new e({conversationMemory:{enabled:!1},enableOrchestration:!1})}return this.neurolinkInstance}async generate(e){const t=Date.now();if(!this.config.enabled)return{success:!1,error:"Image generation is disabled"};if(!e.prompt||e.prompt.trim().length===0)return{success:!1,error:"Prompt is required for image generation"};try{const r=await this.getNeuroLink();let n=e.prompt;e.style&&(n=`${e.style} style: ${n}`),e.negativePrompt&&(n=`${n}. Avoid: ${e.negativePrompt}`);const o={text:n};if(e.images?.length){const f=this.config.maxReferenceImages??5,g=e.images.slice(0,f);o.images=g.map(y=>Buffer.isBuffer(y)?y.toString("base64"):y)}if(e.pdfFiles?.length){const f=this.config.maxReferencePdfs??1;o.pdfFiles=e.pdfFiles.slice(0,f)}const i=e.provider??this.config.defaultProvider,s=e.model??this.config.defaultModel,a=e.region??this.config.defaultRegion,l={input:o,provider:i,model:s,disableTools:!0,temperature:e.temperature??this.config.defaultTemperature??.75,timeout:this.config.timeout};a&&(l.region=a);const c=this.config.maxImages??4,u=Math.min(e.numberOfImages??1,c);l.numberOfImages=u,e.aspectRatio&&(l.aspectRatio=e.aspectRatio);const d=await Ue(r.generate(l),this.config.timeout,new Error(`Image generation timed out after ${this.config.timeout}ms`)),p=this.extractImageFromResult(d),m=Date.now()-t;return p?{success:!0,imageBuffer:p.imageBuffer,base64:p.base64,mimeType:p.mimeType,model:s,provider:i,generationTimeMs:m}:{success:!1,error:"No image generated",model:s,provider:i,generationTimeMs:m}}catch(r){return{success:!1,error:`Generation failed: ${r instanceof Error?r.message:String(r)}`,generationTimeMs:Date.now()-t}}}extractImageFromResult(e){if(!e||typeof e!="object")return null;const t=e,r=t.imageOutput??t.images?.[0];if(r&&typeof r=="object"){const o=r;if(typeof o.base64=="string"){const i=o.base64,s=Buffer.from(i,"base64"),a=typeof o.mimeType=="string"?o.mimeType:QC(s);return{imageBuffer:s,base64:i,mimeType:a}}}if(Buffer.isBuffer(r)){const o=r.toString("base64");return{imageBuffer:r,base64:o,mimeType:QC(r)}}const n=t.content;if(typeof n=="string"&&n.startsWith("data:image")){const o=n.match(/^data:image\/(\w+);base64,(.+)$/);if(o?.[2]){const i=`image/${o[1]}`,s=o[2];return{imageBuffer:Buffer.from(s,"base64"),base64:s,mimeType:i}}}if(typeof n=="string"&&!n.startsWith("data:"))try{const o=Buffer.from(n,"base64"),i=ZC(o);if(i!==null)return{imageBuffer:o,base64:n,mimeType:i}}catch{}return null}isEnabled(){return this.config.enabled}getModel(){return this.config.defaultModel}getProvider(){return this.config.defaultProvider}getConfig(){return{...this.config}}getInstanceId(){return this.instanceId}updateConfig(e){this.config={...this.config,...e}}enable(){this.config.enabled=!0}disable(){this.config.enabled=!1}};ob(),qHt(),b1(),await au();function pEn(){const e=process.env.LANGFUSE_ENABLED?.trim().toLowerCase()==="true",t=process.env.LANGFUSE_PUBLIC_KEY?.trim(),r=process.env.LANGFUSE_SECRET_KEY?.trim();if(!(!e||!t||!r))return{langfuse:{enabled:e,publicKey:t,secretKey:r,baseUrl:process.env.LANGFUSE_BASE_URL?.trim()||"https://cloud.langfuse.com",environment:process.env.LANGFUSE_ENVIRONMENT?.trim()||process.env.PUBLIC_APP_ENVIRONMENT?.trim()||"dev",release:process.env.PUBLIC_APP_VERSION?.trim()||process.env.npm_package_version?.trim()||"v1.0.0"}}}Im(),ul(),nYe(),aot(),uot(),Xl(),ejr(),tjr(),eK(),fYe(),eet(),ut(),v2(),tt(),G(),uQt(),mWt(),cWt(),lWt(),Kte(),fne(),DYt(),cne(),ace(),bur(),Ut(),G(),qr(),nce();function Hb(e){return{jsonrpc:"2.0",id:it(),method:"elicitation/request",params:{type:e.type,message:e.message,toolName:e.toolName,serverId:e.serverId,timeout:e.timeout,optional:e.optional,defaultValue:e.defaultValue,options:e.options??{}}}}function xkr(e,t){return{jsonrpc:"2.0",id:it(),method:"elicitation/response",params:{requestId:e,responded:t.responded,value:t.value,cancelled:t.cancelled,timedOut:t.timedOut,error:t.error}}}function mEn(e,t){return{jsonrpc:"2.0",id:it(),method:"elicitation/cancel",params:{requestId:e,reason:t}}}function hEn(e){if(typeof e!="object"||e===null)return!1;const t=e;return t.jsonrpc==="2.0"&&typeof t.id=="string"&&(t.method==="elicitation/request"||t.method==="elicitation/response"||t.method==="elicitation/cancel")&&typeof t.params=="object"&&t.params!==null}function jme(e){const{type:t,message:r,toolName:n,serverId:o,timeout:i,optional:s,defaultValue:a,options:l}=e.params,c={id:e.id,type:t,message:r,toolName:n,serverId:o,timeout:i,optional:s,defaultValue:a};switch(t){case"confirmation":return{...c,type:"confirmation",confirmLabel:l?.confirmLabel,cancelLabel:l?.cancelLabel};case"text":return{...c,type:"text",placeholder:l?.placeholder,minLength:l?.minLength,maxLength:l?.maxLength,pattern:l?.pattern,multiline:l?.multiline};case"select":return{...c,type:"select",options:l?.options??[]};case"multiselect":return{...c,type:"multiselect",options:l?.options??[],minSelections:l?.minSelections,maxSelections:l?.maxSelections};case"form":return{...c,type:"form",fields:l?.fields??[],submitLabel:l?.submitLabel};case"file":return{...c,type:"file",accept:l?.accept,multiple:l?.multiple,maxSize:l?.maxSize};case"secret":return{...c,type:"secret",hint:l?.hint};default:return c}}function Akr(e){return xkr(e.requestId,{responded:e.responded,value:e.value,cancelled:e.cancelled,timedOut:e.timedOut,error:e.error})}var Ckr=class{manager;config;constructor(e={}){this.manager=e.manager??MF,this.config={manager:this.manager,defaultTimeout:e.defaultTimeout??6e4,enableLogging:e.enableLogging??!1,customHandler:e.customHandler}}async handleMessage(e){if(this.config.enableLogging&&h.info("[ElicitationProtocol] Received:",e.method),this.config.customHandler)return await At(this.config.customHandler(e),this.config.defaultTimeout,`[ElicitationProtocol] Custom handler timed out after ${this.config.defaultTimeout}ms`);switch(e.method){case"elicitation/request":return this.handleRequest(e);case"elicitation/response":return this.handleResponse(e);case"elicitation/cancel":return this.handleCancel(e);default:this.config.enableLogging&&h.warn(`[ElicitationProtocol] Unhandled method: ${e.method}`);return}}async handleRequest(e){const t=jme(e),r=await this.manager.request({...t,timeout:t.timeout??this.config.defaultTimeout});return Akr(r)}async handleResponse(e){this.config.enableLogging&&h.info("[ElicitationProtocol] Response received (no action needed)")}async handleCancel(e){this.manager.cancel(e.params.requestId,e.params.reason)}async requestElicitation(e){const t=Hb(e),r=jme(t);return this.manager.request({...r,timeout:r.timeout??this.config.defaultTimeout})}cancelElicitation(e,t){this.manager.cancel(e,t)}getManager(){return this.manager}setHandler(e){this.manager.setHandler(e)}setEnabled(e){this.manager.setEnabled(e)}isEnabled(){return this.manager.isEnabled()}};function fEn(e,t){const r={};return t.confirmLabel!==void 0&&(r.confirmLabel=t.confirmLabel),t.cancelLabel!==void 0&&(r.cancelLabel=t.cancelLabel),Hb({type:"confirmation",message:e,toolName:t.toolName,serverId:t.serverId,timeout:t.timeout,options:r})}function gEn(e,t){const r={};return t.placeholder!==void 0&&(r.placeholder=t.placeholder),t.minLength!==void 0&&(r.minLength=t.minLength),t.maxLength!==void 0&&(r.maxLength=t.maxLength),t.pattern!==void 0&&(r.pattern=t.pattern),t.multiline!==void 0&&(r.multiline=t.multiline),Hb({type:"text",message:e,toolName:t.toolName,serverId:t.serverId,defaultValue:t.defaultValue,timeout:t.timeout,options:r})}function yEn(e,t,r){return Hb({type:"select",message:e,toolName:r.toolName,serverId:r.serverId,defaultValue:r.defaultValue,timeout:r.timeout,options:{options:t}})}function vEn(e,t,r){const n={fields:t};return r.submitLabel!==void 0&&(n.submitLabel=r.submitLabel),Hb({type:"form",message:e,toolName:r.toolName,serverId:r.serverId,timeout:r.timeout,options:n})}var wEn=new Ckr;jte(),kur(),Yn(),qr(),tt();var TEn=class extends fn{config;tools=new Map;isInitialized=!1;isRunning=!1;constructor(e){super(),this.config={id:e.id,name:e.name,description:e.description??"",version:e.version??"1.0.0",category:e.category??"custom",transport:e.transport??"stdio",metadata:e.metadata??{},defaultTimeoutMs:e.defaultTimeoutMs??3e4,defaultAnnotations:e.defaultAnnotations??{}}}async init(){this.isInitialized||(await this.onInit(),this.isInitialized=!0,this.emit("serverReady",{tools:Array.from(this.tools.keys())}))}async onInit(){}async start(){this.isInitialized||await this.init(),!this.isRunning&&(await this.onStart(),this.isRunning=!0)}async onStart(){}async stop(e){this.isRunning&&(await this.onStop(),this.isRunning=!1,this.emit("serverStopped",{reason:e}))}async onStop(){}registerTool(e){this.validateTool(e);const t={...e,annotations:{...this.config.defaultAnnotations,...e.annotations}};return this.tools.set(e.name,t),this.emit("toolRegistered",{toolName:e.name,tool:t}),this}registerTools(e){for(const t of e)this.registerTool(t);return this}validateTool(e){if(!e.name||typeof e.name!="string")throw he.invalidConfiguration("tool.name","Tool name is required and must be a string");if(e.name.length>64)throw he.invalidConfiguration("tool.name","Tool name must be 64 characters or less",{toolName:e.name});if(!/^[a-zA-Z_][a-zA-Z0-9_-]*$/.test(e.name))throw he.invalidConfiguration("tool.name","Tool name must start with a letter or underscore and contain only alphanumeric characters, underscores, and hyphens",{toolName:e.name});if(!e.description||typeof e.description!="string")throw he.invalidConfiguration("tool.description","Tool description is required and must be a string",{toolName:e.name});if(typeof e.execute!="function")throw he.invalidConfiguration("tool.execute","Tool execute function is required",{toolName:e.name});if(this.tools.has(e.name))throw he.invalidConfiguration("tool.name",`Tool '${e.name}' is already registered`,{toolName:e.name})}async executeTool(e,t,r){const n=this.tools.get(e);if(!n)return{success:!1,error:`Tool '${e}' not found on server '${this.config.id}'`,metadata:{toolName:e,serverId:this.config.id}};const o=Date.now(),i=this.config.defaultTimeoutMs??3e4;try{const s=await At(n.execute(t,r??{}),i,he.toolTimeout(e,i).message),a=Date.now()-o;return this.emit("toolExecuted",{toolName:e,duration:a,success:!0}),this.isToolResult(s)?{...s,metadata:{...s.metadata,toolName:e,serverId:this.config.id,executionTime:a}}:{success:!0,data:s,metadata:{toolName:e,serverId:this.config.id,executionTime:a}}}catch(s){const a=Date.now()-o;return this.emit("toolError",{toolName:e,error:s instanceof Error?s:new Error(String(s))}),this.emit("toolExecuted",{toolName:e,duration:a,success:!1}),{success:!1,error:s instanceof Error?s.message:String(s),metadata:{toolName:e,serverId:this.config.id,executionTime:a}}}}isToolResult(e){return e!==null&&typeof e=="object"&&"success"in e&&typeof e.success=="boolean"}getTools(){return Array.from(this.tools.values())}getTool(e){return this.tools.get(e)}hasTool(e){return this.tools.has(e)}removeTool(e){return this.tools.delete(e)}toServerInfo(){return{id:this.config.id,name:this.config.name,description:this.config.description,transport:this.config.transport,status:this.isRunning?"connected":"stopped",tools:this.getTools().map(e=>({name:e.name,description:e.description,inputSchema:e.inputSchema,execute:(t,r)=>this.executeTool(e.name,t,r)})),metadata:{...this.config.metadata,category:this.config.category,version:this.config.version}}}getToolsByAnnotation(e,t){return this.getTools().filter(r=>{const n=r.annotations?.[e];return Array.isArray(t)&&Array.isArray(n)?t.some(o=>n.includes(o)):n===t})}getReadOnlyTools(){return this.getToolsByAnnotation("readOnlyHint",!0)}getDestructiveTools(){return this.getToolsByAnnotation("destructiveHint",!0)}getIdempotentTools(){return this.getToolsByAnnotation("idempotentHint",!0)}getToolsRequiringConfirmation(){return this.getToolsByAnnotation("requiresConfirmation",!0)}get id(){return this.config.id}get name(){return this.config.name}get description(){return this.config.description}get version(){return this.config.version}get category(){return this.config.category}get initialized(){return this.isInitialized}get running(){return this.isRunning}};Vte(),Yn(),G(),tt(),qr();var bEn=class extends fn{config;resources=new Map;prompts=new Map;subscriptions=new Map;resourceTemplates=new Map;constructor(e={}){super(),this.config={resources:e.resources??!0,prompts:e.prompts??!0,resourceSubscriptions:e.resourceSubscriptions??!0}}registerResource(e){if(!this.config.resources)throw he.invalidConfiguration("resources","Resource support is not enabled");return this.validateResourceUri(e.uri),this.resources.set(e.uri,e),this.emit("resourceRegistered",{uri:e.uri,name:e.name,timestamp:new Date}),h.debug(`[ServerCapabilities] Registered resource: ${e.uri}`),this}registerResourceTemplate(e,t){if(!this.config.resources)throw he.invalidConfiguration("resources","Resource support is not enabled");return this.resourceTemplates.set(e,{...t,uri:t.uriPattern}),this.emit("resourceTemplateRegistered",{pattern:e,timestamp:new Date}),this}unregisterResource(e){const t=this.resources.delete(e);return t&&(this.subscriptions.delete(e),this.emit("resourceUnregistered",{uri:e,timestamp:new Date})),t}listResources(){return Array.from(this.resources.values()).map(e=>({uri:e.uri,name:e.name,description:e.description,mimeType:e.mimeType,size:e.size,dynamic:e.dynamic,annotations:e.annotations}))}async readResource(e,t){let r=this.resources.get(e);if(r||(r=this.findResourceTemplate(e)),!r)throw he.invalidConfiguration("resource",`Resource not found: ${e}`);const n=Date.now(),o=3e4;try{const i=await At(r.reader(e,t),o,`Resource read timed out after ${o}ms for URI: ${e}`),s=Date.now()-n;return this.emit("resourceRead",{uri:e,duration:s,success:!0,timestamp:new Date}),i}catch(i){const s=Date.now()-n;throw this.emit("resourceRead",{uri:e,duration:s,success:!1,error:i instanceof Error?i.message:String(i),timestamp:new Date}),i}}subscribeToResource(e,t){if(!this.config.resourceSubscriptions)throw he.invalidConfiguration("resourceSubscriptions","Resource subscriptions are not enabled");this.subscriptions.has(e)||this.subscriptions.set(e,new Set);const r=this.subscriptions.get(e);return r&&r.add(t),this.emit("resourceSubscribed",{uri:e,timestamp:new Date}),()=>{const n=this.subscriptions.get(e);n&&(n.delete(t),n.size===0&&this.subscriptions.delete(e)),this.emit("resourceUnsubscribed",{uri:e,timestamp:new Date})}}async notifyResourceChanged(e){const t=this.subscriptions.get(e);if(!(!t||t.size===0))try{const r=await this.readResource(e);for(const n of t)try{const o=n(e,r);o&&typeof o.catch=="function"&&o.catch(i=>{h.error(`[ServerCapabilities] Async error notifying subscriber for ${e}:`,i)})}catch(o){h.error(`[ServerCapabilities] Error notifying subscriber for ${e}:`,o)}this.emit("resourceChanged",{uri:e,subscriberCount:t.size,timestamp:new Date})}catch(r){h.error(`[ServerCapabilities] Error reading resource for notification: ${e}`,r)}}getResource(e){return this.resources.get(e)??this.findResourceTemplate(e)}validateResourceUri(e){try{new URL(e)}catch{h.warn(`[ServerCapabilities] Resource URI is not a valid URL: ${e}`)}}findResourceTemplate(e){for(const[t,r]of this.resourceTemplates)if(this.matchesPattern(e,t))return{...r,uri:e}}matchesPattern(e,t){if(t.length>200)return!1;const r=t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".").replace(/\\\{[^}]*\\\}/g,"[^/]+");try{return new RegExp(`^${r}$`).test(e)}catch{return!1}}registerPrompt(e){if(!this.config.prompts)throw he.invalidConfiguration("prompts","Prompt support is not enabled");return this.validatePromptName(e.name),this.prompts.set(e.name,e),this.emit("promptRegistered",{name:e.name,timestamp:new Date}),h.debug(`[ServerCapabilities] Registered prompt: ${e.name}`),this}unregisterPrompt(e){const t=this.prompts.delete(e);return t&&this.emit("promptUnregistered",{name:e,timestamp:new Date}),t}listPrompts(){return Array.from(this.prompts.values()).map(e=>({name:e.name,description:e.description,arguments:e.arguments}))}async getPrompt(e,t={},r){const n=this.prompts.get(e);if(!n)throw he.invalidConfiguration("prompt",`Prompt not found: ${e}`);for(const s of n.arguments??[])if(s.required&&t[s.name]===void 0)throw he.invalidConfiguration("promptArgument",`Missing required argument: ${s.name}`);const o=Date.now(),i=3e4;try{const s=await At(n.generator(t,r),i,`Prompt generation timed out after ${i}ms for prompt: ${e}`),a=Date.now()-o;return this.emit("promptGenerated",{name:e,duration:a,success:!0,messageCount:s.messages.length,timestamp:new Date}),s}catch(s){const a=Date.now()-o;throw this.emit("promptGenerated",{name:e,duration:a,success:!1,error:s instanceof Error?s.message:String(s),timestamp:new Date}),s}}getPromptDefinition(e){return this.prompts.get(e)}validatePromptName(e){if(!e||typeof e!="string")throw he.invalidConfiguration("promptName","Prompt name is required and must be a string");if(!/^[a-zA-Z_][a-zA-Z0-9_-]*$/.test(e))throw he.invalidConfiguration("promptName","Prompt name must start with a letter or underscore and contain only alphanumeric characters, underscores, and hyphens");if(this.prompts.has(e))throw he.invalidConfiguration("promptName",`Prompt '${e}' is already registered`)}getCapabilities(){const e={};return this.config.resources&&(e.resources={subscribe:this.config.resourceSubscriptions,listChanged:!0}),this.config.prompts&&(e.prompts={listChanged:!0}),e}getStatistics(){let e=0;for(const t of this.subscriptions.values())e+=t.size;return{resourceCount:this.resources.size,templateCount:this.resourceTemplates.size,promptCount:this.prompts.size,subscriptionCount:e}}clear(){this.resources.clear(),this.resourceTemplates.clear(),this.prompts.clear(),this.subscriptions.clear(),this.emit("cleared",{timestamp:new Date})}};function _En(e,t,r,n){return{uri:e,name:t,description:n?.description,mimeType:"text/plain",dynamic:n?.dynamic??typeof r=="function",reader:async o=>({uri:o,mimeType:"text/plain",text:typeof r=="function"?await r():r})}}function EEn(e,t,r,n){return{uri:e,name:t,description:n?.description,mimeType:"application/json",dynamic:n?.dynamic??typeof r=="function",reader:async o=>({uri:o,mimeType:"application/json",text:JSON.stringify(typeof r=="function"?await r():r,null,2)})}}function SEn(e,t,r){return{name:e,description:r?.description,arguments:r?.arguments,generator:async n=>{let o=t;for(const[i,s]of Object.entries(n)){const a=i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");o=o.replace(new RegExp(`\\{${a}\\}`,"g"),()=>String(s))}return{messages:[{role:"user",content:{type:"text",text:o}}]}}}}rA(),UF(),Pur(),HHt(),JHt(),sQt();async function kEn(){return Promise.resolve()}async function xEn(){return[]}async function AEn(e,t,r,n){throw he.invalidConfiguration("executeMCP","Direct legacy MCP execution is deprecated. Use the new module APIs (createMCPServer, MultiServerManager, ToolRouter, etc.) instead.")}async function CEn(){return{initialized:!1,pluginsDiscovered:0,pluginsBySource:{},availablePlugins:[]}}Sct(),G(),TL(),Qjt(),Kjt(),Fjt(),$K(),Usr(),nle();function IEn(e){const t=new Map;e.forEach(n=>{const o=`${n.provider}/${n.model}`,i=t.get(o)||{total:0,successful:0,totalTime:0};t.set(o,{total:i.total+1,successful:i.successful+(n.status==="success"?1:0),totalTime:i.totalTime+n.responseTime})});const r={};return t.forEach((n,o)=>{r[o]={successRate:n.successful/n.total,avgResponseTime:n.totalTime/n.total}}),r}function Hme(e){if(e.length===0)return{totalExecutions:0,averageScore:0,averageConfidence:0,averageExecutionTime:0,successRate:0,totalCost:0};const t=e.reduce((s,a)=>s+a.score,0),r=e.reduce((s,a)=>s+a.confidence,0),n=e.reduce((s,a)=>s+a.totalTime,0),o=e.reduce((s,a)=>s+(a.cost||0),0),i=e.filter(s=>s.score>0).length;return{totalExecutions:e.length,averageScore:t/e.length,averageConfidence:r/e.length,averageExecutionTime:n/e.length,successRate:i/e.length,totalCost:o}}function REn(e,t){const r=Hme(e),n=Hme(t),o=r.averageExecutionTime>0?1/r.averageExecutionTime*1e4*.2:0,i=n.averageExecutionTime>0?1/n.averageExecutionTime*1e4*.2:0,s=r.averageScore*.4+r.averageConfidence*100*.3+o+1/(r.totalCost+1)*100*.1,a=n.averageScore*.4+n.averageConfidence*100*.3+i+1/(n.totalCost+1)*100*.1,l=Math.abs(s-a);let c,u;return l<5?(c="tie",u="Workflows perform similarly overall"):s>a?(c="workflow1",u=`Workflow 1 scores higher (${s.toFixed(2)} vs ${a.toFixed(2)})`):(c="workflow2",u=`Workflow 2 scores higher (${a.toFixed(2)} vs ${s.toFixed(2)})`),{workflow1:r,workflow2:n,winner:c,reasoning:u}}yh(),G();var Ikr={id:"quality-max",name:"Quality-Max Adaptive",description:"Adaptive 3-tier execution optimizing for maximum quality",version:"1.0.0",type:"adaptive",models:[{provider:"openai",model:"gpt-4o"}],modelGroups:[{id:"validation-tier",name:"Validation Tier",description:"Fast models to assess complexity and confidence",models:[{provider:"openai",model:"gpt-4o-mini",label:"GPT-4o-mini",temperature:.7,timeout:1e4},{provider:"google-ai",model:"gemini-2.0-flash",label:"Gemini Flash",temperature:.7,timeout:1e4}],executionStrategy:"parallel",continueOnFailure:!0,minSuccessful:1,parallelism:2},{id:"premium-tier",name:"Premium Tier",description:"High-quality models for thorough analysis",models:[{provider:"openai",model:"gpt-4o",label:"GPT-4o",temperature:.7,systemPrompt:"Provide comprehensive, high-quality responses with deep analysis.",timeout:2e4},{provider:"anthropic",model:"claude-3-5-sonnet-20241022",label:"Claude 3.5 Sonnet",temperature:.7,systemPrompt:"Think deeply and provide nuanced, well-reasoned responses.",timeout:2e4}],executionStrategy:"parallel",continueOnFailure:!0,minSuccessful:1,parallelism:2},{id:"expert-tier",name:"Expert Tier",description:"Top-tier model for final quality assurance",models:[{provider:"anthropic",model:"claude-3-5-sonnet-20241022",label:"Claude 3.5 Sonnet Expert",temperature:.6,systemPrompt:"You are an expert. Provide the highest quality, most accurate response possible. Be thorough, precise, and authoritative.",timeout:3e4}],executionStrategy:"sequential",continueOnFailure:!1,minSuccessful:1}],judge:{provider:"openai",model:"gpt-4o",criteria:["quality","depth","accuracy","completeness"],outputFormat:"detailed",includeReasoning:!0,temperature:.1,scoreScale:{min:0,max:100},customPrompt:"Evaluate responses for maximum quality. Prioritize depth, accuracy, and completeness. Be rigorous in assessment."},execution:{timeout:7e4,minResponses:2,costThreshold:.12},tags:["adaptive","quality","tiered","escalation"],metadata:{useCase:"Quality-critical tasks with adaptive execution",recommendedFor:["complex analysis","expert consultation","high-stakes decisions","technical documentation"],averageCost:.08,averageLatency:4500},createdAt:ru},Rkr={id:"speed-first",name:"Speed-First Adaptive",description:"Fast execution with quality fallback",version:"1.0.0",type:"adaptive",models:[{provider:"openai",model:"gpt-4o-mini"}],modelGroups:[{id:"fast-tier",name:"Fast Tier",models:[{provider:"openai",model:"gpt-4o-mini",temperature:.7,timeout:5e3}],executionStrategy:"sequential",continueOnFailure:!0,minSuccessful:1},{id:"balanced-tier",name:"Balanced Tier",models:[{provider:"google-ai",model:"gemini-2.0-flash",temperature:.7,timeout:1e4}],executionStrategy:"sequential",continueOnFailure:!0,minSuccessful:1},{id:"quality-tier",name:"Quality Tier",models:[{provider:"openai",model:"gpt-4o",temperature:.7,timeout:15e3}],executionStrategy:"sequential",continueOnFailure:!1,minSuccessful:1}],judge:{provider:"openai",model:"gpt-4o-mini",criteria:["speed","quality"],outputFormat:"best",includeReasoning:!0,temperature:.1,scoreScale:{min:0,max:100}},execution:{timeout:35e3,minResponses:1,costThreshold:.05},tags:["adaptive","speed","fallback"],metadata:{useCase:"Speed-optimized with quality guarantee",recommendedFor:["real-time applications","quick queries"],averageCost:.01,averageLatency:1500},createdAt:ru},Mkr={id:"balanced-adaptive",name:"Balanced Adaptive",description:"Balanced 2-tier execution",version:"1.0.0",type:"adaptive",models:[{provider:"openai",model:"gpt-4o-mini"}],modelGroups:[{id:"standard-tier",name:"Standard Tier",description:"Fast, cost-effective models",models:[{provider:"openai",model:"gpt-4o-mini",temperature:.7},{provider:"google-ai",model:"gemini-2.0-flash",temperature:.7}],executionStrategy:"parallel",continueOnFailure:!0,minSuccessful:1,parallelism:2},{id:"premium-tier",name:"Premium Tier",description:"High-quality models for complex cases",models:[{provider:"openai",model:"gpt-4o",temperature:.7},{provider:"anthropic",model:"claude-3-5-sonnet-20241022",temperature:.7}],executionStrategy:"parallel",continueOnFailure:!1,minSuccessful:1,parallelism:2}],judge:{provider:"openai",model:"gpt-4o",criteria:["quality","accuracy","balance"],outputFormat:"detailed",includeReasoning:!0,temperature:.1,scoreScale:{min:0,max:100}},execution:{timeout:4e4,minResponses:2,costThreshold:.08},tags:["adaptive","balanced","tiered"],metadata:{useCase:"Balanced speed/quality/cost tradeoff",recommendedFor:["general purpose","production applications"],averageCost:.04,averageLatency:2500},createdAt:ru};function MEn(e,t){const r={speed:Rkr,balanced:Mkr,quality:Ikr},n=t==="balanced"?2:3;return e!==n&&h.warn(`[AdaptiveWorkflow] Requested ${e} tiers but ${t} strategy uses ${n} tiers`),{...r[t],id:`adaptive-${n}tier-${t}`,name:`Adaptive ${n}-Tier (${t})`,description:`${n}-tier adaptive execution optimized for ${t}`}}yh();var Pkr={id:"consensus-3",name:"Consensus-3 Ensemble",description:"3-model parallel ensemble with judge-based selection",version:"1.0.0",type:"ensemble",models:[{provider:"openai",model:"gpt-4o",label:"GPT-4o",weight:1,temperature:.7},{provider:"anthropic",model:"claude-3-5-sonnet-20241022",label:"Claude 3.5 Sonnet",weight:1,temperature:.7},{provider:"google-ai",model:"gemini-2.0-flash",label:"Gemini 2.0 Flash",weight:1,temperature:.7}],judge:{provider:"openai",model:"gpt-4o",criteria:["accuracy","clarity","completeness"],outputFormat:"detailed",includeReasoning:!0,temperature:.1,scoreScale:{min:0,max:100}},execution:{parallelism:3,timeout:3e4,modelTimeout:25e3,minResponses:2,costThreshold:.1},tags:["ensemble","consensus","balanced","multi-provider"],metadata:{useCase:"Balanced quality across providers",recommendedFor:["general queries","explanations","analysis"],averageCost:.02,averageLatency:2e3},createdAt:ru};function PEn(e){return{...Pkr,id:`consensus-3-custom-${Date.now()}`,defaultSystemPrompt:e}}var OEn={id:"consensus-3-fast",name:"Consensus-3 Fast",description:"3-model fast ensemble (lower cost)",version:"1.0.0",type:"ensemble",models:[{provider:"openai",model:"gpt-4o-mini",label:"GPT-4o-mini",weight:1,temperature:.7},{provider:"anthropic",model:"claude-3-haiku-20240307",label:"Claude 3 Haiku",weight:1,temperature:.7},{provider:"google-ai",model:"gemini-2.0-flash",label:"Gemini 2.0 Flash",weight:1,temperature:.7}],judge:{provider:"openai",model:"gpt-4o-mini",criteria:["accuracy","clarity"],outputFormat:"best",includeReasoning:!0,temperature:.1,scoreScale:{min:0,max:100}},execution:{parallelism:3,timeout:2e4,modelTimeout:15e3,minResponses:2,costThreshold:.02},tags:["ensemble","fast","low-cost","consensus"],metadata:{useCase:"Fast consensus for simple queries",recommendedFor:["quick questions","simple explanations"],averageCost:.01,averageLatency:1500},createdAt:ru};yh();var DEn={id:"fast-fallback",name:"Fast-Fallback Chain",description:"Sequential fallback: fast \u2192 mid \u2192 premium",version:"1.0.0",type:"chain",models:[{provider:"openai",model:"gpt-4o-mini"}],modelGroups:[{id:"fast-tier",name:"Fast Tier",description:"Try fast model first (lowest cost)",models:[{provider:"openai",model:"gpt-4o-mini",label:"GPT-4o-mini",temperature:.7,timeout:1e4}],executionStrategy:"sequential",continueOnFailure:!0,minSuccessful:1},{id:"mid-tier",name:"Mid Tier",description:"Mid-tier model (balanced cost/quality)",models:[{provider:"google-ai",model:"gemini-2.0-flash",label:"Gemini 2.0 Flash",temperature:.7,timeout:15e3}],executionStrategy:"sequential",continueOnFailure:!0,minSuccessful:1},{id:"premium-tier",name:"Premium Tier",description:"Premium models (last resort, highest quality)",models:[{provider:"openai",model:"gpt-4o",label:"GPT-4o",temperature:.7,timeout:2e4}],executionStrategy:"sequential",continueOnFailure:!1,minSuccessful:1}],judge:{provider:"openai",model:"gpt-4o-mini",criteria:["quality","response_time"],outputFormat:"best",includeReasoning:!0,temperature:.1,scoreScale:{min:0,max:100}},execution:{timeout:5e4,minResponses:1,costThreshold:.05},tags:["chain","fallback","cost-optimized","reliable"],metadata:{useCase:"Cost-optimized with quality guarantee",recommendedFor:["variable complexity queries","cost-sensitive applications"],averageCost:.01,averageLatency:2e3},createdAt:ru},NEn={id:"aggressive-fallback",name:"Aggressive Fallback",description:"Fast first, then both premium models in parallel",version:"1.0.0",type:"chain",models:[{provider:"openai",model:"gpt-4o-mini"}],modelGroups:[{id:"fast-tier",name:"Fast Tier",models:[{provider:"openai",model:"gpt-4o-mini",temperature:.7,timeout:8e3}],executionStrategy:"sequential",continueOnFailure:!0,minSuccessful:1},{id:"premium-tier",name:"Premium Tier (Both)",description:"Run both premium models in parallel for guaranteed quality",models:[{provider:"openai",model:"gpt-4o",label:"GPT-4o",temperature:.7},{provider:"anthropic",model:"claude-3-5-sonnet-20241022",label:"Claude 3.5 Sonnet",temperature:.7}],executionStrategy:"parallel",continueOnFailure:!1,minSuccessful:1,parallelism:2}],judge:{provider:"openai",model:"gpt-4o",criteria:["quality","completeness"],outputFormat:"detailed",includeReasoning:!0,temperature:.1,scoreScale:{min:0,max:100}},execution:{timeout:4e4,minResponses:1,costThreshold:.08},tags:["chain","fallback","high-quality","reliable"],metadata:{useCase:"High quality guarantee with cost optimization attempt",recommendedFor:["important queries","when quality matters most"],averageCost:.03,averageLatency:2500},createdAt:ru};yh();var LEn={id:"multi-judge-5",name:"Multi-Judge-5 Ensemble",description:"5-model ensemble with 3-judge voting for high confidence",version:"1.0.0",type:"ensemble",models:[{provider:"openai",model:"gpt-4o",label:"GPT-4o",weight:1,temperature:.7},{provider:"openai",model:"gpt-4o-mini",label:"GPT-4o-mini",weight:.8,temperature:.7},{provider:"anthropic",model:"claude-3-5-sonnet-20241022",label:"Claude 3.5 Sonnet",weight:1,temperature:.7},{provider:"anthropic",model:"claude-3-haiku-20240307",label:"Claude 3 Haiku",weight:.7,temperature:.7},{provider:"google-ai",model:"gemini-2.0-flash",label:"Gemini 2 Flash",weight:.9,temperature:.7}],judges:[{provider:"openai",model:"gpt-4o",criteria:["accuracy","clarity","factual_correctness"],outputFormat:"detailed",includeReasoning:!0,temperature:.1,scoreScale:{min:0,max:100},label:"Accuracy Judge"},{provider:"anthropic",model:"claude-3-5-sonnet-20241022",criteria:["reasoning_quality","depth","nuance"],outputFormat:"detailed",includeReasoning:!0,temperature:.1,scoreScale:{min:0,max:100},label:"Reasoning Judge"},{provider:"google-ai",model:"gemini-2.0-flash",criteria:["completeness","coherence","relevance"],outputFormat:"detailed",includeReasoning:!0,temperature:.1,scoreScale:{min:0,max:100},label:"Completeness Judge"}],execution:{parallelism:5,timeout:45e3,modelTimeout:3e4,minResponses:3,costThreshold:.15},tags:["ensemble","multi-judge","voting","high-confidence","critical"],metadata:{useCase:"Critical decisions requiring high confidence",recommendedFor:["important business decisions","technical evaluations","complex analysis","fact-checking"],averageCost:.1,averageLatency:5e3,consensusThreshold:.7},createdAt:ru},FEn={id:"multi-judge-3",name:"Multi-Judge-3 Ensemble",description:"3-model ensemble with 2-judge voting",version:"1.0.0",type:"ensemble",models:[{provider:"openai",model:"gpt-4o",label:"GPT-4o",weight:1,temperature:.7},{provider:"anthropic",model:"claude-3-5-sonnet-20241022",label:"Claude 3.5 Sonnet",weight:1,temperature:.7},{provider:"google-ai",model:"gemini-2.0-flash",label:"Gemini 2.0 Flash",weight:1,temperature:.7}],judges:[{provider:"openai",model:"gpt-4o",criteria:["accuracy","clarity","completeness"],outputFormat:"detailed",includeReasoning:!0,temperature:.1,scoreScale:{min:0,max:100},label:"Primary Judge"},{provider:"anthropic",model:"claude-3-5-sonnet-20241022",criteria:["reasoning","depth","coherence"],outputFormat:"detailed",includeReasoning:!0,temperature:.1,scoreScale:{min:0,max:100},label:"Secondary Judge"}],execution:{parallelism:3,timeout:35e3,modelTimeout:25e3,minResponses:2,costThreshold:.08},tags:["ensemble","multi-judge","voting","balanced"],metadata:{useCase:"Balanced multi-judge evaluation",recommendedFor:["important queries","quality verification"],averageCost:.04,averageLatency:3500},createdAt:ru};function $En(e,t){const r=[{provider:"openai",model:"gpt-4o",label:"GPT-4o",weight:1,temperature:.7},{provider:"anthropic",model:"claude-3-5-sonnet-20241022",label:"Claude 3.5 Sonnet",weight:1,temperature:.7},{provider:"google-ai",model:"gemini-2.0-flash",label:"Gemini 2.0 Flash",weight:1,temperature:.7}],n=[{provider:"openai",model:"gpt-4o-mini",label:"GPT-4o-mini",weight:.8,temperature:.7},{provider:"anthropic",model:"claude-3-haiku-20240307",label:"Claude 3 Haiku",weight:.7,temperature:.7},{provider:"google-ai",model:"gemini-2.5-flash",label:"Gemini 2.5 Flash",weight:.8,temperature:.7},{provider:"openai",model:"gpt-3.5-turbo",label:"GPT-3.5 Turbo",weight:.6,temperature:.7}],o=[...r,...n.slice(0,e-3)],i=[{provider:"openai",model:"gpt-4o",criteria:["accuracy","clarity","completeness"],outputFormat:"detailed",includeReasoning:!0,temperature:.1,scoreScale:{min:0,max:100},label:"Primary Judge"},{provider:"anthropic",model:"claude-3-5-sonnet-20241022",criteria:["reasoning","depth","coherence"],outputFormat:"detailed",includeReasoning:!0,temperature:.1,scoreScale:{min:0,max:100},label:"Secondary Judge"}],s={provider:"google-ai",model:"gemini-2.0-flash",criteria:["relevance","factual_accuracy","structure"],outputFormat:"detailed",includeReasoning:!0,temperature:.1,scoreScale:{min:0,max:100},label:"Tertiary Judge"},a=t===3?[...i,s]:i;return{id:`multi-judge-${e}-${t}`,name:`Multi-Judge ${e}x${t}`,description:`${e}-model ensemble with ${t}-judge voting`,version:"1.0.0",type:"ensemble",models:o,judges:a,execution:{parallelism:e,timeout:45e3,modelTimeout:3e4,minResponses:Math.ceil(e/2),costThreshold:.2},tags:["ensemble","multi-judge","custom"],metadata:{useCase:"Custom multi-judge evaluation",modelCount:e,judgeCount:t},createdAt:ru}}yh();var UEn="1.0.0";Zae(),qar(),Ug(),Ote(),Wl(),await m0r(),fle(),ule(),zjt(),vjt(),Ug(),G();var BEn=["One specific fact, definition or value. A single passage answers it completely.","A handful of related points \u2014 a procedure, a short comparison, one topic explained.","Several distinct areas that each need their own supporting passage.","A broad survey that needs evidence from across the whole corpus."],Okr=[.5,1,1.5,2.5],zEn=.5,GEn=1,qEn=50;async function Dkr(e,t,r){if(!e.trim())return null;const n={breadth:{type:"score",instructions:"How much supporting material does answering this question require from a document collection?",criteria:BEn}};r.canHybrid&&(n.hybrid={type:"boolean",instructions:"This question contains exact terms that must be matched literally \u2014 an identifier, error code, file name, version number, API name, or a quoted phrase \u2014 rather than only a topic to match by meaning."}),r.canGraph&&(n.graph={type:"boolean",instructions:"Answering this requires connecting information that lives in separate documents, such as how two things relate, what depends on what, or tracing a chain across sources."}),r.canRerank&&(n.rerank={type:"boolean",instructions:"This question is specific enough that the ORDER of the retrieved passages matters \u2014 a nearly-right passage would produce a wrong answer, so precision is worth an extra ranking pass."});const o=await t({site:"ragPlan",state:{query:e.slice(0,4e3)},questions:n,timeoutMs:r.timeoutMs});if(!o)return null;const i={model:o.model,latencyMs:o.latencyMs},s=Gee(o.answers,"breadth");if(s&&s.confidence>=zEn){const l=Math.max(0,Math.min(Okr.length-1,Math.round(s.score))),c=Okr[l]??1;i.topK=Math.max(GEn,Math.min(qEn,Math.round(r.defaultTopK*c))),i.breadthLevel=l}return r.canHybrid&&(i.hybrid=Ym(o.answers,"hybrid")),r.canGraph&&(i.graph=Ym(o.answers,"graph")),r.canRerank&&(i.rerank=Ym(o.answers,"rerank")),i.topK!==void 0||i.hybrid!==void 0||i.graph!==void 0||i.rerank!==void 0?(h.debug("[RAG] Search plan decided",{model:o.model,latencyMs:o.latencyMs,topK:i.topK,hybrid:i.hybrid,graph:i.graph,rerank:i.rerank}),i):null}WVt(),S1(),wvr(),bvr(),bwr(),Ewr(),du(),G();var Wme=class Mu{static adapters=new Map;static registerAdapter(t,r){Mu.adapters.set(t,r),h.debug(`[ServerAdapterFactory] Registered adapter for framework: ${t}`)}static async create(t){const{framework:r,neurolink:n,config:o}=t;h.info(`[ServerAdapterFactory] Creating adapter for framework: ${r}`);const i=Mu.adapters.get(r);if(i)return new i(n,o);switch(r){case"hono":{const{HonoServerAdapter:s}=await Promise.resolve().then(()=>(bwr(),Twr));return Mu.adapters.set("hono",s),new s(n,o)}case"express":{const{ExpressServerAdapter:s}=await Promise.resolve().then(()=>(wvr(),vvr));return Mu.adapters.set("express",s),new s(n,o)}case"fastify":{const{FastifyServerAdapter:s}=await Promise.resolve().then(()=>(bvr(),Tvr));return Mu.adapters.set("fastify",s),new s(n,o)}case"koa":{const{KoaServerAdapter:s}=await Promise.resolve().then(()=>(Ewr(),_wr));return Mu.adapters.set("koa",s),new s(n,o)}default:throw new Error(`Unknown framework: ${r}. Supported frameworks: hono (recommended), express, fastify, koa`)}}static async createHono(t,r){return Mu.create({framework:"hono",neurolink:t,config:r})}static async createExpress(t,r){return Mu.create({framework:"express",neurolink:t,config:r})}static async createFastify(t,r){return Mu.create({framework:"fastify",neurolink:t,config:r})}static async createKoa(t,r){return Mu.create({framework:"koa",neurolink:t,config:r})}static isSupported(t){return["hono","express","fastify","koa"].includes(t)}static getSupportedFrameworks(){return[{framework:"hono",status:"available",description:"Multi-runtime support (Node.js, Bun, Deno, Edge)"},{framework:"express",status:"available",description:"Popular Node.js framework with extensive middleware ecosystem"},{framework:"fastify",status:"available",description:"High-performance framework with schema validation"},{framework:"koa",status:"available",description:"Elegant middleware composition with async/await"}]}static getRecommendedFramework(){return"hono"}};async function VEn(e,t){const r=t?.framework??Wme.getRecommendedFramework();return Wme.create({framework:r,neurolink:e,config:t?.config})}du();function jEn(e){const t=r=>{const n=e[r.toLowerCase()];return Array.isArray(n)?n[0]:n};return t("x-neurolink-dev-playground")==="true"||t("x-neurolink-playground")==="true"}var Kme={id:"playground",roles:["developer"]};function HEn(e){const{type:t,validate:r,skipPaths:n=[],errorMessage:o="Authentication required",skipDevPlayground:i=!0}=e,s=e.headerName??WEn(t);return{name:"authentication",order:10,excludePaths:n,handler:async(a,l)=>{if(i&&process.env.NODE_ENV!=="production"&&jEn(a.headers))return a.user={id:Kme.id,email:Kme.email,roles:Kme.roles},l();try{const c=KEn(a,t,s,e.extractToken);if(!c)throw new Eb(o);const u=await r(c,a);if(!u)throw new K$("Invalid authentication token");return a.user={id:u.id,email:u.email,roles:u.roles},u.metadata&&(a.metadata.auth=u.metadata),l()}catch(c){throw c instanceof Eb||c instanceof K$?c:new Eb(c instanceof Error?c.message:"Authentication failed")}}}}function WEn(e){switch(e){case"bearer":case"basic":return"authorization";case"api-key":return"x-api-key";case"custom":return"authorization";default:return"authorization"}}function KEn(e,t,r,n){if(t==="custom"&&n)return n(e);const o=e.headers[r.toLowerCase()];if(!o)return null;switch(t){case"bearer":{const i=o.match(/^Bearer\s+(.+)$/i);return i?i[1]:null}case"basic":{const i=o.match(/^Basic\s+(.+)$/i);return i?i[1]:null}case"api-key":return o;case"custom":return o;default:return null}}function JEn(e){const{requiredRoles:t,requireAll:r=!1,errorMessage:n="Insufficient permissions"}=e;return{name:"role-check",order:11,handler:async(o,i)=>{if(!o.user)throw new Eb("Authentication required");const s=o.user.roles||[];if(!(r?t.every(l=>s.includes(l)):t.some(l=>s.includes(l))))throw new cpe(n,o.requestId,t);return i()}}}var Nkr=class{cache=new Map;accessOrder=[];maxSize;constructor(e=1e3){this.maxSize=e}async get(e){const t=this.cache.get(e);if(t){if(Date.now()-t.createdAt>t.ttlMs){await this.delete(e);return}return this.updateAccessOrder(e),t}}async set(e,t){if(this.cache.size>=this.maxSize&&!this.cache.has(e)){const r=this.accessOrder.shift();r&&this.cache.delete(r)}this.cache.set(e,t),this.updateAccessOrder(e)}async delete(e){this.cache.delete(e);const t=this.accessOrder.indexOf(e);t>-1&&this.accessOrder.splice(t,1)}async clear(){this.cache.clear(),this.accessOrder=[]}updateAccessOrder(e){const t=this.accessOrder.indexOf(e);t>-1&&this.accessOrder.splice(t,1),this.accessOrder.push(e)}};function XEn(e){const{ttlMs:t,maxSize:r=1e3,keyGenerator:n=YEn,methods:o=["GET"],paths:i,excludePaths:s=[],store:a=new Nkr(r),includeQuery:l=!0,ttlByPath:c={}}=e;return{name:"cache",order:20,excludePaths:s,handler:async(u,d)=>{if(!o.includes(u.method.toUpperCase())||i&&!i.some(y=>u.path.startsWith(y)))return d();const p=n(u),m=await a.get(p);if(m)return u.responseHeaders=u.responseHeaders||{},u.responseHeaders["X-Cache"]="HIT",u.responseHeaders["X-Cache-Age"]=String(Math.floor((Date.now()-m.createdAt)/1e3)),u.metadata.cachedResponse=m.data,m.data;const f=await d();let g=t;for(const[y,v]of Object.entries(c))if(u.path.startsWith(y)){g=v;break}return await a.set(p,{data:f,createdAt:Date.now(),ttlMs:g}),u.responseHeaders=u.responseHeaders||{},u.responseHeaders["X-Cache"]="MISS",u.responseHeaders["Cache-Control"]=`max-age=${Math.floor(g/1e3)}`,f}}}function YEn(e){const t=[e.method,e.path],r=Object.keys(e.query).sort();if(r.length>0){const n=r.map(o=>`${o}=${e.query[o]}`).join("&");t.push(n)}return t.join(":")}function ZEn(e){return{invalidate:async t=>{await e.delete(t)},clear:async()=>{await e.clear()}}}Xn(),tr(),vr(),G();function QEn(){return{name:"timing",order:0,handler:async(e,t)=>ze.middleware.startActiveSpan("neurolink.middleware.timing",async r=>{try{const n=Date.now(),o=process.hrtime.bigint();e.metadata.requestStartTime=n;const i=Ce.createSpan("server.request","server.middleware.timing",{"server.operation":"middleware","server.middleware":"timing"});try{const s=await t(),a=process.hrtime.bigint(),c=Number(a-o)/1e6;e.responseHeaders=e.responseHeaders||{},e.responseHeaders["X-Response-Time"]=`${c.toFixed(2)}ms`,e.responseHeaders["Server-Timing"]=`total;dur=${c.toFixed(2)}`,i.durationMs=Date.now()-n;const u=Ce.endSpan(i,1);return rt().recordSpan(u),s}catch(s){r.recordException(s instanceof Error?s:new Error(String(s))),r.setStatus({code:Be.ERROR,message:s instanceof Error?s.message:String(s)}),i.durationMs=Date.now()-n;const a=Ce.endSpan(i,2);throw a.statusMessage=s instanceof Error?s.message:String(s),rt().recordSpan(a),s}}finally{r.end()}})}}function eSn(e){const{headerName:t="x-request-id",prefix:r="req",generator:n=()=>`${r}-${Date.now()}-${Math.random().toString(36).substring(2,11)}`}=e??{};return{name:"request-id",order:0,handler:async(o,i)=>(o.requestId=o.headers[t.toLowerCase()]||o.requestId||n(),o.responseHeaders=o.responseHeaders||{},o.responseHeaders["X-Request-ID"]=o.requestId,i())}}function tSn(e){const{includeStack:t=!1,onError:r,logErrors:n=!0}=e??{};return{name:"error-handling",order:1,handler:async(o,i)=>{const s=Ce.createSpan("server.request","server.middleware.errorHandling",{"server.operation":"middleware","server.middleware":"error-handling"}),a=Date.now();try{const l=await i();s.durationMs=Date.now()-a;const c=Ce.endSpan(s,1);return rt().recordSpan(c),l}catch(l){const c=l;n&&h.error("[ErrorMiddleware]",{requestId:o.requestId,error:c.message,stack:c.stack}),s.durationMs=Date.now()-a;const u=Ce.endSpan(s,2);if(u.statusMessage=c.message,rt().recordSpan(u),r)return r(c,o);const d=c.statusCode||500,p={error:{code:c.code||`HTTP_${d}`,message:d===500?"Internal server error":c.message},metadata:{requestId:o.requestId,timestamp:new Date().toISOString()}};throw t&&c.stack&&(p.error.stack=c.stack),o.metadata.errorResponse=p,o.metadata.errorStatusCode=d,l}}}}function rSn(e){const{contentSecurityPolicy:t,frameOptions:r="DENY",contentTypeOptions:n="nosniff",hstsMaxAge:o=31536e3,referrerPolicy:i="strict-origin-when-cross-origin",customHeaders:s={}}=e??{},a={};return t&&(a["Content-Security-Policy"]=t),r&&(a["X-Frame-Options"]=r),n&&(a["X-Content-Type-Options"]=n),o!==!1&&(a["Strict-Transport-Security"]=`max-age=${o}; includeSubDomains`),i&&(a["Referrer-Policy"]=i),a["X-XSS-Protection"]="1; mode=block",Object.assign(a,s),{name:"security-headers",order:2,handler:async(l,c)=>(l.responseHeaders=l.responseHeaders||{},Object.assign(l.responseHeaders,a),c())}}function nSn(e){const{logBody:t=!1,logResponse:r=!1,logger:n=console,skipPaths:o=["/health","/ready","/metrics"]}=e??{};return{name:"logging",order:3,excludePaths:o,handler:async(i,s)=>{const a=Date.now(),l={requestId:i.requestId,method:i.method,path:i.path,query:Object.keys(i.query).length>0?i.query:void 0};t&&i.body&&(l.body=i.body),n.info(`[Request] ${i.method} ${i.path}`,l);try{const c=await s(),u=Date.now()-a,d={requestId:i.requestId,duration:`${u}ms`,status:200};return r&&c&&(d.response=c),n.info(`[Response] ${i.method} ${i.path}`,d),c}catch(c){const u=Date.now()-a,d=c;throw n.error(`[Error] ${i.method} ${i.path}`,{requestId:i.requestId,duration:`${u}ms`,error:d.message,status:d.statusCode||500}),c}}}}function oSn(e){const{threshold:t=1024,contentTypes:r=["text/","application/json","application/javascript","application/xml"]}=e??{};return{name:"compression",order:5,handler:async(n,o)=>(n.metadata.compression={enabled:!0,threshold:t,contentTypes:r,acceptEncoding:n.headers["accept-encoding"]||""},o())}}du();var Lkr=class{store=new Map;cleanupInterval;constructor(){this.cleanupInterval=setInterval(()=>this.cleanup(),6e4)}async get(e){const t=this.store.get(e);if(t){if(Date.now()>t.resetAt){this.store.delete(e);return}return t}}async set(e,t){this.store.set(e,t)}async increment(e,t){const r=Date.now();let n=this.store.get(e);return(!n||r>n.resetAt)&&(n={count:0,resetAt:r+t},this.store.set(e,n)),n.count++,{count:n.count,resetAt:n.resetAt}}async reset(e){this.store.delete(e)}cleanup(){const e=Date.now();for(const[t,r]of this.store.entries())e>r.resetAt&&this.store.delete(t)}destroy(){this.cleanupInterval&&clearInterval(this.cleanupInterval),this.store.clear()}};function iSn(e){const{maxRequests:t,windowMs:r,message:n="Too many requests, please try again later",skipPaths:o=[],keyGenerator:i=Fkr,onRateLimitExceeded:s,store:a=new Lkr}=e;return{name:"rate-limit",order:5,excludePaths:o,handler:async(l,c)=>{const u=i(l),{count:d,resetAt:p}=await a.increment(u,r);if(l.responseHeaders=l.responseHeaders||{},l.responseHeaders["X-RateLimit-Limit"]=String(t),l.responseHeaders["X-RateLimit-Remaining"]=String(Math.max(0,t-d)),l.responseHeaders["X-RateLimit-Reset"]=String(Math.ceil(p/1e3)),d>t){const m=Math.ceil((p-Date.now())/1e3);if(l.responseHeaders["Retry-After"]=String(Math.max(0,m)),s)return s(l,m);throw new J$(m*1e3,n,l.requestId)}return c()}}}function Fkr(e){return e.headers["x-forwarded-for"]?.split(",")[0].trim()||e.headers["x-real-ip"]||"unknown"}function sSn(e){const{maxRequests:t,windowMs:r,message:n="Too many requests, please try again later",skipPaths:o=[],keyGenerator:i=Fkr,onRateLimitExceeded:s,subWindows:a=10}=e,l=new Map,c=r/a;return setInterval(()=>{const u=Date.now();for(const[d,p]of l.entries()){const m=p.filter(f=>u-f<r);m.length===0?l.delete(d):l.set(d,m)}},c),{name:"sliding-window-rate-limit",order:5,excludePaths:o,handler:async(u,d)=>{const p=i(u),m=Date.now();let f=l.get(p)||[];f=f.filter(y=>m-y<r);const g=f.length;if(u.responseHeaders=u.responseHeaders||{},u.responseHeaders["X-RateLimit-Limit"]=String(t),u.responseHeaders["X-RateLimit-Remaining"]=String(Math.max(0,t-g-1)),u.responseHeaders["X-RateLimit-Reset"]=String(Math.ceil((m+r)/1e3)),g>=t){const y=f[0]||m,v=Math.ceil((y+r-m)/1e3);if(u.responseHeaders["Retry-After"]=String(Math.max(0,v)),s)return s(u,v);throw new J$(v*1e3,n,u.requestId)}return f.push(m),l.set(p,f),d()}}}du(),du();function aSn(e){const{bodySchema:t,querySchema:r,paramsSchema:n,headersSchema:o,customValidator:i,skipPaths:s=[],errorFormatter:a=cSn}=e;return{name:"request-validation",order:15,excludePaths:s,handler:async(l,c)=>{const u=[];if(t&&l.body){const d=F6(l.body,t,"body");u.push(...d)}if(r){const d=F6(l.query,r,"query");u.push(...d)}if(n){const d=F6(l.params,n,"params");u.push(...d)}if(o){const d=F6(l.headers,o,"headers");u.push(...d)}if(i)try{await i(l)}catch(d){d instanceof Wy?u.push(...d.errors):u.push({field:"custom",message:d instanceof Error?d.message:String(d)})}if(u.length>0){const d=a(u.map(m=>new Wy([m],l.requestId))),p=new Wy(u,l.requestId);throw p.response=d,p}return c()}}}function F6(e,t,r){const n=[];if(t.required)for(const o of t.required)(!(o in e)||e[o]===void 0||e[o]===null)&&n.push({field:`${r}.${o}`,message:`${o} is required`});if(t.additionalProperties===!1&&t.properties){const o=new Set(Object.keys(t.properties));for(const i of Object.keys(e))o.has(i)||n.push({field:`${r}.${i}`,message:`Unknown property: ${i}`})}if(t.properties)for(const[o,i]of Object.entries(t.properties)){const s=e[o];if(s===void 0)continue;const a=$kr(s,i,`${r}.${o}`);n.push(...a)}return n}function $kr(e,t,r){const n=[],o=lSn(e);if(o!==t.type)return n.push({field:r,message:`Expected ${t.type}, got ${o}`}),n;if(t.type==="number"&&typeof e=="number"&&(t.minimum!==void 0&&e<t.minimum&&n.push({field:r,message:`Value must be at least ${t.minimum}`}),t.maximum!==void 0&&e>t.maximum&&n.push({field:r,message:`Value must be at most ${t.maximum}`})),t.type==="string"&&typeof e=="string"){const i=t.minLength??t.minimum,s=t.maxLength??t.maximum;i!==void 0&&e.length<i&&n.push({field:r,message:`String must be at least ${i} characters`}),s!==void 0&&e.length>s&&n.push({field:r,message:`String must be at most ${s} characters`}),t.pattern&&!new RegExp(t.pattern).test(e)&&n.push({field:r,message:`String does not match pattern: ${t.pattern}`})}if(t.type==="array"&&Array.isArray(e)){const i=t.minItems??t.minimum,s=t.maxItems??t.maximum;i!==void 0&&e.length<i&&n.push({field:r,message:`Array must have at least ${i} items`}),s!==void 0&&e.length>s&&n.push({field:r,message:`Array must have at most ${s} items`})}if(t.enum&&!t.enum.includes(e)&&n.push({field:r,message:`Value must be one of: ${t.enum.join(", ")}`}),t.validate){const i=t.validate(e);i!==!0&&n.push({field:r,message:typeof i=="string"?i:"Custom validation failed"})}return n}function lSn(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function cSn(e){return{error:{code:"VALIDATION_ERROR",message:"Request validation failed",details:e.flatMap(t=>t.errors)}}}function uSn(e,t){return r=>{const n=$kr(r,t,e);if(n.length>0)throw new Wy(n)}}yer();var dSn={type:"object",required:["error"],properties:{error:{type:"object",required:["code","message"],properties:{code:{type:"string",description:"Error code identifier",example:"VALIDATION_ERROR"},message:{type:"string",description:"Human-readable error message",example:"Invalid request body"},details:{type:"object",description:"Additional error details",additionalProperties:!0}}},metadata:{type:"object",properties:{timestamp:{type:"string",format:"date-time",description:"Error timestamp"},requestId:{type:"string",description:"Request identifier for tracing"}}}}},Ukr={type:"object",properties:{input:{type:"integer",description:"Number of input/prompt tokens",minimum:0},output:{type:"integer",description:"Number of output/completion tokens",minimum:0},total:{type:"integer",description:"Total tokens used",minimum:0},cacheCreationTokens:{type:"integer",description:"Tokens used for cache creation",minimum:0},cacheReadTokens:{type:"integer",description:"Tokens read from cache",minimum:0},reasoning:{type:"integer",description:"Tokens used for reasoning",minimum:0},cacheSavingsPercent:{type:"number",description:"Percentage of cache savings",minimum:0,maximum:100}}},Bkr={oneOf:[{type:"string",description:"Simple text input"},{type:"object",required:["text"],properties:{text:{type:"string",description:"Text content"},images:{type:"array",items:{type:"string"},description:"Array of image URLs or base64 data"},files:{type:"array",items:{type:"string"},description:"Array of file paths or URLs"}}}]},pSn={type:"object",required:["input"],properties:{input:Bkr,provider:{type:"string",description:"AI provider to use (e.g., openai, anthropic, google-ai)",example:"openai"},model:{type:"string",description:"Specific model to use",example:"gpt-4o"},systemPrompt:{type:"string",description:"System prompt to guide AI behavior"},temperature:{type:"number",minimum:0,maximum:2,description:"Sampling temperature (0-2)",default:.7},maxTokens:{type:"integer",minimum:1,description:"Maximum tokens to generate",default:1e3},tools:{type:"array",items:{type:"string"},description:"Tool names to enable for this request"},stream:{type:"boolean",description:"Enable streaming response",default:!1},sessionId:{type:"string",description:"Session ID for conversation memory"},userId:{type:"string",description:"User ID for context"}}},zkr={type:"object",required:["name","arguments"],properties:{name:{type:"string",description:"Tool name"},arguments:{type:"object",additionalProperties:!0,description:"Tool arguments"},result:{description:"Tool execution result"}}},mSn={type:"object",required:["content","provider","model"],properties:{content:{type:"string",description:"Generated text content"},provider:{type:"string",description:"Provider that handled the request"},model:{type:"string",description:"Model that generated the response"},usage:Ukr,toolCalls:{type:"array",items:zkr,description:"Tool calls made during generation"},finishReason:{type:"string",description:"Reason for completion",enum:["stop","length","tool_calls","content_filter"]},metadata:{type:"object",additionalProperties:!0,description:"Additional response metadata"}}},hSn={type:"object",required:["providers","total"],properties:{providers:{type:"array",items:{type:"string"},description:"List of available provider names"},total:{type:"integer",description:"Total number of providers"}}},Gkr={type:"object",properties:{type:{type:"string",description:"Parameter type"},description:{type:"string",description:"Parameter description"},required:{type:"boolean",description:"Whether parameter is required"},default:{description:"Default value"},enum:{type:"array",description:"Allowed values"}}},qkr={type:"object",required:["name"],properties:{name:{type:"string",description:"Tool name"},description:{type:"string",description:"Tool description"},source:{type:"string",description:"Tool source (builtin, external, custom)"},parameters:{type:"object",additionalProperties:Gkr,description:"Tool parameters schema"}}},fSn={type:"object",required:["tools","total"],properties:{tools:{type:"array",items:qkr,description:"List of available tools"},total:{type:"integer",description:"Total number of tools"}}},gSn={type:"object",required:["name"],properties:{name:{type:"string",description:"Tool name to execute"},arguments:{type:"object",additionalProperties:!0,description:"Tool arguments",default:{}},sessionId:{type:"string",description:"Session context"},userId:{type:"string",description:"User context"}}},ySn={type:"object",required:["success","duration"],properties:{success:{type:"boolean",description:"Whether execution was successful"},data:{description:"Result data"},error:{type:"string",description:"Error message if failed"},duration:{type:"number",description:"Execution duration in milliseconds"},metadata:{type:"object",additionalProperties:!0,description:"Additional metadata"}}},vSn={type:"object",properties:{name:{type:"string",description:"Tool name"},description:{type:"string",description:"Tool description"}}},Vkr={type:"object",required:["serverId","name","status","toolCount"],properties:{serverId:{type:"string",description:"Server ID"},name:{type:"string",description:"Server name"},status:{type:"string",enum:["connected","disconnected","error","connecting"],description:"Connection status"},toolCount:{type:"integer",description:"Number of available tools"},lastHealthCheck:{type:"string",format:"date-time",description:"Last health check timestamp"},error:{type:"string",description:"Error message if in error state"}}},wSn={type:"object",required:["servers","total"],properties:{servers:{type:"array",items:Vkr,description:"List of MCP servers"},total:{type:"integer",description:"Total number of servers"}}},jkr={type:"object",required:["role","content"],properties:{role:{type:"string",enum:["user","assistant","system"],description:"Message role"},content:{type:"string",description:"Message content"},timestamp:{type:"string",format:"date-time",description:"Message timestamp"}}},TSn={type:"object",required:["sessionId"],properties:{sessionId:{type:"string",description:"Session identifier"},messages:{type:"array",items:jkr,description:"Conversation messages"},metadata:{type:"object",additionalProperties:!0,description:"Session metadata"},createdAt:{type:"string",format:"date-time",description:"Session creation time"},updatedAt:{type:"string",format:"date-time",description:"Last update time"}}},bSn={type:"object",required:["sessions","total"],properties:{sessions:{type:"array",items:{type:"object",properties:{sessionId:{type:"string"},messageCount:{type:"integer"},createdAt:{type:"string",format:"date-time"},updatedAt:{type:"string",format:"date-time"}}},description:"List of sessions"},total:{type:"integer",description:"Total number of sessions"}}},_Sn={type:"object",required:["status","timestamp","uptime","version"],properties:{status:{type:"string",enum:["ok","degraded","unhealthy"],description:"Health status"},timestamp:{type:"string",format:"date-time",description:"Check timestamp"},uptime:{type:"integer",description:"Server uptime in milliseconds"},version:{type:"string",description:"Server version"}}},ESn={type:"object",required:["ready","timestamp","services"],properties:{ready:{type:"boolean",description:"Overall readiness status"},timestamp:{type:"string",format:"date-time",description:"Check timestamp"},services:{type:"object",properties:{neurolink:{type:"boolean",description:"NeuroLink SDK status"},tools:{type:"boolean",description:"Tool registry status"},externalServers:{type:"boolean",description:"External MCP servers status"}},description:"Service status breakdown"}}},SSn={type:"object",required:["server","process","timestamp"],properties:{server:{type:"object",properties:{running:{type:"boolean"},uptime:{type:"integer"},routes:{type:"integer"},middlewares:{type:"integer"}}},process:{type:"object",properties:{memoryUsage:{type:"object",properties:{heapUsed:{type:"integer"},heapTotal:{type:"integer"},external:{type:"integer"},rss:{type:"integer"}}},cpuUsage:{type:"object",properties:{user:{type:"integer"},system:{type:"integer"}}},pid:{type:"integer"}}},timestamp:{type:"string",format:"date-time"}}},kSn={ErrorResponse:dSn,TokenUsage:Ukr,AgentInput:Bkr,AgentExecuteRequest:pSn,AgentExecuteResponse:mSn,ToolCall:zkr,ProviderInfo:hSn,ToolParameter:Gkr,ToolDefinition:qkr,ToolListResponse:fSn,ToolExecuteRequest:gSn,ToolExecuteResponse:ySn,MCPServerTool:vSn,MCPServerStatus:Vkr,MCPServersListResponse:wSn,ConversationMessage:jkr,Session:TSn,SessionsListResponse:bSn,HealthResponse:_Sn,ReadyResponse:ESn,MetricsResponse:SSn};function Hkr(e,t,r="application/json"){return{description:e,content:{[r]:{schema:{$ref:`#/components/schemas/${t}`}}}}}function Wb(e,t=400){return{description:e,content:{"application/json":{schema:{$ref:"#/components/schemas/ErrorResponse"}}}}}function xSn(e){return{description:e,content:{"text/event-stream":{schema:{type:"string",description:"Server-Sent Events stream"}}}}}var Kb={400:Wb("Bad Request - Invalid input"),401:Wb("Unauthorized - Authentication required"),403:Wb("Forbidden - Insufficient permissions"),404:Wb("Not Found - Resource does not exist"),429:Wb("Too Many Requests - Rate limit exceeded"),500:Wb("Internal Server Error")};function Jme(e,t,r={type:"string"}){return{name:e,in:"path",required:!0,description:t,schema:r}}function Xme(e,t,r={type:"string"},n=!1){return{name:e,in:"query",required:n,description:t,schema:r}}function Wkr(e,t,r=!1){return{name:e,in:"header",required:r,description:t,schema:{type:"string"}}}var Xs={sessionId:Jme("sessionId","Session identifier"),serverName:Jme("name","MCP server name"),toolName:Jme("name","Tool name"),limitQuery:Xme("limit","Maximum number of items to return",{type:"integer",minimum:1,maximum:100,default:25}),offsetQuery:Xme("offset","Number of items to skip",{type:"integer",minimum:0,default:0}),searchQuery:Xme("q","Search query string",{type:"string"}),requestIdHeader:Wkr("X-Request-ID","Unique request identifier for tracing"),authorizationHeader:Wkr("Authorization","Bearer token or API key",!0)};function Su(e,t,r,n,o){return{summary:e,description:t,tags:r,parameters:o??[],responses:{200:Hkr("Success",n),...Kb}}}function Kkr(e,t,r,n,o,i){return{summary:e,description:t,tags:r,parameters:i??[],requestBody:{required:!0,content:{"application/json":{schema:{$ref:`#/components/schemas/${n}`}}}},responses:{200:Hkr("Success",o),...Kb}}}function ASn(e,t,r,n,o){return{summary:e,description:t,tags:r,parameters:o??[],requestBody:{required:!0,content:{"application/json":{schema:{$ref:`#/components/schemas/${n}`}}}},responses:{200:xSn("Streaming response"),...Kb}}}function CSn(e,t,r,n){return{summary:e,description:t,tags:r,parameters:n,responses:{204:{description:"Successfully deleted"},...Kb}}}var ISn={type:"http",scheme:"bearer",bearerFormat:"JWT",description:"JWT Bearer token authentication"},RSn={type:"apiKey",in:"header",name:"X-API-Key",description:"API key authentication via header"},MSn=[{name:"agent",description:"Agent execution and streaming endpoints"},{name:"tools",description:"Tool discovery and execution endpoints"},{name:"mcp",description:"MCP server management endpoints"},{name:"memory",description:"Conversation memory and session management"},{name:"health",description:"Health check and metrics endpoints"},{name:"streaming",description:"Real-time streaming endpoints"}];function Jkr(e,t,r){const n={url:e,description:t};return r&&(n.variables=Object.entries(r).reduce((o,[i,s])=>(o[i]={default:s.default,description:s.description},o),{})),n}var PSn=[Jkr("http://localhost:3000","Local development server"),Jkr("{protocol}://{host}:{port}","Custom server",{protocol:{default:"http",description:"Protocol (http or https)"},host:{default:"localhost",description:"Server hostname"},port:{default:"3000",description:"Server port"}})];function OSn(e,t,r,n){const o={title:e,version:t,description:r};return n?.termsOfService&&(o.termsOfService=n.termsOfService),n?.contact&&(o.contact=n.contact),n?.license&&(o.license=n.license),o}var DSn=OSn("NeuroLink API","1.0.0",`
2300
+ \u2022 Custom schema: { parameters: { parse: (data) => { ... } } }`;throw new Error(i)}}if(t.metadata){if(typeof t.metadata!="object"||Array.isArray(t.metadata))throw new Error(`Tool '${e}' metadata must be an object. Received: ${typeof t.metadata}. Example: { category: "data", version: "1.0.0", author: "team@company.com" }`);if(t.metadata.version&&typeof t.metadata.version!="string")throw new Error(`Tool '${e}' metadata.version must be a string. Received: ${typeof t.metadata.version}. Example: "1.0.0", "2.1.3-beta"`);if(t.metadata.category&&typeof t.metadata.category!="string")throw new Error(`Tool '${e}' metadata.category must be a string. Received: ${typeof t.metadata.category}. Example: "data", "communication", "utility"`);if(t.metadata.tags&&!Array.isArray(t.metadata.tags))throw new Error(`Tool '${e}' metadata.tags must be an array of strings. Received: ${typeof t.metadata.tags}. Example: ["api", "external", "web"]`)}h.debug(`Tool '${e}' validation passed`,{nameLength:e.length,descriptionLength:t.description.length,hasParameters:!!t.parameters,hasMetadata:!!t.metadata})}Rer(),Ser(),wer(),ber(),Per(),yQt(),ut(),tt(),dl(),gh(),pl(),pl(),dJ(),Jm(),Jm(),_h(),_h(),Cp(),Cp(),Rg(),xf(),ext(),Sce(),qm(),Zle(),rce(),Z0r(),MQ(),tt(),ut(),ob();var dEn=class{config;neurolinkInstance=null;instanceId;constructor(e){this.config={...L8,...e},this.instanceId=`ImageGenService-${Date.now()}-${Math.random().toString(36).substring(2,11)}`}async getNeuroLink(){if(!this.neurolinkInstance){const{NeuroLink:e}=await au().then(()=>Fce);this.neurolinkInstance=new e({conversationMemory:{enabled:!1},enableOrchestration:!1})}return this.neurolinkInstance}async generate(e){const t=Date.now();if(!this.config.enabled)return{success:!1,error:"Image generation is disabled"};if(!e.prompt||e.prompt.trim().length===0)return{success:!1,error:"Prompt is required for image generation"};try{const r=await this.getNeuroLink();let n=e.prompt;e.style&&(n=`${e.style} style: ${n}`),e.negativePrompt&&(n=`${n}. Avoid: ${e.negativePrompt}`);const o={text:n};if(e.images?.length){const f=this.config.maxReferenceImages??5,g=e.images.slice(0,f);o.images=g.map(y=>Buffer.isBuffer(y)?y.toString("base64"):y)}if(e.pdfFiles?.length){const f=this.config.maxReferencePdfs??1;o.pdfFiles=e.pdfFiles.slice(0,f)}const i=e.provider??this.config.defaultProvider,s=e.model??this.config.defaultModel,a=e.region??this.config.defaultRegion,l={input:o,provider:i,model:s,disableTools:!0,temperature:e.temperature??this.config.defaultTemperature??.75,timeout:this.config.timeout};a&&(l.region=a);const c=this.config.maxImages??4,u=Math.min(e.numberOfImages??1,c);l.numberOfImages=u,e.aspectRatio&&(l.aspectRatio=e.aspectRatio);const d=await Ue(r.generate(l),this.config.timeout,new Error(`Image generation timed out after ${this.config.timeout}ms`)),p=this.extractImageFromResult(d),m=Date.now()-t;return p?{success:!0,imageBuffer:p.imageBuffer,base64:p.base64,mimeType:p.mimeType,model:s,provider:i,generationTimeMs:m}:{success:!1,error:"No image generated",model:s,provider:i,generationTimeMs:m}}catch(r){return{success:!1,error:`Generation failed: ${r instanceof Error?r.message:String(r)}`,generationTimeMs:Date.now()-t}}}extractImageFromResult(e){if(!e||typeof e!="object")return null;const t=e,r=t.imageOutput??t.images?.[0];if(r&&typeof r=="object"){const o=r;if(typeof o.base64=="string"){const i=o.base64,s=Buffer.from(i,"base64"),a=typeof o.mimeType=="string"?o.mimeType:QC(s);return{imageBuffer:s,base64:i,mimeType:a}}}if(Buffer.isBuffer(r)){const o=r.toString("base64");return{imageBuffer:r,base64:o,mimeType:QC(r)}}const n=t.content;if(typeof n=="string"&&n.startsWith("data:image")){const o=n.match(/^data:image\/(\w+);base64,(.+)$/);if(o?.[2]){const i=`image/${o[1]}`,s=o[2];return{imageBuffer:Buffer.from(s,"base64"),base64:s,mimeType:i}}}if(typeof n=="string"&&!n.startsWith("data:"))try{const o=Buffer.from(n,"base64"),i=ZC(o);if(i!==null)return{imageBuffer:o,base64:n,mimeType:i}}catch{}return null}isEnabled(){return this.config.enabled}getModel(){return this.config.defaultModel}getProvider(){return this.config.defaultProvider}getConfig(){return{...this.config}}getInstanceId(){return this.instanceId}updateConfig(e){this.config={...this.config,...e}}enable(){this.config.enabled=!0}disable(){this.config.enabled=!1}};ob(),qHt(),b1(),await au();function pEn(){const e=process.env.LANGFUSE_ENABLED?.trim().toLowerCase()==="true",t=process.env.LANGFUSE_PUBLIC_KEY?.trim(),r=process.env.LANGFUSE_SECRET_KEY?.trim();if(!(!e||!t||!r))return{langfuse:{enabled:e,publicKey:t,secretKey:r,baseUrl:process.env.LANGFUSE_BASE_URL?.trim()||"https://cloud.langfuse.com",environment:process.env.LANGFUSE_ENVIRONMENT?.trim()||process.env.PUBLIC_APP_ENVIRONMENT?.trim()||"dev",release:process.env.PUBLIC_APP_VERSION?.trim()||process.env.npm_package_version?.trim()||"v1.0.0"}}}Im(),ul(),nYe(),aot(),uot(),Xl(),ejr(),tjr(),eK(),fYe(),eet(),ut(),v2(),tt(),G(),uQt(),mWt(),cWt(),lWt(),Kte(),fne(),DYt(),cne(),ace(),bur(),Ut(),G(),qr(),nce();function Hb(e){return{jsonrpc:"2.0",id:it(),method:"elicitation/request",params:{type:e.type,message:e.message,toolName:e.toolName,serverId:e.serverId,timeout:e.timeout,optional:e.optional,defaultValue:e.defaultValue,options:e.options??{}}}}function xkr(e,t){return{jsonrpc:"2.0",id:it(),method:"elicitation/response",params:{requestId:e,responded:t.responded,value:t.value,cancelled:t.cancelled,timedOut:t.timedOut,error:t.error}}}function mEn(e,t){return{jsonrpc:"2.0",id:it(),method:"elicitation/cancel",params:{requestId:e,reason:t}}}function hEn(e){if(typeof e!="object"||e===null)return!1;const t=e;return t.jsonrpc==="2.0"&&typeof t.id=="string"&&(t.method==="elicitation/request"||t.method==="elicitation/response"||t.method==="elicitation/cancel")&&typeof t.params=="object"&&t.params!==null}function jme(e){const{type:t,message:r,toolName:n,serverId:o,timeout:i,optional:s,defaultValue:a,options:l}=e.params,c={id:e.id,type:t,message:r,toolName:n,serverId:o,timeout:i,optional:s,defaultValue:a};switch(t){case"confirmation":return{...c,type:"confirmation",confirmLabel:l?.confirmLabel,cancelLabel:l?.cancelLabel};case"text":return{...c,type:"text",placeholder:l?.placeholder,minLength:l?.minLength,maxLength:l?.maxLength,pattern:l?.pattern,multiline:l?.multiline};case"select":return{...c,type:"select",options:l?.options??[]};case"multiselect":return{...c,type:"multiselect",options:l?.options??[],minSelections:l?.minSelections,maxSelections:l?.maxSelections};case"form":return{...c,type:"form",fields:l?.fields??[],submitLabel:l?.submitLabel};case"file":return{...c,type:"file",accept:l?.accept,multiple:l?.multiple,maxSize:l?.maxSize};case"secret":return{...c,type:"secret",hint:l?.hint};default:return c}}function Akr(e){return xkr(e.requestId,{responded:e.responded,value:e.value,cancelled:e.cancelled,timedOut:e.timedOut,error:e.error})}var Ckr=class{manager;config;constructor(e={}){this.manager=e.manager??MF,this.config={manager:this.manager,defaultTimeout:e.defaultTimeout??6e4,enableLogging:e.enableLogging??!1,customHandler:e.customHandler}}async handleMessage(e){if(this.config.enableLogging&&h.info("[ElicitationProtocol] Received:",e.method),this.config.customHandler)return await At(this.config.customHandler(e),this.config.defaultTimeout,`[ElicitationProtocol] Custom handler timed out after ${this.config.defaultTimeout}ms`);switch(e.method){case"elicitation/request":return this.handleRequest(e);case"elicitation/response":return this.handleResponse(e);case"elicitation/cancel":return this.handleCancel(e);default:this.config.enableLogging&&h.warn(`[ElicitationProtocol] Unhandled method: ${e.method}`);return}}async handleRequest(e){const t=jme(e),r=await this.manager.request({...t,timeout:t.timeout??this.config.defaultTimeout});return Akr(r)}async handleResponse(e){this.config.enableLogging&&h.info("[ElicitationProtocol] Response received (no action needed)")}async handleCancel(e){this.manager.cancel(e.params.requestId,e.params.reason)}async requestElicitation(e){const t=Hb(e),r=jme(t);return this.manager.request({...r,timeout:r.timeout??this.config.defaultTimeout})}cancelElicitation(e,t){this.manager.cancel(e,t)}getManager(){return this.manager}setHandler(e){this.manager.setHandler(e)}setEnabled(e){this.manager.setEnabled(e)}isEnabled(){return this.manager.isEnabled()}};function fEn(e,t){const r={};return t.confirmLabel!==void 0&&(r.confirmLabel=t.confirmLabel),t.cancelLabel!==void 0&&(r.cancelLabel=t.cancelLabel),Hb({type:"confirmation",message:e,toolName:t.toolName,serverId:t.serverId,timeout:t.timeout,options:r})}function gEn(e,t){const r={};return t.placeholder!==void 0&&(r.placeholder=t.placeholder),t.minLength!==void 0&&(r.minLength=t.minLength),t.maxLength!==void 0&&(r.maxLength=t.maxLength),t.pattern!==void 0&&(r.pattern=t.pattern),t.multiline!==void 0&&(r.multiline=t.multiline),Hb({type:"text",message:e,toolName:t.toolName,serverId:t.serverId,defaultValue:t.defaultValue,timeout:t.timeout,options:r})}function yEn(e,t,r){return Hb({type:"select",message:e,toolName:r.toolName,serverId:r.serverId,defaultValue:r.defaultValue,timeout:r.timeout,options:{options:t}})}function vEn(e,t,r){const n={fields:t};return r.submitLabel!==void 0&&(n.submitLabel=r.submitLabel),Hb({type:"form",message:e,toolName:r.toolName,serverId:r.serverId,timeout:r.timeout,options:n})}var wEn=new Ckr;jte(),kur(),Yn(),qr(),tt();var TEn=class extends fn{config;tools=new Map;isInitialized=!1;isRunning=!1;constructor(e){super(),this.config={id:e.id,name:e.name,description:e.description??"",version:e.version??"1.0.0",category:e.category??"custom",transport:e.transport??"stdio",metadata:e.metadata??{},defaultTimeoutMs:e.defaultTimeoutMs??3e4,defaultAnnotations:e.defaultAnnotations??{}}}async init(){this.isInitialized||(await this.onInit(),this.isInitialized=!0,this.emit("serverReady",{tools:Array.from(this.tools.keys())}))}async onInit(){}async start(){this.isInitialized||await this.init(),!this.isRunning&&(await this.onStart(),this.isRunning=!0)}async onStart(){}async stop(e){this.isRunning&&(await this.onStop(),this.isRunning=!1,this.emit("serverStopped",{reason:e}))}async onStop(){}registerTool(e){this.validateTool(e);const t={...e,annotations:{...this.config.defaultAnnotations,...e.annotations}};return this.tools.set(e.name,t),this.emit("toolRegistered",{toolName:e.name,tool:t}),this}registerTools(e){for(const t of e)this.registerTool(t);return this}validateTool(e){if(!e.name||typeof e.name!="string")throw he.invalidConfiguration("tool.name","Tool name is required and must be a string");if(e.name.length>64)throw he.invalidConfiguration("tool.name","Tool name must be 64 characters or less",{toolName:e.name});if(!/^[a-zA-Z_][a-zA-Z0-9_-]*$/.test(e.name))throw he.invalidConfiguration("tool.name","Tool name must start with a letter or underscore and contain only alphanumeric characters, underscores, and hyphens",{toolName:e.name});if(!e.description||typeof e.description!="string")throw he.invalidConfiguration("tool.description","Tool description is required and must be a string",{toolName:e.name});if(typeof e.execute!="function")throw he.invalidConfiguration("tool.execute","Tool execute function is required",{toolName:e.name});if(this.tools.has(e.name))throw he.invalidConfiguration("tool.name",`Tool '${e.name}' is already registered`,{toolName:e.name})}async executeTool(e,t,r){const n=this.tools.get(e);if(!n)return{success:!1,error:`Tool '${e}' not found on server '${this.config.id}'`,metadata:{toolName:e,serverId:this.config.id}};const o=Date.now(),i=this.config.defaultTimeoutMs??3e4;try{const s=await At(n.execute(t,r??{}),i,he.toolTimeout(e,i).message),a=Date.now()-o;return this.emit("toolExecuted",{toolName:e,duration:a,success:!0}),this.isToolResult(s)?{...s,metadata:{...s.metadata,toolName:e,serverId:this.config.id,executionTime:a}}:{success:!0,data:s,metadata:{toolName:e,serverId:this.config.id,executionTime:a}}}catch(s){const a=Date.now()-o;return this.emit("toolError",{toolName:e,error:s instanceof Error?s:new Error(String(s))}),this.emit("toolExecuted",{toolName:e,duration:a,success:!1}),{success:!1,error:s instanceof Error?s.message:String(s),metadata:{toolName:e,serverId:this.config.id,executionTime:a}}}}isToolResult(e){return e!==null&&typeof e=="object"&&"success"in e&&typeof e.success=="boolean"}getTools(){return Array.from(this.tools.values())}getTool(e){return this.tools.get(e)}hasTool(e){return this.tools.has(e)}removeTool(e){return this.tools.delete(e)}toServerInfo(){return{id:this.config.id,name:this.config.name,description:this.config.description,transport:this.config.transport,status:this.isRunning?"connected":"stopped",tools:this.getTools().map(e=>({name:e.name,description:e.description,inputSchema:e.inputSchema,execute:(t,r)=>this.executeTool(e.name,t,r)})),metadata:{...this.config.metadata,category:this.config.category,version:this.config.version}}}getToolsByAnnotation(e,t){return this.getTools().filter(r=>{const n=r.annotations?.[e];return Array.isArray(t)&&Array.isArray(n)?t.some(o=>n.includes(o)):n===t})}getReadOnlyTools(){return this.getToolsByAnnotation("readOnlyHint",!0)}getDestructiveTools(){return this.getToolsByAnnotation("destructiveHint",!0)}getIdempotentTools(){return this.getToolsByAnnotation("idempotentHint",!0)}getToolsRequiringConfirmation(){return this.getToolsByAnnotation("requiresConfirmation",!0)}get id(){return this.config.id}get name(){return this.config.name}get description(){return this.config.description}get version(){return this.config.version}get category(){return this.config.category}get initialized(){return this.isInitialized}get running(){return this.isRunning}};Vte(),Yn(),G(),tt(),qr();var bEn=class extends fn{config;resources=new Map;prompts=new Map;subscriptions=new Map;resourceTemplates=new Map;constructor(e={}){super(),this.config={resources:e.resources??!0,prompts:e.prompts??!0,resourceSubscriptions:e.resourceSubscriptions??!0}}registerResource(e){if(!this.config.resources)throw he.invalidConfiguration("resources","Resource support is not enabled");return this.validateResourceUri(e.uri),this.resources.set(e.uri,e),this.emit("resourceRegistered",{uri:e.uri,name:e.name,timestamp:new Date}),h.debug(`[ServerCapabilities] Registered resource: ${e.uri}`),this}registerResourceTemplate(e,t){if(!this.config.resources)throw he.invalidConfiguration("resources","Resource support is not enabled");return this.resourceTemplates.set(e,{...t,uri:t.uriPattern}),this.emit("resourceTemplateRegistered",{pattern:e,timestamp:new Date}),this}unregisterResource(e){const t=this.resources.delete(e);return t&&(this.subscriptions.delete(e),this.emit("resourceUnregistered",{uri:e,timestamp:new Date})),t}listResources(){return Array.from(this.resources.values()).map(e=>({uri:e.uri,name:e.name,description:e.description,mimeType:e.mimeType,size:e.size,dynamic:e.dynamic,annotations:e.annotations}))}async readResource(e,t){let r=this.resources.get(e);if(r||(r=this.findResourceTemplate(e)),!r)throw he.invalidConfiguration("resource",`Resource not found: ${e}`);const n=Date.now(),o=3e4;try{const i=await At(r.reader(e,t),o,`Resource read timed out after ${o}ms for URI: ${e}`),s=Date.now()-n;return this.emit("resourceRead",{uri:e,duration:s,success:!0,timestamp:new Date}),i}catch(i){const s=Date.now()-n;throw this.emit("resourceRead",{uri:e,duration:s,success:!1,error:i instanceof Error?i.message:String(i),timestamp:new Date}),i}}subscribeToResource(e,t){if(!this.config.resourceSubscriptions)throw he.invalidConfiguration("resourceSubscriptions","Resource subscriptions are not enabled");this.subscriptions.has(e)||this.subscriptions.set(e,new Set);const r=this.subscriptions.get(e);return r&&r.add(t),this.emit("resourceSubscribed",{uri:e,timestamp:new Date}),()=>{const n=this.subscriptions.get(e);n&&(n.delete(t),n.size===0&&this.subscriptions.delete(e)),this.emit("resourceUnsubscribed",{uri:e,timestamp:new Date})}}async notifyResourceChanged(e){const t=this.subscriptions.get(e);if(!(!t||t.size===0))try{const r=await this.readResource(e);for(const n of t)try{const o=n(e,r);o&&typeof o.catch=="function"&&o.catch(i=>{h.error(`[ServerCapabilities] Async error notifying subscriber for ${e}:`,i)})}catch(o){h.error(`[ServerCapabilities] Error notifying subscriber for ${e}:`,o)}this.emit("resourceChanged",{uri:e,subscriberCount:t.size,timestamp:new Date})}catch(r){h.error(`[ServerCapabilities] Error reading resource for notification: ${e}`,r)}}getResource(e){return this.resources.get(e)??this.findResourceTemplate(e)}validateResourceUri(e){try{new URL(e)}catch{h.warn(`[ServerCapabilities] Resource URI is not a valid URL: ${e}`)}}findResourceTemplate(e){for(const[t,r]of this.resourceTemplates)if(this.matchesPattern(e,t))return{...r,uri:e}}matchesPattern(e,t){if(t.length>200)return!1;const r=t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".").replace(/\\\{[^}]*\\\}/g,"[^/]+");try{return new RegExp(`^${r}$`).test(e)}catch{return!1}}registerPrompt(e){if(!this.config.prompts)throw he.invalidConfiguration("prompts","Prompt support is not enabled");return this.validatePromptName(e.name),this.prompts.set(e.name,e),this.emit("promptRegistered",{name:e.name,timestamp:new Date}),h.debug(`[ServerCapabilities] Registered prompt: ${e.name}`),this}unregisterPrompt(e){const t=this.prompts.delete(e);return t&&this.emit("promptUnregistered",{name:e,timestamp:new Date}),t}listPrompts(){return Array.from(this.prompts.values()).map(e=>({name:e.name,description:e.description,arguments:e.arguments}))}async getPrompt(e,t={},r){const n=this.prompts.get(e);if(!n)throw he.invalidConfiguration("prompt",`Prompt not found: ${e}`);for(const s of n.arguments??[])if(s.required&&t[s.name]===void 0)throw he.invalidConfiguration("promptArgument",`Missing required argument: ${s.name}`);const o=Date.now(),i=3e4;try{const s=await At(n.generator(t,r),i,`Prompt generation timed out after ${i}ms for prompt: ${e}`),a=Date.now()-o;return this.emit("promptGenerated",{name:e,duration:a,success:!0,messageCount:s.messages.length,timestamp:new Date}),s}catch(s){const a=Date.now()-o;throw this.emit("promptGenerated",{name:e,duration:a,success:!1,error:s instanceof Error?s.message:String(s),timestamp:new Date}),s}}getPromptDefinition(e){return this.prompts.get(e)}validatePromptName(e){if(!e||typeof e!="string")throw he.invalidConfiguration("promptName","Prompt name is required and must be a string");if(!/^[a-zA-Z_][a-zA-Z0-9_-]*$/.test(e))throw he.invalidConfiguration("promptName","Prompt name must start with a letter or underscore and contain only alphanumeric characters, underscores, and hyphens");if(this.prompts.has(e))throw he.invalidConfiguration("promptName",`Prompt '${e}' is already registered`)}getCapabilities(){const e={};return this.config.resources&&(e.resources={subscribe:this.config.resourceSubscriptions,listChanged:!0}),this.config.prompts&&(e.prompts={listChanged:!0}),e}getStatistics(){let e=0;for(const t of this.subscriptions.values())e+=t.size;return{resourceCount:this.resources.size,templateCount:this.resourceTemplates.size,promptCount:this.prompts.size,subscriptionCount:e}}clear(){this.resources.clear(),this.resourceTemplates.clear(),this.prompts.clear(),this.subscriptions.clear(),this.emit("cleared",{timestamp:new Date})}};function _En(e,t,r,n){return{uri:e,name:t,description:n?.description,mimeType:"text/plain",dynamic:n?.dynamic??typeof r=="function",reader:async o=>({uri:o,mimeType:"text/plain",text:typeof r=="function"?await r():r})}}function EEn(e,t,r,n){return{uri:e,name:t,description:n?.description,mimeType:"application/json",dynamic:n?.dynamic??typeof r=="function",reader:async o=>({uri:o,mimeType:"application/json",text:JSON.stringify(typeof r=="function"?await r():r,null,2)})}}function SEn(e,t,r){return{name:e,description:r?.description,arguments:r?.arguments,generator:async n=>{let o=t;for(const[i,s]of Object.entries(n)){const a=i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");o=o.replace(new RegExp(`\\{${a}\\}`,"g"),()=>String(s))}return{messages:[{role:"user",content:{type:"text",text:o}}]}}}}rA(),UF(),Pur(),HHt(),JHt(),sQt();async function kEn(){return Promise.resolve()}async function xEn(){return[]}async function AEn(e,t,r,n){throw he.invalidConfiguration("executeMCP","Direct legacy MCP execution is deprecated. Use the new module APIs (createMCPServer, MultiServerManager, ToolRouter, etc.) instead.")}async function CEn(){return{initialized:!1,pluginsDiscovered:0,pluginsBySource:{},availablePlugins:[]}}Sct(),G(),TL(),Qjt(),Kjt(),Fjt(),$K(),Usr(),nle();function IEn(e){const t=new Map;e.forEach(n=>{const o=`${n.provider}/${n.model}`,i=t.get(o)||{total:0,successful:0,totalTime:0};t.set(o,{total:i.total+1,successful:i.successful+(n.status==="success"?1:0),totalTime:i.totalTime+n.responseTime})});const r={};return t.forEach((n,o)=>{r[o]={successRate:n.successful/n.total,avgResponseTime:n.totalTime/n.total}}),r}function Hme(e){if(e.length===0)return{totalExecutions:0,averageScore:0,averageConfidence:0,averageExecutionTime:0,successRate:0,totalCost:0};const t=e.reduce((s,a)=>s+a.score,0),r=e.reduce((s,a)=>s+a.confidence,0),n=e.reduce((s,a)=>s+a.totalTime,0),o=e.reduce((s,a)=>s+(a.cost||0),0),i=e.filter(s=>s.score>0).length;return{totalExecutions:e.length,averageScore:t/e.length,averageConfidence:r/e.length,averageExecutionTime:n/e.length,successRate:i/e.length,totalCost:o}}function REn(e,t){const r=Hme(e),n=Hme(t),o=r.averageExecutionTime>0?1/r.averageExecutionTime*1e4*.2:0,i=n.averageExecutionTime>0?1/n.averageExecutionTime*1e4*.2:0,s=r.averageScore*.4+r.averageConfidence*100*.3+o+1/(r.totalCost+1)*100*.1,a=n.averageScore*.4+n.averageConfidence*100*.3+i+1/(n.totalCost+1)*100*.1,l=Math.abs(s-a);let c,u;return l<5?(c="tie",u="Workflows perform similarly overall"):s>a?(c="workflow1",u=`Workflow 1 scores higher (${s.toFixed(2)} vs ${a.toFixed(2)})`):(c="workflow2",u=`Workflow 2 scores higher (${a.toFixed(2)} vs ${s.toFixed(2)})`),{workflow1:r,workflow2:n,winner:c,reasoning:u}}yh(),G();var Ikr={id:"quality-max",name:"Quality-Max Adaptive",description:"Adaptive 3-tier execution optimizing for maximum quality",version:"1.0.0",type:"adaptive",models:[{provider:"openai",model:"gpt-4o"}],modelGroups:[{id:"validation-tier",name:"Validation Tier",description:"Fast models to assess complexity and confidence",models:[{provider:"openai",model:"gpt-4o-mini",label:"GPT-4o-mini",temperature:.7,timeout:1e4},{provider:"google-ai",model:"gemini-2.0-flash",label:"Gemini Flash",temperature:.7,timeout:1e4}],executionStrategy:"parallel",continueOnFailure:!0,minSuccessful:1,parallelism:2},{id:"premium-tier",name:"Premium Tier",description:"High-quality models for thorough analysis",models:[{provider:"openai",model:"gpt-4o",label:"GPT-4o",temperature:.7,systemPrompt:"Provide comprehensive, high-quality responses with deep analysis.",timeout:2e4},{provider:"anthropic",model:"claude-3-5-sonnet-20241022",label:"Claude 3.5 Sonnet",temperature:.7,systemPrompt:"Think deeply and provide nuanced, well-reasoned responses.",timeout:2e4}],executionStrategy:"parallel",continueOnFailure:!0,minSuccessful:1,parallelism:2},{id:"expert-tier",name:"Expert Tier",description:"Top-tier model for final quality assurance",models:[{provider:"anthropic",model:"claude-3-5-sonnet-20241022",label:"Claude 3.5 Sonnet Expert",temperature:.6,systemPrompt:"You are an expert. Provide the highest quality, most accurate response possible. Be thorough, precise, and authoritative.",timeout:3e4}],executionStrategy:"sequential",continueOnFailure:!1,minSuccessful:1}],judge:{provider:"openai",model:"gpt-4o",criteria:["quality","depth","accuracy","completeness"],outputFormat:"detailed",includeReasoning:!0,temperature:.1,scoreScale:{min:0,max:100},customPrompt:"Evaluate responses for maximum quality. Prioritize depth, accuracy, and completeness. Be rigorous in assessment."},execution:{timeout:7e4,minResponses:2,costThreshold:.12},tags:["adaptive","quality","tiered","escalation"],metadata:{useCase:"Quality-critical tasks with adaptive execution",recommendedFor:["complex analysis","expert consultation","high-stakes decisions","technical documentation"],averageCost:.08,averageLatency:4500},createdAt:ru},Rkr={id:"speed-first",name:"Speed-First Adaptive",description:"Fast execution with quality fallback",version:"1.0.0",type:"adaptive",models:[{provider:"openai",model:"gpt-4o-mini"}],modelGroups:[{id:"fast-tier",name:"Fast Tier",models:[{provider:"openai",model:"gpt-4o-mini",temperature:.7,timeout:5e3}],executionStrategy:"sequential",continueOnFailure:!0,minSuccessful:1},{id:"balanced-tier",name:"Balanced Tier",models:[{provider:"google-ai",model:"gemini-2.0-flash",temperature:.7,timeout:1e4}],executionStrategy:"sequential",continueOnFailure:!0,minSuccessful:1},{id:"quality-tier",name:"Quality Tier",models:[{provider:"openai",model:"gpt-4o",temperature:.7,timeout:15e3}],executionStrategy:"sequential",continueOnFailure:!1,minSuccessful:1}],judge:{provider:"openai",model:"gpt-4o-mini",criteria:["speed","quality"],outputFormat:"best",includeReasoning:!0,temperature:.1,scoreScale:{min:0,max:100}},execution:{timeout:35e3,minResponses:1,costThreshold:.05},tags:["adaptive","speed","fallback"],metadata:{useCase:"Speed-optimized with quality guarantee",recommendedFor:["real-time applications","quick queries"],averageCost:.01,averageLatency:1500},createdAt:ru},Mkr={id:"balanced-adaptive",name:"Balanced Adaptive",description:"Balanced 2-tier execution",version:"1.0.0",type:"adaptive",models:[{provider:"openai",model:"gpt-4o-mini"}],modelGroups:[{id:"standard-tier",name:"Standard Tier",description:"Fast, cost-effective models",models:[{provider:"openai",model:"gpt-4o-mini",temperature:.7},{provider:"google-ai",model:"gemini-2.0-flash",temperature:.7}],executionStrategy:"parallel",continueOnFailure:!0,minSuccessful:1,parallelism:2},{id:"premium-tier",name:"Premium Tier",description:"High-quality models for complex cases",models:[{provider:"openai",model:"gpt-4o",temperature:.7},{provider:"anthropic",model:"claude-3-5-sonnet-20241022",temperature:.7}],executionStrategy:"parallel",continueOnFailure:!1,minSuccessful:1,parallelism:2}],judge:{provider:"openai",model:"gpt-4o",criteria:["quality","accuracy","balance"],outputFormat:"detailed",includeReasoning:!0,temperature:.1,scoreScale:{min:0,max:100}},execution:{timeout:4e4,minResponses:2,costThreshold:.08},tags:["adaptive","balanced","tiered"],metadata:{useCase:"Balanced speed/quality/cost tradeoff",recommendedFor:["general purpose","production applications"],averageCost:.04,averageLatency:2500},createdAt:ru};function MEn(e,t){const r={speed:Rkr,balanced:Mkr,quality:Ikr},n=t==="balanced"?2:3;return e!==n&&h.warn(`[AdaptiveWorkflow] Requested ${e} tiers but ${t} strategy uses ${n} tiers`),{...r[t],id:`adaptive-${n}tier-${t}`,name:`Adaptive ${n}-Tier (${t})`,description:`${n}-tier adaptive execution optimized for ${t}`}}yh();var Pkr={id:"consensus-3",name:"Consensus-3 Ensemble",description:"3-model parallel ensemble with judge-based selection",version:"1.0.0",type:"ensemble",models:[{provider:"openai",model:"gpt-4o",label:"GPT-4o",weight:1,temperature:.7},{provider:"anthropic",model:"claude-3-5-sonnet-20241022",label:"Claude 3.5 Sonnet",weight:1,temperature:.7},{provider:"google-ai",model:"gemini-2.0-flash",label:"Gemini 2.0 Flash",weight:1,temperature:.7}],judge:{provider:"openai",model:"gpt-4o",criteria:["accuracy","clarity","completeness"],outputFormat:"detailed",includeReasoning:!0,temperature:.1,scoreScale:{min:0,max:100}},execution:{parallelism:3,timeout:3e4,modelTimeout:25e3,minResponses:2,costThreshold:.1},tags:["ensemble","consensus","balanced","multi-provider"],metadata:{useCase:"Balanced quality across providers",recommendedFor:["general queries","explanations","analysis"],averageCost:.02,averageLatency:2e3},createdAt:ru};function PEn(e){return{...Pkr,id:`consensus-3-custom-${Date.now()}`,defaultSystemPrompt:e}}var OEn={id:"consensus-3-fast",name:"Consensus-3 Fast",description:"3-model fast ensemble (lower cost)",version:"1.0.0",type:"ensemble",models:[{provider:"openai",model:"gpt-4o-mini",label:"GPT-4o-mini",weight:1,temperature:.7},{provider:"anthropic",model:"claude-3-haiku-20240307",label:"Claude 3 Haiku",weight:1,temperature:.7},{provider:"google-ai",model:"gemini-2.0-flash",label:"Gemini 2.0 Flash",weight:1,temperature:.7}],judge:{provider:"openai",model:"gpt-4o-mini",criteria:["accuracy","clarity"],outputFormat:"best",includeReasoning:!0,temperature:.1,scoreScale:{min:0,max:100}},execution:{parallelism:3,timeout:2e4,modelTimeout:15e3,minResponses:2,costThreshold:.02},tags:["ensemble","fast","low-cost","consensus"],metadata:{useCase:"Fast consensus for simple queries",recommendedFor:["quick questions","simple explanations"],averageCost:.01,averageLatency:1500},createdAt:ru};yh();var DEn={id:"fast-fallback",name:"Fast-Fallback Chain",description:"Sequential fallback: fast \u2192 mid \u2192 premium",version:"1.0.0",type:"chain",models:[{provider:"openai",model:"gpt-4o-mini"}],modelGroups:[{id:"fast-tier",name:"Fast Tier",description:"Try fast model first (lowest cost)",models:[{provider:"openai",model:"gpt-4o-mini",label:"GPT-4o-mini",temperature:.7,timeout:1e4}],executionStrategy:"sequential",continueOnFailure:!0,minSuccessful:1},{id:"mid-tier",name:"Mid Tier",description:"Mid-tier model (balanced cost/quality)",models:[{provider:"google-ai",model:"gemini-2.0-flash",label:"Gemini 2.0 Flash",temperature:.7,timeout:15e3}],executionStrategy:"sequential",continueOnFailure:!0,minSuccessful:1},{id:"premium-tier",name:"Premium Tier",description:"Premium models (last resort, highest quality)",models:[{provider:"openai",model:"gpt-4o",label:"GPT-4o",temperature:.7,timeout:2e4}],executionStrategy:"sequential",continueOnFailure:!1,minSuccessful:1}],judge:{provider:"openai",model:"gpt-4o-mini",criteria:["quality","response_time"],outputFormat:"best",includeReasoning:!0,temperature:.1,scoreScale:{min:0,max:100}},execution:{timeout:5e4,minResponses:1,costThreshold:.05},tags:["chain","fallback","cost-optimized","reliable"],metadata:{useCase:"Cost-optimized with quality guarantee",recommendedFor:["variable complexity queries","cost-sensitive applications"],averageCost:.01,averageLatency:2e3},createdAt:ru},NEn={id:"aggressive-fallback",name:"Aggressive Fallback",description:"Fast first, then both premium models in parallel",version:"1.0.0",type:"chain",models:[{provider:"openai",model:"gpt-4o-mini"}],modelGroups:[{id:"fast-tier",name:"Fast Tier",models:[{provider:"openai",model:"gpt-4o-mini",temperature:.7,timeout:8e3}],executionStrategy:"sequential",continueOnFailure:!0,minSuccessful:1},{id:"premium-tier",name:"Premium Tier (Both)",description:"Run both premium models in parallel for guaranteed quality",models:[{provider:"openai",model:"gpt-4o",label:"GPT-4o",temperature:.7},{provider:"anthropic",model:"claude-3-5-sonnet-20241022",label:"Claude 3.5 Sonnet",temperature:.7}],executionStrategy:"parallel",continueOnFailure:!1,minSuccessful:1,parallelism:2}],judge:{provider:"openai",model:"gpt-4o",criteria:["quality","completeness"],outputFormat:"detailed",includeReasoning:!0,temperature:.1,scoreScale:{min:0,max:100}},execution:{timeout:4e4,minResponses:1,costThreshold:.08},tags:["chain","fallback","high-quality","reliable"],metadata:{useCase:"High quality guarantee with cost optimization attempt",recommendedFor:["important queries","when quality matters most"],averageCost:.03,averageLatency:2500},createdAt:ru};yh();var LEn={id:"multi-judge-5",name:"Multi-Judge-5 Ensemble",description:"5-model ensemble with 3-judge voting for high confidence",version:"1.0.0",type:"ensemble",models:[{provider:"openai",model:"gpt-4o",label:"GPT-4o",weight:1,temperature:.7},{provider:"openai",model:"gpt-4o-mini",label:"GPT-4o-mini",weight:.8,temperature:.7},{provider:"anthropic",model:"claude-3-5-sonnet-20241022",label:"Claude 3.5 Sonnet",weight:1,temperature:.7},{provider:"anthropic",model:"claude-3-haiku-20240307",label:"Claude 3 Haiku",weight:.7,temperature:.7},{provider:"google-ai",model:"gemini-2.0-flash",label:"Gemini 2 Flash",weight:.9,temperature:.7}],judges:[{provider:"openai",model:"gpt-4o",criteria:["accuracy","clarity","factual_correctness"],outputFormat:"detailed",includeReasoning:!0,temperature:.1,scoreScale:{min:0,max:100},label:"Accuracy Judge"},{provider:"anthropic",model:"claude-3-5-sonnet-20241022",criteria:["reasoning_quality","depth","nuance"],outputFormat:"detailed",includeReasoning:!0,temperature:.1,scoreScale:{min:0,max:100},label:"Reasoning Judge"},{provider:"google-ai",model:"gemini-2.0-flash",criteria:["completeness","coherence","relevance"],outputFormat:"detailed",includeReasoning:!0,temperature:.1,scoreScale:{min:0,max:100},label:"Completeness Judge"}],execution:{parallelism:5,timeout:45e3,modelTimeout:3e4,minResponses:3,costThreshold:.15},tags:["ensemble","multi-judge","voting","high-confidence","critical"],metadata:{useCase:"Critical decisions requiring high confidence",recommendedFor:["important business decisions","technical evaluations","complex analysis","fact-checking"],averageCost:.1,averageLatency:5e3,consensusThreshold:.7},createdAt:ru},FEn={id:"multi-judge-3",name:"Multi-Judge-3 Ensemble",description:"3-model ensemble with 2-judge voting",version:"1.0.0",type:"ensemble",models:[{provider:"openai",model:"gpt-4o",label:"GPT-4o",weight:1,temperature:.7},{provider:"anthropic",model:"claude-3-5-sonnet-20241022",label:"Claude 3.5 Sonnet",weight:1,temperature:.7},{provider:"google-ai",model:"gemini-2.0-flash",label:"Gemini 2.0 Flash",weight:1,temperature:.7}],judges:[{provider:"openai",model:"gpt-4o",criteria:["accuracy","clarity","completeness"],outputFormat:"detailed",includeReasoning:!0,temperature:.1,scoreScale:{min:0,max:100},label:"Primary Judge"},{provider:"anthropic",model:"claude-3-5-sonnet-20241022",criteria:["reasoning","depth","coherence"],outputFormat:"detailed",includeReasoning:!0,temperature:.1,scoreScale:{min:0,max:100},label:"Secondary Judge"}],execution:{parallelism:3,timeout:35e3,modelTimeout:25e3,minResponses:2,costThreshold:.08},tags:["ensemble","multi-judge","voting","balanced"],metadata:{useCase:"Balanced multi-judge evaluation",recommendedFor:["important queries","quality verification"],averageCost:.04,averageLatency:3500},createdAt:ru};function $En(e,t){const r=[{provider:"openai",model:"gpt-4o",label:"GPT-4o",weight:1,temperature:.7},{provider:"anthropic",model:"claude-3-5-sonnet-20241022",label:"Claude 3.5 Sonnet",weight:1,temperature:.7},{provider:"google-ai",model:"gemini-2.0-flash",label:"Gemini 2.0 Flash",weight:1,temperature:.7}],n=[{provider:"openai",model:"gpt-4o-mini",label:"GPT-4o-mini",weight:.8,temperature:.7},{provider:"anthropic",model:"claude-3-haiku-20240307",label:"Claude 3 Haiku",weight:.7,temperature:.7},{provider:"google-ai",model:"gemini-2.5-flash",label:"Gemini 2.5 Flash",weight:.8,temperature:.7},{provider:"openai",model:"gpt-3.5-turbo",label:"GPT-3.5 Turbo",weight:.6,temperature:.7}],o=[...r,...n.slice(0,e-3)],i=[{provider:"openai",model:"gpt-4o",criteria:["accuracy","clarity","completeness"],outputFormat:"detailed",includeReasoning:!0,temperature:.1,scoreScale:{min:0,max:100},label:"Primary Judge"},{provider:"anthropic",model:"claude-3-5-sonnet-20241022",criteria:["reasoning","depth","coherence"],outputFormat:"detailed",includeReasoning:!0,temperature:.1,scoreScale:{min:0,max:100},label:"Secondary Judge"}],s={provider:"google-ai",model:"gemini-2.0-flash",criteria:["relevance","factual_accuracy","structure"],outputFormat:"detailed",includeReasoning:!0,temperature:.1,scoreScale:{min:0,max:100},label:"Tertiary Judge"},a=t===3?[...i,s]:i;return{id:`multi-judge-${e}-${t}`,name:`Multi-Judge ${e}x${t}`,description:`${e}-model ensemble with ${t}-judge voting`,version:"1.0.0",type:"ensemble",models:o,judges:a,execution:{parallelism:e,timeout:45e3,modelTimeout:3e4,minResponses:Math.ceil(e/2),costThreshold:.2},tags:["ensemble","multi-judge","custom"],metadata:{useCase:"Custom multi-judge evaluation",modelCount:e,judgeCount:t},createdAt:ru}}yh();var UEn="1.0.0";Zae(),qar(),Ug(),Ote(),Wl(),await m0r(),fle(),ule(),zjt(),vjt(),Ug(),G();var BEn=["One specific fact, definition or value. A single passage answers it completely.","A handful of related points \u2014 a procedure, a short comparison, one topic explained.","Several distinct areas that each need their own supporting passage.","A broad survey that needs evidence from across the whole corpus."],Okr=[.5,1,1.5,2.5],zEn=.5,GEn=1,qEn=50;async function Dkr(e,t,r){if(!e.trim())return null;const n={breadth:{type:"score",instructions:"How much supporting material does answering this question require from a document collection?",criteria:BEn}};r.canHybrid&&(n.hybrid={type:"boolean",instructions:"This question contains exact terms that must be matched literally \u2014 an identifier, error code, file name, version number, API name, or a quoted phrase \u2014 rather than only a topic to match by meaning."}),r.canGraph&&(n.graph={type:"boolean",instructions:"Answering this requires connecting information that lives in separate documents, such as how two things relate, what depends on what, or tracing a chain across sources."}),r.canRerank&&(n.rerank={type:"boolean",instructions:"This question is specific enough that the ORDER of the retrieved passages matters \u2014 a nearly-right passage would produce a wrong answer, so precision is worth an extra ranking pass."});const o=await t({site:"ragPlan",state:{query:e.slice(0,4e3)},questions:n,timeoutMs:r.timeoutMs});if(!o)return null;const i={model:o.model,latencyMs:o.latencyMs},s=Gee(o.answers,"breadth");if(s&&s.confidence>=zEn){const l=Math.max(0,Math.min(Okr.length-1,Math.round(s.score))),c=Okr[l]??1;i.topK=Math.max(GEn,Math.min(qEn,Math.round(r.defaultTopK*c))),i.breadthLevel=l}return r.canHybrid&&(i.hybrid=Ym(o.answers,"hybrid")),r.canGraph&&(i.graph=Ym(o.answers,"graph")),r.canRerank&&(i.rerank=Ym(o.answers,"rerank")),i.topK!==void 0||i.hybrid!==void 0||i.graph!==void 0||i.rerank!==void 0?(h.debug("[RAG] Search plan decided",{model:o.model,latencyMs:o.latencyMs,topK:i.topK,hybrid:i.hybrid,graph:i.graph,rerank:i.rerank}),i):null}WVt(),S1(),wvr(),bvr(),bwr(),Ewr(),du(),G();var Wme=class Mu{static adapters=new Map;static registerAdapter(t,r){Mu.adapters.set(t,r),h.debug(`[ServerAdapterFactory] Registered adapter for framework: ${t}`)}static async create(t){const{framework:r,neurolink:n,config:o}=t;h.info(`[ServerAdapterFactory] Creating adapter for framework: ${r}`);const i=Mu.adapters.get(r);if(i)return new i(n,o);switch(r){case"hono":{const{HonoServerAdapter:s}=await Promise.resolve().then(()=>(bwr(),Twr));return Mu.adapters.set("hono",s),new s(n,o)}case"express":{const{ExpressServerAdapter:s}=await Promise.resolve().then(()=>(wvr(),vvr));return Mu.adapters.set("express",s),new s(n,o)}case"fastify":{const{FastifyServerAdapter:s}=await Promise.resolve().then(()=>(bvr(),Tvr));return Mu.adapters.set("fastify",s),new s(n,o)}case"koa":{const{KoaServerAdapter:s}=await Promise.resolve().then(()=>(Ewr(),_wr));return Mu.adapters.set("koa",s),new s(n,o)}default:throw new Error(`Unknown framework: ${r}. Supported frameworks: hono (recommended), express, fastify, koa`)}}static async createHono(t,r){return Mu.create({framework:"hono",neurolink:t,config:r})}static async createExpress(t,r){return Mu.create({framework:"express",neurolink:t,config:r})}static async createFastify(t,r){return Mu.create({framework:"fastify",neurolink:t,config:r})}static async createKoa(t,r){return Mu.create({framework:"koa",neurolink:t,config:r})}static isSupported(t){return["hono","express","fastify","koa"].includes(t)}static getSupportedFrameworks(){return[{framework:"hono",status:"available",description:"Multi-runtime support (Node.js, Bun, Deno, Edge)"},{framework:"express",status:"available",description:"Popular Node.js framework with extensive middleware ecosystem"},{framework:"fastify",status:"available",description:"High-performance framework with schema validation"},{framework:"koa",status:"available",description:"Elegant middleware composition with async/await"}]}static getRecommendedFramework(){return"hono"}};async function VEn(e,t){const r=t?.framework??Wme.getRecommendedFramework();return Wme.create({framework:r,neurolink:e,config:t?.config})}du();function jEn(e){const t=r=>{const n=e[r.toLowerCase()];return Array.isArray(n)?n[0]:n};return t("x-neurolink-dev-playground")==="true"||t("x-neurolink-playground")==="true"}var Kme={id:"playground",roles:["developer"]};function HEn(e){const{type:t,validate:r,skipPaths:n=[],errorMessage:o="Authentication required",skipDevPlayground:i=!0}=e,s=e.headerName??WEn(t);return{name:"authentication",order:10,excludePaths:n,handler:async(a,l)=>{if(i&&process.env.NODE_ENV!=="production"&&jEn(a.headers))return a.user={id:Kme.id,email:Kme.email,roles:Kme.roles},l();try{const c=KEn(a,t,s,e.extractToken);if(!c)throw new Eb(o);const u=await r(c,a);if(!u)throw new K$("Invalid authentication token");return a.user={id:u.id,email:u.email,roles:u.roles},u.metadata&&(a.metadata.auth=u.metadata),l()}catch(c){throw c instanceof Eb||c instanceof K$?c:new Eb(c instanceof Error?c.message:"Authentication failed")}}}}function WEn(e){switch(e){case"bearer":case"basic":return"authorization";case"api-key":return"x-api-key";case"custom":return"authorization";default:return"authorization"}}function KEn(e,t,r,n){if(t==="custom"&&n)return n(e);const o=e.headers[r.toLowerCase()];if(!o)return null;switch(t){case"bearer":{const i=o.match(/^Bearer\s+(\S.*)$/i);return i?i[1]:null}case"basic":{const i=o.match(/^Basic\s+(\S.*)$/i);return i?i[1]:null}case"api-key":return o;case"custom":return o;default:return null}}function JEn(e){const{requiredRoles:t,requireAll:r=!1,errorMessage:n="Insufficient permissions"}=e;return{name:"role-check",order:11,handler:async(o,i)=>{if(!o.user)throw new Eb("Authentication required");const s=o.user.roles||[];if(!(r?t.every(l=>s.includes(l)):t.some(l=>s.includes(l))))throw new cpe(n,o.requestId,t);return i()}}}var Nkr=class{cache=new Map;accessOrder=[];maxSize;constructor(e=1e3){this.maxSize=e}async get(e){const t=this.cache.get(e);if(t){if(Date.now()-t.createdAt>t.ttlMs){await this.delete(e);return}return this.updateAccessOrder(e),t}}async set(e,t){if(this.cache.size>=this.maxSize&&!this.cache.has(e)){const r=this.accessOrder.shift();r&&this.cache.delete(r)}this.cache.set(e,t),this.updateAccessOrder(e)}async delete(e){this.cache.delete(e);const t=this.accessOrder.indexOf(e);t>-1&&this.accessOrder.splice(t,1)}async clear(){this.cache.clear(),this.accessOrder=[]}updateAccessOrder(e){const t=this.accessOrder.indexOf(e);t>-1&&this.accessOrder.splice(t,1),this.accessOrder.push(e)}};function XEn(e){const{ttlMs:t,maxSize:r=1e3,keyGenerator:n=YEn,methods:o=["GET"],paths:i,excludePaths:s=[],store:a=new Nkr(r),includeQuery:l=!0,ttlByPath:c={}}=e;return{name:"cache",order:20,excludePaths:s,handler:async(u,d)=>{if(!o.includes(u.method.toUpperCase())||i&&!i.some(y=>u.path.startsWith(y)))return d();const p=n(u),m=await a.get(p);if(m)return u.responseHeaders=u.responseHeaders||{},u.responseHeaders["X-Cache"]="HIT",u.responseHeaders["X-Cache-Age"]=String(Math.floor((Date.now()-m.createdAt)/1e3)),u.metadata.cachedResponse=m.data,m.data;const f=await d();let g=t;for(const[y,v]of Object.entries(c))if(u.path.startsWith(y)){g=v;break}return await a.set(p,{data:f,createdAt:Date.now(),ttlMs:g}),u.responseHeaders=u.responseHeaders||{},u.responseHeaders["X-Cache"]="MISS",u.responseHeaders["Cache-Control"]=`max-age=${Math.floor(g/1e3)}`,f}}}function YEn(e){const t=[e.method,e.path],r=Object.keys(e.query).sort();if(r.length>0){const n=r.map(o=>`${o}=${e.query[o]}`).join("&");t.push(n)}return t.join(":")}function ZEn(e){return{invalidate:async t=>{await e.delete(t)},clear:async()=>{await e.clear()}}}Xn(),tr(),vr(),G();function QEn(){return{name:"timing",order:0,handler:async(e,t)=>ze.middleware.startActiveSpan("neurolink.middleware.timing",async r=>{try{const n=Date.now(),o=process.hrtime.bigint();e.metadata.requestStartTime=n;const i=Ce.createSpan("server.request","server.middleware.timing",{"server.operation":"middleware","server.middleware":"timing"});try{const s=await t(),a=process.hrtime.bigint(),c=Number(a-o)/1e6;e.responseHeaders=e.responseHeaders||{},e.responseHeaders["X-Response-Time"]=`${c.toFixed(2)}ms`,e.responseHeaders["Server-Timing"]=`total;dur=${c.toFixed(2)}`,i.durationMs=Date.now()-n;const u=Ce.endSpan(i,1);return rt().recordSpan(u),s}catch(s){r.recordException(s instanceof Error?s:new Error(String(s))),r.setStatus({code:Be.ERROR,message:s instanceof Error?s.message:String(s)}),i.durationMs=Date.now()-n;const a=Ce.endSpan(i,2);throw a.statusMessage=s instanceof Error?s.message:String(s),rt().recordSpan(a),s}}finally{r.end()}})}}function eSn(e){const{headerName:t="x-request-id",prefix:r="req",generator:n=()=>`${r}-${Date.now()}-${Math.random().toString(36).substring(2,11)}`}=e??{};return{name:"request-id",order:0,handler:async(o,i)=>(o.requestId=o.headers[t.toLowerCase()]||o.requestId||n(),o.responseHeaders=o.responseHeaders||{},o.responseHeaders["X-Request-ID"]=o.requestId,i())}}function tSn(e){const{includeStack:t=!1,onError:r,logErrors:n=!0}=e??{};return{name:"error-handling",order:1,handler:async(o,i)=>{const s=Ce.createSpan("server.request","server.middleware.errorHandling",{"server.operation":"middleware","server.middleware":"error-handling"}),a=Date.now();try{const l=await i();s.durationMs=Date.now()-a;const c=Ce.endSpan(s,1);return rt().recordSpan(c),l}catch(l){const c=l;n&&h.error("[ErrorMiddleware]",{requestId:o.requestId,error:c.message,stack:c.stack}),s.durationMs=Date.now()-a;const u=Ce.endSpan(s,2);if(u.statusMessage=c.message,rt().recordSpan(u),r)return r(c,o);const d=c.statusCode||500,p={error:{code:c.code||`HTTP_${d}`,message:d===500?"Internal server error":c.message},metadata:{requestId:o.requestId,timestamp:new Date().toISOString()}};throw t&&c.stack&&(p.error.stack=c.stack),o.metadata.errorResponse=p,o.metadata.errorStatusCode=d,l}}}}function rSn(e){const{contentSecurityPolicy:t,frameOptions:r="DENY",contentTypeOptions:n="nosniff",hstsMaxAge:o=31536e3,referrerPolicy:i="strict-origin-when-cross-origin",customHeaders:s={}}=e??{},a={};return t&&(a["Content-Security-Policy"]=t),r&&(a["X-Frame-Options"]=r),n&&(a["X-Content-Type-Options"]=n),o!==!1&&(a["Strict-Transport-Security"]=`max-age=${o}; includeSubDomains`),i&&(a["Referrer-Policy"]=i),a["X-XSS-Protection"]="1; mode=block",Object.assign(a,s),{name:"security-headers",order:2,handler:async(l,c)=>(l.responseHeaders=l.responseHeaders||{},Object.assign(l.responseHeaders,a),c())}}function nSn(e){const{logBody:t=!1,logResponse:r=!1,logger:n=console,skipPaths:o=["/health","/ready","/metrics"]}=e??{};return{name:"logging",order:3,excludePaths:o,handler:async(i,s)=>{const a=Date.now(),l={requestId:i.requestId,method:i.method,path:i.path,query:Object.keys(i.query).length>0?i.query:void 0};t&&i.body&&(l.body=i.body),n.info(`[Request] ${i.method} ${i.path}`,l);try{const c=await s(),u=Date.now()-a,d={requestId:i.requestId,duration:`${u}ms`,status:200};return r&&c&&(d.response=c),n.info(`[Response] ${i.method} ${i.path}`,d),c}catch(c){const u=Date.now()-a,d=c;throw n.error(`[Error] ${i.method} ${i.path}`,{requestId:i.requestId,duration:`${u}ms`,error:d.message,status:d.statusCode||500}),c}}}}function oSn(e){const{threshold:t=1024,contentTypes:r=["text/","application/json","application/javascript","application/xml"]}=e??{};return{name:"compression",order:5,handler:async(n,o)=>(n.metadata.compression={enabled:!0,threshold:t,contentTypes:r,acceptEncoding:n.headers["accept-encoding"]||""},o())}}du();var Lkr=class{store=new Map;cleanupInterval;constructor(){this.cleanupInterval=setInterval(()=>this.cleanup(),6e4)}async get(e){const t=this.store.get(e);if(t){if(Date.now()>t.resetAt){this.store.delete(e);return}return t}}async set(e,t){this.store.set(e,t)}async increment(e,t){const r=Date.now();let n=this.store.get(e);return(!n||r>n.resetAt)&&(n={count:0,resetAt:r+t},this.store.set(e,n)),n.count++,{count:n.count,resetAt:n.resetAt}}async reset(e){this.store.delete(e)}cleanup(){const e=Date.now();for(const[t,r]of this.store.entries())e>r.resetAt&&this.store.delete(t)}destroy(){this.cleanupInterval&&clearInterval(this.cleanupInterval),this.store.clear()}};function iSn(e){const{maxRequests:t,windowMs:r,message:n="Too many requests, please try again later",skipPaths:o=[],keyGenerator:i=Fkr,onRateLimitExceeded:s,store:a=new Lkr}=e;return{name:"rate-limit",order:5,excludePaths:o,handler:async(l,c)=>{const u=i(l),{count:d,resetAt:p}=await a.increment(u,r);if(l.responseHeaders=l.responseHeaders||{},l.responseHeaders["X-RateLimit-Limit"]=String(t),l.responseHeaders["X-RateLimit-Remaining"]=String(Math.max(0,t-d)),l.responseHeaders["X-RateLimit-Reset"]=String(Math.ceil(p/1e3)),d>t){const m=Math.ceil((p-Date.now())/1e3);if(l.responseHeaders["Retry-After"]=String(Math.max(0,m)),s)return s(l,m);throw new J$(m*1e3,n,l.requestId)}return c()}}}function Fkr(e){return e.headers["x-forwarded-for"]?.split(",")[0].trim()||e.headers["x-real-ip"]||"unknown"}function sSn(e){const{maxRequests:t,windowMs:r,message:n="Too many requests, please try again later",skipPaths:o=[],keyGenerator:i=Fkr,onRateLimitExceeded:s,subWindows:a=10}=e,l=new Map,c=r/a;return setInterval(()=>{const u=Date.now();for(const[d,p]of l.entries()){const m=p.filter(f=>u-f<r);m.length===0?l.delete(d):l.set(d,m)}},c),{name:"sliding-window-rate-limit",order:5,excludePaths:o,handler:async(u,d)=>{const p=i(u),m=Date.now();let f=l.get(p)||[];f=f.filter(y=>m-y<r);const g=f.length;if(u.responseHeaders=u.responseHeaders||{},u.responseHeaders["X-RateLimit-Limit"]=String(t),u.responseHeaders["X-RateLimit-Remaining"]=String(Math.max(0,t-g-1)),u.responseHeaders["X-RateLimit-Reset"]=String(Math.ceil((m+r)/1e3)),g>=t){const y=f[0]||m,v=Math.ceil((y+r-m)/1e3);if(u.responseHeaders["Retry-After"]=String(Math.max(0,v)),s)return s(u,v);throw new J$(v*1e3,n,u.requestId)}return f.push(m),l.set(p,f),d()}}}du(),du();function aSn(e){const{bodySchema:t,querySchema:r,paramsSchema:n,headersSchema:o,customValidator:i,skipPaths:s=[],errorFormatter:a=cSn}=e;return{name:"request-validation",order:15,excludePaths:s,handler:async(l,c)=>{const u=[];if(t&&l.body){const d=F6(l.body,t,"body");u.push(...d)}if(r){const d=F6(l.query,r,"query");u.push(...d)}if(n){const d=F6(l.params,n,"params");u.push(...d)}if(o){const d=F6(l.headers,o,"headers");u.push(...d)}if(i)try{await i(l)}catch(d){d instanceof Wy?u.push(...d.errors):u.push({field:"custom",message:d instanceof Error?d.message:String(d)})}if(u.length>0){const d=a(u.map(m=>new Wy([m],l.requestId))),p=new Wy(u,l.requestId);throw p.response=d,p}return c()}}}function F6(e,t,r){const n=[];if(t.required)for(const o of t.required)(!(o in e)||e[o]===void 0||e[o]===null)&&n.push({field:`${r}.${o}`,message:`${o} is required`});if(t.additionalProperties===!1&&t.properties){const o=new Set(Object.keys(t.properties));for(const i of Object.keys(e))o.has(i)||n.push({field:`${r}.${i}`,message:`Unknown property: ${i}`})}if(t.properties)for(const[o,i]of Object.entries(t.properties)){const s=e[o];if(s===void 0)continue;const a=$kr(s,i,`${r}.${o}`);n.push(...a)}return n}function $kr(e,t,r){const n=[],o=lSn(e);if(o!==t.type)return n.push({field:r,message:`Expected ${t.type}, got ${o}`}),n;if(t.type==="number"&&typeof e=="number"&&(t.minimum!==void 0&&e<t.minimum&&n.push({field:r,message:`Value must be at least ${t.minimum}`}),t.maximum!==void 0&&e>t.maximum&&n.push({field:r,message:`Value must be at most ${t.maximum}`})),t.type==="string"&&typeof e=="string"){const i=t.minLength??t.minimum,s=t.maxLength??t.maximum;i!==void 0&&e.length<i&&n.push({field:r,message:`String must be at least ${i} characters`}),s!==void 0&&e.length>s&&n.push({field:r,message:`String must be at most ${s} characters`}),t.pattern&&!new RegExp(t.pattern).test(e)&&n.push({field:r,message:`String does not match pattern: ${t.pattern}`})}if(t.type==="array"&&Array.isArray(e)){const i=t.minItems??t.minimum,s=t.maxItems??t.maximum;i!==void 0&&e.length<i&&n.push({field:r,message:`Array must have at least ${i} items`}),s!==void 0&&e.length>s&&n.push({field:r,message:`Array must have at most ${s} items`})}if(t.enum&&!t.enum.includes(e)&&n.push({field:r,message:`Value must be one of: ${t.enum.join(", ")}`}),t.validate){const i=t.validate(e);i!==!0&&n.push({field:r,message:typeof i=="string"?i:"Custom validation failed"})}return n}function lSn(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function cSn(e){return{error:{code:"VALIDATION_ERROR",message:"Request validation failed",details:e.flatMap(t=>t.errors)}}}function uSn(e,t){return r=>{const n=$kr(r,t,e);if(n.length>0)throw new Wy(n)}}yer();var dSn={type:"object",required:["error"],properties:{error:{type:"object",required:["code","message"],properties:{code:{type:"string",description:"Error code identifier",example:"VALIDATION_ERROR"},message:{type:"string",description:"Human-readable error message",example:"Invalid request body"},details:{type:"object",description:"Additional error details",additionalProperties:!0}}},metadata:{type:"object",properties:{timestamp:{type:"string",format:"date-time",description:"Error timestamp"},requestId:{type:"string",description:"Request identifier for tracing"}}}}},Ukr={type:"object",properties:{input:{type:"integer",description:"Number of input/prompt tokens",minimum:0},output:{type:"integer",description:"Number of output/completion tokens",minimum:0},total:{type:"integer",description:"Total tokens used",minimum:0},cacheCreationTokens:{type:"integer",description:"Tokens used for cache creation",minimum:0},cacheReadTokens:{type:"integer",description:"Tokens read from cache",minimum:0},reasoning:{type:"integer",description:"Tokens used for reasoning",minimum:0},cacheSavingsPercent:{type:"number",description:"Percentage of cache savings",minimum:0,maximum:100}}},Bkr={oneOf:[{type:"string",description:"Simple text input"},{type:"object",required:["text"],properties:{text:{type:"string",description:"Text content"},images:{type:"array",items:{type:"string"},description:"Array of image URLs or base64 data"},files:{type:"array",items:{type:"string"},description:"Array of file paths or URLs"}}}]},pSn={type:"object",required:["input"],properties:{input:Bkr,provider:{type:"string",description:"AI provider to use (e.g., openai, anthropic, google-ai)",example:"openai"},model:{type:"string",description:"Specific model to use",example:"gpt-4o"},systemPrompt:{type:"string",description:"System prompt to guide AI behavior"},temperature:{type:"number",minimum:0,maximum:2,description:"Sampling temperature (0-2)",default:.7},maxTokens:{type:"integer",minimum:1,description:"Maximum tokens to generate",default:1e3},tools:{type:"array",items:{type:"string"},description:"Tool names to enable for this request"},stream:{type:"boolean",description:"Enable streaming response",default:!1},sessionId:{type:"string",description:"Session ID for conversation memory"},userId:{type:"string",description:"User ID for context"}}},zkr={type:"object",required:["name","arguments"],properties:{name:{type:"string",description:"Tool name"},arguments:{type:"object",additionalProperties:!0,description:"Tool arguments"},result:{description:"Tool execution result"}}},mSn={type:"object",required:["content","provider","model"],properties:{content:{type:"string",description:"Generated text content"},provider:{type:"string",description:"Provider that handled the request"},model:{type:"string",description:"Model that generated the response"},usage:Ukr,toolCalls:{type:"array",items:zkr,description:"Tool calls made during generation"},finishReason:{type:"string",description:"Reason for completion",enum:["stop","length","tool_calls","content_filter"]},metadata:{type:"object",additionalProperties:!0,description:"Additional response metadata"}}},hSn={type:"object",required:["providers","total"],properties:{providers:{type:"array",items:{type:"string"},description:"List of available provider names"},total:{type:"integer",description:"Total number of providers"}}},Gkr={type:"object",properties:{type:{type:"string",description:"Parameter type"},description:{type:"string",description:"Parameter description"},required:{type:"boolean",description:"Whether parameter is required"},default:{description:"Default value"},enum:{type:"array",description:"Allowed values"}}},qkr={type:"object",required:["name"],properties:{name:{type:"string",description:"Tool name"},description:{type:"string",description:"Tool description"},source:{type:"string",description:"Tool source (builtin, external, custom)"},parameters:{type:"object",additionalProperties:Gkr,description:"Tool parameters schema"}}},fSn={type:"object",required:["tools","total"],properties:{tools:{type:"array",items:qkr,description:"List of available tools"},total:{type:"integer",description:"Total number of tools"}}},gSn={type:"object",required:["name"],properties:{name:{type:"string",description:"Tool name to execute"},arguments:{type:"object",additionalProperties:!0,description:"Tool arguments",default:{}},sessionId:{type:"string",description:"Session context"},userId:{type:"string",description:"User context"}}},ySn={type:"object",required:["success","duration"],properties:{success:{type:"boolean",description:"Whether execution was successful"},data:{description:"Result data"},error:{type:"string",description:"Error message if failed"},duration:{type:"number",description:"Execution duration in milliseconds"},metadata:{type:"object",additionalProperties:!0,description:"Additional metadata"}}},vSn={type:"object",properties:{name:{type:"string",description:"Tool name"},description:{type:"string",description:"Tool description"}}},Vkr={type:"object",required:["serverId","name","status","toolCount"],properties:{serverId:{type:"string",description:"Server ID"},name:{type:"string",description:"Server name"},status:{type:"string",enum:["connected","disconnected","error","connecting"],description:"Connection status"},toolCount:{type:"integer",description:"Number of available tools"},lastHealthCheck:{type:"string",format:"date-time",description:"Last health check timestamp"},error:{type:"string",description:"Error message if in error state"}}},wSn={type:"object",required:["servers","total"],properties:{servers:{type:"array",items:Vkr,description:"List of MCP servers"},total:{type:"integer",description:"Total number of servers"}}},jkr={type:"object",required:["role","content"],properties:{role:{type:"string",enum:["user","assistant","system"],description:"Message role"},content:{type:"string",description:"Message content"},timestamp:{type:"string",format:"date-time",description:"Message timestamp"}}},TSn={type:"object",required:["sessionId"],properties:{sessionId:{type:"string",description:"Session identifier"},messages:{type:"array",items:jkr,description:"Conversation messages"},metadata:{type:"object",additionalProperties:!0,description:"Session metadata"},createdAt:{type:"string",format:"date-time",description:"Session creation time"},updatedAt:{type:"string",format:"date-time",description:"Last update time"}}},bSn={type:"object",required:["sessions","total"],properties:{sessions:{type:"array",items:{type:"object",properties:{sessionId:{type:"string"},messageCount:{type:"integer"},createdAt:{type:"string",format:"date-time"},updatedAt:{type:"string",format:"date-time"}}},description:"List of sessions"},total:{type:"integer",description:"Total number of sessions"}}},_Sn={type:"object",required:["status","timestamp","uptime","version"],properties:{status:{type:"string",enum:["ok","degraded","unhealthy"],description:"Health status"},timestamp:{type:"string",format:"date-time",description:"Check timestamp"},uptime:{type:"integer",description:"Server uptime in milliseconds"},version:{type:"string",description:"Server version"}}},ESn={type:"object",required:["ready","timestamp","services"],properties:{ready:{type:"boolean",description:"Overall readiness status"},timestamp:{type:"string",format:"date-time",description:"Check timestamp"},services:{type:"object",properties:{neurolink:{type:"boolean",description:"NeuroLink SDK status"},tools:{type:"boolean",description:"Tool registry status"},externalServers:{type:"boolean",description:"External MCP servers status"}},description:"Service status breakdown"}}},SSn={type:"object",required:["server","process","timestamp"],properties:{server:{type:"object",properties:{running:{type:"boolean"},uptime:{type:"integer"},routes:{type:"integer"},middlewares:{type:"integer"}}},process:{type:"object",properties:{memoryUsage:{type:"object",properties:{heapUsed:{type:"integer"},heapTotal:{type:"integer"},external:{type:"integer"},rss:{type:"integer"}}},cpuUsage:{type:"object",properties:{user:{type:"integer"},system:{type:"integer"}}},pid:{type:"integer"}}},timestamp:{type:"string",format:"date-time"}}},kSn={ErrorResponse:dSn,TokenUsage:Ukr,AgentInput:Bkr,AgentExecuteRequest:pSn,AgentExecuteResponse:mSn,ToolCall:zkr,ProviderInfo:hSn,ToolParameter:Gkr,ToolDefinition:qkr,ToolListResponse:fSn,ToolExecuteRequest:gSn,ToolExecuteResponse:ySn,MCPServerTool:vSn,MCPServerStatus:Vkr,MCPServersListResponse:wSn,ConversationMessage:jkr,Session:TSn,SessionsListResponse:bSn,HealthResponse:_Sn,ReadyResponse:ESn,MetricsResponse:SSn};function Hkr(e,t,r="application/json"){return{description:e,content:{[r]:{schema:{$ref:`#/components/schemas/${t}`}}}}}function Wb(e,t=400){return{description:e,content:{"application/json":{schema:{$ref:"#/components/schemas/ErrorResponse"}}}}}function xSn(e){return{description:e,content:{"text/event-stream":{schema:{type:"string",description:"Server-Sent Events stream"}}}}}var Kb={400:Wb("Bad Request - Invalid input"),401:Wb("Unauthorized - Authentication required"),403:Wb("Forbidden - Insufficient permissions"),404:Wb("Not Found - Resource does not exist"),429:Wb("Too Many Requests - Rate limit exceeded"),500:Wb("Internal Server Error")};function Jme(e,t,r={type:"string"}){return{name:e,in:"path",required:!0,description:t,schema:r}}function Xme(e,t,r={type:"string"},n=!1){return{name:e,in:"query",required:n,description:t,schema:r}}function Wkr(e,t,r=!1){return{name:e,in:"header",required:r,description:t,schema:{type:"string"}}}var Xs={sessionId:Jme("sessionId","Session identifier"),serverName:Jme("name","MCP server name"),toolName:Jme("name","Tool name"),limitQuery:Xme("limit","Maximum number of items to return",{type:"integer",minimum:1,maximum:100,default:25}),offsetQuery:Xme("offset","Number of items to skip",{type:"integer",minimum:0,default:0}),searchQuery:Xme("q","Search query string",{type:"string"}),requestIdHeader:Wkr("X-Request-ID","Unique request identifier for tracing"),authorizationHeader:Wkr("Authorization","Bearer token or API key",!0)};function Su(e,t,r,n,o){return{summary:e,description:t,tags:r,parameters:o??[],responses:{200:Hkr("Success",n),...Kb}}}function Kkr(e,t,r,n,o,i){return{summary:e,description:t,tags:r,parameters:i??[],requestBody:{required:!0,content:{"application/json":{schema:{$ref:`#/components/schemas/${n}`}}}},responses:{200:Hkr("Success",o),...Kb}}}function ASn(e,t,r,n,o){return{summary:e,description:t,tags:r,parameters:o??[],requestBody:{required:!0,content:{"application/json":{schema:{$ref:`#/components/schemas/${n}`}}}},responses:{200:xSn("Streaming response"),...Kb}}}function CSn(e,t,r,n){return{summary:e,description:t,tags:r,parameters:n,responses:{204:{description:"Successfully deleted"},...Kb}}}var ISn={type:"http",scheme:"bearer",bearerFormat:"JWT",description:"JWT Bearer token authentication"},RSn={type:"apiKey",in:"header",name:"X-API-Key",description:"API key authentication via header"},MSn=[{name:"agent",description:"Agent execution and streaming endpoints"},{name:"tools",description:"Tool discovery and execution endpoints"},{name:"mcp",description:"MCP server management endpoints"},{name:"memory",description:"Conversation memory and session management"},{name:"health",description:"Health check and metrics endpoints"},{name:"streaming",description:"Real-time streaming endpoints"}];function Jkr(e,t,r){const n={url:e,description:t};return r&&(n.variables=Object.entries(r).reduce((o,[i,s])=>(o[i]={default:s.default,description:s.description},o),{})),n}var PSn=[Jkr("http://localhost:3000","Local development server"),Jkr("{protocol}://{host}:{port}","Custom server",{protocol:{default:"http",description:"Protocol (http or https)"},host:{default:"localhost",description:"Server hostname"},port:{default:"3000",description:"Server port"}})];function OSn(e,t,r,n){const o={title:e,version:t,description:r};return n?.termsOfService&&(o.termsOfService=n.termsOfService),n?.contact&&(o.contact=n.contact),n?.license&&(o.license=n.license),o}var DSn=OSn("NeuroLink API","1.0.0",`
2301
2301
  NeuroLink Server API provides a unified interface to access AI capabilities
2302
2302
  through multiple providers. This API supports:
2303
2303
 
@@ -135,13 +135,17 @@ function extractToken(ctx, type, headerName, customExtractor) {
135
135
  }
136
136
  switch (type) {
137
137
  case "bearer": {
138
- // Extract token from "Bearer <token>"
139
- const match = headerValue.match(/^Bearer\s+(.+)$/i);
138
+ // Extract token from "Bearer <token>". The token must open with a
139
+ // non-whitespace character. With `\s+(.+)` the whitespace run and the
140
+ // token could both claim the same tabs, so a header that failed to match
141
+ // (a line terminator after a long run of tabs) was retried at every
142
+ // split, which is quadratic in the header length.
143
+ const match = headerValue.match(/^Bearer\s+(\S.*)$/i);
140
144
  return match ? match[1] : null;
141
145
  }
142
146
  case "basic": {
143
- // Extract credentials from "Basic <base64>"
144
- const match = headerValue.match(/^Basic\s+(.+)$/i);
147
+ // Extract credentials from "Basic <base64>" (same shape as above).
148
+ const match = headerValue.match(/^Basic\s+(\S.*)$/i);
145
149
  return match ? match[1] : null;
146
150
  }
147
151
  case "api-key":
@@ -1,4 +1,5 @@
1
1
  import express from "express";
2
+ import rateLimit from "express-rate-limit";
2
3
  import fs from "fs";
3
4
  import http from "http";
4
5
  import path from "path";
@@ -29,6 +30,24 @@ function resolvePublicPath() {
29
30
  }
30
31
  return compiled; // let express.static handle the 404
31
32
  }
33
+ // Per-client request budget for the HTTP surface (the page and its static
34
+ // assets). One page load is a handful of requests, so the default leaves normal
35
+ // use untouched and only bounds a client that is hammering the file-serving
36
+ // routes. Both values are operator settings, read once at startup.
37
+ const DEFAULT_RATE_LIMIT_WINDOW_MS = 60_000;
38
+ const DEFAULT_RATE_LIMIT_MAX = 300;
39
+ function positiveIntegerFromEnv(name, fallback) {
40
+ const raw = process.env[name];
41
+ if (raw === undefined || raw.trim() === "") {
42
+ return fallback;
43
+ }
44
+ const parsed = Number(raw);
45
+ if (!Number.isSafeInteger(parsed) || parsed < 1) {
46
+ logger.warn(`[SERVER] Ignoring ${name}: expected a positive integer, using ${fallback}`);
47
+ return fallback;
48
+ }
49
+ return parsed;
50
+ }
32
51
  export async function startVoiceServer(port = 3000) {
33
52
  const app = express();
34
53
  // NEW11: refuse to bind to non-loopback interfaces unless the operator
@@ -46,6 +65,22 @@ export async function startVoiceServer(port = 3000) {
46
65
  // set custom headers — see voiceWebSocketHandler.verifyClient. HTTP routes
47
66
  // intentionally reject `?token=` (would leak via Referer + access logs).
48
67
  const authToken = process.env.VOICE_SERVER_AUTH_TOKEN;
68
+ /* ---------- RATE LIMIT ---------- */
69
+ // Registered first so it also bounds failed-auth attempts and oversized
70
+ // bodies. /health stays exempt for the same reason the auth middleware skips
71
+ // it: a load balancer probes it on a fixed cadence with no credentials.
72
+ const rateLimitWindowMs = positiveIntegerFromEnv("VOICE_SERVER_RATE_LIMIT_WINDOW_MS", DEFAULT_RATE_LIMIT_WINDOW_MS);
73
+ const rateLimitMax = positiveIntegerFromEnv("VOICE_SERVER_RATE_LIMIT_MAX", DEFAULT_RATE_LIMIT_MAX);
74
+ app.use(rateLimit({
75
+ windowMs: rateLimitWindowMs,
76
+ limit: rateLimitMax,
77
+ standardHeaders: "draft-6",
78
+ legacyHeaders: false,
79
+ skip: (req) => req.path === "/health",
80
+ handler: (_req, res) => {
81
+ res.status(429).json({ error: "Too many requests" });
82
+ },
83
+ }));
49
84
  /* ---------- BODY LIMITS + AUTH ---------- */
50
85
  // NEW11: cap JSON / urlencoded body to 100kb. Express's default is 100kb
51
86
  // for json() but only when explicitly registered; without this any future
@@ -108,7 +143,7 @@ export async function startVoiceServer(port = 3000) {
108
143
  const exposure = allowPublic
109
144
  ? `bound publicly on ${host}:${port} (VOICE_SERVER_ALLOW_PUBLIC=1)`
110
145
  : `bound to loopback ${host}:${port} (set VOICE_SERVER_ALLOW_PUBLIC=1 to expose externally)`;
111
- logger.info(`[SERVER] Voice server running — ${exposure}${authToken ? " (auth required)" : " (no auth — token via VOICE_SERVER_AUTH_TOKEN recommended)"}`);
146
+ logger.info(`[SERVER] Voice server running — ${exposure}${authToken ? " (auth required)" : " (no auth — token via VOICE_SERVER_AUTH_TOKEN recommended)"}; rate limit ${rateLimitMax} requests per ${rateLimitWindowMs}ms per client`);
112
147
  resolve();
113
148
  });
114
149
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@juspay/neurolink",
3
- "version": "12.51.2",
3
+ "version": "12.51.3",
4
4
  "packageManager": "pnpm@10.15.1",
5
5
  "description": "The pipe layer of an AI nervous system: one interface connecting provider neurons to your application, across three inference types — generate, stream and decide. `decide` returns typed, calibrated judgements from a non-generative model (~400ms, ~$0.00002/call) for routing, tool selection and context budgeting. MCP-native (4 transports), voice TTS/STT/realtime, RAG, agents, memory, compaction, 9 observability exporters. OpenAI · Anthropic · Gemini · Bedrock · Azure · Ollama · TypeSafe Jev and more.",
6
6
  "author": {
@@ -169,6 +169,7 @@
169
169
  "test:decide-catalog": "pnpm exec tsx test/continuous-test-suite-decide-catalog.ts",
170
170
  "test:agent-mode": "pnpm exec tsx test/continuous-test-suite-agent-mode.ts",
171
171
  "test:servers": "pnpm exec tsx test/continuous-test-suite-servers.ts",
172
+ "test:server-boundaries": "pnpm exec tsx test/continuous-test-suite-server-boundaries.ts",
172
173
  "test:websocket-agent-handler": "pnpm exec tsx test/continuous-test-suite-websocket-agent-handler.ts",
173
174
  "test:tool-reliability": "pnpm exec tsx test/continuous-test-suite-tool-reliability.ts",
174
175
  "test:video-abort": "pnpm exec tsx test/continuous-test-suite-video-abort.ts",