@juspay/neurolink 9.88.1 → 9.88.2

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,3 +1,9 @@
1
+ ## [9.88.2](https://github.com/juspay/neurolink/compare/v9.88.1...v9.88.2) (2026-07-15)
2
+
3
+ ### Bug Fixes
4
+
5
+ - **(security):** harden isMultimodalInput guard + remove hardcoded AWS account ID ([b9d140f](https://github.com/juspay/neurolink/commit/b9d140fadcc09349a90389bf93f98167583b5d7b)), closes [#278](https://github.com/juspay/neurolink/issues/278)
6
+
1
7
  ## [9.88.1](https://github.com/juspay/neurolink/compare/v9.88.0...v9.88.1) (2026-07-15)
2
8
 
3
9
  ### Bug Fixes
@@ -156,7 +156,7 @@ Additional Context: ${JSON.stringify(n,null,2)}`}static formatForSystemPrompt(e)
156
156
  ${JSON.stringify(e,null,2)}
157
157
  [/CONTEXT]
158
158
 
159
- `}static extractAnalyticsContext(e){return{hasUserId:!!e.userId,hasSessionId:!!e.sessionId,hasUserRole:!!e.userRole,hasOrgContext:!!e.organizationId,contextKeys:Object.keys(e),contextSize:JSON.stringify(e).length}}static extractEvaluationContext(e){return{userRole:e.userRole||"unknown",applicationContext:e.applicationContext?.name||"unknown",organizationContext:e.organizationId||"unknown",hasPreferences:!!e.userPreferences}}},WCe=class r{static convertBusinessContext(e,t,n={}){let{preserveLegacyFields:o=!1,validateDomainData:s=!0,includeMetadata:i=!0}=n;return{sessionId:e.sessionId,userId:e.userId,config:{domainType:t,providerConfig:{token:e.apiToken||e.authToken||e.accessToken,endpoint:e.apiEndpoint||e.serviceUrl,provider:r.inferProvider(e)},platformConfig:{type:e.platformType||"generic",url:e.platformUrl||e.serviceUrl,id:e.platformId||e.serviceId,integrations:e.platformIntegrations||[]},operationalConfig:{demoMode:e.enableDemoMode||!1,environment:e.environment||"production",region:e.region,features:e.enabledFeatures||[]},customData:{...o?{entityId:e.entityId||e.organizationId,departmentId:e.departmentId,projectId:e.projectId}:{},...r.extractCustomData(e)}},metadata:i?{convertedFrom:"legacy-business-context",conversionTime:Date.now(),originalKeys:Object.keys(e),domainType:t}:void 0}}static createDomainContext(e,t,n={}){return{sessionId:n.sessionId||`session_${Date.now()}`,userId:n.userId,config:{domainType:e,customData:t},metadata:{source:"domain-context-factory",createdAt:Date.now(),domainType:e}}}static inferProvider(e){return e.apiToken||e.authToken?"api-provider":e.serviceUrl||e.endpoint?"service-provider":"generic-provider"}static extractCustomData(e){let t=TZ.getFrameworkFieldsConfig(),n;t.overrideFields?n=new Set(t.overrideFields):n=new Set([...t.defaultFields,...t.additionalFields||[]]),t.includeFields&&t.includeFields.forEach(s=>n.delete(s));let o={};return Object.entries(e).forEach(([s,i])=>{n.has(s)||(o[s]=i)}),o}}});var Tc,JCe=k(()=>{"use strict";Tc=class extends Error{constructor(t,n,o){super(t);this.code=n;this.details=o;this.name="ConversationMemoryError"}code;details}});var YCe=k(()=>{"use strict"});var XCe=k(()=>{"use strict"});function oRe(r){if(typeof r!="string"||r.length===0||r.length>XSt)return;let e=r.toLowerCase(),t=e.indexOf("models",0);for(;t!==-1;){let n=t+6;for(;n<r.length&&/\s/.test(r[n]);)n++;if(r[n]!=="="){t=e.indexOf("models",t+1);continue}for(n++;n<r.length&&/\s/.test(r[n]);)n++;if(r[n]!=="["){t=e.indexOf("models",t+1);continue}let o=n,s=r.indexOf("]",o+1);if(s===-1)return;let a=r.slice(o+1,s).split(",").map(c=>c.trim().replace(/^['"]|['"]$/g,"")).filter(c=>c.length>0);return a.length>0?a:void 0}}function sRe(r){let e=r.toLowerCase();return e.includes("team")&&e.includes("not allowed")||e.includes("team can only access")||/not\s+allowed\s+to\s+access\s+(this\s+)?model/i.test(r)}var iE,qe,Mt,aE,zt,er,Zt,ny,ZCe,QCe,eRe,tRe,rRe,nRe,go,qI,um,XSt,iRe=k(()=>{"use strict";iE=class extends Error{constructor(e){super(e),this.name=this.constructor.name}},qe=class extends iE{constructor(t,n){super(n?`[${n}] ${t}`:t);this.provider=n}provider},Mt=class extends qe{constructor(e,t){super(e,t)}},aE=class extends qe{constructor(e,t){super(e,t)}},zt=class extends qe{constructor(e,t){super(e,t)}},er=class extends qe{constructor(e,t){super(e,t)}},Zt=class extends qe{constructor(e,t){super(e,t)}},ny=class extends iE{constructor(t,n){super(t);this.code=n;this.name="OAuthError"}code},ZCe=class extends ny{constructor(e){super(e,"CONFIGURATION_ERROR"),this.name="OAuthConfigurationError"}},QCe=class extends ny{constructor(t,n){super(t,"TOKEN_EXCHANGE_ERROR");this.statusCode=n;this.name="OAuthTokenExchangeError"}statusCode},eRe=class extends ny{constructor(t,n){super(t,"TOKEN_REFRESH_ERROR");this.statusCode=n;this.name="OAuthTokenRefreshError"}statusCode},tRe=class extends ny{constructor(e){super(e,"TOKEN_VALIDATION_ERROR"),this.name="OAuthTokenValidationError"}},rRe=class extends ny{constructor(t,n){super(t,"TOKEN_REVOCATION_ERROR");this.statusCode=n;this.name="OAuthTokenRevocationError"}statusCode},nRe=class extends ny{constructor(e){super(e,"CALLBACK_SERVER_ERROR"),this.name="OAuthCallbackServerError"}},go=class extends iE{constructor(t,n="STORAGE_ERROR"){super(t);this.code=n;this.name="TokenStoreError"}code},qI=class extends iE{model;tier;requiredTier;constructor(e,t,n){super(`Model "${e}" is not available for tier "${t}". Required tier: "${n}" or higher.`),this.name="ModelAccessError",this.model=e,this.tier=t,this.requiredTier=n}},um=class extends qe{requestedModel;allowedModels;code="MODEL_ACCESS_DENIED";constructor(e,t={}){super(e,t.provider),this.name="ModelAccessDeniedError",this.requestedModel=t.requestedModel,this.allowedModels=t.allowedModels}},XSt=1e4});var aRe=k(()=>{"use strict"});var cRe=k(()=>{"use strict"});var lRe=k(()=>{"use strict"});var uRe=k(()=>{"use strict"});var oy,dRe=k(()=>{"use strict";oy={TINY_MAX:10240,SMALL_MAX:102400,MEDIUM_MAX:5242880,LARGE_MAX:104857600,HUGE_MAX:2147483648}});var pRe=k(()=>{"use strict"});var mRe=k(()=>{"use strict"});var fRe=k(()=>{"use strict"});var gRe=k(()=>{"use strict"});var hRe=k(()=>{"use strict"});var yRe=k(()=>{"use strict"});var xRe=k(()=>{"use strict"});var vRe=k(()=>{"use strict"});var bRe=k(()=>{"use strict"});var ZSt,rgn,TRe=k(()=>{"use strict";ao();ZSt=m.object({id:m.string(),displayName:m.string(),capabilities:m.array(m.string()),deprecated:m.boolean(),pricing:m.object({input:m.number(),output:m.number()}),contextWindow:m.number(),releaseDate:m.string()}),rgn=m.object({version:m.string(),lastUpdated:m.string(),models:m.record(m.string(),m.record(m.string(),ZSt)),aliases:m.record(m.string(),m.string()).optional(),defaults:m.record(m.string(),m.string()).optional()})});function ogn(r){return r.type==="text"}function sgn(r){return r.type==="image"}function ign(r){return r.type==="csv"}function agn(r){return r.type==="pdf"}function cgn(r){return r.type==="audio"}function lgn(r){return r.type==="video"}function QSt(r){if(!r||typeof r!="object")return!1;let e=r;if(typeof e.prompt!="string"||!e.prompt)return!1;let{image:t}=e;if(!t)return!1;if(Buffer.isBuffer(t)||typeof t=="string")return!0;if(typeof t=="object"&&"data"in t){let n=t.data;return Buffer.isBuffer(n)||typeof n=="string"}return!1}function ugn(r){let e=r;return!!(e?.images?.length||e?.csvFiles?.length||e?.pdfFiles?.length||e?.files?.length||e?.content?.length||e?.audioFiles?.length||e?.videoFiles?.length||e?.segments?.length&&Array.isArray(e.segments)&&e.segments.every(QSt))}function dgn(r){return Array.isArray(r)}var SRe=k(()=>{"use strict"});var wRe=k(()=>{"use strict"});var ERe=k(()=>{"use strict"});function ggn(r){return/^[0-9A-Fa-f]{6}$/.test(r)}function hgn(r){return r.startsWith("#")?r.slice(1):r}var mgn,fgn,SZ,_Re=k(()=>{"use strict";mgn=5,fgn=50,SZ={"16:9":{width:10,height:5.625},"4:3":{width:10,height:7.5}}});var H2,kRe,wZ=k(()=>{"use strict";H2=(R=>(R.DOWNLOAD_FAILED="DOWNLOAD_FAILED",R.DOWNLOAD_TIMEOUT="DOWNLOAD_TIMEOUT",R.DOWNLOAD_AUTH_FAILED="DOWNLOAD_AUTH_FAILED",R.NETWORK_ERROR="NETWORK_ERROR",R.FILE_NOT_FOUND="FILE_NOT_FOUND",R.RATE_LIMITED="RATE_LIMITED",R.FILE_TOO_LARGE="FILE_TOO_LARGE",R.UNSUPPORTED_TYPE="UNSUPPORTED_TYPE",R.INVALID_FORMAT="INVALID_FORMAT",R.INVALID_MIME_TYPE="INVALID_MIME_TYPE",R.INVALID_MAGIC_BYTES="INVALID_MAGIC_BYTES",R.CORRUPTED_FILE="CORRUPTED_FILE",R.INVALID_STRUCTURE="INVALID_STRUCTURE",R.PROCESSING_FAILED="PROCESSING_FAILED",R.PARSING_FAILED="PARSING_FAILED",R.ENCODING_ERROR="ENCODING_ERROR",R.EXTRACTION_FAILED="EXTRACTION_FAILED",R.DECOMPRESSION_FAILED="DECOMPRESSION_FAILED",R.SECURITY_VALIDATION_FAILED="SECURITY_VALIDATION_FAILED",R.XXE_DETECTED="XXE_DETECTED",R.XSS_DETECTED="XSS_DETECTED",R.CODE_EXECUTION_DETECTED="CODE_EXECUTION_DETECTED",R.ZIP_BOMB_DETECTED="ZIP_BOMB_DETECTED",R.UNKNOWN_ERROR="UNKNOWN_ERROR",R))(H2||{}),kRe={DOWNLOAD_FAILED:{message:"Failed to download the file from the source.",userMessage:"We couldn't download your file.",suggestedAction:"Please try uploading the file again. If the problem persists, the file may have been deleted or access revoked.",retryable:!0},DOWNLOAD_TIMEOUT:{message:"File download timed out.",userMessage:"The download took too long and was cancelled.",suggestedAction:"This usually happens with very large files or slow connections. Try re-uploading a smaller version or check your network connection.",retryable:!0},DOWNLOAD_AUTH_FAILED:{message:"Authentication failed when accessing the file.",userMessage:"We don't have permission to access this file.",suggestedAction:"Please check the file permissions and ensure it's accessible, then try again.",retryable:!1},NETWORK_ERROR:{message:"Network error while downloading the file.",userMessage:"A network error occurred while downloading.",suggestedAction:"This is usually temporary. Please try uploading the file again.",retryable:!0},FILE_NOT_FOUND:{message:"The file could not be found at the specified location.",userMessage:"The file could not be found.",suggestedAction:"The file may have been moved or deleted. Please re-upload the file.",retryable:!1},RATE_LIMITED:{message:"Request was rate limited by the server.",userMessage:"Too many requests in a short time.",suggestedAction:"Please wait a few seconds and try again.",retryable:!0},FILE_TOO_LARGE:{message:"File exceeds the maximum allowed size.",userMessage:"This file is too large to process.",suggestedAction:"Try compressing the file or splitting it into smaller parts. Consider reducing image quality or removing unnecessary content.",retryable:!1},UNSUPPORTED_TYPE:{message:"The file type is not supported for processing.",userMessage:"This file type is not supported.",suggestedAction:"Please convert your file to a supported format and try again.",retryable:!1},INVALID_FORMAT:{message:"The file format is invalid or malformed.",userMessage:"This file appears to be in an invalid format.",suggestedAction:"Please ensure the file is properly saved and not corrupted, then try again.",retryable:!1},INVALID_MIME_TYPE:{message:"File MIME type doesn't match the expected format.",userMessage:"The file type doesn't match its extension.",suggestedAction:"Please ensure the file extension matches its actual content type and try again.",retryable:!1},INVALID_MAGIC_BYTES:{message:"File magic bytes don't match the expected file type.",userMessage:"This file doesn't appear to be a valid file of the expected type.",suggestedAction:"The file may be corrupted or saved in the wrong format. Try re-saving the file in the correct format.",retryable:!0},CORRUPTED_FILE:{message:"File appears to be corrupted or damaged.",userMessage:"This file appears to be corrupted or invalid.",suggestedAction:"The file structure is invalid. Try re-downloading from the original source or re-creating the file.",retryable:!1},INVALID_STRUCTURE:{message:"File internal structure is invalid.",userMessage:"The file has an invalid internal structure.",suggestedAction:"The file format is correct but the content is malformed. Try validating the file with a format checker or re-exporting from the original application.",retryable:!1},PROCESSING_FAILED:{message:"Failed to process the file content.",userMessage:"We couldn't process this file.",suggestedAction:"Please try again. If the problem persists, the file may be in an unsupported variant.",retryable:!0},PARSING_FAILED:{message:"Failed to parse the file content.",userMessage:"We couldn't read the contents of this file.",suggestedAction:"The file structure may be invalid. Try validating the file with a format checker or re-creating the file.",retryable:!1},ENCODING_ERROR:{message:"Text encoding error detected.",userMessage:"We couldn't decode the text in this file.",suggestedAction:"Try re-saving the file with UTF-8 encoding. Most modern text editors have this option in 'Save As' settings.",retryable:!1},EXTRACTION_FAILED:{message:"Failed to extract content from the file.",userMessage:"We couldn't extract the content from this file.",suggestedAction:"The file may be password-protected, corrupted, or use an unsupported variant. Try re-saving without protection.",retryable:!1},DECOMPRESSION_FAILED:{message:"Failed to decompress the file content.",userMessage:"We couldn't decompress this file.",suggestedAction:"The file may be corrupted or use an unsupported compression method. Try re-uploading or using a different file format.",retryable:!0},SECURITY_VALIDATION_FAILED:{message:"File failed security validation.",userMessage:"This file contains content that is blocked for security reasons.",suggestedAction:"Please remove the problematic content and try again. If you believe this is a legitimate file, please contact support.",retryable:!1},XXE_DETECTED:{message:"XML External Entity (XXE) attack pattern detected.",userMessage:"This XML file contains DOCTYPE or ENTITY declarations that could pose security risks.",suggestedAction:"Please remove DOCTYPE and ENTITY declarations from the XML file. Most XML files don't need these for basic data storage.",retryable:!1},XSS_DETECTED:{message:"Cross-site scripting (XSS) attack pattern detected.",userMessage:"This file contains script tags or event handlers that could pose security risks.",suggestedAction:"Please remove <script> tags and event handlers (onclick, onerror, etc.) from the file.",retryable:!1},CODE_EXECUTION_DETECTED:{message:"Potentially malicious code execution pattern detected.",userMessage:"This file contains code execution tags that are not allowed.",suggestedAction:"Please remove custom object/function tags and use standard data structures only.",retryable:!1},ZIP_BOMB_DETECTED:{message:"Zip bomb or decompression bomb pattern detected.",userMessage:"This file has an unusually high compression ratio that could indicate a security threat.",suggestedAction:"If this is a legitimate file, try re-saving it without extreme compression. Otherwise, please verify the file source.",retryable:!1},UNKNOWN_ERROR:{message:"An unexpected error occurred.",userMessage:"An unexpected error occurred while processing your file.",suggestedAction:"Please try again. If the problem persists, contact support.",retryable:!0}}});var CRe,vgn,bgn,Tgn,Sgn,wgn,RRe=k(()=>{"use strict";wZ();CRe={maxRetries:3,baseDelayMs:1e3,maxDelayMs:1e4},vgn=3e4,bgn=10,Tgn=3e4,Sgn=10,wgn={SVG:5,IMAGE:10,PDF:20,CSV:30,MARKDOWN:40,JSON:50,YAML:60,XML:70,HTML:80,EXCEL:90,DOC:95,WORD:100,TEXT:110,SOURCE_CODE:120,CONFIG:130,RTF:140,OPENDOCUMENT:150,VIDEO:160,AUDIO:170,ARCHIVE:180}});function kgn(r){if(r==null||typeof r!="object")return!1;let e=r,t=["api_key","oauth"],n=["free","pro","max","max_5","max_20","api"];if(e.authMethod!==void 0&&typeof e.authMethod=="string"&&t.includes(e.authMethod)||e.subscriptionTier!==void 0&&typeof e.subscriptionTier=="string"&&n.includes(e.subscriptionTier)||e.oauthConfig!==void 0&&typeof e.oauthConfig=="object"&&e.oauthConfig!==null)return!0;if(e.authConfig!==void 0&&typeof e.authConfig=="object"&&e.authConfig!==null){let o=e.authConfig;if(o.method!==void 0&&typeof o.method=="string"&&t.includes(o.method))return!0}return!1}var EZ,Cgn,Rgn,ARe=k(()=>{"use strict";EZ={LATEST_OPENAI:"gpt-4o",FASTEST_OPENAI:"gpt-4o-mini",LATEST_ANTHROPIC:"claude-3-5-sonnet-20241022",FASTEST_ANTHROPIC:"claude-3-5-haiku-20241022",LATEST_GOOGLE:"gemini-2.5-pro",FASTEST_GOOGLE:"gemini-2.5-flash",BEST_CODING:"claude-3-5-sonnet-20241022",BEST_ANALYSIS:"gemini-2.5-pro",BEST_CREATIVE:"claude-3-5-sonnet-20241022",BEST_VALUE:"gemini-2.5-flash"},Cgn=EZ,Rgn=[{provider:"bedrock",models:["anthropic.claude-3-7-sonnet-20250219-v1:0","anthropic.claude-3-5-sonnet-20241022-v1:0"]},{provider:"vertex",models:["claude-sonnet-4@20250514","gemini-2.5-flash"]},{provider:"openai",models:["gpt-4o","gpt-4o-mini"]}]});var IRe=k(()=>{"use strict"});var PRe=k(()=>{"use strict"});var MRe=k(()=>{"use strict"});var ORe=k(()=>{"use strict"});var an,co,en,NRe=k(()=>{"use strict";an={CONFIG:"CONFIG",VALIDATION:"VALIDATION",EXECUTION:"EXECUTION",EXTERNAL:"EXTERNAL",RATE_LIMIT:"RATE_LIMIT",AUTHENTICATION:"AUTHENTICATION",AUTHORIZATION:"AUTHORIZATION",STREAMING:"STREAMING",WEBSOCKET:"WEBSOCKET"},co={LOW:"LOW",MEDIUM:"MEDIUM",HIGH:"HIGH",CRITICAL:"CRITICAL"},en={INVALID_CONFIG:"SERVER_ADAPTER_INVALID_CONFIG",MISSING_DEPENDENCY:"SERVER_ADAPTER_MISSING_DEPENDENCY",FRAMEWORK_INIT_FAILED:"SERVER_ADAPTER_FRAMEWORK_INIT_FAILED",ROUTE_NOT_FOUND:"SERVER_ADAPTER_ROUTE_NOT_FOUND",ROUTE_CONFLICT:"SERVER_ADAPTER_ROUTE_CONFLICT",INVALID_ROUTE:"SERVER_ADAPTER_INVALID_ROUTE",HANDLER_ERROR:"SERVER_ADAPTER_HANDLER_ERROR",TIMEOUT:"SERVER_ADAPTER_TIMEOUT",MIDDLEWARE_ERROR:"SERVER_ADAPTER_MIDDLEWARE_ERROR",RATE_LIMIT_EXCEEDED:"SERVER_ADAPTER_RATE_LIMIT_EXCEEDED",AUTH_REQUIRED:"SERVER_ADAPTER_AUTH_REQUIRED",AUTH_INVALID:"SERVER_ADAPTER_AUTH_INVALID",FORBIDDEN:"SERVER_ADAPTER_FORBIDDEN",STREAM_ERROR:"SERVER_ADAPTER_STREAM_ERROR",STREAM_ABORTED:"SERVER_ADAPTER_STREAM_ABORTED",WEBSOCKET_ERROR:"SERVER_ADAPTER_WEBSOCKET_ERROR",WEBSOCKET_CONNECTION_FAILED:"SERVER_ADAPTER_WEBSOCKET_CONNECTION_FAILED",VALIDATION_ERROR:"SERVER_ADAPTER_VALIDATION_ERROR",SCHEMA_ERROR:"SERVER_ADAPTER_SCHEMA_ERROR",START_FAILED:"SERVER_ADAPTER_START_FAILED",STOP_FAILED:"SERVER_ADAPTER_STOP_FAILED",ALREADY_RUNNING:"SERVER_ADAPTER_ALREADY_RUNNING",NOT_RUNNING:"SERVER_ADAPTER_NOT_RUNNING"}});var DRe=k(()=>{"use strict"});var LRe=k(()=>{"use strict"});var URe=k(()=>{"use strict"});var FRe=k(()=>{"use strict"});var ho,$Re=k(()=>{"use strict";ho={enabled:!0,maxTasks:100,backend:"bullmq",mode:"isolated",timeout:12e4,maxConcurrentRuns:5,maxRunLogs:2e3,maxHistoryEntries:200,tools:!0,retry:{maxAttempts:3,backoffMs:[3e4,6e4,3e5]},storePath:".neurolink/tasks/tasks.json",logsPath:".neurolink/tasks/runs/",redis:{host:"localhost",port:6379},retention:{completedTTL:2592e6,failedTTL:6048e5,cancelledTTL:6048e5,runLogTTL:2592e6}}});var BRe=k(()=>{"use strict"});var zRe=k(()=>{"use strict"});var jRe=k(()=>{"use strict"});function Mgn(r){return typeof r=="object"&&r!==null&&"success"in r&&typeof r.success=="boolean"}function Ogn(r){return typeof r=="object"&&r!==null&&"description"in r&&"execute"in r&&typeof r.description=="string"&&typeof r.execute=="function"}var GRe=k(()=>{"use strict"});function Dgn(r){if(!r||typeof r!="object")return!1;let e=r;return Buffer.isBuffer(e.buffer)&&typeof e.format=="string"&&VRe.includes(e.format)&&typeof e.size=="number"&&e.size>=0}function Lgn(r){if(!r||typeof r!="object")return!1;let e=r;return!(e.speed!==void 0&&(typeof e.speed!="number"||e.speed<.25||e.speed>4)||e.format!==void 0&&!VRe.includes(e.format)||e.quality!==void 0&&!ewt.includes(e.quality))}var VRe,ewt,qRe=k(()=>{"use strict";VRe=["mp3","wav","ogg","opus","m4a","flac","webm","mp4","mpeg","mpga","pcm16"],ewt=["standard","hd"]});function $gn(r){if(!r||typeof r!="object")return!1;let e=r;return typeof e.text=="string"&&typeof e.confidence=="number"&&e.confidence>=0&&e.confidence<=1}function Bgn(r){if(!r||typeof r!="object")return!1;let e=r;return!(e.sampleRate!==void 0&&(typeof e.sampleRate!="number"||e.sampleRate<=0)||e.speakerCount!==void 0&&(typeof e.speakerCount!="number"||e.speakerCount<1||e.speakerCount>10))}function zgn(r){if(!r||typeof r!="object")return!1;let e=r;return(e.index===void 0||typeof e.index=="number")&&typeof e.text=="string"&&typeof e.isFinal=="boolean"}var Sc,Fgn,HRe=k(()=>{"use strict";Sc={AUDIO_EMPTY:"STT_AUDIO_EMPTY",AUDIO_TOO_LONG:"STT_AUDIO_TOO_LONG",INVALID_AUDIO_FORMAT:"STT_INVALID_AUDIO_FORMAT",LANGUAGE_NOT_SUPPORTED:"STT_LANGUAGE_NOT_SUPPORTED",TRANSCRIPTION_FAILED:"STT_TRANSCRIPTION_FAILED",PROVIDER_NOT_CONFIGURED:"STT_PROVIDER_NOT_CONFIGURED",PROVIDER_NOT_SUPPORTED:"STT_PROVIDER_NOT_SUPPORTED",STREAM_ERROR:"STT_STREAM_ERROR",STREAMING_NOT_SUPPORTED:"STT_STREAMING_NOT_SUPPORTED"},Fgn={language:"en-US",punctuation:!0,profanityFilter:!1,sampleRate:16e3}});function Ggn(r){if(!r||typeof r!="object")return!1;let e=r;return!(!e.provider||!["openai-realtime","gemini-live"].includes(e.provider)||e.timeout!==void 0&&(typeof e.timeout!="number"||e.timeout<=0)||e.vadThreshold!==void 0&&(typeof e.vadThreshold!="number"||e.vadThreshold<0||e.vadThreshold>1))}var za,WRe,KRe=k(()=>{"use strict";za={CONNECTION_FAILED:"REALTIME_CONNECTION_FAILED",SESSION_TIMEOUT:"REALTIME_SESSION_TIMEOUT",PROTOCOL_ERROR:"REALTIME_PROTOCOL_ERROR",AUDIO_STREAM_ERROR:"REALTIME_AUDIO_STREAM_ERROR",PROVIDER_NOT_CONFIGURED:"REALTIME_PROVIDER_NOT_CONFIGURED",PROVIDER_NOT_SUPPORTED:"REALTIME_PROVIDER_NOT_SUPPORTED",SESSION_ALREADY_ACTIVE:"REALTIME_SESSION_ALREADY_ACTIVE",SESSION_NOT_ACTIVE:"REALTIME_SESSION_NOT_ACTIVE",INVALID_MESSAGE:"REALTIME_INVALID_MESSAGE"},WRe={timeout:3e4,inputSampleRate:24e3,outputSampleRate:24e3,vadEnabled:!0,vadThreshold:.5,turnDetection:"server_vad"}});var twt,qgn,JRe=k(()=>{"use strict";qRe();HRe();KRe();twt={PROVIDER_NOT_FOUND:"VOICE_PROVIDER_NOT_FOUND",INVALID_CONFIGURATION:"VOICE_INVALID_CONFIGURATION",INITIALIZATION_FAILED:"VOICE_INITIALIZATION_FAILED",OPERATION_CANCELLED:"VOICE_OPERATION_CANCELLED",PROVIDER_NOT_CONFIGURED:"VOICE_PROVIDER_NOT_CONFIGURED",PROVIDER_NOT_SUPPORTED:"VOICE_PROVIDER_NOT_SUPPORTED",FEATURE_NOT_SUPPORTED:"VOICE_FEATURE_NOT_SUPPORTED",TTS_EMPTY_TEXT:"VOICE_TTS_EMPTY_TEXT",TTS_TEXT_TOO_LONG:"VOICE_TTS_TEXT_TOO_LONG",TTS_SYNTHESIS_FAILED:"VOICE_TTS_SYNTHESIS_FAILED",STT_EMPTY_AUDIO:"VOICE_STT_EMPTY_AUDIO",STT_INVALID_FORMAT:"VOICE_STT_INVALID_FORMAT",STT_TRANSCRIPTION_FAILED:"VOICE_STT_TRANSCRIPTION_FAILED",REALTIME_CONNECTION_FAILED:"VOICE_REALTIME_CONNECTION_FAILED",REALTIME_SESSION_ERROR:"VOICE_REALTIME_SESSION_ERROR",NETWORK_ERROR:"VOICE_NETWORK_ERROR",TIMEOUT:"VOICE_TIMEOUT"},qgn={mp3:{format:"mp3",mimeType:"audio/mpeg",extension:".mp3",supportsStreaming:!0,sampleRates:[8e3,16e3,22050,24e3,44100,48e3],bitDepths:[16]},wav:{format:"wav",mimeType:"audio/wav",extension:".wav",supportsStreaming:!1,sampleRates:[8e3,16e3,22050,24e3,44100,48e3],bitDepths:[8,16,24,32]},ogg:{format:"ogg",mimeType:"audio/ogg",extension:".ogg",supportsStreaming:!0,sampleRates:[8e3,16e3,22050,24e3,44100,48e3],bitDepths:[16]},opus:{format:"opus",mimeType:"audio/opus",extension:".opus",supportsStreaming:!0,sampleRates:[8e3,12e3,16e3,24e3,48e3],bitDepths:[16]},m4a:{format:"m4a",mimeType:"audio/mp4",extension:".m4a",supportsStreaming:!1,sampleRates:[44100,48e3],bitDepths:[16]},flac:{format:"flac",mimeType:"audio/flac",extension:".flac",supportsStreaming:!1,sampleRates:[44100,48e3,96e3],bitDepths:[16,24]},webm:{format:"webm",mimeType:"audio/webm",extension:".webm",supportsStreaming:!0,sampleRates:[44100,48e3],bitDepths:[16]},mp4:{format:"mp4",mimeType:"audio/mp4",extension:".mp4",supportsStreaming:!1,sampleRates:[44100,48e3],bitDepths:[16]},mpeg:{format:"mpeg",mimeType:"audio/mpeg",extension:".mpeg",supportsStreaming:!0,sampleRates:[8e3,16e3,22050,24e3,44100,48e3],bitDepths:[16]},mpga:{format:"mpga",mimeType:"audio/mpeg",extension:".mpga",supportsStreaming:!0,sampleRates:[8e3,16e3,22050,24e3,44100,48e3],bitDepths:[16]}}});var YRe,XRe=k(()=>{"use strict";YRe=class r{static normalizeToUniversal(e){return typeof e=="string"?{prompt:e}:e}static getProviderType(e){return"providerType"in e?e.providerType:null}static extractProviderOptions(e,t){let n=r.getProviderType(e);if(n===t)return e;if(n!==null){let{providerType:o,...s}=e;return s}return e}static mergeWithDefaults(e,t){return{...t,...e,context:{...t.context,...e.context},contextConfig:{...t.contextConfig,...e.contextConfig},metadata:{...t.metadata,...e.metadata}}}}});var ZRe=k(()=>{"use strict"});var ip,QRe=k(()=>{"use strict";ip=class r extends Error{details;constructor(e,t){super(e),this.name="WorkflowError",this.details=t,"captureStackTrace"in Error&&typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,r)}}});var eAe=k(()=>{"use strict"});var tAe=k(()=>{"use strict"});var eo,to,rwt,Zgn,rAe=k(()=>{"use strict";eo=(T=>(T.AGENT_RUN="agent.run",T.WORKFLOW_STEP="workflow.step",T.TOOL_CALL="tool.call",T.MODEL_GENERATION="model.generation",T.EMBEDDING="embedding",T.RETRIEVAL="retrieval",T.MEMORY="memory",T.CONTEXT_COMPACTION="context.compaction",T.RAG="rag",T.EVALUATION="evaluation",T.MCP_TRANSPORT="mcp.transport",T.MEDIA_GENERATION="media.generation",T.PPT_GENERATION="ppt.generation",T.WORKFLOW="workflow",T.TTS="tts",T.STT="stt",T.SERVER_REQUEST="server.request",T.CUSTOM="custom",T))(eo||{}),to=(o=>(o[o.UNSET=0]="UNSET",o[o.OK=1]="OK",o[o.ERROR=2]="ERROR",o[o.WARNING=3]="WARNING",o))(to||{}),rwt={GEN_AI_SYSTEM:"gen_ai.system",GEN_AI_REQUEST_MODEL:"gen_ai.request.model",GEN_AI_RESPONSE_MODEL:"gen_ai.response.model",GEN_AI_USAGE_INPUT_TOKENS:"gen_ai.usage.input_tokens",GEN_AI_USAGE_OUTPUT_TOKENS:"gen_ai.usage.output_tokens",GEN_AI_USAGE_TOTAL_TOKENS:"gen_ai.usage.total_tokens",GEN_AI_REQUEST_TEMPERATURE:"gen_ai.request.temperature",GEN_AI_REQUEST_TOP_P:"gen_ai.request.top_p",GEN_AI_REQUEST_MAX_TOKENS:"gen_ai.request.max_tokens",GEN_AI_REQUEST_STOP_SEQUENCES:"gen_ai.request.stop_sequences",GEN_AI_RESPONSE_FINISH_REASON:"gen_ai.response.finish_reasons",GEN_AI_RESPONSE_ID:"gen_ai.response.id",GEN_AI_TOOL_NAME:"gen_ai.tool.name",GEN_AI_TOOL_CALL_ID:"gen_ai.tool.call_id",GEN_AI_PROMPT:"gen_ai.prompt",GEN_AI_COMPLETION:"gen_ai.completion"},Zgn={AGENT_NAME:"gen_ai.agent.name",AGENT_STEP_TYPE:"gen_ai.agent.step_type",AGENT_TOOL_CALLS:"gen_ai.agent.tool_calls",AGENT_MEMORY_ACCESS:"gen_ai.agent.memory_access",AGENT_REASONING_TRACE:"gen_ai.agent.reasoning_trace"}});var nAe,oAe=k(()=>{"use strict";nAe={enabled:!0,defaultModel:"imagen-3.0-generate-001",defaultProvider:"vertex",defaultRegion:"global",timeout:12e4,defaultTemperature:.75,maxImages:4,maxReferenceImages:5,maxReferencePdfs:1}});var sAe=k(()=>{"use strict"});var iAe=k(()=>{"use strict"});var aAe=k(()=>{"use strict"});var cAe=k(()=>{"use strict"});var lAe=k(()=>{"use strict"});var thn,uAe=k(()=>{"use strict";thn=["mp4","webm","mov"]});var nhn,dAe=k(()=>{"use strict";nhn=["mp3","wav","flac","ogg"]});var pAe=k(()=>{"use strict"});var mAe=k(()=>{"use strict"});var fAe=k(()=>{"use strict"});var gAe=k(()=>{"use strict"});var hAe=k(()=>{"use strict"});var yAe=k(()=>{"use strict"});var Dt=k(()=>{"use strict";Wke();Kke();RCe();ACe();ICe();PCe();MCe();OCe();NCe();DCe();FCe();HCe();KCe();JCe();YCe();XCe();iRe();aRe();cRe();lRe();uRe();dRe();pRe();mRe();fRe();gRe();hRe();yRe();xRe();vRe();bRe();TRe();SRe();wRe();ERe();_Re();RRe();ARe();IRe();PRe();MRe();ORe();NRe();DRe();LRe();URe();FRe();$Re();BRe();zRe();jRe();GRe();JRe();XRe();ZRe();QRe();eAe();tAe();rAe();oAe();sAe();iAe();aAe();cAe();lAe();uAe();dAe();pAe();mAe();fAe();gAe();hAe();yAe()});var cE,_Z,kZ=k(()=>{"use strict";cE=class{name="always";shouldSample(e){return!0}getDescription(){return"Samples 100% of spans"}},_Z=class{name="never";shouldSample(e){return!1}getDescription(){return"Samples 0% of spans"}}});function vAe(r,e,t){return new Promise((n,o)=>{let s=setTimeout(()=>{o(new Error(`Export to '${t}' timed out after ${e}ms`))},e);r.then(i=>{clearTimeout(s),n(i)},i=>{clearTimeout(s),o(i)})})}var xAe,CZ,bAe=k(()=>{"use strict";H();kZ();xAe=3e4;CZ=class{exporters=new Map;defaultExporter=null;sampler=new cE;circuitBreakers=new Map;circuitBreakerConfig={failureThreshold:5,resetTimeout:3e4};register(e){this.exporters.set(e.getName(),e)}unregister(e){return this.exporters.delete(e)}get(e){return this.exporters.get(e)}getNames(){return Array.from(this.exporters.keys())}getCount(){return this.exporters.size}setDefault(e){if(!this.exporters.has(e))throw new Error(`Exporter '${e}' not registered`);this.defaultExporter=e}getDefault(){if(this.defaultExporter)return this.exporters.get(this.defaultExporter)}setSampler(e){this.sampler=e}getSampler(){return this.sampler}configureCircuitBreaker(e){Object.assign(this.circuitBreakerConfig,e)}isCircuitOpen(e){let t=this.circuitBreakers.get(e);return t&&t.state==="open"?Date.now()-t.lastFailure>this.circuitBreakerConfig.resetTimeout?(t.state="half-open",g.info(`[ExporterRegistry] Circuit half-open for ${e}, attempting recovery`),!1):!0:!1}recordFailure(e){let t=this.circuitBreakers.get(e);t||(t={failures:0,lastFailure:0,state:"closed"},this.circuitBreakers.set(e,t)),t.failures++,t.lastFailure=Date.now(),t.failures>=this.circuitBreakerConfig.failureThreshold&&(t.state="open",g.warn(`[ExporterRegistry] Circuit opened for ${e} after ${t.failures} failures`))}recordSuccess(e){let t=this.circuitBreakers.get(e);t&&(t.state==="half-open"&&g.info(`[ExporterRegistry] Circuit closed for ${e} after successful recovery`),t.failures=0,t.state="closed")}getCircuitBreakerStatus(e){return this.circuitBreakers.get(e)}resetCircuitBreaker(e){this.circuitBreakers.delete(e)}async exportToAll(e){let t=new Map;if(!this.sampler.shouldSample(e))return t;let n=Array.from(this.exporters.entries()).map(async([o,s])=>{if(this.isCircuitOpen(o)){t.set(o,{success:!1,exportedCount:0,failedCount:1,errors:[{spanId:e.spanId,error:"Circuit breaker open - exporter temporarily disabled",retryable:!0}],durationMs:0});return}if(s.isInitialized())try{let i=await vAe(s.exportSpan(e),xAe,o);t.set(o,i),i.success?this.recordSuccess(o):this.recordFailure(o)}catch(i){this.recordFailure(o),t.set(o,{success:!1,exportedCount:0,failedCount:1,errors:[{spanId:e.spanId,error:i instanceof Error?i.message:String(i),retryable:!0}],durationMs:0})}else g.debug(`[ExporterRegistry] Skipping uninitialized exporter '${o}' for span ${e.spanId}`)});return await Promise.all(n),t}async exportTo(e,t){let n=this.exporters.get(e);if(!n)return null;if(!n.isInitialized())return g.debug(`[ExporterRegistry] Skipping uninitialized exporter '${e}' for span ${t.spanId}`),null;if(this.isCircuitOpen(e))return{success:!1,exportedCount:0,failedCount:1,errors:[{spanId:t.spanId,error:"Circuit breaker open - exporter temporarily disabled",retryable:!0}],durationMs:0};if(!this.sampler.shouldSample(t))return{success:!0,exportedCount:0,failedCount:0,durationMs:0};try{let o=await vAe(n.exportSpan(t),xAe,e);return o.success?this.recordSuccess(e):this.recordFailure(e),o}catch(o){return this.recordFailure(e),{success:!1,exportedCount:0,failedCount:1,errors:[{spanId:t.spanId,error:o instanceof Error?o.message:String(o),retryable:!0}],durationMs:0}}}async initializeAll(){let e=await Promise.allSettled(Array.from(this.exporters.entries()).map(([t,n])=>n.initialize().catch(o=>{throw g.error(`[ExporterRegistry] Failed to initialize exporter '${t}':`,o),o})));for(let t of e)if(t.status==="rejected"){g.warn("[ExporterRegistry] One or more exporters failed to initialize");break}}async shutdownAll(){let e=await Promise.allSettled(Array.from(this.exporters.entries()).map(([t,n])=>n.shutdown().catch(o=>{throw g.error(`[ExporterRegistry] Failed to shutdown exporter '${t}':`,o),o})));for(let t of e)if(t.status==="rejected"){g.warn("[ExporterRegistry] One or more exporters failed to shutdown");break}}async flushAll(){let e=await Promise.allSettled(Array.from(this.exporters.entries()).map(([t,n])=>n.flush().catch(o=>{throw g.error(`[ExporterRegistry] Failed to flush exporter '${t}':`,o),o})));for(let t of e)if(t.status==="rejected"){g.warn("[ExporterRegistry] One or more exporters failed to flush");break}}async healthCheckAll(){let e=new Map,t=Array.from(this.exporters.entries()).map(async([n,o])=>{let s=await o.healthCheck();e.set(n,s)});return await Promise.all(t),e}async isHealthy(){let e=await this.healthCheckAll();return Array.from(e.values()).every(t=>t.healthy)}getTotalPendingSpans(){let e=0,t=Array.from(this.exporters.values());for(let n of t)e+=n.getPendingCount();return e}clear(){this.exporters.clear(),this.defaultExporter=null,this.circuitBreakers.clear(),this.sampler=new cE}}});var RZ,AZ,TAe=k(()=>{"use strict";H();RZ=class{name;config;initialized=!1;buffer=[];maxBufferSize;retries;flushInterval=null;lastExportTime=0;constructor(e,t){this.name=e,this.config=t,this.maxBufferSize=t.maxBufferSize??100,this.retries=t.retries??3}async ping(){}bufferSpan(e){this.buffer.push(e),this.buffer.length>=this.maxBufferSize&&this.flush()}startFlushInterval(e){this.flushInterval&&clearInterval(this.flushInterval),this.flushInterval=setInterval(()=>{this.flush().catch(t=>{g.warn(`[${this.name}] Periodic flush failed`,{error:t instanceof Error?t.message:String(t)})})},e)}stopFlushInterval(){this.flushInterval&&(clearInterval(this.flushInterval),this.flushInterval=null)}getName(){return this.name}isInitialized(){return this.initialized}getPendingCount(){return this.buffer.length}getLastExportTime(){return this.lastExportTime}createSuccessResult(e,t){return this.lastExportTime=Date.now(),{success:!0,exportedCount:e,failedCount:0,durationMs:t}}createFailureResult(e,t,n,o=!0){return{success:!1,exportedCount:0,failedCount:e.length,errors:e.map(s=>({spanId:s,error:t,retryable:o})),durationMs:n}}createHealthStatus(e,t){return{healthy:e,name:this.name,pendingSpans:this.buffer.length,lastExportTime:this.lastExportTime||void 0,errors:t}}async withRetry(e,t){let n=this.retries,o=1e3,s;for(let i=0;i<=n;i++)try{return await e()}catch(a){if(s=a,i<n){let c=o*2**i;g.warn(`[${this.name}] ${t} failed, retrying in ${c}ms`,{attempt:i+1,maxRetries:n,error:s.message}),await new Promise(l=>setTimeout(l,c))}}throw s}},AZ=class extends RZ{constructor(){super("noop",{enabled:!1})}async initialize(){this.initialized=!0}async exportSpan(e){return this.createSuccessResult(0,0)}async exportBatch(e){return this.createSuccessResult(0,0)}async flush(){}async shutdown(){this.initialized=!1}async healthCheck(){return this.createHealthStatus(!0)}}});var SAe,PZ,Yo,MZ,Pyn,Myn,Oyn,OZ,nwt,IZ,Nyn,Dyn,Uyn,Fyn,xl=k(()=>{SAe=r=>{let e=[];return{update(t){return e.push(typeof t=="string"?new IZ().encode(t):t),this},digest(t){let n=0;for(let s of e)for(let i=0;i<s.length;i++)n=(n<<5)-n+s[i]|0;let o=(n>>>0).toString(16).padStart(8,"0");return t==="hex"?o:t==="base64"?btoa(o):o}}},PZ=r=>new Uint8Array(r||32),Yo=()=>globalThis.crypto?.randomUUID?.()||Math.random().toString(36),MZ=globalThis.crypto,Pyn=globalThis.ReadableStream||class{},Myn=globalThis.URL,Oyn=globalThis.URLSearchParams,OZ=r=>{try{return JSON.stringify(r,null,2)}catch{return String(r)}};OZ.custom=Symbol.for("nodejs.util.inspect.custom");OZ.colors={};OZ.styles={};nwt=globalThis.TextDecoder,IZ=globalThis.TextEncoder,Nyn=globalThis.performance||{now:()=>Date.now()},Dyn=globalThis.Buffer||class extends Uint8Array{static from(e,t){if(typeof e=="string"){let n=(t||"utf8").toLowerCase();if(n==="base64"){let o=atob(e),s=new Uint8Array(o.length);for(let i=0;i<o.length;i++)s[i]=o.charCodeAt(i);return s}if(n==="hex"){let o=new Uint8Array(e.length/2);for(let s=0;s<e.length;s+=2)o[s/2]=parseInt(e.substr(s,2),16);return o}return new IZ().encode(e)}return new Uint8Array(e)}static alloc(e){return new Uint8Array(e)}static isBuffer(e){return e instanceof Uint8Array}static concat(e){let t=e.reduce((s,i)=>s+i.length,0),n=new Uint8Array(t),o=0;for(let s of e)n.set(s,o),o+=s.length;return n}static byteLength(e,t){return t==="base64"?Math.ceil(e.length*3/4):new IZ().encode(e).length}toString(e){let t=(e||"utf8").toLowerCase();if(t==="hex")return Array.from(new Uint8Array(this.buffer,this.byteOffset,this.byteLength)).map(n=>n.toString(16).padStart(2,"0")).join("");if(t==="base64"){let n="";for(let o=0;o<this.length;o++)n+=String.fromCharCode(this[o]);return btoa(n)}return new nwt().decode(this)}},Uyn=globalThis.clearTimeout,Fyn=globalThis.clearInterval});function od(){let r=Tt.getSpan(wr.active());if(!r)return{};let e=r.spanContext();return!e.traceId||e.traceId==="00000000000000000000000000000000"?{}:{traceId:e.traceId,parentSpanId:e.spanId}}var Gv=k(()=>{"use strict";Dr()});function wAe(r){let e={};for(let t of swt)r[t]!==void 0&&(e[t]=r[t]);return e}var swt,EAe=k(()=>{"use strict";swt=new Set(["ai.provider","ai.model","ai.temperature","ai.max_tokens"])});var xe,HI=k(()=>{"use strict";xl();Gv();EAe();xe=class r{static createSpan(e,t,n={},o,s){let i=s,a=o;if(!i){let c=od();i=c.traceId??PZ(16).toString("hex"),!a&&c.parentSpanId&&(a=c.parentSpanId)}return{spanId:PZ(8).toString("hex"),traceId:i,parentSpanId:a,type:e,name:t,startTime:new Date().toISOString(),status:0,attributes:n,events:[],links:[]}}static endSpan(e,t=1,n){let o=new Date,s=new Date(e.startTime);return{...e,endTime:o.toISOString(),durationMs:o.getTime()-s.getTime(),status:t,statusMessage:n}}static addEvent(e,t,n){let o={name:t,timestamp:new Date().toISOString(),attributes:n};return{...e,events:[...e.events,o]}}static updateAttributes(e,t){return{...e,attributes:{...e.attributes,...t}}}static toJSON(e){return JSON.stringify(e,null,2)}serialize(e){return JSON.stringify(e,null,2)}deserialize(e){return JSON.parse(e)}static fromJSON(e){return JSON.parse(e)}static toLangfuseFormat(e){return{id:e.spanId,traceId:e.traceId,parentObservationId:e.parentSpanId,name:e.name,startTime:e.startTime,endTime:e.endTime,metadata:wAe(e.attributes),level:e.status===2?"ERROR":e.status===3?"WARNING":"DEFAULT",statusMessage:e.statusMessage,input:e.attributes.input,output:e.attributes.output,usage:e.attributes["ai.tokens.total"]!==void 0?{promptTokens:e.attributes["ai.tokens.input"],completionTokens:e.attributes["ai.tokens.output"],totalTokens:e.attributes["ai.tokens.total"]}:void 0}}static toLangSmithFormat(e){return{id:e.spanId,trace_id:e.traceId,parent_run_id:e.parentSpanId,name:e.name,run_type:r.mapSpanTypeToLangSmithRunType(e.type),start_time:e.startTime,end_time:e.endTime,extra:{...e.attributes},error:e.status===2?e.statusMessage:void 0,inputs:e.attributes.input,outputs:e.attributes.output,tags:r.extractTags(e.attributes)}}static toOtelFormat(e){return{traceId:e.traceId,spanId:e.spanId,parentSpanId:e.parentSpanId,name:e.name,kind:1,startTimeUnixNano:new Date(e.startTime).getTime()*1e6,endTimeUnixNano:e.endTime?new Date(e.endTime).getTime()*1e6:void 0,attributes:Object.entries(e.attributes).filter(([,t])=>t!==void 0).map(([t,n])=>({key:t,value:r.toOtelAttributeValue(n)})),status:{code:e.status,message:e.statusMessage},events:e.events.map(t=>({name:t.name,timeUnixNano:new Date(t.timestamp).getTime()*1e6,attributes:t.attributes?Object.entries(t.attributes).map(([n,o])=>({key:n,value:r.toOtelAttributeValue(o)})):[]}))}}static toOtelAttributeValue(e){return typeof e=="string"?{stringValue:e}:typeof e=="number"?Number.isInteger(e)?{intValue:e}:{stringValue:String(e)}:typeof e=="boolean"?{boolValue:e}:{stringValue:JSON.stringify(e)}}static mapSpanTypeToLangSmithRunType(e){return{"agent.run":"chain","workflow.step":"chain","tool.call":"tool","model.generation":"llm",embedding:"embedding",retrieval:"retriever",memory:"chain","context.compaction":"chain",rag:"retriever",evaluation:"chain","mcp.transport":"tool","media.generation":"llm","ppt.generation":"chain",workflow:"chain",tts:"chain",stt:"chain","server.request":"chain",custom:"chain"}[e]||"chain"}static extractTags(e){let t=[];return e["ai.provider"]&&t.push(`provider:${e["ai.provider"]}`),e["ai.model"]&&t.push(`model:${e["ai.model"]}`),e["deployment.environment"]&&t.push(`env:${e["deployment.environment"]}`),e["tool.name"]&&t.push(`tool:${e["tool.name"]}`),t}static createGenerationSpan(e){return r.createSpan("model.generation",e.name??`gen_ai.${e.provider}.chat`,{"ai.provider":e.provider,"ai.model":e.model,"ai.temperature":e.temperature,"ai.max_tokens":e.maxTokens,input:e.input,"user.id":e.userId,"session.id":e.sessionId},e.parentSpanId,e.traceId)}static createToolCallSpan(e){return r.createSpan("tool.call",`tool.${e.toolName}`,{"tool.name":e.toolName,"tool.server":e.server,input:e.input},e.parentSpanId,e.traceId)}static enrichWithTokenUsage(e,t){return r.updateAttributes(e,{"ai.tokens.input":t.promptTokens??0,"ai.tokens.output":t.completionTokens??0,"ai.tokens.total":t.totalTokens??(t.promptTokens??0)+(t.completionTokens??0),"ai.tokens.cache_creation":t.cacheCreationTokens,"ai.tokens.cache_read":t.cacheReadTokens,"ai.tokens.reasoning":t.reasoningTokens})}static enrichWithCost(e,t){return r.updateAttributes(e,{"ai.cost.input":t.inputCost,"ai.cost.output":t.outputCost,"ai.cost.total":t.totalCost,"ai.cost.currency":t.currency??"USD"})}}});var WI={};te(WI,{AsyncLocalStorage:()=>kwt,Buffer:()=>f_t,Channel:()=>n_t,DatabaseSync:()=>m_t,Duplex:()=>Rwt,EventEmitter:()=>_wt,Http2ServerRequest:()=>v_t,Http2ServerResponse:()=>b_t,Interface:()=>p_t,MIMEType:()=>k_t,PassThrough:()=>Awt,PerformanceObserver:()=>e_t,Readable:()=>kAe,ReadableStream:()=>Iwt,Resolver:()=>ZEt,TextDecoder:()=>AAe,TextEncoder:()=>W2,Transform:()=>Cwt,URL:()=>$Et,URLSearchParams:()=>BEt,Worker:()=>a_t,Writable:()=>CAe,access:()=>oEt,appendFile:()=>Uwt,appendFileSync:()=>pwt,arch:()=>bEt,arrayBuffer:()=>T_t,basename:()=>xwt,builtinModules:()=>DEt,callbackify:()=>WEt,channel:()=>r_t,chmodSync:()=>Lwt,clearInterval:()=>__t,clearTimeout:()=>w_t,closeSync:()=>zwt,connect:()=>EEt,constants:()=>g_t,copyFileSync:()=>$wt,cpSync:()=>mwt,cpus:()=>hEt,createConnection:()=>_Et,createGunzip:()=>IEt,createGzip:()=>PEt,createHash:()=>_Ae,createHmac:()=>cwt,createInterface:()=>d_t,createReadStream:()=>Xwt,createRequire:()=>NEt,createServer:()=>fwt,createWriteStream:()=>Ywt,debug:()=>qEt,debuglog:()=>RAe,default:()=>iwt,deflateSync:()=>CEt,deprecate:()=>HEt,deserialize:()=>i_t,dirname:()=>ywt,exec:()=>cEt,execFile:()=>uEt,execFileSync:()=>dEt,execSync:()=>lEt,existsSync:()=>Owt,extname:()=>vwt,fileURLToPath:()=>zEt,finished:()=>Mwt,format:()=>FEt,freemem:()=>yEt,fstatSync:()=>jwt,get:()=>wEt,gunzip:()=>DZ,gunzipSync:()=>REt,gzip:()=>NZ,gzipSync:()=>AEt,hasSubscribers:()=>o_t,homedir:()=>mEt,hostname:()=>gEt,inflateSync:()=>kEt,inherits:()=>GEt,inspect:()=>K2,isAbsolute:()=>Twt,isBuiltin:()=>LEt,isDeepStrictEqual:()=>KEt,isIP:()=>x_t,isIPv4:()=>y_t,isIPv6:()=>h_t,isMainThread:()=>c_t,join:()=>gwt,lookup:()=>XEt,mkdir:()=>eEt,mkdirSync:()=>Gwt,monitorEventLoopDelay:()=>t_t,normalize:()=>Ewt,ok:()=>MEt,openSync:()=>Bwt,parentPort:()=>l_t,parse:()=>UEt,pathToFileURL:()=>jEt,performance:()=>QEt,pipeline:()=>Pwt,platform:()=>pEt,posix:()=>wwt,promises:()=>awt,promisify:()=>VEt,randomBytes:()=>lwt,randomUUID:()=>uwt,readFile:()=>Zwt,readFileSync:()=>Nwt,readdir:()=>rEt,readdirSync:()=>qwt,realpathSync:()=>Fwt,relative:()=>bwt,release:()=>TEt,rename:()=>sEt,renameSync:()=>Wwt,request:()=>SEt,resolve:()=>hwt,rm:()=>iEt,rmSync:()=>Jwt,rmdirSync:()=>Kwt,sep:()=>Swt,serialize:()=>s_t,setInterval:()=>E_t,setTimeout:()=>S_t,spawn:()=>aEt,stat:()=>tEt,statSync:()=>Vwt,strict:()=>OEt,tmpdir:()=>fEt,toUSVString:()=>JEt,totalmem:()=>xEt,type:()=>vEt,types:()=>YEt,unlink:()=>nEt,unlinkSync:()=>Hwt,webcrypto:()=>dwt,workerData:()=>u_t,writeFile:()=>Qwt,writeFileSync:()=>Dwt});var Xo,ai,iwt,awt,_Ae,cwt,lwt,uwt,dwt,pwt,mwt,fwt,gwt,hwt,ywt,xwt,vwt,bwt,Twt,Swt,wwt,Ewt,_wt,kwt,kAe,CAe,Cwt,Rwt,Awt,Iwt,Pwt,Mwt,Owt,Nwt,Dwt,Lwt,Uwt,Fwt,$wt,Bwt,zwt,jwt,Gwt,Vwt,qwt,Hwt,Wwt,Kwt,Jwt,Ywt,Xwt,Zwt,Qwt,eEt,tEt,rEt,nEt,oEt,sEt,iEt,aEt,cEt,lEt,uEt,dEt,pEt,mEt,fEt,gEt,hEt,yEt,xEt,vEt,bEt,TEt,SEt,wEt,EEt,_Et,kEt,CEt,REt,AEt,NZ,DZ,IEt,PEt,MEt,OEt,NEt,DEt,LEt,UEt,FEt,$Et,BEt,zEt,jEt,GEt,VEt,RAe,qEt,K2,HEt,WEt,KEt,JEt,YEt,AAe,W2,XEt,ZEt,QEt,e_t,t_t,r_t,n_t,o_t,s_t,i_t,a_t,c_t,l_t,u_t,d_t,p_t,m_t,f_t,g_t,h_t,y_t,x_t,v_t,b_t,T_t,IAe,S_t,w_t,E_t,__t,k_t,Vv=k(()=>{Xo=()=>{},ai=async()=>{},iwt={},awt={readFile:ai,writeFile:ai,mkdir:ai,stat:ai,readdir:ai,unlink:ai,access:ai,rm:ai,rename:ai},_Ae=r=>{let e=[];return{update(t){return e.push(typeof t=="string"?new W2().encode(t):t),this},digest(t){let n=0;for(let s of e)for(let i=0;i<s.length;i++)n=(n<<5)-n+s[i]|0;let o=(n>>>0).toString(16).padStart(8,"0");return t==="hex"?o:t==="base64"?btoa(o):o}}},cwt=(r,e)=>_Ae(r),lwt=r=>new Uint8Array(r||32),uwt=()=>globalThis.crypto?.randomUUID?.()||Math.random().toString(36),dwt=globalThis.crypto,pwt=()=>{throw new Error("[NeuroLink:browser] fs.appendFileSync is not supported in browser runtime \u2014 use server-side execution")},mwt=()=>{throw new Error("[NeuroLink:browser] fs.cpSync is not supported in browser runtime \u2014 use server-side execution")},fwt=()=>({listen:Xo,close:Xo,on:Xo}),gwt=(...r)=>r.join("/"),hwt=(...r)=>r.join("/"),ywt=r=>r||"",xwt=r=>r?.split?.("/")?.pop?.()||"",vwt=r=>{let e=r?.match?.(/\.[^.]+$/);return e?e[0]:""},bwt=(r,e)=>e||"",Twt=()=>!1,Swt="/",wwt={normalize:r=>r,join:(...r)=>r.join("/"),resolve:(...r)=>r.join("/"),sep:"/"},Ewt=r=>r,_wt=class{on(){return this}off(){return this}emit(){return this}once(){return this}removeListener(){return this}addListener(){return this}},kwt=class{getStore(){}run(r,e,...t){return e(...t)}enterWith(){}disable(){}},kAe=class{pipe(){return this}on(){return this}read(){return null}push(){}destroy(){}},CAe=class{write(){return!0}end(){}on(){return this}destroy(){}},Cwt=class{push(){}on(){return this}},Rwt=class{on(){return this}},Awt=class{pipe(){return this}on(){return this}},Iwt=globalThis.ReadableStream||class{},Pwt=Xo,Mwt=Xo,Owt=()=>!1,Nwt=()=>"",Dwt=Xo,Lwt=Xo,Uwt=ai,Fwt=r=>r,$wt=Xo,Bwt=()=>0,zwt=Xo,jwt=()=>({}),Gwt=Xo,Vwt=()=>({}),qwt=()=>[],Hwt=Xo,Wwt=Xo,Kwt=Xo,Jwt=Xo,Ywt=()=>new CAe,Xwt=()=>new kAe,Zwt=ai,Qwt=ai,eEt=ai,tEt=ai,rEt=ai,nEt=ai,oEt=ai,sEt=ai,iEt=ai,aEt=()=>({on:Xo,stdout:{on:Xo},stderr:{on:Xo},kill:Xo}),cEt=(r,e)=>e?.(null,"",""),lEt=()=>"",uEt=(r,e,t)=>{typeof e=="function"?e(null,"",""):t?.(null,"","")},dEt=()=>"",pEt="browser",mEt=()=>"/",fEt=()=>"/tmp",gEt=()=>"browser",hEt=()=>[{}],yEt=()=>0,xEt=()=>0,vEt=()=>"Browser",bEt=()=>"wasm",TEt=()=>"0",SEt=()=>({}),wEt=()=>({}),EEt=()=>({}),_Et=()=>({}),kEt=()=>new Uint8Array,CEt=()=>new Uint8Array,REt=()=>new Uint8Array,AEt=()=>new Uint8Array,NZ=(r,e)=>e?.(null,r),DZ=(r,e)=>e?.(null,r),IEt=()=>({}),PEt=()=>({}),MEt=Xo,OEt={},NEt=()=>()=>({}),DEt=[],LEt=()=>!1,UEt=r=>({pathname:r||"",hostname:"",protocol:"",search:"",hash:""}),FEt=()=>"",$Et=globalThis.URL,BEt=globalThis.URLSearchParams,zEt=r=>typeof r=="string"?r.replace("file://",""):r,jEt=r=>new globalThis.URL("file://"+r),GEt=(r,e)=>{e&&(r.super_=e,Object.setPrototypeOf(r.prototype,e.prototype))},VEt=r=>(...e)=>new Promise((t,n)=>r(...e,(o,s)=>o?n(o):t(s))),RAe=r=>{let e=(...t)=>{};return e.enabled=!1,e},qEt=RAe,K2=r=>{try{return JSON.stringify(r,null,2)}catch{return String(r)}};K2.custom=Symbol.for("nodejs.util.inspect.custom");K2.colors={};K2.styles={};HEt=r=>r,WEt=r=>(...e)=>{let t=e.pop();r(...e).then(n=>t(null,n)).catch(t)},KEt=(r,e)=>JSON.stringify(r)===JSON.stringify(e),JEt=r=>String(r),YEt={isPromise:r=>r instanceof Promise,isDate:r=>r instanceof Date,isRegExp:r=>r instanceof RegExp,isNativeError:r=>r instanceof Error,isArrayBuffer:r=>r instanceof ArrayBuffer,isTypedArray:r=>ArrayBuffer.isView(r),isUint8Array:r=>r instanceof Uint8Array,isProxy:()=>!1},AAe=globalThis.TextDecoder,W2=globalThis.TextEncoder,XEt=(r,e)=>e?.(null,"127.0.0.1",4),ZEt=class{},QEt=globalThis.performance||{now:()=>Date.now()},e_t=class{observe(){}disconnect(){}},t_t=()=>({enable:Xo,disable:Xo,percentile:()=>0}),r_t=()=>({}),n_t=class{},o_t=()=>!1,s_t=()=>new Uint8Array,i_t=Xo,a_t=class{},c_t=!0,l_t=null,u_t=null,d_t=()=>({}),p_t=class{},m_t=class{},f_t=globalThis.Buffer||class extends Uint8Array{static from(e,t){if(typeof e=="string"){let n=(t||"utf8").toLowerCase();if(n==="base64"){let o=atob(e),s=new Uint8Array(o.length);for(let i=0;i<o.length;i++)s[i]=o.charCodeAt(i);return s}if(n==="hex"){let o=new Uint8Array(e.length/2);for(let s=0;s<e.length;s+=2)o[s/2]=parseInt(e.substr(s,2),16);return o}return new W2().encode(e)}return new Uint8Array(e)}static alloc(e){return new Uint8Array(e)}static isBuffer(e){return e instanceof Uint8Array}static concat(e){let t=e.reduce((s,i)=>s+i.length,0),n=new Uint8Array(t),o=0;for(let s of e)n.set(s,o),o+=s.length;return n}static byteLength(e,t){return t==="base64"?Math.ceil(e.length*3/4):new W2().encode(e).length}toString(e){let t=(e||"utf8").toLowerCase();if(t==="hex")return Array.from(new Uint8Array(this.buffer,this.byteOffset,this.byteLength)).map(n=>n.toString(16).padStart(2,"0")).join("");if(t==="base64"){let n="";for(let o=0;o<this.length;o++)n+=String.fromCharCode(this[o]);return btoa(n)}return new AAe().decode(this)}},g_t={F_OK:0,R_OK:4,W_OK:2,X_OK:1},h_t=()=>!1,y_t=()=>!1,x_t=()=>0,v_t=class{},b_t=class{},T_t=async()=>new ArrayBuffer(0),IAe=r=>({[Symbol.toPrimitive](){return r},ref(){return this},unref(){return this},hasRef(){return!1},refresh(){return this},close(){}}),S_t=(...r)=>IAe(globalThis.setTimeout(...r)),w_t=globalThis.clearTimeout,E_t=(...r)=>IAe(globalThis.setInterval(...r)),__t=globalThis.clearInterval,k_t=class{constructor(r){this.type=r}toString(){return this.type}}});var J2,KI,LZ=k(()=>{"use strict";J2={"gpt-4o":{inputPricePerMillion:2.5,outputPricePerMillion:10,cachedInputPricePerMillion:1.25},"gpt-4o-mini":{inputPricePerMillion:.15,outputPricePerMillion:.6,cachedInputPricePerMillion:.075},o1:{inputPricePerMillion:15,outputPricePerMillion:60,cachedInputPricePerMillion:7.5},"o1-mini":{inputPricePerMillion:3,outputPricePerMillion:12,cachedInputPricePerMillion:1.5},"claude-sonnet-4-20250514":{inputPricePerMillion:3,outputPricePerMillion:15,cachedInputPricePerMillion:.3},"claude-3-5-sonnet-20241022":{inputPricePerMillion:3,outputPricePerMillion:15,cachedInputPricePerMillion:.3},"claude-3-5-haiku-20241022":{inputPricePerMillion:.8,outputPricePerMillion:4,cachedInputPricePerMillion:.08},"gemini-2.5-flash":{inputPricePerMillion:.15,outputPricePerMillion:.6},"gemini-2.5-pro":{inputPricePerMillion:1.25,outputPricePerMillion:10},"gemini-2.0-flash-exp":{inputPricePerMillion:.15,outputPricePerMillion:.6},"mistral-large-latest":{inputPricePerMillion:2,outputPricePerMillion:6},"mistral-small-latest":{inputPricePerMillion:.2,outputPricePerMillion:.6}},KI=class r{stats={totalInputTokens:0,totalOutputTokens:0,totalTokens:0,cacheReadTokens:0,cacheCreationTokens:0,reasoningTokens:0,totalCost:0,byProvider:new Map,byModel:new Map,bySpanType:new Map};customPricing=new Map;setObservabilityModelPricing(e,t){this.customPricing.set(e,t)}updatePricing(e,t){this.customPricing.set(e,t)}loadPricingFromConfig(e){for(let[t,n]of Object.entries(e))this.customPricing.set(t,n)}getModelPricing(e){return this.customPricing.get(e)??J2[e]}getAllPricing(){let e={...J2},t=Array.from(this.customPricing.entries());for(let[n,o]of t)e[n]=o;return e}removeCustomPricing(e){return this.customPricing.delete(e)}trackSpan(e){let t=e.attributes,n=t["ai.tokens.input"]??0,o=t["ai.tokens.output"]??0,s=t["ai.tokens.total"]??n+o,i=t["ai.tokens.cache_read"]??0,a=t["ai.tokens.cache_creation"]??0,c=t["ai.tokens.reasoning"]??0,l=t["ai.cost.total"]??this.calculateCost(t,n,o,i);this.stats.totalInputTokens+=n,this.stats.totalOutputTokens+=o,this.stats.totalTokens+=s,this.stats.cacheReadTokens+=i,this.stats.cacheCreationTokens+=a,this.stats.reasoningTokens+=c,this.stats.totalCost+=l;let u=t["ai.provider"];if(u){let f=this.stats.byProvider.get(u)??{provider:u,inputTokens:0,outputTokens:0,totalTokens:0,cost:0,requestCount:0};f.inputTokens+=n,f.outputTokens+=o,f.totalTokens+=s,f.cost+=l,f.requestCount+=1,this.stats.byProvider.set(u,f)}let d=t["ai.model"];if(d){let f=this.stats.byModel.get(d)??{model:d,provider:u??"unknown",inputTokens:0,outputTokens:0,totalTokens:0,cost:0,requestCount:0,avgTokensPerRequest:0};f.inputTokens+=n,f.outputTokens+=o,f.totalTokens+=s,f.cost+=l,f.requestCount+=1,f.avgTokensPerRequest=f.totalTokens/f.requestCount,this.stats.byModel.set(d,f)}let p=this.stats.bySpanType.get(e.type)??0;this.stats.bySpanType.set(e.type,p+s)}calculateCost(e,t,n,o=0){let s=e["ai.model"];if(!s)return 0;let i=this.customPricing.get(s)??J2[s];if(!i)return 0;let c=(t-o)/1e6*i.inputPricePerMillion,l=o/1e6*(i.cachedInputPricePerMillion??i.inputPricePerMillion),u=n/1e6*i.outputPricePerMillion;return c+l+u}trackUsage(e){let t=e.promptTokens??0,n=e.completionTokens??0,o=e.totalTokens??t+n;this.stats.totalInputTokens+=t,this.stats.totalOutputTokens+=n,this.stats.totalTokens+=o;let s=0;if(e.model){let i=this.customPricing.get(e.model)??J2[e.model];i&&(s=t/1e6*i.inputPricePerMillion+n/1e6*i.outputPricePerMillion)}if(this.stats.totalCost+=s,e.provider){let i=this.stats.byProvider.get(e.provider)??{provider:e.provider,inputTokens:0,outputTokens:0,totalTokens:0,cost:0,requestCount:0};i.inputTokens+=t,i.outputTokens+=n,i.totalTokens+=o,i.cost+=s,i.requestCount+=1,this.stats.byProvider.set(e.provider,i)}if(e.model){let i=this.stats.byModel.get(e.model)??{model:e.model,provider:e.provider??"unknown",inputTokens:0,outputTokens:0,totalTokens:0,cost:0,requestCount:0,avgTokensPerRequest:0};i.inputTokens+=t,i.outputTokens+=n,i.totalTokens+=o,i.cost+=s,i.requestCount+=1,i.avgTokensPerRequest=i.totalTokens/i.requestCount,this.stats.byModel.set(e.model,i)}}getStats(){return{...this.stats}}getStatsForWindow(e){let t=new r;for(let[n,o]of this.customPricing)t.setObservabilityModelPricing(n,o);for(let n of e)t.trackSpan(n);return t.getStats()}reset(){this.stats={totalInputTokens:0,totalOutputTokens:0,totalTokens:0,cacheReadTokens:0,cacheCreationTokens:0,reasoningTokens:0,totalCost:0,byProvider:new Map,byModel:new Map,bySpanType:new Map}}toJSON(){return{totalInputTokens:this.stats.totalInputTokens,totalOutputTokens:this.stats.totalOutputTokens,totalTokens:this.stats.totalTokens,cacheReadTokens:this.stats.cacheReadTokens,cacheCreationTokens:this.stats.cacheCreationTokens,reasoningTokens:this.stats.reasoningTokens,totalCost:this.stats.totalCost,byProvider:Object.fromEntries(this.stats.byProvider),byModel:Object.fromEntries(this.stats.byModel),bySpanType:Object.fromEntries(this.stats.bySpanType)}}formatCost(e,t="USD"){return new Intl.NumberFormat("en-US",{style:"currency",currency:t,minimumFractionDigits:4}).format(e)}getSummary(){let e=this.stats;return["Token Usage Summary:",` Input tokens: ${e.totalInputTokens.toLocaleString()}`,` Output tokens: ${e.totalOutputTokens.toLocaleString()}`,` Total tokens: ${e.totalTokens.toLocaleString()}`,` Total cost: ${this.formatCost(e.totalCost)}`,e.cacheReadTokens>0?` Cache read tokens: ${e.cacheReadTokens.toLocaleString()}`:"",e.reasoningTokens>0?` Reasoning tokens: ${e.reasoningTokens.toLocaleString()}`:""].filter(Boolean).join(`
159
+ `}static extractAnalyticsContext(e){return{hasUserId:!!e.userId,hasSessionId:!!e.sessionId,hasUserRole:!!e.userRole,hasOrgContext:!!e.organizationId,contextKeys:Object.keys(e),contextSize:JSON.stringify(e).length}}static extractEvaluationContext(e){return{userRole:e.userRole||"unknown",applicationContext:e.applicationContext?.name||"unknown",organizationContext:e.organizationId||"unknown",hasPreferences:!!e.userPreferences}}},WCe=class r{static convertBusinessContext(e,t,n={}){let{preserveLegacyFields:o=!1,validateDomainData:s=!0,includeMetadata:i=!0}=n;return{sessionId:e.sessionId,userId:e.userId,config:{domainType:t,providerConfig:{token:e.apiToken||e.authToken||e.accessToken,endpoint:e.apiEndpoint||e.serviceUrl,provider:r.inferProvider(e)},platformConfig:{type:e.platformType||"generic",url:e.platformUrl||e.serviceUrl,id:e.platformId||e.serviceId,integrations:e.platformIntegrations||[]},operationalConfig:{demoMode:e.enableDemoMode||!1,environment:e.environment||"production",region:e.region,features:e.enabledFeatures||[]},customData:{...o?{entityId:e.entityId||e.organizationId,departmentId:e.departmentId,projectId:e.projectId}:{},...r.extractCustomData(e)}},metadata:i?{convertedFrom:"legacy-business-context",conversionTime:Date.now(),originalKeys:Object.keys(e),domainType:t}:void 0}}static createDomainContext(e,t,n={}){return{sessionId:n.sessionId||`session_${Date.now()}`,userId:n.userId,config:{domainType:e,customData:t},metadata:{source:"domain-context-factory",createdAt:Date.now(),domainType:e}}}static inferProvider(e){return e.apiToken||e.authToken?"api-provider":e.serviceUrl||e.endpoint?"service-provider":"generic-provider"}static extractCustomData(e){let t=TZ.getFrameworkFieldsConfig(),n;t.overrideFields?n=new Set(t.overrideFields):n=new Set([...t.defaultFields,...t.additionalFields||[]]),t.includeFields&&t.includeFields.forEach(s=>n.delete(s));let o={};return Object.entries(e).forEach(([s,i])=>{n.has(s)||(o[s]=i)}),o}}});var Tc,JCe=k(()=>{"use strict";Tc=class extends Error{constructor(t,n,o){super(t);this.code=n;this.details=o;this.name="ConversationMemoryError"}code;details}});var YCe=k(()=>{"use strict"});var XCe=k(()=>{"use strict"});function oRe(r){if(typeof r!="string"||r.length===0||r.length>XSt)return;let e=r.toLowerCase(),t=e.indexOf("models",0);for(;t!==-1;){let n=t+6;for(;n<r.length&&/\s/.test(r[n]);)n++;if(r[n]!=="="){t=e.indexOf("models",t+1);continue}for(n++;n<r.length&&/\s/.test(r[n]);)n++;if(r[n]!=="["){t=e.indexOf("models",t+1);continue}let o=n,s=r.indexOf("]",o+1);if(s===-1)return;let a=r.slice(o+1,s).split(",").map(c=>c.trim().replace(/^['"]|['"]$/g,"")).filter(c=>c.length>0);return a.length>0?a:void 0}}function sRe(r){let e=r.toLowerCase();return e.includes("team")&&e.includes("not allowed")||e.includes("team can only access")||/not\s+allowed\s+to\s+access\s+(this\s+)?model/i.test(r)}var iE,qe,Mt,aE,zt,er,Zt,ny,ZCe,QCe,eRe,tRe,rRe,nRe,go,qI,um,XSt,iRe=k(()=>{"use strict";iE=class extends Error{constructor(e){super(e),this.name=this.constructor.name}},qe=class extends iE{constructor(t,n){super(n?`[${n}] ${t}`:t);this.provider=n}provider},Mt=class extends qe{constructor(e,t){super(e,t)}},aE=class extends qe{constructor(e,t){super(e,t)}},zt=class extends qe{constructor(e,t){super(e,t)}},er=class extends qe{constructor(e,t){super(e,t)}},Zt=class extends qe{constructor(e,t){super(e,t)}},ny=class extends iE{constructor(t,n){super(t);this.code=n;this.name="OAuthError"}code},ZCe=class extends ny{constructor(e){super(e,"CONFIGURATION_ERROR"),this.name="OAuthConfigurationError"}},QCe=class extends ny{constructor(t,n){super(t,"TOKEN_EXCHANGE_ERROR");this.statusCode=n;this.name="OAuthTokenExchangeError"}statusCode},eRe=class extends ny{constructor(t,n){super(t,"TOKEN_REFRESH_ERROR");this.statusCode=n;this.name="OAuthTokenRefreshError"}statusCode},tRe=class extends ny{constructor(e){super(e,"TOKEN_VALIDATION_ERROR"),this.name="OAuthTokenValidationError"}},rRe=class extends ny{constructor(t,n){super(t,"TOKEN_REVOCATION_ERROR");this.statusCode=n;this.name="OAuthTokenRevocationError"}statusCode},nRe=class extends ny{constructor(e){super(e,"CALLBACK_SERVER_ERROR"),this.name="OAuthCallbackServerError"}},go=class extends iE{constructor(t,n="STORAGE_ERROR"){super(t);this.code=n;this.name="TokenStoreError"}code},qI=class extends iE{model;tier;requiredTier;constructor(e,t,n){super(`Model "${e}" is not available for tier "${t}". Required tier: "${n}" or higher.`),this.name="ModelAccessError",this.model=e,this.tier=t,this.requiredTier=n}},um=class extends qe{requestedModel;allowedModels;code="MODEL_ACCESS_DENIED";constructor(e,t={}){super(e,t.provider),this.name="ModelAccessDeniedError",this.requestedModel=t.requestedModel,this.allowedModels=t.allowedModels}},XSt=1e4});var aRe=k(()=>{"use strict"});var cRe=k(()=>{"use strict"});var lRe=k(()=>{"use strict"});var uRe=k(()=>{"use strict"});var oy,dRe=k(()=>{"use strict";oy={TINY_MAX:10240,SMALL_MAX:102400,MEDIUM_MAX:5242880,LARGE_MAX:104857600,HUGE_MAX:2147483648}});var pRe=k(()=>{"use strict"});var mRe=k(()=>{"use strict"});var fRe=k(()=>{"use strict"});var gRe=k(()=>{"use strict"});var hRe=k(()=>{"use strict"});var yRe=k(()=>{"use strict"});var xRe=k(()=>{"use strict"});var vRe=k(()=>{"use strict"});var bRe=k(()=>{"use strict"});var ZSt,rgn,TRe=k(()=>{"use strict";ao();ZSt=m.object({id:m.string(),displayName:m.string(),capabilities:m.array(m.string()),deprecated:m.boolean(),pricing:m.object({input:m.number(),output:m.number()}),contextWindow:m.number(),releaseDate:m.string()}),rgn=m.object({version:m.string(),lastUpdated:m.string(),models:m.record(m.string(),m.record(m.string(),ZSt)),aliases:m.record(m.string(),m.string()).optional(),defaults:m.record(m.string(),m.string()).optional()})});function ogn(r){return r.type==="text"}function sgn(r){return r.type==="image"}function ign(r){return r.type==="csv"}function agn(r){return r.type==="pdf"}function cgn(r){return r.type==="audio"}function lgn(r){return r.type==="video"}function QSt(r){if(!r||typeof r!="object")return!1;let e=r;if(typeof e.prompt!="string"||!e.prompt)return!1;let{image:t}=e;if(!t)return!1;if(Buffer.isBuffer(t)||typeof t=="string")return!0;if(typeof t=="object"&&"data"in t){let n=t.data;return Buffer.isBuffer(n)||typeof n=="string"}return!1}function ugn(r){if(typeof r!="object"||r===null)return!1;let e=r,t=n=>Array.isArray(n)&&n.length>0;return!!(t(e.images)||t(e.csvFiles)||t(e.pdfFiles)||t(e.files)||t(e.content)||t(e.audioFiles)||t(e.videoFiles)||Array.isArray(e.segments)&&e.segments.length>0&&e.segments.every(QSt))}function dgn(r){return Array.isArray(r)}var SRe=k(()=>{"use strict"});var wRe=k(()=>{"use strict"});var ERe=k(()=>{"use strict"});function ggn(r){return/^[0-9A-Fa-f]{6}$/.test(r)}function hgn(r){return r.startsWith("#")?r.slice(1):r}var mgn,fgn,SZ,_Re=k(()=>{"use strict";mgn=5,fgn=50,SZ={"16:9":{width:10,height:5.625},"4:3":{width:10,height:7.5}}});var H2,kRe,wZ=k(()=>{"use strict";H2=(R=>(R.DOWNLOAD_FAILED="DOWNLOAD_FAILED",R.DOWNLOAD_TIMEOUT="DOWNLOAD_TIMEOUT",R.DOWNLOAD_AUTH_FAILED="DOWNLOAD_AUTH_FAILED",R.NETWORK_ERROR="NETWORK_ERROR",R.FILE_NOT_FOUND="FILE_NOT_FOUND",R.RATE_LIMITED="RATE_LIMITED",R.FILE_TOO_LARGE="FILE_TOO_LARGE",R.UNSUPPORTED_TYPE="UNSUPPORTED_TYPE",R.INVALID_FORMAT="INVALID_FORMAT",R.INVALID_MIME_TYPE="INVALID_MIME_TYPE",R.INVALID_MAGIC_BYTES="INVALID_MAGIC_BYTES",R.CORRUPTED_FILE="CORRUPTED_FILE",R.INVALID_STRUCTURE="INVALID_STRUCTURE",R.PROCESSING_FAILED="PROCESSING_FAILED",R.PARSING_FAILED="PARSING_FAILED",R.ENCODING_ERROR="ENCODING_ERROR",R.EXTRACTION_FAILED="EXTRACTION_FAILED",R.DECOMPRESSION_FAILED="DECOMPRESSION_FAILED",R.SECURITY_VALIDATION_FAILED="SECURITY_VALIDATION_FAILED",R.XXE_DETECTED="XXE_DETECTED",R.XSS_DETECTED="XSS_DETECTED",R.CODE_EXECUTION_DETECTED="CODE_EXECUTION_DETECTED",R.ZIP_BOMB_DETECTED="ZIP_BOMB_DETECTED",R.UNKNOWN_ERROR="UNKNOWN_ERROR",R))(H2||{}),kRe={DOWNLOAD_FAILED:{message:"Failed to download the file from the source.",userMessage:"We couldn't download your file.",suggestedAction:"Please try uploading the file again. If the problem persists, the file may have been deleted or access revoked.",retryable:!0},DOWNLOAD_TIMEOUT:{message:"File download timed out.",userMessage:"The download took too long and was cancelled.",suggestedAction:"This usually happens with very large files or slow connections. Try re-uploading a smaller version or check your network connection.",retryable:!0},DOWNLOAD_AUTH_FAILED:{message:"Authentication failed when accessing the file.",userMessage:"We don't have permission to access this file.",suggestedAction:"Please check the file permissions and ensure it's accessible, then try again.",retryable:!1},NETWORK_ERROR:{message:"Network error while downloading the file.",userMessage:"A network error occurred while downloading.",suggestedAction:"This is usually temporary. Please try uploading the file again.",retryable:!0},FILE_NOT_FOUND:{message:"The file could not be found at the specified location.",userMessage:"The file could not be found.",suggestedAction:"The file may have been moved or deleted. Please re-upload the file.",retryable:!1},RATE_LIMITED:{message:"Request was rate limited by the server.",userMessage:"Too many requests in a short time.",suggestedAction:"Please wait a few seconds and try again.",retryable:!0},FILE_TOO_LARGE:{message:"File exceeds the maximum allowed size.",userMessage:"This file is too large to process.",suggestedAction:"Try compressing the file or splitting it into smaller parts. Consider reducing image quality or removing unnecessary content.",retryable:!1},UNSUPPORTED_TYPE:{message:"The file type is not supported for processing.",userMessage:"This file type is not supported.",suggestedAction:"Please convert your file to a supported format and try again.",retryable:!1},INVALID_FORMAT:{message:"The file format is invalid or malformed.",userMessage:"This file appears to be in an invalid format.",suggestedAction:"Please ensure the file is properly saved and not corrupted, then try again.",retryable:!1},INVALID_MIME_TYPE:{message:"File MIME type doesn't match the expected format.",userMessage:"The file type doesn't match its extension.",suggestedAction:"Please ensure the file extension matches its actual content type and try again.",retryable:!1},INVALID_MAGIC_BYTES:{message:"File magic bytes don't match the expected file type.",userMessage:"This file doesn't appear to be a valid file of the expected type.",suggestedAction:"The file may be corrupted or saved in the wrong format. Try re-saving the file in the correct format.",retryable:!0},CORRUPTED_FILE:{message:"File appears to be corrupted or damaged.",userMessage:"This file appears to be corrupted or invalid.",suggestedAction:"The file structure is invalid. Try re-downloading from the original source or re-creating the file.",retryable:!1},INVALID_STRUCTURE:{message:"File internal structure is invalid.",userMessage:"The file has an invalid internal structure.",suggestedAction:"The file format is correct but the content is malformed. Try validating the file with a format checker or re-exporting from the original application.",retryable:!1},PROCESSING_FAILED:{message:"Failed to process the file content.",userMessage:"We couldn't process this file.",suggestedAction:"Please try again. If the problem persists, the file may be in an unsupported variant.",retryable:!0},PARSING_FAILED:{message:"Failed to parse the file content.",userMessage:"We couldn't read the contents of this file.",suggestedAction:"The file structure may be invalid. Try validating the file with a format checker or re-creating the file.",retryable:!1},ENCODING_ERROR:{message:"Text encoding error detected.",userMessage:"We couldn't decode the text in this file.",suggestedAction:"Try re-saving the file with UTF-8 encoding. Most modern text editors have this option in 'Save As' settings.",retryable:!1},EXTRACTION_FAILED:{message:"Failed to extract content from the file.",userMessage:"We couldn't extract the content from this file.",suggestedAction:"The file may be password-protected, corrupted, or use an unsupported variant. Try re-saving without protection.",retryable:!1},DECOMPRESSION_FAILED:{message:"Failed to decompress the file content.",userMessage:"We couldn't decompress this file.",suggestedAction:"The file may be corrupted or use an unsupported compression method. Try re-uploading or using a different file format.",retryable:!0},SECURITY_VALIDATION_FAILED:{message:"File failed security validation.",userMessage:"This file contains content that is blocked for security reasons.",suggestedAction:"Please remove the problematic content and try again. If you believe this is a legitimate file, please contact support.",retryable:!1},XXE_DETECTED:{message:"XML External Entity (XXE) attack pattern detected.",userMessage:"This XML file contains DOCTYPE or ENTITY declarations that could pose security risks.",suggestedAction:"Please remove DOCTYPE and ENTITY declarations from the XML file. Most XML files don't need these for basic data storage.",retryable:!1},XSS_DETECTED:{message:"Cross-site scripting (XSS) attack pattern detected.",userMessage:"This file contains script tags or event handlers that could pose security risks.",suggestedAction:"Please remove <script> tags and event handlers (onclick, onerror, etc.) from the file.",retryable:!1},CODE_EXECUTION_DETECTED:{message:"Potentially malicious code execution pattern detected.",userMessage:"This file contains code execution tags that are not allowed.",suggestedAction:"Please remove custom object/function tags and use standard data structures only.",retryable:!1},ZIP_BOMB_DETECTED:{message:"Zip bomb or decompression bomb pattern detected.",userMessage:"This file has an unusually high compression ratio that could indicate a security threat.",suggestedAction:"If this is a legitimate file, try re-saving it without extreme compression. Otherwise, please verify the file source.",retryable:!1},UNKNOWN_ERROR:{message:"An unexpected error occurred.",userMessage:"An unexpected error occurred while processing your file.",suggestedAction:"Please try again. If the problem persists, contact support.",retryable:!0}}});var CRe,vgn,bgn,Tgn,Sgn,wgn,RRe=k(()=>{"use strict";wZ();CRe={maxRetries:3,baseDelayMs:1e3,maxDelayMs:1e4},vgn=3e4,bgn=10,Tgn=3e4,Sgn=10,wgn={SVG:5,IMAGE:10,PDF:20,CSV:30,MARKDOWN:40,JSON:50,YAML:60,XML:70,HTML:80,EXCEL:90,DOC:95,WORD:100,TEXT:110,SOURCE_CODE:120,CONFIG:130,RTF:140,OPENDOCUMENT:150,VIDEO:160,AUDIO:170,ARCHIVE:180}});function kgn(r){if(r==null||typeof r!="object")return!1;let e=r,t=["api_key","oauth"],n=["free","pro","max","max_5","max_20","api"];if(e.authMethod!==void 0&&typeof e.authMethod=="string"&&t.includes(e.authMethod)||e.subscriptionTier!==void 0&&typeof e.subscriptionTier=="string"&&n.includes(e.subscriptionTier)||e.oauthConfig!==void 0&&typeof e.oauthConfig=="object"&&e.oauthConfig!==null)return!0;if(e.authConfig!==void 0&&typeof e.authConfig=="object"&&e.authConfig!==null){let o=e.authConfig;if(o.method!==void 0&&typeof o.method=="string"&&t.includes(o.method))return!0}return!1}var EZ,Cgn,Rgn,ARe=k(()=>{"use strict";EZ={LATEST_OPENAI:"gpt-4o",FASTEST_OPENAI:"gpt-4o-mini",LATEST_ANTHROPIC:"claude-3-5-sonnet-20241022",FASTEST_ANTHROPIC:"claude-3-5-haiku-20241022",LATEST_GOOGLE:"gemini-2.5-pro",FASTEST_GOOGLE:"gemini-2.5-flash",BEST_CODING:"claude-3-5-sonnet-20241022",BEST_ANALYSIS:"gemini-2.5-pro",BEST_CREATIVE:"claude-3-5-sonnet-20241022",BEST_VALUE:"gemini-2.5-flash"},Cgn=EZ,Rgn=[{provider:"bedrock",models:["anthropic.claude-3-7-sonnet-20250219-v1:0","anthropic.claude-3-5-sonnet-20241022-v1:0"]},{provider:"vertex",models:["claude-sonnet-4@20250514","gemini-2.5-flash"]},{provider:"openai",models:["gpt-4o","gpt-4o-mini"]}]});var IRe=k(()=>{"use strict"});var PRe=k(()=>{"use strict"});var MRe=k(()=>{"use strict"});var ORe=k(()=>{"use strict"});var an,co,en,NRe=k(()=>{"use strict";an={CONFIG:"CONFIG",VALIDATION:"VALIDATION",EXECUTION:"EXECUTION",EXTERNAL:"EXTERNAL",RATE_LIMIT:"RATE_LIMIT",AUTHENTICATION:"AUTHENTICATION",AUTHORIZATION:"AUTHORIZATION",STREAMING:"STREAMING",WEBSOCKET:"WEBSOCKET"},co={LOW:"LOW",MEDIUM:"MEDIUM",HIGH:"HIGH",CRITICAL:"CRITICAL"},en={INVALID_CONFIG:"SERVER_ADAPTER_INVALID_CONFIG",MISSING_DEPENDENCY:"SERVER_ADAPTER_MISSING_DEPENDENCY",FRAMEWORK_INIT_FAILED:"SERVER_ADAPTER_FRAMEWORK_INIT_FAILED",ROUTE_NOT_FOUND:"SERVER_ADAPTER_ROUTE_NOT_FOUND",ROUTE_CONFLICT:"SERVER_ADAPTER_ROUTE_CONFLICT",INVALID_ROUTE:"SERVER_ADAPTER_INVALID_ROUTE",HANDLER_ERROR:"SERVER_ADAPTER_HANDLER_ERROR",TIMEOUT:"SERVER_ADAPTER_TIMEOUT",MIDDLEWARE_ERROR:"SERVER_ADAPTER_MIDDLEWARE_ERROR",RATE_LIMIT_EXCEEDED:"SERVER_ADAPTER_RATE_LIMIT_EXCEEDED",AUTH_REQUIRED:"SERVER_ADAPTER_AUTH_REQUIRED",AUTH_INVALID:"SERVER_ADAPTER_AUTH_INVALID",FORBIDDEN:"SERVER_ADAPTER_FORBIDDEN",STREAM_ERROR:"SERVER_ADAPTER_STREAM_ERROR",STREAM_ABORTED:"SERVER_ADAPTER_STREAM_ABORTED",WEBSOCKET_ERROR:"SERVER_ADAPTER_WEBSOCKET_ERROR",WEBSOCKET_CONNECTION_FAILED:"SERVER_ADAPTER_WEBSOCKET_CONNECTION_FAILED",VALIDATION_ERROR:"SERVER_ADAPTER_VALIDATION_ERROR",SCHEMA_ERROR:"SERVER_ADAPTER_SCHEMA_ERROR",START_FAILED:"SERVER_ADAPTER_START_FAILED",STOP_FAILED:"SERVER_ADAPTER_STOP_FAILED",ALREADY_RUNNING:"SERVER_ADAPTER_ALREADY_RUNNING",NOT_RUNNING:"SERVER_ADAPTER_NOT_RUNNING"}});var DRe=k(()=>{"use strict"});var LRe=k(()=>{"use strict"});var URe=k(()=>{"use strict"});var FRe=k(()=>{"use strict"});var ho,$Re=k(()=>{"use strict";ho={enabled:!0,maxTasks:100,backend:"bullmq",mode:"isolated",timeout:12e4,maxConcurrentRuns:5,maxRunLogs:2e3,maxHistoryEntries:200,tools:!0,retry:{maxAttempts:3,backoffMs:[3e4,6e4,3e5]},storePath:".neurolink/tasks/tasks.json",logsPath:".neurolink/tasks/runs/",redis:{host:"localhost",port:6379},retention:{completedTTL:2592e6,failedTTL:6048e5,cancelledTTL:6048e5,runLogTTL:2592e6}}});var BRe=k(()=>{"use strict"});var zRe=k(()=>{"use strict"});var jRe=k(()=>{"use strict"});function Mgn(r){return typeof r=="object"&&r!==null&&"success"in r&&typeof r.success=="boolean"}function Ogn(r){return typeof r=="object"&&r!==null&&"description"in r&&"execute"in r&&typeof r.description=="string"&&typeof r.execute=="function"}var GRe=k(()=>{"use strict"});function Dgn(r){if(!r||typeof r!="object")return!1;let e=r;return Buffer.isBuffer(e.buffer)&&typeof e.format=="string"&&VRe.includes(e.format)&&typeof e.size=="number"&&e.size>=0}function Lgn(r){if(!r||typeof r!="object")return!1;let e=r;return!(e.speed!==void 0&&(typeof e.speed!="number"||e.speed<.25||e.speed>4)||e.format!==void 0&&!VRe.includes(e.format)||e.quality!==void 0&&!ewt.includes(e.quality))}var VRe,ewt,qRe=k(()=>{"use strict";VRe=["mp3","wav","ogg","opus","m4a","flac","webm","mp4","mpeg","mpga","pcm16"],ewt=["standard","hd"]});function $gn(r){if(!r||typeof r!="object")return!1;let e=r;return typeof e.text=="string"&&typeof e.confidence=="number"&&e.confidence>=0&&e.confidence<=1}function Bgn(r){if(!r||typeof r!="object")return!1;let e=r;return!(e.sampleRate!==void 0&&(typeof e.sampleRate!="number"||e.sampleRate<=0)||e.speakerCount!==void 0&&(typeof e.speakerCount!="number"||e.speakerCount<1||e.speakerCount>10))}function zgn(r){if(!r||typeof r!="object")return!1;let e=r;return(e.index===void 0||typeof e.index=="number")&&typeof e.text=="string"&&typeof e.isFinal=="boolean"}var Sc,Fgn,HRe=k(()=>{"use strict";Sc={AUDIO_EMPTY:"STT_AUDIO_EMPTY",AUDIO_TOO_LONG:"STT_AUDIO_TOO_LONG",INVALID_AUDIO_FORMAT:"STT_INVALID_AUDIO_FORMAT",LANGUAGE_NOT_SUPPORTED:"STT_LANGUAGE_NOT_SUPPORTED",TRANSCRIPTION_FAILED:"STT_TRANSCRIPTION_FAILED",PROVIDER_NOT_CONFIGURED:"STT_PROVIDER_NOT_CONFIGURED",PROVIDER_NOT_SUPPORTED:"STT_PROVIDER_NOT_SUPPORTED",STREAM_ERROR:"STT_STREAM_ERROR",STREAMING_NOT_SUPPORTED:"STT_STREAMING_NOT_SUPPORTED"},Fgn={language:"en-US",punctuation:!0,profanityFilter:!1,sampleRate:16e3}});function Ggn(r){if(!r||typeof r!="object")return!1;let e=r;return!(!e.provider||!["openai-realtime","gemini-live"].includes(e.provider)||e.timeout!==void 0&&(typeof e.timeout!="number"||e.timeout<=0)||e.vadThreshold!==void 0&&(typeof e.vadThreshold!="number"||e.vadThreshold<0||e.vadThreshold>1))}var za,WRe,KRe=k(()=>{"use strict";za={CONNECTION_FAILED:"REALTIME_CONNECTION_FAILED",SESSION_TIMEOUT:"REALTIME_SESSION_TIMEOUT",PROTOCOL_ERROR:"REALTIME_PROTOCOL_ERROR",AUDIO_STREAM_ERROR:"REALTIME_AUDIO_STREAM_ERROR",PROVIDER_NOT_CONFIGURED:"REALTIME_PROVIDER_NOT_CONFIGURED",PROVIDER_NOT_SUPPORTED:"REALTIME_PROVIDER_NOT_SUPPORTED",SESSION_ALREADY_ACTIVE:"REALTIME_SESSION_ALREADY_ACTIVE",SESSION_NOT_ACTIVE:"REALTIME_SESSION_NOT_ACTIVE",INVALID_MESSAGE:"REALTIME_INVALID_MESSAGE"},WRe={timeout:3e4,inputSampleRate:24e3,outputSampleRate:24e3,vadEnabled:!0,vadThreshold:.5,turnDetection:"server_vad"}});var twt,qgn,JRe=k(()=>{"use strict";qRe();HRe();KRe();twt={PROVIDER_NOT_FOUND:"VOICE_PROVIDER_NOT_FOUND",INVALID_CONFIGURATION:"VOICE_INVALID_CONFIGURATION",INITIALIZATION_FAILED:"VOICE_INITIALIZATION_FAILED",OPERATION_CANCELLED:"VOICE_OPERATION_CANCELLED",PROVIDER_NOT_CONFIGURED:"VOICE_PROVIDER_NOT_CONFIGURED",PROVIDER_NOT_SUPPORTED:"VOICE_PROVIDER_NOT_SUPPORTED",FEATURE_NOT_SUPPORTED:"VOICE_FEATURE_NOT_SUPPORTED",TTS_EMPTY_TEXT:"VOICE_TTS_EMPTY_TEXT",TTS_TEXT_TOO_LONG:"VOICE_TTS_TEXT_TOO_LONG",TTS_SYNTHESIS_FAILED:"VOICE_TTS_SYNTHESIS_FAILED",STT_EMPTY_AUDIO:"VOICE_STT_EMPTY_AUDIO",STT_INVALID_FORMAT:"VOICE_STT_INVALID_FORMAT",STT_TRANSCRIPTION_FAILED:"VOICE_STT_TRANSCRIPTION_FAILED",REALTIME_CONNECTION_FAILED:"VOICE_REALTIME_CONNECTION_FAILED",REALTIME_SESSION_ERROR:"VOICE_REALTIME_SESSION_ERROR",NETWORK_ERROR:"VOICE_NETWORK_ERROR",TIMEOUT:"VOICE_TIMEOUT"},qgn={mp3:{format:"mp3",mimeType:"audio/mpeg",extension:".mp3",supportsStreaming:!0,sampleRates:[8e3,16e3,22050,24e3,44100,48e3],bitDepths:[16]},wav:{format:"wav",mimeType:"audio/wav",extension:".wav",supportsStreaming:!1,sampleRates:[8e3,16e3,22050,24e3,44100,48e3],bitDepths:[8,16,24,32]},ogg:{format:"ogg",mimeType:"audio/ogg",extension:".ogg",supportsStreaming:!0,sampleRates:[8e3,16e3,22050,24e3,44100,48e3],bitDepths:[16]},opus:{format:"opus",mimeType:"audio/opus",extension:".opus",supportsStreaming:!0,sampleRates:[8e3,12e3,16e3,24e3,48e3],bitDepths:[16]},m4a:{format:"m4a",mimeType:"audio/mp4",extension:".m4a",supportsStreaming:!1,sampleRates:[44100,48e3],bitDepths:[16]},flac:{format:"flac",mimeType:"audio/flac",extension:".flac",supportsStreaming:!1,sampleRates:[44100,48e3,96e3],bitDepths:[16,24]},webm:{format:"webm",mimeType:"audio/webm",extension:".webm",supportsStreaming:!0,sampleRates:[44100,48e3],bitDepths:[16]},mp4:{format:"mp4",mimeType:"audio/mp4",extension:".mp4",supportsStreaming:!1,sampleRates:[44100,48e3],bitDepths:[16]},mpeg:{format:"mpeg",mimeType:"audio/mpeg",extension:".mpeg",supportsStreaming:!0,sampleRates:[8e3,16e3,22050,24e3,44100,48e3],bitDepths:[16]},mpga:{format:"mpga",mimeType:"audio/mpeg",extension:".mpga",supportsStreaming:!0,sampleRates:[8e3,16e3,22050,24e3,44100,48e3],bitDepths:[16]}}});var YRe,XRe=k(()=>{"use strict";YRe=class r{static normalizeToUniversal(e){return typeof e=="string"?{prompt:e}:e}static getProviderType(e){return"providerType"in e?e.providerType:null}static extractProviderOptions(e,t){let n=r.getProviderType(e);if(n===t)return e;if(n!==null){let{providerType:o,...s}=e;return s}return e}static mergeWithDefaults(e,t){return{...t,...e,context:{...t.context,...e.context},contextConfig:{...t.contextConfig,...e.contextConfig},metadata:{...t.metadata,...e.metadata}}}}});var ZRe=k(()=>{"use strict"});var ip,QRe=k(()=>{"use strict";ip=class r extends Error{details;constructor(e,t){super(e),this.name="WorkflowError",this.details=t,"captureStackTrace"in Error&&typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,r)}}});var eAe=k(()=>{"use strict"});var tAe=k(()=>{"use strict"});var eo,to,rwt,Zgn,rAe=k(()=>{"use strict";eo=(T=>(T.AGENT_RUN="agent.run",T.WORKFLOW_STEP="workflow.step",T.TOOL_CALL="tool.call",T.MODEL_GENERATION="model.generation",T.EMBEDDING="embedding",T.RETRIEVAL="retrieval",T.MEMORY="memory",T.CONTEXT_COMPACTION="context.compaction",T.RAG="rag",T.EVALUATION="evaluation",T.MCP_TRANSPORT="mcp.transport",T.MEDIA_GENERATION="media.generation",T.PPT_GENERATION="ppt.generation",T.WORKFLOW="workflow",T.TTS="tts",T.STT="stt",T.SERVER_REQUEST="server.request",T.CUSTOM="custom",T))(eo||{}),to=(o=>(o[o.UNSET=0]="UNSET",o[o.OK=1]="OK",o[o.ERROR=2]="ERROR",o[o.WARNING=3]="WARNING",o))(to||{}),rwt={GEN_AI_SYSTEM:"gen_ai.system",GEN_AI_REQUEST_MODEL:"gen_ai.request.model",GEN_AI_RESPONSE_MODEL:"gen_ai.response.model",GEN_AI_USAGE_INPUT_TOKENS:"gen_ai.usage.input_tokens",GEN_AI_USAGE_OUTPUT_TOKENS:"gen_ai.usage.output_tokens",GEN_AI_USAGE_TOTAL_TOKENS:"gen_ai.usage.total_tokens",GEN_AI_REQUEST_TEMPERATURE:"gen_ai.request.temperature",GEN_AI_REQUEST_TOP_P:"gen_ai.request.top_p",GEN_AI_REQUEST_MAX_TOKENS:"gen_ai.request.max_tokens",GEN_AI_REQUEST_STOP_SEQUENCES:"gen_ai.request.stop_sequences",GEN_AI_RESPONSE_FINISH_REASON:"gen_ai.response.finish_reasons",GEN_AI_RESPONSE_ID:"gen_ai.response.id",GEN_AI_TOOL_NAME:"gen_ai.tool.name",GEN_AI_TOOL_CALL_ID:"gen_ai.tool.call_id",GEN_AI_PROMPT:"gen_ai.prompt",GEN_AI_COMPLETION:"gen_ai.completion"},Zgn={AGENT_NAME:"gen_ai.agent.name",AGENT_STEP_TYPE:"gen_ai.agent.step_type",AGENT_TOOL_CALLS:"gen_ai.agent.tool_calls",AGENT_MEMORY_ACCESS:"gen_ai.agent.memory_access",AGENT_REASONING_TRACE:"gen_ai.agent.reasoning_trace"}});var nAe,oAe=k(()=>{"use strict";nAe={enabled:!0,defaultModel:"imagen-3.0-generate-001",defaultProvider:"vertex",defaultRegion:"global",timeout:12e4,defaultTemperature:.75,maxImages:4,maxReferenceImages:5,maxReferencePdfs:1}});var sAe=k(()=>{"use strict"});var iAe=k(()=>{"use strict"});var aAe=k(()=>{"use strict"});var cAe=k(()=>{"use strict"});var lAe=k(()=>{"use strict"});var thn,uAe=k(()=>{"use strict";thn=["mp4","webm","mov"]});var nhn,dAe=k(()=>{"use strict";nhn=["mp3","wav","flac","ogg"]});var pAe=k(()=>{"use strict"});var mAe=k(()=>{"use strict"});var fAe=k(()=>{"use strict"});var gAe=k(()=>{"use strict"});var hAe=k(()=>{"use strict"});var yAe=k(()=>{"use strict"});var Dt=k(()=>{"use strict";Wke();Kke();RCe();ACe();ICe();PCe();MCe();OCe();NCe();DCe();FCe();HCe();KCe();JCe();YCe();XCe();iRe();aRe();cRe();lRe();uRe();dRe();pRe();mRe();fRe();gRe();hRe();yRe();xRe();vRe();bRe();TRe();SRe();wRe();ERe();_Re();RRe();ARe();IRe();PRe();MRe();ORe();NRe();DRe();LRe();URe();FRe();$Re();BRe();zRe();jRe();GRe();JRe();XRe();ZRe();QRe();eAe();tAe();rAe();oAe();sAe();iAe();aAe();cAe();lAe();uAe();dAe();pAe();mAe();fAe();gAe();hAe();yAe()});var cE,_Z,kZ=k(()=>{"use strict";cE=class{name="always";shouldSample(e){return!0}getDescription(){return"Samples 100% of spans"}},_Z=class{name="never";shouldSample(e){return!1}getDescription(){return"Samples 0% of spans"}}});function vAe(r,e,t){return new Promise((n,o)=>{let s=setTimeout(()=>{o(new Error(`Export to '${t}' timed out after ${e}ms`))},e);r.then(i=>{clearTimeout(s),n(i)},i=>{clearTimeout(s),o(i)})})}var xAe,CZ,bAe=k(()=>{"use strict";H();kZ();xAe=3e4;CZ=class{exporters=new Map;defaultExporter=null;sampler=new cE;circuitBreakers=new Map;circuitBreakerConfig={failureThreshold:5,resetTimeout:3e4};register(e){this.exporters.set(e.getName(),e)}unregister(e){return this.exporters.delete(e)}get(e){return this.exporters.get(e)}getNames(){return Array.from(this.exporters.keys())}getCount(){return this.exporters.size}setDefault(e){if(!this.exporters.has(e))throw new Error(`Exporter '${e}' not registered`);this.defaultExporter=e}getDefault(){if(this.defaultExporter)return this.exporters.get(this.defaultExporter)}setSampler(e){this.sampler=e}getSampler(){return this.sampler}configureCircuitBreaker(e){Object.assign(this.circuitBreakerConfig,e)}isCircuitOpen(e){let t=this.circuitBreakers.get(e);return t&&t.state==="open"?Date.now()-t.lastFailure>this.circuitBreakerConfig.resetTimeout?(t.state="half-open",g.info(`[ExporterRegistry] Circuit half-open for ${e}, attempting recovery`),!1):!0:!1}recordFailure(e){let t=this.circuitBreakers.get(e);t||(t={failures:0,lastFailure:0,state:"closed"},this.circuitBreakers.set(e,t)),t.failures++,t.lastFailure=Date.now(),t.failures>=this.circuitBreakerConfig.failureThreshold&&(t.state="open",g.warn(`[ExporterRegistry] Circuit opened for ${e} after ${t.failures} failures`))}recordSuccess(e){let t=this.circuitBreakers.get(e);t&&(t.state==="half-open"&&g.info(`[ExporterRegistry] Circuit closed for ${e} after successful recovery`),t.failures=0,t.state="closed")}getCircuitBreakerStatus(e){return this.circuitBreakers.get(e)}resetCircuitBreaker(e){this.circuitBreakers.delete(e)}async exportToAll(e){let t=new Map;if(!this.sampler.shouldSample(e))return t;let n=Array.from(this.exporters.entries()).map(async([o,s])=>{if(this.isCircuitOpen(o)){t.set(o,{success:!1,exportedCount:0,failedCount:1,errors:[{spanId:e.spanId,error:"Circuit breaker open - exporter temporarily disabled",retryable:!0}],durationMs:0});return}if(s.isInitialized())try{let i=await vAe(s.exportSpan(e),xAe,o);t.set(o,i),i.success?this.recordSuccess(o):this.recordFailure(o)}catch(i){this.recordFailure(o),t.set(o,{success:!1,exportedCount:0,failedCount:1,errors:[{spanId:e.spanId,error:i instanceof Error?i.message:String(i),retryable:!0}],durationMs:0})}else g.debug(`[ExporterRegistry] Skipping uninitialized exporter '${o}' for span ${e.spanId}`)});return await Promise.all(n),t}async exportTo(e,t){let n=this.exporters.get(e);if(!n)return null;if(!n.isInitialized())return g.debug(`[ExporterRegistry] Skipping uninitialized exporter '${e}' for span ${t.spanId}`),null;if(this.isCircuitOpen(e))return{success:!1,exportedCount:0,failedCount:1,errors:[{spanId:t.spanId,error:"Circuit breaker open - exporter temporarily disabled",retryable:!0}],durationMs:0};if(!this.sampler.shouldSample(t))return{success:!0,exportedCount:0,failedCount:0,durationMs:0};try{let o=await vAe(n.exportSpan(t),xAe,e);return o.success?this.recordSuccess(e):this.recordFailure(e),o}catch(o){return this.recordFailure(e),{success:!1,exportedCount:0,failedCount:1,errors:[{spanId:t.spanId,error:o instanceof Error?o.message:String(o),retryable:!0}],durationMs:0}}}async initializeAll(){let e=await Promise.allSettled(Array.from(this.exporters.entries()).map(([t,n])=>n.initialize().catch(o=>{throw g.error(`[ExporterRegistry] Failed to initialize exporter '${t}':`,o),o})));for(let t of e)if(t.status==="rejected"){g.warn("[ExporterRegistry] One or more exporters failed to initialize");break}}async shutdownAll(){let e=await Promise.allSettled(Array.from(this.exporters.entries()).map(([t,n])=>n.shutdown().catch(o=>{throw g.error(`[ExporterRegistry] Failed to shutdown exporter '${t}':`,o),o})));for(let t of e)if(t.status==="rejected"){g.warn("[ExporterRegistry] One or more exporters failed to shutdown");break}}async flushAll(){let e=await Promise.allSettled(Array.from(this.exporters.entries()).map(([t,n])=>n.flush().catch(o=>{throw g.error(`[ExporterRegistry] Failed to flush exporter '${t}':`,o),o})));for(let t of e)if(t.status==="rejected"){g.warn("[ExporterRegistry] One or more exporters failed to flush");break}}async healthCheckAll(){let e=new Map,t=Array.from(this.exporters.entries()).map(async([n,o])=>{let s=await o.healthCheck();e.set(n,s)});return await Promise.all(t),e}async isHealthy(){let e=await this.healthCheckAll();return Array.from(e.values()).every(t=>t.healthy)}getTotalPendingSpans(){let e=0,t=Array.from(this.exporters.values());for(let n of t)e+=n.getPendingCount();return e}clear(){this.exporters.clear(),this.defaultExporter=null,this.circuitBreakers.clear(),this.sampler=new cE}}});var RZ,AZ,TAe=k(()=>{"use strict";H();RZ=class{name;config;initialized=!1;buffer=[];maxBufferSize;retries;flushInterval=null;lastExportTime=0;constructor(e,t){this.name=e,this.config=t,this.maxBufferSize=t.maxBufferSize??100,this.retries=t.retries??3}async ping(){}bufferSpan(e){this.buffer.push(e),this.buffer.length>=this.maxBufferSize&&this.flush()}startFlushInterval(e){this.flushInterval&&clearInterval(this.flushInterval),this.flushInterval=setInterval(()=>{this.flush().catch(t=>{g.warn(`[${this.name}] Periodic flush failed`,{error:t instanceof Error?t.message:String(t)})})},e)}stopFlushInterval(){this.flushInterval&&(clearInterval(this.flushInterval),this.flushInterval=null)}getName(){return this.name}isInitialized(){return this.initialized}getPendingCount(){return this.buffer.length}getLastExportTime(){return this.lastExportTime}createSuccessResult(e,t){return this.lastExportTime=Date.now(),{success:!0,exportedCount:e,failedCount:0,durationMs:t}}createFailureResult(e,t,n,o=!0){return{success:!1,exportedCount:0,failedCount:e.length,errors:e.map(s=>({spanId:s,error:t,retryable:o})),durationMs:n}}createHealthStatus(e,t){return{healthy:e,name:this.name,pendingSpans:this.buffer.length,lastExportTime:this.lastExportTime||void 0,errors:t}}async withRetry(e,t){let n=this.retries,o=1e3,s;for(let i=0;i<=n;i++)try{return await e()}catch(a){if(s=a,i<n){let c=o*2**i;g.warn(`[${this.name}] ${t} failed, retrying in ${c}ms`,{attempt:i+1,maxRetries:n,error:s.message}),await new Promise(l=>setTimeout(l,c))}}throw s}},AZ=class extends RZ{constructor(){super("noop",{enabled:!1})}async initialize(){this.initialized=!0}async exportSpan(e){return this.createSuccessResult(0,0)}async exportBatch(e){return this.createSuccessResult(0,0)}async flush(){}async shutdown(){this.initialized=!1}async healthCheck(){return this.createHealthStatus(!0)}}});var SAe,PZ,Yo,MZ,Pyn,Myn,Oyn,OZ,nwt,IZ,Nyn,Dyn,Uyn,Fyn,xl=k(()=>{SAe=r=>{let e=[];return{update(t){return e.push(typeof t=="string"?new IZ().encode(t):t),this},digest(t){let n=0;for(let s of e)for(let i=0;i<s.length;i++)n=(n<<5)-n+s[i]|0;let o=(n>>>0).toString(16).padStart(8,"0");return t==="hex"?o:t==="base64"?btoa(o):o}}},PZ=r=>new Uint8Array(r||32),Yo=()=>globalThis.crypto?.randomUUID?.()||Math.random().toString(36),MZ=globalThis.crypto,Pyn=globalThis.ReadableStream||class{},Myn=globalThis.URL,Oyn=globalThis.URLSearchParams,OZ=r=>{try{return JSON.stringify(r,null,2)}catch{return String(r)}};OZ.custom=Symbol.for("nodejs.util.inspect.custom");OZ.colors={};OZ.styles={};nwt=globalThis.TextDecoder,IZ=globalThis.TextEncoder,Nyn=globalThis.performance||{now:()=>Date.now()},Dyn=globalThis.Buffer||class extends Uint8Array{static from(e,t){if(typeof e=="string"){let n=(t||"utf8").toLowerCase();if(n==="base64"){let o=atob(e),s=new Uint8Array(o.length);for(let i=0;i<o.length;i++)s[i]=o.charCodeAt(i);return s}if(n==="hex"){let o=new Uint8Array(e.length/2);for(let s=0;s<e.length;s+=2)o[s/2]=parseInt(e.substr(s,2),16);return o}return new IZ().encode(e)}return new Uint8Array(e)}static alloc(e){return new Uint8Array(e)}static isBuffer(e){return e instanceof Uint8Array}static concat(e){let t=e.reduce((s,i)=>s+i.length,0),n=new Uint8Array(t),o=0;for(let s of e)n.set(s,o),o+=s.length;return n}static byteLength(e,t){return t==="base64"?Math.ceil(e.length*3/4):new IZ().encode(e).length}toString(e){let t=(e||"utf8").toLowerCase();if(t==="hex")return Array.from(new Uint8Array(this.buffer,this.byteOffset,this.byteLength)).map(n=>n.toString(16).padStart(2,"0")).join("");if(t==="base64"){let n="";for(let o=0;o<this.length;o++)n+=String.fromCharCode(this[o]);return btoa(n)}return new nwt().decode(this)}},Uyn=globalThis.clearTimeout,Fyn=globalThis.clearInterval});function od(){let r=Tt.getSpan(wr.active());if(!r)return{};let e=r.spanContext();return!e.traceId||e.traceId==="00000000000000000000000000000000"?{}:{traceId:e.traceId,parentSpanId:e.spanId}}var Gv=k(()=>{"use strict";Dr()});function wAe(r){let e={};for(let t of swt)r[t]!==void 0&&(e[t]=r[t]);return e}var swt,EAe=k(()=>{"use strict";swt=new Set(["ai.provider","ai.model","ai.temperature","ai.max_tokens"])});var xe,HI=k(()=>{"use strict";xl();Gv();EAe();xe=class r{static createSpan(e,t,n={},o,s){let i=s,a=o;if(!i){let c=od();i=c.traceId??PZ(16).toString("hex"),!a&&c.parentSpanId&&(a=c.parentSpanId)}return{spanId:PZ(8).toString("hex"),traceId:i,parentSpanId:a,type:e,name:t,startTime:new Date().toISOString(),status:0,attributes:n,events:[],links:[]}}static endSpan(e,t=1,n){let o=new Date,s=new Date(e.startTime);return{...e,endTime:o.toISOString(),durationMs:o.getTime()-s.getTime(),status:t,statusMessage:n}}static addEvent(e,t,n){let o={name:t,timestamp:new Date().toISOString(),attributes:n};return{...e,events:[...e.events,o]}}static updateAttributes(e,t){return{...e,attributes:{...e.attributes,...t}}}static toJSON(e){return JSON.stringify(e,null,2)}serialize(e){return JSON.stringify(e,null,2)}deserialize(e){return JSON.parse(e)}static fromJSON(e){return JSON.parse(e)}static toLangfuseFormat(e){return{id:e.spanId,traceId:e.traceId,parentObservationId:e.parentSpanId,name:e.name,startTime:e.startTime,endTime:e.endTime,metadata:wAe(e.attributes),level:e.status===2?"ERROR":e.status===3?"WARNING":"DEFAULT",statusMessage:e.statusMessage,input:e.attributes.input,output:e.attributes.output,usage:e.attributes["ai.tokens.total"]!==void 0?{promptTokens:e.attributes["ai.tokens.input"],completionTokens:e.attributes["ai.tokens.output"],totalTokens:e.attributes["ai.tokens.total"]}:void 0}}static toLangSmithFormat(e){return{id:e.spanId,trace_id:e.traceId,parent_run_id:e.parentSpanId,name:e.name,run_type:r.mapSpanTypeToLangSmithRunType(e.type),start_time:e.startTime,end_time:e.endTime,extra:{...e.attributes},error:e.status===2?e.statusMessage:void 0,inputs:e.attributes.input,outputs:e.attributes.output,tags:r.extractTags(e.attributes)}}static toOtelFormat(e){return{traceId:e.traceId,spanId:e.spanId,parentSpanId:e.parentSpanId,name:e.name,kind:1,startTimeUnixNano:new Date(e.startTime).getTime()*1e6,endTimeUnixNano:e.endTime?new Date(e.endTime).getTime()*1e6:void 0,attributes:Object.entries(e.attributes).filter(([,t])=>t!==void 0).map(([t,n])=>({key:t,value:r.toOtelAttributeValue(n)})),status:{code:e.status,message:e.statusMessage},events:e.events.map(t=>({name:t.name,timeUnixNano:new Date(t.timestamp).getTime()*1e6,attributes:t.attributes?Object.entries(t.attributes).map(([n,o])=>({key:n,value:r.toOtelAttributeValue(o)})):[]}))}}static toOtelAttributeValue(e){return typeof e=="string"?{stringValue:e}:typeof e=="number"?Number.isInteger(e)?{intValue:e}:{stringValue:String(e)}:typeof e=="boolean"?{boolValue:e}:{stringValue:JSON.stringify(e)}}static mapSpanTypeToLangSmithRunType(e){return{"agent.run":"chain","workflow.step":"chain","tool.call":"tool","model.generation":"llm",embedding:"embedding",retrieval:"retriever",memory:"chain","context.compaction":"chain",rag:"retriever",evaluation:"chain","mcp.transport":"tool","media.generation":"llm","ppt.generation":"chain",workflow:"chain",tts:"chain",stt:"chain","server.request":"chain",custom:"chain"}[e]||"chain"}static extractTags(e){let t=[];return e["ai.provider"]&&t.push(`provider:${e["ai.provider"]}`),e["ai.model"]&&t.push(`model:${e["ai.model"]}`),e["deployment.environment"]&&t.push(`env:${e["deployment.environment"]}`),e["tool.name"]&&t.push(`tool:${e["tool.name"]}`),t}static createGenerationSpan(e){return r.createSpan("model.generation",e.name??`gen_ai.${e.provider}.chat`,{"ai.provider":e.provider,"ai.model":e.model,"ai.temperature":e.temperature,"ai.max_tokens":e.maxTokens,input:e.input,"user.id":e.userId,"session.id":e.sessionId},e.parentSpanId,e.traceId)}static createToolCallSpan(e){return r.createSpan("tool.call",`tool.${e.toolName}`,{"tool.name":e.toolName,"tool.server":e.server,input:e.input},e.parentSpanId,e.traceId)}static enrichWithTokenUsage(e,t){return r.updateAttributes(e,{"ai.tokens.input":t.promptTokens??0,"ai.tokens.output":t.completionTokens??0,"ai.tokens.total":t.totalTokens??(t.promptTokens??0)+(t.completionTokens??0),"ai.tokens.cache_creation":t.cacheCreationTokens,"ai.tokens.cache_read":t.cacheReadTokens,"ai.tokens.reasoning":t.reasoningTokens})}static enrichWithCost(e,t){return r.updateAttributes(e,{"ai.cost.input":t.inputCost,"ai.cost.output":t.outputCost,"ai.cost.total":t.totalCost,"ai.cost.currency":t.currency??"USD"})}}});var WI={};te(WI,{AsyncLocalStorage:()=>kwt,Buffer:()=>f_t,Channel:()=>n_t,DatabaseSync:()=>m_t,Duplex:()=>Rwt,EventEmitter:()=>_wt,Http2ServerRequest:()=>v_t,Http2ServerResponse:()=>b_t,Interface:()=>p_t,MIMEType:()=>k_t,PassThrough:()=>Awt,PerformanceObserver:()=>e_t,Readable:()=>kAe,ReadableStream:()=>Iwt,Resolver:()=>ZEt,TextDecoder:()=>AAe,TextEncoder:()=>W2,Transform:()=>Cwt,URL:()=>$Et,URLSearchParams:()=>BEt,Worker:()=>a_t,Writable:()=>CAe,access:()=>oEt,appendFile:()=>Uwt,appendFileSync:()=>pwt,arch:()=>bEt,arrayBuffer:()=>T_t,basename:()=>xwt,builtinModules:()=>DEt,callbackify:()=>WEt,channel:()=>r_t,chmodSync:()=>Lwt,clearInterval:()=>__t,clearTimeout:()=>w_t,closeSync:()=>zwt,connect:()=>EEt,constants:()=>g_t,copyFileSync:()=>$wt,cpSync:()=>mwt,cpus:()=>hEt,createConnection:()=>_Et,createGunzip:()=>IEt,createGzip:()=>PEt,createHash:()=>_Ae,createHmac:()=>cwt,createInterface:()=>d_t,createReadStream:()=>Xwt,createRequire:()=>NEt,createServer:()=>fwt,createWriteStream:()=>Ywt,debug:()=>qEt,debuglog:()=>RAe,default:()=>iwt,deflateSync:()=>CEt,deprecate:()=>HEt,deserialize:()=>i_t,dirname:()=>ywt,exec:()=>cEt,execFile:()=>uEt,execFileSync:()=>dEt,execSync:()=>lEt,existsSync:()=>Owt,extname:()=>vwt,fileURLToPath:()=>zEt,finished:()=>Mwt,format:()=>FEt,freemem:()=>yEt,fstatSync:()=>jwt,get:()=>wEt,gunzip:()=>DZ,gunzipSync:()=>REt,gzip:()=>NZ,gzipSync:()=>AEt,hasSubscribers:()=>o_t,homedir:()=>mEt,hostname:()=>gEt,inflateSync:()=>kEt,inherits:()=>GEt,inspect:()=>K2,isAbsolute:()=>Twt,isBuiltin:()=>LEt,isDeepStrictEqual:()=>KEt,isIP:()=>x_t,isIPv4:()=>y_t,isIPv6:()=>h_t,isMainThread:()=>c_t,join:()=>gwt,lookup:()=>XEt,mkdir:()=>eEt,mkdirSync:()=>Gwt,monitorEventLoopDelay:()=>t_t,normalize:()=>Ewt,ok:()=>MEt,openSync:()=>Bwt,parentPort:()=>l_t,parse:()=>UEt,pathToFileURL:()=>jEt,performance:()=>QEt,pipeline:()=>Pwt,platform:()=>pEt,posix:()=>wwt,promises:()=>awt,promisify:()=>VEt,randomBytes:()=>lwt,randomUUID:()=>uwt,readFile:()=>Zwt,readFileSync:()=>Nwt,readdir:()=>rEt,readdirSync:()=>qwt,realpathSync:()=>Fwt,relative:()=>bwt,release:()=>TEt,rename:()=>sEt,renameSync:()=>Wwt,request:()=>SEt,resolve:()=>hwt,rm:()=>iEt,rmSync:()=>Jwt,rmdirSync:()=>Kwt,sep:()=>Swt,serialize:()=>s_t,setInterval:()=>E_t,setTimeout:()=>S_t,spawn:()=>aEt,stat:()=>tEt,statSync:()=>Vwt,strict:()=>OEt,tmpdir:()=>fEt,toUSVString:()=>JEt,totalmem:()=>xEt,type:()=>vEt,types:()=>YEt,unlink:()=>nEt,unlinkSync:()=>Hwt,webcrypto:()=>dwt,workerData:()=>u_t,writeFile:()=>Qwt,writeFileSync:()=>Dwt});var Xo,ai,iwt,awt,_Ae,cwt,lwt,uwt,dwt,pwt,mwt,fwt,gwt,hwt,ywt,xwt,vwt,bwt,Twt,Swt,wwt,Ewt,_wt,kwt,kAe,CAe,Cwt,Rwt,Awt,Iwt,Pwt,Mwt,Owt,Nwt,Dwt,Lwt,Uwt,Fwt,$wt,Bwt,zwt,jwt,Gwt,Vwt,qwt,Hwt,Wwt,Kwt,Jwt,Ywt,Xwt,Zwt,Qwt,eEt,tEt,rEt,nEt,oEt,sEt,iEt,aEt,cEt,lEt,uEt,dEt,pEt,mEt,fEt,gEt,hEt,yEt,xEt,vEt,bEt,TEt,SEt,wEt,EEt,_Et,kEt,CEt,REt,AEt,NZ,DZ,IEt,PEt,MEt,OEt,NEt,DEt,LEt,UEt,FEt,$Et,BEt,zEt,jEt,GEt,VEt,RAe,qEt,K2,HEt,WEt,KEt,JEt,YEt,AAe,W2,XEt,ZEt,QEt,e_t,t_t,r_t,n_t,o_t,s_t,i_t,a_t,c_t,l_t,u_t,d_t,p_t,m_t,f_t,g_t,h_t,y_t,x_t,v_t,b_t,T_t,IAe,S_t,w_t,E_t,__t,k_t,Vv=k(()=>{Xo=()=>{},ai=async()=>{},iwt={},awt={readFile:ai,writeFile:ai,mkdir:ai,stat:ai,readdir:ai,unlink:ai,access:ai,rm:ai,rename:ai},_Ae=r=>{let e=[];return{update(t){return e.push(typeof t=="string"?new W2().encode(t):t),this},digest(t){let n=0;for(let s of e)for(let i=0;i<s.length;i++)n=(n<<5)-n+s[i]|0;let o=(n>>>0).toString(16).padStart(8,"0");return t==="hex"?o:t==="base64"?btoa(o):o}}},cwt=(r,e)=>_Ae(r),lwt=r=>new Uint8Array(r||32),uwt=()=>globalThis.crypto?.randomUUID?.()||Math.random().toString(36),dwt=globalThis.crypto,pwt=()=>{throw new Error("[NeuroLink:browser] fs.appendFileSync is not supported in browser runtime \u2014 use server-side execution")},mwt=()=>{throw new Error("[NeuroLink:browser] fs.cpSync is not supported in browser runtime \u2014 use server-side execution")},fwt=()=>({listen:Xo,close:Xo,on:Xo}),gwt=(...r)=>r.join("/"),hwt=(...r)=>r.join("/"),ywt=r=>r||"",xwt=r=>r?.split?.("/")?.pop?.()||"",vwt=r=>{let e=r?.match?.(/\.[^.]+$/);return e?e[0]:""},bwt=(r,e)=>e||"",Twt=()=>!1,Swt="/",wwt={normalize:r=>r,join:(...r)=>r.join("/"),resolve:(...r)=>r.join("/"),sep:"/"},Ewt=r=>r,_wt=class{on(){return this}off(){return this}emit(){return this}once(){return this}removeListener(){return this}addListener(){return this}},kwt=class{getStore(){}run(r,e,...t){return e(...t)}enterWith(){}disable(){}},kAe=class{pipe(){return this}on(){return this}read(){return null}push(){}destroy(){}},CAe=class{write(){return!0}end(){}on(){return this}destroy(){}},Cwt=class{push(){}on(){return this}},Rwt=class{on(){return this}},Awt=class{pipe(){return this}on(){return this}},Iwt=globalThis.ReadableStream||class{},Pwt=Xo,Mwt=Xo,Owt=()=>!1,Nwt=()=>"",Dwt=Xo,Lwt=Xo,Uwt=ai,Fwt=r=>r,$wt=Xo,Bwt=()=>0,zwt=Xo,jwt=()=>({}),Gwt=Xo,Vwt=()=>({}),qwt=()=>[],Hwt=Xo,Wwt=Xo,Kwt=Xo,Jwt=Xo,Ywt=()=>new CAe,Xwt=()=>new kAe,Zwt=ai,Qwt=ai,eEt=ai,tEt=ai,rEt=ai,nEt=ai,oEt=ai,sEt=ai,iEt=ai,aEt=()=>({on:Xo,stdout:{on:Xo},stderr:{on:Xo},kill:Xo}),cEt=(r,e)=>e?.(null,"",""),lEt=()=>"",uEt=(r,e,t)=>{typeof e=="function"?e(null,"",""):t?.(null,"","")},dEt=()=>"",pEt="browser",mEt=()=>"/",fEt=()=>"/tmp",gEt=()=>"browser",hEt=()=>[{}],yEt=()=>0,xEt=()=>0,vEt=()=>"Browser",bEt=()=>"wasm",TEt=()=>"0",SEt=()=>({}),wEt=()=>({}),EEt=()=>({}),_Et=()=>({}),kEt=()=>new Uint8Array,CEt=()=>new Uint8Array,REt=()=>new Uint8Array,AEt=()=>new Uint8Array,NZ=(r,e)=>e?.(null,r),DZ=(r,e)=>e?.(null,r),IEt=()=>({}),PEt=()=>({}),MEt=Xo,OEt={},NEt=()=>()=>({}),DEt=[],LEt=()=>!1,UEt=r=>({pathname:r||"",hostname:"",protocol:"",search:"",hash:""}),FEt=()=>"",$Et=globalThis.URL,BEt=globalThis.URLSearchParams,zEt=r=>typeof r=="string"?r.replace("file://",""):r,jEt=r=>new globalThis.URL("file://"+r),GEt=(r,e)=>{e&&(r.super_=e,Object.setPrototypeOf(r.prototype,e.prototype))},VEt=r=>(...e)=>new Promise((t,n)=>r(...e,(o,s)=>o?n(o):t(s))),RAe=r=>{let e=(...t)=>{};return e.enabled=!1,e},qEt=RAe,K2=r=>{try{return JSON.stringify(r,null,2)}catch{return String(r)}};K2.custom=Symbol.for("nodejs.util.inspect.custom");K2.colors={};K2.styles={};HEt=r=>r,WEt=r=>(...e)=>{let t=e.pop();r(...e).then(n=>t(null,n)).catch(t)},KEt=(r,e)=>JSON.stringify(r)===JSON.stringify(e),JEt=r=>String(r),YEt={isPromise:r=>r instanceof Promise,isDate:r=>r instanceof Date,isRegExp:r=>r instanceof RegExp,isNativeError:r=>r instanceof Error,isArrayBuffer:r=>r instanceof ArrayBuffer,isTypedArray:r=>ArrayBuffer.isView(r),isUint8Array:r=>r instanceof Uint8Array,isProxy:()=>!1},AAe=globalThis.TextDecoder,W2=globalThis.TextEncoder,XEt=(r,e)=>e?.(null,"127.0.0.1",4),ZEt=class{},QEt=globalThis.performance||{now:()=>Date.now()},e_t=class{observe(){}disconnect(){}},t_t=()=>({enable:Xo,disable:Xo,percentile:()=>0}),r_t=()=>({}),n_t=class{},o_t=()=>!1,s_t=()=>new Uint8Array,i_t=Xo,a_t=class{},c_t=!0,l_t=null,u_t=null,d_t=()=>({}),p_t=class{},m_t=class{},f_t=globalThis.Buffer||class extends Uint8Array{static from(e,t){if(typeof e=="string"){let n=(t||"utf8").toLowerCase();if(n==="base64"){let o=atob(e),s=new Uint8Array(o.length);for(let i=0;i<o.length;i++)s[i]=o.charCodeAt(i);return s}if(n==="hex"){let o=new Uint8Array(e.length/2);for(let s=0;s<e.length;s+=2)o[s/2]=parseInt(e.substr(s,2),16);return o}return new W2().encode(e)}return new Uint8Array(e)}static alloc(e){return new Uint8Array(e)}static isBuffer(e){return e instanceof Uint8Array}static concat(e){let t=e.reduce((s,i)=>s+i.length,0),n=new Uint8Array(t),o=0;for(let s of e)n.set(s,o),o+=s.length;return n}static byteLength(e,t){return t==="base64"?Math.ceil(e.length*3/4):new W2().encode(e).length}toString(e){let t=(e||"utf8").toLowerCase();if(t==="hex")return Array.from(new Uint8Array(this.buffer,this.byteOffset,this.byteLength)).map(n=>n.toString(16).padStart(2,"0")).join("");if(t==="base64"){let n="";for(let o=0;o<this.length;o++)n+=String.fromCharCode(this[o]);return btoa(n)}return new AAe().decode(this)}},g_t={F_OK:0,R_OK:4,W_OK:2,X_OK:1},h_t=()=>!1,y_t=()=>!1,x_t=()=>0,v_t=class{},b_t=class{},T_t=async()=>new ArrayBuffer(0),IAe=r=>({[Symbol.toPrimitive](){return r},ref(){return this},unref(){return this},hasRef(){return!1},refresh(){return this},close(){}}),S_t=(...r)=>IAe(globalThis.setTimeout(...r)),w_t=globalThis.clearTimeout,E_t=(...r)=>IAe(globalThis.setInterval(...r)),__t=globalThis.clearInterval,k_t=class{constructor(r){this.type=r}toString(){return this.type}}});var J2,KI,LZ=k(()=>{"use strict";J2={"gpt-4o":{inputPricePerMillion:2.5,outputPricePerMillion:10,cachedInputPricePerMillion:1.25},"gpt-4o-mini":{inputPricePerMillion:.15,outputPricePerMillion:.6,cachedInputPricePerMillion:.075},o1:{inputPricePerMillion:15,outputPricePerMillion:60,cachedInputPricePerMillion:7.5},"o1-mini":{inputPricePerMillion:3,outputPricePerMillion:12,cachedInputPricePerMillion:1.5},"claude-sonnet-4-20250514":{inputPricePerMillion:3,outputPricePerMillion:15,cachedInputPricePerMillion:.3},"claude-3-5-sonnet-20241022":{inputPricePerMillion:3,outputPricePerMillion:15,cachedInputPricePerMillion:.3},"claude-3-5-haiku-20241022":{inputPricePerMillion:.8,outputPricePerMillion:4,cachedInputPricePerMillion:.08},"gemini-2.5-flash":{inputPricePerMillion:.15,outputPricePerMillion:.6},"gemini-2.5-pro":{inputPricePerMillion:1.25,outputPricePerMillion:10},"gemini-2.0-flash-exp":{inputPricePerMillion:.15,outputPricePerMillion:.6},"mistral-large-latest":{inputPricePerMillion:2,outputPricePerMillion:6},"mistral-small-latest":{inputPricePerMillion:.2,outputPricePerMillion:.6}},KI=class r{stats={totalInputTokens:0,totalOutputTokens:0,totalTokens:0,cacheReadTokens:0,cacheCreationTokens:0,reasoningTokens:0,totalCost:0,byProvider:new Map,byModel:new Map,bySpanType:new Map};customPricing=new Map;setObservabilityModelPricing(e,t){this.customPricing.set(e,t)}updatePricing(e,t){this.customPricing.set(e,t)}loadPricingFromConfig(e){for(let[t,n]of Object.entries(e))this.customPricing.set(t,n)}getModelPricing(e){return this.customPricing.get(e)??J2[e]}getAllPricing(){let e={...J2},t=Array.from(this.customPricing.entries());for(let[n,o]of t)e[n]=o;return e}removeCustomPricing(e){return this.customPricing.delete(e)}trackSpan(e){let t=e.attributes,n=t["ai.tokens.input"]??0,o=t["ai.tokens.output"]??0,s=t["ai.tokens.total"]??n+o,i=t["ai.tokens.cache_read"]??0,a=t["ai.tokens.cache_creation"]??0,c=t["ai.tokens.reasoning"]??0,l=t["ai.cost.total"]??this.calculateCost(t,n,o,i);this.stats.totalInputTokens+=n,this.stats.totalOutputTokens+=o,this.stats.totalTokens+=s,this.stats.cacheReadTokens+=i,this.stats.cacheCreationTokens+=a,this.stats.reasoningTokens+=c,this.stats.totalCost+=l;let u=t["ai.provider"];if(u){let f=this.stats.byProvider.get(u)??{provider:u,inputTokens:0,outputTokens:0,totalTokens:0,cost:0,requestCount:0};f.inputTokens+=n,f.outputTokens+=o,f.totalTokens+=s,f.cost+=l,f.requestCount+=1,this.stats.byProvider.set(u,f)}let d=t["ai.model"];if(d){let f=this.stats.byModel.get(d)??{model:d,provider:u??"unknown",inputTokens:0,outputTokens:0,totalTokens:0,cost:0,requestCount:0,avgTokensPerRequest:0};f.inputTokens+=n,f.outputTokens+=o,f.totalTokens+=s,f.cost+=l,f.requestCount+=1,f.avgTokensPerRequest=f.totalTokens/f.requestCount,this.stats.byModel.set(d,f)}let p=this.stats.bySpanType.get(e.type)??0;this.stats.bySpanType.set(e.type,p+s)}calculateCost(e,t,n,o=0){let s=e["ai.model"];if(!s)return 0;let i=this.customPricing.get(s)??J2[s];if(!i)return 0;let c=(t-o)/1e6*i.inputPricePerMillion,l=o/1e6*(i.cachedInputPricePerMillion??i.inputPricePerMillion),u=n/1e6*i.outputPricePerMillion;return c+l+u}trackUsage(e){let t=e.promptTokens??0,n=e.completionTokens??0,o=e.totalTokens??t+n;this.stats.totalInputTokens+=t,this.stats.totalOutputTokens+=n,this.stats.totalTokens+=o;let s=0;if(e.model){let i=this.customPricing.get(e.model)??J2[e.model];i&&(s=t/1e6*i.inputPricePerMillion+n/1e6*i.outputPricePerMillion)}if(this.stats.totalCost+=s,e.provider){let i=this.stats.byProvider.get(e.provider)??{provider:e.provider,inputTokens:0,outputTokens:0,totalTokens:0,cost:0,requestCount:0};i.inputTokens+=t,i.outputTokens+=n,i.totalTokens+=o,i.cost+=s,i.requestCount+=1,this.stats.byProvider.set(e.provider,i)}if(e.model){let i=this.stats.byModel.get(e.model)??{model:e.model,provider:e.provider??"unknown",inputTokens:0,outputTokens:0,totalTokens:0,cost:0,requestCount:0,avgTokensPerRequest:0};i.inputTokens+=t,i.outputTokens+=n,i.totalTokens+=o,i.cost+=s,i.requestCount+=1,i.avgTokensPerRequest=i.totalTokens/i.requestCount,this.stats.byModel.set(e.model,i)}}getStats(){return{...this.stats}}getStatsForWindow(e){let t=new r;for(let[n,o]of this.customPricing)t.setObservabilityModelPricing(n,o);for(let n of e)t.trackSpan(n);return t.getStats()}reset(){this.stats={totalInputTokens:0,totalOutputTokens:0,totalTokens:0,cacheReadTokens:0,cacheCreationTokens:0,reasoningTokens:0,totalCost:0,byProvider:new Map,byModel:new Map,bySpanType:new Map}}toJSON(){return{totalInputTokens:this.stats.totalInputTokens,totalOutputTokens:this.stats.totalOutputTokens,totalTokens:this.stats.totalTokens,cacheReadTokens:this.stats.cacheReadTokens,cacheCreationTokens:this.stats.cacheCreationTokens,reasoningTokens:this.stats.reasoningTokens,totalCost:this.stats.totalCost,byProvider:Object.fromEntries(this.stats.byProvider),byModel:Object.fromEntries(this.stats.byModel),bySpanType:Object.fromEntries(this.stats.bySpanType)}}formatCost(e,t="USD"){return new Intl.NumberFormat("en-US",{style:"currency",currency:t,minimumFractionDigits:4}).format(e)}getSummary(){let e=this.stats;return["Token Usage Summary:",` Input tokens: ${e.totalInputTokens.toLocaleString()}`,` Output tokens: ${e.totalOutputTokens.toLocaleString()}`,` Total tokens: ${e.totalTokens.toLocaleString()}`,` Total cost: ${this.formatCost(e.totalCost)}`,e.cacheReadTokens>0?` Cache read tokens: ${e.cacheReadTokens.toLocaleString()}`:"",e.reasoningTokens>0?` Reasoning tokens: ${e.reasoningTokens.toLocaleString()}`:""].filter(Boolean).join(`
160
160
  `)}}});function Ze(){return lE||(lE=new qv),lE}function PAe(){lE&&lE.reset(),lE=null}var qv,lE,Y2=k(()=>{"use strict";LZ();qv=class r{spans=[];latencyValues=[];tokenTracker;timeWindows=new Map;config;spansByType=new Map;costByProvider=new Map;costByModel=new Map;successCount=0;failureCount=0;firstSpanTime;lastSpanTime;constructor(e={}){this.config={maxSpansRetained:e.maxSpansRetained??1e4,enableTimeWindows:e.enableTimeWindows??!0,timeWindowMs:e.timeWindowMs??6e4,maxTimeWindows:e.maxTimeWindows??60},this.tokenTracker=new KI}recordSpan(e){this.spans.length>=this.config.maxSpansRetained&&this.spans.shift()?.durationMs!==void 0&&this.latencyValues.shift(),this.spans.push(e);let t=new Date(e.startTime);(!this.firstSpanTime||t<this.firstSpanTime)&&(this.firstSpanTime=t),(!this.lastSpanTime||t>this.lastSpanTime)&&(this.lastSpanTime=t),e.durationMs!==void 0&&this.latencyValues.push(e.durationMs),e.status===2?this.failureCount++:this.successCount++;let n=this.spansByType.get(e.type)??0;this.spansByType.set(e.type,n+1),this.tokenTracker.trackSpan(e),this.trackCosts(e),this.config.enableTimeWindows&&this.updateTimeWindow(e)}trackCosts(e){let t=e.attributes,n=t["ai.provider"],o=t["ai.model"],s=t["ai.cost.input"]??0,i=t["ai.cost.output"]??0,a=t["ai.cost.total"]??s+i,c=t["ai.tokens.input"]??0,l=t["ai.tokens.output"]??0;if(n){let u=this.costByProvider.get(n)??{provider:n,totalCost:0,requestCount:0,avgCostPerRequest:0,inputCost:0,outputCost:0};u.totalCost+=a,u.requestCount+=1,u.avgCostPerRequest=u.totalCost/u.requestCount,u.inputCost+=s,u.outputCost+=i,this.costByProvider.set(n,u)}if(o){let u=this.costByModel.get(o)??{model:o,provider:n??"unknown",totalCost:0,requestCount:0,avgCostPerRequest:0,inputTokens:0,outputTokens:0,inputCost:0,outputCost:0};u.totalCost+=a,u.requestCount+=1,u.avgCostPerRequest=u.totalCost/u.requestCount,u.inputTokens+=c,u.outputTokens+=l,u.inputCost+=s,u.outputCost+=i,this.costByModel.set(o,u)}}updateTimeWindow(e){let t=new Date(e.startTime).getTime(),n=Math.floor(t/this.config.timeWindowMs)*this.config.timeWindowMs;if(this.timeWindows.size>=this.config.maxTimeWindows&&!this.timeWindows.has(n)){let i=Math.min(...Array.from(this.timeWindows.keys()));this.timeWindows.delete(i)}let o=this.timeWindows.get(n);o||(o=this.createEmptyTimeWindow(n),this.timeWindows.set(n,o)),o.requestCount++,e.status===2&&o.errorCount++,o.successRate=(o.requestCount-o.errorCount)/o.requestCount,o.throughput=o.requestCount/(o.windowDurationMs/1e3);let s=new Date(e.endTime??e.startTime);s>o.windowEnd&&(o.windowEnd=s)}createEmptyTimeWindow(e){return{windowStart:new Date(e),windowEnd:new Date(e+this.config.timeWindowMs),windowDurationMs:this.config.timeWindowMs,requestCount:0,errorCount:0,successRate:1,throughput:0,latency:this.createEmptyLatencyStats(),tokens:{totalInputTokens:0,totalOutputTokens:0,totalTokens:0,cacheReadTokens:0,cacheCreationTokens:0,reasoningTokens:0,totalCost:0,byProvider:new Map,byModel:new Map,bySpanType:new Map},costByProvider:new Map,costByModel:new Map}}createEmptyLatencyStats(){return{min:0,max:0,mean:0,median:0,p50:0,p75:0,p90:0,p95:0,p99:0,stdDev:0,count:0}}calculatePercentile(e,t){if(e.length===0)return 0;let n=Math.ceil(t/100*e.length)-1;return e[Math.max(0,n)]??0}calculateStdDev(e,t){if(e.length<2)return 0;let o=e.map(s=>(s-t)**2).reduce((s,i)=>s+i,0)/e.length;return Math.sqrt(o)}getLatencyStats(){if(this.latencyValues.length===0)return this.createEmptyLatencyStats();let e=[...this.latencyValues].sort((o,s)=>o-s),n=e.reduce((o,s)=>o+s,0)/e.length;return{min:e[0]??0,max:e[e.length-1]??0,mean:n,median:this.calculatePercentile(e,50),p50:this.calculatePercentile(e,50),p75:this.calculatePercentile(e,75),p90:this.calculatePercentile(e,90),p95:this.calculatePercentile(e,95),p99:this.calculatePercentile(e,99),stdDev:this.calculateStdDev(e,n),count:e.length}}getTokenStats(){return this.tokenTracker.getStats()}getCostByProvider(){return Array.from(this.costByProvider.values())}getCostByModel(){return Array.from(this.costByModel.values())}getTotalCost(){let e=0,t=Array.from(this.costByProvider.values());for(let n of t)e+=n.totalCost;return e}getTimeWindows(){return Array.from(this.timeWindows.values()).sort((e,t)=>e.windowStart.getTime()-t.windowStart.getTime())}getStatsForTimeRange(e,t){let n=this.spans.filter(a=>{let c=new Date(a.startTime);return c>=e&&c<=t}),o=new r({enableTimeWindows:!1});for(let a of n)o.recordSpan(a);let s=o.getSummary(),i=t.getTime()-e.getTime();return{windowStart:e,windowEnd:t,windowDurationMs:i,requestCount:s.totalSpans,errorCount:s.failedSpans,successRate:s.successRate,throughput:s.totalSpans/(i/1e3),latency:s.latency,tokens:s.tokens,costByProvider:new Map(s.costByProvider.map(a=>[a.provider,a])),costByModel:new Map(s.costByModel.map(a=>[a.model,a]))}}recordLatency(e,t){this.latencyValues.push(t);let n=this.spansByType.get(e)??0;this.spansByType.set(e,n+1);let o=new Date;this.firstSpanTime||(this.firstSpanTime=o),this.lastSpanTime=o,this.successCount++}getMetrics(){return this.getSummary()}getSummary(){let e=this.successCount+this.failureCount;return{totalSpans:e,successfulSpans:this.successCount,failedSpans:this.failureCount,successRate:e>0?this.successCount/e:1,latency:this.getLatencyStats(),tokens:this.getTokenStats(),costByProvider:this.getCostByProvider(),costByModel:this.getCostByModel(),totalCost:this.getTotalCost(),spansByType:Object.fromEntries(this.spansByType),firstSpanTime:this.firstSpanTime,lastSpanTime:this.lastSpanTime,trackingDurationMs:this.firstSpanTime&&this.lastSpanTime?this.lastSpanTime.getTime()-this.firstSpanTime.getTime():void 0}}getSpans(){return[...this.spans]}getTraces(){let e=new Map;for(let n of this.spans){let o=e.get(n.traceId)||[];o.push(n),e.set(n.traceId,o)}let t=[];for(let[n,o]of e){let s=o.find(d=>!d.parentSpanId)||o[0],i=o.filter(d=>d!==s),a=0;for(let d of o)d.durationMs&&(a=Math.max(a,d.durationMs));let c=o.some(d=>d.status===2),l=o.every(d=>d.status===1),u=c?"error":l?"ok":"partial";t.push({traceId:n,rootSpan:s,childSpans:i,totalDurationMs:a,spanCount:o.length,status:u})}return t}getTokenTracker(){return this.tokenTracker}reset(){this.spans=[],this.latencyValues=[],this.tokenTracker.reset(),this.timeWindows.clear(),this.spansByType.clear(),this.costByProvider.clear(),this.costByModel.clear(),this.successCount=0,this.failureCount=0,this.firstSpanTime=void 0,this.lastSpanTime=void 0}toJSON(){let e=this.getSummary();return{totalSpans:e.totalSpans,successfulSpans:e.successfulSpans,failedSpans:e.failedSpans,successRate:e.successRate,latency:e.latency,tokens:this.tokenTracker.toJSON(),costByProvider:e.costByProvider,costByModel:e.costByModel,totalCost:e.totalCost,spansByType:e.spansByType,firstSpanTime:e.firstSpanTime?.toISOString(),lastSpanTime:e.lastSpanTime?.toISOString(),trackingDurationMs:e.trackingDurationMs,timeWindows:this.config.enableTimeWindows?this.getTimeWindows().map(t=>({windowStart:t.windowStart.toISOString(),windowEnd:t.windowEnd.toISOString(),requestCount:t.requestCount,errorCount:t.errorCount,successRate:t.successRate,throughput:t.throughput})):void 0}}formatCost(e,t="USD"){return new Intl.NumberFormat("en-US",{style:"currency",currency:t,minimumFractionDigits:4}).format(e)}getFormattedSummary(){let e=this.getSummary(),t=e.latency,n=["=== Metrics Summary ===","","Request Statistics:",` Total requests: ${e.totalSpans.toLocaleString()}`,` Successful: ${e.successfulSpans.toLocaleString()}`,` Failed: ${e.failedSpans.toLocaleString()}`,` Success rate: ${(e.successRate*100).toFixed(2)}%`,"","Latency (ms):",` Min: ${t.min.toFixed(2)}`,` Max: ${t.max.toFixed(2)}`,` Mean: ${t.mean.toFixed(2)}`,` P50: ${t.p50.toFixed(2)}`,` P95: ${t.p95.toFixed(2)}`,` P99: ${t.p99.toFixed(2)}`,"","Token Usage:",` Input tokens: ${e.tokens.totalInputTokens.toLocaleString()}`,` Output tokens: ${e.tokens.totalOutputTokens.toLocaleString()}`,` Total tokens: ${e.tokens.totalTokens.toLocaleString()}`,"","Cost:",` Total: ${this.formatCost(e.totalCost)}`];if(e.costByProvider.length>0){n.push(""),n.push("Cost by Provider:");for(let o of e.costByProvider)n.push(` ${o.provider}: ${this.formatCost(o.totalCost)} (${o.requestCount} requests)`)}if(e.costByModel.length>0){n.push(""),n.push("Cost by Model:");for(let o of e.costByModel)n.push(` ${o.model}: ${this.formatCost(o.totalCost)} (${o.requestCount} requests)`)}if(e.trackingDurationMs){let o=e.trackingDurationMs/1e3,s=e.totalSpans/o;n.push(""),n.push(`Tracking duration: ${o.toFixed(1)}s (${s.toFixed(2)} req/s)`)}return n.join(`
161
161
  `)}},lE=null});var Lf,UZ=k(()=>{"use strict";Dr();HI();Lf=class{tracer=Tt.getTracer("neurolink-bridge");extractContext(e){let t={...e};typeof t.traceparent=="string"&&t.traceparent.includes(", ")&&(t.traceparent=t.traceparent.split(", ")[0]);let n=dv.extract(wr.active(),t);return Tt.getSpanContext(n)??null}injectContext(e,t=wr.active()){return dv.inject(t,e),e}createSpanFromOtelContext(e,t,n){return xe.createSpan(t,n,{},e.spanId,e.traceId)}async wrapWithTracing(e,t,n,o){let s=this.tracer.startSpan(e),i=xe.createSpan(t,e,{},void 0,s.spanContext().traceId);try{let a=await wr.with(Tt.setSpan(wr.active(),s),()=>n(i)),c=xe.endSpan(i,1);return s.setStatus({code:1}),o&&o(c),a}catch(a){let c=xe.endSpan(i,2,a instanceof Error?a.message:String(a));throw s.setStatus({code:2,message:a instanceof Error?a.message:String(a)}),s.recordException(a),o&&o(c),a}finally{s.end()}}exportToOtel(e){let t=this.tracer.startSpan(e.name,{startTime:new Date(e.startTime),attributes:this.filterAttributes(e.attributes)});for(let o of e.events)t.addEvent(o.name,this.filterEventAttributes(o.attributes),new Date(o.timestamp));let n=e.status===2?2:1;t.setStatus({code:n,message:e.statusMessage}),e.endTime?t.end(new Date(e.endTime)):t.end()}getCurrentTraceContext(){let e=Tt.getActiveSpan()?.spanContext();return e?{traceId:e.traceId,spanId:e.spanId}:null}filterAttributes(e){let t={};for(let[n,o]of Object.entries(e))typeof o=="string"||typeof o=="number"||typeof o=="boolean"?t[n]=o:o!=null&&(t[n]=JSON.stringify(o));return t}filterEventAttributes(e){if(e)return this.filterAttributes(e)}}});var yo=k(()=>{"use strict";Y2();HI()});async function Ke(r,e){let{name:t,tracer:n,kind:o=Cr.INTERNAL,attributes:s}=r;return n.startActiveSpan(t,{kind:o},async i=>{if(s)for(let[a,c]of Object.entries(s))c!==void 0&&i.setAttribute(a,c);try{let a=await e(i);return i.setStatus({code:Ie.OK}),a}catch(a){throw i.setStatus({code:Ie.ERROR,message:a instanceof Error?a.message:String(a)}),a instanceof Error&&i.recordException(a),a}finally{i.end()}})}async function dm(r,e){return Ke({...r,kind:Cr.CLIENT},e)}async function MAe(r,e,t,n){let{name:o,tracer:s,kind:i=Cr.CLIENT,attributes:a}=r,c=s.startSpan(o,{kind:i});if(a)for(let[h,y]of Object.entries(a))y!==void 0&&c.setAttribute(h,y);let l;try{l=await e(c)}catch(h){throw c.setStatus({code:Ie.ERROR,message:h instanceof Error?h.message:String(h)}),h instanceof Error&&c.recordException(h),c.end(),h}let u=t(l),d=!1,p=h=>{d||(d=!0,h?c.setStatus(h):c.setStatus({code:Ie.OK}),c.end())},f=(async function*(){try{for await(let h of u)yield h;p()}catch(h){throw h instanceof Error&&c.recordException(h),p({code:Ie.ERROR,message:h instanceof Error?h.message:String(h)}),h}})();return n(l,f)}async function JI(r,e,t,n){return MAe({...r,kind:Cr.CLIENT},e,t,n)}var Cn=k(()=>{"use strict";Dr()});var OAe={};te(OAe,{RAGASEvaluator:()=>Hv});var Hv,X2=k(()=>{"use strict";gu();Hke();H();yo();Cn();Vr();Hv=class{evaluationModel;providerName;threshold;promptBuilder;promptGenerator;constructor(e,t,n,o){this.evaluationModel=e||process.env.NEUROLINK_RAGAS_EVALUATION_MODEL||"gemini-1.5-flash",this.providerName=t||process.env.NEUROLINK_RAGAS_EVALUATION_PROVIDER||"vertex",this.threshold=n||Number(process.env.NEUROLINK_EVALUATION_THRESHOLD)||7,this.promptBuilder=new P2,this.promptGenerator=o}async evaluate(e){return Ke({name:"neurolink.evaluation.ragas",tracer:_e.sdk,attributes:{"evaluation.provider":this.providerName,"evaluation.model":this.evaluationModel}},async t=>{let n=xe.createSpan("evaluation","evaluation.ragas",{"evaluation.dimension":"relevance|accuracy|completeness","ai.provider":this.providerName,"ai.model":this.evaluationModel}),o=Date.now();try{let s=this.promptBuilder.buildEvaluationPrompt(e,this.promptGenerator),a=await(await dn.createProvider(this.providerName,this.evaluationModel)).generate({input:{text:s}});if(!a)throw new Error("Evaluation generation failed to return a result.");let c=a.content,l=this.parseEvaluationResponse(c),u=Date.now()-o,d={...l,isPassing:l.finalScore>=this.threshold,evaluationModel:this.evaluationModel,evaluationTime:u,attemptNumber:e.attemptNumber,rawEvaluationResponse:c};t.setAttribute("evaluation.relevance_score",d.relevanceScore),t.setAttribute("evaluation.accuracy_score",d.accuracyScore),t.setAttribute("evaluation.completeness_score",d.completenessScore),t.setAttribute("evaluation.final_score",d.finalScore),t.setAttribute("evaluation.is_passing",d.isPassing),n.durationMs=Date.now()-o;let p=xe.endSpan(n,1);return Ze().recordSpan(p),d}catch(s){n.durationMs=Date.now()-o;let i=xe.endSpan(n,2);throw i.statusMessage=s instanceof Error?s.message:String(s),Ze().recordSpan(i),s}})}parseEvaluationResponse(e){try{let t=e.replace(/```json\n|```/g,"").trim(),n=JSON.parse(t);return g.debug("Parsed evaluation response for RAGAS Evaluator:",n),{relevanceScore:Number(n.relevanceScore)||0,accuracyScore:Number(n.accuracyScore)||0,completenessScore:Number(n.completenessScore)||0,finalScore:Number(n.finalScore)||0,suggestedImprovements:n.suggestedImprovements||"No suggestions provided.",reasoning:n.reasoning||"No reasoning provided."}}catch(t){return g.error("Failed to parse evaluation response:",t),{relevanceScore:0,accuracyScore:0,completenessScore:0,finalScore:0,reasoning:"Error parsing evaluation response.",suggestedImprovements:"Error parsing evaluation response."}}}}});function FZ(r,e,t,n=5,o=4){let s=xe.createSpan("evaluation","evaluation.score",{"evaluation.dimension":"relevance|accuracy|completeness|overall",scores:{relevance:e.relevanceScore,accuracy:e.accuracyScore,completeness:e.completenessScore,overall:e.finalScore}}),i=Date.now();try{let a=e.finalScore>=t,c={relevance:e.relevanceScore,accuracy:e.accuracyScore,completeness:e.completenessScore,overall:e.finalScore,isOffTopic:e.finalScore<n,alertSeverity:a?"none":e.finalScore<o?"high":"medium",reasoning:e.reasoning,suggestedImprovements:e.suggestedImprovements,evaluationModel:e.evaluationModel,evaluationTime:e.evaluationTime,evaluationAttempt:e.attemptNumber,responseContent:r.aiResponse,queryContent:r.userQuery};s.durationMs=Date.now()-i;let l=xe.endSpan(s,1);return Ze().recordSpan(l),c}catch(a){s.durationMs=Date.now()-i;let c=xe.endSpan(s,2);throw c.statusMessage=a instanceof Error?a.message:String(a),Ze().recordSpan(c),a}}var NAe=k(()=>{"use strict";yo()});function vl(r,e){return{codes:e,create:(t,n,o)=>new Uf(n,e[t],r,o)}}var Uf,uE=k(()=>{"use strict";Uf=class extends Error{code;feature;retryable;details;cause;constructor(e,t,n,o){super(e),this.name=`${n}Error`,this.code=t,this.feature=n,this.retryable=o?.retryable??!1,this.details=o?.details,this.cause=o?.cause}}});var sy,DAe=k(()=>{"use strict";H();sy=class{items=new Map;aliasMap=new Map;initialized=!1;initPromise=null;async ensureInitialized(){if(!this.initialized){if(this.initPromise)return this.initPromise;this.initPromise=this.registerAll(),await this.initPromise,this.initialized=!0}}register(e,t,n=[],o){this.items.set(e,{factory:t,aliases:n,metadata:o});for(let s of n)this.aliasMap.set(s.toLowerCase(),e);g.debug(`Registered ${e} with aliases: ${n.join(", ")}`)}async create(e,t){await this.ensureInitialized();let n=this.resolveName(e),o=this.items.get(n);if(!o)throw new Error(`Unknown item: ${e}`);return o.factory(t)}resolveName(e){let t=e.toLowerCase();return this.aliasMap.get(t)||e}has(e){let t=this.resolveName(e);return this.items.has(t)}getAvailable(){return Array.from(this.items.keys())}getAliases(){return new Map(this.aliasMap)}clear(){this.items.clear(),this.aliasMap.clear(),this.initialized=!1,this.initPromise=null}}});var dE,LAe=k(()=>{"use strict";H();dE=class{items=new Map;initialized=!1;initPromise=null;async ensureInitialized(){if(!this.initialized){if(this.initPromise)return this.initPromise;this.initPromise=this.registerAll(),await this.initPromise,this.initialized=!0}}register(e,t,n=[],o){let s=o?.metadata??{};this.items.set(e,{factory:t,metadata:s});for(let i of n)this.items.set(i.toLowerCase(),{factory:t,metadata:s});g.debug(`Registered ${e} in registry`)}async get(e){await this.ensureInitialized();let t=this.items.get(e);if(t)return t.instance||(t.instance=await t.factory()),t.instance}has(e){return this.items.has(e)}list(){return Array.from(this.items.entries()).map(([e,t])=>({id:e,metadata:t.metadata}))}clear(){this.items.clear(),this.initialized=!1,this.initPromise=null}isInitialized(){return this.initialized}}});async function UAe(r,e){let{maxRetries:t,baseDelayMs:n,maxDelayMs:o=3e4,shouldRetry:s}=e,i;for(let a=0;a<=t;a++)try{return await r()}catch(c){if(i=c,s&&!s(i))throw i;if(a<t){let l=Math.min(n*2**a,o);await new Promise(u=>setTimeout(u,l))}}throw i}var FAe=k(()=>{"use strict"});var $Z={};te($Z,{AsyncLocalStorage:()=>H_t,Buffer:()=>Lkt,Channel:()=>_kt,DatabaseSync:()=>Dkt,Duplex:()=>K_t,EventEmitter:()=>dr,Http2ServerRequest:()=>zkt,Http2ServerResponse:()=>jkt,Interface:()=>Nkt,MIMEType:()=>Kkt,PassThrough:()=>J_t,PerformanceObserver:()=>Skt,Readable:()=>BAe,ReadableStream:()=>Y_t,Resolver:()=>bkt,TextDecoder:()=>GAe,TextEncoder:()=>Z2,Transform:()=>W_t,URL:()=>akt,URLSearchParams:()=>ckt,Worker:()=>Akt,Writable:()=>zAe,access:()=>E0t,appendFile:()=>n0t,appendFileSync:()=>O_t,arch:()=>B0t,arrayBuffer:()=>Gkt,basename:()=>$_t,builtinModules:()=>nkt,callbackify:()=>gkt,channel:()=>Ekt,chmodSync:()=>r0t,clearInterval:()=>Wkt,clearTimeout:()=>qkt,closeSync:()=>a0t,connect:()=>V0t,constants:()=>Ukt,copyFileSync:()=>s0t,cpSync:()=>N_t,cpus:()=>L0t,createConnection:()=>q0t,createGunzip:()=>Z0t,createGzip:()=>Q0t,createHash:()=>$Ae,createHmac:()=>A_t,createInterface:()=>Okt,createReadStream:()=>y0t,createRequire:()=>rkt,createServer:()=>D_t,createWriteStream:()=>h0t,debug:()=>mkt,debuglog:()=>jAe,default:()=>C_t,deflateSync:()=>W0t,deprecate:()=>fkt,deserialize:()=>Rkt,dirname:()=>F_t,exec:()=>R0t,execFile:()=>I0t,execFileSync:()=>P0t,execSync:()=>A0t,existsSync:()=>Q_t,extname:()=>B_t,fileURLToPath:()=>lkt,finished:()=>Z_t,format:()=>ikt,freemem:()=>U0t,fstatSync:()=>c0t,get:()=>G0t,gunzip:()=>X0t,gunzipSync:()=>K0t,gzip:()=>Y0t,gzipSync:()=>J0t,hasSubscribers:()=>kkt,homedir:()=>O0t,hostname:()=>D0t,inflateSync:()=>H0t,inherits:()=>dkt,inspect:()=>Q2,isAbsolute:()=>j_t,isBuiltin:()=>okt,isDeepStrictEqual:()=>hkt,isIP:()=>Bkt,isIPv4:()=>$kt,isIPv6:()=>Fkt,isMainThread:()=>Ikt,join:()=>L_t,lookup:()=>vkt,mkdir:()=>b0t,mkdirSync:()=>l0t,monitorEventLoopDelay:()=>wkt,normalize:()=>q_t,ok:()=>ekt,openSync:()=>i0t,parentPort:()=>Pkt,parse:()=>skt,pathToFileURL:()=>ukt,performance:()=>Tkt,pipeline:()=>X_t,platform:()=>M0t,posix:()=>V_t,promises:()=>R_t,promisify:()=>pkt,randomBytes:()=>I_t,randomUUID:()=>P_t,readFile:()=>x0t,readFileSync:()=>e0t,readdir:()=>S0t,readdirSync:()=>d0t,realpathSync:()=>o0t,relative:()=>z_t,release:()=>z0t,rename:()=>_0t,renameSync:()=>m0t,request:()=>j0t,resolve:()=>U_t,rm:()=>k0t,rmSync:()=>g0t,rmdirSync:()=>f0t,sep:()=>G_t,serialize:()=>Ckt,setInterval:()=>Hkt,setTimeout:()=>Vkt,spawn:()=>C0t,stat:()=>T0t,statSync:()=>u0t,strict:()=>tkt,tmpdir:()=>N0t,toUSVString:()=>ykt,totalmem:()=>F0t,type:()=>$0t,types:()=>xkt,unlink:()=>w0t,unlinkSync:()=>p0t,webcrypto:()=>M_t,workerData:()=>Mkt,writeFile:()=>v0t,writeFileSync:()=>t0t});var Zo,ci,C_t,R_t,$Ae,A_t,I_t,P_t,M_t,O_t,N_t,D_t,L_t,U_t,F_t,$_t,B_t,z_t,j_t,G_t,V_t,q_t,dr,H_t,BAe,zAe,W_t,K_t,J_t,Y_t,X_t,Z_t,Q_t,e0t,t0t,r0t,n0t,o0t,s0t,i0t,a0t,c0t,l0t,u0t,d0t,p0t,m0t,f0t,g0t,h0t,y0t,x0t,v0t,b0t,T0t,S0t,w0t,E0t,_0t,k0t,C0t,R0t,A0t,I0t,P0t,M0t,O0t,N0t,D0t,L0t,U0t,F0t,$0t,B0t,z0t,j0t,G0t,V0t,q0t,H0t,W0t,K0t,J0t,Y0t,X0t,Z0t,Q0t,ekt,tkt,rkt,nkt,okt,skt,ikt,akt,ckt,lkt,ukt,dkt,pkt,jAe,mkt,Q2,fkt,gkt,hkt,ykt,xkt,GAe,Z2,vkt,bkt,Tkt,Skt,wkt,Ekt,_kt,kkt,Ckt,Rkt,Akt,Ikt,Pkt,Mkt,Okt,Nkt,Dkt,Lkt,Ukt,Fkt,$kt,Bkt,zkt,jkt,Gkt,VAe,Vkt,qkt,Hkt,Wkt,Kkt,lo=k(()=>{Zo=()=>{},ci=async()=>{},C_t={},R_t={readFile:ci,writeFile:ci,mkdir:ci,stat:ci,readdir:ci,unlink:ci,access:ci,rm:ci,rename:ci},$Ae=r=>{let e=[];return{update(t){return e.push(typeof t=="string"?new Z2().encode(t):t),this},digest(t){let n=0;for(let s of e)for(let i=0;i<s.length;i++)n=(n<<5)-n+s[i]|0;let o=(n>>>0).toString(16).padStart(8,"0");return t==="hex"?o:t==="base64"?btoa(o):o}}},A_t=(r,e)=>$Ae(r),I_t=r=>new Uint8Array(r||32),P_t=()=>globalThis.crypto?.randomUUID?.()||Math.random().toString(36),M_t=globalThis.crypto,O_t=()=>{throw new Error("[NeuroLink:browser] fs.appendFileSync is not supported in browser runtime \u2014 use server-side execution")},N_t=()=>{throw new Error("[NeuroLink:browser] fs.cpSync is not supported in browser runtime \u2014 use server-side execution")},D_t=()=>({listen:Zo,close:Zo,on:Zo}),L_t=(...r)=>r.join("/"),U_t=(...r)=>r.join("/"),F_t=r=>r||"",$_t=r=>r?.split?.("/")?.pop?.()||"",B_t=r=>{let e=r?.match?.(/\.[^.]+$/);return e?e[0]:""},z_t=(r,e)=>e||"",j_t=()=>!1,G_t="/",V_t={normalize:r=>r,join:(...r)=>r.join("/"),resolve:(...r)=>r.join("/"),sep:"/"},q_t=r=>r,dr=class{on(){return this}off(){return this}emit(){return this}once(){return this}removeListener(){return this}addListener(){return this}},H_t=class{getStore(){}run(r,e,...t){return e(...t)}enterWith(){}disable(){}},BAe=class{pipe(){return this}on(){return this}read(){return null}push(){}destroy(){}},zAe=class{write(){return!0}end(){}on(){return this}destroy(){}},W_t=class{push(){}on(){return this}},K_t=class{on(){return this}},J_t=class{pipe(){return this}on(){return this}},Y_t=globalThis.ReadableStream||class{},X_t=Zo,Z_t=Zo,Q_t=()=>!1,e0t=()=>"",t0t=Zo,r0t=Zo,n0t=ci,o0t=r=>r,s0t=Zo,i0t=()=>0,a0t=Zo,c0t=()=>({}),l0t=Zo,u0t=()=>({}),d0t=()=>[],p0t=Zo,m0t=Zo,f0t=Zo,g0t=Zo,h0t=()=>new zAe,y0t=()=>new BAe,x0t=ci,v0t=ci,b0t=ci,T0t=ci,S0t=ci,w0t=ci,E0t=ci,_0t=ci,k0t=ci,C0t=()=>({on:Zo,stdout:{on:Zo},stderr:{on:Zo},kill:Zo}),R0t=(r,e)=>e?.(null,"",""),A0t=()=>"",I0t=(r,e,t)=>{typeof e=="function"?e(null,"",""):t?.(null,"","")},P0t=()=>"",M0t="browser",O0t=()=>"/",N0t=()=>"/tmp",D0t=()=>"browser",L0t=()=>[{}],U0t=()=>0,F0t=()=>0,$0t=()=>"Browser",B0t=()=>"wasm",z0t=()=>"0",j0t=()=>({}),G0t=()=>({}),V0t=()=>({}),q0t=()=>({}),H0t=()=>new Uint8Array,W0t=()=>new Uint8Array,K0t=()=>new Uint8Array,J0t=()=>new Uint8Array,Y0t=(r,e)=>e?.(null,r),X0t=(r,e)=>e?.(null,r),Z0t=()=>({}),Q0t=()=>({}),ekt=Zo,tkt={},rkt=()=>()=>({}),nkt=[],okt=()=>!1,skt=r=>({pathname:r||"",hostname:"",protocol:"",search:"",hash:""}),ikt=()=>"",akt=globalThis.URL,ckt=globalThis.URLSearchParams,lkt=r=>typeof r=="string"?r.replace("file://",""):r,ukt=r=>new globalThis.URL("file://"+r),dkt=(r,e)=>{e&&(r.super_=e,Object.setPrototypeOf(r.prototype,e.prototype))},pkt=r=>(...e)=>new Promise((t,n)=>r(...e,(o,s)=>o?n(o):t(s))),jAe=r=>{let e=(...t)=>{};return e.enabled=!1,e},mkt=jAe,Q2=r=>{try{return JSON.stringify(r,null,2)}catch{return String(r)}};Q2.custom=Symbol.for("nodejs.util.inspect.custom");Q2.colors={};Q2.styles={};fkt=r=>r,gkt=r=>(...e)=>{let t=e.pop();r(...e).then(n=>t(null,n)).catch(t)},hkt=(r,e)=>JSON.stringify(r)===JSON.stringify(e),ykt=r=>String(r),xkt={isPromise:r=>r instanceof Promise,isDate:r=>r instanceof Date,isRegExp:r=>r instanceof RegExp,isNativeError:r=>r instanceof Error,isArrayBuffer:r=>r instanceof ArrayBuffer,isTypedArray:r=>ArrayBuffer.isView(r),isUint8Array:r=>r instanceof Uint8Array,isProxy:()=>!1},GAe=globalThis.TextDecoder,Z2=globalThis.TextEncoder,vkt=(r,e)=>e?.(null,"127.0.0.1",4),bkt=class{},Tkt=globalThis.performance||{now:()=>Date.now()},Skt=class{observe(){}disconnect(){}},wkt=()=>({enable:Zo,disable:Zo,percentile:()=>0}),Ekt=()=>({}),_kt=class{},kkt=()=>!1,Ckt=()=>new Uint8Array,Rkt=Zo,Akt=class{},Ikt=!0,Pkt=null,Mkt=null,Okt=()=>({}),Nkt=class{},Dkt=class{},Lkt=globalThis.Buffer||class extends Uint8Array{static from(e,t){if(typeof e=="string"){let n=(t||"utf8").toLowerCase();if(n==="base64"){let o=atob(e),s=new Uint8Array(o.length);for(let i=0;i<o.length;i++)s[i]=o.charCodeAt(i);return s}if(n==="hex"){let o=new Uint8Array(e.length/2);for(let s=0;s<e.length;s+=2)o[s/2]=parseInt(e.substr(s,2),16);return o}return new Z2().encode(e)}return new Uint8Array(e)}static alloc(e){return new Uint8Array(e)}static isBuffer(e){return e instanceof Uint8Array}static concat(e){let t=e.reduce((s,i)=>s+i.length,0),n=new Uint8Array(t),o=0;for(let s of e)n.set(s,o),o+=s.length;return n}static byteLength(e,t){return t==="base64"?Math.ceil(e.length*3/4):new Z2().encode(e).length}toString(e){let t=(e||"utf8").toLowerCase();if(t==="hex")return Array.from(new Uint8Array(this.buffer,this.byteOffset,this.byteLength)).map(n=>n.toString(16).padStart(2,"0")).join("");if(t==="base64"){let n="";for(let o=0;o<this.length;o++)n+=String.fromCharCode(this[o]);return btoa(n)}return new GAe().decode(this)}},Ukt={F_OK:0,R_OK:4,W_OK:2,X_OK:1},Fkt=()=>!1,$kt=()=>!1,Bkt=()=>0,zkt=class{},jkt=class{},Gkt=async()=>new ArrayBuffer(0),VAe=r=>({[Symbol.toPrimitive](){return r},ref(){return this},unref(){return this},hasRef(){return!1},refresh(){return this},close(){}}),Vkt=(...r)=>VAe(globalThis.setTimeout(...r)),qkt=globalThis.clearTimeout,Hkt=(...r)=>VAe(globalThis.setInterval(...r)),Wkt=globalThis.clearInterval,Kkt=class{constructor(r){this.type=r}toString(){return this.type}}});var pE,qAe=k(()=>{"use strict";lo();pE=class{emitter=new dr;on(e,t){return this.emitter.on(e,t),this}off(e,t){return this.emitter.off(e,t),this}emit(e,...t){return this.emitter.emit(e,...t)}once(e,t){return this.emitter.once(e,t),this}removeAllListeners(e){return this.emitter.removeAllListeners(e),this}}});var iy=k(()=>{"use strict";uE();DAe();LAe();FAe();qAe()});function HAe(r){return r.retryable?!0:[eB.TIMEOUT_ERROR,eB.RATE_LIMIT_ERROR].includes(r.code)}function WAe(r){return r instanceof Uf&&r.feature==="Evaluation"}function KAe(r,e,t){return ja.create("EVALUATION_FAILED",r,{retryable:!1,details:{evaluationContext:e},cause:t})}function JAe(r,e){return ja.create("PARSE_ERROR","Failed to parse evaluation response from judge LLM",{retryable:!1,details:{rawResponseLength:r.length},cause:e})}function tB(r,e=[]){return ja.create("STRATEGY_NOT_FOUND",`Evaluation strategy "${r}" not found in registry`,{retryable:!1,details:{requestedStrategy:r,availableStrategies:e}})}function YAe(r,e,t,n){return ja.create("PROVIDER_ERROR",r,{retryable:n?.retryable??!1,details:{provider:e,errorMessage:t?.message},cause:t})}function XAe(r,e,t,n){return ja.create("MAX_RETRIES_EXCEEDED",`Maximum retry attempts (${r}) exceeded. Last score: ${e}, threshold: ${t}`,{retryable:!1,details:{attempts:r,lastScore:e,threshold:t,evaluationContext:n}})}function ZAe(r,e,t){return ja.create("BATCH_EVALUATION_ERROR",`Batch evaluation failed: ${r} of ${e} evaluations failed`,{retryable:!1,details:{failedCount:r,totalCount:e,successCount:e-r,errors:t.map(n=>({index:n.index,message:n.error.message}))}})}function Wv(r,e){return ja.create("CONFIGURATION_ERROR",r,{retryable:!1,details:{configIssue:e}})}function QAe(r){return{userQueryLength:r.userQuery?.length,aiResponseLength:r.aiResponse?.length,attemptNumber:r.attemptNumber,previousScores:r.previousEvaluations?.map(e=>e.finalScore),evaluationModel:void 0,provider:r.provider}}var eB,ja,mE=k(()=>{"use strict";iy();eB={EVALUATION_FAILED:"EVALUATION_FAILED",PARSE_ERROR:"PARSE_ERROR",STRATEGY_NOT_FOUND:"STRATEGY_NOT_FOUND",PROVIDER_ERROR:"PROVIDER_ERROR",CONFIGURATION_ERROR:"CONFIGURATION_ERROR",CUSTOM_EVALUATOR_ERROR:"CUSTOM_EVALUATOR_ERROR",BATCH_EVALUATION_ERROR:"BATCH_EVALUATION_ERROR",AGGREGATION_ERROR:"AGGREGATION_ERROR",REGISTRY_ERROR:"REGISTRY_ERROR",MAX_RETRIES_EXCEEDED:"MAX_RETRIES_EXCEEDED",TIMEOUT_ERROR:"TIMEOUT_ERROR",RATE_LIMIT_ERROR:"RATE_LIMIT_ERROR"},ja=vl("Evaluation",eB)});var eIe=k(()=>{"use strict";mE()});function tIe(){hu.on("scorer:start",r=>{g.info(`[SCORER] ${r.scorerName} started at ${new Date(r.timestamp).toISOString()}`)}),hu.on("scorer:end",r=>{g.info(`[SCORER] ${r.scorerName} completed: score=${r.result.score.toFixed(1)}, passed=${r.result.passed}, duration=${r.duration}ms`)}),hu.on("scorer:error",r=>{g.error(`[SCORER] ${r.scorerName} error: ${r.error}`)}),hu.on("pipeline:start",r=>{g.info(`[PIPELINE] ${r.pipelineName} started with ${r.scorerCount} scorers (correlationId: ${r.correlationId})`)}),hu.on("pipeline:end",r=>{g.info(`[PIPELINE] ${r.pipelineName} completed: overall=${r.result.overallScore.toFixed(1)}, passed=${r.result.passed}, duration=${r.duration}ms`)}),hu.on("pipeline:error",r=>{g.error(`[PIPELINE] ${r.pipelineName} error: ${r.error}`)})}function rIe(r){hu.on("scorer:end",e=>{r.recordScorer(e.scorerId,e.scorerName,e.result)}),hu.on("pipeline:end",e=>{r.recordPipeline(e.result)})}function nIe(r){return{"scorer.id":r.scorerId,"scorer.name":r.scorerName,"scorer.score":r.score,"scorer.normalizedScore":r.normalizedScore,"scorer.passed":r.passed,"scorer.threshold":r.threshold,"scorer.computeTime":r.computeTime,...r.confidence!==void 0&&{"scorer.confidence":r.confidence},...r.error&&{"scorer.error":r.error}}}function oIe(r){return{"pipeline.name":r.pipelineConfig.name??"unnamed","pipeline.overallScore":r.overallScore,"pipeline.passed":r.passed,"pipeline.aggregationMethod":r.aggregationMethod,"pipeline.scorerCount":r.scores.length,"pipeline.totalComputeTime":r.totalComputeTime,"pipeline.errorCount":r.errors.length,"pipeline.skippedCount":r.skippedScorers.length,...r.correlationId&&{"pipeline.correlationId":r.correlationId}}}var YI,hu,BZ=k(()=>{"use strict";H();YI=class{_handlers=new Map;_traceContext;_enabled=!0;set enabled(e){this._enabled=e}get enabled(){return this._enabled}setTraceContext(e){this._traceContext=e}clearTraceContext(){this._traceContext=void 0}getTraceContext(){return this._traceContext}on(e,t){let n=this._handlers.get(e);return n||(n=new Set,this._handlers.set(e,n)),n.add(t),()=>{this._handlers.get(e)?.delete(t)}}off(e,t){this._handlers.get(e)?.delete(t)}async emit(e,t){if(!this._enabled)return;let n=this._handlers.get(e);if(!n||n.size===0)return;let o={...t,traceContext:this._traceContext},s=[];for(let i of n)try{let a=i(o);a instanceof Promise&&s.push(a.catch(c=>{g.error(`Event handler error for ${e}`,{error:c})}))}catch(a){g.error(`Event handler error for ${e}`,{error:a})}await Promise.all(s)}clear(){this._handlers.clear()}listenerCount(e){return this._handlers.get(e)?.size??0}},hu=new YI});function sIe(r){return new XI(r)}function iIe(r){let e=new XI(r);return e.start(),e}function aIe(){let r=[];return{scores:r,score:async e=>(r.push(e),{id:`score-${r.length}`}),shutdown:async()=>{}}}var XI,cIe=k(()=>{"use strict";H();BZ();XI=class{_config;_unsubscribers=[];_traceIdMap=new Map;constructor(e){this._config={scorePrefix:"eval",includeMetadata:!0,tags:[],sendPipelineScores:!0,sendScorerScores:!0,...e}}start(){if(!(this._unsubscribers.length>0)){if(this._config.sendScorerScores){let e=hu.on("scorer:end",t=>{this._sendScorerScore(t.result,t.traceContext?.traceId)});this._unsubscribers.push(e)}if(this._config.sendPipelineScores){let e=hu.on("pipeline:end",t=>{this._sendPipelineScores(t.result,t.traceContext?.traceId)});this._unsubscribers.push(e)}g.debug("Langfuse adapter started")}}stop(){for(let e of this._unsubscribers)e();this._unsubscribers=[],this._traceIdMap.clear(),g.debug("Langfuse adapter stopped")}async _sendScorerScore(e,t){try{let n=`${this._config.scorePrefix}.${e.scorerId}`,o=e.normalizedScore;await this._config.client.score({name:n,value:o,traceId:t,comment:e.reasoning,metadata:this._config.includeMetadata?{passed:e.passed,threshold:e.threshold,computeTime:e.computeTime,confidence:e.confidence,...e.metadata??{}}:void 0}),g.debug(`Sent score to Langfuse: ${n}=${o}`)}catch(n){g.error("Failed to send score to Langfuse",{scorerId:e.scorerId,error:n instanceof Error?n.message:String(n)})}}async _sendPipelineScores(e,t){let n=t??e.correlationId,o=e.pipelineConfig.name??"unnamed";try{await this._config.client.score({name:`${this._config.scorePrefix}.pipeline.${o}.overall`,value:e.overallScore/10,traceId:n,comment:`Pipeline evaluation: ${e.passed?"PASSED":"FAILED"}`,metadata:this._config.includeMetadata?{passed:e.passed,aggregationMethod:e.aggregationMethod,scorerCount:e.scores.length,totalComputeTime:e.totalComputeTime,errorCount:e.errors.length}:void 0}),g.debug(`Sent pipeline score to Langfuse: ${o}=${e.overallScore/10}`)}catch(s){g.error("Failed to send pipeline score to Langfuse",{pipelineName:o,error:s instanceof Error?s.message:String(s)})}}async sendScore(e,t,n){let o=`${this._config.scorePrefix}.${e}`;await this._config.client.score({name:o,value:t,traceId:n?.traceId,comment:n?.comment,metadata:n?.metadata})}async shutdown(){this.stop(),this._config.client.shutdown&&await this._config.client.shutdown()}}});var lIe=k(()=>{"use strict";cIe();BZ()});var ZI,ay,pm,Kv,QI=k(()=>{"use strict";ZI=class extends Error{constructor(t,n){super(t);this.confirmationId=n;this.name="HITLError"}confirmationId},ay=class extends ZI{constructor(t,n,o,s){super(t,s);this.toolName=n;this.reason=o;this.name="HITLUserRejectedError"}toolName;reason},pm=class extends ZI{constructor(t,n,o){super(t,n);this.timeout=o;this.name="HITLTimeoutError"}timeout},Kv=class extends ZI{constructor(e){super(e),this.name="HITLConfigurationError"}}});var tP={};te(tP,{CircuitBreaker:()=>fE,ERROR_CODES:()=>ut,ErrorFactory:()=>pe,NeuroLinkError:()=>Fe,isAbortError:()=>Hr,isRecoverableError:()=>eP,isRetriableError:()=>rB,logStructuredError:()=>jZ,withRetry:()=>zZ,withTimeout:()=>je});async function je(r,e,t){let n=new Promise((o,s)=>{setTimeout(()=>{s(t||new Error(`Operation timed out after ${e}ms`))},e)});return Promise.race([r,n])}async function zZ(r,e){let{maxAttempts:t,delayMs:n,isRetriable:o=()=>!0,onRetry:s}=e,i;for(let a=1;a<=t;a++)try{return await r()}catch(c){if(i=c instanceof Error?c:new Error(String(c)),a===t||!o(i))throw i;s&&s(a,i),await new Promise(l=>setTimeout(l,n))}throw i||new Error("Retry operation failed with no error information")}function Hr(r){return!!(r instanceof DOMException&&r.name==="AbortError"||r instanceof Error&&r.name==="AbortError"||r instanceof Fe&&r.category==="abort"||r instanceof Error&&(r.message?.includes("This operation was aborted")||r.message?.includes("The operation was aborted")||r.message?.includes("The user aborted a request")))}function rB(r){return r instanceof Fe?r.retriable:r instanceof pm?!1:[/timeout/i,/network/i,/connection/i,/temporary/i,/rate limit/i,/quota/i,/503/i,/502/i,/504/i].some(t=>t.test(r.message))}function eP(r){let e=r;if("retriable"in r&&typeof e.retriable=="boolean")return e.retriable;let t=r.message?.toLowerCase()||"";return!!(t.includes("rate limit")||t.includes("too many requests")||/\b429\b/.test(t)||t.includes("timeout")||t.includes("etimedout")||t.includes("timed out")||t.includes("econnreset")||t.includes("econnrefused")||t.includes("network")||t.includes("socket")||/\b50[0234]\b/.test(t))}function jZ(r,e){let t={...r.toJSON(),...e};switch(r.severity){case"critical":g.error(`[CRITICAL] ${r.message}`,t);break;case"high":g.error(`[HIGH] ${r.message}`,t);break;case"medium":g.warn(`[MEDIUM] ${r.message}`,t);break;case"low":g.info(`[LOW] ${r.message}`,t);break}}var ut,Fe,pe,fE,It=k(()=>{"use strict";H();Dt();QI();ut={TOOL_NOT_FOUND:"TOOL_NOT_FOUND",TOOL_EXECUTION_FAILED:"TOOL_EXECUTION_FAILED",TOOL_TIMEOUT:"TOOL_TIMEOUT",TOOL_VALIDATION_FAILED:"TOOL_VALIDATION_FAILED",INVALID_PARAMETERS:"INVALID_PARAMETERS",MISSING_REQUIRED_PARAM:"MISSING_REQUIRED_PARAM",MEMORY_EXHAUSTED:"MEMORY_EXHAUSTED",NETWORK_ERROR:"NETWORK_ERROR",PERMISSION_DENIED:"PERMISSION_DENIED",PROVIDER_NOT_AVAILABLE:"PROVIDER_NOT_AVAILABLE",PROVIDER_AUTH_FAILED:"PROVIDER_AUTH_FAILED",PROVIDER_QUOTA_EXCEEDED:"PROVIDER_QUOTA_EXCEEDED",OPERATION_ABORTED:"OPERATION_ABORTED",INVALID_CONFIGURATION:"INVALID_CONFIGURATION",MISSING_CONFIGURATION:"MISSING_CONFIGURATION",INVALID_VIDEO_RESOLUTION:"INVALID_VIDEO_RESOLUTION",INVALID_VIDEO_LENGTH:"INVALID_VIDEO_LENGTH",INVALID_VIDEO_ASPECT_RATIO:"INVALID_VIDEO_ASPECT_RATIO",INVALID_VIDEO_AUDIO:"INVALID_VIDEO_AUDIO",INVALID_VIDEO_MODE:"INVALID_VIDEO_MODE",MISSING_VIDEO_IMAGE:"MISSING_VIDEO_IMAGE",EMPTY_VIDEO_PROMPT:"EMPTY_VIDEO_PROMPT",VIDEO_PROMPT_TOO_LONG:"VIDEO_PROMPT_TOO_LONG",EMPTY_IMAGE_PATH:"EMPTY_IMAGE_PATH",INVALID_IMAGE_TYPE:"INVALID_IMAGE_TYPE",IMAGE_TOO_LARGE:"IMAGE_TOO_LARGE",IMAGE_TOO_SMALL:"IMAGE_TOO_SMALL",INVALID_IMAGE_FORMAT:"INVALID_IMAGE_FORMAT",PDF_PAGE_LIMIT_EXCEEDED:"PDF_PAGE_LIMIT_EXCEEDED",RATE_LIMITER_QUEUE_FULL:"RATE_LIMITER_QUEUE_FULL",RATE_LIMITER_QUEUE_TIMEOUT:"RATE_LIMITER_QUEUE_TIMEOUT",RATE_LIMITER_RESET:"RATE_LIMITER_RESET",SCORER_NOT_FOUND:"SCORER_NOT_FOUND",EVALUATION_VALIDATION_FAILED:"EVALUATION_VALIDATION_FAILED",EVALUATION_TIMEOUT:"EVALUATION_TIMEOUT",EVALUATION_EXECUTION_FAILED:"EVALUATION_EXECUTION_FAILED",MISSING_PPT_PROPERTIES:"MISSING_PPT_PROPERTIES",INVALID_PPT_PAGES:"INVALID_PPT_PAGES",INVALID_PPT_FORMAT:"INVALID_PPT_FORMAT",INVALID_PPT_PROVIDER:"INVALID_PPT_PROVIDER",INVALID_PPT_OUTPUT_OPTIONS:"INVALID_PPT_OUTPUT_OPTIONS",INVALID_PPT_OUTPUT_PATH:"INVALID_PPT_OUTPUT_PATH",INVALID_PPT_LOGO_PATH:"INVALID_PPT_LOGO_PATH",INVALID_PPT_MODE:"INVALID_PPT_MODE",INVALID_PPT_PROMPT:"INVALID_PPT_PROMPT"},Fe=class extends Error{code;category;severity;retriable;context;timestamp;toolName;serverId;constructor(e){super(e.message),this.name="NeuroLinkError",this.code=e.code,this.category=e.category,this.severity=e.severity,this.retriable=e.retriable,this.context=e.context||{},this.timestamp=new Date,this.toolName=e.toolName,this.serverId=e.serverId,e.originalError&&(this.stack=e.originalError.stack,this.context.originalMessage=e.originalError.message)}toJSON(){return{code:this.code,message:this.message,category:this.category,severity:this.severity,retriable:this.retriable,context:this.context,timestamp:this.timestamp,toolName:this.toolName,serverId:this.serverId}}},pe=class{static toolNotFound(e,t){return new Fe({code:ut.TOOL_NOT_FOUND,message:`Tool '${e}' not found`,category:"validation",severity:"medium",retriable:!1,context:{toolName:e,availableTools:t},toolName:e})}static toolExecutionFailed(e,t,n){return new Fe({code:ut.TOOL_EXECUTION_FAILED,message:`Tool '${e}' execution failed: ${t.message}`,category:"execution",severity:"high",retriable:!0,originalError:t,toolName:e,serverId:n})}static toolTimeout(e,t,n){return new Fe({code:ut.TOOL_TIMEOUT,message:`Tool '${e}' timed out after ${t}ms`,category:"timeout",severity:"high",retriable:!0,context:{timeoutMs:t},toolName:e,serverId:n})}static invalidParameters(e,t,n){return new Fe({code:ut.INVALID_PARAMETERS,message:`Invalid parameters for tool '${e}': ${t.message}`,category:"validation",severity:"medium",retriable:!1,context:{providedParams:n},originalError:t,toolName:e})}static networkError(e,t,n){return new Fe({code:ut.NETWORK_ERROR,message:`Network error in tool '${e}': ${t.message}`,category:"network",severity:"high",retriable:!0,originalError:t,toolName:e,serverId:n})}static memoryExhausted(e,t){return new Fe({code:ut.MEMORY_EXHAUSTED,message:`Memory exhausted during tool '${e}' execution (${t}MB used)`,category:"resource",severity:"critical",retriable:!1,context:{memoryUsageMB:t},toolName:e})}static aborted(e){let t=new Fe({code:ut.OPERATION_ABORTED,message:e?.message||"The operation was aborted",category:"abort",severity:"low",retriable:!1,context:{},originalError:e});return t.name="AbortError",t}static missingConfiguration(e,t){return new Fe({code:ut.MISSING_CONFIGURATION,message:`Missing required configuration: ${e}`,category:"validation",severity:"high",retriable:!1,context:t||{}})}static invalidConfiguration(e,t,n){return new Fe({code:ut.INVALID_CONFIGURATION,message:`Invalid configuration for '${e}': ${t}`,category:"validation",severity:"high",retriable:!1,context:n||{}})}static invalidVideoResolution(e){return new Fe({code:ut.INVALID_VIDEO_RESOLUTION,message:`Invalid resolution '${e}'. Use '720p' or '1080p'`,category:"validation",severity:"medium",retriable:!1,context:{field:"output.video.resolution",providedValue:e,suggestions:["Use '720p' for standard HD","Use '1080p' for full HD"]}})}static invalidVideoLength(e){return new Fe({code:ut.INVALID_VIDEO_LENGTH,message:`Invalid length '${e}'. Use 4, 6, or 8 seconds`,category:"validation",severity:"medium",retriable:!1,context:{field:"output.video.length",providedValue:e,suggestions:["Use 4 for short clips","Use 6 for balanced duration (recommended)","Use 8 for longer videos"]}})}static invalidVideoAspectRatio(e){return new Fe({code:ut.INVALID_VIDEO_ASPECT_RATIO,message:`Invalid aspect ratio '${e}'. Use '9:16' or '16:9'`,category:"validation",severity:"medium",retriable:!1,context:{field:"output.video.aspectRatio",providedValue:e,suggestions:["Use '9:16' for portrait/vertical video","Use '16:9' for landscape"]}})}static invalidVideoAudio(e){return new Fe({code:ut.INVALID_VIDEO_AUDIO,message:`Invalid audio option '${e}'. Must be true or false`,category:"validation",severity:"medium",retriable:!1,context:{field:"output.video.audio",providedValue:e,suggestions:["Set audio: true to enable audio generation","Set audio: false to disable"]}})}static invalidVideoMode(){return new Fe({code:ut.INVALID_VIDEO_MODE,message:"Video generation requires output.mode to be 'video'",category:"validation",severity:"medium",retriable:!1,context:{field:"output.mode",suggestions:["Set output: { mode: 'video' } for video generation"]}})}static missingVideoImage(){return new Fe({code:ut.MISSING_VIDEO_IMAGE,message:"Video generation requires an input image",category:"validation",severity:"medium",retriable:!1,context:{field:"input.images",suggestions:["Provide an image via input.images array","Example: input: { text: 'prompt', images: [imageBuffer] }"]}})}static emptyVideoPrompt(){return new Fe({code:ut.EMPTY_VIDEO_PROMPT,message:"Video prompt cannot be empty",category:"validation",severity:"medium",retriable:!1,context:{field:"input.text",suggestions:["Provide a text prompt describing the desired video motion/content","Example: 'Smooth camera pan with dramatic lighting'"]}})}static videoPromptTooLong(e,t){return new Fe({code:ut.VIDEO_PROMPT_TOO_LONG,message:`Video prompt must be ${t} characters or less (got ${e})`,category:"validation",severity:"medium",retriable:!1,context:{field:"input.text",providedLength:e,maxLength:t,suggestions:[`Shorten your prompt to ${t} characters or less`,"Focus on key visual elements and camera motion"]}})}static emptyImagePath(){return new Fe({code:ut.EMPTY_IMAGE_PATH,message:"Image path or URL cannot be empty",category:"validation",severity:"medium",retriable:!1,context:{field:"input.images",suggestions:["Provide a valid file path or URL"]}})}static invalidImageType(){return new Fe({code:ut.INVALID_IMAGE_TYPE,message:"Image must be a Buffer, file path string, or URL",category:"validation",severity:"medium",retriable:!1,context:{field:"input.images",suggestions:["Provide image as Buffer: fs.readFileSync('image.jpg')","Or as file path string: './image.jpg'","Or as URL: 'https://example.com/image.jpg'"]}})}static pdfPageLimitExceeded(e,t,n){let o=[`Split the PDF into smaller files (max ${t} pages each)`,"Extract only the pages you need using a PDF editor","For large files, consider Google AI Studio which supports up to 2000MB file size (though page limits still apply)","Convert specific pages to images manually before processing","Bypass this limit with { enforceLimits: false } (not recommended - may cause API errors or unexpected costs)"];return new Fe({code:ut.PDF_PAGE_LIMIT_EXCEEDED,message:`PDF page limit exceeded: ${e} pages detected, but ${n} supports maximum ${t} pages.
162
162
 
@@ -50,7 +50,7 @@ const ConfigSchema = z.object({
50
50
  sessionToken: z.string().optional(),
51
51
  model: z
52
52
  .string()
53
- .default("arn:aws:bedrock:us-east-2:225681119357:inference-profile/us.anthropic.claude-3-7-sonnet-20250219-v1:0"),
53
+ .default("arn:aws:bedrock:us-east-2:123456789012:inference-profile/us.anthropic.claude-3-7-sonnet-20250219-v1:0"),
54
54
  })
55
55
  .optional(),
56
56
  vertex: z
@@ -582,7 +582,7 @@ export class ConfigManager {
582
582
  type: "input",
583
583
  name: "model",
584
584
  message: "Model ARN:",
585
- default: "arn:aws:bedrock:us-east-2:225681119357:inference-profile/us.anthropic.claude-3-7-sonnet-20250219-v1:0",
585
+ default: "arn:aws:bedrock:us-east-2:123456789012:inference-profile/us.anthropic.claude-3-7-sonnet-20250219-v1:0",
586
586
  },
587
587
  ]);
588
588
  this.config.providers.bedrock = {
@@ -115,17 +115,25 @@ function isDirectorSegment(segment) {
115
115
  return false;
116
116
  }
117
117
  export function isMultimodalInput(input) {
118
- const maybeInput = input;
119
- return !!(maybeInput?.images?.length ||
120
- maybeInput?.csvFiles?.length ||
121
- maybeInput?.pdfFiles?.length ||
122
- maybeInput?.files?.length ||
123
- maybeInput?.content?.length ||
124
- maybeInput?.audioFiles?.length ||
125
- maybeInput?.videoFiles?.length ||
126
- (maybeInput?.segments?.length &&
127
- Array.isArray(maybeInput.segments) &&
128
- maybeInput.segments.every(isDirectorSegment)));
118
+ if (typeof input !== "object" || input === null) {
119
+ return false;
120
+ }
121
+ const m = input;
122
+ // Each field must be a NON-EMPTY ARRAY. Checking `.length` alone is unsafe:
123
+ // a string value (e.g. `{ images: "oops" }`) has a truthy `.length`, so the
124
+ // old guard would claim a malformed input is multimodal and then crash
125
+ // downstream when the field is iterated as an array.
126
+ const hasItems = (v) => Array.isArray(v) && v.length > 0;
127
+ return !!(hasItems(m.images) ||
128
+ hasItems(m.csvFiles) ||
129
+ hasItems(m.pdfFiles) ||
130
+ hasItems(m.files) ||
131
+ hasItems(m.content) ||
132
+ hasItems(m.audioFiles) ||
133
+ hasItems(m.videoFiles) ||
134
+ (Array.isArray(m.segments) &&
135
+ m.segments.length > 0 &&
136
+ m.segments.every(isDirectorSegment)));
129
137
  }
130
138
  /**
131
139
  * Type guard to check if message content is multimodal (array)
@@ -115,17 +115,25 @@ function isDirectorSegment(segment) {
115
115
  return false;
116
116
  }
117
117
  export function isMultimodalInput(input) {
118
- const maybeInput = input;
119
- return !!(maybeInput?.images?.length ||
120
- maybeInput?.csvFiles?.length ||
121
- maybeInput?.pdfFiles?.length ||
122
- maybeInput?.files?.length ||
123
- maybeInput?.content?.length ||
124
- maybeInput?.audioFiles?.length ||
125
- maybeInput?.videoFiles?.length ||
126
- (maybeInput?.segments?.length &&
127
- Array.isArray(maybeInput.segments) &&
128
- maybeInput.segments.every(isDirectorSegment)));
118
+ if (typeof input !== "object" || input === null) {
119
+ return false;
120
+ }
121
+ const m = input;
122
+ // Each field must be a NON-EMPTY ARRAY. Checking `.length` alone is unsafe:
123
+ // a string value (e.g. `{ images: "oops" }`) has a truthy `.length`, so the
124
+ // old guard would claim a malformed input is multimodal and then crash
125
+ // downstream when the field is iterated as an array.
126
+ const hasItems = (v) => Array.isArray(v) && v.length > 0;
127
+ return !!(hasItems(m.images) ||
128
+ hasItems(m.csvFiles) ||
129
+ hasItems(m.pdfFiles) ||
130
+ hasItems(m.files) ||
131
+ hasItems(m.content) ||
132
+ hasItems(m.audioFiles) ||
133
+ hasItems(m.videoFiles) ||
134
+ (Array.isArray(m.segments) &&
135
+ m.segments.length > 0 &&
136
+ m.segments.every(isDirectorSegment)));
129
137
  }
130
138
  /**
131
139
  * Type guard to check if message content is multimodal (array)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@juspay/neurolink",
3
- "version": "9.88.1",
3
+ "version": "9.88.2",
4
4
  "packageManager": "pnpm@10.15.1",
5
5
  "description": "TypeScript AI SDK with 24+ LLM providers behind one consistent API. MCP-native (58+ servers), voice TTS/STT/realtime, RAG, agents, memory, context compaction. OpenAI · Anthropic · Gemini · Bedrock · Azure · Ollama · DeepSeek · NVIDIA NIM and more.",
6
6
  "author": {