@juspay/neurolink 13.0.0 → 13.0.1

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,19 +1,8 @@
1
- ## [13.0.0](https://github.com/juspay/neurolink/compare/v12.59.0...v13.0.0) (2026-10-16)
1
+ ## [13.0.1](https://github.com/juspay/neurolink/compare/v13.0.0...v13.0.1) (2026-10-18)
2
2
 
3
- ### ⚠ BREAKING CHANGES
4
-
5
- - **(observability):** removed initializeOpenTelemetry, getSpanProcessors,
6
- createContextEnricher, getLangfuseSpanProcessor, getTracerProvider,
7
- getLangfuseContext, runWithCurrentLangfuseContext, ExporterRegistry, the
8
- samplers, TelemetryService, initializeTelemetry and the LangfuseConfig
9
- fields enabled, userId, sessionId, useExternalTracerProvider,
10
- autoDetectExternalProvider, skipLangfuseSpanProcessor,
11
- autoDetectOperationName and traceNameFormat. See
12
- docs/features/observability.md for the migration table.
13
-
14
- ### Features
3
+ ### Bug Fixes
15
4
 
16
- - **(observability):** send complete AI data to Langfuse through one OTEL pipeline ([fc892bb](https://github.com/juspay/neurolink/commit/fc892bbb58087096594f7ab80d5105e62a94189c))
5
+ - **(server):** honour the dev-playground header only when NODE_ENV is development ([86a3d4b](https://github.com/juspay/neurolink/commit/86a3d4b6520fb486a0720bd4f356a8f82f317c80))
17
6
 
18
7
  ## [11.2.3](https://github.com/juspay/neurolink/compare/v11.2.2...v11.2.3) (2026-08-19)
19
8
 
@@ -2303,7 +2303,7 @@ To:
2303
2303
  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:
2304
2304
  \u2022 Zod schema: { parameters: z.object({ value: z.string() }) }
2305
2305
  \u2022 Custom schema: { parameters: { validate: (data) => { ... } } }
2306
- \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})}ZJt(),HJt(),zJt(),qJt(),eXt(),UKt(),ct(),Qe(),Qu(),kh(),ml(),ml(),DK(),nh(),nh(),Mh(),Mh(),Op(),Op(),Gg(),Gf(),mTt(),tce(),Ym(),Ile(),Ole(),ghr(),eQ(),Qe(),ct(),pT();var _bn=class{config;neurolinkInstance=null;instanceId;constructor(e){this.config={...z8,...e},this.instanceId=`ImageGenService-${Date.now()}-${Math.random().toString(36).substring(2,11)}`}async getNeuroLink(){if(!this.neurolinkInstance){const{NeuroLink:e}=await uu().then(()=>hce);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 Be(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:nC(s);return{imageBuffer:s,base64:i,mimeType:a}}}if(Buffer.isBuffer(r)){const o=r.toString("base64");return{imageBuffer:r,base64:o,mimeType:nC(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=rC(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}};pT(),d9t(),AC(),await uu(),F4(),oWe(),set(),uet(),Xl(),j8(),wke(),nke(),Q8(),AW(),JSe(),JJe(),ct(),vW(),Qe(),z(),PKt(),N9t(),M9t(),R9t(),_te(),jre(),rWt(),Fre(),$le(),zir(),$t(),z(),jr(),Dle();function QT(e){return{jsonrpc:"2.0",id:nt(),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 jbr(e,t){return{jsonrpc:"2.0",id:nt(),method:"elicitation/response",params:{requestId:e,responded:t.responded,value:t.value,cancelled:t.cancelled,timedOut:t.timedOut,error:t.error}}}function Ebn(e,t){return{jsonrpc:"2.0",id:nt(),method:"elicitation/cancel",params:{requestId:e,reason:t}}}function Sbn(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 xme(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 Vbr(e){return jbr(e.requestId,{responded:e.responded,value:e.value,cancelled:e.cancelled,timedOut:e.timedOut,error:e.error})}var Hbr=class{manager;config;constructor(e={}){this.manager=e.manager??gF,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 St(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=xme(e),r=await this.manager.request({...t,timeout:t.timeout??this.config.defaultTimeout});return Vbr(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=QT(e),r=xme(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 kbn(e,t){const r={};return t.confirmLabel!==void 0&&(r.confirmLabel=t.confirmLabel),t.cancelLabel!==void 0&&(r.cancelLabel=t.cancelLabel),QT({type:"confirmation",message:e,toolName:t.toolName,serverId:t.serverId,timeout:t.timeout,options:r})}function xbn(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),QT({type:"text",message:e,toolName:t.toolName,serverId:t.serverId,defaultValue:t.defaultValue,timeout:t.timeout,options:r})}function Abn(e,t,r){return QT({type:"select",message:e,toolName:r.toolName,serverId:r.serverId,defaultValue:r.defaultValue,timeout:r.timeout,options:{options:t}})}function Cbn(e,t,r){const n={fields:t};return r.submitLabel!==void 0&&(n.submitLabel=r.submitLabel),QT({type:"form",message:e,toolName:r.toolName,serverId:r.serverId,timeout:r.timeout,options:n})}var Ibn=new Hbr;wte(),Vir(),Zn(),jr(),Qe();var Rbn=class extends hn{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 pe.invalidConfiguration("tool.name","Tool name is required and must be a string");if(e.name.length>64)throw pe.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 pe.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 pe.invalidConfiguration("tool.description","Tool description is required and must be a string",{toolName:e.name});if(typeof e.execute!="function")throw pe.invalidConfiguration("tool.execute","Tool execute function is required",{toolName:e.name});if(this.tools.has(e.name))throw pe.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 St(n.execute(t,r??{}),i,pe.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(),Zn(),z(),Qe(),jr();var Mbn=class extends hn{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 pe.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 pe.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 pe.invalidConfiguration("resource",`Resource not found: ${e}`);const n=Date.now(),o=3e4;try{const i=await St(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 pe.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 pe.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 pe.invalidConfiguration("prompt",`Prompt not found: ${e}`);for(const s of n.arguments??[])if(s.required&&t[s.name]===void 0)throw pe.invalidConfiguration("promptArgument",`Missing required argument: ${s.name}`);const o=Date.now(),i=3e4;try{const s=await St(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 pe.invalidConfiguration("promptName","Prompt name is required and must be a string");if(!/^[a-zA-Z_][a-zA-Z0-9_-]*$/.test(e))throw pe.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 pe.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 Pbn(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 Obn(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 Dbn(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}}]}}}}sA(),SF(),Zir(),h9t(),y9t(),CKt();async function Nbn(){return Promise.resolve()}async function Lbn(){return[]}async function Fbn(e,t,r,n){throw pe.invalidConfiguration("executeMCP","Direct legacy MCP execution is deprecated. Use the new module APIs (createMCPServer, MultiServerManager, ToolRouter, etc.) instead.")}async function $bn(){return{initialized:!1,pluginsDiscovered:0,pluginsBySource:{},availablePlugins:[]}}Fot(),z(),nL(),T8t(),g8t(),i8t(),gK(),nrr(),Pae();function Ubn(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 Ame(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 Bbn(e,t){const r=Ame(e),n=Ame(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}}xh(),z();var Wbr={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:iu},Kbr={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:iu},Jbr={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:iu};function zbn(e,t){const r={speed:Kbr,balanced:Jbr,quality:Wbr},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}`}}xh();var Xbr={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:iu};function Gbn(e){return{...Xbr,id:`consensus-3-custom-${Date.now()}`,defaultSystemPrompt:e}}var qbn={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:iu};xh();var jbn={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:iu},Vbn={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:iu};xh();var Hbn={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:iu},Wbn={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:iu};function Kbn(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:iu}}xh();var Jbn="1.0.0";Aae(),snr(),Yg(),ate(),al(),await Nmr(),jae(),Uae(),c8t(),Bqt(),Yg(),z();var Xbn=["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."],Ybr=[.5,1,1.5,2.5],Ybn=.5,Zbn=1,Qbn=50;async function Zbr(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:Xbn}};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>=Ybn){const l=Math.max(0,Math.min(Ybr.length-1,Math.round(s.score))),c=Ybr[l]??1;i.topK=Math.max(Zbn,Math.min(Qbn,Math.round(r.defaultTopK*c))),i.breadthLevel=l}return r.canHybrid&&(i.hybrid=sh(o.answers,"hybrid")),r.canGraph&&(i.graph=sh(o.answers,"graph")),r.canRerank&&(i.rerank=sh(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}fqt(),RC(),Fhr(),Uhr(),Ufr(),zfr(),hu(),z();var Cme=class Nu{static adapters=new Map;static registerAdapter(t,r){Nu.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=Nu.adapters.get(r);if(i)return new i(n,o);switch(r){case"hono":{const{HonoServerAdapter:s}=await Promise.resolve().then(()=>(Ufr(),$fr));return Nu.adapters.set("hono",s),new s(n,o)}case"express":{const{ExpressServerAdapter:s}=await Promise.resolve().then(()=>(Fhr(),Lhr));return Nu.adapters.set("express",s),new s(n,o)}case"fastify":{const{FastifyServerAdapter:s}=await Promise.resolve().then(()=>(Uhr(),$hr));return Nu.adapters.set("fastify",s),new s(n,o)}case"koa":{const{KoaServerAdapter:s}=await Promise.resolve().then(()=>(zfr(),Bfr));return Nu.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 Nu.create({framework:"hono",neurolink:t,config:r})}static async createExpress(t,r){return Nu.create({framework:"express",neurolink:t,config:r})}static async createFastify(t,r){return Nu.create({framework:"fastify",neurolink:t,config:r})}static async createKoa(t,r){return Nu.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 eTn(e,t){const r=t?.framework??Cme.getRecommendedFramework();return Cme.create({framework:r,neurolink:e,config:t?.config})}hu();function tTn(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 Ime={id:"playground",roles:["developer"]};function rTn(e){const{type:t,validate:r,skipPaths:n=[],errorMessage:o="Authentication required",skipDevPlayground:i=!0}=e,s=e.headerName??nTn(t);return{name:"authentication",order:10,excludePaths:n,handler:async(a,l)=>{if(i&&process.env.NODE_ENV!=="production"&&tTn(a.headers))return a.user={id:Ime.id,email:Ime.email,roles:Ime.roles},l();try{const c=oTn(a,t,s,e.extractToken);if(!c)throw new RT(o);const u=await r(c,a);if(!u)throw new P$("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 RT||c instanceof P$?c:new RT(c instanceof Error?c.message:"Authentication failed")}}}}function nTn(e){switch(e){case"bearer":case"basic":return"authorization";case"api-key":return"x-api-key";case"custom":return"authorization";default:return"authorization"}}function oTn(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 iTn(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 RT("Authentication required");const s=o.user.roles||[];if(!(r?t.every(l=>s.includes(l)):t.some(l=>s.includes(l))))throw new jde(n,o.requestId,t);return i()}}}var Qbr=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 sTn(e){const{ttlMs:t,maxSize:r=1e3,keyGenerator:n=aTn,methods:o=["GET"],paths:i,excludePaths:s=[],store:a=new Qbr(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 aTn(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 lTn(e){return{invalidate:async t=>{await e.delete(t)},clear:async()=>{await e.clear()}}}Yn(),Wt(),nr(),z();function cTn(){return{name:"timing",order:0,handler:async(e,t)=>Ue.middleware.startActiveSpan("middleware.timing",async r=>{try{const n=Date.now(),o=process.hrtime.bigint();e.metadata.requestStartTime=n;const i=ke.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=ke.endSpan(i,1);return et().recordSpan(u),s}catch(s){r.recordException(s instanceof Error?s:new Error(String(s))),r.setStatus({code:ze.ERROR,message:s instanceof Error?s.message:String(s)}),i.durationMs=Date.now()-n;const a=ke.endSpan(i,2);throw a.statusMessage=s instanceof Error?s.message:String(s),et().recordSpan(a),s}}finally{r.end()}})}}function uTn(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 dTn(e){const{includeStack:t=!1,onError:r,logErrors:n=!0}=e??{};return{name:"error-handling",order:1,handler:async(o,i)=>{const s=ke.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=ke.endSpan(s,1);return et().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=ke.endSpan(s,2);if(u.statusMessage=c.message,et().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 pTn(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 mTn(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 hTn(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())}}hu();var eTr=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 fTn(e){const{maxRequests:t,windowMs:r,message:n="Too many requests, please try again later",skipPaths:o=[],keyGenerator:i=tTr,onRateLimitExceeded:s,store:a=new eTr}=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 O$(m*1e3,n,l.requestId)}return c()}}}function tTr(e){return e.headers["x-forwarded-for"]?.split(",")[0].trim()||e.headers["x-real-ip"]||"unknown"}function gTn(e){const{maxRequests:t,windowMs:r,message:n="Too many requests, please try again later",skipPaths:o=[],keyGenerator:i=tTr,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 O$(v*1e3,n,u.requestId)}return f.push(m),l.set(p,f),d()}}}hu(),hu();function yTn(e){const{bodySchema:t,querySchema:r,paramsSchema:n,headersSchema:o,customValidator:i,skipPaths:s=[],errorFormatter:a=wTn}=e;return{name:"request-validation",order:15,excludePaths:s,handler:async(l,c)=>{const u=[];if(t&&l.body){const d=T6(l.body,t,"body");u.push(...d)}if(r){const d=T6(l.query,r,"query");u.push(...d)}if(n){const d=T6(l.params,n,"params");u.push(...d)}if(o){const d=T6(l.headers,o,"headers");u.push(...d)}if(i)try{await i(l)}catch(d){d instanceof o0?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 o0([m],l.requestId))),p=new o0(u,l.requestId);throw p.response=d,p}return c()}}}function T6(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=rTr(s,i,`${r}.${o}`);n.push(...a)}return n}function rTr(e,t,r){const n=[],o=vTn(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 vTn(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function wTn(e){return{error:{code:"VALIDATION_ERROR",message:"Request validation failed",details:e.flatMap(t=>t.errors)}}}function bTn(e,t){return r=>{const n=rTr(r,t,e);if(n.length>0)throw new o0(n)}}UJt();var TTn={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"}}}}},nTr={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}}},oTr={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"}}}]},_Tn={type:"object",required:["input"],properties:{input:oTr,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"}}},iTr={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"}}},ETn={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:nTr,toolCalls:{type:"array",items:iTr,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"}}},STn={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"}}},sTr={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"}}},aTr={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:sTr,description:"Tool parameters schema"}}},kTn={type:"object",required:["tools","total"],properties:{tools:{type:"array",items:aTr,description:"List of available tools"},total:{type:"integer",description:"Total number of tools"}}},xTn={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"}}},ATn={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"}}},CTn={type:"object",properties:{name:{type:"string",description:"Tool name"},description:{type:"string",description:"Tool description"}}},lTr={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"}}},ITn={type:"object",required:["servers","total"],properties:{servers:{type:"array",items:lTr,description:"List of MCP servers"},total:{type:"integer",description:"Total number of servers"}}},cTr={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"}}},RTn={type:"object",required:["sessionId"],properties:{sessionId:{type:"string",description:"Session identifier"},messages:{type:"array",items:cTr,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"}}},MTn={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"}}},PTn={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"}}},OTn={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"}}},DTn={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"}}},NTn={ErrorResponse:TTn,TokenUsage:nTr,AgentInput:oTr,AgentExecuteRequest:_Tn,AgentExecuteResponse:ETn,ToolCall:iTr,ProviderInfo:STn,ToolParameter:sTr,ToolDefinition:aTr,ToolListResponse:kTn,ToolExecuteRequest:xTn,ToolExecuteResponse:ATn,MCPServerTool:CTn,MCPServerStatus:lTr,MCPServersListResponse:ITn,ConversationMessage:cTr,Session:RTn,SessionsListResponse:MTn,HealthResponse:PTn,ReadyResponse:OTn,MetricsResponse:DTn};function uTr(e,t,r="application/json"){return{description:e,content:{[r]:{schema:{$ref:`#/components/schemas/${t}`}}}}}function e_(e,t=400){return{description:e,content:{"application/json":{schema:{$ref:"#/components/schemas/ErrorResponse"}}}}}function LTn(e){return{description:e,content:{"text/event-stream":{schema:{type:"string",description:"Server-Sent Events stream"}}}}}var t_={400:e_("Bad Request - Invalid input"),401:e_("Unauthorized - Authentication required"),403:e_("Forbidden - Insufficient permissions"),404:e_("Not Found - Resource does not exist"),429:e_("Too Many Requests - Rate limit exceeded"),500:e_("Internal Server Error")};function Rme(e,t,r={type:"string"}){return{name:e,in:"path",required:!0,description:t,schema:r}}function Mme(e,t,r={type:"string"},n=!1){return{name:e,in:"query",required:n,description:t,schema:r}}function dTr(e,t,r=!1){return{name:e,in:"header",required:r,description:t,schema:{type:"string"}}}var Zs={sessionId:Rme("sessionId","Session identifier"),serverName:Rme("name","MCP server name"),toolName:Rme("name","Tool name"),limitQuery:Mme("limit","Maximum number of items to return",{type:"integer",minimum:1,maximum:100,default:25}),offsetQuery:Mme("offset","Number of items to skip",{type:"integer",minimum:0,default:0}),searchQuery:Mme("q","Search query string",{type:"string"}),requestIdHeader:dTr("X-Request-ID","Unique request identifier for tracing"),authorizationHeader:dTr("Authorization","Bearer token or API key",!0)};function Au(e,t,r,n,o){return{summary:e,description:t,tags:r,parameters:o??[],responses:{200:uTr("Success",n),...t_}}}function pTr(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:uTr("Success",o),...t_}}}function FTn(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:LTn("Streaming response"),...t_}}}function $Tn(e,t,r,n){return{summary:e,description:t,tags:r,parameters:n,responses:{204:{description:"Successfully deleted"},...t_}}}var UTn={type:"http",scheme:"bearer",bearerFormat:"JWT",description:"JWT Bearer token authentication"},BTn={type:"apiKey",in:"header",name:"X-API-Key",description:"API key authentication via header"},zTn=[{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 mTr(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 GTn=[mTr("http://localhost:3000","Local development server"),mTr("{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 qTn(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 jTn=qTn("NeuroLink API","1.0.0",`
2306
+ \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})}ZJt(),HJt(),zJt(),qJt(),eXt(),UKt(),ct(),Qe(),Qu(),kh(),ml(),ml(),DK(),nh(),nh(),Mh(),Mh(),Op(),Op(),Gg(),Gf(),mTt(),tce(),Ym(),Ile(),Ole(),ghr(),eQ(),Qe(),ct(),pT();var _bn=class{config;neurolinkInstance=null;instanceId;constructor(e){this.config={...z8,...e},this.instanceId=`ImageGenService-${Date.now()}-${Math.random().toString(36).substring(2,11)}`}async getNeuroLink(){if(!this.neurolinkInstance){const{NeuroLink:e}=await uu().then(()=>hce);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 Be(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:nC(s);return{imageBuffer:s,base64:i,mimeType:a}}}if(Buffer.isBuffer(r)){const o=r.toString("base64");return{imageBuffer:r,base64:o,mimeType:nC(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=rC(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}};pT(),d9t(),AC(),await uu(),F4(),oWe(),set(),uet(),Xl(),j8(),wke(),nke(),Q8(),AW(),JSe(),JJe(),ct(),vW(),Qe(),z(),PKt(),N9t(),M9t(),R9t(),_te(),jre(),rWt(),Fre(),$le(),zir(),$t(),z(),jr(),Dle();function QT(e){return{jsonrpc:"2.0",id:nt(),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 jbr(e,t){return{jsonrpc:"2.0",id:nt(),method:"elicitation/response",params:{requestId:e,responded:t.responded,value:t.value,cancelled:t.cancelled,timedOut:t.timedOut,error:t.error}}}function Ebn(e,t){return{jsonrpc:"2.0",id:nt(),method:"elicitation/cancel",params:{requestId:e,reason:t}}}function Sbn(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 xme(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 Vbr(e){return jbr(e.requestId,{responded:e.responded,value:e.value,cancelled:e.cancelled,timedOut:e.timedOut,error:e.error})}var Hbr=class{manager;config;constructor(e={}){this.manager=e.manager??gF,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 St(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=xme(e),r=await this.manager.request({...t,timeout:t.timeout??this.config.defaultTimeout});return Vbr(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=QT(e),r=xme(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 kbn(e,t){const r={};return t.confirmLabel!==void 0&&(r.confirmLabel=t.confirmLabel),t.cancelLabel!==void 0&&(r.cancelLabel=t.cancelLabel),QT({type:"confirmation",message:e,toolName:t.toolName,serverId:t.serverId,timeout:t.timeout,options:r})}function xbn(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),QT({type:"text",message:e,toolName:t.toolName,serverId:t.serverId,defaultValue:t.defaultValue,timeout:t.timeout,options:r})}function Abn(e,t,r){return QT({type:"select",message:e,toolName:r.toolName,serverId:r.serverId,defaultValue:r.defaultValue,timeout:r.timeout,options:{options:t}})}function Cbn(e,t,r){const n={fields:t};return r.submitLabel!==void 0&&(n.submitLabel=r.submitLabel),QT({type:"form",message:e,toolName:r.toolName,serverId:r.serverId,timeout:r.timeout,options:n})}var Ibn=new Hbr;wte(),Vir(),Zn(),jr(),Qe();var Rbn=class extends hn{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 pe.invalidConfiguration("tool.name","Tool name is required and must be a string");if(e.name.length>64)throw pe.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 pe.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 pe.invalidConfiguration("tool.description","Tool description is required and must be a string",{toolName:e.name});if(typeof e.execute!="function")throw pe.invalidConfiguration("tool.execute","Tool execute function is required",{toolName:e.name});if(this.tools.has(e.name))throw pe.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 St(n.execute(t,r??{}),i,pe.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(),Zn(),z(),Qe(),jr();var Mbn=class extends hn{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 pe.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 pe.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 pe.invalidConfiguration("resource",`Resource not found: ${e}`);const n=Date.now(),o=3e4;try{const i=await St(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 pe.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 pe.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 pe.invalidConfiguration("prompt",`Prompt not found: ${e}`);for(const s of n.arguments??[])if(s.required&&t[s.name]===void 0)throw pe.invalidConfiguration("promptArgument",`Missing required argument: ${s.name}`);const o=Date.now(),i=3e4;try{const s=await St(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 pe.invalidConfiguration("promptName","Prompt name is required and must be a string");if(!/^[a-zA-Z_][a-zA-Z0-9_-]*$/.test(e))throw pe.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 pe.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 Pbn(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 Obn(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 Dbn(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}}]}}}}sA(),SF(),Zir(),h9t(),y9t(),CKt();async function Nbn(){return Promise.resolve()}async function Lbn(){return[]}async function Fbn(e,t,r,n){throw pe.invalidConfiguration("executeMCP","Direct legacy MCP execution is deprecated. Use the new module APIs (createMCPServer, MultiServerManager, ToolRouter, etc.) instead.")}async function $bn(){return{initialized:!1,pluginsDiscovered:0,pluginsBySource:{},availablePlugins:[]}}Fot(),z(),nL(),T8t(),g8t(),i8t(),gK(),nrr(),Pae();function Ubn(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 Ame(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 Bbn(e,t){const r=Ame(e),n=Ame(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}}xh(),z();var Wbr={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:iu},Kbr={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:iu},Jbr={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:iu};function zbn(e,t){const r={speed:Kbr,balanced:Jbr,quality:Wbr},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}`}}xh();var Xbr={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:iu};function Gbn(e){return{...Xbr,id:`consensus-3-custom-${Date.now()}`,defaultSystemPrompt:e}}var qbn={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:iu};xh();var jbn={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:iu},Vbn={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:iu};xh();var Hbn={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:iu},Wbn={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:iu};function Kbn(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:iu}}xh();var Jbn="1.0.0";Aae(),snr(),Yg(),ate(),al(),await Nmr(),jae(),Uae(),c8t(),Bqt(),Yg(),z();var Xbn=["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."],Ybr=[.5,1,1.5,2.5],Ybn=.5,Zbn=1,Qbn=50;async function Zbr(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:Xbn}};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>=Ybn){const l=Math.max(0,Math.min(Ybr.length-1,Math.round(s.score))),c=Ybr[l]??1;i.topK=Math.max(Zbn,Math.min(Qbn,Math.round(r.defaultTopK*c))),i.breadthLevel=l}return r.canHybrid&&(i.hybrid=sh(o.answers,"hybrid")),r.canGraph&&(i.graph=sh(o.answers,"graph")),r.canRerank&&(i.rerank=sh(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}fqt(),RC(),Fhr(),Uhr(),Ufr(),zfr(),hu(),z();var Cme=class Nu{static adapters=new Map;static registerAdapter(t,r){Nu.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=Nu.adapters.get(r);if(i)return new i(n,o);switch(r){case"hono":{const{HonoServerAdapter:s}=await Promise.resolve().then(()=>(Ufr(),$fr));return Nu.adapters.set("hono",s),new s(n,o)}case"express":{const{ExpressServerAdapter:s}=await Promise.resolve().then(()=>(Fhr(),Lhr));return Nu.adapters.set("express",s),new s(n,o)}case"fastify":{const{FastifyServerAdapter:s}=await Promise.resolve().then(()=>(Uhr(),$hr));return Nu.adapters.set("fastify",s),new s(n,o)}case"koa":{const{KoaServerAdapter:s}=await Promise.resolve().then(()=>(zfr(),Bfr));return Nu.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 Nu.create({framework:"hono",neurolink:t,config:r})}static async createExpress(t,r){return Nu.create({framework:"express",neurolink:t,config:r})}static async createFastify(t,r){return Nu.create({framework:"fastify",neurolink:t,config:r})}static async createKoa(t,r){return Nu.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 eTn(e,t){const r=t?.framework??Cme.getRecommendedFramework();return Cme.create({framework:r,neurolink:e,config:t?.config})}hu();function tTn(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 Ime={id:"playground",roles:["developer"]};function rTn(e){const{type:t,validate:r,skipPaths:n=[],errorMessage:o="Authentication required",skipDevPlayground:i=!0}=e,s=e.headerName??nTn(t);return{name:"authentication",order:10,excludePaths:n,handler:async(a,l)=>{if(i&&process.env.NODE_ENV==="development"&&tTn(a.headers))return a.user={id:Ime.id,email:Ime.email,roles:Ime.roles},l();try{const c=oTn(a,t,s,e.extractToken);if(!c)throw new RT(o);const u=await r(c,a);if(!u)throw new P$("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 RT||c instanceof P$?c:new RT(c instanceof Error?c.message:"Authentication failed")}}}}function nTn(e){switch(e){case"bearer":case"basic":return"authorization";case"api-key":return"x-api-key";case"custom":return"authorization";default:return"authorization"}}function oTn(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 iTn(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 RT("Authentication required");const s=o.user.roles||[];if(!(r?t.every(l=>s.includes(l)):t.some(l=>s.includes(l))))throw new jde(n,o.requestId,t);return i()}}}var Qbr=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 sTn(e){const{ttlMs:t,maxSize:r=1e3,keyGenerator:n=aTn,methods:o=["GET"],paths:i,excludePaths:s=[],store:a=new Qbr(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 aTn(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 lTn(e){return{invalidate:async t=>{await e.delete(t)},clear:async()=>{await e.clear()}}}Yn(),Wt(),nr(),z();function cTn(){return{name:"timing",order:0,handler:async(e,t)=>Ue.middleware.startActiveSpan("middleware.timing",async r=>{try{const n=Date.now(),o=process.hrtime.bigint();e.metadata.requestStartTime=n;const i=ke.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=ke.endSpan(i,1);return et().recordSpan(u),s}catch(s){r.recordException(s instanceof Error?s:new Error(String(s))),r.setStatus({code:ze.ERROR,message:s instanceof Error?s.message:String(s)}),i.durationMs=Date.now()-n;const a=ke.endSpan(i,2);throw a.statusMessage=s instanceof Error?s.message:String(s),et().recordSpan(a),s}}finally{r.end()}})}}function uTn(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 dTn(e){const{includeStack:t=!1,onError:r,logErrors:n=!0}=e??{};return{name:"error-handling",order:1,handler:async(o,i)=>{const s=ke.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=ke.endSpan(s,1);return et().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=ke.endSpan(s,2);if(u.statusMessage=c.message,et().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 pTn(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 mTn(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 hTn(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())}}hu();var eTr=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 fTn(e){const{maxRequests:t,windowMs:r,message:n="Too many requests, please try again later",skipPaths:o=[],keyGenerator:i=tTr,onRateLimitExceeded:s,store:a=new eTr}=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 O$(m*1e3,n,l.requestId)}return c()}}}function tTr(e){return e.headers["x-forwarded-for"]?.split(",")[0].trim()||e.headers["x-real-ip"]||"unknown"}function gTn(e){const{maxRequests:t,windowMs:r,message:n="Too many requests, please try again later",skipPaths:o=[],keyGenerator:i=tTr,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 O$(v*1e3,n,u.requestId)}return f.push(m),l.set(p,f),d()}}}hu(),hu();function yTn(e){const{bodySchema:t,querySchema:r,paramsSchema:n,headersSchema:o,customValidator:i,skipPaths:s=[],errorFormatter:a=wTn}=e;return{name:"request-validation",order:15,excludePaths:s,handler:async(l,c)=>{const u=[];if(t&&l.body){const d=T6(l.body,t,"body");u.push(...d)}if(r){const d=T6(l.query,r,"query");u.push(...d)}if(n){const d=T6(l.params,n,"params");u.push(...d)}if(o){const d=T6(l.headers,o,"headers");u.push(...d)}if(i)try{await i(l)}catch(d){d instanceof o0?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 o0([m],l.requestId))),p=new o0(u,l.requestId);throw p.response=d,p}return c()}}}function T6(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=rTr(s,i,`${r}.${o}`);n.push(...a)}return n}function rTr(e,t,r){const n=[],o=vTn(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 vTn(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function wTn(e){return{error:{code:"VALIDATION_ERROR",message:"Request validation failed",details:e.flatMap(t=>t.errors)}}}function bTn(e,t){return r=>{const n=rTr(r,t,e);if(n.length>0)throw new o0(n)}}UJt();var TTn={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"}}}}},nTr={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}}},oTr={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"}}}]},_Tn={type:"object",required:["input"],properties:{input:oTr,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"}}},iTr={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"}}},ETn={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:nTr,toolCalls:{type:"array",items:iTr,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"}}},STn={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"}}},sTr={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"}}},aTr={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:sTr,description:"Tool parameters schema"}}},kTn={type:"object",required:["tools","total"],properties:{tools:{type:"array",items:aTr,description:"List of available tools"},total:{type:"integer",description:"Total number of tools"}}},xTn={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"}}},ATn={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"}}},CTn={type:"object",properties:{name:{type:"string",description:"Tool name"},description:{type:"string",description:"Tool description"}}},lTr={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"}}},ITn={type:"object",required:["servers","total"],properties:{servers:{type:"array",items:lTr,description:"List of MCP servers"},total:{type:"integer",description:"Total number of servers"}}},cTr={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"}}},RTn={type:"object",required:["sessionId"],properties:{sessionId:{type:"string",description:"Session identifier"},messages:{type:"array",items:cTr,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"}}},MTn={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"}}},PTn={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"}}},OTn={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"}}},DTn={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"}}},NTn={ErrorResponse:TTn,TokenUsage:nTr,AgentInput:oTr,AgentExecuteRequest:_Tn,AgentExecuteResponse:ETn,ToolCall:iTr,ProviderInfo:STn,ToolParameter:sTr,ToolDefinition:aTr,ToolListResponse:kTn,ToolExecuteRequest:xTn,ToolExecuteResponse:ATn,MCPServerTool:CTn,MCPServerStatus:lTr,MCPServersListResponse:ITn,ConversationMessage:cTr,Session:RTn,SessionsListResponse:MTn,HealthResponse:PTn,ReadyResponse:OTn,MetricsResponse:DTn};function uTr(e,t,r="application/json"){return{description:e,content:{[r]:{schema:{$ref:`#/components/schemas/${t}`}}}}}function e_(e,t=400){return{description:e,content:{"application/json":{schema:{$ref:"#/components/schemas/ErrorResponse"}}}}}function LTn(e){return{description:e,content:{"text/event-stream":{schema:{type:"string",description:"Server-Sent Events stream"}}}}}var t_={400:e_("Bad Request - Invalid input"),401:e_("Unauthorized - Authentication required"),403:e_("Forbidden - Insufficient permissions"),404:e_("Not Found - Resource does not exist"),429:e_("Too Many Requests - Rate limit exceeded"),500:e_("Internal Server Error")};function Rme(e,t,r={type:"string"}){return{name:e,in:"path",required:!0,description:t,schema:r}}function Mme(e,t,r={type:"string"},n=!1){return{name:e,in:"query",required:n,description:t,schema:r}}function dTr(e,t,r=!1){return{name:e,in:"header",required:r,description:t,schema:{type:"string"}}}var Zs={sessionId:Rme("sessionId","Session identifier"),serverName:Rme("name","MCP server name"),toolName:Rme("name","Tool name"),limitQuery:Mme("limit","Maximum number of items to return",{type:"integer",minimum:1,maximum:100,default:25}),offsetQuery:Mme("offset","Number of items to skip",{type:"integer",minimum:0,default:0}),searchQuery:Mme("q","Search query string",{type:"string"}),requestIdHeader:dTr("X-Request-ID","Unique request identifier for tracing"),authorizationHeader:dTr("Authorization","Bearer token or API key",!0)};function Au(e,t,r,n,o){return{summary:e,description:t,tags:r,parameters:o??[],responses:{200:uTr("Success",n),...t_}}}function pTr(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:uTr("Success",o),...t_}}}function FTn(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:LTn("Streaming response"),...t_}}}function $Tn(e,t,r,n){return{summary:e,description:t,tags:r,parameters:n,responses:{204:{description:"Successfully deleted"},...t_}}}var UTn={type:"http",scheme:"bearer",bearerFormat:"JWT",description:"JWT Bearer token authentication"},BTn={type:"apiKey",in:"header",name:"X-API-Key",description:"API key authentication via header"},zTn=[{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 mTr(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 GTn=[mTr("http://localhost:3000","Local development server"),mTr("{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 qTn(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 jTn=qTn("NeuroLink API","1.0.0",`
2307
2307
  NeuroLink Server API provides a unified interface to access AI capabilities
2308
2308
  through multiple providers. This API supports:
2309
2309
 
@@ -7,12 +7,16 @@ import type { ApiKeyAuthOptions, AuthResult, AuthenticatedUser, BearerAuthOption
7
7
  * Check if request is from development playground.
8
8
  * Detects playground requests via special headers for development mode.
9
9
  *
10
+ * This only inspects the headers. `createAuthMiddleware` honours the result
11
+ * solely when `process.env.NODE_ENV` is exactly `"development"`, so a caller
12
+ * that acts on this on its own must apply that gate itself.
13
+ *
10
14
  * @param headers - Request headers to check
11
15
  * @returns True if request is from dev playground
12
16
  *
13
17
  * @example
14
18
  * ```typescript
15
- * if (isDevPlayground(ctx.headers)) {
19
+ * if (process.env.NODE_ENV === "development" && isDevPlayground(ctx.headers)) {
16
20
  * // Skip authentication for playground
17
21
  * }
18
22
  * ```
@@ -7,12 +7,16 @@ import { AuthenticationError, AuthorizationError, InvalidAuthenticationError, }
7
7
  * Check if request is from development playground.
8
8
  * Detects playground requests via special headers for development mode.
9
9
  *
10
+ * This only inspects the headers. `createAuthMiddleware` honours the result
11
+ * solely when `process.env.NODE_ENV` is exactly `"development"`, so a caller
12
+ * that acts on this on its own must apply that gate itself.
13
+ *
10
14
  * @param headers - Request headers to check
11
15
  * @returns True if request is from dev playground
12
16
  *
13
17
  * @example
14
18
  * ```typescript
15
- * if (isDevPlayground(ctx.headers)) {
19
+ * if (process.env.NODE_ENV === "development" && isDevPlayground(ctx.headers)) {
16
20
  * // Skip authentication for playground
17
21
  * }
18
22
  * ```
@@ -61,9 +65,12 @@ export function createAuthMiddleware(config) {
61
65
  order: 10, // Run early but after request ID
62
66
  excludePaths: skipPaths,
63
67
  handler: async (ctx, next) => {
64
- // Skip auth for dev playground in non-production
68
+ // The playground header is a development convenience, so it is honoured
69
+ // only when NODE_ENV is exactly "development". An unset NODE_ENV (the
70
+ // default for most deployments), "test", "staging" or a misspelling must
71
+ // not let an unauthenticated caller claim the developer identity.
65
72
  if (skipDevPlayground &&
66
- process.env.NODE_ENV !== "production" &&
73
+ process.env.NODE_ENV === "development" &&
67
74
  isDevPlayground(ctx.headers)) {
68
75
  ctx.user = {
69
76
  id: DEV_PLAYGROUND_USER.id,
@@ -941,12 +941,16 @@ export type ServerServerAuthConfig = {
941
941
  */
942
942
  extractToken?: (ctx: ServerContext) => string | null;
943
943
  /**
944
- * Skip authentication for dev playground requests in non-production.
945
- * When true (default), requests with x-neurolink-dev-playground or
946
- * x-neurolink-playground header set to "true" will bypass authentication
947
- * and receive a default developer user context.
944
+ * Skip authentication for dev playground requests during development.
945
+ * When true (default), a request with an x-neurolink-dev-playground or
946
+ * x-neurolink-playground header set to "true" bypasses authentication and
947
+ * receives a default developer user context (`id: "playground"`,
948
+ * `roles: ["developer"]`).
948
949
  *
949
- * Only applies when NODE_ENV is not "production".
950
+ * Only applies when `process.env.NODE_ENV` is exactly `"development"`,
951
+ * read on every request. With NODE_ENV unset, `"production"`, `"test"` or
952
+ * any other value the header is ignored and the request must authenticate
953
+ * as usual. Set this to `false` to refuse the header even in development.
950
954
  *
951
955
  * @default true
952
956
  */
@@ -8562,7 +8562,7 @@
8562
8562
  {"objectID":"7826f375db586c8004183275c0715b410e96f673701874419ba565b6ff3dd214","title":"When to Use","url":"/docs/guides/server-adapters/middleware#when-to-use-9","content":"API abuse prevention\nFair usage enforcement\nCost control for expensive operations\nProtection against DDoS attacks","hierarchy":{"lvl0":"Guides","lvl1":"Middleware Reference","lvl2":"When to Use","lvl3":""}},
8563
8563
  {"objectID":"ce6af8a97b716420a9742ad3d965d5cb0aa5912e3d52d961814c83e9e1abaa19","title":"Authentication Middleware","url":"/docs/guides/server-adapters/middleware#authentication-middleware","content":"Provides flexible authentication support with multiple strategies.","hierarchy":{"lvl0":"Guides","lvl1":"Middleware Reference","lvl2":"Authentication Middleware","lvl3":""}},
8564
8564
  {"objectID":"dc019f0ad08d89054d4f68945d6855bbc6d74da0b3f8082e35f56fa5f731ec51","title":"Headers Read","url":"/docs/guides/server-adapters/middleware#headers-read","content":"| Header | Auth Type | Description |\n| --------------- | ------------- | ------------------------------------ |\n| Authorization | bearer, basic | Bearer <token> or Basic <base64> |\n| X-API-Key | api-key | Raw API key value |","hierarchy":{"lvl0":"Guides","lvl1":"Middleware Reference","lvl2":"Headers Read","lvl3":""}},
8565
- {"objectID":"43776c9da774387f221eb7918931d5a4a59b42c949ef248c30c7afb5512ee7ea","title":"Dev Playground Support","url":"/docs/guides/server-adapters/middleware#dev-playground-support","content":"In non-production environments, requests with X-NeuroLink-Dev-Playground: true header bypass authentication and receive a default developer user context.","hierarchy":{"lvl0":"Guides","lvl1":"Middleware Reference","lvl2":"Dev Playground Support","lvl3":""}},
8565
+ {"objectID":"43776c9da774387f221eb7918931d5a4a59b42c949ef248c30c7afb5512ee7ea","title":"Dev Playground Support","url":"/docs/guides/server-adapters/middleware#dev-playground-support","content":"Requests with an X-NeuroLink-Dev-Playground: true (or X-NeuroLink-Playground: true) header bypass authentication and receive a default developer user context (id: \"playground\", roles: [\"developer\"]), but only when NODE_ENV is exactly development. The variable is read on every request.\n\nWith NODE_ENV unset, production, test, staging or any other value, the header is ignored and the request must carry a valid credential. The bypass is therefore off by default in a deployment that never sets NODE_ENV. Pass skipDevPlayground: false to refuse the header even in development.","hierarchy":{"lvl0":"Guides","lvl1":"Middleware Reference","lvl2":"Dev Playground Support","lvl3":""}},
8566
8566
  {"objectID":"a2d39b213dc8603fb3d7889b019eebc14f3705eb13b1185d7f98bf26d988f4aa","title":"When to Use","url":"/docs/guides/server-adapters/middleware#when-to-use-10","content":"Protecting API endpoints\nUser identification and authorization\nRate limiting by user\nAudit logging","hierarchy":{"lvl0":"Guides","lvl1":"Middleware Reference","lvl2":"When to Use","lvl3":""}},
8567
8567
  {"objectID":"fb39a14f946d17f7771143d4e3c349bc51999e8aa360456371d0b8dec29a6449","title":"Request Validation Middleware","url":"/docs/guides/server-adapters/middleware#request-validation-middleware","content":"Provides schema-based request validation for body, query, params, and headers.","hierarchy":{"lvl0":"Guides","lvl1":"Middleware Reference","lvl2":"Request Validation Middleware","lvl3":""}},
8568
8568
  {"objectID":"82758f32126cb9af5f9e25763494cfdbba464d89d977e292be0ad93ce5407717","title":"Common Schemas","url":"/docs/guides/server-adapters/middleware#common-schemas","content":"Pre-built schemas for common validation patterns:\n\n| Schema | Fields |\n| ------------ | ----------------------------- |\n| uuid | UUID string format |\n| email | Email string format |\n| pagination | page, limit, offset |\n| sorting | sortBy, sortOrder |\n| idParam | Required id parameter |\n| dateRange | startDate, endDate |\n| search | q (query), fields (array) |","hierarchy":{"lvl0":"Guides","lvl1":"Middleware Reference","lvl2":"Common Schemas","lvl3":""}},
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@juspay/neurolink",
3
- "version": "13.0.0",
3
+ "version": "13.0.1",
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": {