@frontmcp/sdk 1.13.0 → 1.13.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/esm/index.mjs CHANGED
@@ -64,7 +64,7 @@ ${this.originalError.stack}`}return this.message}}}});var OffloadBudgetExceededE
64
64
 
65
65
  To fix this issue:
66
66
  ${this.suggestion}`}};DuplicatePluginError=class extends PublicMcpError{constructor(pluginName,reason){super(`Plugin "${pluginName}" can be installed once per server, and this server installs it twice. ${reason}`,"DUPLICATE_PLUGIN",500)}};DuplicatePluginEntryError=class extends PublicMcpError{constructor(pluginName,listName,firstEntry,secondEntry){super(`Plugin "${pluginName}" is listed twice in ${listName} (entries ${firstEntry} and ${secondEntry}), and only one entry could be installed. List it once, with all its options in that entry, or install the other configuration on an @App of its own.`,"DUPLICATE_PLUGIN_ENTRY",500)}};PluginConfiguredTwiceError=class extends PublicMcpError{constructor(pluginClassName,serverOption){super(`${pluginClassName} is configured twice: by @FrontMcp({ ${serverOption} }) and by an ${pluginClassName} entry in @FrontMcp({ plugins }). Configure it in one place: move the entry's options to ${serverOption} and remove the entry, or remove ${serverOption}.`,"PLUGIN_CONFIGURED_TWICE",500)}}}});var ToolUiConfigurationError,InvalidToolUiConfigError;var init_tool_ui_errors=__esm({"libs/sdk/src/errors/tool-ui.errors.ts"(){"use strict";init_mcp_error();ToolUiConfigurationError=class extends PublicMcpError{problems;constructor(toolName,problems){super(`Tool "${toolName}": ${problems.join(" ")}`,"TOOL_UI_CONFIGURATION",500);this.problems=problems}};InvalidToolUiConfigError=class extends InternalMcpError{problems;constructor(problems){super(`Invalid tool ui config:
67
- - ${problems.join("\n- ")}`,"INVALID_TOOL_UI_CONFIG");this.problems=problems}}}});var errors_exports={};__export(errors_exports,{AgentCallDepthExceededError:()=>AgentCallDepthExceededError,AgentConfigKeyNotFoundError:()=>AgentConfigKeyNotFoundError,AgentConfigurationError:()=>AgentConfigurationError,AgentExecutionError:()=>AgentExecutionError,AgentLlmError:()=>AgentLlmError,AgentLoopExceededError:()=>AgentLoopExceededError,AgentMethodNotAvailableError:()=>AgentMethodNotAvailableError,AgentNotConfiguredError:()=>AgentNotConfiguredError,AgentNotFoundError:()=>AgentNotFoundError,AgentTimeoutError:()=>AgentTimeoutError,AgentToolExecutionError:()=>AgentToolExecutionError,AgentToolNotFoundError:()=>AgentToolNotFoundError,AgentVisibilityError:()=>AgentVisibilityError,AuthConfigurationError:()=>AuthConfigurationError,AuthProvidersNotConfiguredError:()=>AuthProvidersNotConfiguredError,AuthorizationRequiredError:()=>AuthorizationRequiredError,BrowserEntryPointUnavailableError:()=>BrowserEntryPointUnavailableError,BrowserStoreUnavailableError:()=>BrowserStoreUnavailableError,CallRecorderConfigurationError:()=>CallRecorderConfigurationError,ClusterScopeNeedsRedisError:()=>ClusterScopeNeedsRedisError,ConfigNotFoundError:()=>ConfigNotFoundError,ContextExtensionNotAvailableError:()=>ContextExtensionNotAvailableError,CredentialProviderAlreadyRegisteredError:()=>CredentialProviderAlreadyRegisteredError,CrossOriginRequestError:()=>CrossOriginRequestError,DependencyCycleError:()=>DependencyCycleError,DependencyNotFoundError:()=>DependencyNotFoundError,DuplicateAppIdError:()=>DuplicateAppIdError,DuplicatePluginEntryError:()=>DuplicatePluginEntryError,DuplicatePluginError:()=>DuplicatePluginError,DutyNameConflictError:()=>DutyNameConflictError,DynamicAdapterNameError:()=>DynamicAdapterNameError,DynamicJobDirectExecutionError:()=>DynamicJobDirectExecutionError,DynamicJobRegistrationDisabledError:()=>DynamicJobRegistrationDisabledError,ElicitationDisabledError:()=>ElicitationDisabledError,ElicitationEncryptionError:()=>ElicitationEncryptionError,ElicitationFallbackRequired:()=>ElicitationFallbackRequired,ElicitationNotOwnedError:()=>ElicitationNotOwnedError,ElicitationNotSupportedError:()=>ElicitationNotSupportedError,ElicitationSecretRequiredError:()=>ElicitationSecretRequiredError,ElicitationStoreNotInitializedError:()=>ElicitationStoreNotInitializedError,ElicitationSubscriptionError:()=>ElicitationSubscriptionError,ElicitationTimeoutError:()=>ElicitationTimeoutError,EnclaveExecutionError:()=>EnclaveExecutionError,EncryptionContextNotSetError:()=>EncryptionContextNotSetError,EncryptionKeyNotConfiguredError:()=>EncryptionKeyNotConfiguredError,EntryUnavailableError:()=>EntryUnavailableError,EntryValidationError:()=>EntryValidationError,ErrorHandler:()=>ErrorHandler,EsmCacheError:()=>EsmCacheError,EsmInvalidSpecifierError:()=>EsmInvalidSpecifierError,EsmManifestInvalidError:()=>EsmManifestInvalidError,EsmPackageLoadError:()=>EsmPackageLoadError,EsmRegistryAuthError:()=>EsmRegistryAuthError,EsmVersionResolutionError:()=>EsmVersionResolutionError,EventCallbackEndpointError:()=>EventCallbackEndpointError,EventForbiddenError:()=>EventForbiddenError,EventNameConflictError:()=>EventNameConflictError,EventNotFoundError:()=>EventNotFoundError,EventNotRegisteredError:()=>EventNotRegisteredError,EventProtocolError:()=>EventProtocolError,EventPublishEndpointError:()=>EventPublishEndpointError,EventResourceExhaustedError:()=>EventResourceExhaustedError,EventSubscriptionStoreError:()=>EventSubscriptionStoreError,EventUnsupportedError:()=>EventUnsupportedError,EventsNotEnabledError:()=>EventsNotEnabledError,ExternalEntryError:()=>ExternalEntryError,ExternalEntryLoadError:()=>ExternalEntryLoadError,ExternalEntryNotFoundError:()=>ExternalEntryNotFoundError,ExternalEntryNotSupportedError:()=>ExternalEntryNotSupportedError,FeatureOffError:()=>FeatureOffError,FlowExitedWithoutOutputError:()=>FlowExitedWithoutOutputError,FlowInputMissingError:()=>FlowInputMissingError,FlowNotRegisteredError:()=>FlowNotRegisteredError,GenericServerError:()=>GenericServerError,GlobalConfigNotFoundError:()=>GlobalConfigNotFoundError,GuardLimitMcpError:()=>GuardLimitMcpError,HaConfigurationError:()=>HaConfigurationError,HookOrderCycleError:()=>HookOrderCycleError,HookTargetNotDefinedError:()=>HookTargetNotDefinedError,InMemoryStoreRequiredError:()=>InMemoryStoreRequiredError,InputRequiredSignal:()=>InputRequiredSignal,InternalMcpError:()=>InternalMcpError,InvalidDecoratorMetadataError:()=>InvalidDecoratorMetadataError,InvalidDependencyScopeError:()=>InvalidDependencyScopeError,InvalidDutyCronError:()=>InvalidDutyCronError,InvalidEntityError:()=>InvalidEntityError,InvalidEventPublishError:()=>InvalidEventPublishError,InvalidFileSignalError:()=>InvalidFileSignalError,InvalidHookFlowError:()=>InvalidHookFlowError,InvalidHttpRouteError:()=>InvalidHttpRouteError,InvalidHttpRouteResponseError:()=>InvalidHttpRouteResponseError,InvalidInputError:()=>InvalidInputError,InvalidInstructionSourceError:()=>InvalidInstructionSourceError,InvalidMethodError:()=>InvalidMethodError,InvalidOffloadCallError:()=>InvalidOffloadCallError,InvalidOutputError:()=>InvalidOutputError,InvalidPeopleAuthOptionsError:()=>InvalidPeopleAuthOptionsError,InvalidPluginScopeError:()=>InvalidPluginScopeError,InvalidRegistryKindError:()=>InvalidRegistryKindError,InvalidResourceStoreError:()=>InvalidResourceStoreError,InvalidResourceUriError:()=>InvalidResourceUriError,InvalidRetryOptionsError:()=>InvalidRetryOptionsError,InvalidSharedServerOptionsError:()=>InvalidSharedServerOptionsError,InvalidSkillError:()=>InvalidSkillError,InvalidToolUiConfigError:()=>InvalidToolUiConfigError,InvalidTransportSessionError:()=>InvalidTransportSessionError,InvalidUseClassError:()=>InvalidUseClassError,InvalidUseFactoryError:()=>InvalidUseFactoryError,InvalidUseValueError:()=>InvalidUseValueError,InvokeStateMissingKeyError:()=>InvokeStateMissingKeyError,JobAdmissionTimeoutError:()=>JobAdmissionTimeoutError,JobCancelledError:()=>JobCancelledError,JobInterruptedError:()=>JobInterruptedError,JobNotAuthorizedError:()=>JobNotAuthorizedError,JobRunFinishedError:()=>JobRunFinishedError,JobRunNotCancellableError:()=>JobRunNotCancellableError,JobRunNotFoundError:()=>JobRunNotFoundError,JobRunnerBootError:()=>JobRunnerBootError,JobRunnerUnavailableError:()=>JobRunnerUnavailableError,JobStoreNotSupportedError:()=>JobStoreNotSupportedError,JobTimeoutError:()=>JobTimeoutError,JwtSecretRequiredError:()=>JwtSecretRequiredError,JwtSecretWeakError:()=>JwtSecretWeakError,LazyAppConfigurationError:()=>LazyAppConfigurationError,LazyAppLoadError:()=>LazyAppLoadError,MCP_ERROR_CODES:()=>MCP_ERROR_CODES,McpError:()=>McpError,MethodNotImplementedError:()=>MethodNotImplementedError,MissingClientCapabilityError:()=>MissingClientCapabilityError,MissingPromptArgumentError:()=>MissingPromptArgumentError,MissingProvideError:()=>MissingProvideError,NameDisambiguationError:()=>NameDisambiguationError,NoProviderIdError:()=>NoProviderIdError,OffloadAbortedError:()=>OffloadAbortedError,OffloadBudgetExceededError:()=>OffloadBudgetExceededError,OffloadNotCloneableError:()=>OffloadNotCloneableError,OffloadUnsupportedRuntimeError:()=>OffloadUnsupportedRuntimeError,OffloadWorkerError:()=>OffloadWorkerError,OrchestratedAuthNotAvailableError:()=>OrchestratedAuthNotAvailableError,OrchestratorJwksNotAvailableError:()=>OrchestratorJwksNotAvailableError,PayloadTooLargeError:()=>PayloadTooLargeError,PersonNotSignedInError:()=>PersonNotSignedInError,PluginConfiguredTwiceError:()=>PluginConfiguredTwiceError,PluginDependencyError:()=>PluginDependencyError,PromptExecutionError:()=>PromptExecutionError,PromptNotFoundError:()=>PromptNotFoundError,ProviderBootstrapError:()=>ProviderBootstrapError,ProviderConstructionError:()=>ProviderConstructionError,ProviderDependencyError:()=>ProviderDependencyError,ProviderNotAvailableError:()=>ProviderNotAvailableError,ProviderNotInstantiatedError:()=>ProviderNotInstantiatedError,ProviderNotRegisteredError:()=>ProviderNotRegisteredError,ProviderScopeMismatchError:()=>ProviderScopeMismatchError,ProviderScopedAccessError:()=>ProviderScopedAccessError,PublicAccessDeniedError:()=>PublicAccessDeniedError,PublicMcpError:()=>PublicMcpError,QuotaExceededError:()=>QuotaExceededError,RateLimitError:()=>RateLimitError,RegistryDefinitionNotFoundError:()=>RegistryDefinitionNotFoundError,RegistryDependencyNotRegisteredError:()=>RegistryDependencyNotRegisteredError,RegistryGraphEntryNotFoundError:()=>RegistryGraphEntryNotFoundError,RegistryNotInitializedError:()=>RegistryNotInitializedError,RemoteAuthError:()=>RemoteAuthError,RemoteAuthorizationError:()=>RemoteAuthorizationError,RemoteCapabilityDiscoveryError:()=>RemoteCapabilityDiscoveryError,RemoteCapabilityNotSupportedError:()=>RemoteCapabilityNotSupportedError,RemoteConfigurationError:()=>RemoteConfigurationError,RemoteConnectionError:()=>RemoteConnectionError,RemoteDisconnectError:()=>RemoteDisconnectError,RemoteNotConnectedError:()=>RemoteNotConnectedError,RemotePromptGetError:()=>RemotePromptGetError,RemotePromptNotFoundError:()=>RemotePromptNotFoundError,RemoteResourceNotFoundError:()=>RemoteResourceNotFoundError,RemoteResourceReadError:()=>RemoteResourceReadError,RemoteTimeoutError:()=>RemoteTimeoutError,RemoteToolExecutionError:()=>RemoteToolExecutionError,RemoteToolNotFoundError:()=>RemoteToolNotFoundError,RemoteTransportError:()=>RemoteTransportError,RemoteUnsupportedTransportError:()=>RemoteUnsupportedTransportError,RequestContextNotAvailableError:()=>RequestContextNotAvailableError,RequiredConfigUndefinedError:()=>RequiredConfigUndefinedError,ReservedAppIdError:()=>ReservedAppIdError,ResourceNotFoundError:()=>ResourceNotFoundError,ResourceReadError:()=>ResourceReadError,SamplingNotAvailableError:()=>SamplingNotAvailableError,ScopeConfigurationError:()=>ScopeConfigurationError,ScopeDeniedError:()=>ScopeDeniedError,ServerNotFoundError:()=>ServerNotFoundError,ServerlessHandlerNotInitializedError:()=>ServerlessHandlerNotInitializedError,SessionClaimConflictError:()=>SessionClaimConflictError,SessionIdEmptyError:()=>SessionIdEmptyError,SessionIdentityRequiredError:()=>SessionIdentityRequiredError,SessionMissingError:()=>SessionMissingError,SessionOwnerUnreachableError:()=>SessionOwnerUnreachableError,SessionSecretRequiredError:()=>SessionSecretRequiredError,SessionVerificationFailedError:()=>SessionVerificationFailedError,SharedServerIdentityError:()=>SharedServerIdentityError,SharedServerStartError:()=>SharedServerStartError,SignInLockedError:()=>SignInLockedError,SignInRefusedError:()=>SignInRefusedError,SigningKeyInvalidError:()=>SigningKeyInvalidError,SkillContextNotImplementedError:()=>SkillContextNotImplementedError,SkillInstructionFetchError:()=>SkillInstructionFetchError,SkillSessionError:()=>SkillSessionError,SocketInUseError:()=>SocketInUseError,SocketPathConflictError:()=>SocketPathConflictError,SocketPermissionError:()=>SocketPermissionError,StaleToolListError:()=>StaleToolListError,StoreNotOpenedInBuildError:()=>StoreNotOpenedInBuildError,TaskAlreadyTerminalError:()=>TaskAlreadyTerminalError,TaskAugmentationNotSupportedError:()=>TaskAugmentationNotSupportedError,TaskAugmentationRequiredError:()=>TaskAugmentationRequiredError,TaskConcurrencyLimitError:()=>TaskConcurrencyLimitError,TaskNotFoundError:()=>TaskNotFoundError,TaskStoreNotInitializedError:()=>TaskStoreNotInitializedError,TokenLeakDetectedError:()=>TokenLeakDetectedError,TokenNotAvailableError:()=>TokenNotAvailableError,TokenStoreRequiredError:()=>TokenStoreRequiredError,ToolAliasConflictError:()=>ToolAliasConflictError,ToolCallError:()=>ToolCallError,ToolCredentialsRequiredError:()=>ToolCredentialsRequiredError,ToolExecutionError:()=>ToolExecutionError,ToolNameConflictError:()=>ToolNameConflictError,ToolNotConsentedError:()=>ToolNotConsentedError,ToolNotFoundError:()=>ToolNotFoundError,ToolUiConfigurationError:()=>ToolUiConfigurationError,TransportAlreadyStartedError:()=>TransportAlreadyStartedError,TransportBusRequiredError:()=>TransportBusRequiredError,TransportNotConnectedError:()=>TransportNotConnectedError,TransportServiceNotAvailableError:()=>TransportServiceNotAvailableError,UnauthorizedError:()=>UnauthorizedError,UnenforcedMetadataError:()=>UnenforcedMetadataError,UnsafeDutyStoreError:()=>UnsafeDutyStoreError,UnsafeSharedServerDirectoryError:()=>UnsafeSharedServerDirectoryError,UnsafeSocketDirectoryError:()=>UnsafeSocketDirectoryError,UnsupportedClientVersionError:()=>UnsupportedClientVersionError,UnsupportedContentTypeError:()=>UnsupportedContentTypeError,UnsupportedHookOwnerKindError:()=>UnsupportedHookOwnerKindError,UnsupportedTransportTypeError:()=>UnsupportedTransportTypeError,VaultLoadError:()=>VaultLoadError,VaultNotFoundError:()=>VaultNotFoundError,VercelKvAsyncInitRequiredError:()=>VercelKvAsyncInitRequiredError,VercelKvNotSupportedError:()=>VercelKvNotSupportedError,WorkerNameConflictError:()=>WorkerNameConflictError,WorkflowDagValidationError:()=>WorkflowDagValidationError,WorkflowJobTimeoutError:()=>WorkflowJobTimeoutError,WorkflowStepNotFoundError:()=>WorkflowStepNotFoundError,WorkflowTimeoutError:()=>WorkflowTimeoutError,WorkflowTriggerConfigError:()=>WorkflowTriggerConfigError,authorizationRequiredDataSchema:()=>authorizationRequiredDataSchema,authorizationRequiredMetaSchema:()=>authorizationRequiredMetaSchema,authorizationRequiredParamsSchema:()=>authorizationRequiredParamsSchema,createErrorHandler:()=>createErrorHandler,describeConfigIssues:()=>describeConfigIssues,extractPublicMessage:()=>extractPublicMessage,formatMcpErrorResponse:()=>formatMcpErrorResponse,isClientFacingError:()=>isClientFacingError,isMrtrSignal:()=>isMrtrSignal,isPublicError:()=>isPublicError,refused:()=>refused,shouldStopExecution:()=>shouldStopExecution,toMcpError:()=>toMcpError});var init_errors=__esm({"libs/sdk/src/errors/index.ts"(){"use strict";init_mcp_error();init_authorization_required_error();init_tool_credentials_required_error();init_tool_call_error();init_misconfiguration();init_session_identity_required_error();init_error_handler();init_agent_errors();init_task_error();init_elicitation_error();init_offload_errors();init_mrtr_error();init_remote_errors();init_normalization_errors();init_registry_errors();init_provider_errors();init_decorator_errors();init_duty_errors();init_event_errors();init_worker_errors();init_browser_store_errors();init_build_store_errors();init_browser_entry_point_errors();init_http_route_errors();init_shared_server_errors();init_transport_errors();init_auth_internal_errors();init_workflow_errors();init_esm_errors();init_external_entry_errors();init_lazy_app_errors();init_sdk_errors();init_job_errors();init_plugin_errors();init_tool_ui_errors()}});var loadProtocolClient;var init_import_protocol_client=__esm({"libs/sdk/src/third-party/import-protocol-client.ts"(){"use strict";loadProtocolClient=()=>import("@frontmcp/protocol/client")}});async function listAllPages(method,fetchPage,fail=message=>new InternalMcpError(message,"LIST_PAGINATION_STALLED")){const items=[];const seenCursors=new Set;let cursor;for(let page2=0;page2<MAX_LIST_PAGES;page2++){const result=await fetchPage(cursor);items.push(...result.items??[]);const next=result.nextCursor;if(!next)return items;if(seenCursors.has(next)){throw fail(`${method} returned the cursor "${next}" twice`)}seenCursors.add(next);cursor=next}throw fail(`${method} did not finish within ${MAX_LIST_PAGES} pages`)}var MAX_LIST_PAGES;var init_list_all_pages_utils=__esm({"libs/sdk/src/common/utils/list-all-pages.utils.ts"(){"use strict";init_mcp_error();MAX_LIST_PAGES=1e3}});var ELICITATION_META_KEY;var init_elicitation_meta=__esm({"libs/sdk/src/elicitation/elicitation-meta.ts"(){"use strict";ELICITATION_META_KEY="frontmcp/elicitation"}});var EventRequestError,NoCompatibleDeliveryModeError,EventSubscriptionTerminatedError,DuplicateEventSubscriptionError;var init_event_client_errors=__esm({"libs/sdk/src/event-client/event-client.errors.ts"(){"use strict";init_mcp_error();EventRequestError=class extends PublicMcpError{constructor(method,rpcCode,message,data){super(`${method} failed (${rpcCode}): ${message}`,"EVENT_REQUEST_FAILED",400);this.method=method;this.rpcCode=rpcCode;this.data=data}method;rpcCode;data};NoCompatibleDeliveryModeError=class extends PublicMcpError{constructor(eventName,offered,usable){super(`Event "${eventName}" is offered by ${offered.join(", ")||"no mode"}, and this client can use ${usable.join(", ")}. Configure a webhook receiver, use a transport that streams, or pick another event.`,"NO_COMPATIBLE_DELIVERY_MODE",400)}};EventSubscriptionTerminatedError=class extends PublicMcpError{constructor(eventName,error){super(`The subscription to "${eventName}" was terminated by the server: ${error.message}`,"EVENT_TERMINATED",410);this.eventName=eventName;this.error=error}eventName;error};DuplicateEventSubscriptionError=class extends PublicMcpError{constructor(eventName,url){super(`This client already holds a webhook subscription to "${eventName}" with these arguments at ${url}, and the server keeps one subscription for them. Read the existing subscription, or cancel it first.`,"DUPLICATE_EVENT_SUBSCRIPTION",409)}}}});import{EventErrorSchema,EventOccurrenceSchema,EVENTS_ERROR_CODES,EVENTS_METHODS,EVENTS_NOTIFICATIONS,EVENTS_SKETCH_ERROR_CODES,ListEventsResultSchema,PollEventsResultSchema,SubscribeEventResultSchema}from"@frontmcp/protocol";import{canonicalJson,generateStandardWebhookSecret}from"@frontmcp/utils";function isTerminal2(error){return error instanceof EventRequestError&&TERMINAL_CODES.has(error.rpcCode)}function eventErrorOf(error){const data=typeof error.data==="object"&&error.data!==null?error.data:{};return{code:error.rpcCode,message:error.message,data}}function sameArguments(first3,second){const keyOf=({name:name59,arguments:args})=>canonicalJson({name:name59,arguments:args});return keyOf(first3)===keyOf(second)}function sleep(ms,signal){return new Promise(resolve4=>{if(signal.aborted)return resolve4();const done=()=>{clearTimeout(timer);signal.removeEventListener("abort",done);resolve4()};const timer=setTimeout(done,ms);signal.addEventListener("abort",done,{once:true})})}var DEFAULT_POLL_FLOOR_MS,DEFAULT_HEARTBEAT_TIMEOUT_MS,NO_EXPIRY_REFRESH_MS,REFRESH_AT_SHARE,DEDUPE_WINDOW,MAX_TIMER_MS3,MAX_RETRY_DELAY_MS,TERMINAL_CODES,MemoryCursorStore,OccurrenceQueue,ClientEventSubscription,EventsClient;var init_events_client=__esm({"libs/sdk/src/event-client/events-client.ts"(){"use strict";init_list_all_pages_utils();init_event_client_errors();DEFAULT_POLL_FLOOR_MS=1e3;DEFAULT_HEARTBEAT_TIMEOUT_MS=6e4;NO_EXPIRY_REFRESH_MS=36e5;REFRESH_AT_SHARE=.8;DEDUPE_WINDOW=1e3;MAX_TIMER_MS3=2147483647;MAX_RETRY_DELAY_MS=6e4;TERMINAL_CODES=new Set([-32602,...[EVENTS_ERROR_CODES,EVENTS_SKETCH_ERROR_CODES].flatMap(({notFound,forbidden,unsupported})=>[notFound,forbidden,unsupported])]);MemoryCursorStore=class{cursors=new Map;get(key){return this.cursors.get(key)}set(key,cursor){this.cursors.set(key,cursor)}};OccurrenceQueue=class{constructor(onReturn){this.onReturn=onReturn}onReturn;items=[];seen=new Set;waiter;ended=false;failure;push(occurrence){if(this.ended||this.seen.has(occurrence.eventId))return;this.seen.add(occurrence.eventId);if(this.seen.size>DEDUPE_WINDOW)this.seen.delete(this.seen.values().next().value);const waiter=this.waiter;this.waiter=void 0;if(waiter)waiter.resolve({value:occurrence,done:false});else this.items.push(occurrence)}end(failure){if(this.ended)return;this.ended=true;this.failure=failure;if(!failure)this.items.length=0;const waiter=this.waiter;this.waiter=void 0;if(!waiter)return;if(failure)waiter.reject(failure);else waiter.resolve({value:void 0,done:true})}[Symbol.asyncIterator](){return{next:()=>this.next(),return:async()=>{await this.onReturn();return{value:void 0,done:true}}}}next(){const item=this.items.shift();if(item)return Promise.resolve({value:item,done:false});if(this.failure)return Promise.reject(this.failure);if(this.ended)return Promise.resolve({value:void 0,done:true});return new Promise((resolve4,reject)=>{this.waiter={resolve:resolve4,reject}})}};ClientEventSubscription=class{constructor(settings){this.settings=settings;this.name=settings.name;this.arguments=settings.arguments;this.mode=settings.mode;this.cursor=settings.cursor;this.queue=new OccurrenceQueue(()=>this.cancel())}settings;name;arguments;mode;cursor;id;deliveryStatus;queue;stopController=new AbortController;streamController;registration;secret;refreshTimer;pendingRefresh;immediateRefreshOwed=false;firstRequest=true;failedAttempts=0;[Symbol.asyncIterator](){return this.queue[Symbol.asyncIterator]()}get stopped(){return this.stopController.signal.aborted}async start(){if(this.mode==="poll"){const waitMs=await this.pollOnce();void this.pollLoop(waitMs)}else if(this.mode==="push"){await this.openStream()}else{await this.startWebhook()}}async cancel(){if(this.stopped)return;this.stop();this.queue.end();if(this.mode!=="webhook")return;await this.pendingRefresh?.catch(()=>void 0);const delivery={mode:"webhook",url:this.settings.webhook?.url};await this.settings.transport.request(EVENTS_METHODS.unsubscribe,{name:this.name,arguments:this.arguments,delivery}).catch(()=>void 0)}stop(){this.settings.onStopped(this);this.stopController.abort();this.streamController?.abort();clearTimeout(this.refreshTimer);this.registration?.release()}discard(){if(this.stopped)return;this.stop();this.queue.end()}refreshNow(){if(this.stopped)return;this.immediateRefreshOwed=true;this.scheduleRefresh(0)}terminate(error){if(this.stopped)return;this.stop();this.queue.end(new EventSubscriptionTerminatedError(this.name,error))}advance(cursor,truncated){this.cursor=cursor??null;const key=canonicalJson({name:this.name,arguments:this.arguments});try{Promise.resolve(this.settings.cursorStore.set(key,this.cursor)).catch(()=>void 0)}catch{}if(truncated)this.settings.options.onTruncated?.(this.cursor)}retryDelayMs(){const delayMs=Math.min(this.settings.pollFloorMs*2**this.failedAttempts,MAX_RETRY_DELAY_MS);this.failedAttempts+=1;return delayMs}subscriptionParams(){const{maxAgeMs}=this.settings.options;const params={name:this.name,arguments:this.arguments,cursor:this.cursor};if(this.firstRequest&&maxAgeMs!==void 0)params["maxAgeMs"]=maxAgeMs;this.firstRequest=false;return params}async pollOnce(){const{maxEvents}=this.settings.options;const params={...this.subscriptionParams(),...maxEvents!==void 0&&{maxEvents}};const result=PollEventsResultSchema.parse(await this.settings.transport.request(EVENTS_METHODS.poll,params));this.advance(result.cursor,result.truncated);for(const occurrence of result.events)this.queue.push(occurrence);this.failedAttempts=0;if(result.hasMore)return 0;return Math.max(result.nextPollMs??this.settings.pollFloorMs,this.settings.pollFloorMs)}async pollLoop(firstWaitMs){let waitMs=firstWaitMs;while(!this.stopped){await sleep(waitMs,this.stopController.signal);if(this.stopped)return;try{waitMs=await this.pollOnce()}catch(error){if(isTerminal2(error))return this.terminate(eventErrorOf(error));waitMs=this.retryDelayMs()}}}openStream(){const{transport}=this.settings;const openStream=transport.openStream.bind(transport);const controller=new AbortController;this.streamController=controller;let confirmed=false;let watchdog;const resetWatchdog=()=>{clearTimeout(watchdog);watchdog=setTimeout(()=>controller.abort(),this.settings.heartbeatTimeoutMs)};return new Promise((confirm,refuse)=>{const onNotification=notification=>{resetWatchdog();if(notification.method===EVENTS_NOTIFICATIONS.active){confirmed=true;confirm()}this.onStreamNotification(notification)};resetWatchdog();openStream({...this.subscriptionParams()},onNotification,controller.signal).then(()=>this.streamEnded(confirmed,watchdog,refuse,void 0),error=>this.streamEnded(confirmed,watchdog,refuse,error))})}streamEnded(confirmed,watchdog,refuse,error){clearTimeout(watchdog);if(!confirmed)return refuse(error??new Error("The events/stream ended before the server confirmed it"));if(!this.stopped)void this.reconnect()}async reconnect(){while(!this.stopped){await sleep(this.retryDelayMs(),this.stopController.signal);if(this.stopped)return;try{await this.openStream();this.failedAttempts=0;return}catch(error){if(isTerminal2(error))return this.terminate(eventErrorOf(error))}}}onStreamNotification({method,params={}}){if(method===EVENTS_NOTIFICATIONS.active){this.advance(params["cursor"],params["truncated"]===true)}else if(method===EVENTS_NOTIFICATIONS.heartbeat){this.advance(params["cursor"])}else if(method===EVENTS_NOTIFICATIONS.event){const{_meta:_subscriptionMeta,...fields}=params;const occurrence=EventOccurrenceSchema.safeParse(fields);if(!occurrence.success)return;this.advance(occurrence.data.cursor);this.queue.push(occurrence.data)}else if(method===EVENTS_NOTIFICATIONS.error||method===EVENTS_NOTIFICATIONS.terminated){const error=EventErrorSchema.safeParse(params["error"]);if(!error.success)return;if(method===EVENTS_NOTIFICATIONS.error)this.settings.options.onError?.(error.data);else this.terminate(error.data)}}async startWebhook(){const webhook=this.settings.webhook;const secret=generateStandardWebhookSecret();this.secret=secret;this.registration=webhook.receiver.register({secret,listener:{onEvent:occurrence=>{this.advance(occurrence.cursor);this.queue.push(occurrence)},onGap:cursor=>this.advance(cursor,true),onTerminated:error=>this.terminate(error)}});try{this.pendingRefresh=this.refresh();await this.pendingRefresh}catch(error){this.registration.release();throw error}}async refresh(){const webhook=this.settings.webhook;const params={...this.subscriptionParams(),delivery:{mode:"webhook",url:webhook.url,secret:this.secret},...webhook.ttlMs!==void 0&&{ttlMs:webhook.ttlMs}};const result=SubscribeEventResultSchema.parse(await this.settings.transport.request(EVENTS_METHODS.subscribe,params));this.id=result.id;this.registration.bind(result.id);this.deliveryStatus=result.deliveryStatus;this.advance(result.cursor,result.truncated);if(this.stopped)return;this.failedAttempts=0;const remainingMs=result.refreshBefore===null?Number.NaN:Date.parse(result.refreshBefore)-Date.now();const delayMs=Number.isNaN(remainingMs)?NO_EXPIRY_REFRESH_MS:remainingMs*REFRESH_AT_SHARE;this.scheduleRefresh(Math.min(Math.max(delayMs,this.settings.pollFloorMs),MAX_TIMER_MS3))}scheduleRefresh(delayMs){clearTimeout(this.refreshTimer);this.refreshTimer=setTimeout(()=>this.refreshAfterInFlight(),this.immediateRefreshOwed?0:delayMs)}refreshAfterInFlight(){this.immediateRefreshOwed=false;const inFlight=this.pendingRefresh?.catch(()=>void 0)??Promise.resolve();this.pendingRefresh=inFlight.then(()=>this.stopped?void 0:this.refresh());this.pendingRefresh.catch(error=>{if(isTerminal2(error))this.terminate(eventErrorOf(error));else if(!this.stopped)this.scheduleRefresh(this.retryDelayMs())})}};EventsClient=class{constructor(transport,options={}){this.transport=transport;this.options=options;this.cursorStore=options.cursorStore??new MemoryCursorStore}transport;options;cursorStore;definitions;subscriptions=new Set;async list(){const events=await listAllPages(EVENTS_METHODS.list,async cursor=>{const result=ListEventsResultSchema.parse(await this.transport.request(EVENTS_METHODS.list,cursor?{cursor}:{}));return{items:result.events,nextCursor:result.nextCursor}});this.definitions=new Map(events.map(definition=>[definition.name,definition]));return events}async subscribe(name59,args={},options={}){const mode=await this.modeFor(name59,options.delivery);const storedCursor=await this.cursorStore.get(canonicalJson({name:name59,arguments:args}));const subscription=new ClientEventSubscription({transport:this.transport,cursorStore:this.cursorStore,pollFloorMs:this.options.pollFloorMs??DEFAULT_POLL_FLOOR_MS,heartbeatTimeoutMs:this.options.heartbeatTimeoutMs??DEFAULT_HEARTBEAT_TIMEOUT_MS,webhook:this.options.webhook,name:name59,arguments:args,mode,cursor:options.cursor!==void 0?options.cursor:storedCursor??null,options,onStopped:stopped=>this.subscriptions.delete(stopped)});if(mode==="webhook"&&this.webhookHolderOf(held=>sameArguments(held,subscription))){throw new DuplicateEventSubscriptionError(name59,this.options.webhook?.url??"")}this.subscriptions.add(subscription);try{await subscription.start()}catch(error){this.subscriptions.delete(subscription);throw error}const holder=mode==="webhook"&&this.webhookHolderOf(held=>held!==subscription&&held.id===subscription.id);if(holder){subscription.discard();holder.refreshNow();throw new DuplicateEventSubscriptionError(name59,this.options.webhook?.url??"")}return subscription}webhookHolderOf(matches){return[...this.subscriptions].find(held=>held.mode==="webhook"&&matches(held))}async close(){await Promise.all([...this.subscriptions].map(subscription=>subscription.cancel()))}async modeFor(name59,forced){const usable=[];if(this.options.webhook)usable.push("webhook");if(this.transport.openStream)usable.push("push");usable.push("poll");if(!this.definitions)await this.list();const offered=this.definitions?.get(name59)?.delivery??usable;const mode=forced??usable.find(candidate=>offered.includes(candidate));if(!mode||!usable.includes(mode)||!offered.includes(mode)){throw new NoCompatibleDeliveryModeError(name59,offered,usable)}return mode}}}});import{EventErrorSchema as EventErrorSchema2,EventOccurrenceSchema as EventOccurrenceSchema2,MCP_SUBSCRIPTION_ID_HEADER}from"@frontmcp/protocol";import{signingKeyOf,verifyWebhookSignature,WEBHOOK_ID_HEADER,WEBHOOK_SIGNATURE_HEADER,WEBHOOK_TIMESTAMP_HEADER}from"@frontmcp/utils";function headerOf(headers,name59){if(typeof headers.get==="function")return headers.get(name59)??void 0;const lowerName=name59.toLowerCase();for(const[key,value]of Object.entries(headers)){if(key.toLowerCase()===lowerName)return Array.isArray(value)?value[0]:value}return void 0}function jsonObjectOf(body){try{const parsed=JSON.parse(body);return typeof parsed==="object"&&parsed!==null&&!Array.isArray(parsed)?parsed:void 0}catch{return void 0}}function createEventWebhookReceiver(options={}){const sharedKeys=(options.secrets??[]).map(signingKeyOf);const registrations=new Set;const seenWebhookIds=new Set;const inFlight=new Set;const boundTo=subscriptionId=>[...registrations].filter(registration=>registration.subscriptionId===subscriptionId);const check=(request2,signingKeys)=>verifyWebhookSignature({id:headerOf(request2.headers,WEBHOOK_ID_HEADER),timestamp:headerOf(request2.headers,WEBHOOK_TIMESTAMP_HEADER),signature:headerOf(request2.headers,WEBHOOK_SIGNATURE_HEADER),body:request2.rawBody},signingKeys);const bindUnbound=(request2,subscriptionId)=>{let result="mismatch";for(const registration of registrations){if(registration.subscriptionId!==void 0)continue;result=check(request2,registration.signingKeys);if(result==="valid"){registration.subscriptionId=subscriptionId;return result}if(result!=="mismatch")return result}return result};const verify=request2=>{const subscriptionId=headerOf(request2.headers,MCP_SUBSCRIPTION_ID_HEADER)??"";const signingKeys=[...sharedKeys,...boundTo(subscriptionId).flatMap(registration=>registration.signingKeys)];return signingKeys.length>0?check(request2,signingKeys):void 0};const remember=dedupeKey=>{seenWebhookIds.add(dedupeKey);if(seenWebhookIds.size>WEBHOOK_DEDUPE_WINDOW){const oldest=seenWebhookIds.values().next().value;seenWebhookIds.delete(oldest)}};const dispatch=async(json,listener,delivery)=>{if(json["type"]==="gap"){await listener.onGap?.(typeof json["cursor"]==="string"?json["cursor"]:null,delivery);return{status:200}}if(json["type"]==="terminated"){const error=EventErrorSchema2.safeParse(json["error"]);if(!error.success)return{status:400};await listener.onTerminated?.(error.data,delivery);return{status:200}}const occurrence=EventOccurrenceSchema2.safeParse(json);if(json["type"]!==void 0||!occurrence.success)return{status:400};await listener.onEvent?.(occurrence.data,delivery);return{status:200}};return{async handle(request2){const subscriptionId=headerOf(request2.headers,MCP_SUBSCRIPTION_ID_HEADER)??"";const webhookId=headerOf(request2.headers,WEBHOOK_ID_HEADER)??"";const json=jsonObjectOf(request2.rawBody);const isVerification=json?.["type"]==="verification"&&typeof json["challenge"]==="string";const bound=boundTo(subscriptionId);let signature=verify(request2);if(signature!=="valid"&&isVerification&&bound.length===0){signature=bindUnbound(request2,subscriptionId)}if(signature===void 0)return{status:503};if(signature!=="valid")return{status:401,signature};if(!json)return{status:400,signature};if(isVerification)return{status:200,body:{challenge:json["challenge"]},signature};const dedupeKey=`${subscriptionId} ${webhookId}`;if(seenWebhookIds.has(dedupeKey))return{status:200,signature};if(inFlight.has(dedupeKey))return{status:503,signature};const listener=bound[0]?.listener??options;inFlight.add(dedupeKey);try{const response=await dispatch(json,listener,{subscriptionId,webhookId});if(response.status===200)remember(dedupeKey);return{...response,signature}}catch{return{status:500,signature}}finally{inFlight.delete(dedupeKey)}},verify,register({secret,subscriptionId,listener}){const record={subscriptionId,signingKeys:[signingKeyOf(secret)],listener};registrations.add(record);return{get subscriptionId(){return record.subscriptionId},bind(id){record.subscriptionId=id},addSecret(next){record.signingKeys.push(signingKeyOf(next))},release(){registrations.delete(record)}}},addSecret(secret){sharedKeys.push(signingKeyOf(secret))},hasSecrets(){return sharedKeys.length>0||registrations.size>0}}}var WEBHOOK_DEDUPE_WINDOW;var init_event_webhook_receiver=__esm({"libs/sdk/src/event-client/event-webhook-receiver.ts"(){"use strict";WEBHOOK_DEDUPE_WINDOW=1e4}});var init_event_client=__esm({"libs/sdk/src/event-client/index.ts"(){"use strict";init_events_client();init_event_webhook_receiver();init_event_client_errors()}});import{internalZ as z55}from"@frontmcp/lazy-zod";var SkillsSearchRequestSchema,SkillsSearchResultSchema,MAX_SKILLS_PER_LOAD,SkillsLoadRequestSchema,SkillsLoadResultSchema,SkillsListRequestSchema,SkillsListResultSchema;var init_skills_mcp_types=__esm({"libs/sdk/src/transport/mcp-handlers/skills-mcp.types.ts"(){"use strict";SkillsSearchRequestSchema=z55.object({method:z55.literal("skills/search"),params:z55.object({query:z55.string().describe("Search query string"),tags:z55.array(z55.string()).optional().describe("Filter by specific tags"),tools:z55.array(z55.string()).optional().describe("Filter by specific tools"),limit:z55.number().min(1).max(50).optional().describe("Maximum results (1-50, default: 10)"),requireAllTools:z55.boolean().optional().describe("Require all specified tools")})});SkillsSearchResultSchema=z55.object({skills:z55.array(z55.object({id:z55.string(),name:z55.string(),description:z55.string(),score:z55.number(),tags:z55.array(z55.string()).optional(),tools:z55.array(z55.object({name:z55.string(),available:z55.boolean()})),source:z55.enum(["local","external"]),bundleVersion:z55.string().optional().describe("Version of the bundle a runtime-registered skill came from")})),total:z55.number(),hasMore:z55.boolean(),guidance:z55.string()});MAX_SKILLS_PER_LOAD=100;SkillsLoadRequestSchema=z55.object({method:z55.literal("skills/load"),params:z55.object({skillIds:z55.array(z55.string()).min(1).max(MAX_SKILLS_PER_LOAD).describe("Array of skill IDs to load"),format:z55.enum(["full","markdown","instructions-only"]).optional().describe("'full' (default): the fields with tool schemas, and formattedContent; 'markdown': formattedContent alone, without instructions and parameters; 'instructions-only': no tool schemas"),activateSession:z55.boolean().optional().describe("Whether to activate a skill session"),policyMode:z55.enum(["strict","approval","permissive"]).optional().describe("Policy mode for session")})});SkillsLoadResultSchema=z55.object({skills:z55.array(z55.object({id:z55.string(),name:z55.string(),description:z55.string(),instructions:z55.string().optional(),tools:z55.array(z55.object({name:z55.string(),purpose:z55.string().optional(),available:z55.boolean(),inputSchema:z55.unknown().optional(),outputSchema:z55.unknown().optional()})),parameters:z55.array(z55.object({name:z55.string(),description:z55.string().optional(),required:z55.boolean().optional(),type:z55.string().optional()})).optional(),availableTools:z55.array(z55.string()),missingTools:z55.array(z55.string()),isComplete:z55.boolean(),formattedContent:z55.string(),session:z55.object({activated:z55.boolean(),sessionId:z55.string().optional(),policyMode:z55.string().optional(),allowedTools:z55.array(z55.string()).optional()}).optional()})),summary:z55.object({totalSkills:z55.number(),totalTools:z55.number(),allToolsAvailable:z55.boolean(),combinedWarnings:z55.array(z55.string()).optional()}),nextSteps:z55.string()});SkillsListRequestSchema=z55.object({method:z55.literal("skills/list"),params:z55.object({offset:z55.number().min(0).optional().describe("Number of skills to skip"),limit:z55.number().min(1).max(100).optional().describe("Maximum skills to return"),tags:z55.array(z55.string()).optional().describe("Filter by specific tags"),sortBy:z55.enum(["name","priority","createdAt"]).optional().describe("Field to sort by"),sortOrder:z55.enum(["asc","desc"]).optional().describe("Sort order"),includeHidden:z55.boolean().optional().describe("Include hidden skills")}).optional()});SkillsListResultSchema=z55.object({skills:z55.array(z55.object({id:z55.string(),name:z55.string(),description:z55.string(),tags:z55.array(z55.string()).optional(),priority:z55.number().optional(),bundleVersion:z55.string().optional().describe("Version of the bundle a runtime-registered skill came from")})),total:z55.number(),hasMore:z55.boolean()})}});import{internalZ as z56}from"@frontmcp/lazy-zod";import{EVENTS_METHODS as EVENTS_METHODS2,MCP_20260728_META}from"@frontmcp/protocol";function requestErrorOf(method,error){const{code,message,data}=error??{};if(typeof code!=="number")return error;const text=typeof message==="string"?message.replace(/^MCP error -?\d+: /,""):"";return new EventRequestError(method,code,text,data)}function directEventsTransport(client,notifications){return{async request(method,params){try{return await client.request({method,params},anyResultSchema)}catch(error){throw requestErrorOf(method,error)}},async openStream(params,onNotification,signal){const requestId=client._requestMessageId;if(typeof requestId!=="number")throw new Error("This MCP client cannot hold an events/stream");const stopListening=notifications(notification=>{const meta=notification.params?._meta;if(meta?.[MCP_20260728_META.subscriptionId]!==requestId)return;onNotification(notification)});try{await client.request({method:EVENTS_METHODS2.stream,params},anyResultSchema,{signal,timeout:NO_TIMEOUT_MS})}catch(error){if(!signal.aborted)throw requestErrorOf(EVENTS_METHODS2.stream,error)}finally{stopListening()}}}}var NO_TIMEOUT_MS,anyResultSchema;var init_direct_events_transport=__esm({"libs/sdk/src/direct/direct-events-transport.ts"(){"use strict";init_event_client();NO_TIMEOUT_MS=2147483647;anyResultSchema=z56.record(z56.string(),z56.unknown())}});import{getEnv as getEnv4}from"@frontmcp/utils";var DirectPublicAuth;var init_direct_public_auth=__esm({"libs/sdk/src/auth/direct-public-auth.ts"(){"use strict";init_common();DirectPublicAuth=class extends FrontMcpAuth{ready=Promise.resolve();issuer;constructor(scope,options){super(options);const host=getEnv4("FRONTMCP_PUBLIC_HOST")?.trim()||"localhost";this.issuer=`http://${host}:${scope.metadata.http?.port??defaultHttpPort()}${scope.fullPath}`}fetch(input,init){return fetch(input,init)}validate(){return Promise.resolve()}}}});import{isAnonymousSubject}from"@frontmcp/auth";async function authInfoForToken(scope,token){if(scope.auth instanceof DirectPublicAuth)return{};const mcpPath=`${normalizeEntryPrefix(scope.entryPath)}${normalizeScopeBase(scope.routeBase)}`||"/";const request2={method:"POST",path:mcpPath,url:mcpPath,headers:{host:"localhost",authorization:`Bearer ${token}`},query:{}};const verified=await scope.runFlow("session:verify",{request:request2,sessionless:true});if(!verified)throw new SessionVerificationFailedError;if(verified.kind==="unauthorized"){throw new UnauthorizedError("The server's auth did not accept the auth token",verified.prmMetadataHeader)}if(verified.kind==="forbidden"){throw new PublicMcpError("The auth token lacks the scopes the server requires","INSUFFICIENT_SCOPE",403)}if(isAnonymousSubject(verified.authorization.user.sub))return{};return authInfoFromAuthorization(verified.authorization)}var init_token_auth_info=__esm({"libs/sdk/src/direct/token-auth-info.ts"(){"use strict";init_direct_public_auth();init_common();init_errors()}});function keepingListsUnchanged(change){depth++;try{return change()}finally{depth--}}function listsUnchanged(){return depth>0}var depth;var init_unchanged_lists=__esm({"libs/sdk/src/surface/unchanged-lists.ts"(){"use strict";depth=0}});import{AsyncLocalStorage as AsyncLocalStorage3}from"@frontmcp/utils";function openBatchOf(lists){for(let run=runningBatches.getStore();run;run=run.outer){if(run.open&&run.lists===lists)return run}return void 0}async function runListChangeBatch(lists,change){const run={lists,changed:new Set,outer:runningBatches.getStore(),open:true};const batch={listsRestored:()=>run.changed.clear()};let outcome;try{outcome={completed:true,result:await runningBatches.run(run,()=>change(batch))}}catch(error){outcome={completed:false,error}}run.open=false;const announcementFailure=announceChangedLists(run,lists);if(!outcome.completed)throw outcome.error;if(announcementFailure)throw announcementFailure.error;return outcome.result}function announceChangedLists(run,lists){const enclosing=openBatchOf(lists);let firstFailure;for(const kind of run.changed){if(enclosing){enclosing.changed.add(kind);continue}try{lists[kind].notifyListChanged()}catch(error){firstFailure??={error}}}return firstFailure}function announcesListChangeNow(lists,kind){if(listsUnchanged())return false;const batch=openBatchOf(lists);batch?.changed.add(kind);return batch===void 0}var runningBatches;var init_list_change_batch=__esm({"libs/sdk/src/surface/list-change-batch.ts"(){"use strict";init_unchanged_lists();runningBatches=new AsyncLocalStorage3}});function mcpRequestSurface(scope){return scope?.metadata?.["__cliMode"]===true?"cli":"mcp"}function withMcpSurface(scope,ctx){return{...ctx,surface:mcpRequestSurface(scope)}}function mcpRequestSessionId(ctx){const sessionId=ctx?.authInfo?.sessionId;return typeof sessionId==="string"&&sessionId?sessionId:void 0}var init_mcp_surface=__esm({"libs/sdk/src/transport/mcp-handlers/mcp-surface.ts"(){"use strict"}});var resource_update_access_exports={};__export(resource_update_access_exports,{callerMayStillRead:()=>callerMayStillRead});import{runRequestExclusive}from"@frontmcp/utils";async function callerMayStillRead(scope,session,caller,uri){const request2={method:"resources/subscribe",params:{uri}};const authInfo={...caller,sessionId:session.sessionId};const{platformEnv}=session;const ctx={authInfo,surface:mcpRequestSurface(scope),ownRequest:true,checkOnly:true,...platformEnv!==void 0?{platformEnv}:{}};return runRequestExclusive(()=>scope.runFlow("resources:subscribe",{request:request2,ctx})).then(()=>true,()=>false)}var init_resource_update_access=__esm({"libs/sdk/src/notification/resource-update-access.ts"(){"use strict";init_mcp_surface()}});import{ListRootsResultSchema}from"@frontmcp/protocol";import{awaitOutsideRequest}from"@frontmcp/utils";function hasMcpAppsExtension(capabilities){const declared=capabilities?.experimental?.[MCP_APPS_EXTENSION_KEY]??capabilities?.extensions?.[MCP_APPS_EXTENSION_KEY];return declared!==void 0&&declared!==null}function detectPlatformFromCapabilities(capabilities){if(hasMcpAppsExtension(capabilities)){return"ext-apps"}return void 0}function supportsElicitation(capabilities,mode){if(!capabilities?.elicitation){return false}if(mode==="form"){return capabilities.elicitation.form!==void 0}if(mode==="url"){return capabilities.elicitation.url!==void 0}return true}function matchCustomMappings(clientName,mappings){if(!mappings||mappings.length===0){return void 0}const lowerClientName=clientName.toLowerCase();for(const mapping of mappings){if(typeof mapping.pattern==="string"){if(lowerClientName===mapping.pattern.toLowerCase()){return mapping.platform}}else{if(clientName.search(mapping.pattern)!==-1){return mapping.platform}}}return void 0}function defaultPlatformDetection(identifier){const lowerIdentifier=identifier.toLowerCase();if(lowerIdentifier.includes("codex")){return"codex"}if(lowerIdentifier.includes("claude-code")||lowerIdentifier.includes("claude code")){return"claude-code"}if(lowerIdentifier.includes("chatgpt")||lowerIdentifier.includes("openai")||lowerIdentifier.includes("gpt")){return"openai"}if(lowerIdentifier.includes("claude")||lowerIdentifier.includes("anthropic")){return"claude"}if(lowerIdentifier.includes("gemini")||lowerIdentifier.includes("bard")||lowerIdentifier.includes("google-ai")||lowerIdentifier.includes("google ai")){return"gemini"}if(lowerIdentifier.includes("cursor")){return"cursor"}if(lowerIdentifier.includes("continue")){return"continue"}if(lowerIdentifier.includes("cody")||lowerIdentifier.includes("sourcegraph")){return"cody"}if(lowerIdentifier.includes("mcp")){return"generic-mcp"}return"unknown"}function detectPlatformFromUserAgent(userAgent,config){if(!userAgent){return"unknown"}const customMatch=matchCustomMappings(userAgent,config?.mappings);if(customMatch){return customMatch}if(config?.customOnly){return"unknown"}return defaultPlatformDetection(userAgent)}function detectAIPlatform(clientInfo,config){if(!clientInfo?.name){return"unknown"}const customMatch=matchCustomMappings(clientInfo.name,config?.mappings);if(customMatch){return customMatch}if(config?.customOnly){return"unknown"}return defaultPlatformDetection(clientInfo.name)}function resolvePlatformType(clientInfo,capabilities,config){const mapped=clientInfo?.name?matchCustomMappings(clientInfo.name,config?.mappings):void 0;if(mapped)return mapped;const fromCapabilities=detectPlatformFromCapabilities(capabilities);if(fromCapabilities)return fromCapabilities;return detectAIPlatform(clientInfo,config)}function supportsChannels(capabilities){return capabilities?.experimental?.["claude/channel"]!==void 0}function isChannelCapableSession(session){return session.stdio===true||supportsChannels(session.clientCapabilities)}function sessionCallerOf(authInfo){const{clientId,scopes,user,claims:claims3}=authInfo;return{clientId,scopes,user,claims:claims3,expiresAt:authInfo.expiresAt??user?.exp}}function isSameCaller(left,right){return left===right||JSON.stringify(left)===JSON.stringify(right)}function hasExpiredCaller(session){const expiresAt=session.caller?.expiresAt;return expiresAt!==void 0&&expiresAt*1e3<Date.now()}var MCP_APPS_EXTENSION_KEY,MAX_CALLER_RECHECKS,MCP_LOGGING_LEVEL_PRIORITY,NotificationService;var init_notification_service=__esm({"libs/sdk/src/notification/notification.service.ts"(){"use strict";init_list_change_batch();MCP_APPS_EXTENSION_KEY="io.modelcontextprotocol/ui";MAX_CALLER_RECHECKS=3;MCP_LOGGING_LEVEL_PRIORITY={debug:0,info:1,notice:2,warning:3,error:4,critical:5,alert:6,emergency:7};NotificationService=class _NotificationService{constructor(scope,options={}){this.scope=scope;this.options=options;this.logger=scope.logger.child("NotificationService")}scope;options;logger;servers=new Map;unsubscribers=[];subscriptions=new Map;channelSubscriptions=new Map;logLevels=new Map;terminatedSessions=new Set;static MAX_TERMINATED_SESSIONS=1e4;get maxTerminatedSessions(){return this.options.maxTerminatedSessions??_NotificationService.MAX_TERMINATED_SESSIONS}async initialize(){this.logger.verbose("Initializing notification service");const unsubResources=this.scope.resources.subscribe({immediate:false},event=>{if(event.changeScope==="global"){if(event.kind==="updated"&&event.updatedUri){this.notifyResourceUpdated(event.updatedUri)}else if(announcesListChangeNow(this.scope,"resources")){this.broadcastNotification("notifications/resources/list_changed")}}});this.unsubscribers.push(unsubResources);const unsubTools=this.scope.tools.subscribe({immediate:false},event=>{if(event.changeScope==="global"&&announcesListChangeNow(this.scope,"tools")){this.broadcastNotification("notifications/tools/list_changed")}});this.unsubscribers.push(unsubTools);const unsubPrompts=this.scope.prompts.subscribe({immediate:false},event=>{if(event.changeScope==="global"&&announcesListChangeNow(this.scope,"prompts")){this.broadcastNotification("notifications/prompts/list_changed")}});this.unsubscribers.push(unsubPrompts);const skillRegistry=this.scope.skills;if(skillRegistry?.subscribe){const unsubSkills=skillRegistry.subscribe({immediate:false},event=>{if(event.changeScope==="global"&&announcesListChangeNow(this.scope,"skills")){this.broadcastNotification("notifications/skills/list_changed")}});this.unsubscribers.push(unsubSkills)}this.logger.info("Notification service initialized with registry subscriptions")}registerServer(sessionId,server,connection={}){if(this.servers.has(sessionId)){this.logger.warn(`Server already registered for session: ${sessionId.slice(0,20)}...`);return}const registered={sessionId,server,registeredAt:Date.now()};if(connection.stdio)registered.stdio=true;this.servers.set(sessionId,registered);this.logger.verbose(`Registered server for session: ${sessionId.slice(0,20)}... (total: ${this.servers.size})`)}unregisterServer(sessionId){const deleted=this.servers.delete(sessionId);const subCount=this.subscriptions.get(sessionId)?.size??0;this.subscriptions.delete(sessionId);const channelSubCount=this.channelSubscriptions.get(sessionId)?.size??0;this.channelSubscriptions.delete(sessionId);const hadLogLevel=this.logLevels.delete(sessionId);if(deleted){this.logger.verbose(`Unregistered server for session: ${sessionId.slice(0,20)}... (remaining: ${this.servers.size}, cleaned ${subCount} resource sub(s), ${channelSubCount} channel sub(s)${hadLogLevel?", removed log level":""})`)}return deleted}terminateSession(sessionId){const wasRegistered=this.unregisterServer(sessionId);this.scope.providers.cleanupSession(sessionId);this.logger.verbose(`Cleaned up provider cache for terminated session: ${sessionId.slice(0,20)}...`);this.scope.skillSession?.endSession(sessionId).catch(error=>{this.logger.warn(`Failed to forget the skill session of ${sessionId.slice(0,20)}...: ${String(error)}`)});if(this.terminatedSessions.size>=this.maxTerminatedSessions){const oldest=this.terminatedSessions.values().next().value;if(oldest){this.terminatedSessions.delete(oldest);this.logger.verbose(`Evicted oldest terminated session to make room: ${oldest.slice(0,20)}...`)}}this.terminatedSessions.add(sessionId);this.logger.verbose(`Terminated session: ${sessionId.slice(0,20)}... (total terminated: ${this.terminatedSessions.size})`);return wasRegistered}isSessionTerminated(sessionId){return this.terminatedSessions.has(sessionId)}unmarkTerminated(sessionId){this.terminatedSessions.delete(sessionId)}broadcastNotification(method,params){if(this.servers.size===0){this.logger.verbose(`No servers registered for notification: ${method}`);return}this.logger.verbose(`Broadcasting ${method} to ${this.servers.size} server(s)`);for(const[sessionId,{server}]of this.servers){this.sendNotificationToServer(server,sessionId,method,params)}}sendNotificationToSession(sessionId,method,params){const registered=this.servers.get(sessionId);if(!registered){const relay=this.scope.haManager?.getRelay();const transportService=this.scope.transportService;if(relay&&transportService){this.logger.debug(`[HA] Relaying notification ${method} for non-local session ${sessionId.slice(0,20)}...`);void this.relayNotification(sessionId,method,params);return}this.logger.warn(`Cannot send notification to unregistered session: ${sessionId.slice(0,20)}...`);return}this.sendNotificationToServer(registered.server,sessionId,method,params)}deliverRelayedNotification(sessionId,method,params){const registered=this.servers.get(sessionId);if(!registered){this.logger.verbose(`[HA] Relayed ${method} for session ${sessionId.slice(0,20)}... not served here \u2014 dropped`);return false}this.sendNotificationToServer(registered.server,sessionId,method,params);return true}async relayNotification(sessionId,method,params){const label=sessionId.slice(0,20);try{const owner=await this.scope.transportService?.lookupSessionOwner(sessionId);const relay=this.scope.haManager?.getRelay();if(!owner||!relay||owner.nodeId===this.scope.haManager?.getNodeId()){this.logger.warn(`Cannot send notification to unregistered session: ${label}...`);return}await relay.publish(owner.nodeId,sessionId,{method,params})}catch{this.logger.warn(`[HA] Failed to relay notification ${method} to session ${label}...`)}}subscribeResource(sessionId,uri,platformEnv){const registered=this.servers.get(sessionId);if(!registered){this.logger.warn(`Cannot subscribe unregistered session ${sessionId.slice(0,20)}... to resource ${uri}`);return false}if(platformEnv!==void 0)registered.platformEnv=platformEnv;let sessionSubs=this.subscriptions.get(sessionId);if(!sessionSubs){sessionSubs=new Set;this.subscriptions.set(sessionId,sessionSubs)}const isNew=!sessionSubs.has(uri);sessionSubs.add(uri);if(isNew){this.logger.verbose(`Session ${sessionId.slice(0,20)}... subscribed to resource ${uri}`)}return isNew}unsubscribeResource(sessionId,uri){const sessionSubs=this.subscriptions.get(sessionId);if(!sessionSubs){return false}const wasSubscribed=sessionSubs.delete(uri);if(sessionSubs.size===0){this.subscriptions.delete(sessionId)}if(wasSubscribed){this.logger.verbose(`Session ${sessionId.slice(0,20)}... unsubscribed from resource ${uri}`)}return wasSubscribed}isSubscribed(sessionId,uri){return this.subscriptions.get(sessionId)?.has(uri)??false}getSubscribersForResource(uri){const subscribers=[];for(const[sessionId,uris]of this.subscriptions){if(uris.has(uri)){subscribers.push(sessionId)}}return subscribers}notifyResourceUpdated(uri){const subscribers=this.getSubscribersForResource(uri);if(subscribers.length===0){this.logger.verbose(`No subscribers for resource ${uri}, skipping notification`);return}this.logger.verbose(`Notifying ${subscribers.length} subscriber(s) of resource update: ${uri}`);for(const sessionId of subscribers){void this.notifyIfStillReadable(sessionId,uri)}}async notifyIfStillReadable(sessionId,uri){const registered=this.servers.get(sessionId);if(!registered||hasExpiredCaller(registered))return;const{callerMayStillRead:callerMayStillRead2}=await Promise.resolve().then(()=>(init_resource_update_access(),resource_update_access_exports));let checkedCaller=registered.caller;for(let attempt=0;attempt<MAX_CALLER_RECHECKS;attempt++){const mayRead=await callerMayStillRead2(this.scope,registered,checkedCaller,uri);const current=this.servers.get(sessionId);if(current!==registered||!this.isSubscribed(sessionId,uri)||hasExpiredCaller(current))return;if(isSameCaller(current.caller,checkedCaller)){if(mayRead)this.sendNotificationToSession(sessionId,"notifications/resources/updated",{uri});return}checkedCaller=current.caller}}subscribeChannel(sessionId,channelName){if(!this.servers.has(sessionId)){this.logger.warn(`Cannot subscribe unregistered session ${sessionId.slice(0,20)}... to channel ${channelName}`);return false}let sessionSubs=this.channelSubscriptions.get(sessionId);if(!sessionSubs){sessionSubs=new Set;this.channelSubscriptions.set(sessionId,sessionSubs)}const isNew=!sessionSubs.has(channelName);sessionSubs.add(channelName);if(isNew){this.logger.verbose(`Session ${sessionId.slice(0,20)}... subscribed to channel "${channelName}"`)}return isNew}unsubscribeChannel(sessionId,channelName){const sessionSubs=this.channelSubscriptions.get(sessionId);if(!sessionSubs)return false;const wasSubscribed=sessionSubs.delete(channelName);if(sessionSubs.size===0){this.channelSubscriptions.delete(sessionId)}return wasSubscribed}subscribeAllChannels(sessionId,channelNames){for(const name59 of channelNames){this.subscribeChannel(sessionId,name59)}}isChannelSubscribed(sessionId,channelName){return this.channelSubscriptions.get(sessionId)?.has(channelName)??false}getSubscribersForChannel(channelName){const subscribers=[];for(const[sessionId,channels]of this.channelSubscriptions){if(channels.has(channelName)){subscribers.push(sessionId)}}return subscribers}getChannelSubscriptions(sessionId){const subs=this.channelSubscriptions.get(sessionId);return subs?[...subs]:[]}get serverCount(){return this.servers.size}setLogLevel(sessionId,level){if(!this.servers.has(sessionId)){this.logger.warn(`Cannot set log level for unregistered session: ${sessionId.slice(0,20)}...`);return false}this.logLevels.set(sessionId,level);this.logger.verbose(`Set log level to '${level}' for session ${sessionId.slice(0,20)}...`);return true}getLogLevel(sessionId){return this.logLevels.get(sessionId)}sendLogMessage(level,loggerName,data){const messagePriority=MCP_LOGGING_LEVEL_PRIORITY[level];for(const[sessionId,{server}]of this.servers){const sessionLevel=this.logLevels.get(sessionId);if(!sessionLevel){continue}const sessionPriority=MCP_LOGGING_LEVEL_PRIORITY[sessionLevel];if(messagePriority>=sessionPriority){const params={level,data};if(loggerName){params["logger"]=loggerName}this.sendNotificationToServer(server,sessionId,"notifications/message",params)}}}sendLogMessageToSession(sessionId,level,loggerName,data,relatedRequestId){const registered=this.servers.get(sessionId);if(!registered){return false}const sessionLevel=this.logLevels.get(sessionId);if(!sessionLevel){return false}const messagePriority=MCP_LOGGING_LEVEL_PRIORITY[level];const sessionPriority=MCP_LOGGING_LEVEL_PRIORITY[sessionLevel];if(messagePriority<sessionPriority){return false}const params={level,data};if(loggerName){params["logger"]=loggerName}this.sendNotificationToServer(registered.server,sessionId,"notifications/message",params,relatedRequestId);return true}sendProgressNotification(sessionId,progressToken,progress,total,message,relatedRequestId){const registered=this.servers.get(sessionId);if(!registered){return false}const params={progressToken,progress,...total!==void 0&&{total},...message!==void 0&&{message}};this.sendNotificationToServer(registered.server,sessionId,"notifications/progress",params,relatedRequestId);return true}setClientCapabilities(sessionId,capabilities){const registered=this.servers.get(sessionId);if(!registered){this.logger.warn(`Cannot set client capabilities for unregistered session: ${sessionId.slice(0,20)}...`);return false}registered.clientCapabilities=capabilities;if(!registered.clientInfo)registered.platformType=detectPlatformFromCapabilities(capabilities);this.logger.verbose(`Set client capabilities for session ${sessionId.slice(0,20)}...: roots.listChanged=${capabilities.roots?.listChanged??false}`);return true}setCaller(sessionId,caller){const registered=this.servers.get(sessionId);if(!registered)return false;registered.caller=caller;return true}getClientCapabilities(sessionId){return this.servers.get(sessionId)?.clientCapabilities}setClientInfo(sessionId,clientInfo){const registered=this.servers.get(sessionId);if(!registered){this.logger.warn(`Cannot set client info for unregistered session: ${sessionId.slice(0,20)}...`);return void 0}registered.clientInfo=clientInfo;const platformDetectionConfig=this.scope.metadata.transport?.platformDetection;registered.platformType=resolvePlatformType(clientInfo,registered.clientCapabilities,platformDetectionConfig);this.logger.verbose(`Set client info for session ${sessionId.slice(0,20)}...: name=${clientInfo.name}, version=${clientInfo.version}, platform=${registered.platformType}`);return registered.platformType}getClientInfo(sessionId){return this.servers.get(sessionId)?.clientInfo}getPlatformType(sessionId){const session=this.servers.get(sessionId);return session?.platformType??"unknown"}supportsRoots(sessionId){const capabilities=this.getClientCapabilities(sessionId);return capabilities?.roots!==void 0}async listRoots(sessionId,options){const registered=this.servers.get(sessionId);if(!registered){this.logger.warn(`Cannot list roots for unregistered session: ${sessionId.slice(0,20)}...`);return[]}if(!this.supportsRoots(sessionId)){this.logger.verbose(`Client for session ${sessionId.slice(0,20)}... does not support roots`);return[]}if(!options?.forceRefresh&&registered.cachedRoots!==void 0){this.logger.verbose(`Returning cached roots for session ${sessionId.slice(0,20)}... (${registered.cachedRoots.length} roots)`);return registered.cachedRoots}try{this.logger.verbose(`Requesting roots from client for session ${sessionId.slice(0,20)}...`);const result=await awaitOutsideRequest(registered.server.request({method:"roots/list"},ListRootsResultSchema,{timeout:options?.timeout??3e4}));registered.cachedRoots=result.roots;registered.rootsFetchedAt=Date.now();this.logger.verbose(`Received ${registered.cachedRoots.length} root(s) from client for session ${sessionId.slice(0,20)}...`);return registered.cachedRoots}catch(error){this.logger.warn(`Failed to list roots for session ${sessionId.slice(0,20)}...: ${error instanceof Error?error.message:"Unknown error"}`);return registered.cachedRoots??[]}}invalidateRootsCache(sessionId){const registered=this.servers.get(sessionId);if(!registered){return false}const hadCache=registered.cachedRoots!==void 0;registered.cachedRoots=void 0;registered.rootsFetchedAt=void 0;if(hadCache){this.logger.verbose(`Invalidated roots cache for session ${sessionId.slice(0,20)}...`)}return hadCache}getCachedRoots(sessionId){return this.servers.get(sessionId)?.cachedRoots}async destroy(){this.logger.verbose("Destroying notification service");for(const unsub of this.unsubscribers){unsub()}this.unsubscribers.length=0;this.servers.clear();this.subscriptions.clear();this.logLevels.clear();this.terminatedSessions.clear();this.logger.info("Notification service destroyed")}sendCustomNotification(method,params,filter){if(this.servers.size===0){this.logger.verbose(`No servers registered for custom notification: ${method}`);return}let sent=0;for(const[sessionId,registered]of this.servers){if(filter&&!filter(registered))continue;this.sendNotificationToServer(registered.server,sessionId,method,params);sent++}this.logger.verbose(`Sent custom notification ${method} to ${sent}/${this.servers.size} session(s)`)}getChannelCapableSessions(){return[...this.servers.values()].filter(isChannelCapableSession)}getRegisteredServer(sessionId){return this.servers.get(sessionId)}sendNotificationToServer(server,sessionId,method,params,relatedRequestId){if(relatedRequestId!==void 0){void this.sendOnRequestStream(server,sessionId,method,params,relatedRequestId);return}try{server.notification({method,params:params??{}});this.logger.verbose(`Sent ${method} to session ${sessionId.slice(0,20)}...`)}catch(error){this.logger.warn(`Failed to send notification ${method} to session ${sessionId.slice(0,20)}...: ${error instanceof Error?error.message:"Unknown error"}`);this.unregisterServer(sessionId)}}async sendOnRequestStream(server,sessionId,method,params,relatedRequestId){try{await server.notification({method,params:params??{}},{relatedRequestId});this.logger.verbose(`Sent ${method} to session ${sessionId.slice(0,20)}... for request ${relatedRequestId}`)}catch{this.sendNotificationToServer(server,sessionId,method,params)}}}}});var SEP_2640_EXTENSION_ID,SEP_2640_META_NAMESPACE,SKILL_URI_SCHEME,SKILL_INDEX_URI,SKILL_INDEX_SCHEMA_URI,SKILL_MD_MIME_TYPE,SKILL_INDEX_MIME_TYPE,SKILL_MD_PRIORITY;var init_sep_2640_constants=__esm({"libs/sdk/src/skill/sep-2640/sep-2640.constants.ts"(){"use strict";SEP_2640_EXTENSION_ID="io.modelcontextprotocol/skills";SEP_2640_META_NAMESPACE="io.modelcontextprotocol.skills/";SKILL_URI_SCHEME="skill://";SKILL_INDEX_URI="skill://index.json";SKILL_INDEX_SCHEMA_URI="https://schemas.agentskills.io/discovery/0.2.0/schema.json";SKILL_MD_MIME_TYPE="text/markdown";SKILL_INDEX_MIME_TYPE="application/json";SKILL_MD_PRIORITY=.8}});import{createGlobMatcher as createGlobMatcher2}from"@frontmcp/utils";function compile(clients){const known=compiledProfiles.get(clients);if(known)return known;const compiled=Object.entries(clients).map(([glob,profile])=>[createGlobMatcher2(glob.toLowerCase()),profile]);compiledProfiles.set(clients,compiled);return compiled}function resolveClientProfile(clients,clientName){if(!clients||clientName===void 0||clientName.length>MAX_CLIENT_NAME_LENGTH)return void 0;const lowerName=clientName.toLowerCase();return compile(clients).find(([matches])=>matches(lowerName))?.[1]}function callerClientName({context,authInfo,notifications}){const sessionId=authInfo?.sessionId;return context?.clientInfo?.name??authInfo?.sessionIdPayload?.clientName??(sessionId?notifications?.getClientInfo(sessionId)?.name:void 0)}function callerClientProfile(clients,sources3){return clients?resolveClientProfile(clients,callerClientName(sources3)):void 0}function describeValue(value){if(Array.isArray(value))return` (${value.length} ${value.length===1?"item":"items"})`;if(typeof value==="object"&&value!==null)return` (${Object.keys(value).length} keys)`;if(typeof value==="string"){return value.length<=SHORT_STRING?`: ${JSON.stringify(value)}`:` (${value.length} characters)`}return`: ${String(value)}`}function summarizeStructuredContent(structuredContent){const keys=Object.keys(structuredContent);const described=keys.slice(0,SUMMARY_KEYS).map(key=>`${key}${describeValue(structuredContent[key])}`);if(keys.length>SUMMARY_KEYS)described.push(`${keys.length-SUMMARY_KEYS} more keys`);return described.length>0?`The answer is in structuredContent: ${described.join(", ")}.`:"The answer is in structuredContent."}function shapeToolAnswer(result,mode,listsOutputSchema){const{structuredContent}=result;if(mode==="both"||structuredContent===void 0)return void 0;if(mode==="text"){const{structuredContent:_dropped,...textOnly}=result;return textOnly}if(!listsOutputSchema||result.isError)return void 0;const structuredText=JSON.stringify(structuredContent);const summary=summarizeStructuredContent(structuredContent);return{...result,content:result.content.map(block=>block.type==="text"&&block.text===structuredText?{...block,text:summary}:block)}}function annotationsForClient(annotations,mode,skillMd){if(mode==="no-numbers"){if(!annotations||annotations.priority===void 0)return annotations;const{priority:_dropped,...withoutNumbers}=annotations;return Object.keys(withoutNumbers).length>0?withoutNumbers:void 0}if(mode==="full"&&skillMd){return{audience:["assistant"],...annotations,priority:SKILL_MD_PRIORITY}}return annotations}var SUMMARY_KEYS,SHORT_STRING,MAX_CLIENT_NAME_LENGTH,compiledProfiles;var init_client_profile=__esm({"libs/sdk/src/answer/client-profile.ts"(){"use strict";init_sep_2640_constants();SUMMARY_KEYS=12;SHORT_STRING=40;MAX_CLIENT_NAME_LENGTH=256;compiledProfiles=new WeakMap}});import{checkEntryAvailability,getRuntimeContext as getRuntimeContext3,isEntryAvailable}from"@frontmcp/utils";function callSurfaceOf(ctx){const surface=ctx?.surface;return typeof surface==="string"&&CALL_SURFACES.includes(surface)?surface:void 0}function isOfferedOnSurface(availability,surface){const offered=availability?.surface;return offered===void 0||surface===void 0||offered.includes(surface)}function availabilityForCall(availability,surface){if(!isOfferedOnSurface(availability,surface))return"not-offered";return isEntryAvailable(availability,getRuntimeContext3())?"available":"unavailable"}function entryUnavailableError(entryType,entryName,availability,surface){const ctx=getRuntimeContext3();const{missingAxes}=checkEntryAvailability(availability,ctx,surface?{surface}:void 0);return new EntryUnavailableError(entryType,entryName,availability,{...ctx,surface},missingAxes)}function logAvailabilityFiltering(registryKind,entries,logger){const ctx=getRuntimeContext3();const constrained=[];const filtered=[];const emptyConstraints=[];const fields=["platform","runtime","deployment","env"];for(const entry of entries){const aw=entry.metadata.availableWhen;if(!aw)continue;constrained.push(entry);for(const field of fields){const arr=aw[field];if(arr&&arr.length===0){emptyConstraints.push(entry);break}}if(!isEntryAvailable(aw,ctx)){filtered.push(entry)}}if(constrained.length===0)return;const available=constrained.length-filtered.length;logger.info(`[${registryKind}] availability: ${entries.length} total, ${constrained.length} with availableWhen constraint, ${available} available, ${filtered.length} filtered [ctx: platform=${ctx.platform}, runtime=${ctx.runtime}, deployment=${ctx.deployment}, env=${ctx.env}]`);for(const entry of filtered){const aw=entry.metadata.availableWhen;logger.verbose(`[${registryKind}] filtered: "${entry.name}" \u2014 constraint=${JSON.stringify(aw)}, current=${formatContextForConstraint(aw,ctx)}`)}for(const entry of emptyConstraints){const aw=entry.metadata.availableWhen;const emptyFields=fields.filter(f=>aw?.[f]?.length===0);logger.warn(`[${registryKind}] "${entry.name}" has empty availableWhen arrays for [${emptyFields.join(", ")}] \u2014 this entry will never be available. This is likely a configuration bug.`)}}function formatContextForConstraint(aw,ctx){const parts=[];if(aw.platform)parts.push(`platform=${ctx.platform}`);if(aw.runtime)parts.push(`runtime=${ctx.runtime}`);if(aw.deployment)parts.push(`deployment=${ctx.deployment}`);if(aw.env)parts.push(`env=${ctx.env}`);return parts.join(", ")}var CALL_SURFACES;var init_availability_utils=__esm({"libs/sdk/src/common/availability/availability.utils.ts"(){"use strict";init_mcp_error();CALL_SURFACES=["mcp","cli","http-trigger","job","agent","webmcp"]}});var init_availability=__esm({"libs/sdk/src/common/availability/index.ts"(){"use strict";init_availability_utils()}});var AUTHORITIES_NOT_CONFIGURED;var init_authorities_not_configured=__esm({"libs/sdk/src/builtin/authorities/authorities-not-configured.ts"(){"use strict";AUTHORITIES_NOT_CONFIGURED="no authorities engine is configured (add 'authorities' to @FrontMcp())"}});async function isListedByAuthorities(engine,contextBuilder,authorities,authInfo,entryName,logger){try{const result=await engine.evaluate(authorities,contextBuilder.build(authInfo));return result.granted}catch(error){logger?.warn(`The authorities of "${entryName}" failed to answer, so it is left out of the list: ${error instanceof Error?error.message:String(error)}`);return false}}var init_entry_authorized=__esm({"libs/sdk/src/surface/entry-authorized.ts"(){"use strict"}});import{AuthorityDeniedError as AuthorityDeniedError2,resolveRequiredScopes}from"@frontmcp/auth";function normalizeAuthInfoForAuthorities(authInfo){if(authInfo["user"])return authInfo;const extra=authInfo["extra"];const extraUser=extra?.["user"];if(extraUser)return{...authInfo,user:extraUser};return authInfo}function getSkillAuthorities(skill){const metadata=skill.metadata;const authorities=metadata["authorities"];return authorities}async function assertSkillAuthorized(scope,skill,authInfo,input={}){const authorities=getSkillAuthorities(skill);if(!authorities)return;const engine=scope.authoritiesEngine;const ctxBuilder=scope.authoritiesContextBuilder;if(!engine||!ctxBuilder){throw new AuthorityDeniedError2({entryType:"Skill",entryName:skill.fullName||skill.name,deniedBy:AUTHORITIES_NOT_CONFIGURED})}const evalCtx=ctxBuilder.build(normalizeAuthInfoForAuthorities(authInfo),input);const result=await engine.evaluate(authorities,evalCtx);if(result.granted)return;let requiredScopes;const scopeMapping=scope.authoritiesScopeMapping;if(scopeMapping&&result.denial){requiredScopes=resolveRequiredScopes(result.denial,scopeMapping,authorities)}throw new AuthorityDeniedError2({entryType:"Skill",entryName:skill.fullName||skill.name,deniedBy:result.deniedBy??"policy denied",denial:result.denial,requiredScopes})}async function filterSkillsByAuthorities(scope,skills,authInfo){const engine=scope.authoritiesEngine;const ctxBuilder=scope.authoritiesContextBuilder;if(!engine||!ctxBuilder)return skills.filter(skill=>!getSkillAuthorities(skill));const normalized2=normalizeAuthInfoForAuthorities(authInfo);const grants=await Promise.all(skills.map(async skill=>{const authorities=getSkillAuthorities(skill);if(!authorities)return true;return isListedByAuthorities(engine,ctxBuilder,authorities,normalized2,skill.fullName||skill.name,scope.logger)}));return skills.filter((_,i)=>grants[i])}var init_skill_authorities_helper=__esm({"libs/sdk/src/skill/skill-authorities.helper.ts"(){"use strict";init_authorities_not_configured();init_entry_authorized()}});var SkillBundleNotLoadedError;var init_skill_bundle_not_loaded_error=__esm({"libs/sdk/src/skill/errors/skill-bundle-not-loaded.error.ts"(){"use strict";init_errors();SkillBundleNotLoadedError=class extends PublicMcpError{constructor(reason){super(`No skill bundle is loaded: ${reason}`,"SKILL_BUNDLE_NOT_LOADED",503)}toJsonRpcError(){return{code:MCP_ERROR_CODES.INTERNAL_ERROR,message:this.getPublicMessage(),data:{code:this.code,retryable:true}}}toMcpError(isDevelopment7=false){const response=super.toMcpError(isDevelopment7);return response._meta?{...response,_meta:{...response._meta,retryable:true}}:response}}}});function findSkillCatalogSource(scope){if(!scope.providers)return void 0;try{return scope.providers.get(SkillCatalogSourceToken)}catch(error){if(error instanceof ProviderNotRegisteredError||error instanceof ProviderNotAvailableError||error instanceof DependencyNotFoundError){return void 0}scope.logger.warn("the skill source provider failed; serving skills without it",{error:error instanceof Error?error.message:String(error)});return void 0}}async function readySkillCatalog(scope){const source=findSkillCatalogSource(scope);if(!source)return{};try{await source.ready()}catch(error){scope.logger.warn("a skill source failed to load; serving the skills registered so far",{error:error instanceof Error?error.message:String(error)})}return{source,notLoadedReason:notLoadedReasonOf(source,scope)}}function notLoadedReasonOf(source,scope){try{return source.notLoadedReason?.()}catch(error){scope.logger.warn("a skill source failed to report whether its skills loaded; serving the skills registered so far",{error:error instanceof Error?error.message:String(error)});return void 0}}async function assertSkillCatalogLoaded(scope){const{notLoadedReason}=await readySkillCatalog(scope);if(notLoadedReason!==void 0)throw new SkillBundleNotLoadedError(notLoadedReason)}var SkillCatalogSourceToken;var init_skill_catalog_source=__esm({"libs/sdk/src/skill/skill-catalog-source.ts"(){"use strict";init_errors();init_skill_bundle_not_loaded_error();SkillCatalogSourceToken=Symbol.for("frontmcp:SKILL_CATALOG_SOURCE")}});import{isAnonymousSubject as isAnonymousSubject2}from"@frontmcp/auth";function publicAccessFor(authOptions,authInfo){const publicAccess=authOptions?.publicAccess;if(!publicAccess)return void 0;const info=authInfo;return isAnonymousSubject2(info?.user?.sub??info?.extra?.user?.sub)?publicAccess:void 0}function isPubliclyListed(publicAccess,kind,names){const allowed=publicAccess[kind]??"all";return allowed==="all"||names.some(name59=>allowed.includes(name59))}async function enforcePublicAccess(publicAccess,entry,guard,partition){if(!isPubliclyListed(publicAccess,entry.kind==="tool"?"tools":"prompts",entry.names)){throw new PublicAccessDeniedError(entry.kind,entry.names[0])}if(!guard||!publicAccess.rateLimit)return;const result=await guard.checkRateLimit(PUBLIC_ACCESS_RATE_LIMIT_KEY,{maxRequests:publicAccess.rateLimit,windowMs:PUBLIC_ACCESS_WINDOW_MS,partitionBy:"ip"},partition);if(!result.allowed)throw new RateLimitError(Math.ceil((result.retryAfterMs??PUBLIC_ACCESS_WINDOW_MS)/1e3))}var PUBLIC_ACCESS_RATE_LIMIT_KEY,PUBLIC_ACCESS_WINDOW_MS;var init_public_access_utils=__esm({"libs/sdk/src/auth/public-access.utils.ts"(){"use strict";init_errors();PUBLIC_ACCESS_RATE_LIMIT_KEY="__public_access__";PUBLIC_ACCESS_WINDOW_MS=6e4}});import{AsyncLocalStorage as AsyncLocalStorage4}from"@frontmcp/utils";function runOnSurface(surface,fn){return callSurfaces.run({surface},fn)}function getCallSurface(){return callSurfaces.getStore()?.surface}var callSurfaces;var init_call_surface=__esm({"libs/sdk/src/context/call-surface.ts"(){"use strict";callSurfaces=new AsyncLocalStorage4}});function skillResultId(result){return result.metadata.id??result.metadata.name}function createSkillEntryResolver(registry){let fallback;const fallbackEntry=id=>{if(!fallback){const skills=registry.getSkills(true);fallback=new Map;for(const skill of skills){const skillId=skill.metadata.id??skill.name;if(!fallback.has(skillId))fallback.set(skillId,skill)}for(const skill of skills){if(!fallback.has(skill.metadata.name))fallback.set(skill.metadata.name,skill)}}return fallback.get(id)};const lookup=id=>registry.findByName(id)??(id.includes(":")?registry.findByQualifiedName(id):void 0)??fallbackEntry(id);return(...ids)=>{for(const id of ids){if(!id)continue;const entry=lookup(id);if(entry)return entry}return void 0}}var init_skill_entry_resolver=__esm({"libs/sdk/src/skill/skill-entry.resolver.ts"(){"use strict"}});function callerSurface(ctx,surface){return surface??callSurfaceOf(ctx)??getCallSurface()}async function filterServableSkills(scope,skills,ctx,surface){const caller=callerSurface(ctx,surface);const offered=skills.filter(skill=>availabilityForCall(skill.metadata.availableWhen,caller)==="available");if(offered.length===0)return[];const{skills:servable}=await scope.runFlowForOutput("skills:filter",{skills:[...offered],ctx});const servableSkills=new Set(servable);return offered.filter(skill=>servableSkills.has(skill))}async function isSkillServable(scope,skill,ctx,surface){const servable=await filterServableSkills(scope,[skill],ctx,surface);return servable.length===1}async function filterDiscoverableSkillResults(scope,registry,results,caller={}){const resolve4=createSkillEntryResolver(registry);const entries=results.map(result=>resolve4(skillResultId(result)));const registered=[...new Set(entries.filter(entry=>entry!==void 0))];const authorized=await filterSkillsByAuthorities(scope,registered,caller.authInfo??{});const servable=new Set(await filterServableSkills(scope,authorized,caller.ctx,caller.surface));return results.filter((_,index)=>{const entry=entries[index];return entry===void 0||servable.has(entry)})}function skillToolsForCaller(loaded,tools,ctx,surface){const caller=callerSurface(ctx,surface);if(!tools||caller===void 0||loaded.availableTools.length===0)return loaded;const availability=new Map(tools.getTools(true).map(tool=>[tool.name,tool.metadata?.availableWhen]));return withToolsMissing(loaded,loaded.availableTools.filter(name59=>!isOfferedOnSurface(availability.get(name59),caller)))}async function skillToolsListedFor(scope,loaded,authInfo){const{tools,authoritiesEngine:engine,authoritiesContextBuilder:contextBuilder}=scope;const publicAccess=publicAccessFor(scope.auth?.options,authInfo);if(!tools||loaded.availableTools.length===0||!publicAccess&&(!engine||!contextBuilder))return loaded;const toolsByName=new Map(tools.getTools(true).map(tool=>[tool.name,tool]));const caller=normalizeAuthInfoForAuthorities(authInfo);const listed=await Promise.all(loaded.availableTools.map(async name59=>{const tool=toolsByName.get(name59);if(publicAccess&&!isPubliclyListed(publicAccess,"tools",[tool?.fullName??name59,name59]))return false;const authorities=tool?.metadata?.authorities;if(!authorities||!engine||!contextBuilder)return true;return isListedByAuthorities(engine,contextBuilder,authorities,caller,name59,scope.logger)}));return withToolsMissing(loaded,loaded.availableTools.filter((_,index)=>!listed[index]))}function withToolsMissing(loaded,names){if(names.length===0)return loaded;return{...loaded,availableTools:loaded.availableTools.filter(name59=>!names.includes(name59)),missingTools:[...loaded.missingTools,...names],isComplete:false,warning:warningWithMissingTools(loaded.warning,loaded.skill?.name,names)}}function warningWithMissingTools(warning,skillName,names){const prefix=warning?.match(WARNING_PREFIX);if(warning&&prefix&&warning.endsWith(WARNING_SUFFIX)){const parts=warning.slice(prefix[0].length,-WARNING_SUFFIX.length).split("; ");const missing=parts.findIndex(part=>part.startsWith(MISSING_PART));if(missing===-1)parts.unshift(`${MISSING_PART}${names.join(", ")}`);else parts[missing]=`${parts[missing]}, ${names.join(", ")}`;return`${prefix[0]}${parts.join("; ")}${WARNING_SUFFIX}`}const sentence=`Skill "${skillName??"skill"}" references ${MISSING_PART}${names.join(", ")}${WARNING_SUFFIX}`;return warning?`${warning} ${sentence}`:sentence}var SKILLS_HTTP_SURFACE,WARNING_PREFIX,WARNING_SUFFIX,MISSING_PART;var init_skill_filter_helper=__esm({"libs/sdk/src/skill/skill-filter.helper.ts"(){"use strict";init_public_access_utils();init_availability();init_call_surface();init_entry_authorized();init_skill_authorities_helper();init_skill_entry_resolver();SKILLS_HTTP_SURFACE="mcp";WARNING_PREFIX=/^Skill "(.*)" references /;WARNING_SUFFIX=". Some functionality may be limited.";MISSING_PART="missing tools: "}});function pointersFor(options){return options.pointers??(options.mcpResources===false?METHOD_POINTERS:RESOURCE_POINTERS)}function listedSkills(skillRegistry,options){return options.skills??skillRegistry?.getSkills({visibility:"mcp"})??[]}function sanitizeDescription(raw){if(!raw)return"";return raw.replace(/\r?\n/g," ").replace(/\s+/g," ").replace(/^\s*-{3,}\s*$/g,"").replace(/\\/g,"\\\\").replace(/`/g,"\\`").replace(/\*/g,"\\*").replace(/_/g,"\\_").replace(/\[/g,"\\[").trim()}function sanitizeName(raw){if(!raw)return"(unnamed)";const s=raw.replace(/\s+/g," ").trim();if(!s)return"(unnamed)";return s.length>MAX_SKILL_NAME_CHARS?`${s.slice(0,MAX_SKILL_NAME_CHARS)}\u2026`:s}function buildSkillsCatalogSummary(skillRegistry,options={}){const skills=listedSkills(skillRegistry,options);if(skills.length===0)return"";const pointers=pointersFor(options);const lines=[pointers.header,""];let truncated=false;let shownCount=0;let charCount=lines.join("\n").length;const effectiveCap=MAX_SKILL_CATALOG_CHARS-TRUNCATION_FOOTER_RESERVE;for(const skill of skills){const name59=sanitizeName(skill.metadata.name);const description=sanitizeDescription(skill.getDescription());const line=description?`- **${name59}**: ${description}`:`- **${name59}**`;if(charCount+line.length+1>effectiveCap){truncated=true;break}lines.push(line);charCount+=line.length+1;shownCount+=1}if(truncated){lines.push("",`_(catalog truncated \u2014 showing ${shownCount} of ${skills.length} skills; ${pointers.truncationHint})_`)}return lines.join("\n")}function buildCompactSkillsLine(skillRegistry,options){const count=listedSkills(skillRegistry,options).length;const servesExternalSkills=skillRegistry?.getExternalProvider()?.isReadOnly()===true;if(count===0&&!servesExternalSkills)return"";let skills=count===1?"1 skill":`${count} skills`;if(servesExternalSkills)skills="skills";return`This server has ${skills}: ${pointersFor(options).compact}`}function buildSkillsNotLoadedLine(reason){const singleLineReason=reason.replace(/\s+/g," ").trim();return`This server's skills have not loaded yet (${singleLineReason}). Ask for them again shortly; the server sends notifications/skills/list_changed once they load.`}function composeInitializeInstructions(options){const policy=options.policy??DEFAULT_POLICY;const user=(options.userInstructions??"").trim();const channel2=(options.channelInstructions??"").trim();if(policy==="replace"){if(user.length>0){return user}}if(policy==="off"){return joinSections([user,channel2])}if(options.skillsNotLoaded!==void 0){const notLoaded=buildSkillsNotLoadedLine(options.skillsNotLoaded);return joinSections(policy==="prepend"?[notLoaded,channel2,user]:[user,channel2,notLoaded])}const summaryOptions={mcpResources:options.mcpResources,skills:options.skills,pointers:options.pointers};if(policy==="compact"){return joinSections([user,channel2,buildCompactSkillsLine(options.skillRegistry,summaryOptions)])}const catalog=buildSkillsCatalogSummary(options.skillRegistry,summaryOptions);if(policy==="prepend"){return joinSections([catalog,channel2,user])}return joinSections([user,channel2,catalog])}function buildChannelInstructions(channels,events){const hasChannels=channels?.hasAny()===true;const tellsEvents=(events?.getChannelEvents().length??0)>0;if(!hasChannels&&!tellsEvents)return"";const sentences=["Events arrive as <channel> tags."];if(channels?.getChannelInstances().some(ch=>ch.twoWay))sentences.push(CHANNEL_REPLY_HINT);if(tellsEvents)sentences.push(CHANNEL_EVENT_HINT);return sentences.join(" ")}function instructionsPolicyFor(scope,clientName){const profiled=resolveClientProfile(scope.metadata.clients,clientName)?.instructions;if(profiled==="full")return"append";return profiled??scope.metadata.skillsConfig?.injectInstructions}async function composeCallerInstructions(scope,options={}){const skillsConfig=scope.metadata.skillsConfig;const{source,notLoadedReason}=await readySkillCatalog(scope);const composeOptions={userInstructions:scope.metadata.instructions,channelInstructions:buildChannelInstructions(scope.channels,scope.events),skillRegistry:scope.skills,policy:instructionsPolicyFor(scope,options.clientName),mcpResources:skillsConfig?.mcpResources,pointers:source?.pointers,skillsNotLoaded:notLoadedReason};const withUriHints=options.skillUriHints===true&&notLoadedReason===void 0&&skillUriHintsEnabled(scope);const listsSkills=withUriHints||includesSkillCatalog(composeOptions);let skills=[];if(listsSkills){try{skills=await skillsVisibleTo(scope,options.ctx)}catch(error){scope.logger.warn("initialize instructions: left the skills out, the skills:filter flow failed",{error:error instanceof Error?error.message:String(error)})}}const composed=composeInitializeInstructions({...composeOptions,skills});const uriHints=withUriHints?buildSkillUriHints(skills,scope.skills?.getSep2640InstructionUris?.()??[]):"";return[composed,uriHints].filter(section=>section.length>0).join("\n\n---\n\n")}function buildSkillUriHints(skills,extraUris=[]){if(skills.length===0)return"";const lines=["Available skills (load via resources/read):"];for(const skill of skills){lines.push(`- skill://${skill.getSkillPath()}/SKILL.md \u2014 ${skill.getDescription()}`)}for(const extra of extraUris){lines.push(`- ${extra}`)}return lines.join("\n")}function skillUriHintsEnabled(scope){const skillsConfig=scope.metadata.skillsConfig;if(!skillsConfig?.sep2640InInstructions||skillsConfig.mcpResources===false)return false;const serverInstructions=(scope.metadata.instructions??"").trim();return!(skillsConfig.injectInstructions==="replace"&&serverInstructions.length>0)}function includesSkillCatalog(options){const policy=options.policy??DEFAULT_POLICY;if(policy==="off"||options.skillsNotLoaded!==void 0)return false;return!(policy==="replace"&&(options.userInstructions??"").trim().length>0)}async function skillsVisibleTo(scope,ctx){const visible=scope.skills?.getSkills({visibility:"mcp"})??[];if(visible.length===0)return[];const authInfo=ctx?.authInfo??{};const authorized=await filterSkillsByAuthorities(scope,visible,authInfo);return filterServableSkills(scope,authorized,ctx,callSurfaceOf(ctx)??mcpRequestSurface(scope))}function joinSections(sections){return sections.map(s=>(s??"").trim()).filter(s=>s.length>0).join("\n\n---\n\n")}var DEFAULT_POLICY,MAX_SKILL_CATALOG_CHARS,TRUNCATION_FOOTER_RESERVE,RESOURCE_POINTERS,METHOD_POINTERS,MAX_SKILL_NAME_CHARS,CHANNEL_REPLY_HINT,CHANNEL_EVENT_HINT;var init_skill_instructions_helper=__esm({"libs/sdk/src/skill/skill-instructions.helper.ts"(){"use strict";init_client_profile();init_availability();init_mcp_surface();init_sep_2640_constants();init_skill_authorities_helper();init_skill_catalog_source();init_skill_filter_helper();DEFAULT_POLICY="compact";MAX_SKILL_CATALOG_CHARS=16e3;TRUNCATION_FOOTER_RESERVE=160;RESOURCE_POINTERS={header:`Available skills (read the \`${SKILL_INDEX_URI}\` resource for each skill's \`SKILL.md\` URI):`,truncationHint:`read \`${SKILL_INDEX_URI}\` to browse`,compact:`the \`${SKILL_INDEX_URI}\` resource lists each skill's \`SKILL.md\` URI.`};METHOD_POINTERS={header:"Available skills (load full content with the `skills/load` request, or find others with `skills/search`):",truncationHint:"use `skills/search` to find the rest",compact:"find one with the `skills/search` request and load it with `skills/load`."};MAX_SKILL_NAME_CHARS=80;CHANNEL_REPLY_HINT="Reply with the channel-reply tool.";CHANNEL_EVENT_HINT="A tag with event and event_id attributes is an event this server published: event is its name, event_id its id."}});function computeTaskCapabilities(scope){const registry=scope.tasks;if(!registry)return{};const hasTaskEnabledTool=scope.tools.getTools(true).some(t=>{const supp=t.metadata.execution?.taskSupport;return supp==="optional"||supp==="required"});const canIdentifyRequestors=true;return registry.getCapabilities({hasTaskEnabledTool,canIdentifyRequestors})}var init_task_scope_helper=__esm({"libs/sdk/src/task/task-scope.helper.ts"(){"use strict"}});var build_scoped_server_options_exports={};__export(build_scoped_server_options_exports,{buildScopedServerOptions:()=>buildScopedServerOptions});function buildScopedServerOptions(scope,instructions=""){const hasRemoteApps=scope.apps?.getApps().some(app=>app.isRemote)??false;const hasPrompts=scope.prompts.hasAny()||hasRemoteApps;const hasResources=scope.resources.hasAny()||hasRemoteApps;const completionsCapability=hasPrompts||hasResources?{completions:{}}:{};const remoteCapabilities=hasRemoteApps?{tools:{listChanged:true},resources:{subscribe:true,listChanged:true},prompts:{listChanged:true}}:{};const skillsCapabilities=scope.skills?.getCapabilities()??{};const toolsCapabilities=scope.tools.getCapabilities();const resourcesCapabilities=scope.resources.getCapabilities();const promptsCapabilities=scope.prompts.getCapabilities();const agentsCapabilities=scope.agents.getCapabilities();const channelCapabilities=channelCapabilitiesOf(scope);const eventCapabilities=scope.events?.getCapabilities()??{};const taskCapabilities=computeTaskCapabilities(scope);const fragments=[remoteCapabilities,toolsCapabilities,resourcesCapabilities,promptsCapabilities,agentsCapabilities,channelCapabilities,eventCapabilities,skillsCapabilities,completionsCapability,taskCapabilities];const experimental={};const extensions={};for(const cap2 of fragments){if(cap2["experimental"]&&typeof cap2["experimental"]==="object"){Object.assign(experimental,cap2["experimental"])}if(cap2["extensions"]&&typeof cap2["extensions"]==="object"){Object.assign(extensions,cap2["extensions"])}}const baseCapabilities={...remoteCapabilities,...toolsCapabilities,...resourcesCapabilities,...promptsCapabilities,...agentsCapabilities,...eventCapabilities,...completionsCapability,...taskCapabilities,logging:{}};if(Object.keys(experimental).length>0)baseCapabilities["experimental"]=experimental;if(Object.keys(extensions).length>0)baseCapabilities["extensions"]=extensions;return{instructions,capabilities:baseCapabilities,serverInfo:scope.metadata.info}}var init_build_scoped_server_options=__esm({"libs/sdk/src/transport/build-scoped-server-options.ts"(){"use strict";init_channel_utils();init_task_scope_helper()}});import{AjvJsonSchemaValidator,McpServer}from"@frontmcp/protocol";function createMcpServer(info,options){let validator;return new McpServer(info,{...options,jsonSchemaValidator:{getValidator:schema=>(validator??=new AjvJsonSchemaValidator).getValidator(schema)}})}var init_mcp_server_factory=__esm({"libs/sdk/src/transport/mcp-server.factory.ts"(){"use strict"}});import{McpError as McpError2}from"@frontmcp/protocol";import{isProduction as isProduction3}from"@frontmcp/utils";function hasJsonRpcError(err){return typeof err?.toJsonRpcError==="function"}function jsonRpcCodeForStatus(statusCode){if(statusCode===401)return MCP_ERROR_CODES.UNAUTHORIZED;if(statusCode===403)return MCP_ERROR_CODES.FORBIDDEN;return statusCode<500?MCP_ERROR_CODES.INVALID_PARAMS:MCP_ERROR_CODES.INTERNAL_ERROR}function errorBehindFlowControl(err){if(!(err instanceof FlowControl))return err;const original=err.originalError;if(err.type==="fail"&&original!==void 0)return original;return new InternalMcpError(`Flow ended with: ${err.type}`)}function toReportedError(err){const failure=errorBehindFlowControl(err);return failure instanceof McpError2?failure:toMcpError(failure)}function remedyData(error){return isPublicError(error)&&error.remedy?{remedy:error.remedy}:{}}function toSdkMcpError(err){const error=toReportedError(err);if(error instanceof McpError2)return error;if(hasJsonRpcError(error)){const jsonRpc=error.toJsonRpcError();return new McpError2(jsonRpc.code,jsonRpc.message,{...jsonRpc.data,errorId:error.errorId,...remedyData(error)})}const data={errorId:error.errorId,code:error.code,...remedyData(error)};if(error.isPublic){return new McpError2(jsonRpcCodeForStatus(error.statusCode),error.getPublicMessage(),data)}const message=isProduction3()?error.getPublicMessage():error.message;return new McpError2(MCP_ERROR_CODES.INTERNAL_ERROR,message,data)}var init_mcp_error_utils=__esm({"libs/sdk/src/transport/mcp-handlers/mcp-error.utils.ts"(){"use strict";init_common();init_errors()}});import{CallToolResultSchema}from"@frontmcp/protocol";function toolCallErrorResult(error,options){const{errorHandler,toolName,logger}=options;if(error instanceof FlowControl){if(error.type==="respond"){const parsed=CallToolResultSchema.safeParse(error.output);if(parsed.success)return parsed.data;logger?.error("FlowControl.respond has invalid output",{tool:toolName,validationErrors:parsed.error.issues});return formatMcpErrorResponse(new InternalMcpError("FlowControl output is not a valid CallToolResult"))}const original=error.originalError;if(error.type==="fail"&&original!==void 0){return errorHandler.handle(original,{toolName})}logger?.warn(`FlowControl ended with type: ${error.type}`,{tool:toolName,type:error.type,output:error.output});return formatMcpErrorResponse(new InternalMcpError(`Flow ended with: ${error.type}`))}if(error instanceof InputRequiredSignal||error instanceof MissingClientCapabilityError){throw error}if(error instanceof TaskAugmentationNotSupportedError||error instanceof TaskAugmentationRequiredError||error instanceof ToolCredentialsRequiredError){throw toSdkMcpError(error)}return errorHandler.handle(error,{toolName})}var init_call_tool_error_utils=__esm({"libs/sdk/src/transport/mcp-handlers/call-tool-error.utils.ts"(){"use strict";init_common();init_errors();init_mcp_error_utils()}});import{CallToolRequestSchema}from"@frontmcp/protocol";function callToolRequestHandler({scope}){const logger=scope.logger.child("call-tool-request-handler");const errorHandler=new ErrorHandler({logger});return{requestSchema:CallToolRequestSchema,handler:async(request2,ctx)=>{const toolName=request2.params?.name||"unknown";logger.info(`tools/call: ${toolName}`);const start=Date.now();try{const taggedCtx=withMcpSurface(scope,ctx);const result=await scope.runFlowForOutput("tools:call-tool",{request:request2,ctx:taggedCtx});logger.verbose("tools/call completed",{tool:toolName,durationMs:Date.now()-start});return result}catch(e){return toolCallErrorResult(e,{errorHandler,toolName,logger})}}}}var init_call_tool_request_handler=__esm({"libs/sdk/src/transport/mcp-handlers/call-tool-request.handler.ts"(){"use strict";init_errors();init_call_tool_error_utils();init_mcp_surface()}});import{CompleteRequestSchema}from"@frontmcp/protocol";function completeRequestHandler({scope}){const logger=scope.logger.child("complete-request-handler");return{requestSchema:CompleteRequestSchema,handler:async(request2,ctx)=>{logger.verbose("completion/complete requested");const start=Date.now();try{const result=await scope.runFlowForOutput("completion:complete",{request:request2,ctx:withMcpSurface(scope,ctx)});logger.verbose("completion/complete completed",{durationMs:Date.now()-start});return result}catch(e){logger.error("completion/complete failed",{error:e instanceof Error?{name:e.name,message:e.message,stack:e.stack}:e});throw e}}}}var init_complete_request_handler=__esm({"libs/sdk/src/transport/mcp-handlers/complete-request.handler.ts"(){"use strict";init_mcp_surface()}});import{ListEventsRequestSchema}from"@frontmcp/protocol";function eventsListRequestHandler({scope}){const logger=scope.logger.child("events-list-request-handler");return{requestSchema:ListEventsRequestSchema,handler:async(request2,ctx)=>{logger.verbose("events/list requested");try{return await scope.runFlowForOutput("events:list",{request:request2,ctx:withMcpSurface(scope,ctx)})}catch(error){throw toSdkMcpError(error)}}}}var init_events_list_request_handler=__esm({"libs/sdk/src/transport/mcp-handlers/events-list-request.handler.ts"(){"use strict";init_mcp_error_utils();init_mcp_surface()}});import{PollEventsRequestSchema}from"@frontmcp/protocol";function eventsPollRequestHandler({scope}){const logger=scope.logger.child("events-poll-request-handler");return{requestSchema:PollEventsRequestSchema,handler:async(request2,ctx)=>{logger.verbose(`events/poll requested for "${request2.params.name}"`);try{return await scope.runFlowForOutput("events:poll",{request:request2,ctx:withMcpSurface(scope,ctx)})}catch(error){throw toSdkMcpError(error)}}}}var init_events_poll_request_handler=__esm({"libs/sdk/src/transport/mcp-handlers/events-poll-request.handler.ts"(){"use strict";init_mcp_error_utils();init_mcp_surface()}});import{MCP_20260728_META as MCP_20260728_META2,StreamEventsRequestSchema}from"@frontmcp/protocol";import{awaitOutsideRequest as awaitOutsideRequest2}from"@frontmcp/utils";function eventsStreamRequestHandler({scope}){const logger=scope.logger.child("events-stream-request-handler");return{requestSchema:StreamEventsRequestSchema,handler:async(request2,ctx)=>{logger.verbose(`events/stream requested for "${request2.params.name}"`);let opened;try{opened=await scope.runFlowForOutput("events:stream",{request:request2,ctx:withMcpSurface(scope,ctx),requestId:ctx.requestId,signal:ctx.signal})}catch(error){throw toSdkMcpError(error)}const notifications=opened.stream[Symbol.asyncIterator]();try{for(;;){const next=await awaitOutsideRequest2(notifications.next());if(next.done)break;await ctx.sendNotification(next.value)}}finally{opened.stream.close()}return{_meta:{[MCP_20260728_META2.subscriptionId]:ctx.requestId}}}}}var init_events_stream_request_handler=__esm({"libs/sdk/src/transport/mcp-handlers/events-stream-request.handler.ts"(){"use strict";init_mcp_error_utils();init_mcp_surface()}});import{SubscribeEventRequestSchema}from"@frontmcp/protocol";function eventsSubscribeRequestHandler({scope}){const logger=scope.logger.child("events-subscribe-request-handler");return{requestSchema:SubscribeEventRequestSchema,handler:async(request2,ctx)=>{logger.verbose(`events/subscribe requested for "${request2.params.name}"`);try{return await scope.runFlowForOutput("events:subscribe",{request:request2,ctx:withMcpSurface(scope,ctx)})}catch(error){throw toSdkMcpError(error)}}}}var init_events_subscribe_request_handler=__esm({"libs/sdk/src/transport/mcp-handlers/events-subscribe-request.handler.ts"(){"use strict";init_mcp_error_utils();init_mcp_surface()}});import{UnsubscribeEventRequestSchema}from"@frontmcp/protocol";function eventsUnsubscribeRequestHandler({scope}){const logger=scope.logger.child("events-unsubscribe-request-handler");return{requestSchema:UnsubscribeEventRequestSchema,handler:async(request2,ctx)=>{logger.verbose(`events/unsubscribe requested for "${request2.params.name}"`);try{return await scope.runFlowForOutput("events:unsubscribe",{request:request2,ctx:withMcpSurface(scope,ctx)})}catch(error){throw toSdkMcpError(error)}}}}var init_events_unsubscribe_request_handler=__esm({"libs/sdk/src/transport/mcp-handlers/events-unsubscribe-request.handler.ts"(){"use strict";init_mcp_error_utils();init_mcp_surface()}});import{GetPromptRequestSchema}from"@frontmcp/protocol";function getPromptRequestHandler({scope}){const logger=scope.logger.child("get-prompt-request-handler");const errorHandler=new ErrorHandler({logger});return{requestSchema:GetPromptRequestSchema,handler:async(request2,ctx)=>{const promptName=request2.params?.name||"unknown";logger.info(`prompts/get: ${promptName}`);const start=Date.now();try{const result=await scope.runFlowForOutput("prompts:get-prompt",{request:request2,ctx:withMcpSurface(scope,ctx)});logger.verbose("prompts/get completed",{prompt:promptName,durationMs:Date.now()-start});return result}catch(e){const cause=errorBehindFlowControl(e);if(isMrtrSignal(cause))throw cause;const failure=toReportedError(cause);errorHandler.logError(failure,{flowName:"prompts:get-prompt",prompt:promptName});throw toSdkMcpError(failure)}}}}var init_get_prompt_request_handler=__esm({"libs/sdk/src/transport/mcp-handlers/get-prompt-request.handler.ts"(){"use strict";init_errors();init_mcp_error_utils();init_mcp_surface()}});import{encryptJson,getTokenSignatureFingerprint,safeDecrypt,TinyTtlCache}from"@frontmcp/auth";import{getMachineId,randomUUID as randomUUID5}from"@frontmcp/utils";function hasValidSessionStructure(dec){if(typeof dec!=="object"||dec===null)return false;const d=dec;return typeof d["nodeId"]==="string"&&typeof d["authSig"]==="string"&&typeof d["uuid"]==="string"&&typeof d["iat"]==="number"}function isValidSessionPayload(dec,sig){return hasValidSessionStructure(dec)&&dec.authSig===sig}function isValidPublicSessionPayload(dec,expectedAuthSig="public"){if(typeof dec!=="object"||dec===null)return false;const d=dec;return typeof d["nodeId"]==="string"&&d["authSig"]===expectedAuthSig&&typeof d["uuid"]==="string"&&typeof d["iat"]==="number"&&d["isPublic"]===(expectedAuthSig==="public")}function decryptSessionId(sessionId,sig){const dec=safeDecrypt(sessionId);return isValidSessionPayload(dec,sig)?dec:null}function decryptPublicSession(sessionId,expectedAuthSig="public"){const cached=cache.get(sessionId);if(cached&&isValidPublicSessionPayload(cached,expectedAuthSig)){return cached}const dec=safeDecrypt(sessionId);if(isValidPublicSessionPayload(dec,expectedAuthSig)){cache.set(sessionId,dec);return dec}return null}function isDeploymentSessionId(sessionId){return cache.get(sessionId)!==void 0||hasValidSessionStructure(safeDecrypt(sessionId))}function nowSec(){return Math.floor(Date.now()/1e3)}function parseSessionHeader(sessionHeader,token){const currentAuthSig=getTokenSignatureFingerprint(token);if(sessionHeader){const cached=cache.get(sessionHeader);if(cached){if(cached.authSig===currentAuthSig){return{id:sessionHeader,payload:cached}}}const dec=decryptSessionId(sessionHeader,currentAuthSig);if(dec){cache.set(sessionHeader,dec);return{id:sessionHeader,payload:dec}}}return void 0}function createSessionId(protocol,token,options){const authSig=getTokenSignatureFingerprint(token);let platformType;if(options?.userAgent){platformType=detectPlatformFromUserAgent(options.userAgent,options.platformDetectionConfig);if(platformType==="unknown"){platformType=void 0}}const payload={nodeId:getMachineId(),authSig,uuid:randomUUID5(),iat:nowSec(),protocol,platformType,...options?.skillsOnlyMode&&{skillsOnlyMode:true}};const id=encryptJson(payload);cache.set(id,payload);return{id,payload}}function updateSessionPayload(sessionId,updates){let payload;const existing=cache.get(sessionId);if(existing){payload=existing}else{const decrypted=safeDecrypt(sessionId);if(hasValidSessionStructure(decrypted)||isValidPublicSessionPayload(decrypted)){payload=decrypted}}if(!payload)return null;Object.assign(payload,updates);const newSessionId=encryptJson(payload);cache.set(sessionId,payload);cache.set(newSessionId,payload);return newSessionId}var cache;var init_session_id_utils=__esm({"libs/sdk/src/auth/session/utils/session-id.utils.ts"(){"use strict";init_notification_service();cache=new TinyTtlCache(5e3)}});var init_notification=__esm({"libs/sdk/src/notification/index.ts"(){"use strict";init_notification_service()}});import{PROTOCOL_2026_07_28}from"@frontmcp/protocol";var FRONTMCP_SUPPORTED_PROTOCOL_VERSIONS,INITIALIZE_PROTOCOL_VERSIONS,LEGACY_PROTOCOL_VERSIONS,PROTOCOL_20260728_ONLY_METHODS,MCP_HEADERS,NAME_FROM_PARAMS_NAME,NAME_FROM_PARAMS_URI,DEFAULT_CACHE_TTL_MS,CACHEABLE_METHODS,ADVERTISED_EXTENSIONS;var init_protocol_20260728_constants=__esm({"libs/sdk/src/transport/mcp-20260728/protocol-20260728.constants.ts"(){"use strict";FRONTMCP_SUPPORTED_PROTOCOL_VERSIONS=[PROTOCOL_2026_07_28,"2025-11-25","2025-06-18","2025-03-26","2024-11-05"];INITIALIZE_PROTOCOL_VERSIONS=FRONTMCP_SUPPORTED_PROTOCOL_VERSIONS.filter(version=>version!==PROTOCOL_2026_07_28);LEGACY_PROTOCOL_VERSIONS=["2024-10-07","2024-11-05","2025-03-26","2025-06-18","2025-11-25"];PROTOCOL_20260728_ONLY_METHODS=["server/discover","subscriptions/listen"];MCP_HEADERS={protocolVersion:"mcp-protocol-version",method:"mcp-method",name:"mcp-name",paramPrefix:"mcp-param-"};NAME_FROM_PARAMS_NAME=["tools/call","prompts/get","events/subscribe","events/unsubscribe","events/poll","events/stream"];NAME_FROM_PARAMS_URI=["resources/read"];DEFAULT_CACHE_TTL_MS={"server/discover":3e5,"tools/list":6e4,"prompts/list":6e4,"resources/list":6e4,"resources/templates/list":6e4,"resources/read":0};CACHEABLE_METHODS=Object.keys(DEFAULT_CACHE_TTL_MS);ADVERTISED_EXTENSIONS={"io.modelcontextprotocol/tasks":{}}}});import{InitializeRequestSchema,LATEST_PROTOCOL_VERSION}from"@frontmcp/protocol";function persistInitPayload(sessionId,initPayload,ctx){updateSessionPayload(sessionId,initPayload);const transport=ctx.authInfo?.transport;transport?.setInitSessionPayload(initPayload)}function guardClientVersion(clientVersion){const parsed=new Date(clientVersion);if(isNaN(parsed.getTime())){throw UnsupportedClientVersionError.fromVersion(clientVersion)}}function initializeRequestHandler({serverOptions,scope,composeInstructions}){const logger=scope.logger.child("initialize-handler");return{requestSchema:InitializeRequestSchema,handler:async(request2,ctx)=>{logger.info("initialize: received request",{clientName:request2.params.clientInfo?.name,clientVersion:request2.params.clientInfo?.version,protocolVersion:request2.params.protocolVersion,hasCapabilities:!!request2.params.capabilities,sessionId:ctx.authInfo?.sessionId?.slice(0,20)});guardClientVersion(request2.params.protocolVersion);const sessionId=ctx.authInfo?.sessionId;let detectedPlatform=void 0;const clientSupportsElicitation=supportsElicitation(request2.params.capabilities?.elicitation?{elicitation:request2.params.capabilities.elicitation}:void 0);if(sessionId){const hasRegisteredServer=scope.notifications.getRegisteredServer(sessionId)!==void 0;if(request2.params.capabilities){const clientCapabilities={roots:request2.params.capabilities.roots,sampling:request2.params.capabilities.sampling,experimental:request2.params.capabilities.experimental,extensions:request2.params.capabilities.extensions,elicitation:request2.params.capabilities.elicitation};if(hasRegisteredServer)scope.notifications.setClientCapabilities(sessionId,clientCapabilities);await scope.transportService?.updateStoredSessionCapabilities(sessionId,clientCapabilities);detectedPlatform=detectPlatformFromCapabilities(clientCapabilities)}if(request2.params.clientInfo){const{name:clientName,version:clientVersion}=request2.params.clientInfo;if(hasRegisteredServer){scope.notifications.setClientInfo(sessionId,{name:clientName,version:clientVersion})}const finalPlatform=resolvePlatformType(request2.params.clientInfo,request2.params.capabilities,scope.metadata.transport?.platformDetection);if(ctx.authInfo?.sessionIdPayload){ctx.authInfo.sessionIdPayload.clientName=clientName;ctx.authInfo.sessionIdPayload.clientVersion=clientVersion;ctx.authInfo.sessionIdPayload.supportsElicitation=clientSupportsElicitation;if(finalPlatform){ctx.authInfo.sessionIdPayload.platformType=finalPlatform}persistInitPayload(sessionId,{clientName,clientVersion,supportsElicitation:clientSupportsElicitation,...finalPlatform&&{platformType:finalPlatform}},ctx)}}else if(ctx.authInfo?.sessionIdPayload){ctx.authInfo.sessionIdPayload.supportsElicitation=clientSupportsElicitation;if(detectedPlatform){ctx.authInfo.sessionIdPayload.platformType=detectedPlatform}persistInitPayload(sessionId,{supportsElicitation:clientSupportsElicitation,...detectedPlatform&&{platformType:detectedPlatform}},ctx)}}const declaresChannels=request2.params.capabilities?.experimental?.["claude/channel"]!==void 0;const registered=sessionId?scope.notifications.getRegisteredServer(sessionId):void 0;if(sessionId&&(declaresChannels||registered?.stdio)){if(scope.channels){const listed=await scope.runFlowForOutput("channels:list",{});const channelNames=listed.channels.map(ch=>ch.name);scope.notifications.subscribeAllChannels(sessionId,channelNames);logger.info(`initialize: auto-subscribed session to ${channelNames.length} channel(s)`,{channels:channelNames.join(", "),sessionId:sessionId.slice(0,20)})}}const requestedVersion=request2.params.protocolVersion;const protocolVersion=INITIALIZE_PROTOCOL_VERSIONS.includes(requestedVersion)?requestedVersion:LATEST_PROTOCOL_VERSION;const configuredInfo=scope.metadata?.info??{name:"FrontMcpServer",version:"0.0.1"};const composed=await composeInstructions?.(ctx,request2.params.clientInfo?.name);const instructions=composed!==void 0?composed:serverOptions.instructions;const result={capabilities:serverOptions.capabilities??{},instructions:instructions&&instructions.length>0?instructions:void 0,serverInfo:{...configuredInfo,title:configuredInfo.title??configuredInfo.name},protocolVersion};logger.info("initialize: sending response",{capabilities:JSON.stringify(result.capabilities),protocolVersion:result.protocolVersion,serverName:result.serverInfo.name,sessionId:ctx.authInfo?.sessionId?.slice(0,20)});return result}}}var init_initialize_request_handler=__esm({"libs/sdk/src/transport/mcp-handlers/initialize-request.handler.ts"(){"use strict";init_session_id_utils();init_errors();init_notification();init_protocol_20260728_constants()}});import{InitializedNotificationSchema}from"@frontmcp/protocol";function initializedNotificationHandler(options){return{requestSchema:InitializedNotificationSchema,handler:async(request2,ctx)=>{return{}}}}var init_Initialized_notification_hanlder=__esm({"libs/sdk/src/transport/mcp-handlers/Initialized-notification.hanlder.ts"(){"use strict"}});import{ListPromptsRequestSchema}from"@frontmcp/protocol";function listPromptsRequestHandler({scope}){const logger=scope.logger.child("list-prompts-request-handler");return{requestSchema:ListPromptsRequestSchema,handler:async(request2,ctx)=>{logger.verbose("prompts/list requested");const start=Date.now();try{const result=await scope.runFlowForOutput("prompts:list-prompts",{request:request2,ctx:withMcpSurface(scope,ctx)});logger.verbose("prompts/list completed",{durationMs:Date.now()-start});return result}catch(e){logger.error("prompts/list failed",{error:e instanceof Error?{name:e.name,message:e.message,stack:e.stack}:e});throw e}}}}var init_list_prompts_request_handler=__esm({"libs/sdk/src/transport/mcp-handlers/list-prompts-request.handler.ts"(){"use strict";init_mcp_surface()}});import{ListResourceTemplatesRequestSchema}from"@frontmcp/protocol";function listResourceTemplatesRequestHandler({scope}){const logger=scope.logger.child("list-resource-templates-request-handler");return{requestSchema:ListResourceTemplatesRequestSchema,handler:async(request2,ctx)=>{logger.verbose("resources/listTemplates requested");const start=Date.now();try{const result=await scope.runFlowForOutput("resources:list-resource-templates",{request:request2,ctx:withMcpSurface(scope,ctx)});logger.verbose("resources/listTemplates completed",{durationMs:Date.now()-start});return result}catch(e){logger.error("resources/listTemplates failed",{error:e instanceof Error?{name:e.name,message:e.message,stack:e.stack}:e});throw e}}}}var init_list_resource_templates_request_handler=__esm({"libs/sdk/src/transport/mcp-handlers/list-resource-templates-request.handler.ts"(){"use strict";init_mcp_surface()}});import{ListResourcesRequestSchema}from"@frontmcp/protocol";function listResourcesRequestHandler({scope}){const logger=scope.logger.child("list-resources-request-handler");return{requestSchema:ListResourcesRequestSchema,handler:async(request2,ctx)=>{logger.verbose("resources/list requested");const start=Date.now();try{const result=await scope.runFlowForOutput("resources:list-resources",{request:request2,ctx:withMcpSurface(scope,ctx)});logger.verbose("resources/list completed",{durationMs:Date.now()-start});return result}catch(e){logger.error("resources/list failed",{error:e instanceof Error?{name:e.name,message:e.message,stack:e.stack}:e});throw e}}}}var init_list_resources_request_handler=__esm({"libs/sdk/src/transport/mcp-handlers/list-resources-request.handler.ts"(){"use strict";init_mcp_surface()}});import{ListToolsRequestSchema}from"@frontmcp/protocol";function listToolsRequestHandler({scope}){const logger=scope.logger.child("list-tools-request-handler");return{requestSchema:ListToolsRequestSchema,handler:async(request2,ctx)=>{logger.verbose("tools/list requested");const start=Date.now();try{const result=await scope.runFlowForOutput("tools:list-tools",{request:request2,ctx:withMcpSurface(scope,ctx)});logger.verbose("tools/list completed",{durationMs:Date.now()-start});return result}catch(e){logger.error("tools/list failed",{error:e instanceof Error?{name:e.name,message:e.message,stack:e.stack}:e});throw e}}}}var init_list_tools_request_handler=__esm({"libs/sdk/src/transport/mcp-handlers/list-tools-request.handler.ts"(){"use strict";init_mcp_surface()}});import{SetLevelRequestSchema}from"@frontmcp/protocol";function LoggingSetLevelRequestHandler({scope}){return{requestSchema:SetLevelRequestSchema,handler:async(request2,ctx)=>{try{return await scope.runFlowForOutput("logging:set-level",{request:request2,ctx:withMcpSurface(scope,ctx)})}catch(error){throw toSdkMcpError(error)}}}}var init_logging_set_level_request_handler=__esm({"libs/sdk/src/transport/mcp-handlers/logging-set-level-request.handler.ts"(){"use strict";init_mcp_error_utils();init_mcp_surface()}});import{ReadResourceRequestSchema}from"@frontmcp/protocol";function readResourceRequestHandler({scope}){const logger=scope.logger.child("read-resource-request-handler");const errorHandler=new ErrorHandler({logger});return{requestSchema:ReadResourceRequestSchema,handler:async(request2,ctx)=>{const uri=request2.params?.uri||"unknown";logger.info(`resources/read: ${uri}`);const start=Date.now();try{const result=await scope.runFlowForOutput("resources:read-resource",{request:request2,ctx:withMcpSurface(scope,ctx)});logger.verbose("resources/read completed",{uri,durationMs:Date.now()-start});return result}catch(e){const cause=errorBehindFlowControl(e);if(isMrtrSignal(cause))throw cause;const failure=toReportedError(cause);errorHandler.logError(failure,{flowName:"resources:read-resource",uri});throw toSdkMcpError(failure)}}}}var init_read_resource_request_handler=__esm({"libs/sdk/src/transport/mcp-handlers/read-resource-request.handler.ts"(){"use strict";init_errors();init_mcp_error_utils();init_mcp_surface()}});import{RootsListChangedNotificationSchema}from"@frontmcp/protocol";function rootsListChangedNotificationHandler({scope}){return{requestSchema:RootsListChangedNotificationSchema,handler:async(request2,ctx)=>{const sessionId=ctx.authInfo?.sessionId;if(sessionId){scope.notifications.invalidateRootsCache(sessionId)}return{}}}}var init_roots_list_changed_notification_handler=__esm({"libs/sdk/src/transport/mcp-handlers/roots-list-changed-notification.handler.ts"(){"use strict"}});async function listAllMatching(registry,options){const skills=[];let limit=REGISTRY_PAGE_SIZE;for(;;){const page2=await registry.listSkills({...options,offset:skills.length,limit});skills.push(...page2.skills);if(!page2.hasMore||page2.skills.length===0||skills.length>=page2.total)return skills;limit=Math.max(REGISTRY_PAGE_SIZE,page2.total-skills.length)}}function skillsListRequestHandler({scope}){const logger=scope.logger.child("skills-list-request-handler");return{requestSchema:SkillsListRequestSchema,responseSchema:SkillsListResultSchema,handler:async(request2,ctx)=>{const params=request2.params??{};const{offset,limit,tags,sortBy,sortOrder,includeHidden}=params;logger.verbose(`skills/list: offset=${offset}, limit=${limit}`);const skillRegistry=scope.skills;if(!skillRegistry){throw new PublicMcpError("Skills capability not available","CAPABILITY_NOT_AVAILABLE",501)}try{await assertSkillCatalogLoaded(scope)}catch(error){throw toSdkMcpError(error)}const matching=await listAllMatching(skillRegistry,{tags,sortBy,sortOrder,includeHidden});const listedOverMcp=matching.filter(metadata=>metadata.visibility!=="http");const authInfo=ctx?.authInfo??{};const visible=await filterDiscoverableSkillResults(scope,skillRegistry,listedOverMcp.map(metadata=>({metadata})),{authInfo,ctx:withMcpSurface(scope,ctx)});const start=offset??0;const page2=visible.slice(start,start+(limit??DEFAULT_PAGE_SIZE));const skills=page2.map(({metadata:s})=>{const id=s.id??s.name;const bundleVersion=skillRegistry.bundleVersionOf?.(id);return{id,name:s.name,description:s.description??"",tags:s.tags,priority:s.priority,...bundleVersion!==void 0&&{bundleVersion}}});const result={skills,total:visible.length,hasMore:start+page2.length<visible.length};return SkillsListResultSchema.parse(result)}}}var DEFAULT_PAGE_SIZE,REGISTRY_PAGE_SIZE;var init_skills_list_request_handler=__esm({"libs/sdk/src/transport/mcp-handlers/skills-list-request.handler.ts"(){"use strict";init_errors();init_skill_catalog_source();init_skill_filter_helper();init_mcp_error_utils();init_mcp_surface();init_skills_mcp_types();DEFAULT_PAGE_SIZE=50;REGISTRY_PAGE_SIZE=100}});function skillsLoadRequestHandler({scope}){const logger=scope.logger.child("skills-load-request-handler");return{requestSchema:SkillsLoadRequestSchema,responseSchema:SkillsLoadResultSchema,handler:async(request2,ctx)=>{logger.verbose(`skills/load: [${request2.params.skillIds.join(", ")}]`);try{return await scope.runFlowForOutput("skills:load",{request:request2,ctx:withMcpSurface(scope,ctx)})}catch(error){throw toSdkMcpError(error)}}}}var init_skills_load_request_handler=__esm({"libs/sdk/src/transport/mcp-handlers/skills-load-request.handler.ts"(){"use strict";init_mcp_error_utils();init_mcp_surface();init_skills_mcp_types()}});function skillsSearchRequestHandler({scope}){const logger=scope.logger.child("skills-search-request-handler");return{requestSchema:SkillsSearchRequestSchema,responseSchema:SkillsSearchResultSchema,handler:async(request2,ctx)=>{logger.verbose(`skills/search: "${request2.params.query}"`);try{return await scope.runFlowForOutput("skills:search",{request:request2,ctx:withMcpSurface(scope,ctx)})}catch(error){throw toSdkMcpError(error)}}}}var init_skills_search_request_handler=__esm({"libs/sdk/src/transport/mcp-handlers/skills-search-request.handler.ts"(){"use strict";init_mcp_error_utils();init_mcp_surface();init_skills_mcp_types()}});import{SubscribeRequestSchema}from"@frontmcp/protocol";function SubscribeRequestHandler({scope}){return{requestSchema:SubscribeRequestSchema,handler:async(request2,ctx)=>{try{return await scope.runFlowForOutput("resources:subscribe",{request:request2,ctx:withMcpSurface(scope,ctx)})}catch(error){throw toSdkMcpError(error)}}}}var init_subscribe_request_handler=__esm({"libs/sdk/src/transport/mcp-handlers/subscribe-request.handler.ts"(){"use strict";init_mcp_error_utils();init_mcp_surface()}});import{CancelTaskRequestSchema}from"@frontmcp/protocol";function tasksCancelRequestHandler({scope}){const logger=scope.logger.child("tasks-cancel-request-handler");return{requestSchema:CancelTaskRequestSchema,handler:async(request2,ctx)=>{logger.info(`tasks/cancel: ${request2.params?.taskId}`);try{const result=await scope.runFlowForOutput("tasks:cancel",{request:request2,ctx});return result}catch(e){logger.error("tasks/cancel failed",{error:e instanceof Error?e.message:e});throw toSdkMcpError(e)}}}}var init_tasks_cancel_request_handler=__esm({"libs/sdk/src/transport/mcp-handlers/tasks-cancel-request.handler.ts"(){"use strict";init_mcp_error_utils()}});import{GetTaskRequestSchema}from"@frontmcp/protocol";function tasksGetRequestHandler({scope}){const logger=scope.logger.child("tasks-get-request-handler");return{requestSchema:GetTaskRequestSchema,handler:async(request2,ctx)=>{logger.verbose(`tasks/get: ${request2.params?.taskId}`);try{const result=await scope.runFlowForOutput("tasks:get",{request:request2,ctx});return result}catch(e){logger.error("tasks/get failed",{error:e instanceof Error?e.message:e});throw toSdkMcpError(e)}}}}var init_tasks_get_request_handler=__esm({"libs/sdk/src/transport/mcp-handlers/tasks-get-request.handler.ts"(){"use strict";init_mcp_error_utils()}});import{ListTasksRequestSchema}from"@frontmcp/protocol";function tasksListRequestHandler({scope}){const logger=scope.logger.child("tasks-list-request-handler");return{requestSchema:ListTasksRequestSchema,handler:async(request2,ctx)=>{logger.verbose("tasks/list");try{const result=await scope.runFlowForOutput("tasks:list",{request:request2,ctx});return result}catch(e){logger.error("tasks/list failed",{error:e instanceof Error?e.message:e});throw toSdkMcpError(e)}}}}var init_tasks_list_request_handler=__esm({"libs/sdk/src/transport/mcp-handlers/tasks-list-request.handler.ts"(){"use strict";init_mcp_error_utils()}});import{GetTaskPayloadRequestSchema}from"@frontmcp/protocol";function tasksResultRequestHandler({scope}){const logger=scope.logger.child("tasks-result-request-handler");return{requestSchema:GetTaskPayloadRequestSchema,handler:async(request2,ctx)=>{logger.verbose(`tasks/result: ${request2.params?.taskId}`);try{const result=await scope.runFlowForOutput("tasks:result",{request:request2,ctx});return result}catch(e){logger.error("tasks/result failed",{error:e instanceof Error?e.message:e});throw toSdkMcpError(e)}}}}var init_tasks_result_request_handler=__esm({"libs/sdk/src/transport/mcp-handlers/tasks-result-request.handler.ts"(){"use strict";init_mcp_error_utils()}});import{UnsubscribeRequestSchema}from"@frontmcp/protocol";function UnsubscribeRequestHandler({scope}){return{requestSchema:UnsubscribeRequestSchema,handler:async(request2,ctx)=>{try{return await scope.runFlowForOutput("resources:unsubscribe",{request:request2,ctx:withMcpSurface(scope,ctx)})}catch(error){throw toSdkMcpError(error)}}}}var init_unsubscribe_request_handler=__esm({"libs/sdk/src/transport/mcp-handlers/unsubscribe-request.handler.ts"(){"use strict";init_mcp_error_utils();init_mcp_surface()}});var mcp_handlers_exports={};__export(mcp_handlers_exports,{createMcpHandlers:()=>createMcpHandlers,methodOfSchema:()=>methodOfSchema,registerMcpHandler:()=>registerMcpHandler});function methodOfSchema(schema){const shape=schema?.shape;const method=shape?.["method"];if(typeof method?.value==="string")return method.value;const values=method?._def?.values;return Array.isArray(values)&&typeof values[0]==="string"?values[0]:void 0}function registerMcpHandler(server,schema,handle,notificationContext={}){if(!methodOfSchema(schema)?.startsWith("notifications/")){server.setRequestHandler(schema,handle);return}server.setNotificationHandler(schema,async notification=>{await handle(notification,notificationContext)})}function createMcpHandlers(options){const listHandlers=[listToolsRequestHandler(options),listResourcesRequestHandler(options),listResourceTemplatesRequestHandler(options),listPromptsRequestHandler(options)];const toolsHandler=options.serverOptions?.capabilities?.tools?[callToolRequestHandler(options)]:[];const resourcesHandler=options.serverOptions?.capabilities?.resources?[readResourceRequestHandler(options),SubscribeRequestHandler(options),UnsubscribeRequestHandler(options)]:[];const promptsHandler=options.serverOptions?.capabilities?.prompts?[getPromptRequestHandler(options)]:[];const hasPromptsOrResources=options.scope?.prompts?.hasAny()||options.scope?.resources?.hasAny();const completionHandler=hasPromptsOrResources&&options.serverOptions?.capabilities?.completions?[completeRequestHandler(options)]:[];const loggingHandler=options.serverOptions?.capabilities?.logging?[LoggingSetLevelRequestHandler(options)]:[];const skillRegistry=options.scope?.skills;const skillsHandler=skillRegistry?.servesSkills?.()??skillRegistry?.hasAny()?[skillsSearchRequestHandler(options),skillsLoadRequestHandler(options),skillsListRequestHandler(options)]:[];const eventsHandler=options.scope?.events?.servesEvents()?[eventsListRequestHandler(options)]:[];const eventPollHandler=options.scope?.events?.performs("poll")?[eventsPollRequestHandler(options)]:[];const eventStreamHandler=options.scope?.events?.performs("push")?[eventsStreamRequestHandler(options)]:[];const eventSubscriptionHandlers=options.scope?.events?.subscriptions?[eventsSubscribeRequestHandler(options),eventsUnsubscribeRequestHandler(options)]:[];const tasksHandler=options.serverOptions?.capabilities?.["tasks"]?[tasksGetRequestHandler(options),tasksResultRequestHandler(options),tasksCancelRequestHandler(options),tasksListRequestHandler(options)]:[];return[initializeRequestHandler(options),initializedNotificationHandler(options),rootsListChangedNotificationHandler(options),...listHandlers,...toolsHandler,...resourcesHandler,...promptsHandler,...completionHandler,...loggingHandler,...skillsHandler,...eventsHandler,...eventSubscriptionHandlers,...eventPollHandler,...eventStreamHandler,...tasksHandler]}var init_mcp_handlers=__esm({"libs/sdk/src/transport/mcp-handlers/index.ts"(){"use strict";init_call_tool_request_handler();init_complete_request_handler();init_events_list_request_handler();init_events_poll_request_handler();init_events_stream_request_handler();init_events_subscribe_request_handler();init_events_unsubscribe_request_handler();init_get_prompt_request_handler();init_initialize_request_handler();init_Initialized_notification_hanlder();init_list_prompts_request_handler();init_list_resource_templates_request_handler();init_list_resources_request_handler();init_list_tools_request_handler();init_logging_set_level_request_handler();init_read_resource_request_handler();init_roots_list_changed_notification_handler();init_skills_list_request_handler();init_skills_load_request_handler();init_skills_search_request_handler();init_subscribe_request_handler();init_tasks_cancel_request_handler();init_tasks_get_request_handler();init_tasks_list_request_handler();init_tasks_result_request_handler();init_unsubscribe_request_handler()}});var in_memory_server_exports={};__export(in_memory_server_exports,{createInMemoryServer:()=>createInMemoryServer});import{toJSONSchema}from"@frontmcp/lazy-zod";import{ElicitResultSchema,ErrorCode,InMemoryTransport,McpError as McpError3}from"@frontmcp/protocol";import{randomUUID as randomUUID6,runRequestExclusive as runRequestExclusive2}from"@frontmcp/utils";async function createInMemoryServer(scope,options){const{createMcpHandlers:createMcpHandlers2,registerMcpHandler:registerMcpHandler2}=await Promise.resolve().then(()=>(init_mcp_handlers(),mcp_handlers_exports));const sessionId=options?.sessionId??`in-memory:${randomUUID6()}`;const[clientTransport,serverTransport]=InMemoryTransport.createLinkedPair();let currentAuthInfo=options?.authInfo??{};const elicitTransport={type:"in-memory",sendElicitRequest:async(relatedRequestId,message,requestedSchema,elicitOptions)=>{const{elicitId,expiresAt,requestParams}=await scope.runFlowForOutput("elicitation:request",{relatedRequestId,sessionId,message,requestedSchema:toJSONSchema(requestedSchema),options:elicitOptions});const ttl=Math.max(expiresAt-Date.now(),0);let answer;try{answer=await mcpServer.request({method:"elicitation/create",params:{...requestParams,_meta:{[ELICITATION_META_KEY]:{elicitId,expiresAt}}}},ElicitResultSchema,{relatedRequestId,timeout:ttl})}catch(error){await scope.elicitationStore?.deletePending(sessionId);if(error instanceof McpError3&&error.code===ErrorCode.RequestTimeout){throw new ElicitationTimeoutError(elicitId,ttl)}throw error}const output=await scope.runFlow("elicitation:result",{sessionId,result:answer});return output?.result??{status:answer.action}}};const serverOptions=buildScopedServerOptions(scope);const mcpServer=createMcpServer(scope.metadata.info,serverOptions);const composeInstructions=(caller,clientName)=>composeCallerInstructions(scope,{ctx:caller,clientName,skillUriHints:true});const handlers=createMcpHandlers2({scope,serverOptions,composeInstructions});for(const handler of handlers){const originalHandler=handler.handler;const wrappedHandler=async(request2,ctx)=>{const enrichedCtx={...ctx,authInfo:{...currentAuthInfo,sessionId,transport:elicitTransport},...options?.workerEnv!==void 0?{platformEnv:options.workerEnv}:{},ownRequest:true};return runRequestExclusive2(()=>originalHandler(request2,enrichedCtx))};registerMcpHandler2(mcpServer,handler.requestSchema,wrappedHandler)}scope.notifications.registerServer(sessionId,mcpServer);scope.notifications.setCaller(sessionId,sessionCallerOf(currentAuthInfo));await mcpServer.connect(serverTransport);return{clientTransport,setAuthInfo:authInfo=>{currentAuthInfo=authInfo;scope.notifications.setCaller(sessionId,sessionCallerOf(authInfo))},close:async()=>{scope.notifications.unregisterServer(sessionId);await mcpServer.close()}}}var init_in_memory_server=__esm({"libs/sdk/src/transport/in-memory-server.ts"(){"use strict";init_elicitation_meta();init_errors();init_notification_service();init_skill_instructions_helper();init_build_scoped_server_options();init_mcp_server_factory()}});var direct_client_exports={};__export(direct_client_exports,{DirectClientImpl:()=>DirectClientImpl});import{ElicitRequestSchema,ResourceUpdatedNotificationSchema}from"@frontmcp/protocol";import{fileExists,pathResolve,randomUUID as randomUUID7}from"@frontmcp/utils";function toElicitationRequest(params){const{_meta,...question}=params;const sent=_meta?.[ELICITATION_META_KEY];const elicitId=sent?.elicitId??("elicitationId"in question?question.elicitationId:"");return{...question,elicitId,expiresAt:sent?.expiresAt??0}}function findFileFromRoot(root,relativePath,skillName){const fs=__require("fs");const path4=__require("path");const cleanRelative=relativePath.replace(/^\.\//,"");const searchDirs=["src","."];for(const srcDir of searchDirs){const srcRoot=path4.join(root,srcDir);if(!fs.existsSync(srcRoot))continue;const matches=[];walkForFile(srcRoot,cleanRelative,fs,path4,matches);if(matches.length===0)continue;if(matches.length===1)return matches[0];const namedAfterSkill=matches.filter(match=>path4.basename(match.baseDir)===skillName);return namedAfterSkill.length===1?namedAfterSkill[0]:void 0}return void 0}function walkForFile(dir,targetRelative,fs,path4,matches,maxDepth=10){const candidate=path4.join(dir,targetRelative);if(fs.existsSync(candidate)){matches.push({absolute:candidate,baseDir:dir})}if(maxDepth<=0)return;try{const entries=fs.readdirSync(dir,{withFileTypes:true});for(const entry of entries){if(entry.isDirectory()&&!entry.name.startsWith(".")&&entry.name!=="node_modules"&&entry.name!=="dist"){walkForFile(path4.join(dir,entry.name),targetRelative,fs,path4,matches,maxDepth-1)}}}catch{}}var DirectClientImpl;var init_direct_client=__esm({"libs/sdk/src/direct/direct-client.ts"(){"use strict";init_import_protocol_client();init_list_all_pages_utils();init_elicitation_meta();init_errors();init_event_client();init_skills_mcp_types();init_direct_events_transport();init_llm_platform();init_token_auth_info();DirectClientImpl=class _DirectClientImpl{mcpClient;sessionId;clientInfo;platform;serverInfo;capabilities;closeServer;elicitationHandler;resourceUpdateHandlers=new Set;notificationHandlers=new Set;scopeRef;releaseScope;events;constructor(mcpClient,sessionId,clientInfo,serverInfo,capabilities,eventsOptions){this.mcpClient=mcpClient;this.sessionId=sessionId;this.clientInfo=clientInfo;this.platform=detectPlatform(clientInfo);this.serverInfo=serverInfo;this.capabilities=capabilities;const transport=directEventsTransport(mcpClient,handler=>this.onNotification(handler));this.events=new EventsClient(transport,eventsOptions)}static async create(scope,options,releaseScope){const{createInMemoryServer:createInMemoryServer2}=await Promise.resolve().then(()=>(init_in_memory_server(),in_memory_server_exports));const sessionId=options?.session?.id??`direct:${randomUUID7()}`;const clientInfo=options?.clientInfo??{name:"mcp-client",version:"1.0.0"};const authInfo={};if(options?.authToken){authInfo["token"]=options.authToken}if(options?.session?.user){authInfo["user"]={iss:"direct",...options.session.user,sub:options.session.user?.sub??"direct"}}if(options?.session?.scopes){authInfo["scopes"]=options.session.scopes}if(options?.authToken){Object.assign(authInfo,await authInfoForToken(scope,options.authToken))}const{clientTransport,close}=await createInMemoryServer2(scope,{sessionId,authInfo:Object.keys(authInfo).length>0?authInfo:void 0,workerEnv:options?.workerEnv});try{const clientCapabilities={capabilities:{...options?.onElicitation&&{elicitation:{form:{},url:{}}},...options?.capabilities}};const{Client}=await loadProtocolClient();const mcpClient=new Client(clientInfo,clientCapabilities);await mcpClient.connect(clientTransport);const serverInfo=mcpClient.getServerVersion();const serverCapabilities=mcpClient.getServerCapabilities();if(!serverInfo){throw new PublicMcpError("Failed to get server info from MCP handshake","HANDSHAKE_FAILED",500)}if(!serverCapabilities){throw new PublicMcpError("Failed to get server capabilities from MCP handshake","HANDSHAKE_FAILED",500)}const client=new _DirectClientImpl(mcpClient,sessionId,clientInfo,serverInfo,serverCapabilities,options?.events);client.closeServer=close;client.scopeRef=scope;client.releaseScope=releaseScope;client.elicitationHandler=options?.onElicitation;await client.setupNotificationHandlers(mcpClient);return client}catch(error){await close();throw error}}async setupNotificationHandlers(mcpClient){try{if(typeof mcpClient.setNotificationHandler==="function"){mcpClient.setNotificationHandler(ResourceUpdatedNotificationSchema,notification=>{const uri=notification.params?.uri;if(uri){this.resourceUpdateHandlers.forEach(h2=>h2(uri))}this.notificationHandlers.forEach(h2=>h2({method:notification.method??"notifications/resources/updated",params:notification.params}))})}if(typeof mcpClient.setNotificationHandler==="function"){mcpClient.fallbackNotificationHandler=notification=>{this.notificationHandlers.forEach(h2=>h2(notification))}}if(typeof mcpClient.setRequestHandler==="function"){mcpClient.setRequestHandler(ElicitRequestSchema,async request2=>{const params=request2.params;if(params){return this.handleElicitationRequestInternal(toElicitationRequest(params))}return{action:"decline"}})}}catch{}}async handleElicitationRequestInternal(params){if(this.elicitationHandler){try{return await this.elicitationHandler(params)}catch{return{action:"decline"}}}return{action:"decline"}}async listTools(){const tools=await listAllPages("tools/list",async cursor=>{const result=await this.mcpClient.listTools(cursor?{cursor}:void 0);return{items:result.tools,nextCursor:result.nextCursor}});return formatToolsForPlatform(tools,this.platform)}async callTool(name59,args,options){const result=await this.mcpClient.callTool({name:name59,arguments:args??{}},void 0,options?.onProgress&&{onprogress:options.onProgress});if(result.isError&&this.platform!=="raw")throw new ToolCallError(name59,result);return formatResultForPlatform(result,this.platform)}async listResources(){const resources=await listAllPages("resources/list",async cursor=>{const result=await this.mcpClient.listResources(cursor?{cursor}:void 0);return{items:result.resources,nextCursor:result.nextCursor}});return{resources}}async readResource(uri){return this.mcpClient.readResource({uri})}async listResourceTemplates(){const resourceTemplates=await listAllPages("resources/templates/list",async cursor=>{const result=await this.mcpClient.listResourceTemplates(cursor?{cursor}:void 0);return{items:result.resourceTemplates,nextCursor:result.nextCursor}});return{resourceTemplates}}async listPrompts(){const prompts=await listAllPages("prompts/list",async cursor=>{const result=await this.mcpClient.listPrompts(cursor?{cursor}:void 0);return{items:result.prompts,nextCursor:result.nextCursor}});return{prompts}}async getPrompt(name59,args){return this.mcpClient.getPrompt({name:name59,arguments:args})}getSessionId(){return this.sessionId}getClientInfo(){return this.clientInfo}getServerInfo(){return this.serverInfo}getCapabilities(){return this.capabilities}getDetectedPlatform(){return this.platform}async close(){await this.events.close();try{await this.mcpClient.close()}finally{await this.closeServer?.();const releaseScope=this.releaseScope;this.releaseScope=void 0;try{await releaseScope?.()}catch{}}}async searchSkills(query,options){return this.mcpClient.request({method:"skills/search",params:{query,...options}},SkillsSearchResultSchema)}async loadSkills(skillIds,options){const result=await this.mcpClient.request({method:"skills/load",params:{skillIds,...options}},SkillsLoadResultSchema);return result}async listSkills(options){return this.mcpClient.request({method:"skills/list",params:options??{}},SkillsListResultSchema)}async listSep2640Skills(){let read;try{read=await this.mcpClient.readResource({uri:"skill://index.json"})}catch{return[]}const text=read.contents?.[0]?.text;if(typeof text!=="string")return[];let parsed;try{parsed=JSON.parse(text)}catch{console.warn("[DirectClient] skill://index.json was not valid JSON");return[]}if(!parsed||typeof parsed!=="object"||!Array.isArray(parsed.skills)){return[]}const doc=parsed;if(doc.$schema&&!doc.$schema.startsWith("https://schemas.agentskills.io/discovery/")){console.warn(`[DirectClient] skill://index.json $schema "${doc.$schema}" is not an agentskills.io discovery URI`)}const ALLOWED_TYPES=new Set(["skill-md","mcp-resource-template","archive"]);return doc.skills.filter(e=>{if(!e||typeof e!=="object")return false;const entry=e;if(typeof entry.type!=="string"||!ALLOWED_TYPES.has(entry.type))return false;if(typeof entry.url!=="string"||!entry.url.startsWith("skill://"))return false;if(entry.type==="skill-md"&&typeof entry.name!=="string"){return false}return true})}async readSkillTextUri(uri){if(!uri.startsWith("skill://")){throw new PublicMcpError(`readSkillTextUri: expected a skill:// URI, got "${uri}"`,"INVALID_PARAMS",400)}const read=await this.mcpClient.readResource({uri});const text=read.contents?.[0]?.text;if(typeof text!=="string"){throw new PublicMcpError(`readSkillTextUri: resource "${uri}" returned no text content; use readResource() for binary skill assets`,"INVALID_REQUEST",400)}return text}onElicitation(handler){this.elicitationHandler=handler;return()=>{this.elicitationHandler=void 0}}async submitElicitationResult(elicitId,response){return this.callTool("sendElicitationResult",{elicitId,...response})}async complete(options){return this.mcpClient.complete(options)}async subscribeResource(uri){await this.mcpClient.subscribeResource({uri})}async unsubscribeResource(uri){await this.mcpClient.unsubscribeResource({uri})}onResourceUpdated(handler){this.resourceUpdateHandlers.add(handler);return()=>{this.resourceUpdateHandlers.delete(handler)}}onNotification(handler){this.notificationHandlers.add(handler);return()=>{this.notificationHandlers.delete(handler)}}async setLogLevel(level){await this.mcpClient.setLoggingLevel(level)}async callToolAndParseJson(toolName,args){const result=await this.mcpClient.callTool({name:toolName,arguments:args});const textContent=result.content?.find(c=>c.type==="text");if(!textContent?.text){throw new PublicMcpError(`No text content from ${toolName}`,"EMPTY_RESPONSE",500)}return JSON.parse(textContent.text)}async listJobs(options){return this.callToolAndParseJson("list_jobs",{...options})}async executeJob(name59,input,options){return this.callToolAndParseJson("execute_job",{name:name59,input:input??{},background:options?.background??false})}async getJobStatus(runId){return this.callToolAndParseJson("get_job_status",{runId})}async listWorkflows(options){return this.callToolAndParseJson("list_workflows",{...options})}async executeWorkflow(name59,input,options){return this.callToolAndParseJson("execute_workflow",{name:name59,input:input??{},background:options?.background??false})}async getWorkflowStatus(runId){return this.callToolAndParseJson("get_workflow_status",{runId})}async collectSkillAssets(){const scope=this.scopeRef;if(!scope?.skills)return{entries:[]};const skills=scope.skills.getSkills({includeHidden:true});const entries=[];for(const skill of skills){const baseDir=skill.getBaseDir?.();const meta=skill.metadata;const entry={skillName:meta.name,baseDir,description:meta.description,tags:meta.tags,license:meta.license};if(meta.instructions&&typeof meta.instructions==="object"&&"file"in meta.instructions){const filePath=meta.instructions.file;const resolved=filePath.startsWith("/")?filePath:baseDir?pathResolve(baseDir,filePath):void 0;if(resolved&&await fileExists(resolved)){entry.instructionFile=resolved}else if(!filePath.startsWith("/")){const fromCwd=findFileFromRoot(process.cwd(),filePath,meta.name);if(fromCwd){entry.instructionFile=fromCwd.absolute;entry.baseDir=fromCwd.baseDir}}}else if(meta.instructions){try{entry.instructionContent=await skill.loadInstructions()}catch{}}if(typeof meta.instructions==="string"){const loaded=await scope.skills.loadSkill(meta.id??meta.name).catch(()=>void 0);if(loaded?.skill.bundleVersion!==void 0)entry.bundleVersion=loaded.skill.bundleVersion}const resources=skill.getResources?.();if(resources){entry.resources={};for(const key of["references","examples","scripts","assets"]){const p=resources[key];if(p){const base=entry.baseDir||baseDir;const resolved=p.startsWith("/")?p:base?pathResolve(base,p):void 0;if(resolved&&await fileExists(resolved)){entry.resources[key]=resolved}}}}entries.push(entry)}return{entries}}}}});import"reflect-metadata";function instanceCacheOf(mode){let cache2=instanceCaches.get(mode);if(!cache2){cache2=new WeakMap;instanceCaches.set(mode,cache2)}return cache2}function getInstance(config,mode="full"){let resolvedConfig=config;if(typeof config==="function"){const stored=getDecoratorConfig(config);if(stored){resolvedConfig=stored}}const cacheKey=resolvedConfig;const instanceCache2=instanceCacheOf(mode);let instancePromise=instanceCache2.get(cacheKey);if(!instancePromise){instancePromise=(async()=>{try{const{FrontMcpInstance:FrontMcpInstance2}=await Promise.resolve().then(()=>(init_front_mcp(),front_mcp_exports));if(mode==="cli")return await FrontMcpInstance2.createForCli(resolvedConfig);if(mode==="manifest")return await FrontMcpInstance2.createForManifest(resolvedConfig);return await FrontMcpInstance2.createForConnect(resolvedConfig)}catch(error){instanceCache2.delete(cacheKey);throw error}})();instanceCache2.set(cacheKey,instancePromise)}return{cacheKey,instancePromise}}function joinInstance(config,mode="full"){const{cacheKey,instancePromise}=getInstance(config,mode);const instanceCache2=instanceCacheOf(mode);instanceClients.set(instancePromise,(instanceClients.get(instancePromise)??0)+1);const release=async()=>{const remaining=(instanceClients.get(instancePromise)??1)-1;instanceClients.set(instancePromise,remaining);if(remaining>0)return;if(instanceCache2.get(cacheKey)===instancePromise)instanceCache2.delete(cacheKey);const instance=await instancePromise;await Promise.all(instance.getScopes().map(scope=>scope.dispose()))};return{instancePromise,release}}async function endpointScope(instance,app){if(app!==void 0)return instance.getAppScope(app);const scope=instance.getPrimaryScope();if(!scope){const{PublicMcpError:PublicMcpError2}=await Promise.resolve().then(()=>(init_errors(),errors_exports));throw new PublicMcpError2("No scopes initialized. Ensure at least one app is configured.","NO_SCOPES",500)}return scope}async function connect(config,options){const{DirectClientImpl:DirectClientImpl2}=await Promise.resolve().then(()=>(init_direct_client(),direct_client_exports));const{instancePromise,release}=joinInstance(config,options?.mode);try{const instance=await instancePromise;const scope=await endpointScope(instance,options?.app);if(options?.mode!=="manifest")await instance.emitProvidersReady();return await DirectClientImpl2.create(scope,options,release)}catch(error){await release().catch(()=>void 0);throw error}}async function connectOpenAI(config,options){return connect(config,{clientInfo:PLATFORM_CLIENT_INFO.openai,...options})}async function connectClaude(config,options){return connect(config,{clientInfo:PLATFORM_CLIENT_INFO.claude,...options})}async function connectLangChain(config,options){return connect(config,{clientInfo:PLATFORM_CLIENT_INFO.langchain,...options})}async function connectVercelAI(config,options){return connect(config,{clientInfo:PLATFORM_CLIENT_INFO["vercel-ai"],...options})}var instanceCaches,instanceClients;var init_connect=__esm({"libs/sdk/src/direct/connect.ts"(){"use strict";init_common();init_llm_platform();instanceCaches=new Map;instanceClients=new WeakMap}});var DEFAULT_ELICIT_TTL,DEFAULT_FALLBACK_WAIT_TTL;var init_elicitation_types=__esm({"libs/sdk/src/elicitation/elicitation.types.ts"(){"use strict";DEFAULT_ELICIT_TTL=3e5;DEFAULT_FALLBACK_WAIT_TTL=3e5}});function workflowTriggerOf(authInfo){const trigger=asRecord(authInfo?.["extra"])?.["workflowTrigger"];return trigger instanceof WorkflowTriggerPrincipal?trigger:void 0}function toStringArray(value){if(Array.isArray(value))return value.filter(v=>typeof v==="string");if(typeof value==="string"&&value.length>0)return value.split(" ").filter(Boolean);return[]}function asRecord(value){return value&&typeof value==="object"?value:void 0}function firstPresent(sources3,convert){for(const source of sources3){if(source!==void 0&&source!==null)return convert(source)}return[]}function resolvePrincipal(authInfo,contextBuilder){const trigger=workflowTriggerOf(authInfo);if(trigger)return{sub:"",roles:[trigger.role],permissions:[],scopes:[],claims:{}};const info=authInfo??{};const user=asRecord(info["user"])??{};const extraAuthorization=asRecord(asRecord(info["extra"])?.["authorization"]);const authInfoClaims=asRecord(info["claims"])??{};const authorizationClaims=asRecord(extraAuthorization?.["claims"])??{};const claims3={...authorizationClaims,...authInfoClaims,...user};const scopes=toStringArray(info["scopes"]).length?toStringArray(info["scopes"]):firstPresent([extraAuthorization?.["scopes"],claims3["scope"],claims3["scopes"]],toStringArray);if(contextBuilder){const ctx=contextBuilder.build(info);return{sub:ctx.user.sub??"",roles:ctx.user.roles,permissions:ctx.user.permissions,scopes,claims:ctx.user.claims}}const roles=firstPresent([user["roles"],claims3["roles"],extraAuthorization?.["scopes"]],toStringArray);const permissions=firstPresent([user["permissions"],claims3["permissions"]],toStringArray);return{sub:typeof user["sub"]==="string"?user["sub"]:"",roles,permissions,scopes,claims:claims3}}var WorkflowTriggerPrincipal;var init_principal_utils=__esm({"libs/sdk/src/common/utils/principal.utils.ts"(){"use strict";WorkflowTriggerPrincipal=class{constructor(kind,name59){this.kind=kind;this.name=name59}kind;name;get role(){return`${this.kind}:${this.name}`}toAuthInfo(){return{extra:{workflowTrigger:this}}}}}});import{isAnonymousSubject as isAnonymousSubject3}from"@frontmcp/auth";function createErrorResult(message){return{content:[{type:"text",text:message}],isError:true}}function resolveElicitationOwner(requestContext){const authInfo=requestContext?.authInfo;const session=[authInfo?.sessionId,authInfo?.extra?.["sessionId"]].find(candidate=>typeof candidate==="string"&&candidate.length>0&&candidate!==STATELESS_SESSION_ID);if(session!==void 0){return`session:${session}`}const principal=authInfo?.clientId;return isAnonymousSubject3(principal)?void 0:`principal:${principal}`}function canDeliverNotifications(scope,sessionId){const capabilities=scope.notifications.getClientCapabilities(sessionId);if(!capabilities)return false;return Object.values(capabilities).some(v=>v!==void 0)}function sendFallbackNotification(deps,error){const{scope,sessionId,logger}=deps;const notificationData={type:"elicitation_fallback",elicitId:error.elicitId,message:error.elicitMessage,schema:error.schema,instructions:`Call sendElicitationResult tool with elicitId: "${error.elicitId}"`};scope.notifications.sendNotificationToSession(sessionId,"notifications/message",{level:"info",data:notificationData,logger:"elicitation"});logger.verbose("sendFallbackNotification: sent notification",{elicitId:error.elicitId,sessionId:sessionId.slice(0,20)})}async function handleWaitingFallback(deps,error){const{scope,sessionId,logger}=deps;logger.info("handleWaitingFallback: starting waiting fallback",{elicitId:error.elicitId,toolName:error.toolName});sendFallbackNotification(deps,error);return new Promise((resolve4,reject)=>{let resolved=false;let unsubscribeFn=null;const ttl=error.ttl||DEFAULT_FALLBACK_WAIT_TTL;const safeUnsubscribe=()=>{if(unsubscribeFn){unsubscribeFn().catch(()=>{});unsubscribeFn=null}};const timeoutHandle=setTimeout(()=>{if(!resolved){resolved=true;safeUnsubscribe();logger.warn("handleWaitingFallback: timeout waiting for result",{elicitId:error.elicitId,ttl});resolve4(createErrorResult(`Elicitation request timed out after ${Math.round(ttl/1e3)} seconds. The user did not respond in time.`))}},ttl);const store=scope.elicitationStore;if(!store){resolved=true;clearTimeout(timeoutHandle);reject(new ElicitationStoreNotInitializedError);return}store.subscribeFallbackResult(error.elicitId,result=>{if(!resolved){resolved=true;clearTimeout(timeoutHandle);safeUnsubscribe();logger.info("handleWaitingFallback: received result via pub/sub",{elicitId:error.elicitId,success:result.success});if(result.success&&result.result!==void 0){resolve4(result.result)}else{resolve4(createErrorResult(result.error||"Elicitation fallback execution failed"))}}},sessionId).then(unsubscribe=>{if(resolved){unsubscribe().catch(()=>{})}else{unsubscribeFn=unsubscribe}}).catch(err=>{if(!resolved){resolved=true;clearTimeout(timeoutHandle);logger.error("handleWaitingFallback: failed to subscribe",err);reject(new ElicitationSubscriptionError(error.elicitId,err instanceof Error?err:void 0))}})})}var init_fallback_helper=__esm({"libs/sdk/src/elicitation/helpers/fallback.helper.ts"(){"use strict";init_errors();init_transport_types();init_elicitation_types()}});import{isAnonymousSubject as isAnonymousSubject4}from"@frontmcp/auth";function principalKeyOf(authInfo){const{sub,claims:claims3}=resolvePrincipal(authInfo);if(isAnonymousSubject4(sub))return void 0;const issuer=typeof claims3["iss"]==="string"?claims3["iss"]:"";return issuer?`principal:${issuer}#${sub}`:`principal:${sub}`}function questionSubjectOf(authInfo){const principalKey=principalKeyOf(authInfo);if(principalKey)return principalKey;const owner=resolveElicitationOwner({authInfo});return owner?.startsWith("session:")?owner:void 0}var init_question_subject=__esm({"libs/sdk/src/elicitation/questions/question-subject.ts"(){"use strict";init_principal_utils();init_fallback_helper()}});var QuestionPendingError,QuestionSupersededError,QuestionNotFoundError,QuestionAlreadyAnsweredError,QuestionStoreBusyError,InvalidQuestionStoreError;var init_question_errors=__esm({"libs/sdk/src/elicitation/questions/question.errors.ts"(){"use strict";init_mcp_error();QuestionPendingError=class extends PublicMcpError{key;expiresAt;constructor(key,expiresAt){super(`The question "${key}" has no answer yet. It waits in the inbox until ${new Date(expiresAt).toISOString()}; call again to get its answer.`,"QUESTION_PENDING",408);this.key=key;this.expiresAt=expiresAt}};QuestionSupersededError=class extends PublicMcpError{key;constructor(key){super(`A newer call asked the question "${key}" and waits for its answer instead.`,"QUESTION_SUPERSEDED",409);this.key=key}};QuestionNotFoundError=class extends PublicMcpError{mcpErrorCode=MCP_ERROR_CODES.RESOURCE_NOT_FOUND;constructor(){super("No such question.","QUESTION_NOT_FOUND",404)}};QuestionAlreadyAnsweredError=class extends PublicMcpError{constructor(){super("This question was answered already.","QUESTION_ALREADY_ANSWERED",409)}};QuestionStoreBusyError=class extends InternalMcpError{constructor(){super("The question changed under every attempt to update it; try again.","QUESTION_STORE_BUSY")}};InvalidQuestionStoreError=class extends InternalMcpError{constructor(reason){super(`elicitation.persistent: ${reason}`,"INVALID_QUESTION_STORE")}}}});var ask_question_exports={};__export(ask_question_exports,{askPersistentQuestion:()=>askPersistentQuestion,elicitPersistent:()=>elicitPersistent});import{toJSONSchema as toJSONSchema2,internalZ as z57}from"@frontmcp/lazy-zod";import{randomUUID as randomUUID8}from"@frontmcp/utils";async function delivered(answer,schema){if(answer.status!=="accept")return{status:answer.status};const parsed=await schema.safeParseAsync(answer.content);if(!parsed.success){throw new InvalidInputError("The answer does not match the requested schema",parsed.error.issues)}return{status:"accept",content:parsed.data}}async function askPersistentQuestion(deps,message,schema,options){const{store,subject,signal}=deps;const request2={subject,key:options.key,message,requestedSchema:toJSONSchema2(schema),ttlMs:options.ttlMs,waiter:`call-${randomUUID8()}`};const handOver=async taken=>{const putBack=async()=>{await store.restore(request2,taken.answer,taken.expiresAt).catch(()=>void 0);return new QuestionPendingError(options.key,taken.expiresAt)};if(signal?.aborted)throw await putBack();const result=await delivered(taken.answer,schema);if(signal?.aborted)throw await putBack();return result};const asked=await store.ask(request2);if(asked.kind==="answered")return handOver(asked);const{expiresAt}=asked.question;const answer=await new Promise((resolve4,reject)=>{let settled=false;let queued=false;let chain=Promise.resolve();const finish=settle=>{if(settled)return;settled=true;clearTimeout(timer);clearInterval(poll);stop();signal?.removeEventListener("abort",onAbort);settle()};const pending=()=>finish(()=>reject(new QuestionPendingError(options.key,expiresAt)));const handle=outcome=>{if(outcome.kind==="answered"){if(settled||signal?.aborted){pending();void store.restore(request2,outcome.answer,outcome.expiresAt).catch(()=>void 0);return}finish(()=>resolve4(outcome))}else if(outcome.kind==="superseded"){finish(()=>reject(new QuestionSupersededError(options.key)))}};const serialized=task=>{chain=chain.then(task).catch(error=>finish(()=>reject(error)))};const take=()=>store.take(subject,options.key,request2.waiter);const check=()=>{if(settled||queued)return;queued=true;serialized(async()=>{queued=false;if(!settled)handle(await take())})};const giveUp=()=>serialized(async()=>{if(settled)return;const outcome=await take();handle(outcome);if(outcome.kind==="waiting")pending()});const onAbort=()=>pending();const timer=setTimeout(giveUp,options.waitMs);const poll=setInterval(check,RECHECK_MS);const stop=store.subscribeToQuestion(subject,options.key,check);if(signal?.aborted)return onAbort();signal?.addEventListener("abort",onAbort,{once:true});check()});return handOver(answer)}async function elicitPersistent(deps,message,requestedSchema,options){const{persist}=options;if(typeof persist.key!=="string"||persist.key.length===0||persist.key.length>MAX_QUESTION_KEY_LENGTH){throw new InvalidInputError(`persist.key must be a string of 1 to ${MAX_QUESTION_KEY_LENGTH} characters`)}if(options.mode==="url")throw new InvalidInputError('a persistent question is a form: drop mode "url"');const waitMs=options.ttl??DEFAULT_ELICIT_TTL;const{questions}=deps;if(!questions){throw new ElicitationNotSupportedError("Persistent questions are off: enable them with @FrontMcp({ elicitation: { enabled: true, persistent: true } })")}const ttlMs=persist.ttlMs??questions.ttlMs;if(!Number.isInteger(ttlMs)||ttlMs<=waitMs){throw new InvalidInputError(`persist.ttlMs (${ttlMs}) must be a whole number longer than ttl (${waitMs}), the wait`)}const subject=questionSubjectOf(deps.tryGetContext()?.authInfo);if(!subject){throw new ElicitationNotSupportedError("A persistent question is kept for a signed-in user or a session, and this anonymous caller has neither")}const zodSchema=requestedSchema instanceof z57.ZodType?requestedSchema:z57.object(requestedSchema);return askPersistentQuestion({store:questions.store,subject,signal:deps.signal},message,zodSchema,{key:persist.key,ttlMs,waitMs})}var RECHECK_MS,MAX_QUESTION_KEY_LENGTH;var init_ask_question=__esm({"libs/sdk/src/elicitation/questions/ask-question.ts"(){"use strict";init_errors();init_elicitation_types();init_question_subject();init_question_errors();RECHECK_MS=5e3;MAX_QUESTION_KEY_LENGTH=256}});import{toJSONSchema as toJSONSchema3,internalZ as z58}from"@frontmcp/lazy-zod";import{awaitOutsideRequest as awaitOutsideRequest3,randomUUID as randomUUID9}from"@frontmcp/utils";async function performElicit(deps,message,requestedSchema,options){const{sessionId,getClientCapabilities,tryGetContext,entryName,entryInput,elicitationEnabled}=deps;if(elicitationEnabled!==true){throw new ElicitationDisabledError}if(options?.persist){const{elicitPersistent:elicitPersistent2}=await Promise.resolve().then(()=>(init_ask_question(),ask_question_exports));return elicitPersistent2(deps,message,requestedSchema,{...options,persist:options.persist})}if(options?.mode==="url"&&!options.url){throw new InvalidInputError('url is required when mode is "url"')}const elicitOptions=options?.mode==="url"?{...options,elicitationId:options.elicitationId||generateElicitationId()}:options;const ctx=tryGetContext();const mrtr=ctx?.getMrtrExchange?.();if(mrtr&&mrtr.clientDeclaredRevision===false&&mrtr.supportsElicitation?.(options?.mode??"form")!==true){throw new ElicitationNotSupportedError("This client does not support elicitation: it declared no elicitation capability, and without a session the elicitation fallback has no one to answer it")}if(mrtr){const zodSchema=requestedSchema instanceof z58.ZodType?requestedSchema:z58.object(requestedSchema);const answer=mrtr.resolveElicitation({message,requestedSchema:toJSONSchema3(zodSchema),...elicitOptions?.mode?{mode:elicitOptions.mode}:{},...elicitOptions?.url?{url:elicitOptions.url}:{},...elicitOptions?.elicitationId?{elicitationId:elicitOptions.elicitationId}:{}},deps.inputKey);return checkedElicitAnswer(answer,requestedSchema,elicitOptions)}if(!sessionId){throw new ElicitationNotSupportedError("No session available for elicitation")}const preResolved=ctx?.getPreResolvedElicitResult?.();if(preResolved){ctx?.clearPreResolvedElicitResult?.();return checkedElicitAnswer(preResolved,requestedSchema,elicitOptions)}const capabilities=getClientCapabilities(sessionId);const mode=options?.mode??"form";if(!supportsElicitation(capabilities,mode)){const elicitId=elicitOptions?.elicitationId||generateElicitationId();const ttl=elicitOptions?.ttl??DEFAULT_ELICIT_TTL;const zodSchema=requestedSchema instanceof z58.ZodType?requestedSchema:z58.object(requestedSchema);const jsonSchema=toJSONSchema3(zodSchema);throw new ElicitationFallbackRequired(elicitId,message,jsonSchema,entryName,entryInput,ttl)}const transport=ctx?.transport;if(!transport){throw new ElicitationNotSupportedError("Transport not available for elicitation")}return awaitOutsideRequest3(transport.elicit(message,requestedSchema,elicitOptions))}function generateElicitationId(){return`elicit-${randomUUID9()}`}var init_elicit_helper=__esm({"libs/sdk/src/elicitation/helpers/elicit.helper.ts"(){"use strict";init_errors();init_notification();init_elicitation_types();init_checked_elicit_answer()}});function performSample(ctx,options){const mrtr=ctx?.getMrtrExchange?.();if(!mrtr)throw new SamplingNotAvailableError;return mrtr.resolveSampling({messages:options.messages,maxTokens:options.maxTokens,...options.systemPrompt===void 0?{}:{systemPrompt:options.systemPrompt},...options.modelPreferences===void 0?{}:{modelPreferences:options.modelPreferences},...options.temperature===void 0?{}:{temperature:options.temperature},...options.stopSequences===void 0?{}:{stopSequences:options.stopSequences},...options.includeContext===void 0?{}:{includeContext:options.includeContext},...options.metadata===void 0?{}:{metadata:options.metadata}})}function performListRoots(ctx){const mrtr=ctx?.getMrtrExchange?.();if(!mrtr)throw new SamplingNotAvailableError("roots/list");return mrtr.resolveRoots().roots}var init_mrtr_request_helper=__esm({"libs/sdk/src/elicitation/helpers/mrtr-request.helper.ts"(){"use strict";init_errors()}});var ELICITATION_FALLBACK_JSON_SCHEMA;var init_elicitation_fallback_schema=__esm({"libs/sdk/src/elicitation/elicitation-fallback.schema.ts"(){"use strict";ELICITATION_FALLBACK_JSON_SCHEMA={type:"object",properties:{elicitationPending:{type:"object",description:"Indicates this tool requires user input before it can complete",properties:{elicitId:{type:"string",description:"Unique identifier for this elicitation request. Pass to sendElicitationResult."},message:{type:"string",description:"Question or prompt to display to the user"},instructions:{type:"string",description:"Instructions for the LLM on how to handle the elicitation request"},schema:{type:"object",description:"JSON Schema describing the expected user response format"}},required:["elicitId","message"]}},required:["elicitationPending"],description:"Elicitation fallback response - tool requires user input to continue"}}});function extendOutputSchemaForElicitation(originalSchema){if(!originalSchema){return{type:"object",anyOf:[{type:"object",additionalProperties:true},ELICITATION_FALLBACK_JSON_SCHEMA]}}if(Array.isArray(originalSchema["oneOf"])){const existingOneOf=originalSchema["oneOf"];const hasElicitationFallback=existingOneOf.some(schema=>schema["properties"]&&typeof schema["properties"]==="object"&&"elicitationPending"in schema["properties"]);if(hasElicitationFallback){return{type:"object",...originalSchema}}return{type:"object",...originalSchema,oneOf:[...existingOneOf,ELICITATION_FALLBACK_JSON_SCHEMA]}}const{$defs:definitions,...wrappedSchema}=originalSchema;return{type:"object",oneOf:[wrappedSchema,ELICITATION_FALLBACK_JSON_SCHEMA],...definitions!==void 0&&{$defs:definitions}}}var init_extend_output_schema=__esm({"libs/sdk/src/elicitation/helpers/extend-output-schema.ts"(){"use strict";init_elicitation_fallback_schema()}});import{internalZ as z59}from"@frontmcp/lazy-zod";function validateElicitationContent(content,jsonSchema){try{const zodSchema=z59.fromJSONSchema(jsonSchema,{defaultTarget:"draft-2020-12"});const parseResult=zodSchema.safeParse(content);if(parseResult.success){return{success:true}}const errors=parseResult.error.issues.map(issue=>({path:issue.path.map(String),message:issue.message}));return{success:false,errors}}catch(err){return{success:false,errors:[{path:[],message:`Schema validation error: ${err instanceof Error?err.message:String(err)}`}]}}}var init_validate_elicitation_content=__esm({"libs/sdk/src/elicitation/helpers/validate-elicitation-content.ts"(){"use strict"}});var init_helpers=__esm({"libs/sdk/src/elicitation/helpers/index.ts"(){"use strict";init_elicit_helper();init_mrtr_request_helper();init_extend_output_schema();init_validate_elicitation_content();init_fallback_helper()}});function entryClassHooksJoin(join2){contextStageByFlow.set(join2.flow,join2.contextStage);return join2}function entryContextStageOf(flow){return contextStageByFlow.get(flow)}function stagesInOrder(plan58){return[...plan58.pre??[],...plan58.execute??[],...plan58.post??[],...plan58.finalize??[],...plan58.error??[]]}function describeUnreachableEntryClassHooks(hooks,join2,listFlows){const stages=stagesInOrder(join2.plan);const contextIndex=stages.indexOf(join2.contextStage);const problems=[];for(const{metadata}of hooks){const kind=metadata.static?"static ":"";const label=`${kind}${metadata.method}() (${metadata.type} '${String(metadata.stage)}' of ${metadata.flow})`;if(listFlows.includes(metadata.flow)){problems.push(`${label}: list flows build no entry instance and resolve no single entry to run it for`);continue}if(metadata.flow!==join2.flow||metadata.static)continue;const index=stages.indexOf(String(metadata.stage));const tooEarly=index!==-1&&(index<contextIndex||index===contextIndex&&(metadata.type==="will"||metadata.type==="around"));if(tooEarly){problems.push(`${label}: runs before '${join2.contextStage}' builds the instance it runs on; declare it as a static method to run it without an instance`)}}return problems}function unreachableHooksMessage(kind,className,problems){return`${kind} "${className}" declares hooks that would never run: ${problems.join("; ")}. Hooks declared as instance methods on a ${kind.toLowerCase()} class run on the instance built for each call; static methods run without one, from the first stage of a call. Declare hooks for list flows on a provider or a plugin instead.`}var contextStageByFlow;var init_entry_class_hooks=__esm({"libs/sdk/src/hooks/entry-class-hooks.ts"(){"use strict";contextStageByFlow=new Map}});function isTC39MethodContext(arg){return typeof arg==="object"&&arg!==null&&"kind"in arg&&arg.kind==="method"}var PendingMetadataRegistry;var init_decorator_utils=__esm({"libs/sdk/src/common/decorators/decorator-utils.ts"(){"use strict";PendingMetadataRegistry=class{pending=new WeakMap;store(method,metadata){const existing=this.pending.get(method)??[];existing.push(metadata);this.pending.set(method,existing)}consume(method){const pending=this.pending.get(method)??[];this.pending.delete(method);return pending}resolveForClass(ctor,consume=true){const resolved=[];const proto=ctor.prototype;if(proto){for(const name59 of Object.getOwnPropertyNames(proto)){if(name59==="constructor")continue;try{const desc=Object.getOwnPropertyDescriptor(proto,name59);const method=desc?.value;if(typeof method==="function"){const pending=consume?this.consume(method):this.pending.get(method)??[];resolved.push(...pending)}}catch{}}}for(const name59 of Object.getOwnPropertyNames(ctor)){if(["prototype","length","name"].includes(name59))continue;try{const desc=Object.getOwnPropertyDescriptor(ctor,name59);const method=desc?.value;if(typeof method==="function"){const pending=consume?this.consume(method):this.pending.get(method)??[];resolved.push(...pending)}}catch{}}return resolved}}}});function registerHookOnClass(ctor,meta){const arr=Reflect.getMetadata(FrontMcpFlowHookTokens.hooks,ctor)??[];arr.push(meta);Reflect.defineMetadata(FrontMcpFlowHookTokens.hooks,arr,ctor)}function resolvePendingTC39HooksForClass(ctor){return pendingHookRegistry.resolveForClass(ctor)}function peekPendingTC39HooksForClass(ctor){return pendingHookRegistry.resolveForClass(ctor,false)}function registerPendingTC39Hook(method,meta){pendingHookRegistry.store(method,meta)}function consumePendingTC39Hooks(method){return pendingHookRegistry.consume(method)}function assertHookOptions(type,stage,opts){const parsed=hookOptionsSchema.safeParse(opts);if(parsed.success)return;const[issue]=parsed.error.issues;const decoratorName=`${type[0].toUpperCase()}${type.slice(1)}('${stage}')`;throw new InvalidDecoratorMetadataError(decoratorName,String(issue?.path[0]??"options"),issue?.message??"")}function make(flow,type){return function(stage,opts={}){assertHookOptions(type,stage,opts);return(target,keyOrContext,_desc)=>{const{priority=0,filter,...rest}=opts;if(isTC39MethodContext(keyOrContext)){const context=keyOrContext;const methodName=String(context.name);const isStatic=context.static;const method=target;const meta={...rest,[FrontMcpFlowHookTokens.type]:true,flow,type,stage,method:methodName,priority,filter,target:null,static:isStatic};pendingHookRegistry.store(method,meta);return target}else{const key=keyOrContext;const methodName=String(key);const isStatic=typeof target==="function";const ctor=isStatic?target:target.constructor;const meta={...rest,[FrontMcpFlowHookTokens.type]:true,flow,type,stage,method:methodName,priority,filter,target,static:isStatic};registerHookOnClass(ctor,meta);return void 0}}}}function StageHookOf(flow){const base=make(flow,"stage");return function(stage,opts={}){return base(stage,opts)}}function WillHookOf(flow){const base=make(flow,"will");return function(stage,opts={}){return base(stage,opts)}}function DidHookOf(flow){const base=make(flow,"did");return function(stage,opts={}){return base(stage,opts)}}function AroundHookOf(name59){const base=make(name59,"around");return function(stage,opts={}){return base(stage,opts)}}function FinallyHookOf(name59){const base=make(name59,"finally");return function(stage,opts={}){return base(stage,opts)}}function FlowHooksOf(name59){return{Stage:StageHookOf(name59),Will:WillHookOf(name59),Did:DidHookOf(name59),Around:AroundHookOf(name59),Finally:FinallyHookOf(name59)}}var pendingHookRegistry;var init_hook_decorator=__esm({"libs/sdk/src/common/decorators/hook.decorator.ts"(){"use strict";init_decorator_errors();init_metadata();init_tokens();init_decorator_utils();pendingHookRegistry=new PendingMetadataRegistry}});import{getMetadata as getMetadata2,isClass as isClass2,ProviderKind,tokenName}from"@frontmcp/di";function collectProviderMetadata(cls){const metadata=Object.entries(FrontMcpProviderTokens).reduce((collected,[key,token])=>{return Object.assign(collected,{[key]:getMetadata2(token,cls)})},{});const ownName=Reflect.getOwnMetadata(FrontMcpProviderTokens.name,cls);metadata.name=ownName??tokenName(cls);return metadata}function extractProviderMetadata(item){const nested=item.metadata;const topLevel={};if(item.name!==void 0)topLevel.name=item.name;if(item.scope!==void 0)topLevel.scope=item.scope;if(item.description!==void 0)topLevel.description=item.description;if(item.id!==void 0)topLevel.id=item.id;const result={...nested,...topLevel};if(!result.name){result.name=(item.provide?tokenName(item.provide):void 0)||"UnknownProvider"}return result}function normalizeProvider(item){if(isClass2(item)){const metadata=collectProviderMetadata(item);return{kind:ProviderKind.CLASS_TOKEN,provide:item,metadata}}if(item&&typeof item==="object"){const providerItem=item;const{provide,useClass,useValue,useFactory,inject}=providerItem;if(!provide){const name60=providerItem.name??"[object]";throw new MissingProvideError("Provider",name60)}const metadata=extractProviderMetadata(providerItem);if(useClass){if(!isClass2(useClass)){throw new InvalidUseClassError("provider",tokenName(provide))}return{kind:ProviderKind.CLASS,provide,useClass,metadata}}if(useFactory){if(typeof useFactory!=="function"){throw new InvalidUseFactoryError("provider",tokenName(provide))}const inj=typeof inject==="function"?inject:()=>[];return{kind:ProviderKind.FACTORY,provide,inject:inj,useFactory,metadata}}if("useValue"in item){return{kind:ProviderKind.VALUE,provide,useValue,metadata}}}const name59=item?.name??String(item);throw new InvalidEntityError("provider",name59,"a class or a provider object")}function providerDiscoveryDeps(rec,tokens,depsOfClass14){switch(rec.kind){case ProviderKind.VALUE:return[];case ProviderKind.FACTORY:{const all=[...rec.inject()];return all.filter(d=>tokens.has(d))}case ProviderKind.CLASS:return depsOfClass14(rec.useClass,"discovery");case ProviderKind.CLASS_TOKEN:return depsOfClass14(rec.provide,"discovery");case ProviderKind.INJECTED:return depsOfClass14(rec.value,"discovery")}}function providerInvocationTokens(rec,depsOfClass14){switch(rec.kind){case ProviderKind.VALUE:return[];case ProviderKind.FACTORY:return[...rec.inject()];case ProviderKind.CLASS:return depsOfClass14(rec.useClass,"invocation");case ProviderKind.CLASS_TOKEN:return depsOfClass14(rec.provide,"invocation");case ProviderKind.INJECTED:return depsOfClass14(rec.value,"invocation")}}var init_provider_utils=__esm({"libs/sdk/src/provider/provider.utils.ts"(){"use strict";init_common();init_errors()}});import{getMetadata as getMetadata3,isClass as isClass3}from"@frontmcp/di";function collectHook(cls){return getMetadata3(FrontMcpFlowHookTokens.hooks,cls)??[]}function normalizeHooksFromCls(source){const cls=isClass3(source)?source:source?.constructor;if(!isClass3(cls)){return[]}const methodHolder=cls===source?cls.prototype:source;const allHooks=[...collectHook(cls),...resolvePendingTC39HooksForClass(cls)];return allHooks.map(hook=>({kind:"METHOD_TOKEN",provide:hook.static?cls[hook.method]:methodHolder[hook.method],metadata:{...hook,target:hook.static?cls:methodHolder}}))}function normalizeHooksFromProviders(providers,only){const records=[];for(const[token,instance]of providers.getAllSingletons()){if(only&&!only.has(token))continue;if(typeof instance==="object"&&instance!==null)records.push(...normalizeHooksFromCls(instance))}for(const{token,cls}of providers.getContextScopedClasses()){if(only&&!only.has(token))continue;for(const record of normalizeHooksFromCls(cls)){records.push(record.metadata.static?record:{...record,metadata:{...record.metadata,contextTarget:contextInstanceOf(providers,token)}})}}return records}function serverProviderHooks(providers,declared,owner){if(!declared?.length)return[];const tokens=new Set(declared.map(provider=>normalizeProvider(provider).provide));return normalizeHooksFromProviders(providers,tokens).map(hook=>({...hook,metadata:{...hook.metadata,owner}}))}function contextInstanceOf(providers,token){return async({sessionKey,contextProviders,contextSource})=>{const views=await providers.buildViews(sessionKey,new Map(contextProviders),contextSource);const instance=views.context.get(token);return typeof instance==="object"&&instance!==null?instance:void 0}}function sourceMetadataOf(metadata){return boundFrom.get(metadata)??metadata}async function bindContextHookTargets(hooks,run){if(!hooks.some(hook=>hook.metadata.contextTarget))return[...hooks];const bound=[];for(const hook of hooks){const{contextTarget}=hook.metadata;if(!contextTarget){bound.push(hook);continue}const target=await contextTarget(run);if(target){const metadata={...hook.metadata,target,contextTarget:void 0};boundFrom.set(metadata,hook.metadata);bound.push({metadata})}}return bound}function hooksBoundTo(entries,instance){const target=instance;return entries.filter(entry=>!entry.metadata.static).map(entry=>({metadata:{...entry.metadata,target}}))}function staticHooksFor(entries,flow){return entries.filter(entry=>entry.metadata.static===true&&entry.metadata.flow===flow)}var boundFrom;var init_hooks_utils=__esm({"libs/sdk/src/hooks/hooks.utils.ts"(){"use strict";init_common();init_hook_decorator();init_provider_utils();boundFrom=new WeakMap}});import{z as z60}from"@frontmcp/lazy-zod";function utf8Bytes(text){return encoder.encode(text).byteLength}function jsonBytes(value){return utf8Bytes(JSON.stringify(value)??"")}function isLeftOut(value){return value===void 0||typeof value==="function"||typeof value==="symbol"}function isPlainContainer(value){if(typeof value.toJSON==="function")return false;const prototype=Object.getPrototypeOf(value);return Array.isArray(value)||prototype===Object.prototype||prototype===null}function sizeOf(value,sizes){if(typeof value!=="object"||value===null||!isPlainContainer(value))return jsonBytes(value);const known=sizes.get(value);if(known!==void 0)return known;let size=2;if(Array.isArray(value)){for(const item of value)size+=isLeftOut(item)?4:sizeOf(item,sizes);size+=Math.max(value.length-1,0)}else{let written=0;for(const[key,item]of Object.entries(value)){if(isLeftOut(item))continue;size+=jsonBytes(key)+1+sizeOf(item,sizes);written++}size+=Math.max(written-1,0)}sizes.set(value,size);return size}function isRecord2(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function prefixOf(text,length){const lastCode=text.charCodeAt(length-1);const splitsPair=length>0&&lastCode>=55296&&lastCode<=56319;return text.slice(0,splitsPair?length-1:length)}function longestPrefix(text,allowance,sizeOf2){let low=0;let high=text.length;while(low<high){const middle=Math.ceil((low+high)/2);if(sizeOf2(prefixOf(text,middle))<=allowance)low=middle;else high=middle-1}return prefixOf(text,low)}function childPath(path4,key){return IDENTIFIER.test(key)?`${path4}.${key}`:`${path4}[${JSON.stringify(key)}]`}function fitNode(node,size,allowance,path4,context){if(size<=allowance)return node;if(typeof node==="string")return fitString(node,allowance,path4,context);if(Array.isArray(node))return fitList(node,allowance,path4,context);if(isRecord2(node))return fitRecord(node,size,allowance,path4,context);return node}function fitString(text,allowance,path4,context){const kept=longestPrefix(text,allowance,jsonBytes);context.omitted.push({path:path4,chars:text.length-kept.length});return kept}function fitList(items,allowance,path4,context){if(items.length===0)return items;const sizes=items.map(item=>sizeOf(item,context.sizes));const indexes=items.map((_,index)=>index);const preferred=context.lists==="keep-newest"?indexes.reverse():indexes;const kept=[];let used=2;for(const index of preferred){const added=sizes[index]+(kept.length>0?1:0);if(used+added>allowance)break;used+=added;kept.push(index)}if(kept.length===0){const[first3]=preferred;if(items.length>1)context.omitted.push({path:path4,items:items.length-1,of:items.length});return[fitNode(items[first3],sizes[first3],allowance-2,`${path4}[0]`,context)]}context.omitted.push({path:path4,items:items.length-kept.length,of:items.length});return kept.sort((left,right)=>left-right).map(index=>items[index])}function fitRecord(record,size,allowance,path4,context){const entries=Object.entries(record);const sizes=entries.map(([,value])=>sizeOf(value,context.sizes));const largestFirst=entries.map((_,index)=>index).sort((left,right)=>sizes[right]-sizes[left]);const fitted={...record};let total=size;for(const index of largestFirst){if(total<=allowance)break;const[key,value]=entries[index];const shrunk=fitNode(value,sizes[index],Math.max(sizes[index]-(total-allowance),0),childPath(path4,key),context);if(shrunk===value)continue;total-=sizes[index]-sizeOf(shrunk,context.sizes);fitted[key]=shrunk}return fitted}function fitJsonToBudget(value,maxBytes,lists="keep-newest"){const context={lists,omitted:[],sizes:new WeakMap};const size=sizeOf(value,context.sizes);if(size<=maxBytes)return{value,omitted:[]};return{value:fitNode(value,size,maxBytes,"$",context),omitted:context.omitted}}function parseJsonText(text){const start=text.trimStart()[0];if(start!=="{"&&start!=="[")return void 0;try{return JSON.parse(text)}catch{return void 0}}function fitTextToBudget(text,maxBytes,lists){if(utf8Bytes(text)<=maxBytes)return{value:text,omitted:[]};const json=parseJsonText(text);if(json!==void 0){const fitted=fitJsonToBudget(json,maxBytes,lists);return{value:JSON.stringify(fitted.value),omitted:fitted.omitted}}const kept=longestPrefix(text,maxBytes,utf8Bytes);return{value:kept,omitted:[{path:"$",chars:text.length-kept.length}]}}function describeOmission(omission,lists){const where=omission.path==="$"?"the answer":omission.path;if(omission.items!==void 0){const end=lists==="keep-newest"?"first":"last";return`the ${end} ${omission.items} of ${omission.of} items of ${where}`}return`the last ${omission.chars} characters of ${where}`}function describeBudgetNote(note){const described=note.omitted.slice(0,NOTED_OMISSIONS).map(omission=>describeOmission(omission,note.lists));const more=note.omitted.length-described.length;if(more>0)described.push(`${more} more parts listed in _meta["${BUDGET_META_KEY}"]`);return`This answer was shortened to fit its ${note.maxBytes}-byte budget: left out ${described.join("; ")}.`}function addOmissions(omitted,added){const known=new Set(omitted.map(omission=>JSON.stringify(omission)));omitted.push(...added.filter(omission=>!known.has(JSON.stringify(omission))))}function fitToolAnswer(result,budget){const lists=budget.lists??"keep-newest";const omitted=[];let changed=false;let structuredContent=result.structuredContent;const structuredText=structuredContent===void 0?void 0:JSON.stringify(structuredContent);let fittedStructuredText;if(structuredContent!==void 0&&structuredText!==void 0&&utf8Bytes(structuredText)>budget.maxBytes){const fitted=fitJsonToBudget(structuredContent,budget.maxBytes,lists);structuredContent=fitted.value;fittedStructuredText=JSON.stringify(structuredContent);omitted.push(...fitted.omitted);changed=true}const content=result.content.map(block=>{if(block.type!=="text")return block;if(fittedStructuredText!==void 0&&block.text===structuredText)return{...block,text:fittedStructuredText};const fitted=fitTextToBudget(block.text,budget.maxBytes,lists);if(fitted.value===block.text)return block;addOmissions(omitted,fitted.omitted);changed=true;return{...block,text:fitted.value}});if(!changed)return void 0;if(omitted.length===0)return{...result,content};const note={maxBytes:budget.maxBytes,lists,omitted};return{...result,content:[...content,{type:"text",text:describeBudgetNote(note)}],...structuredContent!==void 0&&{structuredContent},_meta:{...result._meta,[BUDGET_META_KEY]:note}}}function fitResourceAnswer(result,budget){const lists=budget.lists??"keep-newest";const omitted=[];let changed=false;const contents=result.contents.map(content=>{if(!("text"in content)||typeof content.text!=="string"||content.mimeType?.startsWith("text/html")){return content}const fitted=fitTextToBudget(content.text,budget.maxBytes,lists);if(fitted.value===content.text)return content;omitted.push(...fitted.omitted.map(omission=>({uri:content.uri,...omission})));changed=true;return{...content,text:fitted.value}});if(!changed)return void 0;if(omitted.length===0)return{...result,contents};const note={maxBytes:budget.maxBytes,lists,omitted};const noteUri=omitted[0].uri??result.contents[0].uri;return{...result,contents:[...contents,{uri:noteUri,mimeType:"text/plain",text:describeBudgetNote(note)}],_meta:{...result._meta,[BUDGET_META_KEY]:note}}}function parserOf(outputSchema51){const known=listedSchemaParsers.get(outputSchema51);if(known)return known;let parser;try{parser=z60.fromJSONSchema(withUndeclaredKeysAllowed(outputSchema51),{defaultTarget:"draft-2020-12"})}catch(error){parser=error instanceof Error?error:new Error(String(error))}listedSchemaParsers.set(outputSchema51,parser);return parser}function outputSchemaMismatch(outputSchema51,structuredContent){const parser=parserOf(outputSchema51);if(parser instanceof Error)return`the schema could not be checked: ${parser.message}`;const parsed=parser.safeParse(structuredContent);if(parsed.success)return void 0;const[issue]=parsed.error.issues;return`${["$",...issue.path.map(String)].join(".")}: ${issue.message}`}var BUDGET_META_KEY,NOTED_OMISSIONS,listedSchemaParsers,IDENTIFIER,encoder;var init_answer_budget=__esm({"libs/sdk/src/answer/answer-budget.ts"(){"use strict";init_output_policy();BUDGET_META_KEY="frontmcp/budget";NOTED_OMISSIONS=5;listedSchemaParsers=new WeakMap;IDENTIFIER=/^[A-Za-z_$][\w$]*$/;encoder=new TextEncoder}});import{registerOptionalModule,requireOptionalModule}from"@frontmcp/utils";function probeOptionalDependency(moduleName,loadError,resolve4){let resolvedPath;try{resolvedPath=resolve4(moduleName)}catch{resolvedPath=void 0}const error=loadError instanceof Error?loadError.message:String(loadError);return resolvedPath?{status:"load-failed",resolvedPath,error}:{status:"not-installed",error}}var init_optional_dependency_util=__esm({"libs/sdk/src/scope/optional-dependency.util.ts"(){"use strict"}});function meteringEnabled(metrics){if(metrics?.enabled!==true)return false;return!metrics.include||metrics.include.length===0||metrics.include.includes("tools")}function measureAnswer(result){const bytes=encoder2.encode(JSON.stringify(result)).byteLength;const structuredText=result.structuredContent===void 0?void 0:JSON.stringify(result.structuredContent);const duplicatedBytes=result.content.reduce((sum,block)=>block.type==="text"&&block.text===structuredText?sum+encoder2.encode(block.text).byteLength:sum,0);return{bytes,estimatedTokens:Math.ceil(bytes/4),duplicatedBytes}}function loadCounterFactory(){return requireOptionalModule("@frontmcp/observability",()=>__require("@frontmcp/observability")).createCounter}function recordAnswerCost(cost,labels,createCounter=loadCounterFactory()){for(const key of Object.keys(ANSWER_COUNTERS)){createCounter(ANSWER_COUNTERS[key],COUNTER_DESCRIPTIONS[key]).inc(cost[key],labels)}}var ANSWER_COUNTERS,COUNTER_DESCRIPTIONS,encoder2;var init_answer_meter=__esm({"libs/sdk/src/answer/answer-meter.ts"(){"use strict";init_optional_dependency_util();ANSWER_COUNTERS={bytes:"frontmcp_tool_answer_bytes_total",estimatedTokens:"frontmcp_tool_answer_estimated_tokens_total",duplicatedBytes:"frontmcp_tool_answer_duplicated_bytes_total"};COUNTER_DESCRIPTIONS={bytes:"UTF-8 bytes of tool answers as JSON",estimatedTokens:"Tokens tool answers cost, estimated as bytes / 4",duplicatedBytes:"Bytes of tool answer text that repeats structuredContent"};encoder2=new TextEncoder}});var init_answer=__esm({"libs/sdk/src/answer/index.ts"(){"use strict";init_answer_budget();init_answer_meter();init_client_profile()}});async function isEntryEnabled(enabled,context,logger){if(enabled===void 0||typeof enabled==="boolean")return enabled!==false;try{return await enabled.get(context)===true}catch(error){logger?.warn(`An enabled source failed to answer, so its entry is off: ${error instanceof Error?error.message:String(error)}`);return false}}async function enabledItems(items,enabledOf,context,logger){const answers=await Promise.all(items.map(item=>isEntryEnabled(enabledOf(item),context,logger)));return items.filter((_item,index)=>answers[index])}async function assertEntryEnabled(entryType,entryName,enabled,context,logger){if(await isEntryEnabled(enabled,context,logger))return;throw new FeatureOffError(entryType,entryName,typeof enabled==="object"?enabled.remedy:void 0)}var init_entry_enabled=__esm({"libs/sdk/src/surface/entry-enabled.ts"(){"use strict";init_mcp_error()}});function markPlaceholder(entry,app){appOfPlaceholder.set(entry,app)}function lazyAppOf(entry){return appOfPlaceholder.get(entry)}async function loadAppOfPlaceholder(scope,entry){const app=lazyAppOf(entry);if(!app||!await isEntryEnabled(entry.metadata.enabled,requestContextOf(scope)))return false;return app.load().then(()=>true,()=>false)}function requestContextOf(scope){try{return scope.providers.get(FrontMcpContextStorage).getStore()}catch{return void 0}}function assertAppLoaded(entry){const app=lazyAppOf(entry);if(app)throw new LazyAppLoadError(app.metadata.name,app.retryable)}var appOfPlaceholder;var init_lazy_placeholders=__esm({"libs/sdk/src/app/lazy/lazy-placeholders.ts"(){"use strict";init_frontmcp_context_storage();init_lazy_app_errors();init_entry_enabled();appOfPlaceholder=new WeakMap}});async function loadRemoteAppCapabilities(scope,onError=()=>void 0){const remoteApps=scope.providers.getRegistries("AppRegistry").flatMap(appRegistry=>appRegistry.getApps()).filter(app=>app.isRemote);await Promise.all(remoteApps.map(async app=>{if(!("ensureCapabilitiesLoaded"in app)||typeof app.ensureCapabilitiesLoaded!=="function")return;try{await app.ensureCapabilitiesLoaded()}catch(error){onError(app.id,error)}}));return remoteApps.length}var init_remote_capabilities_utils=__esm({"libs/sdk/src/app/remote-capabilities.utils.ts"(){"use strict"}});import{decodeJwtPayloadSafe,isOrchestratedMode as isOrchestratedMode2}from"@frontmcp/auth";function readAuthorizedApps(source){if(!source||typeof source!=="object")return void 0;return source["authorized_apps"]}function readUser(source){if(!source||typeof source!=="object")return void 0;return source["user"]}function asAppIdList(value){if(!Array.isArray(value))return void 0;return value.filter(id=>typeof id==="string")}function getAuthorizedAppIds(authInfo){if(!authInfo)return void 0;const list=asAppIdList(readAuthorizedApps(readUser(authInfo.extra)))??asAppIdList(readAuthorizedApps(authInfo.extra))??asAppIdList(readAuthorizedApps(authInfo.user))??asAppIdList(decodeJwtPayloadSafe(authInfo.token)?.["authorized_apps"]);if(!list)return void 0;return new Set(list)}function grantAppId(app){return app.id??app.metadata.id??""}function isIncrementalAuthEnabled(authOptions){if(!authOptions||!isOrchestratedMode2(authOptions))return false;return authOptions.incrementalAuth!==void 0&&authOptions.incrementalAuth.enabled!==false}function incrementalTicketAudience(scope){const issuer=scope.auth?.issuer;return JSON.stringify([typeof issuer==="string"?issuer:"",scope.fullPath])}function initialAuthorizedApps(authOptions,apps,requestedAppIds){if(!isIncrementalAuthEnabled(authOptions))return void 0;const knownAppIds=new Set(apps.map(grantAppId).filter(Boolean));return requestedAppIds?[...new Set(requestedAppIds)].filter(id=>knownAppIds.has(id)):[...knownAppIds]}function withoutSkippedApps(grant,apps,skippedProviderIds){if(!skippedProviderIds||skippedProviderIds.length===0)return[...grant];const skippedAppIds=new Set(apps.filter(app=>app.metadata.auth&&skippedProviderIds.includes(app.metadata.id||app.metadata.name||"")).map(grantAppId));return grant.filter(id=>!skippedAppIds.has(id))}var init_authorized_apps_utils=__esm({"libs/sdk/src/auth/authorized-apps.utils.ts"(){"use strict"}});import{decodeJwtPayloadSafe as decodeJwtPayloadSafe2}from"@frontmcp/auth";function readConsent(source){if(!source||typeof source!=="object")return void 0;return source["consent"]}function readUser2(source){if(!source||typeof source!=="object")return void 0;return source["user"]}function asConsentClaim(value){if(!value||typeof value!=="object")return void 0;const claim=value;if(claim.enabled!==true)return void 0;return claim}function getConsentedToolIds(authInfo){if(!authInfo)return void 0;const claim=asConsentClaim(readConsent(readUser2(authInfo.extra)))??asConsentClaim(readConsent(authInfo.extra))??asConsentClaim(readConsent(authInfo.user))??asConsentClaim(decodeJwtPayloadSafe2(authInfo.token)?.["consent"]);if(!claim)return void 0;const selected=Array.isArray(claim.selectedTools)?claim.selectedTools.filter(t=>typeof t==="string"):[];return new Set(selected)}function isToolConsented(consented,...toolIds){if(!consented)return true;return toolIds.some(id=>id!==void 0&&consented.has(id))}var init_consent_utils=__esm({"libs/sdk/src/auth/consent.utils.ts"(){"use strict"}});function toolNameCandidates(name59){if(!/[-_]/.test(name59))return[name59];return[name59,name59.includes("_")?name59.replace(/_/g,"-"):name59.replace(/-/g,"_")]}function toolAliasesOf(tool){return tool.metadata.aliases??[]}function lookupTool(scope,name59){const fullName=ownerQualifiedName(name59);const scopeTools=scope.tools.getTools(true);return findTool(scope,scopeTools,entry=>toolAliasesOf(entry).includes(name59))??findTool(scope,scopeTools,matchesName(name59))??(fullName===void 0?void 0:findTool(scope,scopeTools,matchesName(fullName)))}function ownerQualifiedName(name59){const separator=name59.indexOf(".");return separator>0?`${name59.slice(0,separator)}:${name59.slice(separator+1)}`:void 0}function describeToolAliasConflicts(tools){const uniqueTools=[...new Set(tools)];const toolByName=new Map;for(const tool of uniqueTools){toolByName.set(tool.name,tool);toolByName.set(tool.fullName,tool)}const toolByAlias=new Map;const conflicts=[];for(const tool of uniqueTools){for(const alias of toolAliasesOf(tool)){const named=toolByName.get(alias);if(named)conflicts.push(`alias "${alias}" of tool "${tool.name}" is the name of tool "${named.name}"`);const declarer=toolByAlias.get(alias);if(declarer&&declarer!==tool){conflicts.push(`alias "${alias}" is declared by both "${declarer.fullName}" and "${tool.fullName}"`)}toolByAlias.set(alias,tool)}}return conflicts}function matchesName(name59){const candidateNames=toolNameCandidates(name59);return entry=>candidateNames.includes(entry.fullName)||candidateNames.includes(entry.name)}function findTool(scope,scopeTools,matches){const scopeTool=scopeTools.find(matches);if(scopeTool)return scopeTool;for(const appRegistry of scope.providers?.getRegistries("AppRegistry")??[]){for(const app of appRegistry.getApps()){if(!app.isRemote)continue;const remoteTool=app.tools.getTools(true).find(matches);if(remoteTool)return remoteTool}}return void 0}var init_tool_lookup_utils=__esm({"libs/sdk/src/common/utils/tool-lookup.utils.ts"(){"use strict"}});import{AsyncLocalStorage as AsyncLocalStorage5}from"@frontmcp/utils";function runAsTool(tool,fn){return runningTools.run(tool,fn)}function getRunningTool(){return runningTools.getStore()}var runningTools;var init_running_tool=__esm({"libs/sdk/src/context/running-tool.ts"(){"use strict";runningTools=new AsyncLocalStorage5}});var ResolvedEntries;var init_resolved_entries=__esm({"libs/sdk/src/flows/resolved-entries.ts"(){"use strict";ResolvedEntries=class{byInput=new WeakMap;remember(rawInput,key,entry){if(typeof rawInput==="object"&&rawInput!==null)this.byInput.set(rawInput,{key,entry})}peek(rawInput,key){if(typeof rawInput!=="object"||rawInput===null)return void 0;const resolved=this.byInput.get(rawInput);return resolved?.key===key?resolved.entry:void 0}take(rawInput,key){const entry=this.peek(rawInput,key);if(typeof rawInput==="object"&&rawInput!==null)this.byInput.delete(rawInput);return entry}}}});var FlowContextProviders;var init_flow_context_providers=__esm({"libs/sdk/src/provider/flow-context-providers.ts"(){"use strict";FlowContextProviders=class{constructor(baseProviders,contextDeps){this.baseProviders=baseProviders;this.contextDeps=contextDeps}baseProviders;contextDeps;get(token){if(this.contextDeps.has(token)){return this.contextDeps.get(token)}return this.baseProviders.get(token)}getScope(){return this.baseProviders.getScope()}getProviders(){return this.baseProviders.getProviders()}getRegistries(type){return this.baseProviders.getRegistries(type)}buildViews(sessionKey,contextProviders,contextSource){return this.baseProviders.buildViews(sessionKey,contextProviders,contextSource)}}}});function detectSkillsOnlyMode(query){if(!query)return false;const mode=query["mode"];if(mode==="skills_only"){return true}if(Array.isArray(mode)&&mode.includes("skills_only")){return true}return false}function isSkillsOnlySession(sessionPayload){return sessionPayload?.skillsOnlyMode===true}function isSkillsOnlyRequest(authInfo,context){return isSkillsOnlySession(authInfo?.sessionIdPayload)||context?.has(SKILLS_ONLY_REQUEST)===true}var SKILLS_ONLY_REQUEST;var init_skill_mode_utils=__esm({"libs/sdk/src/skill/skill-mode.utils.ts"(){"use strict";SKILLS_ONLY_REQUEST=Symbol.for("frontmcp:skills:skills-only-request")}});import{basename as basename2,dirname as dirname2,readFile,watchFile}from"@frontmcp/utils";function fileSignal(path4,key,options={}){if(!path4)throw new InvalidFileSignalError("it needs a file path");if(!key)throw new InvalidFileSignalError("it needs a key");const{pollIntervalMs}=options;if(pollIntervalMs!==void 0&&!(Number.isFinite(pollIntervalMs)&&pollIntervalMs>0)){throw new InvalidFileSignalError(`pollIntervalMs must be a positive number, got ${pollIntervalMs}`)}return new FileSignal(path4,key,options)}var FileSignal;var init_file_signal=__esm({"libs/sdk/src/surface/file-signal.ts"(){"use strict";init_mcp_error();FileSignal=class{constructor(path4,key,options){this.path=path4;this.key=key;this.defaultValue=options.defaultValue??false;this.pollIntervalMs=options.pollIntervalMs??2e3;this.remedy=options.remedy??{say:`Turn on the "${key}" feature, then try again.`};this.logger=options.logger??console}path;key;remedy;defaultValue;pollIntervalMs;logger;listeners=new Set;value;problem;watcher;poller;checking=Promise.resolve();async get(){return this.value??this.read()}subscribe(listener){this.listeners.add(listener);if(this.listeners.size===1)this.start();return()=>{if(this.listeners.delete(listener)&&this.listeners.size===0)this.stop()}}start(){this.check();try{const fileName=basename2(this.path);this.watcher=watchFile(dirname2(this.path),(_event,changed)=>{if(!changed||changed===fileName)this.check()});this.watcher.onError(()=>this.closeWatcher())}catch{this.watcher=void 0}this.poller=setInterval(()=>this.check(),this.pollIntervalMs);this.poller.unref?.()}stop(){this.closeWatcher();clearInterval(this.poller);this.poller=void 0;this.value=void 0}closeWatcher(){this.watcher?.close();this.watcher=void 0}check(){this.checking=this.checking.then(async()=>{const next=await this.read();if(this.listeners.size===0)return;const previous=this.value;this.value=next;if(previous===void 0||previous===next)return;for(const listener of[...this.listeners])this.notify(listener)})}notify(listener){try{listener()}catch(error){this.logger.warn(`fileSignal: a listener of "${this.key}" failed: ${error instanceof Error?error.message:String(error)}`)}}async read(){let content;try{content=await readFile(this.path)}catch{return this.fallBack(`${this.path} could not be read`)}let parsed;try{parsed=JSON.parse(content)}catch{return this.fallBack(`${this.path} is not valid JSON`,this.value)}const value=parsed?.[this.key];if(typeof value!=="boolean")return this.fallBack(`${this.path} has no boolean "${this.key}"`);this.problem=void 0;return value}fallBack(problem2,lastValue){const value=lastValue??this.defaultValue;if(this.problem!==problem2){this.problem=problem2;const kept=lastValue===void 0?"its default":"its last value";this.logger.warn(`fileSignal: ${problem2}; "${this.key}" is ${value?"on":"off"}, ${kept}.`)}return value}}}});import{sha256Hex as sha256Hex2}from"@frontmcp/utils";function messageOf(error){return error instanceof Error?error.message:String(error)}function surfaceHash(names){return sha256Hex2([...names].sort().join("\n")).slice(0,16)}var SURFACE_META_KEY,LIST_KINDS,LiveSurface;var init_live_surface=__esm({"libs/sdk/src/surface/live-surface.ts"(){"use strict";init_enabled_metadata();init_transport_types();init_list_change_batch();SURFACE_META_KEY="frontmcp/surface";LIST_KINDS=["tools","resources","prompts"];LiveSurface=class{constructor(scope,options={}){this.scope=scope;this.windowMs=options.windowMs??100;this.maxSessions=options.maxSessions??1e4}scope;windowMs;maxSessions;sources=new Map;pending=new Map;stops=[];toolsVersion=0;listedVersions=new Map;running=false;start(){if(this.running)return;this.running=true;for(const kind of LIST_KINDS){this.followSources(kind);this.stops.push(this.registryOf(kind).subscribe({immediate:false},()=>this.followSources(kind)))}this.stops.push(this.scope.tools.subscribe({immediate:false},()=>{if(announcesListChangeNow(this.scope,"tools"))this.toolsVersion++}))}stop(){this.running=false;for(const stop of this.stops.splice(0))stop();for(const watched of this.sources.values())for(const unsubscribe of watched.values())unsubscribe();this.sources.clear();for(const timer of this.pending.values())clearTimeout(timer);this.pending.clear()}listChanged(kind){if(!this.running||this.pending.has(kind))return;const timer=setTimeout(()=>{this.pending.delete(kind);try{this.registryOf(kind).notifyListChanged()}catch(error){this.scope.logger.warn(`The ${kind} list change could not be announced: ${messageOf(error)}`)}},this.windowMs);timer.unref?.();this.pending.set(kind,timer)}recordToolList(sessionId,names){if(this.isConnectedSession(sessionId)){this.listedVersions.delete(sessionId);this.listedVersions.set(sessionId,this.toolsVersion);if(this.listedVersions.size>this.maxSessions){const[leastRecent]=this.listedVersions.keys();this.listedVersions.delete(leastRecent)}}return surfaceHash(names)}isStale(sessionId){const listed=sessionId===void 0?void 0:this.listedVersions.get(sessionId);return listed!==void 0&&listed<this.toolsVersion}refreshSession(sessionId){if(this.listedVersions.has(sessionId))this.listedVersions.set(sessionId,this.toolsVersion);this.scope.notifications.sendNotificationToSession(sessionId,"notifications/tools/list_changed")}isConnectedSession(sessionId){if(!sessionId||sessionId===STATELESS_SESSION_ID)return false;return this.scope.notifications.getRegisteredServer(sessionId)!==void 0}registryOf(kind){return this.scope[kind]}followSources(kind){const used=new Set(this.registryOf(kind).listAllInstances().map(entry=>entry.metadata.enabled).filter(isEnabledSource));const watched=this.sources.get(kind)??new Map;this.sources.set(kind,watched);for(const[source,unsubscribe]of watched){if(used.has(source))continue;unsubscribe();watched.delete(source)}for(const source of used){if(watched.has(source))continue;try{watched.set(source,source.subscribe(()=>this.listChanged(kind)))}catch(error){watched.set(source,()=>void 0);this.scope.logger.warn(`An enabled source of the ${kind} could not be followed: ${messageOf(error)}`)}}}}}});var init_surface=__esm({"libs/sdk/src/surface/index.ts"(){"use strict";init_file_signal();init_entry_enabled();init_live_surface()}});import{randomUUID as randomUUID10}from"@frontmcp/utils";function generateTaskId(){return randomUUID10()}var init_task_id=__esm({"libs/sdk/src/task/helpers/task-id.ts"(){"use strict"}});var TaskNotifier;var init_task_notifier=__esm({"libs/sdk/src/task/helpers/task-notifier.ts"(){"use strict";init_task_types();TaskNotifier=class{constructor(notifications,logger){this.notifications=notifications;this.logger=logger}notifications;logger;sendStatus(record){const params={...toWireShape(record)};try{this.notifications.sendNotificationToSession(record.sessionId,"notifications/tasks/status",params)}catch(err){this.logger?.warn("[TaskNotifier] sendStatus failed",{taskId:record.taskId,error:err instanceof Error?err.message:String(err)})}}}}});function linkedAbortController(signal){return detachableAbortController(signal).controller}function detachableAbortController(signal){const controller=new AbortController;const followSignal=()=>controller.abort(signal?.reason);if(signal?.aborted)controller.abort(signal.reason);else signal?.addEventListener("abort",followSignal,{once:true});return{controller,unlink:()=>signal?.removeEventListener("abort",followSignal)}}var init_abort_utils=__esm({"libs/sdk/src/utils/abort.utils.ts"(){"use strict"}});var FrontMcpConfig;var init_front_mcp_tokens2=__esm({"libs/sdk/src/front-mcp/front-mcp.tokens.ts"(){"use strict";FrontMcpConfig=Symbol("FrontMcpConfig")}});function isServerEntryOwner(owner){return owner?.kind===serverEntryOwner.kind&&owner.id===serverEntryOwner.id&&owner.ref===serverEntryOwner.ref}function ownerKeyOf(lineage){return lineage.map(o=>`${o.kind}:${o.id}`).join("/")}function qualifiedNameOf(lineage,name59){return`${ownerKeyOf(lineage)}:${name59}`}function hookOwnerIdOf(lineage,owner){const owners2=owner?[...lineage,owner]:lineage;return appOwnerIdOf(owners2)??owners2[owners2.length-1]?.id}function appOwnerIdOf(lineage,owner){const owners2=owner?[...lineage,owner]:lineage;return owners2.find(candidate=>candidate.kind==="app")?.id}var serverEntryOwner,EntryLineageIndex;var init_lineage_utils=__esm({"libs/sdk/src/utils/lineage.utils.ts"(){"use strict";init_front_mcp_tokens2();serverEntryOwner={kind:"scope",id:"server",ref:FrontMcpConfig};EntryLineageIndex=class{lineages=new Map;rebuild(rows){this.lineages.clear();for(const row of rows){if(!this.lineages.has(row.instance))this.lineages.set(row.instance,row.lineage)}}lineageOf(entry){return this.lineages.get(entry)}}}});function toolOutputPolicies(tool,scope){const appOutput=appMetadataOf(tool,scope)?.output;return[tool.metadata.output,appOutput,scope.metadata.output]}function resolveStructuredContentValidation(tool,app,server){return tool?.validateStructuredContent??app?.validateStructuredContent??server?.validateStructuredContent??"enforce"}function toolInputPolicies(tool,scope){const appInput=appMetadataOf(tool,scope)?.input;return[tool.metadata.input,appInput,scope.metadata.input]}function appMetadataOf(tool,scope){const appId=appOwnerIdOf(scope.tools.lineageOf(tool)??[],tool.owner);return appId===void 0?void 0:scope.apps.getApps().find(candidate=>candidate.id===appId)?.metadata}function describeUnlistedOutputSchemas(scope){return scope.tools.getTools().flatMap(tool=>{const reason=tool.getUnlistedOutputSchemaReason();if(!reason||resolveOutputSchemaMode(...toolOutputPolicies(tool,scope))==="none")return[];return[`Tool "${tool.metadata.name}": tools/list leaves out its outputSchema because ${reason}. Declare a z.object() or a union of z.object() schemas to list it.`]})}var init_tool_output_policy=__esm({"libs/sdk/src/tool/tool-output-policy.ts"(){"use strict";init_common();init_lineage_utils()}});import{inferMimeType,sanitizeToJson}from"@frontmcp/utils";function toStructuredContent(value){const result=sanitizeToJson(value);if(result===void 0||result===null)return void 0;if(typeof result==="object"&&!Array.isArray(result)){return result}return{value:result}}function buildResourceContent(uri,content,mimeType){if(content&&typeof content==="object"){const obj=content;if("blob"in obj&&typeof obj["blob"]==="string"){return{uri,mimeType:obj["mimeType"]||mimeType,blob:obj["blob"]}}if("text"in obj&&typeof obj["text"]==="string"){return{uri,mimeType:obj["mimeType"]||mimeType,text:obj["text"]}}}if(Buffer.isBuffer(content)||content instanceof Uint8Array){const buffer=Buffer.isBuffer(content)?content:Buffer.from(content);return{uri,mimeType:mimeType||"application/octet-stream",blob:buffer.toString("base64")}}if(typeof content==="string"){return{uri,mimeType:mimeType||inferMimeType(uri,content),text:content}}try{return{uri,mimeType:mimeType||"application/json",text:JSON.stringify(content)}}catch{return{uri,mimeType:mimeType||"text/plain",text:String(content)}}}var init_content_utils=__esm({"libs/sdk/src/utils/content.utils.ts"(){"use strict"}});import{depsOfClass,depsOfFunc,getMetadata as getMetadata4,isClass as isClass4}from"@frontmcp/di";import{hasTransform,internalZ as z61,ZodBigInt,ZodBoolean,ZodDate,ZodNumber,ZodString}from"@frontmcp/lazy-zod";import{findDroppedKeys}from"@frontmcp/utils";function collectToolMetadata(cls){const extended=getMetadata4(extendedToolMetadata,cls);const seed=extended?{...extended}:{};return Object.entries(FrontMcpToolTokens).reduce((metadata,[key,token])=>{const value=getMetadata4(token,cls);if(value!==void 0){return Object.assign(metadata,{[key]:value})}else{return metadata}},seed)}function normalizeTool(item){if(item&&typeof item==="object"&&(item.kind==="ESM"||item.kind==="REMOTE")){return item}if(typeof item==="string"){if(isPackageSpecifier(item)){const specifier=parsePackageSpecifier(item);return{kind:"ESM",provide:item,specifier,metadata:{name:specifier.fullName,description:`ESM tools from ${specifier.fullName}`,inputSchema:{}}}}throw new InvalidEntityError("tool",item,"a class, a tool object, or a valid package specifier")}if(item&&typeof item==="function"&&item[FrontMcpToolTokens.type]==="function-tool"&&item[FrontMcpToolTokens.metadata]){return{kind:"FUNCTION",provide:item(),metadata:item[FrontMcpToolTokens.metadata]}}if(isClass4(item)){const metadata=collectToolMetadata(item);return{kind:"CLASS_TOKEN",provide:item,metadata}}const name59=item?.name??String(item);throw new InvalidEntityError("tool",name59,"a class or a tool object")}function isExternalToolRecord(record){return record.kind==="ESM"||record.kind==="REMOTE"}function toolDiscoveryDeps(rec){switch(rec.kind){case"FUNCTION":return depsOfFunc(rec.provide,"discovery");case"CLASS_TOKEN":return depsOfClass(rec.provide,"discovery");case"ESM":case"REMOTE":return[]}}function isCallToolResult(value){if(typeof value!=="object"||value===null)return false;const obj=value;if(!Array.isArray(obj["content"]))return false;const content=obj["content"];if(content.length>0){const firstItem=content[0];if(typeof firstItem!=="object"||firstItem===null)return false;if(typeof firstItem["type"]!=="string")return false;const validTypes=["text","image","audio","resource","resource_link"];if(!validTypes.includes(firstItem["type"]))return false}return true}function buildParsedToolResult(descriptor,raw,options={}){if(isReturnedCallToolResult(descriptor,raw)){return withDeclaredStructuredContent(descriptor,raw,options)}const content=[];let structuredData;if(!descriptor){const structuredContent=toStructuredContent(raw);const sanitized=structuredContent??raw;content.push(makeJsonTextContent(sanitized));return{content,structuredContent}}if(Array.isArray(descriptor)){const values=Array.isArray(raw)?raw:[raw];const parsedItems=[];descriptor.forEach((singleDescriptor,idx)=>{const value=values[idx];const{blocks,parsedValue,isPrimitive}=parseSingleValue(singleDescriptor,value,options,String(idx));parsedItems.push({blocks,parsedValue,isPrimitive});content.push(...blocks)});const hasNonPrimitive=parsedItems.some(item=>!item.isPrimitive);if(hasNonPrimitive&&parsedItems.length>1){structuredData={};parsedItems.forEach((item,idx)=>{if(item.parsedValue!==void 0){structuredData[idx]=item.parsedValue}})}else if(parsedItems.length===1&&parsedItems[0].parsedValue!==void 0){if(parsedItems[0].isPrimitive){structuredData={content:parsedItems[0].parsedValue}}else if(typeof parsedItems[0].parsedValue==="object"&&parsedItems[0].parsedValue!==null){structuredData=parsedItems[0].parsedValue}else{structuredData={content:parsedItems[0].parsedValue}}}else if(hasNonPrimitive){structuredData={};parsedItems.forEach((item,idx)=>{if(item.parsedValue!==void 0){structuredData[idx]=item.parsedValue}})}}else{const{blocks,parsedValue,isPrimitive}=parseSingleValue(descriptor,raw,options);content.push(...blocks);if(parsedValue!==void 0){if(isPrimitive){structuredData={content:parsedValue}}else if(typeof parsedValue==="object"&&parsedValue!==null){structuredData=parsedValue}else{structuredData={content:parsedValue}}}}const result={content};if(structuredData!==void 0){result.structuredContent=structuredData}return result}function isReturnedCallToolResult(descriptor,raw){if(!isCallToolResult(raw))return false;if(raw.content.length>0||raw.structuredContent!==void 0||raw.isError)return true;return!structuredOutputSchemaOf(descriptor)?.safeParse(raw).success}function asElicitationFallback(answer){elicitationFallbacks.add(answer);return answer}function withDeclaredStructuredContent(descriptor,result,options){const schema=structuredOutputSchemaOf(descriptor);if(!schema||result.isError||elicitationFallbacks.has(result))return result;const{structuredContent}=result;const parsed=declaredStructuredContent(schema,structuredContent);if("error"in parsed){if(resolveStructuredContentValidation({validateStructuredContent:options.validateStructuredContent})==="enforce"){throw parsed.error}options.onInvalidStructuredContent?.();return result}const declared=toStructuredContent(applyUndeclaredKeysPolicy(schema,structuredContent,parsed.declared,options));const sent=JSON.parse(JSON.stringify(structuredContent));if(isSameJson(declared,sent))return result;const content=result.content.map(block=>block.type==="text"&&repeatsJson(block.text,sent)?{...block,text:JSON.stringify(declared)}:block);return{...result,content,structuredContent:declared}}function repeatsJson(text,value){try{return isSameJson(JSON.parse(text),value)}catch{return false}}function isSameJson(left,right){if(left===right)return true;if(Array.isArray(left)||Array.isArray(right)){return Array.isArray(left)&&Array.isArray(right)&&left.length===right.length&&left.every((item,index)=>isSameJson(item,right[index]))}if(!isRecord3(left)||!isRecord3(right))return false;const leftKeys=Object.keys(left);return leftKeys.length===Object.keys(right).length&&leftKeys.every(key=>Object.prototype.hasOwnProperty.call(right,key)&&isSameJson(left[key],right[key]))}function declaredStructuredContent(schema,structuredContent){if(structuredContent===void 0)return{error:new InvalidOutputError({reason:"missing structuredContent"})};try{return{declared:parseDeclaredOutput(schema,structuredContent)}}catch(error){return{error:error instanceof InvalidOutputError?error:new InvalidOutputError}}}function answersObject(schema,lazies=new Set){const def=schema?._zod?.def;if(!def)return false;const type=String(def["type"]);if(type==="object"||type==="record")return true;if(type==="lazy"){return!lazies.has(def)&&answersObject(def["getter"](),new Set([...lazies,def]))}if(type==="pipe")return answersObject(def["in"],lazies);if(type==="union")return def["options"].every(option=>answersObject(option,lazies));if(type==="intersection")return answersObject(def["left"],lazies)&&answersObject(def["right"],lazies);return SHAPE_KEEPING_WRAPPERS.has(type)&&answersObject(def["innerType"],lazies)}function structuredOutputSchemaOf(descriptor){if(descriptor instanceof z61.ZodType)return answersObject(descriptor)?descriptor:void 0;return!Array.isArray(descriptor)&&isZodRawShape2(descriptor)?z61.object(descriptor):void 0}function parseSingleValue(descriptor,value,options,path4){if(typeof descriptor==="string"){switch(descriptor){case"string":if(typeof value!=="string")throw literalMismatch(descriptor,path4);return{blocks:[makePrimitiveTextContent(value)],parsedValue:value,isPrimitive:true};case"number":if(typeof value!=="number")throw literalMismatch(descriptor,path4);return{blocks:[makePrimitiveTextContent(value)],parsedValue:value,isPrimitive:false};case"boolean":if(typeof value!=="boolean")throw literalMismatch(descriptor,path4);return{blocks:[makePrimitiveTextContent(value)],parsedValue:value,isPrimitive:false};case"date":{const dateValue=toValidDate(value);if(!dateValue)throw literalMismatch(descriptor,path4);return makeDateResult(dateValue)}case"image":return{blocks:toContentBlocks(ImageOutputSchema,descriptor,value,path4),isPrimitive:false};case"audio":return{blocks:toContentBlocks(AudioOutputSchema,descriptor,value,path4),isPrimitive:false};case"resource":return{blocks:toContentBlocks(ResourceOutputSchema,descriptor,value,path4),isPrimitive:false};case"resource_link":return{blocks:toContentBlocks(ResourceLinkOutputSchema,descriptor,value,path4),isPrimitive:false};default:return{blocks:[makePrimitiveTextContent(value)],parsedValue:value,isPrimitive:true}}}if(descriptor instanceof ZodString){const stringValue=parseAgainstOutputSchema(descriptor,value);return{blocks:[makePrimitiveTextContent(stringValue)],parsedValue:stringValue,isPrimitive:true}}if(descriptor instanceof ZodNumber||descriptor instanceof ZodBoolean){return{blocks:[makePrimitiveTextContent(value)],parsedValue:parseAgainstOutputSchema(descriptor,value),isPrimitive:false}}if(descriptor instanceof ZodBigInt){return{blocks:[makePrimitiveTextContent(value)],parsedValue:String(parseAgainstOutputSchema(descriptor,value)),isPrimitive:false}}if(descriptor instanceof ZodDate){return makeDateResult(parseAgainstOutputSchema(descriptor,value))}let parsedValue;if(descriptor instanceof z61.ZodType){parsedValue=toStructuredContent(parseAgainstOutputSchema(descriptor,value,options))}else if(isZodRawShape2(descriptor)){parsedValue=toStructuredContent(parseAgainstOutputSchema(z61.object(descriptor),value,options))}else{parsedValue=toStructuredContent(value)}return{blocks:[makeJsonTextContent(parsedValue)],parsedValue,isPrimitive:false}}function parseAgainstOutputSchema(schema,value,options={}){return applyUndeclaredKeysPolicy(schema,value,parseDeclaredOutput(schema,value),options)}function applyUndeclaredKeysPolicy(schema,value,declared,options){const policy=options.undeclaredKeys??"strip";if(policy==="strip"||hasTransform(schema))return declared;const undeclaredKeys=findDroppedKeys(value,declared);if(undeclaredKeys.length===0)return declared;switch(policy){case"keep":{const kept=withUndeclaredKeys(value,declared);const unkeptKeys=findDroppedKeys(value,kept);if(unkeptKeys.length>0){throw new InvalidOutputError({reason:"undeclared keys the outputSchema cannot keep",value:unkeptKeys.join(", ")})}return kept}case"fail":throw new InvalidOutputError({reason:"undeclared keys",value:undeclaredKeys.join(", ")});case"warn":options.onUndeclaredKeys?.(undeclaredKeys);return declared}}function withUndeclaredKeys(original,declared){if(original===declared)return declared;if(Array.isArray(original)&&Array.isArray(declared)){return declared.map((item,index)=>withUndeclaredKeys(original[index],item))}if(!isRecord3(original)||!isRecord3(declared))return declared;const declaredEntries=Object.entries(declared).map(([key,item])=>[key,withUndeclaredKeys(original[key],item)]);const undeclaredEntries=Object.entries(original).filter(([key,item])=>item!==void 0&&!Object.prototype.hasOwnProperty.call(declared,key));return Object.fromEntries([...declaredEntries,...undeclaredEntries])}function isRecord3(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function parseDeclaredOutput(schema,value){const parseResult=schema.safeParse(value);if(parseResult.success){return parseResult.data}const{issues}=parseResult.error;if(issues.every(issue=>isNonFiniteNumberIssue(issue,value))){const withStandIns=issues.reduce((current,issue)=>withValueAt(current,issue.path,finiteStandIn(valueAt(value,issue.path))),value);const retry=schema.safeParse(withStandIns);if(retry.success){return issues.reduce((parsed,issue)=>withValueAt(parsed,issue.path,valueAt(value,issue.path)),retry.data)}}const firstIssue=issues[0];throw new InvalidOutputError({reason:"output does not match outputSchema",path:firstIssue?.path.length?firstIssue.path.join("."):void 0})}function isNonFiniteNumberIssue(issue,root){if(issue.code!=="invalid_type"||issue.expected!=="number"){return false}const valueAtPath=valueAt(root,issue.path);return typeof valueAtPath==="number"&&!Number.isFinite(valueAtPath)}function finiteStandIn(value){return Number.isNaN(value)?0:Math.sign(value)*Number.MAX_VALUE}function valueAt(root,path4){return path4.reduce((node,key)=>typeof node==="object"&&node!==null?node[key]:void 0,root)}function withValueAt(root,path4,replacement){if(path4.length===0){return replacement}const[key,...rest]=path4;const container=Array.isArray(root)?[...root]:{...root};container[key]=withValueAt(container[key],rest,replacement);return container}function isZodRawShape2(descriptor){return typeof descriptor==="object"&&descriptor!==null&&Object.values(descriptor).every(field=>field instanceof z61.ZodType)}function makePrimitiveTextContent(value){return{type:"text",text:value==null?"":String(value)}}function makeJsonTextContent(jsonValue){let text;try{text=JSON.stringify(jsonValue)}catch{text=jsonValue==null?"":String(jsonValue)}return{type:"text",text}}function literalMismatch(literal,path4){return new InvalidOutputError({reason:`output does not match outputSchema '${literal}'`,path:path4})}function toValidDate(value){if(value instanceof Date)return Number.isNaN(value.getTime())?void 0:value;if(typeof value!=="string"&&typeof value!=="number")return void 0;const parsed=new Date(value);return Number.isNaN(parsed.getTime())?void 0:parsed}function makeDateResult(date){const iso=date.toISOString();return{blocks:[makePrimitiveTextContent(iso)],parsedValue:{iso,timeInMilli:date.getTime()},isPrimitive:false}}function toContentBlocks(schema,literal,value,path4){const items=Array.isArray(value)?value:[value];return items.map((item,index)=>{const itemPath=Array.isArray(value)?[path4,index].filter(part=>part!==void 0).join("."):path4;if(!schema.safeParse(item).success)throw literalMismatch(literal,itemPath);return item})}function buildAgentToolDefinition(tool){const parameters=tool.getInputJsonSchema()??{type:"object",properties:{}};return{name:tool.metadata.id??tool.metadata.name,description:tool.metadata.description??"",parameters}}var elicitationFallbacks,SHAPE_KEEPING_WRAPPERS;var init_tool_utils=__esm({"libs/sdk/src/tool/tool.utils.ts"(){"use strict";init_common();init_errors();init_package_specifier();init_content_utils();init_tool_output_policy();elicitationFallbacks=new WeakSet;SHAPE_KEEPING_WRAPPERS=new Set(["readonly","optional","nullable","default","prefault","nonoptional","catch"])}});function isAppOnlyTool(metadata){const ui=metadata._meta?.["ui"];const visibility=typeof ui==="object"&&ui!==null?Reflect.get(ui,"visibility"):void 0;return Array.isArray(visibility)&&!visibility.includes("model")}function knownPlatformOf(...platforms){return platforms.find(platform=>platform!==void 0&&platform!=="unknown")}function rendersAppPages(platformType){return platformType==="ext-apps"||platformType==="openai"}var init_app_only_tools=__esm({"libs/sdk/src/tool/ui/app-only-tools.ts"(){"use strict"}});function withBundlingMode(mode,bundlingMode){if(bundlingMode==="dynamic")return"inline";if(bundlingMode==="static")return BUILT_ONCE_SERVING_MODES.includes(mode)?mode:"static";return mode}function toolServingMode(tool,scope){const own=tool.metadata.ui?.servingMode;if(own!==void 0&&own!=="auto")return own;const bundlingMode=tool.metadata.ui?.bundlingMode;if(own==="auto")return withBundlingMode(own,bundlingMode);const appId=appOwnerIdOf(scope.tools.lineageOf(tool)??[],tool.owner);const app=appId===void 0?void 0:scope.apps.getApps().find(candidate=>candidate.id===appId);const appMode=app?.metadata?.ui?.servingMode;return withBundlingMode(resolveWidgetServingMode(void 0,appMode,scope.metadata.ui?.servingMode),bundlingMode)}var BUILT_ONCE_SERVING_MODES;var init_serving_mode_default=__esm({"libs/sdk/src/tool/ui/serving-mode-default.ts"(){"use strict";init_ui_serving_mode();init_lineage_utils();BUILT_ONCE_SERVING_MODES=["static","hybrid","direct-url","custom-url"]}});function detectUIType(template){if(template===null||template===void 0)return"auto";if(typeof template==="object"&&"file"in template){return/\.(tsx|jsx)$/i.test(template.file)?"react":"auto"}if(typeof template==="function"){if(typeof template.prototype?.render==="function")return"react";if(template["$$typeof"]!==void 0)return"react";if(template.name&&/^[A-Z]/.test(template.name))return"react";return"html"}if(typeof template==="string")return template.includes("<")&&template.includes(">")?"html":"markdown";return"auto"}function isComponentReference(template){if(typeof template==="object"&&template!==null&&"$$typeof"in template)return true;if(typeof template!=="function"||detectUIType(template)!=="react")return false;if(typeof template.prototype?.render==="function")return true;if(template["$$typeof"]!==void 0)return true;return COMPILED_JSX_PATTERN.test(Function.prototype.toString.call(template))}function warnIfComponentReference(toolName,template,logger){if(!isComponentReference(template))return false;const warned2=warnedComponentReferences.get(template)??new Set;if(!warned2.has(toolName)){warned2.add(toolName);warnedComponentReferences.set(template,warned2);logger.warn(`[FrontMCP] Tool "${toolName}": \`ui.template\` is a React component reference, which cannot be bundled (there is no source file to compile), so the widget would render an empty page. Use \`template: { file: './widget.tsx' }\` instead, or set \`ui.uiType: 'react'\` to render it on the server.`)}return true}var COMPILED_JSX_PATTERN,warnedComponentReferences;var init_template_detection=__esm({"libs/sdk/src/tool/ui/template-detection.ts"(){"use strict";COMPILED_JSX_PATTERN=/\b(?:React\.createElement|_?jsx(?:s|DEV)?)\)?\s*\(/;warnedComponentReferences=new WeakMap}});var ui_render_exports={};__export(ui_render_exports,{MCP_APPS_MIME_TYPE:()=>MCP_APPS_MIME_TYPE,buildCDNInfoForUIType:()=>buildCDNInfoForUIType,buildHtmlResponseText:()=>buildHtmlResponseText,buildToolResponseContent:()=>buildToolResponseContent,describeRenderOptionProblems:()=>describeRenderOptionProblems,extractSizing:()=>extractSizing,getUIResourceMimeType:()=>getUIResourceMimeType,isUIRenderFailure:()=>isUIRenderFailure,pageCsp:()=>pageCsp,prepareRenderOptions:()=>prepareRenderOptions,renderToolTemplate:()=>renderToolTemplate,resolveServingMode:()=>resolveServingMode,warnIfComponentReference:()=>warnIfComponentReference2});import{buildCDNInfoForUIType,buildHtmlResponseText,buildToolResponseContent,describeRenderOptionProblems,isUIRenderFailure,MCP_APPS_MIME_TYPE,prepareRenderOptions,renderToolTemplate,resolveServingMode,warnIfComponentReference as warnIfComponentReference2}from"@frontmcp/uipack/adapters";import{validateCSPDomain}from"@frontmcp/uipack/shell";function extractSizing(uiConfig){if(!uiConfig)return void 0;const sizing={};let has=false;if(uiConfig["preferredHeight"]!==void 0){sizing.preferredHeight=uiConfig["preferredHeight"];has=true}if(uiConfig["minHeight"]!==void 0){sizing.minHeight=uiConfig["minHeight"];has=true}if(uiConfig["maxHeight"]!==void 0){sizing.maxHeight=uiConfig["maxHeight"];has=true}if(uiConfig["aspectRatio"]!==void 0){sizing.aspectRatio=uiConfig["aspectRatio"];has=true}if(uiConfig["autoResize"]!==void 0){sizing.autoResize=uiConfig["autoResize"];has=true}return has?sizing:void 0}function pageCsp(uiConfig){const csp=uiConfig?.["csp"];if(!csp)return void 0;const listable=domains=>Array.isArray(domains)?domains.filter(domain=>typeof domain==="string"&&validateCSPDomain(domain)):void 0;return{connectDomains:listable(csp.connectDomains),resourceDomains:listable(csp.resourceDomains)}}function getUIResourceMimeType(_platformOrUri){if(_platformOrUri?.endsWith(".js"))return"application/javascript";if(_platformOrUri?.endsWith(".css"))return"text/css";return MCP_APPS_MIME_TYPE}var init_ui_render=__esm({"libs/sdk/src/tool/ui/ui-render.ts"(){"use strict"}});function hasUIConfig(tool){if(typeof tool!=="object"||tool===null)return false;const metadata=tool["ui"];return metadata!==void 0&&metadata!==null}function renderOptions(uiConfig){const runtimeOptions=uiConfig?.["runtimeOptions"];return{contentSecurity:uiConfig?.["contentSecurity"],markdown:runtimeOptions?.markdown,mdxComponents:uiConfig?.["mdxComponents"],uiType:uiConfig?.["uiType"],hydrate:uiConfig?.["hydrate"]??runtimeOptions?.hydrate}}function isUIResourceUri(uri){return uri.startsWith("ui://")}function isStaticWidgetUri(uri){return uri.startsWith("ui://widget/")}function parseWidgetUri(uri){const match=uri.match(WIDGET_URI_PATTERN);if(!match)return null;const toolName=decodeWidgetToolName(match[1]);if(toolName===null||!WIDGET_TOOL_NAME_PATTERN.test(toolName))return null;return{toolName,extension:match[2]}}function decodeWidgetToolName(segment){try{return decodeURIComponent(segment)}catch{return null}}function buildStaticWidgetUri(toolName){return`ui://widget/${encodeURIComponent(toolName)}.html`}var WIDGET_CALL_META_KEY,ToolUIRegistry,WIDGET_URI_PATTERN,WIDGET_TOOL_NAME_PATTERN;var init_ui_shared=__esm({"libs/sdk/src/tool/ui/ui-shared.ts"(){"use strict";init_mcp_error();init_tool_ui_errors();init_template_detection();WIDGET_CALL_META_KEY="frontmcp/widgetCall";ToolUIRegistry=class{widgets=new Map;manifests=new Map;resourceMeta=new Map;uiTools=new Set;customUris=new Map;widgetUrls=new Map;resolver;options;renderer;constructor(resolver,options={}){this.resolver=resolver;this.options=options}stringResultOptions(uiConfig){const toolSetting=uiConfig?.["escapeStringResults"];return{escapeStringResults:typeof toolSetting==="boolean"?toolSetting:this.options.escapeStringResults,logger:this.options.logger}}registerTool(toolName,resourceUri){this.uiTools.add(toolName);if(resourceUri)this.customUris.set(resourceUri,toolName)}async load(){this.renderer??=await Promise.resolve().then(()=>(init_ui_render(),ui_render_exports))}get loadedRenderer(){if(!this.renderer){throw new InternalMcpError("The tool UI renderer is used before ToolUIRegistry.load()","TOOL_UI_NOT_LOADED")}return this.renderer}checkTemplate(toolName,template,uiType){if(uiType==="react")return;const warnIfComponent=this.renderer?.warnIfComponentReference??warnIfComponentReference;warnIfComponent(toolName,template,this.options.logger??console)}async checkRenderOptions(toolName,uiConfig){if(!uiConfig)return;await this.load();const{describeRenderOptionProblems:describeRenderOptionProblems2,prepareRenderOptions:prepareRenderOptions2}=this.loadedRenderer;const template=uiConfig["template"];const problems=describeRenderOptionProblems2(template,renderOptions(uiConfig));if(problems.length>0)throw new ToolUiConfigurationError(toolName,problems);try{await prepareRenderOptions2(template,renderOptions(uiConfig))}catch(error){throw new ToolUiConfigurationError(toolName,[error instanceof Error?error.message:String(error)])}}registerWidgetUrl(toolName,source){this.widgetUrls.set(toolName,source)}getWidgetUrl(toolName){return this.widgetUrls.get(toolName)}widgetRoutes(){return[...this.widgetUrls].flatMap(([toolName,source])=>source.servingMode==="direct-url"?[{toolName,path:source.path}]:[])}resolveCustomUri(uri){return this.customUris.get(uri)}holdsWidgetUri(uri){return isStaticWidgetUri(uri)||this.customUris.has(uri)}hasWidget(uri){const toolName=this.resolveCustomUri(uri)??parseWidgetUri(uri)?.toolName;return toolName!==void 0&&this.hasTool(toolName)}hasTool(name59){const known=n=>this.uiTools.has(n)||this.widgets.has(n)||this.resourceMeta.has(n);if(known(name59))return true;const sep=name59.indexOf(":");return sep>0&&known(name59.slice(sep+1))}getStaticWidget(name59){return this.widgets.get(name59)}hasAny(){return this.widgets.size>0}getManifest(toolName){return this.manifests.get(toolName)}getResourceMeta(toolName){return this.resourceMeta.get(toolName)}detectUIType(template,uiConfig){if(typeof uiConfig?.uiType==="string"&&uiConfig.uiType!=="auto")return uiConfig.uiType;if(typeof template==="string"&&uiConfig?.mdxComponents)return"mdx";return detectUIType(template)}async compileStaticWidgetAsync(options){const toolName=options["toolName"];const template=options["template"];const input=options["input"];const output=options["output"];const uiConfig=options["uiConfig"];const resourceMode=uiConfig?.["resourceMode"]??options["resourceMode"];if(!toolName)return;this.updateResourceMetaFromConfig(toolName,uiConfig);if(!template)return;await this.load();const{renderToolTemplate:renderToolTemplate2,extractSizing:extractSizing2,pageCsp:pageCsp2}=this.loadedRenderer;const result=renderToolTemplate2({toolName,input,output,template,resolver:this.resolver,resourceMode,sizing:extractSizing2(uiConfig),displayMode:uiConfig?.["displayMode"],csp:pageCsp2(uiConfig),...this.stringResultOptions(uiConfig),...renderOptions(uiConfig)});this.widgets.set(toolName,result.html);this.manifests.set(toolName,{uiType:result.uiType,hash:result.hash,size:result.size})}updateResourceMetaFromConfig(toolName,uiConfig){const resourceMeta={csp:uiConfig?.["csp"],permissions:uiConfig?.["permissions"],prefersBorder:uiConfig?.["prefersBorder"],domain:uiConfig?.["sandboxDomain"],description:uiConfig?.["widgetDescription"]};if(Object.values(resourceMeta).some(value=>value!==void 0)){this.resourceMeta.set(toolName,resourceMeta)}else{this.resourceMeta.delete(toolName)}}async compileLeanWidgetAsync(options){await this.compileStaticWidgetAsync(options)}async compileHybridWidgetAsync(options){await this.load();try{await this.compileStaticWidgetAsync(options)}catch{const toolName=options["toolName"];const template=options["template"];if(toolName&&template){const uiType=this.detectUIType(template,options["uiConfig"]);this.manifests.set(toolName,{uiType,hash:"",size:0})}}}buildHybridComponentPayload(options){const toolName=options["toolName"];if(!toolName)return void 0;const manifest=this.manifests.get(toolName);if(!manifest)return void 0;return{type:manifest["uiType"],hash:manifest["hash"],toolName}}async renderAndRegisterAsync(options){const toolName=options["toolName"];const uiConfig=options["uiConfig"];const template=uiConfig?.["template"];const input=options["input"]??{};const output=options["output"]??{};const platformType=options["platformType"];const resourceMode=uiConfig?.["resourceMode"];if(!toolName||!template){return{meta:{}}}this.updateResourceMetaFromConfig(toolName,uiConfig);await this.load();const{renderToolTemplate:renderToolTemplate2,extractSizing:extractSizing2,pageCsp:pageCsp2}=this.loadedRenderer;const result=renderToolTemplate2({toolName,input,output,template,platformType,resolver:this.resolver,resourceMode,sizing:extractSizing2(uiConfig),displayMode:uiConfig?.["displayMode"],csp:pageCsp2(uiConfig),...this.stringResultOptions(uiConfig),...renderOptions(uiConfig)});return{meta:result.meta}}};WIDGET_URI_PATTERN=/^ui:\/\/widget\/([A-Za-z0-9_.:@%/-]+)\.(html|js|css)$/;WIDGET_TOOL_NAME_PATTERN=/^[A-Za-z0-9_.:@/-]+$/}});import{hasTransform as hasTransform2}from"@frontmcp/lazy-zod";function findUndeclaredArguments(shape,sent,parsed){const dropped=new Map;const walk=(source,target,path4)=>{if(source===target)return;if(Array.isArray(source)){source.forEach((item,index)=>walk(item,Array.isArray(target)?target[index]:void 0,[...path4,"[]"]));return}if(!isPlainRecord(source))return;const targetRecord=isPlainRecord(target)?target:{};for(const[key,value]of Object.entries(source)){if(value===void 0)continue;const keyPath=[...path4,key];if(!Object.prototype.hasOwnProperty.call(targetRecord,key))dropped.set(JSON.stringify(keyPath),keyPath);else if(path4.length>0||!hasTransform2(shape[key]))walk(value,targetRecord[key],keyPath)}};walk(sent,parsed,[]);return[...dropped.values()].sort((left,right)=>formatKeyPath(left).localeCompare(formatKeyPath(right)))}function formatKeyPath(keyPath){return keyPath.reduce((text,segment)=>segment==="[]"?`${text}[]`:text?`${text}.${segment}`:segment,"")}function isPlainRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}var init_undeclared_arguments=__esm({"libs/sdk/src/tool/undeclared-arguments.ts"(){"use strict"}});import{AUTH_PROVIDERS_ACCESSOR,CREDENTIALS_ACCESSOR}from"@frontmcp/auth";import{internalZ as z62}from"@frontmcp/lazy-zod";function isAuthProvidersLike(v){return typeof v==="object"&&v!==null&&typeof v.get==="function"}function isCredentialsLike(v){return typeof v==="object"&&v!==null&&typeof v.requireConnect==="function"}async function evaluateToolCredentialGate(providers,tryGet){const required=providers.filter(p=>p.required);if(required.length===0){return{evaluated:true,missing:[]}}const authProviders=resolveAccessor(tryGet,AUTH_PROVIDERS_ACCESSOR,isAuthProvidersLike);const credentials=resolveAccessor(tryGet,CREDENTIALS_ACCESSOR,isCredentialsLike);if(!authProviders&&!credentials){return{evaluated:false,missing:[]}}const missing=[];for(const provider of required){const missingProvider=await missingProviderOf(provider.name,authProviders,credentials);if(missingProvider)missing.push(missingProvider)}return{evaluated:true,missing}}function resolveAccessor(tryGet,token,guard){const value=tryGet(token);return guard(value)?value:void 0}async function missingProviderOf(name59,authProviders,credentials){if(authProviders){try{const resolved=await authProviders.get(name59);if(resolved){return void 0}}catch{}}if(credentials){try{const res=await credentials.requireConnect({key:name59});if(res.connected){return void 0}return{name:name59,...res.resumeUrl?{authUrl:res.resumeUrl}:{},...res.signInRequired?{signInRequired:true}:{}}}catch{return{name:name59}}}return{name:name59}}function credentialsRequiredErrorOf(toolId,missing){return new ToolCredentialsRequiredError({toolId,providers:missing.map(provider=>provider.name),authUrl:missing.find(provider=>provider.authUrl)?.authUrl,signInRequired:missing.some(provider=>provider.signInRequired)})}async function askToOpenConnectPages(ask,missing){const everyProviderHasPage=missing.every(provider=>provider.authUrl);if(!ask.elicitationEnabled||!everyProviderHasPage||!clientTakesUrlElicitation(ask))return false;for(const provider of missing){try{const answer=await performElicit({sessionId:ask.context?.sessionId,getClientCapabilities:ask.getClientCapabilities,tryGetContext:()=>ask.context,entryName:ask.toolId,entryInput:ask.toolInput,elicitationEnabled:ask.elicitationEnabled,signal:ask.signal,inputKey:`connect-${provider.name}`},`Connect ${provider.name} to continue: tool "${ask.toolId}" needs it.`,z62.object({}),{mode:"url",url:provider.authUrl});if(answer.status!=="accept")return false}catch(error){if(error instanceof InputRequiredSignal)throw error;return false}}return true}function clientTakesUrlElicitation(ask){const exchange=ask.context?.getMrtrExchange?.();if(exchange)return exchange.supportsElicitation?.("url")===true;const sessionId=ask.context?.sessionId;return sessionId!==void 0&&supportsElicitation(ask.getClientCapabilities(sessionId),"url")}var init_tool_credentials_gate=__esm({"libs/sdk/src/tool/flows/tool-credentials.gate.ts"(){"use strict";init_elicit_helper();init_errors();init_notification()}});var undeclared_arguments_message_exports={};__export(undeclared_arguments_message_exports,{describeUndeclaredArguments:()=>describeUndeclaredArguments,undeclaredArgumentsNote:()=>undeclaredArgumentsNote,undeclaredArgumentsRefusal:()=>undeclaredArgumentsRefusal,undeclaredArgumentsWarning:()=>undeclaredArgumentsWarning});function undeclaredArgumentsRefusal(keyPaths,declaredKeys){return`Unknown arguments: ${describeUndeclaredArguments(keyPaths,declaredKeys)}`}function undeclaredArgumentsNote(keyPaths,declaredKeys){return`These arguments are not declared and were ignored: ${describeUndeclaredArguments(keyPaths,declaredKeys)}.`}function undeclaredArgumentsWarning(toolName,newKeyPaths){return`Tool "${toolName}" was called with arguments its inputSchema does not declare, so they were ignored: ${namedWithTheRestCounted(newKeyPaths.map(shortened))}. Declare them, or set input.undeclaredKeys to 'strip' or 'fail'.`}function describeUndeclaredArguments(keyPaths,declaredKeys){const described=keyPaths.slice(0,MAX_NAMED_ARGUMENTS).map(keyPath=>{const shown=shortened(formatKeyPath(keyPath));const closest=keyPath.length===1?closestKey(keyPath[0],declaredKeys):void 0;return closest?`'${shown}' (did you mean '${closest}'?)`:`'${shown}'`});return namedWithTheRestCounted(described,keyPaths.length)}function namedWithTheRestCounted(names,total=names.length){const named=names.slice(0,MAX_NAMED_ARGUMENTS);const unnamed=total-named.length;return unnamed>0?`${named.join(", ")} and ${unnamed} more`:named.join(", ")}function shortened(text){return text.length>MAX_KEY_LENGTH?`${text.slice(0,MAX_KEY_LENGTH)}\u2026`:text}function closestKey(key,declaredKeys){if(key.length>MAX_KEY_LENGTH)return void 0;const candidates=declaredKeys.slice(0,MAX_COMPARED_KEYS).filter(candidate=>candidate.length<=MAX_KEY_LENGTH);let closest;for(const candidate of candidates){const distance=editDistance(key.toLowerCase(),candidate.toLowerCase());if(!closest||distance<closest.distance)closest={candidate,distance}}if(!closest)return void 0;return closest.distance*2<=Math.max(key.length,closest.candidate.length)?closest.candidate:void 0}function editDistance(source,target){const row=Array.from({length:target.length+1},(_,index)=>index);for(let sourceIndex=1;sourceIndex<=source.length;sourceIndex++){let diagonal=row[0];row[0]=sourceIndex;for(let targetIndex=1;targetIndex<=target.length;targetIndex++){const above=row[targetIndex];const substitution=diagonal+(source[sourceIndex-1]===target[targetIndex-1]?0:1);row[targetIndex]=Math.min(above+1,row[targetIndex-1]+1,substitution);diagonal=above}}return row[target.length]}var MAX_NAMED_ARGUMENTS,MAX_KEY_LENGTH,MAX_COMPARED_KEYS;var init_undeclared_arguments_message=__esm({"libs/sdk/src/tool/undeclared-arguments-message.ts"(){"use strict";init_undeclared_arguments();MAX_NAMED_ARGUMENTS=20;MAX_KEY_LENGTH=64;MAX_COMPARED_KEYS=200}});import{AuthorityDeniedError as AuthorityDeniedError3,resolveRequiredScopes as resolveRequiredScopes2,signIncrementalAuthTicket}from"@frontmcp/auth";import{ExecutionTimeoutError,withTimeout}from"@frontmcp/guard";import{internalZ as z63}from"@frontmcp/lazy-zod";import{CallToolRequestSchema as CallToolRequestSchema2,CallToolResultSchema as CallToolResultSchema2}from"@frontmcp/protocol";import{awaitOutsideRequest as awaitOutsideRequest4,escapeControlCharacters as escapeControlCharacters2,findNonFiniteNumber,getRuntimeContext as getRuntimeContext4,isDebug,isDevelopment as isDevelopment2,randomUUID as randomUUID11}from"@frontmcp/utils";function htmlResponsePrefixFor(ui,platformType){const prefix=ui?.htmlResponsePrefix;return typeof prefix==="string"&&platformType==="claude"?prefix:void 0}function isWidgetCall(requestMeta){return typeof requestMeta==="object"&&requestMeta!==null&&Reflect.get(requestMeta,WIDGET_CALL_META_KEY)===true}function unreportedKeyPaths(reported,tool,keyPaths){const reportedKeyPaths=reported.get(tool)??new Set;reported.set(tool,reportedKeyPaths);const roomLeft=MAX_REPORTED_UNDECLARED_KEY_PATHS-reportedKeyPaths.size;const newKeyPaths=keyPaths.filter(keyPath=>!reportedKeyPaths.has(keyPath)).slice(0,roomLeft);newKeyPaths.forEach(keyPath=>reportedKeyPaths.add(keyPath));return newKeyPaths}function declaredOutput(tool,output,undeclaredKeys){if(!tool?.outputSchema||typeof output!=="object"||output===null||Array.isArray(output))return output;const parsed=tool.safeParseOutput(output,{undeclaredKeys});if(!parsed.success)return output;if(isReturnedCallToolResult(tool.outputSchema,output))return parsed.data;const structured=parsed.data.structuredContent;return typeof structured==="object"&&structured!==null&&!Array.isArray(structured)?structured:output}var inputSchema,outputSchema,stateSchema,plan,name,toolClassHooksJoin,Stage,resolvedTools,reportedUndeclaredKeyPaths,reportedInvalidStructuredContent,reportedUndeclaredArguments,reportedUnfittedTools,loggedAliasCalls,MAX_REPORTED_UNDECLARED_KEY_PATHS,CallToolFlow;var init_call_tool_flow=__esm({"libs/sdk/src/tool/flows/call-tool.flow.ts"(){"use strict";init_answer();init_lazy_placeholders();init_remote_capabilities_utils();init_authorized_apps_utils();init_consent_utils();init_public_access_utils();init_authorities_not_configured();init_common();init_availability();init_input_policy();init_tool_metadata();init_tool_lookup_utils();init_call_surface();init_running_tool();init_helpers();init_fallback_helper();init_errors();init_resolved_entries();init_entry_class_hooks();init_hooks_utils();init_flow_context_providers();init_skill_mode_utils();init_surface();init_task_id();init_task_notifier();init_task_types();init_abort_utils();init_lineage_utils();init_tool_output_policy();init_tool_utils();init_app_only_tools();init_serving_mode_default();init_ui_shared();init_undeclared_arguments();init_tool_credentials_gate();inputSchema=z63.object({request:CallToolRequestSchema2,ctx:z63.any()});outputSchema=CallToolResultSchema2;stateSchema=z63.object({input:z63.looseObject({name:z63.string().min(1).max(64),arguments:z63.looseObject({}).optional()}),authInfo:z63.any().optional(),tool:z63.instanceof(ToolEntry),toolContext:z63.instanceof(ToolContext),rawOutput:z63.any().optional(),output:outputSchema,flowError:z63.instanceof(Error).optional(),uiResult:z63.any().optional(),uiMeta:z63.record(z63.string(),z63.unknown()).optional(),undeclaredArgumentsNote:z63.string().optional(),resultMeta:z63.record(z63.string(),z63.unknown()).optional(),progressToken:z63.union([z63.string(),z63.number()]).optional(),jsonRpcRequestId:z63.union([z63.string(),z63.number()]).optional(),semaphoreTicket:z63.any().optional(),executionAbort:z63.instanceof(AbortController).optional(),abandonedExecution:z63.instanceof(Promise).optional(),taskRequest:z63.object({ttl:z63.number().int().positive().nullish()}).passthrough().optional()});plan={pre:["parseInput","checkSkillsOnlyMode","ensureRemoteCapabilities","checkSurface","findTool","useToolHooks","checkEnabled","checkAppLoaded","checkPublicAccess","checkToolAuthorization","checkEntryAuthorities","createTaskIfRequested","createToolCallContext","checkToolCredentials","acquireQuota","acquireSemaphore"],execute:["validateInput","execute","validateOutput"],finalize:["releaseSemaphore","releaseQuota","applyUI","finalize","fitAnswer","shapeAnswer","meterAnswer"]};name="tools:call-tool";toolClassHooksJoin=entryClassHooksJoin({flow:name,plan,contextStage:"createToolCallContext"});({Stage}=FlowHooksOf(name));resolvedTools=new ResolvedEntries;reportedUndeclaredKeyPaths=new WeakMap;reportedInvalidStructuredContent=new WeakSet;reportedUndeclaredArguments=new WeakMap;reportedUnfittedTools=new WeakSet;loggedAliasCalls=new WeakMap;MAX_REPORTED_UNDECLARED_KEY_PATHS=100;CallToolFlow=class extends FlowBase{static async resolveHookOwnerId(rawInput,scope){const toolName=rawInput?.request?.params?.name;if(typeof toolName!=="string")return void 0;let tool=lookupTool(scope,toolName);if(!tool){await loadRemoteAppCapabilities(scope);tool=lookupTool(scope,toolName)}if(tool&&await loadAppOfPlaceholder(scope,tool))tool=lookupTool(scope,toolName);if(!tool)return void 0;resolvedTools.remember(rawInput,toolName,tool);return hookOwnerIdOf(scope.tools.lineageOf(tool)??[],tool.owner)}static resolveHookEntryClass(rawInput,scope){const toolName=rawInput?.request?.params?.name;if(typeof toolName!=="string")return void 0;return(resolvedTools.peek(rawInput,toolName)??lookupTool(scope,toolName))?.record.provide}logger=this.scopeLogger.child("CallToolFlow");declaredUiOutput;get toolName(){return this.state.tool?.name??(this.state.input??this.input.request.params).name}get toolInput(){return(this.state.input??this.input.request.params).arguments}async parseInput(){this.logger.verbose("parseInput:start");let method;let params;let ctx;try{const inputData=inputSchema.parse(this.rawInput);method=inputData.request.method;params=inputData.request.params;ctx=inputData.ctx}catch(e){throw new InvalidInputError("Invalid Input",e instanceof z63.ZodError?e.issues:void 0)}if(method!=="tools/call"){this.logger.warn(`parseInput: invalid method "${method}"`);throw new InvalidMethodError(method,"tools/call")}const progressToken=params._meta?.progressToken;const jsonRpcRequestId=ctx.requestId;const taskRequest=params.task&&typeof params.task==="object"?params.task:void 0;this.state.set({input:params,authInfo:ctx.authInfo,progressToken,jsonRpcRequestId,taskRequest});this.logger.verbose("parseInput:done")}async checkSkillsOnlyMode(){if(!this.isClientCall())return;if(!isSkillsOnlyRequest(this.state.authInfo,this.tryGetContext()))return;const{name:name59}=this.state.required.input;this.logger.verbose(`checkSkillsOnlyMode: refusing tool "${escapeControlCharacters2(name59)}" in skills-only mode`);throw new ToolNotFoundError(name59)}async ensureRemoteCapabilities(){this.logger.verbose("ensureRemoteCapabilities:start");const remoteAppCount=await loadRemoteAppCapabilities(this.scope,(appId,error)=>this.logger.warn(`Failed to load capabilities for remote app ${appId}: ${error.message}`));this.logger.verbose(`ensureRemoteCapabilities:done (${remoteAppCount} remote app(s))`)}async checkSurface(){const sessionId=this.state.authInfo?.sessionId;const surface=this.scope.surface;const callerCtx=this.input.ctx;if(!surface||!sessionId||callerCtx?.taskId||!this.isClientCall()||!surface.isStale(sessionId))return;const{name:name59}=this.state.required.input;const tool=resolvedTools.peek(this.rawInput,name59)??lookupTool(this.scope,name59);const callable=tool!==void 0&&resolveToolVisibility(tool.metadata)!=="internal"&&isOfferedOnSurface(tool.metadata.availableWhen,callSurfaceOf(this.input.ctx));if(callable&&await isEntryEnabled(tool.metadata.enabled,this.tryGetContext(),this.logger))return;this.logger.verbose(`checkSurface: "${escapeControlCharacters2(name59)}" is not in the tool list that replaced this session's`);surface.refreshSession(sessionId);throw new StaleToolListError(name59)}async findTool(){this.logger.verbose("findTool:start");const{name:name59}=this.state.required.input;const tool=resolvedTools.take(this.rawInput,name59)??lookupTool(this.scope,name59);const exactNames=[name59,ownerQualifiedName(name59)];if(tool&&toolAliasesOf(tool).includes(name59)){this.logAliasCall(tool,name59)}else if(tool&&!exactNames.includes(tool.fullName)&&!exactNames.includes(tool.name)){const[,alias]=toolNameCandidates(name59);this.logger.warn(`findTool: tool "${name59}" resolved via legacy name alias to "${alias}". Update callers to use "${alias}" \u2014 the alias will be removed in a future release.`)}const callSurface=callSurfaceOf(this.input.ctx);if(!tool){const allUnfiltered=this.scope.tools.listAllInstances();const unavailable=allUnfiltered.find(t=>exactNames.includes(t.fullName)||exactNames.includes(t.name)||toolAliasesOf(t).includes(name59));if(unavailable&&isOfferedOnSurface(unavailable.metadata.availableWhen,callSurface)){const error=entryUnavailableError("Tool",name59,unavailable.metadata.availableWhen,callSurface);const ctx=getRuntimeContext4();this.logger.warn(`findTool: tool "${name59}" exists but is unavailable \u2014 constraint=${JSON.stringify(unavailable.metadata.availableWhen)}, missingAxes=${JSON.stringify(error.missingAxes)}, current=[os=${ctx.os}, runtime=${ctx.runtime}, deployment=${ctx.deployment}, provider=${ctx.provider}, target=${ctx.target}, surface=${callSurface??"none"}, env=${ctx.env}]`);throw error}this.logger.warn(`findTool: tool "${escapeControlCharacters2(name59)}" not found`);throw new ToolNotFoundError(name59)}if(!isOfferedOnSurface(tool.metadata.availableWhen,callSurface)){this.logger.warn(`findTool: tool "${name59}" is not offered on surface "${callSurface}"`);throw new ToolNotFoundError(name59)}const ctxObj=this.input.ctx;const visibility=resolveToolVisibility(tool.metadata);if(visibility==="internal"&&!ctxObj?.internalCall){this.logger.warn(`findTool: rejecting external tools/call for internal tool "${name59}"`);throw new ToolNotFoundError(name59)}const isTaskRun=Boolean(ctxObj?.taskId);if(isAppOnlyTool(tool.metadata)&&this.isClientCall()&&!isTaskRun&&!rendersAppPages(this.appPagePlatform())){this.logger.warn(`findTool: rejecting tools/call of "${name59}", a tool for the MCP Apps page only`);throw new ToolNotFoundError(name59)}this.logger=this.logger.child(`CallToolFlow(${name59})`);this.state.set("tool",tool);this.logger.verbose(`findTool: tool "${name59}" found`);this.logger.verbose("findTool:done")}async useToolHooks(){const{tool}=this.state;if(!tool)return;await this.useEntryHooks(hookOwnerIdOf(this.scope.tools.lineageOf(tool)??[],tool.owner),tool.record.provide)}async checkEnabled(){const{tool}=this.state.required;await assertEntryEnabled("Tool",tool.name,tool.metadata.enabled,this.tryGetContext(),this.logger)}async checkAppLoaded(){assertAppLoaded(this.state.required.tool)}logAliasCall(tool,alias){const loggedAliases=loggedAliasCalls.get(tool)??new Set;if(loggedAliases.has(alias))return;loggedAliases.add(alias);loggedAliasCalls.set(tool,loggedAliases);this.logger.info(`findTool: tool "${alias}" is an alias of "${tool.name}"; call "${tool.name}" instead.`)}async createTaskIfRequested(){this.logger.verbose("createTaskIfRequested:start");const{tool}=this.state.required;const taskRequest=this.state.taskRequest;const taskSupport=tool.metadata.execution?.taskSupport;const toolName=tool.fullName||tool.metadata.name;const ctx=this.input.ctx;if(ctx?.taskId){this.logger.verbose("createTaskIfRequested:skip (internal task re-dispatch)");return}if(taskRequest&&(!taskSupport||taskSupport==="forbidden")){throw new TaskAugmentationNotSupportedError(toolName)}if(!taskRequest&&taskSupport==="required"){throw new TaskAugmentationRequiredError(toolName)}if(!taskRequest){this.logger.verbose("createTaskIfRequested:skip (non-task call)");return}const store=this.scope.taskStore;const registry=this.scope.tasks;if(!store||!registry){throw new TaskStoreNotInitializedError}const authInfo=this.state.authInfo;const sessionId=authInfo?.sessionId;if(!sessionId){throw new InternalMcpError("Task-augmented tools/call requires an identified session","TASK_SESSION_REQUIRED")}const config=registry.getConfig();const rawTtlValue=taskRequest["ttl"];const rawTtl=rawTtlValue===null?null:typeof rawTtlValue==="number"?rawTtlValue:void 0;const maxTtl=config.maxTtlMs??TASK_DEFAULTS.maxTtlMs;const defaultTtl=config.defaultTtlMs??TASK_DEFAULTS.defaultTtlMs;const ttlMs=rawTtl===null?maxTtl:rawTtl===void 0?defaultTtl:Math.min(rawTtl,maxTtl);const pollIntervalMs=config.defaultPollIntervalMs??TASK_DEFAULTS.defaultPollIntervalMs;const now=Date.now();const nowIso=new Date(now).toISOString();const taskId=generateTaskId();const expiresAt=now+ttlMs;const cleanedParams={...this.state.required.input};delete cleanedParams["task"];const record={taskId,sessionId,status:"working",statusMessage:"The operation is now in progress.",createdAt:nowIso,lastUpdatedAt:nowIso,ttlMs,pollIntervalMs,expiresAt,request:{method:"tools/call",params:cleanedParams},scopeId:this.scope.id};const callSurface=callSurfaceOf(this.input.ctx);if(callSurface!==void 0)record.surface=callSurface;if(this.state.progressToken!==void 0){record.progressToken=this.state.progressToken}const maxActive=config.maxConcurrentPerSession??TASK_DEFAULTS.maxConcurrentPerSession;if(!await store.createWithinLimit(record,maxActive)){throw new TaskConcurrencyLimitError(maxActive)}const notifier=new TaskNotifier(this.scope.notifications,this.logger);notifier.sendStatus(record);const runner=registry.runner;if(!runner){throw new InternalMcpError("Task runner is not configured \u2014 scope initialization did not set one","TASK_RUNNER_MISSING")}try{await runner.run(record,{cleanedRequestParams:cleanedParams,ctx:this.input.ctx})}catch(err){this.logger.error("createTaskIfRequested: runner.run threw",{taskId,error:err instanceof Error?err.message:String(err)});try{await store.update(taskId,sessionId,{status:"failed",statusMessage:"Task runner failed to schedule execution"})}catch(bookkeepingErr){this.logger.warn("createTaskIfRequested: failed to mark task failed after runner error",{taskId,sessionId,error:bookkeepingErr instanceof Error?bookkeepingErr.message:String(bookkeepingErr)})}throw err}const createTaskResult={task:toWireShape(record),_meta:{"io.modelcontextprotocol/related-task":{taskId}}};this.logger.info("createTaskIfRequested: task created, responding with CreateTaskResult",{taskId,tool:toolName});this.respond(createTaskResult)}async checkPublicAccess(){const{tool,authInfo}=this.state;const callerCtx=this.input.ctx;const publicAccess=publicAccessFor(this.scope.auth?.options,authInfo);if(!tool||!publicAccess||callerCtx?.internalCall||callerCtx?.agentPrivateCall)return;if(callerCtx?.taskId)return;await enforcePublicAccess(publicAccess,{kind:"tool",names:[tool.fullName||tool.name,tool.name]},this.scope.publicAccessGuard,buildPartitionContext(this.tryGetContext()))}async checkToolAuthorization(){this.logger.verbose("checkToolAuthorization:start");const{tool,authInfo}=this.state;const consentCtx=this.input.ctx;if(!consentCtx?.internalCall&&!consentCtx?.agentPrivateCall){const consentedToolIds=getConsentedToolIds(authInfo);if(consentedToolIds&&tool){const bareNameCount=this.scope.tools.getTools(true).filter(t=>t.name===tool.name).length;const consented=bareNameCount>1?isToolConsented(consentedToolIds,tool.fullName):isToolConsented(consentedToolIds,tool.name,tool.fullName);if(!consented){this.logger.info(`checkToolAuthorization: tool "${tool.fullName||tool.name}" not in consented set \u2014 rejecting`);throw new ToolNotConsentedError(tool.fullName||tool.name)}}}const claimAuthorizedApps=getAuthorizedAppIds(authInfo);const legacyAuthorization=authInfo?.extra?.["authorization"];if(!claimAuthorizedApps&&!legacyAuthorization){const incrementalEnabled=!consentCtx?.internalCall&&!!authInfo?.token&&this.scope.auth?.options?.incrementalAuth?.enabled===true;if(!incrementalEnabled){this.logger.verbose("checkToolAuthorization:skip (no auth context)");return}this.logger.warn("checkToolAuthorization: incrementalAuth enabled but the verified token carries no authorized_apps claim \u2014 failing closed")}const appId=!tool||isServerEntryOwner(tool.owner)?void 0:this.grantingAppIdOf(tool);if(!appId){this.logger.verbose("checkToolAuthorization:skip (no app owner)");return}const isAppAuthorized=(claimAuthorizedApps?.has(appId)??false)||(legacyAuthorization?.authorizedAppIds?.includes(appId)??false)||appId in(legacyAuthorization?.authorizedApps||{});if(!isAppAuthorized){const apps=this.scope.apps.getApps();const app=apps.find(a=>a.metadata.id===appId);const authOptions=this.scope.auth?.options;let skippedBehavior="anonymous";if(authOptions&&isOrchestratedMode(authOptions)){const incrementalConfig=authOptions.incrementalAuth;if(incrementalConfig){if(incrementalConfig.enabled===false){skippedBehavior="require-auth"}else{skippedBehavior=incrementalConfig.skippedAppBehavior||"anonymous"}}}if(skippedBehavior==="anonymous"&&app?.metadata?.auth?.mode==="public"){this.logger.verbose(`checkToolAuthorization: using anonymous for ${appId}`);return}const authUrl=this.buildProgressiveAuthUrl(appId,tool?.fullName||"",authInfo,claimAuthorizedApps);const requiredScopes=normalizeToolAuthProviders(tool?.metadata?.authProviders).flatMap(provider=>provider.scopes??[]);this.logger.info(`checkToolAuthorization: authorization required for app "${appId}"`);throw new AuthorizationRequiredError({appId,toolId:tool?.fullName||tool?.name||"unknown",authUrl,requiredScopes:requiredScopes.length>0?[...new Set(requiredScopes)]:void 0,message:`Authorization required for ${appId}. Please authorize to use ${tool?.fullName||tool?.name}.`})}this.logger.verbose("checkToolAuthorization:done")}grantingAppIdOf(tool){const{owner}=tool;if(owner?.kind!=="plugin"&&owner?.kind!=="adapter")return owner?.id;return appOwnerIdOf(this.scope.tools.lineageOf(tool)??[],owner)}buildProgressiveAuthUrl(appId,toolId,authInfo,priorAppIds){const baseUrl=this.scope.fullPath||"";const url=new URL(`${baseUrl}/oauth/authorize`,"http://placeholder.invalid");url.searchParams.set("app",appId);url.searchParams.set("tool",toolId);const ticket=this.mintIncrementalTicket(appId,toolId,authInfo,priorAppIds);if(ticket){url.searchParams.set("ticket",ticket)}else{this.logger.verbose("buildProgressiveAuthUrl: no incremental ticket minted \u2014 link requires a full login")}return baseUrl.startsWith("http")?url.toString():`${url.pathname}${url.search}`}mintIncrementalTicket(appId,toolId,authInfo,priorAppIds){const extraUser=authInfo?.extra?.user;const user=extraUser?.sub?extraUser:authInfo?.user;if(!user?.sub)return void 0;const sub=user.sub;const secret=this.scope.auth?.signingSecret;if(!secret)return void 0;return signIncrementalAuthTicket({sub,appId,toolId,audience:incrementalTicketAudience(this.scope),...priorAppIds&&priorAppIds.size>0?{priorAppIds:[...priorAppIds]}:{},...typeof user.email==="string"?{email:user.email}:{},...typeof user.name==="string"?{name:user.name}:{}},secret)}async checkEntryAuthorities(){this.logger.verbose("checkEntryAuthorities:start");const tool=this.state.tool;if(!tool)return;const metadata=tool.metadata;const authorities=metadata["authorities"];if(!authorities){this.logger.verbose("checkEntryAuthorities:skip (no authorities on tool)");return}const engine=this.scope.authoritiesEngine;const ctxBuilder=this.scope.authoritiesContextBuilder;if(!engine||!ctxBuilder){throw new AuthorityDeniedError3({entryType:"Tool",entryName:tool.fullName||tool.name,deniedBy:AUTHORITIES_NOT_CONFIGURED})}const authInfo=this.state.authInfo??{};const stateInput=this.state.input;const input=stateInput?.["arguments"]??stateInput??{};const evalCtx=ctxBuilder.build(authInfo,input);const result=await engine.evaluate(authorities,evalCtx);if(!result.granted){let requiredScopes;const scopeMapping=this.scope.authoritiesScopeMapping;if(scopeMapping&&result.denial){requiredScopes=resolveRequiredScopes2(result.denial,scopeMapping,authorities)}throw new AuthorityDeniedError3({entryType:"Tool",entryName:tool.fullName||tool.name,deniedBy:result.deniedBy??"policy denied",denial:result.denial,requiredScopes})}this.logger.verbose("checkEntryAuthorities:done")}async createToolCallContext(){this.logger.verbose("createToolCallContext:start");const{ctx}=this.input;const{tool,input}=this.state.required;const authInfo=this.state.authInfo;const progressToken=this.state.progressToken;try{const sessionKey=authInfo?.sessionId??"anonymous";const toolViews=await tool.providers.buildViews(sessionKey,new Map(this.deps),this.scope.providers);const contextProviders=new FlowContextProviders(tool.providers,toolViews.context);const executionAbort=linkedAbortController(ctx.signal);this.state.set("executionAbort",executionAbort);const context=runAsTool({name:tool.name,fullName:tool.fullName},()=>tool.create(input.arguments,{...ctx,progressToken,contextProviders,signal:executionAbort.signal}));await context.loadAuthContext();this.appendContextHooks(hooksBoundTo(this.scope.hooks.getClsHooks(tool.record.provide),context));context.mark("createToolCallContext");context._toolNameInternal=tool.metadata.id??tool.metadata.name;context._toolInputInternal=input.arguments;context.idempotencyKey=ctx.idempotencyKey;context._jsonRpcRequestIdInternal=this.state.jsonRpcRequestId;context._onRespondInternal=value=>this.state.set("rawOutput",value);context._onRecordsChangedInternal=ctx.onRecordsChanged;const frontmcpContext=context.tryGetContext();const authInfoWithTransport=authInfo;const jsonRpcRequestId=this.state.jsonRpcRequestId;if(frontmcpContext&&authInfoWithTransport?.transport?.sendElicitRequest&&jsonRpcRequestId!==void 0){const transport=authInfoWithTransport.transport;frontmcpContext.setTransport({sendElicitRequest:transport.sendElicitRequest.bind(transport),type:transport.type,jsonRpcRequestId})}this.state.set("toolContext",context);this.logger.verbose("createToolCallContext:done")}catch(error){if(error instanceof FlowControl||isClientFacingError(error))throw error;this.logger.error("createToolCallContext: failed to create context",error);throw new ToolExecutionError(tool.metadata.name,error instanceof Error?error:void 0)}}async checkToolCredentials(){this.logger.verbose("checkToolCredentials:start");const{tool}=this.state.required;const ctxObj=this.input.ctx;if(ctxObj?.internalCall){this.logger.verbose("checkToolCredentials:skip (internal call)");return}const providers=normalizeToolAuthProviders(tool.metadata["authProviders"]);if(providers.length===0){this.logger.verbose("checkToolCredentials:skip (no authProviders)");return}const toolContext=this.state.toolContext;if(!toolContext){this.logger.verbose("checkToolCredentials:skip (no tool context)");return}toolContext.mark("checkToolCredentials");const result=await evaluateToolCredentialGate(providers,token=>toolContext.tryGet(token));if(!result.evaluated){this.logger.verbose("checkToolCredentials:skip (no credential accessor configured)");return}if(result.missing.length===0){this.logger.verbose("checkToolCredentials:done (all required credentials present)");return}const toolId=tool.fullName||tool.metadata.name;const missingNames=result.missing.map(m=>m.name);this.logger.info(`checkToolCredentials: tool "${toolId}" missing required credential(s): ${missingNames.join(", ")}`);const connectPageAsk={context:this.tryGetContext(),getClientCapabilities:sessionId=>this.scope.notifications.getClientCapabilities(sessionId),elicitationEnabled:this.scope.metadata.elicitation?.enabled===true,toolId,toolInput:this.state.input?.arguments,signal:this.state.executionAbort?.signal};let missing=result.missing;if(await askToOpenConnectPages(connectPageAsk,missing)){missing=(await evaluateToolCredentialGate(providers,token=>toolContext.tryGet(token))).missing;if(missing.length===0){this.logger.verbose("checkToolCredentials:done (connected through the connect page)");return}}throw credentialsRequiredErrorOf(toolId,missing)}async acquireQuota(){this.logger.verbose("acquireQuota:start");const manager=this.scope.rateLimitManager;if(!manager){this.state.toolContext?.mark("acquireQuota");this.logger.verbose("acquireQuota:done (no rate limit manager)");return}const{tool}=this.state.required;const context=this.tryGetContext();const partitionCtx=buildPartitionContext(context);if(!context?.has(GLOBAL_RATE_LIMIT_CHECKED)){const globalResult=await manager.checkGlobalRateLimit(partitionCtx);if(!globalResult.allowed){this.logger.warn("acquireQuota: global rate limit exceeded",{retryAfterMs:globalResult.retryAfterMs});throw new RateLimitError(Math.ceil((globalResult.retryAfterMs??6e4)/1e3))}}const result=await manager.checkRateLimit(tool.metadata.name,tool.metadata.rateLimit,partitionCtx);if(!result.allowed){this.logger.warn("acquireQuota: tool rate limit exceeded",{tool:tool.metadata.name,retryAfterMs:result.retryAfterMs});throw new RateLimitError(Math.ceil((result.retryAfterMs??6e4)/1e3))}this.state.toolContext?.mark("acquireQuota");this.logger.verbose("acquireQuota:done")}async acquireSemaphore(){this.logger.verbose("acquireSemaphore:start");const manager=this.scope.rateLimitManager;if(!manager){this.state.toolContext?.mark("acquireSemaphore");this.logger.verbose("acquireSemaphore:done (no rate limit manager)");return}const{tool}=this.state.required;const partitionCtx=buildPartitionContext(this.tryGetContext());const isNestedCall=this.input.ctx?.internalCall===true||callSurfaceOf(this.input.ctx)==="agent";const ticket=await acquireConcurrencySlots(manager,tool.metadata.name,tool.metadata.concurrency,partitionCtx,{skipGlobal:isNestedCall});this.state.set("semaphoreTicket",ticket);this.state.toolContext?.mark("acquireSemaphore");this.logger.verbose("acquireSemaphore:done")}async validateInput(){this.logger.verbose("validateInput:start");const{tool,input}=this.state.required;const{toolContext}=this.state;if(!toolContext){return}toolContext.mark("validateInput");try{toolContext.input=tool.parseInput(input)}catch(err){if(err instanceof z63.ZodError){throw new InvalidInputError("Invalid tool input",err.issues)}this.logger.error("validateInput: failed to parse input",err);throw new InvalidInputError("Unknown error occurred when trying to parse input")}await this.applyInputPolicy(tool,input.arguments,toolContext.input);this.logger.verbose("validateInput:done")}async applyInputPolicy(tool,sent,parsed){const policy=resolveInputUndeclaredKeysPolicy(...toolInputPolicies(tool,this.scope));if(policy==="strip")return;const keyPaths=findUndeclaredArguments(tool.inputSchema??{},sent,parsed);if(keyPaths.length===0)return;const messages=await Promise.resolve().then(()=>(init_undeclared_arguments_message(),undeclared_arguments_message_exports));const declaredKeys=Object.keys(tool.inputSchema??{});if(policy==="fail")throw new InvalidInputError(messages.undeclaredArgumentsRefusal(keyPaths,declaredKeys));this.state.set("undeclaredArgumentsNote",messages.undeclaredArgumentsNote(keyPaths,declaredKeys));const newKeyPaths=unreportedKeyPaths(reportedUndeclaredArguments,tool,keyPaths.map(formatKeyPath));if(newKeyPaths.length>0)this.logger.warn(messages.undeclaredArgumentsWarning(tool.metadata.name,newKeyPaths))}async execute(){this.logger.verbose("execute:start");const toolContext=this.state.toolContext;if(!toolContext){return}toolContext.mark("execute");const{tool}=this.state.required;const timeoutMs=tool.metadata.timeout?.executeMs??this.scope.rateLimitManager?.config?.defaultTimeout?.executeMs;const running=runOnSurface(callSurfaceOf(this.input.ctx),()=>runAsTool({name:tool.name,fullName:tool.fullName},async()=>{await this.input.ctx.beforeExecute?.();if(toolContext.signal?.aborted)return;toolContext.output=await toolContext.execute(toolContext.input)}));try{await(timeoutMs?withTimeout(()=>running,timeoutMs,tool.metadata.name):running);this.logger.verbose("execute:done")}catch(error){if(error instanceof FlowControl&&error.type==="respond"){this.logger.verbose("execute:done (respond)");return}if(error instanceof FlowControl){throw error}if(error instanceof InputRequiredSignal||error instanceof MissingClientCapabilityError){throw error}if(error instanceof ExecutionTimeoutError){this.logger.warn("execute: tool execution timed out",{tool:tool.metadata.name,timeoutMs});this.state.executionAbort?.abort(error);this.state.set("abandonedExecution",running);throw error}if(error instanceof ElicitationFallbackRequired){this.logger.info("execute: elicitation fallback required",{elicitId:error.elicitId,toolName:error.toolName});const authInfo=this.state.authInfo;const authInfoWithTransport=authInfo;const sessionId=authInfo?.sessionId??"anonymous";const store=this.scope.elicitationStore;if(!store){throw new InternalMcpError("Elicitation store not initialized")}const owner=resolveElicitationOwner(this.tryGetContext());if(!owner){throw new ElicitationNotSupportedError("This client does not support elicitation, and the elicitation fallback needs a verified session or an authenticated caller to know who may answer it")}await store.setPendingFallback({elicitId:error.elicitId,sessionId,owner,toolName:tool.fullName,toolInput:this.state.required.input.arguments,idempotencyKey:toolContext.idempotencyKey,elicitMessage:error.elicitMessage,elicitSchema:error.schema,createdAt:Date.now(),expiresAt:Date.now()+error.ttl});const transportType=authInfoWithTransport?.transport?.type;if(transportType==="streamable-http"&&canDeliverNotifications(this.scope,sessionId)){this.logger.info("execute: using waiting fallback for streamable-http",{elicitId:error.elicitId});const deps={scope:this.scope,sessionId,logger:this.logger};const result=await awaitOutsideRequest4(handleWaitingFallback(deps,error));toolContext.output=result;this.logger.verbose("execute:done (elicitation waiting fallback)");return}const fallbackResponse={content:[{type:"text",text:`This tool requires user input to continue.
67
+ - ${problems.join("\n- ")}`,"INVALID_TOOL_UI_CONFIG");this.problems=problems}}}});var errors_exports={};__export(errors_exports,{AgentCallDepthExceededError:()=>AgentCallDepthExceededError,AgentConfigKeyNotFoundError:()=>AgentConfigKeyNotFoundError,AgentConfigurationError:()=>AgentConfigurationError,AgentExecutionError:()=>AgentExecutionError,AgentLlmError:()=>AgentLlmError,AgentLoopExceededError:()=>AgentLoopExceededError,AgentMethodNotAvailableError:()=>AgentMethodNotAvailableError,AgentNotConfiguredError:()=>AgentNotConfiguredError,AgentNotFoundError:()=>AgentNotFoundError,AgentTimeoutError:()=>AgentTimeoutError,AgentToolExecutionError:()=>AgentToolExecutionError,AgentToolNotFoundError:()=>AgentToolNotFoundError,AgentVisibilityError:()=>AgentVisibilityError,AuthConfigurationError:()=>AuthConfigurationError,AuthProvidersNotConfiguredError:()=>AuthProvidersNotConfiguredError,AuthorizationRequiredError:()=>AuthorizationRequiredError,BrowserEntryPointUnavailableError:()=>BrowserEntryPointUnavailableError,BrowserStoreUnavailableError:()=>BrowserStoreUnavailableError,CallRecorderConfigurationError:()=>CallRecorderConfigurationError,ClusterScopeNeedsRedisError:()=>ClusterScopeNeedsRedisError,ConfigNotFoundError:()=>ConfigNotFoundError,ContextExtensionNotAvailableError:()=>ContextExtensionNotAvailableError,CredentialProviderAlreadyRegisteredError:()=>CredentialProviderAlreadyRegisteredError,CrossOriginRequestError:()=>CrossOriginRequestError,DependencyCycleError:()=>DependencyCycleError,DependencyNotFoundError:()=>DependencyNotFoundError,DuplicateAppIdError:()=>DuplicateAppIdError,DuplicatePluginEntryError:()=>DuplicatePluginEntryError,DuplicatePluginError:()=>DuplicatePluginError,DutyNameConflictError:()=>DutyNameConflictError,DynamicAdapterNameError:()=>DynamicAdapterNameError,DynamicJobDirectExecutionError:()=>DynamicJobDirectExecutionError,DynamicJobRegistrationDisabledError:()=>DynamicJobRegistrationDisabledError,ElicitationDisabledError:()=>ElicitationDisabledError,ElicitationEncryptionError:()=>ElicitationEncryptionError,ElicitationFallbackRequired:()=>ElicitationFallbackRequired,ElicitationNotOwnedError:()=>ElicitationNotOwnedError,ElicitationNotSupportedError:()=>ElicitationNotSupportedError,ElicitationSecretRequiredError:()=>ElicitationSecretRequiredError,ElicitationStoreNotInitializedError:()=>ElicitationStoreNotInitializedError,ElicitationSubscriptionError:()=>ElicitationSubscriptionError,ElicitationTimeoutError:()=>ElicitationTimeoutError,EnclaveExecutionError:()=>EnclaveExecutionError,EncryptionContextNotSetError:()=>EncryptionContextNotSetError,EncryptionKeyNotConfiguredError:()=>EncryptionKeyNotConfiguredError,EntryUnavailableError:()=>EntryUnavailableError,EntryValidationError:()=>EntryValidationError,ErrorHandler:()=>ErrorHandler,EsmCacheError:()=>EsmCacheError,EsmInvalidSpecifierError:()=>EsmInvalidSpecifierError,EsmManifestInvalidError:()=>EsmManifestInvalidError,EsmPackageLoadError:()=>EsmPackageLoadError,EsmRegistryAuthError:()=>EsmRegistryAuthError,EsmVersionResolutionError:()=>EsmVersionResolutionError,EventCallbackEndpointError:()=>EventCallbackEndpointError,EventForbiddenError:()=>EventForbiddenError,EventNameConflictError:()=>EventNameConflictError,EventNotFoundError:()=>EventNotFoundError,EventNotRegisteredError:()=>EventNotRegisteredError,EventProtocolError:()=>EventProtocolError,EventPublishEndpointError:()=>EventPublishEndpointError,EventResourceExhaustedError:()=>EventResourceExhaustedError,EventSubscriptionStoreError:()=>EventSubscriptionStoreError,EventUnsupportedError:()=>EventUnsupportedError,EventsNotEnabledError:()=>EventsNotEnabledError,ExternalEntryError:()=>ExternalEntryError,ExternalEntryLoadError:()=>ExternalEntryLoadError,ExternalEntryNotFoundError:()=>ExternalEntryNotFoundError,ExternalEntryNotSupportedError:()=>ExternalEntryNotSupportedError,FeatureOffError:()=>FeatureOffError,FlowExitedWithoutOutputError:()=>FlowExitedWithoutOutputError,FlowInputMissingError:()=>FlowInputMissingError,FlowNotRegisteredError:()=>FlowNotRegisteredError,GenericServerError:()=>GenericServerError,GlobalConfigNotFoundError:()=>GlobalConfigNotFoundError,GuardLimitMcpError:()=>GuardLimitMcpError,HaConfigurationError:()=>HaConfigurationError,HookOrderCycleError:()=>HookOrderCycleError,HookTargetNotDefinedError:()=>HookTargetNotDefinedError,InMemoryStoreRequiredError:()=>InMemoryStoreRequiredError,InputRequiredSignal:()=>InputRequiredSignal,InternalMcpError:()=>InternalMcpError,InvalidDecoratorMetadataError:()=>InvalidDecoratorMetadataError,InvalidDependencyScopeError:()=>InvalidDependencyScopeError,InvalidDutyCronError:()=>InvalidDutyCronError,InvalidEntityError:()=>InvalidEntityError,InvalidEventPublishError:()=>InvalidEventPublishError,InvalidFileSignalError:()=>InvalidFileSignalError,InvalidHookFlowError:()=>InvalidHookFlowError,InvalidHttpRouteError:()=>InvalidHttpRouteError,InvalidHttpRouteResponseError:()=>InvalidHttpRouteResponseError,InvalidInputError:()=>InvalidInputError,InvalidInstructionSourceError:()=>InvalidInstructionSourceError,InvalidMethodError:()=>InvalidMethodError,InvalidOffloadCallError:()=>InvalidOffloadCallError,InvalidOutputError:()=>InvalidOutputError,InvalidPeopleAuthOptionsError:()=>InvalidPeopleAuthOptionsError,InvalidPluginScopeError:()=>InvalidPluginScopeError,InvalidRegistryKindError:()=>InvalidRegistryKindError,InvalidResourceStoreError:()=>InvalidResourceStoreError,InvalidResourceUriError:()=>InvalidResourceUriError,InvalidRetryOptionsError:()=>InvalidRetryOptionsError,InvalidSharedServerOptionsError:()=>InvalidSharedServerOptionsError,InvalidSkillError:()=>InvalidSkillError,InvalidToolUiConfigError:()=>InvalidToolUiConfigError,InvalidTransportSessionError:()=>InvalidTransportSessionError,InvalidUseClassError:()=>InvalidUseClassError,InvalidUseFactoryError:()=>InvalidUseFactoryError,InvalidUseValueError:()=>InvalidUseValueError,InvokeStateMissingKeyError:()=>InvokeStateMissingKeyError,JobAdmissionTimeoutError:()=>JobAdmissionTimeoutError,JobCancelledError:()=>JobCancelledError,JobInterruptedError:()=>JobInterruptedError,JobNotAuthorizedError:()=>JobNotAuthorizedError,JobRunFinishedError:()=>JobRunFinishedError,JobRunNotCancellableError:()=>JobRunNotCancellableError,JobRunNotFoundError:()=>JobRunNotFoundError,JobRunnerBootError:()=>JobRunnerBootError,JobRunnerUnavailableError:()=>JobRunnerUnavailableError,JobStoreNotSupportedError:()=>JobStoreNotSupportedError,JobTimeoutError:()=>JobTimeoutError,JwtSecretRequiredError:()=>JwtSecretRequiredError,JwtSecretWeakError:()=>JwtSecretWeakError,LazyAppConfigurationError:()=>LazyAppConfigurationError,LazyAppLoadError:()=>LazyAppLoadError,MCP_ERROR_CODES:()=>MCP_ERROR_CODES,McpError:()=>McpError,MethodNotImplementedError:()=>MethodNotImplementedError,MissingClientCapabilityError:()=>MissingClientCapabilityError,MissingPromptArgumentError:()=>MissingPromptArgumentError,MissingProvideError:()=>MissingProvideError,NameDisambiguationError:()=>NameDisambiguationError,NoProviderIdError:()=>NoProviderIdError,OffloadAbortedError:()=>OffloadAbortedError,OffloadBudgetExceededError:()=>OffloadBudgetExceededError,OffloadNotCloneableError:()=>OffloadNotCloneableError,OffloadUnsupportedRuntimeError:()=>OffloadUnsupportedRuntimeError,OffloadWorkerError:()=>OffloadWorkerError,OrchestratedAuthNotAvailableError:()=>OrchestratedAuthNotAvailableError,OrchestratorJwksNotAvailableError:()=>OrchestratorJwksNotAvailableError,PayloadTooLargeError:()=>PayloadTooLargeError,PersonNotSignedInError:()=>PersonNotSignedInError,PluginConfiguredTwiceError:()=>PluginConfiguredTwiceError,PluginDependencyError:()=>PluginDependencyError,PromptExecutionError:()=>PromptExecutionError,PromptNotFoundError:()=>PromptNotFoundError,ProviderBootstrapError:()=>ProviderBootstrapError,ProviderConstructionError:()=>ProviderConstructionError,ProviderDependencyError:()=>ProviderDependencyError,ProviderNotAvailableError:()=>ProviderNotAvailableError,ProviderNotInstantiatedError:()=>ProviderNotInstantiatedError,ProviderNotRegisteredError:()=>ProviderNotRegisteredError,ProviderScopeMismatchError:()=>ProviderScopeMismatchError,ProviderScopedAccessError:()=>ProviderScopedAccessError,PublicAccessDeniedError:()=>PublicAccessDeniedError,PublicMcpError:()=>PublicMcpError,QuotaExceededError:()=>QuotaExceededError,RateLimitError:()=>RateLimitError,RegistryDefinitionNotFoundError:()=>RegistryDefinitionNotFoundError,RegistryDependencyNotRegisteredError:()=>RegistryDependencyNotRegisteredError,RegistryGraphEntryNotFoundError:()=>RegistryGraphEntryNotFoundError,RegistryNotInitializedError:()=>RegistryNotInitializedError,RemoteAuthError:()=>RemoteAuthError,RemoteAuthorizationError:()=>RemoteAuthorizationError,RemoteCapabilityDiscoveryError:()=>RemoteCapabilityDiscoveryError,RemoteCapabilityNotSupportedError:()=>RemoteCapabilityNotSupportedError,RemoteConfigurationError:()=>RemoteConfigurationError,RemoteConnectionError:()=>RemoteConnectionError,RemoteDisconnectError:()=>RemoteDisconnectError,RemoteNotConnectedError:()=>RemoteNotConnectedError,RemotePromptGetError:()=>RemotePromptGetError,RemotePromptNotFoundError:()=>RemotePromptNotFoundError,RemoteResourceNotFoundError:()=>RemoteResourceNotFoundError,RemoteResourceReadError:()=>RemoteResourceReadError,RemoteTimeoutError:()=>RemoteTimeoutError,RemoteToolExecutionError:()=>RemoteToolExecutionError,RemoteToolNotFoundError:()=>RemoteToolNotFoundError,RemoteTransportError:()=>RemoteTransportError,RemoteUnsupportedTransportError:()=>RemoteUnsupportedTransportError,RequestContextNotAvailableError:()=>RequestContextNotAvailableError,RequiredConfigUndefinedError:()=>RequiredConfigUndefinedError,ReservedAppIdError:()=>ReservedAppIdError,ResourceNotFoundError:()=>ResourceNotFoundError,ResourceReadError:()=>ResourceReadError,SamplingNotAvailableError:()=>SamplingNotAvailableError,ScopeConfigurationError:()=>ScopeConfigurationError,ScopeDeniedError:()=>ScopeDeniedError,ServerNotFoundError:()=>ServerNotFoundError,ServerlessHandlerNotInitializedError:()=>ServerlessHandlerNotInitializedError,SessionClaimConflictError:()=>SessionClaimConflictError,SessionIdEmptyError:()=>SessionIdEmptyError,SessionIdentityRequiredError:()=>SessionIdentityRequiredError,SessionMissingError:()=>SessionMissingError,SessionOwnerUnreachableError:()=>SessionOwnerUnreachableError,SessionSecretRequiredError:()=>SessionSecretRequiredError,SessionVerificationFailedError:()=>SessionVerificationFailedError,SharedServerIdentityError:()=>SharedServerIdentityError,SharedServerStartError:()=>SharedServerStartError,SignInLockedError:()=>SignInLockedError,SignInRefusedError:()=>SignInRefusedError,SigningKeyInvalidError:()=>SigningKeyInvalidError,SkillContextNotImplementedError:()=>SkillContextNotImplementedError,SkillInstructionFetchError:()=>SkillInstructionFetchError,SkillSessionError:()=>SkillSessionError,SocketInUseError:()=>SocketInUseError,SocketPathConflictError:()=>SocketPathConflictError,SocketPermissionError:()=>SocketPermissionError,StaleToolListError:()=>StaleToolListError,StoreNotOpenedInBuildError:()=>StoreNotOpenedInBuildError,TaskAlreadyTerminalError:()=>TaskAlreadyTerminalError,TaskAugmentationNotSupportedError:()=>TaskAugmentationNotSupportedError,TaskAugmentationRequiredError:()=>TaskAugmentationRequiredError,TaskConcurrencyLimitError:()=>TaskConcurrencyLimitError,TaskNotFoundError:()=>TaskNotFoundError,TaskStoreNotInitializedError:()=>TaskStoreNotInitializedError,TokenLeakDetectedError:()=>TokenLeakDetectedError,TokenNotAvailableError:()=>TokenNotAvailableError,TokenStoreRequiredError:()=>TokenStoreRequiredError,ToolAliasConflictError:()=>ToolAliasConflictError,ToolCallError:()=>ToolCallError,ToolCredentialsRequiredError:()=>ToolCredentialsRequiredError,ToolExecutionError:()=>ToolExecutionError,ToolNameConflictError:()=>ToolNameConflictError,ToolNotConsentedError:()=>ToolNotConsentedError,ToolNotFoundError:()=>ToolNotFoundError,ToolUiConfigurationError:()=>ToolUiConfigurationError,TransportAlreadyStartedError:()=>TransportAlreadyStartedError,TransportBusRequiredError:()=>TransportBusRequiredError,TransportNotConnectedError:()=>TransportNotConnectedError,TransportServiceNotAvailableError:()=>TransportServiceNotAvailableError,UnauthorizedError:()=>UnauthorizedError,UnenforcedMetadataError:()=>UnenforcedMetadataError,UnsafeDutyStoreError:()=>UnsafeDutyStoreError,UnsafeSharedServerDirectoryError:()=>UnsafeSharedServerDirectoryError,UnsafeSocketDirectoryError:()=>UnsafeSocketDirectoryError,UnsupportedClientVersionError:()=>UnsupportedClientVersionError,UnsupportedContentTypeError:()=>UnsupportedContentTypeError,UnsupportedHookOwnerKindError:()=>UnsupportedHookOwnerKindError,UnsupportedTransportTypeError:()=>UnsupportedTransportTypeError,VaultLoadError:()=>VaultLoadError,VaultNotFoundError:()=>VaultNotFoundError,VercelKvAsyncInitRequiredError:()=>VercelKvAsyncInitRequiredError,VercelKvNotSupportedError:()=>VercelKvNotSupportedError,WorkerNameConflictError:()=>WorkerNameConflictError,WorkflowDagValidationError:()=>WorkflowDagValidationError,WorkflowJobTimeoutError:()=>WorkflowJobTimeoutError,WorkflowStepNotFoundError:()=>WorkflowStepNotFoundError,WorkflowTimeoutError:()=>WorkflowTimeoutError,WorkflowTriggerConfigError:()=>WorkflowTriggerConfigError,authorizationRequiredDataSchema:()=>authorizationRequiredDataSchema,authorizationRequiredMetaSchema:()=>authorizationRequiredMetaSchema,authorizationRequiredParamsSchema:()=>authorizationRequiredParamsSchema,createErrorHandler:()=>createErrorHandler,describeConfigIssues:()=>describeConfigIssues,extractPublicMessage:()=>extractPublicMessage,formatMcpErrorResponse:()=>formatMcpErrorResponse,isClientFacingError:()=>isClientFacingError,isMrtrSignal:()=>isMrtrSignal,isPublicError:()=>isPublicError,refused:()=>refused,shouldStopExecution:()=>shouldStopExecution,toMcpError:()=>toMcpError});var init_errors=__esm({"libs/sdk/src/errors/index.ts"(){"use strict";init_mcp_error();init_authorization_required_error();init_tool_credentials_required_error();init_tool_call_error();init_misconfiguration();init_session_identity_required_error();init_error_handler();init_agent_errors();init_task_error();init_elicitation_error();init_offload_errors();init_mrtr_error();init_remote_errors();init_normalization_errors();init_registry_errors();init_provider_errors();init_decorator_errors();init_duty_errors();init_event_errors();init_worker_errors();init_browser_store_errors();init_build_store_errors();init_browser_entry_point_errors();init_http_route_errors();init_shared_server_errors();init_transport_errors();init_auth_internal_errors();init_workflow_errors();init_esm_errors();init_external_entry_errors();init_lazy_app_errors();init_sdk_errors();init_job_errors();init_plugin_errors();init_tool_ui_errors()}});var loadProtocolClient;var init_import_protocol_client=__esm({"libs/sdk/src/third-party/import-protocol-client.ts"(){"use strict";loadProtocolClient=()=>import("@frontmcp/protocol/client")}});async function listAllPages(method,fetchPage,fail=message=>new InternalMcpError(message,"LIST_PAGINATION_STALLED")){const items=[];const seenCursors=new Set;let cursor;for(let page2=0;page2<MAX_LIST_PAGES;page2++){const result=await fetchPage(cursor);items.push(...result.items??[]);const next=result.nextCursor;if(!next)return items;if(seenCursors.has(next)){throw fail(`${method} returned the cursor "${next}" twice`)}seenCursors.add(next);cursor=next}throw fail(`${method} did not finish within ${MAX_LIST_PAGES} pages`)}var MAX_LIST_PAGES;var init_list_all_pages_utils=__esm({"libs/sdk/src/common/utils/list-all-pages.utils.ts"(){"use strict";init_mcp_error();MAX_LIST_PAGES=1e3}});var ELICITATION_META_KEY;var init_elicitation_meta=__esm({"libs/sdk/src/elicitation/elicitation-meta.ts"(){"use strict";ELICITATION_META_KEY="frontmcp/elicitation"}});var EventRequestError,NoCompatibleDeliveryModeError,EventSubscriptionTerminatedError,DuplicateEventSubscriptionError;var init_event_client_errors=__esm({"libs/sdk/src/event-client/event-client.errors.ts"(){"use strict";init_mcp_error();EventRequestError=class extends PublicMcpError{constructor(method,rpcCode,message,data){super(`${method} failed (${rpcCode}): ${message}`,"EVENT_REQUEST_FAILED",400);this.method=method;this.rpcCode=rpcCode;this.data=data}method;rpcCode;data};NoCompatibleDeliveryModeError=class extends PublicMcpError{constructor(eventName,offered,usable){super(`Event "${eventName}" is offered by ${offered.join(", ")||"no mode"}, and this client can use ${usable.join(", ")}. Configure a webhook receiver, use a transport that streams, or pick another event.`,"NO_COMPATIBLE_DELIVERY_MODE",400)}};EventSubscriptionTerminatedError=class extends PublicMcpError{constructor(eventName,error){super(`The subscription to "${eventName}" was terminated by the server: ${error.message}`,"EVENT_TERMINATED",410);this.eventName=eventName;this.error=error}eventName;error};DuplicateEventSubscriptionError=class extends PublicMcpError{constructor(eventName,url){super(`This client already holds a webhook subscription to "${eventName}" with these arguments at ${url}, and the server keeps one subscription for them. Read the existing subscription, or cancel it first.`,"DUPLICATE_EVENT_SUBSCRIPTION",409)}}}});import{EventErrorSchema,EventOccurrenceSchema,EVENTS_ERROR_CODES,EVENTS_METHODS,EVENTS_NOTIFICATIONS,EVENTS_SKETCH_ERROR_CODES,ListEventsResultSchema,PollEventsResultSchema,SubscribeEventResultSchema}from"@frontmcp/protocol";import{canonicalJson,generateStandardWebhookSecret}from"@frontmcp/utils";function isTerminal2(error){return error instanceof EventRequestError&&TERMINAL_CODES.has(error.rpcCode)}function eventErrorOf(error){const data=typeof error.data==="object"&&error.data!==null?error.data:{};return{code:error.rpcCode,message:error.message,data}}function sameArguments(first3,second){const keyOf=({name:name59,arguments:args})=>canonicalJson({name:name59,arguments:args});return keyOf(first3)===keyOf(second)}function sleep(ms,signal){return new Promise(resolve4=>{if(signal.aborted)return resolve4();const done=()=>{clearTimeout(timer);signal.removeEventListener("abort",done);resolve4()};const timer=setTimeout(done,ms);signal.addEventListener("abort",done,{once:true})})}var DEFAULT_POLL_FLOOR_MS,DEFAULT_HEARTBEAT_TIMEOUT_MS,NO_EXPIRY_REFRESH_MS,REFRESH_AT_SHARE,DEDUPE_WINDOW,MAX_TIMER_MS3,MAX_RETRY_DELAY_MS,TERMINAL_CODES,MemoryCursorStore,OccurrenceQueue,ClientEventSubscription,EventsClient;var init_events_client=__esm({"libs/sdk/src/event-client/events-client.ts"(){"use strict";init_list_all_pages_utils();init_event_client_errors();DEFAULT_POLL_FLOOR_MS=1e3;DEFAULT_HEARTBEAT_TIMEOUT_MS=6e4;NO_EXPIRY_REFRESH_MS=36e5;REFRESH_AT_SHARE=.8;DEDUPE_WINDOW=1e3;MAX_TIMER_MS3=2147483647;MAX_RETRY_DELAY_MS=6e4;TERMINAL_CODES=new Set([-32602,...[EVENTS_ERROR_CODES,EVENTS_SKETCH_ERROR_CODES].flatMap(({notFound,forbidden,unsupported})=>[notFound,forbidden,unsupported])]);MemoryCursorStore=class{cursors=new Map;get(key){return this.cursors.get(key)}set(key,cursor){this.cursors.set(key,cursor)}};OccurrenceQueue=class{constructor(onReturn){this.onReturn=onReturn}onReturn;items=[];seen=new Set;waiter;ended=false;failure;push(occurrence){if(this.ended||this.seen.has(occurrence.eventId))return;this.seen.add(occurrence.eventId);if(this.seen.size>DEDUPE_WINDOW)this.seen.delete(this.seen.values().next().value);const waiter=this.waiter;this.waiter=void 0;if(waiter)waiter.resolve({value:occurrence,done:false});else this.items.push(occurrence)}end(failure){if(this.ended)return;this.ended=true;this.failure=failure;if(!failure)this.items.length=0;const waiter=this.waiter;this.waiter=void 0;if(!waiter)return;if(failure)waiter.reject(failure);else waiter.resolve({value:void 0,done:true})}[Symbol.asyncIterator](){return{next:()=>this.next(),return:async()=>{await this.onReturn();return{value:void 0,done:true}}}}next(){const item=this.items.shift();if(item)return Promise.resolve({value:item,done:false});if(this.failure)return Promise.reject(this.failure);if(this.ended)return Promise.resolve({value:void 0,done:true});return new Promise((resolve4,reject)=>{this.waiter={resolve:resolve4,reject}})}};ClientEventSubscription=class{constructor(settings){this.settings=settings;this.name=settings.name;this.arguments=settings.arguments;this.mode=settings.mode;this.cursor=settings.cursor;this.queue=new OccurrenceQueue(()=>this.cancel())}settings;name;arguments;mode;cursor;id;deliveryStatus;queue;stopController=new AbortController;streamController;registration;secret;refreshTimer;pendingRefresh;immediateRefreshOwed=false;firstRequest=true;failedAttempts=0;[Symbol.asyncIterator](){return this.queue[Symbol.asyncIterator]()}get stopped(){return this.stopController.signal.aborted}async start(){if(this.mode==="poll"){const waitMs=await this.pollOnce();void this.pollLoop(waitMs)}else if(this.mode==="push"){await this.openStream()}else{await this.startWebhook()}}async cancel(){if(this.stopped)return;this.stop();this.queue.end();if(this.mode!=="webhook")return;await this.pendingRefresh?.catch(()=>void 0);const delivery={mode:"webhook",url:this.settings.webhook?.url};await this.settings.transport.request(EVENTS_METHODS.unsubscribe,{name:this.name,arguments:this.arguments,delivery}).catch(()=>void 0)}stop(){this.settings.onStopped(this);this.stopController.abort();this.streamController?.abort();clearTimeout(this.refreshTimer);this.registration?.release()}discard(){if(this.stopped)return;this.stop();this.queue.end()}refreshNow(){if(this.stopped)return;this.immediateRefreshOwed=true;this.scheduleRefresh(0)}terminate(error){if(this.stopped)return;this.stop();this.queue.end(new EventSubscriptionTerminatedError(this.name,error))}advance(cursor,truncated){this.cursor=cursor??null;const key=canonicalJson({name:this.name,arguments:this.arguments});try{Promise.resolve(this.settings.cursorStore.set(key,this.cursor)).catch(()=>void 0)}catch{}if(truncated)this.settings.options.onTruncated?.(this.cursor)}retryDelayMs(){const delayMs=Math.min(this.settings.pollFloorMs*2**this.failedAttempts,MAX_RETRY_DELAY_MS);this.failedAttempts+=1;return delayMs}subscriptionParams(){const{maxAgeMs}=this.settings.options;const params={name:this.name,arguments:this.arguments,cursor:this.cursor};if(this.firstRequest&&maxAgeMs!==void 0)params["maxAgeMs"]=maxAgeMs;this.firstRequest=false;return params}async pollOnce(){const{maxEvents}=this.settings.options;const params={...this.subscriptionParams(),...maxEvents!==void 0&&{maxEvents}};const result=PollEventsResultSchema.parse(await this.settings.transport.request(EVENTS_METHODS.poll,params));this.advance(result.cursor,result.truncated);for(const occurrence of result.events)this.queue.push(occurrence);this.failedAttempts=0;if(result.hasMore)return 0;return Math.max(result.nextPollMs??this.settings.pollFloorMs,this.settings.pollFloorMs)}async pollLoop(firstWaitMs){let waitMs=firstWaitMs;while(!this.stopped){await sleep(waitMs,this.stopController.signal);if(this.stopped)return;try{waitMs=await this.pollOnce()}catch(error){if(isTerminal2(error))return this.terminate(eventErrorOf(error));waitMs=this.retryDelayMs()}}}openStream(){const{transport}=this.settings;const openStream=transport.openStream.bind(transport);const controller=new AbortController;this.streamController=controller;let confirmed=false;let watchdog;const resetWatchdog=()=>{clearTimeout(watchdog);watchdog=setTimeout(()=>controller.abort(),this.settings.heartbeatTimeoutMs)};return new Promise((confirm,refuse)=>{const onNotification=notification=>{resetWatchdog();if(notification.method===EVENTS_NOTIFICATIONS.active){confirmed=true;confirm()}this.onStreamNotification(notification)};resetWatchdog();openStream({...this.subscriptionParams()},onNotification,controller.signal).then(()=>this.streamEnded(confirmed,watchdog,refuse,void 0),error=>this.streamEnded(confirmed,watchdog,refuse,error))})}streamEnded(confirmed,watchdog,refuse,error){clearTimeout(watchdog);if(!confirmed)return refuse(error??new Error("The events/stream ended before the server confirmed it"));if(!this.stopped)void this.reconnect()}async reconnect(){while(!this.stopped){await sleep(this.retryDelayMs(),this.stopController.signal);if(this.stopped)return;try{await this.openStream();this.failedAttempts=0;return}catch(error){if(isTerminal2(error))return this.terminate(eventErrorOf(error))}}}onStreamNotification({method,params={}}){if(method===EVENTS_NOTIFICATIONS.active){this.advance(params["cursor"],params["truncated"]===true)}else if(method===EVENTS_NOTIFICATIONS.heartbeat){this.advance(params["cursor"])}else if(method===EVENTS_NOTIFICATIONS.event){const{_meta:_subscriptionMeta,...fields}=params;const occurrence=EventOccurrenceSchema.safeParse(fields);if(!occurrence.success)return;this.advance(occurrence.data.cursor);this.queue.push(occurrence.data)}else if(method===EVENTS_NOTIFICATIONS.error||method===EVENTS_NOTIFICATIONS.terminated){const error=EventErrorSchema.safeParse(params["error"]);if(!error.success)return;if(method===EVENTS_NOTIFICATIONS.error)this.settings.options.onError?.(error.data);else this.terminate(error.data)}}async startWebhook(){const webhook=this.settings.webhook;const secret=generateStandardWebhookSecret();this.secret=secret;this.registration=webhook.receiver.register({secret,listener:{onEvent:occurrence=>{this.advance(occurrence.cursor);this.queue.push(occurrence)},onGap:cursor=>this.advance(cursor,true),onTerminated:error=>this.terminate(error)}});try{this.pendingRefresh=this.refresh();await this.pendingRefresh}catch(error){this.registration.release();throw error}}async refresh(){const webhook=this.settings.webhook;const params={...this.subscriptionParams(),delivery:{mode:"webhook",url:webhook.url,secret:this.secret},...webhook.ttlMs!==void 0&&{ttlMs:webhook.ttlMs}};const result=SubscribeEventResultSchema.parse(await this.settings.transport.request(EVENTS_METHODS.subscribe,params));this.id=result.id;this.registration.bind(result.id);this.deliveryStatus=result.deliveryStatus;this.advance(result.cursor,result.truncated);if(this.stopped)return;this.failedAttempts=0;const remainingMs=result.refreshBefore===null?Number.NaN:Date.parse(result.refreshBefore)-Date.now();const delayMs=Number.isNaN(remainingMs)?NO_EXPIRY_REFRESH_MS:remainingMs*REFRESH_AT_SHARE;this.scheduleRefresh(Math.min(Math.max(delayMs,this.settings.pollFloorMs),MAX_TIMER_MS3))}scheduleRefresh(delayMs){clearTimeout(this.refreshTimer);this.refreshTimer=setTimeout(()=>this.refreshAfterInFlight(),this.immediateRefreshOwed?0:delayMs)}refreshAfterInFlight(){this.immediateRefreshOwed=false;const inFlight=this.pendingRefresh?.catch(()=>void 0)??Promise.resolve();this.pendingRefresh=inFlight.then(()=>this.stopped?void 0:this.refresh());this.pendingRefresh.catch(error=>{if(isTerminal2(error))this.terminate(eventErrorOf(error));else if(!this.stopped)this.scheduleRefresh(this.retryDelayMs())})}};EventsClient=class{constructor(transport,options={}){this.transport=transport;this.options=options;this.cursorStore=options.cursorStore??new MemoryCursorStore}transport;options;cursorStore;definitions;subscriptions=new Set;async list(){const events=await listAllPages(EVENTS_METHODS.list,async cursor=>{const result=ListEventsResultSchema.parse(await this.transport.request(EVENTS_METHODS.list,cursor?{cursor}:{}));return{items:result.events,nextCursor:result.nextCursor}});this.definitions=new Map(events.map(definition=>[definition.name,definition]));return events}async subscribe(name59,args={},options={}){const mode=await this.modeFor(name59,options.delivery);const storedCursor=await this.cursorStore.get(canonicalJson({name:name59,arguments:args}));const subscription=new ClientEventSubscription({transport:this.transport,cursorStore:this.cursorStore,pollFloorMs:this.options.pollFloorMs??DEFAULT_POLL_FLOOR_MS,heartbeatTimeoutMs:this.options.heartbeatTimeoutMs??DEFAULT_HEARTBEAT_TIMEOUT_MS,webhook:this.options.webhook,name:name59,arguments:args,mode,cursor:options.cursor!==void 0?options.cursor:storedCursor??null,options,onStopped:stopped=>this.subscriptions.delete(stopped)});if(mode==="webhook"&&this.webhookHolderOf(held=>sameArguments(held,subscription))){throw new DuplicateEventSubscriptionError(name59,this.options.webhook?.url??"")}this.subscriptions.add(subscription);try{await subscription.start()}catch(error){this.subscriptions.delete(subscription);throw error}const holder=mode==="webhook"&&this.webhookHolderOf(held=>held!==subscription&&held.id===subscription.id);if(holder){subscription.discard();holder.refreshNow();throw new DuplicateEventSubscriptionError(name59,this.options.webhook?.url??"")}return subscription}webhookHolderOf(matches){return[...this.subscriptions].find(held=>held.mode==="webhook"&&matches(held))}async close(){await Promise.all([...this.subscriptions].map(subscription=>subscription.cancel()))}async modeFor(name59,forced){const usable=[];if(this.options.webhook)usable.push("webhook");if(this.transport.openStream)usable.push("push");usable.push("poll");if(!this.definitions)await this.list();const offered=this.definitions?.get(name59)?.delivery??usable;const mode=forced??usable.find(candidate=>offered.includes(candidate));if(!mode||!usable.includes(mode)||!offered.includes(mode)){throw new NoCompatibleDeliveryModeError(name59,offered,usable)}return mode}}}});import{EventErrorSchema as EventErrorSchema2,EventOccurrenceSchema as EventOccurrenceSchema2,MCP_SUBSCRIPTION_ID_HEADER}from"@frontmcp/protocol";import{signingKeyOf,verifyWebhookSignature,WEBHOOK_ID_HEADER,WEBHOOK_SIGNATURE_HEADER,WEBHOOK_TIMESTAMP_HEADER}from"@frontmcp/utils";function headerOf(headers,name59){if(typeof headers.get==="function")return headers.get(name59)??void 0;const lowerName=name59.toLowerCase();for(const[key,value]of Object.entries(headers)){if(key.toLowerCase()===lowerName)return Array.isArray(value)?value[0]:value}return void 0}function jsonObjectOf(body){try{const parsed=JSON.parse(body);return typeof parsed==="object"&&parsed!==null&&!Array.isArray(parsed)?parsed:void 0}catch{return void 0}}function createEventWebhookReceiver(options={}){const sharedKeys=(options.secrets??[]).map(signingKeyOf);const registrations=new Set;const seenWebhookIds=new Set;const inFlight=new Set;const boundTo=subscriptionId=>[...registrations].filter(registration=>registration.subscriptionId===subscriptionId);const check=(request2,signingKeys)=>verifyWebhookSignature({id:headerOf(request2.headers,WEBHOOK_ID_HEADER),timestamp:headerOf(request2.headers,WEBHOOK_TIMESTAMP_HEADER),signature:headerOf(request2.headers,WEBHOOK_SIGNATURE_HEADER),body:request2.rawBody},signingKeys);const bindUnbound=(request2,subscriptionId)=>{let result="mismatch";for(const registration of registrations){if(registration.subscriptionId!==void 0)continue;result=check(request2,registration.signingKeys);if(result==="valid"){registration.subscriptionId=subscriptionId;return result}if(result!=="mismatch")return result}return result};const verify=request2=>{const subscriptionId=headerOf(request2.headers,MCP_SUBSCRIPTION_ID_HEADER)??"";const signingKeys=[...sharedKeys,...boundTo(subscriptionId).flatMap(registration=>registration.signingKeys)];return signingKeys.length>0?check(request2,signingKeys):void 0};const remember=dedupeKey=>{seenWebhookIds.add(dedupeKey);if(seenWebhookIds.size>WEBHOOK_DEDUPE_WINDOW){const oldest=seenWebhookIds.values().next().value;seenWebhookIds.delete(oldest)}};const dispatch=async(json,listener,delivery)=>{if(json["type"]==="gap"){await listener.onGap?.(typeof json["cursor"]==="string"?json["cursor"]:null,delivery);return{status:200}}if(json["type"]==="terminated"){const error=EventErrorSchema2.safeParse(json["error"]);if(!error.success)return{status:400};await listener.onTerminated?.(error.data,delivery);return{status:200}}const occurrence=EventOccurrenceSchema2.safeParse(json);if(json["type"]!==void 0||!occurrence.success)return{status:400};await listener.onEvent?.(occurrence.data,delivery);return{status:200}};return{async handle(request2){const subscriptionId=headerOf(request2.headers,MCP_SUBSCRIPTION_ID_HEADER)??"";const webhookId=headerOf(request2.headers,WEBHOOK_ID_HEADER)??"";const json=jsonObjectOf(request2.rawBody);const isVerification=json?.["type"]==="verification"&&typeof json["challenge"]==="string";const bound=boundTo(subscriptionId);let signature=verify(request2);if(signature!=="valid"&&isVerification&&bound.length===0){signature=bindUnbound(request2,subscriptionId)}if(signature===void 0)return{status:503};if(signature!=="valid")return{status:401,signature};if(!json)return{status:400,signature};if(isVerification)return{status:200,body:{challenge:json["challenge"]},signature};const dedupeKey=`${subscriptionId} ${webhookId}`;if(seenWebhookIds.has(dedupeKey))return{status:200,signature};if(inFlight.has(dedupeKey))return{status:503,signature};const listener=bound[0]?.listener??options;inFlight.add(dedupeKey);try{const response=await dispatch(json,listener,{subscriptionId,webhookId});if(response.status===200)remember(dedupeKey);return{...response,signature}}catch{return{status:500,signature}}finally{inFlight.delete(dedupeKey)}},verify,register({secret,subscriptionId,listener}){const record={subscriptionId,signingKeys:[signingKeyOf(secret)],listener};registrations.add(record);return{get subscriptionId(){return record.subscriptionId},bind(id){record.subscriptionId=id},addSecret(next){record.signingKeys.push(signingKeyOf(next))},release(){registrations.delete(record)}}},addSecret(secret){sharedKeys.push(signingKeyOf(secret))},hasSecrets(){return sharedKeys.length>0||registrations.size>0}}}var WEBHOOK_DEDUPE_WINDOW;var init_event_webhook_receiver=__esm({"libs/sdk/src/event-client/event-webhook-receiver.ts"(){"use strict";WEBHOOK_DEDUPE_WINDOW=1e4}});var init_event_client=__esm({"libs/sdk/src/event-client/index.ts"(){"use strict";init_events_client();init_event_webhook_receiver();init_event_client_errors()}});import{internalZ as z55}from"@frontmcp/lazy-zod";var SkillsSearchRequestSchema,SkillsSearchResultSchema,MAX_SKILLS_PER_LOAD,SkillsLoadRequestSchema,SkillsLoadResultSchema,SkillsListRequestSchema,SkillsListResultSchema;var init_skills_mcp_types=__esm({"libs/sdk/src/transport/mcp-handlers/skills-mcp.types.ts"(){"use strict";SkillsSearchRequestSchema=z55.object({method:z55.literal("skills/search"),params:z55.object({query:z55.string().describe("Search query string"),tags:z55.array(z55.string()).optional().describe("Filter by specific tags"),tools:z55.array(z55.string()).optional().describe("Filter by specific tools"),limit:z55.number().min(1).max(50).optional().describe("Maximum results (1-50, default: 10)"),requireAllTools:z55.boolean().optional().describe("Require all specified tools")})});SkillsSearchResultSchema=z55.object({skills:z55.array(z55.object({id:z55.string(),name:z55.string(),description:z55.string(),score:z55.number(),tags:z55.array(z55.string()).optional(),tools:z55.array(z55.object({name:z55.string(),available:z55.boolean()})),source:z55.enum(["local","external"]),bundleVersion:z55.string().optional().describe("Version of the bundle a runtime-registered skill came from")})),total:z55.number(),hasMore:z55.boolean(),guidance:z55.string()});MAX_SKILLS_PER_LOAD=100;SkillsLoadRequestSchema=z55.object({method:z55.literal("skills/load"),params:z55.object({skillIds:z55.array(z55.string()).min(1).max(MAX_SKILLS_PER_LOAD).describe("Array of skill IDs to load"),format:z55.enum(["full","markdown","instructions-only"]).optional().describe("'full' (default): the fields with tool schemas, and formattedContent; 'markdown': formattedContent alone, without instructions and parameters; 'instructions-only': no tool schemas"),activateSession:z55.boolean().optional().describe("Whether to activate a skill session"),policyMode:z55.enum(["strict","approval","permissive"]).optional().describe("Policy mode for session")})});SkillsLoadResultSchema=z55.object({skills:z55.array(z55.object({id:z55.string(),name:z55.string(),description:z55.string(),instructions:z55.string().optional(),tools:z55.array(z55.object({name:z55.string(),purpose:z55.string().optional(),available:z55.boolean(),inputSchema:z55.unknown().optional(),outputSchema:z55.unknown().optional()})),parameters:z55.array(z55.object({name:z55.string(),description:z55.string().optional(),required:z55.boolean().optional(),type:z55.string().optional()})).optional(),availableTools:z55.array(z55.string()),missingTools:z55.array(z55.string()),isComplete:z55.boolean(),formattedContent:z55.string(),session:z55.object({activated:z55.boolean(),sessionId:z55.string().optional(),policyMode:z55.string().optional(),allowedTools:z55.array(z55.string()).optional()}).optional()})),summary:z55.object({totalSkills:z55.number(),totalTools:z55.number(),allToolsAvailable:z55.boolean(),combinedWarnings:z55.array(z55.string()).optional()}),nextSteps:z55.string()});SkillsListRequestSchema=z55.object({method:z55.literal("skills/list"),params:z55.object({offset:z55.number().min(0).optional().describe("Number of skills to skip"),limit:z55.number().min(1).max(100).optional().describe("Maximum skills to return"),tags:z55.array(z55.string()).optional().describe("Filter by specific tags"),sortBy:z55.enum(["name","priority","createdAt"]).optional().describe("Field to sort by"),sortOrder:z55.enum(["asc","desc"]).optional().describe("Sort order"),includeHidden:z55.boolean().optional().describe("Include hidden skills")}).optional()});SkillsListResultSchema=z55.object({skills:z55.array(z55.object({id:z55.string(),name:z55.string(),description:z55.string(),tags:z55.array(z55.string()).optional(),priority:z55.number().optional(),bundleVersion:z55.string().optional().describe("Version of the bundle a runtime-registered skill came from")})),total:z55.number(),hasMore:z55.boolean()})}});import{internalZ as z56}from"@frontmcp/lazy-zod";import{EVENTS_METHODS as EVENTS_METHODS2,MCP_20260728_META}from"@frontmcp/protocol";function requestErrorOf(method,error){const{code,message,data}=error??{};if(typeof code!=="number")return error;const text=typeof message==="string"?message.replace(/^MCP error -?\d+: /,""):"";return new EventRequestError(method,code,text,data)}function directEventsTransport(client,notifications){return{async request(method,params){try{return await client.request({method,params},anyResultSchema)}catch(error){throw requestErrorOf(method,error)}},async openStream(params,onNotification,signal){const requestId=client._requestMessageId;if(typeof requestId!=="number")throw new Error("This MCP client cannot hold an events/stream");const stopListening=notifications(notification=>{const meta=notification.params?._meta;if(meta?.[MCP_20260728_META.subscriptionId]!==requestId)return;onNotification(notification)});try{await client.request({method:EVENTS_METHODS2.stream,params},anyResultSchema,{signal,timeout:NO_TIMEOUT_MS})}catch(error){if(!signal.aborted)throw requestErrorOf(EVENTS_METHODS2.stream,error)}finally{stopListening()}}}}var NO_TIMEOUT_MS,anyResultSchema;var init_direct_events_transport=__esm({"libs/sdk/src/direct/direct-events-transport.ts"(){"use strict";init_event_client();NO_TIMEOUT_MS=2147483647;anyResultSchema=z56.record(z56.string(),z56.unknown())}});import{getEnv as getEnv4}from"@frontmcp/utils";var DirectPublicAuth;var init_direct_public_auth=__esm({"libs/sdk/src/auth/direct-public-auth.ts"(){"use strict";init_common();DirectPublicAuth=class extends FrontMcpAuth{ready=Promise.resolve();issuer;constructor(scope,options){super(options);const host=getEnv4("FRONTMCP_PUBLIC_HOST")?.trim()||"localhost";this.issuer=`http://${host}:${scope.metadata.http?.port??defaultHttpPort()}${scope.fullPath}`}fetch(input,init){return fetch(input,init)}validate(){return Promise.resolve()}}}});import{isAnonymousSubject}from"@frontmcp/auth";async function authInfoForToken(scope,token){if(scope.auth instanceof DirectPublicAuth)return{};const mcpPath=`${normalizeEntryPrefix(scope.entryPath)}${normalizeScopeBase(scope.routeBase)}`||"/";const request2={method:"POST",path:mcpPath,url:mcpPath,headers:{host:"localhost",authorization:`Bearer ${token}`},query:{}};const verified=await scope.runFlow("session:verify",{request:request2,sessionless:true});if(!verified)throw new SessionVerificationFailedError;if(verified.kind==="unauthorized"){throw new UnauthorizedError("The server's auth did not accept the auth token",verified.prmMetadataHeader)}if(verified.kind==="forbidden"){throw new PublicMcpError("The auth token lacks the scopes the server requires","INSUFFICIENT_SCOPE",403)}if(isAnonymousSubject(verified.authorization.user.sub))return{};return authInfoFromAuthorization(verified.authorization)}var init_token_auth_info=__esm({"libs/sdk/src/direct/token-auth-info.ts"(){"use strict";init_direct_public_auth();init_common();init_errors()}});function keepingListsUnchanged(change){depth++;try{return change()}finally{depth--}}function listsUnchanged(){return depth>0}var depth;var init_unchanged_lists=__esm({"libs/sdk/src/surface/unchanged-lists.ts"(){"use strict";depth=0}});import{AsyncLocalStorage as AsyncLocalStorage3}from"@frontmcp/utils";function openBatchOf(lists){for(let run=runningBatches.getStore();run;run=run.outer){if(run.open&&run.lists===lists)return run}return void 0}async function runListChangeBatch(lists,change){const run={lists,changed:new Set,outer:runningBatches.getStore(),open:true};const batch={listsRestored:()=>run.changed.clear()};let outcome;try{outcome={completed:true,result:await runningBatches.run(run,()=>change(batch))}}catch(error){outcome={completed:false,error}}run.open=false;const announcementFailure=announceChangedLists(run,lists);if(!outcome.completed)throw outcome.error;if(announcementFailure)throw announcementFailure.error;return outcome.result}function announceChangedLists(run,lists){const enclosing=openBatchOf(lists);let firstFailure;for(const kind of run.changed){if(enclosing){enclosing.changed.add(kind);continue}try{lists[kind].notifyListChanged()}catch(error){firstFailure??={error}}}return firstFailure}function announcesListChangeNow(lists,kind){if(listsUnchanged())return false;const batch=openBatchOf(lists);batch?.changed.add(kind);return batch===void 0}var runningBatches;var init_list_change_batch=__esm({"libs/sdk/src/surface/list-change-batch.ts"(){"use strict";init_unchanged_lists();runningBatches=new AsyncLocalStorage3}});function mcpRequestSurface(scope){return scope?.metadata?.["__cliMode"]===true?"cli":"mcp"}function withMcpSurface(scope,ctx){return{...ctx,surface:mcpRequestSurface(scope)}}function mcpRequestSessionId(ctx){const sessionId=ctx?.authInfo?.sessionId;return typeof sessionId==="string"&&sessionId?sessionId:void 0}var init_mcp_surface=__esm({"libs/sdk/src/transport/mcp-handlers/mcp-surface.ts"(){"use strict"}});var resource_update_access_exports={};__export(resource_update_access_exports,{callerMayStillRead:()=>callerMayStillRead});import{runRequestExclusive}from"@frontmcp/utils";async function callerMayStillRead(scope,session,caller,uri){const request2={method:"resources/subscribe",params:{uri}};const authInfo={...caller,sessionId:session.sessionId};const{platformEnv}=session;const ctx={authInfo,surface:mcpRequestSurface(scope),ownRequest:true,checkOnly:true,...platformEnv!==void 0?{platformEnv}:{}};return runRequestExclusive(()=>scope.runFlow("resources:subscribe",{request:request2,ctx})).then(()=>true,()=>false)}var init_resource_update_access=__esm({"libs/sdk/src/notification/resource-update-access.ts"(){"use strict";init_mcp_surface()}});import{ListRootsResultSchema}from"@frontmcp/protocol";import{awaitOutsideRequest}from"@frontmcp/utils";function hasMcpAppsExtension(capabilities){const declared=capabilities?.experimental?.[MCP_APPS_EXTENSION_KEY]??capabilities?.extensions?.[MCP_APPS_EXTENSION_KEY];return declared!==void 0&&declared!==null}function detectPlatformFromCapabilities(capabilities){if(hasMcpAppsExtension(capabilities)){return"ext-apps"}return void 0}function supportsElicitation(capabilities,mode){if(!capabilities?.elicitation){return false}if(mode==="form"){return capabilities.elicitation.form!==void 0}if(mode==="url"){return capabilities.elicitation.url!==void 0}return true}function matchCustomMappings(clientName,mappings){if(!mappings||mappings.length===0){return void 0}const lowerClientName=clientName.toLowerCase();for(const mapping of mappings){if(typeof mapping.pattern==="string"){if(lowerClientName===mapping.pattern.toLowerCase()){return mapping.platform}}else{if(clientName.search(mapping.pattern)!==-1){return mapping.platform}}}return void 0}function defaultPlatformDetection(identifier){const lowerIdentifier=identifier.toLowerCase();if(lowerIdentifier.includes("codex")){return"codex"}if(lowerIdentifier.includes("claude-code")||lowerIdentifier.includes("claude code")){return"claude-code"}if(lowerIdentifier.includes("chatgpt")||lowerIdentifier.includes("openai")||lowerIdentifier.includes("gpt")){return"openai"}if(lowerIdentifier.includes("claude")||lowerIdentifier.includes("anthropic")){return"claude"}if(lowerIdentifier.includes("gemini")||lowerIdentifier.includes("bard")||lowerIdentifier.includes("google-ai")||lowerIdentifier.includes("google ai")){return"gemini"}if(lowerIdentifier.includes("cursor")){return"cursor"}if(lowerIdentifier.includes("continue")){return"continue"}if(lowerIdentifier.includes("cody")||lowerIdentifier.includes("sourcegraph")){return"cody"}if(lowerIdentifier.includes("mcp")){return"generic-mcp"}return"unknown"}function detectPlatformFromUserAgent(userAgent,config){if(!userAgent){return"unknown"}const customMatch=matchCustomMappings(userAgent,config?.mappings);if(customMatch){return customMatch}if(config?.customOnly){return"unknown"}return defaultPlatformDetection(userAgent)}function detectAIPlatform(clientInfo,config){if(!clientInfo?.name){return"unknown"}const customMatch=matchCustomMappings(clientInfo.name,config?.mappings);if(customMatch){return customMatch}if(config?.customOnly){return"unknown"}return defaultPlatformDetection(clientInfo.name)}function resolvePlatformType(clientInfo,capabilities,config){const mapped=clientInfo?.name?matchCustomMappings(clientInfo.name,config?.mappings):void 0;if(mapped)return mapped;const fromCapabilities=detectPlatformFromCapabilities(capabilities);if(fromCapabilities)return fromCapabilities;return detectAIPlatform(clientInfo,config)}function supportsChannels(capabilities){return capabilities?.experimental?.["claude/channel"]!==void 0}function isChannelCapableSession(session){return session.stdio===true||supportsChannels(session.clientCapabilities)}function sessionCallerOf(authInfo){const{clientId,scopes,user,claims:claims3}=authInfo;return{clientId,scopes,user,claims:claims3,expiresAt:authInfo.expiresAt??user?.exp}}function isSameCaller(left,right){return left===right||JSON.stringify(left)===JSON.stringify(right)}function hasExpiredCaller(session){const expiresAt=session.caller?.expiresAt;return expiresAt!==void 0&&expiresAt*1e3<Date.now()}var MCP_APPS_EXTENSION_KEY,MAX_CALLER_RECHECKS,MCP_LOGGING_LEVEL_PRIORITY,NotificationService;var init_notification_service=__esm({"libs/sdk/src/notification/notification.service.ts"(){"use strict";init_list_change_batch();MCP_APPS_EXTENSION_KEY="io.modelcontextprotocol/ui";MAX_CALLER_RECHECKS=3;MCP_LOGGING_LEVEL_PRIORITY={debug:0,info:1,notice:2,warning:3,error:4,critical:5,alert:6,emergency:7};NotificationService=class _NotificationService{constructor(scope,options={}){this.scope=scope;this.options=options;this.logger=scope.logger.child("NotificationService")}scope;options;logger;servers=new Map;unsubscribers=[];subscriptions=new Map;channelSubscriptions=new Map;logLevels=new Map;terminatedSessions=new Set;static MAX_TERMINATED_SESSIONS=1e4;get maxTerminatedSessions(){return this.options.maxTerminatedSessions??_NotificationService.MAX_TERMINATED_SESSIONS}async initialize(){this.logger.verbose("Initializing notification service");const unsubResources=this.scope.resources.subscribe({immediate:false},event=>{if(event.changeScope==="global"){if(event.kind==="updated"&&event.updatedUri){this.notifyResourceUpdated(event.updatedUri)}else if(announcesListChangeNow(this.scope,"resources")){this.broadcastNotification("notifications/resources/list_changed")}}});this.unsubscribers.push(unsubResources);const unsubTools=this.scope.tools.subscribe({immediate:false},event=>{if(event.changeScope==="global"&&announcesListChangeNow(this.scope,"tools")){this.broadcastNotification("notifications/tools/list_changed")}});this.unsubscribers.push(unsubTools);const unsubPrompts=this.scope.prompts.subscribe({immediate:false},event=>{if(event.changeScope==="global"&&announcesListChangeNow(this.scope,"prompts")){this.broadcastNotification("notifications/prompts/list_changed")}});this.unsubscribers.push(unsubPrompts);const skillRegistry=this.scope.skills;if(skillRegistry?.subscribe){const unsubSkills=skillRegistry.subscribe({immediate:false},event=>{if(event.changeScope==="global"&&announcesListChangeNow(this.scope,"skills")){this.broadcastNotification("notifications/skills/list_changed")}});this.unsubscribers.push(unsubSkills)}this.logger.info("Notification service initialized with registry subscriptions")}registerServer(sessionId,server,connection={}){if(this.servers.has(sessionId)){this.logger.warn(`Server already registered for session: ${sessionId.slice(0,20)}...`);return}const registered={sessionId,server,registeredAt:Date.now()};if(connection.stdio)registered.stdio=true;this.servers.set(sessionId,registered);this.logger.verbose(`Registered server for session: ${sessionId.slice(0,20)}... (total: ${this.servers.size})`)}unregisterServer(sessionId){const deleted=this.servers.delete(sessionId);const subCount=this.subscriptions.get(sessionId)?.size??0;this.subscriptions.delete(sessionId);const channelSubCount=this.channelSubscriptions.get(sessionId)?.size??0;this.channelSubscriptions.delete(sessionId);const hadLogLevel=this.logLevels.delete(sessionId);if(deleted){this.logger.verbose(`Unregistered server for session: ${sessionId.slice(0,20)}... (remaining: ${this.servers.size}, cleaned ${subCount} resource sub(s), ${channelSubCount} channel sub(s)${hadLogLevel?", removed log level":""})`)}return deleted}terminateSession(sessionId){const wasRegistered=this.unregisterServer(sessionId);this.scope.providers.cleanupSession(sessionId);this.logger.verbose(`Cleaned up provider cache for terminated session: ${sessionId.slice(0,20)}...`);this.scope.skillSession?.endSession(sessionId).catch(error=>{this.logger.warn(`Failed to forget the skill session of ${sessionId.slice(0,20)}...: ${String(error)}`)});if(this.terminatedSessions.size>=this.maxTerminatedSessions){const oldest=this.terminatedSessions.values().next().value;if(oldest){this.terminatedSessions.delete(oldest);this.logger.verbose(`Evicted oldest terminated session to make room: ${oldest.slice(0,20)}...`)}}this.terminatedSessions.add(sessionId);this.logger.verbose(`Terminated session: ${sessionId.slice(0,20)}... (total terminated: ${this.terminatedSessions.size})`);return wasRegistered}isSessionTerminated(sessionId){return this.terminatedSessions.has(sessionId)}unmarkTerminated(sessionId){this.terminatedSessions.delete(sessionId)}broadcastNotification(method,params){if(this.servers.size===0){this.logger.verbose(`No servers registered for notification: ${method}`);return}this.logger.verbose(`Broadcasting ${method} to ${this.servers.size} server(s)`);for(const[sessionId,{server}]of this.servers){this.sendNotificationToServer(server,sessionId,method,params)}}sendNotificationToSession(sessionId,method,params){const registered=this.servers.get(sessionId);if(!registered){const relay=this.scope.haManager?.getRelay();const transportService=this.scope.transportService;if(relay&&transportService){this.logger.debug(`[HA] Relaying notification ${method} for non-local session ${sessionId.slice(0,20)}...`);void this.relayNotification(sessionId,method,params);return}this.logger.warn(`Cannot send notification to unregistered session: ${sessionId.slice(0,20)}...`);return}this.sendNotificationToServer(registered.server,sessionId,method,params)}deliverRelayedNotification(sessionId,method,params){const registered=this.servers.get(sessionId);if(!registered){this.logger.verbose(`[HA] Relayed ${method} for session ${sessionId.slice(0,20)}... not served here \u2014 dropped`);return false}this.sendNotificationToServer(registered.server,sessionId,method,params);return true}async relayNotification(sessionId,method,params){const label=sessionId.slice(0,20);try{const owner=await this.scope.transportService?.lookupSessionOwner(sessionId);const relay=this.scope.haManager?.getRelay();if(!owner||!relay||owner.nodeId===this.scope.haManager?.getNodeId()){this.logger.warn(`Cannot send notification to unregistered session: ${label}...`);return}await relay.publish(owner.nodeId,sessionId,{method,params})}catch{this.logger.warn(`[HA] Failed to relay notification ${method} to session ${label}...`)}}subscribeResource(sessionId,uri,platformEnv){const registered=this.servers.get(sessionId);if(!registered){this.logger.warn(`Cannot subscribe unregistered session ${sessionId.slice(0,20)}... to resource ${uri}`);return false}if(platformEnv!==void 0)registered.platformEnv=platformEnv;let sessionSubs=this.subscriptions.get(sessionId);if(!sessionSubs){sessionSubs=new Set;this.subscriptions.set(sessionId,sessionSubs)}const isNew=!sessionSubs.has(uri);sessionSubs.add(uri);if(isNew){this.logger.verbose(`Session ${sessionId.slice(0,20)}... subscribed to resource ${uri}`)}return isNew}unsubscribeResource(sessionId,uri){const sessionSubs=this.subscriptions.get(sessionId);if(!sessionSubs){return false}const wasSubscribed=sessionSubs.delete(uri);if(sessionSubs.size===0){this.subscriptions.delete(sessionId)}if(wasSubscribed){this.logger.verbose(`Session ${sessionId.slice(0,20)}... unsubscribed from resource ${uri}`)}return wasSubscribed}isSubscribed(sessionId,uri){return this.subscriptions.get(sessionId)?.has(uri)??false}getSubscribersForResource(uri){const subscribers=[];for(const[sessionId,uris]of this.subscriptions){if(uris.has(uri)){subscribers.push(sessionId)}}return subscribers}notifyResourceUpdated(uri){const subscribers=this.getSubscribersForResource(uri);if(subscribers.length===0){this.logger.verbose(`No subscribers for resource ${uri}, skipping notification`);return}this.logger.verbose(`Notifying ${subscribers.length} subscriber(s) of resource update: ${uri}`);for(const sessionId of subscribers){void this.notifyIfStillReadable(sessionId,uri)}}async notifyIfStillReadable(sessionId,uri){const registered=this.servers.get(sessionId);if(!registered||hasExpiredCaller(registered))return;const{callerMayStillRead:callerMayStillRead2}=await Promise.resolve().then(()=>(init_resource_update_access(),resource_update_access_exports));let checkedCaller=registered.caller;for(let attempt=0;attempt<MAX_CALLER_RECHECKS;attempt++){const mayRead=await callerMayStillRead2(this.scope,registered,checkedCaller,uri);const current=this.servers.get(sessionId);if(current!==registered||!this.isSubscribed(sessionId,uri)||hasExpiredCaller(current))return;if(isSameCaller(current.caller,checkedCaller)){if(mayRead)this.sendNotificationToSession(sessionId,"notifications/resources/updated",{uri});return}checkedCaller=current.caller}}subscribeChannel(sessionId,channelName){if(!this.servers.has(sessionId)){this.logger.warn(`Cannot subscribe unregistered session ${sessionId.slice(0,20)}... to channel ${channelName}`);return false}let sessionSubs=this.channelSubscriptions.get(sessionId);if(!sessionSubs){sessionSubs=new Set;this.channelSubscriptions.set(sessionId,sessionSubs)}const isNew=!sessionSubs.has(channelName);sessionSubs.add(channelName);if(isNew){this.logger.verbose(`Session ${sessionId.slice(0,20)}... subscribed to channel "${channelName}"`)}return isNew}unsubscribeChannel(sessionId,channelName){const sessionSubs=this.channelSubscriptions.get(sessionId);if(!sessionSubs)return false;const wasSubscribed=sessionSubs.delete(channelName);if(sessionSubs.size===0){this.channelSubscriptions.delete(sessionId)}return wasSubscribed}subscribeAllChannels(sessionId,channelNames){for(const name59 of channelNames){this.subscribeChannel(sessionId,name59)}}isChannelSubscribed(sessionId,channelName){return this.channelSubscriptions.get(sessionId)?.has(channelName)??false}getSubscribersForChannel(channelName){const subscribers=[];for(const[sessionId,channels]of this.channelSubscriptions){if(channels.has(channelName)){subscribers.push(sessionId)}}return subscribers}getChannelSubscriptions(sessionId){const subs=this.channelSubscriptions.get(sessionId);return subs?[...subs]:[]}get serverCount(){return this.servers.size}setLogLevel(sessionId,level){if(!this.servers.has(sessionId)){this.logger.warn(`Cannot set log level for unregistered session: ${sessionId.slice(0,20)}...`);return false}this.logLevels.set(sessionId,level);this.logger.verbose(`Set log level to '${level}' for session ${sessionId.slice(0,20)}...`);return true}getLogLevel(sessionId){return this.logLevels.get(sessionId)}sendLogMessage(level,loggerName,data){const messagePriority=MCP_LOGGING_LEVEL_PRIORITY[level];for(const[sessionId,{server}]of this.servers){const sessionLevel=this.logLevels.get(sessionId);if(!sessionLevel){continue}const sessionPriority=MCP_LOGGING_LEVEL_PRIORITY[sessionLevel];if(messagePriority>=sessionPriority){const params={level,data};if(loggerName){params["logger"]=loggerName}this.sendNotificationToServer(server,sessionId,"notifications/message",params)}}}sendLogMessageToSession(sessionId,level,loggerName,data,relatedRequestId){const registered=this.servers.get(sessionId);if(!registered){return false}const sessionLevel=this.logLevels.get(sessionId);if(!sessionLevel){return false}const messagePriority=MCP_LOGGING_LEVEL_PRIORITY[level];const sessionPriority=MCP_LOGGING_LEVEL_PRIORITY[sessionLevel];if(messagePriority<sessionPriority){return false}const params={level,data};if(loggerName){params["logger"]=loggerName}this.sendNotificationToServer(registered.server,sessionId,"notifications/message",params,relatedRequestId);return true}sendProgressNotification(sessionId,progressToken,progress,total,message,relatedRequestId){const registered=this.servers.get(sessionId);if(!registered){return false}const params={progressToken,progress,...total!==void 0&&{total},...message!==void 0&&{message}};this.sendNotificationToServer(registered.server,sessionId,"notifications/progress",params,relatedRequestId);return true}setClientCapabilities(sessionId,capabilities){const registered=this.servers.get(sessionId);if(!registered){this.logger.warn(`Cannot set client capabilities for unregistered session: ${sessionId.slice(0,20)}...`);return false}registered.clientCapabilities=capabilities;if(!registered.clientInfo)registered.platformType=detectPlatformFromCapabilities(capabilities);this.logger.verbose(`Set client capabilities for session ${sessionId.slice(0,20)}...: roots.listChanged=${capabilities.roots?.listChanged??false}`);return true}setCaller(sessionId,caller){const registered=this.servers.get(sessionId);if(!registered)return false;registered.caller=caller;return true}getClientCapabilities(sessionId){return this.servers.get(sessionId)?.clientCapabilities}setClientInfo(sessionId,clientInfo){const registered=this.servers.get(sessionId);if(!registered){this.logger.warn(`Cannot set client info for unregistered session: ${sessionId.slice(0,20)}...`);return void 0}registered.clientInfo=clientInfo;const platformDetectionConfig=this.scope.metadata.transport?.platformDetection;registered.platformType=resolvePlatformType(clientInfo,registered.clientCapabilities,platformDetectionConfig);this.logger.verbose(`Set client info for session ${sessionId.slice(0,20)}...: name=${clientInfo.name}, version=${clientInfo.version}, platform=${registered.platformType}`);return registered.platformType}getClientInfo(sessionId){return this.servers.get(sessionId)?.clientInfo}getPlatformType(sessionId){const session=this.servers.get(sessionId);return session?.platformType??"unknown"}supportsRoots(sessionId){const capabilities=this.getClientCapabilities(sessionId);return capabilities?.roots!==void 0}async listRoots(sessionId,options){const registered=this.servers.get(sessionId);if(!registered){this.logger.warn(`Cannot list roots for unregistered session: ${sessionId.slice(0,20)}...`);return[]}if(!this.supportsRoots(sessionId)){this.logger.verbose(`Client for session ${sessionId.slice(0,20)}... does not support roots`);return[]}if(!options?.forceRefresh&&registered.cachedRoots!==void 0){this.logger.verbose(`Returning cached roots for session ${sessionId.slice(0,20)}... (${registered.cachedRoots.length} roots)`);return registered.cachedRoots}try{this.logger.verbose(`Requesting roots from client for session ${sessionId.slice(0,20)}...`);const result=await awaitOutsideRequest(registered.server.request({method:"roots/list"},ListRootsResultSchema,{timeout:options?.timeout??3e4}));registered.cachedRoots=result.roots;registered.rootsFetchedAt=Date.now();this.logger.verbose(`Received ${registered.cachedRoots.length} root(s) from client for session ${sessionId.slice(0,20)}...`);return registered.cachedRoots}catch(error){this.logger.warn(`Failed to list roots for session ${sessionId.slice(0,20)}...: ${error instanceof Error?error.message:"Unknown error"}`);return registered.cachedRoots??[]}}invalidateRootsCache(sessionId){const registered=this.servers.get(sessionId);if(!registered){return false}const hadCache=registered.cachedRoots!==void 0;registered.cachedRoots=void 0;registered.rootsFetchedAt=void 0;if(hadCache){this.logger.verbose(`Invalidated roots cache for session ${sessionId.slice(0,20)}...`)}return hadCache}getCachedRoots(sessionId){return this.servers.get(sessionId)?.cachedRoots}async destroy(){this.logger.verbose("Destroying notification service");for(const unsub of this.unsubscribers){unsub()}this.unsubscribers.length=0;this.servers.clear();this.subscriptions.clear();this.logLevels.clear();this.terminatedSessions.clear();this.logger.info("Notification service destroyed")}sendCustomNotification(method,params,filter){if(this.servers.size===0){this.logger.verbose(`No servers registered for custom notification: ${method}`);return}let sent=0;for(const[sessionId,registered]of this.servers){if(filter&&!filter(registered))continue;this.sendNotificationToServer(registered.server,sessionId,method,params);sent++}this.logger.verbose(`Sent custom notification ${method} to ${sent}/${this.servers.size} session(s)`)}getChannelCapableSessions(){return[...this.servers.values()].filter(isChannelCapableSession)}getRegisteredServer(sessionId){return this.servers.get(sessionId)}sendNotificationToServer(server,sessionId,method,params,relatedRequestId){if(relatedRequestId!==void 0){void this.sendOnRequestStream(server,sessionId,method,params,relatedRequestId);return}try{server.notification({method,params:params??{}});this.logger.verbose(`Sent ${method} to session ${sessionId.slice(0,20)}...`)}catch(error){this.logger.warn(`Failed to send notification ${method} to session ${sessionId.slice(0,20)}...: ${error instanceof Error?error.message:"Unknown error"}`);this.unregisterServer(sessionId)}}async sendOnRequestStream(server,sessionId,method,params,relatedRequestId){try{await server.notification({method,params:params??{}},{relatedRequestId});this.logger.verbose(`Sent ${method} to session ${sessionId.slice(0,20)}... for request ${relatedRequestId}`)}catch{this.sendNotificationToServer(server,sessionId,method,params)}}}}});var SEP_2640_EXTENSION_ID,SEP_2640_META_NAMESPACE,SKILL_URI_SCHEME,SKILL_INDEX_URI,SKILL_INDEX_SCHEMA_URI,SKILL_MD_MIME_TYPE,SKILL_INDEX_MIME_TYPE,SKILL_MD_PRIORITY;var init_sep_2640_constants=__esm({"libs/sdk/src/skill/sep-2640/sep-2640.constants.ts"(){"use strict";SEP_2640_EXTENSION_ID="io.modelcontextprotocol/skills";SEP_2640_META_NAMESPACE="io.modelcontextprotocol.skills/";SKILL_URI_SCHEME="skill://";SKILL_INDEX_URI="skill://index.json";SKILL_INDEX_SCHEMA_URI="https://schemas.agentskills.io/discovery/0.2.0/schema.json";SKILL_MD_MIME_TYPE="text/markdown";SKILL_INDEX_MIME_TYPE="application/json";SKILL_MD_PRIORITY=.8}});import{createGlobMatcher as createGlobMatcher2}from"@frontmcp/utils";function compile(clients){const known=compiledProfiles.get(clients);if(known)return known;const compiled=Object.entries(clients).map(([glob,profile])=>[createGlobMatcher2(glob.toLowerCase()),profile]);compiledProfiles.set(clients,compiled);return compiled}function resolveClientProfile(clients,clientName){if(!clients||clientName===void 0||clientName.length>MAX_CLIENT_NAME_LENGTH)return void 0;const lowerName=clientName.toLowerCase();return compile(clients).find(([matches])=>matches(lowerName))?.[1]}function callerClientName({context,authInfo,notifications}){const sessionId=authInfo?.sessionId;return context?.clientInfo?.name??authInfo?.sessionIdPayload?.clientName??(sessionId?notifications?.getClientInfo(sessionId)?.name:void 0)}function callerClientProfile(clients,sources3){return clients?resolveClientProfile(clients,callerClientName(sources3)):void 0}function describeValue(value){if(Array.isArray(value))return` (${value.length} ${value.length===1?"item":"items"})`;if(typeof value==="object"&&value!==null)return` (${Object.keys(value).length} keys)`;if(typeof value==="string"){return value.length<=SHORT_STRING?`: ${JSON.stringify(value)}`:` (${value.length} characters)`}return`: ${String(value)}`}function summarizeStructuredContent(structuredContent){const keys=Object.keys(structuredContent);const described=keys.slice(0,SUMMARY_KEYS).map(key=>`${key}${describeValue(structuredContent[key])}`);if(keys.length>SUMMARY_KEYS)described.push(`${keys.length-SUMMARY_KEYS} more keys`);return described.length>0?`The answer is in structuredContent: ${described.join(", ")}.`:"The answer is in structuredContent."}function shapeToolAnswer(result,mode,listsOutputSchema){const{structuredContent}=result;if(mode==="both"||structuredContent===void 0)return void 0;if(mode==="text"){const{structuredContent:_dropped,...textOnly}=result;return textOnly}if(!listsOutputSchema||result.isError)return void 0;const structuredText=JSON.stringify(structuredContent);const summary=summarizeStructuredContent(structuredContent);return{...result,content:result.content.map(block=>block.type==="text"&&block.text===structuredText?{...block,text:summary}:block)}}function annotationsForClient(annotations,mode,skillMd){if(mode==="no-numbers"){if(!annotations||annotations.priority===void 0)return annotations;const{priority:_dropped,...withoutNumbers}=annotations;return Object.keys(withoutNumbers).length>0?withoutNumbers:void 0}if(mode==="full"&&skillMd){return{audience:["assistant"],...annotations,priority:SKILL_MD_PRIORITY}}return annotations}var SUMMARY_KEYS,SHORT_STRING,MAX_CLIENT_NAME_LENGTH,compiledProfiles;var init_client_profile=__esm({"libs/sdk/src/answer/client-profile.ts"(){"use strict";init_sep_2640_constants();SUMMARY_KEYS=12;SHORT_STRING=40;MAX_CLIENT_NAME_LENGTH=256;compiledProfiles=new WeakMap}});import{checkEntryAvailability,getRuntimeContext as getRuntimeContext3,isEntryAvailable}from"@frontmcp/utils";function callSurfaceOf(ctx){const surface=ctx?.surface;return typeof surface==="string"&&CALL_SURFACES.includes(surface)?surface:void 0}function isOfferedOnSurface(availability,surface){const offered=availability?.surface;return offered===void 0||surface===void 0||offered.includes(surface)}function availabilityForCall(availability,surface){if(!isOfferedOnSurface(availability,surface))return"not-offered";return isEntryAvailable(availability,getRuntimeContext3())?"available":"unavailable"}function entryUnavailableError(entryType,entryName,availability,surface){const ctx=getRuntimeContext3();const{missingAxes}=checkEntryAvailability(availability,ctx,surface?{surface}:void 0);return new EntryUnavailableError(entryType,entryName,availability,{...ctx,surface},missingAxes)}function logAvailabilityFiltering(registryKind,entries,logger){const ctx=getRuntimeContext3();const constrained=[];const filtered=[];const emptyConstraints=[];const fields=["platform","runtime","deployment","env"];for(const entry of entries){const aw=entry.metadata.availableWhen;if(!aw)continue;constrained.push(entry);for(const field of fields){const arr=aw[field];if(arr&&arr.length===0){emptyConstraints.push(entry);break}}if(!isEntryAvailable(aw,ctx)){filtered.push(entry)}}if(constrained.length===0)return;const available=constrained.length-filtered.length;logger.info(`[${registryKind}] availability: ${entries.length} total, ${constrained.length} with availableWhen constraint, ${available} available, ${filtered.length} filtered [ctx: platform=${ctx.platform}, runtime=${ctx.runtime}, deployment=${ctx.deployment}, env=${ctx.env}]`);for(const entry of filtered){const aw=entry.metadata.availableWhen;logger.verbose(`[${registryKind}] filtered: "${entry.name}" \u2014 constraint=${JSON.stringify(aw)}, current=${formatContextForConstraint(aw,ctx)}`)}for(const entry of emptyConstraints){const aw=entry.metadata.availableWhen;const emptyFields=fields.filter(f=>aw?.[f]?.length===0);logger.warn(`[${registryKind}] "${entry.name}" has empty availableWhen arrays for [${emptyFields.join(", ")}] \u2014 this entry will never be available. This is likely a configuration bug.`)}}function formatContextForConstraint(aw,ctx){const parts=[];if(aw.platform)parts.push(`platform=${ctx.platform}`);if(aw.runtime)parts.push(`runtime=${ctx.runtime}`);if(aw.deployment)parts.push(`deployment=${ctx.deployment}`);if(aw.env)parts.push(`env=${ctx.env}`);return parts.join(", ")}var CALL_SURFACES;var init_availability_utils=__esm({"libs/sdk/src/common/availability/availability.utils.ts"(){"use strict";init_mcp_error();CALL_SURFACES=["mcp","cli","http-trigger","job","agent","webmcp"]}});var init_availability=__esm({"libs/sdk/src/common/availability/index.ts"(){"use strict";init_availability_utils()}});var AUTHORITIES_NOT_CONFIGURED;var init_authorities_not_configured=__esm({"libs/sdk/src/builtin/authorities/authorities-not-configured.ts"(){"use strict";AUTHORITIES_NOT_CONFIGURED="no authorities engine is configured (add 'authorities' to @FrontMcp())"}});async function isListedByAuthorities(engine,contextBuilder,authorities,authInfo,entryName,logger){try{const result=await engine.evaluate(authorities,contextBuilder.build(authInfo));return result.granted}catch(error){logger?.warn(`The authorities of "${entryName}" failed to answer, so it is left out of the list: ${error instanceof Error?error.message:String(error)}`);return false}}var init_entry_authorized=__esm({"libs/sdk/src/surface/entry-authorized.ts"(){"use strict"}});import{AuthorityDeniedError as AuthorityDeniedError2,resolveRequiredScopes}from"@frontmcp/auth";function normalizeAuthInfoForAuthorities(authInfo){if(authInfo["user"])return authInfo;const extra=authInfo["extra"];const extraUser=extra?.["user"];if(extraUser)return{...authInfo,user:extraUser};return authInfo}function getSkillAuthorities(skill){const metadata=skill.metadata;const authorities=metadata["authorities"];return authorities}async function assertSkillAuthorized(scope,skill,authInfo,input={}){const authorities=getSkillAuthorities(skill);if(!authorities)return;const engine=scope.authoritiesEngine;const ctxBuilder=scope.authoritiesContextBuilder;if(!engine||!ctxBuilder){throw new AuthorityDeniedError2({entryType:"Skill",entryName:skill.fullName||skill.name,deniedBy:AUTHORITIES_NOT_CONFIGURED})}const evalCtx=ctxBuilder.build(normalizeAuthInfoForAuthorities(authInfo),input);const result=await engine.evaluate(authorities,evalCtx);if(result.granted)return;let requiredScopes;const scopeMapping=scope.authoritiesScopeMapping;if(scopeMapping&&result.denial){requiredScopes=resolveRequiredScopes(result.denial,scopeMapping,authorities)}throw new AuthorityDeniedError2({entryType:"Skill",entryName:skill.fullName||skill.name,deniedBy:result.deniedBy??"policy denied",denial:result.denial,requiredScopes})}async function filterSkillsByAuthorities(scope,skills,authInfo){const engine=scope.authoritiesEngine;const ctxBuilder=scope.authoritiesContextBuilder;if(!engine||!ctxBuilder)return skills.filter(skill=>!getSkillAuthorities(skill));const normalized2=normalizeAuthInfoForAuthorities(authInfo);const grants=await Promise.all(skills.map(async skill=>{const authorities=getSkillAuthorities(skill);if(!authorities)return true;return isListedByAuthorities(engine,ctxBuilder,authorities,normalized2,skill.fullName||skill.name,scope.logger)}));return skills.filter((_,i)=>grants[i])}var init_skill_authorities_helper=__esm({"libs/sdk/src/skill/skill-authorities.helper.ts"(){"use strict";init_authorities_not_configured();init_entry_authorized()}});var SkillBundleNotLoadedError;var init_skill_bundle_not_loaded_error=__esm({"libs/sdk/src/skill/errors/skill-bundle-not-loaded.error.ts"(){"use strict";init_errors();SkillBundleNotLoadedError=class extends PublicMcpError{constructor(reason){super(`No skill bundle is loaded: ${reason}`,"SKILL_BUNDLE_NOT_LOADED",503)}toJsonRpcError(){return{code:MCP_ERROR_CODES.INTERNAL_ERROR,message:this.getPublicMessage(),data:{code:this.code,retryable:true}}}toMcpError(isDevelopment7=false){const response=super.toMcpError(isDevelopment7);return response._meta?{...response,_meta:{...response._meta,retryable:true}}:response}}}});function findSkillCatalogSource(scope){if(!scope.providers)return void 0;try{return scope.providers.get(SkillCatalogSourceToken)}catch(error){if(error instanceof ProviderNotRegisteredError||error instanceof ProviderNotAvailableError||error instanceof DependencyNotFoundError){return void 0}scope.logger.warn("the skill source provider failed; serving skills without it",{error:error instanceof Error?error.message:String(error)});return void 0}}async function readySkillCatalog(scope){const source=findSkillCatalogSource(scope);if(!source)return{};try{await source.ready()}catch(error){scope.logger.warn("a skill source failed to load; serving the skills registered so far",{error:error instanceof Error?error.message:String(error)})}return{source,notLoadedReason:notLoadedReasonOf(source,scope)}}function notLoadedReasonOf(source,scope){try{return source.notLoadedReason?.()}catch(error){scope.logger.warn("a skill source failed to report whether its skills loaded; serving the skills registered so far",{error:error instanceof Error?error.message:String(error)});return void 0}}async function assertSkillCatalogLoaded(scope){const{notLoadedReason}=await readySkillCatalog(scope);if(notLoadedReason!==void 0)throw new SkillBundleNotLoadedError(notLoadedReason)}var SkillCatalogSourceToken;var init_skill_catalog_source=__esm({"libs/sdk/src/skill/skill-catalog-source.ts"(){"use strict";init_errors();init_skill_bundle_not_loaded_error();SkillCatalogSourceToken=Symbol.for("frontmcp:SKILL_CATALOG_SOURCE")}});import{isAnonymousSubject as isAnonymousSubject2}from"@frontmcp/auth";function publicAccessFor(authOptions,authInfo){const publicAccess=authOptions?.publicAccess;if(!publicAccess)return void 0;const info=authInfo;return isAnonymousSubject2(info?.user?.sub??info?.extra?.user?.sub)?publicAccess:void 0}function isPubliclyListed(publicAccess,kind,names){const allowed=publicAccess[kind]??"all";return allowed==="all"||names.some(name59=>allowed.includes(name59))}async function enforcePublicAccess(publicAccess,entry,guard,partition){if(!isPubliclyListed(publicAccess,entry.kind==="tool"?"tools":"prompts",entry.names)){throw new PublicAccessDeniedError(entry.kind,entry.names[0])}if(!guard||!publicAccess.rateLimit)return;const result=await guard.checkRateLimit(PUBLIC_ACCESS_RATE_LIMIT_KEY,{maxRequests:publicAccess.rateLimit,windowMs:PUBLIC_ACCESS_WINDOW_MS,partitionBy:"ip"},partition);if(!result.allowed)throw new RateLimitError(Math.ceil((result.retryAfterMs??PUBLIC_ACCESS_WINDOW_MS)/1e3))}var PUBLIC_ACCESS_RATE_LIMIT_KEY,PUBLIC_ACCESS_WINDOW_MS;var init_public_access_utils=__esm({"libs/sdk/src/auth/public-access.utils.ts"(){"use strict";init_errors();PUBLIC_ACCESS_RATE_LIMIT_KEY="__public_access__";PUBLIC_ACCESS_WINDOW_MS=6e4}});import{AsyncLocalStorage as AsyncLocalStorage4}from"@frontmcp/utils";function runOnSurface(surface,fn){return callSurfaces.run({surface},fn)}function getCallSurface(){return callSurfaces.getStore()?.surface}var callSurfaces;var init_call_surface=__esm({"libs/sdk/src/context/call-surface.ts"(){"use strict";callSurfaces=new AsyncLocalStorage4}});function skillResultId(result){return result.metadata.id??result.metadata.name}function createSkillEntryResolver(registry){let fallback;const fallbackEntry=id=>{if(!fallback){const skills=registry.getSkills(true);fallback=new Map;for(const skill of skills){const skillId=skill.metadata.id??skill.name;if(!fallback.has(skillId))fallback.set(skillId,skill)}for(const skill of skills){if(!fallback.has(skill.metadata.name))fallback.set(skill.metadata.name,skill)}}return fallback.get(id)};const lookup=id=>registry.findByName(id)??(id.includes(":")?registry.findByQualifiedName(id):void 0)??fallbackEntry(id);return(...ids)=>{for(const id of ids){if(!id)continue;const entry=lookup(id);if(entry)return entry}return void 0}}var init_skill_entry_resolver=__esm({"libs/sdk/src/skill/skill-entry.resolver.ts"(){"use strict"}});function callerSurface(ctx,surface){return surface??callSurfaceOf(ctx)??getCallSurface()}async function filterServableSkills(scope,skills,ctx,surface){const caller=callerSurface(ctx,surface);const offered=skills.filter(skill=>availabilityForCall(skill.metadata.availableWhen,caller)==="available");if(offered.length===0)return[];const{skills:servable}=await scope.runFlowForOutput("skills:filter",{skills:[...offered],ctx});const servableSkills=new Set(servable);return offered.filter(skill=>servableSkills.has(skill))}async function isSkillServable(scope,skill,ctx,surface){const servable=await filterServableSkills(scope,[skill],ctx,surface);return servable.length===1}async function filterDiscoverableSkillResults(scope,registry,results,caller={}){const resolve4=createSkillEntryResolver(registry);const entries=results.map(result=>resolve4(skillResultId(result)));const registered=[...new Set(entries.filter(entry=>entry!==void 0))];const authorized=await filterSkillsByAuthorities(scope,registered,caller.authInfo??{});const servable=new Set(await filterServableSkills(scope,authorized,caller.ctx,caller.surface));return results.filter((_,index)=>{const entry=entries[index];return entry===void 0||servable.has(entry)})}function skillToolsForCaller(loaded,tools,ctx,surface){const caller=callerSurface(ctx,surface);if(!tools||caller===void 0||loaded.availableTools.length===0)return loaded;const availability=new Map(tools.getTools(true).map(tool=>[tool.name,tool.metadata?.availableWhen]));return withToolsMissing(loaded,loaded.availableTools.filter(name59=>!isOfferedOnSurface(availability.get(name59),caller)))}async function skillToolsListedFor(scope,loaded,authInfo){const{tools,authoritiesEngine:engine,authoritiesContextBuilder:contextBuilder}=scope;const publicAccess=publicAccessFor(scope.auth?.options,authInfo);if(!tools||loaded.availableTools.length===0||!publicAccess&&(!engine||!contextBuilder))return loaded;const toolsByName=new Map(tools.getTools(true).map(tool=>[tool.name,tool]));const caller=normalizeAuthInfoForAuthorities(authInfo);const listed=await Promise.all(loaded.availableTools.map(async name59=>{const tool=toolsByName.get(name59);if(publicAccess&&!isPubliclyListed(publicAccess,"tools",[tool?.fullName??name59,name59]))return false;const authorities=tool?.metadata?.authorities;if(!authorities||!engine||!contextBuilder)return true;return isListedByAuthorities(engine,contextBuilder,authorities,caller,name59,scope.logger)}));return withToolsMissing(loaded,loaded.availableTools.filter((_,index)=>!listed[index]))}function withToolsMissing(loaded,names){if(names.length===0)return loaded;return{...loaded,availableTools:loaded.availableTools.filter(name59=>!names.includes(name59)),missingTools:[...loaded.missingTools,...names],isComplete:false,warning:warningWithMissingTools(loaded.warning,loaded.skill?.name,names)}}function warningWithMissingTools(warning,skillName,names){const prefix=warning?.match(WARNING_PREFIX);if(warning&&prefix&&warning.endsWith(WARNING_SUFFIX)){const parts=warning.slice(prefix[0].length,-WARNING_SUFFIX.length).split("; ");const missing=parts.findIndex(part=>part.startsWith(MISSING_PART));if(missing===-1)parts.unshift(`${MISSING_PART}${names.join(", ")}`);else parts[missing]=`${parts[missing]}, ${names.join(", ")}`;return`${prefix[0]}${parts.join("; ")}${WARNING_SUFFIX}`}const sentence=`Skill "${skillName??"skill"}" references ${MISSING_PART}${names.join(", ")}${WARNING_SUFFIX}`;return warning?`${warning} ${sentence}`:sentence}var SKILLS_HTTP_SURFACE,WARNING_PREFIX,WARNING_SUFFIX,MISSING_PART;var init_skill_filter_helper=__esm({"libs/sdk/src/skill/skill-filter.helper.ts"(){"use strict";init_public_access_utils();init_availability();init_call_surface();init_entry_authorized();init_skill_authorities_helper();init_skill_entry_resolver();SKILLS_HTTP_SURFACE="mcp";WARNING_PREFIX=/^Skill "(.*)" references /;WARNING_SUFFIX=". Some functionality may be limited.";MISSING_PART="missing tools: "}});function pointersFor(options){return options.pointers??(options.mcpResources===false?METHOD_POINTERS:RESOURCE_POINTERS)}function listedSkills(skillRegistry,options){return options.skills??skillRegistry?.getSkills({visibility:"mcp"})??[]}function sanitizeDescription(raw){if(!raw)return"";return raw.replace(/\r?\n/g," ").replace(/\s+/g," ").replace(/^\s*-{3,}\s*$/g,"").replace(/\\/g,"\\\\").replace(/`/g,"\\`").replace(/\*/g,"\\*").replace(/_/g,"\\_").replace(/\[/g,"\\[").trim()}function sanitizeName(raw){if(!raw)return"(unnamed)";const s=raw.replace(/\s+/g," ").trim();if(!s)return"(unnamed)";return s.length>MAX_SKILL_NAME_CHARS?`${s.slice(0,MAX_SKILL_NAME_CHARS)}\u2026`:s}function buildSkillsCatalogSummary(skillRegistry,options={}){const skills=listedSkills(skillRegistry,options);if(skills.length===0)return"";const pointers=pointersFor(options);const lines=[pointers.header,""];let truncated=false;let shownCount=0;let charCount=lines.join("\n").length;const effectiveCap=MAX_SKILL_CATALOG_CHARS-TRUNCATION_FOOTER_RESERVE;for(const skill of skills){const name59=sanitizeName(skill.metadata.name);const description=sanitizeDescription(skill.getDescription());const line=description?`- **${name59}**: ${description}`:`- **${name59}**`;if(charCount+line.length+1>effectiveCap){truncated=true;break}lines.push(line);charCount+=line.length+1;shownCount+=1}if(truncated){lines.push("",`_(catalog truncated \u2014 showing ${shownCount} of ${skills.length} skills; ${pointers.truncationHint})_`)}return lines.join("\n")}function buildCompactSkillsLine(skillRegistry,options){const count=listedSkills(skillRegistry,options).length;const servesExternalSkills=skillRegistry?.getExternalProvider()?.isReadOnly()===true;if(count===0&&!servesExternalSkills)return"";let skills=count===1?"1 skill":`${count} skills`;if(servesExternalSkills)skills="skills";return`This server has ${skills}: ${pointersFor(options).compact}`}function buildSkillsNotLoadedLine(reason){const singleLineReason=reason.replace(/\s+/g," ").trim();return`This server's skills have not loaded yet (${singleLineReason}). Ask for them again shortly; the server sends notifications/skills/list_changed once they load.`}function composeInitializeInstructions(options){const policy=options.policy??DEFAULT_POLICY;const user=(options.userInstructions??"").trim();const channel2=(options.channelInstructions??"").trim();if(policy==="replace"){if(user.length>0){return user}}if(policy==="off"){return joinSections([user,channel2])}if(options.skillsNotLoaded!==void 0){const notLoaded=buildSkillsNotLoadedLine(options.skillsNotLoaded);return joinSections(policy==="prepend"?[notLoaded,channel2,user]:[user,channel2,notLoaded])}const summaryOptions={mcpResources:options.mcpResources,skills:options.skills,pointers:options.pointers};if(policy==="compact"){return joinSections([user,channel2,buildCompactSkillsLine(options.skillRegistry,summaryOptions)])}const catalog=buildSkillsCatalogSummary(options.skillRegistry,summaryOptions);if(policy==="prepend"){return joinSections([catalog,channel2,user])}return joinSections([user,channel2,catalog])}function buildChannelInstructions(channels,events){const hasChannels=channels?.hasAny()===true;const tellsEvents=(events?.getChannelEvents().length??0)>0;if(!hasChannels&&!tellsEvents)return"";const sentences=["Events arrive as <channel> tags."];if(channels?.getChannelInstances().some(ch=>ch.twoWay))sentences.push(CHANNEL_REPLY_HINT);if(tellsEvents)sentences.push(CHANNEL_EVENT_HINT);return sentences.join(" ")}function instructionsPolicyFor(scope,clientName){const profiled=resolveClientProfile(scope.metadata.clients,clientName)?.instructions;if(profiled==="full")return"append";return profiled??scope.metadata.skillsConfig?.injectInstructions}async function composeCallerInstructions(scope,options={}){const skillsConfig=scope.metadata.skillsConfig;const{source,notLoadedReason}=await readySkillCatalog(scope);const composeOptions={userInstructions:scope.metadata.instructions,channelInstructions:buildChannelInstructions(scope.channels,scope.events),skillRegistry:scope.skills,policy:instructionsPolicyFor(scope,options.clientName),mcpResources:skillsConfig?.mcpResources,pointers:source?.pointers,skillsNotLoaded:notLoadedReason};const withUriHints=options.skillUriHints===true&&notLoadedReason===void 0&&skillUriHintsEnabled(scope);const listsSkills=withUriHints||includesSkillCatalog(composeOptions);let skills=[];if(listsSkills){try{skills=await skillsVisibleTo(scope,options.ctx)}catch(error){scope.logger.warn("initialize instructions: left the skills out, the skills:filter flow failed",{error:error instanceof Error?error.message:String(error)})}}const composed=composeInitializeInstructions({...composeOptions,skills});const uriHints=withUriHints?buildSkillUriHints(skills,scope.skills?.getSep2640InstructionUris?.()??[]):"";return[composed,uriHints].filter(section=>section.length>0).join("\n\n---\n\n")}function buildSkillUriHints(skills,extraUris=[]){if(skills.length===0)return"";const lines=["Available skills (load via resources/read):"];for(const skill of skills){lines.push(`- skill://${skill.getSkillPath()}/SKILL.md \u2014 ${skill.getDescription()}`)}for(const extra of extraUris){lines.push(`- ${extra}`)}return lines.join("\n")}function skillUriHintsEnabled(scope){const skillsConfig=scope.metadata.skillsConfig;if(!skillsConfig?.sep2640InInstructions||skillsConfig.mcpResources===false)return false;const serverInstructions=(scope.metadata.instructions??"").trim();return!(skillsConfig.injectInstructions==="replace"&&serverInstructions.length>0)}function includesSkillCatalog(options){const policy=options.policy??DEFAULT_POLICY;if(policy==="off"||options.skillsNotLoaded!==void 0)return false;return!(policy==="replace"&&(options.userInstructions??"").trim().length>0)}async function skillsVisibleTo(scope,ctx){const visible=scope.skills?.getSkills({visibility:"mcp"})??[];if(visible.length===0)return[];const authInfo=ctx?.authInfo??{};const authorized=await filterSkillsByAuthorities(scope,visible,authInfo);return filterServableSkills(scope,authorized,ctx,callSurfaceOf(ctx)??mcpRequestSurface(scope))}function joinSections(sections){return sections.map(s=>(s??"").trim()).filter(s=>s.length>0).join("\n\n---\n\n")}var DEFAULT_POLICY,MAX_SKILL_CATALOG_CHARS,TRUNCATION_FOOTER_RESERVE,RESOURCE_POINTERS,METHOD_POINTERS,MAX_SKILL_NAME_CHARS,CHANNEL_REPLY_HINT,CHANNEL_EVENT_HINT;var init_skill_instructions_helper=__esm({"libs/sdk/src/skill/skill-instructions.helper.ts"(){"use strict";init_client_profile();init_availability();init_mcp_surface();init_sep_2640_constants();init_skill_authorities_helper();init_skill_catalog_source();init_skill_filter_helper();DEFAULT_POLICY="compact";MAX_SKILL_CATALOG_CHARS=16e3;TRUNCATION_FOOTER_RESERVE=160;RESOURCE_POINTERS={header:`Available skills (read the \`${SKILL_INDEX_URI}\` resource for each skill's \`SKILL.md\` URI):`,truncationHint:`read \`${SKILL_INDEX_URI}\` to browse`,compact:`the \`${SKILL_INDEX_URI}\` resource lists each skill's \`SKILL.md\` URI.`};METHOD_POINTERS={header:"Available skills (load full content with the `skills/load` request, or find others with `skills/search`):",truncationHint:"use `skills/search` to find the rest",compact:"find one with the `skills/search` request and load it with `skills/load`."};MAX_SKILL_NAME_CHARS=80;CHANNEL_REPLY_HINT="Reply with the channel-reply tool.";CHANNEL_EVENT_HINT="A tag with event and event_id attributes is an event this server published: event is its name, event_id its id."}});function computeTaskCapabilities(scope){const registry=scope.tasks;if(!registry)return{};const hasTaskEnabledTool=scope.tools.getTools(true).some(t=>{const supp=t.metadata.execution?.taskSupport;return supp==="optional"||supp==="required"});const canIdentifyRequestors=true;return registry.getCapabilities({hasTaskEnabledTool,canIdentifyRequestors})}var init_task_scope_helper=__esm({"libs/sdk/src/task/task-scope.helper.ts"(){"use strict"}});var build_scoped_server_options_exports={};__export(build_scoped_server_options_exports,{buildScopedServerOptions:()=>buildScopedServerOptions});function buildScopedServerOptions(scope,instructions=""){const hasRemoteApps=scope.apps?.getApps().some(app=>app.isRemote)??false;const hasPrompts=scope.prompts.hasAny()||hasRemoteApps;const hasResources=scope.resources.hasAny()||hasRemoteApps;const completionsCapability=hasPrompts||hasResources?{completions:{}}:{};const remoteCapabilities=hasRemoteApps?{tools:{listChanged:true},resources:{subscribe:true,listChanged:true},prompts:{listChanged:true}}:{};const skillsCapabilities=scope.skills?.getCapabilities()??{};const toolsCapabilities=scope.tools.getCapabilities();const resourcesCapabilities=scope.resources.getCapabilities();const promptsCapabilities=scope.prompts.getCapabilities();const agentsCapabilities=scope.agents.getCapabilities();const channelCapabilities=channelCapabilitiesOf(scope);const eventCapabilities=scope.events?.getCapabilities()??{};const taskCapabilities=computeTaskCapabilities(scope);const fragments=[remoteCapabilities,toolsCapabilities,resourcesCapabilities,promptsCapabilities,agentsCapabilities,channelCapabilities,eventCapabilities,skillsCapabilities,completionsCapability,taskCapabilities];const experimental={};const extensions={};for(const cap2 of fragments){if(cap2["experimental"]&&typeof cap2["experimental"]==="object"){Object.assign(experimental,cap2["experimental"])}if(cap2["extensions"]&&typeof cap2["extensions"]==="object"){Object.assign(extensions,cap2["extensions"])}}const baseCapabilities={...remoteCapabilities,...toolsCapabilities,...resourcesCapabilities,...promptsCapabilities,...agentsCapabilities,...eventCapabilities,...completionsCapability,...taskCapabilities,logging:{}};if(Object.keys(experimental).length>0)baseCapabilities["experimental"]=experimental;if(Object.keys(extensions).length>0)baseCapabilities["extensions"]=extensions;return{instructions,capabilities:baseCapabilities,serverInfo:scope.metadata.info}}var init_build_scoped_server_options=__esm({"libs/sdk/src/transport/build-scoped-server-options.ts"(){"use strict";init_channel_utils();init_task_scope_helper()}});import{AjvJsonSchemaValidator,McpServer}from"@frontmcp/protocol";function createMcpServer(info,options){let validator;return new McpServer(info,{...options,jsonSchemaValidator:{getValidator:schema=>(validator??=new AjvJsonSchemaValidator).getValidator(schema)}})}var init_mcp_server_factory=__esm({"libs/sdk/src/transport/mcp-server.factory.ts"(){"use strict"}});import{McpError as McpError2}from"@frontmcp/protocol";import{isProduction as isProduction3}from"@frontmcp/utils";function hasJsonRpcError(err){return typeof err?.toJsonRpcError==="function"}function jsonRpcCodeForStatus(statusCode){if(statusCode===401)return MCP_ERROR_CODES.UNAUTHORIZED;if(statusCode===403)return MCP_ERROR_CODES.FORBIDDEN;return statusCode<500?MCP_ERROR_CODES.INVALID_PARAMS:MCP_ERROR_CODES.INTERNAL_ERROR}function errorBehindFlowControl(err){if(!(err instanceof FlowControl))return err;const original=err.originalError;if(err.type==="fail"&&original!==void 0)return original;return new InternalMcpError(`Flow ended with: ${err.type}`)}function toReportedError(err){const failure=errorBehindFlowControl(err);return failure instanceof McpError2?failure:toMcpError(failure)}function remedyData(error){return isPublicError(error)&&error.remedy?{remedy:error.remedy}:{}}function toSdkMcpError(err){const error=toReportedError(err);if(error instanceof McpError2)return error;if(hasJsonRpcError(error)){const jsonRpc=error.toJsonRpcError();return new McpError2(jsonRpc.code,jsonRpc.message,{...jsonRpc.data,errorId:error.errorId,...remedyData(error)})}const data={errorId:error.errorId,code:error.code,...remedyData(error)};if(error.isPublic){return new McpError2(jsonRpcCodeForStatus(error.statusCode),error.getPublicMessage(),data)}const message=isProduction3()?error.getPublicMessage():error.message;return new McpError2(MCP_ERROR_CODES.INTERNAL_ERROR,message,data)}var init_mcp_error_utils=__esm({"libs/sdk/src/transport/mcp-handlers/mcp-error.utils.ts"(){"use strict";init_common();init_errors()}});import{CallToolResultSchema}from"@frontmcp/protocol";function toolCallErrorResult(error,options){const{errorHandler,toolName,logger}=options;if(error instanceof FlowControl){if(error.type==="respond"){const parsed=CallToolResultSchema.safeParse(error.output);if(parsed.success)return parsed.data;logger?.error("FlowControl.respond has invalid output",{tool:toolName,validationErrors:parsed.error.issues});return formatMcpErrorResponse(new InternalMcpError("FlowControl output is not a valid CallToolResult"))}const original=error.originalError;if(error.type==="fail"&&original!==void 0){return errorHandler.handle(original,{toolName})}logger?.warn(`FlowControl ended with type: ${error.type}`,{tool:toolName,type:error.type,output:error.output});return formatMcpErrorResponse(new InternalMcpError(`Flow ended with: ${error.type}`))}if(error instanceof InputRequiredSignal||error instanceof MissingClientCapabilityError){throw error}if(error instanceof TaskAugmentationNotSupportedError||error instanceof TaskAugmentationRequiredError||error instanceof ToolCredentialsRequiredError){throw toSdkMcpError(error)}return errorHandler.handle(error,{toolName})}var init_call_tool_error_utils=__esm({"libs/sdk/src/transport/mcp-handlers/call-tool-error.utils.ts"(){"use strict";init_common();init_errors();init_mcp_error_utils()}});import{CallToolRequestSchema}from"@frontmcp/protocol";function callToolRequestHandler({scope}){const logger=scope.logger.child("call-tool-request-handler");const errorHandler=new ErrorHandler({logger});return{requestSchema:CallToolRequestSchema,handler:async(request2,ctx)=>{const toolName=request2.params?.name||"unknown";logger.info(`tools/call: ${toolName}`);const start=Date.now();try{const taggedCtx=withMcpSurface(scope,ctx);const result=await scope.runFlowForOutput("tools:call-tool",{request:request2,ctx:taggedCtx});logger.verbose("tools/call completed",{tool:toolName,durationMs:Date.now()-start});return result}catch(e){return toolCallErrorResult(e,{errorHandler,toolName,logger})}}}}var init_call_tool_request_handler=__esm({"libs/sdk/src/transport/mcp-handlers/call-tool-request.handler.ts"(){"use strict";init_errors();init_call_tool_error_utils();init_mcp_surface()}});import{CompleteRequestSchema}from"@frontmcp/protocol";function completeRequestHandler({scope}){const logger=scope.logger.child("complete-request-handler");return{requestSchema:CompleteRequestSchema,handler:async(request2,ctx)=>{logger.verbose("completion/complete requested");const start=Date.now();try{const result=await scope.runFlowForOutput("completion:complete",{request:request2,ctx:withMcpSurface(scope,ctx)});logger.verbose("completion/complete completed",{durationMs:Date.now()-start});return result}catch(e){logger.error("completion/complete failed",{error:e instanceof Error?{name:e.name,message:e.message,stack:e.stack}:e});throw e}}}}var init_complete_request_handler=__esm({"libs/sdk/src/transport/mcp-handlers/complete-request.handler.ts"(){"use strict";init_mcp_surface()}});import{ListEventsRequestSchema}from"@frontmcp/protocol";function eventsListRequestHandler({scope}){const logger=scope.logger.child("events-list-request-handler");return{requestSchema:ListEventsRequestSchema,handler:async(request2,ctx)=>{logger.verbose("events/list requested");try{return await scope.runFlowForOutput("events:list",{request:request2,ctx:withMcpSurface(scope,ctx)})}catch(error){throw toSdkMcpError(error)}}}}var init_events_list_request_handler=__esm({"libs/sdk/src/transport/mcp-handlers/events-list-request.handler.ts"(){"use strict";init_mcp_error_utils();init_mcp_surface()}});import{PollEventsRequestSchema}from"@frontmcp/protocol";function eventsPollRequestHandler({scope}){const logger=scope.logger.child("events-poll-request-handler");return{requestSchema:PollEventsRequestSchema,handler:async(request2,ctx)=>{logger.verbose(`events/poll requested for "${request2.params.name}"`);try{return await scope.runFlowForOutput("events:poll",{request:request2,ctx:withMcpSurface(scope,ctx)})}catch(error){throw toSdkMcpError(error)}}}}var init_events_poll_request_handler=__esm({"libs/sdk/src/transport/mcp-handlers/events-poll-request.handler.ts"(){"use strict";init_mcp_error_utils();init_mcp_surface()}});import{MCP_20260728_META as MCP_20260728_META2,StreamEventsRequestSchema}from"@frontmcp/protocol";import{awaitOutsideRequest as awaitOutsideRequest2}from"@frontmcp/utils";function eventsStreamRequestHandler({scope}){const logger=scope.logger.child("events-stream-request-handler");return{requestSchema:StreamEventsRequestSchema,handler:async(request2,ctx)=>{logger.verbose(`events/stream requested for "${request2.params.name}"`);let opened;try{opened=await scope.runFlowForOutput("events:stream",{request:request2,ctx:withMcpSurface(scope,ctx),requestId:ctx.requestId,signal:ctx.signal})}catch(error){throw toSdkMcpError(error)}const notifications=opened.stream[Symbol.asyncIterator]();try{for(;;){const next=await awaitOutsideRequest2(notifications.next());if(next.done)break;await ctx.sendNotification(next.value)}}finally{opened.stream.close()}return{_meta:{[MCP_20260728_META2.subscriptionId]:ctx.requestId}}}}}var init_events_stream_request_handler=__esm({"libs/sdk/src/transport/mcp-handlers/events-stream-request.handler.ts"(){"use strict";init_mcp_error_utils();init_mcp_surface()}});import{SubscribeEventRequestSchema}from"@frontmcp/protocol";function eventsSubscribeRequestHandler({scope}){const logger=scope.logger.child("events-subscribe-request-handler");return{requestSchema:SubscribeEventRequestSchema,handler:async(request2,ctx)=>{logger.verbose(`events/subscribe requested for "${request2.params.name}"`);try{return await scope.runFlowForOutput("events:subscribe",{request:request2,ctx:withMcpSurface(scope,ctx)})}catch(error){throw toSdkMcpError(error)}}}}var init_events_subscribe_request_handler=__esm({"libs/sdk/src/transport/mcp-handlers/events-subscribe-request.handler.ts"(){"use strict";init_mcp_error_utils();init_mcp_surface()}});import{UnsubscribeEventRequestSchema}from"@frontmcp/protocol";function eventsUnsubscribeRequestHandler({scope}){const logger=scope.logger.child("events-unsubscribe-request-handler");return{requestSchema:UnsubscribeEventRequestSchema,handler:async(request2,ctx)=>{logger.verbose(`events/unsubscribe requested for "${request2.params.name}"`);try{return await scope.runFlowForOutput("events:unsubscribe",{request:request2,ctx:withMcpSurface(scope,ctx)})}catch(error){throw toSdkMcpError(error)}}}}var init_events_unsubscribe_request_handler=__esm({"libs/sdk/src/transport/mcp-handlers/events-unsubscribe-request.handler.ts"(){"use strict";init_mcp_error_utils();init_mcp_surface()}});import{GetPromptRequestSchema}from"@frontmcp/protocol";function getPromptRequestHandler({scope}){const logger=scope.logger.child("get-prompt-request-handler");const errorHandler=new ErrorHandler({logger});return{requestSchema:GetPromptRequestSchema,handler:async(request2,ctx)=>{const promptName=request2.params?.name||"unknown";logger.info(`prompts/get: ${promptName}`);const start=Date.now();try{const result=await scope.runFlowForOutput("prompts:get-prompt",{request:request2,ctx:withMcpSurface(scope,ctx)});logger.verbose("prompts/get completed",{prompt:promptName,durationMs:Date.now()-start});return result}catch(e){const cause=errorBehindFlowControl(e);if(isMrtrSignal(cause))throw cause;const failure=toReportedError(cause);errorHandler.logError(failure,{flowName:"prompts:get-prompt",prompt:promptName});throw toSdkMcpError(failure)}}}}var init_get_prompt_request_handler=__esm({"libs/sdk/src/transport/mcp-handlers/get-prompt-request.handler.ts"(){"use strict";init_errors();init_mcp_error_utils();init_mcp_surface()}});import{encryptJson,getTokenSignatureFingerprint,safeDecrypt,TinyTtlCache}from"@frontmcp/auth";import{getMachineId,randomUUID as randomUUID5}from"@frontmcp/utils";function hasValidSessionStructure(dec){if(typeof dec!=="object"||dec===null)return false;const d=dec;return typeof d["nodeId"]==="string"&&typeof d["authSig"]==="string"&&typeof d["uuid"]==="string"&&typeof d["iat"]==="number"}function isValidSessionPayload(dec,sig){return hasValidSessionStructure(dec)&&dec.authSig===sig}function isValidPublicSessionPayload(dec,expectedAuthSig="public"){if(typeof dec!=="object"||dec===null)return false;const d=dec;return typeof d["nodeId"]==="string"&&d["authSig"]===expectedAuthSig&&typeof d["uuid"]==="string"&&typeof d["iat"]==="number"&&d["isPublic"]===(expectedAuthSig==="public")}function decryptSessionId(sessionId,sig){const dec=safeDecrypt(sessionId);return isValidSessionPayload(dec,sig)?dec:null}function decryptPublicSession(sessionId,expectedAuthSig="public"){const cached=cache.get(sessionId);if(cached&&isValidPublicSessionPayload(cached,expectedAuthSig)){return cached}const dec=safeDecrypt(sessionId);if(isValidPublicSessionPayload(dec,expectedAuthSig)){cache.set(sessionId,dec);return dec}return null}function isDeploymentSessionId(sessionId){return cache.get(sessionId)!==void 0||hasValidSessionStructure(safeDecrypt(sessionId))}function nowSec(){return Math.floor(Date.now()/1e3)}function parseSessionHeader(sessionHeader,token){const currentAuthSig=getTokenSignatureFingerprint(token);if(sessionHeader){const cached=cache.get(sessionHeader);if(cached){if(cached.authSig===currentAuthSig){return{id:sessionHeader,payload:cached}}}const dec=decryptSessionId(sessionHeader,currentAuthSig);if(dec){cache.set(sessionHeader,dec);return{id:sessionHeader,payload:dec}}}return void 0}function createSessionId(protocol,token,options){const authSig=getTokenSignatureFingerprint(token);let platformType;if(options?.userAgent){platformType=detectPlatformFromUserAgent(options.userAgent,options.platformDetectionConfig);if(platformType==="unknown"){platformType=void 0}}const payload={nodeId:getMachineId(),authSig,uuid:randomUUID5(),iat:nowSec(),protocol,platformType,...options?.skillsOnlyMode&&{skillsOnlyMode:true}};const id=encryptJson(payload);cache.set(id,payload);return{id,payload}}function updateSessionPayload(sessionId,updates){let payload;const existing=cache.get(sessionId);if(existing){payload=existing}else{const decrypted=safeDecrypt(sessionId);if(hasValidSessionStructure(decrypted)||isValidPublicSessionPayload(decrypted)){payload=decrypted}}if(!payload)return null;Object.assign(payload,updates);const newSessionId=encryptJson(payload);cache.set(sessionId,payload);cache.set(newSessionId,payload);return newSessionId}var cache;var init_session_id_utils=__esm({"libs/sdk/src/auth/session/utils/session-id.utils.ts"(){"use strict";init_notification_service();cache=new TinyTtlCache(5e3)}});var init_notification=__esm({"libs/sdk/src/notification/index.ts"(){"use strict";init_notification_service()}});import{PROTOCOL_2026_07_28}from"@frontmcp/protocol";var FRONTMCP_SUPPORTED_PROTOCOL_VERSIONS,INITIALIZE_PROTOCOL_VERSIONS,LEGACY_PROTOCOL_VERSIONS,PROTOCOL_20260728_ONLY_METHODS,MCP_HEADERS,NAME_FROM_PARAMS_NAME,NAME_FROM_PARAMS_URI,DEFAULT_CACHE_TTL_MS,CACHEABLE_METHODS,ADVERTISED_EXTENSIONS;var init_protocol_20260728_constants=__esm({"libs/sdk/src/transport/mcp-20260728/protocol-20260728.constants.ts"(){"use strict";FRONTMCP_SUPPORTED_PROTOCOL_VERSIONS=[PROTOCOL_2026_07_28,"2025-11-25","2025-06-18","2025-03-26","2024-11-05"];INITIALIZE_PROTOCOL_VERSIONS=FRONTMCP_SUPPORTED_PROTOCOL_VERSIONS.filter(version=>version!==PROTOCOL_2026_07_28);LEGACY_PROTOCOL_VERSIONS=["2024-10-07","2024-11-05","2025-03-26","2025-06-18","2025-11-25"];PROTOCOL_20260728_ONLY_METHODS=["server/discover","subscriptions/listen"];MCP_HEADERS={protocolVersion:"mcp-protocol-version",method:"mcp-method",name:"mcp-name",paramPrefix:"mcp-param-"};NAME_FROM_PARAMS_NAME=["tools/call","prompts/get","events/subscribe","events/unsubscribe","events/poll","events/stream"];NAME_FROM_PARAMS_URI=["resources/read"];DEFAULT_CACHE_TTL_MS={"server/discover":3e5,"tools/list":6e4,"prompts/list":6e4,"resources/list":6e4,"resources/templates/list":6e4,"resources/read":0};CACHEABLE_METHODS=Object.keys(DEFAULT_CACHE_TTL_MS);ADVERTISED_EXTENSIONS={"io.modelcontextprotocol/tasks":{}}}});import{InitializeRequestSchema,LATEST_PROTOCOL_VERSION}from"@frontmcp/protocol";function persistInitPayload(sessionId,initPayload,ctx){updateSessionPayload(sessionId,initPayload);const transport=ctx.authInfo?.transport;transport?.setInitSessionPayload(initPayload)}function guardClientVersion(clientVersion){const parsed=new Date(clientVersion);if(isNaN(parsed.getTime())){throw UnsupportedClientVersionError.fromVersion(clientVersion)}}function initializeRequestHandler({serverOptions,scope,composeInstructions}){const logger=scope.logger.child("initialize-handler");return{requestSchema:InitializeRequestSchema,handler:async(request2,ctx)=>{logger.info("initialize: received request",{clientName:request2.params.clientInfo?.name,clientVersion:request2.params.clientInfo?.version,protocolVersion:request2.params.protocolVersion,hasCapabilities:!!request2.params.capabilities,sessionId:ctx.authInfo?.sessionId?.slice(0,20)});guardClientVersion(request2.params.protocolVersion);const sessionId=ctx.authInfo?.sessionId;let detectedPlatform=void 0;const clientSupportsElicitation=supportsElicitation(request2.params.capabilities?.elicitation?{elicitation:request2.params.capabilities.elicitation}:void 0);if(sessionId){const hasRegisteredServer=scope.notifications.getRegisteredServer(sessionId)!==void 0;if(request2.params.capabilities){const clientCapabilities={roots:request2.params.capabilities.roots,sampling:request2.params.capabilities.sampling,experimental:request2.params.capabilities.experimental,extensions:request2.params.capabilities.extensions,elicitation:request2.params.capabilities.elicitation};if(hasRegisteredServer)scope.notifications.setClientCapabilities(sessionId,clientCapabilities);await scope.transportService?.updateStoredSessionCapabilities(sessionId,clientCapabilities);detectedPlatform=detectPlatformFromCapabilities(clientCapabilities)}if(request2.params.clientInfo){const{name:clientName,version:clientVersion}=request2.params.clientInfo;if(hasRegisteredServer){scope.notifications.setClientInfo(sessionId,{name:clientName,version:clientVersion})}const finalPlatform=resolvePlatformType(request2.params.clientInfo,request2.params.capabilities,scope.metadata.transport?.platformDetection);if(ctx.authInfo?.sessionIdPayload){ctx.authInfo.sessionIdPayload.clientName=clientName;ctx.authInfo.sessionIdPayload.clientVersion=clientVersion;ctx.authInfo.sessionIdPayload.supportsElicitation=clientSupportsElicitation;if(finalPlatform){ctx.authInfo.sessionIdPayload.platformType=finalPlatform}persistInitPayload(sessionId,{clientName,clientVersion,supportsElicitation:clientSupportsElicitation,...finalPlatform&&{platformType:finalPlatform}},ctx)}}else if(ctx.authInfo?.sessionIdPayload){ctx.authInfo.sessionIdPayload.supportsElicitation=clientSupportsElicitation;if(detectedPlatform){ctx.authInfo.sessionIdPayload.platformType=detectedPlatform}persistInitPayload(sessionId,{supportsElicitation:clientSupportsElicitation,...detectedPlatform&&{platformType:detectedPlatform}},ctx)}}const declaresChannels=request2.params.capabilities?.experimental?.["claude/channel"]!==void 0;const registered=sessionId?scope.notifications.getRegisteredServer(sessionId):void 0;if(sessionId&&(declaresChannels||registered?.stdio)){if(scope.channels){const listed=await scope.runFlowForOutput("channels:list",{});const channelNames=listed.channels.map(ch=>ch.name);scope.notifications.subscribeAllChannels(sessionId,channelNames);logger.info(`initialize: auto-subscribed session to ${channelNames.length} channel(s)`,{channels:channelNames.join(", "),sessionId:sessionId.slice(0,20)})}}const requestedVersion=request2.params.protocolVersion;const protocolVersion=INITIALIZE_PROTOCOL_VERSIONS.includes(requestedVersion)?requestedVersion:LATEST_PROTOCOL_VERSION;const configuredInfo=scope.metadata?.info??{name:"FrontMcpServer",version:"0.0.1"};const composed=await composeInstructions?.(ctx,request2.params.clientInfo?.name);const instructions=composed!==void 0?composed:serverOptions.instructions;const result={capabilities:serverOptions.capabilities??{},instructions:instructions&&instructions.length>0?instructions:void 0,serverInfo:{...configuredInfo,title:configuredInfo.title??configuredInfo.name},protocolVersion};logger.info("initialize: sending response",{capabilities:JSON.stringify(result.capabilities),protocolVersion:result.protocolVersion,serverName:result.serverInfo.name,sessionId:ctx.authInfo?.sessionId?.slice(0,20)});return result}}}var init_initialize_request_handler=__esm({"libs/sdk/src/transport/mcp-handlers/initialize-request.handler.ts"(){"use strict";init_session_id_utils();init_errors();init_notification();init_protocol_20260728_constants()}});import{InitializedNotificationSchema}from"@frontmcp/protocol";function initializedNotificationHandler(options){return{requestSchema:InitializedNotificationSchema,handler:async(request2,ctx)=>{return{}}}}var init_Initialized_notification_hanlder=__esm({"libs/sdk/src/transport/mcp-handlers/Initialized-notification.hanlder.ts"(){"use strict"}});import{ListPromptsRequestSchema}from"@frontmcp/protocol";function listPromptsRequestHandler({scope}){const logger=scope.logger.child("list-prompts-request-handler");return{requestSchema:ListPromptsRequestSchema,handler:async(request2,ctx)=>{logger.verbose("prompts/list requested");const start=Date.now();try{const result=await scope.runFlowForOutput("prompts:list-prompts",{request:request2,ctx:withMcpSurface(scope,ctx)});logger.verbose("prompts/list completed",{durationMs:Date.now()-start});return result}catch(e){logger.error("prompts/list failed",{error:e instanceof Error?{name:e.name,message:e.message,stack:e.stack}:e});throw e}}}}var init_list_prompts_request_handler=__esm({"libs/sdk/src/transport/mcp-handlers/list-prompts-request.handler.ts"(){"use strict";init_mcp_surface()}});import{ListResourceTemplatesRequestSchema}from"@frontmcp/protocol";function listResourceTemplatesRequestHandler({scope}){const logger=scope.logger.child("list-resource-templates-request-handler");return{requestSchema:ListResourceTemplatesRequestSchema,handler:async(request2,ctx)=>{logger.verbose("resources/listTemplates requested");const start=Date.now();try{const result=await scope.runFlowForOutput("resources:list-resource-templates",{request:request2,ctx:withMcpSurface(scope,ctx)});logger.verbose("resources/listTemplates completed",{durationMs:Date.now()-start});return result}catch(e){logger.error("resources/listTemplates failed",{error:e instanceof Error?{name:e.name,message:e.message,stack:e.stack}:e});throw e}}}}var init_list_resource_templates_request_handler=__esm({"libs/sdk/src/transport/mcp-handlers/list-resource-templates-request.handler.ts"(){"use strict";init_mcp_surface()}});import{ListResourcesRequestSchema}from"@frontmcp/protocol";function listResourcesRequestHandler({scope}){const logger=scope.logger.child("list-resources-request-handler");return{requestSchema:ListResourcesRequestSchema,handler:async(request2,ctx)=>{logger.verbose("resources/list requested");const start=Date.now();try{const result=await scope.runFlowForOutput("resources:list-resources",{request:request2,ctx:withMcpSurface(scope,ctx)});logger.verbose("resources/list completed",{durationMs:Date.now()-start});return result}catch(e){logger.error("resources/list failed",{error:e instanceof Error?{name:e.name,message:e.message,stack:e.stack}:e});throw e}}}}var init_list_resources_request_handler=__esm({"libs/sdk/src/transport/mcp-handlers/list-resources-request.handler.ts"(){"use strict";init_mcp_surface()}});import{ListToolsRequestSchema}from"@frontmcp/protocol";function listToolsRequestHandler({scope}){const logger=scope.logger.child("list-tools-request-handler");return{requestSchema:ListToolsRequestSchema,handler:async(request2,ctx)=>{logger.verbose("tools/list requested");const start=Date.now();try{const result=await scope.runFlowForOutput("tools:list-tools",{request:request2,ctx:withMcpSurface(scope,ctx)});logger.verbose("tools/list completed",{durationMs:Date.now()-start});return result}catch(e){logger.error("tools/list failed",{error:e instanceof Error?{name:e.name,message:e.message,stack:e.stack}:e});throw e}}}}var init_list_tools_request_handler=__esm({"libs/sdk/src/transport/mcp-handlers/list-tools-request.handler.ts"(){"use strict";init_mcp_surface()}});import{SetLevelRequestSchema}from"@frontmcp/protocol";function LoggingSetLevelRequestHandler({scope}){return{requestSchema:SetLevelRequestSchema,handler:async(request2,ctx)=>{try{return await scope.runFlowForOutput("logging:set-level",{request:request2,ctx:withMcpSurface(scope,ctx)})}catch(error){throw toSdkMcpError(error)}}}}var init_logging_set_level_request_handler=__esm({"libs/sdk/src/transport/mcp-handlers/logging-set-level-request.handler.ts"(){"use strict";init_mcp_error_utils();init_mcp_surface()}});import{ReadResourceRequestSchema}from"@frontmcp/protocol";function readResourceRequestHandler({scope}){const logger=scope.logger.child("read-resource-request-handler");const errorHandler=new ErrorHandler({logger});return{requestSchema:ReadResourceRequestSchema,handler:async(request2,ctx)=>{const uri=request2.params?.uri||"unknown";logger.info(`resources/read: ${uri}`);const start=Date.now();try{const result=await scope.runFlowForOutput("resources:read-resource",{request:request2,ctx:withMcpSurface(scope,ctx)});logger.verbose("resources/read completed",{uri,durationMs:Date.now()-start});return result}catch(e){const cause=errorBehindFlowControl(e);if(isMrtrSignal(cause))throw cause;const failure=toReportedError(cause);errorHandler.logError(failure,{flowName:"resources:read-resource",uri});throw toSdkMcpError(failure)}}}}var init_read_resource_request_handler=__esm({"libs/sdk/src/transport/mcp-handlers/read-resource-request.handler.ts"(){"use strict";init_errors();init_mcp_error_utils();init_mcp_surface()}});import{RootsListChangedNotificationSchema}from"@frontmcp/protocol";function rootsListChangedNotificationHandler({scope}){return{requestSchema:RootsListChangedNotificationSchema,handler:async(request2,ctx)=>{const sessionId=ctx.authInfo?.sessionId;if(sessionId){scope.notifications.invalidateRootsCache(sessionId)}return{}}}}var init_roots_list_changed_notification_handler=__esm({"libs/sdk/src/transport/mcp-handlers/roots-list-changed-notification.handler.ts"(){"use strict"}});async function listAllMatching(registry,options){const skills=[];let limit=REGISTRY_PAGE_SIZE;for(;;){const page2=await registry.listSkills({...options,offset:skills.length,limit});skills.push(...page2.skills);if(!page2.hasMore||page2.skills.length===0||skills.length>=page2.total)return skills;limit=Math.max(REGISTRY_PAGE_SIZE,page2.total-skills.length)}}function skillsListRequestHandler({scope}){const logger=scope.logger.child("skills-list-request-handler");return{requestSchema:SkillsListRequestSchema,responseSchema:SkillsListResultSchema,handler:async(request2,ctx)=>{const params=request2.params??{};const{offset,limit,tags,sortBy,sortOrder,includeHidden}=params;logger.verbose(`skills/list: offset=${offset}, limit=${limit}`);const skillRegistry=scope.skills;if(!skillRegistry){throw new PublicMcpError("Skills capability not available","CAPABILITY_NOT_AVAILABLE",501)}try{await assertSkillCatalogLoaded(scope)}catch(error){throw toSdkMcpError(error)}const matching=await listAllMatching(skillRegistry,{tags,sortBy,sortOrder,includeHidden});const listedOverMcp=matching.filter(metadata=>metadata.visibility!=="http");const authInfo=ctx?.authInfo??{};const visible=await filterDiscoverableSkillResults(scope,skillRegistry,listedOverMcp.map(metadata=>({metadata})),{authInfo,ctx:withMcpSurface(scope,ctx)});const start=offset??0;const page2=visible.slice(start,start+(limit??DEFAULT_PAGE_SIZE));const skills=page2.map(({metadata:s})=>{const id=s.id??s.name;const bundleVersion=skillRegistry.bundleVersionOf?.(id);return{id,name:s.name,description:s.description??"",tags:s.tags,priority:s.priority,...bundleVersion!==void 0&&{bundleVersion}}});const result={skills,total:visible.length,hasMore:start+page2.length<visible.length};return SkillsListResultSchema.parse(result)}}}var DEFAULT_PAGE_SIZE,REGISTRY_PAGE_SIZE;var init_skills_list_request_handler=__esm({"libs/sdk/src/transport/mcp-handlers/skills-list-request.handler.ts"(){"use strict";init_errors();init_skill_catalog_source();init_skill_filter_helper();init_mcp_error_utils();init_mcp_surface();init_skills_mcp_types();DEFAULT_PAGE_SIZE=50;REGISTRY_PAGE_SIZE=100}});function skillsLoadRequestHandler({scope}){const logger=scope.logger.child("skills-load-request-handler");return{requestSchema:SkillsLoadRequestSchema,responseSchema:SkillsLoadResultSchema,handler:async(request2,ctx)=>{logger.verbose(`skills/load: [${request2.params.skillIds.join(", ")}]`);try{return await scope.runFlowForOutput("skills:load",{request:request2,ctx:withMcpSurface(scope,ctx)})}catch(error){throw toSdkMcpError(error)}}}}var init_skills_load_request_handler=__esm({"libs/sdk/src/transport/mcp-handlers/skills-load-request.handler.ts"(){"use strict";init_mcp_error_utils();init_mcp_surface();init_skills_mcp_types()}});function skillsSearchRequestHandler({scope}){const logger=scope.logger.child("skills-search-request-handler");return{requestSchema:SkillsSearchRequestSchema,responseSchema:SkillsSearchResultSchema,handler:async(request2,ctx)=>{logger.verbose(`skills/search: "${request2.params.query}"`);try{return await scope.runFlowForOutput("skills:search",{request:request2,ctx:withMcpSurface(scope,ctx)})}catch(error){throw toSdkMcpError(error)}}}}var init_skills_search_request_handler=__esm({"libs/sdk/src/transport/mcp-handlers/skills-search-request.handler.ts"(){"use strict";init_mcp_error_utils();init_mcp_surface();init_skills_mcp_types()}});import{SubscribeRequestSchema}from"@frontmcp/protocol";function SubscribeRequestHandler({scope}){return{requestSchema:SubscribeRequestSchema,handler:async(request2,ctx)=>{try{return await scope.runFlowForOutput("resources:subscribe",{request:request2,ctx:withMcpSurface(scope,ctx)})}catch(error){throw toSdkMcpError(error)}}}}var init_subscribe_request_handler=__esm({"libs/sdk/src/transport/mcp-handlers/subscribe-request.handler.ts"(){"use strict";init_mcp_error_utils();init_mcp_surface()}});import{CancelTaskRequestSchema}from"@frontmcp/protocol";function tasksCancelRequestHandler({scope}){const logger=scope.logger.child("tasks-cancel-request-handler");return{requestSchema:CancelTaskRequestSchema,handler:async(request2,ctx)=>{logger.info(`tasks/cancel: ${request2.params?.taskId}`);try{const result=await scope.runFlowForOutput("tasks:cancel",{request:request2,ctx});return result}catch(e){logger.error("tasks/cancel failed",{error:e instanceof Error?e.message:e});throw toSdkMcpError(e)}}}}var init_tasks_cancel_request_handler=__esm({"libs/sdk/src/transport/mcp-handlers/tasks-cancel-request.handler.ts"(){"use strict";init_mcp_error_utils()}});import{GetTaskRequestSchema}from"@frontmcp/protocol";function tasksGetRequestHandler({scope}){const logger=scope.logger.child("tasks-get-request-handler");return{requestSchema:GetTaskRequestSchema,handler:async(request2,ctx)=>{logger.verbose(`tasks/get: ${request2.params?.taskId}`);try{const result=await scope.runFlowForOutput("tasks:get",{request:request2,ctx});return result}catch(e){logger.error("tasks/get failed",{error:e instanceof Error?e.message:e});throw toSdkMcpError(e)}}}}var init_tasks_get_request_handler=__esm({"libs/sdk/src/transport/mcp-handlers/tasks-get-request.handler.ts"(){"use strict";init_mcp_error_utils()}});import{ListTasksRequestSchema}from"@frontmcp/protocol";function tasksListRequestHandler({scope}){const logger=scope.logger.child("tasks-list-request-handler");return{requestSchema:ListTasksRequestSchema,handler:async(request2,ctx)=>{logger.verbose("tasks/list");try{const result=await scope.runFlowForOutput("tasks:list",{request:request2,ctx});return result}catch(e){logger.error("tasks/list failed",{error:e instanceof Error?e.message:e});throw toSdkMcpError(e)}}}}var init_tasks_list_request_handler=__esm({"libs/sdk/src/transport/mcp-handlers/tasks-list-request.handler.ts"(){"use strict";init_mcp_error_utils()}});import{GetTaskPayloadRequestSchema}from"@frontmcp/protocol";function tasksResultRequestHandler({scope}){const logger=scope.logger.child("tasks-result-request-handler");return{requestSchema:GetTaskPayloadRequestSchema,handler:async(request2,ctx)=>{logger.verbose(`tasks/result: ${request2.params?.taskId}`);try{const result=await scope.runFlowForOutput("tasks:result",{request:request2,ctx});return result}catch(e){logger.error("tasks/result failed",{error:e instanceof Error?e.message:e});throw toSdkMcpError(e)}}}}var init_tasks_result_request_handler=__esm({"libs/sdk/src/transport/mcp-handlers/tasks-result-request.handler.ts"(){"use strict";init_mcp_error_utils()}});import{UnsubscribeRequestSchema}from"@frontmcp/protocol";function UnsubscribeRequestHandler({scope}){return{requestSchema:UnsubscribeRequestSchema,handler:async(request2,ctx)=>{try{return await scope.runFlowForOutput("resources:unsubscribe",{request:request2,ctx:withMcpSurface(scope,ctx)})}catch(error){throw toSdkMcpError(error)}}}}var init_unsubscribe_request_handler=__esm({"libs/sdk/src/transport/mcp-handlers/unsubscribe-request.handler.ts"(){"use strict";init_mcp_error_utils();init_mcp_surface()}});var mcp_handlers_exports={};__export(mcp_handlers_exports,{createMcpHandlers:()=>createMcpHandlers,methodOfSchema:()=>methodOfSchema,registerMcpHandler:()=>registerMcpHandler});function methodOfSchema(schema){const shape=schema?.shape;const method=shape?.["method"];if(typeof method?.value==="string")return method.value;const values=method?._def?.values;return Array.isArray(values)&&typeof values[0]==="string"?values[0]:void 0}function registerMcpHandler(server,schema,handle,notificationContext={}){if(!methodOfSchema(schema)?.startsWith("notifications/")){server.setRequestHandler(schema,handle);return}server.setNotificationHandler(schema,async notification=>{await handle(notification,notificationContext)})}function createMcpHandlers(options){const listHandlers=[listToolsRequestHandler(options),listResourcesRequestHandler(options),listResourceTemplatesRequestHandler(options),listPromptsRequestHandler(options)];const toolsHandler=options.serverOptions?.capabilities?.tools?[callToolRequestHandler(options)]:[];const resourcesHandler=options.serverOptions?.capabilities?.resources?[readResourceRequestHandler(options),SubscribeRequestHandler(options),UnsubscribeRequestHandler(options)]:[];const promptsHandler=options.serverOptions?.capabilities?.prompts?[getPromptRequestHandler(options)]:[];const hasPromptsOrResources=options.scope?.prompts?.hasAny()||options.scope?.resources?.hasAny();const completionHandler=hasPromptsOrResources&&options.serverOptions?.capabilities?.completions?[completeRequestHandler(options)]:[];const loggingHandler=options.serverOptions?.capabilities?.logging?[LoggingSetLevelRequestHandler(options)]:[];const skillRegistry=options.scope?.skills;const skillsHandler=skillRegistry?.servesSkills?.()??skillRegistry?.hasAny()?[skillsSearchRequestHandler(options),skillsLoadRequestHandler(options),skillsListRequestHandler(options)]:[];const eventsHandler=options.scope?.events?.servesEvents()?[eventsListRequestHandler(options)]:[];const eventPollHandler=options.scope?.events?.performs("poll")?[eventsPollRequestHandler(options)]:[];const eventStreamHandler=options.scope?.events?.performs("push")?[eventsStreamRequestHandler(options)]:[];const eventSubscriptionHandlers=options.scope?.events?.subscriptions?[eventsSubscribeRequestHandler(options),eventsUnsubscribeRequestHandler(options)]:[];const tasksHandler=options.serverOptions?.capabilities?.["tasks"]?[tasksGetRequestHandler(options),tasksResultRequestHandler(options),tasksCancelRequestHandler(options),tasksListRequestHandler(options)]:[];return[initializeRequestHandler(options),initializedNotificationHandler(options),rootsListChangedNotificationHandler(options),...listHandlers,...toolsHandler,...resourcesHandler,...promptsHandler,...completionHandler,...loggingHandler,...skillsHandler,...eventsHandler,...eventSubscriptionHandlers,...eventPollHandler,...eventStreamHandler,...tasksHandler]}var init_mcp_handlers=__esm({"libs/sdk/src/transport/mcp-handlers/index.ts"(){"use strict";init_call_tool_request_handler();init_complete_request_handler();init_events_list_request_handler();init_events_poll_request_handler();init_events_stream_request_handler();init_events_subscribe_request_handler();init_events_unsubscribe_request_handler();init_get_prompt_request_handler();init_initialize_request_handler();init_Initialized_notification_hanlder();init_list_prompts_request_handler();init_list_resource_templates_request_handler();init_list_resources_request_handler();init_list_tools_request_handler();init_logging_set_level_request_handler();init_read_resource_request_handler();init_roots_list_changed_notification_handler();init_skills_list_request_handler();init_skills_load_request_handler();init_skills_search_request_handler();init_subscribe_request_handler();init_tasks_cancel_request_handler();init_tasks_get_request_handler();init_tasks_list_request_handler();init_tasks_result_request_handler();init_unsubscribe_request_handler()}});var in_memory_server_exports={};__export(in_memory_server_exports,{createInMemoryServer:()=>createInMemoryServer});import{toJSONSchema}from"@frontmcp/lazy-zod";import{ElicitResultSchema,ErrorCode,InMemoryTransport,McpError as McpError3}from"@frontmcp/protocol";import{randomUUID as randomUUID6,runRequestExclusive as runRequestExclusive2}from"@frontmcp/utils";async function createInMemoryServer(scope,options){const{createMcpHandlers:createMcpHandlers2,registerMcpHandler:registerMcpHandler2}=await Promise.resolve().then(()=>(init_mcp_handlers(),mcp_handlers_exports));const sessionId=options?.sessionId??`in-memory:${randomUUID6()}`;const[clientTransport,serverTransport]=InMemoryTransport.createLinkedPair();let currentAuthInfo=options?.authInfo??{};const elicitTransport={type:"in-memory",sendElicitRequest:async(relatedRequestId,message,requestedSchema,elicitOptions)=>{const{elicitId,expiresAt,requestParams}=await scope.runFlowForOutput("elicitation:request",{relatedRequestId,sessionId,message,requestedSchema:toJSONSchema(requestedSchema),options:elicitOptions});const ttl=Math.max(expiresAt-Date.now(),0);let answer;try{answer=await mcpServer.request({method:"elicitation/create",params:{...requestParams,_meta:{[ELICITATION_META_KEY]:{elicitId,expiresAt}}}},ElicitResultSchema,{relatedRequestId,timeout:ttl})}catch(error){await scope.elicitationStore?.deletePending(sessionId);if(error instanceof McpError3&&error.code===ErrorCode.RequestTimeout){throw new ElicitationTimeoutError(elicitId,ttl)}throw error}const output=await scope.runFlow("elicitation:result",{sessionId,result:answer});return output?.result??{status:answer.action}}};const serverOptions=buildScopedServerOptions(scope);const mcpServer=createMcpServer(scope.metadata.info,serverOptions);const composeInstructions=(caller,clientName)=>composeCallerInstructions(scope,{ctx:caller,clientName,skillUriHints:true});const handlers=createMcpHandlers2({scope,serverOptions,composeInstructions});for(const handler of handlers){const originalHandler=handler.handler;const wrappedHandler=async(request2,ctx)=>{const enrichedCtx={...ctx,authInfo:{...currentAuthInfo,sessionId,transport:elicitTransport},...options?.workerEnv!==void 0?{platformEnv:options.workerEnv}:{},ownRequest:true};return runRequestExclusive2(()=>originalHandler(request2,enrichedCtx))};registerMcpHandler2(mcpServer,handler.requestSchema,wrappedHandler)}scope.notifications.registerServer(sessionId,mcpServer);scope.notifications.setCaller(sessionId,sessionCallerOf(currentAuthInfo));await mcpServer.connect(serverTransport);return{clientTransport,setAuthInfo:authInfo=>{currentAuthInfo=authInfo;scope.notifications.setCaller(sessionId,sessionCallerOf(authInfo))},close:async()=>{scope.notifications.unregisterServer(sessionId);await mcpServer.close()}}}var init_in_memory_server=__esm({"libs/sdk/src/transport/in-memory-server.ts"(){"use strict";init_elicitation_meta();init_errors();init_notification_service();init_skill_instructions_helper();init_build_scoped_server_options();init_mcp_server_factory()}});var direct_client_exports={};__export(direct_client_exports,{DirectClientImpl:()=>DirectClientImpl});import{ElicitRequestSchema,ResourceUpdatedNotificationSchema}from"@frontmcp/protocol";import{fileExists,pathResolve,randomUUID as randomUUID7}from"@frontmcp/utils";function toElicitationRequest(params){const{_meta,...question}=params;const sent=_meta?.[ELICITATION_META_KEY];const elicitId=sent?.elicitId??("elicitationId"in question?question.elicitationId:"");return{...question,elicitId,expiresAt:sent?.expiresAt??0}}function findFileFromRoot(root,relativePath,skillName){const fs=__require("fs");const path4=__require("path");const cleanRelative=relativePath.replace(/^\.\//,"");const searchDirs=["src","."];for(const srcDir of searchDirs){const srcRoot=path4.join(root,srcDir);if(!fs.existsSync(srcRoot))continue;const matches=[];walkForFile(srcRoot,cleanRelative,fs,path4,matches);if(matches.length===0)continue;if(matches.length===1)return matches[0];const namedAfterSkill=matches.filter(match=>path4.basename(match.baseDir)===skillName);return namedAfterSkill.length===1?namedAfterSkill[0]:void 0}return void 0}function walkForFile(dir,targetRelative,fs,path4,matches,maxDepth=10){const candidate=path4.join(dir,targetRelative);if(fs.existsSync(candidate)){matches.push({absolute:candidate,baseDir:dir})}if(maxDepth<=0)return;try{const entries=fs.readdirSync(dir,{withFileTypes:true});for(const entry of entries){if(entry.isDirectory()&&!entry.name.startsWith(".")&&entry.name!=="node_modules"&&entry.name!=="dist"){walkForFile(path4.join(dir,entry.name),targetRelative,fs,path4,matches,maxDepth-1)}}}catch{}}var DirectClientImpl;var init_direct_client=__esm({"libs/sdk/src/direct/direct-client.ts"(){"use strict";init_import_protocol_client();init_list_all_pages_utils();init_elicitation_meta();init_errors();init_event_client();init_skills_mcp_types();init_direct_events_transport();init_llm_platform();init_token_auth_info();DirectClientImpl=class _DirectClientImpl{mcpClient;sessionId;clientInfo;platform;serverInfo;capabilities;closeServer;elicitationHandler;resourceUpdateHandlers=new Set;notificationHandlers=new Set;scopeRef;releaseScope;events;constructor(mcpClient,sessionId,clientInfo,serverInfo,capabilities,eventsOptions){this.mcpClient=mcpClient;this.sessionId=sessionId;this.clientInfo=clientInfo;this.platform=detectPlatform(clientInfo);this.serverInfo=serverInfo;this.capabilities=capabilities;const transport=directEventsTransport(mcpClient,handler=>this.onNotification(handler));this.events=new EventsClient(transport,eventsOptions)}static async create(scope,options,releaseScope){const{createInMemoryServer:createInMemoryServer2}=await Promise.resolve().then(()=>(init_in_memory_server(),in_memory_server_exports));const sessionId=options?.session?.id??`direct:${randomUUID7()}`;const clientInfo=options?.clientInfo??{name:"mcp-client",version:"1.0.0"};const authInfo={};if(options?.authToken){authInfo["token"]=options.authToken}if(options?.session?.user){authInfo["user"]={iss:"direct",...options.session.user,sub:options.session.user?.sub??"direct"}}if(options?.session?.scopes){authInfo["scopes"]=options.session.scopes}if(options?.authToken){Object.assign(authInfo,await authInfoForToken(scope,options.authToken))}const{clientTransport,close}=await createInMemoryServer2(scope,{sessionId,authInfo:Object.keys(authInfo).length>0?authInfo:void 0,workerEnv:options?.workerEnv});try{const clientCapabilities={capabilities:{...options?.onElicitation&&{elicitation:{form:{},url:{}}},...options?.capabilities}};const{Client}=await loadProtocolClient();const mcpClient=new Client(clientInfo,clientCapabilities);await mcpClient.connect(clientTransport);const serverInfo=mcpClient.getServerVersion();const serverCapabilities=mcpClient.getServerCapabilities();if(!serverInfo){throw new PublicMcpError("Failed to get server info from MCP handshake","HANDSHAKE_FAILED",500)}if(!serverCapabilities){throw new PublicMcpError("Failed to get server capabilities from MCP handshake","HANDSHAKE_FAILED",500)}const client=new _DirectClientImpl(mcpClient,sessionId,clientInfo,serverInfo,serverCapabilities,options?.events);client.closeServer=close;client.scopeRef=scope;client.releaseScope=releaseScope;client.elicitationHandler=options?.onElicitation;await client.setupNotificationHandlers(mcpClient);return client}catch(error){await close();throw error}}async setupNotificationHandlers(mcpClient){try{if(typeof mcpClient.setNotificationHandler==="function"){mcpClient.setNotificationHandler(ResourceUpdatedNotificationSchema,notification=>{const uri=notification.params?.uri;if(uri){this.resourceUpdateHandlers.forEach(h2=>h2(uri))}this.notificationHandlers.forEach(h2=>h2({method:notification.method??"notifications/resources/updated",params:notification.params}))})}if(typeof mcpClient.setNotificationHandler==="function"){mcpClient.fallbackNotificationHandler=notification=>{this.notificationHandlers.forEach(h2=>h2(notification))}}if(typeof mcpClient.setRequestHandler==="function"){mcpClient.setRequestHandler(ElicitRequestSchema,async request2=>{const params=request2.params;if(params){return this.handleElicitationRequestInternal(toElicitationRequest(params))}return{action:"decline"}})}}catch{}}async handleElicitationRequestInternal(params){if(this.elicitationHandler){try{return await this.elicitationHandler(params)}catch{return{action:"decline"}}}return{action:"decline"}}async listTools(){const tools=await listAllPages("tools/list",async cursor=>{const result=await this.mcpClient.listTools(cursor?{cursor}:void 0);return{items:result.tools,nextCursor:result.nextCursor}});return formatToolsForPlatform(tools,this.platform)}async callTool(name59,args,options){const result=await this.mcpClient.callTool({name:name59,arguments:args??{}},void 0,options?.onProgress&&{onprogress:options.onProgress});if(result.isError&&this.platform!=="raw")throw new ToolCallError(name59,result);return formatResultForPlatform(result,this.platform)}async listResources(){const resources=await listAllPages("resources/list",async cursor=>{const result=await this.mcpClient.listResources(cursor?{cursor}:void 0);return{items:result.resources,nextCursor:result.nextCursor}});return{resources}}async readResource(uri){return this.mcpClient.readResource({uri})}async listResourceTemplates(){const resourceTemplates=await listAllPages("resources/templates/list",async cursor=>{const result=await this.mcpClient.listResourceTemplates(cursor?{cursor}:void 0);return{items:result.resourceTemplates,nextCursor:result.nextCursor}});return{resourceTemplates}}async listPrompts(){const prompts=await listAllPages("prompts/list",async cursor=>{const result=await this.mcpClient.listPrompts(cursor?{cursor}:void 0);return{items:result.prompts,nextCursor:result.nextCursor}});return{prompts}}async getPrompt(name59,args){return this.mcpClient.getPrompt({name:name59,arguments:args})}getSessionId(){return this.sessionId}getClientInfo(){return this.clientInfo}getServerInfo(){return this.serverInfo}getCapabilities(){return this.capabilities}getDetectedPlatform(){return this.platform}async close(){await this.events.close();try{await this.mcpClient.close()}finally{await this.closeServer?.();const releaseScope=this.releaseScope;this.releaseScope=void 0;try{await releaseScope?.()}catch{}}}async searchSkills(query,options){return this.mcpClient.request({method:"skills/search",params:{query,...options}},SkillsSearchResultSchema)}async loadSkills(skillIds,options){const result=await this.mcpClient.request({method:"skills/load",params:{skillIds,...options}},SkillsLoadResultSchema);return result}async listSkills(options){return this.mcpClient.request({method:"skills/list",params:options??{}},SkillsListResultSchema)}async listSep2640Skills(){let read;try{read=await this.mcpClient.readResource({uri:"skill://index.json"})}catch{return[]}const text=read.contents?.[0]?.text;if(typeof text!=="string")return[];let parsed;try{parsed=JSON.parse(text)}catch{console.warn("[DirectClient] skill://index.json was not valid JSON");return[]}if(!parsed||typeof parsed!=="object"||!Array.isArray(parsed.skills)){return[]}const doc=parsed;if(doc.$schema&&!doc.$schema.startsWith("https://schemas.agentskills.io/discovery/")){console.warn(`[DirectClient] skill://index.json $schema "${doc.$schema}" is not an agentskills.io discovery URI`)}const ALLOWED_TYPES=new Set(["skill-md","mcp-resource-template","archive"]);return doc.skills.filter(e=>{if(!e||typeof e!=="object")return false;const entry=e;if(typeof entry.type!=="string"||!ALLOWED_TYPES.has(entry.type))return false;if(typeof entry.url!=="string"||!entry.url.startsWith("skill://"))return false;if(entry.type==="skill-md"&&typeof entry.name!=="string"){return false}return true})}async readSkillTextUri(uri){if(!uri.startsWith("skill://")){throw new PublicMcpError(`readSkillTextUri: expected a skill:// URI, got "${uri}"`,"INVALID_PARAMS",400)}const read=await this.mcpClient.readResource({uri});const text=read.contents?.[0]?.text;if(typeof text!=="string"){throw new PublicMcpError(`readSkillTextUri: resource "${uri}" returned no text content; use readResource() for binary skill assets`,"INVALID_REQUEST",400)}return text}onElicitation(handler){this.elicitationHandler=handler;return()=>{this.elicitationHandler=void 0}}async submitElicitationResult(elicitId,response){return this.callTool("sendElicitationResult",{elicitId,...response})}async complete(options){return this.mcpClient.complete(options)}async subscribeResource(uri){await this.mcpClient.subscribeResource({uri})}async unsubscribeResource(uri){await this.mcpClient.unsubscribeResource({uri})}onResourceUpdated(handler){this.resourceUpdateHandlers.add(handler);return()=>{this.resourceUpdateHandlers.delete(handler)}}onNotification(handler){this.notificationHandlers.add(handler);return()=>{this.notificationHandlers.delete(handler)}}async setLogLevel(level){await this.mcpClient.setLoggingLevel(level)}async callToolAndParseJson(toolName,args){const result=await this.mcpClient.callTool({name:toolName,arguments:args});const textContent=result.content?.find(c=>c.type==="text");if(!textContent?.text){throw new PublicMcpError(`No text content from ${toolName}`,"EMPTY_RESPONSE",500)}return JSON.parse(textContent.text)}async listJobs(options){return this.callToolAndParseJson("list_jobs",{...options})}async executeJob(name59,input,options){return this.callToolAndParseJson("execute_job",{name:name59,input:input??{},background:options?.background??false})}async getJobStatus(runId){return this.callToolAndParseJson("get_job_status",{runId})}async listWorkflows(options){return this.callToolAndParseJson("list_workflows",{...options})}async executeWorkflow(name59,input,options){return this.callToolAndParseJson("execute_workflow",{name:name59,input:input??{},background:options?.background??false})}async getWorkflowStatus(runId){return this.callToolAndParseJson("get_workflow_status",{runId})}async collectSkillAssets(){const scope=this.scopeRef;if(!scope?.skills)return{entries:[]};const skills=scope.skills.getSkills({includeHidden:true});const entries=[];for(const skill of skills){const baseDir=skill.getBaseDir?.();const meta=skill.metadata;const entry={skillName:meta.name,baseDir,description:meta.description,tags:meta.tags,license:meta.license};if(meta.instructions&&typeof meta.instructions==="object"&&"file"in meta.instructions){const filePath=meta.instructions.file;const resolved=filePath.startsWith("/")?filePath:baseDir?pathResolve(baseDir,filePath):void 0;if(resolved&&await fileExists(resolved)){entry.instructionFile=resolved}else if(!filePath.startsWith("/")){const fromCwd=findFileFromRoot(process.cwd(),filePath,meta.name);if(fromCwd){entry.instructionFile=fromCwd.absolute;entry.baseDir=fromCwd.baseDir}}}else if(meta.instructions){try{entry.instructionContent=await skill.loadInstructions()}catch{}}if(typeof meta.instructions==="string"){const loaded=await scope.skills.loadSkill(meta.id??meta.name).catch(()=>void 0);if(loaded?.skill.bundleVersion!==void 0)entry.bundleVersion=loaded.skill.bundleVersion}const resources=skill.getResources?.();if(resources){entry.resources={};for(const key of["references","examples","scripts","assets"]){const p=resources[key];if(p){const base=entry.baseDir||baseDir;const resolved=p.startsWith("/")?p:base?pathResolve(base,p):void 0;if(resolved&&await fileExists(resolved)){entry.resources[key]=resolved}}}}entries.push(entry)}return{entries}}}}});import"reflect-metadata";function instanceCacheOf(mode){let cache2=instanceCaches.get(mode);if(!cache2){cache2=new WeakMap;instanceCaches.set(mode,cache2)}return cache2}function getInstance(config,mode="full"){let resolvedConfig=config;if(typeof config==="function"){const stored=getDecoratorConfig(config);if(stored){resolvedConfig=stored}}const cacheKey=resolvedConfig;const instanceCache2=instanceCacheOf(mode);let instancePromise=instanceCache2.get(cacheKey);if(!instancePromise){instancePromise=(async()=>{try{const{FrontMcpInstance:FrontMcpInstance2}=await Promise.resolve().then(()=>(init_front_mcp(),front_mcp_exports));if(mode==="cli")return await FrontMcpInstance2.createForCli(resolvedConfig);if(mode==="manifest")return await FrontMcpInstance2.createForManifest(resolvedConfig);return await FrontMcpInstance2.createForConnect(resolvedConfig)}catch(error){instanceCache2.delete(cacheKey);throw error}})();instanceCache2.set(cacheKey,instancePromise)}return{cacheKey,instancePromise}}function joinInstance(config,mode="full"){const{cacheKey,instancePromise}=getInstance(config,mode);const instanceCache2=instanceCacheOf(mode);instanceClients.set(instancePromise,(instanceClients.get(instancePromise)??0)+1);const release=async()=>{const remaining=(instanceClients.get(instancePromise)??1)-1;instanceClients.set(instancePromise,remaining);if(remaining>0)return;if(instanceCache2.get(cacheKey)===instancePromise)instanceCache2.delete(cacheKey);const instance=await instancePromise;await Promise.all(instance.getScopes().map(scope=>scope.dispose()))};return{instancePromise,release}}async function endpointScope(instance,app){if(app!==void 0)return instance.getAppScope(app);const scope=instance.getPrimaryScope();if(!scope){const{PublicMcpError:PublicMcpError2}=await Promise.resolve().then(()=>(init_errors(),errors_exports));throw new PublicMcpError2("No scopes initialized. Ensure at least one app is configured.","NO_SCOPES",500)}return scope}async function connect(config,options){const{DirectClientImpl:DirectClientImpl2}=await Promise.resolve().then(()=>(init_direct_client(),direct_client_exports));const{instancePromise,release}=joinInstance(config,options?.mode);try{const instance=await instancePromise;const scope=await endpointScope(instance,options?.app);if(options?.mode!=="manifest")await instance.emitProvidersReady();return await DirectClientImpl2.create(scope,options,release)}catch(error){await release().catch(()=>void 0);throw error}}async function connectOpenAI(config,options){return connect(config,{clientInfo:PLATFORM_CLIENT_INFO.openai,...options})}async function connectClaude(config,options){return connect(config,{clientInfo:PLATFORM_CLIENT_INFO.claude,...options})}async function connectLangChain(config,options){return connect(config,{clientInfo:PLATFORM_CLIENT_INFO.langchain,...options})}async function connectVercelAI(config,options){return connect(config,{clientInfo:PLATFORM_CLIENT_INFO["vercel-ai"],...options})}var instanceCaches,instanceClients;var init_connect=__esm({"libs/sdk/src/direct/connect.ts"(){"use strict";init_common();init_llm_platform();instanceCaches=new Map;instanceClients=new WeakMap}});var DEFAULT_ELICIT_TTL,DEFAULT_FALLBACK_WAIT_TTL;var init_elicitation_types=__esm({"libs/sdk/src/elicitation/elicitation.types.ts"(){"use strict";DEFAULT_ELICIT_TTL=3e5;DEFAULT_FALLBACK_WAIT_TTL=3e5}});function workflowTriggerOf(authInfo){const trigger=asRecord(authInfo?.["extra"])?.["workflowTrigger"];return trigger instanceof WorkflowTriggerPrincipal?trigger:void 0}function toStringArray(value){if(Array.isArray(value))return value.filter(v=>typeof v==="string");if(typeof value==="string"&&value.length>0)return value.split(" ").filter(Boolean);return[]}function asRecord(value){return value&&typeof value==="object"?value:void 0}function firstPresent(sources3,convert){for(const source of sources3){if(source!==void 0&&source!==null)return convert(source)}return[]}function resolvePrincipal(authInfo,contextBuilder){const trigger=workflowTriggerOf(authInfo);if(trigger)return{sub:"",roles:[trigger.role],permissions:[],scopes:[],claims:{}};const info=authInfo??{};const user=asRecord(info["user"])??{};const extraAuthorization=asRecord(asRecord(info["extra"])?.["authorization"]);const authInfoClaims=asRecord(info["claims"])??{};const authorizationClaims=asRecord(extraAuthorization?.["claims"])??{};const claims3={...authorizationClaims,...authInfoClaims,...user};const scopes=toStringArray(info["scopes"]).length?toStringArray(info["scopes"]):firstPresent([extraAuthorization?.["scopes"],claims3["scope"],claims3["scopes"]],toStringArray);if(contextBuilder){const ctx=contextBuilder.build(info);return{sub:ctx.user.sub??"",roles:ctx.user.roles,permissions:ctx.user.permissions,scopes,claims:ctx.user.claims}}const roles=firstPresent([user["roles"],claims3["roles"],extraAuthorization?.["scopes"]],toStringArray);const permissions=firstPresent([user["permissions"],claims3["permissions"]],toStringArray);return{sub:typeof user["sub"]==="string"?user["sub"]:"",roles,permissions,scopes,claims:claims3}}var WorkflowTriggerPrincipal;var init_principal_utils=__esm({"libs/sdk/src/common/utils/principal.utils.ts"(){"use strict";WorkflowTriggerPrincipal=class{constructor(kind,name59){this.kind=kind;this.name=name59}kind;name;get role(){return`${this.kind}:${this.name}`}toAuthInfo(){return{extra:{workflowTrigger:this}}}}}});import{isAnonymousSubject as isAnonymousSubject3}from"@frontmcp/auth";function createErrorResult(message){return{content:[{type:"text",text:message}],isError:true}}function resolveElicitationOwner(requestContext){const authInfo=requestContext?.authInfo;const session=[authInfo?.sessionId,authInfo?.extra?.["sessionId"]].find(candidate=>typeof candidate==="string"&&candidate.length>0&&candidate!==STATELESS_SESSION_ID);if(session!==void 0){return`session:${session}`}const principal=authInfo?.clientId;return isAnonymousSubject3(principal)?void 0:`principal:${principal}`}function canDeliverNotifications(scope,sessionId){const capabilities=scope.notifications.getClientCapabilities(sessionId);if(!capabilities)return false;return Object.values(capabilities).some(v=>v!==void 0)}function sendFallbackNotification(deps,error){const{scope,sessionId,logger}=deps;const notificationData={type:"elicitation_fallback",elicitId:error.elicitId,message:error.elicitMessage,schema:error.schema,instructions:`Call sendElicitationResult tool with elicitId: "${error.elicitId}"`};scope.notifications.sendNotificationToSession(sessionId,"notifications/message",{level:"info",data:notificationData,logger:"elicitation"});logger.verbose("sendFallbackNotification: sent notification",{elicitId:error.elicitId,sessionId:sessionId.slice(0,20)})}async function handleWaitingFallback(deps,error){const{scope,sessionId,logger}=deps;logger.info("handleWaitingFallback: starting waiting fallback",{elicitId:error.elicitId,toolName:error.toolName});sendFallbackNotification(deps,error);return new Promise((resolve4,reject)=>{let resolved=false;let unsubscribeFn=null;const ttl=error.ttl||DEFAULT_FALLBACK_WAIT_TTL;const safeUnsubscribe=()=>{if(unsubscribeFn){unsubscribeFn().catch(()=>{});unsubscribeFn=null}};const timeoutHandle=setTimeout(()=>{if(!resolved){resolved=true;safeUnsubscribe();logger.warn("handleWaitingFallback: timeout waiting for result",{elicitId:error.elicitId,ttl});resolve4(createErrorResult(`Elicitation request timed out after ${Math.round(ttl/1e3)} seconds. The user did not respond in time.`))}},ttl);const store=scope.elicitationStore;if(!store){resolved=true;clearTimeout(timeoutHandle);reject(new ElicitationStoreNotInitializedError);return}store.subscribeFallbackResult(error.elicitId,result=>{if(!resolved){resolved=true;clearTimeout(timeoutHandle);safeUnsubscribe();logger.info("handleWaitingFallback: received result via pub/sub",{elicitId:error.elicitId,success:result.success});if(result.success&&result.result!==void 0){resolve4(result.result)}else{resolve4(createErrorResult(result.error||"Elicitation fallback execution failed"))}}},sessionId).then(unsubscribe=>{if(resolved){unsubscribe().catch(()=>{})}else{unsubscribeFn=unsubscribe}}).catch(err=>{if(!resolved){resolved=true;clearTimeout(timeoutHandle);logger.error("handleWaitingFallback: failed to subscribe",err);reject(new ElicitationSubscriptionError(error.elicitId,err instanceof Error?err:void 0))}})})}var init_fallback_helper=__esm({"libs/sdk/src/elicitation/helpers/fallback.helper.ts"(){"use strict";init_errors();init_transport_types();init_elicitation_types()}});import{isAnonymousSubject as isAnonymousSubject4}from"@frontmcp/auth";function principalKeyOf(authInfo){const{sub,claims:claims3}=resolvePrincipal(authInfo);if(isAnonymousSubject4(sub))return void 0;const issuer=typeof claims3["iss"]==="string"?claims3["iss"]:"";return issuer?`principal:${issuer}#${sub}`:`principal:${sub}`}function questionSubjectOf(authInfo){const principalKey=principalKeyOf(authInfo);if(principalKey)return principalKey;const owner=resolveElicitationOwner({authInfo});return owner?.startsWith("session:")?owner:void 0}var init_question_subject=__esm({"libs/sdk/src/elicitation/questions/question-subject.ts"(){"use strict";init_principal_utils();init_fallback_helper()}});var QuestionPendingError,QuestionSupersededError,QuestionNotFoundError,QuestionAlreadyAnsweredError,QuestionStoreBusyError,InvalidQuestionStoreError;var init_question_errors=__esm({"libs/sdk/src/elicitation/questions/question.errors.ts"(){"use strict";init_mcp_error();QuestionPendingError=class extends PublicMcpError{key;expiresAt;constructor(key,expiresAt){super(`The question "${key}" has no answer yet. It waits in the inbox until ${new Date(expiresAt).toISOString()}; call again to get its answer.`,"QUESTION_PENDING",408);this.key=key;this.expiresAt=expiresAt}};QuestionSupersededError=class extends PublicMcpError{key;constructor(key){super(`A newer call asked the question "${key}" and waits for its answer instead.`,"QUESTION_SUPERSEDED",409);this.key=key}};QuestionNotFoundError=class extends PublicMcpError{mcpErrorCode=MCP_ERROR_CODES.RESOURCE_NOT_FOUND;constructor(){super("No such question.","QUESTION_NOT_FOUND",404)}};QuestionAlreadyAnsweredError=class extends PublicMcpError{constructor(){super("This question was answered already.","QUESTION_ALREADY_ANSWERED",409)}};QuestionStoreBusyError=class extends InternalMcpError{constructor(){super("The question changed under every attempt to update it; try again.","QUESTION_STORE_BUSY")}};InvalidQuestionStoreError=class extends InternalMcpError{constructor(reason){super(`elicitation.persistent: ${reason}`,"INVALID_QUESTION_STORE")}}}});var ask_question_exports={};__export(ask_question_exports,{askPersistentQuestion:()=>askPersistentQuestion,elicitPersistent:()=>elicitPersistent});import{toJSONSchema as toJSONSchema2,internalZ as z57}from"@frontmcp/lazy-zod";import{randomUUID as randomUUID8}from"@frontmcp/utils";async function delivered(answer,schema){if(answer.status!=="accept")return{status:answer.status};const parsed=await schema.safeParseAsync(answer.content);if(!parsed.success){throw new InvalidInputError("The answer does not match the requested schema",parsed.error.issues)}return{status:"accept",content:parsed.data}}async function askPersistentQuestion(deps,message,schema,options){const{store,subject,signal,sessionEnded}=deps;const request2={subject,key:options.key,message,requestedSchema:toJSONSchema2(schema),ttlMs:options.ttlMs,waiter:`call-${randomUUID8()}`};const handOver=async taken=>{const putBack=async()=>{await store.restore(request2,taken.answer,taken.expiresAt).catch(()=>void 0);return new QuestionPendingError(options.key,taken.expiresAt)};if(signal?.aborted)throw await putBack();const result=await delivered(taken.answer,schema);const ended=await sessionEnded?.();if(ended||signal?.aborted)throw await putBack();return result};const asked=await store.ask(request2);if(asked.kind==="answered")return handOver(asked);const{expiresAt}=asked.question;const answer=await new Promise((resolve4,reject)=>{let settled=false;let queued=false;let chain=Promise.resolve();const finish=settle=>{if(settled)return;settled=true;clearTimeout(timer);clearInterval(poll);stop();signal?.removeEventListener("abort",onAbort);settle()};const pending=()=>finish(()=>reject(new QuestionPendingError(options.key,expiresAt)));const handle=outcome=>{if(outcome.kind==="answered"){if(settled||signal?.aborted){pending();void store.restore(request2,outcome.answer,outcome.expiresAt).catch(()=>void 0);return}finish(()=>resolve4(outcome))}else if(outcome.kind==="superseded"){finish(()=>reject(new QuestionSupersededError(options.key)))}};const serialized=task=>{chain=chain.then(task).catch(error=>finish(()=>reject(error)))};const take=()=>store.take(subject,options.key,request2.waiter);const check=()=>{if(settled||queued)return;queued=true;serialized(async()=>{queued=false;if(!settled)handle(await take())})};const giveUp=()=>serialized(async()=>{if(settled)return;const outcome=await take();handle(outcome);if(outcome.kind==="waiting")pending()});const onAbort=()=>pending();const timer=setTimeout(giveUp,options.waitMs);const poll=setInterval(check,RECHECK_MS);const stop=store.subscribeToQuestion(subject,options.key,check);if(signal?.aborted)return onAbort();signal?.addEventListener("abort",onAbort,{once:true});check()});return handOver(answer)}async function elicitPersistent(deps,message,requestedSchema,options){const{persist}=options;if(typeof persist.key!=="string"||persist.key.length===0||persist.key.length>MAX_QUESTION_KEY_LENGTH){throw new InvalidInputError(`persist.key must be a string of 1 to ${MAX_QUESTION_KEY_LENGTH} characters`)}if(options.mode==="url")throw new InvalidInputError('a persistent question is a form: drop mode "url"');const waitMs=options.ttl??DEFAULT_ELICIT_TTL;const{questions}=deps;if(!questions){throw new ElicitationNotSupportedError("Persistent questions are off: enable them with @FrontMcp({ elicitation: { enabled: true, persistent: true } })")}const ttlMs=persist.ttlMs??questions.ttlMs;if(!Number.isInteger(ttlMs)||ttlMs<=waitMs){throw new InvalidInputError(`persist.ttlMs (${ttlMs}) must be a whole number longer than ttl (${waitMs}), the wait`)}const subject=questionSubjectOf(deps.tryGetContext()?.authInfo);if(!subject){throw new ElicitationNotSupportedError("A persistent question is kept for a signed-in user or a session, and this anonymous caller has neither")}const zodSchema=requestedSchema instanceof z57.ZodType?requestedSchema:z57.object(requestedSchema);const sessionEnded=deps.sessionId?questions.sessionEndCheck?.(deps.sessionId):void 0;return askPersistentQuestion({store:questions.store,subject,signal:deps.signal,sessionEnded},message,zodSchema,{key:persist.key,ttlMs,waitMs})}var RECHECK_MS,MAX_QUESTION_KEY_LENGTH;var init_ask_question=__esm({"libs/sdk/src/elicitation/questions/ask-question.ts"(){"use strict";init_errors();init_elicitation_types();init_question_subject();init_question_errors();RECHECK_MS=5e3;MAX_QUESTION_KEY_LENGTH=256}});import{toJSONSchema as toJSONSchema3,internalZ as z58}from"@frontmcp/lazy-zod";import{awaitOutsideRequest as awaitOutsideRequest3,randomUUID as randomUUID9}from"@frontmcp/utils";async function performElicit(deps,message,requestedSchema,options){const{sessionId,getClientCapabilities,tryGetContext,entryName,entryInput,elicitationEnabled}=deps;if(elicitationEnabled!==true){throw new ElicitationDisabledError}if(options?.persist){const{elicitPersistent:elicitPersistent2}=await Promise.resolve().then(()=>(init_ask_question(),ask_question_exports));return elicitPersistent2(deps,message,requestedSchema,{...options,persist:options.persist})}if(options?.mode==="url"&&!options.url){throw new InvalidInputError('url is required when mode is "url"')}const elicitOptions=options?.mode==="url"?{...options,elicitationId:options.elicitationId||generateElicitationId()}:options;const ctx=tryGetContext();const mrtr=ctx?.getMrtrExchange?.();if(mrtr&&mrtr.clientDeclaredRevision===false&&mrtr.supportsElicitation?.(options?.mode??"form")!==true){throw new ElicitationNotSupportedError("This client does not support elicitation: it declared no elicitation capability, and without a session the elicitation fallback has no one to answer it")}if(mrtr){const zodSchema=requestedSchema instanceof z58.ZodType?requestedSchema:z58.object(requestedSchema);const answer=mrtr.resolveElicitation({message,requestedSchema:toJSONSchema3(zodSchema),...elicitOptions?.mode?{mode:elicitOptions.mode}:{},...elicitOptions?.url?{url:elicitOptions.url}:{},...elicitOptions?.elicitationId?{elicitationId:elicitOptions.elicitationId}:{}},deps.inputKey);return checkedElicitAnswer(answer,requestedSchema,elicitOptions)}if(!sessionId){throw new ElicitationNotSupportedError("No session available for elicitation")}const preResolved=ctx?.getPreResolvedElicitResult?.();if(preResolved){ctx?.clearPreResolvedElicitResult?.();return checkedElicitAnswer(preResolved,requestedSchema,elicitOptions)}const capabilities=getClientCapabilities(sessionId);const mode=options?.mode??"form";if(!supportsElicitation(capabilities,mode)){const elicitId=elicitOptions?.elicitationId||generateElicitationId();const ttl=elicitOptions?.ttl??DEFAULT_ELICIT_TTL;const zodSchema=requestedSchema instanceof z58.ZodType?requestedSchema:z58.object(requestedSchema);const jsonSchema=toJSONSchema3(zodSchema);throw new ElicitationFallbackRequired(elicitId,message,jsonSchema,entryName,entryInput,ttl)}const transport=ctx?.transport;if(!transport){throw new ElicitationNotSupportedError("Transport not available for elicitation")}return awaitOutsideRequest3(transport.elicit(message,requestedSchema,elicitOptions))}function generateElicitationId(){return`elicit-${randomUUID9()}`}var init_elicit_helper=__esm({"libs/sdk/src/elicitation/helpers/elicit.helper.ts"(){"use strict";init_errors();init_notification();init_elicitation_types();init_checked_elicit_answer()}});function performSample(ctx,options){const mrtr=ctx?.getMrtrExchange?.();if(!mrtr)throw new SamplingNotAvailableError;return mrtr.resolveSampling({messages:options.messages,maxTokens:options.maxTokens,...options.systemPrompt===void 0?{}:{systemPrompt:options.systemPrompt},...options.modelPreferences===void 0?{}:{modelPreferences:options.modelPreferences},...options.temperature===void 0?{}:{temperature:options.temperature},...options.stopSequences===void 0?{}:{stopSequences:options.stopSequences},...options.includeContext===void 0?{}:{includeContext:options.includeContext},...options.metadata===void 0?{}:{metadata:options.metadata}})}function performListRoots(ctx){const mrtr=ctx?.getMrtrExchange?.();if(!mrtr)throw new SamplingNotAvailableError("roots/list");return mrtr.resolveRoots().roots}var init_mrtr_request_helper=__esm({"libs/sdk/src/elicitation/helpers/mrtr-request.helper.ts"(){"use strict";init_errors()}});var ELICITATION_FALLBACK_JSON_SCHEMA;var init_elicitation_fallback_schema=__esm({"libs/sdk/src/elicitation/elicitation-fallback.schema.ts"(){"use strict";ELICITATION_FALLBACK_JSON_SCHEMA={type:"object",properties:{elicitationPending:{type:"object",description:"Indicates this tool requires user input before it can complete",properties:{elicitId:{type:"string",description:"Unique identifier for this elicitation request. Pass to sendElicitationResult."},message:{type:"string",description:"Question or prompt to display to the user"},instructions:{type:"string",description:"Instructions for the LLM on how to handle the elicitation request"},schema:{type:"object",description:"JSON Schema describing the expected user response format"}},required:["elicitId","message"]}},required:["elicitationPending"],description:"Elicitation fallback response - tool requires user input to continue"}}});function extendOutputSchemaForElicitation(originalSchema){if(!originalSchema){return{type:"object",anyOf:[{type:"object",additionalProperties:true},ELICITATION_FALLBACK_JSON_SCHEMA]}}if(Array.isArray(originalSchema["oneOf"])){const existingOneOf=originalSchema["oneOf"];const hasElicitationFallback=existingOneOf.some(schema=>schema["properties"]&&typeof schema["properties"]==="object"&&"elicitationPending"in schema["properties"]);if(hasElicitationFallback){return{type:"object",...originalSchema}}return{type:"object",...originalSchema,oneOf:[...existingOneOf,ELICITATION_FALLBACK_JSON_SCHEMA]}}const{$defs:definitions,...wrappedSchema}=originalSchema;return{type:"object",oneOf:[wrappedSchema,ELICITATION_FALLBACK_JSON_SCHEMA],...definitions!==void 0&&{$defs:definitions}}}var init_extend_output_schema=__esm({"libs/sdk/src/elicitation/helpers/extend-output-schema.ts"(){"use strict";init_elicitation_fallback_schema()}});import{internalZ as z59}from"@frontmcp/lazy-zod";function validateElicitationContent(content,jsonSchema){try{const zodSchema=z59.fromJSONSchema(jsonSchema,{defaultTarget:"draft-2020-12"});const parseResult=zodSchema.safeParse(content);if(parseResult.success){return{success:true}}const errors=parseResult.error.issues.map(issue=>({path:issue.path.map(String),message:issue.message}));return{success:false,errors}}catch(err){return{success:false,errors:[{path:[],message:`Schema validation error: ${err instanceof Error?err.message:String(err)}`}]}}}var init_validate_elicitation_content=__esm({"libs/sdk/src/elicitation/helpers/validate-elicitation-content.ts"(){"use strict"}});var init_helpers=__esm({"libs/sdk/src/elicitation/helpers/index.ts"(){"use strict";init_elicit_helper();init_mrtr_request_helper();init_extend_output_schema();init_validate_elicitation_content();init_fallback_helper()}});function entryClassHooksJoin(join2){contextStageByFlow.set(join2.flow,join2.contextStage);return join2}function entryContextStageOf(flow){return contextStageByFlow.get(flow)}function stagesInOrder(plan58){return[...plan58.pre??[],...plan58.execute??[],...plan58.post??[],...plan58.finalize??[],...plan58.error??[]]}function describeUnreachableEntryClassHooks(hooks,join2,listFlows){const stages=stagesInOrder(join2.plan);const contextIndex=stages.indexOf(join2.contextStage);const problems=[];for(const{metadata}of hooks){const kind=metadata.static?"static ":"";const label=`${kind}${metadata.method}() (${metadata.type} '${String(metadata.stage)}' of ${metadata.flow})`;if(listFlows.includes(metadata.flow)){problems.push(`${label}: list flows build no entry instance and resolve no single entry to run it for`);continue}if(metadata.flow!==join2.flow||metadata.static)continue;const index=stages.indexOf(String(metadata.stage));const tooEarly=index!==-1&&(index<contextIndex||index===contextIndex&&(metadata.type==="will"||metadata.type==="around"));if(tooEarly){problems.push(`${label}: runs before '${join2.contextStage}' builds the instance it runs on; declare it as a static method to run it without an instance`)}}return problems}function unreachableHooksMessage(kind,className,problems){return`${kind} "${className}" declares hooks that would never run: ${problems.join("; ")}. Hooks declared as instance methods on a ${kind.toLowerCase()} class run on the instance built for each call; static methods run without one, from the first stage of a call. Declare hooks for list flows on a provider or a plugin instead.`}var contextStageByFlow;var init_entry_class_hooks=__esm({"libs/sdk/src/hooks/entry-class-hooks.ts"(){"use strict";contextStageByFlow=new Map}});function isTC39MethodContext(arg){return typeof arg==="object"&&arg!==null&&"kind"in arg&&arg.kind==="method"}var PendingMetadataRegistry;var init_decorator_utils=__esm({"libs/sdk/src/common/decorators/decorator-utils.ts"(){"use strict";PendingMetadataRegistry=class{pending=new WeakMap;store(method,metadata){const existing=this.pending.get(method)??[];existing.push(metadata);this.pending.set(method,existing)}consume(method){const pending=this.pending.get(method)??[];this.pending.delete(method);return pending}resolveForClass(ctor,consume=true){const resolved=[];const proto=ctor.prototype;if(proto){for(const name59 of Object.getOwnPropertyNames(proto)){if(name59==="constructor")continue;try{const desc=Object.getOwnPropertyDescriptor(proto,name59);const method=desc?.value;if(typeof method==="function"){const pending=consume?this.consume(method):this.pending.get(method)??[];resolved.push(...pending)}}catch{}}}for(const name59 of Object.getOwnPropertyNames(ctor)){if(["prototype","length","name"].includes(name59))continue;try{const desc=Object.getOwnPropertyDescriptor(ctor,name59);const method=desc?.value;if(typeof method==="function"){const pending=consume?this.consume(method):this.pending.get(method)??[];resolved.push(...pending)}}catch{}}return resolved}}}});function registerHookOnClass(ctor,meta){const arr=Reflect.getMetadata(FrontMcpFlowHookTokens.hooks,ctor)??[];arr.push(meta);Reflect.defineMetadata(FrontMcpFlowHookTokens.hooks,arr,ctor)}function resolvePendingTC39HooksForClass(ctor){return pendingHookRegistry.resolveForClass(ctor)}function peekPendingTC39HooksForClass(ctor){return pendingHookRegistry.resolveForClass(ctor,false)}function registerPendingTC39Hook(method,meta){pendingHookRegistry.store(method,meta)}function consumePendingTC39Hooks(method){return pendingHookRegistry.consume(method)}function assertHookOptions(type,stage,opts){const parsed=hookOptionsSchema.safeParse(opts);if(parsed.success)return;const[issue]=parsed.error.issues;const decoratorName=`${type[0].toUpperCase()}${type.slice(1)}('${stage}')`;throw new InvalidDecoratorMetadataError(decoratorName,String(issue?.path[0]??"options"),issue?.message??"")}function make(flow,type){return function(stage,opts={}){assertHookOptions(type,stage,opts);return(target,keyOrContext,_desc)=>{const{priority=0,filter,...rest}=opts;if(isTC39MethodContext(keyOrContext)){const context=keyOrContext;const methodName=String(context.name);const isStatic=context.static;const method=target;const meta={...rest,[FrontMcpFlowHookTokens.type]:true,flow,type,stage,method:methodName,priority,filter,target:null,static:isStatic};pendingHookRegistry.store(method,meta);return target}else{const key=keyOrContext;const methodName=String(key);const isStatic=typeof target==="function";const ctor=isStatic?target:target.constructor;const meta={...rest,[FrontMcpFlowHookTokens.type]:true,flow,type,stage,method:methodName,priority,filter,target,static:isStatic};registerHookOnClass(ctor,meta);return void 0}}}}function StageHookOf(flow){const base=make(flow,"stage");return function(stage,opts={}){return base(stage,opts)}}function WillHookOf(flow){const base=make(flow,"will");return function(stage,opts={}){return base(stage,opts)}}function DidHookOf(flow){const base=make(flow,"did");return function(stage,opts={}){return base(stage,opts)}}function AroundHookOf(name59){const base=make(name59,"around");return function(stage,opts={}){return base(stage,opts)}}function FinallyHookOf(name59){const base=make(name59,"finally");return function(stage,opts={}){return base(stage,opts)}}function FlowHooksOf(name59){return{Stage:StageHookOf(name59),Will:WillHookOf(name59),Did:DidHookOf(name59),Around:AroundHookOf(name59),Finally:FinallyHookOf(name59)}}var pendingHookRegistry;var init_hook_decorator=__esm({"libs/sdk/src/common/decorators/hook.decorator.ts"(){"use strict";init_decorator_errors();init_metadata();init_tokens();init_decorator_utils();pendingHookRegistry=new PendingMetadataRegistry}});import{getMetadata as getMetadata2,isClass as isClass2,ProviderKind,tokenName}from"@frontmcp/di";function collectProviderMetadata(cls){const metadata=Object.entries(FrontMcpProviderTokens).reduce((collected,[key,token])=>{return Object.assign(collected,{[key]:getMetadata2(token,cls)})},{});const ownName=Reflect.getOwnMetadata(FrontMcpProviderTokens.name,cls);metadata.name=ownName??tokenName(cls);return metadata}function extractProviderMetadata(item){const nested=item.metadata;const topLevel={};if(item.name!==void 0)topLevel.name=item.name;if(item.scope!==void 0)topLevel.scope=item.scope;if(item.description!==void 0)topLevel.description=item.description;if(item.id!==void 0)topLevel.id=item.id;const result={...nested,...topLevel};if(!result.name){result.name=(item.provide?tokenName(item.provide):void 0)||"UnknownProvider"}return result}function normalizeProvider(item){if(isClass2(item)){const metadata=collectProviderMetadata(item);return{kind:ProviderKind.CLASS_TOKEN,provide:item,metadata}}if(item&&typeof item==="object"){const providerItem=item;const{provide,useClass,useValue,useFactory,inject}=providerItem;if(!provide){const name60=providerItem.name??"[object]";throw new MissingProvideError("Provider",name60)}const metadata=extractProviderMetadata(providerItem);if(useClass){if(!isClass2(useClass)){throw new InvalidUseClassError("provider",tokenName(provide))}return{kind:ProviderKind.CLASS,provide,useClass,metadata}}if(useFactory){if(typeof useFactory!=="function"){throw new InvalidUseFactoryError("provider",tokenName(provide))}const inj=typeof inject==="function"?inject:()=>[];return{kind:ProviderKind.FACTORY,provide,inject:inj,useFactory,metadata}}if("useValue"in item){return{kind:ProviderKind.VALUE,provide,useValue,metadata}}}const name59=item?.name??String(item);throw new InvalidEntityError("provider",name59,"a class or a provider object")}function providerDiscoveryDeps(rec,tokens,depsOfClass14){switch(rec.kind){case ProviderKind.VALUE:return[];case ProviderKind.FACTORY:{const all=[...rec.inject()];return all.filter(d=>tokens.has(d))}case ProviderKind.CLASS:return depsOfClass14(rec.useClass,"discovery");case ProviderKind.CLASS_TOKEN:return depsOfClass14(rec.provide,"discovery");case ProviderKind.INJECTED:return depsOfClass14(rec.value,"discovery")}}function providerInvocationTokens(rec,depsOfClass14){switch(rec.kind){case ProviderKind.VALUE:return[];case ProviderKind.FACTORY:return[...rec.inject()];case ProviderKind.CLASS:return depsOfClass14(rec.useClass,"invocation");case ProviderKind.CLASS_TOKEN:return depsOfClass14(rec.provide,"invocation");case ProviderKind.INJECTED:return depsOfClass14(rec.value,"invocation")}}var init_provider_utils=__esm({"libs/sdk/src/provider/provider.utils.ts"(){"use strict";init_common();init_errors()}});import{getMetadata as getMetadata3,isClass as isClass3}from"@frontmcp/di";function collectHook(cls){return getMetadata3(FrontMcpFlowHookTokens.hooks,cls)??[]}function normalizeHooksFromCls(source){const cls=isClass3(source)?source:source?.constructor;if(!isClass3(cls)){return[]}const methodHolder=cls===source?cls.prototype:source;const allHooks=[...collectHook(cls),...resolvePendingTC39HooksForClass(cls)];return allHooks.map(hook=>({kind:"METHOD_TOKEN",provide:hook.static?cls[hook.method]:methodHolder[hook.method],metadata:{...hook,target:hook.static?cls:methodHolder}}))}function normalizeHooksFromProviders(providers,only){const records=[];for(const[token,instance]of providers.getAllSingletons()){if(only&&!only.has(token))continue;if(typeof instance==="object"&&instance!==null)records.push(...normalizeHooksFromCls(instance))}for(const{token,cls}of providers.getContextScopedClasses()){if(only&&!only.has(token))continue;for(const record of normalizeHooksFromCls(cls)){records.push(record.metadata.static?record:{...record,metadata:{...record.metadata,contextTarget:contextInstanceOf(providers,token)}})}}return records}function serverProviderHooks(providers,declared,owner){if(!declared?.length)return[];const tokens=new Set(declared.map(provider=>normalizeProvider(provider).provide));return normalizeHooksFromProviders(providers,tokens).map(hook=>({...hook,metadata:{...hook.metadata,owner}}))}function contextInstanceOf(providers,token){return async({sessionKey,contextProviders,contextSource})=>{const views=await providers.buildViews(sessionKey,new Map(contextProviders),contextSource);const instance=views.context.get(token);return typeof instance==="object"&&instance!==null?instance:void 0}}function sourceMetadataOf(metadata){return boundFrom.get(metadata)??metadata}async function bindContextHookTargets(hooks,run){if(!hooks.some(hook=>hook.metadata.contextTarget))return[...hooks];const bound=[];for(const hook of hooks){const{contextTarget}=hook.metadata;if(!contextTarget){bound.push(hook);continue}const target=await contextTarget(run);if(target){const metadata={...hook.metadata,target,contextTarget:void 0};boundFrom.set(metadata,hook.metadata);bound.push({metadata})}}return bound}function hooksBoundTo(entries,instance){const target=instance;return entries.filter(entry=>!entry.metadata.static).map(entry=>({metadata:{...entry.metadata,target}}))}function staticHooksFor(entries,flow){return entries.filter(entry=>entry.metadata.static===true&&entry.metadata.flow===flow)}var boundFrom;var init_hooks_utils=__esm({"libs/sdk/src/hooks/hooks.utils.ts"(){"use strict";init_common();init_hook_decorator();init_provider_utils();boundFrom=new WeakMap}});import{z as z60}from"@frontmcp/lazy-zod";function utf8Bytes(text){return encoder.encode(text).byteLength}function jsonBytes(value){return utf8Bytes(JSON.stringify(value)??"")}function isLeftOut(value){return value===void 0||typeof value==="function"||typeof value==="symbol"}function isPlainContainer(value){if(typeof value.toJSON==="function")return false;const prototype=Object.getPrototypeOf(value);return Array.isArray(value)||prototype===Object.prototype||prototype===null}function sizeOf(value,sizes){if(typeof value!=="object"||value===null||!isPlainContainer(value))return jsonBytes(value);const known=sizes.get(value);if(known!==void 0)return known;let size=2;if(Array.isArray(value)){for(const item of value)size+=isLeftOut(item)?4:sizeOf(item,sizes);size+=Math.max(value.length-1,0)}else{let written=0;for(const[key,item]of Object.entries(value)){if(isLeftOut(item))continue;size+=jsonBytes(key)+1+sizeOf(item,sizes);written++}size+=Math.max(written-1,0)}sizes.set(value,size);return size}function isRecord2(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function prefixOf(text,length){const lastCode=text.charCodeAt(length-1);const splitsPair=length>0&&lastCode>=55296&&lastCode<=56319;return text.slice(0,splitsPair?length-1:length)}function longestPrefix(text,allowance,sizeOf2){let low=0;let high=text.length;while(low<high){const middle=Math.ceil((low+high)/2);if(sizeOf2(prefixOf(text,middle))<=allowance)low=middle;else high=middle-1}return prefixOf(text,low)}function childPath(path4,key){return IDENTIFIER.test(key)?`${path4}.${key}`:`${path4}[${JSON.stringify(key)}]`}function fitNode(node,size,allowance,path4,context){if(size<=allowance)return node;if(typeof node==="string")return fitString(node,allowance,path4,context);if(Array.isArray(node))return fitList(node,allowance,path4,context);if(isRecord2(node))return fitRecord(node,size,allowance,path4,context);return node}function fitString(text,allowance,path4,context){const kept=longestPrefix(text,allowance,jsonBytes);context.omitted.push({path:path4,chars:text.length-kept.length});return kept}function fitList(items,allowance,path4,context){if(items.length===0)return items;const sizes=items.map(item=>sizeOf(item,context.sizes));const indexes=items.map((_,index)=>index);const preferred=context.lists==="keep-newest"?indexes.reverse():indexes;const kept=[];let used=2;for(const index of preferred){const added=sizes[index]+(kept.length>0?1:0);if(used+added>allowance)break;used+=added;kept.push(index)}if(kept.length===0){const[first3]=preferred;if(items.length>1)context.omitted.push({path:path4,items:items.length-1,of:items.length});return[fitNode(items[first3],sizes[first3],allowance-2,`${path4}[0]`,context)]}context.omitted.push({path:path4,items:items.length-kept.length,of:items.length});return kept.sort((left,right)=>left-right).map(index=>items[index])}function fitRecord(record,size,allowance,path4,context){const entries=Object.entries(record);const sizes=entries.map(([,value])=>sizeOf(value,context.sizes));const largestFirst=entries.map((_,index)=>index).sort((left,right)=>sizes[right]-sizes[left]);const fitted={...record};let total=size;for(const index of largestFirst){if(total<=allowance)break;const[key,value]=entries[index];const shrunk=fitNode(value,sizes[index],Math.max(sizes[index]-(total-allowance),0),childPath(path4,key),context);if(shrunk===value)continue;total-=sizes[index]-sizeOf(shrunk,context.sizes);fitted[key]=shrunk}return fitted}function fitJsonToBudget(value,maxBytes,lists="keep-newest"){const context={lists,omitted:[],sizes:new WeakMap};const size=sizeOf(value,context.sizes);if(size<=maxBytes)return{value,omitted:[]};return{value:fitNode(value,size,maxBytes,"$",context),omitted:context.omitted}}function parseJsonText(text){const start=text.trimStart()[0];if(start!=="{"&&start!=="[")return void 0;try{return JSON.parse(text)}catch{return void 0}}function fitTextToBudget(text,maxBytes,lists){if(utf8Bytes(text)<=maxBytes)return{value:text,omitted:[]};const json=parseJsonText(text);if(json!==void 0){const fitted=fitJsonToBudget(json,maxBytes,lists);return{value:JSON.stringify(fitted.value),omitted:fitted.omitted}}const kept=longestPrefix(text,maxBytes,utf8Bytes);return{value:kept,omitted:[{path:"$",chars:text.length-kept.length}]}}function describeOmission(omission,lists){const where=omission.path==="$"?"the answer":omission.path;if(omission.items!==void 0){const end=lists==="keep-newest"?"first":"last";return`the ${end} ${omission.items} of ${omission.of} items of ${where}`}return`the last ${omission.chars} characters of ${where}`}function describeBudgetNote(note){const described=note.omitted.slice(0,NOTED_OMISSIONS).map(omission=>describeOmission(omission,note.lists));const more=note.omitted.length-described.length;if(more>0)described.push(`${more} more parts listed in _meta["${BUDGET_META_KEY}"]`);return`This answer was shortened to fit its ${note.maxBytes}-byte budget: left out ${described.join("; ")}.`}function addOmissions(omitted,added){const known=new Set(omitted.map(omission=>JSON.stringify(omission)));omitted.push(...added.filter(omission=>!known.has(JSON.stringify(omission))))}function fitToolAnswer(result,budget){const lists=budget.lists??"keep-newest";const omitted=[];let changed=false;let structuredContent=result.structuredContent;const structuredText=structuredContent===void 0?void 0:JSON.stringify(structuredContent);let fittedStructuredText;if(structuredContent!==void 0&&structuredText!==void 0&&utf8Bytes(structuredText)>budget.maxBytes){const fitted=fitJsonToBudget(structuredContent,budget.maxBytes,lists);structuredContent=fitted.value;fittedStructuredText=JSON.stringify(structuredContent);omitted.push(...fitted.omitted);changed=true}const content=result.content.map(block=>{if(block.type!=="text")return block;if(fittedStructuredText!==void 0&&block.text===structuredText)return{...block,text:fittedStructuredText};const fitted=fitTextToBudget(block.text,budget.maxBytes,lists);if(fitted.value===block.text)return block;addOmissions(omitted,fitted.omitted);changed=true;return{...block,text:fitted.value}});if(!changed)return void 0;if(omitted.length===0)return{...result,content};const note={maxBytes:budget.maxBytes,lists,omitted};return{...result,content:[...content,{type:"text",text:describeBudgetNote(note)}],...structuredContent!==void 0&&{structuredContent},_meta:{...result._meta,[BUDGET_META_KEY]:note}}}function fitResourceAnswer(result,budget){const lists=budget.lists??"keep-newest";const omitted=[];let changed=false;const contents=result.contents.map(content=>{if(!("text"in content)||typeof content.text!=="string"||content.mimeType?.startsWith("text/html")){return content}const fitted=fitTextToBudget(content.text,budget.maxBytes,lists);if(fitted.value===content.text)return content;omitted.push(...fitted.omitted.map(omission=>({uri:content.uri,...omission})));changed=true;return{...content,text:fitted.value}});if(!changed)return void 0;if(omitted.length===0)return{...result,contents};const note={maxBytes:budget.maxBytes,lists,omitted};const noteUri=omitted[0].uri??result.contents[0].uri;return{...result,contents:[...contents,{uri:noteUri,mimeType:"text/plain",text:describeBudgetNote(note)}],_meta:{...result._meta,[BUDGET_META_KEY]:note}}}function parserOf(outputSchema51){const known=listedSchemaParsers.get(outputSchema51);if(known)return known;let parser;try{parser=z60.fromJSONSchema(withUndeclaredKeysAllowed(outputSchema51),{defaultTarget:"draft-2020-12"})}catch(error){parser=error instanceof Error?error:new Error(String(error))}listedSchemaParsers.set(outputSchema51,parser);return parser}function outputSchemaMismatch(outputSchema51,structuredContent){const parser=parserOf(outputSchema51);if(parser instanceof Error)return`the schema could not be checked: ${parser.message}`;const parsed=parser.safeParse(structuredContent);if(parsed.success)return void 0;const[issue]=parsed.error.issues;return`${["$",...issue.path.map(String)].join(".")}: ${issue.message}`}var BUDGET_META_KEY,NOTED_OMISSIONS,listedSchemaParsers,IDENTIFIER,encoder;var init_answer_budget=__esm({"libs/sdk/src/answer/answer-budget.ts"(){"use strict";init_output_policy();BUDGET_META_KEY="frontmcp/budget";NOTED_OMISSIONS=5;listedSchemaParsers=new WeakMap;IDENTIFIER=/^[A-Za-z_$][\w$]*$/;encoder=new TextEncoder}});import{registerOptionalModule,requireOptionalModule}from"@frontmcp/utils";function probeOptionalDependency(moduleName,loadError,resolve4){let resolvedPath;try{resolvedPath=resolve4(moduleName)}catch{resolvedPath=void 0}const error=loadError instanceof Error?loadError.message:String(loadError);return resolvedPath?{status:"load-failed",resolvedPath,error}:{status:"not-installed",error}}var init_optional_dependency_util=__esm({"libs/sdk/src/scope/optional-dependency.util.ts"(){"use strict"}});function meteringEnabled(metrics){if(metrics?.enabled!==true)return false;return!metrics.include||metrics.include.length===0||metrics.include.includes("tools")}function measureAnswer(result){const bytes=encoder2.encode(JSON.stringify(result)).byteLength;const structuredText=result.structuredContent===void 0?void 0:JSON.stringify(result.structuredContent);const duplicatedBytes=result.content.reduce((sum,block)=>block.type==="text"&&block.text===structuredText?sum+encoder2.encode(block.text).byteLength:sum,0);return{bytes,estimatedTokens:Math.ceil(bytes/4),duplicatedBytes}}function loadCounterFactory(){return requireOptionalModule("@frontmcp/observability",()=>__require("@frontmcp/observability")).createCounter}function recordAnswerCost(cost,labels,createCounter=loadCounterFactory()){for(const key of Object.keys(ANSWER_COUNTERS)){createCounter(ANSWER_COUNTERS[key],COUNTER_DESCRIPTIONS[key]).inc(cost[key],labels)}}var ANSWER_COUNTERS,COUNTER_DESCRIPTIONS,encoder2;var init_answer_meter=__esm({"libs/sdk/src/answer/answer-meter.ts"(){"use strict";init_optional_dependency_util();ANSWER_COUNTERS={bytes:"frontmcp_tool_answer_bytes_total",estimatedTokens:"frontmcp_tool_answer_estimated_tokens_total",duplicatedBytes:"frontmcp_tool_answer_duplicated_bytes_total"};COUNTER_DESCRIPTIONS={bytes:"UTF-8 bytes of tool answers as JSON",estimatedTokens:"Tokens tool answers cost, estimated as bytes / 4",duplicatedBytes:"Bytes of tool answer text that repeats structuredContent"};encoder2=new TextEncoder}});var init_answer=__esm({"libs/sdk/src/answer/index.ts"(){"use strict";init_answer_budget();init_answer_meter();init_client_profile()}});async function isEntryEnabled(enabled,context,logger){if(enabled===void 0||typeof enabled==="boolean")return enabled!==false;try{return await enabled.get(context)===true}catch(error){logger?.warn(`An enabled source failed to answer, so its entry is off: ${error instanceof Error?error.message:String(error)}`);return false}}async function enabledItems(items,enabledOf,context,logger){const answers=await Promise.all(items.map(item=>isEntryEnabled(enabledOf(item),context,logger)));return items.filter((_item,index)=>answers[index])}async function assertEntryEnabled(entryType,entryName,enabled,context,logger){if(await isEntryEnabled(enabled,context,logger))return;throw new FeatureOffError(entryType,entryName,typeof enabled==="object"?enabled.remedy:void 0)}var init_entry_enabled=__esm({"libs/sdk/src/surface/entry-enabled.ts"(){"use strict";init_mcp_error()}});function markPlaceholder(entry,app){appOfPlaceholder.set(entry,app)}function lazyAppOf(entry){return appOfPlaceholder.get(entry)}async function loadAppOfPlaceholder(scope,entry){const app=lazyAppOf(entry);if(!app||!await isEntryEnabled(entry.metadata.enabled,requestContextOf(scope)))return false;return app.load().then(()=>true,()=>false)}function requestContextOf(scope){try{return scope.providers.get(FrontMcpContextStorage).getStore()}catch{return void 0}}function assertAppLoaded(entry){const app=lazyAppOf(entry);if(app)throw new LazyAppLoadError(app.metadata.name,app.retryable)}var appOfPlaceholder;var init_lazy_placeholders=__esm({"libs/sdk/src/app/lazy/lazy-placeholders.ts"(){"use strict";init_frontmcp_context_storage();init_lazy_app_errors();init_entry_enabled();appOfPlaceholder=new WeakMap}});async function loadRemoteAppCapabilities(scope,onError=()=>void 0){const remoteApps=scope.providers.getRegistries("AppRegistry").flatMap(appRegistry=>appRegistry.getApps()).filter(app=>app.isRemote);await Promise.all(remoteApps.map(async app=>{if(!("ensureCapabilitiesLoaded"in app)||typeof app.ensureCapabilitiesLoaded!=="function")return;try{await app.ensureCapabilitiesLoaded()}catch(error){onError(app.id,error)}}));return remoteApps.length}var init_remote_capabilities_utils=__esm({"libs/sdk/src/app/remote-capabilities.utils.ts"(){"use strict"}});import{decodeJwtPayloadSafe,isOrchestratedMode as isOrchestratedMode2}from"@frontmcp/auth";function readAuthorizedApps(source){if(!source||typeof source!=="object")return void 0;return source["authorized_apps"]}function readUser(source){if(!source||typeof source!=="object")return void 0;return source["user"]}function asAppIdList(value){if(!Array.isArray(value))return void 0;return value.filter(id=>typeof id==="string")}function getAuthorizedAppIds(authInfo){if(!authInfo)return void 0;const list=asAppIdList(readAuthorizedApps(readUser(authInfo.extra)))??asAppIdList(readAuthorizedApps(authInfo.extra))??asAppIdList(readAuthorizedApps(authInfo.user))??asAppIdList(decodeJwtPayloadSafe(authInfo.token)?.["authorized_apps"]);if(!list)return void 0;return new Set(list)}function grantAppId(app){return app.id??app.metadata.id??""}function isIncrementalAuthEnabled(authOptions){if(!authOptions||!isOrchestratedMode2(authOptions))return false;return authOptions.incrementalAuth!==void 0&&authOptions.incrementalAuth.enabled!==false}function incrementalTicketAudience(scope){const issuer=scope.auth?.issuer;return JSON.stringify([typeof issuer==="string"?issuer:"",scope.fullPath])}function initialAuthorizedApps(authOptions,apps,requestedAppIds){if(!isIncrementalAuthEnabled(authOptions))return void 0;const knownAppIds=new Set(apps.map(grantAppId).filter(Boolean));return requestedAppIds?[...new Set(requestedAppIds)].filter(id=>knownAppIds.has(id)):[...knownAppIds]}function withoutSkippedApps(grant,apps,skippedProviderIds){if(!skippedProviderIds||skippedProviderIds.length===0)return[...grant];const skippedAppIds=new Set(apps.filter(app=>app.metadata.auth&&skippedProviderIds.includes(app.metadata.id||app.metadata.name||"")).map(grantAppId));return grant.filter(id=>!skippedAppIds.has(id))}var init_authorized_apps_utils=__esm({"libs/sdk/src/auth/authorized-apps.utils.ts"(){"use strict"}});import{decodeJwtPayloadSafe as decodeJwtPayloadSafe2}from"@frontmcp/auth";function readConsent(source){if(!source||typeof source!=="object")return void 0;return source["consent"]}function readUser2(source){if(!source||typeof source!=="object")return void 0;return source["user"]}function asConsentClaim(value){if(!value||typeof value!=="object")return void 0;const claim=value;if(claim.enabled!==true)return void 0;return claim}function getConsentedToolIds(authInfo){if(!authInfo)return void 0;const claim=asConsentClaim(readConsent(readUser2(authInfo.extra)))??asConsentClaim(readConsent(authInfo.extra))??asConsentClaim(readConsent(authInfo.user))??asConsentClaim(decodeJwtPayloadSafe2(authInfo.token)?.["consent"]);if(!claim)return void 0;const selected=Array.isArray(claim.selectedTools)?claim.selectedTools.filter(t=>typeof t==="string"):[];return new Set(selected)}function isToolConsented(consented,...toolIds){if(!consented)return true;return toolIds.some(id=>id!==void 0&&consented.has(id))}var init_consent_utils=__esm({"libs/sdk/src/auth/consent.utils.ts"(){"use strict"}});function toolNameCandidates(name59){if(!/[-_]/.test(name59))return[name59];return[name59,name59.includes("_")?name59.replace(/_/g,"-"):name59.replace(/-/g,"_")]}function toolAliasesOf(tool){return tool.metadata.aliases??[]}function lookupTool(scope,name59){const fullName=ownerQualifiedName(name59);const scopeTools=scope.tools.getTools(true);return findTool(scope,scopeTools,entry=>toolAliasesOf(entry).includes(name59))??findTool(scope,scopeTools,matchesName(name59))??(fullName===void 0?void 0:findTool(scope,scopeTools,matchesName(fullName)))}function ownerQualifiedName(name59){const separator=name59.indexOf(".");return separator>0?`${name59.slice(0,separator)}:${name59.slice(separator+1)}`:void 0}function describeToolAliasConflicts(tools){const uniqueTools=[...new Set(tools)];const toolByName=new Map;for(const tool of uniqueTools){toolByName.set(tool.name,tool);toolByName.set(tool.fullName,tool)}const toolByAlias=new Map;const conflicts=[];for(const tool of uniqueTools){for(const alias of toolAliasesOf(tool)){const named=toolByName.get(alias);if(named)conflicts.push(`alias "${alias}" of tool "${tool.name}" is the name of tool "${named.name}"`);const declarer=toolByAlias.get(alias);if(declarer&&declarer!==tool){conflicts.push(`alias "${alias}" is declared by both "${declarer.fullName}" and "${tool.fullName}"`)}toolByAlias.set(alias,tool)}}return conflicts}function matchesName(name59){const candidateNames=toolNameCandidates(name59);return entry=>candidateNames.includes(entry.fullName)||candidateNames.includes(entry.name)}function findTool(scope,scopeTools,matches){const scopeTool=scopeTools.find(matches);if(scopeTool)return scopeTool;for(const appRegistry of scope.providers?.getRegistries("AppRegistry")??[]){for(const app of appRegistry.getApps()){if(!app.isRemote)continue;const remoteTool=app.tools.getTools(true).find(matches);if(remoteTool)return remoteTool}}return void 0}var init_tool_lookup_utils=__esm({"libs/sdk/src/common/utils/tool-lookup.utils.ts"(){"use strict"}});import{AsyncLocalStorage as AsyncLocalStorage5}from"@frontmcp/utils";function runAsTool(tool,fn){return runningTools.run(tool,fn)}function getRunningTool(){return runningTools.getStore()}var runningTools;var init_running_tool=__esm({"libs/sdk/src/context/running-tool.ts"(){"use strict";runningTools=new AsyncLocalStorage5}});var ResolvedEntries;var init_resolved_entries=__esm({"libs/sdk/src/flows/resolved-entries.ts"(){"use strict";ResolvedEntries=class{byInput=new WeakMap;remember(rawInput,key,entry){if(typeof rawInput==="object"&&rawInput!==null)this.byInput.set(rawInput,{key,entry})}peek(rawInput,key){if(typeof rawInput!=="object"||rawInput===null)return void 0;const resolved=this.byInput.get(rawInput);return resolved?.key===key?resolved.entry:void 0}take(rawInput,key){const entry=this.peek(rawInput,key);if(typeof rawInput==="object"&&rawInput!==null)this.byInput.delete(rawInput);return entry}}}});var FlowContextProviders;var init_flow_context_providers=__esm({"libs/sdk/src/provider/flow-context-providers.ts"(){"use strict";FlowContextProviders=class{constructor(baseProviders,contextDeps){this.baseProviders=baseProviders;this.contextDeps=contextDeps}baseProviders;contextDeps;get(token){if(this.contextDeps.has(token)){return this.contextDeps.get(token)}return this.baseProviders.get(token)}getScope(){return this.baseProviders.getScope()}getProviders(){return this.baseProviders.getProviders()}getRegistries(type){return this.baseProviders.getRegistries(type)}buildViews(sessionKey,contextProviders,contextSource){return this.baseProviders.buildViews(sessionKey,contextProviders,contextSource)}}}});function detectSkillsOnlyMode(query){if(!query)return false;const mode=query["mode"];if(mode==="skills_only"){return true}if(Array.isArray(mode)&&mode.includes("skills_only")){return true}return false}function isSkillsOnlySession(sessionPayload){return sessionPayload?.skillsOnlyMode===true}function isSkillsOnlyRequest(authInfo,context){return isSkillsOnlySession(authInfo?.sessionIdPayload)||context?.has(SKILLS_ONLY_REQUEST)===true}var SKILLS_ONLY_REQUEST;var init_skill_mode_utils=__esm({"libs/sdk/src/skill/skill-mode.utils.ts"(){"use strict";SKILLS_ONLY_REQUEST=Symbol.for("frontmcp:skills:skills-only-request")}});import{basename as basename2,dirname as dirname2,readFile,watchFile}from"@frontmcp/utils";function fileSignal(path4,key,options={}){if(!path4)throw new InvalidFileSignalError("it needs a file path");if(!key)throw new InvalidFileSignalError("it needs a key");const{pollIntervalMs}=options;if(pollIntervalMs!==void 0&&!(Number.isFinite(pollIntervalMs)&&pollIntervalMs>0)){throw new InvalidFileSignalError(`pollIntervalMs must be a positive number, got ${pollIntervalMs}`)}return new FileSignal(path4,key,options)}var FileSignal;var init_file_signal=__esm({"libs/sdk/src/surface/file-signal.ts"(){"use strict";init_mcp_error();FileSignal=class{constructor(path4,key,options){this.path=path4;this.key=key;this.defaultValue=options.defaultValue??false;this.pollIntervalMs=options.pollIntervalMs??2e3;this.remedy=options.remedy??{say:`Turn on the "${key}" feature, then try again.`};this.logger=options.logger??console}path;key;remedy;defaultValue;pollIntervalMs;logger;listeners=new Set;value;problem;watcher;poller;checking=Promise.resolve();async get(){return this.value??this.read()}subscribe(listener){this.listeners.add(listener);if(this.listeners.size===1)this.start();return()=>{if(this.listeners.delete(listener)&&this.listeners.size===0)this.stop()}}start(){this.check();try{const fileName=basename2(this.path);this.watcher=watchFile(dirname2(this.path),(_event,changed)=>{if(!changed||changed===fileName)this.check()});this.watcher.onError(()=>this.closeWatcher())}catch{this.watcher=void 0}this.poller=setInterval(()=>this.check(),this.pollIntervalMs);this.poller.unref?.()}stop(){this.closeWatcher();clearInterval(this.poller);this.poller=void 0;this.value=void 0}closeWatcher(){this.watcher?.close();this.watcher=void 0}check(){this.checking=this.checking.then(async()=>{const next=await this.read();if(this.listeners.size===0)return;const previous=this.value;this.value=next;if(previous===void 0||previous===next)return;for(const listener of[...this.listeners])this.notify(listener)})}notify(listener){try{listener()}catch(error){this.logger.warn(`fileSignal: a listener of "${this.key}" failed: ${error instanceof Error?error.message:String(error)}`)}}async read(){let content;try{content=await readFile(this.path)}catch{return this.fallBack(`${this.path} could not be read`)}let parsed;try{parsed=JSON.parse(content)}catch{return this.fallBack(`${this.path} is not valid JSON`,this.value)}const value=parsed?.[this.key];if(typeof value!=="boolean")return this.fallBack(`${this.path} has no boolean "${this.key}"`);this.problem=void 0;return value}fallBack(problem2,lastValue){const value=lastValue??this.defaultValue;if(this.problem!==problem2){this.problem=problem2;const kept=lastValue===void 0?"its default":"its last value";this.logger.warn(`fileSignal: ${problem2}; "${this.key}" is ${value?"on":"off"}, ${kept}.`)}return value}}}});import{sha256Hex as sha256Hex2}from"@frontmcp/utils";function messageOf(error){return error instanceof Error?error.message:String(error)}function surfaceHash(names){return sha256Hex2([...names].sort().join("\n")).slice(0,16)}var SURFACE_META_KEY,LIST_KINDS,LiveSurface;var init_live_surface=__esm({"libs/sdk/src/surface/live-surface.ts"(){"use strict";init_enabled_metadata();init_transport_types();init_list_change_batch();SURFACE_META_KEY="frontmcp/surface";LIST_KINDS=["tools","resources","prompts"];LiveSurface=class{constructor(scope,options={}){this.scope=scope;this.windowMs=options.windowMs??100;this.maxSessions=options.maxSessions??1e4}scope;windowMs;maxSessions;sources=new Map;pending=new Map;stops=[];toolsVersion=0;listedVersions=new Map;running=false;start(){if(this.running)return;this.running=true;for(const kind of LIST_KINDS){this.followSources(kind);this.stops.push(this.registryOf(kind).subscribe({immediate:false},()=>this.followSources(kind)))}this.stops.push(this.scope.tools.subscribe({immediate:false},()=>{if(announcesListChangeNow(this.scope,"tools"))this.toolsVersion++}))}stop(){this.running=false;for(const stop of this.stops.splice(0))stop();for(const watched of this.sources.values())for(const unsubscribe of watched.values())unsubscribe();this.sources.clear();for(const timer of this.pending.values())clearTimeout(timer);this.pending.clear()}listChanged(kind){if(!this.running||this.pending.has(kind))return;const timer=setTimeout(()=>{this.pending.delete(kind);try{this.registryOf(kind).notifyListChanged()}catch(error){this.scope.logger.warn(`The ${kind} list change could not be announced: ${messageOf(error)}`)}},this.windowMs);timer.unref?.();this.pending.set(kind,timer)}recordToolList(sessionId,names){if(this.isConnectedSession(sessionId)){this.listedVersions.delete(sessionId);this.listedVersions.set(sessionId,this.toolsVersion);if(this.listedVersions.size>this.maxSessions){const[leastRecent]=this.listedVersions.keys();this.listedVersions.delete(leastRecent)}}return surfaceHash(names)}isStale(sessionId){const listed=sessionId===void 0?void 0:this.listedVersions.get(sessionId);return listed!==void 0&&listed<this.toolsVersion}refreshSession(sessionId){if(this.listedVersions.has(sessionId))this.listedVersions.set(sessionId,this.toolsVersion);this.scope.notifications.sendNotificationToSession(sessionId,"notifications/tools/list_changed")}isConnectedSession(sessionId){if(!sessionId||sessionId===STATELESS_SESSION_ID)return false;return this.scope.notifications.getRegisteredServer(sessionId)!==void 0}registryOf(kind){return this.scope[kind]}followSources(kind){const used=new Set(this.registryOf(kind).listAllInstances().map(entry=>entry.metadata.enabled).filter(isEnabledSource));const watched=this.sources.get(kind)??new Map;this.sources.set(kind,watched);for(const[source,unsubscribe]of watched){if(used.has(source))continue;unsubscribe();watched.delete(source)}for(const source of used){if(watched.has(source))continue;try{watched.set(source,source.subscribe(()=>this.listChanged(kind)))}catch(error){watched.set(source,()=>void 0);this.scope.logger.warn(`An enabled source of the ${kind} could not be followed: ${messageOf(error)}`)}}}}}});var init_surface=__esm({"libs/sdk/src/surface/index.ts"(){"use strict";init_file_signal();init_entry_enabled();init_live_surface()}});import{randomUUID as randomUUID10}from"@frontmcp/utils";function generateTaskId(){return randomUUID10()}var init_task_id=__esm({"libs/sdk/src/task/helpers/task-id.ts"(){"use strict"}});var TaskNotifier;var init_task_notifier=__esm({"libs/sdk/src/task/helpers/task-notifier.ts"(){"use strict";init_task_types();TaskNotifier=class{constructor(notifications,logger){this.notifications=notifications;this.logger=logger}notifications;logger;sendStatus(record){const params={...toWireShape(record)};try{this.notifications.sendNotificationToSession(record.sessionId,"notifications/tasks/status",params)}catch(err){this.logger?.warn("[TaskNotifier] sendStatus failed",{taskId:record.taskId,error:err instanceof Error?err.message:String(err)})}}}}});function linkedAbortController(signal){return detachableAbortController(signal).controller}function detachableAbortController(signal){const controller=new AbortController;const followSignal=()=>controller.abort(signal?.reason);if(signal?.aborted)controller.abort(signal.reason);else signal?.addEventListener("abort",followSignal,{once:true});return{controller,unlink:()=>signal?.removeEventListener("abort",followSignal)}}var init_abort_utils=__esm({"libs/sdk/src/utils/abort.utils.ts"(){"use strict"}});var FrontMcpConfig;var init_front_mcp_tokens2=__esm({"libs/sdk/src/front-mcp/front-mcp.tokens.ts"(){"use strict";FrontMcpConfig=Symbol("FrontMcpConfig")}});function isServerEntryOwner(owner){return owner?.kind===serverEntryOwner.kind&&owner.id===serverEntryOwner.id&&owner.ref===serverEntryOwner.ref}function ownerKeyOf(lineage){return lineage.map(o=>`${o.kind}:${o.id}`).join("/")}function qualifiedNameOf(lineage,name59){return`${ownerKeyOf(lineage)}:${name59}`}function hookOwnerIdOf(lineage,owner){const owners2=owner?[...lineage,owner]:lineage;return appOwnerIdOf(owners2)??owners2[owners2.length-1]?.id}function appOwnerIdOf(lineage,owner){const owners2=owner?[...lineage,owner]:lineage;return owners2.find(candidate=>candidate.kind==="app")?.id}var serverEntryOwner,EntryLineageIndex;var init_lineage_utils=__esm({"libs/sdk/src/utils/lineage.utils.ts"(){"use strict";init_front_mcp_tokens2();serverEntryOwner={kind:"scope",id:"server",ref:FrontMcpConfig};EntryLineageIndex=class{lineages=new Map;rebuild(rows){this.lineages.clear();for(const row of rows){if(!this.lineages.has(row.instance))this.lineages.set(row.instance,row.lineage)}}lineageOf(entry){return this.lineages.get(entry)}}}});function toolOutputPolicies(tool,scope){const appOutput=appMetadataOf(tool,scope)?.output;return[tool.metadata.output,appOutput,scope.metadata.output]}function resolveStructuredContentValidation(tool,app,server){return tool?.validateStructuredContent??app?.validateStructuredContent??server?.validateStructuredContent??"enforce"}function toolInputPolicies(tool,scope){const appInput=appMetadataOf(tool,scope)?.input;return[tool.metadata.input,appInput,scope.metadata.input]}function appMetadataOf(tool,scope){const appId=appOwnerIdOf(scope.tools.lineageOf(tool)??[],tool.owner);return appId===void 0?void 0:scope.apps.getApps().find(candidate=>candidate.id===appId)?.metadata}function describeUnlistedOutputSchemas(scope){return scope.tools.getTools().flatMap(tool=>{const reason=tool.getUnlistedOutputSchemaReason();if(!reason||resolveOutputSchemaMode(...toolOutputPolicies(tool,scope))==="none")return[];return[`Tool "${tool.metadata.name}": tools/list leaves out its outputSchema because ${reason}. Declare a z.object() or a union of z.object() schemas to list it.`]})}var init_tool_output_policy=__esm({"libs/sdk/src/tool/tool-output-policy.ts"(){"use strict";init_common();init_lineage_utils()}});import{inferMimeType,sanitizeToJson}from"@frontmcp/utils";function toStructuredContent(value){const result=sanitizeToJson(value);if(result===void 0||result===null)return void 0;if(typeof result==="object"&&!Array.isArray(result)){return result}return{value:result}}function buildResourceContent(uri,content,mimeType){if(content&&typeof content==="object"){const obj=content;if("blob"in obj&&typeof obj["blob"]==="string"){return{uri,mimeType:obj["mimeType"]||mimeType,blob:obj["blob"]}}if("text"in obj&&typeof obj["text"]==="string"){return{uri,mimeType:obj["mimeType"]||mimeType,text:obj["text"]}}}if(Buffer.isBuffer(content)||content instanceof Uint8Array){const buffer=Buffer.isBuffer(content)?content:Buffer.from(content);return{uri,mimeType:mimeType||"application/octet-stream",blob:buffer.toString("base64")}}if(typeof content==="string"){return{uri,mimeType:mimeType||inferMimeType(uri,content),text:content}}try{return{uri,mimeType:mimeType||"application/json",text:JSON.stringify(content)}}catch{return{uri,mimeType:mimeType||"text/plain",text:String(content)}}}var init_content_utils=__esm({"libs/sdk/src/utils/content.utils.ts"(){"use strict"}});import{depsOfClass,depsOfFunc,getMetadata as getMetadata4,isClass as isClass4}from"@frontmcp/di";import{hasTransform,internalZ as z61,ZodBigInt,ZodBoolean,ZodDate,ZodNumber,ZodString}from"@frontmcp/lazy-zod";import{findDroppedKeys}from"@frontmcp/utils";function collectToolMetadata(cls){const extended=getMetadata4(extendedToolMetadata,cls);const seed=extended?{...extended}:{};return Object.entries(FrontMcpToolTokens).reduce((metadata,[key,token])=>{const value=getMetadata4(token,cls);if(value!==void 0){return Object.assign(metadata,{[key]:value})}else{return metadata}},seed)}function normalizeTool(item){if(item&&typeof item==="object"&&(item.kind==="ESM"||item.kind==="REMOTE")){return item}if(typeof item==="string"){if(isPackageSpecifier(item)){const specifier=parsePackageSpecifier(item);return{kind:"ESM",provide:item,specifier,metadata:{name:specifier.fullName,description:`ESM tools from ${specifier.fullName}`,inputSchema:{}}}}throw new InvalidEntityError("tool",item,"a class, a tool object, or a valid package specifier")}if(item&&typeof item==="function"&&item[FrontMcpToolTokens.type]==="function-tool"&&item[FrontMcpToolTokens.metadata]){return{kind:"FUNCTION",provide:item(),metadata:item[FrontMcpToolTokens.metadata]}}if(isClass4(item)){const metadata=collectToolMetadata(item);return{kind:"CLASS_TOKEN",provide:item,metadata}}const name59=item?.name??String(item);throw new InvalidEntityError("tool",name59,"a class or a tool object")}function isExternalToolRecord(record){return record.kind==="ESM"||record.kind==="REMOTE"}function toolDiscoveryDeps(rec){switch(rec.kind){case"FUNCTION":return depsOfFunc(rec.provide,"discovery");case"CLASS_TOKEN":return depsOfClass(rec.provide,"discovery");case"ESM":case"REMOTE":return[]}}function isCallToolResult(value){if(typeof value!=="object"||value===null)return false;const obj=value;if(!Array.isArray(obj["content"]))return false;const content=obj["content"];if(content.length>0){const firstItem=content[0];if(typeof firstItem!=="object"||firstItem===null)return false;if(typeof firstItem["type"]!=="string")return false;const validTypes=["text","image","audio","resource","resource_link"];if(!validTypes.includes(firstItem["type"]))return false}return true}function buildParsedToolResult(descriptor,raw,options={}){if(isReturnedCallToolResult(descriptor,raw)){return withDeclaredStructuredContent(descriptor,raw,options)}const content=[];let structuredData;if(!descriptor){const structuredContent=toStructuredContent(raw);const sanitized=structuredContent??raw;content.push(makeJsonTextContent(sanitized));return{content,structuredContent}}if(Array.isArray(descriptor)){const values=Array.isArray(raw)?raw:[raw];const parsedItems=[];descriptor.forEach((singleDescriptor,idx)=>{const value=values[idx];const{blocks,parsedValue,isPrimitive}=parseSingleValue(singleDescriptor,value,options,String(idx));parsedItems.push({blocks,parsedValue,isPrimitive});content.push(...blocks)});const hasNonPrimitive=parsedItems.some(item=>!item.isPrimitive);if(hasNonPrimitive&&parsedItems.length>1){structuredData={};parsedItems.forEach((item,idx)=>{if(item.parsedValue!==void 0){structuredData[idx]=item.parsedValue}})}else if(parsedItems.length===1&&parsedItems[0].parsedValue!==void 0){if(parsedItems[0].isPrimitive){structuredData={content:parsedItems[0].parsedValue}}else if(typeof parsedItems[0].parsedValue==="object"&&parsedItems[0].parsedValue!==null){structuredData=parsedItems[0].parsedValue}else{structuredData={content:parsedItems[0].parsedValue}}}else if(hasNonPrimitive){structuredData={};parsedItems.forEach((item,idx)=>{if(item.parsedValue!==void 0){structuredData[idx]=item.parsedValue}})}}else{const{blocks,parsedValue,isPrimitive}=parseSingleValue(descriptor,raw,options);content.push(...blocks);if(parsedValue!==void 0){if(isPrimitive){structuredData={content:parsedValue}}else if(typeof parsedValue==="object"&&parsedValue!==null){structuredData=parsedValue}else{structuredData={content:parsedValue}}}}const result={content};if(structuredData!==void 0){result.structuredContent=structuredData}return result}function isReturnedCallToolResult(descriptor,raw){if(!isCallToolResult(raw))return false;if(raw.content.length>0||raw.structuredContent!==void 0||raw.isError)return true;return!structuredOutputSchemaOf(descriptor)?.safeParse(raw).success}function asElicitationFallback(answer){elicitationFallbacks.add(answer);return answer}function withDeclaredStructuredContent(descriptor,result,options){const schema=structuredOutputSchemaOf(descriptor);if(!schema||result.isError||elicitationFallbacks.has(result))return result;const{structuredContent}=result;const parsed=declaredStructuredContent(schema,structuredContent);if("error"in parsed){if(resolveStructuredContentValidation({validateStructuredContent:options.validateStructuredContent})==="enforce"){throw parsed.error}options.onInvalidStructuredContent?.();return result}const declared=toStructuredContent(applyUndeclaredKeysPolicy(schema,structuredContent,parsed.declared,options));const sent=JSON.parse(JSON.stringify(structuredContent));if(isSameJson(declared,sent))return result;const content=result.content.map(block=>block.type==="text"&&repeatsJson(block.text,sent)?{...block,text:JSON.stringify(declared)}:block);return{...result,content,structuredContent:declared}}function repeatsJson(text,value){try{return isSameJson(JSON.parse(text),value)}catch{return false}}function isSameJson(left,right){if(left===right)return true;if(Array.isArray(left)||Array.isArray(right)){return Array.isArray(left)&&Array.isArray(right)&&left.length===right.length&&left.every((item,index)=>isSameJson(item,right[index]))}if(!isRecord3(left)||!isRecord3(right))return false;const leftKeys=Object.keys(left);return leftKeys.length===Object.keys(right).length&&leftKeys.every(key=>Object.prototype.hasOwnProperty.call(right,key)&&isSameJson(left[key],right[key]))}function declaredStructuredContent(schema,structuredContent){if(structuredContent===void 0)return{error:new InvalidOutputError({reason:"missing structuredContent"})};try{return{declared:parseDeclaredOutput(schema,structuredContent)}}catch(error){return{error:error instanceof InvalidOutputError?error:new InvalidOutputError}}}function answersObject(schema,lazies=new Set){const def=schema?._zod?.def;if(!def)return false;const type=String(def["type"]);if(type==="object"||type==="record")return true;if(type==="lazy"){return!lazies.has(def)&&answersObject(def["getter"](),new Set([...lazies,def]))}if(type==="pipe")return answersObject(def["in"],lazies);if(type==="union")return def["options"].every(option=>answersObject(option,lazies));if(type==="intersection")return answersObject(def["left"],lazies)&&answersObject(def["right"],lazies);return SHAPE_KEEPING_WRAPPERS.has(type)&&answersObject(def["innerType"],lazies)}function structuredOutputSchemaOf(descriptor){if(descriptor instanceof z61.ZodType)return answersObject(descriptor)?descriptor:void 0;return!Array.isArray(descriptor)&&isZodRawShape2(descriptor)?z61.object(descriptor):void 0}function parseSingleValue(descriptor,value,options,path4){if(typeof descriptor==="string"){switch(descriptor){case"string":if(typeof value!=="string")throw literalMismatch(descriptor,path4);return{blocks:[makePrimitiveTextContent(value)],parsedValue:value,isPrimitive:true};case"number":if(typeof value!=="number")throw literalMismatch(descriptor,path4);return{blocks:[makePrimitiveTextContent(value)],parsedValue:value,isPrimitive:false};case"boolean":if(typeof value!=="boolean")throw literalMismatch(descriptor,path4);return{blocks:[makePrimitiveTextContent(value)],parsedValue:value,isPrimitive:false};case"date":{const dateValue=toValidDate(value);if(!dateValue)throw literalMismatch(descriptor,path4);return makeDateResult(dateValue)}case"image":return{blocks:toContentBlocks(ImageOutputSchema,descriptor,value,path4),isPrimitive:false};case"audio":return{blocks:toContentBlocks(AudioOutputSchema,descriptor,value,path4),isPrimitive:false};case"resource":return{blocks:toContentBlocks(ResourceOutputSchema,descriptor,value,path4),isPrimitive:false};case"resource_link":return{blocks:toContentBlocks(ResourceLinkOutputSchema,descriptor,value,path4),isPrimitive:false};default:return{blocks:[makePrimitiveTextContent(value)],parsedValue:value,isPrimitive:true}}}if(descriptor instanceof ZodString){const stringValue=parseAgainstOutputSchema(descriptor,value);return{blocks:[makePrimitiveTextContent(stringValue)],parsedValue:stringValue,isPrimitive:true}}if(descriptor instanceof ZodNumber||descriptor instanceof ZodBoolean){return{blocks:[makePrimitiveTextContent(value)],parsedValue:parseAgainstOutputSchema(descriptor,value),isPrimitive:false}}if(descriptor instanceof ZodBigInt){return{blocks:[makePrimitiveTextContent(value)],parsedValue:String(parseAgainstOutputSchema(descriptor,value)),isPrimitive:false}}if(descriptor instanceof ZodDate){return makeDateResult(parseAgainstOutputSchema(descriptor,value))}let parsedValue;if(descriptor instanceof z61.ZodType){parsedValue=toStructuredContent(parseAgainstOutputSchema(descriptor,value,options))}else if(isZodRawShape2(descriptor)){parsedValue=toStructuredContent(parseAgainstOutputSchema(z61.object(descriptor),value,options))}else{parsedValue=toStructuredContent(value)}return{blocks:[makeJsonTextContent(parsedValue)],parsedValue,isPrimitive:false}}function parseAgainstOutputSchema(schema,value,options={}){return applyUndeclaredKeysPolicy(schema,value,parseDeclaredOutput(schema,value),options)}function applyUndeclaredKeysPolicy(schema,value,declared,options){const policy=options.undeclaredKeys??"strip";if(policy==="strip"||hasTransform(schema))return declared;const undeclaredKeys=findDroppedKeys(value,declared);if(undeclaredKeys.length===0)return declared;switch(policy){case"keep":{const kept=withUndeclaredKeys(value,declared);const unkeptKeys=findDroppedKeys(value,kept);if(unkeptKeys.length>0){throw new InvalidOutputError({reason:"undeclared keys the outputSchema cannot keep",value:unkeptKeys.join(", ")})}return kept}case"fail":throw new InvalidOutputError({reason:"undeclared keys",value:undeclaredKeys.join(", ")});case"warn":options.onUndeclaredKeys?.(undeclaredKeys);return declared}}function withUndeclaredKeys(original,declared){if(original===declared)return declared;if(Array.isArray(original)&&Array.isArray(declared)){return declared.map((item,index)=>withUndeclaredKeys(original[index],item))}if(!isRecord3(original)||!isRecord3(declared))return declared;const declaredEntries=Object.entries(declared).map(([key,item])=>[key,withUndeclaredKeys(original[key],item)]);const undeclaredEntries=Object.entries(original).filter(([key,item])=>item!==void 0&&!Object.prototype.hasOwnProperty.call(declared,key));return Object.fromEntries([...declaredEntries,...undeclaredEntries])}function isRecord3(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function parseDeclaredOutput(schema,value){const parseResult=schema.safeParse(value);if(parseResult.success){return parseResult.data}const{issues}=parseResult.error;if(issues.every(issue=>isNonFiniteNumberIssue(issue,value))){const withStandIns=issues.reduce((current,issue)=>withValueAt(current,issue.path,finiteStandIn(valueAt(value,issue.path))),value);const retry=schema.safeParse(withStandIns);if(retry.success){return issues.reduce((parsed,issue)=>withValueAt(parsed,issue.path,valueAt(value,issue.path)),retry.data)}}const firstIssue=issues[0];throw new InvalidOutputError({reason:"output does not match outputSchema",path:firstIssue?.path.length?firstIssue.path.join("."):void 0})}function isNonFiniteNumberIssue(issue,root){if(issue.code!=="invalid_type"||issue.expected!=="number"){return false}const valueAtPath=valueAt(root,issue.path);return typeof valueAtPath==="number"&&!Number.isFinite(valueAtPath)}function finiteStandIn(value){return Number.isNaN(value)?0:Math.sign(value)*Number.MAX_VALUE}function valueAt(root,path4){return path4.reduce((node,key)=>typeof node==="object"&&node!==null?node[key]:void 0,root)}function withValueAt(root,path4,replacement){if(path4.length===0){return replacement}const[key,...rest]=path4;const container=Array.isArray(root)?[...root]:{...root};container[key]=withValueAt(container[key],rest,replacement);return container}function isZodRawShape2(descriptor){return typeof descriptor==="object"&&descriptor!==null&&Object.values(descriptor).every(field=>field instanceof z61.ZodType)}function makePrimitiveTextContent(value){return{type:"text",text:value==null?"":String(value)}}function makeJsonTextContent(jsonValue){let text;try{text=JSON.stringify(jsonValue)}catch{text=jsonValue==null?"":String(jsonValue)}return{type:"text",text}}function literalMismatch(literal,path4){return new InvalidOutputError({reason:`output does not match outputSchema '${literal}'`,path:path4})}function toValidDate(value){if(value instanceof Date)return Number.isNaN(value.getTime())?void 0:value;if(typeof value!=="string"&&typeof value!=="number")return void 0;const parsed=new Date(value);return Number.isNaN(parsed.getTime())?void 0:parsed}function makeDateResult(date){const iso=date.toISOString();return{blocks:[makePrimitiveTextContent(iso)],parsedValue:{iso,timeInMilli:date.getTime()},isPrimitive:false}}function toContentBlocks(schema,literal,value,path4){const items=Array.isArray(value)?value:[value];return items.map((item,index)=>{const itemPath=Array.isArray(value)?[path4,index].filter(part=>part!==void 0).join("."):path4;if(!schema.safeParse(item).success)throw literalMismatch(literal,itemPath);return item})}function buildAgentToolDefinition(tool){const parameters=tool.getInputJsonSchema()??{type:"object",properties:{}};return{name:tool.metadata.id??tool.metadata.name,description:tool.metadata.description??"",parameters}}var elicitationFallbacks,SHAPE_KEEPING_WRAPPERS;var init_tool_utils=__esm({"libs/sdk/src/tool/tool.utils.ts"(){"use strict";init_common();init_errors();init_package_specifier();init_content_utils();init_tool_output_policy();elicitationFallbacks=new WeakSet;SHAPE_KEEPING_WRAPPERS=new Set(["readonly","optional","nullable","default","prefault","nonoptional","catch"])}});function isAppOnlyTool(metadata){const ui=metadata._meta?.["ui"];const visibility=typeof ui==="object"&&ui!==null?Reflect.get(ui,"visibility"):void 0;return Array.isArray(visibility)&&!visibility.includes("model")}function knownPlatformOf(...platforms){return platforms.find(platform=>platform!==void 0&&platform!=="unknown")}function rendersAppPages(platformType){return platformType==="ext-apps"||platformType==="openai"}var init_app_only_tools=__esm({"libs/sdk/src/tool/ui/app-only-tools.ts"(){"use strict"}});function withBundlingMode(mode,bundlingMode){if(bundlingMode==="dynamic")return"inline";if(bundlingMode==="static")return BUILT_ONCE_SERVING_MODES.includes(mode)?mode:"static";return mode}function toolServingMode(tool,scope){const own=tool.metadata.ui?.servingMode;if(own!==void 0&&own!=="auto")return own;const bundlingMode=tool.metadata.ui?.bundlingMode;if(own==="auto")return withBundlingMode(own,bundlingMode);const appId=appOwnerIdOf(scope.tools.lineageOf(tool)??[],tool.owner);const app=appId===void 0?void 0:scope.apps.getApps().find(candidate=>candidate.id===appId);const appMode=app?.metadata?.ui?.servingMode;return withBundlingMode(resolveWidgetServingMode(void 0,appMode,scope.metadata.ui?.servingMode),bundlingMode)}var BUILT_ONCE_SERVING_MODES;var init_serving_mode_default=__esm({"libs/sdk/src/tool/ui/serving-mode-default.ts"(){"use strict";init_ui_serving_mode();init_lineage_utils();BUILT_ONCE_SERVING_MODES=["static","hybrid","direct-url","custom-url"]}});function detectUIType(template){if(template===null||template===void 0)return"auto";if(typeof template==="object"&&"file"in template){return/\.(tsx|jsx)$/i.test(template.file)?"react":"auto"}if(typeof template==="function"){if(typeof template.prototype?.render==="function")return"react";if(template["$$typeof"]!==void 0)return"react";if(template.name&&/^[A-Z]/.test(template.name))return"react";return"html"}if(typeof template==="string")return template.includes("<")&&template.includes(">")?"html":"markdown";return"auto"}function isComponentReference(template){if(typeof template==="object"&&template!==null&&"$$typeof"in template)return true;if(typeof template!=="function"||detectUIType(template)!=="react")return false;if(typeof template.prototype?.render==="function")return true;if(template["$$typeof"]!==void 0)return true;return COMPILED_JSX_PATTERN.test(Function.prototype.toString.call(template))}function warnIfComponentReference(toolName,template,logger){if(!isComponentReference(template))return false;const warned2=warnedComponentReferences.get(template)??new Set;if(!warned2.has(toolName)){warned2.add(toolName);warnedComponentReferences.set(template,warned2);logger.warn(`[FrontMCP] Tool "${toolName}": \`ui.template\` is a React component reference, which cannot be bundled (there is no source file to compile), so the widget would render an empty page. Use \`template: { file: './widget.tsx' }\` instead, or set \`ui.uiType: 'react'\` to render it on the server.`)}return true}var COMPILED_JSX_PATTERN,warnedComponentReferences;var init_template_detection=__esm({"libs/sdk/src/tool/ui/template-detection.ts"(){"use strict";COMPILED_JSX_PATTERN=/\b(?:React\.createElement|_?jsx(?:s|DEV)?)\)?\s*\(/;warnedComponentReferences=new WeakMap}});var ui_render_exports={};__export(ui_render_exports,{MCP_APPS_MIME_TYPE:()=>MCP_APPS_MIME_TYPE,buildCDNInfoForUIType:()=>buildCDNInfoForUIType,buildHtmlResponseText:()=>buildHtmlResponseText,buildToolResponseContent:()=>buildToolResponseContent,describeRenderOptionProblems:()=>describeRenderOptionProblems,extractSizing:()=>extractSizing,getUIResourceMimeType:()=>getUIResourceMimeType,isUIRenderFailure:()=>isUIRenderFailure,pageCsp:()=>pageCsp,prepareRenderOptions:()=>prepareRenderOptions,renderToolTemplate:()=>renderToolTemplate,resolveServingMode:()=>resolveServingMode,warnIfComponentReference:()=>warnIfComponentReference2});import{buildCDNInfoForUIType,buildHtmlResponseText,buildToolResponseContent,describeRenderOptionProblems,isUIRenderFailure,MCP_APPS_MIME_TYPE,prepareRenderOptions,renderToolTemplate,resolveServingMode,warnIfComponentReference as warnIfComponentReference2}from"@frontmcp/uipack/adapters";import{validateCSPDomain}from"@frontmcp/uipack/shell";function extractSizing(uiConfig){if(!uiConfig)return void 0;const sizing={};let has=false;if(uiConfig["preferredHeight"]!==void 0){sizing.preferredHeight=uiConfig["preferredHeight"];has=true}if(uiConfig["minHeight"]!==void 0){sizing.minHeight=uiConfig["minHeight"];has=true}if(uiConfig["maxHeight"]!==void 0){sizing.maxHeight=uiConfig["maxHeight"];has=true}if(uiConfig["aspectRatio"]!==void 0){sizing.aspectRatio=uiConfig["aspectRatio"];has=true}if(uiConfig["autoResize"]!==void 0){sizing.autoResize=uiConfig["autoResize"];has=true}return has?sizing:void 0}function pageCsp(uiConfig){const csp=uiConfig?.["csp"];if(!csp)return void 0;const listable=domains=>Array.isArray(domains)?domains.filter(domain=>typeof domain==="string"&&validateCSPDomain(domain)):void 0;return{connectDomains:listable(csp.connectDomains),resourceDomains:listable(csp.resourceDomains)}}function getUIResourceMimeType(_platformOrUri){if(_platformOrUri?.endsWith(".js"))return"application/javascript";if(_platformOrUri?.endsWith(".css"))return"text/css";return MCP_APPS_MIME_TYPE}var init_ui_render=__esm({"libs/sdk/src/tool/ui/ui-render.ts"(){"use strict"}});function hasUIConfig(tool){if(typeof tool!=="object"||tool===null)return false;const metadata=tool["ui"];return metadata!==void 0&&metadata!==null}function renderOptions(uiConfig){const runtimeOptions=uiConfig?.["runtimeOptions"];return{contentSecurity:uiConfig?.["contentSecurity"],markdown:runtimeOptions?.markdown,mdxComponents:uiConfig?.["mdxComponents"],uiType:uiConfig?.["uiType"],hydrate:uiConfig?.["hydrate"]??runtimeOptions?.hydrate}}function isUIResourceUri(uri){return uri.startsWith("ui://")}function isStaticWidgetUri(uri){return uri.startsWith("ui://widget/")}function parseWidgetUri(uri){const match=uri.match(WIDGET_URI_PATTERN);if(!match)return null;const toolName=decodeWidgetToolName(match[1]);if(toolName===null||!WIDGET_TOOL_NAME_PATTERN.test(toolName))return null;return{toolName,extension:match[2]}}function decodeWidgetToolName(segment){try{return decodeURIComponent(segment)}catch{return null}}function buildStaticWidgetUri(toolName){return`ui://widget/${encodeURIComponent(toolName)}.html`}var WIDGET_CALL_META_KEY,ToolUIRegistry,WIDGET_URI_PATTERN,WIDGET_TOOL_NAME_PATTERN;var init_ui_shared=__esm({"libs/sdk/src/tool/ui/ui-shared.ts"(){"use strict";init_mcp_error();init_tool_ui_errors();init_template_detection();WIDGET_CALL_META_KEY="frontmcp/widgetCall";ToolUIRegistry=class{widgets=new Map;manifests=new Map;resourceMeta=new Map;uiTools=new Set;customUris=new Map;widgetUrls=new Map;resolver;options;renderer;constructor(resolver,options={}){this.resolver=resolver;this.options=options}stringResultOptions(uiConfig){const toolSetting=uiConfig?.["escapeStringResults"];return{escapeStringResults:typeof toolSetting==="boolean"?toolSetting:this.options.escapeStringResults,logger:this.options.logger}}registerTool(toolName,resourceUri){this.uiTools.add(toolName);if(resourceUri)this.customUris.set(resourceUri,toolName)}async load(){this.renderer??=await Promise.resolve().then(()=>(init_ui_render(),ui_render_exports))}get loadedRenderer(){if(!this.renderer){throw new InternalMcpError("The tool UI renderer is used before ToolUIRegistry.load()","TOOL_UI_NOT_LOADED")}return this.renderer}checkTemplate(toolName,template,uiType){if(uiType==="react")return;const warnIfComponent=this.renderer?.warnIfComponentReference??warnIfComponentReference;warnIfComponent(toolName,template,this.options.logger??console)}async checkRenderOptions(toolName,uiConfig){if(!uiConfig)return;await this.load();const{describeRenderOptionProblems:describeRenderOptionProblems2,prepareRenderOptions:prepareRenderOptions2}=this.loadedRenderer;const template=uiConfig["template"];const problems=describeRenderOptionProblems2(template,renderOptions(uiConfig));if(problems.length>0)throw new ToolUiConfigurationError(toolName,problems);try{await prepareRenderOptions2(template,renderOptions(uiConfig))}catch(error){throw new ToolUiConfigurationError(toolName,[error instanceof Error?error.message:String(error)])}}registerWidgetUrl(toolName,source){this.widgetUrls.set(toolName,source)}getWidgetUrl(toolName){return this.widgetUrls.get(toolName)}widgetRoutes(){return[...this.widgetUrls].flatMap(([toolName,source])=>source.servingMode==="direct-url"?[{toolName,path:source.path}]:[])}resolveCustomUri(uri){return this.customUris.get(uri)}holdsWidgetUri(uri){return isStaticWidgetUri(uri)||this.customUris.has(uri)}hasWidget(uri){const toolName=this.resolveCustomUri(uri)??parseWidgetUri(uri)?.toolName;return toolName!==void 0&&this.hasTool(toolName)}hasTool(name59){const known=n=>this.uiTools.has(n)||this.widgets.has(n)||this.resourceMeta.has(n);if(known(name59))return true;const sep=name59.indexOf(":");return sep>0&&known(name59.slice(sep+1))}getStaticWidget(name59){return this.widgets.get(name59)}hasAny(){return this.widgets.size>0}getManifest(toolName){return this.manifests.get(toolName)}getResourceMeta(toolName){return this.resourceMeta.get(toolName)}detectUIType(template,uiConfig){if(typeof uiConfig?.uiType==="string"&&uiConfig.uiType!=="auto")return uiConfig.uiType;if(typeof template==="string"&&uiConfig?.mdxComponents)return"mdx";return detectUIType(template)}async compileStaticWidgetAsync(options){const toolName=options["toolName"];const template=options["template"];const input=options["input"];const output=options["output"];const uiConfig=options["uiConfig"];const resourceMode=uiConfig?.["resourceMode"]??options["resourceMode"];if(!toolName)return;this.updateResourceMetaFromConfig(toolName,uiConfig);if(!template)return;await this.load();const{renderToolTemplate:renderToolTemplate2,extractSizing:extractSizing2,pageCsp:pageCsp2}=this.loadedRenderer;const result=renderToolTemplate2({toolName,input,output,template,resolver:this.resolver,resourceMode,sizing:extractSizing2(uiConfig),displayMode:uiConfig?.["displayMode"],csp:pageCsp2(uiConfig),...this.stringResultOptions(uiConfig),...renderOptions(uiConfig)});this.widgets.set(toolName,result.html);this.manifests.set(toolName,{uiType:result.uiType,hash:result.hash,size:result.size})}updateResourceMetaFromConfig(toolName,uiConfig){const resourceMeta={csp:uiConfig?.["csp"],permissions:uiConfig?.["permissions"],prefersBorder:uiConfig?.["prefersBorder"],domain:uiConfig?.["sandboxDomain"],description:uiConfig?.["widgetDescription"]};if(Object.values(resourceMeta).some(value=>value!==void 0)){this.resourceMeta.set(toolName,resourceMeta)}else{this.resourceMeta.delete(toolName)}}async compileLeanWidgetAsync(options){await this.compileStaticWidgetAsync(options)}async compileHybridWidgetAsync(options){await this.load();try{await this.compileStaticWidgetAsync(options)}catch{const toolName=options["toolName"];const template=options["template"];if(toolName&&template){const uiType=this.detectUIType(template,options["uiConfig"]);this.manifests.set(toolName,{uiType,hash:"",size:0})}}}buildHybridComponentPayload(options){const toolName=options["toolName"];if(!toolName)return void 0;const manifest=this.manifests.get(toolName);if(!manifest)return void 0;return{type:manifest["uiType"],hash:manifest["hash"],toolName}}async renderAndRegisterAsync(options){const toolName=options["toolName"];const uiConfig=options["uiConfig"];const template=uiConfig?.["template"];const input=options["input"]??{};const output=options["output"]??{};const platformType=options["platformType"];const resourceMode=uiConfig?.["resourceMode"];if(!toolName||!template){return{meta:{}}}this.updateResourceMetaFromConfig(toolName,uiConfig);await this.load();const{renderToolTemplate:renderToolTemplate2,extractSizing:extractSizing2,pageCsp:pageCsp2}=this.loadedRenderer;const result=renderToolTemplate2({toolName,input,output,template,platformType,resolver:this.resolver,resourceMode,sizing:extractSizing2(uiConfig),displayMode:uiConfig?.["displayMode"],csp:pageCsp2(uiConfig),...this.stringResultOptions(uiConfig),...renderOptions(uiConfig)});return{meta:result.meta}}};WIDGET_URI_PATTERN=/^ui:\/\/widget\/([A-Za-z0-9_.:@%/-]+)\.(html|js|css)$/;WIDGET_TOOL_NAME_PATTERN=/^[A-Za-z0-9_.:@/-]+$/}});import{hasTransform as hasTransform2}from"@frontmcp/lazy-zod";function findUndeclaredArguments(shape,sent,parsed){const dropped=new Map;const walk=(source,target,path4)=>{if(source===target)return;if(Array.isArray(source)){source.forEach((item,index)=>walk(item,Array.isArray(target)?target[index]:void 0,[...path4,"[]"]));return}if(!isPlainRecord(source))return;const targetRecord=isPlainRecord(target)?target:{};for(const[key,value]of Object.entries(source)){if(value===void 0)continue;const keyPath=[...path4,key];if(!Object.prototype.hasOwnProperty.call(targetRecord,key))dropped.set(JSON.stringify(keyPath),keyPath);else if(path4.length>0||!hasTransform2(shape[key]))walk(value,targetRecord[key],keyPath)}};walk(sent,parsed,[]);return[...dropped.values()].sort((left,right)=>formatKeyPath(left).localeCompare(formatKeyPath(right)))}function formatKeyPath(keyPath){return keyPath.reduce((text,segment)=>segment==="[]"?`${text}[]`:text?`${text}.${segment}`:segment,"")}function isPlainRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}var init_undeclared_arguments=__esm({"libs/sdk/src/tool/undeclared-arguments.ts"(){"use strict"}});import{AUTH_PROVIDERS_ACCESSOR,CREDENTIALS_ACCESSOR}from"@frontmcp/auth";import{internalZ as z62}from"@frontmcp/lazy-zod";function isAuthProvidersLike(v){return typeof v==="object"&&v!==null&&typeof v.get==="function"}function isCredentialsLike(v){return typeof v==="object"&&v!==null&&typeof v.requireConnect==="function"}async function evaluateToolCredentialGate(providers,tryGet){const required=providers.filter(p=>p.required);if(required.length===0){return{evaluated:true,missing:[]}}const authProviders=resolveAccessor(tryGet,AUTH_PROVIDERS_ACCESSOR,isAuthProvidersLike);const credentials=resolveAccessor(tryGet,CREDENTIALS_ACCESSOR,isCredentialsLike);if(!authProviders&&!credentials){return{evaluated:false,missing:[]}}const missing=[];for(const provider of required){const missingProvider=await missingProviderOf(provider.name,authProviders,credentials);if(missingProvider)missing.push(missingProvider)}return{evaluated:true,missing}}function resolveAccessor(tryGet,token,guard){const value=tryGet(token);return guard(value)?value:void 0}async function missingProviderOf(name59,authProviders,credentials){if(authProviders){try{const resolved=await authProviders.get(name59);if(resolved){return void 0}}catch{}}if(credentials){try{const res=await credentials.requireConnect({key:name59});if(res.connected){return void 0}return{name:name59,...res.resumeUrl?{authUrl:res.resumeUrl}:{},...res.signInRequired?{signInRequired:true}:{}}}catch{return{name:name59}}}return{name:name59}}function credentialsRequiredErrorOf(toolId,missing){return new ToolCredentialsRequiredError({toolId,providers:missing.map(provider=>provider.name),authUrl:missing.find(provider=>provider.authUrl)?.authUrl,signInRequired:missing.some(provider=>provider.signInRequired)})}async function askToOpenConnectPages(ask,missing){const everyProviderHasPage=missing.every(provider=>provider.authUrl);if(!ask.elicitationEnabled||!everyProviderHasPage||!clientTakesUrlElicitation(ask))return false;for(const provider of missing){try{const answer=await performElicit({sessionId:ask.context?.sessionId,getClientCapabilities:ask.getClientCapabilities,tryGetContext:()=>ask.context,entryName:ask.toolId,entryInput:ask.toolInput,elicitationEnabled:ask.elicitationEnabled,signal:ask.signal,inputKey:`connect-${provider.name}`},`Connect ${provider.name} to continue: tool "${ask.toolId}" needs it.`,z62.object({}),{mode:"url",url:provider.authUrl});if(answer.status!=="accept")return false}catch(error){if(error instanceof InputRequiredSignal)throw error;return false}}return true}function clientTakesUrlElicitation(ask){const exchange=ask.context?.getMrtrExchange?.();if(exchange)return exchange.supportsElicitation?.("url")===true;const sessionId=ask.context?.sessionId;return sessionId!==void 0&&supportsElicitation(ask.getClientCapabilities(sessionId),"url")}var init_tool_credentials_gate=__esm({"libs/sdk/src/tool/flows/tool-credentials.gate.ts"(){"use strict";init_elicit_helper();init_errors();init_notification()}});var undeclared_arguments_message_exports={};__export(undeclared_arguments_message_exports,{describeUndeclaredArguments:()=>describeUndeclaredArguments,undeclaredArgumentsNote:()=>undeclaredArgumentsNote,undeclaredArgumentsRefusal:()=>undeclaredArgumentsRefusal,undeclaredArgumentsWarning:()=>undeclaredArgumentsWarning});function undeclaredArgumentsRefusal(keyPaths,declaredKeys){return`Unknown arguments: ${describeUndeclaredArguments(keyPaths,declaredKeys)}`}function undeclaredArgumentsNote(keyPaths,declaredKeys){return`These arguments are not declared and were ignored: ${describeUndeclaredArguments(keyPaths,declaredKeys)}.`}function undeclaredArgumentsWarning(toolName,newKeyPaths){return`Tool "${toolName}" was called with arguments its inputSchema does not declare, so they were ignored: ${namedWithTheRestCounted(newKeyPaths.map(shortened))}. Declare them, or set input.undeclaredKeys to 'strip' or 'fail'.`}function describeUndeclaredArguments(keyPaths,declaredKeys){const described=keyPaths.slice(0,MAX_NAMED_ARGUMENTS).map(keyPath=>{const shown=shortened(formatKeyPath(keyPath));const closest=keyPath.length===1?closestKey(keyPath[0],declaredKeys):void 0;return closest?`'${shown}' (did you mean '${closest}'?)`:`'${shown}'`});return namedWithTheRestCounted(described,keyPaths.length)}function namedWithTheRestCounted(names,total=names.length){const named=names.slice(0,MAX_NAMED_ARGUMENTS);const unnamed=total-named.length;return unnamed>0?`${named.join(", ")} and ${unnamed} more`:named.join(", ")}function shortened(text){return text.length>MAX_KEY_LENGTH?`${text.slice(0,MAX_KEY_LENGTH)}\u2026`:text}function closestKey(key,declaredKeys){if(key.length>MAX_KEY_LENGTH)return void 0;const candidates=declaredKeys.slice(0,MAX_COMPARED_KEYS).filter(candidate=>candidate.length<=MAX_KEY_LENGTH);let closest;for(const candidate of candidates){const distance=editDistance(key.toLowerCase(),candidate.toLowerCase());if(!closest||distance<closest.distance)closest={candidate,distance}}if(!closest)return void 0;return closest.distance*2<=Math.max(key.length,closest.candidate.length)?closest.candidate:void 0}function editDistance(source,target){const row=Array.from({length:target.length+1},(_,index)=>index);for(let sourceIndex=1;sourceIndex<=source.length;sourceIndex++){let diagonal=row[0];row[0]=sourceIndex;for(let targetIndex=1;targetIndex<=target.length;targetIndex++){const above=row[targetIndex];const substitution=diagonal+(source[sourceIndex-1]===target[targetIndex-1]?0:1);row[targetIndex]=Math.min(above+1,row[targetIndex-1]+1,substitution);diagonal=above}}return row[target.length]}var MAX_NAMED_ARGUMENTS,MAX_KEY_LENGTH,MAX_COMPARED_KEYS;var init_undeclared_arguments_message=__esm({"libs/sdk/src/tool/undeclared-arguments-message.ts"(){"use strict";init_undeclared_arguments();MAX_NAMED_ARGUMENTS=20;MAX_KEY_LENGTH=64;MAX_COMPARED_KEYS=200}});import{AuthorityDeniedError as AuthorityDeniedError3,resolveRequiredScopes as resolveRequiredScopes2,signIncrementalAuthTicket}from"@frontmcp/auth";import{ExecutionTimeoutError,withTimeout}from"@frontmcp/guard";import{internalZ as z63}from"@frontmcp/lazy-zod";import{CallToolRequestSchema as CallToolRequestSchema2,CallToolResultSchema as CallToolResultSchema2}from"@frontmcp/protocol";import{awaitOutsideRequest as awaitOutsideRequest4,escapeControlCharacters as escapeControlCharacters2,findNonFiniteNumber,getRuntimeContext as getRuntimeContext4,isDebug,isDevelopment as isDevelopment2,randomUUID as randomUUID11}from"@frontmcp/utils";function htmlResponsePrefixFor(ui,platformType){const prefix=ui?.htmlResponsePrefix;return typeof prefix==="string"&&platformType==="claude"?prefix:void 0}function isWidgetCall(requestMeta){return typeof requestMeta==="object"&&requestMeta!==null&&Reflect.get(requestMeta,WIDGET_CALL_META_KEY)===true}function unreportedKeyPaths(reported,tool,keyPaths){const reportedKeyPaths=reported.get(tool)??new Set;reported.set(tool,reportedKeyPaths);const roomLeft=MAX_REPORTED_UNDECLARED_KEY_PATHS-reportedKeyPaths.size;const newKeyPaths=keyPaths.filter(keyPath=>!reportedKeyPaths.has(keyPath)).slice(0,roomLeft);newKeyPaths.forEach(keyPath=>reportedKeyPaths.add(keyPath));return newKeyPaths}function declaredOutput(tool,output,undeclaredKeys){if(!tool?.outputSchema||typeof output!=="object"||output===null||Array.isArray(output))return output;const parsed=tool.safeParseOutput(output,{undeclaredKeys});if(!parsed.success)return output;if(isReturnedCallToolResult(tool.outputSchema,output))return parsed.data;const structured=parsed.data.structuredContent;return typeof structured==="object"&&structured!==null&&!Array.isArray(structured)?structured:output}var inputSchema,outputSchema,stateSchema,plan,name,toolClassHooksJoin,Stage,resolvedTools,reportedUndeclaredKeyPaths,reportedInvalidStructuredContent,reportedUndeclaredArguments,reportedUnfittedTools,loggedAliasCalls,MAX_REPORTED_UNDECLARED_KEY_PATHS,CallToolFlow;var init_call_tool_flow=__esm({"libs/sdk/src/tool/flows/call-tool.flow.ts"(){"use strict";init_answer();init_lazy_placeholders();init_remote_capabilities_utils();init_authorized_apps_utils();init_consent_utils();init_public_access_utils();init_authorities_not_configured();init_common();init_availability();init_input_policy();init_tool_metadata();init_tool_lookup_utils();init_call_surface();init_running_tool();init_helpers();init_fallback_helper();init_errors();init_resolved_entries();init_entry_class_hooks();init_hooks_utils();init_flow_context_providers();init_skill_mode_utils();init_surface();init_task_id();init_task_notifier();init_task_types();init_abort_utils();init_lineage_utils();init_tool_output_policy();init_tool_utils();init_app_only_tools();init_serving_mode_default();init_ui_shared();init_undeclared_arguments();init_tool_credentials_gate();inputSchema=z63.object({request:CallToolRequestSchema2,ctx:z63.any()});outputSchema=CallToolResultSchema2;stateSchema=z63.object({input:z63.looseObject({name:z63.string().min(1).max(64),arguments:z63.looseObject({}).optional()}),authInfo:z63.any().optional(),tool:z63.instanceof(ToolEntry),toolContext:z63.instanceof(ToolContext),rawOutput:z63.any().optional(),output:outputSchema,flowError:z63.instanceof(Error).optional(),uiResult:z63.any().optional(),uiMeta:z63.record(z63.string(),z63.unknown()).optional(),undeclaredArgumentsNote:z63.string().optional(),resultMeta:z63.record(z63.string(),z63.unknown()).optional(),progressToken:z63.union([z63.string(),z63.number()]).optional(),jsonRpcRequestId:z63.union([z63.string(),z63.number()]).optional(),semaphoreTicket:z63.any().optional(),executionAbort:z63.instanceof(AbortController).optional(),abandonedExecution:z63.instanceof(Promise).optional(),taskRequest:z63.object({ttl:z63.number().int().positive().nullish()}).passthrough().optional()});plan={pre:["parseInput","checkSkillsOnlyMode","ensureRemoteCapabilities","checkSurface","findTool","useToolHooks","checkEnabled","checkAppLoaded","checkPublicAccess","checkToolAuthorization","checkEntryAuthorities","createTaskIfRequested","createToolCallContext","checkToolCredentials","acquireQuota","acquireSemaphore"],execute:["validateInput","execute","validateOutput"],finalize:["releaseSemaphore","releaseQuota","applyUI","finalize","fitAnswer","shapeAnswer","meterAnswer"]};name="tools:call-tool";toolClassHooksJoin=entryClassHooksJoin({flow:name,plan,contextStage:"createToolCallContext"});({Stage}=FlowHooksOf(name));resolvedTools=new ResolvedEntries;reportedUndeclaredKeyPaths=new WeakMap;reportedInvalidStructuredContent=new WeakSet;reportedUndeclaredArguments=new WeakMap;reportedUnfittedTools=new WeakSet;loggedAliasCalls=new WeakMap;MAX_REPORTED_UNDECLARED_KEY_PATHS=100;CallToolFlow=class extends FlowBase{static async resolveHookOwnerId(rawInput,scope){const toolName=rawInput?.request?.params?.name;if(typeof toolName!=="string")return void 0;let tool=lookupTool(scope,toolName);if(!tool){await loadRemoteAppCapabilities(scope);tool=lookupTool(scope,toolName)}if(tool&&await loadAppOfPlaceholder(scope,tool))tool=lookupTool(scope,toolName);if(!tool)return void 0;resolvedTools.remember(rawInput,toolName,tool);return hookOwnerIdOf(scope.tools.lineageOf(tool)??[],tool.owner)}static resolveHookEntryClass(rawInput,scope){const toolName=rawInput?.request?.params?.name;if(typeof toolName!=="string")return void 0;return(resolvedTools.peek(rawInput,toolName)??lookupTool(scope,toolName))?.record.provide}logger=this.scopeLogger.child("CallToolFlow");declaredUiOutput;get toolName(){return this.state.tool?.name??(this.state.input??this.input.request.params).name}get toolInput(){return(this.state.input??this.input.request.params).arguments}async parseInput(){this.logger.verbose("parseInput:start");let method;let params;let ctx;try{const inputData=inputSchema.parse(this.rawInput);method=inputData.request.method;params=inputData.request.params;ctx=inputData.ctx}catch(e){throw new InvalidInputError("Invalid Input",e instanceof z63.ZodError?e.issues:void 0)}if(method!=="tools/call"){this.logger.warn(`parseInput: invalid method "${method}"`);throw new InvalidMethodError(method,"tools/call")}const progressToken=params._meta?.progressToken;const jsonRpcRequestId=ctx.requestId;const taskRequest=params.task&&typeof params.task==="object"?params.task:void 0;this.state.set({input:params,authInfo:ctx.authInfo,progressToken,jsonRpcRequestId,taskRequest});this.logger.verbose("parseInput:done")}async checkSkillsOnlyMode(){if(!this.isClientCall())return;if(!isSkillsOnlyRequest(this.state.authInfo,this.tryGetContext()))return;const{name:name59}=this.state.required.input;this.logger.verbose(`checkSkillsOnlyMode: refusing tool "${escapeControlCharacters2(name59)}" in skills-only mode`);throw new ToolNotFoundError(name59)}async ensureRemoteCapabilities(){this.logger.verbose("ensureRemoteCapabilities:start");const remoteAppCount=await loadRemoteAppCapabilities(this.scope,(appId,error)=>this.logger.warn(`Failed to load capabilities for remote app ${appId}: ${error.message}`));this.logger.verbose(`ensureRemoteCapabilities:done (${remoteAppCount} remote app(s))`)}async checkSurface(){const sessionId=this.state.authInfo?.sessionId;const surface=this.scope.surface;const callerCtx=this.input.ctx;if(!surface||!sessionId||callerCtx?.taskId||!this.isClientCall()||!surface.isStale(sessionId))return;const{name:name59}=this.state.required.input;const tool=resolvedTools.peek(this.rawInput,name59)??lookupTool(this.scope,name59);const callable=tool!==void 0&&resolveToolVisibility(tool.metadata)!=="internal"&&isOfferedOnSurface(tool.metadata.availableWhen,callSurfaceOf(this.input.ctx));if(callable&&await isEntryEnabled(tool.metadata.enabled,this.tryGetContext(),this.logger))return;this.logger.verbose(`checkSurface: "${escapeControlCharacters2(name59)}" is not in the tool list that replaced this session's`);surface.refreshSession(sessionId);throw new StaleToolListError(name59)}async findTool(){this.logger.verbose("findTool:start");const{name:name59}=this.state.required.input;const tool=resolvedTools.take(this.rawInput,name59)??lookupTool(this.scope,name59);const exactNames=[name59,ownerQualifiedName(name59)];if(tool&&toolAliasesOf(tool).includes(name59)){this.logAliasCall(tool,name59)}else if(tool&&!exactNames.includes(tool.fullName)&&!exactNames.includes(tool.name)){const[,alias]=toolNameCandidates(name59);this.logger.warn(`findTool: tool "${name59}" resolved via legacy name alias to "${alias}". Update callers to use "${alias}" \u2014 the alias will be removed in a future release.`)}const callSurface=callSurfaceOf(this.input.ctx);if(!tool){const allUnfiltered=this.scope.tools.listAllInstances();const unavailable=allUnfiltered.find(t=>exactNames.includes(t.fullName)||exactNames.includes(t.name)||toolAliasesOf(t).includes(name59));if(unavailable&&isOfferedOnSurface(unavailable.metadata.availableWhen,callSurface)){const error=entryUnavailableError("Tool",name59,unavailable.metadata.availableWhen,callSurface);const ctx=getRuntimeContext4();this.logger.warn(`findTool: tool "${name59}" exists but is unavailable \u2014 constraint=${JSON.stringify(unavailable.metadata.availableWhen)}, missingAxes=${JSON.stringify(error.missingAxes)}, current=[os=${ctx.os}, runtime=${ctx.runtime}, deployment=${ctx.deployment}, provider=${ctx.provider}, target=${ctx.target}, surface=${callSurface??"none"}, env=${ctx.env}]`);throw error}this.logger.warn(`findTool: tool "${escapeControlCharacters2(name59)}" not found`);throw new ToolNotFoundError(name59)}if(!isOfferedOnSurface(tool.metadata.availableWhen,callSurface)){this.logger.warn(`findTool: tool "${name59}" is not offered on surface "${callSurface}"`);throw new ToolNotFoundError(name59)}const ctxObj=this.input.ctx;const visibility=resolveToolVisibility(tool.metadata);if(visibility==="internal"&&!ctxObj?.internalCall){this.logger.warn(`findTool: rejecting external tools/call for internal tool "${name59}"`);throw new ToolNotFoundError(name59)}const isTaskRun=Boolean(ctxObj?.taskId);if(isAppOnlyTool(tool.metadata)&&this.isClientCall()&&!isTaskRun&&!rendersAppPages(this.appPagePlatform())){this.logger.warn(`findTool: rejecting tools/call of "${name59}", a tool for the MCP Apps page only`);throw new ToolNotFoundError(name59)}this.logger=this.logger.child(`CallToolFlow(${name59})`);this.state.set("tool",tool);this.logger.verbose(`findTool: tool "${name59}" found`);this.logger.verbose("findTool:done")}async useToolHooks(){const{tool}=this.state;if(!tool)return;await this.useEntryHooks(hookOwnerIdOf(this.scope.tools.lineageOf(tool)??[],tool.owner),tool.record.provide)}async checkEnabled(){const{tool}=this.state.required;await assertEntryEnabled("Tool",tool.name,tool.metadata.enabled,this.tryGetContext(),this.logger)}async checkAppLoaded(){assertAppLoaded(this.state.required.tool)}logAliasCall(tool,alias){const loggedAliases=loggedAliasCalls.get(tool)??new Set;if(loggedAliases.has(alias))return;loggedAliases.add(alias);loggedAliasCalls.set(tool,loggedAliases);this.logger.info(`findTool: tool "${alias}" is an alias of "${tool.name}"; call "${tool.name}" instead.`)}async createTaskIfRequested(){this.logger.verbose("createTaskIfRequested:start");const{tool}=this.state.required;const taskRequest=this.state.taskRequest;const taskSupport=tool.metadata.execution?.taskSupport;const toolName=tool.fullName||tool.metadata.name;const ctx=this.input.ctx;if(ctx?.taskId){this.logger.verbose("createTaskIfRequested:skip (internal task re-dispatch)");return}if(taskRequest&&(!taskSupport||taskSupport==="forbidden")){throw new TaskAugmentationNotSupportedError(toolName)}if(!taskRequest&&taskSupport==="required"){throw new TaskAugmentationRequiredError(toolName)}if(!taskRequest){this.logger.verbose("createTaskIfRequested:skip (non-task call)");return}const store=this.scope.taskStore;const registry=this.scope.tasks;if(!store||!registry){throw new TaskStoreNotInitializedError}const authInfo=this.state.authInfo;const sessionId=authInfo?.sessionId;if(!sessionId){throw new InternalMcpError("Task-augmented tools/call requires an identified session","TASK_SESSION_REQUIRED")}const config=registry.getConfig();const rawTtlValue=taskRequest["ttl"];const rawTtl=rawTtlValue===null?null:typeof rawTtlValue==="number"?rawTtlValue:void 0;const maxTtl=config.maxTtlMs??TASK_DEFAULTS.maxTtlMs;const defaultTtl=config.defaultTtlMs??TASK_DEFAULTS.defaultTtlMs;const ttlMs=rawTtl===null?maxTtl:rawTtl===void 0?defaultTtl:Math.min(rawTtl,maxTtl);const pollIntervalMs=config.defaultPollIntervalMs??TASK_DEFAULTS.defaultPollIntervalMs;const now=Date.now();const nowIso=new Date(now).toISOString();const taskId=generateTaskId();const expiresAt=now+ttlMs;const cleanedParams={...this.state.required.input};delete cleanedParams["task"];const record={taskId,sessionId,status:"working",statusMessage:"The operation is now in progress.",createdAt:nowIso,lastUpdatedAt:nowIso,ttlMs,pollIntervalMs,expiresAt,request:{method:"tools/call",params:cleanedParams},scopeId:this.scope.id};const callSurface=callSurfaceOf(this.input.ctx);if(callSurface!==void 0)record.surface=callSurface;if(this.state.progressToken!==void 0){record.progressToken=this.state.progressToken}const maxActive=config.maxConcurrentPerSession??TASK_DEFAULTS.maxConcurrentPerSession;if(!await store.createWithinLimit(record,maxActive)){throw new TaskConcurrencyLimitError(maxActive)}const notifier=new TaskNotifier(this.scope.notifications,this.logger);notifier.sendStatus(record);const runner=registry.runner;if(!runner){throw new InternalMcpError("Task runner is not configured \u2014 scope initialization did not set one","TASK_RUNNER_MISSING")}try{await runner.run(record,{cleanedRequestParams:cleanedParams,ctx:this.input.ctx})}catch(err){this.logger.error("createTaskIfRequested: runner.run threw",{taskId,error:err instanceof Error?err.message:String(err)});try{await store.update(taskId,sessionId,{status:"failed",statusMessage:"Task runner failed to schedule execution"})}catch(bookkeepingErr){this.logger.warn("createTaskIfRequested: failed to mark task failed after runner error",{taskId,sessionId,error:bookkeepingErr instanceof Error?bookkeepingErr.message:String(bookkeepingErr)})}throw err}const createTaskResult={task:toWireShape(record),_meta:{"io.modelcontextprotocol/related-task":{taskId}}};this.logger.info("createTaskIfRequested: task created, responding with CreateTaskResult",{taskId,tool:toolName});this.respond(createTaskResult)}async checkPublicAccess(){const{tool,authInfo}=this.state;const callerCtx=this.input.ctx;const publicAccess=publicAccessFor(this.scope.auth?.options,authInfo);if(!tool||!publicAccess||callerCtx?.internalCall||callerCtx?.agentPrivateCall)return;if(callerCtx?.taskId)return;await enforcePublicAccess(publicAccess,{kind:"tool",names:[tool.fullName||tool.name,tool.name]},this.scope.publicAccessGuard,buildPartitionContext(this.tryGetContext()))}async checkToolAuthorization(){this.logger.verbose("checkToolAuthorization:start");const{tool,authInfo}=this.state;const consentCtx=this.input.ctx;if(!consentCtx?.internalCall&&!consentCtx?.agentPrivateCall){const consentedToolIds=getConsentedToolIds(authInfo);if(consentedToolIds&&tool){const bareNameCount=this.scope.tools.getTools(true).filter(t=>t.name===tool.name).length;const consented=bareNameCount>1?isToolConsented(consentedToolIds,tool.fullName):isToolConsented(consentedToolIds,tool.name,tool.fullName);if(!consented){this.logger.info(`checkToolAuthorization: tool "${tool.fullName||tool.name}" not in consented set \u2014 rejecting`);throw new ToolNotConsentedError(tool.fullName||tool.name)}}}const claimAuthorizedApps=getAuthorizedAppIds(authInfo);const legacyAuthorization=authInfo?.extra?.["authorization"];if(!claimAuthorizedApps&&!legacyAuthorization){const incrementalEnabled=!consentCtx?.internalCall&&!!authInfo?.token&&this.scope.auth?.options?.incrementalAuth?.enabled===true;if(!incrementalEnabled){this.logger.verbose("checkToolAuthorization:skip (no auth context)");return}this.logger.warn("checkToolAuthorization: incrementalAuth enabled but the verified token carries no authorized_apps claim \u2014 failing closed")}const appId=!tool||isServerEntryOwner(tool.owner)?void 0:this.grantingAppIdOf(tool);if(!appId){this.logger.verbose("checkToolAuthorization:skip (no app owner)");return}const isAppAuthorized=(claimAuthorizedApps?.has(appId)??false)||(legacyAuthorization?.authorizedAppIds?.includes(appId)??false)||appId in(legacyAuthorization?.authorizedApps||{});if(!isAppAuthorized){const apps=this.scope.apps.getApps();const app=apps.find(a=>a.metadata.id===appId);const authOptions=this.scope.auth?.options;let skippedBehavior="anonymous";if(authOptions&&isOrchestratedMode(authOptions)){const incrementalConfig=authOptions.incrementalAuth;if(incrementalConfig){if(incrementalConfig.enabled===false){skippedBehavior="require-auth"}else{skippedBehavior=incrementalConfig.skippedAppBehavior||"anonymous"}}}if(skippedBehavior==="anonymous"&&app?.metadata?.auth?.mode==="public"){this.logger.verbose(`checkToolAuthorization: using anonymous for ${appId}`);return}const authUrl=this.buildProgressiveAuthUrl(appId,tool?.fullName||"",authInfo,claimAuthorizedApps);const requiredScopes=normalizeToolAuthProviders(tool?.metadata?.authProviders).flatMap(provider=>provider.scopes??[]);this.logger.info(`checkToolAuthorization: authorization required for app "${appId}"`);throw new AuthorizationRequiredError({appId,toolId:tool?.fullName||tool?.name||"unknown",authUrl,requiredScopes:requiredScopes.length>0?[...new Set(requiredScopes)]:void 0,message:`Authorization required for ${appId}. Please authorize to use ${tool?.fullName||tool?.name}.`})}this.logger.verbose("checkToolAuthorization:done")}grantingAppIdOf(tool){const{owner}=tool;if(owner?.kind!=="plugin"&&owner?.kind!=="adapter")return owner?.id;return appOwnerIdOf(this.scope.tools.lineageOf(tool)??[],owner)}buildProgressiveAuthUrl(appId,toolId,authInfo,priorAppIds){const baseUrl=this.scope.fullPath||"";const url=new URL(`${baseUrl}/oauth/authorize`,"http://placeholder.invalid");url.searchParams.set("app",appId);url.searchParams.set("tool",toolId);const ticket=this.mintIncrementalTicket(appId,toolId,authInfo,priorAppIds);if(ticket){url.searchParams.set("ticket",ticket)}else{this.logger.verbose("buildProgressiveAuthUrl: no incremental ticket minted \u2014 link requires a full login")}return baseUrl.startsWith("http")?url.toString():`${url.pathname}${url.search}`}mintIncrementalTicket(appId,toolId,authInfo,priorAppIds){const extraUser=authInfo?.extra?.user;const user=extraUser?.sub?extraUser:authInfo?.user;if(!user?.sub)return void 0;const sub=user.sub;const secret=this.scope.auth?.signingSecret;if(!secret)return void 0;return signIncrementalAuthTicket({sub,appId,toolId,audience:incrementalTicketAudience(this.scope),...priorAppIds&&priorAppIds.size>0?{priorAppIds:[...priorAppIds]}:{},...typeof user.email==="string"?{email:user.email}:{},...typeof user.name==="string"?{name:user.name}:{}},secret)}async checkEntryAuthorities(){this.logger.verbose("checkEntryAuthorities:start");const tool=this.state.tool;if(!tool)return;const metadata=tool.metadata;const authorities=metadata["authorities"];if(!authorities){this.logger.verbose("checkEntryAuthorities:skip (no authorities on tool)");return}const engine=this.scope.authoritiesEngine;const ctxBuilder=this.scope.authoritiesContextBuilder;if(!engine||!ctxBuilder){throw new AuthorityDeniedError3({entryType:"Tool",entryName:tool.fullName||tool.name,deniedBy:AUTHORITIES_NOT_CONFIGURED})}const authInfo=this.state.authInfo??{};const stateInput=this.state.input;const input=stateInput?.["arguments"]??stateInput??{};const evalCtx=ctxBuilder.build(authInfo,input);const result=await engine.evaluate(authorities,evalCtx);if(!result.granted){let requiredScopes;const scopeMapping=this.scope.authoritiesScopeMapping;if(scopeMapping&&result.denial){requiredScopes=resolveRequiredScopes2(result.denial,scopeMapping,authorities)}throw new AuthorityDeniedError3({entryType:"Tool",entryName:tool.fullName||tool.name,deniedBy:result.deniedBy??"policy denied",denial:result.denial,requiredScopes})}this.logger.verbose("checkEntryAuthorities:done")}async createToolCallContext(){this.logger.verbose("createToolCallContext:start");const{ctx}=this.input;const{tool,input}=this.state.required;const authInfo=this.state.authInfo;const progressToken=this.state.progressToken;try{const sessionKey=authInfo?.sessionId??"anonymous";const toolViews=await tool.providers.buildViews(sessionKey,new Map(this.deps),this.scope.providers);const contextProviders=new FlowContextProviders(tool.providers,toolViews.context);const executionAbort=linkedAbortController(ctx.signal);this.state.set("executionAbort",executionAbort);const context=runAsTool({name:tool.name,fullName:tool.fullName},()=>tool.create(input.arguments,{...ctx,progressToken,contextProviders,signal:executionAbort.signal}));await context.loadAuthContext();this.appendContextHooks(hooksBoundTo(this.scope.hooks.getClsHooks(tool.record.provide),context));context.mark("createToolCallContext");context._toolNameInternal=tool.metadata.id??tool.metadata.name;context._toolInputInternal=input.arguments;context.idempotencyKey=ctx.idempotencyKey;context._jsonRpcRequestIdInternal=this.state.jsonRpcRequestId;context._onRespondInternal=value=>this.state.set("rawOutput",value);context._onRecordsChangedInternal=ctx.onRecordsChanged;const frontmcpContext=context.tryGetContext();const authInfoWithTransport=authInfo;const jsonRpcRequestId=this.state.jsonRpcRequestId;if(frontmcpContext&&authInfoWithTransport?.transport?.sendElicitRequest&&jsonRpcRequestId!==void 0){const transport=authInfoWithTransport.transport;frontmcpContext.setTransport({sendElicitRequest:transport.sendElicitRequest.bind(transport),type:transport.type,jsonRpcRequestId})}this.state.set("toolContext",context);this.logger.verbose("createToolCallContext:done")}catch(error){if(error instanceof FlowControl||isClientFacingError(error))throw error;this.logger.error("createToolCallContext: failed to create context",error);throw new ToolExecutionError(tool.metadata.name,error instanceof Error?error:void 0)}}async checkToolCredentials(){this.logger.verbose("checkToolCredentials:start");const{tool}=this.state.required;const ctxObj=this.input.ctx;if(ctxObj?.internalCall){this.logger.verbose("checkToolCredentials:skip (internal call)");return}const providers=normalizeToolAuthProviders(tool.metadata["authProviders"]);if(providers.length===0){this.logger.verbose("checkToolCredentials:skip (no authProviders)");return}const toolContext=this.state.toolContext;if(!toolContext){this.logger.verbose("checkToolCredentials:skip (no tool context)");return}toolContext.mark("checkToolCredentials");const result=await evaluateToolCredentialGate(providers,token=>toolContext.tryGet(token));if(!result.evaluated){this.logger.verbose("checkToolCredentials:skip (no credential accessor configured)");return}if(result.missing.length===0){this.logger.verbose("checkToolCredentials:done (all required credentials present)");return}const toolId=tool.fullName||tool.metadata.name;const missingNames=result.missing.map(m=>m.name);this.logger.info(`checkToolCredentials: tool "${toolId}" missing required credential(s): ${missingNames.join(", ")}`);const connectPageAsk={context:this.tryGetContext(),getClientCapabilities:sessionId=>this.scope.notifications.getClientCapabilities(sessionId),elicitationEnabled:this.scope.metadata.elicitation?.enabled===true,toolId,toolInput:this.state.input?.arguments,signal:this.state.executionAbort?.signal};let missing=result.missing;if(await askToOpenConnectPages(connectPageAsk,missing)){missing=(await evaluateToolCredentialGate(providers,token=>toolContext.tryGet(token))).missing;if(missing.length===0){this.logger.verbose("checkToolCredentials:done (connected through the connect page)");return}}throw credentialsRequiredErrorOf(toolId,missing)}async acquireQuota(){this.logger.verbose("acquireQuota:start");const manager=this.scope.rateLimitManager;if(!manager){this.state.toolContext?.mark("acquireQuota");this.logger.verbose("acquireQuota:done (no rate limit manager)");return}const{tool}=this.state.required;const context=this.tryGetContext();const partitionCtx=buildPartitionContext(context);if(!context?.has(GLOBAL_RATE_LIMIT_CHECKED)){const globalResult=await manager.checkGlobalRateLimit(partitionCtx);if(!globalResult.allowed){this.logger.warn("acquireQuota: global rate limit exceeded",{retryAfterMs:globalResult.retryAfterMs});throw new RateLimitError(Math.ceil((globalResult.retryAfterMs??6e4)/1e3))}}const result=await manager.checkRateLimit(tool.metadata.name,tool.metadata.rateLimit,partitionCtx);if(!result.allowed){this.logger.warn("acquireQuota: tool rate limit exceeded",{tool:tool.metadata.name,retryAfterMs:result.retryAfterMs});throw new RateLimitError(Math.ceil((result.retryAfterMs??6e4)/1e3))}this.state.toolContext?.mark("acquireQuota");this.logger.verbose("acquireQuota:done")}async acquireSemaphore(){this.logger.verbose("acquireSemaphore:start");const manager=this.scope.rateLimitManager;if(!manager){this.state.toolContext?.mark("acquireSemaphore");this.logger.verbose("acquireSemaphore:done (no rate limit manager)");return}const{tool}=this.state.required;const partitionCtx=buildPartitionContext(this.tryGetContext());const isNestedCall=this.input.ctx?.internalCall===true||callSurfaceOf(this.input.ctx)==="agent";const ticket=await acquireConcurrencySlots(manager,tool.metadata.name,tool.metadata.concurrency,partitionCtx,{skipGlobal:isNestedCall});this.state.set("semaphoreTicket",ticket);this.state.toolContext?.mark("acquireSemaphore");this.logger.verbose("acquireSemaphore:done")}async validateInput(){this.logger.verbose("validateInput:start");const{tool,input}=this.state.required;const{toolContext}=this.state;if(!toolContext){return}toolContext.mark("validateInput");try{toolContext.input=tool.parseInput(input)}catch(err){if(err instanceof z63.ZodError){throw new InvalidInputError("Invalid tool input",err.issues)}this.logger.error("validateInput: failed to parse input",err);throw new InvalidInputError("Unknown error occurred when trying to parse input")}await this.applyInputPolicy(tool,input.arguments,toolContext.input);this.logger.verbose("validateInput:done")}async applyInputPolicy(tool,sent,parsed){const policy=resolveInputUndeclaredKeysPolicy(...toolInputPolicies(tool,this.scope));if(policy==="strip")return;const keyPaths=findUndeclaredArguments(tool.inputSchema??{},sent,parsed);if(keyPaths.length===0)return;const messages=await Promise.resolve().then(()=>(init_undeclared_arguments_message(),undeclared_arguments_message_exports));const declaredKeys=Object.keys(tool.inputSchema??{});if(policy==="fail")throw new InvalidInputError(messages.undeclaredArgumentsRefusal(keyPaths,declaredKeys));this.state.set("undeclaredArgumentsNote",messages.undeclaredArgumentsNote(keyPaths,declaredKeys));const newKeyPaths=unreportedKeyPaths(reportedUndeclaredArguments,tool,keyPaths.map(formatKeyPath));if(newKeyPaths.length>0)this.logger.warn(messages.undeclaredArgumentsWarning(tool.metadata.name,newKeyPaths))}async execute(){this.logger.verbose("execute:start");const toolContext=this.state.toolContext;if(!toolContext){return}toolContext.mark("execute");const{tool}=this.state.required;const timeoutMs=tool.metadata.timeout?.executeMs??this.scope.rateLimitManager?.config?.defaultTimeout?.executeMs;const running=runOnSurface(callSurfaceOf(this.input.ctx),()=>runAsTool({name:tool.name,fullName:tool.fullName},async()=>{await this.input.ctx.beforeExecute?.();if(toolContext.signal?.aborted)return;toolContext.output=await toolContext.execute(toolContext.input)}));try{await(timeoutMs?withTimeout(()=>running,timeoutMs,tool.metadata.name):running);this.logger.verbose("execute:done")}catch(error){if(error instanceof FlowControl&&error.type==="respond"){this.logger.verbose("execute:done (respond)");return}if(error instanceof FlowControl){throw error}if(error instanceof InputRequiredSignal||error instanceof MissingClientCapabilityError){throw error}if(error instanceof ExecutionTimeoutError){this.logger.warn("execute: tool execution timed out",{tool:tool.metadata.name,timeoutMs});this.state.executionAbort?.abort(error);this.state.set("abandonedExecution",running);throw error}if(error instanceof ElicitationFallbackRequired){this.logger.info("execute: elicitation fallback required",{elicitId:error.elicitId,toolName:error.toolName});const authInfo=this.state.authInfo;const authInfoWithTransport=authInfo;const sessionId=authInfo?.sessionId??"anonymous";const store=this.scope.elicitationStore;if(!store){throw new InternalMcpError("Elicitation store not initialized")}const owner=resolveElicitationOwner(this.tryGetContext());if(!owner){throw new ElicitationNotSupportedError("This client does not support elicitation, and the elicitation fallback needs a verified session or an authenticated caller to know who may answer it")}await store.setPendingFallback({elicitId:error.elicitId,sessionId,owner,toolName:tool.fullName,toolInput:this.state.required.input.arguments,idempotencyKey:toolContext.idempotencyKey,elicitMessage:error.elicitMessage,elicitSchema:error.schema,createdAt:Date.now(),expiresAt:Date.now()+error.ttl});const transportType=authInfoWithTransport?.transport?.type;if(transportType==="streamable-http"&&canDeliverNotifications(this.scope,sessionId)){this.logger.info("execute: using waiting fallback for streamable-http",{elicitId:error.elicitId});const deps={scope:this.scope,sessionId,logger:this.logger};const result=await awaitOutsideRequest4(handleWaitingFallback(deps,error));toolContext.output=result;this.logger.verbose("execute:done (elicitation waiting fallback)");return}const fallbackResponse={content:[{type:"text",text:`This tool requires user input to continue.
68
68
 
69
69
  **Question:** ${error.elicitMessage}
70
70
 
@@ -294,7 +294,7 @@ data: ${JSON.stringify(message)}
294
294
  `)}get sessionId(){return this._sessionId}get lastEventId(){return this._eventIdCounter}setEventIdCounter(eventId){this._eventIdCounter=eventId}}}});var init_node_sse_transport=__esm({"libs/sdk/src/transport/adapters/polyfills/node-sse-transport.ts"(){"use strict";init_base_sse_transport()}});var sse_transport_exports={};__export(sse_transport_exports,{RecreateableSSEServerTransport:()=>RecreateableSSEServerTransport});var RecreateableSSEServerTransport;var init_sse_transport=__esm({"libs/sdk/src/transport/adapters/sse-transport.ts"(){"use strict";init_node_sse_transport();RecreateableSSEServerTransport=class extends SSEServerTransport{_isRecreatedSession=false;constructor(endpoint,res,options){super(endpoint,res,options);if(options?.initialEventId!==void 0&&this.isValidEventId(options.initialEventId)){this.setEventIdCounter(options.initialEventId);this._isRecreatedSession=true}}isValidEventId(eventId){return Number.isInteger(eventId)&&eventId>=0&&eventId<=Number.MAX_SAFE_INTEGER}get isRecreatedSession(){return this._isRecreatedSession}get eventIdCounter(){return this.lastEventId}setEventIdCounter(eventId){if(!this.isValidEventId(eventId)){console.warn(`[RecreateableSSEServerTransport] Invalid eventId: ${eventId}. Must be a non-negative integer. Ignoring.`);return}super.setEventIdCounter(eventId)}setSessionState(sessionId,lastEventId){if(this.sessionId!==sessionId){const redact=id=>`${id.slice(0,8)}\u2026`;console.warn(`RecreateableSSEServerTransport: session ID mismatch. Expected ${redact(this.sessionId)}, got ${redact(sessionId)}. Using constructor value.`)}if(lastEventId!==void 0){this.setEventIdCounter(lastEventId)}this._isRecreatedSession=true}}}});import{toJSONSchema as toJSONSchema6}from"@frontmcp/lazy-zod";async function loadSseTransport(){RecreateableTransport??=(await Promise.resolve().then(()=>(init_sse_transport(),sse_transport_exports))).RecreateableSSEServerTransport}function sseTransportClass(){if(!RecreateableTransport){throw new InternalMcpError("The SSE transport was used before loadSseTransport() loaded it")}return RecreateableTransport}var RecreateableTransport,TransportSSEAdapter;var init_transport_sse_adapter=__esm({"libs/sdk/src/transport/adapters/transport.sse.adapter.ts"(){"use strict";init_elicitation_types();init_errors();init_transport_error();init_transport_local_adapter();TransportSSEAdapter=class extends LocalTransportAdapter{sessionId;configureTransportHandlers(transport){transport.onerror=error=>{console.error("SSE error:",error instanceof Error?error.message:"Unknown error")};transport.onclose=this.destroy.bind(this)}createTransport(sessionId,res){this.sessionId=sessionId;this.logger.info(`new transport session: ${sessionId.slice(0,40)}`);const SseTransport=sseTransportClass();const transport=new SseTransport(`${this.scope.fullPath}/message`,res,{sessionId});this.configureTransportHandlers(transport);return transport}createTransportFromSession(sessionId,res,lastEventId){this.sessionId=sessionId;this.logger.info(`recreating transport session: ${sessionId.slice(0,40)}, lastEventId: ${lastEventId??"none"}`);const SseTransport=sseTransportClass();const transport=new SseTransport(`${this.scope.fullPath}/message`,res,{sessionId,initialEventId:lastEventId});this.configureTransportHandlers(transport);return transport}initialize(req,res){this.logger.verbose(`[${this.sessionId}] handle initialize request`);this.ensureAuthInfo(req,this);return Promise.resolve()}async handleRequest(req,res){await this.ready;const authInfo=this.ensureAuthInfo(req,this);if(this.handleIfElicitResult(req)){this.logger.verbose(`[${this.sessionId}] handled elicitation result`);res.writeHead(202,{"Content-Type":"application/json"});res.end(JSON.stringify({jsonrpc:"2.0",id:null,result:{}}));return}if(req.method==="GET"){this.logger.verbose(`[${this.sessionId}] handle get request`);return this.transport.handleMessage(req.body,{requestInfo:{headers:req.headers},authInfo})}else{this.logger.verbose(`[${this.sessionId}] handle post request`);return this.transport.handlePostMessage(req,res,req.body)}}async sendElicitRequest(relatedRequestId,message,requestedSchema,options){const{mode="form",ttl=DEFAULT_ELICIT_TTL,elicitationId,url}=options??{};if(mode==="url"&&!url){throw new InvalidInputError('url is required when mode is "url"')}await this.cancelPendingElicit();const elicitId=elicitationId||`elicit-${this.newRequestId}`;const sessionId=this.key.sessionId;const expiresAt=Date.now()+ttl;const store=this.requireElicitStore();await store.setPending({elicitId,sessionId,createdAt:Date.now(),expiresAt,message,mode});const params={mode,message,requestedSchema:toJSONSchema6(requestedSchema)};if(mode==="url"){params["elicitationId"]=elicitId;params["url"]=url}this.logger.info("sendElicitRequest",{relatedRequestId,elicitId,mode,ttl});await this.transport.send(rpcRequest(this.newRequestId,"elicitation/create",params));return new Promise((resolve4,reject)=>{let settled=false;let unsubscribe;const cleanup=()=>{clearTimeout(timeoutHandle);this.pendingElicit=void 0;void unsubscribe?.()};const safeResolve=result=>{if(settled)return;settled=true;cleanup();resolve4(result)};const safeReject=err=>{if(settled)return;settled=true;cleanup();reject(err)};const timeoutHandle=setTimeout(async()=>{if(settled)return;settled=true;this.pendingElicit=void 0;await unsubscribe?.();await store.deletePending(sessionId);reject(new ElicitationTimeoutError(elicitId,ttl))},ttl);store.subscribeResult(elicitId,result=>{safeResolve(result)},sessionId).then(unsub=>{unsubscribe=unsub}).catch(async err=>{if(settled)return;settled=true;clearTimeout(timeoutHandle);this.pendingElicit=void 0;await unsubscribe?.();await store.deletePending(sessionId);reject(err)});this.pendingElicit={elicitId,timeoutHandle,resolve:safeResolve,reject:safeReject}})}}}});function createSessionScopedEventStore(store,sessionId){const prefix=`${sessionId}${SCOPE_SEPARATOR}`;const scope=streamId=>`${prefix}${streamId}`;const unscope=streamId=>{const value=String(streamId);return value.startsWith(prefix)?value.slice(prefix.length):value};const resolveOwnedStream=async eventId=>{const lookup=store.getStreamIdForEventId;if(lookup){const resolved=await lookup.call(store,eventId);return resolved!==void 0&&String(resolved).startsWith(prefix)?resolved:void 0}if(!String(eventId).startsWith(prefix))return void 0;const value=String(eventId);const lastColon=value.lastIndexOf(":");return lastColon===-1?void 0:value.slice(0,lastColon)};return{async storeEvent(streamId,message){return store.storeEvent(scope(streamId),message)},async getStreamIdForEventId(eventId){const owned=await resolveOwnedStream(eventId);return owned===void 0?void 0:unscope(owned)},async replayEventsAfter(lastEventId,options){const owned=await resolveOwnedStream(lastEventId);if(owned===void 0){return"default-stream"}return unscope(await store.replayEventsAfter(lastEventId,options))}}}var SCOPE_SEPARATOR;var init_session_scoped_event_store=__esm({"libs/sdk/src/transport/event-stores/session-scoped.event-store.ts"(){"use strict";SCOPE_SEPARATOR=" "}});var streamable_http_transport_exports={};__export(streamable_http_transport_exports,{RecreateableStreamableHTTPServerTransport:()=>RecreateableStreamableHTTPServerTransport});import{StreamableHTTPServerTransport,WebStandardStreamableHTTPServerTransport as WebStandardStreamableHTTPServerTransport2}from"@frontmcp/protocol";var RecreateableStreamableHTTPServerTransport;var init_streamable_http_transport=__esm({"libs/sdk/src/transport/adapters/streamable-http-transport.ts"(){"use strict";init_transport_errors();RecreateableStreamableHTTPServerTransport=class extends StreamableHTTPServerTransport{_pendingInitState;_constructorOptions;_isStateless;constructor(options={}){super(options);this._constructorOptions=options;this._isStateless=options.isStateless??false}get isInitialized(){return this._webStandardTransport?._initialized??false}get hasPendingInitState(){return this._pendingInitState!==void 0}setInitializationState(sessionId){if(!sessionId||typeof sessionId!=="string"||sessionId.trim()===""){throw new InvalidTransportSessionError("[RecreateableStreamableHTTPServerTransport] sessionId cannot be empty")}const webTransport=this._webStandardTransport;if(!webTransport){this._pendingInitState=sessionId;return}this._applyInitState(webTransport,sessionId)}resetForReinitialization(){const webTransport=this._webStandardTransport;if(!webTransport){this._pendingInitState=void 0;return}if(!("_initialized"in webTransport)){throw new InvalidTransportSessionError("[RecreateableStreamableHTTPServerTransport] Expected _initialized field not found on internal transport. This may indicate an incompatible MCP SDK version.")}webTransport._initialized=false;webTransport.sessionId=void 0;this._pendingInitState=void 0}_applyInitState(webTransport,sessionId){if(!("_initialized"in webTransport)){throw new InvalidTransportSessionError("[RecreateableStreamableHTTPServerTransport] Expected _initialized field not found on internal transport. This may indicate an incompatible MCP SDK version.")}webTransport._initialized=true;webTransport.sessionId=sessionId}async handleRequest(req,res,body){const oldWebTransport=this._webStandardTransport;if(oldWebTransport&&this._isStateless&&oldWebTransport._hasHandledRequest){const fresh=new WebStandardStreamableHTTPServerTransport2(this._constructorOptions);fresh.onmessage=oldWebTransport.onmessage;fresh.onclose=oldWebTransport.onclose;fresh.onerror=oldWebTransport.onerror;await fresh.start();this._webStandardTransport=fresh}if(this._pendingInitState){const webTransport=this._webStandardTransport;if(webTransport){this._applyInitState(webTransport,this._pendingInitState);this._pendingInitState=void 0}}if(!res.headersSent)res.removeHeader?.("Content-Type");return super.handleRequest(req,res,body)}}}});import{toJSONSchema as toJSONSchema7}from"@frontmcp/lazy-zod";async function loadStreamableHttpTransport(){RecreateableTransport2??=(await Promise.resolve().then(()=>(init_streamable_http_transport(),streamable_http_transport_exports))).RecreateableStreamableHTTPServerTransport}var RecreateableTransport2,resolveSessionIdGenerator,TransportStreamableHttpAdapter;var init_transport_streamable_http_adapter=__esm({"libs/sdk/src/transport/adapters/transport.streamable-http.adapter.ts"(){"use strict";init_errors();init_session_scoped_event_store();init_transport_error();init_transport_types();init_transport_local_adapter();resolveSessionIdGenerator=(transportType,sessionId)=>{return transportType==="stateless-http"?()=>STATELESS_SESSION_ID:()=>sessionId};TransportStreamableHttpAdapter=class extends LocalTransportAdapter{createTransport(sessionId,response){const sessionIdGenerator=resolveSessionIdGenerator(this.key.type,sessionId);const sharedEventStore=this.scope.eventStore;const eventStore=sharedEventStore?createSessionScopedEventStore(sharedEventStore,sessionId):void 0;const isStateless=this.key.type==="stateless-http";if(!RecreateableTransport2){throw new InternalMcpError("The Streamable HTTP transport was used before loadStreamableHttpTransport() loaded it")}return new RecreateableTransport2({sessionIdGenerator,isStateless,onsessionclosed:()=>{},onsessioninitialized:sessionId2=>{if(sessionId2){this.logger.verbose("[StreamableHttpAdapter] session initialized",{sessionId:sessionId2.slice(0,40)})}else{this.logger.verbose("[StreamableHttpAdapter] stateless session initialized")}},eventStore})}async initialize(req,res){this.ensureAuthInfo(req,this);this.logger.verbose("[StreamableHttpAdapter] initialize() called",{method:req.method,sessionId:this.key.sessionId.slice(0,30),bodyMethod:req.body?.method,bodyJsonrpc:req.body?.jsonrpc,bodyId:req.body?.id,bodyType:typeof req.body,bodyKeys:req.body&&typeof req.body==="object"?Object.keys(req.body):[]});await this.ready;this.logger.verbose("[StreamableHttpAdapter] transport state before handleRequest",{isRecreatable:RecreateableTransport2!==void 0&&this.transport instanceof RecreateableTransport2,hasWebTransport:!!this.transport._webStandardTransport,webTransportInitialized:this.transport._webStandardTransport?._initialized,webTransportStarted:this.transport._webStandardTransport?._started,hasSessionIdGenerator:this.transport._webStandardTransport?.sessionIdGenerator!==void 0});const originalWrite=res.write.bind(res);const originalEnd=res.end.bind(res);let responseBody="";res.write=function(chunk,encodingOrCb,cb){if(chunk){responseBody+=typeof chunk==="string"?chunk:Buffer.isBuffer(chunk)?chunk.toString():String(chunk)}return originalWrite.call(this,chunk,encodingOrCb,cb)};const adapter=this;res.end=function(chunk,encodingOrCb,cb){if(chunk){responseBody+=typeof chunk==="string"?chunk:Buffer.isBuffer(chunk)?chunk.toString():String(chunk)}adapter.logger.verbose("[StreamableHttpAdapter] initialize response",{statusCode:res.statusCode,headers:res.getHeaders?.()??{},bodyLength:responseBody.length});return originalEnd.call(this,chunk,encodingOrCb,cb)};return this.transport.handleRequest(req,res,req.body)}async handleRequest(req,res){this.ensureAuthInfo(req,this);if(req.method==="GET"){return this.transport.handleRequest(req,res)}else{if(this.handleIfElicitResult(req)){return}return this.transport.handleRequest(req,res,req.body)}}async destroy(reason){if(reason===void 0)await this.transport.close().catch(()=>void 0);return super.destroy(reason)}async sendElicitRequest(relatedRequestId,message,requestedSchema,options){await this.cancelPendingElicit();const store=this.requireElicitStore();const sessionId=this.key.sessionId;const flowOutput=await this.scope.runFlowForOutput("elicitation:request",{relatedRequestId,sessionId,message,requestedSchema:toJSONSchema7(requestedSchema),options});const{elicitId,expiresAt,requestParams,pendingRecord}=flowOutput;const ttl=expiresAt-Date.now();this.logger.verbose("[StreamableHttpAdapter] sendElicitRequest: sending elicitation/create",{relatedRequestId,elicitId,mode:pendingRecord.mode,message:message.slice(0,100)});try{await this.transport.send(rpcRequest(this.newRequestId,"elicitation/create",requestParams),{relatedRequestId});this.logger.verbose("[StreamableHttpAdapter] sendElicitRequest: transport.send() completed")}catch(error){this.logger.error("[StreamableHttpAdapter] sendElicitRequest: transport.send() failed",error);try{await store.deletePending(sessionId);this.logger.verbose("[StreamableHttpAdapter] sendElicitRequest: cleaned up pending record after send failure")}catch(cleanupError){this.logger.warn("[StreamableHttpAdapter] sendElicitRequest: failed to clean up pending record",cleanupError)}throw error}return new Promise((resolve4,reject)=>{let settled=false;let unsubscribe;const cleanup=()=>{clearTimeout(timeoutHandle);this.pendingElicit=void 0;void unsubscribe?.()};const safeResolve=result=>{if(settled)return;settled=true;cleanup();resolve4(result)};const safeReject=err=>{if(settled)return;settled=true;cleanup();reject(err)};const timeoutHandle=setTimeout(async()=>{if(settled)return;settled=true;this.pendingElicit=void 0;await unsubscribe?.();await store.deletePending(sessionId);reject(new ElicitationTimeoutError(elicitId,ttl))},ttl);store.subscribeResult(elicitId,result=>{safeResolve(result)},sessionId).then(unsub=>{unsubscribe=unsub}).catch(async err=>{if(settled)return;settled=true;clearTimeout(timeoutHandle);this.pendingElicit=void 0;await unsubscribe?.();await store.deletePending(sessionId);reject(err)});this.pendingElicit={elicitId,timeoutHandle,resolve:safeResolve,reject:safeReject}})}get isInitialized(){return this.transport.isInitialized||this.transport.hasPendingInitState}resetForReinitialization(){this.transport.resetForReinitialization();this.logger.info("[StreamableHttpAdapter] Reset transport for re-initialization",{sessionId:this.key.sessionId?.slice(0,20)})}markAsInitialized(){this.transport.setInitializationState(this.key.sessionId);this.logger.info("[StreamableHttpAdapter] Marked transport as pre-initialized for session recreation",{sessionId:this.key.sessionId?.slice(0,20),isInitialized:this.transport.isInitialized})}}}});import{isAnonymousSubject as isAnonymousSubject8}from"@frontmcp/auth";import{internalZ as z113}from"@frontmcp/lazy-zod";import{MCP_20260728_META as MCP_20260728_META8,StreamEventsRequestSchema as StreamEventsRequestSchema2}from"@frontmcp/protocol";import{runRequestExclusive as runRequestExclusive5}from"@frontmcp/utils";function frame3(message){return encoder8.encode(`event: message
295
295
  data: ${JSON.stringify(message)}
296
296
 
297
- `)}function acceptsEventStream(headers){const accept=readHeader(headers,"accept");return typeof accept==="string"&&accept.includes("text/event-stream")}function extractTraceContext(meta){const out={};for(const key of TRACE_META_KEYS){if(typeof meta[key]==="string")out[key]=meta[key]}return Object.keys(out).length>0?out:void 0}async function*streamMessageResponse(options,sink,requestId,runInContext){let outcome;let failure;const running=runInContext(async()=>{try{outcome=await dispatch20260728(options)}catch(error){failure=error}}).finally(()=>sink.close());while(!sink.closed){await sink.waitForActivity();for(const notification of sink.drain()){yield frame3({jsonrpc:"2.0",method:notification.method,params:notification.params})}}await running;for(const notification of sink.drain()){yield frame3({jsonrpc:"2.0",method:notification.method,params:notification.params})}const id=requestId??null;if(failure!==void 0){const mapped=toJsonRpcError(failure);yield frame3({jsonrpc:"2.0",id,error:mapped.error});return}if(outcome?.kind==="error"){yield frame3({jsonrpc:"2.0",id,error:outcome.error});return}yield frame3({jsonrpc:"2.0",id,result:outcome?.result})}function isAnonymousCaller(auth){if(!auth)return true;if(!isAnonymousSubject8(auth.user?.sub))return false;return!auth.token||auth.session?.payload?.isPublic===true}function errorResponse(status,error,id){return httpRespond.json({jsonrpc:"2.0",id:id===void 0?null:id,error},{status})}function toClientInfo(value){if(typeof value!=="object"||value===null)return void 0;const{name:name59,version}=value;return typeof name59==="string"&&typeof version==="string"?{name:name59,version}:void 0}var plan24,MAX_RESOURCE_SUBSCRIPTIONS,subscriptionParamsSchema,requestIdSchema,stateSchema21,name24,Stage24,encoder8,TRACE_META_KEYS,HandleMcp20260728Flow;var init_handle_mcp_20260728_flow=__esm({"libs/sdk/src/transport/flows/handle.mcp-20260728.flow.ts"(){"use strict";init_common();init_tool_lookup_utils();init_context();init_notification();init_notification_service();init_skill_instructions_helper();init_mcp_20260728();init_mcp_surface();plan24={pre:["parseInput","validate","router"],execute:["handleNotification","handleSubscriptions","handleEventStream","handleMessage"],post:[],finalize:["cleanup"]};MAX_RESOURCE_SUBSCRIPTIONS=1e3;subscriptionParamsSchema=z113.object({notifications:z113.object({toolsListChanged:z113.boolean().optional(),promptsListChanged:z113.boolean().optional(),resourcesListChanged:z113.boolean().optional(),resourceSubscriptions:z113.array(z113.string()).max(MAX_RESOURCE_SUBSCRIPTIONS,{message:`subscriptions/listen takes at most ${MAX_RESOURCE_SUBSCRIPTIONS} resourceSubscriptions`}).optional()}).default({})});requestIdSchema=z113.union([z113.string(),z113.number()]);stateSchema21=z113.object({version:z113.string().optional(),requestType:z113.enum(["notification","subscriptions","eventStream","message"]).optional(),isAnonymous:z113.boolean().default(true),clientDeclaredRevision:z113.boolean().optional()});name24="handle:mcp-202607280728";({Stage:Stage24}=FlowHooksOf(name24));encoder8=new TextEncoder;TRACE_META_KEYS=["traceparent","tracestate","baggage"];HandleMcp20260728Flow=class extends FlowBase{name=name24;get log(){return this.scope.logger.child("HandleMcp20260728Flow")}async parseInput(){const{request:request2}=this.rawInput;const auth=request2[ServerRequestTokens.auth];this.state.set(stateSchema21.parse({isAnonymous:isAnonymousCaller(auth)}))}async validate(){const{request:request2}=this.rawInput;const method=request2.method.toUpperCase();if(method==="GET"||method==="DELETE"){this.respond({kind:"text",status:405,body:`HTTP ${method} is not supported by MCP protocol 2026-07-28`,contentType:"text/plain; charset=utf-8",headers:{Allow:"POST"}});return}const body=request2.body??{};const scope=this.scope;const clientDeclaredRevision=declaresProtocol20260728({headers:request2.headers,body});const result=validate20260728Request({headers:request2.headers,body,lookupToolSchema:toolName=>this.findToolSchema(scope,toolName),strictHeaders:clientDeclaredRevision&&!this.stdioOrigin});if(!result.ok){this.log.info("validate: rejected",{code:result.error.code,message:result.error.message});this.respond(errorResponse(result.status,result.error,body["id"]));return}this.state.set("version",result.version);this.state.set("clientDeclaredRevision",clientDeclaredRevision)}get stdioOrigin(){return this.rawInput.request[ServerRequestTokens.stdio]}buildContextRunner(){const context=this.tryGetContext();if(!context)return fn=>fn();const storage=this.scope.providers.get(FrontMcpContextStorage);return async fn=>{await runRequestExclusive5(()=>storage.runWithContext(context,fn))}}findToolSchema(scope,toolName){return lookupTool(scope,toolName)?.getInputJsonSchema()??null}async router(){const body=this.rawInput.request.body??{};const isNotification=body["id"]===void 0||body["id"]===null;if(isNotification){this.state.set("requestType","notification");return}if(body["method"]==="events/stream"&&this.scope.events?.performs("push")){this.state.set("requestType","eventStream");return}this.state.set("requestType",body["method"]==="subscriptions/listen"?"subscriptions":"message")}async handleNotification(){this.respond({kind:"text",status:202,body:"",contentType:"text/plain; charset=utf-8"})}async handleSubscriptions(){const{request:request2,response}=this.rawInput;const body=request2.body??{};const subscriptionId=requestIdSchema.safeParse(body["id"]);if(!subscriptionId.success){this.respond(errorResponse(400,{code:-32602,message:"subscriptions/listen requires a string or number id"},null));return}const parsedParams=subscriptionParamsSchema.safeParse(body["params"]??{});if(!parsedParams.success){this.respond(errorResponse(400,{code:-32602,message:`Invalid subscriptions/listen params: ${parsedParams.error.issues[0]?.message??"not an object"}`},subscriptionId.data));return}const auth=request2[ServerRequestTokens.auth];const listenerAuthInfo=auth?authInfoFromAuthorization(auth):{};const mayRead=this.resourceReadCheck(listenerAuthInfo);const requested={...parsedParams.data.notifications,resourceSubscriptions:await this.readableUris(parsedParams.data.notifications.resourceSubscriptions,mayRead)};const controller=new AbortController;const abort=()=>controller.abort();response?.on?.("close",abort);const stdioSignal=this.stdioOrigin?.signal;if(stdioSignal?.aborted)abort();else stdioSignal?.addEventListener("abort",abort,{once:true});const{acknowledged,stream}=createSubscriptionStream({scope:this.scope,subscriptionId:subscriptionId.data,requested,channels:await this.listenedChannels(body["params"]?._meta),signal:controller.signal,mayReceiveUpdate:(uri,watchedUri)=>listenerMayReceive(()=>hasExpiredCaller({caller:sessionCallerOf(listenerAuthInfo)}),()=>mayRead(this.scope.resources.findResourceForUri(uri)?uri:watchedUri))});this.log.info("handleSubscriptions: stream opened",{subscriptionId:body["id"],acknowledged:Object.keys(acknowledged)});this.respond({kind:"sse",status:200,stream,contentType:"text/event-stream",disposition:"inline",headers:{"X-Accel-Buffering":"no","Cache-Control":"no-cache, no-transform",Connection:"keep-alive"}})}async handleEventStream(){const{request:request2,response}=this.rawInput;const body=request2.body??{};const requestId=requestIdSchema.safeParse(body["id"]);if(!requestId.success){this.respond(errorResponse(400,{code:-32602,message:"events/stream requires a string or number id"},null));return}const streamRequest=StreamEventsRequestSchema2.safeParse({method:"events/stream",params:body["params"]});if(!streamRequest.success){const problem2=streamRequest.error.issues[0]?.message??"not an object";const error={code:-32602,message:`Invalid events/stream params: ${problem2}`};this.respond(errorResponse(400,error,requestId.data));return}const meta=body["params"]?._meta??{};const clientInfo=toClientInfo(meta[MCP_20260728_META8.clientInfo]);const clientCapabilities=meta[MCP_20260728_META8.clientCapabilities]??{};const platformDetection=this.scope.metadata.transport?.platformDetection;this.tryGetContext()?.setClientInfo(clientInfo,resolvePlatformType(clientInfo,clientCapabilities,platformDetection));const auth=request2[ServerRequestTokens.auth];const authInfo=auth?{...authInfoFromAuthorization(auth),sessionId:auth.session?.id??this.tryGetContext()?.sessionId}:{};const controller=new AbortController;const abort=()=>controller.abort();response?.on?.("close",abort);const stdioSignal=this.stdioOrigin?.signal;if(stdioSignal?.aborted)abort();else stdioSignal?.addEventListener("abort",abort,{once:true});let opened;try{opened=await this.scope.runFlowForOutput("events:stream",{request:streamRequest.data,ctx:{authInfo,surface:mcpRequestSurface(this.scope)},requestId:requestId.data,signal:controller.signal})}catch(failure){const mapped=toJsonRpcError(failure);this.respond(errorResponse(mapped.status,mapped.error,requestId.data));return}this.log.info("handleEventStream: stream opened",{subscriptionId:requestId.data});this.respond({kind:"sse",status:200,stream:eventStreamFrames(opened.stream,requestId.data),contentType:"text/event-stream",disposition:"inline",headers:{"X-Accel-Buffering":"no","Cache-Control":"no-cache, no-transform",Connection:"keep-alive"}})}resourceReadCheck(authInfo){const runInRequest=this.buildContextRunner();const ctx={authInfo,surface:mcpRequestSurface(this.scope)};return async uri=>{let allowed=false;await runInRequest(async()=>{const request2={method:"resources/subscribe",params:{uri}};allowed=await this.scope.runFlow("resources:subscribe",{request:request2,ctx}).then(()=>true,()=>false)});return allowed}}async readableUris(uris,mayRead){if(!uris)return void 0;const unique=[...new Set(uris)];const allowed=await Promise.all(unique.map(mayRead));return unique.filter((_uri,index)=>allowed[index])}async listenedChannels(meta){const capabilities=meta?.[MCP_20260728_META8.clientCapabilities];if(!supportsChannels(capabilities)||!this.scope.channels)return[];const listed=await this.scope.runFlowForOutput("channels:list",{});return listed.channels.map(channel2=>channel2.name)}async handleMessage(){const{request:request2}=this.rawInput;const body=request2.body??{};const params=body["params"]??{};const meta=params["_meta"]??{};const auth=request2[ServerRequestTokens.auth];const stdio=this.stdioOrigin;const clientCapabilities=meta[MCP_20260728_META8.clientCapabilities]??{};const logLevel=typeof meta[MCP_20260728_META8.logLevel]==="string"?meta[MCP_20260728_META8.logLevel]:void 0;const rawProgressToken=meta["progressToken"];const progressToken=typeof rawProgressToken==="string"||typeof rawProgressToken==="number"?rawProgressToken:void 0;const sink=new RequestNotificationSink(logLevel,progressToken);const clientInfo=toClientInfo(meta[MCP_20260728_META8.clientInfo]);const platformType=resolvePlatformType(clientInfo,clientCapabilities,this.scope.metadata.transport?.platformDetection);this.tryGetContext()?.setClientInfo(clientInfo,platformType);const dispatchOptions={scope:this.scope,body,clientCapabilities,frontmcpContext:this.tryGetContext(),authInfo:auth?{...authInfoFromAuthorization(auth),sessionId:auth.session?.id??this.tryGetContext()?.sessionId}:stdio&&{sessionId:this.tryGetContext()?.sessionId},isAnonymous:this.state.required.isAnonymous,transportPrincipal:stdio?.principal,signal:stdio?.signal,clientDeclaredRevision:this.state.clientDeclaredRevision!==false,composeInstructions:(caller,clientName)=>composeCallerInstructions(this.scope,{ctx:caller,clientName:clientName??this.tryGetContext()?.clientInfo?.name,skillUriHints:true}),notificationSink:sink,traceContext:extractTraceContext(meta)};const streams=stdio!==void 0||acceptsEventStream(request2.headers);if(sink.active&&streams){this.respond({kind:"sse",status:200,stream:streamMessageResponse(dispatchOptions,sink,body["id"],this.buildContextRunner()),contentType:"text/event-stream",disposition:"inline",headers:{"X-Accel-Buffering":"no","Cache-Control":"no-cache, no-transform",Connection:"keep-alive"}});return}const outcome=await dispatch20260728(dispatchOptions);sink.close();if(outcome.kind==="error"){this.respond(errorResponse(outcome.status,outcome.error,body["id"]));return}this.respond(httpRespond.json({jsonrpc:"2.0",id:body["id"]??null,result:outcome.result},{status:200}))}async cleanup(){}};__decorateClass([Stage24("parseInput")],HandleMcp20260728Flow.prototype,"parseInput",1);__decorateClass([Stage24("validate")],HandleMcp20260728Flow.prototype,"validate",1);__decorateClass([Stage24("router")],HandleMcp20260728Flow.prototype,"router",1);__decorateClass([Stage24("handleNotification",{filter:({state})=>state.required.requestType==="notification"})],HandleMcp20260728Flow.prototype,"handleNotification",1);__decorateClass([Stage24("handleSubscriptions",{filter:({state})=>state.required.requestType==="subscriptions"})],HandleMcp20260728Flow.prototype,"handleSubscriptions",1);__decorateClass([Stage24("handleEventStream",{filter:({state})=>state.required.requestType==="eventStream"})],HandleMcp20260728Flow.prototype,"handleEventStream",1);__decorateClass([Stage24("handleMessage",{filter:({state})=>state.required.requestType==="message"})],HandleMcp20260728Flow.prototype,"handleMessage",1);__decorateClass([Stage24("cleanup")],HandleMcp20260728Flow.prototype,"cleanup",1);HandleMcp20260728Flow=__decorateClass([FrontMcpFlow({name:name24,plan:plan24,access:"authorized",inputSchema:httpInputSchema,outputSchema:httpOutputSchema})],HandleMcp20260728Flow)}});import{internalZ as z114}from"@frontmcp/lazy-zod";function getQuerySessionId2(urlPath){if(!urlPath)return void 0;try{const u=new URL(String(urlPath),"http://local");return u.searchParams.get("sessionId")??void 0}catch{return void 0}}function resolveLegacySseSession(params){const{rawHeader,requestUrl,authorizationSession,createSession}=params;const rawMcpSessionHeader=typeof rawHeader==="string"?rawHeader:void 0;const mcpSessionHeader=validateMcpSessionHeader(rawMcpSessionHeader);const querySessionId=getQuerySessionId2(requestUrl);const validatedQuerySessionId=querySessionId?validateMcpSessionHeader(querySessionId):void 0;if(rawHeader!==void 0&&!mcpSessionHeader){return{responded404:true,createdNew:false}}if(querySessionId!==void 0&&!validatedQuerySessionId){return{responded404:true,createdNew:false}}const effectiveSessionId=mcpSessionHeader??validatedQuerySessionId;if(effectiveSessionId){if(authorizationSession?.id===effectiveSessionId){return{session:authorizationSession,createdNew:false,responded404:false}}return{responded404:true,createdNew:false}}if(authorizationSession){return{session:authorizationSession,createdNew:false,responded404:false}}return{session:createSession(),createdNew:true,responded404:false}}var plan25,stateSessionSchema,stateSchema22,name25,Stage25,HandleSseFlow;var init_handle_sse_flow=__esm({"libs/sdk/src/transport/flows/handle.sse.flow.ts"(){"use strict";init_session_id_utils();init_common();init_errors();init_ha_headers();init_skill_mode_utils();plan25={pre:["parseInput","router"],execute:["onInitialize","onMessage","onElicitResult"],post:[],finalize:["cleanup"]};stateSessionSchema=z114.object({id:z114.string(),payload:z114.object({nodeId:z114.string(),authSig:z114.string(),uuid:z114.string().uuid(),iat:z114.number(),protocol:z114.enum(["legacy-sse","sse","streamable-http","stateful-http","stateless-http"]).optional(),isPublic:z114.boolean().optional(),platformType:z114.enum(["openai","claude","claude-code","codex","gemini","cursor","continue","cody","generic-mcp","ext-apps","unknown"]).optional()}).optional()});stateSchema22=z114.object({token:z114.string(),session:stateSessionSchema,requestType:z114.enum(["initialize","message","elicitResult"]).optional()});name25="handle:legacy-sse";({Stage:Stage25}=FlowHooksOf(name25));HandleSseFlow=class extends FlowBase{async parseInput(){const{request:request2}=this.rawInput;const authorization=request2[ServerRequestTokens.auth];const{token}=authorization;const anyReq=request2;const resolution=resolveLegacySseSession({rawHeader:request2.headers?.["mcp-session-id"],requestUrl:anyReq.url??anyReq.path,authorizationSession:authorization.session,createSession:()=>{const query=request2.query;const skillsOnlyMode=detectSkillsOnlyMode(query);return createSessionId("legacy-sse",token,{userAgent:request2.headers?.["user-agent"],platformDetectionConfig:this.scope.metadata.transport?.platformDetection,skillsOnlyMode})}});if(resolution.responded404||!resolution.session){this.respond(httpRespond.sessionNotFound("invalid session id"));return}const session=resolution.session;this.state.set(stateSchema22.parse({token,session}))}async router(){const{request:request2}=this.rawInput;const requestPath=normalizeEntryPrefix(request2.path);const prefix=normalizeEntryPrefix(this.scope.entryPath);const scopePath=normalizeScopeBase(this.scope.routeBase);const basePath=`${prefix}${scopePath}`;if(requestPath===`${basePath}/sse`){this.state.set("requestType","initialize")}else if(requestPath===`${basePath}/message`){this.state.set("requestType","message")}}async onInitialize(){const transportService=this.scope.transportService;if(!transportService){throw new TransportServiceNotAvailableError}const{request:request2,response}=this.rawInput;const{token,session}=this.state.required;const authorization=request2[ServerRequestTokens.auth];authorization.session??=session;const transport=await transportService.createTransporter("sse",token,session.id,response);applyNodeAffinity(response,request2);await transport.initialize(request2,response);this.handled()}async onElicitResult(){this.fail(new Error("Not implemented"))}async onMessage(){const transportService=this.scope.transportService;if(!transportService){throw new TransportServiceNotAvailableError}const logger=this.scopeLogger.child("handle:legacy-sse:onMessage");const{request:request2,response}=this.rawInput;const{token,session}=this.state.required;const transport=await transportService.getTransporter("sse",token,session.id);if(!transport){const wasCreated=await transportService.wasSessionCreatedAsync("sse",token,session.id);const body=request2.body;if(wasCreated){logger.info("Session expired - client should re-initialize",{sessionId:session.id?.slice(0,20),tokenHash:token.slice(0,8),method:body?.["method"],requestId:body?.["id"]});this.respond(httpRespond.sessionExpired("session expired"))}else{logger.warn("Session not initialized - client attempted request without initializing",{sessionId:session.id?.slice(0,20),tokenHash:token.slice(0,8),method:body?.["method"],requestId:body?.["id"],userAgent:request2.headers?.["user-agent"]?.slice(0,50)});this.respond(httpRespond.sessionNotFound("session not initialized"))}return}await transport.handleRequest(request2,response);this.handled()}};__decorateClass([Stage25("parseInput")],HandleSseFlow.prototype,"parseInput",1);__decorateClass([Stage25("router")],HandleSseFlow.prototype,"router",1);__decorateClass([Stage25("onInitialize",{filter:({state:{requestType}})=>requestType==="initialize"})],HandleSseFlow.prototype,"onInitialize",1);__decorateClass([Stage25("onElicitResult",{filter:({state:{requestType}})=>requestType==="elicitResult"})],HandleSseFlow.prototype,"onElicitResult",1);__decorateClass([Stage25("onMessage",{filter:({state:{requestType}})=>requestType==="message"})],HandleSseFlow.prototype,"onMessage",1);HandleSseFlow=__decorateClass([FrontMcpFlow({name:name25,access:"authorized",inputSchema:httpInputSchema,outputSchema:httpOutputSchema,plan:plan25})],HandleSseFlow)}});import{internalZ as z115}from"@frontmcp/lazy-zod";import{RequestSchema}from"@frontmcp/protocol";var plan26,stateSchema23,name26,Stage26,HandleStatelessHttpFlow;var init_handle_stateless_http_flow=__esm({"libs/sdk/src/transport/flows/handle.stateless-http.flow.ts"(){"use strict";init_common();init_errors();init_ha_headers();init_transport_types();plan26={pre:["applyNodeHeaders","parseInput","router"],execute:["handleRequest"],post:[],finalize:["cleanup"]};stateSchema23=z115.object({token:z115.string().optional(),isAuthenticated:z115.boolean(),requestType:z115.enum(["initialize","message"]).optional()});name26="handle:stateless-http";({Stage:Stage26}=FlowHooksOf(name26));HandleStatelessHttpFlow=class extends FlowBase{name=name26;async applyNodeHeaders(){applyMachineIdHeader(this.rawInput.response)}async parseInput(){const{request:request2}=this.rawInput;const logger=this.scope.logger.child("HandleStatelessHttpFlow");const auth=request2[ServerRequestTokens.auth];const token=auth?.token;const isAuthenticated=!!token&&token.length>0;logger.verbose("parseInput",{isAuthenticated,hasToken:!!token});this.state.set(stateSchema23.parse({token:token||void 0,isAuthenticated}))}async router(){const{request:request2}=this.rawInput;const logger=this.scope.logger.child("HandleStatelessHttpFlow");const body=request2.body;const method=body?.method;if(method==="initialize"){this.state.set("requestType","initialize");logger.verbose("router: requestType=initialize, method=POST")}else if(method&&RequestSchema.safeParse(request2.body).success){this.state.set("requestType","message");logger.verbose(`router: requestType=message, method=${method}`)}else{logger.warn("router: invalid request, no valid method");this.respond(httpRespond.rpcError("Invalid Request"))}}async handleRequest(){const transportService=this.scope.transportService;if(!transportService){throw new TransportServiceNotAvailableError}const logger=this.scope.logger.child("HandleStatelessHttpFlow");const{request:request2,response}=this.rawInput;const{token,isAuthenticated,requestType}=this.state;logger.verbose(`handleRequest: using ${isAuthenticated?"authenticated":"anonymous"} stateless transport`);const transport=isAuthenticated&&token?await transportService.getOrCreateAuthenticatedStatelessTransport("stateless-http",token,response):await transportService.getOrCreateAnonymousStatelessTransport("stateless-http",response);if(!request2.headers["mcp-session-id"]){request2.headers["mcp-session-id"]=STATELESS_SESSION_ID;logger.verbose(`handleRequest: injected ${STATELESS_SESSION_ID} session ID`)}logger.verbose(`handleRequest: requestType=${requestType}, forwarding to transport`);try{if(requestType==="initialize"){await transport.initialize(request2,response)}else{await transport.handleRequest(request2,response)}}catch(error){logger.error("handleRequest: transport failed",{requestType,error:error instanceof Error?{name:error.name,message:error.message}:String(error)});throw error}this.handled()}};__decorateClass([Stage26("applyNodeHeaders")],HandleStatelessHttpFlow.prototype,"applyNodeHeaders",1);__decorateClass([Stage26("parseInput")],HandleStatelessHttpFlow.prototype,"parseInput",1);__decorateClass([Stage26("router")],HandleStatelessHttpFlow.prototype,"router",1);__decorateClass([Stage26("handleRequest")],HandleStatelessHttpFlow.prototype,"handleRequest",1);HandleStatelessHttpFlow=__decorateClass([FrontMcpFlow({name:name26,plan:plan26,access:"authorized",inputSchema:httpInputSchema,outputSchema:httpOutputSchema})],HandleStatelessHttpFlow)}});var EXT_APPS_ERROR_CODES;var init_ext_apps_types=__esm({"libs/sdk/src/ext-apps/ext-apps.types.ts"(){"use strict";EXT_APPS_ERROR_CODES={PARSE_ERROR:-32700,INVALID_REQUEST:-32600,METHOD_NOT_FOUND:-32601,INVALID_PARAMS:-32602,INTERNAL_ERROR:-32603,TOOL_NOT_FOUND:-32001,TOOL_EXECUTION_FAILED:-32002,NOT_SUPPORTED:-32003,CANCELLED:-32004}}});import{escapeControlCharacters as escapeControlCharacters5,isDevelopment as isDevelopment5}from"@frontmcp/utils";function createExtAppsMessageHandler(options){return new ExtAppsMessageHandler(options)}var MCP_LOG_LEVELS,ExtAppsMessageHandler,ExtAppsError,ExtAppsMethodNotFoundError,ExtAppsInvalidParamsError,ExtAppsNotSupportedError,ExtAppsToolNotFoundError;var init_ext_apps_handler=__esm({"libs/sdk/src/ext-apps/ext-apps.handler.ts"(){"use strict";init_errors();init_ext_apps_types();MCP_LOG_LEVELS={debug:"debug",info:"info",notice:"info",warning:"warn",error:"error",critical:"error",alert:"error",emergency:"error"};ExtAppsMessageHandler=class{context;hostCapabilities;logger;constructor(options){this.context=options.context;this.hostCapabilities=options.hostCapabilities||{};this.logger=options.context.logger.child("ExtAppsMessageHandler")}getHostCapabilities(){return{...this.hostCapabilities}}async handleRequest(request2){const{id,method,params}=request2;this.logger.verbose(`handleRequest: method=${escapeControlCharacters5(method)}, id=${escapeControlCharacters5(id)}`);try{const result=await this.routeMethod(method,params);return{jsonrpc:"2.0",id,result:result===void 0?{}:result}}catch(error){const errorMessage2=error instanceof Error?error.message:String(error);const errorCode2=this.getErrorCode(error);this.logger.warn(`handleRequest: method=${escapeControlCharacters5(method)} failed: ${escapeControlCharacters5(errorMessage2)}`);return{jsonrpc:"2.0",id,error:{code:errorCode2,message:this.widgetMessageOf(error),data:isDevelopment5()&&error instanceof Error?{stack:error.stack}:void 0}}}}async handleNotification(notification){const{method,params}=notification;if(method!=="notifications/message"&&method!=="ui/notifications/request-teardown"){this.logger.verbose(`handleNotification: ignoring method=${escapeControlCharacters5(method)}`);return}if(method==="ui/notifications/request-teardown"&&!this.context.close){this.logger.verbose("handleNotification: ignoring ui/notifications/request-teardown (no close callback)");return}try{await this.routeMethod(method,params)}catch(error){const errorMessage2=error instanceof Error?error.message:String(error);this.logger.warn(`handleNotification: method=${escapeControlCharacters5(method)} failed: ${escapeControlCharacters5(errorMessage2)}`)}}async routeMethod(method,params){if(params!==void 0&&(params===null||typeof params!=="object"||Array.isArray(params))){throw new ExtAppsInvalidParamsError("Invalid params: expected object")}const normalizedParams=params??{};switch(method){case"ui/initialize":return this.handleInitialize(normalizedParams);case"ui/callServerTool":return this.handleCallServerTool(normalizedParams);case"ui/update-model-context":return this.handleSpecUpdateModelContext(normalizedParams);case"ui/updateModelContext":return this.handleUpdateModelContext(normalizedParams);case"ui/open-link":case"ui/openLink":return this.handleOpenLink(normalizedParams);case"ui/request-display-mode":case"ui/setDisplayMode":return this.handleSetDisplayMode(normalizedParams);case"ui/notifications/request-teardown":case"ui/close":return this.handleClose(normalizedParams);case"notifications/message":return this.handleLogMessage(normalizedParams);case"ui/log":return this.handleLog(normalizedParams);case"ui/registerTool":return this.handleRegisterTool(normalizedParams);case"ui/unregisterTool":return this.handleUnregisterTool(normalizedParams);default:throw new ExtAppsMethodNotFoundError(`Unknown ext-apps method: ${method}`)}}handleInitialize(params){const{appInfo,protocolVersion}=params;this.logger.verbose(`handleInitialize: app=${escapeControlCharacters5(appInfo?.name||"unknown")} v${escapeControlCharacters5(appInfo?.version||"unknown")}, protocol=${escapeControlCharacters5(protocolVersion)}`);return{hostCapabilities:this.hostCapabilities,protocolVersion:protocolVersion||"2024-11-05"}}async handleCallServerTool(params){if(!this.hostCapabilities.serverToolProxy){throw new ExtAppsNotSupportedError("Server tool proxy not supported by host")}const{name:name59,arguments:args={}}=params;if(!name59||typeof name59!=="string"){throw new ExtAppsInvalidParamsError("Tool name is required")}this.logger.verbose(`handleCallServerTool: tool=${escapeControlCharacters5(name59)}`);return this.context.callTool(name59,args)}async handleUpdateModelContext(params){if(!this.hostCapabilities.modelContextUpdate){throw new ExtAppsNotSupportedError("Model context update not advertised by host")}if(!this.context.updateModelContext){throw new ExtAppsNotSupportedError("Model context update not supported by host")}const{context,merge=true}=params;this.logger.verbose(`handleUpdateModelContext: merge=${merge}`);await this.context.updateModelContext(context,merge)}async handleSpecUpdateModelContext(params){const{content,structuredContent}=params;if(content!==void 0&&!Array.isArray(content)){throw new ExtAppsInvalidParamsError("content must be an array of content blocks")}if(structuredContent!==void 0&&(typeof structuredContent!=="object"||structuredContent===null||Array.isArray(structuredContent))){throw new ExtAppsInvalidParamsError("structuredContent must be an object")}const context={};if(content!==void 0)context.content=content;if(structuredContent!==void 0)context.structuredContent=structuredContent;await this.handleUpdateModelContext({context,merge:false})}async handleOpenLink(params){if(!this.hostCapabilities.openLink){throw new ExtAppsNotSupportedError("Open link not advertised by host")}if(!this.context.openLink){throw new ExtAppsNotSupportedError("Open link not supported by host")}const{url}=params;if(!url||typeof url!=="string"){throw new ExtAppsInvalidParamsError("URL is required")}let parsed;try{parsed=new URL(url)}catch{throw new ExtAppsInvalidParamsError("Invalid URL format")}const allowedSchemes=["http:","https:"];if(!allowedSchemes.includes(parsed.protocol)){throw new ExtAppsInvalidParamsError(`URL scheme '${parsed.protocol}' not allowed. Only http: and https: are permitted.`)}this.logger.verbose(`handleOpenLink: url=${escapeControlCharacters5(url)}`);await this.context.openLink(url)}async handleSetDisplayMode(params){const{mode}=params;if(!mode||!["inline","fullscreen","pip"].includes(mode)){throw new ExtAppsInvalidParamsError("Invalid display mode. Must be inline, fullscreen, or pip")}if(this.hostCapabilities.displayModes&&!this.hostCapabilities.displayModes.includes(mode)){throw new ExtAppsNotSupportedError(`Display mode '${mode}' not advertised by host`)}if(!this.context.setDisplayMode){throw new ExtAppsNotSupportedError("Display mode change not supported by host")}this.logger.verbose(`handleSetDisplayMode: mode=${escapeControlCharacters5(mode)}`);await this.context.setDisplayMode(mode);return{mode}}async handleClose(params){if(!this.context.close){throw new ExtAppsNotSupportedError("Widget close not supported by host")}const{reason}=params;this.logger.verbose(`handleClose: reason=${escapeControlCharacters5(reason||"none")}`);await this.context.close(reason)}async handleLog(params){if(!this.hostCapabilities.logging){throw new ExtAppsNotSupportedError("Logging not supported by host")}const{level,message,data}=params;if(!message||typeof message!=="string"){throw new ExtAppsInvalidParamsError("Log message is required")}const validLevels=["debug","info","warn","error"];if(level&&!validLevels.includes(level)){throw new ExtAppsInvalidParamsError(`Invalid log level '${level}'. Must be one of: ${validLevels.join(", ")}`)}this.writeWidgetLog(level??"info",message,data)}async handleLogMessage(params){if(!this.hostCapabilities.logging){throw new ExtAppsNotSupportedError("Logging not supported by host")}const{level,logger,data}=params;const serverLevel=Object.hasOwn(MCP_LOG_LEVELS,level)?MCP_LOG_LEVELS[level]:void 0;if(!serverLevel){throw new ExtAppsInvalidParamsError(`Invalid log level '${level}'. Must be one of: ${Object.keys(MCP_LOG_LEVELS).join(", ")}`)}if(typeof data==="string"){this.writeWidgetLog(serverLevel,data,void 0)}else{this.writeWidgetLog(serverLevel,logger??"widget log",data)}}writeWidgetLog(level,text,data){const widgetLogger=this.logger.child(`Widget:${this.context.sessionId}`);const message=escapeControlCharacters5(text);switch(level){case"debug":widgetLogger.verbose(message,data);break;case"info":widgetLogger.info(message,data);break;case"warn":widgetLogger.warn(message,data);break;case"error":widgetLogger.error(message,data);break;default:widgetLogger.info(message,data)}}async handleRegisterTool(params){if(!this.hostCapabilities.widgetTools){throw new ExtAppsNotSupportedError("Widget tools not advertised by host")}if(!this.context.registerTool){throw new ExtAppsNotSupportedError("Widget tool registration not supported by host")}const{name:name59,description,inputSchema:inputSchema53}=params;if(!name59||typeof name59!=="string"){throw new ExtAppsInvalidParamsError("Tool name is required")}if(!description||typeof description!=="string"){throw new ExtAppsInvalidParamsError("Tool description is required")}if(!inputSchema53||typeof inputSchema53!=="object"||Array.isArray(inputSchema53)){throw new ExtAppsInvalidParamsError("Tool input schema must be a non-null object")}this.logger.verbose(`handleRegisterTool: name=${escapeControlCharacters5(name59)}`);await this.context.registerTool(name59,description,inputSchema53)}async handleUnregisterTool(params){if(!this.hostCapabilities.widgetTools){throw new ExtAppsNotSupportedError("Widget tools not advertised by host")}if(!this.context.unregisterTool){throw new ExtAppsNotSupportedError("Widget tool unregistration not supported by host")}const{name:name59}=params;if(!name59||typeof name59!=="string"){throw new ExtAppsInvalidParamsError("Tool name is required")}this.logger.verbose(`handleUnregisterTool: name=${escapeControlCharacters5(name59)}`);await this.context.unregisterTool(name59)}widgetMessageOf(error){if(error instanceof ExtAppsError||isDevelopment5())return error instanceof Error?error.message:String(error);return toMcpError(error).getPublicMessage()}getErrorCode(error){if(error instanceof ExtAppsMethodNotFoundError){return EXT_APPS_ERROR_CODES.METHOD_NOT_FOUND}if(error instanceof ExtAppsInvalidParamsError){return EXT_APPS_ERROR_CODES.INVALID_PARAMS}if(error instanceof ExtAppsNotSupportedError){return EXT_APPS_ERROR_CODES.NOT_SUPPORTED}if(error instanceof ExtAppsToolNotFoundError){return EXT_APPS_ERROR_CODES.TOOL_NOT_FOUND}return EXT_APPS_ERROR_CODES.INTERNAL_ERROR}};ExtAppsError=class extends Error{constructor(message){super(message);this.name="ExtAppsError"}};ExtAppsMethodNotFoundError=class extends ExtAppsError{constructor(message){super(message);this.name="ExtAppsMethodNotFoundError"}};ExtAppsInvalidParamsError=class extends ExtAppsError{constructor(message){super(message);this.name="ExtAppsInvalidParamsError"}};ExtAppsNotSupportedError=class extends ExtAppsError{constructor(message){super(message);this.name="ExtAppsNotSupportedError"}};ExtAppsToolNotFoundError=class extends ExtAppsError{constructor(message){super(message);this.name="ExtAppsToolNotFoundError"}}}});var init_ext_apps2=__esm({"libs/sdk/src/ext-apps/index.ts"(){"use strict";init_ext_apps_types();init_ext_apps_handler()}});import{internalZ as z116}from"@frontmcp/lazy-zod";import{CallToolResultSchema as CallToolResultSchema4,ElicitResultSchema as ElicitResultSchema3,RequestSchema as RequestSchema2}from"@frontmcp/protocol";function resolveStreamableHttpSession(params){const{rawHeader,authorizationSession,createSession}=params;const rawMcpSessionHeader=typeof rawHeader==="string"?rawHeader:void 0;const mcpSessionHeader=validateMcpSessionHeader(rawMcpSessionHeader);if(rawHeader!==void 0&&!mcpSessionHeader){return{responded404:true,createdNew:false}}if(mcpSessionHeader){if(authorizationSession?.id===mcpSessionHeader){return{session:authorizationSession,createdNew:false,responded404:false}}return{responded404:true,createdNew:false}}if(authorizationSession){return{session:authorizationSession,createdNew:false,responded404:false}}return{session:createSession(),createdNew:true,responded404:false}}function classifyStreamableHttpRequest(params){const{method,body}=params;if(method.toUpperCase()==="GET"){return{requestType:"sseListener"}}const jsonRpcMethod=body?.method;if(jsonRpcMethod==="initialize"){return{requestType:"initialize"}}if(typeof jsonRpcMethod==="string"&&(jsonRpcMethod.startsWith("ui/")||jsonRpcMethod==="notifications/message")){return{requestType:"extApps"}}if(ElicitResultSchema3.safeParse(body?.result).success){return{requestType:"elicitResult"}}if(jsonRpcMethod&&RequestSchema2.safeParse(body).success){return{requestType:"message"}}return{error:"Invalid Request"}}function syncStreamableHttpAuthorizationSession(authorization,session){if(!authorization.session){authorization.session=session}}function resetInitializedTransportForReinit(transport){if(!transport.isInitialized){return true}transport.resetForReinitialization();transport.reregisterServer();return!transport.isInitialized}function buildReinitFailedResponse(sessionId,requestId){return httpRespond.rpcError(`Could not re-initialize session "${sessionId}". It is stuck in an initialized state \u2014 terminate it with an HTTP DELETE to the MCP endpoint (including the mcp-session-id header), or reconnect without the stored mcp-session-id to start a fresh session.`,requestId)}async function lookupStreamableHttpTransport(params){const{transportService,token,sessionId,response}=params;const inMemoryTransport=await transportService.getTransporter("streamable-http",token,sessionId);if(inMemoryTransport){return{kind:"transport",source:"memory",transport:inMemoryTransport}}let recreationError;try{const storedSession=await transportService.getStoredSession("streamable-http",token,sessionId);if(storedSession){const recreatedTransport=await transportService.recreateTransporter("streamable-http",token,sessionId,storedSession,response);if(recreatedTransport){return{kind:"transport",source:"redis",transport:recreatedTransport}}}}catch(error){recreationError=error}const wasCreated=await transportService.wasSessionCreatedAsync("streamable-http",token,sessionId);if(wasCreated){return{kind:"session-expired",recreationError}}return{kind:"session-not-initialized",recreationError}}function sessionIdForLog(sessionId){return typeof sessionId==="string"?sessionId.slice(0,20):void 0}function errorMessageForLog(error,sessionId){const message=error instanceof Error?error.message:String(error);return sessionId?message.replaceAll(sessionId,`${sessionIdForLog(sessionId)}...`):message}var plan27,stateSessionSchema2,stateSchema24,name27,Stage27,HandleStreamableHttpFlow;var init_handle_streamable_http_flow=__esm({"libs/sdk/src/transport/flows/handle.streamable-http.flow.ts"(){"use strict";init_session_id_utils();init_common();init_errors();init_ext_apps2();init_ha_headers();init_skill_mode_utils();init_mcp_surface();plan27={pre:["applyNodeHeaders","parseInput","router"],execute:["onInitialize","onMessage","onElicitResult","onSseListener","onExtApps"],post:[],finalize:["cleanup"]};stateSessionSchema2=z116.object({id:z116.string(),payload:z116.object({nodeId:z116.string(),authSig:z116.string(),uuid:z116.string().uuid(),iat:z116.number(),protocol:z116.enum(["legacy-sse","sse","streamable-http","stateful-http","stateless-http"]).optional(),isPublic:z116.boolean().optional(),platformType:z116.enum(["openai","claude","claude-code","codex","gemini","cursor","continue","cody","generic-mcp","ext-apps","unknown"]).optional()}).optional()});stateSchema24=z116.object({token:z116.string(),session:stateSessionSchema2,requestType:z116.enum(["initialize","message","elicitResult","sseListener","extApps"]).optional()});name27="handle:streamable-http";({Stage:Stage27}=FlowHooksOf(name27));HandleStreamableHttpFlow=class extends FlowBase{name=name27;async applyNodeHeaders(){applyMachineIdHeader(this.rawInput.response)}async parseInput(){const{request:request2}=this.rawInput;const authorization=request2[ServerRequestTokens.auth];const{token}=authorization;const logger=this.scopeLogger.child("handle:streamable-http:parseInput");const body=request2.body;const isInitialize2=body?.method==="initialize";const createSession=()=>{const query=request2.query;const skillsOnlyMode=detectSkillsOnlyMode(query);return createSessionId("streamable-http",token,{userAgent:request2.headers?.["user-agent"],platformDetectionConfig:this.scope.metadata.transport?.platformDetection,skillsOnlyMode})};let sessionResolution;if(isInitialize2){if(authorization.session?.id){sessionResolution={session:authorization.session,createdNew:false,responded404:false}}else{sessionResolution={session:createSession(),createdNew:true,responded404:false}}}else{sessionResolution=resolveStreamableHttpSession({rawHeader:request2.headers?.["mcp-session-id"],authorizationSession:authorization.session,createSession})}if(sessionResolution.responded404||!sessionResolution.session){logger.warn("parseInput: mcp-session-id is not a session this server verified");this.respond(httpRespond.sessionNotFound("invalid session id"));return}const session=sessionResolution.session;this.state.set(stateSchema24.parse({token,session}));logger.verbose("parseInput: session resolved",{sessionId:session.id?.slice(0,20)})}async router(){const{request:request2}=this.rawInput;const logger=this.scopeLogger.child("handle:streamable-http:router");const classification=classifyStreamableHttpRequest({method:request2.method,body:request2.body});if("error"in classification){logger.warn("router: invalid request, no valid method");this.respond(httpRespond.rpcError("Invalid Request"));return}this.state.set("requestType",classification.requestType);if(classification.requestType==="sseListener"){logger.verbose("router: requestType=sseListener, method=GET")}else if(classification.requestType==="initialize"){logger.verbose("router: requestType=initialize, method=POST")}else if(classification.requestType==="extApps"){const method=request2.body?.method;logger.verbose(`router: requestType=extApps, method=${method}`)}else if(classification.requestType==="elicitResult"){logger.verbose("router: requestType=elicitResult, method=POST")}else{const method=request2.body?.method;logger.verbose(`router: requestType=message, method=${method}`)}}async onInitialize(){const transportService=this.scope.transportService;if(!transportService){throw new TransportServiceNotAvailableError}const logger=this.scope.logger.child("handle:streamable-http:onInitialize");const{request:request2,response}=this.rawInput;const{token,session}=this.state.required;logger.info("onInitialize: creating transport",{sessionId:session.id?.slice(0,20),hasToken:!!token,tokenPrefix:token?.slice(0,10)});try{const authorization=request2[ServerRequestTokens.auth];syncStreamableHttpAuthorizationSession(authorization,session);const transport=await transportService.createTransporter("streamable-http",token,session.id,response);const isReinitialize=!!request2[ServerRequestTokens.reinitialize];if(transport.isInitialized){logger.info("onInitialize: transport already initialized, resetting for re-initialization",{sessionId:session.id?.slice(0,20),reinitialize:isReinitialize});if(!resetInitializedTransportForReinit(transport)){const requestId=request2.body?.id??null;logger.error("onInitialize: transport still initialized after reset \u2014 cannot re-initialize",{sessionId:session.id?.slice(0,20)});this.respond(buildReinitFailedResponse(session.id,requestId));return}}applyNodeAffinity(response,request2);logger.info("onInitialize: transport created, calling initialize");await transport.initialize(request2,response);logger.info("onInitialize: completed successfully");this.handled()}catch(error){if(error instanceof FlowControl){throw error}logger.error("onInitialize: failed",{error:error instanceof Error?error.message:String(error),stack:error instanceof Error?error.stack:void 0});throw error}}async onElicitResult(){const transportService=this.scope.transportService;if(!transportService){throw new TransportServiceNotAvailableError}const logger=this.scopeLogger.child("handle:streamable-http:onElicitResult");const{request:request2,response}=this.rawInput;const{token,session}=this.state.required;logger.verbose("onElicitResult: starting",{sessionId:session.id?.slice(0,20),hasToken:!!token});let transport=await transportService.getTransporter("streamable-http",token,session.id);if(!transport){try{logger.verbose("onElicitResult: transport not in memory, checking stored session",{sessionId:session.id?.slice(0,20)});const storedSession=await transportService.getStoredSession("streamable-http",token,session.id);if(storedSession){logger.verbose("onElicitResult: recreating transport from stored session",{sessionId:session.id?.slice(0,20),createdAt:storedSession.createdAt,initialized:storedSession.initialized});transport=await transportService.recreateTransporter("streamable-http",token,session.id,storedSession,response)}}catch(error){logger.warn("onElicitResult: failed to recreate transport from stored session",{sessionId:session.id?.slice(0,20),error:errorMessageForLog(error,session.id)})}}if(!transport){logger.warn("onElicitResult: transport not found",{sessionId:session.id?.slice(0,20)});this.respond(httpRespond.sessionExpired("session not found"));return}await transport.handleRequest(request2,response);if(!response.writableEnded){response.status(202).json({jsonrpc:"2.0",result:{}})}this.handled()}async onMessage(){const transportService=this.scope.transportService;if(!transportService){throw new TransportServiceNotAvailableError}const logger=this.scopeLogger.child("handle:streamable-http:onMessage");const{request:request2,response}=this.rawInput;const{token,session}=this.state.required;logger.verbose("onMessage: starting",{sessionId:session.id?.slice(0,20),hasToken:!!token});const transportLookup=await lookupStreamableHttpTransport({transportService,token,sessionId:session.id,response});if(transportLookup.kind!=="transport"){const body=request2.body;if(transportLookup.recreationError){logger.warn("Failed to recreate transport from stored session",{sessionId:session.id?.slice(0,20),error:errorMessageForLog(transportLookup.recreationError,session.id)})}if(transportLookup.kind==="session-expired"){logger.info("Session expired - client should re-initialize",{sessionId:session.id?.slice(0,20),tokenHash:token.slice(0,8),method:body?.["method"],requestId:body?.["id"],mcpSessionId:sessionIdForLog(request2.headers?.["mcp-session-id"])});this.respond(httpRespond.sessionExpired("session expired"))}else{logger.warn("Session not initialized - client attempted request without initializing",{sessionId:session.id?.slice(0,20),tokenHash:token.slice(0,8),method:body?.["method"],requestId:body?.["id"],mcpSessionId:sessionIdForLog(request2.headers?.["mcp-session-id"]),userAgent:request2.headers?.["user-agent"]?.slice(0,50)});this.respond(httpRespond.sessionNotFound("session not initialized"))}return}const transport=transportLookup.transport;logger.verbose("onMessage: transport resolved",{source:transportLookup.source});try{await transport.handleRequest(request2,response);this.handled()}catch(error){if(!(error instanceof FlowControl)){const body=request2.body;logger.error("handleRequest failed",{error:error instanceof Error?{name:error.name,message:error.message,stack:error.stack}:error,method:body?.["method"],id:body?.["id"],sessionId:session.id?.slice(0,20)})}throw error}}async onSseListener(){const transportService=this.scope.transportService;if(!transportService){throw new TransportServiceNotAvailableError}const logger=this.scopeLogger.child("handle:streamable-http:onSseListener");const{request:request2,response}=this.rawInput;const{token,session}=this.state.required;let transport=await transportService.getTransporter("streamable-http",token,session.id);if(!transport){try{const storedSession=await transportService.getStoredSession("streamable-http",token,session.id);if(storedSession){logger.info("Recreating transport from Redis session for SSE listener",{sessionId:session.id?.slice(0,20),createdAt:storedSession.createdAt});transport=await transportService.recreateTransporter("streamable-http",token,session.id,storedSession,response)}}catch(error){logger.warn("Failed to recreate transport from stored session for SSE listener",{sessionId:session.id?.slice(0,20),error:errorMessageForLog(error,session.id)})}}if(!transport){logger.warn("onSseListener: transport not found",{sessionId:session.id?.slice(0,20)});this.respond(httpRespond.notFound("Session not found"));return}await transport.handleRequest(request2,response);this.handled()}async onExtApps(){const transportService=this.scope.transportService;if(!transportService){throw new TransportServiceNotAvailableError}const logger=this.scopeLogger.child("handle:streamable-http:onExtApps");const{request:request2,response}=this.rawInput;const{token,session}=this.state.required;const message=request2.body;const isNotification=!("id"in message);if(this.scope.metadata.extApps?.enabled===false){const rpc=request2.body;logger.verbose("onExtApps: ext-apps disabled by config",{method:rpc?.method});if(isNotification){response.status(202).end();this.handled();return}response.status(200).json({jsonrpc:"2.0",id:rpc?.id??null,error:{code:-32601,message:`Method not found: ${rpc?.method}`}});this.handled();return}logger.verbose("onExtApps: starting",{sessionId:session.id?.slice(0,20),method:request2.body?.method});let transport=await transportService.getTransporter("streamable-http",token,session.id);if(!transport){try{logger.verbose("onExtApps: transport not in memory, checking stored session",{sessionId:session.id?.slice(0,20)});const storedSession=await transportService.getStoredSession("streamable-http",token,session.id);if(storedSession){logger.verbose("onExtApps: recreating transport from stored session",{sessionId:session.id?.slice(0,20),createdAt:storedSession.createdAt,initialized:storedSession.initialized});transport=await transportService.recreateTransporter("streamable-http",token,session.id,storedSession,response)}}catch(error){logger.warn("onExtApps: failed to recreate transport from stored session",{sessionId:session.id?.slice(0,20),error:errorMessageForLog(error,session.id)})}}if(!transport){const wasCreated=await transportService.wasSessionCreatedAsync("streamable-http",token,session.id);if(wasCreated){logger.info("onExtApps: session expired - client should re-initialize",{sessionId:session.id?.slice(0,20)});this.respond(httpRespond.sessionExpired("session expired"))}else{logger.warn("onExtApps: session not initialized - client attempted request without initializing",{sessionId:session.id?.slice(0,20)});this.respond(httpRespond.sessionNotFound("session not initialized"))}return}const configuredCapabilities=this.scope.metadata.extApps?.hostCapabilities;const hostCapabilities={serverToolProxy:configuredCapabilities?.serverToolProxy??true,logging:configuredCapabilities?.logging??true,...configuredCapabilities,openLink:false,modelContextUpdate:false,widgetTools:false};const unsupported=["openLink","modelContextUpdate","widgetTools"].filter(key=>configuredCapabilities?.[key]===true);if(unsupported.length>0){logger.warn(`onExtApps: extApps.hostCapabilities ${unsupported.join(", ")} are not supported yet and are not advertised`)}const{user,scopes,claims:claims3}=request2[ServerRequestTokens.auth];const handler=createExtAppsMessageHandler({context:{sessionId:session.id,logger:this.scope.logger,callTool:async(name59,args)=>{const result=await this.scope.runFlow("tools:call-tool",{request:{method:"tools/call",params:{name:name59,arguments:args}},ctx:{authInfo:{sessionId:session.id,sessionIdPayload:session.payload,token,user,scopes:Array.isArray(scopes)?[...scopes]:[],...claims3?{claims:structuredClone(claims3)}:{},clientId:user?.sub??""},surface:mcpRequestSurface(this.scope),_skipUI:true}});const parsed=CallToolResultSchema4.safeParse(result);if(parsed.success){return parsed.data}throw new InternalMcpError("Tool call returned invalid result format")}},hostCapabilities});if(isNotification){await handler.handleNotification(message);response.status(202).end();this.handled();return}const jsonRpcResponse=await handler.handleRequest(message);response.status(200).json(jsonRpcResponse);this.handled()}};__decorateClass([Stage27("applyNodeHeaders")],HandleStreamableHttpFlow.prototype,"applyNodeHeaders",1);__decorateClass([Stage27("parseInput")],HandleStreamableHttpFlow.prototype,"parseInput",1);__decorateClass([Stage27("router")],HandleStreamableHttpFlow.prototype,"router",1);__decorateClass([Stage27("onInitialize",{filter:({state:{requestType}})=>requestType==="initialize"})],HandleStreamableHttpFlow.prototype,"onInitialize",1);__decorateClass([Stage27("onElicitResult",{filter:({state:{requestType}})=>requestType==="elicitResult"})],HandleStreamableHttpFlow.prototype,"onElicitResult",1);__decorateClass([Stage27("onMessage",{filter:({state:{requestType}})=>requestType==="message"})],HandleStreamableHttpFlow.prototype,"onMessage",1);__decorateClass([Stage27("onSseListener",{filter:({state:{requestType}})=>requestType==="sseListener"})],HandleStreamableHttpFlow.prototype,"onSseListener",1);__decorateClass([Stage27("onExtApps",{filter:({state:{requestType}})=>requestType==="extApps"})],HandleStreamableHttpFlow.prototype,"onExtApps",1);HandleStreamableHttpFlow=__decorateClass([FrontMcpFlow({name:name27,plan:plan27,access:"authorized",inputSchema:httpInputSchema,outputSchema:httpOutputSchema})],HandleStreamableHttpFlow)}});import{base64Decode as base64Decode4,base64Encode as base64Encode3}from"@frontmcp/utils";function normalizeRequestHeaders(headers){const out={};if(!headers)return out;for(const[name59,value]of Object.entries(headers)){if(typeof value==="string")out[name59.toLowerCase()]=value;else if(Array.isArray(value))out[name59.toLowerCase()]=value.map(String);else if(typeof value==="number")out[name59.toLowerCase()]=String(value)}return out}function serializeRelayRequest(request2){const raw=request2;const url=typeof raw.originalUrl==="string"&&raw.originalUrl?raw.originalUrl:raw.url??"/";const queryIndex=url.indexOf("?");const path4=typeof raw.path==="string"&&raw.path?raw.path:queryIndex>=0?url.slice(0,queryIndex):url;return{method:(raw.method??"GET").toUpperCase(),url,path:path4,headers:normalizeRequestHeaders(raw.headers),query:raw.query&&typeof raw.query==="object"?{...raw.query}:{},...raw.body!==void 0?{body:raw.body}:{},...typeof raw.protocol==="string"?{protocol:raw.protocol}:{},...raw.socket?.encrypted?{encrypted:true}:{},...typeof raw.socket?.remoteAddress==="string"?{peerAddress:raw.socket.remoteAddress}:{}}}function relayedFrom(request2){const value=request2[ServerRequestTokens.relayedFrom];return typeof value==="string"?value:void 0}function isRelayedRequest(request2){return relayedFrom(request2)!==void 0}function createRelayedServerRequest(relayed,sourceNodeId){const headers=normalizeRequestHeaders(relayed.headers);const rawHeaders=[];for(const[name59,value]of Object.entries(headers)){for(const item of Array.isArray(value)?value:[value])rawHeaders.push(name59,item)}const socket={remoteAddress:relayed.peerAddress,encrypted:relayed.encrypted===true,destroyed:false,destroy(){socket.destroyed=true},destroySoon(){socket.destroyed=true}};const request2=Object.assign(new RelayEmitter,{method:relayed.method,url:relayed.url,originalUrl:relayed.url,path:relayed.path,headers,rawHeaders,query:relayed.query??{},body:relayed.body,protocol:relayed.protocol??(socket.encrypted?"https":"http"),secure:(relayed.protocol??(socket.encrypted?"https":"http"))==="https",httpVersion:"1.1",httpVersionMajor:1,httpVersionMinor:1,complete:true,readable:false,readableEnded:false,aborted:false,errored:null,destroyed:false,socket,connection:socket,resume(){if(!request2.readableEnded){request2.readableEnded=true;queueMicrotask(()=>request2.emit("end"))}return request2},pause(){return request2},destroy(){request2.destroyed=true}});if(relayed.body!==void 0&&typeof Buffer!=="undefined"){const text=typeof relayed.body==="string"?relayed.body:JSON.stringify(relayed.body);Object.assign(request2,{rawBody:Buffer.from(text)})}request2[ServerRequestTokens.relayedFrom]=sourceNodeId;return request2}function encodeBytes(bytes){if(bytes.byteLength===0)return void 0;try{return{data:utf8Decoder.decode(bytes),encoding:"utf8"}}catch{return{data:base64Encode3(bytes),encoding:"base64"}}}function encodeRelayChunk(chunk,encoding){if(chunk===void 0||chunk===null)return void 0;if(typeof chunk==="string"){if(chunk.length===0)return void 0;if(encoding==="base64")return{data:chunk,encoding:"base64"};return{data:chunk,encoding:"utf8"}}if(chunk instanceof Uint8Array)return encodeBytes(chunk);if(chunk instanceof ArrayBuffer)return encodeBytes(new Uint8Array(chunk));const text=String(chunk);return text.length>0?{data:text,encoding:"utf8"}:void 0}function decodeRelayChunk(chunk){return chunk.encoding==="base64"?base64Decode4(chunk.data):chunk.data}function isFlatHeaderList(headers){return Array.isArray(headers)}var RelayEmitter,utf8Decoder,HOP_BY_HOP_HEADERS2,RelayServerResponse;var init_relay_http=__esm({"libs/sdk/src/transport/relay/relay-http.ts"(){"use strict";init_common();init_http_location_utils();RelayEmitter=class{listeners=new Map;on(event,listener){const list=this.listeners.get(event)??[];list.push(listener);this.listeners.set(event,list);return this}addListener(event,listener){return this.on(event,listener)}once(event,listener){const wrapper=(...args)=>{this.off(event,wrapper);listener(...args)};wrapper.listener=listener;return this.on(event,wrapper)}off(event,listener){const list=this.listeners.get(event);if(!list)return this;const index=list.findIndex(l=>l===listener||l.listener===listener);if(index>=0)list.splice(index,1);if(list.length===0)this.listeners.delete(event);return this}removeListener(event,listener){return this.off(event,listener)}removeAllListeners(event){if(event===void 0)this.listeners.clear();else this.listeners.delete(event);return this}listenerCount(event){return this.listeners.get(event)?.length??0}emit(event,...args){const list=this.listeners.get(event);if(!list||list.length===0)return false;for(const listener of[...list])listener(...args);return true}};utf8Decoder=new TextDecoder("utf-8",{fatal:true,ignoreBOM:true});HOP_BY_HOP_HEADERS2=new Set(["connection","keep-alive","transfer-encoding","upgrade"]);RelayServerResponse=class extends RelayEmitter{constructor(sink){super();this.sink=sink}sink;statusCode=200;statusMessage="";headersSent=false;writableEnded=false;writableFinished=false;destroyed=false;headerMap=new Map;get writable(){return!this.writableEnded&&!this.destroyed}get finished(){return this.writableEnded}setHeader(name59,value){if(this.headersSent)return this;this.headerMap.set(name59.toLowerCase(),Array.isArray(value)?value.map(String):String(value));return this}getHeader(name59){return this.headerMap.get(name59.toLowerCase())}getHeaders(){return Object.fromEntries(this.headerMap)}getHeaderNames(){return[...this.headerMap.keys()]}hasHeader(name59){return this.headerMap.has(name59.toLowerCase())}removeHeader(name59){if(!this.headersSent)this.headerMap.delete(name59.toLowerCase())}writeHead(statusCode,reasonOrHeaders,maybeHeaders){if(this.headersSent)return this;this.statusCode=statusCode;let headers;if(typeof reasonOrHeaders==="string"){this.statusMessage=reasonOrHeaders;headers=maybeHeaders}else{headers=reasonOrHeaders}if(isFlatHeaderList(headers)){for(let i=0;i+1<headers.length;i+=2)this.setHeader(headers[i],headers[i+1])}else if(headers){for(const[name59,value]of Object.entries(headers)){if(value!==void 0)this.setHeader(name59,value)}}this.sendHead();return this}flushHeaders(){this.sendHead()}status(code){this.statusCode=code;return this}json(body){if(!this.hasHeader("content-type"))this.setHeader("Content-Type","application/json; charset=utf-8");return this.end(JSON.stringify(body))}send(body){if(body===void 0||body===null)return this.end();if(typeof body==="string"){if(!this.hasHeader("content-type"))this.setHeader("Content-Type","text/html; charset=utf-8");return this.end(body)}if(body instanceof Uint8Array){if(!this.hasHeader("content-type"))this.setHeader("Content-Type","application/octet-stream");return this.end(body)}return this.json(body)}redirect(statusOrUrl,maybeUrl){const status=typeof statusOrUrl==="number"?statusOrUrl:302;const location=typeof statusOrUrl==="string"?statusOrUrl:maybeUrl??"/";this.statusCode=status;this.setHeader("Location",toLocationHeader(location));return this.end()}write(chunk,encodingOrCallback,callback){const cb=typeof encodingOrCallback==="function"?encodingOrCallback:callback;if(!this.writable)return false;this.sendHead();const encoded=encodeRelayChunk(chunk,typeof encodingOrCallback==="string"?encodingOrCallback:void 0);if(encoded)this.sink.data(encoded);if(typeof cb==="function")cb();return true}end(chunk,encodingOrCallback,callback){let data=chunk;let encoding=encodingOrCallback;let cb=callback;if(typeof data==="function"){cb=data;data=void 0;encoding=void 0}else if(typeof encoding==="function"){cb=encoding;encoding=void 0}if(this.writableEnded||this.destroyed){if(typeof cb==="function")cb();return this}this.sendHead();const encoded=encodeRelayChunk(data,typeof encoding==="string"?encoding:void 0);if(encoded)this.sink.data(encoded);this.writableEnded=true;this.sink.end();this.writableFinished=true;this.emit("finish");this.emit("close");if(typeof cb==="function")cb();return this}destroy(error){if(this.destroyed)return this;this.destroyed=true;if(error&&this.listenerCount("error")>0)this.emit("error",error);if(!this.writableFinished)this.emit("close");return this}cork(){}uncork(){}setTimeout(){return this}asServerResponse(){return this}sendHead(){if(this.headersSent||this.destroyed)return;this.headersSent=true;const headers={};for(const[name59,value]of this.headerMap){if(!HOP_BY_HOP_HEADERS2.has(name59))headers[name59]=value}this.sink.head(this.statusCode,headers)}}}});var LocalTransporter;var init_transport_local=__esm({"libs/sdk/src/transport/transport.local.ts"(){"use strict";init_transport_errors();init_transport_sse_adapter();init_transport_streamable_http_adapter();init_transport_error();LocalTransporter=class{constructor(scope,key,res,onDispose){this.onDispose=onDispose;this.type=key.type;this.tokenHash=key.tokenHash;const defaultOnDispose=()=>{};switch(this.type){case"sse":this.adapter=new TransportSSEAdapter(scope,key,onDispose??defaultOnDispose,res);break;case"streamable-http":case"stateless-http":this.adapter=new TransportStreamableHttpAdapter(scope,key,onDispose??defaultOnDispose,res);break;default:throw new UnsupportedTransportTypeError(this.type)}}onDispose;type;tokenHash;sessionId;adapter;ping(timeoutMs){throw new MethodNotImplementedError("LocalTransporter","ping")}async handleRequest(req,res){try{await this.adapter.handleRequest(req,res)}catch(err){console.error("MCP POST error:",err instanceof Error?err.message:"Unknown error");res.status(500).json(rpcError("Internal error"))}}async ready(){return this.adapter.ready}async initialize(req,res){try{await this.adapter.ready;return this.adapter.initialize(req,res)}catch(err){console.error("MCP POST error:",err instanceof Error?err.message:"Unknown error");res.status(500).json(rpcError("Internal error"))}}get isInitialized(){return this.adapter.isInitialized}markAsInitialized(){this.adapter.markAsInitialized()}resetForReinitialization(){this.adapter.resetForReinitialization()}reregisterServer(){this.adapter.reregisterServer()}async destroy(reason){try{await this.adapter.destroy(reason)}finally{this.onDispose?.()}}}}});var RemoteTransporter;var init_transport_remote=__esm({"libs/sdk/src/transport/transport.remote.ts"(){"use strict";init_transport_errors();init_transport_error();RemoteTransporter=class{constructor(key,bus,location){this.key=key;this.bus=bus;this.location=location;this.type=key.type;this.tokenHash=key.tokenHash;this.sessionId=key.sessionId}key;bus;location;type;tokenHash;sessionId;get ownerNodeId(){return this.location.nodeId}ping(_timeoutMs){throw new MethodNotImplementedError("RemoteTransporter","ping")}initialize(req,res){return this.relay(req,res)}handleRequest(req,res){return this.relay(req,res)}async destroy(reason){await this.bus.destroyRemote(this.key,reason)}get isInitialized(){return true}markAsInitialized(){}resetForReinitialization(){}reregisterServer(){}async relay(req,res){try{await this.bus.proxyRequest(this.location,this.sessionId,req,res)}catch(error){if(!(error instanceof SessionOwnerUnreachableError)||res.headersSent)throw error;const requestId=req.body?.id??null;res.setHeader("Retry-After",String(error.retryAfterSeconds));res.status(error.statusCode).json(rpcError(error.getPublicMessage(),requestId))}}}}});import{getMachineId as getMachineId4,sha256Hex as sha256Hex20}from"@frontmcp/utils";var SESSION_STORE_RETRY_BASE_MS,SESSION_STORE_RETRY_MAX_MS,DEFAULT_SESSION_CHECK_TIMEOUT_MS,BUS_REFRESH_INTERVAL_MS,MAX_ROUTABLE_SESSION_ID_LENGTH,RELAYABLE_TYPES,TransportService;var init_transport_registry=__esm({"libs/sdk/src/transport/transport.registry.ts"(){"use strict";init_session_store_factory();init_session_id_utils();init_auth_info_utils();init_transport_errors();init_transport_sse_adapter();init_transport_streamable_http_adapter();init_handle_mcp_20260728_flow();init_handle_sse_flow();init_handle_stateless_http_flow();init_handle_streamable_http_flow();init_relay_http();init_transport_local();init_transport_remote();init_transport_types();SESSION_STORE_RETRY_BASE_MS=1e3;SESSION_STORE_RETRY_MAX_MS=3e4;DEFAULT_SESSION_CHECK_TIMEOUT_MS=500;BUS_REFRESH_INTERVAL_MS=15*60*1e3;MAX_ROUTABLE_SESSION_ID_LENGTH=4096;RELAYABLE_TYPES=new Set(["streamable-http","sse"]);TransportService=class{ready;byType=new Map;distributed;bus;scope;sessionHistory=new Map;MAX_SESSION_HISTORY=1e4;sessionStore;persistenceConfig;pendingStoreConfig;backendKind;transportKeyPrefix="mcp:transport:";sessionStoreConfigured=false;creationMutex=new Map;async newLocalTransporter(key,res,onDispose){if(key.type==="streamable-http"||key.type==="stateless-http"){await loadStreamableHttpTransport()}else if(key.type==="sse"){await loadSseTransport()}return new LocalTransporter(this.scope,key,res,onDispose)}getDefaultTtlMs(){if(this.resolvedTtlMs!==void 0)return this.resolvedTtlMs;return typeof this.persistenceConfig==="object"?this.persistenceConfig?.defaultTtlMs:void 0}resolvedTtlMs;storeRetryConfig;storeRetryTimer;storeRetryAttempt=0;destroyed=false;lastTtlRefreshAt=new Map;lastBusRefreshAt=new Map;localSessionIds=new Map;ownershipGeneration=new Map;relinquishing=new Set;storedLocalSessions=new Set;sessionCheckTimeoutMs;pendingSessionChecks=new Map;getSessionKeyPrefix(){return`${this.transportKeyPrefix}session:`}constructor(scope,persistenceConfig,bus){this.scope=scope;this.persistenceConfig=persistenceConfig;this.distributed=!!bus;this.bus=bus;this.sessionCheckTimeoutMs=(persistenceConfig!==false?persistenceConfig?.sessionCheckTimeoutMs:void 0)??DEFAULT_SESSION_CHECK_TIMEOUT_MS;if(persistenceConfig!==false&&persistenceConfig?.sqlite){this.sessionStoreConfigured=true;this.backendKind="sqlite";const sqliteConfig=persistenceConfig.sqlite;this.transportKeyPrefix="mcp:transport:";this.resolvedTtlMs=persistenceConfig.defaultTtlMs??36e5;this.pendingStoreConfig={sqlite:sqliteConfig,keyPrefix:this.transportKeyPrefix,defaultTtlMs:this.resolvedTtlMs};this.scope.logger.info("[TransportService] sqlite session store will be initialized for transport persistence")}else if(persistenceConfig!==false&&persistenceConfig?.redis){this.sessionStoreConfigured=true;const redisConfig=persistenceConfig.redis;const providerType="provider"in redisConfig?redisConfig.provider:"redis";this.backendKind=providerType==="vercel-kv"?"vercel-kv":"redis";this.transportKeyPrefix=redisConfig.keyPrefix??"mcp:transport:";this.resolvedTtlMs=persistenceConfig.defaultTtlMs??redisConfig.defaultTtlMs??36e5;this.pendingStoreConfig={...redisConfig,keyPrefix:this.transportKeyPrefix,defaultTtlMs:this.resolvedTtlMs};this.scope.logger.info(`[TransportService] ${providerType} session store will be initialized for transport persistence`)}this.storeRetryConfig=this.pendingStoreConfig;this.ready=this.initialize()}async initialize(){if(this.pendingStoreConfig){const connected=await this.connectSessionStore();if(!connected&&this.backendKind!=="sqlite")this.scheduleSessionStoreRetry()}await this.scope.registryFlows(HandleStreamableHttpFlow,HandleSseFlow,HandleStatelessHttpFlow,HandleMcp20260728Flow)}async connectSessionStore(){const storeConfig=this.pendingStoreConfig??this.storeRetryConfig;if(!storeConfig)return false;try{const store=await createSessionStore(storeConfig,this.scope.logger.child("SessionStore"));this.sessionStore=store;this.pendingStoreConfig=void 0}catch(error){const err=error;this.scope.logger.error("[TransportService] Failed to create session store - session persistence disabled",{error:err.message,cause:err.cause?.message});return false}const isConnected=this.sessionStore?.ping?await this.sessionStore.ping():true;if(!isConnected){const providerType=this.backendKind??"redis";this.scope.logger.error(`[TransportService] Failed to connect to ${providerType} - session persistence disabled`);await this.teardownSessionStore().catch(()=>void 0);return false}this.scope.logger.info("[TransportService] Session store connection validated successfully");return true}scheduleSessionStoreRetry(){if(this.destroyed||this.storeRetryTimer)return;const delay=Math.min(SESSION_STORE_RETRY_MAX_MS,SESSION_STORE_RETRY_BASE_MS*2**this.storeRetryAttempt);this.storeRetryAttempt++;this.storeRetryTimer=setTimeout(()=>{this.storeRetryTimer=void 0;void this.retrySessionStore()},delay);this.storeRetryTimer.unref?.()}async retrySessionStore(){if(this.destroyed||this.sessionStore)return;const connected=await this.connectSessionStore().catch(()=>false);if(this.destroyed){await this.teardownSessionStore().catch(()=>void 0);return}if(connected){this.storeRetryAttempt=0;this.scope.logger.info("[TransportService] Session store recovered after startup failure");return}this.scheduleSessionStoreRetry()}async destroy(){this.destroyed=true;if(this.storeRetryTimer){clearTimeout(this.storeRetryTimer);this.storeRetryTimer=void 0}this.lastTtlRefreshAt.clear();this.lastBusRefreshAt.clear();this.ownershipGeneration.clear();this.storedLocalSessions.clear();await this.teardownSessionStore()}async teardownSessionStore(){if(!this.sessionStore)return;const teardown=this.sessionStore.disconnect??this.sessionStore.close;if(!teardown){this.sessionStore=void 0;return}try{await Promise.resolve(teardown.call(this.sessionStore));this.scope.logger.info("[TransportService] Session store disconnected",{backendKind:this.backendKind??"unknown"})}catch(error){this.scope.logger.warn("[TransportService] Error disconnecting session store",{error:error.message,backendKind:this.backendKind??"unknown"})}finally{this.sessionStore=void 0}}async pingSessionStore(){if(!this.sessionStoreConfigured)return true;if(!this.sessionStore)return false;if(typeof this.sessionStore.ping==="function"){return this.sessionStore.ping()}return true}isSessionStoreConfigured(){return this.sessionStoreConfigured}getBackendKind(){return this.backendKind}sessionStoreLabel(){switch(this.backendKind){case"sqlite":return"SQLite";case"vercel-kv":return"Vercel KV";case"redis":return"Redis";default:return"the session store"}}refreshStoredSessionTtl(sessionId){const store=this.sessionStore;const ttlMs=this.getDefaultTtlMs();if(!store||!ttlMs||this.backendKind!=="redis"&&this.backendKind!=="vercel-kv")return;const now=Date.now();const last=this.lastTtlRefreshAt.get(sessionId);if(last!==void 0&&now-last<Math.max(1e3,Math.floor(ttlMs/4)))return;this.lastTtlRefreshAt.set(sessionId,now);store.get(sessionId).catch(err=>{this.scope.logger.warn("[TransportService] Failed to refresh session TTL",{sessionId:sessionId.slice(0,20),error:err instanceof Error?err.message:String(err)})})}async getTransporter(type,token,sessionId){const key=this.keyOf(type,token,sessionId);const local=this.lookupLocal(key);if(local&&await this.holdsLocalSession(sessionId)){this.refreshStoredSessionTtl(sessionId);this.refreshBusAdvertisement(key);return local}if(this.distributed&&this.bus){const location=await this.bus.lookup(key);if(location){if(await this.isNodeAlive(location.nodeId)){return new RemoteTransporter(key,this.bus,location)}this.scope.logger.info("[HA] Session owner is gone \u2014 the session will be taken over",{sessionId:sessionId.slice(0,20),previousNodeId:location.nodeId})}}return void 0}async findRemoteSessionOwner(request2){if(!this.distributed||!this.bus?.canRelay()||isRelayedRequest(request2))return void 0;const sessionId=sessionIdPresentedBy(request2);if(!sessionId||sessionId.length>MAX_ROUTABLE_SESSION_ID_LENGTH)return void 0;if(!isDeploymentSessionId(sessionId))return void 0;try{if(this.localSessionIds.has(sessionId)&&await this.holdsLocalSession(sessionId))return void 0;const owner=await this.lookupSessionOwner(sessionId);if(!owner||owner.nodeId===getMachineId4())return void 0;return await this.isNodeAlive(owner.nodeId)?owner:void 0}catch(error){this.scope.logger.warn("[HA] Could not resolve the session owner \u2014 serving the request here",{sessionId:sessionId.slice(0,20),error:error instanceof Error?error.message:String(error)});return void 0}}async lookupSessionOwner(sessionId){if(!this.bus)return void 0;const advertised=await this.bus.lookupOwner(sessionId);if(advertised)return advertised;const stored=this.sessionStore?await this.sessionStore.get(sessionId):null;const nodeId=stored?.session?.nodeId;if(!nodeId)return void 0;return{nodeId,channel:this.bus.channelOf(nodeId)}}async relayToSessionOwner(location,request2,response){if(!this.bus)throw new InvalidTransportSessionError("Session relay requires the distributed transport bus.");const sessionId=sessionIdPresentedBy(request2)??"";await this.bus.proxyRequest(location,sessionId,request2,response)}async adoptClaimedSession(sessionId,previousNodeId,info){if(!this.bus)return;const type=info.protocol;if(!info.authorizationId||type!=="streamable-http"&&type!=="sse")return;await this.bus.advertise({type,token:"",tokenHash:info.authorizationId,sessionId});this.scope.logger.info("[HA] Adopted an orphaned session \u2014 this node now serves it",{sessionId:sessionId.slice(0,20),previousNodeId})}async destroyLocalSession(sessionId,reason){let found=false;for(const[type,typeBucket]of[...this.byType.entries()]){if(!RELAYABLE_TYPES.has(type))continue;for(const tokenBucket of[...typeBucket.values()]){const transporter=tokenBucket.get(sessionId);if(!transporter)continue;found=true;await transporter.destroy(reason)}}return found}async holdsLocalSession(sessionId){if(!this.distributed)return this.isStillStored(sessionId);const haManager=this.scope.haManager;const store=this.sessionStore;if(!haManager||!store)return true;const generation=haManager.livenessGeneration();if(generation!==void 0&&this.ownershipGeneration.get(sessionId)===generation)return true;let ownerNodeId;try{ownerNodeId=(await this.withSessionCheckTimeout(`get:${sessionId}`,()=>store.get(sessionId)))?.session?.nodeId}catch(error){this.scope.logger.warn("[HA] Could not confirm this node still owns the session \u2014 serving it here",{sessionId:sessionId.slice(0,20),error:error instanceof Error?error.message:String(error)});return true}if(!ownerNodeId||ownerNodeId===getMachineId4()){if(generation!==void 0)this.ownershipGeneration.set(sessionId,generation);return true}this.scope.logger.warn("[HA] Another node took this session over while this node was unreachable \u2014 dropping it here",{sessionId:sessionId.slice(0,20),ownerNodeId});this.relinquishing.add(sessionId);try{await this.destroyLocalSession(sessionId,"the session moved to another node")}finally{this.relinquishing.delete(sessionId)}return false}async isStillStored(sessionId){const store=this.sessionStore;if(!store||!this.storedLocalSessions.has(sessionId))return true;try{if(await this.withSessionCheckTimeout(`exists:${sessionId}`,()=>store.exists(sessionId)))return true}catch(error){this.scope.logger.warn("[TransportService] Could not confirm the session is still stored \u2014 serving it here",{sessionId:sessionId.slice(0,20),error:error instanceof Error?error.message:String(error)});return true}this.scope.logger.info("[TransportService] The stored session is gone \u2014 dropping its transport here",{sessionId:sessionId.slice(0,20)});await this.destroyLocalSession(sessionId,"the session was deleted");return false}withSessionCheckTimeout(key,issueRead){let read=this.pendingSessionChecks.get(key);if(!read){read=issueRead().finally(()=>this.pendingSessionChecks.delete(key));this.pendingSessionChecks.set(key,read)}const timeoutMs=this.sessionCheckTimeoutMs;let timer;const timedOut=new Promise((_resolve,reject)=>{timer=setTimeout(()=>reject(new Error(`The session store did not answer within ${timeoutMs} ms`)),timeoutMs);timer.unref?.()});return Promise.race([read,timedOut]).finally(()=>clearTimeout(timer))}async isNodeAlive(nodeId){const haManager=this.scope.haManager;if(!haManager)return true;try{return await haManager.isNodeAlive(nodeId)}catch{return true}}refreshBusAdvertisement(key){if(!this.distributed||!this.bus||!RELAYABLE_TYPES.has(key.type))return;const now=Date.now();const last=this.lastBusRefreshAt.get(key.sessionId);if(last!==void 0&&now-last<BUS_REFRESH_INTERVAL_MS)return;this.lastBusRefreshAt.set(key.sessionId,now);this.bus.advertise(key).catch(err=>{this.scope.logger.warn("[HA] Failed to refresh the session advertisement",{sessionId:key.sessionId.slice(0,20),error:err instanceof Error?err.message:String(err)})})}async getStoredSession(type,token,sessionId,options){if(!this.sessionStore||type!=="streamable-http"&&type!=="sse")return void 0;const tokenHash=this.sha256(token);const stored=await this.sessionStore.get(sessionId);if(!stored)return void 0;if(stored.authorizationId!==tokenHash){this.scope.logger.warn("[TransportService] Session token mismatch during lookup",{sessionId:sessionId.slice(0,20),storedTokenHash:stored.authorizationId.slice(0,8),requestTokenHash:tokenHash.slice(0,8)});return void 0}if(options?.clientFingerprint&&stored.session.clientFingerprint){if(stored.session.clientFingerprint!==options.clientFingerprint){this.scope.logger.warn("[TransportService] Client fingerprint mismatch",{sessionId:sessionId.slice(0,20),storedFingerprint:stored.session.clientFingerprint.slice(0,8),requestFingerprint:options.clientFingerprint.slice(0,8)});if(!options.warnOnFingerprintMismatch){return void 0}}}return stored}async recreateTransporter(type,token,sessionId,storedSession,res){const key=this.keyOf(type,token,sessionId);const existing=this.lookupLocal(key);if(existing)return existing;const mutexKey=JSON.stringify({t:type,h:key.tokenHash,s:sessionId});const pendingCreation2=this.creationMutex.get(mutexKey);if(pendingCreation2){return pendingCreation2}const recreationPromise=this.doRecreateTransporter(key,sessionId,storedSession,res);this.creationMutex.set(mutexKey,recreationPromise);try{return await recreationPromise}catch(error){this.scope.logger.error("[TransportService] Failed to recreate transport from stored session",{sessionId:sessionId.slice(0,20),error:error instanceof Error?{name:error.name,message:error.message}:String(error)});throw error}finally{this.creationMutex.delete(mutexKey)}}async remoteOwnerTransporter(key,ownerNodeId){if(!this.distributed||!this.bus)return void 0;if(!await this.isNodeAlive(ownerNodeId))return void 0;return new RemoteTransporter(key,this.bus,{nodeId:ownerNodeId,channel:this.bus.channelOf(ownerNodeId)})}async doRecreateTransporter(key,sessionId,storedSession,res){const existing=this.lookupLocal(key);if(existing)return existing;this.scope.logger.info("[TransportService] Recreating transport from stored session",{sessionId:sessionId.slice(0,20),protocol:storedSession.session.protocol,createdAt:storedSession.createdAt});const currentNodeId=getMachineId4();const ownerNodeId=storedSession.session.nodeId;let latestSession=storedSession;if(this.scope.haManager&&ownerNodeId&&ownerNodeId!==currentNodeId){const remote=await this.remoteOwnerTransporter(key,ownerNodeId);if(remote)return remote;const sessionKey=`${this.getSessionKeyPrefix()}${sessionId}`;const result=await this.scope.haManager.attemptTakeover(sessionKey,ownerNodeId);if(result.claimed){latestSession={...storedSession,reassignedAt:result.reassignedAt,reassignedFrom:ownerNodeId};this.scope.logger.info("[HA] Took over session from a stopped node",{sessionId:sessionId.slice(0,20),previousNodeId:ownerNodeId})}else{const current=this.sessionStore?await this.sessionStore.get(sessionId):null;const newOwner=current?.session?.nodeId;if(newOwner!==currentNodeId){const relayed=newOwner?await this.remoteOwnerTransporter(key,newOwner):void 0;if(relayed)return relayed;this.scope.logger.debug("[HA] Session already claimed by another pod",{sessionId:sessionId.slice(0,20)});throw new SessionClaimConflictError(sessionId)}if(current)latestSession=current}}const historyKey=this.makeHistoryKey(key.type,key.tokenHash,sessionId);this.sessionHistory.set(historyKey,storedSession.createdAt);const sessionStore=this.sessionStore;const defaultTtlMs=this.getDefaultTtlMs();const transporter=await this.newLocalTransporter(key,res,()=>this.onSessionTransportDisposed(key,sessionId,sessionStore));await transporter.ready();if(storedSession.initialized!==false){transporter.markAsInitialized()}this.insertLocal(key,transporter);if(sessionStore)this.storedLocalSessions.add(sessionId);if(storedSession.clientCapabilities){this.scope.notifications.setClientCapabilities(sessionId,storedSession.clientCapabilities);this.scope.logger.verbose("[TransportService] Restored client capabilities from stored session",{sessionId:sessionId.slice(0,20)})}if(sessionStore){const updatedSession={...latestSession,session:{...latestSession.session,nodeId:currentNodeId},lastAccessedAt:Date.now()};sessionStore.set(sessionId,updatedSession,defaultTtlMs).catch(err=>{this.scope.logger.warn(`[TransportService] Failed to update session in ${this.sessionStoreLabel()}`,{sessionId:sessionId.slice(0,20),error:err instanceof Error?err.message:String(err)})})}if(this.distributed&&this.bus){await this.bus.advertise(key)}return transporter}async createTransporter(type,token,sessionId,res){const key=this.keyOf(type,token,sessionId);const existing=this.lookupLocal(key);if(existing)return existing;const mutexKey=JSON.stringify({t:type,h:key.tokenHash,s:sessionId});const pendingCreation2=this.creationMutex.get(mutexKey);if(pendingCreation2){return pendingCreation2}const creationPromise=this.doCreateTransporter(key,sessionId,res,type);this.creationMutex.set(mutexKey,creationPromise);try{return await creationPromise}finally{this.creationMutex.delete(mutexKey)}}async doCreateTransporter(key,sessionId,res,type){const existing=this.lookupLocal(key);if(existing)return existing;const sessionStore=this.sessionStore;const defaultTtlMs=this.getDefaultTtlMs();const transporter=await this.newLocalTransporter(key,res,()=>this.onSessionTransportDisposed(key,sessionId,sessionStore));await transporter.ready();this.insertLocal(key,transporter);if(sessionStore&&(type==="streamable-http"||type==="sse")){const storedSession={session:{id:sessionId,authorizationId:key.tokenHash,protocol:type==="sse"?"sse":"streamable-http",createdAt:Date.now(),nodeId:getMachineId4()},authorizationId:key.tokenHash,createdAt:Date.now(),lastAccessedAt:Date.now(),initialized:true};sessionStore.set(sessionId,storedSession,defaultTtlMs).then(()=>{if(this.localSessionIds.has(sessionId))this.storedLocalSessions.add(sessionId)},err=>{this.scope.logger.warn(`[TransportService] Failed to persist session to ${this.sessionStoreLabel()}`,{sessionId:sessionId.slice(0,20),error:err instanceof Error?err.message:String(err)})})}if(this.distributed&&this.bus){await this.bus.advertise(key)}return transporter}onSessionTransportDisposed(key,sessionId,sessionStore){key.sessionId=sessionId;this.evictLocal(key);if(this.distributed&&this.bus){this.bus.revoke(key).catch(()=>void 0)}if(sessionStore&&!this.relinquishing.has(sessionId)){sessionStore.delete(sessionId).catch(()=>void 0)}}async destroyTransporter(type,token,sessionId,reason){const key=this.keyOf(type,token,sessionId);const local=this.lookupLocal(key);if(local){await local.destroy(reason);return}if(this.distributed&&this.bus){const location=await this.bus.lookup(key);if(location){await this.bus.destroyRemote(key,reason);return}}throw new InvalidTransportSessionError("Invalid session: cannot destroy non-existent transporter.")}async deleteStoredSession(sessionId){if(!this.sessionStore)return;try{await this.sessionStore.delete(sessionId)}catch(err){this.scope.logger.warn(`[TransportService] Failed to delete session from ${this.sessionStoreLabel()}`,{sessionId:sessionId.slice(0,20),error:err instanceof Error?err.message:String(err)});throw err}}async updateStoredSessionCapabilities(sessionId,clientCapabilities){if(!this.sessionStore)return;try{const stored=await this.sessionStore.get(sessionId);if(!stored){this.scope.logger.verbose("[TransportService] Cannot update capabilities: session not found in store",{sessionId:sessionId.slice(0,20)});return}const updatedSession={...stored,clientCapabilities,lastAccessedAt:Date.now()};const defaultTtlMs=this.getDefaultTtlMs();await this.sessionStore.set(sessionId,updatedSession,defaultTtlMs);this.scope.logger.verbose("[TransportService] Persisted client capabilities to session store",{sessionId:sessionId.slice(0,20)})}catch(err){this.scope.logger.warn("[TransportService] Failed to persist client capabilities",{sessionId:sessionId.slice(0,20),error:err instanceof Error?err.message:String(err)})}}async getOrCreateAnonymousStatelessTransport(type,res){return this.getOrCreateStatelessTransport(this.keyOf(type,"__anonymous__",STATELESS_SESSION_ID),res)}async getOrCreateAuthenticatedStatelessTransport(type,token,res){return this.getOrCreateStatelessTransport(this.keyOf(type,token,STATELESS_SESSION_ID),res)}async getOrCreateStatelessTransport(key,res){const existing=this.lookupLocal(key);if(existing)return existing;const mutexKey=JSON.stringify({t:key.type,h:key.tokenHash,s:key.sessionId});const pendingCreation2=this.creationMutex.get(mutexKey);if(pendingCreation2)return pendingCreation2;const creationPromise=this.doCreateStatelessTransport(key,res);this.creationMutex.set(mutexKey,creationPromise);try{return await creationPromise}finally{this.creationMutex.delete(mutexKey)}}async doCreateStatelessTransport(key,res){const transporter=await this.newLocalTransporter(key,res,()=>{this.evictLocal(key);if(this.distributed&&this.bus){this.bus.revoke(key).catch(()=>void 0)}});await transporter.ready();this.insertLocal(key,transporter);if(this.distributed&&this.bus){await this.bus.advertise(key)}return transporter}wasSessionCreated(type,token,sessionId){const tokenHash=this.sha256(token);const historyKey=this.makeHistoryKey(type,tokenHash,sessionId);return this.sessionHistory.has(historyKey)}async wasSessionCreatedAsync(type,token,sessionId){if(this.wasSessionCreated(type,token,sessionId)){return true}if(this.sessionStore&&(type==="streamable-http"||type==="sse")){const stored=await this.getStoredSession(type,token,sessionId);return stored!==void 0}return false}sha256(value){return sha256Hex20(value)}makeHistoryKey(type,tokenHash,sessionId){return JSON.stringify({t:type,h:tokenHash,s:sessionId})}parseHistoryKey(key){try{const parsed=JSON.parse(key);if(typeof parsed.t==="string"&&typeof parsed.h==="string"&&typeof parsed.s==="string"){return{type:parsed.t,tokenHash:parsed.h,sessionId:parsed.s}}return void 0}catch{return void 0}}keyOf(type,token,sessionId,sessionIdSse){return{type,token,tokenHash:this.sha256(token),sessionId,sessionIdSse}}ensureTypeBucket(type){let bucket=this.byType.get(type);if(!bucket){bucket=new Map;this.byType.set(type,bucket)}return bucket}ensureTokenBucket(typeBucket,tokenHash){let bucket=typeBucket.get(tokenHash);if(!bucket){bucket=new Map;typeBucket.set(tokenHash,bucket)}return bucket}lookupLocal(key){const typeBucket=this.byType.get(key.type);if(!typeBucket)return void 0;const tokenBucket=typeBucket.get(key.tokenHash);if(!tokenBucket)return void 0;return tokenBucket.get(key.sessionId)}insertLocal(key,t){const typeBucket=this.ensureTypeBucket(key.type);const tokenBucket=this.ensureTokenBucket(typeBucket,key.tokenHash);if(!tokenBucket.has(key.sessionId)){this.localSessionIds.set(key.sessionId,(this.localSessionIds.get(key.sessionId)??0)+1)}tokenBucket.set(key.sessionId,t);const generation=this.distributed?this.scope.haManager?.livenessGeneration():void 0;if(generation!==void 0)this.ownershipGeneration.set(key.sessionId,generation);const historyKey=this.makeHistoryKey(key.type,key.tokenHash,key.sessionId);this.sessionHistory.set(historyKey,Date.now());if(this.sessionHistory.size>this.MAX_SESSION_HISTORY){const entries=[...this.sessionHistory.entries()].sort((a,b)=>a[1]-b[1]);const targetEvictions=Math.ceil(this.MAX_SESSION_HISTORY*.1);let evicted=0;for(const[histKey]of entries){if(evicted>=targetEvictions)break;const parsed=this.parseHistoryKey(histKey);if(!parsed){this.sessionHistory.delete(histKey);evicted++;continue}const{type,tokenHash,sessionId}=parsed;const typeBucket2=this.byType.get(type);const tokenBucket2=typeBucket2?.get(tokenHash);const hasActiveTransport=tokenBucket2?.has(sessionId)??false;if(!hasActiveTransport){this.sessionHistory.delete(histKey);evicted++}}if(evicted<targetEvictions){this.scope.logger.warn("[TransportService] Session history eviction: unable to free target memory",{targetEvictions,actualEvictions:evicted,currentSize:this.sessionHistory.size,maxSize:this.MAX_SESSION_HISTORY})}}}evictLocal(key){this.lastTtlRefreshAt.delete(key.sessionId);this.lastBusRefreshAt.delete(key.sessionId);const typeBucket=this.byType.get(key.type);if(!typeBucket)return;const tokenBucket=typeBucket.get(key.tokenHash);if(!tokenBucket)return;if(tokenBucket.delete(key.sessionId)){const remaining=(this.localSessionIds.get(key.sessionId)??1)-1;if(remaining>0)this.localSessionIds.set(key.sessionId,remaining);else{this.localSessionIds.delete(key.sessionId);this.ownershipGeneration.delete(key.sessionId);this.storedLocalSessions.delete(key.sessionId)}}if(tokenBucket.size===0)typeBucket.delete(key.tokenHash);if(typeBucket.size===0)this.byType.delete(key.type)}}}});function loadStreamableHttpTransportOnStart(scope){const{enableStreamableHttp,enableStatelessHttp,enableStatefulHttp}=toLegacyProtocolFlags(scope.metadata.transport?.protocol);if(!enableStreamableHttp&&!enableStatelessHttp&&!enableStatefulHttp)return;scope.onServerStarted(()=>{setImmediate(()=>{loadStreamableHttpTransport().catch(error=>scope.logger.verbose("Streamable HTTP transport preload failed",{error}))})})}var init_streamable_http_preload=__esm({"libs/sdk/src/transport/streamable-http-preload.ts"(){"use strict";init_schema7();init_transport_streamable_http_adapter()}});function getErrorMessage(err){if(err instanceof Error)return err.message;return String(err)}function createStorageProbe(name59,adapter){return{name:name59,async check(){const start=Date.now();try{const ok=await adapter.ping();const latencyMs=Date.now()-start;return{status:ok?"healthy":"unhealthy",latencyMs,...!ok?{error:"Ping returned false"}:{}}}catch(err){return{status:"unhealthy",latencyMs:Date.now()-start,error:getErrorMessage(err)}}}}}function createRemoteAppProbe(appId,provider){return{name:`remote:${appId}`,async check(){const result=provider.getHealthStatus(appId);if(!result||result.status==="unknown"&&result.consecutiveFailures===0){return{status:"degraded",details:{state:"unknown"}}}return{status:result.status==="healthy"?"healthy":result.status==="degraded"?"degraded":"unhealthy",latencyMs:result.latencyMs,...result.error?{error:result.error}:{}}}}}function createTransportSessionProbe(provider){return{name:"session-store",async check(){const start=Date.now();try{const ok=await provider.pingSessionStore();const latencyMs=Date.now()-start;return{status:ok?"healthy":"unhealthy",latencyMs,...!ok?{error:"Session store ping returned false"}:{}}}catch(err){return{status:"unhealthy",latencyMs:Date.now()-start,error:getErrorMessage(err)}}}}}var init_health_probes=__esm({"libs/sdk/src/health/health.probes.ts"(){"use strict"}});import{getRuntimeContext as getRuntimeContext21,sha256Hex as sha256Hex21}from"@frontmcp/utils";var processStartTime,HealthService;var init_health_service=__esm({"libs/sdk/src/health/health.service.ts"(){"use strict";init_health_probes();processStartTime=Date.now();HealthService=class{probeSources=[];config;serverInfo;scopeView;constructor(config,serverInfo){this.config=config;this.serverInfo=serverInfo}registerProbe(probe2){this.probeSources.push(()=>[probe2])}registerProbeSource(source){this.probeSources.push(source)}autoDiscoverProbes(scope){this.scopeView=scope;if(scope.transportService){this.registerProbe(createTransportSessionProbe(scope.transportService))}for(const app of scope.apps.getApps()){if(app.isRemote&&typeof app.getMcpClient==="function"){const client=app.getMcpClient();if(client&&typeof client.getHealthStatus==="function"){this.registerProbe(createRemoteAppProbe(app.id,client))}}}if(scope.haManager?.isStarted()){const ha=scope.haManager;this.registerProbe({name:"ha",check:async()=>{const alive=await ha.isNodeAlive(ha.getNodeId());return{status:alive?"healthy":"unhealthy",details:{nodeId:ha.getNodeId(),heartbeatActive:alive}}}})}this.registerProbeSource(()=>scope.healthProbes??[]);const userProbes=this.config.probes??[];for(const probe2 of userProbes){if(probe2&&typeof probe2.check==="function"&&typeof probe2.name==="string"){this.registerProbe({name:probe2.name,check:()=>probe2.check()})}}}getHealthz(){const ctx=getRuntimeContext21();return{status:"ok",server:{name:this.serverInfo.name??"unknown",version:this.serverInfo.version??"unknown"},runtime:{platform:ctx.platform,runtime:ctx.runtime,deployment:ctx.deployment,env:ctx.env},uptime:(Date.now()-processStartTime)/1e3}}async getReadyz(){const start=Date.now();const timeoutMs=this.config.readyz?.timeoutMs??5e3;const includeDetails=this.resolveIncludeDetails();const results=await Promise.all(this.getProbes().map(async probe2=>{const result=await this.runProbeWithTimeout(probe2,timeoutMs);return{name:probe2.name,result}}));const hasUnhealthy=results.some(r=>r.result.status==="unhealthy");const catalog=this.computeCatalogInfo();const response={status:hasUnhealthy?"not_ready":"ready",totalLatencyMs:Date.now()-start,catalog};if(includeDetails){const probes={};for(const{name:name59,result}of results){probes[name59]=result}response.probes=probes}return response}getProbeCount(){return this.getProbes().length}getProbes(){return this.probeSources.flatMap(source=>source())}setScopeView(scope){this.scopeView=scope}async runProbeWithTimeout(probe2,timeoutMs){let timeoutId;try{const timeoutPromise=new Promise(resolve4=>{timeoutId=setTimeout(()=>resolve4({status:"unhealthy",latencyMs:timeoutMs,error:`Probe timed out after ${timeoutMs}ms`}),timeoutMs)});return await Promise.race([probe2.check(),timeoutPromise])}catch(err){return{status:"unhealthy",error:err instanceof Error?err.message:String(err)}}finally{if(timeoutId!==void 0){clearTimeout(timeoutId)}}}computeCatalogInfo(){if(!this.scopeView){return{toolsHash:"",toolCount:0,resourceCount:0,promptCount:0,skillCount:0,agentCount:0}}const tools=this.scopeView.tools.getTools(true);const toolNames=tools.map(t=>t.name).sort();const toolsHash=sha256Hex21(toolNames.join(","));return{toolsHash,toolCount:tools.length,resourceCount:this.scopeView.resources.getResources(true).length,promptCount:this.scopeView.prompts.getPrompts(true).length,skillCount:this.scopeView.skills.getSkills(true).length,agentCount:this.scopeView.agents.getAgents().length}}resolveIncludeDetails(){if(this.config.includeDetails!==void 0){return this.config.includeDetails}const ctx=getRuntimeContext21();return ctx.env!=="production"}}}});var health_exports={};__export(health_exports,{HealthService:()=>HealthService,createRemoteAppProbe:()=>createRemoteAppProbe,createStorageProbe:()=>createStorageProbe,createTransportSessionProbe:()=>createTransportSessionProbe,isReadyzEnabled:()=>isReadyzEnabled,registerHealthRoutes:()=>registerHealthRoutes,servedHealthPaths:()=>servedHealthPaths});var init_health2=__esm({"libs/sdk/src/health/index.ts"(){"use strict";init_health_probes();init_health_service();init_health_routes()}});var http_scope_helper_exports={};__export(http_scope_helper_exports,{HealthService:()=>HealthService,HttpIpFilterFlow:()=>HttpIpFilterFlow,HttpRequestFlow:()=>HttpRequestFlow,HttpRouteFlow:()=>HttpRouteFlow,TransportService:()=>TransportService,attachHttpRoutes:()=>attachHttpRoutes,loadStreamableHttpTransportOnStart:()=>loadStreamableHttpTransportOnStart,registerCustomHttpRoutes:()=>registerCustomHttpRoutes,servedHealthPaths:()=>servedHealthPaths});var init_http_scope_helper=__esm({"libs/sdk/src/scope/http-scope.helper.ts"(){"use strict";init_http_route_flow();init_http_route_table();init_http_request_flow();init_http_ip_filter_flow();init_transport_registry();init_streamable_http_preload();init_custom_routes_helper();init_health2()}});var DEFAULT_HA_CONFIG;var init_ha_types=__esm({"libs/sdk/src/ha/ha.types.ts"(){"use strict";init_ha_constants();DEFAULT_HA_CONFIG={heartbeatIntervalMs:1e4,heartbeatTtlMs:3e4,takeoverGracePeriodMs:5e3,redisKeyPrefix:"mcp:ha:",affinityCookieName:DEFAULT_FRONTMCP_NODE_COOKIE,machineIdHeader:DEFAULT_FRONTMCP_MACHINE_ID_HEADER}}});var HeartbeatService;var init_heartbeat_service=__esm({"libs/sdk/src/ha/heartbeat.service.ts"(){"use strict";init_ha_types();HeartbeatService=class{constructor(redis,nodeId,config){this.redis=redis;this.nodeId=nodeId;this.startedAt=Date.now();this.lastBeatAt=this.startedAt;this.keyPrefix=config?.redisKeyPrefix??DEFAULT_HA_CONFIG.redisKeyPrefix;this.intervalMs=config?.heartbeatIntervalMs??DEFAULT_HA_CONFIG.heartbeatIntervalMs;this.ttlMs=config?.heartbeatTtlMs??DEFAULT_HA_CONFIG.heartbeatTtlMs}redis;nodeId;timer;startedAt;keyPrefix;intervalMs;ttlMs;sessionCount=0;lastBeatAt;lapses=0;start(){if(this.timer)return;this.writeHeartbeat();this.timer=setInterval(()=>this.writeHeartbeat(),this.intervalMs);if(this.timer.unref)this.timer.unref()}async stop(){if(this.timer){clearInterval(this.timer);this.timer=void 0}try{await this.redis.del(this.heartbeatKey())}catch{}}setSessionCount(count){this.sessionCount=count}async isAlive(nodeId){const exists=await this.redis.exists(`${this.keyPrefix}heartbeat:${nodeId}`);return exists===1}async getHeartbeat(nodeId){const raw=await this.redis.get(`${this.keyPrefix}heartbeat:${nodeId}`);if(!raw)return null;try{return JSON.parse(raw)}catch{return null}}livenessGeneration(){return Date.now()-this.lastBeatAt>=this.ttlMs?void 0:this.lapses}async getAliveNodes(){const keys=await this.redis.keys(`${this.keyPrefix}heartbeat:*`);return keys.map(key=>key.slice(`${this.keyPrefix}heartbeat:`.length))}heartbeatKey(){return`${this.keyPrefix}heartbeat:${this.nodeId}`}writeHeartbeat(){const value={nodeId:this.nodeId,startedAt:this.startedAt,lastBeat:Date.now(),sessionCount:this.sessionCount};this.redis.set(this.heartbeatKey(),JSON.stringify(value),"PX",this.ttlMs).then(()=>this.recordBeat(value.lastBeat),()=>void 0)}recordBeat(writtenAt){if(Date.now()-this.lastBeatAt>=this.ttlMs)this.lapses++;this.lastBeatAt=Math.max(this.lastBeatAt,writtenAt)}}}});var NotificationRelay;var init_notification_relay=__esm({"libs/sdk/src/ha/notification-relay.ts"(){"use strict";init_ha_types();NotificationRelay=class{constructor(subscriber,publisher,nodeId,config){this.subscriber=subscriber;this.publisher=publisher;this.nodeId=nodeId;this.keyPrefix=config?.redisKeyPrefix??DEFAULT_HA_CONFIG.redisKeyPrefix;this.channel=this.channelOf(nodeId)}subscriber;publisher;nodeId;handler;channel;keyPrefix;channelOf(nodeId){return`${this.keyPrefix}notify:${nodeId}`}async subscribe(handler){this.handler=handler;this.subscriber.removeListener("message",this.onMessage);this.subscriber.on("message",this.onMessage);await this.subscriber.subscribe(this.channel)}async unsubscribe(){this.handler=void 0;this.subscriber.removeListener("message",this.onMessage);try{await this.subscriber.unsubscribe(this.channel)}catch{}}async publish(targetNodeId,sessionId,notification){await this.send(targetNodeId,{kind:"notification",sessionId,notification,sourceNodeId:this.nodeId,timestamp:Date.now()})}async send(targetNodeId,message){return this.publisher.publish(this.channelOf(targetNodeId),JSON.stringify(message))}onMessage=(channel2,raw)=>{if(!this.handler||channel2!==this.channel)return;let message;try{message=JSON.parse(raw)}catch{return}if(!message||typeof message!=="object")return;try{Promise.resolve(this.handler(message)).catch(()=>void 0)}catch{}}}}});async function attemptSessionTakeover(redis,sessionKey,expectedOldNodeId,newNodeId){const reassignedAt=Date.now();const result=await redis.eval(TAKEOVER_LUA,1,sessionKey,expectedOldNodeId,newNodeId,reassignedAt.toString());const claimed=result===1;return{claimed,sessionId:sessionKey,previousNodeId:claimed?expectedOldNodeId:void 0,reassignedAt:claimed?reassignedAt:void 0}}var TAKEOVER_LUA;var init_session_takeover=__esm({"libs/sdk/src/ha/session-takeover.ts"(){"use strict";TAKEOVER_LUA=`
297
+ `)}function acceptsEventStream(headers){const accept=readHeader(headers,"accept");return typeof accept==="string"&&accept.includes("text/event-stream")}function extractTraceContext(meta){const out={};for(const key of TRACE_META_KEYS){if(typeof meta[key]==="string")out[key]=meta[key]}return Object.keys(out).length>0?out:void 0}async function*streamMessageResponse(options,sink,requestId,runInContext){let outcome;let failure;const running=runInContext(async()=>{try{outcome=await dispatch20260728(options)}catch(error){failure=error}}).finally(()=>sink.close());while(!sink.closed){await sink.waitForActivity();for(const notification of sink.drain()){yield frame3({jsonrpc:"2.0",method:notification.method,params:notification.params})}}await running;for(const notification of sink.drain()){yield frame3({jsonrpc:"2.0",method:notification.method,params:notification.params})}const id=requestId??null;if(failure!==void 0){const mapped=toJsonRpcError(failure);yield frame3({jsonrpc:"2.0",id,error:mapped.error});return}if(outcome?.kind==="error"){yield frame3({jsonrpc:"2.0",id,error:outcome.error});return}yield frame3({jsonrpc:"2.0",id,result:outcome?.result})}function isAnonymousCaller(auth){if(!auth)return true;if(!isAnonymousSubject8(auth.user?.sub))return false;return!auth.token||auth.session?.payload?.isPublic===true}function errorResponse(status,error,id){return httpRespond.json({jsonrpc:"2.0",id:id===void 0?null:id,error},{status})}function toClientInfo(value){if(typeof value!=="object"||value===null)return void 0;const{name:name59,version}=value;return typeof name59==="string"&&typeof version==="string"?{name:name59,version}:void 0}var plan24,MAX_RESOURCE_SUBSCRIPTIONS,subscriptionParamsSchema,requestIdSchema,stateSchema21,name24,Stage24,encoder8,TRACE_META_KEYS,HandleMcp20260728Flow;var init_handle_mcp_20260728_flow=__esm({"libs/sdk/src/transport/flows/handle.mcp-20260728.flow.ts"(){"use strict";init_common();init_tool_lookup_utils();init_context();init_notification();init_notification_service();init_skill_instructions_helper();init_mcp_20260728();init_mcp_surface();plan24={pre:["parseInput","validate","router"],execute:["handleNotification","handleSubscriptions","handleEventStream","handleMessage"],post:[],finalize:["cleanup"]};MAX_RESOURCE_SUBSCRIPTIONS=1e3;subscriptionParamsSchema=z113.object({notifications:z113.object({toolsListChanged:z113.boolean().optional(),promptsListChanged:z113.boolean().optional(),resourcesListChanged:z113.boolean().optional(),resourceSubscriptions:z113.array(z113.string()).max(MAX_RESOURCE_SUBSCRIPTIONS,{message:`subscriptions/listen takes at most ${MAX_RESOURCE_SUBSCRIPTIONS} resourceSubscriptions`}).optional()}).default({})});requestIdSchema=z113.union([z113.string(),z113.number()]);stateSchema21=z113.object({version:z113.string().optional(),requestType:z113.enum(["notification","subscriptions","eventStream","message"]).optional(),isAnonymous:z113.boolean().default(true),clientDeclaredRevision:z113.boolean().optional()});name24="handle:mcp-202607280728";({Stage:Stage24}=FlowHooksOf(name24));encoder8=new TextEncoder;TRACE_META_KEYS=["traceparent","tracestate","baggage"];HandleMcp20260728Flow=class extends FlowBase{name=name24;get log(){return this.scope.logger.child("HandleMcp20260728Flow")}async parseInput(){const{request:request2}=this.rawInput;const auth=request2[ServerRequestTokens.auth];this.state.set(stateSchema21.parse({isAnonymous:isAnonymousCaller(auth)}))}async validate(){const{request:request2}=this.rawInput;const method=request2.method.toUpperCase();if(method==="GET"||method==="DELETE"){this.respond({kind:"text",status:405,body:`HTTP ${method} is not supported by MCP protocol 2026-07-28`,contentType:"text/plain; charset=utf-8",headers:{Allow:"POST"}});return}const body=request2.body??{};const scope=this.scope;const clientDeclaredRevision=declaresProtocol20260728({headers:request2.headers,body});const result=validate20260728Request({headers:request2.headers,body,lookupToolSchema:toolName=>this.findToolSchema(scope,toolName),strictHeaders:clientDeclaredRevision&&!this.stdioOrigin});if(!result.ok){this.log.info("validate: rejected",{code:result.error.code,message:result.error.message});this.respond(errorResponse(result.status,result.error,body["id"]));return}this.state.set("version",result.version);this.state.set("clientDeclaredRevision",clientDeclaredRevision)}get stdioOrigin(){return this.rawInput.request[ServerRequestTokens.stdio]}buildContextRunner(){const context=this.tryGetContext();if(!context)return fn=>fn();const storage=this.scope.providers.get(FrontMcpContextStorage);return async fn=>{await runRequestExclusive5(()=>storage.runWithContext(context,fn))}}findToolSchema(scope,toolName){return lookupTool(scope,toolName)?.getInputJsonSchema()??null}async router(){const body=this.rawInput.request.body??{};const isNotification=body["id"]===void 0||body["id"]===null;if(isNotification){this.state.set("requestType","notification");return}if(body["method"]==="events/stream"&&this.scope.events?.performs("push")){this.state.set("requestType","eventStream");return}this.state.set("requestType",body["method"]==="subscriptions/listen"?"subscriptions":"message")}async handleNotification(){this.respond({kind:"text",status:202,body:"",contentType:"text/plain; charset=utf-8"})}async handleSubscriptions(){const{request:request2,response}=this.rawInput;const body=request2.body??{};const subscriptionId=requestIdSchema.safeParse(body["id"]);if(!subscriptionId.success){this.respond(errorResponse(400,{code:-32602,message:"subscriptions/listen requires a string or number id"},null));return}const parsedParams=subscriptionParamsSchema.safeParse(body["params"]??{});if(!parsedParams.success){this.respond(errorResponse(400,{code:-32602,message:`Invalid subscriptions/listen params: ${parsedParams.error.issues[0]?.message??"not an object"}`},subscriptionId.data));return}const auth=request2[ServerRequestTokens.auth];const listenerAuthInfo=auth?authInfoFromAuthorization(auth):{};const mayRead=this.resourceReadCheck(listenerAuthInfo);const requested={...parsedParams.data.notifications,resourceSubscriptions:await this.readableUris(parsedParams.data.notifications.resourceSubscriptions,mayRead)};const controller=new AbortController;const abort=()=>controller.abort();response?.on?.("close",abort);const stdioSignal=this.stdioOrigin?.signal;if(stdioSignal?.aborted)abort();else stdioSignal?.addEventListener("abort",abort,{once:true});const{acknowledged,stream}=createSubscriptionStream({scope:this.scope,subscriptionId:subscriptionId.data,requested,channels:await this.listenedChannels(body["params"]?._meta),signal:controller.signal,mayReceiveUpdate:(uri,watchedUri)=>listenerMayReceive(()=>hasExpiredCaller({caller:sessionCallerOf(listenerAuthInfo)}),()=>mayRead(this.scope.resources.findResourceForUri(uri)?uri:watchedUri))});this.log.info("handleSubscriptions: stream opened",{subscriptionId:body["id"],acknowledged:Object.keys(acknowledged)});this.respond({kind:"sse",status:200,stream,contentType:"text/event-stream",disposition:"inline",headers:{"X-Accel-Buffering":"no","Cache-Control":"no-cache, no-transform",Connection:"keep-alive"}})}async handleEventStream(){const{request:request2,response}=this.rawInput;const body=request2.body??{};const requestId=requestIdSchema.safeParse(body["id"]);if(!requestId.success){this.respond(errorResponse(400,{code:-32602,message:"events/stream requires a string or number id"},null));return}const streamRequest=StreamEventsRequestSchema2.safeParse({method:"events/stream",params:body["params"]});if(!streamRequest.success){const problem2=streamRequest.error.issues[0]?.message??"not an object";const error={code:-32602,message:`Invalid events/stream params: ${problem2}`};this.respond(errorResponse(400,error,requestId.data));return}const meta=body["params"]?._meta??{};const clientInfo=toClientInfo(meta[MCP_20260728_META8.clientInfo]);const clientCapabilities=meta[MCP_20260728_META8.clientCapabilities]??{};const platformDetection=this.scope.metadata.transport?.platformDetection;this.tryGetContext()?.setClientInfo(clientInfo,resolvePlatformType(clientInfo,clientCapabilities,platformDetection));const auth=request2[ServerRequestTokens.auth];const authInfo=auth?{...authInfoFromAuthorization(auth),sessionId:auth.session?.id??this.tryGetContext()?.sessionId}:{};const controller=new AbortController;const abort=()=>controller.abort();response?.on?.("close",abort);const stdioSignal=this.stdioOrigin?.signal;if(stdioSignal?.aborted)abort();else stdioSignal?.addEventListener("abort",abort,{once:true});let opened;try{opened=await this.scope.runFlowForOutput("events:stream",{request:streamRequest.data,ctx:{authInfo,surface:mcpRequestSurface(this.scope)},requestId:requestId.data,signal:controller.signal})}catch(failure){const mapped=toJsonRpcError(failure);this.respond(errorResponse(mapped.status,mapped.error,requestId.data));return}this.log.info("handleEventStream: stream opened",{subscriptionId:requestId.data});this.respond({kind:"sse",status:200,stream:eventStreamFrames(opened.stream,requestId.data),contentType:"text/event-stream",disposition:"inline",headers:{"X-Accel-Buffering":"no","Cache-Control":"no-cache, no-transform",Connection:"keep-alive"}})}resourceReadCheck(authInfo){const runInRequest=this.buildContextRunner();const ctx={authInfo,surface:mcpRequestSurface(this.scope)};return async uri=>{let allowed=false;await runInRequest(async()=>{const request2={method:"resources/subscribe",params:{uri}};allowed=await this.scope.runFlow("resources:subscribe",{request:request2,ctx}).then(()=>true,()=>false)});return allowed}}async readableUris(uris,mayRead){if(!uris)return void 0;const unique=[...new Set(uris)];const allowed=await Promise.all(unique.map(mayRead));return unique.filter((_uri,index)=>allowed[index])}async listenedChannels(meta){const capabilities=meta?.[MCP_20260728_META8.clientCapabilities];if(!supportsChannels(capabilities)||!this.scope.channels)return[];const listed=await this.scope.runFlowForOutput("channels:list",{});return listed.channels.map(channel2=>channel2.name)}async handleMessage(){const{request:request2}=this.rawInput;const body=request2.body??{};const params=body["params"]??{};const meta=params["_meta"]??{};const auth=request2[ServerRequestTokens.auth];const stdio=this.stdioOrigin;const clientCapabilities=meta[MCP_20260728_META8.clientCapabilities]??{};const logLevel=typeof meta[MCP_20260728_META8.logLevel]==="string"?meta[MCP_20260728_META8.logLevel]:void 0;const rawProgressToken=meta["progressToken"];const progressToken=typeof rawProgressToken==="string"||typeof rawProgressToken==="number"?rawProgressToken:void 0;const sink=new RequestNotificationSink(logLevel,progressToken);const clientInfo=toClientInfo(meta[MCP_20260728_META8.clientInfo]);const platformType=resolvePlatformType(clientInfo,clientCapabilities,this.scope.metadata.transport?.platformDetection);this.tryGetContext()?.setClientInfo(clientInfo,platformType);const dispatchOptions={scope:this.scope,body,clientCapabilities,frontmcpContext:this.tryGetContext(),authInfo:auth?{...authInfoFromAuthorization(auth),sessionId:auth.session?.id??this.tryGetContext()?.sessionId}:stdio&&{sessionId:this.tryGetContext()?.sessionId},isAnonymous:this.state.required.isAnonymous,transportPrincipal:stdio?.principal,signal:stdio?.signal,clientDeclaredRevision:this.state.clientDeclaredRevision!==false,composeInstructions:(caller,clientName)=>composeCallerInstructions(this.scope,{ctx:caller,clientName:clientName??this.tryGetContext()?.clientInfo?.name,skillUriHints:true}),notificationSink:sink,traceContext:extractTraceContext(meta)};const streams=stdio!==void 0||acceptsEventStream(request2.headers);if(sink.active&&streams){this.respond({kind:"sse",status:200,stream:streamMessageResponse(dispatchOptions,sink,body["id"],this.buildContextRunner()),contentType:"text/event-stream",disposition:"inline",headers:{"X-Accel-Buffering":"no","Cache-Control":"no-cache, no-transform",Connection:"keep-alive"}});return}const outcome=await dispatch20260728(dispatchOptions);sink.close();if(outcome.kind==="error"){this.respond(errorResponse(outcome.status,outcome.error,body["id"]));return}this.respond(httpRespond.json({jsonrpc:"2.0",id:body["id"]??null,result:outcome.result},{status:200}))}async cleanup(){}};__decorateClass([Stage24("parseInput")],HandleMcp20260728Flow.prototype,"parseInput",1);__decorateClass([Stage24("validate")],HandleMcp20260728Flow.prototype,"validate",1);__decorateClass([Stage24("router")],HandleMcp20260728Flow.prototype,"router",1);__decorateClass([Stage24("handleNotification",{filter:({state})=>state.required.requestType==="notification"})],HandleMcp20260728Flow.prototype,"handleNotification",1);__decorateClass([Stage24("handleSubscriptions",{filter:({state})=>state.required.requestType==="subscriptions"})],HandleMcp20260728Flow.prototype,"handleSubscriptions",1);__decorateClass([Stage24("handleEventStream",{filter:({state})=>state.required.requestType==="eventStream"})],HandleMcp20260728Flow.prototype,"handleEventStream",1);__decorateClass([Stage24("handleMessage",{filter:({state})=>state.required.requestType==="message"})],HandleMcp20260728Flow.prototype,"handleMessage",1);__decorateClass([Stage24("cleanup")],HandleMcp20260728Flow.prototype,"cleanup",1);HandleMcp20260728Flow=__decorateClass([FrontMcpFlow({name:name24,plan:plan24,access:"authorized",inputSchema:httpInputSchema,outputSchema:httpOutputSchema})],HandleMcp20260728Flow)}});import{internalZ as z114}from"@frontmcp/lazy-zod";function getQuerySessionId2(urlPath){if(!urlPath)return void 0;try{const u=new URL(String(urlPath),"http://local");return u.searchParams.get("sessionId")??void 0}catch{return void 0}}function resolveLegacySseSession(params){const{rawHeader,requestUrl,authorizationSession,createSession}=params;const rawMcpSessionHeader=typeof rawHeader==="string"?rawHeader:void 0;const mcpSessionHeader=validateMcpSessionHeader(rawMcpSessionHeader);const querySessionId=getQuerySessionId2(requestUrl);const validatedQuerySessionId=querySessionId?validateMcpSessionHeader(querySessionId):void 0;if(rawHeader!==void 0&&!mcpSessionHeader){return{responded404:true,createdNew:false}}if(querySessionId!==void 0&&!validatedQuerySessionId){return{responded404:true,createdNew:false}}const effectiveSessionId=mcpSessionHeader??validatedQuerySessionId;if(effectiveSessionId){if(authorizationSession?.id===effectiveSessionId){return{session:authorizationSession,createdNew:false,responded404:false}}return{responded404:true,createdNew:false}}if(authorizationSession){return{session:authorizationSession,createdNew:false,responded404:false}}return{session:createSession(),createdNew:true,responded404:false}}var plan25,stateSessionSchema,stateSchema22,name25,Stage25,HandleSseFlow;var init_handle_sse_flow=__esm({"libs/sdk/src/transport/flows/handle.sse.flow.ts"(){"use strict";init_session_id_utils();init_common();init_errors();init_ha_headers();init_skill_mode_utils();plan25={pre:["parseInput","router"],execute:["onInitialize","onMessage","onElicitResult"],post:[],finalize:["cleanup"]};stateSessionSchema=z114.object({id:z114.string(),payload:z114.object({nodeId:z114.string(),authSig:z114.string(),uuid:z114.string().uuid(),iat:z114.number(),protocol:z114.enum(["legacy-sse","sse","streamable-http","stateful-http","stateless-http"]).optional(),isPublic:z114.boolean().optional(),platformType:z114.enum(["openai","claude","claude-code","codex","gemini","cursor","continue","cody","generic-mcp","ext-apps","unknown"]).optional()}).optional()});stateSchema22=z114.object({token:z114.string(),session:stateSessionSchema,requestType:z114.enum(["initialize","message","elicitResult"]).optional()});name25="handle:legacy-sse";({Stage:Stage25}=FlowHooksOf(name25));HandleSseFlow=class extends FlowBase{async parseInput(){const{request:request2}=this.rawInput;const authorization=request2[ServerRequestTokens.auth];const{token}=authorization;const anyReq=request2;const resolution=resolveLegacySseSession({rawHeader:request2.headers?.["mcp-session-id"],requestUrl:anyReq.url??anyReq.path,authorizationSession:authorization.session,createSession:()=>{const query=request2.query;const skillsOnlyMode=detectSkillsOnlyMode(query);return createSessionId("legacy-sse",token,{userAgent:request2.headers?.["user-agent"],platformDetectionConfig:this.scope.metadata.transport?.platformDetection,skillsOnlyMode})}});if(resolution.responded404||!resolution.session){this.respond(httpRespond.sessionNotFound("invalid session id"));return}const session=resolution.session;this.state.set(stateSchema22.parse({token,session}))}async router(){const{request:request2}=this.rawInput;const requestPath=normalizeEntryPrefix(request2.path);const prefix=normalizeEntryPrefix(this.scope.entryPath);const scopePath=normalizeScopeBase(this.scope.routeBase);const basePath=`${prefix}${scopePath}`;if(requestPath===`${basePath}/sse`){this.state.set("requestType","initialize")}else if(requestPath===`${basePath}/message`){this.state.set("requestType","message")}}async onInitialize(){const transportService=this.scope.transportService;if(!transportService){throw new TransportServiceNotAvailableError}const{request:request2,response}=this.rawInput;const{token,session}=this.state.required;const authorization=request2[ServerRequestTokens.auth];authorization.session??=session;const transport=await transportService.createTransporter("sse",token,session.id,response);applyNodeAffinity(response,request2);await transport.initialize(request2,response);this.handled()}async onElicitResult(){this.fail(new Error("Not implemented"))}async onMessage(){const transportService=this.scope.transportService;if(!transportService){throw new TransportServiceNotAvailableError}const logger=this.scopeLogger.child("handle:legacy-sse:onMessage");const{request:request2,response}=this.rawInput;const{token,session}=this.state.required;const transport=await transportService.getTransporter("sse",token,session.id);if(!transport){const wasCreated=await transportService.wasSessionCreatedAsync("sse",token,session.id);const body=request2.body;if(wasCreated){logger.info("Session expired - client should re-initialize",{sessionId:session.id?.slice(0,20),tokenHash:token.slice(0,8),method:body?.["method"],requestId:body?.["id"]});this.respond(httpRespond.sessionExpired("session expired"))}else{logger.warn("Session not initialized - client attempted request without initializing",{sessionId:session.id?.slice(0,20),tokenHash:token.slice(0,8),method:body?.["method"],requestId:body?.["id"],userAgent:request2.headers?.["user-agent"]?.slice(0,50)});this.respond(httpRespond.sessionNotFound("session not initialized"))}return}await transport.handleRequest(request2,response);this.handled()}};__decorateClass([Stage25("parseInput")],HandleSseFlow.prototype,"parseInput",1);__decorateClass([Stage25("router")],HandleSseFlow.prototype,"router",1);__decorateClass([Stage25("onInitialize",{filter:({state:{requestType}})=>requestType==="initialize"})],HandleSseFlow.prototype,"onInitialize",1);__decorateClass([Stage25("onElicitResult",{filter:({state:{requestType}})=>requestType==="elicitResult"})],HandleSseFlow.prototype,"onElicitResult",1);__decorateClass([Stage25("onMessage",{filter:({state:{requestType}})=>requestType==="message"})],HandleSseFlow.prototype,"onMessage",1);HandleSseFlow=__decorateClass([FrontMcpFlow({name:name25,access:"authorized",inputSchema:httpInputSchema,outputSchema:httpOutputSchema,plan:plan25})],HandleSseFlow)}});import{internalZ as z115}from"@frontmcp/lazy-zod";import{RequestSchema}from"@frontmcp/protocol";var plan26,stateSchema23,name26,Stage26,HandleStatelessHttpFlow;var init_handle_stateless_http_flow=__esm({"libs/sdk/src/transport/flows/handle.stateless-http.flow.ts"(){"use strict";init_common();init_errors();init_ha_headers();init_transport_types();plan26={pre:["applyNodeHeaders","parseInput","router"],execute:["handleRequest"],post:[],finalize:["cleanup"]};stateSchema23=z115.object({token:z115.string().optional(),isAuthenticated:z115.boolean(),requestType:z115.enum(["initialize","message"]).optional()});name26="handle:stateless-http";({Stage:Stage26}=FlowHooksOf(name26));HandleStatelessHttpFlow=class extends FlowBase{name=name26;async applyNodeHeaders(){applyMachineIdHeader(this.rawInput.response)}async parseInput(){const{request:request2}=this.rawInput;const logger=this.scope.logger.child("HandleStatelessHttpFlow");const auth=request2[ServerRequestTokens.auth];const token=auth?.token;const isAuthenticated=!!token&&token.length>0;logger.verbose("parseInput",{isAuthenticated,hasToken:!!token});this.state.set(stateSchema23.parse({token:token||void 0,isAuthenticated}))}async router(){const{request:request2}=this.rawInput;const logger=this.scope.logger.child("HandleStatelessHttpFlow");const body=request2.body;const method=body?.method;if(method==="initialize"){this.state.set("requestType","initialize");logger.verbose("router: requestType=initialize, method=POST")}else if(method&&RequestSchema.safeParse(request2.body).success){this.state.set("requestType","message");logger.verbose(`router: requestType=message, method=${method}`)}else{logger.warn("router: invalid request, no valid method");this.respond(httpRespond.rpcError("Invalid Request"))}}async handleRequest(){const transportService=this.scope.transportService;if(!transportService){throw new TransportServiceNotAvailableError}const logger=this.scope.logger.child("HandleStatelessHttpFlow");const{request:request2,response}=this.rawInput;const{token,isAuthenticated,requestType}=this.state;logger.verbose(`handleRequest: using ${isAuthenticated?"authenticated":"anonymous"} stateless transport`);const transport=isAuthenticated&&token?await transportService.getOrCreateAuthenticatedStatelessTransport("stateless-http",token,response):await transportService.getOrCreateAnonymousStatelessTransport("stateless-http",response);if(!request2.headers["mcp-session-id"]){request2.headers["mcp-session-id"]=STATELESS_SESSION_ID;logger.verbose(`handleRequest: injected ${STATELESS_SESSION_ID} session ID`)}logger.verbose(`handleRequest: requestType=${requestType}, forwarding to transport`);try{if(requestType==="initialize"){await transport.initialize(request2,response)}else{await transport.handleRequest(request2,response)}}catch(error){logger.error("handleRequest: transport failed",{requestType,error:error instanceof Error?{name:error.name,message:error.message}:String(error)});throw error}this.handled()}};__decorateClass([Stage26("applyNodeHeaders")],HandleStatelessHttpFlow.prototype,"applyNodeHeaders",1);__decorateClass([Stage26("parseInput")],HandleStatelessHttpFlow.prototype,"parseInput",1);__decorateClass([Stage26("router")],HandleStatelessHttpFlow.prototype,"router",1);__decorateClass([Stage26("handleRequest")],HandleStatelessHttpFlow.prototype,"handleRequest",1);HandleStatelessHttpFlow=__decorateClass([FrontMcpFlow({name:name26,plan:plan26,access:"authorized",inputSchema:httpInputSchema,outputSchema:httpOutputSchema})],HandleStatelessHttpFlow)}});var EXT_APPS_ERROR_CODES;var init_ext_apps_types=__esm({"libs/sdk/src/ext-apps/ext-apps.types.ts"(){"use strict";EXT_APPS_ERROR_CODES={PARSE_ERROR:-32700,INVALID_REQUEST:-32600,METHOD_NOT_FOUND:-32601,INVALID_PARAMS:-32602,INTERNAL_ERROR:-32603,TOOL_NOT_FOUND:-32001,TOOL_EXECUTION_FAILED:-32002,NOT_SUPPORTED:-32003,CANCELLED:-32004}}});import{escapeControlCharacters as escapeControlCharacters5,isDevelopment as isDevelopment5}from"@frontmcp/utils";function createExtAppsMessageHandler(options){return new ExtAppsMessageHandler(options)}var MCP_LOG_LEVELS,ExtAppsMessageHandler,ExtAppsError,ExtAppsMethodNotFoundError,ExtAppsInvalidParamsError,ExtAppsNotSupportedError,ExtAppsToolNotFoundError;var init_ext_apps_handler=__esm({"libs/sdk/src/ext-apps/ext-apps.handler.ts"(){"use strict";init_errors();init_ext_apps_types();MCP_LOG_LEVELS={debug:"debug",info:"info",notice:"info",warning:"warn",error:"error",critical:"error",alert:"error",emergency:"error"};ExtAppsMessageHandler=class{context;hostCapabilities;logger;constructor(options){this.context=options.context;this.hostCapabilities=options.hostCapabilities||{};this.logger=options.context.logger.child("ExtAppsMessageHandler")}getHostCapabilities(){return{...this.hostCapabilities}}async handleRequest(request2){const{id,method,params}=request2;this.logger.verbose(`handleRequest: method=${escapeControlCharacters5(method)}, id=${escapeControlCharacters5(id)}`);try{const result=await this.routeMethod(method,params);return{jsonrpc:"2.0",id,result:result===void 0?{}:result}}catch(error){const errorMessage2=error instanceof Error?error.message:String(error);const errorCode2=this.getErrorCode(error);this.logger.warn(`handleRequest: method=${escapeControlCharacters5(method)} failed: ${escapeControlCharacters5(errorMessage2)}`);return{jsonrpc:"2.0",id,error:{code:errorCode2,message:this.widgetMessageOf(error),data:isDevelopment5()&&error instanceof Error?{stack:error.stack}:void 0}}}}async handleNotification(notification){const{method,params}=notification;if(method!=="notifications/message"&&method!=="ui/notifications/request-teardown"){this.logger.verbose(`handleNotification: ignoring method=${escapeControlCharacters5(method)}`);return}if(method==="ui/notifications/request-teardown"&&!this.context.close){this.logger.verbose("handleNotification: ignoring ui/notifications/request-teardown (no close callback)");return}try{await this.routeMethod(method,params)}catch(error){const errorMessage2=error instanceof Error?error.message:String(error);this.logger.warn(`handleNotification: method=${escapeControlCharacters5(method)} failed: ${escapeControlCharacters5(errorMessage2)}`)}}async routeMethod(method,params){if(params!==void 0&&(params===null||typeof params!=="object"||Array.isArray(params))){throw new ExtAppsInvalidParamsError("Invalid params: expected object")}const normalizedParams=params??{};switch(method){case"ui/initialize":return this.handleInitialize(normalizedParams);case"ui/callServerTool":return this.handleCallServerTool(normalizedParams);case"ui/update-model-context":return this.handleSpecUpdateModelContext(normalizedParams);case"ui/updateModelContext":return this.handleUpdateModelContext(normalizedParams);case"ui/open-link":case"ui/openLink":return this.handleOpenLink(normalizedParams);case"ui/request-display-mode":case"ui/setDisplayMode":return this.handleSetDisplayMode(normalizedParams);case"ui/notifications/request-teardown":case"ui/close":return this.handleClose(normalizedParams);case"notifications/message":return this.handleLogMessage(normalizedParams);case"ui/log":return this.handleLog(normalizedParams);case"ui/registerTool":return this.handleRegisterTool(normalizedParams);case"ui/unregisterTool":return this.handleUnregisterTool(normalizedParams);default:throw new ExtAppsMethodNotFoundError(`Unknown ext-apps method: ${method}`)}}handleInitialize(params){const{appInfo,protocolVersion}=params;this.logger.verbose(`handleInitialize: app=${escapeControlCharacters5(appInfo?.name||"unknown")} v${escapeControlCharacters5(appInfo?.version||"unknown")}, protocol=${escapeControlCharacters5(protocolVersion)}`);return{hostCapabilities:this.hostCapabilities,protocolVersion:protocolVersion||"2024-11-05"}}async handleCallServerTool(params){if(!this.hostCapabilities.serverToolProxy){throw new ExtAppsNotSupportedError("Server tool proxy not supported by host")}const{name:name59,arguments:args={}}=params;if(!name59||typeof name59!=="string"){throw new ExtAppsInvalidParamsError("Tool name is required")}this.logger.verbose(`handleCallServerTool: tool=${escapeControlCharacters5(name59)}`);return this.context.callTool(name59,args)}async handleUpdateModelContext(params){if(!this.hostCapabilities.modelContextUpdate){throw new ExtAppsNotSupportedError("Model context update not advertised by host")}if(!this.context.updateModelContext){throw new ExtAppsNotSupportedError("Model context update not supported by host")}const{context,merge=true}=params;this.logger.verbose(`handleUpdateModelContext: merge=${merge}`);await this.context.updateModelContext(context,merge)}async handleSpecUpdateModelContext(params){const{content,structuredContent}=params;if(content!==void 0&&!Array.isArray(content)){throw new ExtAppsInvalidParamsError("content must be an array of content blocks")}if(structuredContent!==void 0&&(typeof structuredContent!=="object"||structuredContent===null||Array.isArray(structuredContent))){throw new ExtAppsInvalidParamsError("structuredContent must be an object")}const context={};if(content!==void 0)context.content=content;if(structuredContent!==void 0)context.structuredContent=structuredContent;await this.handleUpdateModelContext({context,merge:false})}async handleOpenLink(params){if(!this.hostCapabilities.openLink){throw new ExtAppsNotSupportedError("Open link not advertised by host")}if(!this.context.openLink){throw new ExtAppsNotSupportedError("Open link not supported by host")}const{url}=params;if(!url||typeof url!=="string"){throw new ExtAppsInvalidParamsError("URL is required")}let parsed;try{parsed=new URL(url)}catch{throw new ExtAppsInvalidParamsError("Invalid URL format")}const allowedSchemes=["http:","https:"];if(!allowedSchemes.includes(parsed.protocol)){throw new ExtAppsInvalidParamsError(`URL scheme '${parsed.protocol}' not allowed. Only http: and https: are permitted.`)}this.logger.verbose(`handleOpenLink: url=${escapeControlCharacters5(url)}`);await this.context.openLink(url)}async handleSetDisplayMode(params){const{mode}=params;if(!mode||!["inline","fullscreen","pip"].includes(mode)){throw new ExtAppsInvalidParamsError("Invalid display mode. Must be inline, fullscreen, or pip")}if(this.hostCapabilities.displayModes&&!this.hostCapabilities.displayModes.includes(mode)){throw new ExtAppsNotSupportedError(`Display mode '${mode}' not advertised by host`)}if(!this.context.setDisplayMode){throw new ExtAppsNotSupportedError("Display mode change not supported by host")}this.logger.verbose(`handleSetDisplayMode: mode=${escapeControlCharacters5(mode)}`);await this.context.setDisplayMode(mode);return{mode}}async handleClose(params){if(!this.context.close){throw new ExtAppsNotSupportedError("Widget close not supported by host")}const{reason}=params;this.logger.verbose(`handleClose: reason=${escapeControlCharacters5(reason||"none")}`);await this.context.close(reason)}async handleLog(params){if(!this.hostCapabilities.logging){throw new ExtAppsNotSupportedError("Logging not supported by host")}const{level,message,data}=params;if(!message||typeof message!=="string"){throw new ExtAppsInvalidParamsError("Log message is required")}const validLevels=["debug","info","warn","error"];if(level&&!validLevels.includes(level)){throw new ExtAppsInvalidParamsError(`Invalid log level '${level}'. Must be one of: ${validLevels.join(", ")}`)}this.writeWidgetLog(level??"info",message,data)}async handleLogMessage(params){if(!this.hostCapabilities.logging){throw new ExtAppsNotSupportedError("Logging not supported by host")}const{level,logger,data}=params;const serverLevel=Object.hasOwn(MCP_LOG_LEVELS,level)?MCP_LOG_LEVELS[level]:void 0;if(!serverLevel){throw new ExtAppsInvalidParamsError(`Invalid log level '${level}'. Must be one of: ${Object.keys(MCP_LOG_LEVELS).join(", ")}`)}if(typeof data==="string"){this.writeWidgetLog(serverLevel,data,void 0)}else{this.writeWidgetLog(serverLevel,logger??"widget log",data)}}writeWidgetLog(level,text,data){const widgetLogger=this.logger.child(`Widget:${this.context.sessionId}`);const message=escapeControlCharacters5(text);switch(level){case"debug":widgetLogger.verbose(message,data);break;case"info":widgetLogger.info(message,data);break;case"warn":widgetLogger.warn(message,data);break;case"error":widgetLogger.error(message,data);break;default:widgetLogger.info(message,data)}}async handleRegisterTool(params){if(!this.hostCapabilities.widgetTools){throw new ExtAppsNotSupportedError("Widget tools not advertised by host")}if(!this.context.registerTool){throw new ExtAppsNotSupportedError("Widget tool registration not supported by host")}const{name:name59,description,inputSchema:inputSchema53}=params;if(!name59||typeof name59!=="string"){throw new ExtAppsInvalidParamsError("Tool name is required")}if(!description||typeof description!=="string"){throw new ExtAppsInvalidParamsError("Tool description is required")}if(!inputSchema53||typeof inputSchema53!=="object"||Array.isArray(inputSchema53)){throw new ExtAppsInvalidParamsError("Tool input schema must be a non-null object")}this.logger.verbose(`handleRegisterTool: name=${escapeControlCharacters5(name59)}`);await this.context.registerTool(name59,description,inputSchema53)}async handleUnregisterTool(params){if(!this.hostCapabilities.widgetTools){throw new ExtAppsNotSupportedError("Widget tools not advertised by host")}if(!this.context.unregisterTool){throw new ExtAppsNotSupportedError("Widget tool unregistration not supported by host")}const{name:name59}=params;if(!name59||typeof name59!=="string"){throw new ExtAppsInvalidParamsError("Tool name is required")}this.logger.verbose(`handleUnregisterTool: name=${escapeControlCharacters5(name59)}`);await this.context.unregisterTool(name59)}widgetMessageOf(error){if(error instanceof ExtAppsError||isDevelopment5())return error instanceof Error?error.message:String(error);return toMcpError(error).getPublicMessage()}getErrorCode(error){if(error instanceof ExtAppsMethodNotFoundError){return EXT_APPS_ERROR_CODES.METHOD_NOT_FOUND}if(error instanceof ExtAppsInvalidParamsError){return EXT_APPS_ERROR_CODES.INVALID_PARAMS}if(error instanceof ExtAppsNotSupportedError){return EXT_APPS_ERROR_CODES.NOT_SUPPORTED}if(error instanceof ExtAppsToolNotFoundError){return EXT_APPS_ERROR_CODES.TOOL_NOT_FOUND}return EXT_APPS_ERROR_CODES.INTERNAL_ERROR}};ExtAppsError=class extends Error{constructor(message){super(message);this.name="ExtAppsError"}};ExtAppsMethodNotFoundError=class extends ExtAppsError{constructor(message){super(message);this.name="ExtAppsMethodNotFoundError"}};ExtAppsInvalidParamsError=class extends ExtAppsError{constructor(message){super(message);this.name="ExtAppsInvalidParamsError"}};ExtAppsNotSupportedError=class extends ExtAppsError{constructor(message){super(message);this.name="ExtAppsNotSupportedError"}};ExtAppsToolNotFoundError=class extends ExtAppsError{constructor(message){super(message);this.name="ExtAppsToolNotFoundError"}}}});var init_ext_apps2=__esm({"libs/sdk/src/ext-apps/index.ts"(){"use strict";init_ext_apps_types();init_ext_apps_handler()}});import{internalZ as z116}from"@frontmcp/lazy-zod";import{CallToolResultSchema as CallToolResultSchema4,ElicitResultSchema as ElicitResultSchema3,RequestSchema as RequestSchema2}from"@frontmcp/protocol";function resolveStreamableHttpSession(params){const{rawHeader,authorizationSession,createSession}=params;const rawMcpSessionHeader=typeof rawHeader==="string"?rawHeader:void 0;const mcpSessionHeader=validateMcpSessionHeader(rawMcpSessionHeader);if(rawHeader!==void 0&&!mcpSessionHeader){return{responded404:true,createdNew:false}}if(mcpSessionHeader){if(authorizationSession?.id===mcpSessionHeader){return{session:authorizationSession,createdNew:false,responded404:false}}return{responded404:true,createdNew:false}}if(authorizationSession){return{session:authorizationSession,createdNew:false,responded404:false}}return{session:createSession(),createdNew:true,responded404:false}}function classifyStreamableHttpRequest(params){const{method,body}=params;if(method.toUpperCase()==="GET"){return{requestType:"sseListener"}}const jsonRpcMethod=body?.method;if(jsonRpcMethod==="initialize"){return{requestType:"initialize"}}if(typeof jsonRpcMethod==="string"&&(jsonRpcMethod.startsWith("ui/")||jsonRpcMethod==="notifications/message")){return{requestType:"extApps"}}if(ElicitResultSchema3.safeParse(body?.result).success){return{requestType:"elicitResult"}}if(jsonRpcMethod&&RequestSchema2.safeParse(body).success){return{requestType:"message"}}return{error:"Invalid Request"}}function syncStreamableHttpAuthorizationSession(authorization,session){if(!authorization.session){authorization.session=session}}function resetInitializedTransportForReinit(transport){if(!transport.isInitialized){return true}transport.resetForReinitialization();transport.reregisterServer();return!transport.isInitialized}function buildReinitFailedResponse(sessionId,requestId){return httpRespond.rpcError(`Could not re-initialize session "${sessionId}". It is stuck in an initialized state \u2014 terminate it with an HTTP DELETE to the MCP endpoint (including the mcp-session-id header), or reconnect without the stored mcp-session-id to start a fresh session.`,requestId)}async function lookupStreamableHttpTransport(params){const{transportService,token,sessionId,response}=params;const inMemoryTransport=await transportService.getTransporter("streamable-http",token,sessionId);if(inMemoryTransport){return{kind:"transport",source:"memory",transport:inMemoryTransport}}let recreationError;try{const storedSession=await transportService.getStoredSession("streamable-http",token,sessionId);if(storedSession){const recreatedTransport=await transportService.recreateTransporter("streamable-http",token,sessionId,storedSession,response);if(recreatedTransport){return{kind:"transport",source:"redis",transport:recreatedTransport}}}}catch(error){recreationError=error}const wasCreated=await transportService.wasSessionCreatedAsync("streamable-http",token,sessionId);if(wasCreated){return{kind:"session-expired",recreationError}}return{kind:"session-not-initialized",recreationError}}function sessionIdForLog(sessionId){return typeof sessionId==="string"?sessionId.slice(0,20):void 0}function errorMessageForLog(error,sessionId){const message=error instanceof Error?error.message:String(error);return sessionId?message.replaceAll(sessionId,`${sessionIdForLog(sessionId)}...`):message}var plan27,stateSessionSchema2,stateSchema24,name27,Stage27,HandleStreamableHttpFlow;var init_handle_streamable_http_flow=__esm({"libs/sdk/src/transport/flows/handle.streamable-http.flow.ts"(){"use strict";init_session_id_utils();init_common();init_errors();init_ext_apps2();init_ha_headers();init_skill_mode_utils();init_mcp_surface();plan27={pre:["applyNodeHeaders","parseInput","router"],execute:["onInitialize","onMessage","onElicitResult","onSseListener","onExtApps"],post:[],finalize:["cleanup"]};stateSessionSchema2=z116.object({id:z116.string(),payload:z116.object({nodeId:z116.string(),authSig:z116.string(),uuid:z116.string().uuid(),iat:z116.number(),protocol:z116.enum(["legacy-sse","sse","streamable-http","stateful-http","stateless-http"]).optional(),isPublic:z116.boolean().optional(),platformType:z116.enum(["openai","claude","claude-code","codex","gemini","cursor","continue","cody","generic-mcp","ext-apps","unknown"]).optional()}).optional()});stateSchema24=z116.object({token:z116.string(),session:stateSessionSchema2,requestType:z116.enum(["initialize","message","elicitResult","sseListener","extApps"]).optional()});name27="handle:streamable-http";({Stage:Stage27}=FlowHooksOf(name27));HandleStreamableHttpFlow=class extends FlowBase{name=name27;async applyNodeHeaders(){applyMachineIdHeader(this.rawInput.response)}async parseInput(){const{request:request2}=this.rawInput;const authorization=request2[ServerRequestTokens.auth];const{token}=authorization;const logger=this.scopeLogger.child("handle:streamable-http:parseInput");const body=request2.body;const isInitialize2=body?.method==="initialize";const createSession=()=>{const query=request2.query;const skillsOnlyMode=detectSkillsOnlyMode(query);return createSessionId("streamable-http",token,{userAgent:request2.headers?.["user-agent"],platformDetectionConfig:this.scope.metadata.transport?.platformDetection,skillsOnlyMode})};let sessionResolution;if(isInitialize2){if(authorization.session?.id){sessionResolution={session:authorization.session,createdNew:false,responded404:false}}else{sessionResolution={session:createSession(),createdNew:true,responded404:false}}}else{sessionResolution=resolveStreamableHttpSession({rawHeader:request2.headers?.["mcp-session-id"],authorizationSession:authorization.session,createSession})}if(sessionResolution.responded404||!sessionResolution.session){logger.warn("parseInput: mcp-session-id is not a session this server verified");this.respond(httpRespond.sessionNotFound("invalid session id"));return}const session=sessionResolution.session;this.state.set(stateSchema24.parse({token,session}));logger.verbose("parseInput: session resolved",{sessionId:session.id?.slice(0,20)})}async router(){const{request:request2}=this.rawInput;const logger=this.scopeLogger.child("handle:streamable-http:router");const classification=classifyStreamableHttpRequest({method:request2.method,body:request2.body});if("error"in classification){logger.warn("router: invalid request, no valid method");this.respond(httpRespond.rpcError("Invalid Request"));return}this.state.set("requestType",classification.requestType);if(classification.requestType==="sseListener"){logger.verbose("router: requestType=sseListener, method=GET")}else if(classification.requestType==="initialize"){logger.verbose("router: requestType=initialize, method=POST")}else if(classification.requestType==="extApps"){const method=request2.body?.method;logger.verbose(`router: requestType=extApps, method=${method}`)}else if(classification.requestType==="elicitResult"){logger.verbose("router: requestType=elicitResult, method=POST")}else{const method=request2.body?.method;logger.verbose(`router: requestType=message, method=${method}`)}}async onInitialize(){const transportService=this.scope.transportService;if(!transportService){throw new TransportServiceNotAvailableError}const logger=this.scope.logger.child("handle:streamable-http:onInitialize");const{request:request2,response}=this.rawInput;const{token,session}=this.state.required;logger.info("onInitialize: creating transport",{sessionId:session.id?.slice(0,20),hasToken:!!token,tokenPrefix:token?.slice(0,10)});try{const authorization=request2[ServerRequestTokens.auth];syncStreamableHttpAuthorizationSession(authorization,session);const transport=await transportService.createTransporter("streamable-http",token,session.id,response);const isReinitialize=!!request2[ServerRequestTokens.reinitialize];if(transport.isInitialized){logger.info("onInitialize: transport already initialized, resetting for re-initialization",{sessionId:session.id?.slice(0,20),reinitialize:isReinitialize});if(!resetInitializedTransportForReinit(transport)){const requestId=request2.body?.id??null;logger.error("onInitialize: transport still initialized after reset \u2014 cannot re-initialize",{sessionId:session.id?.slice(0,20)});this.respond(buildReinitFailedResponse(session.id,requestId));return}}applyNodeAffinity(response,request2);logger.info("onInitialize: transport created, calling initialize");await transport.initialize(request2,response);logger.info("onInitialize: completed successfully");this.handled()}catch(error){if(error instanceof FlowControl){throw error}logger.error("onInitialize: failed",{error:error instanceof Error?error.message:String(error),stack:error instanceof Error?error.stack:void 0});throw error}}async onElicitResult(){const transportService=this.scope.transportService;if(!transportService){throw new TransportServiceNotAvailableError}const logger=this.scopeLogger.child("handle:streamable-http:onElicitResult");const{request:request2,response}=this.rawInput;const{token,session}=this.state.required;logger.verbose("onElicitResult: starting",{sessionId:session.id?.slice(0,20),hasToken:!!token});let transport=await transportService.getTransporter("streamable-http",token,session.id);if(!transport){try{logger.verbose("onElicitResult: transport not in memory, checking stored session",{sessionId:session.id?.slice(0,20)});const storedSession=await transportService.getStoredSession("streamable-http",token,session.id);if(storedSession){logger.verbose("onElicitResult: recreating transport from stored session",{sessionId:session.id?.slice(0,20),createdAt:storedSession.createdAt,initialized:storedSession.initialized});transport=await transportService.recreateTransporter("streamable-http",token,session.id,storedSession,response)}}catch(error){logger.warn("onElicitResult: failed to recreate transport from stored session",{sessionId:session.id?.slice(0,20),error:errorMessageForLog(error,session.id)})}}if(!transport){logger.warn("onElicitResult: transport not found",{sessionId:session.id?.slice(0,20)});this.respond(httpRespond.sessionExpired("session not found"));return}await transport.handleRequest(request2,response);if(!response.writableEnded){response.status(202).json({jsonrpc:"2.0",result:{}})}this.handled()}async onMessage(){const transportService=this.scope.transportService;if(!transportService){throw new TransportServiceNotAvailableError}const logger=this.scopeLogger.child("handle:streamable-http:onMessage");const{request:request2,response}=this.rawInput;const{token,session}=this.state.required;logger.verbose("onMessage: starting",{sessionId:session.id?.slice(0,20),hasToken:!!token});const transportLookup=await lookupStreamableHttpTransport({transportService,token,sessionId:session.id,response});if(transportLookup.kind!=="transport"){const body=request2.body;if(transportLookup.recreationError){logger.warn("Failed to recreate transport from stored session",{sessionId:session.id?.slice(0,20),error:errorMessageForLog(transportLookup.recreationError,session.id)})}if(transportLookup.kind==="session-expired"){logger.info("Session expired - client should re-initialize",{sessionId:session.id?.slice(0,20),tokenHash:token.slice(0,8),method:body?.["method"],requestId:body?.["id"],mcpSessionId:sessionIdForLog(request2.headers?.["mcp-session-id"])});this.respond(httpRespond.sessionExpired("session expired"))}else{logger.warn("Session not initialized - client attempted request without initializing",{sessionId:session.id?.slice(0,20),tokenHash:token.slice(0,8),method:body?.["method"],requestId:body?.["id"],mcpSessionId:sessionIdForLog(request2.headers?.["mcp-session-id"]),userAgent:request2.headers?.["user-agent"]?.slice(0,50)});this.respond(httpRespond.sessionNotFound("session not initialized"))}return}const transport=transportLookup.transport;logger.verbose("onMessage: transport resolved",{source:transportLookup.source});try{await transport.handleRequest(request2,response);this.handled()}catch(error){if(!(error instanceof FlowControl)){const body=request2.body;logger.error("handleRequest failed",{error:error instanceof Error?{name:error.name,message:error.message,stack:error.stack}:error,method:body?.["method"],id:body?.["id"],sessionId:session.id?.slice(0,20)})}throw error}}async onSseListener(){const transportService=this.scope.transportService;if(!transportService){throw new TransportServiceNotAvailableError}const logger=this.scopeLogger.child("handle:streamable-http:onSseListener");const{request:request2,response}=this.rawInput;const{token,session}=this.state.required;let transport=await transportService.getTransporter("streamable-http",token,session.id);if(!transport){try{const storedSession=await transportService.getStoredSession("streamable-http",token,session.id);if(storedSession){logger.info("Recreating transport from Redis session for SSE listener",{sessionId:session.id?.slice(0,20),createdAt:storedSession.createdAt});transport=await transportService.recreateTransporter("streamable-http",token,session.id,storedSession,response)}}catch(error){logger.warn("Failed to recreate transport from stored session for SSE listener",{sessionId:session.id?.slice(0,20),error:errorMessageForLog(error,session.id)})}}if(!transport){logger.warn("onSseListener: transport not found",{sessionId:session.id?.slice(0,20)});this.respond(httpRespond.notFound("Session not found"));return}await transport.handleRequest(request2,response);this.handled()}async onExtApps(){const transportService=this.scope.transportService;if(!transportService){throw new TransportServiceNotAvailableError}const logger=this.scopeLogger.child("handle:streamable-http:onExtApps");const{request:request2,response}=this.rawInput;const{token,session}=this.state.required;const message=request2.body;const isNotification=!("id"in message);if(this.scope.metadata.extApps?.enabled===false){const rpc=request2.body;logger.verbose("onExtApps: ext-apps disabled by config",{method:rpc?.method});if(isNotification){response.status(202).end();this.handled();return}response.status(200).json({jsonrpc:"2.0",id:rpc?.id??null,error:{code:-32601,message:`Method not found: ${rpc?.method}`}});this.handled();return}logger.verbose("onExtApps: starting",{sessionId:session.id?.slice(0,20),method:request2.body?.method});let transport=await transportService.getTransporter("streamable-http",token,session.id);if(!transport){try{logger.verbose("onExtApps: transport not in memory, checking stored session",{sessionId:session.id?.slice(0,20)});const storedSession=await transportService.getStoredSession("streamable-http",token,session.id);if(storedSession){logger.verbose("onExtApps: recreating transport from stored session",{sessionId:session.id?.slice(0,20),createdAt:storedSession.createdAt,initialized:storedSession.initialized});transport=await transportService.recreateTransporter("streamable-http",token,session.id,storedSession,response)}}catch(error){logger.warn("onExtApps: failed to recreate transport from stored session",{sessionId:session.id?.slice(0,20),error:errorMessageForLog(error,session.id)})}}if(!transport){const wasCreated=await transportService.wasSessionCreatedAsync("streamable-http",token,session.id);if(wasCreated){logger.info("onExtApps: session expired - client should re-initialize",{sessionId:session.id?.slice(0,20)});this.respond(httpRespond.sessionExpired("session expired"))}else{logger.warn("onExtApps: session not initialized - client attempted request without initializing",{sessionId:session.id?.slice(0,20)});this.respond(httpRespond.sessionNotFound("session not initialized"))}return}const configuredCapabilities=this.scope.metadata.extApps?.hostCapabilities;const hostCapabilities={serverToolProxy:configuredCapabilities?.serverToolProxy??true,logging:configuredCapabilities?.logging??true,...configuredCapabilities,openLink:false,modelContextUpdate:false,widgetTools:false};const unsupported=["openLink","modelContextUpdate","widgetTools"].filter(key=>configuredCapabilities?.[key]===true);if(unsupported.length>0){logger.warn(`onExtApps: extApps.hostCapabilities ${unsupported.join(", ")} are not supported yet and are not advertised`)}const{user,scopes,claims:claims3}=request2[ServerRequestTokens.auth];const handler=createExtAppsMessageHandler({context:{sessionId:session.id,logger:this.scope.logger,callTool:async(name59,args)=>{const result=await this.scope.runFlow("tools:call-tool",{request:{method:"tools/call",params:{name:name59,arguments:args}},ctx:{authInfo:{sessionId:session.id,sessionIdPayload:session.payload,token,user,scopes:Array.isArray(scopes)?[...scopes]:[],...claims3?{claims:structuredClone(claims3)}:{},clientId:user?.sub??""},surface:mcpRequestSurface(this.scope),_skipUI:true}});const parsed=CallToolResultSchema4.safeParse(result);if(parsed.success){return parsed.data}throw new InternalMcpError("Tool call returned invalid result format")}},hostCapabilities});if(isNotification){await handler.handleNotification(message);response.status(202).end();this.handled();return}const jsonRpcResponse=await handler.handleRequest(message);response.status(200).json(jsonRpcResponse);this.handled()}};__decorateClass([Stage27("applyNodeHeaders")],HandleStreamableHttpFlow.prototype,"applyNodeHeaders",1);__decorateClass([Stage27("parseInput")],HandleStreamableHttpFlow.prototype,"parseInput",1);__decorateClass([Stage27("router")],HandleStreamableHttpFlow.prototype,"router",1);__decorateClass([Stage27("onInitialize",{filter:({state:{requestType}})=>requestType==="initialize"})],HandleStreamableHttpFlow.prototype,"onInitialize",1);__decorateClass([Stage27("onElicitResult",{filter:({state:{requestType}})=>requestType==="elicitResult"})],HandleStreamableHttpFlow.prototype,"onElicitResult",1);__decorateClass([Stage27("onMessage",{filter:({state:{requestType}})=>requestType==="message"})],HandleStreamableHttpFlow.prototype,"onMessage",1);__decorateClass([Stage27("onSseListener",{filter:({state:{requestType}})=>requestType==="sseListener"})],HandleStreamableHttpFlow.prototype,"onSseListener",1);__decorateClass([Stage27("onExtApps",{filter:({state:{requestType}})=>requestType==="extApps"})],HandleStreamableHttpFlow.prototype,"onExtApps",1);HandleStreamableHttpFlow=__decorateClass([FrontMcpFlow({name:name27,plan:plan27,access:"authorized",inputSchema:httpInputSchema,outputSchema:httpOutputSchema})],HandleStreamableHttpFlow)}});import{base64Decode as base64Decode4,base64Encode as base64Encode3}from"@frontmcp/utils";function normalizeRequestHeaders(headers){const out={};if(!headers)return out;for(const[name59,value]of Object.entries(headers)){if(typeof value==="string")out[name59.toLowerCase()]=value;else if(Array.isArray(value))out[name59.toLowerCase()]=value.map(String);else if(typeof value==="number")out[name59.toLowerCase()]=String(value)}return out}function serializeRelayRequest(request2){const raw=request2;const url=typeof raw.originalUrl==="string"&&raw.originalUrl?raw.originalUrl:raw.url??"/";const queryIndex=url.indexOf("?");const path4=typeof raw.path==="string"&&raw.path?raw.path:queryIndex>=0?url.slice(0,queryIndex):url;return{method:(raw.method??"GET").toUpperCase(),url,path:path4,headers:normalizeRequestHeaders(raw.headers),query:raw.query&&typeof raw.query==="object"?{...raw.query}:{},...raw.body!==void 0?{body:raw.body}:{},...typeof raw.protocol==="string"?{protocol:raw.protocol}:{},...raw.socket?.encrypted?{encrypted:true}:{},...typeof raw.socket?.remoteAddress==="string"?{peerAddress:raw.socket.remoteAddress}:{}}}function relayedFrom(request2){const value=request2[ServerRequestTokens.relayedFrom];return typeof value==="string"?value:void 0}function isRelayedRequest(request2){return relayedFrom(request2)!==void 0}function createRelayedServerRequest(relayed,sourceNodeId){const headers=normalizeRequestHeaders(relayed.headers);const rawHeaders=[];for(const[name59,value]of Object.entries(headers)){for(const item of Array.isArray(value)?value:[value])rawHeaders.push(name59,item)}const socket={remoteAddress:relayed.peerAddress,encrypted:relayed.encrypted===true,destroyed:false,destroy(){socket.destroyed=true},destroySoon(){socket.destroyed=true}};const request2=Object.assign(new RelayEmitter,{method:relayed.method,url:relayed.url,originalUrl:relayed.url,path:relayed.path,headers,rawHeaders,query:relayed.query??{},body:relayed.body,protocol:relayed.protocol??(socket.encrypted?"https":"http"),secure:(relayed.protocol??(socket.encrypted?"https":"http"))==="https",httpVersion:"1.1",httpVersionMajor:1,httpVersionMinor:1,complete:true,readable:false,readableEnded:false,aborted:false,errored:null,destroyed:false,socket,connection:socket,resume(){if(!request2.readableEnded){request2.readableEnded=true;queueMicrotask(()=>request2.emit("end"))}return request2},pause(){return request2},destroy(){request2.destroyed=true}});if(relayed.body!==void 0&&typeof Buffer!=="undefined"){const text=typeof relayed.body==="string"?relayed.body:JSON.stringify(relayed.body);Object.assign(request2,{rawBody:Buffer.from(text)})}request2[ServerRequestTokens.relayedFrom]=sourceNodeId;return request2}function encodeBytes(bytes){if(bytes.byteLength===0)return void 0;try{return{data:utf8Decoder.decode(bytes),encoding:"utf8"}}catch{return{data:base64Encode3(bytes),encoding:"base64"}}}function encodeRelayChunk(chunk,encoding){if(chunk===void 0||chunk===null)return void 0;if(typeof chunk==="string"){if(chunk.length===0)return void 0;if(encoding==="base64")return{data:chunk,encoding:"base64"};return{data:chunk,encoding:"utf8"}}if(chunk instanceof Uint8Array)return encodeBytes(chunk);if(chunk instanceof ArrayBuffer)return encodeBytes(new Uint8Array(chunk));const text=String(chunk);return text.length>0?{data:text,encoding:"utf8"}:void 0}function decodeRelayChunk(chunk){return chunk.encoding==="base64"?base64Decode4(chunk.data):chunk.data}function isFlatHeaderList(headers){return Array.isArray(headers)}var RelayEmitter,utf8Decoder,HOP_BY_HOP_HEADERS2,RelayServerResponse;var init_relay_http=__esm({"libs/sdk/src/transport/relay/relay-http.ts"(){"use strict";init_common();init_http_location_utils();RelayEmitter=class{listeners=new Map;on(event,listener){const list=this.listeners.get(event)??[];list.push(listener);this.listeners.set(event,list);return this}addListener(event,listener){return this.on(event,listener)}once(event,listener){const wrapper=(...args)=>{this.off(event,wrapper);listener(...args)};wrapper.listener=listener;return this.on(event,wrapper)}off(event,listener){const list=this.listeners.get(event);if(!list)return this;const index=list.findIndex(l=>l===listener||l.listener===listener);if(index>=0)list.splice(index,1);if(list.length===0)this.listeners.delete(event);return this}removeListener(event,listener){return this.off(event,listener)}removeAllListeners(event){if(event===void 0)this.listeners.clear();else this.listeners.delete(event);return this}listenerCount(event){return this.listeners.get(event)?.length??0}emit(event,...args){const list=this.listeners.get(event);if(!list||list.length===0)return false;for(const listener of[...list])listener(...args);return true}};utf8Decoder=new TextDecoder("utf-8",{fatal:true,ignoreBOM:true});HOP_BY_HOP_HEADERS2=new Set(["connection","keep-alive","transfer-encoding","upgrade"]);RelayServerResponse=class extends RelayEmitter{constructor(sink){super();this.sink=sink}sink;statusCode=200;statusMessage="";headersSent=false;writableEnded=false;writableFinished=false;destroyed=false;headerMap=new Map;get writable(){return!this.writableEnded&&!this.destroyed}get finished(){return this.writableEnded}setHeader(name59,value){if(this.headersSent)return this;this.headerMap.set(name59.toLowerCase(),Array.isArray(value)?value.map(String):String(value));return this}getHeader(name59){return this.headerMap.get(name59.toLowerCase())}getHeaders(){return Object.fromEntries(this.headerMap)}getHeaderNames(){return[...this.headerMap.keys()]}hasHeader(name59){return this.headerMap.has(name59.toLowerCase())}removeHeader(name59){if(!this.headersSent)this.headerMap.delete(name59.toLowerCase())}writeHead(statusCode,reasonOrHeaders,maybeHeaders){if(this.headersSent)return this;this.statusCode=statusCode;let headers;if(typeof reasonOrHeaders==="string"){this.statusMessage=reasonOrHeaders;headers=maybeHeaders}else{headers=reasonOrHeaders}if(isFlatHeaderList(headers)){for(let i=0;i+1<headers.length;i+=2)this.setHeader(headers[i],headers[i+1])}else if(headers){for(const[name59,value]of Object.entries(headers)){if(value!==void 0)this.setHeader(name59,value)}}this.sendHead();return this}flushHeaders(){this.sendHead()}status(code){this.statusCode=code;return this}json(body){if(!this.hasHeader("content-type"))this.setHeader("Content-Type","application/json; charset=utf-8");return this.end(JSON.stringify(body))}send(body){if(body===void 0||body===null)return this.end();if(typeof body==="string"){if(!this.hasHeader("content-type"))this.setHeader("Content-Type","text/html; charset=utf-8");return this.end(body)}if(body instanceof Uint8Array){if(!this.hasHeader("content-type"))this.setHeader("Content-Type","application/octet-stream");return this.end(body)}return this.json(body)}redirect(statusOrUrl,maybeUrl){const status=typeof statusOrUrl==="number"?statusOrUrl:302;const location=typeof statusOrUrl==="string"?statusOrUrl:maybeUrl??"/";this.statusCode=status;this.setHeader("Location",toLocationHeader(location));return this.end()}write(chunk,encodingOrCallback,callback){const cb=typeof encodingOrCallback==="function"?encodingOrCallback:callback;if(!this.writable)return false;this.sendHead();const encoded=encodeRelayChunk(chunk,typeof encodingOrCallback==="string"?encodingOrCallback:void 0);if(encoded)this.sink.data(encoded);if(typeof cb==="function")cb();return true}end(chunk,encodingOrCallback,callback){let data=chunk;let encoding=encodingOrCallback;let cb=callback;if(typeof data==="function"){cb=data;data=void 0;encoding=void 0}else if(typeof encoding==="function"){cb=encoding;encoding=void 0}if(this.writableEnded||this.destroyed){if(typeof cb==="function")cb();return this}this.sendHead();const encoded=encodeRelayChunk(data,typeof encoding==="string"?encoding:void 0);if(encoded)this.sink.data(encoded);this.writableEnded=true;this.sink.end();this.writableFinished=true;this.emit("finish");this.emit("close");if(typeof cb==="function")cb();return this}destroy(error){if(this.destroyed)return this;this.destroyed=true;if(error&&this.listenerCount("error")>0)this.emit("error",error);if(!this.writableFinished)this.emit("close");return this}cork(){}uncork(){}setTimeout(){return this}asServerResponse(){return this}sendHead(){if(this.headersSent||this.destroyed)return;this.headersSent=true;const headers={};for(const[name59,value]of this.headerMap){if(!HOP_BY_HOP_HEADERS2.has(name59))headers[name59]=value}this.sink.head(this.statusCode,headers)}}}});var LocalTransporter;var init_transport_local=__esm({"libs/sdk/src/transport/transport.local.ts"(){"use strict";init_transport_errors();init_transport_sse_adapter();init_transport_streamable_http_adapter();init_transport_error();LocalTransporter=class{constructor(scope,key,res,onDispose){this.onDispose=onDispose;this.type=key.type;this.tokenHash=key.tokenHash;const defaultOnDispose=()=>{};switch(this.type){case"sse":this.adapter=new TransportSSEAdapter(scope,key,onDispose??defaultOnDispose,res);break;case"streamable-http":case"stateless-http":this.adapter=new TransportStreamableHttpAdapter(scope,key,onDispose??defaultOnDispose,res);break;default:throw new UnsupportedTransportTypeError(this.type)}}onDispose;type;tokenHash;sessionId;adapter;ping(timeoutMs){throw new MethodNotImplementedError("LocalTransporter","ping")}async handleRequest(req,res){try{await this.adapter.handleRequest(req,res)}catch(err){console.error("MCP POST error:",err instanceof Error?err.message:"Unknown error");res.status(500).json(rpcError("Internal error"))}}async ready(){return this.adapter.ready}async initialize(req,res){try{await this.adapter.ready;return this.adapter.initialize(req,res)}catch(err){console.error("MCP POST error:",err instanceof Error?err.message:"Unknown error");res.status(500).json(rpcError("Internal error"))}}get isInitialized(){return this.adapter.isInitialized}markAsInitialized(){this.adapter.markAsInitialized()}resetForReinitialization(){this.adapter.resetForReinitialization()}reregisterServer(){this.adapter.reregisterServer()}async destroy(reason){try{await this.adapter.destroy(reason)}finally{this.onDispose?.()}}}}});var RemoteTransporter;var init_transport_remote=__esm({"libs/sdk/src/transport/transport.remote.ts"(){"use strict";init_transport_errors();init_transport_error();RemoteTransporter=class{constructor(key,bus,location){this.key=key;this.bus=bus;this.location=location;this.type=key.type;this.tokenHash=key.tokenHash;this.sessionId=key.sessionId}key;bus;location;type;tokenHash;sessionId;get ownerNodeId(){return this.location.nodeId}ping(_timeoutMs){throw new MethodNotImplementedError("RemoteTransporter","ping")}initialize(req,res){return this.relay(req,res)}handleRequest(req,res){return this.relay(req,res)}async destroy(reason){await this.bus.destroyRemote(this.key,reason)}get isInitialized(){return true}markAsInitialized(){}resetForReinitialization(){}reregisterServer(){}async relay(req,res){try{await this.bus.proxyRequest(this.location,this.sessionId,req,res)}catch(error){if(!(error instanceof SessionOwnerUnreachableError)||res.headersSent)throw error;const requestId=req.body?.id??null;res.setHeader("Retry-After",String(error.retryAfterSeconds));res.status(error.statusCode).json(rpcError(error.getPublicMessage(),requestId))}}}}});import{getMachineId as getMachineId4,sha256Hex as sha256Hex20}from"@frontmcp/utils";var SESSION_STORE_RETRY_BASE_MS,SESSION_STORE_RETRY_MAX_MS,DEFAULT_SESSION_CHECK_TIMEOUT_MS,BUS_REFRESH_INTERVAL_MS,MAX_ROUTABLE_SESSION_ID_LENGTH,RELAYABLE_TYPES,TransportService;var init_transport_registry=__esm({"libs/sdk/src/transport/transport.registry.ts"(){"use strict";init_session_store_factory();init_session_id_utils();init_auth_info_utils();init_transport_errors();init_transport_sse_adapter();init_transport_streamable_http_adapter();init_handle_mcp_20260728_flow();init_handle_sse_flow();init_handle_stateless_http_flow();init_handle_streamable_http_flow();init_relay_http();init_transport_local();init_transport_remote();init_transport_types();SESSION_STORE_RETRY_BASE_MS=1e3;SESSION_STORE_RETRY_MAX_MS=3e4;DEFAULT_SESSION_CHECK_TIMEOUT_MS=500;BUS_REFRESH_INTERVAL_MS=15*60*1e3;MAX_ROUTABLE_SESSION_ID_LENGTH=4096;RELAYABLE_TYPES=new Set(["streamable-http","sse"]);TransportService=class{ready;byType=new Map;distributed;bus;scope;sessionHistory=new Map;MAX_SESSION_HISTORY=1e4;sessionStore;persistenceConfig;pendingStoreConfig;backendKind;transportKeyPrefix="mcp:transport:";sessionStoreConfigured=false;creationMutex=new Map;async newLocalTransporter(key,res,onDispose){if(key.type==="streamable-http"||key.type==="stateless-http"){await loadStreamableHttpTransport()}else if(key.type==="sse"){await loadSseTransport()}return new LocalTransporter(this.scope,key,res,onDispose)}getDefaultTtlMs(){if(this.resolvedTtlMs!==void 0)return this.resolvedTtlMs;return typeof this.persistenceConfig==="object"?this.persistenceConfig?.defaultTtlMs:void 0}resolvedTtlMs;storeRetryConfig;storeRetryTimer;storeRetryAttempt=0;destroyed=false;lastTtlRefreshAt=new Map;lastBusRefreshAt=new Map;localSessionIds=new Map;ownershipGeneration=new Map;relinquishing=new Set;storedLocalSessions=new Set;sessionCheckTimeoutMs;pendingSessionChecks=new Map;silentHandoverReads=new Set;getSessionKeyPrefix(){return`${this.transportKeyPrefix}session:`}constructor(scope,persistenceConfig,bus){this.scope=scope;this.persistenceConfig=persistenceConfig;this.distributed=!!bus;this.bus=bus;this.sessionCheckTimeoutMs=(persistenceConfig!==false?persistenceConfig?.sessionCheckTimeoutMs:void 0)??DEFAULT_SESSION_CHECK_TIMEOUT_MS;if(persistenceConfig!==false&&persistenceConfig?.sqlite){this.sessionStoreConfigured=true;this.backendKind="sqlite";const sqliteConfig=persistenceConfig.sqlite;this.transportKeyPrefix="mcp:transport:";this.resolvedTtlMs=persistenceConfig.defaultTtlMs??36e5;this.pendingStoreConfig={sqlite:sqliteConfig,keyPrefix:this.transportKeyPrefix,defaultTtlMs:this.resolvedTtlMs};this.scope.logger.info("[TransportService] sqlite session store will be initialized for transport persistence")}else if(persistenceConfig!==false&&persistenceConfig?.redis){this.sessionStoreConfigured=true;const redisConfig=persistenceConfig.redis;const providerType="provider"in redisConfig?redisConfig.provider:"redis";this.backendKind=providerType==="vercel-kv"?"vercel-kv":"redis";this.transportKeyPrefix=redisConfig.keyPrefix??"mcp:transport:";this.resolvedTtlMs=persistenceConfig.defaultTtlMs??redisConfig.defaultTtlMs??36e5;this.pendingStoreConfig={...redisConfig,keyPrefix:this.transportKeyPrefix,defaultTtlMs:this.resolvedTtlMs};this.scope.logger.info(`[TransportService] ${providerType} session store will be initialized for transport persistence`)}this.storeRetryConfig=this.pendingStoreConfig;this.ready=this.initialize()}async initialize(){if(this.pendingStoreConfig){const connected=await this.connectSessionStore();if(!connected&&this.backendKind!=="sqlite")this.scheduleSessionStoreRetry()}await this.scope.registryFlows(HandleStreamableHttpFlow,HandleSseFlow,HandleStatelessHttpFlow,HandleMcp20260728Flow)}async connectSessionStore(){const storeConfig=this.pendingStoreConfig??this.storeRetryConfig;if(!storeConfig)return false;try{const store=await createSessionStore(storeConfig,this.scope.logger.child("SessionStore"));this.sessionStore=store;this.pendingStoreConfig=void 0}catch(error){const err=error;this.scope.logger.error("[TransportService] Failed to create session store - session persistence disabled",{error:err.message,cause:err.cause?.message});return false}const isConnected=this.sessionStore?.ping?await this.sessionStore.ping():true;if(!isConnected){const providerType=this.backendKind??"redis";this.scope.logger.error(`[TransportService] Failed to connect to ${providerType} - session persistence disabled`);await this.teardownSessionStore().catch(()=>void 0);return false}this.scope.logger.info("[TransportService] Session store connection validated successfully");return true}scheduleSessionStoreRetry(){if(this.destroyed||this.storeRetryTimer)return;const delay=Math.min(SESSION_STORE_RETRY_MAX_MS,SESSION_STORE_RETRY_BASE_MS*2**this.storeRetryAttempt);this.storeRetryAttempt++;this.storeRetryTimer=setTimeout(()=>{this.storeRetryTimer=void 0;void this.retrySessionStore()},delay);this.storeRetryTimer.unref?.()}async retrySessionStore(){if(this.destroyed||this.sessionStore)return;const connected=await this.connectSessionStore().catch(()=>false);if(this.destroyed){await this.teardownSessionStore().catch(()=>void 0);return}if(connected){this.storeRetryAttempt=0;this.scope.logger.info("[TransportService] Session store recovered after startup failure");return}this.scheduleSessionStoreRetry()}async destroy(){this.destroyed=true;if(this.storeRetryTimer){clearTimeout(this.storeRetryTimer);this.storeRetryTimer=void 0}this.lastTtlRefreshAt.clear();this.lastBusRefreshAt.clear();this.ownershipGeneration.clear();this.storedLocalSessions.clear();await this.teardownSessionStore()}async teardownSessionStore(){if(!this.sessionStore)return;const teardown=this.sessionStore.disconnect??this.sessionStore.close;if(!teardown){this.sessionStore=void 0;return}try{await Promise.resolve(teardown.call(this.sessionStore));this.scope.logger.info("[TransportService] Session store disconnected",{backendKind:this.backendKind??"unknown"})}catch(error){this.scope.logger.warn("[TransportService] Error disconnecting session store",{error:error.message,backendKind:this.backendKind??"unknown"})}finally{this.sessionStore=void 0}}async pingSessionStore(){if(!this.sessionStoreConfigured)return true;if(!this.sessionStore)return false;if(typeof this.sessionStore.ping==="function"){return this.sessionStore.ping()}return true}isSessionStoreConfigured(){return this.sessionStoreConfigured}getBackendKind(){return this.backendKind}sessionStoreLabel(){switch(this.backendKind){case"sqlite":return"SQLite";case"vercel-kv":return"Vercel KV";case"redis":return"Redis";default:return"the session store"}}refreshStoredSessionTtl(sessionId){const store=this.sessionStore;const ttlMs=this.getDefaultTtlMs();if(!store||!ttlMs||this.backendKind!=="redis"&&this.backendKind!=="vercel-kv")return;const now=Date.now();const last=this.lastTtlRefreshAt.get(sessionId);if(last!==void 0&&now-last<Math.max(1e3,Math.floor(ttlMs/4)))return;this.lastTtlRefreshAt.set(sessionId,now);store.get(sessionId).catch(err=>{this.scope.logger.warn("[TransportService] Failed to refresh session TTL",{sessionId:sessionId.slice(0,20),error:err instanceof Error?err.message:String(err)})})}async getTransporter(type,token,sessionId){const key=this.keyOf(type,token,sessionId);const local=this.lookupLocal(key);if(local&&await this.holdsLocalSession(sessionId)){this.refreshStoredSessionTtl(sessionId);this.refreshBusAdvertisement(key);return local}if(this.distributed&&this.bus){const location=await this.bus.lookup(key);if(location){if(await this.isNodeAlive(location.nodeId)){return new RemoteTransporter(key,this.bus,location)}this.scope.logger.info("[HA] Session owner is gone \u2014 the session will be taken over",{sessionId:sessionId.slice(0,20),previousNodeId:location.nodeId})}}return void 0}async findRemoteSessionOwner(request2){if(!this.distributed||!this.bus?.canRelay()||isRelayedRequest(request2))return void 0;const sessionId=sessionIdPresentedBy(request2);if(!sessionId||sessionId.length>MAX_ROUTABLE_SESSION_ID_LENGTH)return void 0;if(!isDeploymentSessionId(sessionId))return void 0;try{if(this.localSessionIds.has(sessionId)&&await this.holdsLocalSession(sessionId))return void 0;const owner=await this.lookupSessionOwner(sessionId);if(!owner||owner.nodeId===getMachineId4())return void 0;return await this.isNodeAlive(owner.nodeId)?owner:void 0}catch(error){this.scope.logger.warn("[HA] Could not resolve the session owner \u2014 serving the request here",{sessionId:sessionId.slice(0,20),error:error instanceof Error?error.message:String(error)});return void 0}}async lookupSessionOwner(sessionId){if(!this.bus)return void 0;const advertised=await this.bus.lookupOwner(sessionId);if(advertised)return advertised;const stored=this.sessionStore?await this.sessionStore.get(sessionId):null;const nodeId=stored?.session?.nodeId;if(!nodeId)return void 0;return{nodeId,channel:this.bus.channelOf(nodeId)}}async relayToSessionOwner(location,request2,response){if(!this.bus)throw new InvalidTransportSessionError("Session relay requires the distributed transport bus.");const sessionId=sessionIdPresentedBy(request2)??"";await this.bus.proxyRequest(location,sessionId,request2,response)}async adoptClaimedSession(sessionId,previousNodeId,info){if(!this.bus)return;const type=info.protocol;if(!info.authorizationId||type!=="streamable-http"&&type!=="sse")return;await this.bus.advertise({type,token:"",tokenHash:info.authorizationId,sessionId});this.scope.logger.info("[HA] Adopted an orphaned session \u2014 this node now serves it",{sessionId:sessionId.slice(0,20),previousNodeId})}async destroyLocalSession(sessionId,reason){let found=false;for(const[type,typeBucket]of[...this.byType.entries()]){if(!RELAYABLE_TYPES.has(type))continue;for(const tokenBucket of[...typeBucket.values()]){const transporter=tokenBucket.get(sessionId);if(!transporter)continue;found=true;await transporter.destroy(reason)}}return found}async holdsLocalSession(sessionId){if(!this.distributed)return this.isStillStored(sessionId);const haManager=this.scope.haManager;const store=this.sessionStore;if(!haManager||!store)return true;const generation=haManager.livenessGeneration();if(generation!==void 0&&this.ownershipGeneration.get(sessionId)===generation)return true;let ownerNodeId;try{ownerNodeId=(await this.withSessionCheckTimeout(`get:${sessionId}`,()=>store.get(sessionId)))?.session?.nodeId}catch(error){this.scope.logger.warn("[HA] Could not confirm this node still owns the session \u2014 serving it here",{sessionId:sessionId.slice(0,20),error:error instanceof Error?error.message:String(error)});return true}if(!ownerNodeId||ownerNodeId===getMachineId4()){if(generation!==void 0)this.ownershipGeneration.set(sessionId,generation);return true}this.scope.logger.warn("[HA] Another node took this session over while this node was unreachable \u2014 dropping it here",{sessionId:sessionId.slice(0,20),ownerNodeId});this.relinquishing.add(sessionId);try{await this.destroyLocalSession(sessionId,"the session moved to another node")}finally{this.relinquishing.delete(sessionId)}return false}async isStillStored(sessionId){const store=this.sessionStore;if(!store||!this.storedLocalSessions.has(sessionId))return true;try{if(await this.withSessionCheckTimeout(`exists:${sessionId}`,()=>store.exists(sessionId)))return true}catch(error){this.scope.logger.warn("[TransportService] Could not confirm the session is still stored \u2014 serving it here",{sessionId:sessionId.slice(0,20),error:error instanceof Error?error.message:String(error)});return true}this.scope.logger.info("[TransportService] The stored session is gone \u2014 dropping its transport here",{sessionId:sessionId.slice(0,20)});await this.destroyLocalSession(sessionId,"the session was deleted");return false}sessionEndCheck(sessionId){const store=this.sessionStore;if(this.distributed||!store||!this.storedLocalSessions.has(sessionId))return void 0;return()=>{if(this.silentHandoverReads.has(sessionId))return Promise.resolve(false);const read=store.exists(sessionId);return this.raceSessionCheckTimeout(read).then(stored=>!stored,()=>{this.silentHandoverReads.add(sessionId);read.then(()=>this.silentHandoverReads.delete(sessionId),()=>this.silentHandoverReads.delete(sessionId));return false})}}withSessionCheckTimeout(key,issueRead){let read=this.pendingSessionChecks.get(key);if(!read){read=issueRead().finally(()=>this.pendingSessionChecks.delete(key));this.pendingSessionChecks.set(key,read)}return this.raceSessionCheckTimeout(read)}raceSessionCheckTimeout(read){const timeoutMs=this.sessionCheckTimeoutMs;let timer;const timedOut=new Promise((_resolve,reject)=>{timer=setTimeout(()=>reject(new Error(`The session store did not answer within ${timeoutMs} ms`)),timeoutMs);timer.unref?.()});return Promise.race([read,timedOut]).finally(()=>clearTimeout(timer))}async isNodeAlive(nodeId){const haManager=this.scope.haManager;if(!haManager)return true;try{return await haManager.isNodeAlive(nodeId)}catch{return true}}refreshBusAdvertisement(key){if(!this.distributed||!this.bus||!RELAYABLE_TYPES.has(key.type))return;const now=Date.now();const last=this.lastBusRefreshAt.get(key.sessionId);if(last!==void 0&&now-last<BUS_REFRESH_INTERVAL_MS)return;this.lastBusRefreshAt.set(key.sessionId,now);this.bus.advertise(key).catch(err=>{this.scope.logger.warn("[HA] Failed to refresh the session advertisement",{sessionId:key.sessionId.slice(0,20),error:err instanceof Error?err.message:String(err)})})}async getStoredSession(type,token,sessionId,options){if(!this.sessionStore||type!=="streamable-http"&&type!=="sse")return void 0;const tokenHash=this.sha256(token);const stored=await this.sessionStore.get(sessionId);if(!stored)return void 0;if(stored.authorizationId!==tokenHash){this.scope.logger.warn("[TransportService] Session token mismatch during lookup",{sessionId:sessionId.slice(0,20),storedTokenHash:stored.authorizationId.slice(0,8),requestTokenHash:tokenHash.slice(0,8)});return void 0}if(options?.clientFingerprint&&stored.session.clientFingerprint){if(stored.session.clientFingerprint!==options.clientFingerprint){this.scope.logger.warn("[TransportService] Client fingerprint mismatch",{sessionId:sessionId.slice(0,20),storedFingerprint:stored.session.clientFingerprint.slice(0,8),requestFingerprint:options.clientFingerprint.slice(0,8)});if(!options.warnOnFingerprintMismatch){return void 0}}}return stored}async recreateTransporter(type,token,sessionId,storedSession,res){const key=this.keyOf(type,token,sessionId);const existing=this.lookupLocal(key);if(existing)return existing;const mutexKey=JSON.stringify({t:type,h:key.tokenHash,s:sessionId});const pendingCreation2=this.creationMutex.get(mutexKey);if(pendingCreation2){return pendingCreation2}const recreationPromise=this.doRecreateTransporter(key,sessionId,storedSession,res);this.creationMutex.set(mutexKey,recreationPromise);try{return await recreationPromise}catch(error){this.scope.logger.error("[TransportService] Failed to recreate transport from stored session",{sessionId:sessionId.slice(0,20),error:error instanceof Error?{name:error.name,message:error.message}:String(error)});throw error}finally{this.creationMutex.delete(mutexKey)}}async remoteOwnerTransporter(key,ownerNodeId){if(!this.distributed||!this.bus)return void 0;if(!await this.isNodeAlive(ownerNodeId))return void 0;return new RemoteTransporter(key,this.bus,{nodeId:ownerNodeId,channel:this.bus.channelOf(ownerNodeId)})}async doRecreateTransporter(key,sessionId,storedSession,res){const existing=this.lookupLocal(key);if(existing)return existing;this.scope.logger.info("[TransportService] Recreating transport from stored session",{sessionId:sessionId.slice(0,20),protocol:storedSession.session.protocol,createdAt:storedSession.createdAt});const currentNodeId=getMachineId4();const ownerNodeId=storedSession.session.nodeId;let latestSession=storedSession;if(this.scope.haManager&&ownerNodeId&&ownerNodeId!==currentNodeId){const remote=await this.remoteOwnerTransporter(key,ownerNodeId);if(remote)return remote;const sessionKey=`${this.getSessionKeyPrefix()}${sessionId}`;const result=await this.scope.haManager.attemptTakeover(sessionKey,ownerNodeId);if(result.claimed){latestSession={...storedSession,reassignedAt:result.reassignedAt,reassignedFrom:ownerNodeId};this.scope.logger.info("[HA] Took over session from a stopped node",{sessionId:sessionId.slice(0,20),previousNodeId:ownerNodeId})}else{const current=this.sessionStore?await this.sessionStore.get(sessionId):null;const newOwner=current?.session?.nodeId;if(newOwner!==currentNodeId){const relayed=newOwner?await this.remoteOwnerTransporter(key,newOwner):void 0;if(relayed)return relayed;this.scope.logger.debug("[HA] Session already claimed by another pod",{sessionId:sessionId.slice(0,20)});throw new SessionClaimConflictError(sessionId)}if(current)latestSession=current}}const historyKey=this.makeHistoryKey(key.type,key.tokenHash,sessionId);this.sessionHistory.set(historyKey,storedSession.createdAt);const sessionStore=this.sessionStore;const defaultTtlMs=this.getDefaultTtlMs();const transporter=await this.newLocalTransporter(key,res,()=>this.onSessionTransportDisposed(key,sessionId,sessionStore));await transporter.ready();if(storedSession.initialized!==false){transporter.markAsInitialized()}this.insertLocal(key,transporter);if(sessionStore)this.storedLocalSessions.add(sessionId);if(storedSession.clientCapabilities){this.scope.notifications.setClientCapabilities(sessionId,storedSession.clientCapabilities);this.scope.logger.verbose("[TransportService] Restored client capabilities from stored session",{sessionId:sessionId.slice(0,20)})}if(sessionStore){const updatedSession={...latestSession,session:{...latestSession.session,nodeId:currentNodeId},lastAccessedAt:Date.now()};sessionStore.set(sessionId,updatedSession,defaultTtlMs).catch(err=>{this.scope.logger.warn(`[TransportService] Failed to update session in ${this.sessionStoreLabel()}`,{sessionId:sessionId.slice(0,20),error:err instanceof Error?err.message:String(err)})})}if(this.distributed&&this.bus){await this.bus.advertise(key)}return transporter}async createTransporter(type,token,sessionId,res){const key=this.keyOf(type,token,sessionId);const existing=this.lookupLocal(key);if(existing)return existing;const mutexKey=JSON.stringify({t:type,h:key.tokenHash,s:sessionId});const pendingCreation2=this.creationMutex.get(mutexKey);if(pendingCreation2){return pendingCreation2}const creationPromise=this.doCreateTransporter(key,sessionId,res,type);this.creationMutex.set(mutexKey,creationPromise);try{return await creationPromise}finally{this.creationMutex.delete(mutexKey)}}async doCreateTransporter(key,sessionId,res,type){const existing=this.lookupLocal(key);if(existing)return existing;const sessionStore=this.sessionStore;const defaultTtlMs=this.getDefaultTtlMs();const transporter=await this.newLocalTransporter(key,res,()=>this.onSessionTransportDisposed(key,sessionId,sessionStore));await transporter.ready();this.insertLocal(key,transporter);if(sessionStore&&(type==="streamable-http"||type==="sse")){const storedSession={session:{id:sessionId,authorizationId:key.tokenHash,protocol:type==="sse"?"sse":"streamable-http",createdAt:Date.now(),nodeId:getMachineId4()},authorizationId:key.tokenHash,createdAt:Date.now(),lastAccessedAt:Date.now(),initialized:true};sessionStore.set(sessionId,storedSession,defaultTtlMs).then(()=>{if(this.localSessionIds.has(sessionId))this.storedLocalSessions.add(sessionId)},err=>{this.scope.logger.warn(`[TransportService] Failed to persist session to ${this.sessionStoreLabel()}`,{sessionId:sessionId.slice(0,20),error:err instanceof Error?err.message:String(err)})})}if(this.distributed&&this.bus){await this.bus.advertise(key)}return transporter}onSessionTransportDisposed(key,sessionId,sessionStore){key.sessionId=sessionId;this.evictLocal(key);if(this.distributed&&this.bus){this.bus.revoke(key).catch(()=>void 0)}if(sessionStore&&!this.relinquishing.has(sessionId)){sessionStore.delete(sessionId).catch(()=>void 0)}}async destroyTransporter(type,token,sessionId,reason){const key=this.keyOf(type,token,sessionId);const local=this.lookupLocal(key);if(local){await local.destroy(reason);return}if(this.distributed&&this.bus){const location=await this.bus.lookup(key);if(location){await this.bus.destroyRemote(key,reason);return}}throw new InvalidTransportSessionError("Invalid session: cannot destroy non-existent transporter.")}async deleteStoredSession(sessionId){if(!this.sessionStore)return;try{await this.sessionStore.delete(sessionId)}catch(err){this.scope.logger.warn(`[TransportService] Failed to delete session from ${this.sessionStoreLabel()}`,{sessionId:sessionId.slice(0,20),error:err instanceof Error?err.message:String(err)});throw err}}async updateStoredSessionCapabilities(sessionId,clientCapabilities){if(!this.sessionStore)return;try{const stored=await this.sessionStore.get(sessionId);if(!stored){this.scope.logger.verbose("[TransportService] Cannot update capabilities: session not found in store",{sessionId:sessionId.slice(0,20)});return}const updatedSession={...stored,clientCapabilities,lastAccessedAt:Date.now()};const defaultTtlMs=this.getDefaultTtlMs();await this.sessionStore.set(sessionId,updatedSession,defaultTtlMs);this.scope.logger.verbose("[TransportService] Persisted client capabilities to session store",{sessionId:sessionId.slice(0,20)})}catch(err){this.scope.logger.warn("[TransportService] Failed to persist client capabilities",{sessionId:sessionId.slice(0,20),error:err instanceof Error?err.message:String(err)})}}async getOrCreateAnonymousStatelessTransport(type,res){return this.getOrCreateStatelessTransport(this.keyOf(type,"__anonymous__",STATELESS_SESSION_ID),res)}async getOrCreateAuthenticatedStatelessTransport(type,token,res){return this.getOrCreateStatelessTransport(this.keyOf(type,token,STATELESS_SESSION_ID),res)}async getOrCreateStatelessTransport(key,res){const existing=this.lookupLocal(key);if(existing)return existing;const mutexKey=JSON.stringify({t:key.type,h:key.tokenHash,s:key.sessionId});const pendingCreation2=this.creationMutex.get(mutexKey);if(pendingCreation2)return pendingCreation2;const creationPromise=this.doCreateStatelessTransport(key,res);this.creationMutex.set(mutexKey,creationPromise);try{return await creationPromise}finally{this.creationMutex.delete(mutexKey)}}async doCreateStatelessTransport(key,res){const transporter=await this.newLocalTransporter(key,res,()=>{this.evictLocal(key);if(this.distributed&&this.bus){this.bus.revoke(key).catch(()=>void 0)}});await transporter.ready();this.insertLocal(key,transporter);if(this.distributed&&this.bus){await this.bus.advertise(key)}return transporter}wasSessionCreated(type,token,sessionId){const tokenHash=this.sha256(token);const historyKey=this.makeHistoryKey(type,tokenHash,sessionId);return this.sessionHistory.has(historyKey)}async wasSessionCreatedAsync(type,token,sessionId){if(this.wasSessionCreated(type,token,sessionId)){return true}if(this.sessionStore&&(type==="streamable-http"||type==="sse")){const stored=await this.getStoredSession(type,token,sessionId);return stored!==void 0}return false}sha256(value){return sha256Hex20(value)}makeHistoryKey(type,tokenHash,sessionId){return JSON.stringify({t:type,h:tokenHash,s:sessionId})}parseHistoryKey(key){try{const parsed=JSON.parse(key);if(typeof parsed.t==="string"&&typeof parsed.h==="string"&&typeof parsed.s==="string"){return{type:parsed.t,tokenHash:parsed.h,sessionId:parsed.s}}return void 0}catch{return void 0}}keyOf(type,token,sessionId,sessionIdSse){return{type,token,tokenHash:this.sha256(token),sessionId,sessionIdSse}}ensureTypeBucket(type){let bucket=this.byType.get(type);if(!bucket){bucket=new Map;this.byType.set(type,bucket)}return bucket}ensureTokenBucket(typeBucket,tokenHash){let bucket=typeBucket.get(tokenHash);if(!bucket){bucket=new Map;typeBucket.set(tokenHash,bucket)}return bucket}lookupLocal(key){const typeBucket=this.byType.get(key.type);if(!typeBucket)return void 0;const tokenBucket=typeBucket.get(key.tokenHash);if(!tokenBucket)return void 0;return tokenBucket.get(key.sessionId)}insertLocal(key,t){const typeBucket=this.ensureTypeBucket(key.type);const tokenBucket=this.ensureTokenBucket(typeBucket,key.tokenHash);if(!tokenBucket.has(key.sessionId)){this.localSessionIds.set(key.sessionId,(this.localSessionIds.get(key.sessionId)??0)+1)}tokenBucket.set(key.sessionId,t);const generation=this.distributed?this.scope.haManager?.livenessGeneration():void 0;if(generation!==void 0)this.ownershipGeneration.set(key.sessionId,generation);const historyKey=this.makeHistoryKey(key.type,key.tokenHash,key.sessionId);this.sessionHistory.set(historyKey,Date.now());if(this.sessionHistory.size>this.MAX_SESSION_HISTORY){const entries=[...this.sessionHistory.entries()].sort((a,b)=>a[1]-b[1]);const targetEvictions=Math.ceil(this.MAX_SESSION_HISTORY*.1);let evicted=0;for(const[histKey]of entries){if(evicted>=targetEvictions)break;const parsed=this.parseHistoryKey(histKey);if(!parsed){this.sessionHistory.delete(histKey);evicted++;continue}const{type,tokenHash,sessionId}=parsed;const typeBucket2=this.byType.get(type);const tokenBucket2=typeBucket2?.get(tokenHash);const hasActiveTransport=tokenBucket2?.has(sessionId)??false;if(!hasActiveTransport){this.sessionHistory.delete(histKey);evicted++}}if(evicted<targetEvictions){this.scope.logger.warn("[TransportService] Session history eviction: unable to free target memory",{targetEvictions,actualEvictions:evicted,currentSize:this.sessionHistory.size,maxSize:this.MAX_SESSION_HISTORY})}}}evictLocal(key){this.lastTtlRefreshAt.delete(key.sessionId);this.lastBusRefreshAt.delete(key.sessionId);const typeBucket=this.byType.get(key.type);if(!typeBucket)return;const tokenBucket=typeBucket.get(key.tokenHash);if(!tokenBucket)return;if(tokenBucket.delete(key.sessionId)){const remaining=(this.localSessionIds.get(key.sessionId)??1)-1;if(remaining>0)this.localSessionIds.set(key.sessionId,remaining);else{this.localSessionIds.delete(key.sessionId);this.ownershipGeneration.delete(key.sessionId);this.storedLocalSessions.delete(key.sessionId)}}if(tokenBucket.size===0)typeBucket.delete(key.tokenHash);if(typeBucket.size===0)this.byType.delete(key.type)}}}});function loadStreamableHttpTransportOnStart(scope){const{enableStreamableHttp,enableStatelessHttp,enableStatefulHttp}=toLegacyProtocolFlags(scope.metadata.transport?.protocol);if(!enableStreamableHttp&&!enableStatelessHttp&&!enableStatefulHttp)return;scope.onServerStarted(()=>{setImmediate(()=>{loadStreamableHttpTransport().catch(error=>scope.logger.verbose("Streamable HTTP transport preload failed",{error}))})})}var init_streamable_http_preload=__esm({"libs/sdk/src/transport/streamable-http-preload.ts"(){"use strict";init_schema7();init_transport_streamable_http_adapter()}});function getErrorMessage(err){if(err instanceof Error)return err.message;return String(err)}function createStorageProbe(name59,adapter){return{name:name59,async check(){const start=Date.now();try{const ok=await adapter.ping();const latencyMs=Date.now()-start;return{status:ok?"healthy":"unhealthy",latencyMs,...!ok?{error:"Ping returned false"}:{}}}catch(err){return{status:"unhealthy",latencyMs:Date.now()-start,error:getErrorMessage(err)}}}}}function createRemoteAppProbe(appId,provider){return{name:`remote:${appId}`,async check(){const result=provider.getHealthStatus(appId);if(!result||result.status==="unknown"&&result.consecutiveFailures===0){return{status:"degraded",details:{state:"unknown"}}}return{status:result.status==="healthy"?"healthy":result.status==="degraded"?"degraded":"unhealthy",latencyMs:result.latencyMs,...result.error?{error:result.error}:{}}}}}function createTransportSessionProbe(provider){return{name:"session-store",async check(){const start=Date.now();try{const ok=await provider.pingSessionStore();const latencyMs=Date.now()-start;return{status:ok?"healthy":"unhealthy",latencyMs,...!ok?{error:"Session store ping returned false"}:{}}}catch(err){return{status:"unhealthy",latencyMs:Date.now()-start,error:getErrorMessage(err)}}}}}var init_health_probes=__esm({"libs/sdk/src/health/health.probes.ts"(){"use strict"}});import{getRuntimeContext as getRuntimeContext21,sha256Hex as sha256Hex21}from"@frontmcp/utils";var processStartTime,HealthService;var init_health_service=__esm({"libs/sdk/src/health/health.service.ts"(){"use strict";init_health_probes();processStartTime=Date.now();HealthService=class{probeSources=[];config;serverInfo;scopeView;constructor(config,serverInfo){this.config=config;this.serverInfo=serverInfo}registerProbe(probe2){this.probeSources.push(()=>[probe2])}registerProbeSource(source){this.probeSources.push(source)}autoDiscoverProbes(scope){this.scopeView=scope;if(scope.transportService){this.registerProbe(createTransportSessionProbe(scope.transportService))}for(const app of scope.apps.getApps()){if(app.isRemote&&typeof app.getMcpClient==="function"){const client=app.getMcpClient();if(client&&typeof client.getHealthStatus==="function"){this.registerProbe(createRemoteAppProbe(app.id,client))}}}if(scope.haManager?.isStarted()){const ha=scope.haManager;this.registerProbe({name:"ha",check:async()=>{const alive=await ha.isNodeAlive(ha.getNodeId());return{status:alive?"healthy":"unhealthy",details:{nodeId:ha.getNodeId(),heartbeatActive:alive}}}})}this.registerProbeSource(()=>scope.healthProbes??[]);const userProbes=this.config.probes??[];for(const probe2 of userProbes){if(probe2&&typeof probe2.check==="function"&&typeof probe2.name==="string"){this.registerProbe({name:probe2.name,check:()=>probe2.check()})}}}getHealthz(){const ctx=getRuntimeContext21();return{status:"ok",server:{name:this.serverInfo.name??"unknown",version:this.serverInfo.version??"unknown"},runtime:{platform:ctx.platform,runtime:ctx.runtime,deployment:ctx.deployment,env:ctx.env},uptime:(Date.now()-processStartTime)/1e3}}async getReadyz(){const start=Date.now();const timeoutMs=this.config.readyz?.timeoutMs??5e3;const includeDetails=this.resolveIncludeDetails();const results=await Promise.all(this.getProbes().map(async probe2=>{const result=await this.runProbeWithTimeout(probe2,timeoutMs);return{name:probe2.name,result}}));const hasUnhealthy=results.some(r=>r.result.status==="unhealthy");const catalog=this.computeCatalogInfo();const response={status:hasUnhealthy?"not_ready":"ready",totalLatencyMs:Date.now()-start,catalog};if(includeDetails){const probes={};for(const{name:name59,result}of results){probes[name59]=result}response.probes=probes}return response}getProbeCount(){return this.getProbes().length}getProbes(){return this.probeSources.flatMap(source=>source())}setScopeView(scope){this.scopeView=scope}async runProbeWithTimeout(probe2,timeoutMs){let timeoutId;try{const timeoutPromise=new Promise(resolve4=>{timeoutId=setTimeout(()=>resolve4({status:"unhealthy",latencyMs:timeoutMs,error:`Probe timed out after ${timeoutMs}ms`}),timeoutMs)});return await Promise.race([probe2.check(),timeoutPromise])}catch(err){return{status:"unhealthy",error:err instanceof Error?err.message:String(err)}}finally{if(timeoutId!==void 0){clearTimeout(timeoutId)}}}computeCatalogInfo(){if(!this.scopeView){return{toolsHash:"",toolCount:0,resourceCount:0,promptCount:0,skillCount:0,agentCount:0}}const tools=this.scopeView.tools.getTools(true);const toolNames=tools.map(t=>t.name).sort();const toolsHash=sha256Hex21(toolNames.join(","));return{toolsHash,toolCount:tools.length,resourceCount:this.scopeView.resources.getResources(true).length,promptCount:this.scopeView.prompts.getPrompts(true).length,skillCount:this.scopeView.skills.getSkills(true).length,agentCount:this.scopeView.agents.getAgents().length}}resolveIncludeDetails(){if(this.config.includeDetails!==void 0){return this.config.includeDetails}const ctx=getRuntimeContext21();return ctx.env!=="production"}}}});var health_exports={};__export(health_exports,{HealthService:()=>HealthService,createRemoteAppProbe:()=>createRemoteAppProbe,createStorageProbe:()=>createStorageProbe,createTransportSessionProbe:()=>createTransportSessionProbe,isReadyzEnabled:()=>isReadyzEnabled,registerHealthRoutes:()=>registerHealthRoutes,servedHealthPaths:()=>servedHealthPaths});var init_health2=__esm({"libs/sdk/src/health/index.ts"(){"use strict";init_health_probes();init_health_service();init_health_routes()}});var http_scope_helper_exports={};__export(http_scope_helper_exports,{HealthService:()=>HealthService,HttpIpFilterFlow:()=>HttpIpFilterFlow,HttpRequestFlow:()=>HttpRequestFlow,HttpRouteFlow:()=>HttpRouteFlow,TransportService:()=>TransportService,attachHttpRoutes:()=>attachHttpRoutes,loadStreamableHttpTransportOnStart:()=>loadStreamableHttpTransportOnStart,registerCustomHttpRoutes:()=>registerCustomHttpRoutes,servedHealthPaths:()=>servedHealthPaths});var init_http_scope_helper=__esm({"libs/sdk/src/scope/http-scope.helper.ts"(){"use strict";init_http_route_flow();init_http_route_table();init_http_request_flow();init_http_ip_filter_flow();init_transport_registry();init_streamable_http_preload();init_custom_routes_helper();init_health2()}});var DEFAULT_HA_CONFIG;var init_ha_types=__esm({"libs/sdk/src/ha/ha.types.ts"(){"use strict";init_ha_constants();DEFAULT_HA_CONFIG={heartbeatIntervalMs:1e4,heartbeatTtlMs:3e4,takeoverGracePeriodMs:5e3,redisKeyPrefix:"mcp:ha:",affinityCookieName:DEFAULT_FRONTMCP_NODE_COOKIE,machineIdHeader:DEFAULT_FRONTMCP_MACHINE_ID_HEADER}}});var HeartbeatService;var init_heartbeat_service=__esm({"libs/sdk/src/ha/heartbeat.service.ts"(){"use strict";init_ha_types();HeartbeatService=class{constructor(redis,nodeId,config){this.redis=redis;this.nodeId=nodeId;this.startedAt=Date.now();this.lastBeatAt=this.startedAt;this.keyPrefix=config?.redisKeyPrefix??DEFAULT_HA_CONFIG.redisKeyPrefix;this.intervalMs=config?.heartbeatIntervalMs??DEFAULT_HA_CONFIG.heartbeatIntervalMs;this.ttlMs=config?.heartbeatTtlMs??DEFAULT_HA_CONFIG.heartbeatTtlMs}redis;nodeId;timer;startedAt;keyPrefix;intervalMs;ttlMs;sessionCount=0;lastBeatAt;lapses=0;start(){if(this.timer)return;this.writeHeartbeat();this.timer=setInterval(()=>this.writeHeartbeat(),this.intervalMs);if(this.timer.unref)this.timer.unref()}async stop(){if(this.timer){clearInterval(this.timer);this.timer=void 0}try{await this.redis.del(this.heartbeatKey())}catch{}}setSessionCount(count){this.sessionCount=count}async isAlive(nodeId){const exists=await this.redis.exists(`${this.keyPrefix}heartbeat:${nodeId}`);return exists===1}async getHeartbeat(nodeId){const raw=await this.redis.get(`${this.keyPrefix}heartbeat:${nodeId}`);if(!raw)return null;try{return JSON.parse(raw)}catch{return null}}livenessGeneration(){return Date.now()-this.lastBeatAt>=this.ttlMs?void 0:this.lapses}async getAliveNodes(){const keys=await this.redis.keys(`${this.keyPrefix}heartbeat:*`);return keys.map(key=>key.slice(`${this.keyPrefix}heartbeat:`.length))}heartbeatKey(){return`${this.keyPrefix}heartbeat:${this.nodeId}`}writeHeartbeat(){const value={nodeId:this.nodeId,startedAt:this.startedAt,lastBeat:Date.now(),sessionCount:this.sessionCount};this.redis.set(this.heartbeatKey(),JSON.stringify(value),"PX",this.ttlMs).then(()=>this.recordBeat(value.lastBeat),()=>void 0)}recordBeat(writtenAt){if(Date.now()-this.lastBeatAt>=this.ttlMs)this.lapses++;this.lastBeatAt=Math.max(this.lastBeatAt,writtenAt)}}}});var NotificationRelay;var init_notification_relay=__esm({"libs/sdk/src/ha/notification-relay.ts"(){"use strict";init_ha_types();NotificationRelay=class{constructor(subscriber,publisher,nodeId,config){this.subscriber=subscriber;this.publisher=publisher;this.nodeId=nodeId;this.keyPrefix=config?.redisKeyPrefix??DEFAULT_HA_CONFIG.redisKeyPrefix;this.channel=this.channelOf(nodeId)}subscriber;publisher;nodeId;handler;channel;keyPrefix;channelOf(nodeId){return`${this.keyPrefix}notify:${nodeId}`}async subscribe(handler){this.handler=handler;this.subscriber.removeListener("message",this.onMessage);this.subscriber.on("message",this.onMessage);await this.subscriber.subscribe(this.channel)}async unsubscribe(){this.handler=void 0;this.subscriber.removeListener("message",this.onMessage);try{await this.subscriber.unsubscribe(this.channel)}catch{}}async publish(targetNodeId,sessionId,notification){await this.send(targetNodeId,{kind:"notification",sessionId,notification,sourceNodeId:this.nodeId,timestamp:Date.now()})}async send(targetNodeId,message){return this.publisher.publish(this.channelOf(targetNodeId),JSON.stringify(message))}onMessage=(channel2,raw)=>{if(!this.handler||channel2!==this.channel)return;let message;try{message=JSON.parse(raw)}catch{return}if(!message||typeof message!=="object")return;try{Promise.resolve(this.handler(message)).catch(()=>void 0)}catch{}}}}});async function attemptSessionTakeover(redis,sessionKey,expectedOldNodeId,newNodeId){const reassignedAt=Date.now();const result=await redis.eval(TAKEOVER_LUA,1,sessionKey,expectedOldNodeId,newNodeId,reassignedAt.toString());const claimed=result===1;return{claimed,sessionId:sessionKey,previousNodeId:claimed?expectedOldNodeId:void 0,reassignedAt:claimed?reassignedAt:void 0}}var TAKEOVER_LUA;var init_session_takeover=__esm({"libs/sdk/src/ha/session-takeover.ts"(){"use strict";TAKEOVER_LUA=`
298
298
  local raw = redis.call('GET', KEYS[1])
299
299
  if not raw then return 0 end
300
300
 
@@ -320,7 +320,7 @@ data.reassignedFrom = ARGV[1]
320
320
 
321
321
  redis.call('SET', KEYS[1], cjson.encode(data), 'KEEPTTL')
322
322
  return 1
323
- `}});var HaManager;var init_ha_manager=__esm({"libs/sdk/src/ha/ha-manager.ts"(){"use strict";init_errors();init_ha_types();init_heartbeat_service();init_notification_relay();init_session_takeover();HaManager=class _HaManager{constructor(redis,nodeId,options){this.redis=redis;this.nodeId=nodeId;this.config={...DEFAULT_HA_CONFIG,...options.config};this.logger=options.logger;this.heartbeat=new HeartbeatService(redis,nodeId,this.config);if(options.pubsubSubscriber&&options.pubsubPublisher){this.relay=new NotificationRelay(options.pubsubSubscriber,options.pubsubPublisher,nodeId,this.config)}}redis;nodeId;heartbeat;relay;config;logger;started=false;scannerBootstrapTimer;scannerTimer;scannerOptions;scanning=false;scannerStarted=false;static create(options){if(!options.redis){throw new HaConfigurationError('Distributed mode requires Redis configuration. Add redis: { host: "...", port: 6379 } to your @FrontMcp() config.')}return new _HaManager(options.redis,options.nodeId,options)}async start(){if(this.started)return;this.started=true;this.heartbeat.start();this.logger?.info(`[HA] Heartbeat started for node ${this.nodeId}`);if(this.relay){this.logger?.info(`[HA] Notification relay available`)}}startOrphanScanner(options){if(this.scannerStarted)return;this.scannerStarted=true;this.scannerOptions=options;const delay=this.config.heartbeatIntervalMs+this.config.takeoverGracePeriodMs;this.scannerBootstrapTimer=setTimeout(()=>{if(!this.started||!this.scannerStarted)return;void this.runOrphanScan();this.scannerTimer=setInterval(()=>void this.runOrphanScan(),this.config.heartbeatIntervalMs);this.scannerTimer.unref?.()},delay);this.scannerBootstrapTimer.unref?.();this.logger?.info(`[HA] Orphan scanner started (interval: ${this.config.heartbeatIntervalMs}ms)`)}async stop(){if(!this.started)return;this.started=false;if(this.scannerBootstrapTimer){clearTimeout(this.scannerBootstrapTimer);this.scannerBootstrapTimer=void 0}if(this.scannerTimer){clearInterval(this.scannerTimer);this.scannerTimer=void 0}this.scannerStarted=false;await this.heartbeat.stop();if(this.relay){await this.relay.unsubscribe()}this.logger?.info(`[HA] Services stopped for node ${this.nodeId}`)}async attemptTakeover(sessionKey,expectedOldNodeId){const result=await attemptSessionTakeover(this.redis,sessionKey,expectedOldNodeId,this.nodeId);if(result.claimed){this.logger?.info(`[HA] Took over session ${sessionKey} from ${expectedOldNodeId}`)}else{this.logger?.debug(`[HA] Session ${sessionKey} already claimed by another pod`)}return result}async isNodeAlive(nodeId){return this.heartbeat.isAlive(nodeId)}livenessGeneration(){return this.heartbeat.livenessGeneration()}async getAliveNodes(){return this.heartbeat.getAliveNodes()}getRelay(){return this.relay}async subscribeRelay(handler){if(this.relay){await this.relay.subscribe(handler)}}async publishToNode(nodeId,message){if(!this.relay)return 0;return this.relay.send(nodeId,message)}relayChannelOf(nodeId){return`${this.config.redisKeyPrefix}notify:${nodeId}`}getConfig(){return this.config}setSessionCount(count){this.heartbeat.setSessionCount(count)}isStarted(){return this.started}getNodeId(){return this.nodeId}async runOrphanScan(){if(!this.scannerOptions||this.scanning)return;this.scanning=true;try{const aliveNodes=new Set(await this.heartbeat.getAliveNodes());if(aliveNodes.size===0){this.logger?.debug("[HA] Orphan scan skipped: no alive nodes detected (Redis may be unavailable)");return}const{sessionKeyPrefix,onOrphan,recreatableProtocols}=this.scannerOptions;const allowedProtocols=new Set(recreatableProtocols??["streamable-http"]);const sessionKeys=await this.redis.keys(`${sessionKeyPrefix}*`);let claimed=0;let scanned=0;for(const key of sessionKeys){scanned++;try{const raw=await this.redis.get(key);if(!raw)continue;const data=JSON.parse(raw);const sessionNodeId=data?.session?.nodeId??data?.nodeId;if(!sessionNodeId)continue;const protocol=data?.session?.protocol;if(protocol&&!allowedProtocols.has(protocol))continue;if(aliveNodes.has(sessionNodeId))continue;const result=await attemptSessionTakeover(this.redis,key,sessionNodeId,this.nodeId);if(result.claimed){claimed++;const sessionId=key.slice(sessionKeyPrefix.length);this.logger?.info(`[HA] Orphan scan: claimed session ${sessionId.slice(0,20)} from ${sessionNodeId}`);const authorizationId=data?.session?.authorizationId??data?.authorizationId;try{await Promise.resolve(onOrphan(sessionId,sessionNodeId,{protocol:typeof protocol==="string"?protocol:void 0,authorizationId:typeof authorizationId==="string"?authorizationId:void 0}))}catch(err){this.logger?.warn(`[HA] Orphan handler error for ${sessionId.slice(0,20)}: ${err}`)}}}catch{}}if(scanned>0){this.logger?.debug(`[HA] Orphan scan complete: scanned=${scanned}, claimed=${claimed}`)}}catch(err){this.logger?.warn(`[HA] Orphan scan failed: ${err}`)}finally{this.scanning=false}}}}});function isRequestRelayMessage(message){return message.kind==="relay-request"||message.kind==="relay-response"||message.kind==="relay-cancel"}var init_relay_messages=__esm({"libs/sdk/src/ha/relay-messages.ts"(){"use strict"}});import{getEnv as getEnv14}from"@frontmcp/utils";function positiveInt(name59){const raw=getEnv14(name59);if(raw===void 0||raw.trim()==="")return void 0;const value=Number(raw);return Number.isInteger(value)&&value>0?value:void 0}function resolveHaConfigFromEnv(){const config={};const heartbeatIntervalMs=positiveInt(HA_ENV.heartbeatIntervalMs);if(heartbeatIntervalMs!==void 0)config.heartbeatIntervalMs=heartbeatIntervalMs;const heartbeatTtlMs=positiveInt(HA_ENV.heartbeatTtlMs);if(heartbeatTtlMs!==void 0)config.heartbeatTtlMs=heartbeatTtlMs;const takeoverGracePeriodMs=positiveInt(HA_ENV.takeoverGracePeriodMs);if(takeoverGracePeriodMs!==void 0)config.takeoverGracePeriodMs=takeoverGracePeriodMs;const redisKeyPrefix=getEnv14(HA_ENV.redisKeyPrefix)?.trim();if(redisKeyPrefix)config.redisKeyPrefix=redisKeyPrefix;return config}var HA_ENV;var init_ha_config=__esm({"libs/sdk/src/ha/ha-config.ts"(){"use strict";HA_ENV={heartbeatIntervalMs:"FRONTMCP_HA_HEARTBEAT_INTERVAL_MS",heartbeatTtlMs:"FRONTMCP_HA_HEARTBEAT_TTL_MS",takeoverGracePeriodMs:"FRONTMCP_HA_TAKEOVER_GRACE_MS",redisKeyPrefix:"FRONTMCP_HA_KEY_PREFIX"}}});var ha_exports={};__export(ha_exports,{DEFAULT_FRONTMCP_MACHINE_ID_HEADER:()=>DEFAULT_FRONTMCP_MACHINE_ID_HEADER,DEFAULT_FRONTMCP_NODE_COOKIE:()=>DEFAULT_FRONTMCP_NODE_COOKIE,DEFAULT_HA_CONFIG:()=>DEFAULT_HA_CONFIG,HA_ENV:()=>HA_ENV,HaManager:()=>HaManager,HeartbeatService:()=>HeartbeatService,NotificationRelay:()=>NotificationRelay,attemptSessionTakeover:()=>attemptSessionTakeover,isRequestRelayMessage:()=>isRequestRelayMessage,resolveHaConfigFromEnv:()=>resolveHaConfigFromEnv});var init_ha=__esm({"libs/sdk/src/ha/index.ts"(){"use strict";init_ha_manager();init_heartbeat_service();init_session_takeover();init_notification_relay();init_relay_messages();init_ha_config();init_ha_constants();init_ha_types()}});var DEFAULT_BUS_PREFIX,DEFAULT_BUS_TTL_SECONDS,DEFAULT_RETRY_AFTER_SECONDS,ADVERTISE_LUA,REVOKE_LUA,RedisTransportBus;var init_redis_transport_bus=__esm({"libs/sdk/src/transport/bus/redis-transport-bus.ts"(){"use strict";init_transport_errors();init_relay_http();DEFAULT_BUS_PREFIX="mcp:bus:";DEFAULT_BUS_TTL_SECONDS=3600;DEFAULT_RETRY_AFTER_SECONDS=30;ADVERTISE_LUA=`
323
+ `}});var HaManager;var init_ha_manager=__esm({"libs/sdk/src/ha/ha-manager.ts"(){"use strict";init_errors();init_ha_types();init_heartbeat_service();init_notification_relay();init_session_takeover();HaManager=class _HaManager{constructor(redis,nodeId,options){this.redis=redis;this.nodeId=nodeId;this.config={...DEFAULT_HA_CONFIG,...options.config};this.logger=options.logger;this.heartbeat=new HeartbeatService(redis,nodeId,this.config);if(options.pubsubSubscriber&&options.pubsubPublisher){this.relay=new NotificationRelay(options.pubsubSubscriber,options.pubsubPublisher,nodeId,this.config)}}redis;nodeId;heartbeat;relay;config;logger;started=false;scannerBootstrapTimer;scannerTimer;scannerOptions;scanning=false;scannerStarted=false;static create(options){if(!options.redis){throw new HaConfigurationError('Distributed mode requires Redis configuration. Add redis: { host: "...", port: 6379 } to your @FrontMcp() config.')}return new _HaManager(options.redis,options.nodeId,options)}async start(){if(this.started)return;this.started=true;this.heartbeat.start();this.logger?.info(`[HA] Heartbeat started for node ${this.nodeId}`);if(this.relay){this.logger?.info(`[HA] Notification relay available`)}}startOrphanScanner(options){if(this.scannerStarted)return;this.scannerStarted=true;this.scannerOptions=options;const delay=this.config.heartbeatIntervalMs+this.config.takeoverGracePeriodMs;this.scannerBootstrapTimer=setTimeout(()=>{if(!this.started||!this.scannerStarted)return;void this.runOrphanScan();this.scannerTimer=setInterval(()=>void this.runOrphanScan(),this.config.heartbeatIntervalMs);this.scannerTimer.unref?.()},delay);this.scannerBootstrapTimer.unref?.();this.logger?.info(`[HA] Orphan scanner started (interval: ${this.config.heartbeatIntervalMs}ms)`)}async stop(){if(!this.started)return;this.started=false;if(this.scannerBootstrapTimer){clearTimeout(this.scannerBootstrapTimer);this.scannerBootstrapTimer=void 0}if(this.scannerTimer){clearInterval(this.scannerTimer);this.scannerTimer=void 0}this.scannerStarted=false;await this.heartbeat.stop();if(this.relay){await this.relay.unsubscribe()}this.logger?.info(`[HA] Services stopped for node ${this.nodeId}`)}async attemptTakeover(sessionKey,expectedOldNodeId){const result=await attemptSessionTakeover(this.redis,sessionKey,expectedOldNodeId,this.nodeId);if(result.claimed){this.logger?.info(`[HA] Took over session ${sessionKey} from ${expectedOldNodeId}`)}else{this.logger?.debug(`[HA] Session ${sessionKey} already claimed by another pod`)}return result}async isNodeAlive(nodeId){return this.heartbeat.isAlive(nodeId)}livenessGeneration(){return this.heartbeat.livenessGeneration()}async getAliveNodes(){return this.heartbeat.getAliveNodes()}getRelay(){return this.relay}async subscribeRelay(handler){if(this.relay){await this.relay.subscribe(handler)}}async publishToNode(nodeId,message){if(!this.relay)return 0;return this.relay.send(nodeId,message)}relayChannelOf(nodeId){return`${this.config.redisKeyPrefix}notify:${nodeId}`}getConfig(){return this.config}setSessionCount(count){this.heartbeat.setSessionCount(count)}isStarted(){return this.started}getNodeId(){return this.nodeId}async runOrphanScan(){if(!this.scannerOptions||this.scanning)return;this.scanning=true;try{const aliveNodes=new Set(await this.heartbeat.getAliveNodes());if(aliveNodes.size===0){this.logger?.debug("[HA] Orphan scan skipped: no alive nodes detected (Redis may be unavailable)");return}const{sessionKeyPrefix,onOrphan,recreatableProtocols}=this.scannerOptions;const allowedProtocols=new Set(recreatableProtocols??["streamable-http"]);const sessionKeys=await this.redis.keys(`${sessionKeyPrefix}*`);let claimed=0;let scanned=0;for(const key of sessionKeys){scanned++;try{const raw=await this.redis.get(key);if(!raw)continue;const data=JSON.parse(raw);const sessionNodeId=data?.session?.nodeId??data?.nodeId;if(!sessionNodeId)continue;const protocol=data?.session?.protocol;if(protocol&&!allowedProtocols.has(protocol))continue;if(aliveNodes.has(sessionNodeId))continue;const result=await attemptSessionTakeover(this.redis,key,sessionNodeId,this.nodeId);if(result.claimed){claimed++;const sessionId=key.slice(sessionKeyPrefix.length);this.logger?.info(`[HA] Orphan scan: claimed session ${sessionId.slice(0,20)} from ${sessionNodeId}`);const authorizationId=data?.session?.authorizationId??data?.authorizationId;try{await Promise.resolve(onOrphan(sessionId,sessionNodeId,{protocol:typeof protocol==="string"?protocol:void 0,authorizationId:typeof authorizationId==="string"?authorizationId:void 0}))}catch(err){this.logger?.warn(`[HA] Orphan handler error for ${sessionId.slice(0,20)}: ${err}`)}}}catch{}}if(scanned>0){this.logger?.debug(`[HA] Orphan scan complete: scanned=${scanned}, claimed=${claimed}`)}}catch(err){this.logger?.warn(`[HA] Orphan scan failed: ${err}`)}finally{this.scanning=false}}}}});function isRequestRelayMessage(message){return message.kind==="relay-request"||message.kind==="relay-response"||message.kind==="relay-cancel"}var init_relay_messages=__esm({"libs/sdk/src/ha/relay-messages.ts"(){"use strict"}});import{getEnv as getEnv14}from"@frontmcp/utils";function positiveInt(name59){const raw=getEnv14(name59);if(raw===void 0||raw.trim()==="")return void 0;const value=Number(raw);return Number.isInteger(value)&&value>0?value:void 0}function resolveHaConfigFromEnv(){const config={};const heartbeatIntervalMs=positiveInt(HA_ENV.heartbeatIntervalMs);if(heartbeatIntervalMs!==void 0)config.heartbeatIntervalMs=heartbeatIntervalMs;const heartbeatTtlMs=positiveInt(HA_ENV.heartbeatTtlMs);if(heartbeatTtlMs!==void 0)config.heartbeatTtlMs=heartbeatTtlMs;const takeoverGracePeriodMs=positiveInt(HA_ENV.takeoverGracePeriodMs);if(takeoverGracePeriodMs!==void 0)config.takeoverGracePeriodMs=takeoverGracePeriodMs;const redisKeyPrefix=getEnv14(HA_ENV.redisKeyPrefix)?.trim();if(redisKeyPrefix)config.redisKeyPrefix=redisKeyPrefix;return config}var HA_ENV;var init_ha_config=__esm({"libs/sdk/src/ha/ha-config.ts"(){"use strict";HA_ENV={heartbeatIntervalMs:"FRONTMCP_HA_HEARTBEAT_INTERVAL_MS",heartbeatTtlMs:"FRONTMCP_HA_HEARTBEAT_TTL_MS",takeoverGracePeriodMs:"FRONTMCP_HA_TAKEOVER_GRACE_MS",redisKeyPrefix:"FRONTMCP_HA_KEY_PREFIX"}}});var ha_exports={};__export(ha_exports,{DEFAULT_FRONTMCP_MACHINE_ID_HEADER:()=>DEFAULT_FRONTMCP_MACHINE_ID_HEADER,DEFAULT_FRONTMCP_NODE_COOKIE:()=>DEFAULT_FRONTMCP_NODE_COOKIE,DEFAULT_HA_CONFIG:()=>DEFAULT_HA_CONFIG,HA_ENV:()=>HA_ENV,HaManager:()=>HaManager,HeartbeatService:()=>HeartbeatService,NotificationRelay:()=>NotificationRelay,attemptSessionTakeover:()=>attemptSessionTakeover,isRequestRelayMessage:()=>isRequestRelayMessage,resolveHaConfigFromEnv:()=>resolveHaConfigFromEnv});var init_ha=__esm({"libs/sdk/src/ha/index.ts"(){"use strict";init_ha_manager();init_heartbeat_service();init_session_takeover();init_notification_relay();init_relay_messages();init_ha_config();init_ha_constants();init_ha_types()}});var DEFAULT_BUS_PREFIX,DEFAULT_BUS_TTL_SECONDS,DEFAULT_RETRY_AFTER_SECONDS,RELEASE_TIMEOUT_MS,RELEASE_POLL_MS,ADVERTISE_LUA,REVOKE_LUA,RedisTransportBus;var init_redis_transport_bus=__esm({"libs/sdk/src/transport/bus/redis-transport-bus.ts"(){"use strict";init_transport_errors();init_relay_http();DEFAULT_BUS_PREFIX="mcp:bus:";DEFAULT_BUS_TTL_SECONDS=3600;DEFAULT_RETRY_AFTER_SECONDS=30;RELEASE_TIMEOUT_MS=5e3;RELEASE_POLL_MS=25;ADVERTISE_LUA=`
324
324
  redis.call('HSET', KEYS[1], 'nodeId', ARGV[1], 'channel', ARGV[2], 'type', ARGV[3], 'tokenHash', ARGV[4])
325
325
  redis.call('EXPIRE', KEYS[1], ARGV[5])
326
326
  return 1
@@ -331,7 +331,7 @@ if nodeId == ARGV[1] then
331
331
  return 1
332
332
  end
333
333
  return 0
334
- `;RedisTransportBus=class{constructor(redis,machineId,options){this.redis=redis;this.machineId=machineId;this.keyPrefix=options?.keyPrefix??DEFAULT_BUS_PREFIX;this.ttlSeconds=options?.ttlSeconds??DEFAULT_BUS_TTL_SECONDS;this.haKeyPrefix=options?.haKeyPrefix??"mcp:ha:";this.retryAfterSeconds=options?.retryAfterSeconds??DEFAULT_RETRY_AFTER_SECONDS;this.logger=options?.logger}redis;machineId;keyPrefix;ttlSeconds;haKeyPrefix;retryAfterSeconds;logger;relay;nodeId(){return this.machineId}attachRelay(relay){this.relay=relay}canRelay(){return this.relay!==void 0}channelOf(nodeId){return`${this.haKeyPrefix}notify:${nodeId}`}async advertise(key){await this.redis.eval(ADVERTISE_LUA,1,this.busKey(key.sessionId),this.machineId,this.channelOf(this.machineId),key.type,key.tokenHash,this.ttlSeconds);this.logger?.debug("[TransportBus] Advertised session",{sessionId:key.sessionId.slice(0,20),nodeId:this.machineId})}async revoke(key){const redisKey=this.busKey(key.sessionId);const result=await this.redis.eval(REVOKE_LUA,1,redisKey,this.machineId);this.logger?.debug("[TransportBus] Revoked session",{sessionId:key.sessionId.slice(0,20),deleted:result===1})}async lookup(key){const entry=await this.readEntry(key.sessionId);if(!entry)return null;if(entry.nodeId===this.machineId)return null;if(entry.type&&entry.type!==key.type||entry.tokenHash&&entry.tokenHash!==key.tokenHash){return null}return{nodeId:entry.nodeId,channel:entry.channel}}async lookupOwner(sessionId){const entry=await this.readEntry(sessionId);return entry?{nodeId:entry.nodeId,channel:entry.channel}:null}async proxyRequest(location,sessionId,request2,response){if(isRelayedRequest(request2)){throw new SessionOwnerUnreachableError(location.nodeId,this.retryAfterSeconds,"the request was already relayed once and its session moved again")}if(!this.relay){throw new SessionOwnerUnreachableError(location.nodeId,this.retryAfterSeconds,"request relay is not available on this node (no Redis pub/sub)")}await this.relay.forward(location.nodeId,sessionId,serializeRelayRequest(request2),response)}async destroyRemote(key,reason){const entry=await this.readEntry(key.sessionId);if(!entry||entry.nodeId===this.machineId)return;const message=JSON.stringify({kind:"destroy-session",sessionId:key.sessionId,reason,sourceNodeId:this.machineId,timestamp:Date.now()});await this.redis.publish(entry.channel,message);this.logger?.info("[TransportBus] Sent destroy-remote",{sessionId:key.sessionId.slice(0,20),targetNodeId:entry.nodeId})}async readEntry(sessionId){const fields=await this.redis.hgetall(this.busKey(sessionId));const nodeId=fields?.["nodeId"];if(!nodeId)return null;return{nodeId,channel:fields["channel"]||this.channelOf(nodeId),type:fields["type"]||void 0,tokenHash:fields["tokenHash"]||void 0}}busKey(sessionId){return`${this.keyPrefix}session:${sessionId}`}}}});var bus_exports={};__export(bus_exports,{RedisTransportBus:()=>RedisTransportBus});var init_bus=__esm({"libs/sdk/src/transport/bus/index.ts"(){"use strict";init_redis_transport_bus()}});var MemoryEventStore;var init_memory_event_store=__esm({"libs/sdk/src/transport/event-stores/memory.event-store.ts"(){"use strict";MemoryEventStore=class{streams=new Map;index=new Map;maxEvents;ttlMs;constructor(options={}){this.maxEvents=options.maxEvents??1e4;this.ttlMs=options.ttlMs??3e5}async storeEvent(streamId,message){this.evictExpired();const list=this.streams.get(streamId)??[];const id=`${streamId}:${list.length+1}`;const rec={id,msg:message,timestamp:Date.now()};list.push(rec);this.streams.set(streamId,list);this.index.set(id,{streamId,idx:list.length-1});if(this.index.size>this.maxEvents){this.evictOldest()}return id}async getStreamIdForEventId(eventId){return this.index.get(eventId)?.streamId}async replayEventsAfter(lastEventId,{send}){const meta=this.index.get(lastEventId);if(!meta){const freshStream="default-stream";if(!this.streams.has(freshStream))this.streams.set(freshStream,[]);return freshStream}const{streamId,idx}=meta;const list=this.streams.get(streamId)??[];for(let k=idx+1;k<list.length;k++){const e=list[k];if(Date.now()-e.timestamp<this.ttlMs){await send(e.id,e.msg)}}return streamId}evictExpired(){const now=Date.now();for(const[streamId,list]of this.streams){const validEvents=list.filter(e=>now-e.timestamp<this.ttlMs);if(validEvents.length<list.length){this.streams.set(streamId,validEvents);this.rebuildIndex(streamId,validEvents)}}}evictOldest(){let oldest=null;for(const[streamId,list]of this.streams){if(list.length>0&&(!oldest||list[0].timestamp<oldest.timestamp)){oldest={streamId,idx:0,timestamp:list[0].timestamp}}}if(oldest){const list=this.streams.get(oldest.streamId);if(list&&list.length>0){const removed=list.shift();if(removed){this.index.delete(removed.id)}this.rebuildIndex(oldest.streamId,list)}}}rebuildIndex(streamId,list){for(const[id,meta]of this.index){if(meta.streamId===streamId){this.index.delete(id)}}list.forEach((e,idx)=>this.index.set(e.id,{streamId,idx}))}clear(){this.streams.clear();this.index.clear()}get size(){return this.index.size}}}});import{attachRedisErrorListener as attachRedisErrorListener2}from"@frontmcp/utils";var RedisEventStore;var init_redis_event_store=__esm({"libs/sdk/src/transport/event-stores/redis.event-store.ts"(){"use strict";init_common();init_schema5();init_mcp_error();init_sdk_errors();RedisEventStore=class{client;keyPrefix;maxEvents;ttlSeconds;redisOptions;constructor(options){this.redisOptions=options.redis;this.keyPrefix=options.keyPrefix??"mcp:events:";this.maxEvents=options.maxEvents??1e4;this.ttlSeconds=Math.ceil((options.ttlMs??3e5)/1e3)}async getClient(){if(!this.client){const redis=normalizeRedisOptions(this.redisOptions);if(typeof redis==="string"){throw new InternalMcpError(`The event store's redis option cannot be used: ${redis}. Give a Redis url, or a host.`,"INVALID_REDIS_CONFIG")}if(isVercelKvProvider(redis)){throw new VercelKvNotSupportedError("Redis Streams (required for EventStore). Use standard Redis provider instead")}const Redis=__require("ioredis");const{host,port,password,db,tls}=redis;this.client=new Redis({host,port,password,db,tls:tls?{}:void 0,lazyConnect:true,enableReadyCheck:false,maxRetriesPerRequest:3});attachRedisErrorListener2(this.client,{label:"RedisEventStore"});await this.client.connect()}return this.client}async storeEvent(streamId,message){const client=await this.getClient();const streamKey=`${this.keyPrefix}${streamId}`;const redisId=await client.xadd(streamKey,"MAXLEN","~",this.maxEvents.toString(),"*","msg",JSON.stringify(message));await client.expire(streamKey,this.ttlSeconds);return`${streamId}:${redisId}`}async getStreamIdForEventId(eventId){const parsed=this.parseEventId(eventId);return parsed?parsed[0]:void 0}async replayEventsAfter(lastEventId,{send}){const parsed=this.parseEventId(lastEventId);if(!parsed){return"default-stream"}const client=await this.getClient();const[streamId,redisId]=parsed;const streamKey=`${this.keyPrefix}${streamId}`;const entries=await client.xrange(streamKey,`(${redisId}`,"+");for(const[id,fields]of entries){const msgIndex=fields.indexOf("msg");if(msgIndex!==-1&&msgIndex+1<fields.length){const msgStr=fields[msgIndex+1];const msg=JSON.parse(msgStr);await send(`${streamId}:${id}`,msg)}}return streamId}parseEventId(eventId){const value=String(eventId);const lastDash=value.lastIndexOf("-");const separator=lastDash===-1?value.lastIndexOf(":"):value.lastIndexOf(":",lastDash);if(separator<=0||separator===value.length-1)return void 0;const streamId=value.slice(0,separator);const redisId=value.slice(separator+1);if(!/^\d+(-\d+)?$/.test(redisId))return void 0;return[streamId,redisId]}async close(){if(this.client){await this.client.quit();this.client=void 0}}}}});function createEventStore(config,logger){if(!config?.enabled){logger?.verbose("[EventStoreFactory] EventStore disabled (resumability not available)");return{eventStore:void 0,type:"disabled"}}const provider=config.provider??"memory";const maxEvents=config.maxEvents??1e4;const ttlMs=config.ttlMs??3e5;if(provider==="sqlite"){if(!config.sqlite||!config.sqlite.path){throw new PublicMcpError('EventStore SQLite configuration required when provider is "sqlite". Provide sqlite config: { provider: "sqlite", sqlite: { path: "..." } }',"INVALID_PARAMS")}const{SqliteEventStore}=requireOptionalModule("@frontmcp/storage-sqlite",()=>require_dist());logger?.info("[EventStoreFactory] Creating SQLite EventStore for resumability",{maxEvents,ttlMs,path:config.sqlite.path});return{eventStore:new SqliteEventStore({...config.sqlite,maxEvents,ttlMs}),type:"sqlite"}}if(provider==="redis"){if(!config.redis){throw new PublicMcpError('EventStore Redis configuration required when provider is "redis". Provide redis config: { provider: "redis", host: "...", port: ... }',"INVALID_PARAMS")}logger?.info("[EventStoreFactory] Creating Redis EventStore for resumability",{maxEvents,ttlMs});return{eventStore:new RedisEventStore({redis:config.redis,maxEvents,ttlMs}),type:"redis"}}logger?.info("[EventStoreFactory] Creating in-memory EventStore for resumability",{maxEvents,ttlMs});return{eventStore:new MemoryEventStore({maxEvents,ttlMs}),type:"memory"}}var init_event_store_factory=__esm({"libs/sdk/src/transport/event-stores/event-store.factory.ts"(){"use strict";init_errors();init_optional_dependency_util();init_memory_event_store();init_redis_event_store()}});var event_stores_exports={};__export(event_stores_exports,{MemoryEventStore:()=>MemoryEventStore,RedisEventStore:()=>RedisEventStore,createEventStore:()=>createEventStore,createSessionScopedEventStore:()=>createSessionScopedEventStore});var init_event_stores=__esm({"libs/sdk/src/transport/event-stores/index.ts"(){"use strict";init_event_store_factory();init_memory_event_store();init_redis_event_store();init_session_scoped_event_store()}});var EncryptedElicitationStore;var init_encrypted_elicitation_store=__esm({"libs/sdk/src/elicitation/store/encrypted-elicitation.store.ts"(){"use strict";init_errors();init_elicitation_encryption();EncryptedElicitationStore=class{store;secret;logger;constructor(store,options={}){this.store=store;this.secret=options.secret;this.logger=options.logger}async setPending(record){const{sessionId}=record;try{const encrypted=await encryptElicitationData(record,sessionId,this.secret);await this.store.setPending({sessionId:record.sessionId,elicitId:record.elicitId,createdAt:record.createdAt,expiresAt:record.expiresAt,__encrypted:encrypted});this.logger?.debug("[EncryptedElicitationStore] Stored encrypted pending record",{sessionId:sessionId.slice(0,8)+"...",elicitId:record.elicitId})}catch(error){this.logger?.error("[EncryptedElicitationStore] Failed to encrypt pending record",{sessionId:sessionId.slice(0,8)+"...",error:error instanceof Error?error.message:String(error)});throw error}}async getPending(sessionId){const stored=await this.store.getPending(sessionId);if(!stored){return null}return this.decryptPendingRecord(stored,sessionId)}async deletePending(sessionId){await this.store.deletePending(sessionId)}async subscribeResult(elicitId,callback,sessionId){const decryptingCallback=async rawResult=>{if(sessionId&&isEncryptedBlob(rawResult)){try{const decrypted=await decryptElicitationData(rawResult,sessionId,this.secret);if(decrypted){callback(decrypted);return}this.logger?.warn("[EncryptedElicitationStore] Failed to decrypt pub/sub message (null result)",{elicitId});return}catch(error){this.logger?.warn("[EncryptedElicitationStore] Failed to decrypt pub/sub message",{elicitId,error:error instanceof Error?error.message:String(error)});return}}callback(rawResult)};return this.store.subscribeResult(elicitId,decryptingCallback,sessionId)}async publishResult(elicitId,sessionId,result){try{const encrypted=await encryptElicitationData(result,sessionId,this.secret);await this.store.publishResult(elicitId,sessionId,encrypted);this.logger?.debug("[EncryptedElicitationStore] Published encrypted result",{elicitId,sessionId:sessionId.slice(0,8)+"..."})}catch(error){this.logger?.error("[EncryptedElicitationStore] Failed to encrypt pub/sub result",{elicitId,error:error instanceof Error?error.message:String(error)});throw error}}async setPendingFallback(record){const{sessionId,elicitId}=record;try{const encrypted=await encryptElicitationData(record,sessionId,this.secret);await this.store.setPendingFallback({sessionId:record.sessionId,elicitId:record.elicitId,createdAt:record.createdAt,expiresAt:record.expiresAt,__encrypted:encrypted});this.logger?.debug("[EncryptedElicitationStore] Stored encrypted pending fallback",{elicitId,sessionId:sessionId.slice(0,8)+"..."})}catch(error){this.logger?.error("[EncryptedElicitationStore] Failed to encrypt pending fallback",{elicitId,error:error instanceof Error?error.message:String(error)});throw error}}async getPendingFallback(elicitId,sessionId){const stored=await this.store.getPendingFallback(elicitId);if(!stored){return null}return this.decryptFallbackRecord(stored,sessionId)}async deletePendingFallback(elicitId){await this.store.deletePendingFallback(elicitId)}async setResolvedResult(elicitId,result,sessionId){if(!sessionId){throw new ElicitationEncryptionError(`Cannot store encrypted resolved result without sessionId (elicitId: ${elicitId})`)}try{const record={elicitId,result,resolvedAt:Date.now()};const encrypted=await encryptElicitationData(record,sessionId,this.secret);await this.store.setResolvedResult(elicitId,{__encrypted:encrypted},sessionId);this.logger?.debug("[EncryptedElicitationStore] Stored encrypted resolved result",{elicitId,sessionId:sessionId.slice(0,8)+"..."})}catch(error){if(error instanceof ElicitationEncryptionError){throw error}const originalError=error instanceof Error?error:void 0;throw new ElicitationEncryptionError(`Failed to encrypt resolved result (elicitId: ${elicitId})`,originalError)}}async getResolvedResult(elicitId,sessionId){const stored=await this.store.getResolvedResult(elicitId);if(!stored){return null}return this.decryptResolvedRecord(stored,sessionId)}async deleteResolvedResult(elicitId){await this.store.deleteResolvedResult(elicitId)}async subscribeFallbackResult(elicitId,callback,sessionId){const decryptingCallback=async rawResult=>{if(sessionId&&isEncryptedBlob(rawResult)){try{const decrypted=await decryptElicitationData(rawResult,sessionId,this.secret);if(decrypted){callback(decrypted);return}this.logger?.warn("[EncryptedElicitationStore] Failed to decrypt fallback pub/sub message (null result)",{elicitId});return}catch(error){this.logger?.warn("[EncryptedElicitationStore] Failed to decrypt fallback pub/sub message",{elicitId,error:error instanceof Error?error.message:String(error)});return}}callback(rawResult)};return this.store.subscribeFallbackResult(elicitId,decryptingCallback,sessionId)}async publishFallbackResult(elicitId,sessionId,result){try{const encrypted=await encryptElicitationData(result,sessionId,this.secret);await this.store.publishFallbackResult(elicitId,sessionId,encrypted);this.logger?.debug("[EncryptedElicitationStore] Published encrypted fallback result",{elicitId,sessionId:sessionId.slice(0,8)+"..."})}catch(error){this.logger?.error("[EncryptedElicitationStore] Failed to encrypt fallback result",{elicitId,error:error instanceof Error?error.message:String(error)});throw error}}async destroy(){await this.store.destroy?.()}async decryptPendingRecord(stored,sessionId){const encryptedBlob=stored.__encrypted;if(!encryptedBlob||!isEncryptedBlob(encryptedBlob)){this.logger?.debug("[EncryptedElicitationStore] Plaintext fallback for pending record (migration)",{sessionId:sessionId.slice(0,8)+"...",elicitId:stored.elicitId});return stored}try{const decrypted=await decryptElicitationData(encryptedBlob,sessionId,this.secret);if(decrypted){this.logger?.debug("[EncryptedElicitationStore] Decrypted pending record",{sessionId:sessionId.slice(0,8)+"...",elicitId:decrypted.elicitId});return decrypted}this.logger?.warn("[EncryptedElicitationStore] Failed to decrypt pending record",{sessionId:sessionId.slice(0,8)+"..."});return null}catch(error){this.logger?.warn("[EncryptedElicitationStore] Decryption error for pending record",{sessionId:sessionId.slice(0,8)+"...",error:error instanceof Error?error.message:String(error)});return null}}async decryptFallbackRecord(stored,sessionId){const encryptedBlob=stored.__encrypted;if(!encryptedBlob||!isEncryptedBlob(encryptedBlob)){this.logger?.debug("[EncryptedElicitationStore] Plaintext fallback for fallback record (migration)",{elicitId:stored.elicitId});return stored}if(!sessionId){sessionId=stored.sessionId}if(!sessionId){this.logger?.warn("[EncryptedElicitationStore] Cannot decrypt fallback: no sessionId",{elicitId:stored.elicitId});return null}try{const decrypted=await decryptElicitationData(encryptedBlob,sessionId,this.secret);if(decrypted){this.logger?.debug("[EncryptedElicitationStore] Decrypted fallback record",{elicitId:decrypted.elicitId});return decrypted}this.logger?.warn("[EncryptedElicitationStore] Failed to decrypt fallback record",{elicitId:stored.elicitId});return null}catch(error){this.logger?.warn("[EncryptedElicitationStore] Decryption error for fallback record",{elicitId:stored.elicitId,error:error instanceof Error?error.message:String(error)});return null}}async decryptResolvedRecord(stored,sessionId){const encryptedResult=stored.result;const encryptedBlob=encryptedResult?.__encrypted;if(!encryptedBlob||!isEncryptedBlob(encryptedBlob)){this.logger?.debug("[EncryptedElicitationStore] Plaintext fallback for resolved result (migration)",{elicitId:stored.elicitId});return stored}if(!sessionId){this.logger?.warn("[EncryptedElicitationStore] Cannot decrypt resolved result: no sessionId",{elicitId:stored.elicitId});return null}try{const decrypted=await decryptElicitationData(encryptedBlob,sessionId,this.secret);if(decrypted){this.logger?.debug("[EncryptedElicitationStore] Decrypted resolved result",{elicitId:decrypted.elicitId});return decrypted}this.logger?.warn("[EncryptedElicitationStore] Failed to decrypt resolved result",{elicitId:stored.elicitId});return null}catch(error){this.logger?.warn("[EncryptedElicitationStore] Decryption error for resolved result",{elicitId:stored.elicitId,error:error instanceof Error?error.message:String(error)});return null}}}}});import{sha256Hex as sha256Hex22}from"@frontmcp/utils";function sessionIdHash(sessionId){return sha256Hex22(sessionId).slice(0,12)}var init_session_id_hash=__esm({"libs/sdk/src/logger/session-id-hash.ts"(){"use strict"}});import{expiresAtToTTL,TypedStorage}from"@frontmcp/utils";function elicitationResultRoute(sessionId,elicitId){return`${sessionId.replace(/%/g,"%25").replace(/:/g,"%3A")}:${elicitId}`}function requireSubscriberSession(elicitId,sessionId){if(!sessionId){throw new ElicitationSubscriptionError(elicitId,new Error("a result subscription needs the session ID the elicitation belongs to; pass it as the third argument"))}return sessionId}var RESOLVED_RESULT_TTL_SECONDS,RESULT_CHANNEL_PREFIX,FALLBACK_RESULT_CHANNEL_PREFIX,StorageElicitationStore;var init_storage_elicitation_store=__esm({"libs/sdk/src/elicitation/store/storage-elicitation.store.ts"(){"use strict";init_errors();init_session_id_hash();RESOLVED_RESULT_TTL_SECONDS=300;RESULT_CHANNEL_PREFIX="result:";FALLBACK_RESULT_CHANNEL_PREFIX="fallback-result:";StorageElicitationStore=class{storage;pending;fallback;resolved;logger;localCallbacks=new Map;activeSubscriptions=new Map;pendingSubscriptions=new Map;fallbackResultCallbacks=new Map;activeFallbackSubscriptions=new Map;pendingFallbackSubscriptions=new Map;constructor(storage,logger){this.storage=storage;this.logger=logger;this.pending=new TypedStorage(storage.namespace("pending"));this.fallback=new TypedStorage(storage.namespace("fallback"));this.resolved=new TypedStorage(storage.namespace("resolved"))}async setPending(record){const{sessionId,expiresAt}=record;const ttlSeconds=expiresAtToTTL(expiresAt);if(ttlSeconds<=0){this.logger?.warn("[StorageElicitationStore] Record already expired, not storing",{sessionIdHash:sessionIdHash(sessionId),elicitId:record.elicitId});return}await this.pending.set(sessionId,record,{ttlSeconds});this.logger?.debug("[StorageElicitationStore] Stored pending elicitation",{sessionIdHash:sessionIdHash(sessionId),elicitId:record.elicitId,ttlSeconds})}async getPending(sessionId){const record=await this.pending.get(sessionId);if(!record){return null}if(Date.now()>record.expiresAt){await this.deletePending(sessionId);return null}return record}async deletePending(sessionId){await this.pending.delete(sessionId);this.logger?.debug("[StorageElicitationStore] Deleted pending elicitation",{sessionIdHash:sessionIdHash(sessionId)})}async subscribeResult(elicitId,callback,sessionId){const route=elicitationResultRoute(requireSubscriberSession(elicitId,sessionId),elicitId);let callbacks=this.localCallbacks.get(route);if(!callbacks){callbacks=new Set;this.localCallbacks.set(route,callbacks)}callbacks.add(callback);if(!this.activeSubscriptions.has(route)&&!this.pendingSubscriptions.has(route)&&this.storage.supportsPubSub()){const channel2=RESULT_CHANNEL_PREFIX+route;const subscribePromise=this.storage.subscribe(channel2,message=>{try{const result=JSON.parse(message);const cbs=this.localCallbacks.get(route);if(cbs){for(const cb of cbs){try{cb(result)}catch(err){this.logger?.error("[StorageElicitationStore] Callback error",{elicitId,error:err instanceof Error?err.message:String(err)})}}}}catch(err){this.logger?.error("[StorageElicitationStore] Failed to parse result message",{elicitId,error:err instanceof Error?err.message:String(err)})}}).then(unsubscribe=>{this.pendingSubscriptions.delete(route);this.activeSubscriptions.set(route,unsubscribe);return unsubscribe}).catch(err=>{this.pendingSubscriptions.delete(route);this.logger?.error("[StorageElicitationStore] Failed to subscribe",{elicitId,error:err instanceof Error?err.message:String(err)});throw err});this.pendingSubscriptions.set(route,subscribePromise);try{await subscribePromise}catch(error){callbacks.delete(callback);if(callbacks.size===0){this.localCallbacks.delete(route)}throw error}}else if(this.pendingSubscriptions.has(route)){try{await this.pendingSubscriptions.get(route)}catch(error){callbacks.delete(callback);if(callbacks.size===0){this.localCallbacks.delete(route)}throw error}}return async()=>{callbacks.delete(callback);if(callbacks.size===0){this.localCallbacks.delete(route);if(this.pendingSubscriptions.has(route)){try{await this.pendingSubscriptions.get(route)}catch{}}const unsubscribe=this.activeSubscriptions.get(route);if(unsubscribe){this.activeSubscriptions.delete(route);try{await unsubscribe()}catch(err){this.logger?.error("[StorageElicitationStore] Failed to unsubscribe",{elicitId,error:err instanceof Error?err.message:String(err)})}}}}}async publishResult(elicitId,sessionId,result){const route=elicitationResultRoute(sessionId,elicitId);if(this.storage.supportsPubSub()){const channel2=RESULT_CHANNEL_PREFIX+route;try{await this.storage.publish(channel2,JSON.stringify(result))}catch(err){this.logger?.error("[StorageElicitationStore] Failed to publish result",{elicitId,error:err instanceof Error?err.message:String(err)})}}else{const callbacks=this.localCallbacks.get(route);if(callbacks){for(const cb of callbacks){try{cb(result)}catch(err){this.logger?.error("[StorageElicitationStore] Callback error during publish",{elicitId,error:err instanceof Error?err.message:String(err)})}}}}await this.deletePending(sessionId);this.logger?.debug("[StorageElicitationStore] Published result",{elicitId,sessionIdHash:sessionIdHash(sessionId),status:result.status})}async setPendingFallback(record){const{elicitId,expiresAt}=record;const ttlSeconds=expiresAtToTTL(expiresAt);if(ttlSeconds<=0){this.logger?.warn("[StorageElicitationStore] Fallback record already expired, not storing",{elicitId});return}await this.fallback.set(elicitId,record,{ttlSeconds});this.logger?.debug("[StorageElicitationStore] Stored pending fallback",{elicitId,ttlSeconds})}async getPendingFallback(elicitId,_sessionId){const record=await this.fallback.get(elicitId);if(!record){return null}if(Date.now()>record.expiresAt){await this.deletePendingFallback(elicitId);return null}return record}async deletePendingFallback(elicitId){await this.fallback.delete(elicitId);this.logger?.debug("[StorageElicitationStore] Deleted pending fallback",{elicitId})}async setResolvedResult(elicitId,result,_sessionId){const record={elicitId,result,resolvedAt:Date.now()};await this.resolved.set(elicitId,record,{ttlSeconds:RESOLVED_RESULT_TTL_SECONDS});this.logger?.debug("[StorageElicitationStore] Stored resolved result",{elicitId})}async getResolvedResult(elicitId,_sessionId){return this.resolved.get(elicitId)}async deleteResolvedResult(elicitId){await this.resolved.delete(elicitId);this.logger?.debug("[StorageElicitationStore] Deleted resolved result",{elicitId})}async subscribeFallbackResult(elicitId,callback,sessionId){const route=elicitationResultRoute(requireSubscriberSession(elicitId,sessionId),elicitId);let callbacks=this.fallbackResultCallbacks.get(route);if(!callbacks){callbacks=new Set;this.fallbackResultCallbacks.set(route,callbacks)}callbacks.add(callback);if(!this.activeFallbackSubscriptions.has(route)&&!this.pendingFallbackSubscriptions.has(route)&&this.storage.supportsPubSub()){const channel2=FALLBACK_RESULT_CHANNEL_PREFIX+route;const subscribePromise=this.storage.subscribe(channel2,message=>{try{const result=JSON.parse(message);const cbs=this.fallbackResultCallbacks.get(route);if(cbs){for(const cb of cbs){try{cb(result)}catch(err){this.logger?.error("[StorageElicitationStore] Fallback callback error",{elicitId,error:err instanceof Error?err.message:String(err)})}}}}catch(err){this.logger?.error("[StorageElicitationStore] Failed to parse fallback result message",{elicitId,error:err instanceof Error?err.message:String(err)})}}).then(unsubscribe=>{this.pendingFallbackSubscriptions.delete(route);this.activeFallbackSubscriptions.set(route,unsubscribe);return unsubscribe}).catch(err=>{this.pendingFallbackSubscriptions.delete(route);this.logger?.error("[StorageElicitationStore] Failed to subscribe to fallback result",{elicitId,error:err instanceof Error?err.message:String(err)});throw err});this.pendingFallbackSubscriptions.set(route,subscribePromise);try{await subscribePromise}catch(error){callbacks.delete(callback);if(callbacks.size===0){this.fallbackResultCallbacks.delete(route)}throw error}}else if(this.pendingFallbackSubscriptions.has(route)){try{await this.pendingFallbackSubscriptions.get(route)}catch(error){callbacks.delete(callback);if(callbacks.size===0){this.fallbackResultCallbacks.delete(route)}throw error}}return async()=>{callbacks.delete(callback);if(callbacks.size===0){this.fallbackResultCallbacks.delete(route);if(this.pendingFallbackSubscriptions.has(route)){try{await this.pendingFallbackSubscriptions.get(route)}catch{}}const unsubscribe=this.activeFallbackSubscriptions.get(route);if(unsubscribe){this.activeFallbackSubscriptions.delete(route);try{await unsubscribe()}catch(err){this.logger?.error("[StorageElicitationStore] Failed to unsubscribe from fallback result",{elicitId,error:err instanceof Error?err.message:String(err)})}}}}}async publishFallbackResult(elicitId,sessionId,result){const route=elicitationResultRoute(sessionId,elicitId);if(this.storage.supportsPubSub()){const channel2=FALLBACK_RESULT_CHANNEL_PREFIX+route;try{await this.storage.publish(channel2,JSON.stringify(result))}catch(err){this.logger?.error("[StorageElicitationStore] Failed to publish fallback result",{elicitId,error:err instanceof Error?err.message:String(err)})}}else{const callbacks=this.fallbackResultCallbacks.get(route);if(callbacks){for(const cb of callbacks){try{cb(result)}catch(err){this.logger?.error("[StorageElicitationStore] Fallback callback error during publish",{elicitId,error:err instanceof Error?err.message:String(err)})}}}}this.logger?.debug("[StorageElicitationStore] Published fallback result",{elicitId,sessionIdHash:sessionIdHash(sessionId),success:result.success})}async destroy(){for(const pendingPromise of this.pendingSubscriptions.values()){try{await pendingPromise}catch(err){this.logger?.debug("[StorageElicitationStore] Pending subscription failed during destroy",{error:err instanceof Error?err.message:String(err)})}}for(const unsubscribe of this.activeSubscriptions.values()){try{await unsubscribe()}catch(err){this.logger?.error("[StorageElicitationStore] Failed to unsubscribe during destroy",{error:err instanceof Error?err.message:String(err)})}}for(const pendingPromise of this.pendingFallbackSubscriptions.values()){try{await pendingPromise}catch(err){this.logger?.debug("[StorageElicitationStore] Pending fallback subscription failed during destroy",{error:err instanceof Error?err.message:String(err)})}}for(const unsubscribe of this.activeFallbackSubscriptions.values()){try{await unsubscribe()}catch(err){this.logger?.error("[StorageElicitationStore] Failed to unsubscribe fallback during destroy",{error:err instanceof Error?err.message:String(err)})}}this.pendingSubscriptions.clear();this.activeSubscriptions.clear();this.localCallbacks.clear();this.pendingFallbackSubscriptions.clear();this.activeFallbackSubscriptions.clear();this.fallbackResultCallbacks.clear();this.logger?.debug("[StorageElicitationStore] Destroyed")}}}});var elicitation_store_factory_exports={};__export(elicitation_store_factory_exports,{createElicitationStore:()=>createElicitationStore,createElicitationStoreFromStorage:()=>createElicitationStoreFromStorage,createMemoryElicitationStore:()=>createMemoryElicitationStore,createSqliteElicitationStore:()=>createSqliteElicitationStore});import{createMemoryStorage,createStorage as createStorage5,getEnv as getEnv15}from"@frontmcp/utils";function detectStorageType(storage,configuredType){if(configuredType==="redis"||configuredType==="upstash"||configuredType==="memory"){return configuredType}const backend=storage.type??storage.backendName;if(backend==="redis"||backend==="upstash"||backend==="memory"){return backend}if(getEnv15("UPSTASH_REDIS_REST_URL")){return"upstash"}if(getEnv15("REDIS_URL")||getEnv15("REDIS_HOST")){return"redis"}return"memory"}async function createElicitationStore(options={}){const{storage:storageConfig,redis,sqlite,keyPrefix="mcp:elicit:",logger,isEdgeRuntime:isEdgeRuntime4=false,requiresPubSub=true,encryption}=options;if(sqlite){if(isEdgeRuntime4&&!hasSqliteDriver()){throw new ElicitationNotSupportedError(`SQLite elicitation store is not supported on Edge runtime without a SQLite driver (better-sqlite3 is a native module). ${SQLITE_ON_EDGE_REMEDY} Otherwise use Redis or Upstash instead.`)}let sqliteStore=createSqliteElicitationStore(sqlite,{keyPrefix,logger});let encrypted2=false;const encryptionEnabled2=encryption?.enabled??"auto";const encryptionSecret2=encryption?.secret;const hasSecret2=encryptionSecret2||isElicitationEncryptionAvailable();if(encryptionEnabled2===true){if(!hasSecret2){throw missingEncryptionSecretError()}sqliteStore=new EncryptedElicitationStore(sqliteStore,{secret:encryptionSecret2,logger});encrypted2=true}else if(encryptionEnabled2==="auto"&&hasSecret2){sqliteStore=new EncryptedElicitationStore(sqliteStore,{secret:encryptionSecret2,logger});encrypted2=true}logger?.info("[ElicitationStoreFactory] Created elicitation store",{type:"sqlite",keyPrefix,supportsPubSub:true,encrypted:encrypted2});return{store:sqliteStore,type:"sqlite",encrypted:encrypted2}}let finalStorageConfig=storageConfig;if(redis&&!storageConfig){const redisOptions=normalizeRedisOptions(redis);if(typeof redisOptions==="string"){throw new ElicitationNotSupportedError(`Invalid Redis configuration: ${redisOptions}`)}if(isVercelKvProvider(redisOptions)){throw new ElicitationNotSupportedError('Vercel KV is not supported for elicitation stores. Elicitation requires pub/sub for cross-node result routing, which Vercel KV does not support. Use Redis provider instead: { provider: "redis", host: "...", port: ... }')}const{host,port,password,db,tls}=redisOptions;finalStorageConfig={type:"redis",redis:{config:{host,port,password,db,tls}}};logger?.debug("[ElicitationStoreFactory] Converted redis option to storage config",{host,port})}const explicitBackend=Boolean(storageConfig||redis);if(finalStorageConfig?.type==="vercel-kv"||!explicitBackend&&getEnv15("KV_REST_API_URL")){throw new ElicitationNotSupportedError("Vercel KV is not supported for elicitation stores. Elicitation requires pub/sub for cross-node result routing, which Vercel KV does not support. Use Redis or Upstash instead.")}if(isEdgeRuntime4&&(!finalStorageConfig||finalStorageConfig.type==="memory")){throw new ElicitationNotSupportedError("Elicitation requires distributed storage when running on Edge runtime. Edge functions are stateless and cannot use in-memory elicitation. Configure Redis or Upstash storage.")}const storage=await createStorage5({...finalStorageConfig,prefix:keyPrefix,fallback:isEdgeRuntime4?"error":"memory"});if(requiresPubSub&&!storage.supportsPubSub()){throw new ElicitationNotSupportedError("Elicitation requires pub/sub support for cross-node result routing. The configured storage backend does not support pub/sub. Use Memory (single-node), Redis, or Upstash storage.")}let store=new StorageElicitationStore(storage,logger);const type=detectStorageType(storage,finalStorageConfig?.type);const encryptionEnabled=encryption?.enabled??"auto";const encryptionSecret=encryption?.secret;const hasSecret=encryptionSecret||isElicitationEncryptionAvailable();let encrypted=false;if(encryptionEnabled===true){if(!hasSecret){throw missingEncryptionSecretError()}store=new EncryptedElicitationStore(store,{secret:encryptionSecret,logger});encrypted=true}else if(encryptionEnabled==="auto"&&hasSecret){store=new EncryptedElicitationStore(store,{secret:encryptionSecret,logger});encrypted=true}logger?.info("[ElicitationStoreFactory] Created elicitation store",{type,keyPrefix,supportsPubSub:storage.supportsPubSub(),encrypted});return{store,type,storage,encrypted}}function createMemoryElicitationStore(options={}){const{keyPrefix="mcp:elicit:",logger,encryption}=options;const storage=createMemoryStorage({prefix:keyPrefix});let store=new StorageElicitationStore(storage,logger);const encryptionEnabled=encryption?.enabled??"auto";const encryptionSecret=encryption?.secret;const hasSecret=encryptionSecret||isElicitationEncryptionAvailable();let encrypted=false;if(encryptionEnabled===true&&!hasSecret)throw missingEncryptionSecretError();if(encryptionEnabled===true&&hasSecret){store=new EncryptedElicitationStore(store,{secret:encryptionSecret,logger});encrypted=true}else if(encryptionEnabled==="auto"&&hasSecret){store=new EncryptedElicitationStore(store,{secret:encryptionSecret,logger});encrypted=true}logger?.debug("[ElicitationStoreFactory] Created explicit in-memory elicitation store",{encrypted});return{store,type:"memory",storage,encrypted}}function missingEncryptionSecretError(){return new ElicitationNotSupportedError("Elicitation encryption is enabled but no secret is available. Set MCP_ELICITATION_SECRET, MCP_SESSION_SECRET, or MCP_SERVER_SECRET environment variable, or provide a secret in the encryption configuration.")}function createElicitationStoreFromStorage(storage,options={}){const{keyPrefix="mcp:elicit:",logger,requiresPubSub=true,encryption}=options;if(requiresPubSub&&!storage.supportsPubSub()){throw new ElicitationNotSupportedError("Elicitation requires pub/sub support for cross-node result routing. The provided storage does not support pub/sub.")}const namespacedStorage=storage.namespace(keyPrefix.replace(/:$/,""));let store=new StorageElicitationStore(namespacedStorage,logger);const type=detectStorageType(storage);const encryptionEnabled=encryption?.enabled??"auto";const encryptionSecret=encryption?.secret;const hasSecret=encryptionSecret||isElicitationEncryptionAvailable();let encrypted=false;if(encryptionEnabled===true&&!hasSecret)throw missingEncryptionSecretError();if(encryptionEnabled===true&&hasSecret){store=new EncryptedElicitationStore(store,{secret:encryptionSecret,logger});encrypted=true}else if(encryptionEnabled==="auto"&&hasSecret){store=new EncryptedElicitationStore(store,{secret:encryptionSecret,logger});encrypted=true}logger?.debug("[ElicitationStoreFactory] Created elicitation store from existing storage",{type,keyPrefix,encrypted});return{store,type,storage,encrypted}}function createSqliteElicitationStore(sqliteConfig,storeOptions={}){const{keyPrefix="mcp:elicit:",logger}=storeOptions;const{SqliteElicitationStore}=requireOptionalModule("@frontmcp/storage-sqlite",()=>require_dist());logger?.info("[ElicitationStoreFactory] Creating SQLite elicitation store",{path:sqliteConfig.path,keyPrefix});return new SqliteElicitationStore({...sqliteConfig,keyPrefix})}var init_elicitation_store_factory=__esm({"libs/sdk/src/elicitation/store/elicitation-store.factory.ts"(){"use strict";init_common();init_schema5();init_elicitation_error();init_optional_dependency_util();init_sqlite_on_edge();init_elicitation_encryption();init_encrypted_elicitation_store();init_storage_elicitation_store()}});var task_session_index_exports={};__export(task_session_index_exports,{TaskSessionIndex:()=>TaskSessionIndex});import{expiresAtToTTL as expiresAtToTTL2,randomUUID as randomUUID24}from"@frontmcp/utils";function readyMarkerOf(readiness){if(!readiness?.startsWith(BACKFILLED))return void 0;const[generation,count]=readiness.slice(BACKFILLED.length).split(":");return{generation,count:Number(count??0)}}function sessionTaskKey(sessionId,suffix){return`${sessionId}:${suffix}`}async function mgetInBatches(read,keys){const values=[];for(let start=0;start<keys.length;start+=READ_BATCH_SIZE){values.push(...await read(keys.slice(start,start+READ_BATCH_SIZE)))}return values}var POSITION_GRACE_SECONDS,BACKFILL_CLAIM_TTL_SECONDS,POSITION_WRITE_SECONDS,SETTLED_NOTE_TTL_SECONDS,READ_BATCH_SIZE,BACKFILLED,TaskSessionIndex;var init_task_session_index=__esm({"libs/sdk/src/task/store/task-session-index.ts"(){"use strict";POSITION_GRACE_SECONDS=3600;BACKFILL_CLAIM_TTL_SECONDS=60;POSITION_WRITE_SECONDS=60;SETTLED_NOTE_TTL_SECONDS=3600;READ_BATCH_SIZE=500;BACKFILLED="done:";TaskSessionIndex=class{constructor(storage,source,maxTaskTtlSeconds){this.source=source;this.positions=storage.namespace("index");this.positionOf=storage.namespace("index-of");this.counts=storage.namespace("index-count");this.starts=storage.namespace("index-start");this.skips=storage.namespace("index-skip");this.settled=storage.namespace("index-settled");this.readiness=storage.namespace("index-ready");this.countTtlSeconds=Math.ceil(maxTaskTtlSeconds)+POSITION_GRACE_SECONDS}source;positions;positionOf;counts;starts;skips;settled;readiness;countTtlSeconds;async add(record,ttlSeconds){const{sessionId}=record;const countTtlSeconds=Math.max(this.countTtlSeconds,ttlSeconds+POSITION_GRACE_SECONDS);await this.ensureCount(sessionId,countTtlSeconds);const position=await this.counts.incr(sessionId);if(position===1&&await this.publishedCount(sessionId)>0)await this.readiness.delete(sessionId);await this.keepCountAlive(sessionId,countTtlSeconds);await this.number(record,position,ttlSeconds)}async ensureCount(sessionId,ttlSeconds){await this.counts.extendTtl(sessionId,ttlSeconds);await this.counts.set(sessionId,"0",{ifNotExists:true,ttlSeconds})}async extend(record,ttlSeconds){const{sessionId,taskId}=record;const position=await this.positionOf.get(sessionTaskKey(sessionId,taskId));if(position===null)return;await this.positionOf.extendTtl(sessionTaskKey(sessionId,taskId),ttlSeconds);await this.positions.extendTtl(sessionTaskKey(sessionId,position),ttlSeconds+POSITION_GRACE_SECONDS);await this.keepCountAlive(sessionId,ttlSeconds+POSITION_GRACE_SECONDS)}async keepCountAlive(sessionId,ttlSeconds){await this.counts.extendTtl(sessionId,ttlSeconds);const readiness=await this.readiness.get(sessionId);if(readiness?.startsWith(BACKFILLED))await this.readiness.extendTtl(sessionId,ttlSeconds)}async remove(record){await this.positionOf.delete(sessionTaskKey(record.sessionId,record.taskId))}async page(sessionId,startPosition,pageSize){const generation=startPosition===0?await this.ensureBackfilled(sessionId):await this.generationOf(sessionId);if(startPosition===0&&generation===void 0)return void 0;const positionsUsed=Number(await this.counts.get(sessionId)??0);const writtenUpTo=await this.writtenUpTo(sessionId,positionsUsed,generation);const tasks=[];let anchor=startPosition;let skippedTo=await this.skippedTo(sessionId,anchor,generation);let goneUpTo=skippedTo;let runOpen=true;let position=skippedTo;while(tasks.length<pageSize&&position<positionsUsed){const batchEnd=Math.min(positionsUsed,position+pageSize-tasks.length);const batch=Array.from({length:batchEnd-position},(_,offset)=>position+offset+1);const taskIds=await this.positions.mget(batch.map(indexed=>sessionTaskKey(sessionId,indexed)));const numbers=await this.positionOf.mget(taskIds.map(taskId=>sessionTaskKey(sessionId,taskId??"")));position=batchEnd;for(const[offset,taskId]of taskIds.entries()){const at=batch[offset];const ownPosition=taskId!==null&&numbers[offset]===String(at);const record=ownPosition?await this.source.readTask(taskId,sessionId):null;if(record===null){const gone=taskId===null?at<=writtenUpTo:!ownPosition;runOpen=runOpen&&gone;if(runOpen)goneUpTo=at;continue}if(goneUpTo>skippedTo)await this.rememberSkip(sessionId,anchor,goneUpTo,generation);tasks.push(record);anchor=at;skippedTo=await this.skippedTo(sessionId,at,generation);goneUpTo=skippedTo;runOpen=true;if(skippedTo>at&&tasks.length<pageSize){position=Math.min(skippedTo,positionsUsed);break}}}if(goneUpTo>skippedTo)await this.rememberSkip(sessionId,anchor,goneUpTo,generation);return{tasks,endPosition:position,positionsUsed}}async generationOf(sessionId){return readyMarkerOf(await this.readiness.get(sessionId))?.generation}async publishedCount(sessionId){return readyMarkerOf(await this.readiness.get(sessionId))?.count??0}async skippedTo(sessionId,anchor,generation){if(generation===void 0)return anchor;const stored=anchor===0?await this.starts.get(sessionId):await this.skips.get(sessionTaskKey(sessionId,anchor));const[storedGeneration,goneUpTo]=(stored??"").split(":");return storedGeneration===generation?Math.max(anchor,Number(goneUpTo)):anchor}async rememberSkip(sessionId,anchor,goneUpTo,generation){const remaining=await this.counts.ttl(sessionId);if(generation===void 0||remaining===null||remaining<=0)return;const skip=`${generation}:${goneUpTo}`;if(anchor===0){await this.starts.set(sessionId,skip,{ttlSeconds:remaining})}else{await this.skips.set(sessionTaskKey(sessionId,anchor),skip,{ttlSeconds:remaining})}}async writtenUpTo(sessionId,positionsUsed,generation){if(generation===void 0)return 0;const[notedGeneration,notedPosition]=(await this.settled.get(sessionId)??"").split(":");const noted=notedGeneration===generation?Number(notedPosition):void 0;const remaining=noted===void 0?null:await this.settled.ttl(sessionId);const age=remaining===null||remaining<0?Infinity:SETTLED_NOTE_TTL_SECONDS-remaining;if(age<POSITION_WRITE_SECONDS)return 0;if(noted===void 0||positionsUsed>noted){await this.settled.set(sessionId,`${generation}:${positionsUsed}`,{ttlSeconds:SETTLED_NOTE_TTL_SECONDS})}return noted??0}async number(record,position,ttlSeconds){const{sessionId,taskId}=record;await this.positionOf.set(sessionTaskKey(sessionId,taskId),String(position),{ttlSeconds});await this.positions.set(sessionTaskKey(sessionId,position),taskId,{ttlSeconds:ttlSeconds+POSITION_GRACE_SECONDS})}async ensureBackfilled(sessionId){const state=await this.readiness.get(sessionId);const ready=readyMarkerOf(state);if(ready)return ready.generation;if(state!==null)return void 0;const generation=randomUUID24();const claim=`running:${generation}`;await this.readiness.set(sessionId,claim,{ifNotExists:true,ttlSeconds:BACKFILL_CLAIM_TTL_SECONDS});if(await this.readiness.get(sessionId)!==claim)return void 0;const holding=this.holdClaim(sessionId,claim);try{const publishedCount=await this.backfill(sessionId,holding.held);if(publishedCount===void 0||!await this.renewClaim(sessionId,claim))return void 0;const remaining=await this.counts.ttl(sessionId);const ttlSeconds=remaining!==null&&remaining>0?remaining:this.countTtlSeconds;await this.readiness.set(sessionId,`${BACKFILLED}${generation}:${publishedCount}`,{ttlSeconds});return generation}finally{holding.release()}}holdClaim(sessionId,claim){let held=true;const renewal=setInterval(()=>{void this.renewClaim(sessionId,claim).then(renewed=>{held=held&&renewed},()=>{held=false})},BACKFILL_CLAIM_TTL_SECONDS*1e3/3);renewal.unref?.();return{held:()=>held,release:()=>clearInterval(renewal)}}async renewClaim(sessionId,claim){return this.readiness.expireIfEquals(sessionId,claim,BACKFILL_CLAIM_TTL_SECONDS)}async backfill(sessionId,held){const{records,recordKey:recordKey2,scanSessionTaskIds}=this.source;const taskIds=await scanSessionTaskIds(sessionId);if(!held())return void 0;const stored=await mgetInBatches(keys=>records.mget(keys),taskIds.map(taskId=>recordKey2(sessionId,taskId)));const live=stored.filter(record=>record!==null&&record.sessionId===sessionId&&expiresAtToTTL2(record.expiresAt)>0);const numbered=await mgetInBatches(keys=>this.positionOf.mget(keys),live.map(record=>sessionTaskKey(sessionId,record.taskId)));const listedAt=await mgetInBatches(keys=>this.positions.mget(keys),numbered.map(position=>sessionTaskKey(sessionId,position??0)));const missingAt=live.flatMap((record,index)=>numbered[index]===null||listedAt[index]!==record.taskId?[index]:[]);const missing=missingAt.map(index=>live[index]);if(!held())return void 0;if(missing.length===0)return Number(await this.counts.get(sessionId)??0);const longestTtl=missing.reduce((longest,record)=>Math.max(longest,expiresAtToTTL2(record.expiresAt)),0);const countTtlSeconds=Math.max(this.countTtlSeconds,longestTtl+POSITION_GRACE_SECONDS);await this.ensureCount(sessionId,countTtlSeconds);const lastPosition=await this.counts.incrBy(sessionId,missing.length);await this.keepCountAlive(sessionId,countTtlSeconds);const firstPosition=lastPosition-missing.length+1;for(const[offset,record]of missing.entries()){if(!held())return void 0;const ttlSeconds=expiresAtToTTL2(record.expiresAt);const staleNumber=numbered[missingAt[offset]];if(ttlSeconds>0)await this.numberEarlierTask(record,firstPosition+offset,ttlSeconds,staleNumber)}return lastPosition}async numberEarlierTask(record,position,ttlSeconds,staleNumber){const{sessionId,taskId}=record;const indexOfKey=sessionTaskKey(sessionId,taskId);if(staleNumber!==null)await this.positionOf.deleteIfEquals(indexOfKey,staleNumber);await this.positionOf.set(indexOfKey,String(position),{ttlSeconds,ifNotExists:true});if(await this.positionOf.get(indexOfKey)!==String(position))return;await this.positions.set(sessionTaskKey(sessionId,position),taskId,{ttlSeconds:ttlSeconds+POSITION_GRACE_SECONDS});const current=await this.source.readTask(record.taskId,record.sessionId);const currentTtl=current?expiresAtToTTL2(current.expiresAt):0;if(current&&currentTtl>ttlSeconds)await this.extend(current,currentTtl)}}}});import{base64urlDecode as base64urlDecode3,base64urlEncode as base64urlEncode5,expiresAtToTTL as expiresAtToTTL3,TypedStorage as TypedStorage2}from"@frontmcp/utils";function recordKey(sessionId,taskId){return`${sessionId}:${taskId}`}function slotKey(sessionId,slot){return`${sessionId}:${slot}`}function encodeCursor(offset,source){return base64urlEncode5(new TextEncoder().encode(JSON.stringify({offset,source})))}function decodeCursor(cursor){try{const bytes=base64urlDecode3(cursor);const parsed=JSON.parse(new TextDecoder().decode(bytes));if(typeof parsed?.offset==="number"&&parsed.offset>=0&&Number.isInteger(parsed.offset)){return{offset:parsed.offset,source:parsed.source==="index"?"index":"scan"}}}catch{}return{offset:0,source:"scan"}}var TERMINAL_CHANNEL_PREFIX,CANCEL_CHANNEL_PREFIX,RECORDS_NAMESPACE,SLOTS_NAMESPACE,DEFAULT_PAGE_SIZE2,StorageTaskStore;var init_storage_task_store=__esm({"libs/sdk/src/task/store/storage-task.store.ts"(){"use strict";init_process_liveness();init_task_types();TERMINAL_CHANNEL_PREFIX="terminal:";CANCEL_CHANNEL_PREFIX="cancel:";RECORDS_NAMESPACE="records";SLOTS_NAMESPACE="slots";DEFAULT_PAGE_SIZE2=50;StorageTaskStore=class{storage;records;slots;sessionIndex;logger;listFrom;maxTtlMs;terminalCallbacks=new Map;terminalSubs=new Map;cancelCallbacks=new Map;cancelSubs=new Map;constructor(storage,logger,options={}){this.storage=storage;this.logger=logger;this.listFrom=options.listFrom??"index";this.maxTtlMs=options.maxTtlMs??TASK_DEFAULTS.maxTtlMs;this.records=new TypedStorage2(storage.namespace(RECORDS_NAMESPACE));this.slots=storage.namespace(SLOTS_NAMESPACE)}async create(record){const ttlSeconds=expiresAtToTTL3(record.expiresAt);if(ttlSeconds<=0){this.logger?.warn("[StorageTaskStore] create: record already expired, skipping",{taskId:record.taskId});return}const key=recordKey(record.sessionId,record.taskId);await(await this.loadSessionIndex()).add(record,ttlSeconds);await this.records.set(key,record,{ttlSeconds});this.logger?.debug("[StorageTaskStore] created",{taskId:record.taskId,ttlSeconds})}async createWithinLimit(record,maxActive){const ttlSeconds=expiresAtToTTL3(record.expiresAt);if(ttlSeconds<=0){await this.create(record);return true}const slot=await this.acquireSlot(record,maxActive,ttlSeconds);if(slot===void 0)return false;const slotted={...record,concurrencySlot:slot};try{await this.create(slotted)}catch(err){await this.releaseSlot(slotted);throw err}return true}async get(taskId,sessionId){const record=await this.records.get(recordKey(sessionId,taskId));if(!record)return null;if(record.sessionId!==sessionId)return null;if(record.expiresAt&&Date.now()>record.expiresAt){await this.delete(taskId,sessionId).catch(error=>this.logger?.warn("[StorageTaskStore] failed to clean up an expired task",{taskId,error:error instanceof Error?error.message:String(error)}));return null}return record}async update(taskId,sessionId,patch){const existing=await this.get(taskId,sessionId);if(!existing)return null;const merged={...existing,...patch,taskId:existing.taskId,sessionId:existing.sessionId,createdAt:existing.createdAt,lastUpdatedAt:new Date().toISOString()};const ttlSeconds=expiresAtToTTL3(merged.expiresAt);if(ttlSeconds<=0){await this.delete(taskId,sessionId);return null}await this.records.set(recordKey(sessionId,taskId),merged,{ttlSeconds});if(patch.expiresAt!==void 0)await(await this.loadSessionIndex()).extend(merged,ttlSeconds);if(isTerminal(merged.status))await this.releaseSlot(merged);return merged}async delete(taskId,sessionId){const existing=await this.records.get(recordKey(sessionId,taskId));await this.records.delete(recordKey(sessionId,taskId));if(!existing)return;try{await(await this.loadSessionIndex()).remove(existing)}finally{await this.releaseSlot(existing)}}async acquireSlot(record,maxActive,ttlSeconds){const owner=record.sessionId;const slotKeys=Array.from({length:maxActive},(_,slot)=>slotKey(owner,slot));const holders=await this.slots.mget(slotKeys);const claimed=await this.claimFreeSlot(owner,holders,record.taskId,ttlSeconds);if(claimed!==void 0||!await this.reclaimSlots(owner,holders))return claimed;return this.claimFreeSlot(owner,await this.slots.mget(slotKeys),record.taskId,ttlSeconds)}async claimFreeSlot(owner,holders,taskId,ttlSeconds){for(const[slot,holder]of holders.entries()){if(holder!==null)continue;const key=slotKey(owner,slot);await this.slots.set(key,taskId,{ttlSeconds,ifNotExists:true});if(await this.slots.get(key)===taskId)return slot}return void 0}async reclaimSlots(owner,holders){let reclaimed=false;for(const holderTaskId of holders){if(holderTaskId===null)continue;const holder=await this.records.get(recordKey(owner,holderTaskId));if(!holder)continue;if(isTerminal(holder.status)){await this.releaseSlot(holder);reclaimed=true;continue}const workerPid=holder.executor?.host==="cli"&&isLocalWorker(holder.executor)?holder.executor.pid:void 0;if(workerPid===void 0||isAlive(workerPid))continue;const failed=await this.update(holderTaskId,owner,{status:"failed",statusMessage:"Task runner exited before completing the task"});if(failed)await this.publishTerminal(failed);reclaimed=true}return reclaimed}async releaseSlot(record){if(record.concurrencySlot===void 0)return;try{await this.slots.deleteIfEquals(slotKey(record.sessionId,record.concurrencySlot),record.taskId)}catch(err){this.logger?.warn("[StorageTaskStore] failed to release a concurrency slot",{taskId:record.taskId,error:err instanceof Error?err.message:String(err)})}}async list(sessionId,opts={}){const pageSize=Math.max(1,Math.min(opts.pageSize??DEFAULT_PAGE_SIZE2,500));const resumed=opts.cursor?decodeCursor(opts.cursor):void 0;const startAt=resumed?.offset??0;const source=resumed?.source??this.listFrom;return source==="scan"?this.listFromScan(sessionId,startAt,pageSize):this.listFromIndex(sessionId,startAt,pageSize)}async listFromScan(sessionId,offset,pageSize){const matching=await this.scanSessionTaskIds(sessionId);const slice=matching.slice(offset,offset+pageSize);const tasks=[];for(const taskId of slice){const record=await this.get(taskId,sessionId);if(record)tasks.push(record)}const nextOffset=offset+slice.length;const page2={tasks};if(nextOffset<matching.length)page2.nextCursor=encodeCursor(nextOffset,"scan");return page2}async listFromIndex(sessionId,startPosition,pageSize){const sessionIndex=await this.loadSessionIndex();const indexPage=await sessionIndex.page(sessionId,startPosition,pageSize);if(!indexPage)return this.listFromScan(sessionId,0,pageSize);const{tasks,endPosition,positionsUsed}=indexPage;const page2={tasks};if(endPosition<positionsUsed)page2.nextCursor=encodeCursor(endPosition,"index");return page2}loadSessionIndex(){this.sessionIndex??=Promise.resolve().then(()=>(init_task_session_index(),task_session_index_exports)).then(({TaskSessionIndex:TaskSessionIndex2})=>new TaskSessionIndex2(this.storage,{records:this.records,recordKey,scanSessionTaskIds:sessionId=>this.scanSessionTaskIds(sessionId),readTask:(taskId,sessionId)=>this.get(taskId,sessionId)},this.maxTtlMs/1e3));return this.sessionIndex}async scanSessionTaskIds(sessionId){const sessionPrefix=`${sessionId}:`;return(await this.storage.namespace(RECORDS_NAMESPACE).keys()).filter(key=>key.startsWith(sessionPrefix)).map(key=>key.slice(sessionPrefix.length)).sort()}async subscribeTerminal(taskId,_sessionId,cb){const channel2=TERMINAL_CHANNEL_PREFIX+taskId;let set=this.terminalCallbacks.get(taskId);if(!set){set=new Set;this.terminalCallbacks.set(taskId,set)}set.add(cb);if(!this.terminalSubs.has(taskId)&&this.storage.supportsPubSub()){const unsubscribe=await this.storage.subscribe(channel2,message=>{try{const record=JSON.parse(message);const subs=this.terminalCallbacks.get(taskId);if(subs){for(const fn of subs){try{fn(record)}catch(err){this.logger?.error("[StorageTaskStore] terminal callback threw",{taskId,error:err instanceof Error?err.message:String(err)})}}}}catch(err){this.logger?.error("[StorageTaskStore] failed to parse terminal message",{taskId,error:err instanceof Error?err.message:String(err)})}});this.terminalSubs.set(taskId,unsubscribe)}const callbackSet=set;return async()=>{callbackSet.delete(cb);if(callbackSet.size===0){this.terminalCallbacks.delete(taskId);const unsubscribe=this.terminalSubs.get(taskId);if(unsubscribe){this.terminalSubs.delete(taskId);try{await unsubscribe()}catch{}}}}}async publishTerminal(record){const channel2=TERMINAL_CHANNEL_PREFIX+record.taskId;const fanOutLocal=()=>{const subs=this.terminalCallbacks.get(record.taskId);if(!subs)return;for(const cb of subs){try{cb(record)}catch{}}};if(this.storage.supportsPubSub()){try{await this.storage.publish(channel2,JSON.stringify(record))}catch(err){this.logger?.error("[StorageTaskStore] failed to publish terminal; falling back to local callbacks",{taskId:record.taskId,error:err instanceof Error?err.message:String(err)});fanOutLocal()}}else{fanOutLocal()}}async subscribeCancel(taskId,_sessionId,cb){const channel2=CANCEL_CHANNEL_PREFIX+taskId;let set=this.cancelCallbacks.get(taskId);if(!set){set=new Set;this.cancelCallbacks.set(taskId,set)}set.add(cb);if(!this.cancelSubs.has(taskId)&&this.storage.supportsPubSub()){const unsubscribe=await this.storage.subscribe(channel2,()=>{const subs=this.cancelCallbacks.get(taskId);if(subs){for(const fn of subs){try{fn()}catch{}}}});this.cancelSubs.set(taskId,unsubscribe)}const callbackSet=set;return async()=>{callbackSet.delete(cb);if(callbackSet.size===0){this.cancelCallbacks.delete(taskId);const unsubscribe=this.cancelSubs.get(taskId);if(unsubscribe){this.cancelSubs.delete(taskId);try{await unsubscribe()}catch{}}}}}async publishCancel(taskId,_sessionId){const channel2=CANCEL_CHANNEL_PREFIX+taskId;const fanOutLocal=()=>{const subs=this.cancelCallbacks.get(taskId);if(!subs)return;for(const fn of subs){try{fn()}catch{}}};if(this.storage.supportsPubSub()){try{await this.storage.publish(channel2,"1")}catch(err){this.logger?.error("[StorageTaskStore] failed to publish cancel; falling back to local callbacks",{taskId,error:err instanceof Error?err.message:String(err)});fanOutLocal();return}}else{const subs=this.cancelCallbacks.get(taskId);if(subs){for(const fn of subs){try{fn()}catch{}}}}}async destroy(){for(const unsubscribe of this.terminalSubs.values()){try{await unsubscribe()}catch{}}for(const unsubscribe of this.cancelSubs.values()){try{await unsubscribe()}catch{}}this.terminalSubs.clear();this.cancelSubs.clear();this.terminalCallbacks.clear();this.cancelCallbacks.clear()}}}});import{createMemoryStorage as createMemoryStorage2,createStorage as createStorage6,getEnv as getEnv16}from"@frontmcp/utils";function detectStorageType2(storage,configuredType){if(configuredType==="redis")return"redis";if(configuredType==="upstash")return"upstash";if(configuredType==="memory")return"memory";const storageBackend=storage.type??storage.backendName;if(storageBackend==="redis"||storageBackend==="upstash"||storageBackend==="memory"){return storageBackend}if(getEnv16("UPSTASH_REDIS_REST_URL"))return"upstash";if(getEnv16("REDIS_URL")||getEnv16("REDIS_HOST"))return"redis";return"memory"}async function createTaskStore(options={}){const{storage:storageConfig,redis,keyPrefix="mcp:task:",logger,isEdgeRuntime:isEdgeRuntime4=false,sqlite}=options;if(isEdgeRuntime4&&sqlite&&!hasSqliteDriver()){throw new TaskStoreNotSupportedError(`SQLite task store is not supported on Edge runtime without a SQLite driver (better-sqlite3 is a native module). ${SQLITE_ON_EDGE_REMEDY} Otherwise use Redis or Upstash.`)}if(sqlite){const{SqliteTaskStore}=requireOptionalModule("@frontmcp/storage-sqlite",()=>require_dist());const store2=new SqliteTaskStore({path:sqlite.path,encryption:sqlite.encryption,walMode:sqlite.walMode??true,ttlCleanupIntervalMs:sqlite.ttlCleanupIntervalMs??6e4,busyTimeoutMs:sqlite.busyTimeoutMs,logger:logger?{debug:(m,meta)=>logger.debug(m,meta),warn:(m,meta)=>logger.warn(m,meta),error:(m,meta)=>logger.error(m,meta)}:void 0});logger?.info("[TaskStoreFactory] Created SQLite task store",{path:sqlite.path,keyPrefix});return{store:store2,type:"sqlite"}}let finalStorageConfig=storageConfig;if(redis&&!isExplicitStorage(storageConfig)){const redisOptions=normalizeRedisOptions(redis);if(typeof redisOptions==="string"){throw new TaskStoreNotSupportedError(`Invalid Redis configuration: ${redisOptions}`)}if(isVercelKvProvider(redisOptions)){throw new TaskStoreNotSupportedError("Vercel KV is not supported for task stores. Task result blocking and cancel signalling require pub/sub. Use Redis or Upstash instead.")}const{host,port,password,db,tls}=redisOptions;finalStorageConfig={type:"redis",redis:{config:{host,port,password,db,tls}}}}const explicitBackend=isExplicitStorage(storageConfig)||Boolean(redis);if(finalStorageConfig?.type==="vercel-kv"||!explicitBackend&&getEnv16("KV_REST_API_URL")){throw new TaskStoreNotSupportedError("Vercel KV is not supported for task stores (pub/sub required). Use Redis or Upstash.")}if(isEdgeRuntime4&&(!finalStorageConfig||finalStorageConfig.type==="memory")){throw new TaskStoreNotSupportedError("Tasks require distributed storage on Edge runtime. Configure Redis or Upstash.")}const storage=await createStorage6({...finalStorageConfig,prefix:keyPrefix,fallback:isEdgeRuntime4?"error":"memory"});const store=new StorageTaskStore(storage,logger,{listFrom:options.listFrom,maxTtlMs:options.maxTtlMs});const type=detectStorageType2(storage,finalStorageConfig?.type);logger?.info("[TaskStoreFactory] Created task store",{type,keyPrefix,supportsPubSub:storage.supportsPubSub()});return{store,type,storage}}function createMemoryTaskStore(options={}){const{keyPrefix="mcp:task:",logger}=options;const storage=createMemoryStorage2({prefix:keyPrefix});return{store:new StorageTaskStore(storage,logger),type:"memory",storage}}var TaskStoreNotSupportedError;var init_task_store_factory=__esm({"libs/sdk/src/task/store/task-store.factory.ts"(){"use strict";init_common();init_schema5();init_optional_dependency_util();init_sqlite_on_edge();init_storage_task_store();init_task_backend_utils();init_task_backend_utils();TaskStoreNotSupportedError=class extends Error{constructor(message){super(message);this.name="TaskStoreNotSupportedError"}}}});var TaskRegistry;var init_task_registry=__esm({"libs/sdk/src/task/task.registry.ts"(){"use strict";TaskRegistry=class{abortControllers=new Map;logger;config;_runner;constructor(config={},logger){this.config=config;this.logger=logger}setRunner(runner){this._runner=runner}get runner(){return this._runner}trackRunning(taskId){const controller=new AbortController;this.abortControllers.set(taskId,controller);return controller}untrack(taskId){this.abortControllers.delete(taskId)}abort(taskId,reason){const controller=this.abortControllers.get(taskId);if(!controller)return false;try{controller.abort(reason)}catch(err){this.logger?.warn("[TaskRegistry] abort failed",{taskId,error:err instanceof Error?err.message:String(err)})}return true}runningCount(){return this.abortControllers.size}getConfig(){return this.config}getCapabilities(inputs){if(this.config.enabled===false)return{};if(!inputs.hasTaskEnabledTool)return{};const caps={cancel:{},requests:{tools:{call:{}}}};if(inputs.canIdentifyRequestors){caps["list"]={}}return{tasks:caps}}}}});import{runRequestExclusive as runRequestExclusive6}from"@frontmcp/utils";function runTaskInBackground(params){return Promise.resolve().then(()=>runRequestExclusive6(()=>executeTask(params)))}async function executeTask(params){const{record,cleanedRequestParams,ctx,scope,store,registry,notifier,logger}=params;const{taskId,sessionId}=record;const controller=registry.trackRunning(taskId);let unsubscribeCancel;const taskCtx=ctx;taskCtx.signal=controller.signal;taskCtx.taskId=taskId;try{unsubscribeCancel=await store.subscribeCancel(taskId,sessionId,()=>{if(!controller.signal.aborted){controller.abort("tasks/cancel")}});const innerRequest={method:"tools/call",params:cleanedRequestParams};let outcomeOk;let outcomeErr;try{outcomeOk=await scope.runFlowForOutput("tools:call-tool",{request:innerRequest,ctx:taskCtx})}catch(err){if(err instanceof InputRequiredSignal){const beforePause=await store.get(taskId,sessionId);if(!beforePause||isTerminal(beforePause.status)){logger?.debug("[task-runner] input required but task already terminal; leaving as-is",{taskId,status:beforePause?.status});return}const paused=await store.update(taskId,sessionId,{status:"input_required",statusMessage:"The task is waiting for additional input.",inputRequests:err.inputRequests});logger?.info("[task-runner] task paused awaiting input",{taskId,keys:Object.keys(err.inputRequests)});if(paused)notifier.sendStatus(paused);return}try{outcomeOk=toolCallErrorResult(err,{errorHandler:new ErrorHandler({logger}),toolName:String(cleanedRequestParams["name"]??"unknown"),logger})}catch(protocolError){outcomeErr=toJsonRpcError2(protocolError)}}const current=await store.get(taskId,sessionId);if(!current){logger?.debug("[task-runner] record gone before terminal write",{taskId});return}if(isTerminal(current.status)){await store.publishTerminal(current);notifier.sendStatus(current);return}const isErrorResult=outcomeErr!==void 0||outcomeOk?.isError===true;const finalStatus=controller.signal.aborted?"cancelled":isErrorResult?"failed":"completed";const statusMessage=controller.signal.aborted?"The task was cancelled before completion.":outcomeErr?.message??(outcomeOk?.isError===true?"Tool execution returned isError: true":void 0);const updated=await store.update(taskId,sessionId,{status:finalStatus,statusMessage,outcome:outcomeErr?{kind:"error",error:outcomeErr}:outcomeOk?{kind:"ok",data:outcomeOk}:void 0});if(updated){await store.publishTerminal(updated);notifier.sendStatus(updated)}}catch(err){logger?.error("[task-runner] unhandled error in task lifecycle",{taskId,error:err instanceof Error?err.message:String(err)});if(!controller.signal.aborted)controller.abort("task-runner error");try{const failure=toJsonRpcError2(err);const failed=await store.update(taskId,sessionId,{status:"failed",statusMessage:failure.message,outcome:{kind:"error",error:failure}});if(failed){try{await store.publishTerminal(failed)}catch{}notifier.sendStatus(failed)}}catch{}}finally{registry.untrack(taskId);if(unsubscribeCancel){try{await unsubscribeCancel()}catch{}}}}function toJsonRpcError2(err){const sdkError=toSdkMcpError(err);const message=sdkError.message.replace(/^MCP error -?\d+: /,"");return sdkError.data===void 0?{code:sdkError.code,message}:{code:sdkError.code,message,data:sdkError.data}}var init_task_runner=__esm({"libs/sdk/src/task/helpers/task-runner.ts"(){"use strict";init_errors();init_call_tool_error_utils();init_mcp_error_utils();init_task_types()}});var InProcessTaskRunner;var init_in_process_task_runner=__esm({"libs/sdk/src/task/helpers/in-process-task-runner.ts"(){"use strict";init_task_runner();InProcessTaskRunner=class{constructor(deps){this.deps=deps}deps;kind="in-process";async run(record,context){await this.deps.store.update(record.taskId,record.sessionId,{executor:{host:"in-process",spawnedAt:new Date().toISOString()}});void runTaskInBackground({record,cleanedRequestParams:context.cleanedRequestParams,ctx:context.ctx,scope:this.deps.scope,store:this.deps.store,registry:this.deps.registry,notifier:this.deps.notifier,logger:this.deps.logger})}async cancel(record){this.deps.registry.abort(record.taskId,"tasks/cancel")}}}});import{internalZ as z117}from"@frontmcp/lazy-zod";import{GetTaskRequestSchema as GetTaskRequestSchema2,GetTaskResultSchema}from"@frontmcp/protocol";var inputSchema21,outputSchema20,stateSchema25,plan28,name28,Stage28,TasksGetFlow;var init_tasks_get_flow=__esm({"libs/sdk/src/task/flows/tasks-get.flow.ts"(){"use strict";init_common();init_errors();init_task_types();inputSchema21=z117.object({request:GetTaskRequestSchema2,ctx:z117.any()});outputSchema20=GetTaskResultSchema;stateSchema25=z117.object({taskId:z117.string(),sessionId:z117.string(),authInfo:z117.any()});plan28={pre:["parseInput"],execute:["fetchAndRespond"]};name28="tasks:get";({Stage:Stage28}=FlowHooksOf(name28));TasksGetFlow=class extends FlowBase{logger=this.scopeLogger.child("TasksGetFlow");async parseInput(){let method;let params;let ctx;try{const parsed=inputSchema21.parse(this.rawInput);method=parsed.request.method;params=parsed.request.params;ctx=parsed.ctx}catch(e){throw new InvalidInputError("Invalid tasks/get request",e instanceof z117.ZodError?e.issues:void 0)}if(method!=="tasks/get"){throw new InvalidMethodError(method,"tasks/get")}const authInfo=ctx?.authInfo;if(!authInfo?.sessionId){throw new InternalMcpError("Session ID missing in authorized flow","AUTH_INFO_MISSING")}this.state.set({taskId:params.taskId,sessionId:authInfo.sessionId,authInfo})}async fetchAndRespond(){const store=this.scope.taskStore;if(!store)throw new TaskStoreNotInitializedError;const{taskId,sessionId}=this.state.required;const record=await store.get(taskId,sessionId);if(!record)throw new TaskNotFoundError(taskId);this.respond(toWireShape(record))}};__decorateClass([Stage28("parseInput")],TasksGetFlow.prototype,"parseInput",1);__decorateClass([Stage28("fetchAndRespond")],TasksGetFlow.prototype,"fetchAndRespond",1);TasksGetFlow=__decorateClass([FrontMcpFlow({name:name28,plan:plan28,inputSchema:inputSchema21,outputSchema:outputSchema20,access:"authorized"})],TasksGetFlow)}});import{internalZ as z118}from"@frontmcp/lazy-zod";import{GetTaskPayloadRequestSchema as GetTaskPayloadRequestSchema2,GetTaskPayloadResultSchema}from"@frontmcp/protocol";var inputSchema22,outputSchema21,stateSchema26,plan29,name29,Stage29,TasksResultFlow,JsonRpcReplayError;var init_tasks_result_flow=__esm({"libs/sdk/src/task/flows/tasks-result.flow.ts"(){"use strict";init_common();init_errors();init_task_types();inputSchema22=z118.object({request:GetTaskPayloadRequestSchema2,ctx:z118.any()});outputSchema21=GetTaskPayloadResultSchema;stateSchema26=z118.object({taskId:z118.string(),sessionId:z118.string(),authInfo:z118.any()});plan29={pre:["parseInput"],execute:["awaitTerminal"]};name29="tasks:result";({Stage:Stage29}=FlowHooksOf(name29));TasksResultFlow=class extends FlowBase{logger=this.scopeLogger.child("TasksResultFlow");async parseInput(){let method;let params;let ctx;try{const parsed=inputSchema22.parse(this.rawInput);method=parsed.request.method;params=parsed.request.params;ctx=parsed.ctx}catch(e){throw new InvalidInputError("Invalid tasks/result request",e instanceof z118.ZodError?e.issues:void 0)}if(method!=="tasks/result"){throw new InvalidMethodError(method,"tasks/result")}const authInfo=ctx?.authInfo;if(!authInfo?.sessionId){throw new InternalMcpError("Session ID missing in authorized flow","AUTH_INFO_MISSING")}this.state.set({taskId:params.taskId,sessionId:authInfo.sessionId,authInfo})}async awaitTerminal(){const store=this.scope.taskStore;if(!store)throw new TaskStoreNotInitializedError;const{taskId,sessionId}=this.state.required;const initial=await store.get(taskId,sessionId);if(!initial)throw new TaskNotFoundError(taskId);const finalRecord=isTerminal(initial.status)?initial:await this.waitForTerminal(taskId,sessionId,store);if(!finalRecord)throw new TaskNotFoundError(taskId);this.respondWithOutcome(finalRecord)}async waitForTerminal(taskId,sessionId,store){return new Promise((resolve4,reject)=>{let settled=false;let unsubscribe;let pollTimer;const finalize=async(result,err)=>{if(settled)return;settled=true;if(pollTimer)clearTimeout(pollTimer);if(unsubscribe){try{await unsubscribe()}catch{}}if(err)reject(err);else resolve4(result)};const poll=async()=>{if(settled)return;try{const latest=await store.get(taskId,sessionId);if(!latest)return void finalize(null);if(isTerminal(latest.status))return void finalize(latest)}catch(err){return void finalize(null,err)}pollTimer=setTimeout(()=>void poll(),this.pollDelayMs())};store.subscribeTerminal(taskId,sessionId,record=>{if(isTerminal(record.status)){void finalize(record)}}).then(async unsub=>{unsubscribe=unsub;const latest=await store.get(taskId,sessionId);if(!latest){return void finalize(null)}if(isTerminal(latest.status)){return void finalize(latest)}pollTimer=setTimeout(()=>void poll(),this.pollDelayMs(latest.pollIntervalMs))}).catch(err=>void finalize(null,err))})}pollDelayMs(hint){const min=200;const max=5e3;if(typeof hint==="number"&&hint>0)return Math.max(min,Math.min(hint,max));return 500}respondWithOutcome(record){if(!record.outcome){throw new InternalMcpError("Terminal task has no outcome","TASK_MISSING_OUTCOME")}if(record.outcome.kind==="error"){const{code,message,data}=record.outcome.error;const err=new JsonRpcReplayError(code,message,data,record.taskId);throw err}const payload={...record.outcome.data};const existingMeta=payload["_meta"]??{};payload["_meta"]={...existingMeta,[RELATED_TASK_META_KEY]:{taskId:record.taskId}};this.respond(payload)}};__decorateClass([Stage29("parseInput")],TasksResultFlow.prototype,"parseInput",1);__decorateClass([Stage29("awaitTerminal")],TasksResultFlow.prototype,"awaitTerminal",1);TasksResultFlow=__decorateClass([FrontMcpFlow({name:name29,plan:plan29,inputSchema:inputSchema22,outputSchema:outputSchema21,access:"authorized"})],TasksResultFlow);JsonRpcReplayError=class extends Error{constructor(code,message,data,taskId){super(message);this.code=code;this.data=data;this.taskId=taskId;this.name="JsonRpcReplayError"}code;data;taskId;toJsonRpcError(){const out={code:this.code,message:this.message};if(this.data!==void 0)out.data=this.data;return out}}}});import{internalZ as z119}from"@frontmcp/lazy-zod";import{CancelTaskRequestSchema as CancelTaskRequestSchema2,CancelTaskResultSchema}from"@frontmcp/protocol";var inputSchema23,outputSchema22,stateSchema27,plan30,name30,Stage30,TasksCancelFlow;var init_tasks_cancel_flow=__esm({"libs/sdk/src/task/flows/tasks-cancel.flow.ts"(){"use strict";init_common();init_errors();init_task_types();inputSchema23=z119.object({request:CancelTaskRequestSchema2,ctx:z119.any()});outputSchema22=CancelTaskResultSchema;stateSchema27=z119.object({taskId:z119.string(),sessionId:z119.string(),authInfo:z119.any()});plan30={pre:["parseInput"],execute:["cancelAndRespond"]};name30="tasks:cancel";({Stage:Stage30}=FlowHooksOf(name30));TasksCancelFlow=class extends FlowBase{logger=this.scopeLogger.child("TasksCancelFlow");async parseInput(){let method;let params;let ctx;try{const parsed=inputSchema23.parse(this.rawInput);method=parsed.request.method;params=parsed.request.params;ctx=parsed.ctx}catch(e){throw new InvalidInputError("Invalid tasks/cancel request",e instanceof z119.ZodError?e.issues:void 0)}if(method!=="tasks/cancel"){throw new InvalidMethodError(method,"tasks/cancel")}const authInfo=ctx?.authInfo;if(!authInfo?.sessionId){throw new InternalMcpError("Session ID missing in authorized flow","AUTH_INFO_MISSING")}this.state.set({taskId:params.taskId,sessionId:authInfo.sessionId,authInfo})}async cancelAndRespond(){const store=this.scope.taskStore;const registry=this.scope.tasks;if(!store||!registry)throw new TaskStoreNotInitializedError;const{taskId,sessionId}=this.state.required;const existing=await store.get(taskId,sessionId);if(!existing)throw new TaskNotFoundError(taskId);if(isTerminal(existing.status))throw new TaskAlreadyTerminalError(existing.status);const updated=await store.update(taskId,sessionId,{status:"cancelled",statusMessage:"The task was cancelled by request."});if(!updated)throw new TaskNotFoundError(taskId);if(registry.runner){try{await registry.runner.cancel(updated)}catch(err){this.logger.warn("runner.cancel failed",{taskId,error:err instanceof Error?err.message:String(err)})}}else{registry.abort(taskId,"tasks/cancel")}try{await store.publishCancel(taskId,sessionId)}catch(err){this.logger.warn("publishCancel failed",{taskId,error:err instanceof Error?err.message:String(err)})}try{await store.publishTerminal(updated)}catch(err){this.logger.warn("publishTerminal failed",{taskId,error:err instanceof Error?err.message:String(err)})}this.scope.notifications.sendNotificationToSession(sessionId,"notifications/tasks/status",toWireShape(updated));this.respond(toWireShape(updated))}};__decorateClass([Stage30("parseInput")],TasksCancelFlow.prototype,"parseInput",1);__decorateClass([Stage30("cancelAndRespond")],TasksCancelFlow.prototype,"cancelAndRespond",1);TasksCancelFlow=__decorateClass([FrontMcpFlow({name:name30,plan:plan30,inputSchema:inputSchema23,outputSchema:outputSchema22,access:"authorized"})],TasksCancelFlow)}});import{internalZ as z120}from"@frontmcp/lazy-zod";import{ListTasksRequestSchema as ListTasksRequestSchema2,ListTasksResultSchema}from"@frontmcp/protocol";var inputSchema24,outputSchema23,stateSchema28,plan31,name31,Stage31,TasksListFlow;var init_tasks_list_flow=__esm({"libs/sdk/src/task/flows/tasks-list.flow.ts"(){"use strict";init_common();init_errors();init_task_types();inputSchema24=z120.object({request:ListTasksRequestSchema2,ctx:z120.any()});outputSchema23=ListTasksResultSchema;stateSchema28=z120.object({sessionId:z120.string(),cursor:z120.string().optional(),authInfo:z120.any()});plan31={pre:["parseInput"],execute:["listAndRespond"]};name31="tasks:list";({Stage:Stage31}=FlowHooksOf(name31));TasksListFlow=class extends FlowBase{logger=this.scopeLogger.child("TasksListFlow");async parseInput(){let method;let params;let ctx;try{const parsed=inputSchema24.parse(this.rawInput);method=parsed.request.method;params=parsed.request.params;ctx=parsed.ctx}catch(e){throw new InvalidInputError("Invalid tasks/list request",e instanceof z120.ZodError?e.issues:void 0)}if(method!=="tasks/list"){throw new InvalidMethodError(method,"tasks/list")}const authInfo=ctx?.authInfo;if(!authInfo?.sessionId){throw new InternalMcpError("Session ID missing in authorized flow","AUTH_INFO_MISSING")}this.state.set({sessionId:authInfo.sessionId,cursor:params?.cursor,authInfo})}async listAndRespond(){const store=this.scope.taskStore;if(!store)throw new TaskStoreNotInitializedError;const sessionId=this.state.required.sessionId;const cursor=this.state.cursor;const page2=await store.list(sessionId,{cursor});const tasks=page2.tasks.map(toWireShape);const response={tasks};if(page2.nextCursor)response.nextCursor=page2.nextCursor;this.respond(response)}};__decorateClass([Stage31("parseInput")],TasksListFlow.prototype,"parseInput",1);__decorateClass([Stage31("listAndRespond")],TasksListFlow.prototype,"listAndRespond",1);TasksListFlow=__decorateClass([FrontMcpFlow({name:name31,plan:plan31,inputSchema:inputSchema24,outputSchema:outputSchema23,access:"authorized"})],TasksListFlow)}});var task_scope_runtime_exports={};__export(task_scope_runtime_exports,{InProcessTaskRunner:()=>InProcessTaskRunner,TaskNotifier:()=>TaskNotifier,TaskRegistry:()=>TaskRegistry,TasksCancelFlow:()=>TasksCancelFlow,TasksGetFlow:()=>TasksGetFlow,TasksListFlow:()=>TasksListFlow,TasksResultFlow:()=>TasksResultFlow,createTaskStore:()=>createTaskStore});var init_task_scope_runtime=__esm({"libs/sdk/src/task/task-scope.runtime.ts"(){"use strict";init_task_store_factory();init_task_registry();init_task_notifier();init_in_process_task_runner();init_tasks_get_flow();init_tasks_result_flow();init_tasks_cancel_flow();init_tasks_list_flow()}});import{isAnonymousSubject as isAnonymousSubject9}from"@frontmcp/auth";function sessionScopeIdentity(ctx){const verified=ctx.verifiedSessionId;if(verified)return verified;const authInfo=ctx.authInfo??{};const extraUser=authInfo.extra?.["user"];const principal=[authInfo.user?.sub,extraUser?.sub,authInfo.clientId].find(candidate=>!isAnonymousSubject9(candidate));if(!principal)return void 0;const principalIssuer=authInfo.extra?.["principalIssuer"];if(typeof principalIssuer==="string"){return`issuer-principal:${encodeURIComponent(principalIssuer)}:${principal}`}return`principal:${principal}`}var init_session_scope_identity=__esm({"libs/sdk/src/auth/session-scope-identity.ts"(){"use strict"}});var CREDENTIAL_CACHE;var init_credential_cache=__esm({"libs/sdk/src/auth/vault/credential-cache.ts"(){"use strict";CREDENTIAL_CACHE=Symbol.for("frontmcp:CREDENTIAL_CACHE")}});var auth_providers_providers_exports={};__export(auth_providers_providers_exports,{LAZY_CREDENTIAL_LOADER:()=>LAZY_CREDENTIAL_LOADER,createAuthProvidersProviders:()=>createAuthProvidersProviders,isAuthProvidersEnabled:()=>isAuthProvidersEnabled,registerAuthProvidersVault:()=>registerAuthProvidersVault});import{AUTH_PROVIDERS_ACCESSOR as AUTH_PROVIDERS_ACCESSOR3,AUTH_PROVIDERS_REGISTRY,AUTH_PROVIDERS_VAULT,AuthProvidersAccessorImpl,AuthProvidersRegistry,AuthProvidersVault,CredentialCache,InMemoryAuthorizationVault,isAnonymousSubject as isAnonymousSubject10,LazyCredentialLoader,UNIDENTIFIED_SESSION_PREFIX}from"@frontmcp/auth";import{ProviderScope as ProviderScope8}from"@frontmcp/di";import{createStorage as createStorage7,getEnv as getEnv17,randomUUID as randomUUID25}from"@frontmcp/utils";function createAuthProvidersProviders(options,store,baseVault=new InMemoryAuthorizationVault){const providers=[];providers.push({provide:AUTH_PROVIDERS_REGISTRY,scope:ProviderScope8.GLOBAL,name:"AuthProvidersRegistry",useFactory:()=>new AuthProvidersRegistry(options)});providers.push({provide:AUTH_PROVIDERS_VAULT,scope:ProviderScope8.GLOBAL,name:"AuthProvidersVault",useFactory:logger=>new AuthProvidersVault(store.storage,{namespace:options.namespace,defaultCacheTtl:options.defaultCacheTtl,pepper:store.pepper,logger}),inject:()=>[FrontMcpLogger]});providers.push({provide:CREDENTIAL_CACHE,scope:ProviderScope8.CONTEXT,name:"CredentialCache",useFactory:()=>new CredentialCache(options.maxCredentialsPerSession??100)});providers.push({provide:LAZY_CREDENTIAL_LOADER,scope:ProviderScope8.CONTEXT,name:"LazyCredentialLoader",useFactory:logger=>new LazyCredentialLoader(logger),inject:()=>[FrontMcpLogger]});providers.push({provide:AUTH_PROVIDERS_ACCESSOR3,scope:ProviderScope8.CONTEXT,name:"AuthProvidersAccessor",useFactory:(registry,vault,cache2,loader,ctx,logger)=>{const user=ctx.authInfo?.user;const signedIn=user&&!isAnonymousSubject10(user.sub)?user:void 0;const factoryContext={sessionId:sessionScopeIdentity(ctx)??`${UNIDENTIFIED_SESSION_PREFIX}${randomUUID25()}`,userSub:signedIn?.sub,userEmail:signedIn?.email,userName:signedIn?.name,vault:baseVault};return new AuthProvidersAccessorImpl(registry,vault,cache2,loader,factoryContext,logger)},inject:()=>[AUTH_PROVIDERS_REGISTRY,AUTH_PROVIDERS_VAULT,CREDENTIAL_CACHE,LAZY_CREDENTIAL_LOADER,FRONTMCP_CONTEXT,FrontMcpLogger]});return providers}function isAuthProvidersEnabled(options){if(options?.enabled===false){return false}if(options?.enabled===true){return true}return(options?.providers?.length??0)>0}async function registerAuthProvidersVault(providers,options,tokenStorage,logger){if(!isAuthProvidersEnabled(options))return void 0;if(tokenStorage&&options.useSharedStorage!==false){const pepper=getEnv17("VAULT_SECRET")||getEnv17("JWT_SECRET");if(!pepper){logger.warn("authProvidersVault keeps credentials in auth.tokenStorage, but neither VAULT_SECRET nor JWT_SECRET is set: they are encrypted with a random key of this process, so other instances and a restart do not find them.")}await providers.addDynamicProviders(createAuthProvidersProviders(options,{storage:tokenStorage,pepper}));return void 0}const storage=await createStorage7({type:"memory"});await providers.addDynamicProviders(createAuthProvidersProviders(options,{storage}));return()=>storage.disconnect()}var LAZY_CREDENTIAL_LOADER;var init_auth_providers_providers=__esm({"libs/sdk/src/auth/vault/auth-providers.providers.ts"(){"use strict";init_common();init_frontmcp_context_provider();init_session_scope_identity();init_credential_cache();LAZY_CREDENTIAL_LOADER=Symbol.for("frontmcp:LAZY_CREDENTIAL_LOADER")}});function hasRegisteredTracerProvider({trace,ProxyTracerProvider}){const provider=trace.getTracerProvider();return!(provider instanceof ProxyTracerProvider)||provider.getDelegateTracer("frontmcp")!==void 0}function registerExportingTracerProvider(api,sdk,exporter){api.trace.setGlobalTracerProvider(new sdk.BasicTracerProvider({spanProcessors:[new sdk.SimpleSpanProcessor(exporter)]}))}var init_tracer_provider_utils=__esm({"libs/sdk/src/scope/tracer-provider.utils.ts"(){"use strict"}});var observability_scope_helper_exports={};__export(observability_scope_helper_exports,{observabilityPlugins:()=>observabilityPlugins});import{getRuntimeContext as getRuntimeContext22}from"@frontmcp/utils";function defaultLogSinks(){return[{type:getRuntimeContext22().runtime==="browser"?"console":"stdout"}]}function observabilityPlugins({config:observabilityConfig,logger,globalProviders,implied=false}){const plugins=[];let ObservabilityPluginModule;try{ObservabilityPluginModule=requireOptionalModule("@frontmcp/observability",()=>__require("@frontmcp/observability"))}catch(err){const probe2=probeOptionalDependency("@frontmcp/observability",err,__require.resolve);if(probe2.status==="not-installed"&&implied){logger.info("frontmcp dev writes call timings, failures and stalls to its events file with @frontmcp/observability; install it to get them: npm install @frontmcp/observability")}else if(probe2.status==="not-installed"){logger.warn("observability config is set but @frontmcp/observability is not installed. Install it with: npm install @frontmcp/observability")}else{logger.warn("observability config is set and @frontmcp/observability resolved but failed to load \u2014 telemetry is disabled. Reinstalling will not help: this is usually an export-condition or transpile mismatch (e.g. a dev runtime resolving the package source instead of its built entry) or a failing transitive peer dependency. Inspect the resolved path and error below.",{resolvedPath:probe2.resolvedPath,error:probe2.error})}}if(ObservabilityPluginModule)try{const{ObservabilityPlugin}=ObservabilityPluginModule;const pluginOptions=observabilityConfig===true?{}:observabilityConfig;plugins.push(ObservabilityPlugin.init(pluginOptions));logger.verbose("observability: auto-loaded ObservabilityPlugin from config");const loggingEnabled=pluginOptions.logging!==false;if(loggingEnabled){try{const{StructuredLogTransport,createSinks}=ObservabilityPluginModule;let loggerRegistry;try{loggerRegistry=globalProviders.get(LoggerRegistry)}catch{}if(loggerRegistry&&typeof loggerRegistry.addTransport==="function"&&!loggerRegistry._hasStructuredTransport){const rawLogging=pluginOptions.logging;const loggingOpts=rawLogging===true?{}:typeof rawLogging==="object"?rawLogging:{};const sinkConfigs=loggingOpts["sinks"]??(rawLogging===void 0?[]:defaultLogSinks());const sinks=createSinks(sinkConfigs);let contextStorage;try{contextStorage=globalProviders.get(FrontMcpContextStorage)}catch{}const contextAccessor=contextStorage?()=>{const ctx=contextStorage.getStore();if(!ctx)return void 0;return{requestId:ctx.requestId,traceContext:ctx.traceContext,sessionIdHash:__require("@frontmcp/utils").sha256Hex(ctx.sessionId).slice(0,12),scopeId:ctx.scopeId,flowName:ctx.flow?.name,elapsed:ctx.elapsed()}}:void 0;const transport=new StructuredLogTransport(sinks,{redactFields:loggingOpts["redactFields"],includeStacks:loggingOpts["includeStacks"],staticFields:loggingOpts["staticFields"]},contextAccessor);transport.onEntry=entry=>{const requestLog=contextStorage?.getStore()?.get(Symbol.for("frontmcp:observability:request-log-collector"));requestLog?.addEntry?.(entry)};loggerRegistry.addTransport(transport);loggerRegistry._hasStructuredTransport=true;logger.verbose("observability: wired StructuredLogTransport into SDK logger")}}catch(e){logger.warn("observability: failed to wire structured logging",{error:e instanceof Error?e.message:"Unknown error"})}}if(pluginOptions.tracing!==false){try{if(!hasRegisteredTracerProvider(__require("@opentelemetry/api"))){const{isDevelopment:checkDev}=__require("@frontmcp/utils");if(checkDev()){const sdkTraceBase=__require("@opentelemetry/sdk-trace-base");const{PrettySpanExporter}=ObservabilityPluginModule;const exporter=PrettySpanExporter?new PrettySpanExporter:new sdkTraceBase.ConsoleSpanExporter;registerExportingTracerProvider(__require("@opentelemetry/api"),sdkTraceBase,exporter);logger.info("observability: auto-configured tracing (development mode)")}else{logger.warn("observability: tracing enabled but no TracerProvider configured. Set OTEL_EXPORTER_OTLP_ENDPOINT or call setupOTel() before server start.")}}}catch(e){logger.warn("observability: could not set up development tracing; spans are not recorded",{error:e instanceof Error?e.message:"Unknown error"})}}}catch(e){if(e?.code==="OBSERVABILITY_CONFIGURATION")throw e;logger.warn("observability: plugin initialization failed",{error:e instanceof Error?e.message:"Unknown error"})}return plugins}var init_observability_scope_helper=__esm({"libs/sdk/src/scope/observability-scope.helper.ts"(){"use strict";init_context();init_logger_registry();init_optional_dependency_util();init_tracer_provider_utils()}});import{internalZ as z121}from"@frontmcp/lazy-zod";import{randomUUID as randomUUID26}from"@frontmcp/utils";var inputSchema25,outputSchema24,stateSchema29,plan32,name32,Stage32,ElicitationRequestFlow;var init_elicitation_request_flow=__esm({"libs/sdk/src/elicitation/flows/elicitation-request.flow.ts"(){"use strict";init_common();init_errors();init_session_id_hash();init_elicitation_types();inputSchema25=z121.object({relatedRequestId:z121.union([z121.string(),z121.number()]),sessionId:z121.string(),message:z121.string(),requestedSchema:z121.record(z121.string(),z121.unknown()),options:z121.object({mode:z121.enum(["form","url"]).optional(),ttl:z121.number().optional(),elicitationId:z121.string().optional(),url:z121.string().optional()}).optional()});outputSchema24=z121.object({elicitId:z121.string(),sessionId:z121.string(),expiresAt:z121.number(),mode:z121.enum(["form","url"]),requestParams:z121.record(z121.string(),z121.unknown()),pendingRecord:z121.any()});stateSchema29=z121.object({relatedRequestId:z121.union([z121.string(),z121.number()]),sessionId:z121.string(),message:z121.string(),requestedSchema:z121.record(z121.string(),z121.unknown()),mode:z121.enum(["form","url"]).default("form"),ttl:z121.number().default(DEFAULT_ELICIT_TTL),elicitationId:z121.string().optional(),url:z121.string().optional(),elicitId:z121.string(),expiresAt:z121.number(),pendingRecord:z121.any().optional(),requestParams:z121.record(z121.string(),z121.unknown()).optional(),output:outputSchema24.optional()});plan32={pre:["parseInput","validateRequest"],execute:["generateElicitId","storePendingRecord","buildRequestParams"],finalize:["finalize"]};name32="elicitation:request";({Stage:Stage32}=FlowHooksOf(name32));ElicitationRequestFlow=class extends FlowBase{logger=this.scopeLogger.child("ElicitationRequestFlow");async parseInput(){this.logger.verbose("parseInput:start");const input=inputSchema25.parse(this.rawInput);const{mode="form",ttl=DEFAULT_ELICIT_TTL,elicitationId,url}=input.options??{};this.state.set({relatedRequestId:input.relatedRequestId,sessionId:input.sessionId,message:input.message,requestedSchema:input.requestedSchema,mode,ttl,elicitationId,url});this.logger.verbose("parseInput:done",{sessionIdHash:sessionIdHash(input.sessionId),mode})}async validateRequest(){this.logger.verbose("validateRequest:start");const{mode,url}=this.state;if(mode==="url"&&!url){throw new InvalidInputError('url is required when mode is "url"')}this.logger.verbose("validateRequest:done")}async generateElicitId(){this.logger.verbose("generateElicitId:start");const{elicitationId,ttl}=this.state;const elicitId=elicitationId||`elicit-${randomUUID26()}`;const expiresAt=Date.now()+(ttl??DEFAULT_ELICIT_TTL);this.state.set({elicitId,expiresAt});this.logger.verbose("generateElicitId:done",{elicitId})}async storePendingRecord(){this.logger.verbose("storePendingRecord:start");const{elicitId,sessionId,message,mode,expiresAt,requestedSchema}=this.state.required;const store=this.scope.elicitationStore;if(!store){throw new ElicitationStoreNotInitializedError}const pendingRecord={elicitId,sessionId,createdAt:Date.now(),expiresAt,message,mode,requestedSchema};await store.setPending(pendingRecord);this.state.set("pendingRecord",pendingRecord);this.logger.verbose("storePendingRecord:done",{elicitId,sessionIdHash:sessionIdHash(sessionId)})}async buildRequestParams(){this.logger.verbose("buildRequestParams:start");const{mode,message,requestedSchema,elicitId}=this.state.required;const requestParams={mode,message,requestedSchema};if(mode==="url"){requestParams["elicitationId"]=elicitId;requestParams["url"]=this.state.url}this.state.set("requestParams",requestParams);this.logger.verbose("buildRequestParams:done")}async finalize(){this.logger.verbose("finalize:start");const{elicitId,sessionId,expiresAt,mode}=this.state.required;const{requestParams,pendingRecord}=this.state;if(!requestParams||!pendingRecord){throw new InvalidInputError("finalize: missing requestParams or pendingRecord from prior stages")}this.respond({elicitId,sessionId,expiresAt,mode,requestParams,pendingRecord});this.logger.verbose("finalize:done")}};__decorateClass([Stage32("parseInput")],ElicitationRequestFlow.prototype,"parseInput",1);__decorateClass([Stage32("validateRequest")],ElicitationRequestFlow.prototype,"validateRequest",1);__decorateClass([Stage32("generateElicitId")],ElicitationRequestFlow.prototype,"generateElicitId",1);__decorateClass([Stage32("storePendingRecord")],ElicitationRequestFlow.prototype,"storePendingRecord",1);__decorateClass([Stage32("buildRequestParams")],ElicitationRequestFlow.prototype,"buildRequestParams",1);__decorateClass([Stage32("finalize")],ElicitationRequestFlow.prototype,"finalize",1);ElicitationRequestFlow=__decorateClass([FrontMcpFlow({name:name32,plan:plan32,inputSchema:inputSchema25,outputSchema:outputSchema24,access:"authorized"})],ElicitationRequestFlow)}});import{internalZ as z122}from"@frontmcp/lazy-zod";var inputSchema26,outputSchema25,stateSchema30,plan33,name33,Stage33,ElicitationResultFlow;var init_elicitation_result_flow=__esm({"libs/sdk/src/elicitation/flows/elicitation-result.flow.ts"(){"use strict";init_common();init_errors();init_session_id_hash();init_helpers();inputSchema26=z122.object({sessionId:z122.string(),result:z122.object({action:z122.enum(["accept","cancel","decline"]),content:z122.unknown().optional()})});outputSchema25=z122.object({handled:z122.boolean(),elicitId:z122.string().optional(),result:z122.any().optional()});stateSchema30=z122.object({sessionId:z122.string(),action:z122.enum(["accept","cancel","decline"]),content:z122.unknown().optional(),pendingRecord:z122.any().optional(),elicitResult:z122.any().optional(),handled:z122.boolean().default(false),output:outputSchema25.optional()});plan33={pre:["parseInput"],execute:["lookupPending","validateContent","buildResult","publishResult"],finalize:["finalize"]};name33="elicitation:result";({Stage:Stage33}=FlowHooksOf(name33));ElicitationResultFlow=class extends FlowBase{logger=this.scopeLogger.child("ElicitationResultFlow");async parseInput(){this.logger.verbose("parseInput:start");const input=inputSchema26.parse(this.rawInput);this.state.set({sessionId:input.sessionId,action:input.result.action,content:input.result.content});this.logger.verbose("parseInput:done",{sessionIdHash:sessionIdHash(input.sessionId),action:input.result.action})}async lookupPending(){this.logger.verbose("lookupPending:start");const{sessionId}=this.state.required;const store=this.scope.elicitationStore;if(!store){throw new ElicitationStoreNotInitializedError}const pendingRecord=await store.getPending(sessionId);this.state.set("pendingRecord",pendingRecord??void 0);if(!pendingRecord){this.logger.verbose("lookupPending:notFound",{sessionIdHash:sessionIdHash(sessionId)})}else{this.logger.verbose("lookupPending:found",{sessionIdHash:sessionIdHash(sessionId),elicitId:pendingRecord.elicitId})}}async validateContent(){this.logger.verbose("validateContent:start");const{action,content,pendingRecord}=this.state;if(action!=="accept"){this.logger.verbose("validateContent:skip (non-accept action)",{action});return}if(!pendingRecord){this.logger.verbose("validateContent:skip (no pending record)");return}if(pendingRecord.mode==="url"){this.logger.verbose("validateContent:skip (url mode)");return}if(!pendingRecord.requestedSchema){this.logger.verbose("validateContent:skip (no schema stored)");return}const validationResult=validateElicitationContent(content,pendingRecord.requestedSchema);if(!validationResult.success){this.logger.warn("validateContent:failed",{sessionIdHash:sessionIdHash(pendingRecord.sessionId),elicitId:pendingRecord.elicitId,errors:validationResult.errors});throw new InvalidInputError("Invalid elicitation result content",validationResult.errors)}this.logger.verbose("validateContent:done")}async buildResult(){this.logger.verbose("buildResult:start");const{action}=this.state.required;const{content,pendingRecord}=this.state;const keepsContent=action==="accept"&&content!==void 0&&pendingRecord?.mode!=="url";const elicitResult={status:action,...keepsContent&&{content}};this.state.set("elicitResult",elicitResult);this.logger.verbose("buildResult:done",{status:elicitResult.status})}async publishResult(){this.logger.verbose("publishResult:start");const{pendingRecord,elicitResult}=this.state;const{sessionId}=this.state.required;const store=this.scope.elicitationStore;if(!pendingRecord||!elicitResult||!store){this.state.set("handled",false);this.logger.verbose("publishResult:skip (no pending or no result)");return}try{await store.publishResult(pendingRecord.elicitId,sessionId,elicitResult);this.state.set("handled",true);this.logger.verbose("publishResult:done",{elicitId:pendingRecord.elicitId,sessionId:sessionId.slice(0,20)})}catch(error){this.logger.warn("publishResult:failed",{elicitId:pendingRecord.elicitId,error:error.message});this.state.set("handled",false)}}async finalize(){this.logger.verbose("finalize:start");const{handled,pendingRecord,elicitResult}=this.state;const output={handled:handled??false,elicitId:pendingRecord?.elicitId,result:elicitResult};this.state.set("output",output);this.respond(output);this.logger.verbose("finalize:done",{handled})}};__decorateClass([Stage33("parseInput")],ElicitationResultFlow.prototype,"parseInput",1);__decorateClass([Stage33("lookupPending")],ElicitationResultFlow.prototype,"lookupPending",1);__decorateClass([Stage33("validateContent")],ElicitationResultFlow.prototype,"validateContent",1);__decorateClass([Stage33("buildResult")],ElicitationResultFlow.prototype,"buildResult",1);__decorateClass([Stage33("publishResult")],ElicitationResultFlow.prototype,"publishResult",1);__decorateClass([Stage33("finalize")],ElicitationResultFlow.prototype,"finalize",1);ElicitationResultFlow=__decorateClass([FrontMcpFlow({name:name33,plan:plan33,inputSchema:inputSchema26,outputSchema:outputSchema25,access:"authorized"})],ElicitationResultFlow)}});var flows_exports2={};__export(flows_exports2,{ElicitRequestFlow:()=>ElicitationRequestFlow,ElicitResultFlow:()=>ElicitationResultFlow,ElicitationRequestFlow:()=>ElicitationRequestFlow,ElicitationResultFlow:()=>ElicitationResultFlow});var init_flows2=__esm({"libs/sdk/src/elicitation/flows/index.ts"(){"use strict";init_elicitation_request_flow();init_elicitation_result_flow()}});import{getEnv as getEnv18}from"@frontmcp/utils";function resolveRegistryAuthRecord(scope){const registry=scope.metadata.registry;if(!registry)return void 0;if(registry.publicKey)return toRegistryAuthRecord(registry.publicKey);const envName=registry.publicKeyEnv??DEFAULT_REGISTRY_PUBLIC_KEY_ENV;const configuredKey=getEnv18(envName)?.trim();if(!configuredKey)return void 0;const record=toRegistryAuthRecord(configuredKey);if(!record&&!envVarsReportedInvalid.has(envName)){envVarsReportedInvalid.add(envName);scope.logger.warn(`MCP Registry domain proof not served: ${envName} is neither a base64 Ed25519 public key nor a "v=MCPv1; k=...; p=..." record`)}return record}function mcpEndpointPath(scope){return`${normalizeEntryPrefix(scope.entryPath)}${normalizeScopeBase(scope.routeBase)}`}function serverCardPath(scope){return`${mcpEndpointPath(scope)}/server-card`}var SERVER_CARD_MEDIA_TYPE,envVarsReportedInvalid;var init_mcp_registry_utils=__esm({"libs/sdk/src/mcp-registry/mcp-registry.utils.ts"(){"use strict";init_common();init_registry();SERVER_CARD_MEDIA_TYPE="application/mcp-server-card+json";envVarsReportedInvalid=new Set}});var MCP_REGISTRY_AUTH_PATH,inputSchema27,outputSchema26,plan34,name34,Stage34,WellKnownMcpRegistryAuthFlow;var init_well_known_mcp_registry_auth_flow=__esm({"libs/sdk/src/mcp-registry/flows/well-known.mcp-registry-auth.flow.ts"(){"use strict";init_common();init_mcp_registry_utils();MCP_REGISTRY_AUTH_PATH="/.well-known/mcp-registry-auth";inputSchema27=httpInputSchema;outputSchema26=HttpTextSchema;plan34={pre:["checkIpFilter","acquireQuota"],execute:["serveRecord"]};name34="well-known.mcp-registry-auth";Stage34=StageHookOf(name34);WellKnownMcpRegistryAuthFlow=class extends FlowBase{static canActivate(request2,scope){return request2.path===MCP_REGISTRY_AUTH_PATH&&resolveRegistryAuthRecord(scope)!==void 0}async checkIpFilter(){enforceIpFilter(this.scope,this.tryGetContext()?.metadata.clientIp)}async acquireQuota(){await enforceGlobalRateLimit(this.scope,this.tryGetContext())}async serveRecord(){const record=resolveRegistryAuthRecord(this.scope);this.respond(record?{kind:"text",status:200,body:record,contentType:"text/plain; charset=utf-8"}:httpRespond.notFound())}};__decorateClass([Stage34("checkIpFilter")],WellKnownMcpRegistryAuthFlow.prototype,"checkIpFilter",1);__decorateClass([Stage34("acquireQuota")],WellKnownMcpRegistryAuthFlow.prototype,"acquireQuota",1);__decorateClass([Stage34("serveRecord")],WellKnownMcpRegistryAuthFlow.prototype,"serveRecord",1);WellKnownMcpRegistryAuthFlow=__decorateClass([FrontMcpFlow({name:name34,plan:plan34,inputSchema:inputSchema27,outputSchema:outputSchema26,access:"public",middleware:{method:"GET"}})],WellKnownMcpRegistryAuthFlow)}});import{internalZ as z123}from"@frontmcp/lazy-zod";import{sha256Base64url}from"@frontmcp/utils";function ifNoneMatchIncludes(ifNoneMatch,etag){const candidates=(ifNoneMatch??"").split(",").map(candidate=>candidate.trim().replace(/^W\//,""));return candidates.includes("*")||candidates.includes(etag)}var SERVER_CARD_SCHEMA_URL,MAX_TITLE_LENGTH,MAX_ICON_SRC_LENGTH,SERVER_CARD_CORS_HEADERS,isHttpsUrl,inputSchema28,stateSchema31,outputSchema27,plan35,name35,Stage35,ServerCardFlow;var init_server_card_flow=__esm({"libs/sdk/src/mcp-registry/flows/server-card.flow.ts"(){"use strict";init_common();init_protocol_20260728_constants();init_mcp_registry_utils();SERVER_CARD_SCHEMA_URL="https://static.modelcontextprotocol.io/schemas/v1/server-card.schema.json";MAX_TITLE_LENGTH=100;MAX_ICON_SRC_LENGTH=255;SERVER_CARD_CORS_HEADERS={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET","Access-Control-Allow-Headers":"Content-Type, If-None-Match","Access-Control-Expose-Headers":"ETag"};isHttpsUrl=url=>url.startsWith("https://");inputSchema28=httpInputSchema;stateSchema31=z123.object({card:z123.record(z123.string(),z123.unknown())});outputSchema27=z123.union([HttpJsonSchema,HttpEmptySchema,HttpTextSchema]);plan35={pre:["checkIpFilter","acquireQuota","answerPreflight"],execute:["buildCard","respondWithCard"]};name35="registry:server-card";Stage35=StageHookOf(name35);ServerCardFlow=class extends FlowBase{static canActivate(request2,scope){return(request2.method==="GET"||request2.method==="OPTIONS")&&request2.path===serverCardPath(scope)}async checkIpFilter(){enforceIpFilter(this.scope,this.tryGetContext()?.metadata.clientIp)}async acquireQuota(){await enforceGlobalRateLimit(this.scope,this.tryGetContext())}async answerPreflight(){if(this.rawInput.request.method==="OPTIONS"){this.respond({kind:"empty",status:204,headers:SERVER_CARD_CORS_HEADERS})}}async buildCard(){const{info,registry}=this.scope.metadata;if(!registry?.name){this.respond(httpRespond.notFound());return}const icons=(info.icons??[]).filter(icon=>isHttpsUrl(icon.src)&&icon.src.length<=MAX_ICON_SRC_LENGTH);const endpointUrl=getRequestBaseUrl(this.rawInput.request,mcpEndpointPath(this.scope)||"/");this.state.set({card:{$schema:SERVER_CARD_SCHEMA_URL,name:registry.name,version:info.version,description:registry.description,...info.title&&info.title.length<=MAX_TITLE_LENGTH?{title:info.title}:{},...info.websiteUrl&&isHttpsUrl(info.websiteUrl)?{websiteUrl:info.websiteUrl}:{},...icons.length>0?{icons}:{},...registry.repository?{repository:registry.repository}:{},remotes:[{type:"streamable-http",url:endpointUrl,supportedProtocolVersions:[...FRONTMCP_SUPPORTED_PROTOCOL_VERSIONS]}]}})}async respondWithCard(){const{card}=this.state.required;const etag=`"${sha256Base64url(JSON.stringify(card))}"`;const cacheControl=isPublicUrlPinned()?"public, max-age=3600":"no-store";const headers={...SERVER_CARD_CORS_HEADERS,"Cache-Control":cacheControl,ETag:etag};this.respond(ifNoneMatchIncludes(this.rawInput.request.headers["if-none-match"],etag)?{kind:"empty",status:304,headers}:{kind:"json",status:200,body:card,contentType:SERVER_CARD_MEDIA_TYPE,headers})}};__decorateClass([Stage35("checkIpFilter")],ServerCardFlow.prototype,"checkIpFilter",1);__decorateClass([Stage35("acquireQuota")],ServerCardFlow.prototype,"acquireQuota",1);__decorateClass([Stage35("answerPreflight")],ServerCardFlow.prototype,"answerPreflight",1);__decorateClass([Stage35("buildCard")],ServerCardFlow.prototype,"buildCard",1);__decorateClass([Stage35("respondWithCard")],ServerCardFlow.prototype,"respondWithCard",1);ServerCardFlow=__decorateClass([FrontMcpFlow({name:name35,plan:plan35,inputSchema:inputSchema28,outputSchema:outputSchema27,access:"public",middleware:{}})],ServerCardFlow)}});import{internalZ as z124}from"@frontmcp/lazy-zod";function aiCatalogIdentifier(registryName){const[namespace,serverName]=registryName.split("/");return`urn:air:${namespace.split(".").reverse().join(".")}:mcp:${serverName}`}var AI_CATALOG_PATH,inputSchema29,outputSchema28,plan36,name36,Stage36,WellKnownAiCatalogFlow;var init_well_known_ai_catalog_flow=__esm({"libs/sdk/src/mcp-registry/flows/well-known.ai-catalog.flow.ts"(){"use strict";init_common();init_mcp_registry_utils();AI_CATALOG_PATH="/.well-known/ai-catalog.json";inputSchema29=httpInputSchema;outputSchema28=z124.union([HttpJsonSchema,HttpTextSchema]);plan36={pre:["checkIpFilter","acquireQuota"],execute:["serveCatalog"]};name36="well-known.ai-catalog";Stage36=StageHookOf(name36);WellKnownAiCatalogFlow=class extends FlowBase{static canActivate(request2){return request2.path===AI_CATALOG_PATH}async checkIpFilter(){enforceIpFilter(this.scope,this.tryGetContext()?.metadata.clientIp)}async acquireQuota(){await enforceGlobalRateLimit(this.scope,this.tryGetContext())}async serveCatalog(){const registryName=this.scope.metadata.registry?.name;if(!registryName){this.respond(httpRespond.notFound());return}this.respond({kind:"json",status:200,contentType:"application/ai-catalog+json",body:{specVersion:"1.0",entries:[{identifier:aiCatalogIdentifier(registryName),type:SERVER_CARD_MEDIA_TYPE,url:getRequestBaseUrl(this.rawInput.request,serverCardPath(this.scope))}]}})}};__decorateClass([Stage36("checkIpFilter")],WellKnownAiCatalogFlow.prototype,"checkIpFilter",1);__decorateClass([Stage36("acquireQuota")],WellKnownAiCatalogFlow.prototype,"acquireQuota",1);__decorateClass([Stage36("serveCatalog")],WellKnownAiCatalogFlow.prototype,"serveCatalog",1);WellKnownAiCatalogFlow=__decorateClass([FrontMcpFlow({name:name36,plan:plan36,inputSchema:inputSchema29,outputSchema:outputSchema28,access:"public",middleware:{method:"GET"}})],WellKnownAiCatalogFlow)}});var init_flows3=__esm({"libs/sdk/src/mcp-registry/flows/index.ts"(){"use strict";init_well_known_mcp_registry_auth_flow();init_server_card_flow();init_well_known_ai_catalog_flow()}});var mcp_registry_scope_helper_exports={};__export(mcp_registry_scope_helper_exports,{registerMcpRegistryFlows:()=>registerMcpRegistryFlows});async function registerMcpRegistryFlows(options){const{flowRegistry,registryOptions,servesServerEndpoint}=options;if(!registryOptions)return;const flows=[WellKnownMcpRegistryAuthFlow];if(servesServerEndpoint&&registryOptions.name&&registryOptions.serverCard!==false){flows.push(ServerCardFlow);if(registryOptions.aiCatalog!==false)flows.push(WellKnownAiCatalogFlow)}await flowRegistry.registryFlows(flows)}var init_mcp_registry_scope_helper=__esm({"libs/sdk/src/mcp-registry/mcp-registry-scope.helper.ts"(){"use strict";init_flows3()}});async function serveRelayedHttpRequest(scope,request2,response){let output;try{output=await scope.runFlow("http:request",{request:request2,response})}catch(error){output=flowErrorToHttpOutput(error)}if(output&&!response.writableEnded){await writeHttpResponse(response,output)}if(response.writableEnded)return;if(!response.headersSent){await writeHttpResponse(response,{kind:"json",status:404,contentType:"application/json; charset=utf-8",body:{error:"Not Found"}});return}response.end()}var init_relay_flow=__esm({"libs/sdk/src/transport/relay/relay-flow.ts"(){"use strict";init_server_validation();init_flow_error_output()}});import{randomUUID as randomUUID27}from"@frontmcp/utils";function errorMessage(error){return error instanceof Error?error.message:String(error)}function isServableRequest(message){return typeof message.requestId==="string"&&typeof message.sourceNodeId==="string"&&typeof message.sessionId==="string"&&typeof message.request==="object"&&message.request!==null}function keepaliveIntervalOf(message){const requested=message.keepaliveMs;if(typeof requested!=="number"||!Number.isFinite(requested))return DEFAULT_OWNER_CHECK_INTERVAL_MS;return Math.max(MIN_KEEPALIVE_MS,requested)}var DEFAULT_ACK_TIMEOUT_MS,DEFAULT_OWNER_CHECK_INTERVAL_MS,DEFAULT_RETRY_AFTER_SECONDS2,MIN_KEEPALIVE_MS,SILENT_CHECKS_BEFORE_FAILURE,SessionRelay;var init_session_relay=__esm({"libs/sdk/src/transport/relay/session-relay.ts"(){"use strict";init_transport_errors();init_transport_error();init_relay_http();DEFAULT_ACK_TIMEOUT_MS=5e3;DEFAULT_OWNER_CHECK_INTERVAL_MS=1e4;DEFAULT_RETRY_AFTER_SECONDS2=30;MIN_KEEPALIVE_MS=100;SILENT_CHECKS_BEFORE_FAILURE=3;SessionRelay=class{constructor(options){this.options=options;this.nodeId=options.nodeId;this.ackTimeoutMs=options.ackTimeoutMs??DEFAULT_ACK_TIMEOUT_MS;this.ownerCheckIntervalMs=options.ownerCheckIntervalMs??DEFAULT_OWNER_CHECK_INTERVAL_MS;this.retryAfterSeconds=options.retryAfterSeconds??DEFAULT_RETRY_AFTER_SECONDS2;this.logger=options.logger}options;nodeId;ackTimeoutMs;ownerCheckIntervalMs;retryAfterSeconds;logger;pending=new Map;serving=new Map;closed=false;get pendingCount(){return this.pending.size}get servingCount(){return this.serving.size}unreachable(ownerNodeId,reason){return new SessionOwnerUnreachableError(ownerNodeId,this.retryAfterSeconds,reason)}forward(ownerNodeId,sessionId,request2,response){if(this.closed)return Promise.reject(this.unreachable(ownerNodeId,"this node is shutting down"));const requestId=randomUUID27();const sessionLabel=sessionId.slice(0,20);return new Promise((resolve4,reject)=>{let acked=false;let headWritten=false;let done=false;let lastFrameAt=Date.now();let ownerTimer;const cleanup=()=>{clearTimeout(ackTimer);if(ownerTimer)clearInterval(ownerTimer);response.removeListener("close",onClientClose);this.pending.delete(requestId)};const finish=()=>{if(done)return;done=true;cleanup();resolve4()};const fail=reason=>{if(done)return;done=true;cleanup();this.logger?.warn(`[HA] Relay to session owner failed: ${reason}`,{sessionId:sessionLabel,ownerNodeId});if(!headWritten&&!response.headersSent){reject(this.unreachable(ownerNodeId,reason));return}if(!response.writableEnded)response.end();resolve4()};const onClientClose=()=>{if(done||response.writableFinished)return;done=true;cleanup();this.options.publish(ownerNodeId,{kind:"relay-cancel",requestId,sourceNodeId:this.nodeId}).catch(()=>void 0);resolve4()};const checkOwner=async()=>{if(Date.now()-lastFrameAt>=this.ownerCheckIntervalMs*SILENT_CHECKS_BEFORE_FAILURE){fail("the owner stopped sending the response");return}try{if(!await this.options.isNodeAlive(ownerNodeId))fail("the owner stopped while serving the request")}catch{}};const markAcked=()=>{if(acked)return;acked=true;clearTimeout(ackTimer);ownerTimer=setInterval(()=>void checkOwner(),this.ownerCheckIntervalMs);ownerTimer.unref?.()};const onFrame=frame4=>{if(done)return;lastFrameAt=Date.now();switch(frame4.event){case"ack":markAcked();return;case"keepalive":return;case"head":markAcked();if(!response.headersSent){response.writeHead(frame4.status,frame4.headers);response.flushHeaders?.()}headWritten=true;return;case"data":response.write(decodeRelayChunk(frame4));return;case"end":if(!response.writableEnded)response.end();finish();return;case"error":fail(`the owner could not serve the request: ${frame4.message}`);return}};const ackTimer=setTimeout(()=>fail(`the owner did not acknowledge the request within ${this.ackTimeoutMs}ms`),this.ackTimeoutMs);ackTimer.unref?.();this.pending.set(requestId,{ownerNodeId,onFrame,fail});response.once("close",onClientClose);const message={kind:"relay-request",requestId,sourceNodeId:this.nodeId,sessionId,request:request2,timestamp:Date.now(),keepaliveMs:this.ownerCheckIntervalMs};this.logger?.verbose?.("[HA] Relaying request to session owner",{sessionId:sessionLabel,ownerNodeId});this.options.publish(ownerNodeId,message).then(receivers=>{if(receivers===0)fail("the owner does not listen on its relay channel")},error=>fail(`publishing the request failed: ${errorMessage(error)}`))})}handleMessage(message){switch(message.kind){case"relay-request":if(!isServableRequest(message)){this.logger?.warn("[HA] Dropped a malformed relayed request");return}this.serveRelayed(message).catch(error=>{this.logger?.warn("[HA] Serving a relayed request failed",{error:errorMessage(error)})});return;case"relay-response":{const pending=this.pending.get(message.requestId);if(pending&&pending.ownerNodeId===message.sourceNodeId)pending.onFrame(message);return}case"relay-cancel":{const serving=this.serving.get(message.requestId);if(serving&&serving.sourceNodeId===message.sourceNodeId)serving.response.destroy();return}default:return}}async close(){if(this.closed)return;this.closed=true;for(const pending of[...this.pending.values()])pending.fail("this node is shutting down");for(const serving of[...this.serving.values()]){if(!serving.response.writableEnded){serving.send({event:"error",message:"the owner is shutting down"});serving.response.destroy()}}this.serving.clear()}async serveRelayed(message){const{requestId,sourceNodeId}=message;let undeliverable=false;const publishFrame=event=>{const frame4={kind:"relay-response",requestId,sourceNodeId:this.nodeId,...event};return this.options.publish(sourceNodeId,frame4)};const abandon=reason=>{if(undeliverable)return;undeliverable=true;this.logger?.warn("[HA] Failed to publish a relayed response frame",{reason,targetNodeId:sourceNodeId});publishFrame({event:"error",message:reason}).catch(()=>void 0);response.destroy()};const send=event=>{if(undeliverable)return;publishFrame(event).then(receivers=>{if(receivers===0)abandon("the relaying node no longer listens")},error=>abandon(`publishing a response frame failed: ${errorMessage(error)}`))};const response=new RelayServerResponse({head:(status,headers)=>send({event:"head",status,headers}),data:chunk=>send({event:"data",...chunk}),end:()=>send({event:"end"})});if(this.closed){send({event:"error",message:"the owner is shutting down"});return}send({event:"ack"});const keepaliveTimer=setInterval(()=>send({event:"keepalive"}),keepaliveIntervalOf(message));keepaliveTimer.unref?.();this.serving.set(requestId,{sourceNodeId,response,send});try{const request2=createRelayedServerRequest(message.request,sourceNodeId);await this.options.serve(request2,response.asServerResponse())}catch(error){this.logger?.warn("[HA] Serving a relayed request failed",{sessionId:message.sessionId.slice(0,20),sourceNodeId,error:errorMessage(error)});if(!response.writableEnded&&!response.destroyed&&!response.headersSent){response.status(500).json(rpcError("Internal error"))}}finally{clearInterval(keepaliveTimer);if(!response.writableEnded&&!response.destroyed)response.end();this.serving.delete(requestId)}}}}});var relay_scope_helper_exports={};__export(relay_scope_helper_exports,{wireSessionRelay:()=>wireSessionRelay});function wireSessionRelay(options){const{haManager,bus,transportService,notifications,logger,nodeId}=options;if(!haManager.getRelay())return void 0;const config=haManager.getConfig();const relay=new SessionRelay({nodeId,publish:(target,message)=>haManager.publishToNode(target,message),isNodeAlive:target=>haManager.isNodeAlive(target),serve:(request2,response)=>serveRelayedHttpRequest(options.flows,request2,response),ackTimeoutMs:options.ackTimeoutMs,ownerCheckIntervalMs:config.heartbeatIntervalMs,retryAfterSeconds:Math.ceil(config.heartbeatTtlMs/1e3),logger});const handler=message=>{if(isRequestRelayMessage(message)){relay.handleMessage(message);return}if(message.kind==="destroy-session"){transportService.destroyLocalSession(message.sessionId,message.reason).catch(error=>{logger.warn("[HA] Failed to destroy a session on request of another node",{sessionId:message.sessionId.slice(0,20),error:error instanceof Error?error.message:String(error)})});return}if(message.kind===void 0||message.kind==="notification"){notifications.deliverRelayedNotification(message.sessionId,message.notification.method,message.notification.params)}};let closed=false;let retryTimer;let settleReady=()=>void 0;const ready=new Promise(resolve4=>{settleReady=resolve4;const attempt=failures=>{if(closed){resolve4();return}haManager.subscribeRelay(handler).then(()=>{if(closed){resolve4();return}bus.attachRelay(relay);logger.info("[HA] Request relay ready \u2014 sessions owned by other nodes are served through them");resolve4()},error=>{const delay=Math.min(SUBSCRIBE_RETRY_MAX_MS,SUBSCRIBE_RETRY_BASE_MS*2**failures);logger.warn(`[HA] Relay channel subscription failed \u2014 retrying in ${delay}ms`,{error:error instanceof Error?error.message:String(error)});retryTimer=setTimeout(()=>attempt(failures+1),delay);retryTimer.unref?.()})};attempt(0)});return{relay,ready,close:async()=>{closed=true;if(retryTimer)clearTimeout(retryTimer);settleReady();bus.attachRelay(void 0);await relay.close()}}}var SUBSCRIBE_RETRY_BASE_MS,SUBSCRIBE_RETRY_MAX_MS;var init_relay_scope_helper=__esm({"libs/sdk/src/transport/relay/relay-scope.helper.ts"(){"use strict";init_relay_messages();init_relay_flow();init_session_relay();SUBSCRIBE_RETRY_BASE_MS=1e3;SUBSCRIBE_RETRY_MAX_MS=3e4}});var ChannelNotificationService;var init_channel_notification_service=__esm({"libs/sdk/src/channel/channel-notification.service.ts"(){"use strict";init_notification_service();init_channel_utils();ChannelNotificationService=class{constructor(notificationService,logger,defaultMeta,sendThroughFlow){this.notificationService=notificationService;this.sendThroughFlow=sendThroughFlow;this.logger=logger.child("ChannelNotificationService");this.serverMeta={...defaultMeta??{}}}notificationService;sendThroughFlow;logger;serverMeta;streamListeners=new Set;get defaultMeta(){return this.serverMeta}sendToSubscribedSessions(content,meta){const channelName=meta.source;if(!channelName){this.logger.warn("Cannot send channel notification without source in meta");return}const safeMeta=this.safeMetaOf(meta);for(const listener of this.streamListeners){if(listener.channels.has(channelName))listener.deliver(content,safeMeta)}const subscribers=this.notificationService.getSubscribersForChannel(channelName);if(subscribers.length===0){this.logger.verbose(`No subscribers for channel "${channelName}", notification buffered only`);return}const recipients=new Set(subscribers.filter(sessionId=>{const registered=this.notificationService.getRegisteredServer(sessionId);return registered!==void 0&&isChannelCapableSession(registered)&&!hasExpiredCaller(registered)}));if(recipients.size>0){this.notificationService.sendCustomNotification(CHANNEL_NOTIFICATION_METHOD,{content,meta:safeMeta},session=>recipients.has(session.sessionId))}this.logger.verbose(`Sent channel "${channelName}" notification to ${subscribers.length} subscriber(s)`)}listen(channelNames,deliver){const listener={channels:new Set(channelNames),deliver};this.streamListeners.add(listener);return()=>{this.streamListeners.delete(listener)}}sendToAllCapableSessions(content,meta){this.sendToSubscribedSessions(content,meta)}sendToSession(sessionId,content,meta){const registered=this.notificationService.getRegisteredServer(sessionId);if(!registered){this.logger.warn(`Cannot send channel notification to unregistered session: ${sessionId.slice(0,20)}...`);return false}if(!isChannelCapableSession(registered)){this.logger.verbose(`Session ${sessionId.slice(0,20)}... does not support channels, skipping`);return false}if(hasExpiredCaller(registered)){this.logger.verbose(`Session ${sessionId.slice(0,20)}... was last seen with expired credentials, skipping`);return false}const channelName=meta.source;if(!channelName){this.logger.error(`Channel notification rejected for session ${sessionId.slice(0,20)}...: meta.source is required`);return false}if(!this.notificationService.isChannelSubscribed(sessionId,channelName)){this.logger.verbose(`Session ${sessionId.slice(0,20)}... not subscribed to channel "${channelName}", skipping`);return false}this.notificationService.sendCustomNotification(CHANNEL_NOTIFICATION_METHOD,{content,meta:this.safeMetaOf(meta)},session=>session.sessionId===sessionId);return true}safeMetaOf(meta){return{...channelMetaOf(meta),source:meta.source}}async send(channelName,content,additionalMeta){if(!this.sendThroughFlow){const ownMeta=channelMetaValuesOf(additionalMeta??{});this.sendToSubscribedSessions(content,{...this.serverMeta,...ownMeta,source:channelName});return}try{await this.sendThroughFlow({channelName,content,meta:additionalMeta})}catch(error){this.logger.error(`Channel "${channelName}" notification failed`,{error})}}}}});var ChannelEmitter;var init_channel_events=__esm({"libs/sdk/src/channel/channel.events.ts"(){"use strict";ChannelEmitter=class{listeners=new Set;on(l){this.listeners.add(l);return()=>this.listeners.delete(l)}emit(e){for(const l of[...this.listeners])l(e)}}}});import{watchFiles}from"@frontmcp/utils";function connectsItself(context){return context.onConnect!==ChannelContext.prototype.onConnect}function watchedTypesOf(sourceConfig){if(!sourceConfig.events)return void 0;const watchedTypes=sourceConfig.events.flatMap(declaredEvent=>WATCHED_TYPES[declaredEvent]);return[...new Set(watchedTypes)]}function warnAboutGlobs(channelName,paths,logger){const globs=paths.filter(path4=>path4.includes("*"));if(globs.length===0)return;logger.warn(`Channel "${channelName}" declares ${globs.map(glob=>`"${glob}"`).join(", ")}: a file-watcher path is not expanded as a glob. Declare the directory to watch its direct files.`)}async function forwardFileEvents(channel2,sourceConfig,signal,logger){const events=watchedTypesOf(sourceConfig);for await(const{type,path:path4}of watchFiles(sourceConfig.paths,{events,signal})){const fileEvent={event:REPORTED_EVENTS[type],path:path4};logger.verbose(`File ${fileEvent.event} for channel "${channel2.name}": ${path4}`);try{await channel2.handleEvent(fileEvent)}catch(error){logger.error(`Failed to handle a file event in channel "${channel2.name}"`,{error})}}}function wireFileWatcherSource(channel2,context,sourceConfig,logger){if(connectsItself(context)){logger.info(`Channel "${channel2.name}" defines onConnect(), so it watches by itself: the framework does not watch its declared paths. Remove onConnect() to have the framework watch them.`);return()=>void 0}if(!isLongLivedProcess()){logger.warn(`Channel "${channel2.name}" does not watch its paths in a serverless, edge or browser runtime: watching files needs a long-lived process`);return()=>void 0}warnAboutGlobs(channel2.name,sourceConfig.paths,logger);const watch=new AbortController;forwardFileEvents(channel2,sourceConfig,watch.signal,logger).catch(error=>{logger.error(`Channel "${channel2.name}" stopped watching its paths`,{error})});return()=>watch.abort()}var WATCHED_TYPES,REPORTED_EVENTS;var init_file_watcher_source=__esm({"libs/sdk/src/channel/sources/file-watcher.source.ts"(){"use strict";init_common();init_lease_store();WATCHED_TYPES={create:["add"],change:["change"],delete:["unlink"],rename:["add","unlink"]};REPORTED_EVENTS={add:"create",change:"change",unlink:"delete"}}});var ChannelInstance,FunctionChannelContext;var init_channel_instance=__esm({"libs/sdk/src/channel/channel.instance.ts"(){"use strict";init_common();init_file_watcher_source();ChannelInstance=class extends ChannelEntry{_providers;scope;_channelNotificationService;_serviceContext;_stopFileWatch;_replayBuffer=[];_maxReplayEvents;constructor(record,providers,owner){super(record);this.owner=owner;this._providers=providers;this.name=record.metadata.name;this.fullName=this.owner.id+":"+this.name;this.scope=this._providers.getActiveScope();this._maxReplayEvents=record.metadata.replay?.maxEvents??50;this.ready=this.initialize()}setNotificationService(service){this._channelNotificationService=service}get providers(){return this._providers}get isServiceConnector(){return this.metadata.source.type==="service"||this.metadata.source.type==="file-watcher"}async initialize(){}async connectService(){if(!this.isServiceConnector)return;const logger=this._providers.get(FrontMcpLogger);const ctx=this.create({});ctx._pushIncoming=payload=>{this.handleEvent(payload).catch(err=>{logger.error(`Channel "${this.name}" service: pushIncoming failed`,{error:err})})};try{await ctx.onConnect();this._serviceContext=ctx;const{source}=this.metadata;if(source.type==="file-watcher")this._stopFileWatch=wireFileWatcherSource(this,ctx,source,logger);const sourceLabel=source.type==="service"?source.service:source.type;logger.info(`Channel "${this.name}" connected (${sourceLabel})`)}catch(err){this._serviceContext=void 0;logger.error(`Channel "${this.name}" service failed to connect`,{error:err});throw err}}async disconnectService(){if(!this._serviceContext)return;this._stopFileWatch?.();this._stopFileWatch=void 0;const logger=this._providers.get(FrontMcpLogger);try{await this._serviceContext.onDisconnect();logger.info(`Channel "${this.name}" service disconnected`)}catch(err){logger.error(`Channel "${this.name}" service failed to disconnect`,{error:err})}this._serviceContext=void 0}get serviceContext(){return this._serviceContext}create(authInfo){const logger=this._providers.get(FrontMcpLogger);const ctorArgs={metadata:this.metadata,providers:this._providers,logger,authInfo};switch(this.record.kind){case"FUNCTION":{const fnRecord=this.record;const handler=fnRecord.provide();return new FunctionChannelContext(ctorArgs,handler)}case"CLASS_TOKEN":{return new this.record.provide(ctorArgs)}default:throw new Error(`Unknown channel kind: ${this.record.kind}`)}}get replayEnabled(){return this.metadata.replay?.enabled===true}get replayBuffer(){return this._replayBuffer}async pushNotification(content,meta,targetSessionId){try{await this.scope.runFlow("channels:send-notification",{channelName:this.name,content,meta,...targetSessionId?{targetSessionId}:{}})}catch(err){this._providers.get(FrontMcpLogger).error(`Channel "${this.name}" failed to send a notification`,{error:err})}}recordForReplay(notification){if(!this.replayEnabled)return;this._replayBuffer.push(notification);while(this._replayBuffer.length>this._maxReplayEvents){this._replayBuffer.shift()}}replayBufferedEvents(sessionId){if(!this.replayEnabled||this._replayBuffer.length===0||!this._channelNotificationService){return 0}let count=0;for(const notification of this._replayBuffer){const replayMeta={...notification.meta,replayed:"true"};if(this._channelNotificationService.sendToSession(sessionId,notification.content,replayMeta))count++}return count}clearReplayBuffer(){this._replayBuffer=[]}async handleEvent(payload,targetSessionId){try{const ctx=this._serviceContext??this.create({});const notification=await ctx.onEvent(payload);if(notification){await this.pushNotification(notification.content,notification.meta,targetSessionId)}return notification}catch(err){const logger=this._providers.get(FrontMcpLogger);logger.error(`Channel "${this.name}" failed to handle event`,{error:err});return null}}async handleReply(reply,meta){if(!this.twoWay){return}try{const ctx=this._serviceContext??this.create({});await ctx.onReply(reply,meta)}catch(err){const logger=this._providers.get(FrontMcpLogger);logger.error(`Channel "${this.name}" failed to handle reply`,{error:err});throw err}}};FunctionChannelContext=class extends ChannelContext{handler;constructor(args,handler){super(args);this.handler=handler}async onEvent(payload){return this.handler(payload,this)}}}});import{getRuntimeContext as getRuntimeContext23,isEntryAvailable as isEntryAvailable7}from"@frontmcp/utils";var ChannelRegistry;var init_channel_registry=__esm({"libs/sdk/src/channel/channel.registry.ts"(){"use strict";init_common();init_regsitry();init_channel_events();init_channel_instance();init_channel_utils();ChannelRegistry=class extends RegistryAbstract{owner;localRows=[];version=0;emitter=new ChannelEmitter;logger;entryProviders;constructor(providers,list,owner,entryProviders=new Map){super("ChannelRegistry",providers,list,false);this.owner=owner;this.entryProviders=entryProviders;this.logger=providers.get(FrontMcpLogger).child("ChannelRegistry");this.buildGraph();this.ready=this.initialize()}buildMap(list){const tokens=new Set;const defs=new Map;const graph=new Map;for(const raw of list){const rec=normalizeChannel(raw);const provide=rec.provide;tokens.add(provide);defs.set(provide,rec);graph.set(provide,new Set)}return{tokens,defs,graph}}buildGraph(){}async initialize(){const runtimeContext=getRuntimeContext23();for(const token of this.tokens){const rec=this.defs.get(token);if(!rec)continue;if(!isEntryAvailable7(rec.metadata.availableWhen,runtimeContext)){this.logger.verbose(`Channel "${rec.metadata.name}" is not available in this runtime; skipped`);continue}const instance=new ChannelInstance(rec,this.entryProviders.get(token)??this.providers,this.owner);await instance.ready;const existingRow=this.localRows.find(r=>r.resolvedName===instance.name);if(existingRow){throw new Error(`Duplicate channel name "${instance.name}" \u2014 each channel must have a unique name.`)}this.instances.set(token,instance);this.localRows.push({instance,owner:this.owner,resolvedName:instance.name})}if(this.localRows.length>0){this.logger.info(`Initialized ${this.localRows.length} channel(s): ${this.localRows.map(r=>r.resolvedName).join(", ")}`)}}getChannels(){return this.localRows.map(r=>r.instance)}getChannelInstances(){return this.localRows.map(r=>r.instance)}findByName(name59){return this.localRows.find(r=>r.instance.name===name59)?.instance}hasAny(){return this.localRows.length>0}get size(){return this.localRows.length}getCapabilities(){if(!this.hasAny())return{};return{experimental:{"claude/channel":{}}}}subscribe(opts,cb){const unsub=this.emitter.on(cb);if(opts.immediate&&this.localRows.length>0){cb({kind:"reset",changeScope:"global",version:this.version,snapshot:this.getChannels()})}return unsub}bump(kind){this.version++;this.emitter.emit({kind,changeScope:"global",version:this.version,snapshot:this.getChannels()})}}}});import{internalZ as z125}from"@frontmcp/lazy-zod";var inputSchema30,channelInfoSchema,outputSchema29,stateSchema32,plan37,name37,Stage37,ListChannelsFlow;var init_list_channels_flow=__esm({"libs/sdk/src/channel/flows/list-channels.flow.ts"(){"use strict";init_common();inputSchema30=z125.object({}).optional();channelInfoSchema=z125.object({name:z125.string(),description:z125.string().optional(),sourceType:z125.string(),twoWay:z125.boolean(),tags:z125.array(z125.string())});outputSchema29=z125.object({channels:z125.array(channelInfoSchema),count:z125.number()});stateSchema32=z125.object({output:outputSchema29.optional()});plan37={execute:["listChannels"],finalize:["finalize"]};name37="channels:list";({Stage:Stage37}=FlowHooksOf(name37));ListChannelsFlow=class extends FlowBase{logger=this.scopeLogger.child("ListChannelsFlow");async listChannels(){this.logger.verbose("listChannels:start");const channelRegistry=this.scope.channels;if(!channelRegistry){this.state.set({output:{channels:[],count:0}});return}const channels=channelRegistry.getChannels().map(ch=>({name:ch.name,description:ch.metadata.description,sourceType:ch.source.type,twoWay:ch.twoWay,tags:ch.getTags()}));this.state.set({output:{channels,count:channels.length}});this.logger.verbose("listChannels:done")}async finalize(){this.logger.verbose("finalize:start");this.respond(this.state.required.output??{channels:[],count:0});this.logger.verbose("finalize:done")}};__decorateClass([Stage37("listChannels")],ListChannelsFlow.prototype,"listChannels",1);__decorateClass([Stage37("finalize")],ListChannelsFlow.prototype,"finalize",1);ListChannelsFlow=__decorateClass([FrontMcpFlow({name:name37,plan:plan37,inputSchema:inputSchema30,outputSchema:outputSchema29,access:"authorized"})],ListChannelsFlow)}});import{internalZ as z126}from"@frontmcp/lazy-zod";var inputSchema31,outputSchema30,stateSchema33,plan38,name38,Stage38,SendChannelNotificationFlow;var init_send_channel_notification_flow=__esm({"libs/sdk/src/channel/flows/send-channel-notification.flow.ts"(){"use strict";init_common();init_errors();init_channel_utils();inputSchema31=z126.object({channelName:z126.string().min(1),content:z126.string().min(1),meta:z126.record(z126.string(),z126.unknown()).optional(),targetSessionId:z126.string().min(1).optional()});outputSchema30=z126.object({sent:z126.boolean(),channelName:z126.string()});stateSchema33=z126.object({channelName:z126.string(),content:z126.string(),meta:z126.record(z126.string(),z126.string()).optional(),targetSessionId:z126.string().optional(),output:outputSchema30.optional()});plan38={pre:["parseInput","resolveMeta"],execute:["send"],finalize:["finalize"]};name38="channels:send-notification";({Stage:Stage38}=FlowHooksOf(name38));SendChannelNotificationFlow=class extends FlowBase{logger=this.scopeLogger.child("SendChannelNotificationFlow");async parseInput(){this.logger.verbose("parseInput:start");let data;try{data=inputSchema31.parse(this.rawInput)}catch(e){throw new InvalidInputError("Invalid channel notification input",e instanceof z126.ZodError?e.issues:void 0)}this.state.set({channelName:data.channelName,content:data.content,meta:data.meta&&channelMetaValuesOf(data.meta),targetSessionId:data.targetSessionId});this.logger.verbose("parseInput:done")}async resolveMeta(){const{channelName}=this.state.required;const{meta}=this.state;const channel2=this.findChannel(channelName);const resolved={...this.scope.channelNotifications?.defaultMeta??{},...channel2?.staticMeta??{},...meta??{},source:channelName};this.state.set("meta",resolved)}async send(){this.logger.verbose("send:start");const{channelName,content}=this.state.required;const{targetSessionId}=this.state;const meta={...this.state.meta??{},source:channelName};const channel2=this.findChannel(channelName);if(channel2&&!targetSessionId)channel2.recordForReplay({content,meta});const channelNotifications=this.scope.channelNotifications;if(!channelNotifications){this.logger.warn("Channel notification service not available");this.state.set("output",{sent:false,channelName});return}const sent=targetSessionId?channelNotifications.sendToSession(targetSessionId,content,meta):(channelNotifications.sendToSubscribedSessions(content,meta),true);this.state.set("output",{sent,channelName});this.logger.verbose("send:done")}async finalize(){this.logger.verbose("finalize:start");const output=this.state.output??{sent:false,channelName:this.state.required.channelName};this.respond(output);this.logger.verbose("finalize:done")}findChannel(channelName){return this.scope.channels?.findByName(channelName)}};__decorateClass([Stage38("parseInput")],SendChannelNotificationFlow.prototype,"parseInput",1);__decorateClass([Stage38("resolveMeta")],SendChannelNotificationFlow.prototype,"resolveMeta",1);__decorateClass([Stage38("send")],SendChannelNotificationFlow.prototype,"send",1);__decorateClass([Stage38("finalize")],SendChannelNotificationFlow.prototype,"finalize",1);SendChannelNotificationFlow=__decorateClass([FrontMcpFlow({name:name38,plan:plan38,inputSchema:inputSchema31,outputSchema:outputSchema30,access:"public"})],SendChannelNotificationFlow)}});import{internalZ as z127}from"@frontmcp/lazy-zod";var channelReplyInputSchema;var init_reply_types=__esm({"libs/sdk/src/channel/reply/reply.types.ts"(){"use strict";channelReplyInputSchema={channel_name:z127.string().describe("The name of the channel to reply to"),text:z127.string().describe("The reply text to send back through the channel"),meta:z127.record(z127.string(),z127.string()).optional().describe("Optional metadata for the reply")}}});var ChannelReplyTool;var init_channel_reply_tool=__esm({"libs/sdk/src/channel/reply/channel-reply.tool.ts"(){"use strict";init_common();init_reply_types();ChannelReplyTool=class extends ToolContext{async execute(input){const{channel_name,text,meta}=input;this.logger.info("channel-reply: processing",{channel_name,textLength:text.length});const channelRegistry=this.scope.channels;if(!channelRegistry){this.logger.error("channel-reply: channel registry not available");return{content:[{type:"text",text:"Error: Channel system is not enabled on this server."}],isError:true}}const channel2=channelRegistry.findByName(channel_name);if(!channel2){this.logger.warn(`channel-reply: channel "${channel_name}" not found`);return{content:[{type:"text",text:`Error: Channel "${channel_name}" not found. Available channels: ${channelRegistry.getChannelInstances().filter(c=>c.twoWay).map(c=>c.name).join(", ")}`}],isError:true}}if(!channel2.twoWay){this.logger.warn(`channel-reply: channel "${channel_name}" is not two-way`);return{content:[{type:"text",text:`Error: Channel "${channel_name}" does not support replies (one-way only).`}],isError:true}}try{await channel2.handleReply(text,meta);this.logger.info(`channel-reply: reply sent to channel "${channel_name}"`);return{content:[{type:"text",text:`Reply sent to channel "${channel_name}" successfully.`}]}}catch(err){this.logger.error(`channel-reply: failed to send reply to channel "${channel_name}"`,{error:err});return{content:[{type:"text",text:`Error: Failed to send reply to channel "${channel_name}": ${err instanceof Error?err.message:"Unknown error"}`}],isError:true}}}};ChannelReplyTool=__decorateClass([Tool({name:"channel-reply",description:"Reply to a notification channel. Use this to send a message back through a two-way channel (e.g., chat bridge, messaging service). Specify the channel_name and the text to send.",inputSchema:channelReplyInputSchema,annotations:{title:"Channel Reply",openWorldHint:true}})],ChannelReplyTool)}});function wireAgentCompletionSource(channel2,sourceConfig,agentEmitterSubscribe,logger){const filterAgentIds=sourceConfig.agentIds;return agentEmitterSubscribe(event=>{if(filterAgentIds&&filterAgentIds.length>0){if(!filterAgentIds.includes(event.agentId)){return}}if(!event.sessionId){logger.verbose(`Skipping agent completion for channel "${channel2.name}": no sessionId (prevents cross-session leak)`);return}logger.verbose(`Agent completion event for channel "${channel2.name}": agent=${event.agentId}, status=${event.status}`);channel2.handleEvent(event,event.sessionId).catch(err=>{logger.error(`Failed to handle agent completion event in channel "${channel2.name}"`,{error:err})})})}var init_agent_completion_source=__esm({"libs/sdk/src/channel/sources/agent-completion.source.ts"(){"use strict"}});function wireJobCompletionSource(channel2,sourceConfig,jobEmitterSubscribe,logger){const filterJobNames=sourceConfig.jobNames;return jobEmitterSubscribe(event=>{if(filterJobNames&&filterJobNames.length>0){if(!filterJobNames.includes(event.jobName)&&!filterJobNames.includes(event.jobId)){return}}if(!event.sessionId){logger.verbose(`Skipping job completion for channel "${channel2.name}": no sessionId (prevents cross-session leak)`);return}logger.verbose(`Job completion event for channel "${channel2.name}": job=${event.jobName}, status=${event.status}`);channel2.handleEvent(event,event.sessionId).catch(err=>{logger.error(`Failed to handle job completion event in channel "${channel2.name}"`,{error:err})})})}var init_job_completion_source=__esm({"libs/sdk/src/channel/sources/job-completion.source.ts"(){"use strict"}});function createWebhookMiddleware(channel2,sourceConfig,logger){return async(req,res)=>{const rawHeaders=req.headers??{};const normalizedHeaders={};for(const[key,value]of Object.entries(rawHeaders)){normalizedHeaders[key.toLowerCase()]=value}const payload={body:req.body,headers:normalizedHeaders,method:req.method??"POST",query:req.query};logger.verbose(`Webhook received for channel "${channel2.name}" at ${sourceConfig.path}`);try{const notification=await runOnSurface("http-trigger",()=>channel2.handleEvent(payload));if(notification){res.status(200).json({ok:true,channel:channel2.name})}else{res.status(200).json({ok:true,channel:channel2.name,skipped:true})}}catch(err){logger.error(`Webhook handler failed for channel "${channel2.name}"`,{error:err});res.status(500).json({ok:false,error:"Internal channel error"})}}}var init_webhook_source=__esm({"libs/sdk/src/channel/sources/webhook.source.ts"(){"use strict";init_call_surface()}});var channel_scope_helper_exports={};__export(channel_scope_helper_exports,{registerChannelCapabilities:()=>registerChannelCapabilities});async function registerChannelCapabilities(args){const{providers,owner,channelsList,channelProviders,channelsConfig,notificationService,flowRegistry,toolRegistry,http:http4,logger}=args;const completions=completionEventsOf(providers.getActiveScope());const agentEmitterSubscribe=args.agentEmitterSubscribe??(cb=>completions.agents.subscribe(cb));const jobEmitterSubscribe=args.jobEmitterSubscribe??(cb=>completions.jobs.subscribe(cb));const unsubscribers=[];const reservedPaths=http4?computeReservedPaths(http4.entryPath,http4.routeBase,http4.healthPaths):void 0;const webhookPaths=new Map;const channelRegistry=new ChannelRegistry(providers,channelsList,owner,channelProviders);await channelRegistry.ready;const channelNotificationService=new ChannelNotificationService(notificationService,logger,channelsConfig?.defaultMeta,input=>flowRegistry.runFlow("channels:send-notification",input));const channelEventBus=args.eventBus??new ChannelEventBus(logger);for(const instance of channelRegistry.getChannelInstances()){instance.setNotificationService(channelNotificationService)}for(const instance of channelRegistry.getChannelInstances()){const sourceType=instance.source.type;switch(sourceType){case"agent-completion":{const unsub=wireAgentCompletionSource(instance,instance.metadata.source,agentEmitterSubscribe,logger);unsubscribers.push(unsub);break}case"job-completion":{const unsub=wireJobCompletionSource(instance,instance.metadata.source,jobEmitterSubscribe,logger);unsubscribers.push(unsub);break}case"app-event":{const eventName=instance.metadata.source.event;const unsub=wireAppEventSource(instance,eventName,channelEventBus,logger);unsubscribers.push(unsub);break}case"webhook":{const source=instance.metadata.source;if(!http4||!reservedPaths){logger.warn(`Channel "${instance.name}" has a webhook source but no HTTP server to serve ${source.path}`);break}assertNotReserved("POST",source.path,reservedPaths);const claimedBy=webhookPaths.get(source.path);if(claimedBy){throw new Error(`Channels "${claimedBy}" and "${instance.name}" both declare the webhook path ${source.path}. Give each webhook channel its own path.`)}webhookPaths.set(source.path,instance.name);const handler=createWebhookMiddleware(instance,source,logger);await http4.server.registerRoute("POST",source.path,wrapWithIpFilter(handler,http4.checkClientIp));logger.info(`Registered webhook route for channel "${instance.name}": POST ${source.path}`);break}case"manual":break;case"service":case"file-watcher":break}}await flowRegistry.registryFlows([SendChannelNotificationFlow,ListChannelsFlow]);const hasTwoWayChannels=channelRegistry.getChannelInstances().some(ch=>ch.twoWay);if(hasTwoWayChannels){const replyToolRecord=normalizeTool(ChannelReplyTool);const replyToolInstance=new ToolInstance(replyToolRecord,providers,owner);await replyToolInstance.ready;toolRegistry.registerToolInstance(replyToolInstance);logger.info("Registered channel-reply tool for two-way channel communication")}let channelToolCount=0;for(const instance of channelRegistry.getChannelInstances()){const channelTools=instance.metadata.tools;if(channelTools&&channelTools.length>0){for(const toolDef of channelTools){try{const toolRecord=normalizeTool(toolDef);const toolRecords=isExternalToolRecord(toolRecord)?await loadExternalToolRecords(providers.getActiveScope(),toolRecord):[toolRecord];for(const record of toolRecords){const toolInstance=new ToolInstance(record,instance.providers,{kind:"scope",id:`_channel:${instance.name}`,ref:toolDef});await toolInstance.ready;toolRegistry.registerToolInstance(toolInstance);channelToolCount++}}catch(error){logger.warn(`Failed to register tool from channel "${instance.name}": ${error instanceof Error?error.message:String(error)}`)}}}}if(channelToolCount>0){logger.info(`Registered ${channelToolCount} tool(s) from channel declarations`)}const serviceChannels=channelRegistry.getChannelInstances().filter(ch=>ch.isServiceConnector);logger.info(`Channel system initialized: ${channelRegistry.size} channel(s)`+(hasTwoWayChannels?", reply tool":"")+(channelToolCount>0?`, ${channelToolCount} channel tool(s)`:"")+(serviceChannels.length>0?`, ${serviceChannels.length} service connector(s)`:""));const teardown=async()=>{const results=await Promise.allSettled(serviceChannels.map(instance=>instance.disconnectService()));for(const result of results){if(result.status==="rejected"){logger.error("Channel disconnect failed during teardown",{error:result.reason})}}for(const unsub of unsubscribers)unsub();if(!args.eventBus)channelEventBus.clear()};return{channelRegistry,channelNotificationService,channelEventBus,connectServices:async()=>{try{for(const instance of serviceChannels)await instance.connectService()}catch(err){await teardown();throw err}},teardown}}var init_channel_scope_helper=__esm({"libs/sdk/src/channel/channel-scope.helper.ts"(){"use strict";init_custom_routes_helper();init_tool_external_loader();init_tool_instance();init_tool_utils();init_channel_notification_service();init_channel_registry();init_list_channels_flow();init_send_channel_notification_flow();init_channel_reply_tool();init_agent_completion_source();init_app_event_source();init_completion_events();init_job_completion_source();init_webhook_source()}});function createEventMetrics(metrics,loadFactory=loadCounterFactory){if(metrics?.enabled!==true)return{count:()=>void 0};const createCounter=loadFactory();return{count:(counter,eventName,by=1)=>{createCounter(EVENT_COUNTERS[counter],COUNTER_DESCRIPTIONS2[counter]).inc(by,{event:eventName})}}}var EVENT_COUNTERS,COUNTER_DESCRIPTIONS2;var init_event_metrics=__esm({"libs/sdk/src/event/delivery/event-metrics.ts"(){"use strict";init_answer_meter();EVENT_COUNTERS={published:"frontmcp_events_published_total",matched:"frontmcp_events_matched_total",delivered:"frontmcp_events_delivered_total",retried:"frontmcp_events_retried_total",abandoned:"frontmcp_events_abandoned_total",dropped:"frontmcp_events_dropped_total",suspended:"frontmcp_events_suspended_total",terminated:"frontmcp_events_terminated_total",notified:"frontmcp_events_channel_notified_total"};COUNTER_DESCRIPTIONS2={published:"Events published",matched:"Deliveries queued for the subscriptions an event matched",delivered:"Deliveries a callback acknowledged with 2xx",retried:"Delivery attempts that failed and are retried",abandoned:"Deliveries given up after the last attempt or the retry window",dropped:"Deliveries not retried: the callback answered 410 or 413, the body was too large, or the subscription is gone",suspended:"Subscriptions suspended after repeated delivery failures",terminated:"Subscriptions the server ended",notified:"Channel notifications sent to Claude Code sessions for events with the channel option"}}});import{getMachineId as getMachineId5,getRuntimeContext as getRuntimeContext24,randomUUID as randomUUID28}from"@frontmcp/utils";function reasonOf(outcome){if(outcome.result==="failed")return outcome.category;return outcome.result==="waiting"?"the subscription is suspended":"the attempt could not be made"}var RECORD_PREFIX2,OUTBOX_SWEEP_INTERVAL_MS,LEASE_MARGIN_MS,SUSPENDED_RECHECK_MS,EventOutbox;var init_event_outbox=__esm({"libs/sdk/src/event/delivery/event-outbox.ts"(){"use strict";init_elicitation_encryption();RECORD_PREFIX2="outbox:";OUTBOX_SWEEP_INTERVAL_MS=3e4;LEASE_MARGIN_MS=3e4;SUSPENDED_RECHECK_MS=3e4;EventOutbox=class{constructor(options){this.options=options;this.ownerId=`${getMachineId5()}:${randomUUID28()}`;this.logger=options.logger.child("EventOutbox");this.random=options.random??Math.random;const{runtime,deployment}=getRuntimeContext24();this.usesTimers=deployment!=="serverless"&&runtime!=="edge"&&runtime!=="browser"}options;ownerId;logger;random;usesTimers;timers=new Map;inFlight=new Map;waitingForSlot=[];activeAttempts=0;sweepTimer;lastSweepAt=0;stopped=false;async enqueue(delivery){const now=Date.now();const record={...delivery,id:`dlv_${randomUUID28()}`,attempt:0,nextAttemptAt:now,firstAttemptAt:now,leaseOwner:this.ownerId,leaseUntil:this.leaseEnd(now)};await this.options.storage.set(RECORD_PREFIX2+record.id,await this.encode(record));if(this.usesTimers){this.schedule(record.id,0)}else{await this.run(record.id)}return record.id}async isPending(deliveryId){return this.options.storage.exists(RECORD_PREFIX2+deliveryId)}start(){if(!this.usesTimers||!this.options.durable)return;this.sweepInBackground();this.sweepTimer=setInterval(()=>this.sweepInBackground(),OUTBOX_SWEEP_INTERVAL_MS);this.sweepTimer.unref?.()}async sweepIfDue(now=Date.now()){if(now-this.lastSweepAt<OUTBOX_SWEEP_INTERVAL_MS)return;await this.sweep(now)}async sweep(now=Date.now()){this.lastSweepAt=now;if(!this.options.durable&&this.usesTimers)return;const keys=await this.options.storage.keys(`${RECORD_PREFIX2}*`);const dueAttempts=[];for(const key of keys){const id=key.slice(RECORD_PREFIX2.length);if(this.timers.has(id)||this.inFlight.has(id))continue;const claimed=await this.claim(id,now);if(!claimed)continue;if(this.usesTimers){this.schedule(id,Math.max(0,claimed.nextAttemptAt-now))}else if(claimed.nextAttemptAt<=now){dueAttempts.push(this.run(id))}}await Promise.all(dueAttempts)}async depth(){return this.options.storage.count(`${RECORD_PREFIX2}*`)}async stop(){this.stopped=true;if(this.sweepTimer)clearInterval(this.sweepTimer);this.sweepTimer=void 0;for(const timer of this.timers.values())clearTimeout(timer);this.timers.clear();await Promise.allSettled([...this.inFlight.values()]);await this.releaseLeases().catch(error=>this.logger.warn("The outbox leases were not released",error))}async releaseLeases(){if(!this.options.durable)return;const keys=await this.options.storage.keys(`${RECORD_PREFIX2}*`);for(const key of keys){const stored=await this.read(key.slice(RECORD_PREFIX2.length));if(stored?.record.leaseOwner!==this.ownerId)continue;await this.replace(stored,{...stored.record,leaseUntil:0})}}schedule(id,delayMs){if(this.stopped||this.timers.has(id))return;const timer=setTimeout(()=>{this.timers.delete(id);void this.run(id)},delayMs);timer.unref?.();this.timers.set(id,timer)}run(id){const running=this.inFlight.get(id);if(running)return running;const attempt=this.attemptWithinLimit(id).catch(error=>this.logger.warn(`Delivery ${id} could not be attempted`,error)).finally(()=>this.inFlight.delete(id));this.inFlight.set(id,attempt);return attempt}async attemptWithinLimit(id){if(this.activeAttempts>=this.options.settings.concurrency){await new Promise(resolve4=>this.waitingForSlot.push(resolve4))}else{this.activeAttempts+=1}try{await this.attemptOnce(id)}finally{const nextWaiter=this.waitingForSlot.shift();if(nextWaiter)nextWaiter();else this.activeAttempts-=1}}async attemptOnce(id){const stored=await this.read(id);if(!stored||stored.record.leaseOwner!==this.ownerId)return;const startedAt=Date.now();const held=await this.replace(stored,{...stored.record,leaseUntil:this.leaseEnd(startedAt)});if(!held)return;const outcome=await this.outcomeOf(held.record);if(outcome.result==="delivered"||outcome.result==="dropped"){await this.options.storage.delete(RECORD_PREFIX2+id);this.options.metrics.count(outcome.result,held.record.eventName);return}await this.retryOrAbandon(held,outcome)}async outcomeOf(record){try{return await this.options.attempt(record)}catch(error){this.logger.warn(`The attempt of delivery ${record.id} threw`,error);return{result:"error"}}}async retryOrAbandon(held,outcome){const{settings,metrics,storage}=this.options;const{record}=held;const now=Date.now();const isWaiting=outcome.result==="waiting";const attemptsMade=isWaiting?record.attempt:record.attempt+1;const windowIsOver=now-record.firstAttemptAt>=settings.retryWindowMs;if(attemptsMade>=settings.maxAttempts||windowIsOver){await storage.delete(RECORD_PREFIX2+record.id);metrics.count("abandoned",record.eventName);this.logger.warn(`Delivery ${record.id} of event "${record.eventName}" to subscription ${record.subscriptionId} is abandoned after ${attemptsMade} attempt(s): ${reasonOf(outcome)}`);return}const waitMs=isWaiting?SUSPENDED_RECHECK_MS:this.backoffMs(attemptsMade);const nextAttemptAt=now+waitMs;const next={...record,attempt:attemptsMade,nextAttemptAt,leaseUntil:this.leaseEnd(nextAttemptAt)};if(!await this.replace(held,next))return;if(!isWaiting)metrics.count("retried",record.eventName);if(this.usesTimers)this.schedule(record.id,waitMs)}backoffMs(attemptsMade){const{backoffMs,maxBackoffMs}=this.options.settings;const exponential=Math.min(maxBackoffMs,backoffMs*2**(attemptsMade-1));return Math.round(exponential*(.5+this.random()*.5))}leaseEnd(attemptAt){return attemptAt+this.options.settings.timeoutMs+LEASE_MARGIN_MS}async claim(id,now){const stored=await this.read(id);if(!stored)return void 0;if(stored.record.leaseOwner===this.ownerId)return stored.record;if(stored.record.leaseUntil>now)return void 0;const claimed={...stored.record,leaseOwner:this.ownerId,leaseUntil:this.leaseEnd(now)};return(await this.replace(stored,claimed))?.record}async replace(stored,next){const raw=await this.encode(next);const replaced=await this.options.storage.setIfEquals(RECORD_PREFIX2+next.id,stored.raw,raw);return replaced?{raw,record:next}:void 0}async read(id){const raw=await this.options.storage.get(RECORD_PREFIX2+id);if(raw===null)return void 0;const record=await this.decode(raw,id);return record?{raw,record}:void 0}async encode(record){const{secret}=this.options;if(secret===void 0)return JSON.stringify(record);return encryptAndSerialize(record,`events-outbox:${record.id}`,secret)}async decode(raw,id){const{secret}=this.options;try{const record=secret===void 0?JSON.parse(raw):await deserializeAndDecrypt(raw,`events-outbox:${id}`,secret);return record?.id===id?record:void 0}catch{return void 0}}sweepInBackground(){this.sweep().catch(error=>this.logger.warn("The outbox sweep failed",error))}}}});import{base64urlEncode as base64urlEncode6,randomBytes as randomBytes7}from"@frontmcp/utils";function newEventId(){return`evt_${base64urlEncode6(randomBytes7(EVENT_ID_RANDOM_BYTES))}`}function eventNameOf(event){return typeof event==="string"?event:normalizeEvent(event).metadata.name}function timestampOf(eventName,timestamp){const time=timestamp===void 0?new Date:new Date(timestamp);if(Number.isNaN(time.getTime())){throw new InvalidEventPublishError(eventName,`"${String(timestamp)}" is not a timestamp`)}return time.toISOString()}var EVENT_ID_RANDOM_BYTES,ScopeEventPublisher;var init_event_publisher=__esm({"libs/sdk/src/event/event-publisher.ts"(){"use strict";init_errors();init_event_utils();EVENT_ID_RANDOM_BYTES=18;ScopeEventPublisher=class{constructor(scope,events){this.scope=scope;this.events=events}scope;events;async publish(event,data,options={}){const eventName=eventNameOf(event);const entry=this.events.findByName(eventName);if(!entry)throw new EventNotRegisteredError(eventName);let payload;try{payload=entry.parsePayload(data)}catch(error){const problem2=error instanceof Error?error.message:String(error);throw new InvalidEventPublishError(eventName,`its data does not match payloadSchema: ${problem2}`)}const occurrence={eventId:options.eventId??newEventId(),name:eventName,timestamp:timestampOf(eventName,options.timestamp),data:payload};return this.scope.runFlowForOutput("events:publish",{occurrence,subscriptionId:options.subscriptionId,audience:options.audience})}}}});function isAuthorizeRefusal(error){return isPublicError(error)}function subscriberAuthInfo(subscriber){const user={...subscriber.claims,sub:subscriber.sub,...subscriber.iss&&{iss:subscriber.iss}};return{clientId:subscriber.sub,scopes:subscriber.scopes,extra:{user}}}async function checkAuthorities(args){const engine=args.scope.authoritiesEngine;const contextBuilder=args.scope.authoritiesContextBuilder;const authorities=args.event.getAuthorities();if(!engine||!contextBuilder||!authorities)return{outcome:"granted"};const evaluationContext=contextBuilder.build({},args.arguments);const ownerContext={...evaluationContext,user:{...evaluationContext.user,...args.subscriber}};try{const result=await engine.evaluate(authorities,ownerContext);return result.granted?{outcome:"granted"}:{outcome:"refused",reason:result.deniedBy??"policy denied"}}catch(error){return{outcome:"failed",error}}}async function checkAuthorize(args){const context=args.event.create(args.authInfo??subscriberAuthInfo(args.subscriber));if(!context.authorize)return{outcome:"granted"};try{await context.authorize(args.arguments,args.subscriber);return{outcome:"granted"}}catch(error){if(!isAuthorizeRefusal(error))return{outcome:"failed",error};return{outcome:"refused",reason:error.message}}}async function reauthorizeSubscriber(args){const byAuthorities=await checkAuthorities(args);if(byAuthorities.outcome!=="granted")return byAuthorities;return checkAuthorize(args)}function hasReauthorization(scope,event,hasAuthorize){return hasAuthorize||Boolean(scope.authoritiesEngine&&scope.authoritiesContextBuilder&&event.getAuthorities())}var init_event_reauthorization=__esm({"libs/sdk/src/event/event-reauthorization.ts"(){"use strict";init_errors()}});var FunctionEventContext,EventInstance;var init_event_instance=__esm({"libs/sdk/src/event/event.instance.ts"(){"use strict";init_common();FunctionEventContext=class extends EventContext{};EventInstance=class extends EventEntry{entryProviders;constructor(record,providers,owner){super(record);this.owner=owner;this.entryProviders=providers;this.name=record.metadata.name;this.fullName=`${owner.id}:${this.name}`;this.ready=this.initialize()}get providers(){return this.entryProviders}async initialize(){}create(authInfo){const contextArgs={metadata:this.metadata,providers:this.entryProviders,logger:this.entryProviders.get(FrontMcpLogger),authInfo};if(this.record.kind==="CLASS_TOKEN"){return new this.record.provide(contextArgs)}const context=new FunctionEventContext(contextArgs);return Object.assign(context,this.record.provide())}}}});import{EVENT_DELIVERY_MODES as EVENT_DELIVERY_MODES2,EVENTS_EXTENSION_ID}from"@frontmcp/protocol";import{getRuntimeContext as getRuntimeContext25,isEntryAvailable as isEntryAvailable8}from"@frontmcp/utils";var EventRegistry;var init_event_registry=__esm({"libs/sdk/src/event/event.registry.ts"(){"use strict";init_common();init_errors();init_regsitry();init_event_instance();init_event_utils();EventRegistry=class extends RegistryAbstract{owner;config;subscriptions;publisher;outbox;metrics;storage;publishEndpoint;buffer;pollLeases;streams;replays;channelDelivery=true;withoutWebhook=new Set;eventsByName=new Map;enabledDeliveryModes=new Set;logger;entryProviders;constructor(providers,list,owner,config,entryProviders){super("EventRegistry",providers,list,false);this.owner=owner;this.config=config;this.entryProviders=entryProviders;this.logger=providers.get(FrontMcpLogger).child("EventRegistry");this.buildGraph();this.ready=this.initialize()}buildMap(list){const tokens=new Set;const defs=new Map;const graph=new Map;for(const item of list){const record=normalizeEvent(item);tokens.add(record.provide);defs.set(record.provide,record);graph.set(record.provide,new Set)}return{tokens,defs,graph}}buildGraph(){}async initialize(){const runtimeContext=getRuntimeContext25();for(const[token,record]of this.defs){const eventName=record.metadata.name;if(!isEntryAvailable8(record.metadata.availableWhen,runtimeContext)){this.logger.verbose(`Event "${eventName}" is not available in this runtime; skipped`);continue}if(this.eventsByName.has(eventName)){throw new EventNameConflictError(eventName)}const instance=new EventInstance(record,this.entryProviders.get(token)??this.providers,this.owner);await instance.ready;this.instances.set(token,instance);this.eventsByName.set(eventName,instance)}}getEvents(){return[...this.eventsByName.values()]}findByName(name59){return this.eventsByName.get(name59)}hasAny(){return this.eventsByName.size>0}enableDeliveryMode(mode){this.enabledDeliveryModes.add(mode)}withholdWebhookFrom(eventName){this.withoutWebhook.add(eventName)}performs(mode){return this.enabledDeliveryModes.has(mode)}deliveryModesOf(event){const restriction=event.metadata.delivery;return EVENT_DELIVERY_MODES2.filter(mode=>this.enabledDeliveryModes.has(mode)&&(!restriction||restriction.includes(mode))&&!(mode==="webhook"&&this.withoutWebhook.has(event.name)))}getServedEvents(){return this.getEvents().map(event=>({event,delivery:this.deliveryModesOf(event)})).filter(({delivery})=>delivery.length>0)}servesEvents(){return this.getServedEvents().length>0}sendsToChannelSessions(event){return this.channelDelivery&&event.metadata.channel!==void 0}getChannelEvents(){return this.getEvents().filter(event=>this.sendsToChannelSessions(event))}getCapabilities(){if(!this.servesEvents())return{};return{events:{},extensions:{[EVENTS_EXTENSION_ID]:{}}}}}}});import{isEdgeRuntime}from"@frontmcp/utils";function eventOutboundTargetOptions(allowLocal){return isEdgeRuntime()?{allowLocal,allowPlatformDns:true}:{allowLocal}}var init_event_outbound=__esm({"libs/sdk/src/event/event-outbound.ts"(){"use strict"}});import{internalZ as z128}from"@frontmcp/lazy-zod";import{EventDeliveryErrorCategorySchema,MCP_SUBSCRIPTION_ID_HEADER as MCP_SUBSCRIPTION_ID_HEADER2}from"@frontmcp/protocol";import{outboundFailureCategory,sendOutboundRequest,signingKeyOf as signingKeyOf2,webhookSignatureHeaders}from"@frontmcp/utils";var inputSchema32,outputSchema31,stateSchema34,plan39,name39,Stage39,SUSPEND_AFTER_FAILURES,GONE,PAYLOAD_TOO_LARGE,EventDeliverFlow;var init_event_deliver_flow=__esm({"libs/sdk/src/event/flows/event-deliver.flow.ts"(){"use strict";init_common();init_event_outbound();inputSchema32=z128.object({delivery:z128.any()});outputSchema31=z128.discriminatedUnion("result",[z128.object({result:z128.literal("delivered")}),z128.object({result:z128.literal("dropped"),reason:z128.enum(["gone","refused"])}),z128.object({result:z128.literal("failed"),category:EventDeliveryErrorCategorySchema}),z128.object({result:z128.literal("waiting")})]);stateSchema34=z128.object({target:z128.any(),subscription:z128.any(),headers:z128.record(z128.string(),z128.string()),answer:z128.any(),outcome:z128.any()});plan39={pre:["loadSubscription","buildHeaders"],execute:["send","classify"],post:["buildResult"]};name39="events:deliver";({Stage:Stage39}=FlowHooksOf(name39));SUSPEND_AFTER_FAILURES=20;GONE=410;PAYLOAD_TOO_LARGE=413;EventDeliverFlow=class extends FlowBase{logger=this.scopeLogger.child("EventDeliverFlow");get events(){return this.scope.events}get subscriptions(){return this.events.subscriptions}async loadSubscription(){const{delivery}=this.input;if(delivery.target){this.state.set("target",delivery.target);return}const subscription=await this.subscriptions.store.get(delivery.subscriptionId);if(!subscription){this.state.set("outcome",{result:"dropped",reason:"gone"});return}if(!subscription.active){this.state.set("outcome",{result:"waiting"});return}this.state.set({subscription,target:subscription.delivery})}async buildHeaders(){if(this.state.outcome)return;const{delivery}=this.input;const{secret,previousSecret,previousSecretUntil}=this.state.required.target;const now=Date.now();const signingKeys=[signingKeyOf2(secret)];if(previousSecret!==void 0&&(previousSecretUntil??0)>now){signingKeys.push(signingKeyOf2(previousSecret))}const message={id:delivery.webhookId,timestamp:Math.floor(now/1e3),body:delivery.body};this.state.set("headers",{"content-type":"application/json",[MCP_SUBSCRIPTION_ID_HEADER2]:delivery.subscriptionId,...webhookSignatureHeaders(message,signingKeys)})}async send(){if(this.state.outcome)return;const{webhook}=this.events.config;const answer=await sendOutboundRequest({url:this.state.required.target.url,method:"POST",headers:this.state.required.headers,body:this.input.delivery.body,timeoutMs:webhook.delivery.timeoutMs,...eventOutboundTargetOptions(webhook.unsafeAllowLocalCallbacks)});this.state.set("answer",answer)}async classify(){if(this.state.outcome)return;const{answer}=this.state.required;const category=outboundFailureCategory(answer);if(!category){await this.recordStatus(()=>({status:{lastDeliveryAt:Date.now()}}));this.state.set("outcome",{result:"delivered"});return}if(answer.answered&&(answer.status===GONE||answer.status===PAYLOAD_TOO_LARGE)){await this.recordStatus(status=>({status:{...status,lastError:category}}));this.state.set("outcome",{result:"dropped",reason:"refused"});return}await this.recordFailure(category);this.state.set("outcome",{result:"failed",category})}async buildResult(){this.respond(this.state.required.outcome)}async recordFailure(category){const now=Date.now();const updated=await this.recordStatus((status,active)=>{const failures=(status.failures??0)+1;const failing={...status,lastError:category,failedSince:status.failedSince??now,failures};const suspendsNow=active&&failures>=SUSPEND_AFTER_FAILURES;return suspendsNow?{active:false,status:{...failing,suspendedSince:now}}:{status:failing}});if(updated&&!updated.active&&updated.status.suspendedSince===now){this.events.metrics?.count("suspended",updated.eventName);this.logger.warn(`Subscription ${updated.id} to event "${updated.eventName}" is suspended after ${SUSPEND_AFTER_FAILURES} failed deliveries in a row (${category}). Its next events/subscribe reactivates it.`)}}async recordStatus(change){const{subscription}=this.state;if(!subscription)return void 0;return this.subscriptions.store.update(subscription.id,current=>change(current.status,current.active))}};__decorateClass([Stage39("loadSubscription")],EventDeliverFlow.prototype,"loadSubscription",1);__decorateClass([Stage39("buildHeaders")],EventDeliverFlow.prototype,"buildHeaders",1);__decorateClass([Stage39("send")],EventDeliverFlow.prototype,"send",1);__decorateClass([Stage39("classify")],EventDeliverFlow.prototype,"classify",1);__decorateClass([Stage39("buildResult")],EventDeliverFlow.prototype,"buildResult",1);EventDeliverFlow=__decorateClass([FrontMcpFlow({name:name39,plan:plan39,inputSchema:inputSchema32,outputSchema:outputSchema31,access:"public"})],EventDeliverFlow)}});import{EVENTS_ERROR_CODES as EVENTS_ERROR_CODES2,EVENTS_SKETCH_ERROR_CODES as EVENTS_SKETCH_ERROR_CODES2}from"@frontmcp/protocol";function knownPlatform(platform){return platform&&platform!=="unknown"?platform:void 0}function callerPlatformOf(scope,authInfo,requestPlatform){const detected=knownPlatform(authInfo.sessionIdPayload?.platformType)??knownPlatform(requestPlatform);if(detected)return detected;return authInfo.sessionId?scope.notifications.getPlatformType(authInfo.sessionId):"unknown"}function resolveEventDialect(compat,platform){if(compat!=="auto")return compat;return platform==="openai"?"sketch":"sep-3415"}var EVENT_DIALECTS;var init_event_dialect=__esm({"libs/sdk/src/event/event-dialect.ts"(){"use strict";EVENT_DIALECTS={"sep-3415":{errorCodes:EVENTS_ERROR_CODES2,webhookId:"message",sendsControlEnvelopes:true},sketch:{errorCodes:EVENTS_SKETCH_ERROR_CODES2,webhookId:"eventId",sendsControlEnvelopes:false}}}});function stringClaim(claims3,name59){const value=claims3[name59];return typeof value==="string"&&value!==""?value:void 0}function eventSubscriberOf(authInfo,contextBuilder){const principalKey=principalKeyOf(authInfo);if(!principalKey)return void 0;const plainAuthInfo=authInfo;const tokenPrincipal=resolvePrincipal(plainAuthInfo);const principal=contextBuilder?resolvePrincipal(plainAuthInfo,contextBuilder):tokenPrincipal;const tenantId=contextBuilder?.build(plainAuthInfo).user.tenantId;const issuer=stringClaim(tokenPrincipal.claims,"iss");return{principalKey,subscriber:{sub:principal.sub||tokenPrincipal.sub,...issuer&&{iss:issuer},...tenantId&&{tenantId},roles:principal.roles,permissions:principal.permissions,scopes:principal.scopes,claims:principal.claims}}}var init_event_subscriber=__esm({"libs/sdk/src/event/event-subscriber.ts"(){"use strict";init_principal_utils();init_question_subject()}});import{isPublicMode as isPublicMode2}from"@frontmcp/auth";import{internalZ as z129}from"@frontmcp/lazy-zod";import{canonicalJson as canonicalJson3,sha256Hex as sha256Hex23}from"@frontmcp/utils";function offeredEventOf(events,eventName,mode,requestContext,codes){const event=events.findByName(eventName);if(!event||!isOfferedOnSurface(event.metadata.availableWhen,callSurfaceOf(requestContext))){throw new EventNotFoundError(codes,"event",eventName)}const offeredModes=events.deliveryModesOf(event);if(!offeredModes.includes(mode))throw new EventUnsupportedError(codes,"deliveryMode",mode,offeredModes);return event}function eventReaderOf(scope,authInfo,eventName,codes){const owner=eventSubscriberOf(authInfo,scope.authoritiesContextBuilder);if(owner)return owner;const authOptions=scope.auth?.options;if(authOptions!==void 0&&!isPublicMode2(authOptions)){throw new EventForbiddenError(codes,eventName,"this server needs a signed-in caller")}return{principalKey:void 0,subscriber:ANONYMOUS_SUBSCRIBER}}async function assertEventAuthorities(scope,event,authInfo,args,codes){const engine=scope.authoritiesEngine;const contextBuilder=scope.authoritiesContextBuilder;const authorities=event.getAuthorities();if(!engine||!contextBuilder||!authorities)return;const result=await engine.evaluate(authorities,contextBuilder.build(authInfo,args));if(!result.granted)throw new EventForbiddenError(codes,event.name,result.deniedBy??"policy denied")}function parsedEventArguments(event,args){try{return event.parseArguments(args??{})}catch(error){throw new InvalidInputError("Invalid subscription arguments",error instanceof z129.ZodError?error.issues:void 0)}}async function assertEventAuthorizes(context,eventName,args,subscriber,codes){try{await context.authorize?.(args,subscriber)}catch(error){if(error instanceof EventProtocolError)throw error;const reason=isPublicError(error)?error.getPublicMessage():"the event refused it";throw new EventForbiddenError(codes,eventName,reason)}}function readerSubscriptionOf(reader,mode,eventName,args){const key=canonicalJson3({principalKey:reader.principalKey??null,mode,name:eventName,arguments:args});return{id:`sub_${sha256Hex23(key).slice(0,32)}`,name:eventName,mode,subscriber:reader.subscriber}}var ANONYMOUS_SUBSCRIBER;var init_event_gates=__esm({"libs/sdk/src/event/event-gates.ts"(){"use strict";init_availability();init_errors();init_event_subscriber();ANONYMOUS_SUBSCRIBER={sub:"",roles:[],permissions:[],scopes:[],claims:{}}}});import{getRuntimeContext as getRuntimeContext26}from"@frontmcp/utils";function pollLeaseMs(nextPollMs){return Math.max(POLL_LEASE_MIN_MS,POLL_LEASE_INTERVALS*nextPollMs)}var POLL_LEASE_MIN_MS,POLL_LEASE_INTERVALS,POLL_LEASE_SWEEP_INTERVAL_MS,MAX_POLL_LEASES,EventPollLeases;var init_event_poll_leases=__esm({"libs/sdk/src/event/poll/event-poll-leases.ts"(){"use strict";POLL_LEASE_MIN_MS=3e5;POLL_LEASE_INTERVALS=5;POLL_LEASE_SWEEP_INTERVAL_MS=6e4;MAX_POLL_LEASES=1e4;EventPollLeases=class{constructor(options){this.options=options;this.logger=options.logger.child("EventPollLeases")}options;leases=new Map;starting=new Map;logger;sweepTimer;lastSweepAt=0;get size(){return this.leases.size}isFull(principalKey){if(this.leases.size>=MAX_POLL_LEASES)return true;let held=0;for(const lease of this.leases.values()){if(lease.principalKey===principalKey)held+=1}return held>=this.options.maxPerPrincipal}has(subscriptionId){return this.leases.has(subscriptionId)||this.starting.has(subscriptionId)}async renew(request2){const{subscription,leaseMs}=request2;const now=Date.now();this.sweepIfDue(now);const lease=this.leases.get(subscription.id);if(lease){lease.expiresAt=now+leaseMs;return}const pending=this.starting.get(subscription.id);if(pending)return pending;const start=this.subscribe(request2,now).finally(()=>this.starting.delete(subscription.id));this.starting.set(subscription.id,start);return start}async subscribe(request2,now){const{subscription,context,leaseMs}=request2;await context.onSubscribe?.(request2.arguments,subscription);this.leases.set(subscription.id,{subscription,arguments:request2.arguments,principalKey:request2.principalKey,expiresAt:now+leaseMs,end:async reason=>{await context.onUnsubscribe?.(request2.arguments,subscription,reason)}})}async sweep(now=Date.now()){this.lastSweepAt=now;for(const[subscriptionId,lease]of this.leases){if(lease.expiresAt>now)continue;this.leases.delete(subscriptionId);await this.end(lease,"expired")}}start(){const{runtime,deployment}=getRuntimeContext26();if(deployment==="serverless"||runtime==="edge"||runtime==="browser")return;this.sweepTimer=setInterval(()=>this.sweepInBackground(Date.now()),POLL_LEASE_SWEEP_INTERVAL_MS);this.sweepTimer.unref?.()}stop(){if(this.sweepTimer)clearInterval(this.sweepTimer);this.sweepTimer=void 0;this.leases.clear()}sweepIfDue(now){if(now-this.lastSweepAt<POLL_LEASE_SWEEP_INTERVAL_MS)return;this.sweepInBackground(now)}sweepInBackground(now){this.sweep(now).catch(error=>this.logger.warn("The poll lease sweep failed",error))}async end(lease,reason){try{await lease.end(reason)}catch(error){const{id,name:name59}=lease.subscription;this.logger.warn(`onUnsubscribe of event "${name59}" failed for poll subscription ${id}`,error)}}}}});function eventChannelMessage(event,occurrence){const{channel:channel2}=event.metadata;const options=channel2===void 0||channel2===true?{}:channel2;const payload=occurrence.data;const content=options.content?options.content(payload):JSON.stringify(payload);const ownMeta=options.meta?options.meta(payload):{};return{content,meta:channelMetaOf({...ownMeta,event:occurrence.name,event_id:occurrence.eventId})}}function channelSessionReader(scope,event,session){if(hasExpiredCaller(session))return void 0;if(!isOfferedOnSurface(event.metadata.availableWhen,mcpRequestSurface(scope)))return void 0;try{return eventReaderOf(scope,session.caller??{},event.name,EVENT_DIALECTS["sep-3415"].errorCodes)}catch(error){if(error instanceof EventForbiddenError)return void 0;throw error}}var init_event_channel=__esm({"libs/sdk/src/event/event-channel.ts"(){"use strict";init_channel_utils();init_availability();init_errors();init_notification_service();init_mcp_surface();init_event_dialect();init_event_gates()}});import{generateWebhookMessageId}from"@frontmcp/utils";function accessRevokedError(dialect){return{code:EVENT_DIALECTS[dialect].errorCodes.forbidden,message:"Forbidden",data:{reason:"Access revoked"}}}async function terminateEventSubscription(args){const{subscriptions,outbox,metrics,logger,subscription,error}=args;const removed=await subscriptions?.store.delete(subscription.id);if(!removed||!subscriptions||!outbox)return;await subscriptions.notifyUnsubscribed(removed,"terminated");metrics?.count("terminated",removed.eventName);logger.warn(`Subscription ${removed.id} to event "${removed.eventName}" is terminated: ${error.message} (${String(error.data["reason"])})`);if(!EVENT_DIALECTS[removed.dialect].sendsControlEnvelopes)return;const{url,secret,previousSecret,previousSecretUntil}=removed.delivery;await outbox.enqueue({kind:"terminated",subscriptionId:removed.id,eventName:removed.eventName,body:JSON.stringify({type:"terminated",error}),webhookId:generateWebhookMessageId("terminated"),target:{url,secret,previousSecret,previousSecretUntil}})}var init_event_subscription_termination=__esm({"libs/sdk/src/event/subscription/event-subscription-termination.ts"(){"use strict";init_event_dialect()}});import{internalZ as z130}from"@frontmcp/lazy-zod";import{EventOccurrenceSchema as EventOccurrenceSchema3}from"@frontmcp/protocol";import{sha256Hex as sha256Hex24}from"@frontmcp/utils";function eventWebhookIdOf(subscriptionId,eventId){return`msg_${sha256Hex24(`${subscriptionId}\0${eventId}`).slice(0,32)}`}function isNamed(wanted,actual){if(wanted===void 0)return true;if(actual===void 0)return false;return Array.isArray(wanted)?wanted.includes(actual):wanted===actual}function isInAudience(audience,subscriber){if(!audience)return true;const{any:anyOf,all:allOf}=audience.roles??{};const hasOneOf=!anyOf||anyOf.some(role=>subscriber.roles.includes(role));const hasEveryOf=!allOf||allOf.every(role=>subscriber.roles.includes(role));return isNamed(audience.sub,subscriber.sub)&&isNamed(audience.tenantId,subscriber.tenantId)&&hasOneOf&&hasEveryOf}var EVENT_DELIVERY_MAX_BYTES,audienceValueSchema,inputSchema33,outputSchema32,stateSchema35,plan40,name40,Stage40,encoder9,EventPublishFlow;var init_event_publish_flow=__esm({"libs/sdk/src/event/flows/event-publish.flow.ts"(){"use strict";init_channel_utils();init_common();init_errors();init_event_channel();init_event_dialect();init_event_reauthorization();init_event_subscription_termination();EVENT_DELIVERY_MAX_BYTES=262144;audienceValueSchema=z130.union([z130.string(),z130.array(z130.string())]);inputSchema33=z130.object({occurrence:EventOccurrenceSchema3,subscriptionId:z130.string().optional(),audience:z130.object({sub:audienceValueSchema.optional(),tenantId:audienceValueSchema.optional(),roles:z130.object({any:z130.array(z130.string()).optional(),all:z130.array(z130.string()).optional()}).optional()}).optional()});outputSchema32=z130.object({eventId:z130.string(),matched:z130.number().int().nonnegative()});stateSchema35=z130.object({event:z130.instanceof(EventEntry),context:z130.any(),subscriptions:z130.array(z130.any()),deliveries:z130.array(z130.any()),buffered:z130.any()});plan40={pre:["validate","bufferOccurrence","pushToStreams"],execute:["loadSubscriptions","dropInactive","filterByAudience","reauthorize","match","transform","enforceBodyLimit","enqueue","bridgeToBus","notifyChannelSessions"],post:["buildResult"]};name40="events:publish";({Stage:Stage40}=FlowHooksOf(name40));encoder9=new TextEncoder;EventPublishFlow=class extends FlowBase{logger=this.scopeLogger.child("EventPublishFlow");get events(){return this.scope.events}async validate(){const eventName=this.input.occurrence.name;const event=this.events.findByName(eventName);if(!event)throw new EventNotRegisteredError(eventName);this.events.metrics?.count("published",eventName);this.state.set({event,context:event.create({}),deliveries:[]})}async bufferOccurrence(){const{occurrence,audience,subscriptionId}=this.input;const modes=this.events.deliveryModesOf(this.state.required.event);if(!modes.includes("poll")&&!modes.includes("push"))return;this.state.set("buffered",this.events.buffer?.append(occurrence,audience,subscriptionId))}async pushToStreams(){const{buffered}=this.state;if(buffered)await this.events.streams?.publish(buffered)}async loadSubscriptions(){const{subscriptions,outbox}=this.events;if(!subscriptions||!outbox){this.state.set("subscriptions",[]);return}subscriptions.sweepIfDue();await outbox.sweepIfDue();const{subscriptionId,occurrence}=this.input;if(subscriptionId===void 0){this.state.set("subscriptions",await subscriptions.store.listByEvent(occurrence.name));return}const targeted=await subscriptions.store.get(subscriptionId);this.state.set("subscriptions",targeted?.eventName===occurrence.name?[targeted]:[])}async dropInactive(){const{suspendedTtlMs}=this.events.config.subscriptions;const now=Date.now();const active=[];for(const subscription of this.state.required.subscriptions){if(subscription.active){active.push(subscription);continue}const suspendedFor=now-(subscription.status.suspendedSince??now);if(subscription.expiresAt===null&&suspendedFor>suspendedTtlMs){const codes=EVENT_DIALECTS[subscription.dialect].errorCodes;await this.terminate(subscription,{code:codes.callbackEndpointError,message:"CallbackEndpointError",data:{reason:subscription.status.lastError??"http_5xx"}})}}this.state.set("subscriptions",active)}async filterByAudience(){const{audience}=this.input;const inAudience=this.state.required.subscriptions.filter(subscription=>isInAudience(audience,subscription.subscriber));this.state.set("subscriptions",inAudience)}async reauthorize(){const{event,context}=this.state.required;if(!hasReauthorization(this.scope,event,context.authorize!==void 0))return;const{subscriptions}=this.events;const{reauthorizeEveryMs}=this.events.config.subscriptions;const now=Date.now();const allowed=[];for(const subscription of this.state.required.subscriptions){if(now-subscription.lastAuthorizedAt<=reauthorizeEveryMs){allowed.push(subscription);continue}const{subscriber,arguments:subscriptionArguments}=subscription;const check=await reauthorizeSubscriber({scope:this.scope,event,subscriber,arguments:subscriptionArguments});if(check.outcome==="granted"){await subscriptions?.store.update(subscription.id,{lastAuthorizedAt:now});allowed.push(subscription);continue}if(check.outcome==="failed"){this.logger.warn(`reauthorize: the access of subscription ${subscription.id} could not be checked`,check.error);continue}await this.terminate(subscription,accessRevokedError(subscription.dialect))}this.state.set("subscriptions",allowed)}async match(){const{context,subscriptions}=this.state.required;const{occurrence}=this.input;const deliveries=[];for(const subscription of subscriptions){try{const matches=await context.match?.(occurrence,subscription.arguments,subscription.subscriber)??true;if(matches)deliveries.push({subscription,occurrence})}catch(error){this.logger.warn(`match: event "${occurrence.name}" failed for subscription ${subscription.id}`,error)}}this.state.set("deliveries",deliveries)}async transform(){const{context,deliveries}=this.state.required;if(!context.transform)return;const shaped=[];for(const delivery of deliveries){const{subscription,occurrence}=delivery;try{const transformed=await context.transform(occurrence,subscription.arguments,subscription.subscriber);shaped.push({subscription,occurrence:EventOccurrenceSchema3.parse(transformed)})}catch(error){this.logger.warn(`transform: event "${occurrence.name}" failed for subscription ${subscription.id}`,error)}}this.state.set("deliveries",shaped)}async enforceBodyLimit(){const fitting=[];for(const delivery of this.state.required.deliveries){const body=JSON.stringify(delivery.occurrence);const bytes=encoder9.encode(body).byteLength;if(bytes<=EVENT_DELIVERY_MAX_BYTES){fitting.push({...delivery,body});continue}this.events.metrics?.count("dropped",delivery.occurrence.name);this.logger.warn(`enforceBodyLimit: event "${delivery.occurrence.name}" is ${bytes} bytes for subscription ${delivery.subscription.id}, over the ${EVENT_DELIVERY_MAX_BYTES} byte limit; it is not delivered`)}this.state.set("deliveries",fitting)}async enqueue(){const{outbox}=this.events;const{deliveries}=this.state.required;if(!outbox)return;const queued=deliveries.map(({subscription,occurrence,body})=>{const usesEventId=EVENT_DIALECTS[subscription.dialect].webhookId==="eventId";return outbox.enqueue({kind:"event",subscriptionId:subscription.id,eventName:occurrence.name,body,webhookId:usesEventId?occurrence.eventId:eventWebhookIdOf(subscription.id,occurrence.eventId)})});await Promise.all(queued);this.events.metrics?.count("matched",this.input.occurrence.name,deliveries.length)}async bridgeToBus(){if(!this.events.config.bridge)return;const{occurrence,audience,subscriptionId}=this.input;const forSomeOwners=audience!==void 0||subscriptionId!==void 0;this.scope.channelEventBus?.emit(occurrence.name,occurrence,{forSomeOwners})}async notifyChannelSessions(){const{event}=this.state.required;const{occurrence,subscriptionId}=this.input;if(subscriptionId!==void 0||!this.events.sendsToChannelSessions(event))return;let message;try{message=eventChannelMessage(event,occurrence)}catch(error){this.logger.warn(`notifyChannelSessions: the channel option of event "${occurrence.name}" failed`,error);return}let notified=0;for(const session of this.scope.notifications.getChannelCapableSessions()){const wasSent=await this.notifyChannelSession(session,message);if(wasSent)notified+=1}this.events.metrics?.count("notified",occurrence.name,notified);this.logger.verbose(`notifyChannelSessions: event "${occurrence.name}" was sent to ${notified} session(s)`)}async buildResult(){this.respond({eventId:this.input.occurrence.eventId,matched:this.state.required.deliveries.length})}async notifyChannelSession(session,message){const{event,context}=this.state.required;const{occurrence,audience}=this.input;try{const reader=channelSessionReader(this.scope,event,session);if(!reader||!isInAudience(audience,reader.subscriber))return false;if(hasReauthorization(this.scope,event,context.authorize!==void 0)){const{subscriber}=reader;const authInfo=session.caller;const access=await reauthorizeSubscriber({scope:this.scope,event,subscriber,arguments:{},authInfo});if(access.outcome==="failed")throw access.error;if(access.outcome==="refused")return false}const isThisSession=registered=>registered.sessionId===session.sessionId;this.scope.notifications.sendCustomNotification(CHANNEL_NOTIFICATION_METHOD,message,isThisSession);return true}catch(error){const sessionLabel=session.sessionId.slice(0,20);this.logger.warn(`notifyChannelSessions: event "${occurrence.name}" was not sent to session ${sessionLabel}...`,error);return false}}async terminate(subscription,error){const{subscriptions,outbox,metrics}=this.events;await terminateEventSubscription({subscriptions,outbox,metrics,logger:this.logger,subscription,error})}};__decorateClass([Stage40("validate")],EventPublishFlow.prototype,"validate",1);__decorateClass([Stage40("bufferOccurrence")],EventPublishFlow.prototype,"bufferOccurrence",1);__decorateClass([Stage40("pushToStreams")],EventPublishFlow.prototype,"pushToStreams",1);__decorateClass([Stage40("loadSubscriptions")],EventPublishFlow.prototype,"loadSubscriptions",1);__decorateClass([Stage40("dropInactive")],EventPublishFlow.prototype,"dropInactive",1);__decorateClass([Stage40("filterByAudience")],EventPublishFlow.prototype,"filterByAudience",1);__decorateClass([Stage40("reauthorize")],EventPublishFlow.prototype,"reauthorize",1);__decorateClass([Stage40("match")],EventPublishFlow.prototype,"match",1);__decorateClass([Stage40("transform")],EventPublishFlow.prototype,"transform",1);__decorateClass([Stage40("enforceBodyLimit")],EventPublishFlow.prototype,"enforceBodyLimit",1);__decorateClass([Stage40("enqueue")],EventPublishFlow.prototype,"enqueue",1);__decorateClass([Stage40("bridgeToBus")],EventPublishFlow.prototype,"bridgeToBus",1);__decorateClass([Stage40("notifyChannelSessions")],EventPublishFlow.prototype,"notifyChannelSessions",1);__decorateClass([Stage40("buildResult")],EventPublishFlow.prototype,"buildResult",1);EventPublishFlow=__decorateClass([FrontMcpFlow({name:name40,plan:plan40,inputSchema:inputSchema33,outputSchema:outputSchema32,access:"public"})],EventPublishFlow)}});import{internalZ as z131}from"@frontmcp/lazy-zod";import{EventOccurrenceSchema as EventOccurrenceSchema4,PollEventsRequestSchema as PollEventsRequestSchema2,PollEventsResultSchema as PollEventsResultSchema2}from"@frontmcp/protocol";var inputSchema34,outputSchema33,stateSchema36,plan41,name41,Stage41,EventPollFlow;var init_event_poll_flow=__esm({"libs/sdk/src/event/flows/event-poll.flow.ts"(){"use strict";init_common();init_errors();init_event_dialect();init_event_gates();init_event_publisher();init_event_poll_leases();init_event_publish_flow();inputSchema34=z131.object({request:PollEventsRequestSchema2,ctx:z131.unknown()});outputSchema33=PollEventsResultSchema2;stateSchema36=z131.object({authInfo:z131.any(),dialect:z131.enum(["sep-3415","sketch"]),event:z131.instanceof(EventEntry),reader:z131.any(),arguments:z131.record(z131.string(),z131.unknown()),context:z131.any(),subscription:z131.any(),result:z131.any()});plan41={pre:["parseInput","resolveDialect","findEvent","resolveReader","checkEntryAuthorities","validateArguments","authorize"],execute:["renewLease","readEvents"],post:["buildResult"],finalize:["finalize"]};name41="events:poll";({Stage:Stage41}=FlowHooksOf(name41));EventPollFlow=class extends FlowBase{logger=this.scopeLogger.child("EventPollFlow");get events(){return this.scope.events}get codes(){return EVENT_DIALECTS[this.state.required.dialect].errorCodes}async parseInput(){const authInfo=this.input.ctx?.authInfo??{};this.state.set("authInfo",authInfo)}async resolveDialect(){const platform=callerPlatformOf(this.scope,this.state.required.authInfo,this.tryGetContext()?.platformType);this.state.set("dialect",resolveEventDialect(this.events.config.compat,platform))}async findEvent(){const eventName=this.input.request.params.name;this.state.set("event",offeredEventOf(this.events,eventName,"poll",this.input.ctx,this.codes))}async resolveReader(){const{authInfo,event}=this.state.required;this.state.set("reader",eventReaderOf(this.scope,authInfo,event.name,this.codes))}async checkEntryAuthorities(){const{event,authInfo}=this.state.required;const sentArguments=this.input.request.params.arguments??{};await assertEventAuthorities(this.scope,event,authInfo,sentArguments,this.codes)}async validateArguments(){const{event,reader}=this.state.required;const parsedArguments=parsedEventArguments(event,this.input.request.params.arguments);this.state.set({arguments:parsedArguments,subscription:readerSubscriptionOf(reader,"poll",event.name,parsedArguments)})}async authorize(){const{event,authInfo,reader}=this.state.required;const context=event.create(authInfo);await assertEventAuthorizes(context,event.name,this.state.required.arguments,reader.subscriber,this.codes);this.state.set("context",context)}async renewLease(){await this.renewLeaseFor(this.events.config.poll.nextPollMs)}async readEvents(){const{context}=this.state.required;const result=context.check?await this.readFromCheck():await this.readFromBuffer();this.state.set("result",result);if(result.nextPollMs!==void 0&&result.nextPollMs>this.events.config.poll.nextPollMs){await this.renewLeaseFor(result.nextPollMs)}}async buildResult(){this.respond(this.state.required.result)}async finalize(){this.logger.verbose("finalize")}get limit(){const serverLimit=this.events.config.poll.maxEvents;return Math.min(this.input.request.params.maxEvents??serverLimit,serverLimit)}replayFloor(now){const{cursor,maxAgeMs}=this.input.request.params;const hasCursor=cursor!==void 0&&cursor!==null;return hasCursor&&maxAgeMs!==void 0?now-maxAgeMs:void 0}async renewLeaseFor(nextPollMs){const leases=this.events.pollLeases;const{context,subscription,reader}=this.state.required;if(!context.onSubscribe&&!context.onUnsubscribe)return;if(!leases.has(subscription.id)&&leases.isFull(reader.principalKey)){const{maxPerPrincipal}=this.events.config.subscriptions;throw new EventResourceExhaustedError(this.codes,"pollLeases",maxPerPrincipal)}await leases.renew({subscription,arguments:this.state.required.arguments,principalKey:reader.principalKey,leaseMs:pollLeaseMs(nextPollMs),context})}async readFromCheck(){const{context,event}=this.state.required;const{cursor=null,maxAgeMs}=this.input.request.params;const now=Date.now();const floor=this.replayFloor(now);const limits={maxEvents:this.limit,...floor!==void 0&&{maxAgeMs}};const check=context.check;const checked=await check.call(context,this.state.required.arguments,cursor,limits);if(checked.events.length>this.limit){throw new InvalidEventPublishError(event.name,`check() returned ${checked.events.length} events, more than limits.maxEvents (${this.limit})`)}const events=[];let skippedOldEvents=false;for(const item of checked.events){const timestamp=item.timestamp??new Date(now).toISOString();if(floor!==void 0&&Date.parse(timestamp)<floor){skippedOldEvents=true;continue}events.push({eventId:item.eventId??newEventId(),name:event.name,timestamp,data:this.checkedPayload(item.data)})}return{events,cursor:checked.cursor,truncated:checked.truncated===true||skippedOldEvents,hasMore:checked.hasMore===true,nextPollMs:checked.nextPollMs??this.events.config.poll.nextPollMs}}checkedPayload(data){const{event}=this.state.required;try{return event.parsePayload(data)}catch(error){const problem2=error instanceof Error?error.message:String(error);throw new InvalidEventPublishError(event.name,`check() returned data that does not match payloadSchema: ${problem2}`)}}async readFromBuffer(){const buffer=this.events.buffer;const{cursor}=this.input.request.params;const nextPollMs=this.events.config.poll.nextPollMs;if(cursor===void 0||cursor===null){return{events:[],cursor:buffer.currentCursor(),truncated:false,hasMore:false,nextPollMs}}const read=buffer.read(this.state.required.event.name,cursor);const endCursor=buffer.currentCursor();const floor=this.replayFloor(Date.now());const events=[];let truncated=read.truncated;let lastExamined;for(const buffered of read.events){if(floor!==void 0&&buffered.publishedAt<floor){truncated=true;lastExamined=buffered;continue}const occurrence=await this.occurrenceFor(buffered);if(occurrence&&events.length===this.limit){const resumeCursor=lastExamined?buffer.cursorAt(lastExamined.sequence):cursor;return{events,cursor:resumeCursor,truncated,hasMore:true,nextPollMs}}if(occurrence)events.push(occurrence);lastExamined=buffered}return{events,cursor:endCursor,truncated,hasMore:false,nextPollMs}}async occurrenceFor(buffered){const{context,reader,subscription}=this.state.required;const{occurrence}=buffered;if(buffered.subscriptionId!==void 0&&buffered.subscriptionId!==subscription.id)return void 0;if(!isInAudience(buffered.audience,reader.subscriber))return void 0;const subscriptionArguments=this.state.required.arguments;try{const matches=await context.match?.(occurrence,subscriptionArguments,reader.subscriber)??true;if(!matches)return void 0;if(!context.transform)return occurrence;const transformed=await context.transform(occurrence,subscriptionArguments,reader.subscriber);return EventOccurrenceSchema4.parse(transformed)}catch(error){this.logger.warn(`readEvents: event "${occurrence.name}" failed for poll subscription ${subscription.id}`,error);return void 0}}};__decorateClass([Stage41("parseInput")],EventPollFlow.prototype,"parseInput",1);__decorateClass([Stage41("resolveDialect")],EventPollFlow.prototype,"resolveDialect",1);__decorateClass([Stage41("findEvent")],EventPollFlow.prototype,"findEvent",1);__decorateClass([Stage41("resolveReader")],EventPollFlow.prototype,"resolveReader",1);__decorateClass([Stage41("checkEntryAuthorities")],EventPollFlow.prototype,"checkEntryAuthorities",1);__decorateClass([Stage41("validateArguments")],EventPollFlow.prototype,"validateArguments",1);__decorateClass([Stage41("authorize")],EventPollFlow.prototype,"authorize",1);__decorateClass([Stage41("renewLease")],EventPollFlow.prototype,"renewLease",1);__decorateClass([Stage41("readEvents")],EventPollFlow.prototype,"readEvents",1);__decorateClass([Stage41("buildResult")],EventPollFlow.prototype,"buildResult",1);__decorateClass([Stage41("finalize")],EventPollFlow.prototype,"finalize",1);EventPollFlow=__decorateClass([FrontMcpFlow({name:name41,plan:plan41,inputSchema:inputSchema34,outputSchema:outputSchema33,access:"authorized"})],EventPollFlow)}});import{EventOccurrenceSchema as EventOccurrenceSchema5,EVENTS_NOTIFICATIONS as EVENTS_NOTIFICATIONS2,MCP_20260728_META as MCP_20260728_META9}from"@frontmcp/protocol";var MAX_QUEUED_NOTIFICATIONS,EventStream;var init_event_stream=__esm({"libs/sdk/src/event/stream/event-stream.ts"(){"use strict";init_event_publisher();init_event_publish_flow();MAX_QUEUED_NOTIFICATIONS=1e3;EventStream=class{constructor(options){this.options=options;this.cursor=options.cursor??null;this.delivering=options.buffer?new Promise(resolve4=>this.releaseDelivery=resolve4):Promise.resolve();if(options.signal?.aborted)this.close();else options.signal?.addEventListener("abort",()=>this.close(),{once:true})}options;queue=[];closeListeners=[];wake;closed=false;cursor;lastAuthorizedAt=Date.now();accessUnchecked=false;withheld=false;heartbeatTimer;checkTimer;delivering;releaseDelivery=()=>void 0;lastSequence=0;get subscription(){return this.options.subscription}get eventName(){return this.options.event.name}get principalKey(){return this.options.reader.principalKey}get isClosed(){return this.closed}async open(){const{context,heartbeatMs}=this.options;if(context.check){await this.openOnCheck()}else{await this.openOnBuffer()}this.releaseDelivery();if(this.closed)return;this.heartbeatTimer=setInterval(()=>void this.beat(),heartbeatMs);this.heartbeatTimer.unref?.()}offer(buffered){this.delivering=this.delivering.then(()=>this.deliver(buffered)).catch(error=>this.options.logger.warn(`An event was not delivered on stream ${this.subscription.id}`,error));return this.delivering}terminate(error){if(this.closed)return;this.push(EVENTS_NOTIFICATIONS2.terminated,{error});this.close()}close(){if(this.closed)return;this.closed=true;this.releaseDelivery();if(this.heartbeatTimer)clearInterval(this.heartbeatTimer);if(this.checkTimer)clearTimeout(this.checkTimer);for(const listener of this.closeListeners.splice(0))listener();this.wake?.()}onClose(listener){if(this.closed)listener();else this.closeListeners.push(listener)}[Symbol.asyncIterator](){return{next:()=>this.nextNotification(),return:async()=>{this.close();return{value:void 0,done:true}}}}async nextNotification(){for(;;){const queued=this.queue.shift();if(queued)return{value:queued,done:false};if(this.closed)return{value:void 0,done:true};await new Promise(resolve4=>this.wake=resolve4);this.wake=void 0}}async openOnBuffer(){const{buffer,cursor,maxAgeMs}=this.options;if(!buffer){this.pushActive(false);return}if(cursor===void 0||cursor===null){this.cursor=buffer.currentCursor();this.lastSequence=buffer.currentSequence();this.pushActive(false);return}const read=buffer.read(this.eventName,cursor);const endCursor=buffer.currentCursor();const endSequence=buffer.currentSequence();const floor=maxAgeMs===void 0?void 0:Date.now()-maxAgeMs;const replayed=read.events.filter(buffered=>floor===void 0||buffered.publishedAt>=floor);this.cursor=read.events.length===0?endCursor:cursor;this.pushActive(read.truncated||replayed.length<read.events.length);for(const buffered of replayed)await this.deliver(buffered);this.cursor=endCursor;this.lastSequence=endSequence}async deliver(buffered){if(this.closed||buffered.sequence<=this.lastSequence)return;if(this.accessUnchecked){this.withheld=true;return}this.lastSequence=buffered.sequence;const occurrence=await this.occurrenceFor(buffered);if(!occurrence)return;const{buffer}=this.options;if(buffer)this.cursor=buffer.cursorAt(buffered.sequence);this.pushEvent(occurrence)}async openOnCheck(){const checked=await this.check();this.pushActive(checked?.truncated===true);if(checked)this.pushChecked(checked);this.scheduleCheck(checked?.nextPollMs)}async check(){const{context,checkMaxEvents,maxAgeMs}=this.options;const check=context.check;const limits={maxEvents:checkMaxEvents,...this.cursor!==null&&maxAgeMs!==void 0&&{maxAgeMs}};try{const checked=await check.call(context,this.options.arguments,this.cursor,limits);this.cursor=checked.cursor;return checked}catch(error){this.options.logger.warn(`check() of event "${this.eventName}" failed for stream ${this.subscription.id}`,error);this.push(EVENTS_NOTIFICATIONS2.error,{error:{code:-32603,message:"UpstreamError",data:{reason:"check() failed"}}});return void 0}}scheduleCheck(nextPollMs){if(this.closed)return;this.checkTimer=setTimeout(()=>void this.runCheck(),nextPollMs??this.options.checkIntervalMs);this.checkTimer.unref?.()}async runCheck(){if(this.accessUnchecked){this.scheduleCheck(void 0);return}const checked=await this.check();if(checked?.truncated)this.pushActive(true);if(checked)this.pushChecked(checked);this.scheduleCheck(checked?.hasMore?0:checked?.nextPollMs)}pushChecked(checked){const{event}=this.options;for(const item of checked.events){try{this.pushEvent({eventId:item.eventId??newEventId(),name:event.name,timestamp:item.timestamp??new Date().toISOString(),data:event.parsePayload(item.data)})}catch(error){this.options.logger.warn(`check() of event "${event.name}" returned data that is not its payload`,error)}}}async occurrenceFor(buffered){const{context,reader,subscription}=this.options;const{occurrence}=buffered;if(buffered.subscriptionId!==void 0&&buffered.subscriptionId!==subscription.id)return void 0;if(!isInAudience(buffered.audience,reader.subscriber))return void 0;try{const matches=await context.match?.(occurrence,this.options.arguments,reader.subscriber)??true;if(!matches)return void 0;if(!context.transform)return occurrence;const transformed=await context.transform(occurrence,this.options.arguments,reader.subscriber);return EventOccurrenceSchema5.parse(transformed)}catch(error){this.options.logger.warn(`Event "${occurrence.name}" failed for stream ${subscription.id}`,error);return void 0}}async beat(){if(this.closed)return;const now=Date.now();if(now-this.lastAuthorizedAt>this.options.reauthorizeEveryMs){const check=await this.options.reauthorize().catch(error=>({outcome:"failed",error}));if(check.outcome==="refused"){this.terminate(this.options.accessRevoked);return}if(check.outcome==="failed"){this.accessUnchecked=true;this.options.logger.warn(`The access of stream ${this.subscription.id} could not be checked`,check.error)}else{this.lastAuthorizedAt=now;this.resumeAfterCheck()}}this.push(EVENTS_NOTIFICATIONS2.heartbeat,{cursor:this.cursor})}resumeAfterCheck(){if(!this.accessUnchecked)return;this.accessUnchecked=false;if(this.withheld)this.pushActive(true);this.withheld=false}pushActive(truncated){this.push(EVENTS_NOTIFICATIONS2.active,{cursor:this.cursor,truncated})}pushEvent(occurrence){this.push(EVENTS_NOTIFICATIONS2.event,{...occurrence,cursor:this.cursor})}push(method,params){if(this.closed)return;const meta={[MCP_20260728_META9.subscriptionId]:this.options.requestId};if(this.queue.length>=MAX_QUEUED_NOTIFICATIONS){this.queue.length=0;this.queue.push({method:EVENTS_NOTIFICATIONS2.active,params:{cursor:this.cursor,truncated:true,_meta:meta}})}this.queue.push({method,params:{...params,_meta:meta}});this.wake?.()}}}});import{internalZ as z132}from"@frontmcp/lazy-zod";import{StreamEventsRequestSchema as StreamEventsRequestSchema3}from"@frontmcp/protocol";var inputSchema35,outputSchema34,stateSchema37,plan42,name42,Stage42,EventStreamFlow;var init_event_stream_flow=__esm({"libs/sdk/src/event/flows/event-stream.flow.ts"(){"use strict";init_common();init_errors();init_event_dialect();init_event_gates();init_event_reauthorization();init_event_stream();inputSchema35=z132.object({request:StreamEventsRequestSchema3,ctx:z132.unknown(),requestId:z132.union([z132.string(),z132.number()]),signal:z132.any().optional()});outputSchema34=z132.object({stream:z132.instanceof(EventStream)});stateSchema37=z132.object({authInfo:z132.any(),dialect:z132.enum(["sep-3415","sketch"]),event:z132.instanceof(EventEntry),reader:z132.any(),arguments:z132.record(z132.string(),z132.unknown()),context:z132.any(),subscription:z132.any(),stream:z132.instanceof(EventStream)});plan42={pre:["parseInput","resolveDialect","findEvent","resolveReader","checkEntryAuthorities","validateArguments","authorize"],execute:["openStream"],post:["buildResult"],finalize:["finalize"]};name42="events:stream";({Stage:Stage42}=FlowHooksOf(name42));EventStreamFlow=class extends FlowBase{logger=this.scopeLogger.child("EventStreamFlow");get events(){return this.scope.events}get codes(){return EVENT_DIALECTS[this.state.required.dialect].errorCodes}async parseInput(){const authInfo=this.input.ctx?.authInfo??{};this.state.set("authInfo",authInfo)}async resolveDialect(){const platform=callerPlatformOf(this.scope,this.state.required.authInfo,this.tryGetContext()?.platformType);this.state.set("dialect",resolveEventDialect(this.events.config.compat,platform))}async findEvent(){const eventName=this.input.request.params.name;this.state.set("event",offeredEventOf(this.events,eventName,"push",this.input.ctx,this.codes))}async resolveReader(){const{authInfo,event}=this.state.required;this.state.set("reader",eventReaderOf(this.scope,authInfo,event.name,this.codes))}async checkEntryAuthorities(){const{event,authInfo}=this.state.required;const sentArguments=this.input.request.params.arguments??{};await assertEventAuthorities(this.scope,event,authInfo,sentArguments,this.codes)}async validateArguments(){const{event,reader}=this.state.required;const parsedArguments=parsedEventArguments(event,this.input.request.params.arguments);this.state.set({arguments:parsedArguments,subscription:readerSubscriptionOf(reader,"push",event.name,parsedArguments)})}async authorize(){const{event,authInfo,reader}=this.state.required;const context=event.create(authInfo);await assertEventAuthorizes(context,event.name,this.state.required.arguments,reader.subscriber,this.codes);this.state.set("context",context)}async openStream(){const streams=this.events.streams;const{event,context,reader,subscription,authInfo}=this.state.required;const{config}=this.events;const subscriptionArguments=this.state.required.arguments;const codes=this.codes;const stream=new EventStream({requestId:this.input.requestId,event,context,reader,subscription,arguments:subscriptionArguments,cursor:this.input.request.params.cursor,maxAgeMs:this.input.request.params.maxAgeMs,buffer:context.check?void 0:this.events.buffer,heartbeatMs:config.push.heartbeatMs,checkIntervalMs:config.poll.nextPollMs,checkMaxEvents:config.poll.maxEvents,reauthorizeEveryMs:config.subscriptions.reauthorizeEveryMs,reauthorize:()=>reauthorizeSubscriber({scope:this.scope,event,subscriber:reader.subscriber,arguments:subscriptionArguments,authInfo}),accessRevoked:{code:codes.forbidden,message:"Forbidden",data:{reason:"Access revoked"}},signal:this.input.signal,logger:this.logger});if(!streams.reserve(stream)){stream.close();throw new EventResourceExhaustedError(this.codes,"streams",config.subscriptions.maxPerPrincipal)}try{await context.onSubscribe?.(subscriptionArguments,subscription)}catch(error){stream.close();throw error}stream.onClose(()=>{const warn=error=>this.logger.warn(`onUnsubscribe of event "${event.name}" failed for stream ${subscription.id}`,error);try{Promise.resolve(context.onUnsubscribe?.(subscriptionArguments,subscription,"closed")).catch(warn)}catch(error){warn(error)}});streams.add(stream);try{await stream.open()}catch(error){stream.close();throw error}this.state.set("stream",stream);this.logger.verbose(`openStream: stream ${subscription.id} opened for event "${event.name}"`)}async buildResult(){this.respond({stream:this.state.required.stream})}async finalize(){this.logger.verbose("finalize")}};__decorateClass([Stage42("parseInput")],EventStreamFlow.prototype,"parseInput",1);__decorateClass([Stage42("resolveDialect")],EventStreamFlow.prototype,"resolveDialect",1);__decorateClass([Stage42("findEvent")],EventStreamFlow.prototype,"findEvent",1);__decorateClass([Stage42("resolveReader")],EventStreamFlow.prototype,"resolveReader",1);__decorateClass([Stage42("checkEntryAuthorities")],EventStreamFlow.prototype,"checkEntryAuthorities",1);__decorateClass([Stage42("validateArguments")],EventStreamFlow.prototype,"validateArguments",1);__decorateClass([Stage42("authorize")],EventStreamFlow.prototype,"authorize",1);__decorateClass([Stage42("openStream")],EventStreamFlow.prototype,"openStream",1);__decorateClass([Stage42("buildResult")],EventStreamFlow.prototype,"buildResult",1);__decorateClass([Stage42("finalize")],EventStreamFlow.prototype,"finalize",1);EventStreamFlow=__decorateClass([FrontMcpFlow({name:name42,plan:plan42,inputSchema:inputSchema35,outputSchema:outputSchema34,access:"authorized"})],EventStreamFlow)}});import{canonicalJson as canonicalJson4,getRuntimeContext as getRuntimeContext27,sha256Hex as sha256Hex25}from"@frontmcp/utils";function clamp(value,lowest,highest){return Math.min(Math.max(value,lowest),highest)}function subscriptionRefOf(record){return{id:record.id,name:record.eventName,mode:record.delivery.mode,subscriber:record.subscriber}}function isoTimeOf(time){return time===void 0?null:new Date(time).toISOString()}function deliveryStatusOf(record){const{lastDeliveryAt,lastError,failedSince}=record.status;return{active:record.active,lastDeliveryAt:isoTimeOf(lastDeliveryAt),lastError:lastError??null,failedSince:isoTimeOf(failedSince)}}var SUBSCRIPTION_SWEEP_INTERVAL_MS,EventSubscriptions;var init_event_subscriptions=__esm({"libs/sdk/src/event/subscription/event-subscriptions.ts"(){"use strict";SUBSCRIPTION_SWEEP_INTERVAL_MS=6e4;EventSubscriptions=class{constructor(options){this.options=options;this.store=options.store;this.verifier=options.verifier;this.logger=options.logger.child("EventSubscriptions")}options;store;verifier;logger;sweepTimer;lastSweepAt=0;get settings(){return this.options.settings}identityOf(principalKey,url,eventName,args){const canonicalKey=canonicalJson4({principalKey,url,name:eventName,arguments:args});return{id:`sub_${sha256Hex25(canonicalKey).slice(0,32)}`,argumentsKey:canonicalJson4(args)}}grantExpiry(event,requestedTtlMs,now){const{defaultTtlMs,maxTtlMs,minTtlMs,allowNoExpiry}=this.options.settings;const eventTtl=event.metadata.ttl;const longestMs=Math.min(eventTtl?.maxMs??maxTtlMs,maxTtlMs);const shortestMs=Math.min(minTtlMs,longestMs);if(requestedTtlMs===null){const grantsNoExpiry=allowNoExpiry&&this.options.durable&&eventTtl?.maxMs===void 0;return grantsNoExpiry?null:now+longestMs}if(requestedTtlMs===void 0){return now+clamp(eventTtl?.defaultMs??defaultTtlMs,shortestMs,longestMs)}return now+clamp(requestedTtlMs,shortestMs,longestMs)}rotatedDelivery(current,url,secret,now){const delivery={mode:"webhook",url,secret};if(!current)return delivery;if(current.secret!==secret){return{...delivery,previousSecret:current.secret,previousSecretUntil:now+this.options.rotationGraceMs}}const graceIsRunning=current.previousSecret!==void 0&&(current.previousSecretUntil??0)>now;if(!graceIsRunning)return delivery;return{...delivery,previousSecret:current.previousSecret,previousSecretUntil:current.previousSecretUntil}}async notifySubscribed(event,record,authInfo){await event.create(authInfo).onSubscribe?.(record.arguments,subscriptionRefOf(record))}async notifyUnsubscribed(record,reason,authInfo={}){const event=this.options.events.findByName(record.eventName);if(!event)return;try{await event.create(authInfo).onUnsubscribe?.(record.arguments,subscriptionRefOf(record),reason)}catch(error){this.logger.warn(`onUnsubscribe of event "${record.eventName}" failed for subscription ${record.id}`,error)}}async expire(id,now=Date.now()){const removed=await this.store.deleteExpired(id,now);if(removed)await this.notifyUnsubscribed(removed,"expired")}async sweep(now=Date.now()){this.lastSweepAt=now;const expired=await this.store.listExpired(now);for(const record of expired){await this.expire(record.id,now)}}sweepIfDue(now=Date.now()){if(now-this.lastSweepAt<SUBSCRIPTION_SWEEP_INTERVAL_MS)return;this.sweepInBackground(now)}start(){const{runtime,deployment}=getRuntimeContext27();if(deployment==="serverless"||runtime==="edge"||runtime==="browser")return;this.sweepTimer=setInterval(()=>this.sweepInBackground(Date.now()),SUBSCRIPTION_SWEEP_INTERVAL_MS);this.sweepTimer.unref?.()}async close(){if(this.sweepTimer)clearInterval(this.sweepTimer);this.sweepTimer=void 0;await this.store.close()}sweepInBackground(now){this.sweep(now).catch(error=>this.logger.warn("The subscription expiry sweep failed",error))}}}});import{internalZ as z133}from"@frontmcp/lazy-zod";import{SubscribeEventRequestSchema as SubscribeEventRequestSchema2,SubscribeEventResultSchema as SubscribeEventResultSchema2}from"@frontmcp/protocol";import{isStandardWebhookSecret,validateOutboundUrl}from"@frontmcp/utils";function reactivatedStatus(status={}){const{failures:_failures,suspendedSince:_suspendedSince,...kept}=status;return kept}var inputSchema36,outputSchema35,stateSchema38,plan43,name43,Stage43,URL_PROBLEMS,EventSubscribeFlow;var init_event_subscribe_flow=__esm({"libs/sdk/src/event/flows/event-subscribe.flow.ts"(){"use strict";init_common();init_availability();init_errors();init_event_dialect();init_event_subscriber();init_event_subscriptions();inputSchema36=z133.object({request:SubscribeEventRequestSchema2,ctx:z133.unknown()});outputSchema35=SubscribeEventResultSchema2;stateSchema38=z133.object({authInfo:z133.any(),dialect:z133.enum(["sep-3415","sketch"]),event:z133.instanceof(EventEntry),owner:z133.any(),arguments:z133.record(z133.string(),z133.unknown()),subscriptionId:z133.string(),argumentsKey:z133.string(),existing:z133.any(),verifiedAt:z133.number(),expiresAt:z133.number().nullable(),record:z133.any(),truncated:z133.boolean().optional()});plan43={pre:["parseInput","resolveDialect","findEvent","checkAvailability","requireWebhookMode","requireSubscriber","checkEntryAuthorities","validateArguments","authorize","validateDelivery"],execute:["findSubscription","enforceLimits","verifyCallback","grantTtl","upsertSubscription","notifySubscribed","startReplay"],post:["buildResult"],finalize:["finalize"]};name43="events:subscribe";({Stage:Stage43}=FlowHooksOf(name43));URL_PROBLEMS={malformed:"it is not a URL",scheme:"it must use https",credentials:"it must not carry a user name or a password",host:"its host is local, private or a metadata service"};EventSubscribeFlow=class extends FlowBase{logger=this.scopeLogger.child("EventSubscribeFlow");get events(){return this.scope.events}get subscriptions(){return this.events.subscriptions}get codes(){return EVENT_DIALECTS[this.state.required.dialect].errorCodes}async parseInput(){const authInfo=this.input.ctx?.authInfo??{};this.state.set("authInfo",authInfo)}async resolveDialect(){const platform=callerPlatformOf(this.scope,this.state.required.authInfo,this.tryGetContext()?.platformType);this.state.set("dialect",resolveEventDialect(this.events.config.compat,platform))}async findEvent(){const eventName=this.input.request.params.name;const event=this.events.findByName(eventName);if(!event)throw new EventNotFoundError(this.codes,"event",eventName);this.state.set("event",event)}async checkAvailability(){const{event}=this.state.required;if(!isOfferedOnSurface(event.metadata.availableWhen,callSurfaceOf(this.input.ctx))){throw new EventNotFoundError(this.codes,"event",event.name)}}async requireWebhookMode(){const requestedMode=this.input.request.params.delivery.mode??"webhook";const subscribableModes=this.events.deliveryModesOf(this.state.required.event).filter(mode=>mode==="webhook");if(requestedMode!=="webhook"||subscribableModes.length===0){throw new EventUnsupportedError(this.codes,"deliveryMode",requestedMode,subscribableModes)}}async requireSubscriber(){const{authInfo,event}=this.state.required;const owner=eventSubscriberOf(authInfo,this.scope.authoritiesContextBuilder);if(!owner)throw new EventForbiddenError(this.codes,event.name,"a webhook subscription needs a signed-in caller");this.state.set("owner",owner)}async checkEntryAuthorities(){const engine=this.scope.authoritiesEngine;const contextBuilder=this.scope.authoritiesContextBuilder;const{event,authInfo}=this.state.required;const authorities=event.getAuthorities();if(!engine||!contextBuilder||!authorities)return;const evaluationContext=contextBuilder.build(authInfo,this.input.request.params.arguments??{});const result=await engine.evaluate(authorities,evaluationContext);if(!result.granted){throw new EventForbiddenError(this.codes,event.name,result.deniedBy??"policy denied")}}async validateArguments(){try{this.state.set("arguments",this.state.required.event.parseArguments(this.input.request.params.arguments??{}))}catch(error){throw new InvalidInputError("Invalid subscription arguments",error instanceof z133.ZodError?error.issues:void 0)}}async authorize(){const{event,authInfo,owner}=this.state.required;try{await event.create(authInfo).authorize?.(this.state.required.arguments,owner.subscriber)}catch(error){if(error instanceof EventProtocolError)throw error;const reason=isPublicError(error)?error.getPublicMessage():"the event refused it";throw new EventForbiddenError(this.codes,event.name,reason)}}async validateDelivery(){const{url,secret}=this.input.request.params.delivery;const allowLocal=this.events.config.webhook.unsafeAllowLocalCallbacks;const urlCheck=validateOutboundUrl(url,{allowLocal});if(!urlCheck.ok)throw new InvalidInputError(`Invalid delivery.url: ${URL_PROBLEMS[urlCheck.problem]}`);if(!isStandardWebhookSecret(secret)){throw new InvalidInputError('Invalid delivery.secret: expected "whsec_" followed by base64 that decodes to 24 to 64 bytes')}}async findSubscription(){const{owner,event}=this.state.required;const{url}=this.input.request.params.delivery;const identity=this.subscriptions.identityOf(owner.principalKey,url,event.name,this.state.required.arguments);this.subscriptions.sweepIfDue();const existing=await this.subscriptions.store.get(identity.id);if(!existing)await this.subscriptions.expire(identity.id);this.state.set({subscriptionId:identity.id,argumentsKey:identity.argumentsKey,existing})}async enforceLimits(){if(this.state.existing)return;const{maxPerPrincipal}=this.subscriptions.settings;const held=await this.subscriptions.store.countByPrincipal(this.state.required.owner.principalKey);if(held>=maxPerPrincipal)throw new EventResourceExhaustedError(this.codes,"subscriptions",maxPerPrincipal)}async verifyCallback(){const{url,secret}=this.input.request.params.delivery;const{owner,subscriptionId}=this.state.required;const verification=await this.subscriptions.verifier.verify({principalKey:owner.principalKey,url,secret,subscriptionId,verifiedAt:this.state.existing?.verifiedAt});if(verification.outcome==="limited"){throw new EventResourceExhaustedError(this.codes,"verifications",verification.max)}if(verification.outcome==="failed"){this.logger.verbose(`verifyCallback: subscription ${subscriptionId} refused (${verification.reason})`);throw new EventCallbackEndpointError(this.codes,verification.reason)}this.state.set("verifiedAt",verification.verifiedAt)}async grantTtl(){const requestedTtlMs=this.input.request.params.ttlMs;this.state.set("expiresAt",this.subscriptions.grantExpiry(this.state.required.event,requestedTtlMs,Date.now()))}async upsertSubscription(){const{url,secret}=this.input.request.params.delivery;const{owner,event,dialect,subscriptionId,argumentsKey,verifiedAt}=this.state.required;const expiresAt=this.state.get("expiresAt")??null;const existing=this.state.existing;const replay=existing?await this.currentReplayOf(subscriptionId):void 0;const now=Date.now();const record={id:subscriptionId,principalKey:owner.principalKey,subscriber:owner.subscriber,eventName:event.name,arguments:this.state.required.arguments,argumentsKey,delivery:this.subscriptions.rotatedDelivery(existing?.delivery,url,secret,now),dialect,createdAt:existing?.createdAt??now,updatedAt:now,expiresAt,verifiedAt,lastAuthorizedAt:now,active:true,status:reactivatedStatus(existing?.status),...replay&&{replay}};await this.subscriptions.store.upsert(record);this.state.set("record",record)}async notifySubscribed(){if(this.state.existing)return;const{event,record,authInfo}=this.state.required;try{await this.subscriptions.notifySubscribed(event,record,authInfo)}catch(error){await this.subscriptions.store.delete(record.id);throw error}this.logger.verbose(`notifySubscribed: subscription ${record.id} created for event "${event.name}"`)}async startReplay(){const{replays}=this.events;const{event,record}=this.state.required;if(!replays?.isReplayable(event))return;const{cursor=null,maxAgeMs}=this.input.request.params;const step=record.replay?await replays.refresh(record,record.replay):await replays.begin(event,record,cursor,maxAgeMs);this.state.set({record:{...record,replay:step.replay},truncated:step.truncated})}async currentReplayOf(subscriptionId){const stored=await this.subscriptions.store.get(subscriptionId);return stored?.replay}async buildResult(){const{record}=this.state.required;this.respond({id:record.id,refreshBefore:record.expiresAt===null?null:new Date(record.expiresAt).toISOString(),cursor:record.replay?.watermark??null,truncated:this.state.truncated??false,...this.state.existing&&{deliveryStatus:deliveryStatusOf(record)}})}async finalize(){this.logger.verbose("finalize")}};__decorateClass([Stage43("parseInput")],EventSubscribeFlow.prototype,"parseInput",1);__decorateClass([Stage43("resolveDialect")],EventSubscribeFlow.prototype,"resolveDialect",1);__decorateClass([Stage43("findEvent")],EventSubscribeFlow.prototype,"findEvent",1);__decorateClass([Stage43("checkAvailability")],EventSubscribeFlow.prototype,"checkAvailability",1);__decorateClass([Stage43("requireWebhookMode")],EventSubscribeFlow.prototype,"requireWebhookMode",1);__decorateClass([Stage43("requireSubscriber")],EventSubscribeFlow.prototype,"requireSubscriber",1);__decorateClass([Stage43("checkEntryAuthorities")],EventSubscribeFlow.prototype,"checkEntryAuthorities",1);__decorateClass([Stage43("validateArguments")],EventSubscribeFlow.prototype,"validateArguments",1);__decorateClass([Stage43("authorize")],EventSubscribeFlow.prototype,"authorize",1);__decorateClass([Stage43("validateDelivery")],EventSubscribeFlow.prototype,"validateDelivery",1);__decorateClass([Stage43("findSubscription")],EventSubscribeFlow.prototype,"findSubscription",1);__decorateClass([Stage43("enforceLimits")],EventSubscribeFlow.prototype,"enforceLimits",1);__decorateClass([Stage43("verifyCallback")],EventSubscribeFlow.prototype,"verifyCallback",1);__decorateClass([Stage43("grantTtl")],EventSubscribeFlow.prototype,"grantTtl",1);__decorateClass([Stage43("upsertSubscription")],EventSubscribeFlow.prototype,"upsertSubscription",1);__decorateClass([Stage43("notifySubscribed")],EventSubscribeFlow.prototype,"notifySubscribed",1);__decorateClass([Stage43("startReplay")],EventSubscribeFlow.prototype,"startReplay",1);__decorateClass([Stage43("buildResult")],EventSubscribeFlow.prototype,"buildResult",1);__decorateClass([Stage43("finalize")],EventSubscribeFlow.prototype,"finalize",1);EventSubscribeFlow=__decorateClass([FrontMcpFlow({name:name43,plan:plan43,inputSchema:inputSchema36,outputSchema:outputSchema35,access:"authorized"})],EventSubscribeFlow)}});import{internalZ as z134}from"@frontmcp/lazy-zod";import{UnsubscribeEventRequestSchema as UnsubscribeEventRequestSchema2,UnsubscribeEventResultSchema}from"@frontmcp/protocol";var inputSchema37,outputSchema36,stateSchema39,plan44,name44,Stage44,EventUnsubscribeFlow;var init_event_unsubscribe_flow=__esm({"libs/sdk/src/event/flows/event-unsubscribe.flow.ts"(){"use strict";init_common();init_errors();init_event_dialect();init_event_subscriber();inputSchema37=z134.object({request:UnsubscribeEventRequestSchema2,ctx:z134.unknown()});outputSchema36=UnsubscribeEventResultSchema;stateSchema39=z134.object({authInfo:z134.any(),dialect:z134.enum(["sep-3415","sketch"]),owner:z134.any()});plan44={pre:["parseInput","resolveDialect","requireSubscriber"],execute:["removeSubscription"],post:["buildResult"],finalize:["finalize"]};name44="events:unsubscribe";({Stage:Stage44}=FlowHooksOf(name44));EventUnsubscribeFlow=class extends FlowBase{logger=this.scopeLogger.child("EventUnsubscribeFlow");get events(){return this.scope.events}get subscriptions(){return this.events.subscriptions}async parseInput(){const authInfo=this.input.ctx?.authInfo??{};this.state.set("authInfo",authInfo)}async resolveDialect(){const platform=callerPlatformOf(this.scope,this.state.required.authInfo,this.tryGetContext()?.platformType);this.state.set("dialect",resolveEventDialect(this.events.config.compat,platform))}async requireSubscriber(){const{authInfo,dialect}=this.state.required;const owner=eventSubscriberOf(authInfo,this.scope.authoritiesContextBuilder);if(!owner){const eventName=this.input.request.params.name;const codes=EVENT_DIALECTS[dialect].errorCodes;throw new EventForbiddenError(codes,eventName,"a webhook subscription needs a signed-in caller")}this.state.set("owner",owner)}async removeSubscription(){const{name:eventName,delivery}=this.input.request.params;const{owner,authInfo}=this.state.required;const identity=this.subscriptions.identityOf(owner.principalKey,delivery.url,eventName,this.storedArguments());this.subscriptions.sweepIfDue();const removed=await this.subscriptions.store.delete(identity.id);if(!removed)return;await this.subscriptions.notifyUnsubscribed(removed,"unsubscribed",authInfo);this.logger.verbose(`removeSubscription: subscription ${removed.id} removed from event "${eventName}"`)}async buildResult(){this.respond({})}async finalize(){this.logger.verbose("finalize")}storedArguments(){const{name:eventName,arguments:sentArguments={}}=this.input.request.params;try{return this.events.findByName(eventName)?.parseArguments(sentArguments)??sentArguments}catch{return sentArguments}}};__decorateClass([Stage44("parseInput")],EventUnsubscribeFlow.prototype,"parseInput",1);__decorateClass([Stage44("resolveDialect")],EventUnsubscribeFlow.prototype,"resolveDialect",1);__decorateClass([Stage44("requireSubscriber")],EventUnsubscribeFlow.prototype,"requireSubscriber",1);__decorateClass([Stage44("removeSubscription")],EventUnsubscribeFlow.prototype,"removeSubscription",1);__decorateClass([Stage44("buildResult")],EventUnsubscribeFlow.prototype,"buildResult",1);__decorateClass([Stage44("finalize")],EventUnsubscribeFlow.prototype,"finalize",1);EventUnsubscribeFlow=__decorateClass([FrontMcpFlow({name:name44,plan:plan44,inputSchema:inputSchema37,outputSchema:outputSchema36,access:"authorized"})],EventUnsubscribeFlow)}});import{internalZ as z135}from"@frontmcp/lazy-zod";import{EventDeliveryModeSchema,ListEventsRequestSchema as ListEventsRequestSchema2,ListEventsResultSchema as ListEventsResultSchema2}from"@frontmcp/protocol";function compareByName(left,right){if(left.event.name<right.event.name)return-1;return left.event.name>right.event.name?1:0}var EVENTS_LIST_PAGE_SIZE,inputSchema38,outputSchema37,stateSchema40,plan45,name45,Stage45,ListEventsFlow;var init_list_events_flow=__esm({"libs/sdk/src/event/flows/list-events.flow.ts"(){"use strict";init_common();init_availability();init_offset_cursor_utils();init_errors();init_entry_authorized();EVENTS_LIST_PAGE_SIZE=40;inputSchema38=z135.object({request:ListEventsRequestSchema2,ctx:z135.unknown()});outputSchema37=ListEventsResultSchema2;stateSchema40=z135.object({cursor:z135.string().optional(),authInfo:z135.any(),events:z135.array(z135.object({event:z135.instanceof(EventEntry),delivery:z135.array(EventDeliveryModeSchema)}))});plan45={pre:["parseInput"],execute:["findEvents","filterByAvailability","filterByAuthorities","filterByDiscovery"],post:["parseEvents"],finalize:["finalize"]};name45="events:list";({Stage:Stage45}=FlowHooksOf(name45));ListEventsFlow=class extends FlowBase{logger=this.scopeLogger.child("ListEventsFlow");async parseInput(){const{request:request2,ctx}=this.input;const authInfo=ctx?.authInfo??{};this.state.set({cursor:request2.params?.cursor??void 0,authInfo})}async findEvents(){this.state.set("events",this.scope.events?.getServedEvents()??[])}async filterByAvailability(){const callSurface=callSurfaceOf(this.input.ctx);const offered=this.state.required.events.filter(({event})=>isOfferedOnSurface(event.metadata.availableWhen,callSurface));this.state.set("events",offered)}async filterByAuthorities(){const engine=this.scope.authoritiesEngine;const contextBuilder=this.scope.authoritiesContextBuilder;if(!engine||!contextBuilder)return;const{events,authInfo}=this.state.required;const answers=await Promise.all(events.map(({event})=>{const authorities=event.getAuthorities();if(authorities===void 0)return true;return isListedByAuthorities(engine,contextBuilder,authorities,authInfo,event.name,this.logger)}));this.state.set("events",events.filter((_item,index)=>answers[index]))}async filterByDiscovery(){const discoverable=this.state.required.events.filter(({event})=>!event.metadata.hideFromDiscovery);this.state.set("events",discoverable)}async parseEvents(){const sorted=[...this.state.required.events].sort(compareByName);const offset=this.state.cursor?parseOffsetCursor(this.state.cursor):0;if(offset>sorted.length){throw new InvalidInputError(`Invalid pagination cursor: offset ${offset} exceeds total event count ${sorted.length}`)}const events=sorted.slice(offset,offset+EVENTS_LIST_PAGE_SIZE).map(({event,delivery})=>({name:event.name,...event.metadata.description&&{description:event.metadata.description},delivery,inputSchema:event.getInputJsonSchema(),payloadSchema:event.getPayloadJsonSchema()}));const nextOffset=offset+EVENTS_LIST_PAGE_SIZE;this.respond({events,...nextOffset<sorted.length&&{nextCursor:encodeOffsetCursor(nextOffset)}})}async finalize(){this.logger.verbose("finalize")}};__decorateClass([Stage45("parseInput")],ListEventsFlow.prototype,"parseInput",1);__decorateClass([Stage45("findEvents")],ListEventsFlow.prototype,"findEvents",1);__decorateClass([Stage45("filterByAvailability")],ListEventsFlow.prototype,"filterByAvailability",1);__decorateClass([Stage45("filterByAuthorities")],ListEventsFlow.prototype,"filterByAuthorities",1);__decorateClass([Stage45("filterByDiscovery")],ListEventsFlow.prototype,"filterByDiscovery",1);__decorateClass([Stage45("parseEvents")],ListEventsFlow.prototype,"parseEvents",1);__decorateClass([Stage45("finalize")],ListEventsFlow.prototype,"finalize",1);ListEventsFlow=__decorateClass([FrontMcpFlow({name:name45,plan:plan45,inputSchema:inputSchema38,outputSchema:outputSchema37,access:"authorized"})],ListEventsFlow)}});import{randomUUID as randomUUID29}from"@frontmcp/utils";var CURSOR_SEPARATOR,EventBuffer;var init_event_buffer=__esm({"libs/sdk/src/event/poll/event-buffer.ts"(){"use strict";CURSOR_SEPARATOR=".";EventBuffer=class{constructor(options){this.options=options;this.bootId=randomUUID29().replace(/-/g,"")}options;bootId;rings=new Map;sequence=0;append(occurrence,audience,subscriptionId){const now=Date.now();this.sequence+=1;const buffered={sequence:this.sequence,publishedAt:now,occurrence,audience,subscriptionId};const ring=this.ringOf(occurrence.name);ring.events.push(buffered);this.prune(ring,now);return buffered}currentCursor(){return this.cursorAt(this.sequence)}currentSequence(){return this.sequence}cursorAt(sequence){return`${this.bootId}${CURSOR_SEPARATOR}${sequence}`}read(eventName,cursor){const ring=this.ringOf(eventName);this.prune(ring,Date.now());const position=this.positionOf(cursor);if(position===void 0)return{events:[],truncated:true};return{events:ring.events.filter(buffered=>buffered.sequence>position),truncated:position<ring.droppedThrough}}positionOf(cursor){const[bootId,position,...rest]=cursor.split(CURSOR_SEPARATOR);const sequence=Number(position);const isPosition=Number.isSafeInteger(sequence)&&sequence>=0&&String(sequence)===position;if(bootId!==this.bootId||!isPosition||rest.length>0||sequence>this.sequence)return void 0;return sequence}ringOf(eventName){let ring=this.rings.get(eventName);if(!ring){ring={events:[],droppedThrough:0};this.rings.set(eventName,ring)}return ring}prune(ring,now){const{maxAgeMs,maxEvents}=this.options;const oldestKept=now-maxAgeMs;let dropCount=Math.max(0,ring.events.length-maxEvents);while(dropCount<ring.events.length&&ring.events[dropCount].publishedAt<oldestKept)dropCount+=1;if(dropCount===0)return;ring.droppedThrough=ring.events[dropCount-1].sequence;ring.events.splice(0,dropCount)}}}});import{internalZ as z136}from"@frontmcp/lazy-zod";function isTimestamp(value){return!Number.isNaN(new Date(value).getTime())}function mediaTypeOf2(contentType2){return(contentType2??"").split(";")[0].trim().toLowerCase()}function jsonOf(body){try{return JSON.parse(decoder3.decode(body))}catch{return void 0}}function summarizeIssues(error){return error.issues.map(issue=>({path:issue.path.join("."),message:issue.message}))}var EVENT_PUBLISH_MAX_BODY_BYTES,EVENT_ID_PATTERN,audienceValueSchema2,publishRequestSchema,inputSchema39,outputSchema38,stateSchema41,plan46,name46,Stage46,decoder3,EventPublishHttpFlow;var init_event_publish_http_flow=__esm({"libs/sdk/src/event/flows/event-publish-http.flow.ts"(){"use strict";init_common();init_errors();init_flow_http_path();init_workflow_webhook_signature();init_event_subscriber();EVENT_PUBLISH_MAX_BODY_BYTES=262144;EVENT_ID_PATTERN=/^[\x21-\x7e]{1,255}$/;audienceValueSchema2=z136.union([z136.string(),z136.array(z136.string())]);publishRequestSchema=z136.object({name:z136.string().min(1),data:z136.record(z136.string(),z136.unknown()),eventId:z136.string().regex(EVENT_ID_PATTERN,"eventId must be 1 to 255 visible ASCII characters").optional(),timestamp:z136.string().refine(isTimestamp,"timestamp must be a date such as 2026-10-02T12:00:00Z").optional(),subscriptionId:z136.string().min(1).optional(),audience:z136.object({sub:audienceValueSchema2.optional(),tenantId:audienceValueSchema2.optional(),roles:z136.object({any:z136.array(z136.string()).optional(),all:z136.array(z136.string()).optional()}).strict().optional()}).strict().optional()}).strict();inputSchema39=httpInputSchema;outputSchema38=HttpJsonSchema;stateSchema41=z136.object({body:z136.custom(),caller:z136.custom().optional(),publication:publishRequestSchema,event:z136.instanceof(EventEntry),claimedEventId:z136.string().optional(),claimToken:z136.string().optional(),result:z136.object({eventId:z136.string(),matched:z136.number()}),flowError:z136.instanceof(Error).optional()});plan46={pre:["checkIpFilter","acquireQuota","readBody","authenticate","parseBody","checkAuthorities","findEvent","validatePayload"],execute:["claimEventId","publish","rememberResult","buildResponse"],finalize:["finalize"]};name46="events:publish-http";({Stage:Stage46}=FlowHooksOf(name46));decoder3=new TextDecoder;EventPublishHttpFlow=class extends FlowBase{logger=this.scopeLogger.child("EventPublishHttpFlow");static canActivate(request2,scope){const endpoint=scope.events?.publishEndpoint;return endpoint!==void 0&&request2.method==="POST"&&matchRoutePath(endpoint.path,request2.path)!==void 0}get events(){return this.scope.events}get endpoint(){return this.events.publishEndpoint}get publisher(){return this.events.publisher}get httpRequest(){return this.rawInput.request}refuse(status,error,details={},headers){this.state.set("flowError",new PublicMcpError(`HTTP ${status}: ${error}`,"EVENT_PUBLISH_REFUSED",status));return FlowControl.respond(httpRespond.json({error,...details},{status,headers}))}async recordingRefusal(guard){try{await guard()}catch(signal){const refusal4=signal instanceof FlowControl&&signal.type==="respond"?signal.output:void 0;if(refusal4?.kind==="json"){const reason=Array.isArray(refusal4.body)?void 0:refusal4.body["error"];const error=typeof reason==="string"?reason:"Refused";this.state.set("flowError",new PublicMcpError(`HTTP ${refusal4.status}: ${error}`,"EVENT_PUBLISH_REFUSED",refusal4.status))}throw signal}}async checkIpFilter(){await this.recordingRefusal(()=>enforceIpFilter(this.scope,this.tryGetContext()?.metadata.clientIp))}async acquireQuota(){await this.recordingRefusal(()=>enforceGlobalRateLimit(this.scope,this.tryGetContext()))}async readBody(){const request2=this.httpRequest;if(mediaTypeOf2(request2.headers["content-type"])!=="application/json"){this.refuse(415,"The body must be application/json")}const body=request2.bodyBytes??new Uint8Array;if(body.length>EVENT_PUBLISH_MAX_BODY_BYTES)this.refuse(413,"Payload too large");this.state.set("body",body)}async authenticate(){const{secret,replays}=this.endpoint;if(secret===void 0){this.state.set("caller",await this.verifyBearer());return}const signedRequest={headers:this.httpRequest.headers,body:this.state.required.body};const refusal4=verifyWorkflowWebhook(signedRequest,secret,replays);if(refusal4){this.logger.warn(`authenticate: a publish request was refused: ${refusal4}`);this.refuse(401,"Unauthorized")}}async parseBody(){const parsed=publishRequestSchema.safeParse(jsonOf(this.state.required.body));if(!parsed.success)this.refuse(400,"Invalid publish request",{issues:summarizeIssues(parsed.error)});this.state.set("publication",parsed.data)}async checkAuthorities(){const engine=this.scope.authoritiesEngine;const contextBuilder=this.scope.authoritiesContextBuilder;const{authorities}=this.endpoint;if(!engine||!contextBuilder||authorities===void 0)return;const caller=this.state.caller??{};const evaluationContext=contextBuilder.build(caller,this.state.required.publication);const result=await engine.evaluate(authorities,evaluationContext);if(result.granted)return;this.logger.verbose(`checkAuthorities: a publish request was refused: ${result.deniedBy??"policy denied"}`);this.refuse(403,"Forbidden")}async findEvent(){const eventName=this.state.required.publication.name;const event=this.events.findByName(eventName);if(!event)this.refuse(404,`Event "${eventName}" is not registered`);this.state.set("event",event)}async validatePayload(){const{event,publication}=this.state.required;try{event.parsePayload(publication.data)}catch(error){if(!(error instanceof z136.ZodError))throw error;this.refuse(422,`data does not match the payloadSchema of event "${event.name}"`,{issues:summarizeIssues(error)})}}async claimEventId(){const{name:eventName,eventId}=this.state.required.publication;if(eventId===void 0)return;const claim=await this.endpoint.idempotency.claim(eventName,eventId);if(claim.state==="published")return this.respond(httpRespond.json(claim.result,{status:202}));if(claim.state==="in-flight"){this.refuse(409,`Event "${eventName}" with eventId "${eventId}" is being published; retry for its answer`)}this.state.set({claimedEventId:eventId,claimToken:claim.token})}async publish(){const{name:eventName,data,eventId,timestamp,subscriptionId,audience}=this.state.required.publication;try{const options={eventId,timestamp,subscriptionId,audience};this.state.set("result",await this.publisher.publish(eventName,data,options))}catch(error){const{claimedEventId,claimToken}=this.state;if(claimedEventId!==void 0&&claimToken!==void 0){await this.endpoint.idempotency.release(eventName,claimedEventId,claimToken)}throw error}}async rememberResult(){const{claimedEventId,claimToken}=this.state;if(claimedEventId===void 0||claimToken===void 0)return;const{publication,result}=this.state.required;try{await this.endpoint.idempotency.complete(publication.name,claimedEventId,claimToken,result)}catch(error){this.logger.warn(`rememberResult: event "${publication.name}" with eventId "${claimedEventId}" was published, but its answer could not be kept for a repeat`,error)}}async buildResponse(){this.respond(httpRespond.json(this.state.required.result,{status:202}))}async finalize(){this.logger.verbose(`finalize: ${this.state.result?"published":"not published"}`)}async verifyBearer(){const verified=await this.scope.runFlow("session:verify",{request:this.httpRequest,sessionless:true});if(verified?.kind==="authorized"){const caller=authInfoFromAuthorization(verified.authorization);if(eventSubscriberOf(caller,this.scope.authoritiesContextBuilder))return caller;return this.refuse(401,"Unauthorized",{message:"Publishing needs a signed-in caller"})}const headers=challengeHeaders(verified?.prmMetadataHeader);return verified?.kind==="forbidden"?this.refuse(403,"Forbidden",{},headers):this.refuse(401,"Unauthorized",{},headers)}};__decorateClass([Stage46("checkIpFilter")],EventPublishHttpFlow.prototype,"checkIpFilter",1);__decorateClass([Stage46("acquireQuota")],EventPublishHttpFlow.prototype,"acquireQuota",1);__decorateClass([Stage46("readBody")],EventPublishHttpFlow.prototype,"readBody",1);__decorateClass([Stage46("authenticate")],EventPublishHttpFlow.prototype,"authenticate",1);__decorateClass([Stage46("parseBody")],EventPublishHttpFlow.prototype,"parseBody",1);__decorateClass([Stage46("checkAuthorities")],EventPublishHttpFlow.prototype,"checkAuthorities",1);__decorateClass([Stage46("findEvent")],EventPublishHttpFlow.prototype,"findEvent",1);__decorateClass([Stage46("validatePayload")],EventPublishHttpFlow.prototype,"validatePayload",1);__decorateClass([Stage46("claimEventId")],EventPublishHttpFlow.prototype,"claimEventId",1);__decorateClass([Stage46("publish")],EventPublishHttpFlow.prototype,"publish",1);__decorateClass([Stage46("rememberResult")],EventPublishHttpFlow.prototype,"rememberResult",1);__decorateClass([Stage46("buildResponse")],EventPublishHttpFlow.prototype,"buildResponse",1);__decorateClass([Stage46("finalize")],EventPublishHttpFlow.prototype,"finalize",1);EventPublishHttpFlow=__decorateClass([FrontMcpFlow({name:name46,plan:plan46,inputSchema:inputSchema39,outputSchema:outputSchema38,access:"public",middleware:{method:"POST"}})],EventPublishHttpFlow)}});import{bytesToHex as bytesToHex4,hmacSha256 as hmacSha2564,sha256Hex as sha256Hex26}from"@frontmcp/utils";function isExpired(record,now){return record.expiresAt!==null&&record.expiresAt<=now}function ttlOptionsOf(record){if(record.expiresAt===null)return{};const remainingSeconds=Math.max(0,Math.ceil((record.expiresAt-Date.now())/1e3));return{ttlSeconds:remainingSeconds+EXPIRED_RETENTION_SECONDS}}function idOfIndexKey(indexKey){return indexKey.slice(indexKey.lastIndexOf(":")+1)}var RECORD_PREFIX3,EVENT_INDEX_PREFIX,PRINCIPAL_INDEX_PREFIX,EXPIRY_INDEX_PREFIX,EXPIRED_RETENTION_SECONDS,MAX_ATTEMPTS2,textEncoder3,StorageEventSubscriptionStore;var init_event_subscription_store=__esm({"libs/sdk/src/event/subscription/event-subscription.store.ts"(){"use strict";init_elicitation_encryption();init_errors();RECORD_PREFIX3="s:";EVENT_INDEX_PREFIX="e:";PRINCIPAL_INDEX_PREFIX="p:";EXPIRY_INDEX_PREFIX="x:";EXPIRED_RETENTION_SECONDS=3600;MAX_ATTEMPTS2=16;textEncoder3=new TextEncoder;StorageEventSubscriptionStore=class{constructor(options){this.options=options}options;async upsert(record){const{storage}=this.options;const ttlOptions=ttlOptionsOf(record);await storage.set(RECORD_PREFIX3+record.id,await this.encode(record),ttlOptions);await storage.set(this.eventIndexKey(record),"1",ttlOptions);await storage.set(this.principalIndexKey(record),"1",ttlOptions);if(record.expiresAt!==null){await storage.set(`${EXPIRY_INDEX_PREFIX}${record.expiresAt}:${record.id}`,"1",ttlOptions)}}async get(id){const stored=await this.read(id);return stored&&!isExpired(stored.record,Date.now())?stored.record:void 0}async delete(id){return this.remove(id,()=>true)}async deleteExpired(id,now){return this.remove(id,record=>isExpired(record,now))}async listByEvent(eventName){return this.liveRecordsOf(`${EVENT_INDEX_PREFIX}${this.digest("event",eventName)}:*`)}async countByPrincipal(principalKey){const records=await this.liveRecordsOf(`${PRINCIPAL_INDEX_PREFIX}${this.digest("principal",principalKey)}:*`);return records.length}async update(id,patch){const{storage}=this.options;const recordKey2=RECORD_PREFIX3+id;for(let attempt=0;attempt<MAX_ATTEMPTS2;attempt++){const stored=await this.read(id);if(!stored||isExpired(stored.record,Date.now()))return void 0;const changes=typeof patch==="function"?patch(stored.record):patch;const next={...stored.record,...changes};const nextRaw=await this.encode(next);if(!await storage.setIfEquals(recordKey2,stored.raw,nextRaw))continue;const{ttlSeconds}=ttlOptionsOf(next);if(ttlSeconds!==void 0)await storage.expireIfEquals(recordKey2,nextRaw,ttlSeconds);return next}throw new EventSubscriptionStoreError(`subscription ${id} kept changing while it was updated`)}async listExpired(now){const{storage}=this.options;const expiryKeys=await storage.keys(`${EXPIRY_INDEX_PREFIX}*`);const dueKeys=expiryKeys.filter(expiryKey=>Number(expiryKey.split(":")[1])<=now);const expired=[];for(const expiryKey of dueKeys){const stored=await this.read(idOfIndexKey(expiryKey));if(stored&&isExpired(stored.record,now)){expired.push(stored.record)}else{await storage.delete(expiryKey)}}return expired}async close(){await this.options.storage.disconnect()}async remove(id,shouldRemove){const{storage}=this.options;for(let attempt=0;attempt<MAX_ATTEMPTS2;attempt++){const stored=await this.read(id);if(!stored||!shouldRemove(stored.record))return void 0;if(!await storage.deleteIfEquals(RECORD_PREFIX3+id,stored.raw))continue;await storage.mdelete([this.eventIndexKey(stored.record),this.principalIndexKey(stored.record)]);return stored.record}throw new EventSubscriptionStoreError(`subscription ${id} kept changing while it was removed`)}async liveRecordsOf(indexPattern){const{storage}=this.options;const indexKeys=await storage.keys(indexPattern);if(indexKeys.length===0)return[];const ids=indexKeys.map(idOfIndexKey);const raws=await storage.mget(ids.map(id=>RECORD_PREFIX3+id));const now=Date.now();const records=[];for(let index=0;index<ids.length;index++){const raw=raws[index];const record=raw===null||raw===void 0?void 0:await this.decode(raw,ids[index]);if(record&&!isExpired(record,now))records.push(record)}return records}async read(id){const raw=await this.options.storage.get(RECORD_PREFIX3+id);if(raw===null)return void 0;const record=await this.decode(raw,id);return record?{raw,record}:void 0}async encode(record){const{secret}=this.options;return secret===void 0?JSON.stringify(record):encryptAndSerialize(record,`events:${record.id}`,secret)}async decode(raw,id){const{secret}=this.options;try{const record=secret===void 0?JSON.parse(raw):await deserializeAndDecrypt(raw,`events:${id}`,secret);return record?.id===id?record:void 0}catch{return void 0}}eventIndexKey(record){return`${EVENT_INDEX_PREFIX}${this.digest("event",record.eventName)}:${record.id}`}principalIndexKey(record){return`${PRINCIPAL_INDEX_PREFIX}${this.digest("principal",record.principalKey)}:${record.id}`}digest(kind,value){const{secret}=this.options;const text=`${kind}:${value}`;if(secret===void 0)return sha256Hex26(text);return bytesToHex4(hmacSha2564(textEncoder3.encode(secret),textEncoder3.encode(text)))}}}});import{createStorage as createStorage8,getEnv as getEnv19}from"@frontmcp/utils";function eventsSecretFromEnv(){return getEnv19("MCP_EVENTS_SECRET")||getEnv19("MCP_SESSION_SECRET")||getEnv19("MCP_SERVER_SECRET")||void 0}function storageConfigOf(options){const{redis,sqlite}=options;if(sqlite)return{type:"sqlite",sqlite};if(!redis)return{type:"memory"};if(!isRedisProvider(redis)){throw new EventSubscriptionStoreError("Vercel KV has no atomic compare-and-set, which subscription updates need. Use a Redis server in events.store.redis, or events.store.sqlite.")}const{host,port,password,db,tls}=redis;return{type:"redis",redis:{config:{host,port,password,db,tls}}}}async function openStorage(config,keyPrefix){try{return await createStorage8({...config,prefix:keyPrefix,fallback:"error"})}catch(error){const reason=error instanceof Error?error.message:String(error);throw new EventSubscriptionStoreError(`the ${config.type} store cannot be opened: ${reason}`)}}function openEventStorage(options={}){return openStorage(storageConfigOf(options),options.keyPrefix??"mcp:events:")}async function createEventSubscriptionStore(options={}){const{keyPrefix="mcp:events:",logger}=options;const config=storageConfigOf(options);const durable=config.type!=="memory";const secret=options.secret??eventsSecretFromEnv();if(durable&&!secret){throw new EventSubscriptionStoreError(`the ${config.type} store keeps webhook signing secrets, so it needs a secret to encrypt them with: set MCP_EVENTS_SECRET (or MCP_SESSION_SECRET / MCP_SERVER_SECRET).`)}const storage=await openStorage(config,keyPrefix);logger?.info("Event subscriptions are stored",{type:config.type,encrypted:secret!==void 0});return{store:new StorageEventSubscriptionStore({storage,secret}),type:config.type,durable,encrypted:secret!==void 0,storage,secret}}var init_event_subscription_store_factory=__esm({"libs/sdk/src/event/subscription/event-subscription-store.factory.ts"(){"use strict";init_common();init_errors();init_event_subscription_store()}});import{randomUUID as randomUUID30,sha256Hex as sha256Hex27}from"@frontmcp/utils";function pendingRecordOf(token){return JSON.stringify({pending:token})}function isPending(record){return"pending"in record}var PUBLISH_IDEMPOTENCY_WINDOW_SECONDS,PUBLISH_CLAIM_SECONDS,RECORD_PREFIX4,EventPublishIdempotency;var init_event_publish_idempotency=__esm({"libs/sdk/src/event/publish-endpoint/event-publish-idempotency.ts"(){"use strict";PUBLISH_IDEMPOTENCY_WINDOW_SECONDS=600;PUBLISH_CLAIM_SECONDS=60;RECORD_PREFIX4="published:";EventPublishIdempotency=class{constructor(storage,scopeId){this.storage=storage;this.scopeId=scopeId}storage;scopeId;async claim(eventName,eventId){const key=this.keyOf(eventName,eventId);const token=randomUUID30();await this.storage.set(key,pendingRecordOf(token),{ttlSeconds:PUBLISH_CLAIM_SECONDS,ifNotExists:true});const stored=await this.storage.get(key);if(stored===null)return{state:"in-flight"};const record=JSON.parse(stored);if(!isPending(record))return{state:"published",result:record};return record.pending===token?{state:"claimed",token}:{state:"in-flight"}}async complete(eventName,eventId,token,result){const key=this.keyOf(eventName,eventId);const answer=JSON.stringify(result);if(!await this.storage.setIfEquals(key,pendingRecordOf(token),answer))return;await this.storage.expireIfEquals(key,answer,PUBLISH_IDEMPOTENCY_WINDOW_SECONDS)}async release(eventName,eventId,token){await this.storage.deleteIfEquals(this.keyOf(eventName,eventId),pendingRecordOf(token))}keyOf(eventName,eventId){return RECORD_PREFIX4+sha256Hex27(JSON.stringify([this.scopeId,eventName,eventId])).slice(0,40)}}}});function assertPathFree(scope,path4){const reserved=computeReservedPaths(scope.entryPath,scope.routeBase,servedHealthPaths(scope.metadata.health));try{assertNotReserved("POST",path4,reserved)}catch(error){if(!(error instanceof ReservedRouteCollisionError))throw error;throw new EventPublishEndpointError(`events.publishEndpoint.path "${path4}" is on the reserved FrontMCP path "${error.reserved}": choose another path`)}const routes=[...scope.httpRouteTable?.routes??[],...scope.metadata.http?.routes??[]];const taken=routes.find(route=>route.method.toUpperCase()==="POST"&&matchRoutePath(route.path,path4)!==void 0);if(taken){throw new EventPublishEndpointError(`events.publishEndpoint.path "${path4}" is already served by the route POST ${taken.path}: choose another path`)}}async function enablePublishEndpoint(args){const{scope,eventRegistry,identifiesCallers,keyPrefix,logger}=args;const{secret,authorities,path:configuredPath}=eventRegistry.config.publishEndpoint;const{store:storeConfig}=eventRegistry.config;if(!secret&&!identifiesCallers){throw new EventPublishEndpointError("the server runs in public auth mode, so nothing tells who publishes. Set events.publishEndpoint.secret (at least 32 characters) for signed requests, or configure an auth mode that signs callers in.")}if(authorities!==void 0){assertEntryAuthorities(scope.authoritiesEngine,scope.authoritiesContextBuilder,[{label:"events.publishEndpoint",authorities}])}const path4=`${normalizeScopeBase(scope.routeBase)}${configuredPath}`;assertPathFree(scope,path4);let storage=eventRegistry.storage;if(!storage){const ownStorage=await openEventStorage({redis:storeConfig?.redis,sqlite:storeConfig?.sqlite,keyPrefix});scope.onDispose(()=>ownStorage.disconnect());storage=ownStorage}eventRegistry.publishEndpoint={path:path4,secret,authorities,replays:new WorkflowWebhookReplayGuard,idempotency:new EventPublishIdempotency(storage,scope.id)};await scope.registryFlows(EventPublishHttpFlow);logger.info(`Events can be published over HTTP: POST ${path4} (${secret?"signed requests":"bearer callers"})`);if(!secret&&authorities===void 0){logger.warn(`POST ${path4} lets every signed-in caller publish every event. Set events.publishEndpoint.authorities to name who may publish.`)}}var init_event_publish_endpoint=__esm({"libs/sdk/src/event/publish-endpoint/event-publish-endpoint.ts"(){"use strict";init_common();init_errors();init_flow_http_path();init_authorities_rules_check();init_health_routes();init_custom_routes_helper();init_workflow_webhook_signature();init_event_publish_http_flow();init_event_subscription_store_factory();init_event_publish_idempotency()}});import{generateWebhookMessageId as generateWebhookMessageId2,sha256Hex as sha256Hex28}from"@frontmcp/utils";function isSameReadPosition(current,expected){return current?.cursor===expected.cursor&&current.queuedAtCursor===expected.queuedAtCursor}function isSamePosition(current,expected){if(!current||current.cursor!==expected.cursor||current.pending.length!==expected.pending.length)return false;return current.pending.every((batch,index)=>batch.cursor===expected.pending[index].cursor)}var REPLAY_LEASE_MS,REPLAY_STOP_GRACE_MS,MAX_PENDING_BATCHES,MAX_ROUNDS_PER_TICK,encoder10,EventReplays;var init_event_replays=__esm({"libs/sdk/src/event/replay/event-replays.ts"(){"use strict";init_lease_holder();init_provider_lifecycle();init_event_dialect();init_event_publisher();REPLAY_LEASE_MS=3e4;REPLAY_STOP_GRACE_MS=3e3;MAX_PENDING_BATCHES=50;MAX_ROUNDS_PER_TICK=10;encoder10=new TextEncoder;EventReplays=class{constructor(options){this.options=options;this.logger=options.logger.child("EventReplays")}options;holders=new Map;timers=new Map;ticks=new Map;nextCheckAt=new Map;logger;isReplayable(event){return typeof event.create({}).check==="function"}async start(events){for(const event of events){const holder=new LeaseHolder({label:`Webhook delivery of event "${event.name}"`,key:`replay-lease:${sha256Hex28(event.name).slice(0,32)}`,leaseMs:REPLAY_LEASE_MS,storage:this.options.storage,logger:this.logger,onAcquired:()=>this.schedule(event,0),onLost:()=>this.unschedule(event.name)});this.holders.set(event.name,holder);await holder.start()}}async stop(){const stopping=[...this.holders].map(([eventName,holder])=>{this.unschedule(eventName);return holder.stop(()=>this.turnEnded(eventName))});await Promise.all(stopping);this.holders.clear()}async begin(event,record,cursor,maxAgeMs){const step=await this.advance(event,record,{cursor,watermark:cursor,pending:[]},maxAgeMs);await this.options.store.update(record.id,{replay:step.replay});if(step.failure)throw step.failure;return step}async refresh(record,replay){const{truncated,...settled}=await this.settled(replay);await this.options.store.update(record.id,current=>isSamePosition(current.replay,replay)?{replay:settled}:{});return{replay:settled,truncated:truncated===true,hasMore:false}}schedule(event,delayMs){if(this.timers.has(event.name)||this.ticks.has(event.name))return;const timer=setTimeout(()=>{this.timers.delete(event.name);const tick=this.tick(event).catch(error=>this.logger.warn(`The webhook loop of event "${event.name}" failed`,error)).finally(()=>{this.ticks.delete(event.name);if(this.isRunning(event.name))this.schedule(event,this.options.intervalMs)});this.ticks.set(event.name,tick)},delayMs);timer.unref?.();this.timers.set(event.name,timer)}async turnEnded(eventName){const turn=this.ticks.get(eventName);if(!await outlasts(()=>turn,REPLAY_STOP_GRACE_MS))return true;this.logger.warn(`The webhook loop of event "${eventName}" did not end within ${REPLAY_STOP_GRACE_MS} ms; its lease expires by itself`);return false}isRunning(eventName){const holder=this.holders.get(eventName);return holder!==void 0&&holder.holding&&!holder.stopping}unschedule(eventName){const timer=this.timers.get(eventName);if(timer)clearTimeout(timer);this.timers.delete(eventName)}async tick(event){const subscriptions=await this.options.store.listByEvent(event.name);for(const record of subscriptions){if(!this.isRunning(event.name))return;if(!record.active||!record.replay)continue;if((this.nextCheckAt.get(record.id)??0)>Date.now())continue;try{if(await this.isStillAuthorized(event,record))await this.readFor(event,record,record.replay)}catch(error){this.logger.warn(`The webhook loop of event "${event.name}" failed for subscription ${record.id}`,error)}}}async isStillAuthorized(event,record){const now=Date.now();if(now-record.lastAuthorizedAt<=this.options.reauthorizeEveryMs)return true;const check=await this.options.reauthorize(event,record).catch(error=>({outcome:"failed",error}));if(check.outcome==="granted"){await this.options.store.update(record.id,{lastAuthorizedAt:now});return true}if(check.outcome==="failed"){this.logger.warn(`The access of subscription ${record.id} could not be checked`,check.error);return false}this.nextCheckAt.delete(record.id);await this.options.terminate(record);return false}async readFor(event,record,from){let replay=from;try{for(let round=0;round<MAX_ROUNDS_PER_TICK&&this.isRunning(event.name);round++){const step=await this.advance(event,record,replay,void 0);replay=step.truncated?{...step.replay,truncated:true}:step.replay;if(step.failure)throw step.failure;if(step.truncated)replay=await this.reportGap(record,replay);this.nextCheckAt.set(record.id,Date.now()+(step.nextPollMs??this.options.intervalMs));if(!step.hasMore)break}}finally{if(replay!==from)await this.storeReplay(event.name,record.id,from,replay)}}async storeReplay(eventName,subscriptionId,from,replay){const holder=this.holders.get(eventName);if(!holder?.holding||!await holder.renew())return;await this.options.store.update(subscriptionId,current=>isSameReadPosition(current.replay,from)?{replay}:{})}async reportGap(record,replay){if(!EVENT_DIALECTS[record.dialect].sendsControlEnvelopes)return{...replay,truncated:true};await this.options.outbox.enqueue({kind:"gap",subscriptionId:record.id,eventName:record.eventName,body:JSON.stringify({type:"gap",cursor:replay.watermark}),webhookId:generateWebhookMessageId2("gap")});const{truncated:_told,...told}=replay;return told}async advance(event,record,replay,maxAgeMs){const settled=await this.settled(replay);if(settled.pending.length>=MAX_PENDING_BATCHES)return{replay:settled,truncated:false,hasMore:false};const floor=settled.cursor!==null&&maxAgeMs!==void 0?Date.now()-maxAgeMs:void 0;const checked=await this.check(event,record,settled.cursor,floor===void 0?void 0:maxAgeMs);if(!checked)return{replay:settled,truncated:false,hasMore:false};const alreadyQueued=settled.queuedAtCursor??0;const deliveryIds=[];let skippedOldEvents=false;for(const[index,item]of checked.events.entries()){if(index<alreadyQueued)continue;const timestamp=item.timestamp??new Date().toISOString();if(floor!==void 0&&Date.parse(timestamp)<floor){skippedOldEvents=true;continue}try{const deliveryId=await this.enqueue(event,record,item,timestamp,settled.watermark);if(deliveryId)deliveryIds.push(deliveryId)}catch(failure){return{replay:this.partlyQueued(settled,index,deliveryIds),truncated:false,hasMore:false,failure}}}const{queuedAtCursor:_queued,...read}=settled;const batches=[...read.pending,{cursor:checked.cursor,deliveryIds}];return{replay:await this.settled({...read,cursor:checked.cursor,pending:batches}),truncated:checked.truncated===true||skippedOldEvents,hasMore:checked.hasMore===true,nextPollMs:checked.nextPollMs}}partlyQueued(settled,index,deliveryIds){const pending=deliveryIds.length>0?[...settled.pending,{cursor:settled.cursor,deliveryIds}]:settled.pending;return{...settled,pending,queuedAtCursor:index}}async check(event,record,cursor,maxAgeMs){const context=event.create({});const check=context.check;const limits={maxEvents:this.options.maxEvents,...maxAgeMs!==void 0&&{maxAgeMs}};try{return await check.call(context,record.arguments,cursor,limits)}catch(error){this.logger.warn(`check() of event "${event.name}" failed for subscription ${record.id}`,error);return void 0}}async enqueue(event,record,item,timestamp,watermark){let data;try{data=event.parsePayload(item.data)}catch(error){this.logger.warn(`check() of event "${event.name}" returned data that is not its payload`,error);return void 0}const eventId=item.eventId??newEventId();const body=JSON.stringify({eventId,name:event.name,timestamp,data,cursor:watermark});const bytes=encoder10.encode(body).byteLength;if(bytes>this.options.maxBodyBytes){this.logger.warn(`Event "${event.name}" is ${bytes} bytes for subscription ${record.id}, over the ${this.options.maxBodyBytes} byte limit; it is not delivered`);return void 0}const usesEventId=EVENT_DIALECTS[record.dialect].webhookId==="eventId";return this.options.outbox.enqueue({kind:"event",subscriptionId:record.id,eventName:event.name,body,webhookId:usesEventId?eventId:generateWebhookMessageId2()})}async settled(replay){const pending=[...replay.pending];let{watermark}=replay;while(pending.length>0){const[oldest]=pending;const stillPending=await Promise.all(oldest.deliveryIds.map(id=>this.options.outbox.isPending(id)));if(stillPending.some(Boolean))break;watermark=oldest.cursor;pending.shift()}return{...replay,watermark,pending}}}}});import{EventOccurrenceSchema as EventOccurrenceSchema6}from"@frontmcp/protocol";import{randomUUID as randomUUID31}from"@frontmcp/utils";function parseRelayed(message){let parsed;try{parsed=JSON.parse(message)}catch{return void 0}if(typeof parsed!=="object"||parsed===null)return void 0;const{origin,occurrence,audience,subscriptionId}=parsed;const checked=EventOccurrenceSchema6.safeParse(occurrence);if(typeof origin!=="string"||!checked.success)return void 0;if(subscriptionId!==void 0&&typeof subscriptionId!=="string")return void 0;if(audience!==void 0&&(typeof audience!=="object"||audience===null))return void 0;return{origin,occurrence:checked.data,audience,subscriptionId}}var EVENT_RELAY_CHANNEL,MAX_OPEN_STREAMS,EventStreams;var init_event_streams=__esm({"libs/sdk/src/event/stream/event-streams.ts"(){"use strict";EVENT_RELAY_CHANNEL="occurrences";MAX_OPEN_STREAMS=1e4;EventStreams=class{constructor(options){this.options=options;this.nodeId=randomUUID31();this.logger=options.logger.child("EventStreams")}options;streams=new Map;held=new Set;nodeId;logger;stopRelay;get isRelayed(){return this.options.storage?.supportsPubSub()===true}get size(){return this.held.size}async start(){const{storage}=this.options;if(!storage||!this.isRelayed)return;this.stopRelay=await storage.subscribe(EVENT_RELAY_CHANNEL,message=>this.receive(message))}async stop(){await this.stopRelay?.();this.stopRelay=void 0;for(const streams of[...this.streams.values()]){for(const stream of[...streams])stream.close()}}isFull(principalKey){if(this.held.size>=MAX_OPEN_STREAMS)return true;let heldByOwner=0;for(const stream of this.held){if(stream.principalKey===principalKey)heldByOwner+=1}return heldByOwner>=this.options.maxPerPrincipal}reserve(stream){if(this.held.has(stream))return true;if(this.isFull(stream.principalKey))return false;this.hold(stream);return true}add(stream){this.hold(stream);if(stream.isClosed)return;const streams=this.streams.get(stream.eventName)??new Set;this.streams.set(stream.eventName,streams);streams.add(stream)}hold(stream){if(this.held.has(stream)||stream.isClosed)return;this.held.add(stream);stream.onClose(()=>{this.held.delete(stream);this.streams.get(stream.eventName)?.delete(stream)})}async publish(buffered){await this.deliver(buffered);const{storage}=this.options;if(!storage||!this.isRelayed)return;const{occurrence,audience,subscriptionId}=buffered;const relayed={origin:this.nodeId,occurrence,audience,subscriptionId};try{await storage.publish(EVENT_RELAY_CHANNEL,JSON.stringify(relayed))}catch(error){this.logger.warn(`Event "${occurrence.name}" was not relayed to the other processes`,error)}}async deliver(buffered){const streams=this.streams.get(buffered.occurrence.name);if(!streams)return;await Promise.all([...streams].map(stream=>stream.offer(buffered)))}receive(message){const relayed=parseRelayed(message);if(!relayed||relayed.origin===this.nodeId)return;const buffered=this.options.buffer.append(relayed.occurrence,relayed.audience,relayed.subscriptionId);this.deliver(buffered).catch(error=>this.logger.warn("A relayed event was not delivered",error))}}}});import{MCP_SUBSCRIPTION_ID_HEADER as MCP_SUBSCRIPTION_ID_HEADER3,MCP_WEBHOOK_RECEIVER_WELL_KNOWN_PATH}from"@frontmcp/protocol";import{base64urlEncode as base64urlEncode7,generateWebhookMessageId as generateWebhookMessageId3,outboundFailureCategory as outboundFailureCategory2,randomBytes as randomBytes8,sendOutboundRequest as sendOutboundRequest2,sha256Hex as sha256Hex29,signingKeyOf as signingKeyOf3,timingSafeEqual as timingSafeEqual5,webhookSignatureHeaders as webhookSignatureHeaders2}from"@frontmcp/utils";function isSameText(left,right){const leftBytes=encoder11.encode(left);const rightBytes=encoder11.encode(right);return leftBytes.length===rightBytes.length&&timingSafeEqual5(leftBytes,rightBytes)}function isUnderAllowedPrefix(callback,prefix){if(!URL.canParse(prefix))return false;const allowed=new URL(prefix);if(allowed.origin!==callback.origin)return false;if(callback.pathname===allowed.pathname)return true;const directory=allowed.pathname.endsWith("/")?allowed.pathname:`${allowed.pathname}/`;return callback.pathname.startsWith(directory)}function receiversOf(result){if(!result.answered||result.status!==200||result.bodyTruncated)return[];try{const receivers=JSON.parse(result.body)?.receivers;if(!Array.isArray(receivers))return[];return receivers.filter(prefix=>typeof prefix==="string"&&prefix.startsWith("/"))}catch{return[]}}function challengeOf(answerBody){try{const challenge=JSON.parse(answerBody)?.challenge;return typeof challenge==="string"?challenge:void 0}catch{return void 0}}var VERIFICATION_ATTEMPTS_PER_HOST,VERIFICATION_WINDOW_MS,WELL_KNOWN_CACHE_MS,WELL_KNOWN_MAX_BYTES,CHALLENGE_BYTES,CHALLENGE_ANSWER_MAX_BYTES,MAX_CACHED_ENTRIES,encoder11,ExpiringMap,EventCallbackVerifier;var init_event_callback_verifier=__esm({"libs/sdk/src/event/subscription/event-callback-verifier.ts"(){"use strict";init_event_outbound();VERIFICATION_ATTEMPTS_PER_HOST=10;VERIFICATION_WINDOW_MS=6e4;WELL_KNOWN_CACHE_MS=3e5;WELL_KNOWN_MAX_BYTES=65536;CHALLENGE_BYTES=32;CHALLENGE_ANSWER_MAX_BYTES=4096;MAX_CACHED_ENTRIES=5e3;encoder11=new TextEncoder;ExpiringMap=class{entries=new Map;get(key,now){const entry=this.entries.get(key);if(!entry)return void 0;if(entry.expiresAt>now)return entry.value;this.entries.delete(key);return void 0}set(key,value,expiresAt){this.entries.delete(key);if(this.entries.size>=MAX_CACHED_ENTRIES){const oldestKey=this.entries.keys().next().value;if(oldestKey!==void 0)this.entries.delete(oldestKey)}this.entries.set(key,{value,expiresAt})}};EventCallbackVerifier=class{constructor(options){this.options=options;this.send=options.send??sendOutboundRequest2;this.maxAttemptsPerHost=options.maxAttemptsPerHost??VERIFICATION_ATTEMPTS_PER_HOST}options;verifiedPairs=new ExpiringMap;receiversByOrigin=new ExpiringMap;attemptsByHost=new ExpiringMap;send;maxAttemptsPerHost;async verify(request2){const now=Date.now();const{allowedCallbacks,cacheTtlMs}=this.options;const callback=new URL(request2.url);if(allowedCallbacks.some(prefix=>isUnderAllowedPrefix(callback,prefix))){return{outcome:"verified",verifiedAt:now}}const pairKey=sha256Hex29(`${request2.principalKey}
334
+ `;RedisTransportBus=class{constructor(redis,machineId,options){this.redis=redis;this.machineId=machineId;this.keyPrefix=options?.keyPrefix??DEFAULT_BUS_PREFIX;this.ttlSeconds=options?.ttlSeconds??DEFAULT_BUS_TTL_SECONDS;this.haKeyPrefix=options?.haKeyPrefix??"mcp:ha:";this.retryAfterSeconds=options?.retryAfterSeconds??DEFAULT_RETRY_AFTER_SECONDS;this.logger=options?.logger}redis;machineId;keyPrefix;ttlSeconds;haKeyPrefix;retryAfterSeconds;logger;relay;nodeId(){return this.machineId}attachRelay(relay){this.relay=relay}canRelay(){return this.relay!==void 0}channelOf(nodeId){return`${this.haKeyPrefix}notify:${nodeId}`}async advertise(key){await this.redis.eval(ADVERTISE_LUA,1,this.busKey(key.sessionId),this.machineId,this.channelOf(this.machineId),key.type,key.tokenHash,this.ttlSeconds);this.logger?.debug("[TransportBus] Advertised session",{sessionId:key.sessionId.slice(0,20),nodeId:this.machineId})}async revoke(key){const redisKey=this.busKey(key.sessionId);const result=await this.redis.eval(REVOKE_LUA,1,redisKey,this.machineId);this.logger?.debug("[TransportBus] Revoked session",{sessionId:key.sessionId.slice(0,20),deleted:result===1})}async lookup(key){const entry=await this.readEntry(key.sessionId);if(!entry)return null;if(entry.nodeId===this.machineId)return null;if(entry.type&&entry.type!==key.type||entry.tokenHash&&entry.tokenHash!==key.tokenHash){return null}return{nodeId:entry.nodeId,channel:entry.channel}}async lookupOwner(sessionId){const entry=await this.readEntry(sessionId);return entry?{nodeId:entry.nodeId,channel:entry.channel}:null}async proxyRequest(location,sessionId,request2,response){if(isRelayedRequest(request2)){throw new SessionOwnerUnreachableError(location.nodeId,this.retryAfterSeconds,"the request was already relayed once and its session moved again")}if(!this.relay){throw new SessionOwnerUnreachableError(location.nodeId,this.retryAfterSeconds,"request relay is not available on this node (no Redis pub/sub)")}await this.relay.forward(location.nodeId,sessionId,serializeRelayRequest(request2),response)}async destroyRemote(key,reason){const entry=await this.readEntry(key.sessionId);if(!entry||entry.nodeId===this.machineId)return;const message=JSON.stringify({kind:"destroy-session",sessionId:key.sessionId,reason,sourceNodeId:this.machineId,timestamp:Date.now()});const receivers=await this.redis.publish(entry.channel,message);this.logger?.info("[TransportBus] Sent destroy-remote",{sessionId:key.sessionId.slice(0,20),targetNodeId:entry.nodeId});if(receivers>0)await this.untilReleased(key.sessionId,entry.nodeId)}async untilReleased(sessionId,ownerNodeId){let polling=true;let timer;const released=(async()=>{while(polling){await new Promise(resolve4=>setTimeout(resolve4,RELEASE_POLL_MS));if((await this.readEntry(sessionId))?.nodeId!==ownerNodeId)return true}return false})();const timedOut=new Promise(resolve4=>timer=setTimeout(()=>resolve4(false),RELEASE_TIMEOUT_MS));const releasedInTime=await Promise.race([released,timedOut]).finally(()=>{polling=false;clearTimeout(timer)});if(releasedInTime)return;this.logger?.warn("[TransportBus] The session owner did not release the session in time",{sessionId:sessionId.slice(0,20),ownerNodeId})}async readEntry(sessionId){const fields=await this.redis.hgetall(this.busKey(sessionId));const nodeId=fields?.["nodeId"];if(!nodeId)return null;return{nodeId,channel:fields["channel"]||this.channelOf(nodeId),type:fields["type"]||void 0,tokenHash:fields["tokenHash"]||void 0}}busKey(sessionId){return`${this.keyPrefix}session:${sessionId}`}}}});var bus_exports={};__export(bus_exports,{RedisTransportBus:()=>RedisTransportBus});var init_bus=__esm({"libs/sdk/src/transport/bus/index.ts"(){"use strict";init_redis_transport_bus()}});var MemoryEventStore;var init_memory_event_store=__esm({"libs/sdk/src/transport/event-stores/memory.event-store.ts"(){"use strict";MemoryEventStore=class{streams=new Map;index=new Map;maxEvents;ttlMs;constructor(options={}){this.maxEvents=options.maxEvents??1e4;this.ttlMs=options.ttlMs??3e5}async storeEvent(streamId,message){this.evictExpired();const list=this.streams.get(streamId)??[];const id=`${streamId}:${list.length+1}`;const rec={id,msg:message,timestamp:Date.now()};list.push(rec);this.streams.set(streamId,list);this.index.set(id,{streamId,idx:list.length-1});if(this.index.size>this.maxEvents){this.evictOldest()}return id}async getStreamIdForEventId(eventId){return this.index.get(eventId)?.streamId}async replayEventsAfter(lastEventId,{send}){const meta=this.index.get(lastEventId);if(!meta){const freshStream="default-stream";if(!this.streams.has(freshStream))this.streams.set(freshStream,[]);return freshStream}const{streamId,idx}=meta;const list=this.streams.get(streamId)??[];for(let k=idx+1;k<list.length;k++){const e=list[k];if(Date.now()-e.timestamp<this.ttlMs){await send(e.id,e.msg)}}return streamId}evictExpired(){const now=Date.now();for(const[streamId,list]of this.streams){const validEvents=list.filter(e=>now-e.timestamp<this.ttlMs);if(validEvents.length<list.length){this.streams.set(streamId,validEvents);this.rebuildIndex(streamId,validEvents)}}}evictOldest(){let oldest=null;for(const[streamId,list]of this.streams){if(list.length>0&&(!oldest||list[0].timestamp<oldest.timestamp)){oldest={streamId,idx:0,timestamp:list[0].timestamp}}}if(oldest){const list=this.streams.get(oldest.streamId);if(list&&list.length>0){const removed=list.shift();if(removed){this.index.delete(removed.id)}this.rebuildIndex(oldest.streamId,list)}}}rebuildIndex(streamId,list){for(const[id,meta]of this.index){if(meta.streamId===streamId){this.index.delete(id)}}list.forEach((e,idx)=>this.index.set(e.id,{streamId,idx}))}clear(){this.streams.clear();this.index.clear()}get size(){return this.index.size}}}});import{attachRedisErrorListener as attachRedisErrorListener2}from"@frontmcp/utils";var RedisEventStore;var init_redis_event_store=__esm({"libs/sdk/src/transport/event-stores/redis.event-store.ts"(){"use strict";init_common();init_schema5();init_mcp_error();init_sdk_errors();RedisEventStore=class{client;keyPrefix;maxEvents;ttlSeconds;redisOptions;constructor(options){this.redisOptions=options.redis;this.keyPrefix=options.keyPrefix??"mcp:events:";this.maxEvents=options.maxEvents??1e4;this.ttlSeconds=Math.ceil((options.ttlMs??3e5)/1e3)}async getClient(){if(!this.client){const redis=normalizeRedisOptions(this.redisOptions);if(typeof redis==="string"){throw new InternalMcpError(`The event store's redis option cannot be used: ${redis}. Give a Redis url, or a host.`,"INVALID_REDIS_CONFIG")}if(isVercelKvProvider(redis)){throw new VercelKvNotSupportedError("Redis Streams (required for EventStore). Use standard Redis provider instead")}const Redis=__require("ioredis");const{host,port,password,db,tls}=redis;this.client=new Redis({host,port,password,db,tls:tls?{}:void 0,lazyConnect:true,enableReadyCheck:false,maxRetriesPerRequest:3});attachRedisErrorListener2(this.client,{label:"RedisEventStore"});await this.client.connect()}return this.client}async storeEvent(streamId,message){const client=await this.getClient();const streamKey=`${this.keyPrefix}${streamId}`;const redisId=await client.xadd(streamKey,"MAXLEN","~",this.maxEvents.toString(),"*","msg",JSON.stringify(message));await client.expire(streamKey,this.ttlSeconds);return`${streamId}:${redisId}`}async getStreamIdForEventId(eventId){const parsed=this.parseEventId(eventId);return parsed?parsed[0]:void 0}async replayEventsAfter(lastEventId,{send}){const parsed=this.parseEventId(lastEventId);if(!parsed){return"default-stream"}const client=await this.getClient();const[streamId,redisId]=parsed;const streamKey=`${this.keyPrefix}${streamId}`;const entries=await client.xrange(streamKey,`(${redisId}`,"+");for(const[id,fields]of entries){const msgIndex=fields.indexOf("msg");if(msgIndex!==-1&&msgIndex+1<fields.length){const msgStr=fields[msgIndex+1];const msg=JSON.parse(msgStr);await send(`${streamId}:${id}`,msg)}}return streamId}parseEventId(eventId){const value=String(eventId);const lastDash=value.lastIndexOf("-");const separator=lastDash===-1?value.lastIndexOf(":"):value.lastIndexOf(":",lastDash);if(separator<=0||separator===value.length-1)return void 0;const streamId=value.slice(0,separator);const redisId=value.slice(separator+1);if(!/^\d+(-\d+)?$/.test(redisId))return void 0;return[streamId,redisId]}async close(){if(this.client){await this.client.quit();this.client=void 0}}}}});function createEventStore(config,logger){if(!config?.enabled){logger?.verbose("[EventStoreFactory] EventStore disabled (resumability not available)");return{eventStore:void 0,type:"disabled"}}const provider=config.provider??"memory";const maxEvents=config.maxEvents??1e4;const ttlMs=config.ttlMs??3e5;if(provider==="sqlite"){if(!config.sqlite||!config.sqlite.path){throw new PublicMcpError('EventStore SQLite configuration required when provider is "sqlite". Provide sqlite config: { provider: "sqlite", sqlite: { path: "..." } }',"INVALID_PARAMS")}const{SqliteEventStore}=requireOptionalModule("@frontmcp/storage-sqlite",()=>require_dist());logger?.info("[EventStoreFactory] Creating SQLite EventStore for resumability",{maxEvents,ttlMs,path:config.sqlite.path});return{eventStore:new SqliteEventStore({...config.sqlite,maxEvents,ttlMs}),type:"sqlite"}}if(provider==="redis"){if(!config.redis){throw new PublicMcpError('EventStore Redis configuration required when provider is "redis". Provide redis config: { provider: "redis", host: "...", port: ... }',"INVALID_PARAMS")}logger?.info("[EventStoreFactory] Creating Redis EventStore for resumability",{maxEvents,ttlMs});return{eventStore:new RedisEventStore({redis:config.redis,maxEvents,ttlMs}),type:"redis"}}logger?.info("[EventStoreFactory] Creating in-memory EventStore for resumability",{maxEvents,ttlMs});return{eventStore:new MemoryEventStore({maxEvents,ttlMs}),type:"memory"}}var init_event_store_factory=__esm({"libs/sdk/src/transport/event-stores/event-store.factory.ts"(){"use strict";init_errors();init_optional_dependency_util();init_memory_event_store();init_redis_event_store()}});var event_stores_exports={};__export(event_stores_exports,{MemoryEventStore:()=>MemoryEventStore,RedisEventStore:()=>RedisEventStore,createEventStore:()=>createEventStore,createSessionScopedEventStore:()=>createSessionScopedEventStore});var init_event_stores=__esm({"libs/sdk/src/transport/event-stores/index.ts"(){"use strict";init_event_store_factory();init_memory_event_store();init_redis_event_store();init_session_scoped_event_store()}});var EncryptedElicitationStore;var init_encrypted_elicitation_store=__esm({"libs/sdk/src/elicitation/store/encrypted-elicitation.store.ts"(){"use strict";init_errors();init_elicitation_encryption();EncryptedElicitationStore=class{store;secret;logger;constructor(store,options={}){this.store=store;this.secret=options.secret;this.logger=options.logger}async setPending(record){const{sessionId}=record;try{const encrypted=await encryptElicitationData(record,sessionId,this.secret);await this.store.setPending({sessionId:record.sessionId,elicitId:record.elicitId,createdAt:record.createdAt,expiresAt:record.expiresAt,__encrypted:encrypted});this.logger?.debug("[EncryptedElicitationStore] Stored encrypted pending record",{sessionId:sessionId.slice(0,8)+"...",elicitId:record.elicitId})}catch(error){this.logger?.error("[EncryptedElicitationStore] Failed to encrypt pending record",{sessionId:sessionId.slice(0,8)+"...",error:error instanceof Error?error.message:String(error)});throw error}}async getPending(sessionId){const stored=await this.store.getPending(sessionId);if(!stored){return null}return this.decryptPendingRecord(stored,sessionId)}async deletePending(sessionId){await this.store.deletePending(sessionId)}async subscribeResult(elicitId,callback,sessionId){const decryptingCallback=async rawResult=>{if(sessionId&&isEncryptedBlob(rawResult)){try{const decrypted=await decryptElicitationData(rawResult,sessionId,this.secret);if(decrypted){callback(decrypted);return}this.logger?.warn("[EncryptedElicitationStore] Failed to decrypt pub/sub message (null result)",{elicitId});return}catch(error){this.logger?.warn("[EncryptedElicitationStore] Failed to decrypt pub/sub message",{elicitId,error:error instanceof Error?error.message:String(error)});return}}callback(rawResult)};return this.store.subscribeResult(elicitId,decryptingCallback,sessionId)}async publishResult(elicitId,sessionId,result){try{const encrypted=await encryptElicitationData(result,sessionId,this.secret);await this.store.publishResult(elicitId,sessionId,encrypted);this.logger?.debug("[EncryptedElicitationStore] Published encrypted result",{elicitId,sessionId:sessionId.slice(0,8)+"..."})}catch(error){this.logger?.error("[EncryptedElicitationStore] Failed to encrypt pub/sub result",{elicitId,error:error instanceof Error?error.message:String(error)});throw error}}async setPendingFallback(record){const{sessionId,elicitId}=record;try{const encrypted=await encryptElicitationData(record,sessionId,this.secret);await this.store.setPendingFallback({sessionId:record.sessionId,elicitId:record.elicitId,createdAt:record.createdAt,expiresAt:record.expiresAt,__encrypted:encrypted});this.logger?.debug("[EncryptedElicitationStore] Stored encrypted pending fallback",{elicitId,sessionId:sessionId.slice(0,8)+"..."})}catch(error){this.logger?.error("[EncryptedElicitationStore] Failed to encrypt pending fallback",{elicitId,error:error instanceof Error?error.message:String(error)});throw error}}async getPendingFallback(elicitId,sessionId){const stored=await this.store.getPendingFallback(elicitId);if(!stored){return null}return this.decryptFallbackRecord(stored,sessionId)}async deletePendingFallback(elicitId){await this.store.deletePendingFallback(elicitId)}async setResolvedResult(elicitId,result,sessionId){if(!sessionId){throw new ElicitationEncryptionError(`Cannot store encrypted resolved result without sessionId (elicitId: ${elicitId})`)}try{const record={elicitId,result,resolvedAt:Date.now()};const encrypted=await encryptElicitationData(record,sessionId,this.secret);await this.store.setResolvedResult(elicitId,{__encrypted:encrypted},sessionId);this.logger?.debug("[EncryptedElicitationStore] Stored encrypted resolved result",{elicitId,sessionId:sessionId.slice(0,8)+"..."})}catch(error){if(error instanceof ElicitationEncryptionError){throw error}const originalError=error instanceof Error?error:void 0;throw new ElicitationEncryptionError(`Failed to encrypt resolved result (elicitId: ${elicitId})`,originalError)}}async getResolvedResult(elicitId,sessionId){const stored=await this.store.getResolvedResult(elicitId);if(!stored){return null}return this.decryptResolvedRecord(stored,sessionId)}async deleteResolvedResult(elicitId){await this.store.deleteResolvedResult(elicitId)}async subscribeFallbackResult(elicitId,callback,sessionId){const decryptingCallback=async rawResult=>{if(sessionId&&isEncryptedBlob(rawResult)){try{const decrypted=await decryptElicitationData(rawResult,sessionId,this.secret);if(decrypted){callback(decrypted);return}this.logger?.warn("[EncryptedElicitationStore] Failed to decrypt fallback pub/sub message (null result)",{elicitId});return}catch(error){this.logger?.warn("[EncryptedElicitationStore] Failed to decrypt fallback pub/sub message",{elicitId,error:error instanceof Error?error.message:String(error)});return}}callback(rawResult)};return this.store.subscribeFallbackResult(elicitId,decryptingCallback,sessionId)}async publishFallbackResult(elicitId,sessionId,result){try{const encrypted=await encryptElicitationData(result,sessionId,this.secret);await this.store.publishFallbackResult(elicitId,sessionId,encrypted);this.logger?.debug("[EncryptedElicitationStore] Published encrypted fallback result",{elicitId,sessionId:sessionId.slice(0,8)+"..."})}catch(error){this.logger?.error("[EncryptedElicitationStore] Failed to encrypt fallback result",{elicitId,error:error instanceof Error?error.message:String(error)});throw error}}async destroy(){await this.store.destroy?.()}async decryptPendingRecord(stored,sessionId){const encryptedBlob=stored.__encrypted;if(!encryptedBlob||!isEncryptedBlob(encryptedBlob)){this.logger?.debug("[EncryptedElicitationStore] Plaintext fallback for pending record (migration)",{sessionId:sessionId.slice(0,8)+"...",elicitId:stored.elicitId});return stored}try{const decrypted=await decryptElicitationData(encryptedBlob,sessionId,this.secret);if(decrypted){this.logger?.debug("[EncryptedElicitationStore] Decrypted pending record",{sessionId:sessionId.slice(0,8)+"...",elicitId:decrypted.elicitId});return decrypted}this.logger?.warn("[EncryptedElicitationStore] Failed to decrypt pending record",{sessionId:sessionId.slice(0,8)+"..."});return null}catch(error){this.logger?.warn("[EncryptedElicitationStore] Decryption error for pending record",{sessionId:sessionId.slice(0,8)+"...",error:error instanceof Error?error.message:String(error)});return null}}async decryptFallbackRecord(stored,sessionId){const encryptedBlob=stored.__encrypted;if(!encryptedBlob||!isEncryptedBlob(encryptedBlob)){this.logger?.debug("[EncryptedElicitationStore] Plaintext fallback for fallback record (migration)",{elicitId:stored.elicitId});return stored}if(!sessionId){sessionId=stored.sessionId}if(!sessionId){this.logger?.warn("[EncryptedElicitationStore] Cannot decrypt fallback: no sessionId",{elicitId:stored.elicitId});return null}try{const decrypted=await decryptElicitationData(encryptedBlob,sessionId,this.secret);if(decrypted){this.logger?.debug("[EncryptedElicitationStore] Decrypted fallback record",{elicitId:decrypted.elicitId});return decrypted}this.logger?.warn("[EncryptedElicitationStore] Failed to decrypt fallback record",{elicitId:stored.elicitId});return null}catch(error){this.logger?.warn("[EncryptedElicitationStore] Decryption error for fallback record",{elicitId:stored.elicitId,error:error instanceof Error?error.message:String(error)});return null}}async decryptResolvedRecord(stored,sessionId){const encryptedResult=stored.result;const encryptedBlob=encryptedResult?.__encrypted;if(!encryptedBlob||!isEncryptedBlob(encryptedBlob)){this.logger?.debug("[EncryptedElicitationStore] Plaintext fallback for resolved result (migration)",{elicitId:stored.elicitId});return stored}if(!sessionId){this.logger?.warn("[EncryptedElicitationStore] Cannot decrypt resolved result: no sessionId",{elicitId:stored.elicitId});return null}try{const decrypted=await decryptElicitationData(encryptedBlob,sessionId,this.secret);if(decrypted){this.logger?.debug("[EncryptedElicitationStore] Decrypted resolved result",{elicitId:decrypted.elicitId});return decrypted}this.logger?.warn("[EncryptedElicitationStore] Failed to decrypt resolved result",{elicitId:stored.elicitId});return null}catch(error){this.logger?.warn("[EncryptedElicitationStore] Decryption error for resolved result",{elicitId:stored.elicitId,error:error instanceof Error?error.message:String(error)});return null}}}}});import{sha256Hex as sha256Hex22}from"@frontmcp/utils";function sessionIdHash(sessionId){return sha256Hex22(sessionId).slice(0,12)}var init_session_id_hash=__esm({"libs/sdk/src/logger/session-id-hash.ts"(){"use strict"}});import{expiresAtToTTL,TypedStorage}from"@frontmcp/utils";function elicitationResultRoute(sessionId,elicitId){return`${sessionId.replace(/%/g,"%25").replace(/:/g,"%3A")}:${elicitId}`}function requireSubscriberSession(elicitId,sessionId){if(!sessionId){throw new ElicitationSubscriptionError(elicitId,new Error("a result subscription needs the session ID the elicitation belongs to; pass it as the third argument"))}return sessionId}var RESOLVED_RESULT_TTL_SECONDS,RESULT_CHANNEL_PREFIX,FALLBACK_RESULT_CHANNEL_PREFIX,StorageElicitationStore;var init_storage_elicitation_store=__esm({"libs/sdk/src/elicitation/store/storage-elicitation.store.ts"(){"use strict";init_errors();init_session_id_hash();RESOLVED_RESULT_TTL_SECONDS=300;RESULT_CHANNEL_PREFIX="result:";FALLBACK_RESULT_CHANNEL_PREFIX="fallback-result:";StorageElicitationStore=class{storage;pending;fallback;resolved;logger;localCallbacks=new Map;activeSubscriptions=new Map;pendingSubscriptions=new Map;fallbackResultCallbacks=new Map;activeFallbackSubscriptions=new Map;pendingFallbackSubscriptions=new Map;constructor(storage,logger){this.storage=storage;this.logger=logger;this.pending=new TypedStorage(storage.namespace("pending"));this.fallback=new TypedStorage(storage.namespace("fallback"));this.resolved=new TypedStorage(storage.namespace("resolved"))}async setPending(record){const{sessionId,expiresAt}=record;const ttlSeconds=expiresAtToTTL(expiresAt);if(ttlSeconds<=0){this.logger?.warn("[StorageElicitationStore] Record already expired, not storing",{sessionIdHash:sessionIdHash(sessionId),elicitId:record.elicitId});return}await this.pending.set(sessionId,record,{ttlSeconds});this.logger?.debug("[StorageElicitationStore] Stored pending elicitation",{sessionIdHash:sessionIdHash(sessionId),elicitId:record.elicitId,ttlSeconds})}async getPending(sessionId){const record=await this.pending.get(sessionId);if(!record){return null}if(Date.now()>record.expiresAt){await this.deletePending(sessionId);return null}return record}async deletePending(sessionId){await this.pending.delete(sessionId);this.logger?.debug("[StorageElicitationStore] Deleted pending elicitation",{sessionIdHash:sessionIdHash(sessionId)})}async subscribeResult(elicitId,callback,sessionId){const route=elicitationResultRoute(requireSubscriberSession(elicitId,sessionId),elicitId);let callbacks=this.localCallbacks.get(route);if(!callbacks){callbacks=new Set;this.localCallbacks.set(route,callbacks)}callbacks.add(callback);if(!this.activeSubscriptions.has(route)&&!this.pendingSubscriptions.has(route)&&this.storage.supportsPubSub()){const channel2=RESULT_CHANNEL_PREFIX+route;const subscribePromise=this.storage.subscribe(channel2,message=>{try{const result=JSON.parse(message);const cbs=this.localCallbacks.get(route);if(cbs){for(const cb of cbs){try{cb(result)}catch(err){this.logger?.error("[StorageElicitationStore] Callback error",{elicitId,error:err instanceof Error?err.message:String(err)})}}}}catch(err){this.logger?.error("[StorageElicitationStore] Failed to parse result message",{elicitId,error:err instanceof Error?err.message:String(err)})}}).then(unsubscribe=>{this.pendingSubscriptions.delete(route);this.activeSubscriptions.set(route,unsubscribe);return unsubscribe}).catch(err=>{this.pendingSubscriptions.delete(route);this.logger?.error("[StorageElicitationStore] Failed to subscribe",{elicitId,error:err instanceof Error?err.message:String(err)});throw err});this.pendingSubscriptions.set(route,subscribePromise);try{await subscribePromise}catch(error){callbacks.delete(callback);if(callbacks.size===0){this.localCallbacks.delete(route)}throw error}}else if(this.pendingSubscriptions.has(route)){try{await this.pendingSubscriptions.get(route)}catch(error){callbacks.delete(callback);if(callbacks.size===0){this.localCallbacks.delete(route)}throw error}}return async()=>{callbacks.delete(callback);if(callbacks.size===0){this.localCallbacks.delete(route);if(this.pendingSubscriptions.has(route)){try{await this.pendingSubscriptions.get(route)}catch{}}const unsubscribe=this.activeSubscriptions.get(route);if(unsubscribe){this.activeSubscriptions.delete(route);try{await unsubscribe()}catch(err){this.logger?.error("[StorageElicitationStore] Failed to unsubscribe",{elicitId,error:err instanceof Error?err.message:String(err)})}}}}}async publishResult(elicitId,sessionId,result){const route=elicitationResultRoute(sessionId,elicitId);if(this.storage.supportsPubSub()){const channel2=RESULT_CHANNEL_PREFIX+route;try{await this.storage.publish(channel2,JSON.stringify(result))}catch(err){this.logger?.error("[StorageElicitationStore] Failed to publish result",{elicitId,error:err instanceof Error?err.message:String(err)})}}else{const callbacks=this.localCallbacks.get(route);if(callbacks){for(const cb of callbacks){try{cb(result)}catch(err){this.logger?.error("[StorageElicitationStore] Callback error during publish",{elicitId,error:err instanceof Error?err.message:String(err)})}}}}await this.deletePending(sessionId);this.logger?.debug("[StorageElicitationStore] Published result",{elicitId,sessionIdHash:sessionIdHash(sessionId),status:result.status})}async setPendingFallback(record){const{elicitId,expiresAt}=record;const ttlSeconds=expiresAtToTTL(expiresAt);if(ttlSeconds<=0){this.logger?.warn("[StorageElicitationStore] Fallback record already expired, not storing",{elicitId});return}await this.fallback.set(elicitId,record,{ttlSeconds});this.logger?.debug("[StorageElicitationStore] Stored pending fallback",{elicitId,ttlSeconds})}async getPendingFallback(elicitId,_sessionId){const record=await this.fallback.get(elicitId);if(!record){return null}if(Date.now()>record.expiresAt){await this.deletePendingFallback(elicitId);return null}return record}async deletePendingFallback(elicitId){await this.fallback.delete(elicitId);this.logger?.debug("[StorageElicitationStore] Deleted pending fallback",{elicitId})}async setResolvedResult(elicitId,result,_sessionId){const record={elicitId,result,resolvedAt:Date.now()};await this.resolved.set(elicitId,record,{ttlSeconds:RESOLVED_RESULT_TTL_SECONDS});this.logger?.debug("[StorageElicitationStore] Stored resolved result",{elicitId})}async getResolvedResult(elicitId,_sessionId){return this.resolved.get(elicitId)}async deleteResolvedResult(elicitId){await this.resolved.delete(elicitId);this.logger?.debug("[StorageElicitationStore] Deleted resolved result",{elicitId})}async subscribeFallbackResult(elicitId,callback,sessionId){const route=elicitationResultRoute(requireSubscriberSession(elicitId,sessionId),elicitId);let callbacks=this.fallbackResultCallbacks.get(route);if(!callbacks){callbacks=new Set;this.fallbackResultCallbacks.set(route,callbacks)}callbacks.add(callback);if(!this.activeFallbackSubscriptions.has(route)&&!this.pendingFallbackSubscriptions.has(route)&&this.storage.supportsPubSub()){const channel2=FALLBACK_RESULT_CHANNEL_PREFIX+route;const subscribePromise=this.storage.subscribe(channel2,message=>{try{const result=JSON.parse(message);const cbs=this.fallbackResultCallbacks.get(route);if(cbs){for(const cb of cbs){try{cb(result)}catch(err){this.logger?.error("[StorageElicitationStore] Fallback callback error",{elicitId,error:err instanceof Error?err.message:String(err)})}}}}catch(err){this.logger?.error("[StorageElicitationStore] Failed to parse fallback result message",{elicitId,error:err instanceof Error?err.message:String(err)})}}).then(unsubscribe=>{this.pendingFallbackSubscriptions.delete(route);this.activeFallbackSubscriptions.set(route,unsubscribe);return unsubscribe}).catch(err=>{this.pendingFallbackSubscriptions.delete(route);this.logger?.error("[StorageElicitationStore] Failed to subscribe to fallback result",{elicitId,error:err instanceof Error?err.message:String(err)});throw err});this.pendingFallbackSubscriptions.set(route,subscribePromise);try{await subscribePromise}catch(error){callbacks.delete(callback);if(callbacks.size===0){this.fallbackResultCallbacks.delete(route)}throw error}}else if(this.pendingFallbackSubscriptions.has(route)){try{await this.pendingFallbackSubscriptions.get(route)}catch(error){callbacks.delete(callback);if(callbacks.size===0){this.fallbackResultCallbacks.delete(route)}throw error}}return async()=>{callbacks.delete(callback);if(callbacks.size===0){this.fallbackResultCallbacks.delete(route);if(this.pendingFallbackSubscriptions.has(route)){try{await this.pendingFallbackSubscriptions.get(route)}catch{}}const unsubscribe=this.activeFallbackSubscriptions.get(route);if(unsubscribe){this.activeFallbackSubscriptions.delete(route);try{await unsubscribe()}catch(err){this.logger?.error("[StorageElicitationStore] Failed to unsubscribe from fallback result",{elicitId,error:err instanceof Error?err.message:String(err)})}}}}}async publishFallbackResult(elicitId,sessionId,result){const route=elicitationResultRoute(sessionId,elicitId);if(this.storage.supportsPubSub()){const channel2=FALLBACK_RESULT_CHANNEL_PREFIX+route;try{await this.storage.publish(channel2,JSON.stringify(result))}catch(err){this.logger?.error("[StorageElicitationStore] Failed to publish fallback result",{elicitId,error:err instanceof Error?err.message:String(err)})}}else{const callbacks=this.fallbackResultCallbacks.get(route);if(callbacks){for(const cb of callbacks){try{cb(result)}catch(err){this.logger?.error("[StorageElicitationStore] Fallback callback error during publish",{elicitId,error:err instanceof Error?err.message:String(err)})}}}}this.logger?.debug("[StorageElicitationStore] Published fallback result",{elicitId,sessionIdHash:sessionIdHash(sessionId),success:result.success})}async destroy(){for(const pendingPromise of this.pendingSubscriptions.values()){try{await pendingPromise}catch(err){this.logger?.debug("[StorageElicitationStore] Pending subscription failed during destroy",{error:err instanceof Error?err.message:String(err)})}}for(const unsubscribe of this.activeSubscriptions.values()){try{await unsubscribe()}catch(err){this.logger?.error("[StorageElicitationStore] Failed to unsubscribe during destroy",{error:err instanceof Error?err.message:String(err)})}}for(const pendingPromise of this.pendingFallbackSubscriptions.values()){try{await pendingPromise}catch(err){this.logger?.debug("[StorageElicitationStore] Pending fallback subscription failed during destroy",{error:err instanceof Error?err.message:String(err)})}}for(const unsubscribe of this.activeFallbackSubscriptions.values()){try{await unsubscribe()}catch(err){this.logger?.error("[StorageElicitationStore] Failed to unsubscribe fallback during destroy",{error:err instanceof Error?err.message:String(err)})}}this.pendingSubscriptions.clear();this.activeSubscriptions.clear();this.localCallbacks.clear();this.pendingFallbackSubscriptions.clear();this.activeFallbackSubscriptions.clear();this.fallbackResultCallbacks.clear();this.logger?.debug("[StorageElicitationStore] Destroyed")}}}});var elicitation_store_factory_exports={};__export(elicitation_store_factory_exports,{createElicitationStore:()=>createElicitationStore,createElicitationStoreFromStorage:()=>createElicitationStoreFromStorage,createMemoryElicitationStore:()=>createMemoryElicitationStore,createSqliteElicitationStore:()=>createSqliteElicitationStore});import{createMemoryStorage,createStorage as createStorage5,getEnv as getEnv15}from"@frontmcp/utils";function detectStorageType(storage,configuredType){if(configuredType==="redis"||configuredType==="upstash"||configuredType==="memory"){return configuredType}const backend=storage.type??storage.backendName;if(backend==="redis"||backend==="upstash"||backend==="memory"){return backend}if(getEnv15("UPSTASH_REDIS_REST_URL")){return"upstash"}if(getEnv15("REDIS_URL")||getEnv15("REDIS_HOST")){return"redis"}return"memory"}async function createElicitationStore(options={}){const{storage:storageConfig,redis,sqlite,keyPrefix="mcp:elicit:",logger,isEdgeRuntime:isEdgeRuntime4=false,requiresPubSub=true,encryption}=options;if(sqlite){if(isEdgeRuntime4&&!hasSqliteDriver()){throw new ElicitationNotSupportedError(`SQLite elicitation store is not supported on Edge runtime without a SQLite driver (better-sqlite3 is a native module). ${SQLITE_ON_EDGE_REMEDY} Otherwise use Redis or Upstash instead.`)}let sqliteStore=createSqliteElicitationStore(sqlite,{keyPrefix,logger});let encrypted2=false;const encryptionEnabled2=encryption?.enabled??"auto";const encryptionSecret2=encryption?.secret;const hasSecret2=encryptionSecret2||isElicitationEncryptionAvailable();if(encryptionEnabled2===true){if(!hasSecret2){throw missingEncryptionSecretError()}sqliteStore=new EncryptedElicitationStore(sqliteStore,{secret:encryptionSecret2,logger});encrypted2=true}else if(encryptionEnabled2==="auto"&&hasSecret2){sqliteStore=new EncryptedElicitationStore(sqliteStore,{secret:encryptionSecret2,logger});encrypted2=true}logger?.info("[ElicitationStoreFactory] Created elicitation store",{type:"sqlite",keyPrefix,supportsPubSub:true,encrypted:encrypted2});return{store:sqliteStore,type:"sqlite",encrypted:encrypted2}}let finalStorageConfig=storageConfig;if(redis&&!storageConfig){const redisOptions=normalizeRedisOptions(redis);if(typeof redisOptions==="string"){throw new ElicitationNotSupportedError(`Invalid Redis configuration: ${redisOptions}`)}if(isVercelKvProvider(redisOptions)){throw new ElicitationNotSupportedError('Vercel KV is not supported for elicitation stores. Elicitation requires pub/sub for cross-node result routing, which Vercel KV does not support. Use Redis provider instead: { provider: "redis", host: "...", port: ... }')}const{host,port,password,db,tls}=redisOptions;finalStorageConfig={type:"redis",redis:{config:{host,port,password,db,tls}}};logger?.debug("[ElicitationStoreFactory] Converted redis option to storage config",{host,port})}const explicitBackend=Boolean(storageConfig||redis);if(finalStorageConfig?.type==="vercel-kv"||!explicitBackend&&getEnv15("KV_REST_API_URL")){throw new ElicitationNotSupportedError("Vercel KV is not supported for elicitation stores. Elicitation requires pub/sub for cross-node result routing, which Vercel KV does not support. Use Redis or Upstash instead.")}if(isEdgeRuntime4&&(!finalStorageConfig||finalStorageConfig.type==="memory")){throw new ElicitationNotSupportedError("Elicitation requires distributed storage when running on Edge runtime. Edge functions are stateless and cannot use in-memory elicitation. Configure Redis or Upstash storage.")}const storage=await createStorage5({...finalStorageConfig,prefix:keyPrefix,fallback:isEdgeRuntime4?"error":"memory"});if(requiresPubSub&&!storage.supportsPubSub()){throw new ElicitationNotSupportedError("Elicitation requires pub/sub support for cross-node result routing. The configured storage backend does not support pub/sub. Use Memory (single-node), Redis, or Upstash storage.")}let store=new StorageElicitationStore(storage,logger);const type=detectStorageType(storage,finalStorageConfig?.type);const encryptionEnabled=encryption?.enabled??"auto";const encryptionSecret=encryption?.secret;const hasSecret=encryptionSecret||isElicitationEncryptionAvailable();let encrypted=false;if(encryptionEnabled===true){if(!hasSecret){throw missingEncryptionSecretError()}store=new EncryptedElicitationStore(store,{secret:encryptionSecret,logger});encrypted=true}else if(encryptionEnabled==="auto"&&hasSecret){store=new EncryptedElicitationStore(store,{secret:encryptionSecret,logger});encrypted=true}logger?.info("[ElicitationStoreFactory] Created elicitation store",{type,keyPrefix,supportsPubSub:storage.supportsPubSub(),encrypted});return{store,type,storage,encrypted}}function createMemoryElicitationStore(options={}){const{keyPrefix="mcp:elicit:",logger,encryption}=options;const storage=createMemoryStorage({prefix:keyPrefix});let store=new StorageElicitationStore(storage,logger);const encryptionEnabled=encryption?.enabled??"auto";const encryptionSecret=encryption?.secret;const hasSecret=encryptionSecret||isElicitationEncryptionAvailable();let encrypted=false;if(encryptionEnabled===true&&!hasSecret)throw missingEncryptionSecretError();if(encryptionEnabled===true&&hasSecret){store=new EncryptedElicitationStore(store,{secret:encryptionSecret,logger});encrypted=true}else if(encryptionEnabled==="auto"&&hasSecret){store=new EncryptedElicitationStore(store,{secret:encryptionSecret,logger});encrypted=true}logger?.debug("[ElicitationStoreFactory] Created explicit in-memory elicitation store",{encrypted});return{store,type:"memory",storage,encrypted}}function missingEncryptionSecretError(){return new ElicitationNotSupportedError("Elicitation encryption is enabled but no secret is available. Set MCP_ELICITATION_SECRET, MCP_SESSION_SECRET, or MCP_SERVER_SECRET environment variable, or provide a secret in the encryption configuration.")}function createElicitationStoreFromStorage(storage,options={}){const{keyPrefix="mcp:elicit:",logger,requiresPubSub=true,encryption}=options;if(requiresPubSub&&!storage.supportsPubSub()){throw new ElicitationNotSupportedError("Elicitation requires pub/sub support for cross-node result routing. The provided storage does not support pub/sub.")}const namespacedStorage=storage.namespace(keyPrefix.replace(/:$/,""));let store=new StorageElicitationStore(namespacedStorage,logger);const type=detectStorageType(storage);const encryptionEnabled=encryption?.enabled??"auto";const encryptionSecret=encryption?.secret;const hasSecret=encryptionSecret||isElicitationEncryptionAvailable();let encrypted=false;if(encryptionEnabled===true&&!hasSecret)throw missingEncryptionSecretError();if(encryptionEnabled===true&&hasSecret){store=new EncryptedElicitationStore(store,{secret:encryptionSecret,logger});encrypted=true}else if(encryptionEnabled==="auto"&&hasSecret){store=new EncryptedElicitationStore(store,{secret:encryptionSecret,logger});encrypted=true}logger?.debug("[ElicitationStoreFactory] Created elicitation store from existing storage",{type,keyPrefix,encrypted});return{store,type,storage,encrypted}}function createSqliteElicitationStore(sqliteConfig,storeOptions={}){const{keyPrefix="mcp:elicit:",logger}=storeOptions;const{SqliteElicitationStore}=requireOptionalModule("@frontmcp/storage-sqlite",()=>require_dist());logger?.info("[ElicitationStoreFactory] Creating SQLite elicitation store",{path:sqliteConfig.path,keyPrefix});return new SqliteElicitationStore({...sqliteConfig,keyPrefix})}var init_elicitation_store_factory=__esm({"libs/sdk/src/elicitation/store/elicitation-store.factory.ts"(){"use strict";init_common();init_schema5();init_elicitation_error();init_optional_dependency_util();init_sqlite_on_edge();init_elicitation_encryption();init_encrypted_elicitation_store();init_storage_elicitation_store()}});var task_session_index_exports={};__export(task_session_index_exports,{TaskSessionIndex:()=>TaskSessionIndex});import{expiresAtToTTL as expiresAtToTTL2,randomUUID as randomUUID24}from"@frontmcp/utils";function readyMarkerOf(readiness){if(!readiness?.startsWith(BACKFILLED))return void 0;const[generation,count]=readiness.slice(BACKFILLED.length).split(":");return{generation,count:Number(count??0)}}function sessionTaskKey(sessionId,suffix){return`${sessionId}:${suffix}`}async function mgetInBatches(read,keys){const values=[];for(let start=0;start<keys.length;start+=READ_BATCH_SIZE){values.push(...await read(keys.slice(start,start+READ_BATCH_SIZE)))}return values}var POSITION_GRACE_SECONDS,BACKFILL_CLAIM_TTL_SECONDS,POSITION_WRITE_SECONDS,SETTLED_NOTE_TTL_SECONDS,READ_BATCH_SIZE,BACKFILLED,TaskSessionIndex;var init_task_session_index=__esm({"libs/sdk/src/task/store/task-session-index.ts"(){"use strict";POSITION_GRACE_SECONDS=3600;BACKFILL_CLAIM_TTL_SECONDS=60;POSITION_WRITE_SECONDS=60;SETTLED_NOTE_TTL_SECONDS=3600;READ_BATCH_SIZE=500;BACKFILLED="done:";TaskSessionIndex=class{constructor(storage,source,maxTaskTtlSeconds){this.source=source;this.positions=storage.namespace("index");this.positionOf=storage.namespace("index-of");this.counts=storage.namespace("index-count");this.starts=storage.namespace("index-start");this.skips=storage.namespace("index-skip");this.settled=storage.namespace("index-settled");this.readiness=storage.namespace("index-ready");this.countTtlSeconds=Math.ceil(maxTaskTtlSeconds)+POSITION_GRACE_SECONDS}source;positions;positionOf;counts;starts;skips;settled;readiness;countTtlSeconds;async add(record,ttlSeconds){const{sessionId}=record;const countTtlSeconds=Math.max(this.countTtlSeconds,ttlSeconds+POSITION_GRACE_SECONDS);await this.ensureCount(sessionId,countTtlSeconds);const position=await this.counts.incr(sessionId);if(position===1&&await this.publishedCount(sessionId)>0)await this.readiness.delete(sessionId);await this.keepCountAlive(sessionId,countTtlSeconds);await this.number(record,position,ttlSeconds)}async ensureCount(sessionId,ttlSeconds){await this.counts.extendTtl(sessionId,ttlSeconds);await this.counts.set(sessionId,"0",{ifNotExists:true,ttlSeconds})}async extend(record,ttlSeconds){const{sessionId,taskId}=record;const position=await this.positionOf.get(sessionTaskKey(sessionId,taskId));if(position===null)return;await this.positionOf.extendTtl(sessionTaskKey(sessionId,taskId),ttlSeconds);await this.positions.extendTtl(sessionTaskKey(sessionId,position),ttlSeconds+POSITION_GRACE_SECONDS);await this.keepCountAlive(sessionId,ttlSeconds+POSITION_GRACE_SECONDS)}async keepCountAlive(sessionId,ttlSeconds){await this.counts.extendTtl(sessionId,ttlSeconds);const readiness=await this.readiness.get(sessionId);if(readiness?.startsWith(BACKFILLED))await this.readiness.extendTtl(sessionId,ttlSeconds)}async remove(record){await this.positionOf.delete(sessionTaskKey(record.sessionId,record.taskId))}async page(sessionId,startPosition,pageSize){const generation=startPosition===0?await this.ensureBackfilled(sessionId):await this.generationOf(sessionId);if(startPosition===0&&generation===void 0)return void 0;const positionsUsed=Number(await this.counts.get(sessionId)??0);const writtenUpTo=await this.writtenUpTo(sessionId,positionsUsed,generation);const tasks=[];let anchor=startPosition;let skippedTo=await this.skippedTo(sessionId,anchor,generation);let goneUpTo=skippedTo;let runOpen=true;let position=skippedTo;while(tasks.length<pageSize&&position<positionsUsed){const batchEnd=Math.min(positionsUsed,position+pageSize-tasks.length);const batch=Array.from({length:batchEnd-position},(_,offset)=>position+offset+1);const taskIds=await this.positions.mget(batch.map(indexed=>sessionTaskKey(sessionId,indexed)));const numbers=await this.positionOf.mget(taskIds.map(taskId=>sessionTaskKey(sessionId,taskId??"")));position=batchEnd;for(const[offset,taskId]of taskIds.entries()){const at=batch[offset];const ownPosition=taskId!==null&&numbers[offset]===String(at);const record=ownPosition?await this.source.readTask(taskId,sessionId):null;if(record===null){const gone=taskId===null?at<=writtenUpTo:!ownPosition;runOpen=runOpen&&gone;if(runOpen)goneUpTo=at;continue}if(goneUpTo>skippedTo)await this.rememberSkip(sessionId,anchor,goneUpTo,generation);tasks.push(record);anchor=at;skippedTo=await this.skippedTo(sessionId,at,generation);goneUpTo=skippedTo;runOpen=true;if(skippedTo>at&&tasks.length<pageSize){position=Math.min(skippedTo,positionsUsed);break}}}if(goneUpTo>skippedTo)await this.rememberSkip(sessionId,anchor,goneUpTo,generation);return{tasks,endPosition:position,positionsUsed}}async generationOf(sessionId){return readyMarkerOf(await this.readiness.get(sessionId))?.generation}async publishedCount(sessionId){return readyMarkerOf(await this.readiness.get(sessionId))?.count??0}async skippedTo(sessionId,anchor,generation){if(generation===void 0)return anchor;const stored=anchor===0?await this.starts.get(sessionId):await this.skips.get(sessionTaskKey(sessionId,anchor));const[storedGeneration,goneUpTo]=(stored??"").split(":");return storedGeneration===generation?Math.max(anchor,Number(goneUpTo)):anchor}async rememberSkip(sessionId,anchor,goneUpTo,generation){const remaining=await this.counts.ttl(sessionId);if(generation===void 0||remaining===null||remaining<=0)return;const skip=`${generation}:${goneUpTo}`;if(anchor===0){await this.starts.set(sessionId,skip,{ttlSeconds:remaining})}else{await this.skips.set(sessionTaskKey(sessionId,anchor),skip,{ttlSeconds:remaining})}}async writtenUpTo(sessionId,positionsUsed,generation){if(generation===void 0)return 0;const[notedGeneration,notedPosition]=(await this.settled.get(sessionId)??"").split(":");const noted=notedGeneration===generation?Number(notedPosition):void 0;const remaining=noted===void 0?null:await this.settled.ttl(sessionId);const age=remaining===null||remaining<0?Infinity:SETTLED_NOTE_TTL_SECONDS-remaining;if(age<POSITION_WRITE_SECONDS)return 0;if(noted===void 0||positionsUsed>noted){await this.settled.set(sessionId,`${generation}:${positionsUsed}`,{ttlSeconds:SETTLED_NOTE_TTL_SECONDS})}return noted??0}async number(record,position,ttlSeconds){const{sessionId,taskId}=record;await this.positionOf.set(sessionTaskKey(sessionId,taskId),String(position),{ttlSeconds});await this.positions.set(sessionTaskKey(sessionId,position),taskId,{ttlSeconds:ttlSeconds+POSITION_GRACE_SECONDS})}async ensureBackfilled(sessionId){const state=await this.readiness.get(sessionId);const ready=readyMarkerOf(state);if(ready)return ready.generation;if(state!==null)return void 0;const generation=randomUUID24();const claim=`running:${generation}`;await this.readiness.set(sessionId,claim,{ifNotExists:true,ttlSeconds:BACKFILL_CLAIM_TTL_SECONDS});if(await this.readiness.get(sessionId)!==claim)return void 0;const holding=this.holdClaim(sessionId,claim);try{const publishedCount=await this.backfill(sessionId,holding.held);if(publishedCount===void 0||!await this.renewClaim(sessionId,claim))return void 0;const remaining=await this.counts.ttl(sessionId);const ttlSeconds=remaining!==null&&remaining>0?remaining:this.countTtlSeconds;await this.readiness.set(sessionId,`${BACKFILLED}${generation}:${publishedCount}`,{ttlSeconds});return generation}finally{holding.release()}}holdClaim(sessionId,claim){let held=true;const renewal=setInterval(()=>{void this.renewClaim(sessionId,claim).then(renewed=>{held=held&&renewed},()=>{held=false})},BACKFILL_CLAIM_TTL_SECONDS*1e3/3);renewal.unref?.();return{held:()=>held,release:()=>clearInterval(renewal)}}async renewClaim(sessionId,claim){return this.readiness.expireIfEquals(sessionId,claim,BACKFILL_CLAIM_TTL_SECONDS)}async backfill(sessionId,held){const{records,recordKey:recordKey2,scanSessionTaskIds}=this.source;const taskIds=await scanSessionTaskIds(sessionId);if(!held())return void 0;const stored=await mgetInBatches(keys=>records.mget(keys),taskIds.map(taskId=>recordKey2(sessionId,taskId)));const live=stored.filter(record=>record!==null&&record.sessionId===sessionId&&expiresAtToTTL2(record.expiresAt)>0);const numbered=await mgetInBatches(keys=>this.positionOf.mget(keys),live.map(record=>sessionTaskKey(sessionId,record.taskId)));const listedAt=await mgetInBatches(keys=>this.positions.mget(keys),numbered.map(position=>sessionTaskKey(sessionId,position??0)));const missingAt=live.flatMap((record,index)=>numbered[index]===null||listedAt[index]!==record.taskId?[index]:[]);const missing=missingAt.map(index=>live[index]);if(!held())return void 0;if(missing.length===0)return Number(await this.counts.get(sessionId)??0);const longestTtl=missing.reduce((longest,record)=>Math.max(longest,expiresAtToTTL2(record.expiresAt)),0);const countTtlSeconds=Math.max(this.countTtlSeconds,longestTtl+POSITION_GRACE_SECONDS);await this.ensureCount(sessionId,countTtlSeconds);const lastPosition=await this.counts.incrBy(sessionId,missing.length);await this.keepCountAlive(sessionId,countTtlSeconds);const firstPosition=lastPosition-missing.length+1;for(const[offset,record]of missing.entries()){if(!held())return void 0;const ttlSeconds=expiresAtToTTL2(record.expiresAt);const staleNumber=numbered[missingAt[offset]];if(ttlSeconds>0)await this.numberEarlierTask(record,firstPosition+offset,ttlSeconds,staleNumber)}return lastPosition}async numberEarlierTask(record,position,ttlSeconds,staleNumber){const{sessionId,taskId}=record;const indexOfKey=sessionTaskKey(sessionId,taskId);if(staleNumber!==null)await this.positionOf.deleteIfEquals(indexOfKey,staleNumber);await this.positionOf.set(indexOfKey,String(position),{ttlSeconds,ifNotExists:true});if(await this.positionOf.get(indexOfKey)!==String(position))return;await this.positions.set(sessionTaskKey(sessionId,position),taskId,{ttlSeconds:ttlSeconds+POSITION_GRACE_SECONDS});const current=await this.source.readTask(record.taskId,record.sessionId);const currentTtl=current?expiresAtToTTL2(current.expiresAt):0;if(current&&currentTtl>ttlSeconds)await this.extend(current,currentTtl)}}}});import{base64urlDecode as base64urlDecode3,base64urlEncode as base64urlEncode5,expiresAtToTTL as expiresAtToTTL3,TypedStorage as TypedStorage2}from"@frontmcp/utils";function recordKey(sessionId,taskId){return`${sessionId}:${taskId}`}function slotKey(sessionId,slot){return`${sessionId}:${slot}`}function encodeCursor(offset,source){return base64urlEncode5(new TextEncoder().encode(JSON.stringify({offset,source})))}function decodeCursor(cursor){try{const bytes=base64urlDecode3(cursor);const parsed=JSON.parse(new TextDecoder().decode(bytes));if(typeof parsed?.offset==="number"&&parsed.offset>=0&&Number.isInteger(parsed.offset)){return{offset:parsed.offset,source:parsed.source==="index"?"index":"scan"}}}catch{}return{offset:0,source:"scan"}}var TERMINAL_CHANNEL_PREFIX,CANCEL_CHANNEL_PREFIX,RECORDS_NAMESPACE,SLOTS_NAMESPACE,DEFAULT_PAGE_SIZE2,StorageTaskStore;var init_storage_task_store=__esm({"libs/sdk/src/task/store/storage-task.store.ts"(){"use strict";init_process_liveness();init_task_types();TERMINAL_CHANNEL_PREFIX="terminal:";CANCEL_CHANNEL_PREFIX="cancel:";RECORDS_NAMESPACE="records";SLOTS_NAMESPACE="slots";DEFAULT_PAGE_SIZE2=50;StorageTaskStore=class{storage;records;slots;sessionIndex;logger;listFrom;maxTtlMs;terminalCallbacks=new Map;terminalSubs=new Map;cancelCallbacks=new Map;cancelSubs=new Map;constructor(storage,logger,options={}){this.storage=storage;this.logger=logger;this.listFrom=options.listFrom??"index";this.maxTtlMs=options.maxTtlMs??TASK_DEFAULTS.maxTtlMs;this.records=new TypedStorage2(storage.namespace(RECORDS_NAMESPACE));this.slots=storage.namespace(SLOTS_NAMESPACE)}async create(record){const ttlSeconds=expiresAtToTTL3(record.expiresAt);if(ttlSeconds<=0){this.logger?.warn("[StorageTaskStore] create: record already expired, skipping",{taskId:record.taskId});return}const key=recordKey(record.sessionId,record.taskId);await(await this.loadSessionIndex()).add(record,ttlSeconds);await this.records.set(key,record,{ttlSeconds});this.logger?.debug("[StorageTaskStore] created",{taskId:record.taskId,ttlSeconds})}async createWithinLimit(record,maxActive){const ttlSeconds=expiresAtToTTL3(record.expiresAt);if(ttlSeconds<=0){await this.create(record);return true}const slot=await this.acquireSlot(record,maxActive,ttlSeconds);if(slot===void 0)return false;const slotted={...record,concurrencySlot:slot};try{await this.create(slotted)}catch(err){await this.releaseSlot(slotted);throw err}return true}async get(taskId,sessionId){const record=await this.records.get(recordKey(sessionId,taskId));if(!record)return null;if(record.sessionId!==sessionId)return null;if(record.expiresAt&&Date.now()>record.expiresAt){await this.delete(taskId,sessionId).catch(error=>this.logger?.warn("[StorageTaskStore] failed to clean up an expired task",{taskId,error:error instanceof Error?error.message:String(error)}));return null}return record}async update(taskId,sessionId,patch){const existing=await this.get(taskId,sessionId);if(!existing)return null;const merged={...existing,...patch,taskId:existing.taskId,sessionId:existing.sessionId,createdAt:existing.createdAt,lastUpdatedAt:new Date().toISOString()};const ttlSeconds=expiresAtToTTL3(merged.expiresAt);if(ttlSeconds<=0){await this.delete(taskId,sessionId);return null}await this.records.set(recordKey(sessionId,taskId),merged,{ttlSeconds});if(patch.expiresAt!==void 0)await(await this.loadSessionIndex()).extend(merged,ttlSeconds);if(isTerminal(merged.status))await this.releaseSlot(merged);return merged}async delete(taskId,sessionId){const existing=await this.records.get(recordKey(sessionId,taskId));await this.records.delete(recordKey(sessionId,taskId));if(!existing)return;try{await(await this.loadSessionIndex()).remove(existing)}finally{await this.releaseSlot(existing)}}async acquireSlot(record,maxActive,ttlSeconds){const owner=record.sessionId;const slotKeys=Array.from({length:maxActive},(_,slot)=>slotKey(owner,slot));const holders=await this.slots.mget(slotKeys);const claimed=await this.claimFreeSlot(owner,holders,record.taskId,ttlSeconds);if(claimed!==void 0||!await this.reclaimSlots(owner,holders))return claimed;return this.claimFreeSlot(owner,await this.slots.mget(slotKeys),record.taskId,ttlSeconds)}async claimFreeSlot(owner,holders,taskId,ttlSeconds){for(const[slot,holder]of holders.entries()){if(holder!==null)continue;const key=slotKey(owner,slot);await this.slots.set(key,taskId,{ttlSeconds,ifNotExists:true});if(await this.slots.get(key)===taskId)return slot}return void 0}async reclaimSlots(owner,holders){let reclaimed=false;for(const holderTaskId of holders){if(holderTaskId===null)continue;const holder=await this.records.get(recordKey(owner,holderTaskId));if(!holder)continue;if(isTerminal(holder.status)){await this.releaseSlot(holder);reclaimed=true;continue}const workerPid=holder.executor?.host==="cli"&&isLocalWorker(holder.executor)?holder.executor.pid:void 0;if(workerPid===void 0||isAlive(workerPid))continue;const failed=await this.update(holderTaskId,owner,{status:"failed",statusMessage:"Task runner exited before completing the task"});if(failed)await this.publishTerminal(failed);reclaimed=true}return reclaimed}async releaseSlot(record){if(record.concurrencySlot===void 0)return;try{await this.slots.deleteIfEquals(slotKey(record.sessionId,record.concurrencySlot),record.taskId)}catch(err){this.logger?.warn("[StorageTaskStore] failed to release a concurrency slot",{taskId:record.taskId,error:err instanceof Error?err.message:String(err)})}}async list(sessionId,opts={}){const pageSize=Math.max(1,Math.min(opts.pageSize??DEFAULT_PAGE_SIZE2,500));const resumed=opts.cursor?decodeCursor(opts.cursor):void 0;const startAt=resumed?.offset??0;const source=resumed?.source??this.listFrom;return source==="scan"?this.listFromScan(sessionId,startAt,pageSize):this.listFromIndex(sessionId,startAt,pageSize)}async listFromScan(sessionId,offset,pageSize){const matching=await this.scanSessionTaskIds(sessionId);const slice=matching.slice(offset,offset+pageSize);const tasks=[];for(const taskId of slice){const record=await this.get(taskId,sessionId);if(record)tasks.push(record)}const nextOffset=offset+slice.length;const page2={tasks};if(nextOffset<matching.length)page2.nextCursor=encodeCursor(nextOffset,"scan");return page2}async listFromIndex(sessionId,startPosition,pageSize){const sessionIndex=await this.loadSessionIndex();const indexPage=await sessionIndex.page(sessionId,startPosition,pageSize);if(!indexPage)return this.listFromScan(sessionId,0,pageSize);const{tasks,endPosition,positionsUsed}=indexPage;const page2={tasks};if(endPosition<positionsUsed)page2.nextCursor=encodeCursor(endPosition,"index");return page2}loadSessionIndex(){this.sessionIndex??=Promise.resolve().then(()=>(init_task_session_index(),task_session_index_exports)).then(({TaskSessionIndex:TaskSessionIndex2})=>new TaskSessionIndex2(this.storage,{records:this.records,recordKey,scanSessionTaskIds:sessionId=>this.scanSessionTaskIds(sessionId),readTask:(taskId,sessionId)=>this.get(taskId,sessionId)},this.maxTtlMs/1e3));return this.sessionIndex}async scanSessionTaskIds(sessionId){const sessionPrefix=`${sessionId}:`;return(await this.storage.namespace(RECORDS_NAMESPACE).keys()).filter(key=>key.startsWith(sessionPrefix)).map(key=>key.slice(sessionPrefix.length)).sort()}async subscribeTerminal(taskId,_sessionId,cb){const channel2=TERMINAL_CHANNEL_PREFIX+taskId;let set=this.terminalCallbacks.get(taskId);if(!set){set=new Set;this.terminalCallbacks.set(taskId,set)}set.add(cb);if(!this.terminalSubs.has(taskId)&&this.storage.supportsPubSub()){const unsubscribe=await this.storage.subscribe(channel2,message=>{try{const record=JSON.parse(message);const subs=this.terminalCallbacks.get(taskId);if(subs){for(const fn of subs){try{fn(record)}catch(err){this.logger?.error("[StorageTaskStore] terminal callback threw",{taskId,error:err instanceof Error?err.message:String(err)})}}}}catch(err){this.logger?.error("[StorageTaskStore] failed to parse terminal message",{taskId,error:err instanceof Error?err.message:String(err)})}});this.terminalSubs.set(taskId,unsubscribe)}const callbackSet=set;return async()=>{callbackSet.delete(cb);if(callbackSet.size===0){this.terminalCallbacks.delete(taskId);const unsubscribe=this.terminalSubs.get(taskId);if(unsubscribe){this.terminalSubs.delete(taskId);try{await unsubscribe()}catch{}}}}}async publishTerminal(record){const channel2=TERMINAL_CHANNEL_PREFIX+record.taskId;const fanOutLocal=()=>{const subs=this.terminalCallbacks.get(record.taskId);if(!subs)return;for(const cb of subs){try{cb(record)}catch{}}};if(this.storage.supportsPubSub()){try{await this.storage.publish(channel2,JSON.stringify(record))}catch(err){this.logger?.error("[StorageTaskStore] failed to publish terminal; falling back to local callbacks",{taskId:record.taskId,error:err instanceof Error?err.message:String(err)});fanOutLocal()}}else{fanOutLocal()}}async subscribeCancel(taskId,_sessionId,cb){const channel2=CANCEL_CHANNEL_PREFIX+taskId;let set=this.cancelCallbacks.get(taskId);if(!set){set=new Set;this.cancelCallbacks.set(taskId,set)}set.add(cb);if(!this.cancelSubs.has(taskId)&&this.storage.supportsPubSub()){const unsubscribe=await this.storage.subscribe(channel2,()=>{const subs=this.cancelCallbacks.get(taskId);if(subs){for(const fn of subs){try{fn()}catch{}}}});this.cancelSubs.set(taskId,unsubscribe)}const callbackSet=set;return async()=>{callbackSet.delete(cb);if(callbackSet.size===0){this.cancelCallbacks.delete(taskId);const unsubscribe=this.cancelSubs.get(taskId);if(unsubscribe){this.cancelSubs.delete(taskId);try{await unsubscribe()}catch{}}}}}async publishCancel(taskId,_sessionId){const channel2=CANCEL_CHANNEL_PREFIX+taskId;const fanOutLocal=()=>{const subs=this.cancelCallbacks.get(taskId);if(!subs)return;for(const fn of subs){try{fn()}catch{}}};if(this.storage.supportsPubSub()){try{await this.storage.publish(channel2,"1")}catch(err){this.logger?.error("[StorageTaskStore] failed to publish cancel; falling back to local callbacks",{taskId,error:err instanceof Error?err.message:String(err)});fanOutLocal();return}}else{const subs=this.cancelCallbacks.get(taskId);if(subs){for(const fn of subs){try{fn()}catch{}}}}}async destroy(){for(const unsubscribe of this.terminalSubs.values()){try{await unsubscribe()}catch{}}for(const unsubscribe of this.cancelSubs.values()){try{await unsubscribe()}catch{}}this.terminalSubs.clear();this.cancelSubs.clear();this.terminalCallbacks.clear();this.cancelCallbacks.clear()}}}});import{createMemoryStorage as createMemoryStorage2,createStorage as createStorage6,getEnv as getEnv16}from"@frontmcp/utils";function detectStorageType2(storage,configuredType){if(configuredType==="redis")return"redis";if(configuredType==="upstash")return"upstash";if(configuredType==="memory")return"memory";const storageBackend=storage.type??storage.backendName;if(storageBackend==="redis"||storageBackend==="upstash"||storageBackend==="memory"){return storageBackend}if(getEnv16("UPSTASH_REDIS_REST_URL"))return"upstash";if(getEnv16("REDIS_URL")||getEnv16("REDIS_HOST"))return"redis";return"memory"}async function createTaskStore(options={}){const{storage:storageConfig,redis,keyPrefix="mcp:task:",logger,isEdgeRuntime:isEdgeRuntime4=false,sqlite}=options;if(isEdgeRuntime4&&sqlite&&!hasSqliteDriver()){throw new TaskStoreNotSupportedError(`SQLite task store is not supported on Edge runtime without a SQLite driver (better-sqlite3 is a native module). ${SQLITE_ON_EDGE_REMEDY} Otherwise use Redis or Upstash.`)}if(sqlite){const{SqliteTaskStore}=requireOptionalModule("@frontmcp/storage-sqlite",()=>require_dist());const store2=new SqliteTaskStore({path:sqlite.path,encryption:sqlite.encryption,walMode:sqlite.walMode??true,ttlCleanupIntervalMs:sqlite.ttlCleanupIntervalMs??6e4,busyTimeoutMs:sqlite.busyTimeoutMs,logger:logger?{debug:(m,meta)=>logger.debug(m,meta),warn:(m,meta)=>logger.warn(m,meta),error:(m,meta)=>logger.error(m,meta)}:void 0});logger?.info("[TaskStoreFactory] Created SQLite task store",{path:sqlite.path,keyPrefix});return{store:store2,type:"sqlite"}}let finalStorageConfig=storageConfig;if(redis&&!isExplicitStorage(storageConfig)){const redisOptions=normalizeRedisOptions(redis);if(typeof redisOptions==="string"){throw new TaskStoreNotSupportedError(`Invalid Redis configuration: ${redisOptions}`)}if(isVercelKvProvider(redisOptions)){throw new TaskStoreNotSupportedError("Vercel KV is not supported for task stores. Task result blocking and cancel signalling require pub/sub. Use Redis or Upstash instead.")}const{host,port,password,db,tls}=redisOptions;finalStorageConfig={type:"redis",redis:{config:{host,port,password,db,tls}}}}const explicitBackend=isExplicitStorage(storageConfig)||Boolean(redis);if(finalStorageConfig?.type==="vercel-kv"||!explicitBackend&&getEnv16("KV_REST_API_URL")){throw new TaskStoreNotSupportedError("Vercel KV is not supported for task stores (pub/sub required). Use Redis or Upstash.")}if(isEdgeRuntime4&&(!finalStorageConfig||finalStorageConfig.type==="memory")){throw new TaskStoreNotSupportedError("Tasks require distributed storage on Edge runtime. Configure Redis or Upstash.")}const storage=await createStorage6({...finalStorageConfig,prefix:keyPrefix,fallback:isEdgeRuntime4?"error":"memory"});const store=new StorageTaskStore(storage,logger,{listFrom:options.listFrom,maxTtlMs:options.maxTtlMs});const type=detectStorageType2(storage,finalStorageConfig?.type);logger?.info("[TaskStoreFactory] Created task store",{type,keyPrefix,supportsPubSub:storage.supportsPubSub()});return{store,type,storage}}function createMemoryTaskStore(options={}){const{keyPrefix="mcp:task:",logger}=options;const storage=createMemoryStorage2({prefix:keyPrefix});return{store:new StorageTaskStore(storage,logger),type:"memory",storage}}var TaskStoreNotSupportedError;var init_task_store_factory=__esm({"libs/sdk/src/task/store/task-store.factory.ts"(){"use strict";init_common();init_schema5();init_optional_dependency_util();init_sqlite_on_edge();init_storage_task_store();init_task_backend_utils();init_task_backend_utils();TaskStoreNotSupportedError=class extends Error{constructor(message){super(message);this.name="TaskStoreNotSupportedError"}}}});var TaskRegistry;var init_task_registry=__esm({"libs/sdk/src/task/task.registry.ts"(){"use strict";TaskRegistry=class{abortControllers=new Map;logger;config;_runner;constructor(config={},logger){this.config=config;this.logger=logger}setRunner(runner){this._runner=runner}get runner(){return this._runner}trackRunning(taskId){const controller=new AbortController;this.abortControllers.set(taskId,controller);return controller}untrack(taskId){this.abortControllers.delete(taskId)}abort(taskId,reason){const controller=this.abortControllers.get(taskId);if(!controller)return false;try{controller.abort(reason)}catch(err){this.logger?.warn("[TaskRegistry] abort failed",{taskId,error:err instanceof Error?err.message:String(err)})}return true}runningCount(){return this.abortControllers.size}getConfig(){return this.config}getCapabilities(inputs){if(this.config.enabled===false)return{};if(!inputs.hasTaskEnabledTool)return{};const caps={cancel:{},requests:{tools:{call:{}}}};if(inputs.canIdentifyRequestors){caps["list"]={}}return{tasks:caps}}}}});import{runRequestExclusive as runRequestExclusive6}from"@frontmcp/utils";function runTaskInBackground(params){return Promise.resolve().then(()=>runRequestExclusive6(()=>executeTask(params)))}async function executeTask(params){const{record,cleanedRequestParams,ctx,scope,store,registry,notifier,logger}=params;const{taskId,sessionId}=record;const controller=registry.trackRunning(taskId);let unsubscribeCancel;const taskCtx=ctx;taskCtx.signal=controller.signal;taskCtx.taskId=taskId;try{unsubscribeCancel=await store.subscribeCancel(taskId,sessionId,()=>{if(!controller.signal.aborted){controller.abort("tasks/cancel")}});const innerRequest={method:"tools/call",params:cleanedRequestParams};let outcomeOk;let outcomeErr;try{outcomeOk=await scope.runFlowForOutput("tools:call-tool",{request:innerRequest,ctx:taskCtx})}catch(err){if(err instanceof InputRequiredSignal){const beforePause=await store.get(taskId,sessionId);if(!beforePause||isTerminal(beforePause.status)){logger?.debug("[task-runner] input required but task already terminal; leaving as-is",{taskId,status:beforePause?.status});return}const paused=await store.update(taskId,sessionId,{status:"input_required",statusMessage:"The task is waiting for additional input.",inputRequests:err.inputRequests});logger?.info("[task-runner] task paused awaiting input",{taskId,keys:Object.keys(err.inputRequests)});if(paused)notifier.sendStatus(paused);return}try{outcomeOk=toolCallErrorResult(err,{errorHandler:new ErrorHandler({logger}),toolName:String(cleanedRequestParams["name"]??"unknown"),logger})}catch(protocolError){outcomeErr=toJsonRpcError2(protocolError)}}const current=await store.get(taskId,sessionId);if(!current){logger?.debug("[task-runner] record gone before terminal write",{taskId});return}if(isTerminal(current.status)){await store.publishTerminal(current);notifier.sendStatus(current);return}const isErrorResult=outcomeErr!==void 0||outcomeOk?.isError===true;const finalStatus=controller.signal.aborted?"cancelled":isErrorResult?"failed":"completed";const statusMessage=controller.signal.aborted?"The task was cancelled before completion.":outcomeErr?.message??(outcomeOk?.isError===true?"Tool execution returned isError: true":void 0);const updated=await store.update(taskId,sessionId,{status:finalStatus,statusMessage,outcome:outcomeErr?{kind:"error",error:outcomeErr}:outcomeOk?{kind:"ok",data:outcomeOk}:void 0});if(updated){await store.publishTerminal(updated);notifier.sendStatus(updated)}}catch(err){logger?.error("[task-runner] unhandled error in task lifecycle",{taskId,error:err instanceof Error?err.message:String(err)});if(!controller.signal.aborted)controller.abort("task-runner error");try{const failure=toJsonRpcError2(err);const failed=await store.update(taskId,sessionId,{status:"failed",statusMessage:failure.message,outcome:{kind:"error",error:failure}});if(failed){try{await store.publishTerminal(failed)}catch{}notifier.sendStatus(failed)}}catch{}}finally{registry.untrack(taskId);if(unsubscribeCancel){try{await unsubscribeCancel()}catch{}}}}function toJsonRpcError2(err){const sdkError=toSdkMcpError(err);const message=sdkError.message.replace(/^MCP error -?\d+: /,"");return sdkError.data===void 0?{code:sdkError.code,message}:{code:sdkError.code,message,data:sdkError.data}}var init_task_runner=__esm({"libs/sdk/src/task/helpers/task-runner.ts"(){"use strict";init_errors();init_call_tool_error_utils();init_mcp_error_utils();init_task_types()}});var InProcessTaskRunner;var init_in_process_task_runner=__esm({"libs/sdk/src/task/helpers/in-process-task-runner.ts"(){"use strict";init_task_runner();InProcessTaskRunner=class{constructor(deps){this.deps=deps}deps;kind="in-process";async run(record,context){await this.deps.store.update(record.taskId,record.sessionId,{executor:{host:"in-process",spawnedAt:new Date().toISOString()}});void runTaskInBackground({record,cleanedRequestParams:context.cleanedRequestParams,ctx:context.ctx,scope:this.deps.scope,store:this.deps.store,registry:this.deps.registry,notifier:this.deps.notifier,logger:this.deps.logger})}async cancel(record){this.deps.registry.abort(record.taskId,"tasks/cancel")}}}});import{internalZ as z117}from"@frontmcp/lazy-zod";import{GetTaskRequestSchema as GetTaskRequestSchema2,GetTaskResultSchema}from"@frontmcp/protocol";var inputSchema21,outputSchema20,stateSchema25,plan28,name28,Stage28,TasksGetFlow;var init_tasks_get_flow=__esm({"libs/sdk/src/task/flows/tasks-get.flow.ts"(){"use strict";init_common();init_errors();init_task_types();inputSchema21=z117.object({request:GetTaskRequestSchema2,ctx:z117.any()});outputSchema20=GetTaskResultSchema;stateSchema25=z117.object({taskId:z117.string(),sessionId:z117.string(),authInfo:z117.any()});plan28={pre:["parseInput"],execute:["fetchAndRespond"]};name28="tasks:get";({Stage:Stage28}=FlowHooksOf(name28));TasksGetFlow=class extends FlowBase{logger=this.scopeLogger.child("TasksGetFlow");async parseInput(){let method;let params;let ctx;try{const parsed=inputSchema21.parse(this.rawInput);method=parsed.request.method;params=parsed.request.params;ctx=parsed.ctx}catch(e){throw new InvalidInputError("Invalid tasks/get request",e instanceof z117.ZodError?e.issues:void 0)}if(method!=="tasks/get"){throw new InvalidMethodError(method,"tasks/get")}const authInfo=ctx?.authInfo;if(!authInfo?.sessionId){throw new InternalMcpError("Session ID missing in authorized flow","AUTH_INFO_MISSING")}this.state.set({taskId:params.taskId,sessionId:authInfo.sessionId,authInfo})}async fetchAndRespond(){const store=this.scope.taskStore;if(!store)throw new TaskStoreNotInitializedError;const{taskId,sessionId}=this.state.required;const record=await store.get(taskId,sessionId);if(!record)throw new TaskNotFoundError(taskId);this.respond(toWireShape(record))}};__decorateClass([Stage28("parseInput")],TasksGetFlow.prototype,"parseInput",1);__decorateClass([Stage28("fetchAndRespond")],TasksGetFlow.prototype,"fetchAndRespond",1);TasksGetFlow=__decorateClass([FrontMcpFlow({name:name28,plan:plan28,inputSchema:inputSchema21,outputSchema:outputSchema20,access:"authorized"})],TasksGetFlow)}});import{internalZ as z118}from"@frontmcp/lazy-zod";import{GetTaskPayloadRequestSchema as GetTaskPayloadRequestSchema2,GetTaskPayloadResultSchema}from"@frontmcp/protocol";var inputSchema22,outputSchema21,stateSchema26,plan29,name29,Stage29,TasksResultFlow,JsonRpcReplayError;var init_tasks_result_flow=__esm({"libs/sdk/src/task/flows/tasks-result.flow.ts"(){"use strict";init_common();init_errors();init_task_types();inputSchema22=z118.object({request:GetTaskPayloadRequestSchema2,ctx:z118.any()});outputSchema21=GetTaskPayloadResultSchema;stateSchema26=z118.object({taskId:z118.string(),sessionId:z118.string(),authInfo:z118.any()});plan29={pre:["parseInput"],execute:["awaitTerminal"]};name29="tasks:result";({Stage:Stage29}=FlowHooksOf(name29));TasksResultFlow=class extends FlowBase{logger=this.scopeLogger.child("TasksResultFlow");async parseInput(){let method;let params;let ctx;try{const parsed=inputSchema22.parse(this.rawInput);method=parsed.request.method;params=parsed.request.params;ctx=parsed.ctx}catch(e){throw new InvalidInputError("Invalid tasks/result request",e instanceof z118.ZodError?e.issues:void 0)}if(method!=="tasks/result"){throw new InvalidMethodError(method,"tasks/result")}const authInfo=ctx?.authInfo;if(!authInfo?.sessionId){throw new InternalMcpError("Session ID missing in authorized flow","AUTH_INFO_MISSING")}this.state.set({taskId:params.taskId,sessionId:authInfo.sessionId,authInfo})}async awaitTerminal(){const store=this.scope.taskStore;if(!store)throw new TaskStoreNotInitializedError;const{taskId,sessionId}=this.state.required;const initial=await store.get(taskId,sessionId);if(!initial)throw new TaskNotFoundError(taskId);const finalRecord=isTerminal(initial.status)?initial:await this.waitForTerminal(taskId,sessionId,store);if(!finalRecord)throw new TaskNotFoundError(taskId);this.respondWithOutcome(finalRecord)}async waitForTerminal(taskId,sessionId,store){return new Promise((resolve4,reject)=>{let settled=false;let unsubscribe;let pollTimer;const finalize=async(result,err)=>{if(settled)return;settled=true;if(pollTimer)clearTimeout(pollTimer);if(unsubscribe){try{await unsubscribe()}catch{}}if(err)reject(err);else resolve4(result)};const poll=async()=>{if(settled)return;try{const latest=await store.get(taskId,sessionId);if(!latest)return void finalize(null);if(isTerminal(latest.status))return void finalize(latest)}catch(err){return void finalize(null,err)}pollTimer=setTimeout(()=>void poll(),this.pollDelayMs())};store.subscribeTerminal(taskId,sessionId,record=>{if(isTerminal(record.status)){void finalize(record)}}).then(async unsub=>{unsubscribe=unsub;const latest=await store.get(taskId,sessionId);if(!latest){return void finalize(null)}if(isTerminal(latest.status)){return void finalize(latest)}pollTimer=setTimeout(()=>void poll(),this.pollDelayMs(latest.pollIntervalMs))}).catch(err=>void finalize(null,err))})}pollDelayMs(hint){const min=200;const max=5e3;if(typeof hint==="number"&&hint>0)return Math.max(min,Math.min(hint,max));return 500}respondWithOutcome(record){if(!record.outcome){throw new InternalMcpError("Terminal task has no outcome","TASK_MISSING_OUTCOME")}if(record.outcome.kind==="error"){const{code,message,data}=record.outcome.error;const err=new JsonRpcReplayError(code,message,data,record.taskId);throw err}const payload={...record.outcome.data};const existingMeta=payload["_meta"]??{};payload["_meta"]={...existingMeta,[RELATED_TASK_META_KEY]:{taskId:record.taskId}};this.respond(payload)}};__decorateClass([Stage29("parseInput")],TasksResultFlow.prototype,"parseInput",1);__decorateClass([Stage29("awaitTerminal")],TasksResultFlow.prototype,"awaitTerminal",1);TasksResultFlow=__decorateClass([FrontMcpFlow({name:name29,plan:plan29,inputSchema:inputSchema22,outputSchema:outputSchema21,access:"authorized"})],TasksResultFlow);JsonRpcReplayError=class extends Error{constructor(code,message,data,taskId){super(message);this.code=code;this.data=data;this.taskId=taskId;this.name="JsonRpcReplayError"}code;data;taskId;toJsonRpcError(){const out={code:this.code,message:this.message};if(this.data!==void 0)out.data=this.data;return out}}}});import{internalZ as z119}from"@frontmcp/lazy-zod";import{CancelTaskRequestSchema as CancelTaskRequestSchema2,CancelTaskResultSchema}from"@frontmcp/protocol";var inputSchema23,outputSchema22,stateSchema27,plan30,name30,Stage30,TasksCancelFlow;var init_tasks_cancel_flow=__esm({"libs/sdk/src/task/flows/tasks-cancel.flow.ts"(){"use strict";init_common();init_errors();init_task_types();inputSchema23=z119.object({request:CancelTaskRequestSchema2,ctx:z119.any()});outputSchema22=CancelTaskResultSchema;stateSchema27=z119.object({taskId:z119.string(),sessionId:z119.string(),authInfo:z119.any()});plan30={pre:["parseInput"],execute:["cancelAndRespond"]};name30="tasks:cancel";({Stage:Stage30}=FlowHooksOf(name30));TasksCancelFlow=class extends FlowBase{logger=this.scopeLogger.child("TasksCancelFlow");async parseInput(){let method;let params;let ctx;try{const parsed=inputSchema23.parse(this.rawInput);method=parsed.request.method;params=parsed.request.params;ctx=parsed.ctx}catch(e){throw new InvalidInputError("Invalid tasks/cancel request",e instanceof z119.ZodError?e.issues:void 0)}if(method!=="tasks/cancel"){throw new InvalidMethodError(method,"tasks/cancel")}const authInfo=ctx?.authInfo;if(!authInfo?.sessionId){throw new InternalMcpError("Session ID missing in authorized flow","AUTH_INFO_MISSING")}this.state.set({taskId:params.taskId,sessionId:authInfo.sessionId,authInfo})}async cancelAndRespond(){const store=this.scope.taskStore;const registry=this.scope.tasks;if(!store||!registry)throw new TaskStoreNotInitializedError;const{taskId,sessionId}=this.state.required;const existing=await store.get(taskId,sessionId);if(!existing)throw new TaskNotFoundError(taskId);if(isTerminal(existing.status))throw new TaskAlreadyTerminalError(existing.status);const updated=await store.update(taskId,sessionId,{status:"cancelled",statusMessage:"The task was cancelled by request."});if(!updated)throw new TaskNotFoundError(taskId);if(registry.runner){try{await registry.runner.cancel(updated)}catch(err){this.logger.warn("runner.cancel failed",{taskId,error:err instanceof Error?err.message:String(err)})}}else{registry.abort(taskId,"tasks/cancel")}try{await store.publishCancel(taskId,sessionId)}catch(err){this.logger.warn("publishCancel failed",{taskId,error:err instanceof Error?err.message:String(err)})}try{await store.publishTerminal(updated)}catch(err){this.logger.warn("publishTerminal failed",{taskId,error:err instanceof Error?err.message:String(err)})}this.scope.notifications.sendNotificationToSession(sessionId,"notifications/tasks/status",toWireShape(updated));this.respond(toWireShape(updated))}};__decorateClass([Stage30("parseInput")],TasksCancelFlow.prototype,"parseInput",1);__decorateClass([Stage30("cancelAndRespond")],TasksCancelFlow.prototype,"cancelAndRespond",1);TasksCancelFlow=__decorateClass([FrontMcpFlow({name:name30,plan:plan30,inputSchema:inputSchema23,outputSchema:outputSchema22,access:"authorized"})],TasksCancelFlow)}});import{internalZ as z120}from"@frontmcp/lazy-zod";import{ListTasksRequestSchema as ListTasksRequestSchema2,ListTasksResultSchema}from"@frontmcp/protocol";var inputSchema24,outputSchema23,stateSchema28,plan31,name31,Stage31,TasksListFlow;var init_tasks_list_flow=__esm({"libs/sdk/src/task/flows/tasks-list.flow.ts"(){"use strict";init_common();init_errors();init_task_types();inputSchema24=z120.object({request:ListTasksRequestSchema2,ctx:z120.any()});outputSchema23=ListTasksResultSchema;stateSchema28=z120.object({sessionId:z120.string(),cursor:z120.string().optional(),authInfo:z120.any()});plan31={pre:["parseInput"],execute:["listAndRespond"]};name31="tasks:list";({Stage:Stage31}=FlowHooksOf(name31));TasksListFlow=class extends FlowBase{logger=this.scopeLogger.child("TasksListFlow");async parseInput(){let method;let params;let ctx;try{const parsed=inputSchema24.parse(this.rawInput);method=parsed.request.method;params=parsed.request.params;ctx=parsed.ctx}catch(e){throw new InvalidInputError("Invalid tasks/list request",e instanceof z120.ZodError?e.issues:void 0)}if(method!=="tasks/list"){throw new InvalidMethodError(method,"tasks/list")}const authInfo=ctx?.authInfo;if(!authInfo?.sessionId){throw new InternalMcpError("Session ID missing in authorized flow","AUTH_INFO_MISSING")}this.state.set({sessionId:authInfo.sessionId,cursor:params?.cursor,authInfo})}async listAndRespond(){const store=this.scope.taskStore;if(!store)throw new TaskStoreNotInitializedError;const sessionId=this.state.required.sessionId;const cursor=this.state.cursor;const page2=await store.list(sessionId,{cursor});const tasks=page2.tasks.map(toWireShape);const response={tasks};if(page2.nextCursor)response.nextCursor=page2.nextCursor;this.respond(response)}};__decorateClass([Stage31("parseInput")],TasksListFlow.prototype,"parseInput",1);__decorateClass([Stage31("listAndRespond")],TasksListFlow.prototype,"listAndRespond",1);TasksListFlow=__decorateClass([FrontMcpFlow({name:name31,plan:plan31,inputSchema:inputSchema24,outputSchema:outputSchema23,access:"authorized"})],TasksListFlow)}});var task_scope_runtime_exports={};__export(task_scope_runtime_exports,{InProcessTaskRunner:()=>InProcessTaskRunner,TaskNotifier:()=>TaskNotifier,TaskRegistry:()=>TaskRegistry,TasksCancelFlow:()=>TasksCancelFlow,TasksGetFlow:()=>TasksGetFlow,TasksListFlow:()=>TasksListFlow,TasksResultFlow:()=>TasksResultFlow,createTaskStore:()=>createTaskStore});var init_task_scope_runtime=__esm({"libs/sdk/src/task/task-scope.runtime.ts"(){"use strict";init_task_store_factory();init_task_registry();init_task_notifier();init_in_process_task_runner();init_tasks_get_flow();init_tasks_result_flow();init_tasks_cancel_flow();init_tasks_list_flow()}});import{isAnonymousSubject as isAnonymousSubject9}from"@frontmcp/auth";function sessionScopeIdentity(ctx){const verified=ctx.verifiedSessionId;if(verified)return verified;const authInfo=ctx.authInfo??{};const extraUser=authInfo.extra?.["user"];const principal=[authInfo.user?.sub,extraUser?.sub,authInfo.clientId].find(candidate=>!isAnonymousSubject9(candidate));if(!principal)return void 0;const principalIssuer=authInfo.extra?.["principalIssuer"];if(typeof principalIssuer==="string"){return`issuer-principal:${encodeURIComponent(principalIssuer)}:${principal}`}return`principal:${principal}`}var init_session_scope_identity=__esm({"libs/sdk/src/auth/session-scope-identity.ts"(){"use strict"}});var CREDENTIAL_CACHE;var init_credential_cache=__esm({"libs/sdk/src/auth/vault/credential-cache.ts"(){"use strict";CREDENTIAL_CACHE=Symbol.for("frontmcp:CREDENTIAL_CACHE")}});var auth_providers_providers_exports={};__export(auth_providers_providers_exports,{LAZY_CREDENTIAL_LOADER:()=>LAZY_CREDENTIAL_LOADER,createAuthProvidersProviders:()=>createAuthProvidersProviders,isAuthProvidersEnabled:()=>isAuthProvidersEnabled,registerAuthProvidersVault:()=>registerAuthProvidersVault});import{AUTH_PROVIDERS_ACCESSOR as AUTH_PROVIDERS_ACCESSOR3,AUTH_PROVIDERS_REGISTRY,AUTH_PROVIDERS_VAULT,AuthProvidersAccessorImpl,AuthProvidersRegistry,AuthProvidersVault,CredentialCache,InMemoryAuthorizationVault,isAnonymousSubject as isAnonymousSubject10,LazyCredentialLoader,UNIDENTIFIED_SESSION_PREFIX}from"@frontmcp/auth";import{ProviderScope as ProviderScope8}from"@frontmcp/di";import{createStorage as createStorage7,getEnv as getEnv17,randomUUID as randomUUID25}from"@frontmcp/utils";function createAuthProvidersProviders(options,store,baseVault=new InMemoryAuthorizationVault){const providers=[];providers.push({provide:AUTH_PROVIDERS_REGISTRY,scope:ProviderScope8.GLOBAL,name:"AuthProvidersRegistry",useFactory:()=>new AuthProvidersRegistry(options)});providers.push({provide:AUTH_PROVIDERS_VAULT,scope:ProviderScope8.GLOBAL,name:"AuthProvidersVault",useFactory:logger=>new AuthProvidersVault(store.storage,{namespace:options.namespace,defaultCacheTtl:options.defaultCacheTtl,pepper:store.pepper,logger}),inject:()=>[FrontMcpLogger]});providers.push({provide:CREDENTIAL_CACHE,scope:ProviderScope8.CONTEXT,name:"CredentialCache",useFactory:()=>new CredentialCache(options.maxCredentialsPerSession??100)});providers.push({provide:LAZY_CREDENTIAL_LOADER,scope:ProviderScope8.CONTEXT,name:"LazyCredentialLoader",useFactory:logger=>new LazyCredentialLoader(logger),inject:()=>[FrontMcpLogger]});providers.push({provide:AUTH_PROVIDERS_ACCESSOR3,scope:ProviderScope8.CONTEXT,name:"AuthProvidersAccessor",useFactory:(registry,vault,cache2,loader,ctx,logger)=>{const user=ctx.authInfo?.user;const signedIn=user&&!isAnonymousSubject10(user.sub)?user:void 0;const factoryContext={sessionId:sessionScopeIdentity(ctx)??`${UNIDENTIFIED_SESSION_PREFIX}${randomUUID25()}`,userSub:signedIn?.sub,userEmail:signedIn?.email,userName:signedIn?.name,vault:baseVault};return new AuthProvidersAccessorImpl(registry,vault,cache2,loader,factoryContext,logger)},inject:()=>[AUTH_PROVIDERS_REGISTRY,AUTH_PROVIDERS_VAULT,CREDENTIAL_CACHE,LAZY_CREDENTIAL_LOADER,FRONTMCP_CONTEXT,FrontMcpLogger]});return providers}function isAuthProvidersEnabled(options){if(options?.enabled===false){return false}if(options?.enabled===true){return true}return(options?.providers?.length??0)>0}async function registerAuthProvidersVault(providers,options,tokenStorage,logger){if(!isAuthProvidersEnabled(options))return void 0;if(tokenStorage&&options.useSharedStorage!==false){const pepper=getEnv17("VAULT_SECRET")||getEnv17("JWT_SECRET");if(!pepper){logger.warn("authProvidersVault keeps credentials in auth.tokenStorage, but neither VAULT_SECRET nor JWT_SECRET is set: they are encrypted with a random key of this process, so other instances and a restart do not find them.")}await providers.addDynamicProviders(createAuthProvidersProviders(options,{storage:tokenStorage,pepper}));return void 0}const storage=await createStorage7({type:"memory"});await providers.addDynamicProviders(createAuthProvidersProviders(options,{storage}));return()=>storage.disconnect()}var LAZY_CREDENTIAL_LOADER;var init_auth_providers_providers=__esm({"libs/sdk/src/auth/vault/auth-providers.providers.ts"(){"use strict";init_common();init_frontmcp_context_provider();init_session_scope_identity();init_credential_cache();LAZY_CREDENTIAL_LOADER=Symbol.for("frontmcp:LAZY_CREDENTIAL_LOADER")}});function hasRegisteredTracerProvider({trace,ProxyTracerProvider}){const provider=trace.getTracerProvider();return!(provider instanceof ProxyTracerProvider)||provider.getDelegateTracer("frontmcp")!==void 0}function registerExportingTracerProvider(api,sdk,exporter){api.trace.setGlobalTracerProvider(new sdk.BasicTracerProvider({spanProcessors:[new sdk.SimpleSpanProcessor(exporter)]}))}var init_tracer_provider_utils=__esm({"libs/sdk/src/scope/tracer-provider.utils.ts"(){"use strict"}});var observability_scope_helper_exports={};__export(observability_scope_helper_exports,{observabilityPlugins:()=>observabilityPlugins});import{getRuntimeContext as getRuntimeContext22}from"@frontmcp/utils";function defaultLogSinks(){return[{type:getRuntimeContext22().runtime==="browser"?"console":"stdout"}]}function observabilityPlugins({config:observabilityConfig,logger,globalProviders,implied=false}){const plugins=[];let ObservabilityPluginModule;try{ObservabilityPluginModule=requireOptionalModule("@frontmcp/observability",()=>__require("@frontmcp/observability"))}catch(err){const probe2=probeOptionalDependency("@frontmcp/observability",err,__require.resolve);if(probe2.status==="not-installed"&&implied){logger.info("frontmcp dev writes call timings, failures and stalls to its events file with @frontmcp/observability; install it to get them: npm install @frontmcp/observability")}else if(probe2.status==="not-installed"){logger.warn("observability config is set but @frontmcp/observability is not installed. Install it with: npm install @frontmcp/observability")}else{logger.warn("observability config is set and @frontmcp/observability resolved but failed to load \u2014 telemetry is disabled. Reinstalling will not help: this is usually an export-condition or transpile mismatch (e.g. a dev runtime resolving the package source instead of its built entry) or a failing transitive peer dependency. Inspect the resolved path and error below.",{resolvedPath:probe2.resolvedPath,error:probe2.error})}}if(ObservabilityPluginModule)try{const{ObservabilityPlugin}=ObservabilityPluginModule;const pluginOptions=observabilityConfig===true?{}:observabilityConfig;plugins.push(ObservabilityPlugin.init(pluginOptions));logger.verbose("observability: auto-loaded ObservabilityPlugin from config");const loggingEnabled=pluginOptions.logging!==false;if(loggingEnabled){try{const{StructuredLogTransport,createSinks}=ObservabilityPluginModule;let loggerRegistry;try{loggerRegistry=globalProviders.get(LoggerRegistry)}catch{}if(loggerRegistry&&typeof loggerRegistry.addTransport==="function"&&!loggerRegistry._hasStructuredTransport){const rawLogging=pluginOptions.logging;const loggingOpts=rawLogging===true?{}:typeof rawLogging==="object"?rawLogging:{};const sinkConfigs=loggingOpts["sinks"]??(rawLogging===void 0?[]:defaultLogSinks());const sinks=createSinks(sinkConfigs);let contextStorage;try{contextStorage=globalProviders.get(FrontMcpContextStorage)}catch{}const contextAccessor=contextStorage?()=>{const ctx=contextStorage.getStore();if(!ctx)return void 0;return{requestId:ctx.requestId,traceContext:ctx.traceContext,sessionIdHash:__require("@frontmcp/utils").sha256Hex(ctx.sessionId).slice(0,12),scopeId:ctx.scopeId,flowName:ctx.flow?.name,elapsed:ctx.elapsed()}}:void 0;const transport=new StructuredLogTransport(sinks,{redactFields:loggingOpts["redactFields"],includeStacks:loggingOpts["includeStacks"],staticFields:loggingOpts["staticFields"]},contextAccessor);transport.onEntry=entry=>{const requestLog=contextStorage?.getStore()?.get(Symbol.for("frontmcp:observability:request-log-collector"));requestLog?.addEntry?.(entry)};loggerRegistry.addTransport(transport);loggerRegistry._hasStructuredTransport=true;logger.verbose("observability: wired StructuredLogTransport into SDK logger")}}catch(e){logger.warn("observability: failed to wire structured logging",{error:e instanceof Error?e.message:"Unknown error"})}}if(pluginOptions.tracing!==false){try{if(!hasRegisteredTracerProvider(__require("@opentelemetry/api"))){const{isDevelopment:checkDev}=__require("@frontmcp/utils");if(checkDev()){const sdkTraceBase=__require("@opentelemetry/sdk-trace-base");const{PrettySpanExporter}=ObservabilityPluginModule;const exporter=PrettySpanExporter?new PrettySpanExporter:new sdkTraceBase.ConsoleSpanExporter;registerExportingTracerProvider(__require("@opentelemetry/api"),sdkTraceBase,exporter);logger.info("observability: auto-configured tracing (development mode)")}else{logger.warn("observability: tracing enabled but no TracerProvider configured. Set OTEL_EXPORTER_OTLP_ENDPOINT or call setupOTel() before server start.")}}}catch(e){logger.warn("observability: could not set up development tracing; spans are not recorded",{error:e instanceof Error?e.message:"Unknown error"})}}}catch(e){if(e?.code==="OBSERVABILITY_CONFIGURATION")throw e;logger.warn("observability: plugin initialization failed",{error:e instanceof Error?e.message:"Unknown error"})}return plugins}var init_observability_scope_helper=__esm({"libs/sdk/src/scope/observability-scope.helper.ts"(){"use strict";init_context();init_logger_registry();init_optional_dependency_util();init_tracer_provider_utils()}});import{internalZ as z121}from"@frontmcp/lazy-zod";import{randomUUID as randomUUID26}from"@frontmcp/utils";var inputSchema25,outputSchema24,stateSchema29,plan32,name32,Stage32,ElicitationRequestFlow;var init_elicitation_request_flow=__esm({"libs/sdk/src/elicitation/flows/elicitation-request.flow.ts"(){"use strict";init_common();init_errors();init_session_id_hash();init_elicitation_types();inputSchema25=z121.object({relatedRequestId:z121.union([z121.string(),z121.number()]),sessionId:z121.string(),message:z121.string(),requestedSchema:z121.record(z121.string(),z121.unknown()),options:z121.object({mode:z121.enum(["form","url"]).optional(),ttl:z121.number().optional(),elicitationId:z121.string().optional(),url:z121.string().optional()}).optional()});outputSchema24=z121.object({elicitId:z121.string(),sessionId:z121.string(),expiresAt:z121.number(),mode:z121.enum(["form","url"]),requestParams:z121.record(z121.string(),z121.unknown()),pendingRecord:z121.any()});stateSchema29=z121.object({relatedRequestId:z121.union([z121.string(),z121.number()]),sessionId:z121.string(),message:z121.string(),requestedSchema:z121.record(z121.string(),z121.unknown()),mode:z121.enum(["form","url"]).default("form"),ttl:z121.number().default(DEFAULT_ELICIT_TTL),elicitationId:z121.string().optional(),url:z121.string().optional(),elicitId:z121.string(),expiresAt:z121.number(),pendingRecord:z121.any().optional(),requestParams:z121.record(z121.string(),z121.unknown()).optional(),output:outputSchema24.optional()});plan32={pre:["parseInput","validateRequest"],execute:["generateElicitId","storePendingRecord","buildRequestParams"],finalize:["finalize"]};name32="elicitation:request";({Stage:Stage32}=FlowHooksOf(name32));ElicitationRequestFlow=class extends FlowBase{logger=this.scopeLogger.child("ElicitationRequestFlow");async parseInput(){this.logger.verbose("parseInput:start");const input=inputSchema25.parse(this.rawInput);const{mode="form",ttl=DEFAULT_ELICIT_TTL,elicitationId,url}=input.options??{};this.state.set({relatedRequestId:input.relatedRequestId,sessionId:input.sessionId,message:input.message,requestedSchema:input.requestedSchema,mode,ttl,elicitationId,url});this.logger.verbose("parseInput:done",{sessionIdHash:sessionIdHash(input.sessionId),mode})}async validateRequest(){this.logger.verbose("validateRequest:start");const{mode,url}=this.state;if(mode==="url"&&!url){throw new InvalidInputError('url is required when mode is "url"')}this.logger.verbose("validateRequest:done")}async generateElicitId(){this.logger.verbose("generateElicitId:start");const{elicitationId,ttl}=this.state;const elicitId=elicitationId||`elicit-${randomUUID26()}`;const expiresAt=Date.now()+(ttl??DEFAULT_ELICIT_TTL);this.state.set({elicitId,expiresAt});this.logger.verbose("generateElicitId:done",{elicitId})}async storePendingRecord(){this.logger.verbose("storePendingRecord:start");const{elicitId,sessionId,message,mode,expiresAt,requestedSchema}=this.state.required;const store=this.scope.elicitationStore;if(!store){throw new ElicitationStoreNotInitializedError}const pendingRecord={elicitId,sessionId,createdAt:Date.now(),expiresAt,message,mode,requestedSchema};await store.setPending(pendingRecord);this.state.set("pendingRecord",pendingRecord);this.logger.verbose("storePendingRecord:done",{elicitId,sessionIdHash:sessionIdHash(sessionId)})}async buildRequestParams(){this.logger.verbose("buildRequestParams:start");const{mode,message,requestedSchema,elicitId}=this.state.required;const requestParams={mode,message,requestedSchema};if(mode==="url"){requestParams["elicitationId"]=elicitId;requestParams["url"]=this.state.url}this.state.set("requestParams",requestParams);this.logger.verbose("buildRequestParams:done")}async finalize(){this.logger.verbose("finalize:start");const{elicitId,sessionId,expiresAt,mode}=this.state.required;const{requestParams,pendingRecord}=this.state;if(!requestParams||!pendingRecord){throw new InvalidInputError("finalize: missing requestParams or pendingRecord from prior stages")}this.respond({elicitId,sessionId,expiresAt,mode,requestParams,pendingRecord});this.logger.verbose("finalize:done")}};__decorateClass([Stage32("parseInput")],ElicitationRequestFlow.prototype,"parseInput",1);__decorateClass([Stage32("validateRequest")],ElicitationRequestFlow.prototype,"validateRequest",1);__decorateClass([Stage32("generateElicitId")],ElicitationRequestFlow.prototype,"generateElicitId",1);__decorateClass([Stage32("storePendingRecord")],ElicitationRequestFlow.prototype,"storePendingRecord",1);__decorateClass([Stage32("buildRequestParams")],ElicitationRequestFlow.prototype,"buildRequestParams",1);__decorateClass([Stage32("finalize")],ElicitationRequestFlow.prototype,"finalize",1);ElicitationRequestFlow=__decorateClass([FrontMcpFlow({name:name32,plan:plan32,inputSchema:inputSchema25,outputSchema:outputSchema24,access:"authorized"})],ElicitationRequestFlow)}});import{internalZ as z122}from"@frontmcp/lazy-zod";var inputSchema26,outputSchema25,stateSchema30,plan33,name33,Stage33,ElicitationResultFlow;var init_elicitation_result_flow=__esm({"libs/sdk/src/elicitation/flows/elicitation-result.flow.ts"(){"use strict";init_common();init_errors();init_session_id_hash();init_helpers();inputSchema26=z122.object({sessionId:z122.string(),result:z122.object({action:z122.enum(["accept","cancel","decline"]),content:z122.unknown().optional()})});outputSchema25=z122.object({handled:z122.boolean(),elicitId:z122.string().optional(),result:z122.any().optional()});stateSchema30=z122.object({sessionId:z122.string(),action:z122.enum(["accept","cancel","decline"]),content:z122.unknown().optional(),pendingRecord:z122.any().optional(),elicitResult:z122.any().optional(),handled:z122.boolean().default(false),output:outputSchema25.optional()});plan33={pre:["parseInput"],execute:["lookupPending","validateContent","buildResult","publishResult"],finalize:["finalize"]};name33="elicitation:result";({Stage:Stage33}=FlowHooksOf(name33));ElicitationResultFlow=class extends FlowBase{logger=this.scopeLogger.child("ElicitationResultFlow");async parseInput(){this.logger.verbose("parseInput:start");const input=inputSchema26.parse(this.rawInput);this.state.set({sessionId:input.sessionId,action:input.result.action,content:input.result.content});this.logger.verbose("parseInput:done",{sessionIdHash:sessionIdHash(input.sessionId),action:input.result.action})}async lookupPending(){this.logger.verbose("lookupPending:start");const{sessionId}=this.state.required;const store=this.scope.elicitationStore;if(!store){throw new ElicitationStoreNotInitializedError}const pendingRecord=await store.getPending(sessionId);this.state.set("pendingRecord",pendingRecord??void 0);if(!pendingRecord){this.logger.verbose("lookupPending:notFound",{sessionIdHash:sessionIdHash(sessionId)})}else{this.logger.verbose("lookupPending:found",{sessionIdHash:sessionIdHash(sessionId),elicitId:pendingRecord.elicitId})}}async validateContent(){this.logger.verbose("validateContent:start");const{action,content,pendingRecord}=this.state;if(action!=="accept"){this.logger.verbose("validateContent:skip (non-accept action)",{action});return}if(!pendingRecord){this.logger.verbose("validateContent:skip (no pending record)");return}if(pendingRecord.mode==="url"){this.logger.verbose("validateContent:skip (url mode)");return}if(!pendingRecord.requestedSchema){this.logger.verbose("validateContent:skip (no schema stored)");return}const validationResult=validateElicitationContent(content,pendingRecord.requestedSchema);if(!validationResult.success){this.logger.warn("validateContent:failed",{sessionIdHash:sessionIdHash(pendingRecord.sessionId),elicitId:pendingRecord.elicitId,errors:validationResult.errors});throw new InvalidInputError("Invalid elicitation result content",validationResult.errors)}this.logger.verbose("validateContent:done")}async buildResult(){this.logger.verbose("buildResult:start");const{action}=this.state.required;const{content,pendingRecord}=this.state;const keepsContent=action==="accept"&&content!==void 0&&pendingRecord?.mode!=="url";const elicitResult={status:action,...keepsContent&&{content}};this.state.set("elicitResult",elicitResult);this.logger.verbose("buildResult:done",{status:elicitResult.status})}async publishResult(){this.logger.verbose("publishResult:start");const{pendingRecord,elicitResult}=this.state;const{sessionId}=this.state.required;const store=this.scope.elicitationStore;if(!pendingRecord||!elicitResult||!store){this.state.set("handled",false);this.logger.verbose("publishResult:skip (no pending or no result)");return}try{await store.publishResult(pendingRecord.elicitId,sessionId,elicitResult);this.state.set("handled",true);this.logger.verbose("publishResult:done",{elicitId:pendingRecord.elicitId,sessionId:sessionId.slice(0,20)})}catch(error){this.logger.warn("publishResult:failed",{elicitId:pendingRecord.elicitId,error:error.message});this.state.set("handled",false)}}async finalize(){this.logger.verbose("finalize:start");const{handled,pendingRecord,elicitResult}=this.state;const output={handled:handled??false,elicitId:pendingRecord?.elicitId,result:elicitResult};this.state.set("output",output);this.respond(output);this.logger.verbose("finalize:done",{handled})}};__decorateClass([Stage33("parseInput")],ElicitationResultFlow.prototype,"parseInput",1);__decorateClass([Stage33("lookupPending")],ElicitationResultFlow.prototype,"lookupPending",1);__decorateClass([Stage33("validateContent")],ElicitationResultFlow.prototype,"validateContent",1);__decorateClass([Stage33("buildResult")],ElicitationResultFlow.prototype,"buildResult",1);__decorateClass([Stage33("publishResult")],ElicitationResultFlow.prototype,"publishResult",1);__decorateClass([Stage33("finalize")],ElicitationResultFlow.prototype,"finalize",1);ElicitationResultFlow=__decorateClass([FrontMcpFlow({name:name33,plan:plan33,inputSchema:inputSchema26,outputSchema:outputSchema25,access:"authorized"})],ElicitationResultFlow)}});var flows_exports2={};__export(flows_exports2,{ElicitRequestFlow:()=>ElicitationRequestFlow,ElicitResultFlow:()=>ElicitationResultFlow,ElicitationRequestFlow:()=>ElicitationRequestFlow,ElicitationResultFlow:()=>ElicitationResultFlow});var init_flows2=__esm({"libs/sdk/src/elicitation/flows/index.ts"(){"use strict";init_elicitation_request_flow();init_elicitation_result_flow()}});import{getEnv as getEnv18}from"@frontmcp/utils";function resolveRegistryAuthRecord(scope){const registry=scope.metadata.registry;if(!registry)return void 0;if(registry.publicKey)return toRegistryAuthRecord(registry.publicKey);const envName=registry.publicKeyEnv??DEFAULT_REGISTRY_PUBLIC_KEY_ENV;const configuredKey=getEnv18(envName)?.trim();if(!configuredKey)return void 0;const record=toRegistryAuthRecord(configuredKey);if(!record&&!envVarsReportedInvalid.has(envName)){envVarsReportedInvalid.add(envName);scope.logger.warn(`MCP Registry domain proof not served: ${envName} is neither a base64 Ed25519 public key nor a "v=MCPv1; k=...; p=..." record`)}return record}function mcpEndpointPath(scope){return`${normalizeEntryPrefix(scope.entryPath)}${normalizeScopeBase(scope.routeBase)}`}function serverCardPath(scope){return`${mcpEndpointPath(scope)}/server-card`}var SERVER_CARD_MEDIA_TYPE,envVarsReportedInvalid;var init_mcp_registry_utils=__esm({"libs/sdk/src/mcp-registry/mcp-registry.utils.ts"(){"use strict";init_common();init_registry();SERVER_CARD_MEDIA_TYPE="application/mcp-server-card+json";envVarsReportedInvalid=new Set}});var MCP_REGISTRY_AUTH_PATH,inputSchema27,outputSchema26,plan34,name34,Stage34,WellKnownMcpRegistryAuthFlow;var init_well_known_mcp_registry_auth_flow=__esm({"libs/sdk/src/mcp-registry/flows/well-known.mcp-registry-auth.flow.ts"(){"use strict";init_common();init_mcp_registry_utils();MCP_REGISTRY_AUTH_PATH="/.well-known/mcp-registry-auth";inputSchema27=httpInputSchema;outputSchema26=HttpTextSchema;plan34={pre:["checkIpFilter","acquireQuota"],execute:["serveRecord"]};name34="well-known.mcp-registry-auth";Stage34=StageHookOf(name34);WellKnownMcpRegistryAuthFlow=class extends FlowBase{static canActivate(request2,scope){return request2.path===MCP_REGISTRY_AUTH_PATH&&resolveRegistryAuthRecord(scope)!==void 0}async checkIpFilter(){enforceIpFilter(this.scope,this.tryGetContext()?.metadata.clientIp)}async acquireQuota(){await enforceGlobalRateLimit(this.scope,this.tryGetContext())}async serveRecord(){const record=resolveRegistryAuthRecord(this.scope);this.respond(record?{kind:"text",status:200,body:record,contentType:"text/plain; charset=utf-8"}:httpRespond.notFound())}};__decorateClass([Stage34("checkIpFilter")],WellKnownMcpRegistryAuthFlow.prototype,"checkIpFilter",1);__decorateClass([Stage34("acquireQuota")],WellKnownMcpRegistryAuthFlow.prototype,"acquireQuota",1);__decorateClass([Stage34("serveRecord")],WellKnownMcpRegistryAuthFlow.prototype,"serveRecord",1);WellKnownMcpRegistryAuthFlow=__decorateClass([FrontMcpFlow({name:name34,plan:plan34,inputSchema:inputSchema27,outputSchema:outputSchema26,access:"public",middleware:{method:"GET"}})],WellKnownMcpRegistryAuthFlow)}});import{internalZ as z123}from"@frontmcp/lazy-zod";import{sha256Base64url}from"@frontmcp/utils";function ifNoneMatchIncludes(ifNoneMatch,etag){const candidates=(ifNoneMatch??"").split(",").map(candidate=>candidate.trim().replace(/^W\//,""));return candidates.includes("*")||candidates.includes(etag)}var SERVER_CARD_SCHEMA_URL,MAX_TITLE_LENGTH,MAX_ICON_SRC_LENGTH,SERVER_CARD_CORS_HEADERS,isHttpsUrl,inputSchema28,stateSchema31,outputSchema27,plan35,name35,Stage35,ServerCardFlow;var init_server_card_flow=__esm({"libs/sdk/src/mcp-registry/flows/server-card.flow.ts"(){"use strict";init_common();init_protocol_20260728_constants();init_mcp_registry_utils();SERVER_CARD_SCHEMA_URL="https://static.modelcontextprotocol.io/schemas/v1/server-card.schema.json";MAX_TITLE_LENGTH=100;MAX_ICON_SRC_LENGTH=255;SERVER_CARD_CORS_HEADERS={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET","Access-Control-Allow-Headers":"Content-Type, If-None-Match","Access-Control-Expose-Headers":"ETag"};isHttpsUrl=url=>url.startsWith("https://");inputSchema28=httpInputSchema;stateSchema31=z123.object({card:z123.record(z123.string(),z123.unknown())});outputSchema27=z123.union([HttpJsonSchema,HttpEmptySchema,HttpTextSchema]);plan35={pre:["checkIpFilter","acquireQuota","answerPreflight"],execute:["buildCard","respondWithCard"]};name35="registry:server-card";Stage35=StageHookOf(name35);ServerCardFlow=class extends FlowBase{static canActivate(request2,scope){return(request2.method==="GET"||request2.method==="OPTIONS")&&request2.path===serverCardPath(scope)}async checkIpFilter(){enforceIpFilter(this.scope,this.tryGetContext()?.metadata.clientIp)}async acquireQuota(){await enforceGlobalRateLimit(this.scope,this.tryGetContext())}async answerPreflight(){if(this.rawInput.request.method==="OPTIONS"){this.respond({kind:"empty",status:204,headers:SERVER_CARD_CORS_HEADERS})}}async buildCard(){const{info,registry}=this.scope.metadata;if(!registry?.name){this.respond(httpRespond.notFound());return}const icons=(info.icons??[]).filter(icon=>isHttpsUrl(icon.src)&&icon.src.length<=MAX_ICON_SRC_LENGTH);const endpointUrl=getRequestBaseUrl(this.rawInput.request,mcpEndpointPath(this.scope)||"/");this.state.set({card:{$schema:SERVER_CARD_SCHEMA_URL,name:registry.name,version:info.version,description:registry.description,...info.title&&info.title.length<=MAX_TITLE_LENGTH?{title:info.title}:{},...info.websiteUrl&&isHttpsUrl(info.websiteUrl)?{websiteUrl:info.websiteUrl}:{},...icons.length>0?{icons}:{},...registry.repository?{repository:registry.repository}:{},remotes:[{type:"streamable-http",url:endpointUrl,supportedProtocolVersions:[...FRONTMCP_SUPPORTED_PROTOCOL_VERSIONS]}]}})}async respondWithCard(){const{card}=this.state.required;const etag=`"${sha256Base64url(JSON.stringify(card))}"`;const cacheControl=isPublicUrlPinned()?"public, max-age=3600":"no-store";const headers={...SERVER_CARD_CORS_HEADERS,"Cache-Control":cacheControl,ETag:etag};this.respond(ifNoneMatchIncludes(this.rawInput.request.headers["if-none-match"],etag)?{kind:"empty",status:304,headers}:{kind:"json",status:200,body:card,contentType:SERVER_CARD_MEDIA_TYPE,headers})}};__decorateClass([Stage35("checkIpFilter")],ServerCardFlow.prototype,"checkIpFilter",1);__decorateClass([Stage35("acquireQuota")],ServerCardFlow.prototype,"acquireQuota",1);__decorateClass([Stage35("answerPreflight")],ServerCardFlow.prototype,"answerPreflight",1);__decorateClass([Stage35("buildCard")],ServerCardFlow.prototype,"buildCard",1);__decorateClass([Stage35("respondWithCard")],ServerCardFlow.prototype,"respondWithCard",1);ServerCardFlow=__decorateClass([FrontMcpFlow({name:name35,plan:plan35,inputSchema:inputSchema28,outputSchema:outputSchema27,access:"public",middleware:{}})],ServerCardFlow)}});import{internalZ as z124}from"@frontmcp/lazy-zod";function aiCatalogIdentifier(registryName){const[namespace,serverName]=registryName.split("/");return`urn:air:${namespace.split(".").reverse().join(".")}:mcp:${serverName}`}var AI_CATALOG_PATH,inputSchema29,outputSchema28,plan36,name36,Stage36,WellKnownAiCatalogFlow;var init_well_known_ai_catalog_flow=__esm({"libs/sdk/src/mcp-registry/flows/well-known.ai-catalog.flow.ts"(){"use strict";init_common();init_mcp_registry_utils();AI_CATALOG_PATH="/.well-known/ai-catalog.json";inputSchema29=httpInputSchema;outputSchema28=z124.union([HttpJsonSchema,HttpTextSchema]);plan36={pre:["checkIpFilter","acquireQuota"],execute:["serveCatalog"]};name36="well-known.ai-catalog";Stage36=StageHookOf(name36);WellKnownAiCatalogFlow=class extends FlowBase{static canActivate(request2){return request2.path===AI_CATALOG_PATH}async checkIpFilter(){enforceIpFilter(this.scope,this.tryGetContext()?.metadata.clientIp)}async acquireQuota(){await enforceGlobalRateLimit(this.scope,this.tryGetContext())}async serveCatalog(){const registryName=this.scope.metadata.registry?.name;if(!registryName){this.respond(httpRespond.notFound());return}this.respond({kind:"json",status:200,contentType:"application/ai-catalog+json",body:{specVersion:"1.0",entries:[{identifier:aiCatalogIdentifier(registryName),type:SERVER_CARD_MEDIA_TYPE,url:getRequestBaseUrl(this.rawInput.request,serverCardPath(this.scope))}]}})}};__decorateClass([Stage36("checkIpFilter")],WellKnownAiCatalogFlow.prototype,"checkIpFilter",1);__decorateClass([Stage36("acquireQuota")],WellKnownAiCatalogFlow.prototype,"acquireQuota",1);__decorateClass([Stage36("serveCatalog")],WellKnownAiCatalogFlow.prototype,"serveCatalog",1);WellKnownAiCatalogFlow=__decorateClass([FrontMcpFlow({name:name36,plan:plan36,inputSchema:inputSchema29,outputSchema:outputSchema28,access:"public",middleware:{method:"GET"}})],WellKnownAiCatalogFlow)}});var init_flows3=__esm({"libs/sdk/src/mcp-registry/flows/index.ts"(){"use strict";init_well_known_mcp_registry_auth_flow();init_server_card_flow();init_well_known_ai_catalog_flow()}});var mcp_registry_scope_helper_exports={};__export(mcp_registry_scope_helper_exports,{registerMcpRegistryFlows:()=>registerMcpRegistryFlows});async function registerMcpRegistryFlows(options){const{flowRegistry,registryOptions,servesServerEndpoint}=options;if(!registryOptions)return;const flows=[WellKnownMcpRegistryAuthFlow];if(servesServerEndpoint&&registryOptions.name&&registryOptions.serverCard!==false){flows.push(ServerCardFlow);if(registryOptions.aiCatalog!==false)flows.push(WellKnownAiCatalogFlow)}await flowRegistry.registryFlows(flows)}var init_mcp_registry_scope_helper=__esm({"libs/sdk/src/mcp-registry/mcp-registry-scope.helper.ts"(){"use strict";init_flows3()}});async function serveRelayedHttpRequest(scope,request2,response){let output;try{output=await scope.runFlow("http:request",{request:request2,response})}catch(error){output=flowErrorToHttpOutput(error)}if(output&&!response.writableEnded){await writeHttpResponse(response,output)}if(response.writableEnded)return;if(!response.headersSent){await writeHttpResponse(response,{kind:"json",status:404,contentType:"application/json; charset=utf-8",body:{error:"Not Found"}});return}response.end()}var init_relay_flow=__esm({"libs/sdk/src/transport/relay/relay-flow.ts"(){"use strict";init_server_validation();init_flow_error_output()}});import{randomUUID as randomUUID27}from"@frontmcp/utils";function errorMessage(error){return error instanceof Error?error.message:String(error)}function isServableRequest(message){return typeof message.requestId==="string"&&typeof message.sourceNodeId==="string"&&typeof message.sessionId==="string"&&typeof message.request==="object"&&message.request!==null}function keepaliveIntervalOf(message){const requested=message.keepaliveMs;if(typeof requested!=="number"||!Number.isFinite(requested))return DEFAULT_OWNER_CHECK_INTERVAL_MS;return Math.max(MIN_KEEPALIVE_MS,requested)}var DEFAULT_ACK_TIMEOUT_MS,DEFAULT_OWNER_CHECK_INTERVAL_MS,DEFAULT_RETRY_AFTER_SECONDS2,MIN_KEEPALIVE_MS,SILENT_CHECKS_BEFORE_FAILURE,SessionRelay;var init_session_relay=__esm({"libs/sdk/src/transport/relay/session-relay.ts"(){"use strict";init_transport_errors();init_transport_error();init_relay_http();DEFAULT_ACK_TIMEOUT_MS=5e3;DEFAULT_OWNER_CHECK_INTERVAL_MS=1e4;DEFAULT_RETRY_AFTER_SECONDS2=30;MIN_KEEPALIVE_MS=100;SILENT_CHECKS_BEFORE_FAILURE=3;SessionRelay=class{constructor(options){this.options=options;this.nodeId=options.nodeId;this.ackTimeoutMs=options.ackTimeoutMs??DEFAULT_ACK_TIMEOUT_MS;this.ownerCheckIntervalMs=options.ownerCheckIntervalMs??DEFAULT_OWNER_CHECK_INTERVAL_MS;this.retryAfterSeconds=options.retryAfterSeconds??DEFAULT_RETRY_AFTER_SECONDS2;this.logger=options.logger}options;nodeId;ackTimeoutMs;ownerCheckIntervalMs;retryAfterSeconds;logger;pending=new Map;serving=new Map;closed=false;get pendingCount(){return this.pending.size}get servingCount(){return this.serving.size}unreachable(ownerNodeId,reason){return new SessionOwnerUnreachableError(ownerNodeId,this.retryAfterSeconds,reason)}forward(ownerNodeId,sessionId,request2,response){if(this.closed)return Promise.reject(this.unreachable(ownerNodeId,"this node is shutting down"));const requestId=randomUUID27();const sessionLabel=sessionId.slice(0,20);return new Promise((resolve4,reject)=>{let acked=false;let headWritten=false;let done=false;let lastFrameAt=Date.now();let ownerTimer;const cleanup=()=>{clearTimeout(ackTimer);if(ownerTimer)clearInterval(ownerTimer);response.removeListener("close",onClientClose);this.pending.delete(requestId)};const finish=()=>{if(done)return;done=true;cleanup();resolve4()};const fail=reason=>{if(done)return;done=true;cleanup();this.logger?.warn(`[HA] Relay to session owner failed: ${reason}`,{sessionId:sessionLabel,ownerNodeId});if(!headWritten&&!response.headersSent){reject(this.unreachable(ownerNodeId,reason));return}if(!response.writableEnded)response.end();resolve4()};const onClientClose=()=>{if(done||response.writableFinished)return;done=true;cleanup();this.options.publish(ownerNodeId,{kind:"relay-cancel",requestId,sourceNodeId:this.nodeId}).catch(()=>void 0);resolve4()};const checkOwner=async()=>{if(Date.now()-lastFrameAt>=this.ownerCheckIntervalMs*SILENT_CHECKS_BEFORE_FAILURE){fail("the owner stopped sending the response");return}try{if(!await this.options.isNodeAlive(ownerNodeId))fail("the owner stopped while serving the request")}catch{}};const markAcked=()=>{if(acked)return;acked=true;clearTimeout(ackTimer);ownerTimer=setInterval(()=>void checkOwner(),this.ownerCheckIntervalMs);ownerTimer.unref?.()};const onFrame=frame4=>{if(done)return;lastFrameAt=Date.now();switch(frame4.event){case"ack":markAcked();return;case"keepalive":return;case"head":markAcked();if(!response.headersSent){response.writeHead(frame4.status,frame4.headers);response.flushHeaders?.()}headWritten=true;return;case"data":response.write(decodeRelayChunk(frame4));return;case"end":if(!response.writableEnded)response.end();finish();return;case"error":fail(`the owner could not serve the request: ${frame4.message}`);return}};const ackTimer=setTimeout(()=>fail(`the owner did not acknowledge the request within ${this.ackTimeoutMs}ms`),this.ackTimeoutMs);ackTimer.unref?.();this.pending.set(requestId,{ownerNodeId,onFrame,fail});response.once("close",onClientClose);const message={kind:"relay-request",requestId,sourceNodeId:this.nodeId,sessionId,request:request2,timestamp:Date.now(),keepaliveMs:this.ownerCheckIntervalMs};this.logger?.verbose?.("[HA] Relaying request to session owner",{sessionId:sessionLabel,ownerNodeId});this.options.publish(ownerNodeId,message).then(receivers=>{if(receivers===0)fail("the owner does not listen on its relay channel")},error=>fail(`publishing the request failed: ${errorMessage(error)}`))})}handleMessage(message){switch(message.kind){case"relay-request":if(!isServableRequest(message)){this.logger?.warn("[HA] Dropped a malformed relayed request");return}this.serveRelayed(message).catch(error=>{this.logger?.warn("[HA] Serving a relayed request failed",{error:errorMessage(error)})});return;case"relay-response":{const pending=this.pending.get(message.requestId);if(pending&&pending.ownerNodeId===message.sourceNodeId)pending.onFrame(message);return}case"relay-cancel":{const serving=this.serving.get(message.requestId);if(serving&&serving.sourceNodeId===message.sourceNodeId)serving.response.destroy();return}default:return}}async close(){if(this.closed)return;this.closed=true;for(const pending of[...this.pending.values()])pending.fail("this node is shutting down");for(const serving of[...this.serving.values()]){if(!serving.response.writableEnded){serving.send({event:"error",message:"the owner is shutting down"});serving.response.destroy()}}this.serving.clear()}async serveRelayed(message){const{requestId,sourceNodeId}=message;let undeliverable=false;const publishFrame=event=>{const frame4={kind:"relay-response",requestId,sourceNodeId:this.nodeId,...event};return this.options.publish(sourceNodeId,frame4)};const abandon=reason=>{if(undeliverable)return;undeliverable=true;this.logger?.warn("[HA] Failed to publish a relayed response frame",{reason,targetNodeId:sourceNodeId});publishFrame({event:"error",message:reason}).catch(()=>void 0);response.destroy()};const send=event=>{if(undeliverable)return;publishFrame(event).then(receivers=>{if(receivers===0)abandon("the relaying node no longer listens")},error=>abandon(`publishing a response frame failed: ${errorMessage(error)}`))};const response=new RelayServerResponse({head:(status,headers)=>send({event:"head",status,headers}),data:chunk=>send({event:"data",...chunk}),end:()=>send({event:"end"})});if(this.closed){send({event:"error",message:"the owner is shutting down"});return}send({event:"ack"});const keepaliveTimer=setInterval(()=>send({event:"keepalive"}),keepaliveIntervalOf(message));keepaliveTimer.unref?.();this.serving.set(requestId,{sourceNodeId,response,send});try{const request2=createRelayedServerRequest(message.request,sourceNodeId);await this.options.serve(request2,response.asServerResponse())}catch(error){this.logger?.warn("[HA] Serving a relayed request failed",{sessionId:message.sessionId.slice(0,20),sourceNodeId,error:errorMessage(error)});if(!response.writableEnded&&!response.destroyed&&!response.headersSent){response.status(500).json(rpcError("Internal error"))}}finally{clearInterval(keepaliveTimer);if(!response.writableEnded&&!response.destroyed)response.end();this.serving.delete(requestId)}}}}});var relay_scope_helper_exports={};__export(relay_scope_helper_exports,{wireSessionRelay:()=>wireSessionRelay});function wireSessionRelay(options){const{haManager,bus,transportService,notifications,logger,nodeId}=options;if(!haManager.getRelay())return void 0;const config=haManager.getConfig();const relay=new SessionRelay({nodeId,publish:(target,message)=>haManager.publishToNode(target,message),isNodeAlive:target=>haManager.isNodeAlive(target),serve:(request2,response)=>serveRelayedHttpRequest(options.flows,request2,response),ackTimeoutMs:options.ackTimeoutMs,ownerCheckIntervalMs:config.heartbeatIntervalMs,retryAfterSeconds:Math.ceil(config.heartbeatTtlMs/1e3),logger});const handler=message=>{if(isRequestRelayMessage(message)){relay.handleMessage(message);return}if(message.kind==="destroy-session"){transportService.destroyLocalSession(message.sessionId,message.reason).catch(error=>{logger.warn("[HA] Failed to destroy a session on request of another node",{sessionId:message.sessionId.slice(0,20),error:error instanceof Error?error.message:String(error)})});return}if(message.kind===void 0||message.kind==="notification"){notifications.deliverRelayedNotification(message.sessionId,message.notification.method,message.notification.params)}};let closed=false;let retryTimer;let settleReady=()=>void 0;const ready=new Promise(resolve4=>{settleReady=resolve4;const attempt=failures=>{if(closed){resolve4();return}haManager.subscribeRelay(handler).then(()=>{if(closed){resolve4();return}bus.attachRelay(relay);logger.info("[HA] Request relay ready \u2014 sessions owned by other nodes are served through them");resolve4()},error=>{const delay=Math.min(SUBSCRIBE_RETRY_MAX_MS,SUBSCRIBE_RETRY_BASE_MS*2**failures);logger.warn(`[HA] Relay channel subscription failed \u2014 retrying in ${delay}ms`,{error:error instanceof Error?error.message:String(error)});retryTimer=setTimeout(()=>attempt(failures+1),delay);retryTimer.unref?.()})};attempt(0)});return{relay,ready,close:async()=>{closed=true;if(retryTimer)clearTimeout(retryTimer);settleReady();bus.attachRelay(void 0);await relay.close()}}}var SUBSCRIBE_RETRY_BASE_MS,SUBSCRIBE_RETRY_MAX_MS;var init_relay_scope_helper=__esm({"libs/sdk/src/transport/relay/relay-scope.helper.ts"(){"use strict";init_relay_messages();init_relay_flow();init_session_relay();SUBSCRIBE_RETRY_BASE_MS=1e3;SUBSCRIBE_RETRY_MAX_MS=3e4}});var ChannelNotificationService;var init_channel_notification_service=__esm({"libs/sdk/src/channel/channel-notification.service.ts"(){"use strict";init_notification_service();init_channel_utils();ChannelNotificationService=class{constructor(notificationService,logger,defaultMeta,sendThroughFlow){this.notificationService=notificationService;this.sendThroughFlow=sendThroughFlow;this.logger=logger.child("ChannelNotificationService");this.serverMeta={...defaultMeta??{}}}notificationService;sendThroughFlow;logger;serverMeta;streamListeners=new Set;get defaultMeta(){return this.serverMeta}sendToSubscribedSessions(content,meta){const channelName=meta.source;if(!channelName){this.logger.warn("Cannot send channel notification without source in meta");return}const safeMeta=this.safeMetaOf(meta);for(const listener of this.streamListeners){if(listener.channels.has(channelName))listener.deliver(content,safeMeta)}const subscribers=this.notificationService.getSubscribersForChannel(channelName);if(subscribers.length===0){this.logger.verbose(`No subscribers for channel "${channelName}", notification buffered only`);return}const recipients=new Set(subscribers.filter(sessionId=>{const registered=this.notificationService.getRegisteredServer(sessionId);return registered!==void 0&&isChannelCapableSession(registered)&&!hasExpiredCaller(registered)}));if(recipients.size>0){this.notificationService.sendCustomNotification(CHANNEL_NOTIFICATION_METHOD,{content,meta:safeMeta},session=>recipients.has(session.sessionId))}this.logger.verbose(`Sent channel "${channelName}" notification to ${subscribers.length} subscriber(s)`)}listen(channelNames,deliver){const listener={channels:new Set(channelNames),deliver};this.streamListeners.add(listener);return()=>{this.streamListeners.delete(listener)}}sendToAllCapableSessions(content,meta){this.sendToSubscribedSessions(content,meta)}sendToSession(sessionId,content,meta){const registered=this.notificationService.getRegisteredServer(sessionId);if(!registered){this.logger.warn(`Cannot send channel notification to unregistered session: ${sessionId.slice(0,20)}...`);return false}if(!isChannelCapableSession(registered)){this.logger.verbose(`Session ${sessionId.slice(0,20)}... does not support channels, skipping`);return false}if(hasExpiredCaller(registered)){this.logger.verbose(`Session ${sessionId.slice(0,20)}... was last seen with expired credentials, skipping`);return false}const channelName=meta.source;if(!channelName){this.logger.error(`Channel notification rejected for session ${sessionId.slice(0,20)}...: meta.source is required`);return false}if(!this.notificationService.isChannelSubscribed(sessionId,channelName)){this.logger.verbose(`Session ${sessionId.slice(0,20)}... not subscribed to channel "${channelName}", skipping`);return false}this.notificationService.sendCustomNotification(CHANNEL_NOTIFICATION_METHOD,{content,meta:this.safeMetaOf(meta)},session=>session.sessionId===sessionId);return true}safeMetaOf(meta){return{...channelMetaOf(meta),source:meta.source}}async send(channelName,content,additionalMeta){if(!this.sendThroughFlow){const ownMeta=channelMetaValuesOf(additionalMeta??{});this.sendToSubscribedSessions(content,{...this.serverMeta,...ownMeta,source:channelName});return}try{await this.sendThroughFlow({channelName,content,meta:additionalMeta})}catch(error){this.logger.error(`Channel "${channelName}" notification failed`,{error})}}}}});var ChannelEmitter;var init_channel_events=__esm({"libs/sdk/src/channel/channel.events.ts"(){"use strict";ChannelEmitter=class{listeners=new Set;on(l){this.listeners.add(l);return()=>this.listeners.delete(l)}emit(e){for(const l of[...this.listeners])l(e)}}}});import{watchFiles}from"@frontmcp/utils";function connectsItself(context){return context.onConnect!==ChannelContext.prototype.onConnect}function watchedTypesOf(sourceConfig){if(!sourceConfig.events)return void 0;const watchedTypes=sourceConfig.events.flatMap(declaredEvent=>WATCHED_TYPES[declaredEvent]);return[...new Set(watchedTypes)]}function warnAboutGlobs(channelName,paths,logger){const globs=paths.filter(path4=>path4.includes("*"));if(globs.length===0)return;logger.warn(`Channel "${channelName}" declares ${globs.map(glob=>`"${glob}"`).join(", ")}: a file-watcher path is not expanded as a glob. Declare the directory to watch its direct files.`)}async function forwardFileEvents(channel2,sourceConfig,signal,logger){const events=watchedTypesOf(sourceConfig);for await(const{type,path:path4}of watchFiles(sourceConfig.paths,{events,signal})){const fileEvent={event:REPORTED_EVENTS[type],path:path4};logger.verbose(`File ${fileEvent.event} for channel "${channel2.name}": ${path4}`);try{await channel2.handleEvent(fileEvent)}catch(error){logger.error(`Failed to handle a file event in channel "${channel2.name}"`,{error})}}}function wireFileWatcherSource(channel2,context,sourceConfig,logger){if(connectsItself(context)){logger.info(`Channel "${channel2.name}" defines onConnect(), so it watches by itself: the framework does not watch its declared paths. Remove onConnect() to have the framework watch them.`);return()=>void 0}if(!isLongLivedProcess()){logger.warn(`Channel "${channel2.name}" does not watch its paths in a serverless, edge or browser runtime: watching files needs a long-lived process`);return()=>void 0}warnAboutGlobs(channel2.name,sourceConfig.paths,logger);const watch=new AbortController;forwardFileEvents(channel2,sourceConfig,watch.signal,logger).catch(error=>{logger.error(`Channel "${channel2.name}" stopped watching its paths`,{error})});return()=>watch.abort()}var WATCHED_TYPES,REPORTED_EVENTS;var init_file_watcher_source=__esm({"libs/sdk/src/channel/sources/file-watcher.source.ts"(){"use strict";init_common();init_lease_store();WATCHED_TYPES={create:["add"],change:["change"],delete:["unlink"],rename:["add","unlink"]};REPORTED_EVENTS={add:"create",change:"change",unlink:"delete"}}});var ChannelInstance,FunctionChannelContext;var init_channel_instance=__esm({"libs/sdk/src/channel/channel.instance.ts"(){"use strict";init_common();init_file_watcher_source();ChannelInstance=class extends ChannelEntry{_providers;scope;_channelNotificationService;_serviceContext;_stopFileWatch;_replayBuffer=[];_maxReplayEvents;constructor(record,providers,owner){super(record);this.owner=owner;this._providers=providers;this.name=record.metadata.name;this.fullName=this.owner.id+":"+this.name;this.scope=this._providers.getActiveScope();this._maxReplayEvents=record.metadata.replay?.maxEvents??50;this.ready=this.initialize()}setNotificationService(service){this._channelNotificationService=service}get providers(){return this._providers}get isServiceConnector(){return this.metadata.source.type==="service"||this.metadata.source.type==="file-watcher"}async initialize(){}async connectService(){if(!this.isServiceConnector)return;const logger=this._providers.get(FrontMcpLogger);const ctx=this.create({});ctx._pushIncoming=payload=>{this.handleEvent(payload).catch(err=>{logger.error(`Channel "${this.name}" service: pushIncoming failed`,{error:err})})};try{await ctx.onConnect();this._serviceContext=ctx;const{source}=this.metadata;if(source.type==="file-watcher")this._stopFileWatch=wireFileWatcherSource(this,ctx,source,logger);const sourceLabel=source.type==="service"?source.service:source.type;logger.info(`Channel "${this.name}" connected (${sourceLabel})`)}catch(err){this._serviceContext=void 0;logger.error(`Channel "${this.name}" service failed to connect`,{error:err});throw err}}async disconnectService(){if(!this._serviceContext)return;this._stopFileWatch?.();this._stopFileWatch=void 0;const logger=this._providers.get(FrontMcpLogger);try{await this._serviceContext.onDisconnect();logger.info(`Channel "${this.name}" service disconnected`)}catch(err){logger.error(`Channel "${this.name}" service failed to disconnect`,{error:err})}this._serviceContext=void 0}get serviceContext(){return this._serviceContext}create(authInfo){const logger=this._providers.get(FrontMcpLogger);const ctorArgs={metadata:this.metadata,providers:this._providers,logger,authInfo};switch(this.record.kind){case"FUNCTION":{const fnRecord=this.record;const handler=fnRecord.provide();return new FunctionChannelContext(ctorArgs,handler)}case"CLASS_TOKEN":{return new this.record.provide(ctorArgs)}default:throw new Error(`Unknown channel kind: ${this.record.kind}`)}}get replayEnabled(){return this.metadata.replay?.enabled===true}get replayBuffer(){return this._replayBuffer}async pushNotification(content,meta,targetSessionId){try{await this.scope.runFlow("channels:send-notification",{channelName:this.name,content,meta,...targetSessionId?{targetSessionId}:{}})}catch(err){this._providers.get(FrontMcpLogger).error(`Channel "${this.name}" failed to send a notification`,{error:err})}}recordForReplay(notification){if(!this.replayEnabled)return;this._replayBuffer.push(notification);while(this._replayBuffer.length>this._maxReplayEvents){this._replayBuffer.shift()}}replayBufferedEvents(sessionId){if(!this.replayEnabled||this._replayBuffer.length===0||!this._channelNotificationService){return 0}let count=0;for(const notification of this._replayBuffer){const replayMeta={...notification.meta,replayed:"true"};if(this._channelNotificationService.sendToSession(sessionId,notification.content,replayMeta))count++}return count}clearReplayBuffer(){this._replayBuffer=[]}async handleEvent(payload,targetSessionId){try{const ctx=this._serviceContext??this.create({});const notification=await ctx.onEvent(payload);if(notification){await this.pushNotification(notification.content,notification.meta,targetSessionId)}return notification}catch(err){const logger=this._providers.get(FrontMcpLogger);logger.error(`Channel "${this.name}" failed to handle event`,{error:err});return null}}async handleReply(reply,meta){if(!this.twoWay){return}try{const ctx=this._serviceContext??this.create({});await ctx.onReply(reply,meta)}catch(err){const logger=this._providers.get(FrontMcpLogger);logger.error(`Channel "${this.name}" failed to handle reply`,{error:err});throw err}}};FunctionChannelContext=class extends ChannelContext{handler;constructor(args,handler){super(args);this.handler=handler}async onEvent(payload){return this.handler(payload,this)}}}});import{getRuntimeContext as getRuntimeContext23,isEntryAvailable as isEntryAvailable7}from"@frontmcp/utils";var ChannelRegistry;var init_channel_registry=__esm({"libs/sdk/src/channel/channel.registry.ts"(){"use strict";init_common();init_regsitry();init_channel_events();init_channel_instance();init_channel_utils();ChannelRegistry=class extends RegistryAbstract{owner;localRows=[];version=0;emitter=new ChannelEmitter;logger;entryProviders;constructor(providers,list,owner,entryProviders=new Map){super("ChannelRegistry",providers,list,false);this.owner=owner;this.entryProviders=entryProviders;this.logger=providers.get(FrontMcpLogger).child("ChannelRegistry");this.buildGraph();this.ready=this.initialize()}buildMap(list){const tokens=new Set;const defs=new Map;const graph=new Map;for(const raw of list){const rec=normalizeChannel(raw);const provide=rec.provide;tokens.add(provide);defs.set(provide,rec);graph.set(provide,new Set)}return{tokens,defs,graph}}buildGraph(){}async initialize(){const runtimeContext=getRuntimeContext23();for(const token of this.tokens){const rec=this.defs.get(token);if(!rec)continue;if(!isEntryAvailable7(rec.metadata.availableWhen,runtimeContext)){this.logger.verbose(`Channel "${rec.metadata.name}" is not available in this runtime; skipped`);continue}const instance=new ChannelInstance(rec,this.entryProviders.get(token)??this.providers,this.owner);await instance.ready;const existingRow=this.localRows.find(r=>r.resolvedName===instance.name);if(existingRow){throw new Error(`Duplicate channel name "${instance.name}" \u2014 each channel must have a unique name.`)}this.instances.set(token,instance);this.localRows.push({instance,owner:this.owner,resolvedName:instance.name})}if(this.localRows.length>0){this.logger.info(`Initialized ${this.localRows.length} channel(s): ${this.localRows.map(r=>r.resolvedName).join(", ")}`)}}getChannels(){return this.localRows.map(r=>r.instance)}getChannelInstances(){return this.localRows.map(r=>r.instance)}findByName(name59){return this.localRows.find(r=>r.instance.name===name59)?.instance}hasAny(){return this.localRows.length>0}get size(){return this.localRows.length}getCapabilities(){if(!this.hasAny())return{};return{experimental:{"claude/channel":{}}}}subscribe(opts,cb){const unsub=this.emitter.on(cb);if(opts.immediate&&this.localRows.length>0){cb({kind:"reset",changeScope:"global",version:this.version,snapshot:this.getChannels()})}return unsub}bump(kind){this.version++;this.emitter.emit({kind,changeScope:"global",version:this.version,snapshot:this.getChannels()})}}}});import{internalZ as z125}from"@frontmcp/lazy-zod";var inputSchema30,channelInfoSchema,outputSchema29,stateSchema32,plan37,name37,Stage37,ListChannelsFlow;var init_list_channels_flow=__esm({"libs/sdk/src/channel/flows/list-channels.flow.ts"(){"use strict";init_common();inputSchema30=z125.object({}).optional();channelInfoSchema=z125.object({name:z125.string(),description:z125.string().optional(),sourceType:z125.string(),twoWay:z125.boolean(),tags:z125.array(z125.string())});outputSchema29=z125.object({channels:z125.array(channelInfoSchema),count:z125.number()});stateSchema32=z125.object({output:outputSchema29.optional()});plan37={execute:["listChannels"],finalize:["finalize"]};name37="channels:list";({Stage:Stage37}=FlowHooksOf(name37));ListChannelsFlow=class extends FlowBase{logger=this.scopeLogger.child("ListChannelsFlow");async listChannels(){this.logger.verbose("listChannels:start");const channelRegistry=this.scope.channels;if(!channelRegistry){this.state.set({output:{channels:[],count:0}});return}const channels=channelRegistry.getChannels().map(ch=>({name:ch.name,description:ch.metadata.description,sourceType:ch.source.type,twoWay:ch.twoWay,tags:ch.getTags()}));this.state.set({output:{channels,count:channels.length}});this.logger.verbose("listChannels:done")}async finalize(){this.logger.verbose("finalize:start");this.respond(this.state.required.output??{channels:[],count:0});this.logger.verbose("finalize:done")}};__decorateClass([Stage37("listChannels")],ListChannelsFlow.prototype,"listChannels",1);__decorateClass([Stage37("finalize")],ListChannelsFlow.prototype,"finalize",1);ListChannelsFlow=__decorateClass([FrontMcpFlow({name:name37,plan:plan37,inputSchema:inputSchema30,outputSchema:outputSchema29,access:"authorized"})],ListChannelsFlow)}});import{internalZ as z126}from"@frontmcp/lazy-zod";var inputSchema31,outputSchema30,stateSchema33,plan38,name38,Stage38,SendChannelNotificationFlow;var init_send_channel_notification_flow=__esm({"libs/sdk/src/channel/flows/send-channel-notification.flow.ts"(){"use strict";init_common();init_errors();init_channel_utils();inputSchema31=z126.object({channelName:z126.string().min(1),content:z126.string().min(1),meta:z126.record(z126.string(),z126.unknown()).optional(),targetSessionId:z126.string().min(1).optional()});outputSchema30=z126.object({sent:z126.boolean(),channelName:z126.string()});stateSchema33=z126.object({channelName:z126.string(),content:z126.string(),meta:z126.record(z126.string(),z126.string()).optional(),targetSessionId:z126.string().optional(),output:outputSchema30.optional()});plan38={pre:["parseInput","resolveMeta"],execute:["send"],finalize:["finalize"]};name38="channels:send-notification";({Stage:Stage38}=FlowHooksOf(name38));SendChannelNotificationFlow=class extends FlowBase{logger=this.scopeLogger.child("SendChannelNotificationFlow");async parseInput(){this.logger.verbose("parseInput:start");let data;try{data=inputSchema31.parse(this.rawInput)}catch(e){throw new InvalidInputError("Invalid channel notification input",e instanceof z126.ZodError?e.issues:void 0)}this.state.set({channelName:data.channelName,content:data.content,meta:data.meta&&channelMetaValuesOf(data.meta),targetSessionId:data.targetSessionId});this.logger.verbose("parseInput:done")}async resolveMeta(){const{channelName}=this.state.required;const{meta}=this.state;const channel2=this.findChannel(channelName);const resolved={...this.scope.channelNotifications?.defaultMeta??{},...channel2?.staticMeta??{},...meta??{},source:channelName};this.state.set("meta",resolved)}async send(){this.logger.verbose("send:start");const{channelName,content}=this.state.required;const{targetSessionId}=this.state;const meta={...this.state.meta??{},source:channelName};const channel2=this.findChannel(channelName);if(channel2&&!targetSessionId)channel2.recordForReplay({content,meta});const channelNotifications=this.scope.channelNotifications;if(!channelNotifications){this.logger.warn("Channel notification service not available");this.state.set("output",{sent:false,channelName});return}const sent=targetSessionId?channelNotifications.sendToSession(targetSessionId,content,meta):(channelNotifications.sendToSubscribedSessions(content,meta),true);this.state.set("output",{sent,channelName});this.logger.verbose("send:done")}async finalize(){this.logger.verbose("finalize:start");const output=this.state.output??{sent:false,channelName:this.state.required.channelName};this.respond(output);this.logger.verbose("finalize:done")}findChannel(channelName){return this.scope.channels?.findByName(channelName)}};__decorateClass([Stage38("parseInput")],SendChannelNotificationFlow.prototype,"parseInput",1);__decorateClass([Stage38("resolveMeta")],SendChannelNotificationFlow.prototype,"resolveMeta",1);__decorateClass([Stage38("send")],SendChannelNotificationFlow.prototype,"send",1);__decorateClass([Stage38("finalize")],SendChannelNotificationFlow.prototype,"finalize",1);SendChannelNotificationFlow=__decorateClass([FrontMcpFlow({name:name38,plan:plan38,inputSchema:inputSchema31,outputSchema:outputSchema30,access:"public"})],SendChannelNotificationFlow)}});import{internalZ as z127}from"@frontmcp/lazy-zod";var channelReplyInputSchema;var init_reply_types=__esm({"libs/sdk/src/channel/reply/reply.types.ts"(){"use strict";channelReplyInputSchema={channel_name:z127.string().describe("The name of the channel to reply to"),text:z127.string().describe("The reply text to send back through the channel"),meta:z127.record(z127.string(),z127.string()).optional().describe("Optional metadata for the reply")}}});var ChannelReplyTool;var init_channel_reply_tool=__esm({"libs/sdk/src/channel/reply/channel-reply.tool.ts"(){"use strict";init_common();init_reply_types();ChannelReplyTool=class extends ToolContext{async execute(input){const{channel_name,text,meta}=input;this.logger.info("channel-reply: processing",{channel_name,textLength:text.length});const channelRegistry=this.scope.channels;if(!channelRegistry){this.logger.error("channel-reply: channel registry not available");return{content:[{type:"text",text:"Error: Channel system is not enabled on this server."}],isError:true}}const channel2=channelRegistry.findByName(channel_name);if(!channel2){this.logger.warn(`channel-reply: channel "${channel_name}" not found`);return{content:[{type:"text",text:`Error: Channel "${channel_name}" not found. Available channels: ${channelRegistry.getChannelInstances().filter(c=>c.twoWay).map(c=>c.name).join(", ")}`}],isError:true}}if(!channel2.twoWay){this.logger.warn(`channel-reply: channel "${channel_name}" is not two-way`);return{content:[{type:"text",text:`Error: Channel "${channel_name}" does not support replies (one-way only).`}],isError:true}}try{await channel2.handleReply(text,meta);this.logger.info(`channel-reply: reply sent to channel "${channel_name}"`);return{content:[{type:"text",text:`Reply sent to channel "${channel_name}" successfully.`}]}}catch(err){this.logger.error(`channel-reply: failed to send reply to channel "${channel_name}"`,{error:err});return{content:[{type:"text",text:`Error: Failed to send reply to channel "${channel_name}": ${err instanceof Error?err.message:"Unknown error"}`}],isError:true}}}};ChannelReplyTool=__decorateClass([Tool({name:"channel-reply",description:"Reply to a notification channel. Use this to send a message back through a two-way channel (e.g., chat bridge, messaging service). Specify the channel_name and the text to send.",inputSchema:channelReplyInputSchema,annotations:{title:"Channel Reply",openWorldHint:true}})],ChannelReplyTool)}});function wireAgentCompletionSource(channel2,sourceConfig,agentEmitterSubscribe,logger){const filterAgentIds=sourceConfig.agentIds;return agentEmitterSubscribe(event=>{if(filterAgentIds&&filterAgentIds.length>0){if(!filterAgentIds.includes(event.agentId)){return}}if(!event.sessionId){logger.verbose(`Skipping agent completion for channel "${channel2.name}": no sessionId (prevents cross-session leak)`);return}logger.verbose(`Agent completion event for channel "${channel2.name}": agent=${event.agentId}, status=${event.status}`);channel2.handleEvent(event,event.sessionId).catch(err=>{logger.error(`Failed to handle agent completion event in channel "${channel2.name}"`,{error:err})})})}var init_agent_completion_source=__esm({"libs/sdk/src/channel/sources/agent-completion.source.ts"(){"use strict"}});function wireJobCompletionSource(channel2,sourceConfig,jobEmitterSubscribe,logger){const filterJobNames=sourceConfig.jobNames;return jobEmitterSubscribe(event=>{if(filterJobNames&&filterJobNames.length>0){if(!filterJobNames.includes(event.jobName)&&!filterJobNames.includes(event.jobId)){return}}if(!event.sessionId){logger.verbose(`Skipping job completion for channel "${channel2.name}": no sessionId (prevents cross-session leak)`);return}logger.verbose(`Job completion event for channel "${channel2.name}": job=${event.jobName}, status=${event.status}`);channel2.handleEvent(event,event.sessionId).catch(err=>{logger.error(`Failed to handle job completion event in channel "${channel2.name}"`,{error:err})})})}var init_job_completion_source=__esm({"libs/sdk/src/channel/sources/job-completion.source.ts"(){"use strict"}});function createWebhookMiddleware(channel2,sourceConfig,logger){return async(req,res)=>{const rawHeaders=req.headers??{};const normalizedHeaders={};for(const[key,value]of Object.entries(rawHeaders)){normalizedHeaders[key.toLowerCase()]=value}const payload={body:req.body,headers:normalizedHeaders,method:req.method??"POST",query:req.query};logger.verbose(`Webhook received for channel "${channel2.name}" at ${sourceConfig.path}`);try{const notification=await runOnSurface("http-trigger",()=>channel2.handleEvent(payload));if(notification){res.status(200).json({ok:true,channel:channel2.name})}else{res.status(200).json({ok:true,channel:channel2.name,skipped:true})}}catch(err){logger.error(`Webhook handler failed for channel "${channel2.name}"`,{error:err});res.status(500).json({ok:false,error:"Internal channel error"})}}}var init_webhook_source=__esm({"libs/sdk/src/channel/sources/webhook.source.ts"(){"use strict";init_call_surface()}});var channel_scope_helper_exports={};__export(channel_scope_helper_exports,{registerChannelCapabilities:()=>registerChannelCapabilities});async function registerChannelCapabilities(args){const{providers,owner,channelsList,channelProviders,channelsConfig,notificationService,flowRegistry,toolRegistry,http:http4,logger}=args;const completions=completionEventsOf(providers.getActiveScope());const agentEmitterSubscribe=args.agentEmitterSubscribe??(cb=>completions.agents.subscribe(cb));const jobEmitterSubscribe=args.jobEmitterSubscribe??(cb=>completions.jobs.subscribe(cb));const unsubscribers=[];const reservedPaths=http4?computeReservedPaths(http4.entryPath,http4.routeBase,http4.healthPaths):void 0;const webhookPaths=new Map;const channelRegistry=new ChannelRegistry(providers,channelsList,owner,channelProviders);await channelRegistry.ready;const channelNotificationService=new ChannelNotificationService(notificationService,logger,channelsConfig?.defaultMeta,input=>flowRegistry.runFlow("channels:send-notification",input));const channelEventBus=args.eventBus??new ChannelEventBus(logger);for(const instance of channelRegistry.getChannelInstances()){instance.setNotificationService(channelNotificationService)}for(const instance of channelRegistry.getChannelInstances()){const sourceType=instance.source.type;switch(sourceType){case"agent-completion":{const unsub=wireAgentCompletionSource(instance,instance.metadata.source,agentEmitterSubscribe,logger);unsubscribers.push(unsub);break}case"job-completion":{const unsub=wireJobCompletionSource(instance,instance.metadata.source,jobEmitterSubscribe,logger);unsubscribers.push(unsub);break}case"app-event":{const eventName=instance.metadata.source.event;const unsub=wireAppEventSource(instance,eventName,channelEventBus,logger);unsubscribers.push(unsub);break}case"webhook":{const source=instance.metadata.source;if(!http4||!reservedPaths){logger.warn(`Channel "${instance.name}" has a webhook source but no HTTP server to serve ${source.path}`);break}assertNotReserved("POST",source.path,reservedPaths);const claimedBy=webhookPaths.get(source.path);if(claimedBy){throw new Error(`Channels "${claimedBy}" and "${instance.name}" both declare the webhook path ${source.path}. Give each webhook channel its own path.`)}webhookPaths.set(source.path,instance.name);const handler=createWebhookMiddleware(instance,source,logger);await http4.server.registerRoute("POST",source.path,wrapWithIpFilter(handler,http4.checkClientIp));logger.info(`Registered webhook route for channel "${instance.name}": POST ${source.path}`);break}case"manual":break;case"service":case"file-watcher":break}}await flowRegistry.registryFlows([SendChannelNotificationFlow,ListChannelsFlow]);const hasTwoWayChannels=channelRegistry.getChannelInstances().some(ch=>ch.twoWay);if(hasTwoWayChannels){const replyToolRecord=normalizeTool(ChannelReplyTool);const replyToolInstance=new ToolInstance(replyToolRecord,providers,owner);await replyToolInstance.ready;toolRegistry.registerToolInstance(replyToolInstance);logger.info("Registered channel-reply tool for two-way channel communication")}let channelToolCount=0;for(const instance of channelRegistry.getChannelInstances()){const channelTools=instance.metadata.tools;if(channelTools&&channelTools.length>0){for(const toolDef of channelTools){try{const toolRecord=normalizeTool(toolDef);const toolRecords=isExternalToolRecord(toolRecord)?await loadExternalToolRecords(providers.getActiveScope(),toolRecord):[toolRecord];for(const record of toolRecords){const toolInstance=new ToolInstance(record,instance.providers,{kind:"scope",id:`_channel:${instance.name}`,ref:toolDef});await toolInstance.ready;toolRegistry.registerToolInstance(toolInstance);channelToolCount++}}catch(error){logger.warn(`Failed to register tool from channel "${instance.name}": ${error instanceof Error?error.message:String(error)}`)}}}}if(channelToolCount>0){logger.info(`Registered ${channelToolCount} tool(s) from channel declarations`)}const serviceChannels=channelRegistry.getChannelInstances().filter(ch=>ch.isServiceConnector);logger.info(`Channel system initialized: ${channelRegistry.size} channel(s)`+(hasTwoWayChannels?", reply tool":"")+(channelToolCount>0?`, ${channelToolCount} channel tool(s)`:"")+(serviceChannels.length>0?`, ${serviceChannels.length} service connector(s)`:""));const teardown=async()=>{const results=await Promise.allSettled(serviceChannels.map(instance=>instance.disconnectService()));for(const result of results){if(result.status==="rejected"){logger.error("Channel disconnect failed during teardown",{error:result.reason})}}for(const unsub of unsubscribers)unsub();if(!args.eventBus)channelEventBus.clear()};return{channelRegistry,channelNotificationService,channelEventBus,connectServices:async()=>{try{for(const instance of serviceChannels)await instance.connectService()}catch(err){await teardown();throw err}},teardown}}var init_channel_scope_helper=__esm({"libs/sdk/src/channel/channel-scope.helper.ts"(){"use strict";init_custom_routes_helper();init_tool_external_loader();init_tool_instance();init_tool_utils();init_channel_notification_service();init_channel_registry();init_list_channels_flow();init_send_channel_notification_flow();init_channel_reply_tool();init_agent_completion_source();init_app_event_source();init_completion_events();init_job_completion_source();init_webhook_source()}});function createEventMetrics(metrics,loadFactory=loadCounterFactory){if(metrics?.enabled!==true)return{count:()=>void 0};const createCounter=loadFactory();return{count:(counter,eventName,by=1)=>{createCounter(EVENT_COUNTERS[counter],COUNTER_DESCRIPTIONS2[counter]).inc(by,{event:eventName})}}}var EVENT_COUNTERS,COUNTER_DESCRIPTIONS2;var init_event_metrics=__esm({"libs/sdk/src/event/delivery/event-metrics.ts"(){"use strict";init_answer_meter();EVENT_COUNTERS={published:"frontmcp_events_published_total",matched:"frontmcp_events_matched_total",delivered:"frontmcp_events_delivered_total",retried:"frontmcp_events_retried_total",abandoned:"frontmcp_events_abandoned_total",dropped:"frontmcp_events_dropped_total",suspended:"frontmcp_events_suspended_total",terminated:"frontmcp_events_terminated_total",notified:"frontmcp_events_channel_notified_total"};COUNTER_DESCRIPTIONS2={published:"Events published",matched:"Deliveries queued for the subscriptions an event matched",delivered:"Deliveries a callback acknowledged with 2xx",retried:"Delivery attempts that failed and are retried",abandoned:"Deliveries given up after the last attempt or the retry window",dropped:"Deliveries not retried: the callback answered 410 or 413, the body was too large, or the subscription is gone",suspended:"Subscriptions suspended after repeated delivery failures",terminated:"Subscriptions the server ended",notified:"Channel notifications sent to Claude Code sessions for events with the channel option"}}});import{getMachineId as getMachineId5,getRuntimeContext as getRuntimeContext24,randomUUID as randomUUID28}from"@frontmcp/utils";function reasonOf(outcome){if(outcome.result==="failed")return outcome.category;return outcome.result==="waiting"?"the subscription is suspended":"the attempt could not be made"}var RECORD_PREFIX2,OUTBOX_SWEEP_INTERVAL_MS,LEASE_MARGIN_MS,SUSPENDED_RECHECK_MS,EventOutbox;var init_event_outbox=__esm({"libs/sdk/src/event/delivery/event-outbox.ts"(){"use strict";init_elicitation_encryption();RECORD_PREFIX2="outbox:";OUTBOX_SWEEP_INTERVAL_MS=3e4;LEASE_MARGIN_MS=3e4;SUSPENDED_RECHECK_MS=3e4;EventOutbox=class{constructor(options){this.options=options;this.ownerId=`${getMachineId5()}:${randomUUID28()}`;this.logger=options.logger.child("EventOutbox");this.random=options.random??Math.random;const{runtime,deployment}=getRuntimeContext24();this.usesTimers=deployment!=="serverless"&&runtime!=="edge"&&runtime!=="browser"}options;ownerId;logger;random;usesTimers;timers=new Map;inFlight=new Map;waitingForSlot=[];activeAttempts=0;sweepTimer;lastSweepAt=0;stopped=false;async enqueue(delivery){const now=Date.now();const record={...delivery,id:`dlv_${randomUUID28()}`,attempt:0,nextAttemptAt:now,firstAttemptAt:now,leaseOwner:this.ownerId,leaseUntil:this.leaseEnd(now)};await this.options.storage.set(RECORD_PREFIX2+record.id,await this.encode(record));if(this.usesTimers){this.schedule(record.id,0)}else{await this.run(record.id)}return record.id}async isPending(deliveryId){return this.options.storage.exists(RECORD_PREFIX2+deliveryId)}start(){if(!this.usesTimers||!this.options.durable)return;this.sweepInBackground();this.sweepTimer=setInterval(()=>this.sweepInBackground(),OUTBOX_SWEEP_INTERVAL_MS);this.sweepTimer.unref?.()}async sweepIfDue(now=Date.now()){if(now-this.lastSweepAt<OUTBOX_SWEEP_INTERVAL_MS)return;await this.sweep(now)}async sweep(now=Date.now()){this.lastSweepAt=now;if(!this.options.durable&&this.usesTimers)return;const keys=await this.options.storage.keys(`${RECORD_PREFIX2}*`);const dueAttempts=[];for(const key of keys){const id=key.slice(RECORD_PREFIX2.length);if(this.timers.has(id)||this.inFlight.has(id))continue;const claimed=await this.claim(id,now);if(!claimed)continue;if(this.usesTimers){this.schedule(id,Math.max(0,claimed.nextAttemptAt-now))}else if(claimed.nextAttemptAt<=now){dueAttempts.push(this.run(id))}}await Promise.all(dueAttempts)}async depth(){return this.options.storage.count(`${RECORD_PREFIX2}*`)}async stop(){this.stopped=true;if(this.sweepTimer)clearInterval(this.sweepTimer);this.sweepTimer=void 0;for(const timer of this.timers.values())clearTimeout(timer);this.timers.clear();await Promise.allSettled([...this.inFlight.values()]);await this.releaseLeases().catch(error=>this.logger.warn("The outbox leases were not released",error))}async releaseLeases(){if(!this.options.durable)return;const keys=await this.options.storage.keys(`${RECORD_PREFIX2}*`);for(const key of keys){const stored=await this.read(key.slice(RECORD_PREFIX2.length));if(stored?.record.leaseOwner!==this.ownerId)continue;await this.replace(stored,{...stored.record,leaseUntil:0})}}schedule(id,delayMs){if(this.stopped||this.timers.has(id))return;const timer=setTimeout(()=>{this.timers.delete(id);void this.run(id)},delayMs);timer.unref?.();this.timers.set(id,timer)}run(id){const running=this.inFlight.get(id);if(running)return running;const attempt=this.attemptWithinLimit(id).catch(error=>this.logger.warn(`Delivery ${id} could not be attempted`,error)).finally(()=>this.inFlight.delete(id));this.inFlight.set(id,attempt);return attempt}async attemptWithinLimit(id){if(this.activeAttempts>=this.options.settings.concurrency){await new Promise(resolve4=>this.waitingForSlot.push(resolve4))}else{this.activeAttempts+=1}try{await this.attemptOnce(id)}finally{const nextWaiter=this.waitingForSlot.shift();if(nextWaiter)nextWaiter();else this.activeAttempts-=1}}async attemptOnce(id){const stored=await this.read(id);if(!stored||stored.record.leaseOwner!==this.ownerId)return;const startedAt=Date.now();const held=await this.replace(stored,{...stored.record,leaseUntil:this.leaseEnd(startedAt)});if(!held)return;const outcome=await this.outcomeOf(held.record);if(outcome.result==="delivered"||outcome.result==="dropped"){await this.options.storage.delete(RECORD_PREFIX2+id);this.options.metrics.count(outcome.result,held.record.eventName);return}await this.retryOrAbandon(held,outcome)}async outcomeOf(record){try{return await this.options.attempt(record)}catch(error){this.logger.warn(`The attempt of delivery ${record.id} threw`,error);return{result:"error"}}}async retryOrAbandon(held,outcome){const{settings,metrics,storage}=this.options;const{record}=held;const now=Date.now();const isWaiting=outcome.result==="waiting";const attemptsMade=isWaiting?record.attempt:record.attempt+1;const windowIsOver=now-record.firstAttemptAt>=settings.retryWindowMs;if(attemptsMade>=settings.maxAttempts||windowIsOver){await storage.delete(RECORD_PREFIX2+record.id);metrics.count("abandoned",record.eventName);this.logger.warn(`Delivery ${record.id} of event "${record.eventName}" to subscription ${record.subscriptionId} is abandoned after ${attemptsMade} attempt(s): ${reasonOf(outcome)}`);return}const waitMs=isWaiting?SUSPENDED_RECHECK_MS:this.backoffMs(attemptsMade);const nextAttemptAt=now+waitMs;const next={...record,attempt:attemptsMade,nextAttemptAt,leaseUntil:this.leaseEnd(nextAttemptAt)};if(!await this.replace(held,next))return;if(!isWaiting)metrics.count("retried",record.eventName);if(this.usesTimers)this.schedule(record.id,waitMs)}backoffMs(attemptsMade){const{backoffMs,maxBackoffMs}=this.options.settings;const exponential=Math.min(maxBackoffMs,backoffMs*2**(attemptsMade-1));return Math.round(exponential*(.5+this.random()*.5))}leaseEnd(attemptAt){return attemptAt+this.options.settings.timeoutMs+LEASE_MARGIN_MS}async claim(id,now){const stored=await this.read(id);if(!stored)return void 0;if(stored.record.leaseOwner===this.ownerId)return stored.record;if(stored.record.leaseUntil>now)return void 0;const claimed={...stored.record,leaseOwner:this.ownerId,leaseUntil:this.leaseEnd(now)};return(await this.replace(stored,claimed))?.record}async replace(stored,next){const raw=await this.encode(next);const replaced=await this.options.storage.setIfEquals(RECORD_PREFIX2+next.id,stored.raw,raw);return replaced?{raw,record:next}:void 0}async read(id){const raw=await this.options.storage.get(RECORD_PREFIX2+id);if(raw===null)return void 0;const record=await this.decode(raw,id);return record?{raw,record}:void 0}async encode(record){const{secret}=this.options;if(secret===void 0)return JSON.stringify(record);return encryptAndSerialize(record,`events-outbox:${record.id}`,secret)}async decode(raw,id){const{secret}=this.options;try{const record=secret===void 0?JSON.parse(raw):await deserializeAndDecrypt(raw,`events-outbox:${id}`,secret);return record?.id===id?record:void 0}catch{return void 0}}sweepInBackground(){this.sweep().catch(error=>this.logger.warn("The outbox sweep failed",error))}}}});import{base64urlEncode as base64urlEncode6,randomBytes as randomBytes7}from"@frontmcp/utils";function newEventId(){return`evt_${base64urlEncode6(randomBytes7(EVENT_ID_RANDOM_BYTES))}`}function eventNameOf(event){return typeof event==="string"?event:normalizeEvent(event).metadata.name}function timestampOf(eventName,timestamp){const time=timestamp===void 0?new Date:new Date(timestamp);if(Number.isNaN(time.getTime())){throw new InvalidEventPublishError(eventName,`"${String(timestamp)}" is not a timestamp`)}return time.toISOString()}var EVENT_ID_RANDOM_BYTES,ScopeEventPublisher;var init_event_publisher=__esm({"libs/sdk/src/event/event-publisher.ts"(){"use strict";init_errors();init_event_utils();EVENT_ID_RANDOM_BYTES=18;ScopeEventPublisher=class{constructor(scope,events){this.scope=scope;this.events=events}scope;events;async publish(event,data,options={}){const eventName=eventNameOf(event);const entry=this.events.findByName(eventName);if(!entry)throw new EventNotRegisteredError(eventName);let payload;try{payload=entry.parsePayload(data)}catch(error){const problem2=error instanceof Error?error.message:String(error);throw new InvalidEventPublishError(eventName,`its data does not match payloadSchema: ${problem2}`)}const occurrence={eventId:options.eventId??newEventId(),name:eventName,timestamp:timestampOf(eventName,options.timestamp),data:payload};return this.scope.runFlowForOutput("events:publish",{occurrence,subscriptionId:options.subscriptionId,audience:options.audience})}}}});function isAuthorizeRefusal(error){return isPublicError(error)}function subscriberAuthInfo(subscriber){const user={...subscriber.claims,sub:subscriber.sub,...subscriber.iss&&{iss:subscriber.iss}};return{clientId:subscriber.sub,scopes:subscriber.scopes,extra:{user}}}async function checkAuthorities(args){const engine=args.scope.authoritiesEngine;const contextBuilder=args.scope.authoritiesContextBuilder;const authorities=args.event.getAuthorities();if(!engine||!contextBuilder||!authorities)return{outcome:"granted"};const evaluationContext=contextBuilder.build({},args.arguments);const ownerContext={...evaluationContext,user:{...evaluationContext.user,...args.subscriber}};try{const result=await engine.evaluate(authorities,ownerContext);return result.granted?{outcome:"granted"}:{outcome:"refused",reason:result.deniedBy??"policy denied"}}catch(error){return{outcome:"failed",error}}}async function checkAuthorize(args){const context=args.event.create(args.authInfo??subscriberAuthInfo(args.subscriber));if(!context.authorize)return{outcome:"granted"};try{await context.authorize(args.arguments,args.subscriber);return{outcome:"granted"}}catch(error){if(!isAuthorizeRefusal(error))return{outcome:"failed",error};return{outcome:"refused",reason:error.message}}}async function reauthorizeSubscriber(args){const byAuthorities=await checkAuthorities(args);if(byAuthorities.outcome!=="granted")return byAuthorities;return checkAuthorize(args)}function hasReauthorization(scope,event,hasAuthorize){return hasAuthorize||Boolean(scope.authoritiesEngine&&scope.authoritiesContextBuilder&&event.getAuthorities())}var init_event_reauthorization=__esm({"libs/sdk/src/event/event-reauthorization.ts"(){"use strict";init_errors()}});var FunctionEventContext,EventInstance;var init_event_instance=__esm({"libs/sdk/src/event/event.instance.ts"(){"use strict";init_common();FunctionEventContext=class extends EventContext{};EventInstance=class extends EventEntry{entryProviders;constructor(record,providers,owner){super(record);this.owner=owner;this.entryProviders=providers;this.name=record.metadata.name;this.fullName=`${owner.id}:${this.name}`;this.ready=this.initialize()}get providers(){return this.entryProviders}async initialize(){}create(authInfo){const contextArgs={metadata:this.metadata,providers:this.entryProviders,logger:this.entryProviders.get(FrontMcpLogger),authInfo};if(this.record.kind==="CLASS_TOKEN"){return new this.record.provide(contextArgs)}const context=new FunctionEventContext(contextArgs);return Object.assign(context,this.record.provide())}}}});import{EVENT_DELIVERY_MODES as EVENT_DELIVERY_MODES2,EVENTS_EXTENSION_ID}from"@frontmcp/protocol";import{getRuntimeContext as getRuntimeContext25,isEntryAvailable as isEntryAvailable8}from"@frontmcp/utils";var EventRegistry;var init_event_registry=__esm({"libs/sdk/src/event/event.registry.ts"(){"use strict";init_common();init_errors();init_regsitry();init_event_instance();init_event_utils();EventRegistry=class extends RegistryAbstract{owner;config;subscriptions;publisher;outbox;metrics;storage;publishEndpoint;buffer;pollLeases;streams;replays;channelDelivery=true;withoutWebhook=new Set;eventsByName=new Map;enabledDeliveryModes=new Set;logger;entryProviders;constructor(providers,list,owner,config,entryProviders){super("EventRegistry",providers,list,false);this.owner=owner;this.config=config;this.entryProviders=entryProviders;this.logger=providers.get(FrontMcpLogger).child("EventRegistry");this.buildGraph();this.ready=this.initialize()}buildMap(list){const tokens=new Set;const defs=new Map;const graph=new Map;for(const item of list){const record=normalizeEvent(item);tokens.add(record.provide);defs.set(record.provide,record);graph.set(record.provide,new Set)}return{tokens,defs,graph}}buildGraph(){}async initialize(){const runtimeContext=getRuntimeContext25();for(const[token,record]of this.defs){const eventName=record.metadata.name;if(!isEntryAvailable8(record.metadata.availableWhen,runtimeContext)){this.logger.verbose(`Event "${eventName}" is not available in this runtime; skipped`);continue}if(this.eventsByName.has(eventName)){throw new EventNameConflictError(eventName)}const instance=new EventInstance(record,this.entryProviders.get(token)??this.providers,this.owner);await instance.ready;this.instances.set(token,instance);this.eventsByName.set(eventName,instance)}}getEvents(){return[...this.eventsByName.values()]}findByName(name59){return this.eventsByName.get(name59)}hasAny(){return this.eventsByName.size>0}enableDeliveryMode(mode){this.enabledDeliveryModes.add(mode)}withholdWebhookFrom(eventName){this.withoutWebhook.add(eventName)}performs(mode){return this.enabledDeliveryModes.has(mode)}deliveryModesOf(event){const restriction=event.metadata.delivery;return EVENT_DELIVERY_MODES2.filter(mode=>this.enabledDeliveryModes.has(mode)&&(!restriction||restriction.includes(mode))&&!(mode==="webhook"&&this.withoutWebhook.has(event.name)))}getServedEvents(){return this.getEvents().map(event=>({event,delivery:this.deliveryModesOf(event)})).filter(({delivery})=>delivery.length>0)}servesEvents(){return this.getServedEvents().length>0}sendsToChannelSessions(event){return this.channelDelivery&&event.metadata.channel!==void 0}getChannelEvents(){return this.getEvents().filter(event=>this.sendsToChannelSessions(event))}getCapabilities(){if(!this.servesEvents())return{};return{events:{},extensions:{[EVENTS_EXTENSION_ID]:{}}}}}}});import{isEdgeRuntime}from"@frontmcp/utils";function eventOutboundTargetOptions(allowLocal){return isEdgeRuntime()?{allowLocal,allowPlatformDns:true}:{allowLocal}}var init_event_outbound=__esm({"libs/sdk/src/event/event-outbound.ts"(){"use strict"}});import{internalZ as z128}from"@frontmcp/lazy-zod";import{EventDeliveryErrorCategorySchema,MCP_SUBSCRIPTION_ID_HEADER as MCP_SUBSCRIPTION_ID_HEADER2}from"@frontmcp/protocol";import{outboundFailureCategory,sendOutboundRequest,signingKeyOf as signingKeyOf2,webhookSignatureHeaders}from"@frontmcp/utils";var inputSchema32,outputSchema31,stateSchema34,plan39,name39,Stage39,SUSPEND_AFTER_FAILURES,GONE,PAYLOAD_TOO_LARGE,EventDeliverFlow;var init_event_deliver_flow=__esm({"libs/sdk/src/event/flows/event-deliver.flow.ts"(){"use strict";init_common();init_event_outbound();inputSchema32=z128.object({delivery:z128.any()});outputSchema31=z128.discriminatedUnion("result",[z128.object({result:z128.literal("delivered")}),z128.object({result:z128.literal("dropped"),reason:z128.enum(["gone","refused"])}),z128.object({result:z128.literal("failed"),category:EventDeliveryErrorCategorySchema}),z128.object({result:z128.literal("waiting")})]);stateSchema34=z128.object({target:z128.any(),subscription:z128.any(),headers:z128.record(z128.string(),z128.string()),answer:z128.any(),outcome:z128.any()});plan39={pre:["loadSubscription","buildHeaders"],execute:["send","classify"],post:["buildResult"]};name39="events:deliver";({Stage:Stage39}=FlowHooksOf(name39));SUSPEND_AFTER_FAILURES=20;GONE=410;PAYLOAD_TOO_LARGE=413;EventDeliverFlow=class extends FlowBase{logger=this.scopeLogger.child("EventDeliverFlow");get events(){return this.scope.events}get subscriptions(){return this.events.subscriptions}async loadSubscription(){const{delivery}=this.input;if(delivery.target){this.state.set("target",delivery.target);return}const subscription=await this.subscriptions.store.get(delivery.subscriptionId);if(!subscription){this.state.set("outcome",{result:"dropped",reason:"gone"});return}if(!subscription.active){this.state.set("outcome",{result:"waiting"});return}this.state.set({subscription,target:subscription.delivery})}async buildHeaders(){if(this.state.outcome)return;const{delivery}=this.input;const{secret,previousSecret,previousSecretUntil}=this.state.required.target;const now=Date.now();const signingKeys=[signingKeyOf2(secret)];if(previousSecret!==void 0&&(previousSecretUntil??0)>now){signingKeys.push(signingKeyOf2(previousSecret))}const message={id:delivery.webhookId,timestamp:Math.floor(now/1e3),body:delivery.body};this.state.set("headers",{"content-type":"application/json",[MCP_SUBSCRIPTION_ID_HEADER2]:delivery.subscriptionId,...webhookSignatureHeaders(message,signingKeys)})}async send(){if(this.state.outcome)return;const{webhook}=this.events.config;const answer=await sendOutboundRequest({url:this.state.required.target.url,method:"POST",headers:this.state.required.headers,body:this.input.delivery.body,timeoutMs:webhook.delivery.timeoutMs,...eventOutboundTargetOptions(webhook.unsafeAllowLocalCallbacks)});this.state.set("answer",answer)}async classify(){if(this.state.outcome)return;const{answer}=this.state.required;const category=outboundFailureCategory(answer);if(!category){await this.recordStatus(()=>({status:{lastDeliveryAt:Date.now()}}));this.state.set("outcome",{result:"delivered"});return}if(answer.answered&&(answer.status===GONE||answer.status===PAYLOAD_TOO_LARGE)){await this.recordStatus(status=>({status:{...status,lastError:category}}));this.state.set("outcome",{result:"dropped",reason:"refused"});return}await this.recordFailure(category);this.state.set("outcome",{result:"failed",category})}async buildResult(){this.respond(this.state.required.outcome)}async recordFailure(category){const now=Date.now();const updated=await this.recordStatus((status,active)=>{const failures=(status.failures??0)+1;const failing={...status,lastError:category,failedSince:status.failedSince??now,failures};const suspendsNow=active&&failures>=SUSPEND_AFTER_FAILURES;return suspendsNow?{active:false,status:{...failing,suspendedSince:now}}:{status:failing}});if(updated&&!updated.active&&updated.status.suspendedSince===now){this.events.metrics?.count("suspended",updated.eventName);this.logger.warn(`Subscription ${updated.id} to event "${updated.eventName}" is suspended after ${SUSPEND_AFTER_FAILURES} failed deliveries in a row (${category}). Its next events/subscribe reactivates it.`)}}async recordStatus(change){const{subscription}=this.state;if(!subscription)return void 0;return this.subscriptions.store.update(subscription.id,current=>change(current.status,current.active))}};__decorateClass([Stage39("loadSubscription")],EventDeliverFlow.prototype,"loadSubscription",1);__decorateClass([Stage39("buildHeaders")],EventDeliverFlow.prototype,"buildHeaders",1);__decorateClass([Stage39("send")],EventDeliverFlow.prototype,"send",1);__decorateClass([Stage39("classify")],EventDeliverFlow.prototype,"classify",1);__decorateClass([Stage39("buildResult")],EventDeliverFlow.prototype,"buildResult",1);EventDeliverFlow=__decorateClass([FrontMcpFlow({name:name39,plan:plan39,inputSchema:inputSchema32,outputSchema:outputSchema31,access:"public"})],EventDeliverFlow)}});import{EVENTS_ERROR_CODES as EVENTS_ERROR_CODES2,EVENTS_SKETCH_ERROR_CODES as EVENTS_SKETCH_ERROR_CODES2}from"@frontmcp/protocol";function knownPlatform(platform){return platform&&platform!=="unknown"?platform:void 0}function callerPlatformOf(scope,authInfo,requestPlatform){const detected=knownPlatform(authInfo.sessionIdPayload?.platformType)??knownPlatform(requestPlatform);if(detected)return detected;return authInfo.sessionId?scope.notifications.getPlatformType(authInfo.sessionId):"unknown"}function resolveEventDialect(compat,platform){if(compat!=="auto")return compat;return platform==="openai"?"sketch":"sep-3415"}var EVENT_DIALECTS;var init_event_dialect=__esm({"libs/sdk/src/event/event-dialect.ts"(){"use strict";EVENT_DIALECTS={"sep-3415":{errorCodes:EVENTS_ERROR_CODES2,webhookId:"message",sendsControlEnvelopes:true},sketch:{errorCodes:EVENTS_SKETCH_ERROR_CODES2,webhookId:"eventId",sendsControlEnvelopes:false}}}});function stringClaim(claims3,name59){const value=claims3[name59];return typeof value==="string"&&value!==""?value:void 0}function eventSubscriberOf(authInfo,contextBuilder){const principalKey=principalKeyOf(authInfo);if(!principalKey)return void 0;const plainAuthInfo=authInfo;const tokenPrincipal=resolvePrincipal(plainAuthInfo);const principal=contextBuilder?resolvePrincipal(plainAuthInfo,contextBuilder):tokenPrincipal;const tenantId=contextBuilder?.build(plainAuthInfo).user.tenantId;const issuer=stringClaim(tokenPrincipal.claims,"iss");return{principalKey,subscriber:{sub:principal.sub||tokenPrincipal.sub,...issuer&&{iss:issuer},...tenantId&&{tenantId},roles:principal.roles,permissions:principal.permissions,scopes:principal.scopes,claims:principal.claims}}}var init_event_subscriber=__esm({"libs/sdk/src/event/event-subscriber.ts"(){"use strict";init_principal_utils();init_question_subject()}});import{isPublicMode as isPublicMode2}from"@frontmcp/auth";import{internalZ as z129}from"@frontmcp/lazy-zod";import{canonicalJson as canonicalJson3,sha256Hex as sha256Hex23}from"@frontmcp/utils";function offeredEventOf(events,eventName,mode,requestContext,codes){const event=events.findByName(eventName);if(!event||!isOfferedOnSurface(event.metadata.availableWhen,callSurfaceOf(requestContext))){throw new EventNotFoundError(codes,"event",eventName)}const offeredModes=events.deliveryModesOf(event);if(!offeredModes.includes(mode))throw new EventUnsupportedError(codes,"deliveryMode",mode,offeredModes);return event}function eventReaderOf(scope,authInfo,eventName,codes){const owner=eventSubscriberOf(authInfo,scope.authoritiesContextBuilder);if(owner)return owner;const authOptions=scope.auth?.options;if(authOptions!==void 0&&!isPublicMode2(authOptions)){throw new EventForbiddenError(codes,eventName,"this server needs a signed-in caller")}return{principalKey:void 0,subscriber:ANONYMOUS_SUBSCRIBER}}async function assertEventAuthorities(scope,event,authInfo,args,codes){const engine=scope.authoritiesEngine;const contextBuilder=scope.authoritiesContextBuilder;const authorities=event.getAuthorities();if(!engine||!contextBuilder||!authorities)return;const result=await engine.evaluate(authorities,contextBuilder.build(authInfo,args));if(!result.granted)throw new EventForbiddenError(codes,event.name,result.deniedBy??"policy denied")}function parsedEventArguments(event,args){try{return event.parseArguments(args??{})}catch(error){throw new InvalidInputError("Invalid subscription arguments",error instanceof z129.ZodError?error.issues:void 0)}}async function assertEventAuthorizes(context,eventName,args,subscriber,codes){try{await context.authorize?.(args,subscriber)}catch(error){if(error instanceof EventProtocolError)throw error;const reason=isPublicError(error)?error.getPublicMessage():"the event refused it";throw new EventForbiddenError(codes,eventName,reason)}}function readerSubscriptionOf(reader,mode,eventName,args){const key=canonicalJson3({principalKey:reader.principalKey??null,mode,name:eventName,arguments:args});return{id:`sub_${sha256Hex23(key).slice(0,32)}`,name:eventName,mode,subscriber:reader.subscriber}}var ANONYMOUS_SUBSCRIBER;var init_event_gates=__esm({"libs/sdk/src/event/event-gates.ts"(){"use strict";init_availability();init_errors();init_event_subscriber();ANONYMOUS_SUBSCRIBER={sub:"",roles:[],permissions:[],scopes:[],claims:{}}}});import{getRuntimeContext as getRuntimeContext26}from"@frontmcp/utils";function pollLeaseMs(nextPollMs){return Math.max(POLL_LEASE_MIN_MS,POLL_LEASE_INTERVALS*nextPollMs)}var POLL_LEASE_MIN_MS,POLL_LEASE_INTERVALS,POLL_LEASE_SWEEP_INTERVAL_MS,MAX_POLL_LEASES,EventPollLeases;var init_event_poll_leases=__esm({"libs/sdk/src/event/poll/event-poll-leases.ts"(){"use strict";POLL_LEASE_MIN_MS=3e5;POLL_LEASE_INTERVALS=5;POLL_LEASE_SWEEP_INTERVAL_MS=6e4;MAX_POLL_LEASES=1e4;EventPollLeases=class{constructor(options){this.options=options;this.logger=options.logger.child("EventPollLeases")}options;leases=new Map;starting=new Map;logger;sweepTimer;lastSweepAt=0;get size(){return this.leases.size}isFull(principalKey){if(this.leases.size>=MAX_POLL_LEASES)return true;let held=0;for(const lease of this.leases.values()){if(lease.principalKey===principalKey)held+=1}return held>=this.options.maxPerPrincipal}has(subscriptionId){return this.leases.has(subscriptionId)||this.starting.has(subscriptionId)}async renew(request2){const{subscription,leaseMs}=request2;const now=Date.now();this.sweepIfDue(now);const lease=this.leases.get(subscription.id);if(lease){lease.expiresAt=now+leaseMs;return}const pending=this.starting.get(subscription.id);if(pending)return pending;const start=this.subscribe(request2,now).finally(()=>this.starting.delete(subscription.id));this.starting.set(subscription.id,start);return start}async subscribe(request2,now){const{subscription,context,leaseMs}=request2;await context.onSubscribe?.(request2.arguments,subscription);this.leases.set(subscription.id,{subscription,arguments:request2.arguments,principalKey:request2.principalKey,expiresAt:now+leaseMs,end:async reason=>{await context.onUnsubscribe?.(request2.arguments,subscription,reason)}})}async sweep(now=Date.now()){this.lastSweepAt=now;for(const[subscriptionId,lease]of this.leases){if(lease.expiresAt>now)continue;this.leases.delete(subscriptionId);await this.end(lease,"expired")}}start(){const{runtime,deployment}=getRuntimeContext26();if(deployment==="serverless"||runtime==="edge"||runtime==="browser")return;this.sweepTimer=setInterval(()=>this.sweepInBackground(Date.now()),POLL_LEASE_SWEEP_INTERVAL_MS);this.sweepTimer.unref?.()}stop(){if(this.sweepTimer)clearInterval(this.sweepTimer);this.sweepTimer=void 0;this.leases.clear()}sweepIfDue(now){if(now-this.lastSweepAt<POLL_LEASE_SWEEP_INTERVAL_MS)return;this.sweepInBackground(now)}sweepInBackground(now){this.sweep(now).catch(error=>this.logger.warn("The poll lease sweep failed",error))}async end(lease,reason){try{await lease.end(reason)}catch(error){const{id,name:name59}=lease.subscription;this.logger.warn(`onUnsubscribe of event "${name59}" failed for poll subscription ${id}`,error)}}}}});function eventChannelMessage(event,occurrence){const{channel:channel2}=event.metadata;const options=channel2===void 0||channel2===true?{}:channel2;const payload=occurrence.data;const content=options.content?options.content(payload):JSON.stringify(payload);const ownMeta=options.meta?options.meta(payload):{};return{content,meta:channelMetaOf({...ownMeta,event:occurrence.name,event_id:occurrence.eventId})}}function channelSessionReader(scope,event,session){if(hasExpiredCaller(session))return void 0;if(!isOfferedOnSurface(event.metadata.availableWhen,mcpRequestSurface(scope)))return void 0;try{return eventReaderOf(scope,session.caller??{},event.name,EVENT_DIALECTS["sep-3415"].errorCodes)}catch(error){if(error instanceof EventForbiddenError)return void 0;throw error}}var init_event_channel=__esm({"libs/sdk/src/event/event-channel.ts"(){"use strict";init_channel_utils();init_availability();init_errors();init_notification_service();init_mcp_surface();init_event_dialect();init_event_gates()}});import{generateWebhookMessageId}from"@frontmcp/utils";function accessRevokedError(dialect){return{code:EVENT_DIALECTS[dialect].errorCodes.forbidden,message:"Forbidden",data:{reason:"Access revoked"}}}async function terminateEventSubscription(args){const{subscriptions,outbox,metrics,logger,subscription,error}=args;const removed=await subscriptions?.store.delete(subscription.id);if(!removed||!subscriptions||!outbox)return;await subscriptions.notifyUnsubscribed(removed,"terminated");metrics?.count("terminated",removed.eventName);logger.warn(`Subscription ${removed.id} to event "${removed.eventName}" is terminated: ${error.message} (${String(error.data["reason"])})`);if(!EVENT_DIALECTS[removed.dialect].sendsControlEnvelopes)return;const{url,secret,previousSecret,previousSecretUntil}=removed.delivery;await outbox.enqueue({kind:"terminated",subscriptionId:removed.id,eventName:removed.eventName,body:JSON.stringify({type:"terminated",error}),webhookId:generateWebhookMessageId("terminated"),target:{url,secret,previousSecret,previousSecretUntil}})}var init_event_subscription_termination=__esm({"libs/sdk/src/event/subscription/event-subscription-termination.ts"(){"use strict";init_event_dialect()}});import{internalZ as z130}from"@frontmcp/lazy-zod";import{EventOccurrenceSchema as EventOccurrenceSchema3}from"@frontmcp/protocol";import{sha256Hex as sha256Hex24}from"@frontmcp/utils";function eventWebhookIdOf(subscriptionId,eventId){return`msg_${sha256Hex24(`${subscriptionId}\0${eventId}`).slice(0,32)}`}function isNamed(wanted,actual){if(wanted===void 0)return true;if(actual===void 0)return false;return Array.isArray(wanted)?wanted.includes(actual):wanted===actual}function isInAudience(audience,subscriber){if(!audience)return true;const{any:anyOf,all:allOf}=audience.roles??{};const hasOneOf=!anyOf||anyOf.some(role=>subscriber.roles.includes(role));const hasEveryOf=!allOf||allOf.every(role=>subscriber.roles.includes(role));return isNamed(audience.sub,subscriber.sub)&&isNamed(audience.tenantId,subscriber.tenantId)&&hasOneOf&&hasEveryOf}var EVENT_DELIVERY_MAX_BYTES,audienceValueSchema,inputSchema33,outputSchema32,stateSchema35,plan40,name40,Stage40,encoder9,EventPublishFlow;var init_event_publish_flow=__esm({"libs/sdk/src/event/flows/event-publish.flow.ts"(){"use strict";init_channel_utils();init_common();init_errors();init_event_channel();init_event_dialect();init_event_reauthorization();init_event_subscription_termination();EVENT_DELIVERY_MAX_BYTES=262144;audienceValueSchema=z130.union([z130.string(),z130.array(z130.string())]);inputSchema33=z130.object({occurrence:EventOccurrenceSchema3,subscriptionId:z130.string().optional(),audience:z130.object({sub:audienceValueSchema.optional(),tenantId:audienceValueSchema.optional(),roles:z130.object({any:z130.array(z130.string()).optional(),all:z130.array(z130.string()).optional()}).optional()}).optional()});outputSchema32=z130.object({eventId:z130.string(),matched:z130.number().int().nonnegative()});stateSchema35=z130.object({event:z130.instanceof(EventEntry),context:z130.any(),subscriptions:z130.array(z130.any()),deliveries:z130.array(z130.any()),buffered:z130.any()});plan40={pre:["validate","bufferOccurrence","pushToStreams"],execute:["loadSubscriptions","dropInactive","filterByAudience","reauthorize","match","transform","enforceBodyLimit","enqueue","bridgeToBus","notifyChannelSessions"],post:["buildResult"]};name40="events:publish";({Stage:Stage40}=FlowHooksOf(name40));encoder9=new TextEncoder;EventPublishFlow=class extends FlowBase{logger=this.scopeLogger.child("EventPublishFlow");get events(){return this.scope.events}async validate(){const eventName=this.input.occurrence.name;const event=this.events.findByName(eventName);if(!event)throw new EventNotRegisteredError(eventName);this.events.metrics?.count("published",eventName);this.state.set({event,context:event.create({}),deliveries:[]})}async bufferOccurrence(){const{occurrence,audience,subscriptionId}=this.input;const modes=this.events.deliveryModesOf(this.state.required.event);if(!modes.includes("poll")&&!modes.includes("push"))return;this.state.set("buffered",this.events.buffer?.append(occurrence,audience,subscriptionId))}async pushToStreams(){const{buffered}=this.state;if(buffered)await this.events.streams?.publish(buffered)}async loadSubscriptions(){const{subscriptions,outbox}=this.events;if(!subscriptions||!outbox){this.state.set("subscriptions",[]);return}subscriptions.sweepIfDue();await outbox.sweepIfDue();const{subscriptionId,occurrence}=this.input;if(subscriptionId===void 0){this.state.set("subscriptions",await subscriptions.store.listByEvent(occurrence.name));return}const targeted=await subscriptions.store.get(subscriptionId);this.state.set("subscriptions",targeted?.eventName===occurrence.name?[targeted]:[])}async dropInactive(){const{suspendedTtlMs}=this.events.config.subscriptions;const now=Date.now();const active=[];for(const subscription of this.state.required.subscriptions){if(subscription.active){active.push(subscription);continue}const suspendedFor=now-(subscription.status.suspendedSince??now);if(subscription.expiresAt===null&&suspendedFor>suspendedTtlMs){const codes=EVENT_DIALECTS[subscription.dialect].errorCodes;await this.terminate(subscription,{code:codes.callbackEndpointError,message:"CallbackEndpointError",data:{reason:subscription.status.lastError??"http_5xx"}})}}this.state.set("subscriptions",active)}async filterByAudience(){const{audience}=this.input;const inAudience=this.state.required.subscriptions.filter(subscription=>isInAudience(audience,subscription.subscriber));this.state.set("subscriptions",inAudience)}async reauthorize(){const{event,context}=this.state.required;if(!hasReauthorization(this.scope,event,context.authorize!==void 0))return;const{subscriptions}=this.events;const{reauthorizeEveryMs}=this.events.config.subscriptions;const now=Date.now();const allowed=[];for(const subscription of this.state.required.subscriptions){if(now-subscription.lastAuthorizedAt<=reauthorizeEveryMs){allowed.push(subscription);continue}const{subscriber,arguments:subscriptionArguments}=subscription;const check=await reauthorizeSubscriber({scope:this.scope,event,subscriber,arguments:subscriptionArguments});if(check.outcome==="granted"){await subscriptions?.store.update(subscription.id,{lastAuthorizedAt:now});allowed.push(subscription);continue}if(check.outcome==="failed"){this.logger.warn(`reauthorize: the access of subscription ${subscription.id} could not be checked`,check.error);continue}await this.terminate(subscription,accessRevokedError(subscription.dialect))}this.state.set("subscriptions",allowed)}async match(){const{context,subscriptions}=this.state.required;const{occurrence}=this.input;const deliveries=[];for(const subscription of subscriptions){try{const matches=await context.match?.(occurrence,subscription.arguments,subscription.subscriber)??true;if(matches)deliveries.push({subscription,occurrence})}catch(error){this.logger.warn(`match: event "${occurrence.name}" failed for subscription ${subscription.id}`,error)}}this.state.set("deliveries",deliveries)}async transform(){const{context,deliveries}=this.state.required;if(!context.transform)return;const shaped=[];for(const delivery of deliveries){const{subscription,occurrence}=delivery;try{const transformed=await context.transform(occurrence,subscription.arguments,subscription.subscriber);shaped.push({subscription,occurrence:EventOccurrenceSchema3.parse(transformed)})}catch(error){this.logger.warn(`transform: event "${occurrence.name}" failed for subscription ${subscription.id}`,error)}}this.state.set("deliveries",shaped)}async enforceBodyLimit(){const fitting=[];for(const delivery of this.state.required.deliveries){const body=JSON.stringify(delivery.occurrence);const bytes=encoder9.encode(body).byteLength;if(bytes<=EVENT_DELIVERY_MAX_BYTES){fitting.push({...delivery,body});continue}this.events.metrics?.count("dropped",delivery.occurrence.name);this.logger.warn(`enforceBodyLimit: event "${delivery.occurrence.name}" is ${bytes} bytes for subscription ${delivery.subscription.id}, over the ${EVENT_DELIVERY_MAX_BYTES} byte limit; it is not delivered`)}this.state.set("deliveries",fitting)}async enqueue(){const{outbox}=this.events;const{deliveries}=this.state.required;if(!outbox)return;const queued=deliveries.map(({subscription,occurrence,body})=>{const usesEventId=EVENT_DIALECTS[subscription.dialect].webhookId==="eventId";return outbox.enqueue({kind:"event",subscriptionId:subscription.id,eventName:occurrence.name,body,webhookId:usesEventId?occurrence.eventId:eventWebhookIdOf(subscription.id,occurrence.eventId)})});await Promise.all(queued);this.events.metrics?.count("matched",this.input.occurrence.name,deliveries.length)}async bridgeToBus(){if(!this.events.config.bridge)return;const{occurrence,audience,subscriptionId}=this.input;const forSomeOwners=audience!==void 0||subscriptionId!==void 0;this.scope.channelEventBus?.emit(occurrence.name,occurrence,{forSomeOwners})}async notifyChannelSessions(){const{event}=this.state.required;const{occurrence,subscriptionId}=this.input;if(subscriptionId!==void 0||!this.events.sendsToChannelSessions(event))return;let message;try{message=eventChannelMessage(event,occurrence)}catch(error){this.logger.warn(`notifyChannelSessions: the channel option of event "${occurrence.name}" failed`,error);return}let notified=0;for(const session of this.scope.notifications.getChannelCapableSessions()){const wasSent=await this.notifyChannelSession(session,message);if(wasSent)notified+=1}this.events.metrics?.count("notified",occurrence.name,notified);this.logger.verbose(`notifyChannelSessions: event "${occurrence.name}" was sent to ${notified} session(s)`)}async buildResult(){this.respond({eventId:this.input.occurrence.eventId,matched:this.state.required.deliveries.length})}async notifyChannelSession(session,message){const{event,context}=this.state.required;const{occurrence,audience}=this.input;try{const reader=channelSessionReader(this.scope,event,session);if(!reader||!isInAudience(audience,reader.subscriber))return false;if(hasReauthorization(this.scope,event,context.authorize!==void 0)){const{subscriber}=reader;const authInfo=session.caller;const access=await reauthorizeSubscriber({scope:this.scope,event,subscriber,arguments:{},authInfo});if(access.outcome==="failed")throw access.error;if(access.outcome==="refused")return false}const isThisSession=registered=>registered.sessionId===session.sessionId;this.scope.notifications.sendCustomNotification(CHANNEL_NOTIFICATION_METHOD,message,isThisSession);return true}catch(error){const sessionLabel=session.sessionId.slice(0,20);this.logger.warn(`notifyChannelSessions: event "${occurrence.name}" was not sent to session ${sessionLabel}...`,error);return false}}async terminate(subscription,error){const{subscriptions,outbox,metrics}=this.events;await terminateEventSubscription({subscriptions,outbox,metrics,logger:this.logger,subscription,error})}};__decorateClass([Stage40("validate")],EventPublishFlow.prototype,"validate",1);__decorateClass([Stage40("bufferOccurrence")],EventPublishFlow.prototype,"bufferOccurrence",1);__decorateClass([Stage40("pushToStreams")],EventPublishFlow.prototype,"pushToStreams",1);__decorateClass([Stage40("loadSubscriptions")],EventPublishFlow.prototype,"loadSubscriptions",1);__decorateClass([Stage40("dropInactive")],EventPublishFlow.prototype,"dropInactive",1);__decorateClass([Stage40("filterByAudience")],EventPublishFlow.prototype,"filterByAudience",1);__decorateClass([Stage40("reauthorize")],EventPublishFlow.prototype,"reauthorize",1);__decorateClass([Stage40("match")],EventPublishFlow.prototype,"match",1);__decorateClass([Stage40("transform")],EventPublishFlow.prototype,"transform",1);__decorateClass([Stage40("enforceBodyLimit")],EventPublishFlow.prototype,"enforceBodyLimit",1);__decorateClass([Stage40("enqueue")],EventPublishFlow.prototype,"enqueue",1);__decorateClass([Stage40("bridgeToBus")],EventPublishFlow.prototype,"bridgeToBus",1);__decorateClass([Stage40("notifyChannelSessions")],EventPublishFlow.prototype,"notifyChannelSessions",1);__decorateClass([Stage40("buildResult")],EventPublishFlow.prototype,"buildResult",1);EventPublishFlow=__decorateClass([FrontMcpFlow({name:name40,plan:plan40,inputSchema:inputSchema33,outputSchema:outputSchema32,access:"public"})],EventPublishFlow)}});import{internalZ as z131}from"@frontmcp/lazy-zod";import{EventOccurrenceSchema as EventOccurrenceSchema4,PollEventsRequestSchema as PollEventsRequestSchema2,PollEventsResultSchema as PollEventsResultSchema2}from"@frontmcp/protocol";var inputSchema34,outputSchema33,stateSchema36,plan41,name41,Stage41,EventPollFlow;var init_event_poll_flow=__esm({"libs/sdk/src/event/flows/event-poll.flow.ts"(){"use strict";init_common();init_errors();init_event_dialect();init_event_gates();init_event_publisher();init_event_poll_leases();init_event_publish_flow();inputSchema34=z131.object({request:PollEventsRequestSchema2,ctx:z131.unknown()});outputSchema33=PollEventsResultSchema2;stateSchema36=z131.object({authInfo:z131.any(),dialect:z131.enum(["sep-3415","sketch"]),event:z131.instanceof(EventEntry),reader:z131.any(),arguments:z131.record(z131.string(),z131.unknown()),context:z131.any(),subscription:z131.any(),result:z131.any()});plan41={pre:["parseInput","resolveDialect","findEvent","resolveReader","checkEntryAuthorities","validateArguments","authorize"],execute:["renewLease","readEvents"],post:["buildResult"],finalize:["finalize"]};name41="events:poll";({Stage:Stage41}=FlowHooksOf(name41));EventPollFlow=class extends FlowBase{logger=this.scopeLogger.child("EventPollFlow");get events(){return this.scope.events}get codes(){return EVENT_DIALECTS[this.state.required.dialect].errorCodes}async parseInput(){const authInfo=this.input.ctx?.authInfo??{};this.state.set("authInfo",authInfo)}async resolveDialect(){const platform=callerPlatformOf(this.scope,this.state.required.authInfo,this.tryGetContext()?.platformType);this.state.set("dialect",resolveEventDialect(this.events.config.compat,platform))}async findEvent(){const eventName=this.input.request.params.name;this.state.set("event",offeredEventOf(this.events,eventName,"poll",this.input.ctx,this.codes))}async resolveReader(){const{authInfo,event}=this.state.required;this.state.set("reader",eventReaderOf(this.scope,authInfo,event.name,this.codes))}async checkEntryAuthorities(){const{event,authInfo}=this.state.required;const sentArguments=this.input.request.params.arguments??{};await assertEventAuthorities(this.scope,event,authInfo,sentArguments,this.codes)}async validateArguments(){const{event,reader}=this.state.required;const parsedArguments=parsedEventArguments(event,this.input.request.params.arguments);this.state.set({arguments:parsedArguments,subscription:readerSubscriptionOf(reader,"poll",event.name,parsedArguments)})}async authorize(){const{event,authInfo,reader}=this.state.required;const context=event.create(authInfo);await assertEventAuthorizes(context,event.name,this.state.required.arguments,reader.subscriber,this.codes);this.state.set("context",context)}async renewLease(){await this.renewLeaseFor(this.events.config.poll.nextPollMs)}async readEvents(){const{context}=this.state.required;const result=context.check?await this.readFromCheck():await this.readFromBuffer();this.state.set("result",result);if(result.nextPollMs!==void 0&&result.nextPollMs>this.events.config.poll.nextPollMs){await this.renewLeaseFor(result.nextPollMs)}}async buildResult(){this.respond(this.state.required.result)}async finalize(){this.logger.verbose("finalize")}get limit(){const serverLimit=this.events.config.poll.maxEvents;return Math.min(this.input.request.params.maxEvents??serverLimit,serverLimit)}replayFloor(now){const{cursor,maxAgeMs}=this.input.request.params;const hasCursor=cursor!==void 0&&cursor!==null;return hasCursor&&maxAgeMs!==void 0?now-maxAgeMs:void 0}async renewLeaseFor(nextPollMs){const leases=this.events.pollLeases;const{context,subscription,reader}=this.state.required;if(!context.onSubscribe&&!context.onUnsubscribe)return;if(!leases.has(subscription.id)&&leases.isFull(reader.principalKey)){const{maxPerPrincipal}=this.events.config.subscriptions;throw new EventResourceExhaustedError(this.codes,"pollLeases",maxPerPrincipal)}await leases.renew({subscription,arguments:this.state.required.arguments,principalKey:reader.principalKey,leaseMs:pollLeaseMs(nextPollMs),context})}async readFromCheck(){const{context,event}=this.state.required;const{cursor=null,maxAgeMs}=this.input.request.params;const now=Date.now();const floor=this.replayFloor(now);const limits={maxEvents:this.limit,...floor!==void 0&&{maxAgeMs}};const check=context.check;const checked=await check.call(context,this.state.required.arguments,cursor,limits);if(checked.events.length>this.limit){throw new InvalidEventPublishError(event.name,`check() returned ${checked.events.length} events, more than limits.maxEvents (${this.limit})`)}const events=[];let skippedOldEvents=false;for(const item of checked.events){const timestamp=item.timestamp??new Date(now).toISOString();if(floor!==void 0&&Date.parse(timestamp)<floor){skippedOldEvents=true;continue}events.push({eventId:item.eventId??newEventId(),name:event.name,timestamp,data:this.checkedPayload(item.data)})}return{events,cursor:checked.cursor,truncated:checked.truncated===true||skippedOldEvents,hasMore:checked.hasMore===true,nextPollMs:checked.nextPollMs??this.events.config.poll.nextPollMs}}checkedPayload(data){const{event}=this.state.required;try{return event.parsePayload(data)}catch(error){const problem2=error instanceof Error?error.message:String(error);throw new InvalidEventPublishError(event.name,`check() returned data that does not match payloadSchema: ${problem2}`)}}async readFromBuffer(){const buffer=this.events.buffer;const{cursor}=this.input.request.params;const nextPollMs=this.events.config.poll.nextPollMs;if(cursor===void 0||cursor===null){return{events:[],cursor:buffer.currentCursor(),truncated:false,hasMore:false,nextPollMs}}const read=buffer.read(this.state.required.event.name,cursor);const endCursor=buffer.currentCursor();const floor=this.replayFloor(Date.now());const events=[];let truncated=read.truncated;let lastExamined;for(const buffered of read.events){if(floor!==void 0&&buffered.publishedAt<floor){truncated=true;lastExamined=buffered;continue}const occurrence=await this.occurrenceFor(buffered);if(occurrence&&events.length===this.limit){const resumeCursor=lastExamined?buffer.cursorAt(lastExamined.sequence):cursor;return{events,cursor:resumeCursor,truncated,hasMore:true,nextPollMs}}if(occurrence)events.push(occurrence);lastExamined=buffered}return{events,cursor:endCursor,truncated,hasMore:false,nextPollMs}}async occurrenceFor(buffered){const{context,reader,subscription}=this.state.required;const{occurrence}=buffered;if(buffered.subscriptionId!==void 0&&buffered.subscriptionId!==subscription.id)return void 0;if(!isInAudience(buffered.audience,reader.subscriber))return void 0;const subscriptionArguments=this.state.required.arguments;try{const matches=await context.match?.(occurrence,subscriptionArguments,reader.subscriber)??true;if(!matches)return void 0;if(!context.transform)return occurrence;const transformed=await context.transform(occurrence,subscriptionArguments,reader.subscriber);return EventOccurrenceSchema4.parse(transformed)}catch(error){this.logger.warn(`readEvents: event "${occurrence.name}" failed for poll subscription ${subscription.id}`,error);return void 0}}};__decorateClass([Stage41("parseInput")],EventPollFlow.prototype,"parseInput",1);__decorateClass([Stage41("resolveDialect")],EventPollFlow.prototype,"resolveDialect",1);__decorateClass([Stage41("findEvent")],EventPollFlow.prototype,"findEvent",1);__decorateClass([Stage41("resolveReader")],EventPollFlow.prototype,"resolveReader",1);__decorateClass([Stage41("checkEntryAuthorities")],EventPollFlow.prototype,"checkEntryAuthorities",1);__decorateClass([Stage41("validateArguments")],EventPollFlow.prototype,"validateArguments",1);__decorateClass([Stage41("authorize")],EventPollFlow.prototype,"authorize",1);__decorateClass([Stage41("renewLease")],EventPollFlow.prototype,"renewLease",1);__decorateClass([Stage41("readEvents")],EventPollFlow.prototype,"readEvents",1);__decorateClass([Stage41("buildResult")],EventPollFlow.prototype,"buildResult",1);__decorateClass([Stage41("finalize")],EventPollFlow.prototype,"finalize",1);EventPollFlow=__decorateClass([FrontMcpFlow({name:name41,plan:plan41,inputSchema:inputSchema34,outputSchema:outputSchema33,access:"authorized"})],EventPollFlow)}});import{EventOccurrenceSchema as EventOccurrenceSchema5,EVENTS_NOTIFICATIONS as EVENTS_NOTIFICATIONS2,MCP_20260728_META as MCP_20260728_META9}from"@frontmcp/protocol";var MAX_QUEUED_NOTIFICATIONS,EventStream;var init_event_stream=__esm({"libs/sdk/src/event/stream/event-stream.ts"(){"use strict";init_event_publisher();init_event_publish_flow();MAX_QUEUED_NOTIFICATIONS=1e3;EventStream=class{constructor(options){this.options=options;this.cursor=options.cursor??null;this.delivering=options.buffer?new Promise(resolve4=>this.releaseDelivery=resolve4):Promise.resolve();if(options.signal?.aborted)this.close();else options.signal?.addEventListener("abort",()=>this.close(),{once:true})}options;queue=[];closeListeners=[];wake;closed=false;cursor;lastAuthorizedAt=Date.now();accessUnchecked=false;withheld=false;heartbeatTimer;checkTimer;delivering;releaseDelivery=()=>void 0;lastSequence=0;get subscription(){return this.options.subscription}get eventName(){return this.options.event.name}get principalKey(){return this.options.reader.principalKey}get isClosed(){return this.closed}async open(){const{context,heartbeatMs}=this.options;if(context.check){await this.openOnCheck()}else{await this.openOnBuffer()}this.releaseDelivery();if(this.closed)return;this.heartbeatTimer=setInterval(()=>void this.beat(),heartbeatMs);this.heartbeatTimer.unref?.()}offer(buffered){this.delivering=this.delivering.then(()=>this.deliver(buffered)).catch(error=>this.options.logger.warn(`An event was not delivered on stream ${this.subscription.id}`,error));return this.delivering}terminate(error){if(this.closed)return;this.push(EVENTS_NOTIFICATIONS2.terminated,{error});this.close()}close(){if(this.closed)return;this.closed=true;this.releaseDelivery();if(this.heartbeatTimer)clearInterval(this.heartbeatTimer);if(this.checkTimer)clearTimeout(this.checkTimer);for(const listener of this.closeListeners.splice(0))listener();this.wake?.()}onClose(listener){if(this.closed)listener();else this.closeListeners.push(listener)}[Symbol.asyncIterator](){return{next:()=>this.nextNotification(),return:async()=>{this.close();return{value:void 0,done:true}}}}async nextNotification(){for(;;){const queued=this.queue.shift();if(queued)return{value:queued,done:false};if(this.closed)return{value:void 0,done:true};await new Promise(resolve4=>this.wake=resolve4);this.wake=void 0}}async openOnBuffer(){const{buffer,cursor,maxAgeMs}=this.options;if(!buffer){this.pushActive(false);return}if(cursor===void 0||cursor===null){this.cursor=buffer.currentCursor();this.lastSequence=buffer.currentSequence();this.pushActive(false);return}const read=buffer.read(this.eventName,cursor);const endCursor=buffer.currentCursor();const endSequence=buffer.currentSequence();const floor=maxAgeMs===void 0?void 0:Date.now()-maxAgeMs;const replayed=read.events.filter(buffered=>floor===void 0||buffered.publishedAt>=floor);this.cursor=read.events.length===0?endCursor:cursor;this.pushActive(read.truncated||replayed.length<read.events.length);for(const buffered of replayed)await this.deliver(buffered);this.cursor=endCursor;this.lastSequence=endSequence}async deliver(buffered){if(this.closed||buffered.sequence<=this.lastSequence)return;if(this.accessUnchecked){this.withheld=true;return}this.lastSequence=buffered.sequence;const occurrence=await this.occurrenceFor(buffered);if(!occurrence)return;const{buffer}=this.options;if(buffer)this.cursor=buffer.cursorAt(buffered.sequence);this.pushEvent(occurrence)}async openOnCheck(){const checked=await this.check();this.pushActive(checked?.truncated===true);if(checked)this.pushChecked(checked);this.scheduleCheck(checked?.nextPollMs)}async check(){const{context,checkMaxEvents,maxAgeMs}=this.options;const check=context.check;const limits={maxEvents:checkMaxEvents,...this.cursor!==null&&maxAgeMs!==void 0&&{maxAgeMs}};try{const checked=await check.call(context,this.options.arguments,this.cursor,limits);this.cursor=checked.cursor;return checked}catch(error){this.options.logger.warn(`check() of event "${this.eventName}" failed for stream ${this.subscription.id}`,error);this.push(EVENTS_NOTIFICATIONS2.error,{error:{code:-32603,message:"UpstreamError",data:{reason:"check() failed"}}});return void 0}}scheduleCheck(nextPollMs){if(this.closed)return;this.checkTimer=setTimeout(()=>void this.runCheck(),nextPollMs??this.options.checkIntervalMs);this.checkTimer.unref?.()}async runCheck(){if(this.accessUnchecked){this.scheduleCheck(void 0);return}const checked=await this.check();if(checked?.truncated)this.pushActive(true);if(checked)this.pushChecked(checked);this.scheduleCheck(checked?.hasMore?0:checked?.nextPollMs)}pushChecked(checked){const{event}=this.options;for(const item of checked.events){try{this.pushEvent({eventId:item.eventId??newEventId(),name:event.name,timestamp:item.timestamp??new Date().toISOString(),data:event.parsePayload(item.data)})}catch(error){this.options.logger.warn(`check() of event "${event.name}" returned data that is not its payload`,error)}}}async occurrenceFor(buffered){const{context,reader,subscription}=this.options;const{occurrence}=buffered;if(buffered.subscriptionId!==void 0&&buffered.subscriptionId!==subscription.id)return void 0;if(!isInAudience(buffered.audience,reader.subscriber))return void 0;try{const matches=await context.match?.(occurrence,this.options.arguments,reader.subscriber)??true;if(!matches)return void 0;if(!context.transform)return occurrence;const transformed=await context.transform(occurrence,this.options.arguments,reader.subscriber);return EventOccurrenceSchema5.parse(transformed)}catch(error){this.options.logger.warn(`Event "${occurrence.name}" failed for stream ${subscription.id}`,error);return void 0}}async beat(){if(this.closed)return;const now=Date.now();if(now-this.lastAuthorizedAt>this.options.reauthorizeEveryMs){const check=await this.options.reauthorize().catch(error=>({outcome:"failed",error}));if(check.outcome==="refused"){this.terminate(this.options.accessRevoked);return}if(check.outcome==="failed"){this.accessUnchecked=true;this.options.logger.warn(`The access of stream ${this.subscription.id} could not be checked`,check.error)}else{this.lastAuthorizedAt=now;this.resumeAfterCheck()}}this.push(EVENTS_NOTIFICATIONS2.heartbeat,{cursor:this.cursor})}resumeAfterCheck(){if(!this.accessUnchecked)return;this.accessUnchecked=false;if(this.withheld)this.pushActive(true);this.withheld=false}pushActive(truncated){this.push(EVENTS_NOTIFICATIONS2.active,{cursor:this.cursor,truncated})}pushEvent(occurrence){this.push(EVENTS_NOTIFICATIONS2.event,{...occurrence,cursor:this.cursor})}push(method,params){if(this.closed)return;const meta={[MCP_20260728_META9.subscriptionId]:this.options.requestId};if(this.queue.length>=MAX_QUEUED_NOTIFICATIONS){this.queue.length=0;this.queue.push({method:EVENTS_NOTIFICATIONS2.active,params:{cursor:this.cursor,truncated:true,_meta:meta}})}this.queue.push({method,params:{...params,_meta:meta}});this.wake?.()}}}});import{internalZ as z132}from"@frontmcp/lazy-zod";import{StreamEventsRequestSchema as StreamEventsRequestSchema3}from"@frontmcp/protocol";var inputSchema35,outputSchema34,stateSchema37,plan42,name42,Stage42,EventStreamFlow;var init_event_stream_flow=__esm({"libs/sdk/src/event/flows/event-stream.flow.ts"(){"use strict";init_common();init_errors();init_event_dialect();init_event_gates();init_event_reauthorization();init_event_stream();inputSchema35=z132.object({request:StreamEventsRequestSchema3,ctx:z132.unknown(),requestId:z132.union([z132.string(),z132.number()]),signal:z132.any().optional()});outputSchema34=z132.object({stream:z132.instanceof(EventStream)});stateSchema37=z132.object({authInfo:z132.any(),dialect:z132.enum(["sep-3415","sketch"]),event:z132.instanceof(EventEntry),reader:z132.any(),arguments:z132.record(z132.string(),z132.unknown()),context:z132.any(),subscription:z132.any(),stream:z132.instanceof(EventStream)});plan42={pre:["parseInput","resolveDialect","findEvent","resolveReader","checkEntryAuthorities","validateArguments","authorize"],execute:["openStream"],post:["buildResult"],finalize:["finalize"]};name42="events:stream";({Stage:Stage42}=FlowHooksOf(name42));EventStreamFlow=class extends FlowBase{logger=this.scopeLogger.child("EventStreamFlow");get events(){return this.scope.events}get codes(){return EVENT_DIALECTS[this.state.required.dialect].errorCodes}async parseInput(){const authInfo=this.input.ctx?.authInfo??{};this.state.set("authInfo",authInfo)}async resolveDialect(){const platform=callerPlatformOf(this.scope,this.state.required.authInfo,this.tryGetContext()?.platformType);this.state.set("dialect",resolveEventDialect(this.events.config.compat,platform))}async findEvent(){const eventName=this.input.request.params.name;this.state.set("event",offeredEventOf(this.events,eventName,"push",this.input.ctx,this.codes))}async resolveReader(){const{authInfo,event}=this.state.required;this.state.set("reader",eventReaderOf(this.scope,authInfo,event.name,this.codes))}async checkEntryAuthorities(){const{event,authInfo}=this.state.required;const sentArguments=this.input.request.params.arguments??{};await assertEventAuthorities(this.scope,event,authInfo,sentArguments,this.codes)}async validateArguments(){const{event,reader}=this.state.required;const parsedArguments=parsedEventArguments(event,this.input.request.params.arguments);this.state.set({arguments:parsedArguments,subscription:readerSubscriptionOf(reader,"push",event.name,parsedArguments)})}async authorize(){const{event,authInfo,reader}=this.state.required;const context=event.create(authInfo);await assertEventAuthorizes(context,event.name,this.state.required.arguments,reader.subscriber,this.codes);this.state.set("context",context)}async openStream(){const streams=this.events.streams;const{event,context,reader,subscription,authInfo}=this.state.required;const{config}=this.events;const subscriptionArguments=this.state.required.arguments;const codes=this.codes;const stream=new EventStream({requestId:this.input.requestId,event,context,reader,subscription,arguments:subscriptionArguments,cursor:this.input.request.params.cursor,maxAgeMs:this.input.request.params.maxAgeMs,buffer:context.check?void 0:this.events.buffer,heartbeatMs:config.push.heartbeatMs,checkIntervalMs:config.poll.nextPollMs,checkMaxEvents:config.poll.maxEvents,reauthorizeEveryMs:config.subscriptions.reauthorizeEveryMs,reauthorize:()=>reauthorizeSubscriber({scope:this.scope,event,subscriber:reader.subscriber,arguments:subscriptionArguments,authInfo}),accessRevoked:{code:codes.forbidden,message:"Forbidden",data:{reason:"Access revoked"}},signal:this.input.signal,logger:this.logger});if(!streams.reserve(stream)){stream.close();throw new EventResourceExhaustedError(this.codes,"streams",config.subscriptions.maxPerPrincipal)}try{await context.onSubscribe?.(subscriptionArguments,subscription)}catch(error){stream.close();throw error}stream.onClose(()=>{const warn=error=>this.logger.warn(`onUnsubscribe of event "${event.name}" failed for stream ${subscription.id}`,error);try{Promise.resolve(context.onUnsubscribe?.(subscriptionArguments,subscription,"closed")).catch(warn)}catch(error){warn(error)}});streams.add(stream);try{await stream.open()}catch(error){stream.close();throw error}this.state.set("stream",stream);this.logger.verbose(`openStream: stream ${subscription.id} opened for event "${event.name}"`)}async buildResult(){this.respond({stream:this.state.required.stream})}async finalize(){this.logger.verbose("finalize")}};__decorateClass([Stage42("parseInput")],EventStreamFlow.prototype,"parseInput",1);__decorateClass([Stage42("resolveDialect")],EventStreamFlow.prototype,"resolveDialect",1);__decorateClass([Stage42("findEvent")],EventStreamFlow.prototype,"findEvent",1);__decorateClass([Stage42("resolveReader")],EventStreamFlow.prototype,"resolveReader",1);__decorateClass([Stage42("checkEntryAuthorities")],EventStreamFlow.prototype,"checkEntryAuthorities",1);__decorateClass([Stage42("validateArguments")],EventStreamFlow.prototype,"validateArguments",1);__decorateClass([Stage42("authorize")],EventStreamFlow.prototype,"authorize",1);__decorateClass([Stage42("openStream")],EventStreamFlow.prototype,"openStream",1);__decorateClass([Stage42("buildResult")],EventStreamFlow.prototype,"buildResult",1);__decorateClass([Stage42("finalize")],EventStreamFlow.prototype,"finalize",1);EventStreamFlow=__decorateClass([FrontMcpFlow({name:name42,plan:plan42,inputSchema:inputSchema35,outputSchema:outputSchema34,access:"authorized"})],EventStreamFlow)}});import{canonicalJson as canonicalJson4,getRuntimeContext as getRuntimeContext27,sha256Hex as sha256Hex25}from"@frontmcp/utils";function clamp(value,lowest,highest){return Math.min(Math.max(value,lowest),highest)}function subscriptionRefOf(record){return{id:record.id,name:record.eventName,mode:record.delivery.mode,subscriber:record.subscriber}}function isoTimeOf(time){return time===void 0?null:new Date(time).toISOString()}function deliveryStatusOf(record){const{lastDeliveryAt,lastError,failedSince}=record.status;return{active:record.active,lastDeliveryAt:isoTimeOf(lastDeliveryAt),lastError:lastError??null,failedSince:isoTimeOf(failedSince)}}var SUBSCRIPTION_SWEEP_INTERVAL_MS,EventSubscriptions;var init_event_subscriptions=__esm({"libs/sdk/src/event/subscription/event-subscriptions.ts"(){"use strict";SUBSCRIPTION_SWEEP_INTERVAL_MS=6e4;EventSubscriptions=class{constructor(options){this.options=options;this.store=options.store;this.verifier=options.verifier;this.logger=options.logger.child("EventSubscriptions")}options;store;verifier;logger;sweepTimer;lastSweepAt=0;get settings(){return this.options.settings}identityOf(principalKey,url,eventName,args){const canonicalKey=canonicalJson4({principalKey,url,name:eventName,arguments:args});return{id:`sub_${sha256Hex25(canonicalKey).slice(0,32)}`,argumentsKey:canonicalJson4(args)}}grantExpiry(event,requestedTtlMs,now){const{defaultTtlMs,maxTtlMs,minTtlMs,allowNoExpiry}=this.options.settings;const eventTtl=event.metadata.ttl;const longestMs=Math.min(eventTtl?.maxMs??maxTtlMs,maxTtlMs);const shortestMs=Math.min(minTtlMs,longestMs);if(requestedTtlMs===null){const grantsNoExpiry=allowNoExpiry&&this.options.durable&&eventTtl?.maxMs===void 0;return grantsNoExpiry?null:now+longestMs}if(requestedTtlMs===void 0){return now+clamp(eventTtl?.defaultMs??defaultTtlMs,shortestMs,longestMs)}return now+clamp(requestedTtlMs,shortestMs,longestMs)}rotatedDelivery(current,url,secret,now){const delivery={mode:"webhook",url,secret};if(!current)return delivery;if(current.secret!==secret){return{...delivery,previousSecret:current.secret,previousSecretUntil:now+this.options.rotationGraceMs}}const graceIsRunning=current.previousSecret!==void 0&&(current.previousSecretUntil??0)>now;if(!graceIsRunning)return delivery;return{...delivery,previousSecret:current.previousSecret,previousSecretUntil:current.previousSecretUntil}}async notifySubscribed(event,record,authInfo){await event.create(authInfo).onSubscribe?.(record.arguments,subscriptionRefOf(record))}async notifyUnsubscribed(record,reason,authInfo={}){const event=this.options.events.findByName(record.eventName);if(!event)return;try{await event.create(authInfo).onUnsubscribe?.(record.arguments,subscriptionRefOf(record),reason)}catch(error){this.logger.warn(`onUnsubscribe of event "${record.eventName}" failed for subscription ${record.id}`,error)}}async expire(id,now=Date.now()){const removed=await this.store.deleteExpired(id,now);if(removed)await this.notifyUnsubscribed(removed,"expired")}async sweep(now=Date.now()){this.lastSweepAt=now;const expired=await this.store.listExpired(now);for(const record of expired){await this.expire(record.id,now)}}sweepIfDue(now=Date.now()){if(now-this.lastSweepAt<SUBSCRIPTION_SWEEP_INTERVAL_MS)return;this.sweepInBackground(now)}start(){const{runtime,deployment}=getRuntimeContext27();if(deployment==="serverless"||runtime==="edge"||runtime==="browser")return;this.sweepTimer=setInterval(()=>this.sweepInBackground(Date.now()),SUBSCRIPTION_SWEEP_INTERVAL_MS);this.sweepTimer.unref?.()}async close(){if(this.sweepTimer)clearInterval(this.sweepTimer);this.sweepTimer=void 0;await this.store.close()}sweepInBackground(now){this.sweep(now).catch(error=>this.logger.warn("The subscription expiry sweep failed",error))}}}});import{internalZ as z133}from"@frontmcp/lazy-zod";import{SubscribeEventRequestSchema as SubscribeEventRequestSchema2,SubscribeEventResultSchema as SubscribeEventResultSchema2}from"@frontmcp/protocol";import{isStandardWebhookSecret,validateOutboundUrl}from"@frontmcp/utils";function reactivatedStatus(status={}){const{failures:_failures,suspendedSince:_suspendedSince,...kept}=status;return kept}var inputSchema36,outputSchema35,stateSchema38,plan43,name43,Stage43,URL_PROBLEMS,EventSubscribeFlow;var init_event_subscribe_flow=__esm({"libs/sdk/src/event/flows/event-subscribe.flow.ts"(){"use strict";init_common();init_availability();init_errors();init_event_dialect();init_event_subscriber();init_event_subscriptions();inputSchema36=z133.object({request:SubscribeEventRequestSchema2,ctx:z133.unknown()});outputSchema35=SubscribeEventResultSchema2;stateSchema38=z133.object({authInfo:z133.any(),dialect:z133.enum(["sep-3415","sketch"]),event:z133.instanceof(EventEntry),owner:z133.any(),arguments:z133.record(z133.string(),z133.unknown()),subscriptionId:z133.string(),argumentsKey:z133.string(),existing:z133.any(),verifiedAt:z133.number(),expiresAt:z133.number().nullable(),record:z133.any(),truncated:z133.boolean().optional()});plan43={pre:["parseInput","resolveDialect","findEvent","checkAvailability","requireWebhookMode","requireSubscriber","checkEntryAuthorities","validateArguments","authorize","validateDelivery"],execute:["findSubscription","enforceLimits","verifyCallback","grantTtl","upsertSubscription","notifySubscribed","startReplay"],post:["buildResult"],finalize:["finalize"]};name43="events:subscribe";({Stage:Stage43}=FlowHooksOf(name43));URL_PROBLEMS={malformed:"it is not a URL",scheme:"it must use https",credentials:"it must not carry a user name or a password",host:"its host is local, private or a metadata service"};EventSubscribeFlow=class extends FlowBase{logger=this.scopeLogger.child("EventSubscribeFlow");get events(){return this.scope.events}get subscriptions(){return this.events.subscriptions}get codes(){return EVENT_DIALECTS[this.state.required.dialect].errorCodes}async parseInput(){const authInfo=this.input.ctx?.authInfo??{};this.state.set("authInfo",authInfo)}async resolveDialect(){const platform=callerPlatformOf(this.scope,this.state.required.authInfo,this.tryGetContext()?.platformType);this.state.set("dialect",resolveEventDialect(this.events.config.compat,platform))}async findEvent(){const eventName=this.input.request.params.name;const event=this.events.findByName(eventName);if(!event)throw new EventNotFoundError(this.codes,"event",eventName);this.state.set("event",event)}async checkAvailability(){const{event}=this.state.required;if(!isOfferedOnSurface(event.metadata.availableWhen,callSurfaceOf(this.input.ctx))){throw new EventNotFoundError(this.codes,"event",event.name)}}async requireWebhookMode(){const requestedMode=this.input.request.params.delivery.mode??"webhook";const subscribableModes=this.events.deliveryModesOf(this.state.required.event).filter(mode=>mode==="webhook");if(requestedMode!=="webhook"||subscribableModes.length===0){throw new EventUnsupportedError(this.codes,"deliveryMode",requestedMode,subscribableModes)}}async requireSubscriber(){const{authInfo,event}=this.state.required;const owner=eventSubscriberOf(authInfo,this.scope.authoritiesContextBuilder);if(!owner)throw new EventForbiddenError(this.codes,event.name,"a webhook subscription needs a signed-in caller");this.state.set("owner",owner)}async checkEntryAuthorities(){const engine=this.scope.authoritiesEngine;const contextBuilder=this.scope.authoritiesContextBuilder;const{event,authInfo}=this.state.required;const authorities=event.getAuthorities();if(!engine||!contextBuilder||!authorities)return;const evaluationContext=contextBuilder.build(authInfo,this.input.request.params.arguments??{});const result=await engine.evaluate(authorities,evaluationContext);if(!result.granted){throw new EventForbiddenError(this.codes,event.name,result.deniedBy??"policy denied")}}async validateArguments(){try{this.state.set("arguments",this.state.required.event.parseArguments(this.input.request.params.arguments??{}))}catch(error){throw new InvalidInputError("Invalid subscription arguments",error instanceof z133.ZodError?error.issues:void 0)}}async authorize(){const{event,authInfo,owner}=this.state.required;try{await event.create(authInfo).authorize?.(this.state.required.arguments,owner.subscriber)}catch(error){if(error instanceof EventProtocolError)throw error;const reason=isPublicError(error)?error.getPublicMessage():"the event refused it";throw new EventForbiddenError(this.codes,event.name,reason)}}async validateDelivery(){const{url,secret}=this.input.request.params.delivery;const allowLocal=this.events.config.webhook.unsafeAllowLocalCallbacks;const urlCheck=validateOutboundUrl(url,{allowLocal});if(!urlCheck.ok)throw new InvalidInputError(`Invalid delivery.url: ${URL_PROBLEMS[urlCheck.problem]}`);if(!isStandardWebhookSecret(secret)){throw new InvalidInputError('Invalid delivery.secret: expected "whsec_" followed by base64 that decodes to 24 to 64 bytes')}}async findSubscription(){const{owner,event}=this.state.required;const{url}=this.input.request.params.delivery;const identity=this.subscriptions.identityOf(owner.principalKey,url,event.name,this.state.required.arguments);this.subscriptions.sweepIfDue();const existing=await this.subscriptions.store.get(identity.id);if(!existing)await this.subscriptions.expire(identity.id);this.state.set({subscriptionId:identity.id,argumentsKey:identity.argumentsKey,existing})}async enforceLimits(){if(this.state.existing)return;const{maxPerPrincipal}=this.subscriptions.settings;const held=await this.subscriptions.store.countByPrincipal(this.state.required.owner.principalKey);if(held>=maxPerPrincipal)throw new EventResourceExhaustedError(this.codes,"subscriptions",maxPerPrincipal)}async verifyCallback(){const{url,secret}=this.input.request.params.delivery;const{owner,subscriptionId}=this.state.required;const verification=await this.subscriptions.verifier.verify({principalKey:owner.principalKey,url,secret,subscriptionId,verifiedAt:this.state.existing?.verifiedAt});if(verification.outcome==="limited"){throw new EventResourceExhaustedError(this.codes,"verifications",verification.max)}if(verification.outcome==="failed"){this.logger.verbose(`verifyCallback: subscription ${subscriptionId} refused (${verification.reason})`);throw new EventCallbackEndpointError(this.codes,verification.reason)}this.state.set("verifiedAt",verification.verifiedAt)}async grantTtl(){const requestedTtlMs=this.input.request.params.ttlMs;this.state.set("expiresAt",this.subscriptions.grantExpiry(this.state.required.event,requestedTtlMs,Date.now()))}async upsertSubscription(){const{url,secret}=this.input.request.params.delivery;const{owner,event,dialect,subscriptionId,argumentsKey,verifiedAt}=this.state.required;const expiresAt=this.state.get("expiresAt")??null;const existing=this.state.existing;const replay=existing?await this.currentReplayOf(subscriptionId):void 0;const now=Date.now();const record={id:subscriptionId,principalKey:owner.principalKey,subscriber:owner.subscriber,eventName:event.name,arguments:this.state.required.arguments,argumentsKey,delivery:this.subscriptions.rotatedDelivery(existing?.delivery,url,secret,now),dialect,createdAt:existing?.createdAt??now,updatedAt:now,expiresAt,verifiedAt,lastAuthorizedAt:now,active:true,status:reactivatedStatus(existing?.status),...replay&&{replay}};await this.subscriptions.store.upsert(record);this.state.set("record",record)}async notifySubscribed(){if(this.state.existing)return;const{event,record,authInfo}=this.state.required;try{await this.subscriptions.notifySubscribed(event,record,authInfo)}catch(error){await this.subscriptions.store.delete(record.id);throw error}this.logger.verbose(`notifySubscribed: subscription ${record.id} created for event "${event.name}"`)}async startReplay(){const{replays}=this.events;const{event,record}=this.state.required;if(!replays?.isReplayable(event))return;const{cursor=null,maxAgeMs}=this.input.request.params;const step=record.replay?await replays.refresh(record,record.replay):await replays.begin(event,record,cursor,maxAgeMs);this.state.set({record:{...record,replay:step.replay},truncated:step.truncated})}async currentReplayOf(subscriptionId){const stored=await this.subscriptions.store.get(subscriptionId);return stored?.replay}async buildResult(){const{record}=this.state.required;this.respond({id:record.id,refreshBefore:record.expiresAt===null?null:new Date(record.expiresAt).toISOString(),cursor:record.replay?.watermark??null,truncated:this.state.truncated??false,...this.state.existing&&{deliveryStatus:deliveryStatusOf(record)}})}async finalize(){this.logger.verbose("finalize")}};__decorateClass([Stage43("parseInput")],EventSubscribeFlow.prototype,"parseInput",1);__decorateClass([Stage43("resolveDialect")],EventSubscribeFlow.prototype,"resolveDialect",1);__decorateClass([Stage43("findEvent")],EventSubscribeFlow.prototype,"findEvent",1);__decorateClass([Stage43("checkAvailability")],EventSubscribeFlow.prototype,"checkAvailability",1);__decorateClass([Stage43("requireWebhookMode")],EventSubscribeFlow.prototype,"requireWebhookMode",1);__decorateClass([Stage43("requireSubscriber")],EventSubscribeFlow.prototype,"requireSubscriber",1);__decorateClass([Stage43("checkEntryAuthorities")],EventSubscribeFlow.prototype,"checkEntryAuthorities",1);__decorateClass([Stage43("validateArguments")],EventSubscribeFlow.prototype,"validateArguments",1);__decorateClass([Stage43("authorize")],EventSubscribeFlow.prototype,"authorize",1);__decorateClass([Stage43("validateDelivery")],EventSubscribeFlow.prototype,"validateDelivery",1);__decorateClass([Stage43("findSubscription")],EventSubscribeFlow.prototype,"findSubscription",1);__decorateClass([Stage43("enforceLimits")],EventSubscribeFlow.prototype,"enforceLimits",1);__decorateClass([Stage43("verifyCallback")],EventSubscribeFlow.prototype,"verifyCallback",1);__decorateClass([Stage43("grantTtl")],EventSubscribeFlow.prototype,"grantTtl",1);__decorateClass([Stage43("upsertSubscription")],EventSubscribeFlow.prototype,"upsertSubscription",1);__decorateClass([Stage43("notifySubscribed")],EventSubscribeFlow.prototype,"notifySubscribed",1);__decorateClass([Stage43("startReplay")],EventSubscribeFlow.prototype,"startReplay",1);__decorateClass([Stage43("buildResult")],EventSubscribeFlow.prototype,"buildResult",1);__decorateClass([Stage43("finalize")],EventSubscribeFlow.prototype,"finalize",1);EventSubscribeFlow=__decorateClass([FrontMcpFlow({name:name43,plan:plan43,inputSchema:inputSchema36,outputSchema:outputSchema35,access:"authorized"})],EventSubscribeFlow)}});import{internalZ as z134}from"@frontmcp/lazy-zod";import{UnsubscribeEventRequestSchema as UnsubscribeEventRequestSchema2,UnsubscribeEventResultSchema}from"@frontmcp/protocol";var inputSchema37,outputSchema36,stateSchema39,plan44,name44,Stage44,EventUnsubscribeFlow;var init_event_unsubscribe_flow=__esm({"libs/sdk/src/event/flows/event-unsubscribe.flow.ts"(){"use strict";init_common();init_errors();init_event_dialect();init_event_subscriber();inputSchema37=z134.object({request:UnsubscribeEventRequestSchema2,ctx:z134.unknown()});outputSchema36=UnsubscribeEventResultSchema;stateSchema39=z134.object({authInfo:z134.any(),dialect:z134.enum(["sep-3415","sketch"]),owner:z134.any()});plan44={pre:["parseInput","resolveDialect","requireSubscriber"],execute:["removeSubscription"],post:["buildResult"],finalize:["finalize"]};name44="events:unsubscribe";({Stage:Stage44}=FlowHooksOf(name44));EventUnsubscribeFlow=class extends FlowBase{logger=this.scopeLogger.child("EventUnsubscribeFlow");get events(){return this.scope.events}get subscriptions(){return this.events.subscriptions}async parseInput(){const authInfo=this.input.ctx?.authInfo??{};this.state.set("authInfo",authInfo)}async resolveDialect(){const platform=callerPlatformOf(this.scope,this.state.required.authInfo,this.tryGetContext()?.platformType);this.state.set("dialect",resolveEventDialect(this.events.config.compat,platform))}async requireSubscriber(){const{authInfo,dialect}=this.state.required;const owner=eventSubscriberOf(authInfo,this.scope.authoritiesContextBuilder);if(!owner){const eventName=this.input.request.params.name;const codes=EVENT_DIALECTS[dialect].errorCodes;throw new EventForbiddenError(codes,eventName,"a webhook subscription needs a signed-in caller")}this.state.set("owner",owner)}async removeSubscription(){const{name:eventName,delivery}=this.input.request.params;const{owner,authInfo}=this.state.required;const identity=this.subscriptions.identityOf(owner.principalKey,delivery.url,eventName,this.storedArguments());this.subscriptions.sweepIfDue();const removed=await this.subscriptions.store.delete(identity.id);if(!removed)return;await this.subscriptions.notifyUnsubscribed(removed,"unsubscribed",authInfo);this.logger.verbose(`removeSubscription: subscription ${removed.id} removed from event "${eventName}"`)}async buildResult(){this.respond({})}async finalize(){this.logger.verbose("finalize")}storedArguments(){const{name:eventName,arguments:sentArguments={}}=this.input.request.params;try{return this.events.findByName(eventName)?.parseArguments(sentArguments)??sentArguments}catch{return sentArguments}}};__decorateClass([Stage44("parseInput")],EventUnsubscribeFlow.prototype,"parseInput",1);__decorateClass([Stage44("resolveDialect")],EventUnsubscribeFlow.prototype,"resolveDialect",1);__decorateClass([Stage44("requireSubscriber")],EventUnsubscribeFlow.prototype,"requireSubscriber",1);__decorateClass([Stage44("removeSubscription")],EventUnsubscribeFlow.prototype,"removeSubscription",1);__decorateClass([Stage44("buildResult")],EventUnsubscribeFlow.prototype,"buildResult",1);__decorateClass([Stage44("finalize")],EventUnsubscribeFlow.prototype,"finalize",1);EventUnsubscribeFlow=__decorateClass([FrontMcpFlow({name:name44,plan:plan44,inputSchema:inputSchema37,outputSchema:outputSchema36,access:"authorized"})],EventUnsubscribeFlow)}});import{internalZ as z135}from"@frontmcp/lazy-zod";import{EventDeliveryModeSchema,ListEventsRequestSchema as ListEventsRequestSchema2,ListEventsResultSchema as ListEventsResultSchema2}from"@frontmcp/protocol";function compareByName(left,right){if(left.event.name<right.event.name)return-1;return left.event.name>right.event.name?1:0}var EVENTS_LIST_PAGE_SIZE,inputSchema38,outputSchema37,stateSchema40,plan45,name45,Stage45,ListEventsFlow;var init_list_events_flow=__esm({"libs/sdk/src/event/flows/list-events.flow.ts"(){"use strict";init_common();init_availability();init_offset_cursor_utils();init_errors();init_entry_authorized();EVENTS_LIST_PAGE_SIZE=40;inputSchema38=z135.object({request:ListEventsRequestSchema2,ctx:z135.unknown()});outputSchema37=ListEventsResultSchema2;stateSchema40=z135.object({cursor:z135.string().optional(),authInfo:z135.any(),events:z135.array(z135.object({event:z135.instanceof(EventEntry),delivery:z135.array(EventDeliveryModeSchema)}))});plan45={pre:["parseInput"],execute:["findEvents","filterByAvailability","filterByAuthorities","filterByDiscovery"],post:["parseEvents"],finalize:["finalize"]};name45="events:list";({Stage:Stage45}=FlowHooksOf(name45));ListEventsFlow=class extends FlowBase{logger=this.scopeLogger.child("ListEventsFlow");async parseInput(){const{request:request2,ctx}=this.input;const authInfo=ctx?.authInfo??{};this.state.set({cursor:request2.params?.cursor??void 0,authInfo})}async findEvents(){this.state.set("events",this.scope.events?.getServedEvents()??[])}async filterByAvailability(){const callSurface=callSurfaceOf(this.input.ctx);const offered=this.state.required.events.filter(({event})=>isOfferedOnSurface(event.metadata.availableWhen,callSurface));this.state.set("events",offered)}async filterByAuthorities(){const engine=this.scope.authoritiesEngine;const contextBuilder=this.scope.authoritiesContextBuilder;if(!engine||!contextBuilder)return;const{events,authInfo}=this.state.required;const answers=await Promise.all(events.map(({event})=>{const authorities=event.getAuthorities();if(authorities===void 0)return true;return isListedByAuthorities(engine,contextBuilder,authorities,authInfo,event.name,this.logger)}));this.state.set("events",events.filter((_item,index)=>answers[index]))}async filterByDiscovery(){const discoverable=this.state.required.events.filter(({event})=>!event.metadata.hideFromDiscovery);this.state.set("events",discoverable)}async parseEvents(){const sorted=[...this.state.required.events].sort(compareByName);const offset=this.state.cursor?parseOffsetCursor(this.state.cursor):0;if(offset>sorted.length){throw new InvalidInputError(`Invalid pagination cursor: offset ${offset} exceeds total event count ${sorted.length}`)}const events=sorted.slice(offset,offset+EVENTS_LIST_PAGE_SIZE).map(({event,delivery})=>({name:event.name,...event.metadata.description&&{description:event.metadata.description},delivery,inputSchema:event.getInputJsonSchema(),payloadSchema:event.getPayloadJsonSchema()}));const nextOffset=offset+EVENTS_LIST_PAGE_SIZE;this.respond({events,...nextOffset<sorted.length&&{nextCursor:encodeOffsetCursor(nextOffset)}})}async finalize(){this.logger.verbose("finalize")}};__decorateClass([Stage45("parseInput")],ListEventsFlow.prototype,"parseInput",1);__decorateClass([Stage45("findEvents")],ListEventsFlow.prototype,"findEvents",1);__decorateClass([Stage45("filterByAvailability")],ListEventsFlow.prototype,"filterByAvailability",1);__decorateClass([Stage45("filterByAuthorities")],ListEventsFlow.prototype,"filterByAuthorities",1);__decorateClass([Stage45("filterByDiscovery")],ListEventsFlow.prototype,"filterByDiscovery",1);__decorateClass([Stage45("parseEvents")],ListEventsFlow.prototype,"parseEvents",1);__decorateClass([Stage45("finalize")],ListEventsFlow.prototype,"finalize",1);ListEventsFlow=__decorateClass([FrontMcpFlow({name:name45,plan:plan45,inputSchema:inputSchema38,outputSchema:outputSchema37,access:"authorized"})],ListEventsFlow)}});import{randomUUID as randomUUID29}from"@frontmcp/utils";var CURSOR_SEPARATOR,EventBuffer;var init_event_buffer=__esm({"libs/sdk/src/event/poll/event-buffer.ts"(){"use strict";CURSOR_SEPARATOR=".";EventBuffer=class{constructor(options){this.options=options;this.bootId=randomUUID29().replace(/-/g,"")}options;bootId;rings=new Map;sequence=0;append(occurrence,audience,subscriptionId){const now=Date.now();this.sequence+=1;const buffered={sequence:this.sequence,publishedAt:now,occurrence,audience,subscriptionId};const ring=this.ringOf(occurrence.name);ring.events.push(buffered);this.prune(ring,now);return buffered}currentCursor(){return this.cursorAt(this.sequence)}currentSequence(){return this.sequence}cursorAt(sequence){return`${this.bootId}${CURSOR_SEPARATOR}${sequence}`}read(eventName,cursor){const ring=this.ringOf(eventName);this.prune(ring,Date.now());const position=this.positionOf(cursor);if(position===void 0)return{events:[],truncated:true};return{events:ring.events.filter(buffered=>buffered.sequence>position),truncated:position<ring.droppedThrough}}positionOf(cursor){const[bootId,position,...rest]=cursor.split(CURSOR_SEPARATOR);const sequence=Number(position);const isPosition=Number.isSafeInteger(sequence)&&sequence>=0&&String(sequence)===position;if(bootId!==this.bootId||!isPosition||rest.length>0||sequence>this.sequence)return void 0;return sequence}ringOf(eventName){let ring=this.rings.get(eventName);if(!ring){ring={events:[],droppedThrough:0};this.rings.set(eventName,ring)}return ring}prune(ring,now){const{maxAgeMs,maxEvents}=this.options;const oldestKept=now-maxAgeMs;let dropCount=Math.max(0,ring.events.length-maxEvents);while(dropCount<ring.events.length&&ring.events[dropCount].publishedAt<oldestKept)dropCount+=1;if(dropCount===0)return;ring.droppedThrough=ring.events[dropCount-1].sequence;ring.events.splice(0,dropCount)}}}});import{internalZ as z136}from"@frontmcp/lazy-zod";function isTimestamp(value){return!Number.isNaN(new Date(value).getTime())}function mediaTypeOf2(contentType2){return(contentType2??"").split(";")[0].trim().toLowerCase()}function jsonOf(body){try{return JSON.parse(decoder3.decode(body))}catch{return void 0}}function summarizeIssues(error){return error.issues.map(issue=>({path:issue.path.join("."),message:issue.message}))}var EVENT_PUBLISH_MAX_BODY_BYTES,EVENT_ID_PATTERN,audienceValueSchema2,publishRequestSchema,inputSchema39,outputSchema38,stateSchema41,plan46,name46,Stage46,decoder3,EventPublishHttpFlow;var init_event_publish_http_flow=__esm({"libs/sdk/src/event/flows/event-publish-http.flow.ts"(){"use strict";init_common();init_errors();init_flow_http_path();init_workflow_webhook_signature();init_event_subscriber();EVENT_PUBLISH_MAX_BODY_BYTES=262144;EVENT_ID_PATTERN=/^[\x21-\x7e]{1,255}$/;audienceValueSchema2=z136.union([z136.string(),z136.array(z136.string())]);publishRequestSchema=z136.object({name:z136.string().min(1),data:z136.record(z136.string(),z136.unknown()),eventId:z136.string().regex(EVENT_ID_PATTERN,"eventId must be 1 to 255 visible ASCII characters").optional(),timestamp:z136.string().refine(isTimestamp,"timestamp must be a date such as 2026-10-02T12:00:00Z").optional(),subscriptionId:z136.string().min(1).optional(),audience:z136.object({sub:audienceValueSchema2.optional(),tenantId:audienceValueSchema2.optional(),roles:z136.object({any:z136.array(z136.string()).optional(),all:z136.array(z136.string()).optional()}).strict().optional()}).strict().optional()}).strict();inputSchema39=httpInputSchema;outputSchema38=HttpJsonSchema;stateSchema41=z136.object({body:z136.custom(),caller:z136.custom().optional(),publication:publishRequestSchema,event:z136.instanceof(EventEntry),claimedEventId:z136.string().optional(),claimToken:z136.string().optional(),result:z136.object({eventId:z136.string(),matched:z136.number()}),flowError:z136.instanceof(Error).optional()});plan46={pre:["checkIpFilter","acquireQuota","readBody","authenticate","parseBody","checkAuthorities","findEvent","validatePayload"],execute:["claimEventId","publish","rememberResult","buildResponse"],finalize:["finalize"]};name46="events:publish-http";({Stage:Stage46}=FlowHooksOf(name46));decoder3=new TextDecoder;EventPublishHttpFlow=class extends FlowBase{logger=this.scopeLogger.child("EventPublishHttpFlow");static canActivate(request2,scope){const endpoint=scope.events?.publishEndpoint;return endpoint!==void 0&&request2.method==="POST"&&matchRoutePath(endpoint.path,request2.path)!==void 0}get events(){return this.scope.events}get endpoint(){return this.events.publishEndpoint}get publisher(){return this.events.publisher}get httpRequest(){return this.rawInput.request}refuse(status,error,details={},headers){this.state.set("flowError",new PublicMcpError(`HTTP ${status}: ${error}`,"EVENT_PUBLISH_REFUSED",status));return FlowControl.respond(httpRespond.json({error,...details},{status,headers}))}async recordingRefusal(guard){try{await guard()}catch(signal){const refusal4=signal instanceof FlowControl&&signal.type==="respond"?signal.output:void 0;if(refusal4?.kind==="json"){const reason=Array.isArray(refusal4.body)?void 0:refusal4.body["error"];const error=typeof reason==="string"?reason:"Refused";this.state.set("flowError",new PublicMcpError(`HTTP ${refusal4.status}: ${error}`,"EVENT_PUBLISH_REFUSED",refusal4.status))}throw signal}}async checkIpFilter(){await this.recordingRefusal(()=>enforceIpFilter(this.scope,this.tryGetContext()?.metadata.clientIp))}async acquireQuota(){await this.recordingRefusal(()=>enforceGlobalRateLimit(this.scope,this.tryGetContext()))}async readBody(){const request2=this.httpRequest;if(mediaTypeOf2(request2.headers["content-type"])!=="application/json"){this.refuse(415,"The body must be application/json")}const body=request2.bodyBytes??new Uint8Array;if(body.length>EVENT_PUBLISH_MAX_BODY_BYTES)this.refuse(413,"Payload too large");this.state.set("body",body)}async authenticate(){const{secret,replays}=this.endpoint;if(secret===void 0){this.state.set("caller",await this.verifyBearer());return}const signedRequest={headers:this.httpRequest.headers,body:this.state.required.body};const refusal4=verifyWorkflowWebhook(signedRequest,secret,replays);if(refusal4){this.logger.warn(`authenticate: a publish request was refused: ${refusal4}`);this.refuse(401,"Unauthorized")}}async parseBody(){const parsed=publishRequestSchema.safeParse(jsonOf(this.state.required.body));if(!parsed.success)this.refuse(400,"Invalid publish request",{issues:summarizeIssues(parsed.error)});this.state.set("publication",parsed.data)}async checkAuthorities(){const engine=this.scope.authoritiesEngine;const contextBuilder=this.scope.authoritiesContextBuilder;const{authorities}=this.endpoint;if(!engine||!contextBuilder||authorities===void 0)return;const caller=this.state.caller??{};const evaluationContext=contextBuilder.build(caller,this.state.required.publication);const result=await engine.evaluate(authorities,evaluationContext);if(result.granted)return;this.logger.verbose(`checkAuthorities: a publish request was refused: ${result.deniedBy??"policy denied"}`);this.refuse(403,"Forbidden")}async findEvent(){const eventName=this.state.required.publication.name;const event=this.events.findByName(eventName);if(!event)this.refuse(404,`Event "${eventName}" is not registered`);this.state.set("event",event)}async validatePayload(){const{event,publication}=this.state.required;try{event.parsePayload(publication.data)}catch(error){if(!(error instanceof z136.ZodError))throw error;this.refuse(422,`data does not match the payloadSchema of event "${event.name}"`,{issues:summarizeIssues(error)})}}async claimEventId(){const{name:eventName,eventId}=this.state.required.publication;if(eventId===void 0)return;const claim=await this.endpoint.idempotency.claim(eventName,eventId);if(claim.state==="published")return this.respond(httpRespond.json(claim.result,{status:202}));if(claim.state==="in-flight"){this.refuse(409,`Event "${eventName}" with eventId "${eventId}" is being published; retry for its answer`)}this.state.set({claimedEventId:eventId,claimToken:claim.token})}async publish(){const{name:eventName,data,eventId,timestamp,subscriptionId,audience}=this.state.required.publication;try{const options={eventId,timestamp,subscriptionId,audience};this.state.set("result",await this.publisher.publish(eventName,data,options))}catch(error){const{claimedEventId,claimToken}=this.state;if(claimedEventId!==void 0&&claimToken!==void 0){await this.endpoint.idempotency.release(eventName,claimedEventId,claimToken)}throw error}}async rememberResult(){const{claimedEventId,claimToken}=this.state;if(claimedEventId===void 0||claimToken===void 0)return;const{publication,result}=this.state.required;try{await this.endpoint.idempotency.complete(publication.name,claimedEventId,claimToken,result)}catch(error){this.logger.warn(`rememberResult: event "${publication.name}" with eventId "${claimedEventId}" was published, but its answer could not be kept for a repeat`,error)}}async buildResponse(){this.respond(httpRespond.json(this.state.required.result,{status:202}))}async finalize(){this.logger.verbose(`finalize: ${this.state.result?"published":"not published"}`)}async verifyBearer(){const verified=await this.scope.runFlow("session:verify",{request:this.httpRequest,sessionless:true});if(verified?.kind==="authorized"){const caller=authInfoFromAuthorization(verified.authorization);if(eventSubscriberOf(caller,this.scope.authoritiesContextBuilder))return caller;return this.refuse(401,"Unauthorized",{message:"Publishing needs a signed-in caller"})}const headers=challengeHeaders(verified?.prmMetadataHeader);return verified?.kind==="forbidden"?this.refuse(403,"Forbidden",{},headers):this.refuse(401,"Unauthorized",{},headers)}};__decorateClass([Stage46("checkIpFilter")],EventPublishHttpFlow.prototype,"checkIpFilter",1);__decorateClass([Stage46("acquireQuota")],EventPublishHttpFlow.prototype,"acquireQuota",1);__decorateClass([Stage46("readBody")],EventPublishHttpFlow.prototype,"readBody",1);__decorateClass([Stage46("authenticate")],EventPublishHttpFlow.prototype,"authenticate",1);__decorateClass([Stage46("parseBody")],EventPublishHttpFlow.prototype,"parseBody",1);__decorateClass([Stage46("checkAuthorities")],EventPublishHttpFlow.prototype,"checkAuthorities",1);__decorateClass([Stage46("findEvent")],EventPublishHttpFlow.prototype,"findEvent",1);__decorateClass([Stage46("validatePayload")],EventPublishHttpFlow.prototype,"validatePayload",1);__decorateClass([Stage46("claimEventId")],EventPublishHttpFlow.prototype,"claimEventId",1);__decorateClass([Stage46("publish")],EventPublishHttpFlow.prototype,"publish",1);__decorateClass([Stage46("rememberResult")],EventPublishHttpFlow.prototype,"rememberResult",1);__decorateClass([Stage46("buildResponse")],EventPublishHttpFlow.prototype,"buildResponse",1);__decorateClass([Stage46("finalize")],EventPublishHttpFlow.prototype,"finalize",1);EventPublishHttpFlow=__decorateClass([FrontMcpFlow({name:name46,plan:plan46,inputSchema:inputSchema39,outputSchema:outputSchema38,access:"public",middleware:{method:"POST"}})],EventPublishHttpFlow)}});import{bytesToHex as bytesToHex4,hmacSha256 as hmacSha2564,sha256Hex as sha256Hex26}from"@frontmcp/utils";function isExpired(record,now){return record.expiresAt!==null&&record.expiresAt<=now}function ttlOptionsOf(record){if(record.expiresAt===null)return{};const remainingSeconds=Math.max(0,Math.ceil((record.expiresAt-Date.now())/1e3));return{ttlSeconds:remainingSeconds+EXPIRED_RETENTION_SECONDS}}function idOfIndexKey(indexKey){return indexKey.slice(indexKey.lastIndexOf(":")+1)}var RECORD_PREFIX3,EVENT_INDEX_PREFIX,PRINCIPAL_INDEX_PREFIX,EXPIRY_INDEX_PREFIX,EXPIRED_RETENTION_SECONDS,MAX_ATTEMPTS2,textEncoder3,StorageEventSubscriptionStore;var init_event_subscription_store=__esm({"libs/sdk/src/event/subscription/event-subscription.store.ts"(){"use strict";init_elicitation_encryption();init_errors();RECORD_PREFIX3="s:";EVENT_INDEX_PREFIX="e:";PRINCIPAL_INDEX_PREFIX="p:";EXPIRY_INDEX_PREFIX="x:";EXPIRED_RETENTION_SECONDS=3600;MAX_ATTEMPTS2=16;textEncoder3=new TextEncoder;StorageEventSubscriptionStore=class{constructor(options){this.options=options}options;async upsert(record){const{storage}=this.options;const ttlOptions=ttlOptionsOf(record);await storage.set(RECORD_PREFIX3+record.id,await this.encode(record),ttlOptions);await storage.set(this.eventIndexKey(record),"1",ttlOptions);await storage.set(this.principalIndexKey(record),"1",ttlOptions);if(record.expiresAt!==null){await storage.set(`${EXPIRY_INDEX_PREFIX}${record.expiresAt}:${record.id}`,"1",ttlOptions)}}async get(id){const stored=await this.read(id);return stored&&!isExpired(stored.record,Date.now())?stored.record:void 0}async delete(id){return this.remove(id,()=>true)}async deleteExpired(id,now){return this.remove(id,record=>isExpired(record,now))}async listByEvent(eventName){return this.liveRecordsOf(`${EVENT_INDEX_PREFIX}${this.digest("event",eventName)}:*`)}async countByPrincipal(principalKey){const records=await this.liveRecordsOf(`${PRINCIPAL_INDEX_PREFIX}${this.digest("principal",principalKey)}:*`);return records.length}async update(id,patch){const{storage}=this.options;const recordKey2=RECORD_PREFIX3+id;for(let attempt=0;attempt<MAX_ATTEMPTS2;attempt++){const stored=await this.read(id);if(!stored||isExpired(stored.record,Date.now()))return void 0;const changes=typeof patch==="function"?patch(stored.record):patch;const next={...stored.record,...changes};const nextRaw=await this.encode(next);if(!await storage.setIfEquals(recordKey2,stored.raw,nextRaw))continue;const{ttlSeconds}=ttlOptionsOf(next);if(ttlSeconds!==void 0)await storage.expireIfEquals(recordKey2,nextRaw,ttlSeconds);return next}throw new EventSubscriptionStoreError(`subscription ${id} kept changing while it was updated`)}async listExpired(now){const{storage}=this.options;const expiryKeys=await storage.keys(`${EXPIRY_INDEX_PREFIX}*`);const dueKeys=expiryKeys.filter(expiryKey=>Number(expiryKey.split(":")[1])<=now);const expired=[];for(const expiryKey of dueKeys){const stored=await this.read(idOfIndexKey(expiryKey));if(stored&&isExpired(stored.record,now)){expired.push(stored.record)}else{await storage.delete(expiryKey)}}return expired}async close(){await this.options.storage.disconnect()}async remove(id,shouldRemove){const{storage}=this.options;for(let attempt=0;attempt<MAX_ATTEMPTS2;attempt++){const stored=await this.read(id);if(!stored||!shouldRemove(stored.record))return void 0;if(!await storage.deleteIfEquals(RECORD_PREFIX3+id,stored.raw))continue;await storage.mdelete([this.eventIndexKey(stored.record),this.principalIndexKey(stored.record)]);return stored.record}throw new EventSubscriptionStoreError(`subscription ${id} kept changing while it was removed`)}async liveRecordsOf(indexPattern){const{storage}=this.options;const indexKeys=await storage.keys(indexPattern);if(indexKeys.length===0)return[];const ids=indexKeys.map(idOfIndexKey);const raws=await storage.mget(ids.map(id=>RECORD_PREFIX3+id));const now=Date.now();const records=[];for(let index=0;index<ids.length;index++){const raw=raws[index];const record=raw===null||raw===void 0?void 0:await this.decode(raw,ids[index]);if(record&&!isExpired(record,now))records.push(record)}return records}async read(id){const raw=await this.options.storage.get(RECORD_PREFIX3+id);if(raw===null)return void 0;const record=await this.decode(raw,id);return record?{raw,record}:void 0}async encode(record){const{secret}=this.options;return secret===void 0?JSON.stringify(record):encryptAndSerialize(record,`events:${record.id}`,secret)}async decode(raw,id){const{secret}=this.options;try{const record=secret===void 0?JSON.parse(raw):await deserializeAndDecrypt(raw,`events:${id}`,secret);return record?.id===id?record:void 0}catch{return void 0}}eventIndexKey(record){return`${EVENT_INDEX_PREFIX}${this.digest("event",record.eventName)}:${record.id}`}principalIndexKey(record){return`${PRINCIPAL_INDEX_PREFIX}${this.digest("principal",record.principalKey)}:${record.id}`}digest(kind,value){const{secret}=this.options;const text=`${kind}:${value}`;if(secret===void 0)return sha256Hex26(text);return bytesToHex4(hmacSha2564(textEncoder3.encode(secret),textEncoder3.encode(text)))}}}});import{createStorage as createStorage8,getEnv as getEnv19}from"@frontmcp/utils";function eventsSecretFromEnv(){return getEnv19("MCP_EVENTS_SECRET")||getEnv19("MCP_SESSION_SECRET")||getEnv19("MCP_SERVER_SECRET")||void 0}function storageConfigOf(options){const{redis,sqlite}=options;if(sqlite)return{type:"sqlite",sqlite};if(!redis)return{type:"memory"};if(!isRedisProvider(redis)){throw new EventSubscriptionStoreError("Vercel KV has no atomic compare-and-set, which subscription updates need. Use a Redis server in events.store.redis, or events.store.sqlite.")}const{host,port,password,db,tls}=redis;return{type:"redis",redis:{config:{host,port,password,db,tls}}}}async function openStorage(config,keyPrefix){try{return await createStorage8({...config,prefix:keyPrefix,fallback:"error"})}catch(error){const reason=error instanceof Error?error.message:String(error);throw new EventSubscriptionStoreError(`the ${config.type} store cannot be opened: ${reason}`)}}function openEventStorage(options={}){return openStorage(storageConfigOf(options),options.keyPrefix??"mcp:events:")}async function createEventSubscriptionStore(options={}){const{keyPrefix="mcp:events:",logger}=options;const config=storageConfigOf(options);const durable=config.type!=="memory";const secret=options.secret??eventsSecretFromEnv();if(durable&&!secret){throw new EventSubscriptionStoreError(`the ${config.type} store keeps webhook signing secrets, so it needs a secret to encrypt them with: set MCP_EVENTS_SECRET (or MCP_SESSION_SECRET / MCP_SERVER_SECRET).`)}const storage=await openStorage(config,keyPrefix);logger?.info("Event subscriptions are stored",{type:config.type,encrypted:secret!==void 0});return{store:new StorageEventSubscriptionStore({storage,secret}),type:config.type,durable,encrypted:secret!==void 0,storage,secret}}var init_event_subscription_store_factory=__esm({"libs/sdk/src/event/subscription/event-subscription-store.factory.ts"(){"use strict";init_common();init_errors();init_event_subscription_store()}});import{randomUUID as randomUUID30,sha256Hex as sha256Hex27}from"@frontmcp/utils";function pendingRecordOf(token){return JSON.stringify({pending:token})}function isPending(record){return"pending"in record}var PUBLISH_IDEMPOTENCY_WINDOW_SECONDS,PUBLISH_CLAIM_SECONDS,RECORD_PREFIX4,EventPublishIdempotency;var init_event_publish_idempotency=__esm({"libs/sdk/src/event/publish-endpoint/event-publish-idempotency.ts"(){"use strict";PUBLISH_IDEMPOTENCY_WINDOW_SECONDS=600;PUBLISH_CLAIM_SECONDS=60;RECORD_PREFIX4="published:";EventPublishIdempotency=class{constructor(storage,scopeId){this.storage=storage;this.scopeId=scopeId}storage;scopeId;async claim(eventName,eventId){const key=this.keyOf(eventName,eventId);const token=randomUUID30();await this.storage.set(key,pendingRecordOf(token),{ttlSeconds:PUBLISH_CLAIM_SECONDS,ifNotExists:true});const stored=await this.storage.get(key);if(stored===null)return{state:"in-flight"};const record=JSON.parse(stored);if(!isPending(record))return{state:"published",result:record};return record.pending===token?{state:"claimed",token}:{state:"in-flight"}}async complete(eventName,eventId,token,result){const key=this.keyOf(eventName,eventId);const answer=JSON.stringify(result);if(!await this.storage.setIfEquals(key,pendingRecordOf(token),answer))return;await this.storage.expireIfEquals(key,answer,PUBLISH_IDEMPOTENCY_WINDOW_SECONDS)}async release(eventName,eventId,token){await this.storage.deleteIfEquals(this.keyOf(eventName,eventId),pendingRecordOf(token))}keyOf(eventName,eventId){return RECORD_PREFIX4+sha256Hex27(JSON.stringify([this.scopeId,eventName,eventId])).slice(0,40)}}}});function assertPathFree(scope,path4){const reserved=computeReservedPaths(scope.entryPath,scope.routeBase,servedHealthPaths(scope.metadata.health));try{assertNotReserved("POST",path4,reserved)}catch(error){if(!(error instanceof ReservedRouteCollisionError))throw error;throw new EventPublishEndpointError(`events.publishEndpoint.path "${path4}" is on the reserved FrontMCP path "${error.reserved}": choose another path`)}const routes=[...scope.httpRouteTable?.routes??[],...scope.metadata.http?.routes??[]];const taken=routes.find(route=>route.method.toUpperCase()==="POST"&&matchRoutePath(route.path,path4)!==void 0);if(taken){throw new EventPublishEndpointError(`events.publishEndpoint.path "${path4}" is already served by the route POST ${taken.path}: choose another path`)}}async function enablePublishEndpoint(args){const{scope,eventRegistry,identifiesCallers,keyPrefix,logger}=args;const{secret,authorities,path:configuredPath}=eventRegistry.config.publishEndpoint;const{store:storeConfig}=eventRegistry.config;if(!secret&&!identifiesCallers){throw new EventPublishEndpointError("the server runs in public auth mode, so nothing tells who publishes. Set events.publishEndpoint.secret (at least 32 characters) for signed requests, or configure an auth mode that signs callers in.")}if(authorities!==void 0){assertEntryAuthorities(scope.authoritiesEngine,scope.authoritiesContextBuilder,[{label:"events.publishEndpoint",authorities}])}const path4=`${normalizeScopeBase(scope.routeBase)}${configuredPath}`;assertPathFree(scope,path4);let storage=eventRegistry.storage;if(!storage){const ownStorage=await openEventStorage({redis:storeConfig?.redis,sqlite:storeConfig?.sqlite,keyPrefix});scope.onDispose(()=>ownStorage.disconnect());storage=ownStorage}eventRegistry.publishEndpoint={path:path4,secret,authorities,replays:new WorkflowWebhookReplayGuard,idempotency:new EventPublishIdempotency(storage,scope.id)};await scope.registryFlows(EventPublishHttpFlow);logger.info(`Events can be published over HTTP: POST ${path4} (${secret?"signed requests":"bearer callers"})`);if(!secret&&authorities===void 0){logger.warn(`POST ${path4} lets every signed-in caller publish every event. Set events.publishEndpoint.authorities to name who may publish.`)}}var init_event_publish_endpoint=__esm({"libs/sdk/src/event/publish-endpoint/event-publish-endpoint.ts"(){"use strict";init_common();init_errors();init_flow_http_path();init_authorities_rules_check();init_health_routes();init_custom_routes_helper();init_workflow_webhook_signature();init_event_publish_http_flow();init_event_subscription_store_factory();init_event_publish_idempotency()}});import{generateWebhookMessageId as generateWebhookMessageId2,sha256Hex as sha256Hex28}from"@frontmcp/utils";function isSameReadPosition(current,expected){return current?.cursor===expected.cursor&&current.queuedAtCursor===expected.queuedAtCursor}function isSamePosition(current,expected){if(!current||current.cursor!==expected.cursor||current.pending.length!==expected.pending.length)return false;return current.pending.every((batch,index)=>batch.cursor===expected.pending[index].cursor)}var REPLAY_LEASE_MS,REPLAY_STOP_GRACE_MS,MAX_PENDING_BATCHES,MAX_ROUNDS_PER_TICK,encoder10,EventReplays;var init_event_replays=__esm({"libs/sdk/src/event/replay/event-replays.ts"(){"use strict";init_lease_holder();init_provider_lifecycle();init_event_dialect();init_event_publisher();REPLAY_LEASE_MS=3e4;REPLAY_STOP_GRACE_MS=3e3;MAX_PENDING_BATCHES=50;MAX_ROUNDS_PER_TICK=10;encoder10=new TextEncoder;EventReplays=class{constructor(options){this.options=options;this.logger=options.logger.child("EventReplays")}options;holders=new Map;timers=new Map;ticks=new Map;nextCheckAt=new Map;logger;isReplayable(event){return typeof event.create({}).check==="function"}async start(events){for(const event of events){const holder=new LeaseHolder({label:`Webhook delivery of event "${event.name}"`,key:`replay-lease:${sha256Hex28(event.name).slice(0,32)}`,leaseMs:REPLAY_LEASE_MS,storage:this.options.storage,logger:this.logger,onAcquired:()=>this.schedule(event,0),onLost:()=>this.unschedule(event.name)});this.holders.set(event.name,holder);await holder.start()}}async stop(){const stopping=[...this.holders].map(([eventName,holder])=>{this.unschedule(eventName);return holder.stop(()=>this.turnEnded(eventName))});await Promise.all(stopping);this.holders.clear()}async begin(event,record,cursor,maxAgeMs){const step=await this.advance(event,record,{cursor,watermark:cursor,pending:[]},maxAgeMs);await this.options.store.update(record.id,{replay:step.replay});if(step.failure)throw step.failure;return step}async refresh(record,replay){const{truncated,...settled}=await this.settled(replay);await this.options.store.update(record.id,current=>isSamePosition(current.replay,replay)?{replay:settled}:{});return{replay:settled,truncated:truncated===true,hasMore:false}}schedule(event,delayMs){if(this.timers.has(event.name)||this.ticks.has(event.name))return;const timer=setTimeout(()=>{this.timers.delete(event.name);const tick=this.tick(event).catch(error=>this.logger.warn(`The webhook loop of event "${event.name}" failed`,error)).finally(()=>{this.ticks.delete(event.name);if(this.isRunning(event.name))this.schedule(event,this.options.intervalMs)});this.ticks.set(event.name,tick)},delayMs);timer.unref?.();this.timers.set(event.name,timer)}async turnEnded(eventName){const turn=this.ticks.get(eventName);if(!await outlasts(()=>turn,REPLAY_STOP_GRACE_MS))return true;this.logger.warn(`The webhook loop of event "${eventName}" did not end within ${REPLAY_STOP_GRACE_MS} ms; its lease expires by itself`);return false}isRunning(eventName){const holder=this.holders.get(eventName);return holder!==void 0&&holder.holding&&!holder.stopping}unschedule(eventName){const timer=this.timers.get(eventName);if(timer)clearTimeout(timer);this.timers.delete(eventName)}async tick(event){const subscriptions=await this.options.store.listByEvent(event.name);for(const record of subscriptions){if(!this.isRunning(event.name))return;if(!record.active||!record.replay)continue;if((this.nextCheckAt.get(record.id)??0)>Date.now())continue;try{if(await this.isStillAuthorized(event,record))await this.readFor(event,record,record.replay)}catch(error){this.logger.warn(`The webhook loop of event "${event.name}" failed for subscription ${record.id}`,error)}}}async isStillAuthorized(event,record){const now=Date.now();if(now-record.lastAuthorizedAt<=this.options.reauthorizeEveryMs)return true;const check=await this.options.reauthorize(event,record).catch(error=>({outcome:"failed",error}));if(check.outcome==="granted"){await this.options.store.update(record.id,{lastAuthorizedAt:now});return true}if(check.outcome==="failed"){this.logger.warn(`The access of subscription ${record.id} could not be checked`,check.error);return false}this.nextCheckAt.delete(record.id);await this.options.terminate(record);return false}async readFor(event,record,from){let replay=from;try{for(let round=0;round<MAX_ROUNDS_PER_TICK&&this.isRunning(event.name);round++){const step=await this.advance(event,record,replay,void 0);replay=step.truncated?{...step.replay,truncated:true}:step.replay;if(step.failure)throw step.failure;if(step.truncated)replay=await this.reportGap(record,replay);this.nextCheckAt.set(record.id,Date.now()+(step.nextPollMs??this.options.intervalMs));if(!step.hasMore)break}}finally{if(replay!==from)await this.storeReplay(event.name,record.id,from,replay)}}async storeReplay(eventName,subscriptionId,from,replay){const holder=this.holders.get(eventName);if(!holder?.holding||!await holder.renew())return;await this.options.store.update(subscriptionId,current=>isSameReadPosition(current.replay,from)?{replay}:{})}async reportGap(record,replay){if(!EVENT_DIALECTS[record.dialect].sendsControlEnvelopes)return{...replay,truncated:true};await this.options.outbox.enqueue({kind:"gap",subscriptionId:record.id,eventName:record.eventName,body:JSON.stringify({type:"gap",cursor:replay.watermark}),webhookId:generateWebhookMessageId2("gap")});const{truncated:_told,...told}=replay;return told}async advance(event,record,replay,maxAgeMs){const settled=await this.settled(replay);if(settled.pending.length>=MAX_PENDING_BATCHES)return{replay:settled,truncated:false,hasMore:false};const floor=settled.cursor!==null&&maxAgeMs!==void 0?Date.now()-maxAgeMs:void 0;const checked=await this.check(event,record,settled.cursor,floor===void 0?void 0:maxAgeMs);if(!checked)return{replay:settled,truncated:false,hasMore:false};const alreadyQueued=settled.queuedAtCursor??0;const deliveryIds=[];let skippedOldEvents=false;for(const[index,item]of checked.events.entries()){if(index<alreadyQueued)continue;const timestamp=item.timestamp??new Date().toISOString();if(floor!==void 0&&Date.parse(timestamp)<floor){skippedOldEvents=true;continue}try{const deliveryId=await this.enqueue(event,record,item,timestamp,settled.watermark);if(deliveryId)deliveryIds.push(deliveryId)}catch(failure){return{replay:this.partlyQueued(settled,index,deliveryIds),truncated:false,hasMore:false,failure}}}const{queuedAtCursor:_queued,...read}=settled;const batches=[...read.pending,{cursor:checked.cursor,deliveryIds}];return{replay:await this.settled({...read,cursor:checked.cursor,pending:batches}),truncated:checked.truncated===true||skippedOldEvents,hasMore:checked.hasMore===true,nextPollMs:checked.nextPollMs}}partlyQueued(settled,index,deliveryIds){const pending=deliveryIds.length>0?[...settled.pending,{cursor:settled.cursor,deliveryIds}]:settled.pending;return{...settled,pending,queuedAtCursor:index}}async check(event,record,cursor,maxAgeMs){const context=event.create({});const check=context.check;const limits={maxEvents:this.options.maxEvents,...maxAgeMs!==void 0&&{maxAgeMs}};try{return await check.call(context,record.arguments,cursor,limits)}catch(error){this.logger.warn(`check() of event "${event.name}" failed for subscription ${record.id}`,error);return void 0}}async enqueue(event,record,item,timestamp,watermark){let data;try{data=event.parsePayload(item.data)}catch(error){this.logger.warn(`check() of event "${event.name}" returned data that is not its payload`,error);return void 0}const eventId=item.eventId??newEventId();const body=JSON.stringify({eventId,name:event.name,timestamp,data,cursor:watermark});const bytes=encoder10.encode(body).byteLength;if(bytes>this.options.maxBodyBytes){this.logger.warn(`Event "${event.name}" is ${bytes} bytes for subscription ${record.id}, over the ${this.options.maxBodyBytes} byte limit; it is not delivered`);return void 0}const usesEventId=EVENT_DIALECTS[record.dialect].webhookId==="eventId";return this.options.outbox.enqueue({kind:"event",subscriptionId:record.id,eventName:event.name,body,webhookId:usesEventId?eventId:generateWebhookMessageId2()})}async settled(replay){const pending=[...replay.pending];let{watermark}=replay;while(pending.length>0){const[oldest]=pending;const stillPending=await Promise.all(oldest.deliveryIds.map(id=>this.options.outbox.isPending(id)));if(stillPending.some(Boolean))break;watermark=oldest.cursor;pending.shift()}return{...replay,watermark,pending}}}}});import{EventOccurrenceSchema as EventOccurrenceSchema6}from"@frontmcp/protocol";import{randomUUID as randomUUID31}from"@frontmcp/utils";function parseRelayed(message){let parsed;try{parsed=JSON.parse(message)}catch{return void 0}if(typeof parsed!=="object"||parsed===null)return void 0;const{origin,occurrence,audience,subscriptionId}=parsed;const checked=EventOccurrenceSchema6.safeParse(occurrence);if(typeof origin!=="string"||!checked.success)return void 0;if(subscriptionId!==void 0&&typeof subscriptionId!=="string")return void 0;if(audience!==void 0&&(typeof audience!=="object"||audience===null))return void 0;return{origin,occurrence:checked.data,audience,subscriptionId}}var EVENT_RELAY_CHANNEL,MAX_OPEN_STREAMS,EventStreams;var init_event_streams=__esm({"libs/sdk/src/event/stream/event-streams.ts"(){"use strict";EVENT_RELAY_CHANNEL="occurrences";MAX_OPEN_STREAMS=1e4;EventStreams=class{constructor(options){this.options=options;this.nodeId=randomUUID31();this.logger=options.logger.child("EventStreams")}options;streams=new Map;held=new Set;nodeId;logger;stopRelay;get isRelayed(){return this.options.storage?.supportsPubSub()===true}get size(){return this.held.size}async start(){const{storage}=this.options;if(!storage||!this.isRelayed)return;this.stopRelay=await storage.subscribe(EVENT_RELAY_CHANNEL,message=>this.receive(message))}async stop(){await this.stopRelay?.();this.stopRelay=void 0;for(const streams of[...this.streams.values()]){for(const stream of[...streams])stream.close()}}isFull(principalKey){if(this.held.size>=MAX_OPEN_STREAMS)return true;let heldByOwner=0;for(const stream of this.held){if(stream.principalKey===principalKey)heldByOwner+=1}return heldByOwner>=this.options.maxPerPrincipal}reserve(stream){if(this.held.has(stream))return true;if(this.isFull(stream.principalKey))return false;this.hold(stream);return true}add(stream){this.hold(stream);if(stream.isClosed)return;const streams=this.streams.get(stream.eventName)??new Set;this.streams.set(stream.eventName,streams);streams.add(stream)}hold(stream){if(this.held.has(stream)||stream.isClosed)return;this.held.add(stream);stream.onClose(()=>{this.held.delete(stream);this.streams.get(stream.eventName)?.delete(stream)})}async publish(buffered){await this.deliver(buffered);const{storage}=this.options;if(!storage||!this.isRelayed)return;const{occurrence,audience,subscriptionId}=buffered;const relayed={origin:this.nodeId,occurrence,audience,subscriptionId};try{await storage.publish(EVENT_RELAY_CHANNEL,JSON.stringify(relayed))}catch(error){this.logger.warn(`Event "${occurrence.name}" was not relayed to the other processes`,error)}}async deliver(buffered){const streams=this.streams.get(buffered.occurrence.name);if(!streams)return;await Promise.all([...streams].map(stream=>stream.offer(buffered)))}receive(message){const relayed=parseRelayed(message);if(!relayed||relayed.origin===this.nodeId)return;const buffered=this.options.buffer.append(relayed.occurrence,relayed.audience,relayed.subscriptionId);this.deliver(buffered).catch(error=>this.logger.warn("A relayed event was not delivered",error))}}}});import{MCP_SUBSCRIPTION_ID_HEADER as MCP_SUBSCRIPTION_ID_HEADER3,MCP_WEBHOOK_RECEIVER_WELL_KNOWN_PATH}from"@frontmcp/protocol";import{base64urlEncode as base64urlEncode7,generateWebhookMessageId as generateWebhookMessageId3,outboundFailureCategory as outboundFailureCategory2,randomBytes as randomBytes8,sendOutboundRequest as sendOutboundRequest2,sha256Hex as sha256Hex29,signingKeyOf as signingKeyOf3,timingSafeEqual as timingSafeEqual5,webhookSignatureHeaders as webhookSignatureHeaders2}from"@frontmcp/utils";function isSameText(left,right){const leftBytes=encoder11.encode(left);const rightBytes=encoder11.encode(right);return leftBytes.length===rightBytes.length&&timingSafeEqual5(leftBytes,rightBytes)}function isUnderAllowedPrefix(callback,prefix){if(!URL.canParse(prefix))return false;const allowed=new URL(prefix);if(allowed.origin!==callback.origin)return false;if(callback.pathname===allowed.pathname)return true;const directory=allowed.pathname.endsWith("/")?allowed.pathname:`${allowed.pathname}/`;return callback.pathname.startsWith(directory)}function receiversOf(result){if(!result.answered||result.status!==200||result.bodyTruncated)return[];try{const receivers=JSON.parse(result.body)?.receivers;if(!Array.isArray(receivers))return[];return receivers.filter(prefix=>typeof prefix==="string"&&prefix.startsWith("/"))}catch{return[]}}function challengeOf(answerBody){try{const challenge=JSON.parse(answerBody)?.challenge;return typeof challenge==="string"?challenge:void 0}catch{return void 0}}var VERIFICATION_ATTEMPTS_PER_HOST,VERIFICATION_WINDOW_MS,WELL_KNOWN_CACHE_MS,WELL_KNOWN_MAX_BYTES,CHALLENGE_BYTES,CHALLENGE_ANSWER_MAX_BYTES,MAX_CACHED_ENTRIES,encoder11,ExpiringMap,EventCallbackVerifier;var init_event_callback_verifier=__esm({"libs/sdk/src/event/subscription/event-callback-verifier.ts"(){"use strict";init_event_outbound();VERIFICATION_ATTEMPTS_PER_HOST=10;VERIFICATION_WINDOW_MS=6e4;WELL_KNOWN_CACHE_MS=3e5;WELL_KNOWN_MAX_BYTES=65536;CHALLENGE_BYTES=32;CHALLENGE_ANSWER_MAX_BYTES=4096;MAX_CACHED_ENTRIES=5e3;encoder11=new TextEncoder;ExpiringMap=class{entries=new Map;get(key,now){const entry=this.entries.get(key);if(!entry)return void 0;if(entry.expiresAt>now)return entry.value;this.entries.delete(key);return void 0}set(key,value,expiresAt){this.entries.delete(key);if(this.entries.size>=MAX_CACHED_ENTRIES){const oldestKey=this.entries.keys().next().value;if(oldestKey!==void 0)this.entries.delete(oldestKey)}this.entries.set(key,{value,expiresAt})}};EventCallbackVerifier=class{constructor(options){this.options=options;this.send=options.send??sendOutboundRequest2;this.maxAttemptsPerHost=options.maxAttemptsPerHost??VERIFICATION_ATTEMPTS_PER_HOST}options;verifiedPairs=new ExpiringMap;receiversByOrigin=new ExpiringMap;attemptsByHost=new ExpiringMap;send;maxAttemptsPerHost;async verify(request2){const now=Date.now();const{allowedCallbacks,cacheTtlMs}=this.options;const callback=new URL(request2.url);if(allowedCallbacks.some(prefix=>isUnderAllowedPrefix(callback,prefix))){return{outcome:"verified",verifiedAt:now}}const pairKey=sha256Hex29(`${request2.principalKey}
335
335
  ${request2.url}`);const earlierProof=this.verifiedPairs.get(pairKey,now)??request2.verifiedAt??void 0;if(earlierProof!==void 0&&now-earlierProof<cacheTtlMs){return{outcome:"verified",verifiedAt:earlierProof}}if(!this.takeAttempt(callback.hostname,now))return{outcome:"limited",max:this.maxAttemptsPerHost};const failure=await this.isDeclaredReceiver(callback,now)?void 0:await this.challenge(request2,now);if(failure)return{outcome:"failed",reason:failure};this.verifiedPairs.set(pairKey,now,now+cacheTtlMs);return{outcome:"verified",verifiedAt:now}}takeAttempt(host,now){const attempts=this.attemptsByHost.get(host,now);if(attempts===void 0){this.attemptsByHost.set(host,1,now+VERIFICATION_WINDOW_MS);return true}if(attempts>=this.maxAttemptsPerHost)return false;this.attemptsByHost.set(host,attempts+1,now+VERIFICATION_WINDOW_MS);return true}async isDeclaredReceiver(callback,now){let receivers=this.receiversByOrigin.get(callback.origin,now);if(!receivers){const result=await this.send({url:new URL(MCP_WEBHOOK_RECEIVER_WELL_KNOWN_PATH,callback.origin).toString(),method:"GET",timeoutMs:this.options.timeoutMs,maxResponseBytes:WELL_KNOWN_MAX_BYTES,...eventOutboundTargetOptions(this.options.allowLocal)});receivers=receiversOf(result);this.receiversByOrigin.set(callback.origin,receivers,now+WELL_KNOWN_CACHE_MS)}return receivers.some(prefix=>callback.pathname.startsWith(prefix))}async challenge(request2,now){const nonce=base64urlEncode7(randomBytes8(CHALLENGE_BYTES));const body=JSON.stringify({type:"verification",challenge:nonce});const message={id:generateWebhookMessageId3("verification"),timestamp:Math.floor(now/1e3),body};const result=await this.send({url:request2.url,method:"POST",headers:{"content-type":"application/json",[MCP_SUBSCRIPTION_ID_HEADER3]:request2.subscriptionId,...webhookSignatureHeaders2(message,[signingKeyOf3(request2.secret)])},body,timeoutMs:this.options.timeoutMs,maxResponseBytes:CHALLENGE_ANSWER_MAX_BYTES,...eventOutboundTargetOptions(this.options.allowLocal)});const category=outboundFailureCategory2(result);if(category)return category;if(!result.answered||result.bodyTruncated)return"challenge_failed";const echoed=challengeOf(result.body);return echoed!==void 0&&isSameText(echoed,nonce)?void 0:"challenge_failed"}}}});var event_scope_helper_exports={};__export(event_scope_helper_exports,{registerEventCapabilities:()=>registerEventCapabilities});import{isPublicMode as isPublicMode3}from"@frontmcp/auth";import{getRuntimeContext as getRuntimeContext28,sha256Hex as sha256Hex30}from"@frontmcp/utils";function eventsWithAuthorities(events){const guarded=[];for(const event of events){const authorities=event.getAuthorities();if(authorities!==void 0)guarded.push({label:`Event "${event.name}"`,authorities})}return guarded}function assertEventAuthorities2(scope,events){const guarded=eventsWithAuthorities(events);if(guarded.length===0)return;assertEntryAuthorities(scope.authoritiesEngine,scope.authoritiesContextBuilder,guarded)}function ignoreChannelOption(eventRegistry,logger){const ignoredEvents=eventRegistry.getChannelEvents().map(event=>`"${event.name}"`);eventRegistry.channelDelivery=false;if(ignoredEvents.length===0)return;logger.warn(`Channels are disabled (channels.enabled: false), so the channel option of ${ignoredEvents.length} event(s) is ignored: ${ignoredEvents.join(", ")}. Remove channels.enabled: false to send them to Claude Code sessions.`)}function describeEventChannels(scope,eventRegistry,logger){if(!eventRegistry.config.bridge)return;for(const channel2 of scope.channels?.getChannelInstances()??[]){const{source}=channel2.metadata;if(source.type!=="app-event")continue;const event=eventRegistry.findByName(source.event);if(!event)continue;if(eventRegistry.sendsToChannelSessions(event)){logger.warn(`Channel "${channel2.name}" listens to event "${event.name}", which has the channel option: Claude Code sessions get each occurrence twice, once from the event and once from the channel. Keep one: remove the channel, or the option when the channel does what the option cannot.`);continue}logger.info(`Channel "${channel2.name}" listens to event "${event.name}": the event has no channel option. Setting it can replace this channel, and checks each session's access.`)}}function canIdentifyCallers(scope){const authOptions=scope.auth?.options;return authOptions!==void 0&&!isPublicMode3(authOptions)}function storeKeyPrefixOf(scope,eventsConfig){const configuredPrefix=eventsConfig.store?.keyPrefix;if(configuredPrefix)return configuredPrefix;return`mcp:events:${sha256Hex30(`server:${scope.metadata.info.name}`).slice(0,16)}:`}async function outboxHealth(outbox){try{return{status:"healthy",details:{pendingDeliveries:await outbox.depth()}}}catch(error){return{status:"unhealthy",error:error instanceof Error?error.message:String(error)}}}async function startReplays(eventRegistry,replays,logger){const replayable=eventRegistry.getEvents().filter(event=>replays.isReplayable(event));if(replayable.length===0)return;if(isLongLivedProcess()){eventRegistry.replays=replays;await replays.start(replayable);return}for(const event of replayable)eventRegistry.withholdWebhookFrom(event.name);logger.warn(`${replayable.length} event(s) with check() are not offered by webhook here: delivering them needs a long-lived process, which a serverless, edge or browser runtime is not. They are offered by poll.`)}async function enableWebhookDelivery(scope,eventRegistry,eventsConfig,logger){const{webhook,store:storeConfig}=eventsConfig;const{store,durable,storage,secret}=await createEventSubscriptionStore({redis:storeConfig?.redis,sqlite:storeConfig?.sqlite,keyPrefix:storeKeyPrefixOf(scope,eventsConfig),logger});const verifier=new EventCallbackVerifier({allowedCallbacks:webhook.allowedCallbacks,allowLocal:webhook.unsafeAllowLocalCallbacks,cacheTtlMs:webhook.verification.cacheTtlMs,timeoutMs:webhook.verification.timeoutMs,maxAttemptsPerHost:webhook.verification.maxAttemptsPerHost});const subscriptions=new EventSubscriptions({events:eventRegistry,store,durable,verifier,settings:eventsConfig.subscriptions,rotationGraceMs:webhook.rotationGraceMs,logger});const outbox=new EventOutbox({storage,secret,durable,settings:webhook.delivery,attempt:delivery=>scope.runFlowForOutput("events:deliver",{delivery}),metrics:eventRegistry.metrics??createEventMetrics(void 0),logger});eventRegistry.subscriptions=subscriptions;eventRegistry.outbox=outbox;eventRegistry.storage=storage;await scope.registryFlows(EventDeliverFlow);subscriptions.start();outbox.start();const replays=new EventReplays({store,outbox,storage,intervalMs:eventsConfig.poll.nextPollMs,maxEvents:eventsConfig.poll.maxEvents,maxBodyBytes:EVENT_DELIVERY_MAX_BYTES,reauthorizeEveryMs:eventsConfig.subscriptions.reauthorizeEveryMs,reauthorize:(event,record)=>reauthorizeSubscriber({scope,event,subscriber:record.subscriber,arguments:record.arguments}),terminate:record=>terminateEventSubscription({subscriptions,outbox,metrics:eventRegistry.metrics,logger,subscription:record,error:accessRevokedError(record.dialect)}),logger});await startReplays(eventRegistry,replays,logger);scope.onDispose(async()=>{await replays.stop();await outbox.stop();await subscriptions.close()});scope.registerHealthProbe({name:"events-outbox",check:()=>outboxHealth(outbox)});if(webhook.unsafeAllowLocalCallbacks){logger.warn("events.webhook.unsafeAllowLocalCallbacks is on: callbacks may be http and local. Use it in tests only.")}eventRegistry.enableDeliveryMode("webhook");await scope.registryFlows(EventSubscribeFlow,EventUnsubscribeFlow);return storage}async function enablePollDelivery(scope,eventRegistry,eventsConfig,logger){const pollLeases=new EventPollLeases({maxPerPrincipal:eventsConfig.subscriptions.maxPerPrincipal,logger});eventRegistry.pollLeases=pollLeases;pollLeases.start();scope.onDispose(()=>pollLeases.stop());eventRegistry.enableDeliveryMode("poll");await scope.registryFlows(EventPollFlow);const readsBuffer=eventRegistry.getEvents().some(event=>typeof event.create({}).check!=="function");if(readsBuffer&&getRuntimeContext28().deployment==="serverless"){logger.warn("events/poll reads published events from the memory of the process that published them, which a serverless function does not keep between calls. Give those events a check(), or deliver them by webhook.")}}function canHoldStreams(){return getRuntimeContext28().deployment!=="serverless"}function describeUnrelayedStreams(scope,eventsConfig){const carried="Event streams carry what this process publishes.";if(!eventsConfig.store?.redis){return`${carried} With several processes, set events.store.redis so an event published on one reaches the streams the others hold.`}const reasons=[];if(!eventsConfig.webhook.enabled)reasons.push("events.webhook.enabled is false, so remove that setting");if(!canIdentifyCallers(scope)){reasons.push("the server runs in public auth mode, so configure an auth mode that signs callers in")}return`${carried} events.store.redis is set, but it relays events between processes only with webhook delivery, which is off: ${reasons.join("; ")}. Then an event published on one process reaches the streams the others hold.`}async function enableStreamDelivery(scope,eventRegistry,buffer,eventsConfig,storage,logger){const streams=new EventStreams({buffer,maxPerPrincipal:eventsConfig.subscriptions.maxPerPrincipal,storage:eventsConfig.store?.redis?storage:void 0,logger});eventRegistry.streams=streams;await streams.start();scope.onDispose(()=>streams.stop());if(!streams.isRelayed)logger.info(describeUnrelayedStreams(scope,eventsConfig));eventRegistry.enableDeliveryMode("push");await scope.registryFlows(EventStreamFlow)}async function registerEventCapabilities(args){const{providers,owner,eventsList,eventProviders,logger}=args;const eventsConfig=eventsConfigSchema.parse(args.eventsConfig??{});if(eventsConfig.enabled===false){logger.warn(`Events are disabled (events.enabled: false), so the ${eventsList.length} event(s) apps declare are not served. Remove events.enabled: false to serve them.`);return void 0}const scope=providers.getActiveScope();const eventRegistry=new EventRegistry(providers,eventsList,owner,eventsConfig,eventProviders);await eventRegistry.ready;assertEventAuthorities2(scope,eventRegistry.getEvents());if(args.channelsEnabled===false)ignoreChannelOption(eventRegistry,logger);describeEventChannels(scope,eventRegistry,logger);const publisher=new ScopeEventPublisher(scope,eventRegistry);eventRegistry.publisher=publisher;eventRegistry.metrics=createEventMetrics(scope.metadata.metrics);providers.injectProvider({provide:EVENT_PUBLISHER,value:publisher,metadata:{id:"frontmcp-event-publisher",name:"EventPublisher",scope:ProviderScope2.GLOBAL,description:"Publishes the events of the server to their subscribers."}});await scope.registryFlows(ListEventsFlow,EventPublishFlow);let storage;if(eventsConfig.webhook.enabled&&canIdentifyCallers(scope)){storage=await enableWebhookDelivery(scope,eventRegistry,eventsConfig,logger)}else if(eventsConfig.webhook.enabled){logger.warn("Webhook event delivery is off: the server runs in public auth mode, so a subscription would have no owner. Configure an auth mode that signs callers in to deliver events by webhook.")}const pushes=eventsConfig.push.enabled&&canHoldStreams();const buffer=eventsConfig.poll.enabled||pushes?new EventBuffer(eventsConfig.buffer):void 0;eventRegistry.buffer=buffer;if(eventsConfig.poll.enabled)await enablePollDelivery(scope,eventRegistry,eventsConfig,logger);if(buffer&&pushes)await enableStreamDelivery(scope,eventRegistry,buffer,eventsConfig,storage,logger);if(eventsConfig.publishEndpoint.enabled){await enablePublishEndpoint({scope,eventRegistry,identifiesCallers:canIdentifyCallers(scope),keyPrefix:storeKeyPrefixOf(scope,eventsConfig),logger})}logger.info(`Event system initialized: ${eventRegistry.getEvents().length} event(s)`);return{eventRegistry}}var init_event_scope_helper=__esm({"libs/sdk/src/event/event-scope.helper.ts"(){"use strict";init_common();init_event_metadata();init_event_tokens();init_lease_store();init_authorities_rules_check();init_event_metrics();init_event_outbox();init_event_publisher();init_event_reauthorization();init_event_registry();init_event_deliver_flow();init_event_poll_flow();init_event_publish_flow();init_event_stream_flow();init_event_subscribe_flow();init_event_unsubscribe_flow();init_list_events_flow();init_event_buffer();init_event_poll_leases();init_event_publish_endpoint();init_event_replays();init_event_streams();init_event_callback_verifier();init_event_subscription_store_factory();init_event_subscription_termination();init_event_subscriptions()}});import{noopLogger as noopLogger2,clientMetadataDocumentSchema,cimdCacheConfigSchema,cimdSecurityConfigSchema,cimdNetworkConfigSchema,cimdConfigSchema,CimdError,InvalidClientIdUrlError,CimdFetchError,CimdValidationError,CimdClientIdMismatchError,CimdSecurityError,RedirectUriMismatchError,CimdResponseTooLargeError,CimdDisabledError,isCimdClientId,validateClientIdUrl,checkSsrfProtection,hasOnlyLocalhostRedirectUris,InMemoryCimdCache,extractCacheHeaders,parseCacheHeaders,CimdService}from"@frontmcp/auth";var init_cimd=__esm({"libs/sdk/src/auth/cimd/index.ts"(){"use strict"}});import{CREDENTIALS_ACCESSOR as CREDENTIALS_ACCESSOR2,CredentialsAccessorImpl}from"@frontmcp/auth";import{ProviderScope as ProviderScope9}from"@frontmcp/di";function resolveRequestSub(ctx){const extra=ctx.authInfo?.extra;const sub=extra?.user?.sub;if(typeof sub!=="string"||sub.length===0||sub.startsWith("anon:")){return void 0}return sub}function createCredentialsProviders(opts){const{vault,signingSecret,basePath,resumeTtlMs}=opts;const vaultProvider={provide:SESSION_CREDENTIAL_VAULT,useValue:vault,scope:ProviderScope9.GLOBAL,name:"SessionCredentialVault"};const accessorProvider={provide:CREDENTIALS_ACCESSOR2,inject:()=>[FRONTMCP_CONTEXT,FrontMcpLogger],useFactory:(ctx,logger)=>new CredentialsAccessorImpl({vault,resolveSub:()=>resolveRequestSub(ctx),signingSecret,basePath,resumeTtlMs,logger:logger.child("CredentialsAccessor")}),scope:ProviderScope9.CONTEXT,name:"CredentialsAccessor"};return[vaultProvider,accessorProvider]}var SESSION_CREDENTIAL_VAULT;var init_credentials_providers=__esm({"libs/sdk/src/auth/credentials/credentials.providers.ts"(){"use strict";init_common();init_frontmcp_context_provider();SESSION_CREDENTIAL_VAULT=Symbol.for("frontmcp:SESSION_CREDENTIAL_VAULT")}});import{CREDENTIALS_ACCESSOR as CREDENTIALS_ACCESSOR3}from"@frontmcp/auth";var credentialsContextExtension;var init_credentials_context_extension=__esm({"libs/sdk/src/auth/credentials/credentials.context-extension.ts"(){"use strict";credentialsContextExtension={property:"credentials",token:CREDENTIALS_ACCESSOR3,errorMessage:"Per-session credentials are not available. Ensure the server uses auth mode 'local' (or 'remote'); credentials are persisted by a local authenticate() verifier."}}});var init_credentials=__esm({"libs/sdk/src/auth/credentials/index.ts"(){"use strict";init_credentials_providers()}});var AUTH_FLOW_GLOBAL_KEY,AUTH_MOUNT_ID,AUTH_WIRE_FIELDS;var init_auth_ui_contract=__esm({"libs/sdk/src/auth/auth-ui/auth-ui.contract.ts"(){"use strict";AUTH_FLOW_GLOBAL_KEY="__FRONTMCP_AUTH__";AUTH_MOUNT_ID="frontmcp-auth-root";AUTH_WIRE_FIELDS={federated:"federated",incremental:"incremental",appId:"app_id"}}});import{isAbsolute as isAbsolute4,pathResolve as pathResolve7,randomBytes as randomBytes9,sha256Hex as sha256Hex31}from"@frontmcp/utils";function timingSafeEqualStr(a,b){if(a.length!==b.length)return false;let diff=0;for(let i=0;i<a.length;i++){diff|=a.charCodeAt(i)^b.charCodeAt(i)}return diff===0}var ALL_SLOTS,PENDING_UI_TTL_MS,MAX_ITEMS_PER_EXTRA,AuthUiRegistry;var init_auth_ui_registry=__esm({"libs/sdk/src/auth/auth-ui/auth-ui.registry.ts"(){"use strict";ALL_SLOTS=["login","consent","incremental","federated","error"];PENDING_UI_TTL_MS=10*60*1e3;MAX_ITEMS_PER_EXTRA=100;AuthUiRegistry=class{slots=new Map;extras=new Map;pending=new Map;logger;resolverOverrides;constructor(logger){this.logger=logger?.child("AuthUiRegistry")}registerAuthUiMap(map,sourceDir){if(!map)return;for(const[slotKey2,rawPath]of Object.entries(map)){const slot=slotKey2;if(!ALL_SLOTS.includes(slot)){throw new Error(`auth.ui slot "${slot}" is not one of: ${ALL_SLOTS.join(", ")}.`)}if(typeof rawPath!=="string"||rawPath.length===0)continue;const file=isAbsolute4(rawPath)?rawPath:pathResolve7(sourceDir,rawPath);this.slots.set(slot,{file});this.logger?.verbose(`Registered auth.ui slot "${slot}" \u2192 ${file}`)}}registerAuthExtrasMap(map){if(!map)return;for(const[name59,handler]of Object.entries(map)){if(typeof handler!=="function"){throw new Error(`auth.extras["${name59}"] must be a handler function (input, ctx) => AuthExtraResult.`)}this.extras.set(name59,handler);this.logger?.verbose(`Registered auth.extras handler "${name59}"`)}}setResolverOverrides(overrides){this.resolverOverrides=overrides}getResolverOverrides(){return this.resolverOverrides}hasAny(){return this.slots.size>0}hasSlot(slot){return this.slots.has(slot)}hasExtras(){return this.extras.size>0}getSlotSource(slot){const entry=this.slots.get(slot);if(!entry||entry.error)return void 0;return{file:entry.file}}canRenderSlot(slot){return this.getSlotSource(slot)!==void 0}recordSlotError(slot,message){const entry=this.slots.get(slot);if(entry&&!entry.error){entry.error=message;this.logger?.error(`Failed to build auth.ui page for slot "${slot}": ${message}`)}}mintCsrf(pendingAuthId){const existing=this.pending.get(pendingAuthId);if(existing)return existing.csrf;const csrf=sha256Hex31(randomBytes9(32)).slice(0,43);this.pending.set(pendingAuthId,{csrf,addedItems:{},createdAt:Date.now()});this.pruneExpired();return csrf}getActivePending(pendingAuthId){const state=this.pending.get(pendingAuthId);if(!state)return void 0;if(Date.now()-state.createdAt>PENDING_UI_TTL_MS){this.pending.delete(pendingAuthId);return void 0}return state}verifyCsrf(pendingAuthId,submitted){if(!pendingAuthId||!submitted)return false;const state=this.getActivePending(pendingAuthId);if(!state)return false;return timingSafeEqualStr(state.csrf,submitted)}getAddedItems(pendingAuthId){if(!pendingAuthId)return{};const state=this.pending.get(pendingAuthId);if(!state)return{};return Object.fromEntries(Object.entries(state.addedItems).map(([name59,items])=>[name59,[...items]]))}appendItems(pendingAuthId,extraName2,items){const state=this.ensurePending(pendingAuthId);const current=state.addedItems[extraName2]??[];state.addedItems[extraName2]=[...current,...items];return{...state.addedItems}}ensurePending(pendingAuthId){let state=this.pending.get(pendingAuthId);if(!state){state={csrf:sha256Hex31(randomBytes9(32)).slice(0,43),addedItems:{},createdAt:Date.now()};this.pending.set(pendingAuthId,state);this.pruneExpired()}return state}pruneExpired(){const now=Date.now();for(const[id,state]of this.pending){if(now-state.createdAt>PENDING_UI_TTL_MS)this.pending.delete(id)}}hasExtra(name59){return this.extras.has(name59)}async runExtra(name59,pendingAuthId,input){const handler=this.extras.get(name59);if(!handler){return{ok:false,error:`Unknown extra "${name59}".`}}const ctx={name:name59,pendingAuthId,current:pendingAuthId?this.getAddedItems(pendingAuthId)[name59]??[]:[]};let result;try{result=await handler(input,ctx)}catch(err){this.logger?.error(`auth.extras["${name59}"] handler threw: ${err instanceof Error?err.message:String(err)}`);return{ok:false,error:"Validation failed. Please try again."}}if(!result||typeof result.ok!=="boolean"){this.logger?.error(`auth.extras["${name59}"] returned a malformed result.`);return{ok:false,error:"Validation failed. Please try again."}}if(result.ok&&pendingAuthId&&Array.isArray(result.addedItems)&&result.addedItems.length>0){if(ctx.current.length+result.addedItems.length>MAX_ITEMS_PER_EXTRA){return{ok:false,error:`This list holds at most ${MAX_ITEMS_PER_EXTRA} items.`,addedItems:this.getAddedItems(pendingAuthId)}}const addedItems=this.appendItems(pendingAuthId,name59,result.addedItems);return{ok:true,sideEffects:result.sideEffects,addedItems}}return{ok:result.ok,error:result.error,sideEffects:result.sideEffects,...pendingAuthId?{addedItems:this.getAddedItems(pendingAuthId)}:{}}}async warmup(){if(!this.hasAny())return;for(const slot of this.slots.keys()){if(this.getSlotSource(slot)){this.logger?.verbose(`Validated auth.ui source for slot "${slot}"`)}}}}}});import{createResolverWithOverrides,renderComponent}from"@frontmcp/uipack";var init_uipack_render=__esm({"libs/sdk/src/third-party/uipack-render.ts"(){"use strict"}});function authUiExtraPath(fullPath){return`${fullPath.replace(/\/+$/,"")}/oauth/ui/extra`}function formActionSource(target){let url;try{url=new URL(target)}catch{return void 0}if(url.protocol==="http:"||url.protocol==="https:"){return url.hostname.startsWith("[")?void 0:url.origin}if(!/^[a-z][a-z0-9+.-]*:$/.test(url.protocol)||UNSAFE_FORM_TARGET_SCHEMES.has(url.protocol))return void 0;return url.protocol}function authUiCsp(formTargets=[]){const formAction=new Set(["'self'"]);for(const target of formTargets){const source=formActionSource(target);if(source)formAction.add(source)}return["default-src 'self'","script-src 'self' 'unsafe-inline' https://esm.sh","connect-src 'self' https://esm.sh","style-src 'self' 'unsafe-inline' https://esm.sh","img-src 'self' data: https:","frame-ancestors 'none'","base-uri 'self'",`form-action ${[...formAction].join(" ")}`].join("; ")}function authUiPageHeaders(csp=AUTH_UI_CSP){return{"Content-Security-Policy":csp,"X-Frame-Options":"DENY","X-Content-Type-Options":"nosniff","Referrer-Policy":"same-origin","Cache-Control":"no-store"}}function authUiSecurityHeaders(){return authUiPageHeaders(AUTH_UI_CSP)}function authMountDescriptor(){return{moduleSpecifier:"@frontmcp/ui/auth",generate:exportName=>`
336
336
  import { mountAuthPage as __mountAuthPage } from '@frontmcp/ui/auth';
337
337
  __mountAuthPage(${exportName});`,mountNodeId:AUTH_MOUNT_ID,mountNodeInnerHtml:"<noscript>This authorization page requires JavaScript.</noscript>"}}function buildAuthUiPage(options){const{registry,slot,state}=options;const source=registry.getSlotSource(slot);if(!source)return void 0;try{const overrides=registry.getResolverOverrides();const shellConfig={toolName:"auth-ui",withShell:true,includeBridge:false,title:options.title??defaultTitle(slot),csp:{connectDomains:["https://esm.sh"],resourceDomains:["https://esm.sh"]},mount:authMountDescriptor(),dataInjection:{globalKey:AUTH_FLOW_GLOBAL_KEY,value:state},...overrides?{resolver:createResolverWithOverrides(overrides)}:{}};const result=renderComponent({source:{file:source.file},transformOnly:true},shellConfig);return{html:result.html,headers:authUiPageHeaders(authUiCsp(options.formTargets))}}catch(err){registry.recordSlotError(slot,err instanceof Error?err.message:String(err));return void 0}}function defaultTitle(slot){switch(slot){case"login":return"Sign In";case"consent":return"Authorize Access";case"incremental":return"Authorize Application";case"federated":return"Choose a Provider";case"error":return"Authorization Error";default:return"Authorization"}}var UNSAFE_FORM_TARGET_SCHEMES,AUTH_UI_CSP;var init_auth_ui_render=__esm({"libs/sdk/src/auth/auth-ui/auth-ui.render.ts"(){"use strict";init_uipack_render();init_auth_ui_contract();UNSAFE_FORM_TARGET_SCHEMES=new Set(["javascript:","data:","blob:","filesystem:","about:","file:"]);AUTH_UI_CSP=authUiCsp()}});function buildLoginState(common,data){return{slot:"login",pendingAuthId:common.pendingAuthId,clientId:data.clientId,clientName:data.clientName??data.clientId,scopes:data.scopes,redirectUri:data.redirectUri,csrfToken:common.csrfToken,submitUrl:common.submitUrl,submitMethod:SUBMIT_METHOD,extraUrl:common.extraUrl,addedItems:common.addedItems,...data.logoUri?{extras:{logoUri:data.logoUri}}:{}}}function buildConsentState(common,data){return{slot:"consent",pendingAuthId:common.pendingAuthId,clientId:data.clientId,clientName:data.clientName??data.clientId,redirectUri:data.redirectUri,tools:data.tools,csrfToken:common.csrfToken,submitUrl:common.submitUrl,submitMethod:SUBMIT_METHOD,extraUrl:common.extraUrl,addedItems:common.addedItems}}function buildFederatedState(common,data){return{slot:"federated",pendingAuthId:common.pendingAuthId,clientId:data.clientId,clientName:data.clientName??data.clientId,redirectUri:data.redirectUri,providers:data.providers,csrfToken:common.csrfToken,submitUrl:common.submitUrl,submitMethod:SUBMIT_METHOD,extraUrl:common.extraUrl,addedItems:common.addedItems,extras:{[AUTH_WIRE_FIELDS.federated]:true,...data.step?{step:data.step}:{}}}}function buildIncrementalState(common,data){return{slot:"incremental",pendingAuthId:common.pendingAuthId,redirectUri:data.redirectUri,csrfToken:common.csrfToken,submitUrl:common.submitUrl,submitMethod:SUBMIT_METHOD,extraUrl:common.extraUrl,addedItems:common.addedItems,extras:{[AUTH_WIRE_FIELDS.incremental]:true,[AUTH_WIRE_FIELDS.appId]:data.appId,appName:data.appName,appDescription:data.appDescription,toolId:data.toolId}}}function buildErrorState(data){return{slot:"error",error:data.error,...data.pendingAuthId?{pendingAuthId:data.pendingAuthId}:{}}}var SUBMIT_METHOD;var init_auth_ui_state=__esm({"libs/sdk/src/auth/auth-ui/auth-ui.state.ts"(){"use strict";init_auth_ui_contract();SUBMIT_METHOD="POST"}});var auth_ui_exports={};__export(auth_ui_exports,{AUTH_FLOW_GLOBAL_KEY:()=>AUTH_FLOW_GLOBAL_KEY,AUTH_MOUNT_ID:()=>AUTH_MOUNT_ID,AUTH_UI_CSP:()=>AUTH_UI_CSP,AuthUiRegistry:()=>AuthUiRegistry,authUiExtraPath:()=>authUiExtraPath,authUiPageHeaders:()=>authUiPageHeaders,authUiSecurityHeaders:()=>authUiSecurityHeaders,buildAuthUiPage:()=>buildAuthUiPage,buildConsentState:()=>buildConsentState,buildErrorState:()=>buildErrorState,buildFederatedState:()=>buildFederatedState,buildIncrementalState:()=>buildIncrementalState,buildLoginState:()=>buildLoginState});var init_auth_ui=__esm({"libs/sdk/src/auth/auth-ui/index.ts"(){"use strict";init_auth_ui_contract();init_auth_ui_registry();init_auth_ui_render();init_auth_ui_state()}});function effectiveToolId(metadata){return metadata.id??metadata.name}function projectConsentTools(scope,excludedTools){const excluded=new Set(excludedTools??[]);const apps=scope.apps.getApps();const appNameById=new Map;for(const app of apps){const appId=app.id??app.metadata?.id;if(appId)appNameById.set(appId,app.metadata?.name??appId)}const toolCards=[];const availableToolIds=[];for(const tool of scope.tools.getTools()){const id=effectiveToolId(tool.metadata);if(excluded.has(id))continue;const appId=tool.owner?.id??"app";toolCards.push({toolId:id,toolName:tool.metadata.name,description:tool.metadata.description,appId,appName:appNameById.get(appId)??appId});availableToolIds.push(id)}return{toolCards,availableToolIds}}var init_consent_tools_helper=__esm({"libs/sdk/src/auth/consent-tools.helper.ts"(){"use strict"}});import{isOrchestratedMode as isOrchestratedMode3}from"@frontmcp/auth";function allowsSkippingApps(authOptions){return!(authOptions&&isOrchestratedMode3(authOptions)&&authOptions.incrementalAuth?.allowSkip===false)}function requiredProviderIds(authOptions,apps){if(!authOptions||!isOrchestratedMode3(authOptions))return[];const configured=authOptions.federatedAuth?.requiredProviders??[];if(allowsSkippingApps(authOptions))return configured;const appProviderIds=apps.filter(app=>app.metadata.auth).map(app=>app.metadata.id||app.metadata.name||"").filter(Boolean);return[...new Set([...configured,...appProviderIds])]}var init_required_providers_utils=__esm({"libs/sdk/src/auth/required-providers.utils.ts"(){"use strict"}});import{buildFederatedStepPage,builtInAuthPageHeaders}from"@frontmcp/auth";import{base64urlEncode as base64urlEncode8,randomBytes as randomBytes10}from"@frontmcp/utils";function showsProvidersStepByStep(authOptions){return!!authOptions&&isOrchestratedMode(authOptions)&&authOptions.incrementalAuth?.showAllAppsAtOnce===false}function getConfiguredProviders(auth){const providers=auth?.providers;if(!Array.isArray(providers)){return[]}return providers.filter(p=>!!p&&typeof p.id==="string")}function pickerProviders(scope){const authOptions=scope.metadata.auth;const providers=[];const configuredProviders=getConfiguredProviders(authOptions);for(const p of configuredProviders){providers.push({id:p.id,mode:"local",appIds:[p.id],scopes:p.scopes??[],isParentProvider:false})}if(configuredProviders.length===0&&authOptions&&isOrchestratedMode(authOptions)){providers.push({id:"__parent__",mode:authOptions.mode,appIds:["__parent__"],scopes:[],isParentProvider:true})}for(const app of scope.apps.getApps()){const appAuth=app.metadata.auth;if(!appAuth)continue;const appId=app.metadata.id||app.metadata.name;if(providers.some(p=>p.id===appId))continue;providers.push({id:appId,providerUrl:appAuth.mode==="transparent"?appAuth.provider:void 0,mode:appAuth.mode,appIds:[appId],scopes:[],isParentProvider:false})}return providers}function toAuthProvider(provider){return{id:provider.id,name:provider.id,url:provider.providerUrl,mode:provider.mode,appIds:provider.appIds.filter(id=>id!=="__parent__"),primary:provider.isParentProvider}}function startFederatedSteps(record,scope){if(!record.federatedLogin)return;record.federatedLogin.currentStep=0;record.federatedLogin.selectedProviderIds=[];record.federatedLogin.skippedProviderIds=[];record.authUiCsrf??=scope.authUi?.mintCsrf(record.id)??base64urlEncode8(randomBytes10(32))}function answerFederatedStep(record,answer,rules){const federatedLogin=record.federatedLogin;const current=federatedLogin?.currentStep;if(!federatedLogin||current===void 0)return{kind:"refuse",message:"Invalid provider selection"};if(answer.step!==String(current))return{kind:"show"};const action=answer.action;if(action!=="continue"&&action!=="skip"&&action!=="back"){return{kind:"refuse",message:"Invalid step action"}}if(action==="back"){federatedLogin.currentStep=Math.max(0,current-1);return{kind:"show"}}const{providerIds}=federatedLogin;const providerId=providerIds[current];const linked=(federatedLogin.selectedProviderIds??[]).filter(id=>id!==providerId);const skipped=(federatedLogin.skippedProviderIds??[]).filter(id=>id!==providerId);if(action==="skip"){if(rules.requiredProviderIds.includes(providerId)){return{kind:"refuse",message:`Required provider(s) not linked: ${providerId}`}}const stillLinkable=providerIds.length-current-1;if(linked.length+stillLinkable<rules.minProviders){const plural=rules.minProviders===1?"":"s";return{kind:"refuse",message:`At least ${rules.minProviders} provider${plural} must be linked`}}}federatedLogin.selectedProviderIds=action==="continue"?[...linked,providerId]:linked;federatedLogin.skippedProviderIds=action==="skip"?[...skipped,providerId]:skipped;if(current<providerIds.length-1){federatedLogin.currentStep=current+1;return{kind:"show"}}const selected=federatedLogin.selectedProviderIds;return{kind:"done",selectedProviderIds:providerIds.filter(id=>selected.includes(id))}}function renderFederatedStep(scope,record,options){const federatedLogin=record.federatedLogin;const providerIds=federatedLogin?.providerIds??[];const index=federatedLogin?.currentStep??0;const providerId=providerIds[index]??"";const providers=pickerProviders(scope);const provider=providers.find(p=>p.id===providerId);const required=requiredProviderIds(scope.auth?.options,scope.apps.getApps());const decision=federatedLogin?.selectedProviderIds?.includes(providerId)?"continue":federatedLogin?.skippedProviderIds?.includes(providerId)?"skip":void 0;const step={index,count:providerIds.length,providerId,last:index===providerIds.length-1,canGoBack:index>0,canSkip:!required.includes(providerId),...decision?{decision}:{}};const csrfToken=record.authUiCsrf??"";const submitUrl=`${oauthBasePath(scope)}/oauth/callback`;const authUi=scope.authUi;if(authUi?.hasSlot("federated")){const state=buildFederatedState({pendingAuthId:record.id,submitUrl,extraUrl:authUiExtraPath(scope.fullPath),csrfToken,addedItems:authUi.getAddedItems(record.id)},{clientId:record.clientId,clientName:options.clientName,redirectUri:record.redirectUri,providers:providers.map(toAuthProvider),step});const page2=buildAuthUiPage({registry:authUi,slot:"federated",state,fullPath:scope.fullPath,formTargets:[record.redirectUri,...providerAuthorizationEndpoints(scope,providerIds)]});if(page2)return httpRespond.html(page2.html,200,page2.headers)}const markup=buildFederatedStepPage({provider:{providerId,providerName:providerId,providerUrl:provider?.providerUrl,mode:provider?.mode??"unknown",appIds:(provider?.appIds??[]).filter(id=>id!=="__parent__"),isPrimary:provider?.isParentProvider,required:!step.canSkip},step,clientName:options.clientName,pendingAuthId:record.id,callbackPath:submitUrl,csrfToken,error:options.error});return httpRespond.html(markup,200,builtInAuthPageHeaders())}function providerAuthorizationEndpoints(scope,providerIds){const localAuth=scope.auth;if(typeof localAuth?.getProviderConfig!=="function")return[];const endpoints=[];for(const id of providerIds){const endpoint=localAuth.getProviderConfig(id)?.authorizationEndpoint;if(endpoint)endpoints.push(endpoint)}return endpoints}var FEDERATED_STEP_FIELD;var init_federated_steps=__esm({"libs/sdk/src/auth/federated-steps.ts"(){"use strict";init_common();init_flow_http_path();init_auth_ui();init_required_providers_utils();FEDERATED_STEP_FIELD="federated_step"}});import{createSigninBinding,SIGNIN_BINDING_MAX_AGE_SECONDS,signinBindingCookieName,signinBindingMatches}from"@frontmcp/auth";import{isSecureRequest}from"@frontmcp/utils";function signinCookiePath(issuer,scopePath){let issuerPath;try{issuerPath=new URL(issuer).pathname.replace(/\/+$/,"")}catch{return"/"}return issuerPath===""&&scopePath.replace(/\/+$/,"")===""?"/oauth":"/"}function signinOverHttps(request2){if(isSecureRequest(request2))return true;if(getRequestBaseUrl(request2).startsWith("https:"))return true;const webRequest=request2[ServerRequestTokens.webRequest];return webRequest instanceof Request&&webRequest.url.startsWith("https:")}function createRequestSigninBinding(request2,pendingAuthId){return createSigninBinding(pendingAuthId,{secure:signinOverHttps(request2)})}function signinBindingCookie(request2,binding,path4){const secure=signinOverHttps(request2);return{name:binding.cookieName,value:binding.value,path:secure?"/":path4,httpOnly:true,sameSite:"lax",secure,maxAge:SIGNIN_BINDING_MAX_AGE_SECONDS}}function clearedSigninBindingCookie(request2,pendingAuthId,path4){const secure=signinOverHttps(request2);return{name:signinBindingCookieName(pendingAuthId,{secure}),value:"",path:secure?"/":path4,httpOnly:true,sameSite:"lax",secure,maxAge:0}}function requestHoldsSigninBinding(request2,pendingAuthId,hash){const raw=request2.headers?.["cookie"];const header2=Array.isArray(raw)?raw.join("; "):raw;return signinBindingMatches(header2,pendingAuthId,hash,{secure:signinOverHttps(request2)})}function withCookie(output,cookie){return{...output,cookies:[...output.cookies??[],cookie]}}var SIGNIN_BINDING_REFUSED;var init_signin_binding_utils=__esm({"libs/sdk/src/auth/flows/signin-binding.utils.ts"(){"use strict";init_common();SIGNIN_BINDING_REFUSED="This sign-in was started in another browser, or at another address. Start it again from the app."}});var oauth_authorize_flow_exports={};__export(oauth_authorize_flow_exports,{OauthAuthorizeFlow:()=>OauthAuthorizeFlow,default:()=>OauthAuthorizeFlow});import{buildFederatedLoginPage,buildIncrementalAuthPage,builtInAuthPageHeaders as builtInAuthPageHeaders2,createFederatedAuthSession,escapeHtml as escapeHtml2,grantScopes,isLoopbackRedirectUri,openIncrementalAuthTicketProfile,renderLocalLoginPage,sealPendingLogin,startNextProvider,verifyIncrementalAuthTicket}from"@frontmcp/auth";import{internalZ as z137}from"@frontmcp/lazy-zod";import{generateCodeVerifier,randomUUID as randomUUID32,sha256Base64url as sha256Base64url2}from"@frontmcp/utils";function getConfiguredProviderIds(auth){return getConfiguredProviders(auth).map(p=>p.id)}var pkceChallengeSchema,codeChallengeMethodSchema,responseTypeSchema,safeRedirectUriSchema,oauthAuthorizeRequestSchema,anonymousAuthorizeRequestSchema,inputSchema40,stateSchema42,outputSchema39,plan47,name47,Stage47,OauthAuthorizeFlow;var init_oauth_authorize_flow=__esm({"libs/sdk/src/auth/flows/oauth.authorize.flow.ts"(){"use strict";init_common();init_flow_http_path();init_auth_ui();init_authorized_apps_utils();init_cimd();init_consent_tools_helper();init_federated_steps();init_required_providers_utils();init_signin_binding_utils();pkceChallengeSchema=z137.string().min(43,"code_challenge must be at least 43 characters").max(128,"code_challenge must be at most 128 characters").regex(/^[A-Za-z0-9_-]+$/,"code_challenge must contain only A-Za-z0-9-_");codeChallengeMethodSchema=z137.literal("S256",{message:'code_challenge_method must be "S256" (OAuth 2.1)'});responseTypeSchema=z137.literal("code",{message:'response_type must be "code" (OAuth 2.1)'});safeRedirectUriSchema=z137.url().refine(uri=>{try{const url=new URL(uri);return url.protocol==="http:"||url.protocol==="https:"}catch{return false}},{message:"redirect_uri must use http or https scheme"});oauthAuthorizeRequestSchema=z137.object({response_type:responseTypeSchema,client_id:z137.string().min(1,"client_id is required"),redirect_uri:safeRedirectUriSchema,code_challenge:pkceChallengeSchema,code_challenge_method:codeChallengeMethodSchema.optional().default("S256"),scope:z137.string().optional(),state:z137.string().optional(),resource:z137.string().url().optional()});anonymousAuthorizeRequestSchema=z137.object({redirect_uri:safeRedirectUriSchema,state:z137.string().optional()});inputSchema40=httpInputSchema;stateSchema42=z137.object({isDefaultAuthProvider:z137.boolean().describe("No sign-in to run: no auth options, or public mode (the same configuration, written out)"),isOrchestrated:z137.boolean().describe("If FrontMcp is orchestrated (local oauth proxy, remote oauth proxy)"),allowAnonymous:z137.boolean().describe("Allow anonymous access, force orchestrated mode"),validatedRequest:oauthAuthorizeRequestSchema.optional(),rawRedirectUri:z137.string().optional(),rawState:z137.string().optional(),validationErrors:z137.array(z137.string()).optional(),pendingAuthId:z137.string().optional(),isIncrementalAuth:z137.boolean().default(false).describe("Whether this is an incremental auth request"),targetAppId:z137.string().optional().describe("Target app ID for incremental authorization"),targetToolId:z137.string().optional().describe("Target tool ID that triggered the incremental auth"),existingSessionId:z137.string().optional().describe("Existing session ID for incremental auth"),incrementalTicket:z137.custom().optional(),priorAuthorizedAppIds:z137.array(z137.string()).optional().describe("Prior authorized app IDs to carry forward"),requiresFederatedLogin:z137.boolean().default(false).describe("Whether this auth requires federated login UI"),requiresConsent:z137.boolean().default(false).describe("Whether consent flow is enabled"),isCimdClient:z137.boolean().default(false).describe("Whether client_id is a CIMD URL"),cimdMetadata:clientMetadataDocumentSchema.optional().describe("CIMD metadata document for the client")});outputSchema39=z137.union([HttpRedirectSchema,HttpTextSchema,HttpHtmlSchema]);plan47={pre:["checkIpFilter","acquireQuota","parseInput","validateInput","checkIfAuthorized"],execute:["prepareAuthorizationRequest","buildAuthorizeOutput"],post:["validateOutput"]};name47="oauth:authorize";Stage47=StageHookOf(name47);OauthAuthorizeFlow=class extends FlowBase{resolveIssuer(request2){const auth=this.scope.auth;const issuer=request2&&auth?.issuerFor?auth.issuerFor(request2):auth?.issuer;return typeof issuer==="string"&&issuer.length>0?issuer:void 0}logger=this.scope.logger.child("OauthAuthorizeFlow");signinCookie;signinBindingHash;federatedStepRecord;respond(output){super.respond(this.signinCookie?withCookie(output,this.signinCookie):output)}async checkIpFilter(){enforceIpFilter(this.scope,this.tryGetContext()?.metadata.clientIp)}async acquireQuota(){await enforceGlobalRateLimit(this.scope,this.tryGetContext())}async parseInput(){const{metadata}=this.scope;const{request:request2}=this.rawInput;const rawRedirectUri=request2.query["redirect_uri"];const rawState=request2.query["state"];const incrementalTicket=this.verifyIncrementalTicket(request2.query["ticket"]);const isIncrementalAuth=incrementalTicket!==void 0;const targetAppId=incrementalTicket?.appId;const targetToolId=incrementalTicket?.toolId;let priorAuthorizedAppIds;if(incrementalTicket){priorAuthorizedAppIds=incrementalTicket.priorAppIds&&incrementalTicket.priorAppIds.length>0?Array.from(new Set(incrementalTicket.priorAppIds)):void 0}else{const appsParam=request2.query["apps"];if(appsParam){const ids=(Array.isArray(appsParam)?appsParam:[appsParam]).flatMap(v=>String(v).split(",")).map(v=>v.trim()).filter(Boolean);priorAuthorizedAppIds=ids.length>0?Array.from(new Set(ids)):void 0}}const existingSessionId=request2.query["session_id"];const isDefaultAuthProvider=!metadata.auth||isPublicMode(metadata.auth);let requiresFederatedLogin=false;if(metadata.auth&&isOrchestratedMode(metadata.auth)){const configProviders=getConfiguredProviderIds(metadata.auth);const apps=this.scope.apps.getApps();const appsWithAuth=apps.filter(app=>app.metadata.auth);requiresFederatedLogin=configProviders.length>0||appsWithAuth.length>0}const federatedAuth=metadata.auth&&isLocalMode(metadata.auth)?metadata.auth.federatedAuth:void 0;if(!requiresFederatedLogin&&(federatedAuth?.minProviders||federatedAuth?.requiredProviders?.length)){this.logger.error("OAuth authorize: federatedAuth.minProviders or requiredProviders is set, but there is no provider to link");this.respondWithError(["Sign-in is not available: this server requires linked providers but none is configured. Add auth.providers (or an app with its own auth), or remove federatedAuth.minProviders and requiredProviders."],void 0,rawState,"server_error");return}let requiresConsent=false;if(metadata.auth&&isOrchestratedMode(metadata.auth)){const consentConfig=metadata.auth.consent;requiresConsent=consentConfig?.enabled===true}this.state.set({isOrchestrated:true,allowAnonymous:isDefaultAuthProvider,isDefaultAuthProvider,rawRedirectUri,rawState,isIncrementalAuth,targetAppId,targetToolId,existingSessionId,priorAuthorizedAppIds,incrementalTicket,requiresFederatedLogin,requiresConsent});if(isIncrementalAuth){this.logger.info(`Incremental authorization requested for app: ${targetAppId}, tool: ${targetToolId}`)}if(requiresFederatedLogin){this.logger.info(`Federated login required: Multiple auth providers detected`)}if(requiresConsent){this.logger.info(`Consent flow enabled: User will select tools to expose`)}}async validateInput(){const{isDefaultAuthProvider,rawRedirectUri,rawState}=this.state;const{request:request2}=this.rawInput;if(isDefaultAuthProvider){const result2=anonymousAuthorizeRequestSchema.safeParse({redirect_uri:rawRedirectUri,state:rawState});if(!result2.success){const errors=this.formatZodErrors(result2.error);this.logger.warn(`Anonymous authorization request validation failed: ${errors.join(", ")}`);this.respond(this.htmlPage(this.renderErrorPage("invalid_request",errors.join("; ")),400));return}if(!isLoopbackRedirectUri(result2.data.redirect_uri)){this.logger.warn("Anonymous authorization request with a non-loopback redirect_uri refused");this.respond(this.htmlPage(this.renderErrorPage("invalid_request","This server has no authorization configured; only a loopback redirect_uri is accepted"),400));return}const url=new URL(result2.data.redirect_uri);url.searchParams.set("code","anonymous");if(result2.data.state){url.searchParams.set("state",result2.data.state)}const issuer=this.resolveIssuer(this.rawInput.request);if(issuer)url.searchParams.set("iss",issuer);this.respond(httpRespond.redirect(url.toString()));return}const authConfig=this.scope.metadata.auth;if(!authConfig||!isOrchestratedMode(authConfig)){const mode=authConfig?.mode??"public";this.logger.warn(`Authorization request refused: auth mode ${mode} does not sign users in`);this.respond(this.htmlPage(this.renderErrorPage("unsupported_response_type",`This server does not sign users in (auth mode: ${mode}). Present its access token instead.`),400));return}const result=oauthAuthorizeRequestSchema.safeParse({response_type:request2.query["response_type"],client_id:request2.query["client_id"],redirect_uri:rawRedirectUri,code_challenge:request2.query["code_challenge"],code_challenge_method:request2.query["code_challenge_method"]??"S256",scope:request2.query["scope"],state:rawState,resource:request2.query["resource"]});if(!result.success){const errors=this.formatZodErrors(result.error);this.logger.warn(`Authorization request validation failed: ${errors.join(", ")}`);this.respondWithError(errors,void 0,rawState);return}const authOptions=this.scope.auth?.options;const requestedScopes=result.data.scope?result.data.scope.split(" ").filter(Boolean):[];const grantedScopes=grantScopes(requestedScopes,authOptions?.allowedScopes);if(grantedScopes.length<requestedScopes.length){this.logger.info(`OAuth authorize: not granting scope(s) outside allowedScopes: ${requestedScopes.filter(s=>!grantedScopes.includes(s)).join(" ")}`)}let validatedRequest={...result.data,scope:grantedScopes.length>0?grantedScopes.join(" "):void 0};this.state.set("validatedRequest",validatedRequest);const{client_id,redirect_uri}=validatedRequest;const cimdService=this.get(CimdService);const registry=this.scope.auth?.dcrClientRegistry;const redirectAllowlisted=!!registry?.hasRedirectAllowlist()&&registry.isRedirectUriAllowed(redirect_uri);let redirectVerified=redirectAllowlisted;let declaredClientScope;const isCimdClientId2=!!cimdService?.enabled&&cimdService.isCimdClientId(client_id);const redirectError=this.checkDcrRedirectAllowlist(redirect_uri);if(redirectError){this.logger.warn(`OAuth authorize: DCR allowlist rejection \u2014 ${redirectError}`);this.respondWithError([redirectError],void 0,rawState);return}if(cimdService&&!cimdService.enabled&&cimdService.isCimdClientId(client_id)&&!registry?.get?.(client_id)){const disabled=new CimdDisabledError;this.logger.warn(`OAuth authorize: CIMD client_id refused, CIMD is disabled: ${client_id}`);this.respondWithError([disabled.message],void 0,rawState);return}if(isCimdClientId2){try{this.logger.debug(`Processing CIMD client_id: ${client_id}`);const resolution=await cimdService.resolveClientMetadata(client_id);if(resolution.isCimdClient&&resolution.metadata){cimdService.validateRedirectUri(redirect_uri,resolution.metadata);redirectVerified=true;cimdService.assertSupportedClient(resolution.metadata);declaredClientScope=resolution.metadata.scope;this.state.set("isCimdClient",true);this.state.set("cimdMetadata",resolution.metadata);this.logger.info(`CIMD client validated: ${resolution.metadata.client_name} (${client_id})`,resolution.fromCache?" [from cache]":"")}}catch(error){const detail=error instanceof Error?error.message:String(error);this.logger.warn(`CIMD validation failed for ${client_id}: ${detail}`);const publicMessage=error instanceof CimdError?error.getPublicMessage():"CIMD validation failed";this.respondWithError([publicMessage],void 0,rawState);return}}const registered=isCimdClientId2?void 0:registry?.get?.(client_id);if(registered){if(!registered.redirect_uris.includes(redirect_uri)){this.logger.warn(`OAuth authorize: redirect_uri "${redirect_uri}" not registered for client "${client_id}"`);this.respondWithError(["redirect_uri is not registered for this client"],void 0,rawState);return}redirectVerified=true;declaredClientScope=registered.scope}const clientIdError=isCimdClientId2?void 0:this.checkDcrClientIdAllowlist(client_id);if(clientIdError){this.logger.warn(`OAuth authorize: DCR allowlist rejection \u2014 ${clientIdError}`);this.respondWithError([clientIdError],redirectVerified?redirect_uri:void 0,rawState,"unauthorized_client");return}if(!isCimdClientId2&&!registered&&authOptions?.requireRegisteredClients!==false){this.logger.warn(`OAuth authorize: rejecting unregistered client_id "${client_id}" (requireRegisteredClients)`);this.respondWithError(["Unknown client_id: register the client (DCR / pre-registered) or use a CIMD client-id URL"],void 0,rawState);return}if(declaredClientScope!==void 0){const clientScopes=declaredClientScope.split(" ");const clientGrantedScopes=grantedScopes.filter(scope=>clientScopes.includes(scope));validatedRequest={...validatedRequest,scope:clientGrantedScopes.length>0?clientGrantedScopes.join(" "):void 0};this.state.set("validatedRequest",validatedRequest)}const canonicalResource=computeResource(request2,this.scope.entryPath,this.scope.routeBase);if(!validatedRequest.resource){this.state.set("validatedRequest",{...validatedRequest,resource:canonicalResource})}else if(!resourceUriMatches(validatedRequest.resource,canonicalResource)){this.logger.warn(`OAuth authorize: resource mismatch. Provided: ${validatedRequest.resource}, canonical: ${canonicalResource}`);this.respondWithError(["Invalid resource parameter: does not match server resource URI"],redirectVerified?redirect_uri:void 0,rawState);return}}verifyIncrementalTicket(raw){const token=typeof raw==="string"?raw:Array.isArray(raw)?raw[0]:void 0;if(typeof token!=="string"||token.length===0)return void 0;const localAuth=this.scope.auth;const secret=localAuth?.signingSecret;if(!secret)return void 0;const payload=verifyIncrementalAuthTicket(token,secret);if(!payload){this.logger.warn("Incremental auth ticket failed verification \u2014 treating as an ordinary login");return void 0}if(payload.aud!==void 0&&payload.aud!==incrementalTicketAudience(this.scope)){this.logger.warn("Incremental auth ticket was minted for another server or endpoint \u2014 treating as an ordinary login");return void 0}const grant=initialAuthorizedApps(this.scope.auth?.options,this.scope.apps.getApps(),[payload.appId]);if(!grant?.includes(payload.appId)){this.logger.warn("Incremental auth ticket names an app this endpoint does not authorize incrementally \u2014 treating as an ordinary login");return void 0}return payload}async checkIfAuthorized(){}async prepareAuthorizationRequest(){const{validatedRequest,isIncrementalAuth,targetAppId,targetToolId,existingSessionId,priorAuthorizedAppIds,requiresFederatedLogin,requiresConsent,incrementalTicket}=this.state;const{metadata}=this.scope;if(!validatedRequest){return}const auth=this.scope.auth;if(!auth||!("authorizationStore"in auth)){this.respond(this.htmlPage(this.renderErrorPage("server_error","Authorization not configured"),500));return}const localAuth=auth;const store=localAuth.authorizationStore;let effectiveIncremental=isIncrementalAuth;let effectivePriorAppIds=priorAuthorizedAppIds;if(incrementalTicket){const claimed=await localAuth.claimIncrementalTicket(incrementalTicket.jti,Math.max(0,incrementalTicket.exp-Date.now()));if(!claimed){this.logger.warn("Incremental auth ticket already used \u2014 falling back to an ordinary login");effectiveIncremental=false;effectivePriorAppIds=void 0;this.state.set({isIncrementalAuth:false,targetAppId:void 0,targetToolId:void 0,priorAuthorizedAppIds:void 0})}}let federatedLogin;if(requiresFederatedLogin){const apps=this.scope.apps.getApps();const providerIds=[];for(const id of getConfiguredProviderIds(metadata.auth)){if(!providerIds.includes(id)){providerIds.push(id)}}if(providerIds.length===0&&metadata.auth&&isOrchestratedMode(metadata.auth)){providerIds.push("__parent__")}for(const app of apps){if(app.metadata.auth){const appId=app.metadata.id||app.metadata.name;if(!providerIds.includes(appId)){providerIds.push(appId)}}}federatedLogin={providerIds,selectedProviderIds:void 0,skippedProviderIds:void 0}}let consent;if(requiresConsent){const consentConfig=metadata.auth&&isOrchestratedMode(metadata.auth)?metadata.auth.consent:void 0;const{availableToolIds}=projectConsentTools(this.scope,consentConfig?.excludedTools);consent={enabled:true,availableToolIds,selectedToolIds:void 0,consentCompleted:false}}const pendingRecord=store.createPendingRecord({clientId:validatedRequest.client_id,redirectUri:validatedRequest.redirect_uri,scopes:validatedRequest.scope?validatedRequest.scope.split(" "):[],pkce:{challenge:validatedRequest.code_challenge,method:"S256"},state:validatedRequest.state,resource:validatedRequest.resource,isIncremental:effectiveIncremental,incrementalSub:effectiveIncremental?incrementalTicket?.sub:void 0,targetAppId:effectiveIncremental?targetAppId:void 0,targetToolId:effectiveIncremental?targetToolId:void 0,existingSessionId,priorAuthorizedAppIds:effectivePriorAppIds,federatedLogin,consent,clientAuthMethod:this.clientAuthMethodOf(validatedRequest.client_id,localAuth)});const ticketProfile=effectiveIncremental&&incrementalTicket&&localAuth.signingSecret?openIncrementalAuthTicketProfile(incrementalTicket,localAuth.signingSecret):void 0;if(ticketProfile){pendingRecord.verifiedLogin=sealPendingLogin(localAuth.secret,pendingRecord.id,ticketProfile)}if(federatedLogin&&!effectiveIncremental&&metadata.auth&&!isRemoteMode(metadata.auth)&&showsProvidersStepByStep(this.scope.auth?.options)){startFederatedSteps(pendingRecord,this.scope);this.federatedStepRecord=pendingRecord}const binding=createRequestSigninBinding(this.rawInput.request,pendingRecord.id);pendingRecord.signinBinding=binding.hash;this.signinBindingHash=binding.hash;this.signinCookie=signinBindingCookie(this.rawInput.request,binding,signinCookiePath(localAuth.issuer,this.scope.fullPath));await localAuth.authorizationStore.storePendingAuthorization(pendingRecord);this.logger.info(`Pending authorization created: ${pendingRecord.id}${effectiveIncremental?` (incremental for app: ${targetAppId})`:""}${requiresFederatedLogin?" (federated)":""}${requiresConsent?" (consent enabled)":""}`);this.state.set("pendingAuthId",pendingRecord.id)}async buildAuthorizeOutput(){const{pendingAuthId,validatedRequest,isIncrementalAuth,targetAppId,targetToolId,requiresFederatedLogin,isCimdClient,cimdMetadata}=this.state;if(!validatedRequest||!pendingAuthId){return}const{metadata}=this.scope;if(metadata.auth&&isRemoteMode(metadata.auth)&&!isIncrementalAuth){await this.startRemoteFederation(pendingAuthId,validatedRequest);return}const clientDisplayName=cimdMetadata?.client_name??validatedRequest.client_id;if(isIncrementalAuth&&targetAppId){const apps=this.scope.apps.getApps();const app=apps.find(a=>a.metadata.id===targetAppId);const appName=app?.metadata?.name||targetAppId;const appDescription=app?.metadata?.description;const customIncremental=await this.tryRenderCustomSlot("incremental",pendingAuthId,common=>buildIncrementalState(common,{appId:targetAppId,appName,appDescription,toolId:targetToolId,redirectUri:validatedRequest.redirect_uri}),[validatedRequest.redirect_uri]);if(customIncremental)return;const incrementalAuthHtml=this.renderIncrementalAuthPage({pendingAuthId,appId:targetAppId,appName,appDescription,toolId:targetToolId,redirectUri:validatedRequest.redirect_uri});this.respond(this.htmlPage(incrementalAuthHtml));return}if(requiresFederatedLogin){if(this.federatedStepRecord){this.respond(renderFederatedStep(this.scope,this.federatedStepRecord,{clientName:clientDisplayName}));return}const providers=pickerProviders(this.scope);const hasConfiguredProviders=getConfiguredProviders(metadata.auth).length>0;const detection={providers:new Map(providers.map(p=>[p.id,p])),requiresOrchestration:true,parentProviderId:hasConfiguredProviders?void 0:"__parent__",childProviderIds:providers.filter(p=>!p.isParentProvider).map(p=>p.id),uniqueProviderCount:providers.length,validationErrors:[],warnings:[]};const customFederated=await this.tryRenderCustomSlot("federated",pendingAuthId,common=>buildFederatedState(common,{clientId:validatedRequest.client_id,clientName:clientDisplayName,redirectUri:validatedRequest.redirect_uri,providers:[...detection.providers.values()].map(toAuthProvider)}),[validatedRequest.redirect_uri,...providerAuthorizationEndpoints(this.scope,detection.providers.keys())]);if(customFederated)return;const federatedLoginHtml=this.renderFederatedLoginPage({pendingAuthId,detection,clientId:validatedRequest.client_id,redirectUri:validatedRequest.redirect_uri});this.respond(this.htmlPage(federatedLoginHtml));return}const customLogin=await this.tryRenderCustomSlot("login",pendingAuthId,common=>buildLoginState(common,{clientId:validatedRequest.client_id,clientName:clientDisplayName,scopes:validatedRequest.scope?validatedRequest.scope.split(" ").filter(Boolean):[],redirectUri:validatedRequest.redirect_uri,logoUri:cimdMetadata?.logo_uri}),[validatedRequest.redirect_uri]);if(customLogin)return;const loginHtml=this.renderLoginPage({pendingAuthId,clientId:validatedRequest.client_id,clientName:clientDisplayName,scope:validatedRequest.scope??"",redirectUri:validatedRequest.redirect_uri,logoUri:cimdMetadata?.logo_uri});const auth=this.scope.metadata.auth;const customRender=!!(auth&&auth.mode==="local"&&auth.login?.render);this.respond(httpRespond.html(loginHtml,200,builtInAuthPageHeaders2({csp:!customRender})))}async tryRenderCustomSlot(slot,pendingAuthId,buildState,formTargets){const authUi=this.scope.authUi;if(!authUi||!authUi.hasSlot(slot))return false;const csrfToken=authUi.mintCsrf(pendingAuthId);try{const localAuth=this.scope.auth;const record=await localAuth.authorizationStore.getPendingAuthorization(pendingAuthId);if(record){record.authUiCsrf=csrfToken;await localAuth.authorizationStore.storePendingAuthorization(record)}}catch(err){this.logger.warn(`Failed to persist auth-UI CSRF on pending record: ${err instanceof Error?err.message:err}`)}const state=buildState({pendingAuthId,submitUrl:`${oauthBasePath(this.scope)}/oauth/callback`,extraUrl:authUiExtraPath(this.scope.fullPath),csrfToken,addedItems:authUi.getAddedItems(pendingAuthId)});const page2=buildAuthUiPage({registry:authUi,slot,state,fullPath:this.scope.fullPath,formTargets});if(!page2)return false;this.respond(httpRespond.html(page2.html,200,page2.headers));return true}clientAuthMethodOf(clientId,localAuth){return this.state.cimdMetadata?.token_endpoint_auth_method??localAuth.dcrClientRegistry.get(clientId)?.token_endpoint_auth_method??"none"}async startRemoteFederation(pendingAuthId,validatedRequest){const auth=this.scope.auth;if(!auth||!("federatedSessionStore"in auth)){this.respond(this.htmlPage(this.renderErrorPage("server_error","Authorization not configured"),500));return}const localAuth=auth;const providerId=localAuth.remoteProviderId;if(!providerId||!localAuth.getProviderConfig(providerId)){this.logger.error("Remote mode: no upstream provider configured for federation");await localAuth.authorizationStore.deletePendingAuthorization(pendingAuthId);this.respond(this.htmlPage(this.renderErrorPage("server_error","Upstream identity provider is not configured"),500));return}const session=createFederatedAuthSession({pendingAuthId,clientId:validatedRequest.client_id,redirectUri:validatedRequest.redirect_uri,scopes:validatedRequest.scope?validatedRequest.scope.split(" ").filter(Boolean):[],state:validatedRequest.state,resource:validatedRequest.resource,userInfo:{},frontmcpPkce:{challenge:validatedRequest.code_challenge,method:"S256"},providerIds:[providerId],signinBinding:this.signinBindingHash,clientAuthMethod:this.clientAuthMethodOf(validatedRequest.client_id,localAuth),authorizedAppIds:initialAuthorizedApps(this.scope.auth?.options,this.scope.apps.getApps(),this.state.priorAuthorizedAppIds)});const verifier=generateCodeVerifier();const challenge=sha256Base64url2(verifier);const pkce={verifier,challenge,method:"S256"};const providerState=`federated:${session.id}:${randomUUID32()}`;startNextProvider(session,pkce,providerState);await localAuth.federatedSessionStore.store(session);const redirectUrl=await localAuth.buildProviderAuthorizeUrl(providerId,{state:providerState,codeChallenge:pkce.challenge,codeChallengeMethod:"S256"});if(!redirectUrl){this.logger.error(`Remote mode: failed to build authorize URL for provider: ${providerId}`);await localAuth.federatedSessionStore.delete(session.id);await localAuth.authorizationStore.deletePendingAuthorization(pendingAuthId);this.respond(this.htmlPage(this.renderErrorPage("server_error",`Failed to initiate authentication with provider: ${providerId}`),500));return}this.logger.info(`Remote mode: redirecting to upstream provider: ${providerId}`);this.respond(httpRespond.redirect(redirectUrl))}async validateOutput(){}htmlPage(markup,status=200){return httpRespond.html(markup,status,builtInAuthPageHeaders2())}checkDcrRedirectAllowlist(redirectUri){const registry=this.scope.auth?.dcrClientRegistry;if(registry?.hasRedirectAllowlist()&&!registry.isRedirectUriAllowed(redirectUri)){return`redirect_uri "${redirectUri}" is not in the configured allowlist`}return void 0}checkDcrClientIdAllowlist(clientId){const registry=this.scope.auth?.dcrClientRegistry;if(registry?.hasClientIdAllowlist()&&!registry.isClientIdAllowed(clientId)){return`client_id "${clientId}" is not in the configured allowlist`}return void 0}formatZodErrors(error){return error.issues.map(err=>{const path4=err.path.length>0?`${err.path.join(".")}: `:"";return`${path4}${err.message}`})}respondWithError(errors,redirectUri,state,error="invalid_request"){const errorDescription=errors.join("; ");if(redirectUri){const safe=safeRedirectUriSchema.safeParse(redirectUri);if(safe.success){const url=new URL(safe.data);url.searchParams.set("error",error);url.searchParams.set("error_description",errorDescription);if(state){url.searchParams.set("state",state)}const issuer=this.resolveIssuer(this.rawInput.request);if(issuer)url.searchParams.set("iss",issuer);this.respond(httpRespond.redirect(url.toString()));return}}this.respond(this.htmlPage(this.renderErrorPage(error,errorDescription),400))}renderLoginPage(params){const{pendingAuthId,clientId,clientName,scope,logoUri}=params;const callbackPath=`${oauthBasePath(this.scope)}/oauth/callback`;const auth=this.scope.metadata.auth;const login=auth&&auth.mode==="local"?auth.login:void 0;const ctx={clientId,clientName:clientName??clientId,logoUri,scopes:scope?scope.split(" ").filter(Boolean):[],pendingAuthId,callbackPath,fields:login?.fields??{}};return renderLocalLoginPage(login,ctx)}renderIncrementalAuthPage(params){const{pendingAuthId,appId,appName,appDescription,toolId}=params;const callbackPath=`${oauthBasePath(this.scope)}/oauth/callback`;const app={appId,appName,description:appDescription};return buildIncrementalAuthPage({app,toolId:toolId||"unknown tool",sessionHint:pendingAuthId,callbackPath})}renderFederatedLoginPage(params){const{pendingAuthId,detection,clientId}=params;const callbackPath=`${oauthBasePath(this.scope)}/oauth/callback`;const authOptions=this.scope.auth?.options;const required=requiredProviderIds(authOptions,this.scope.apps.getApps());const providers=[...detection.providers.values()].map(provider=>({providerId:provider.id,providerName:provider.id,providerUrl:provider.providerUrl,mode:provider.mode,appIds:provider.appIds.filter(id=>id!=="__parent__"),isPrimary:provider.isParentProvider,required:required.includes(provider.id)}));return buildFederatedLoginPage({providers,clientName:clientId,pendingAuthId,callbackPath,allowSkip:allowsSkippingApps(authOptions)})}renderErrorPage(error,description){return`<!DOCTYPE html>
@@ -486,7 +486,7 @@ This tool was blocked during the '${skillDisplay}' skill session. Please use the
486
486
 
487
487
  The '${skillDisplay}' skill session has reached its maximum tool call limit.`;case"no_active_skill":return`Cannot call tool '${toolName}': no skill is active and explicit activation is required.
488
488
 
489
- Activate a skill first: send a skills/load request with activateSession: true.`;default:return`Tool '${toolName}' is not authorized for use in this skill session.`}}static formatSkillDisplay(skillName,skillId,activeSkillNames){if(activeSkillNames&&activeSkillNames.length>1){return activeSkillNames.join(" + ")}return skillName||skillId||"the active skill"}getPublicMessage(){return this.message}toJsonRpcError(){return{code:this.mcpErrorCode,message:this.getPublicMessage(),data:{toolName:this.toolName,skillId:this.skillId,skillName:this.skillName,activeSkillIds:this.activeSkillIds,activeSkillNames:this.activeSkillNames,reason:this.reason,allowedTools:this.allowedTools}}}};ToolApprovalRequiredError=class extends PublicMcpError{mcpErrorCode=MCP_ERROR_CODES.INVALID_REQUEST;toolName;skillId;constructor(toolName,skillId){const message=skillId?`Tool '${toolName}' requires approval to be used with skill '${skillId}'.`:`Tool '${toolName}' requires approval.`;super(message);this.name="ToolApprovalRequiredError";this.toolName=toolName;this.skillId=skillId}getPublicMessage(){return this.message}toJsonRpcError(){return{code:this.mcpErrorCode,message:this.getPublicMessage(),data:{toolName:this.toolName,skillId:this.skillId,requiresApproval:true}}}}}});async function handleAuthorizationResult(authResult,sessionManager,policyMode,skillId,onApprovalRequired,logger){if(authResult.allowed){logger?.verbose(`SkillToolGuard: tool "${authResult.toolName}" allowed`,{reason:authResult.reason});return}const allowlist=sessionManager.getToolAllowlist();if(authResult.reason==="no_active_skill")throw new ToolNotAllowedError(authResult,allowlist);switch(policyMode){case"strict":logger?.warn(`SkillToolGuard: blocking tool "${authResult.toolName}" (strict mode)`,{skillId,reason:authResult.reason,allowedTools:allowlist});throw new ToolNotAllowedError(authResult,allowlist);case"approval":logger?.info(`SkillToolGuard: tool "${authResult.toolName}" requires approval`,{skillId});if(authResult.requiresApproval&&onApprovalRequired){const approved=await onApprovalRequired(authResult.toolName,skillId);if(approved){sessionManager.approveToolForSession(authResult.toolName);logger?.info(`SkillToolGuard: tool "${authResult.toolName}" approved dynamically`);return}}throw new ToolApprovalRequiredError(authResult.toolName,skillId);case"permissive":default:logger?.warn(`SkillToolGuard: tool "${authResult.toolName}" not in allowlist (permissive mode)`,{skillId,reason:authResult.reason,allowedTools:allowlist});sessionManager.recordToolCall(authResult.toolName);return}}function createSkillToolGuardHook(sessionManager,options={}){const{logger,onApprovalRequired,trackToolCalls=true,verifiedSessionId}=options;class SkillToolGuardHookImpl{async checkSkillToolAuthorization(ctx){const{tool}=ctx.state;const rawToolName=tool?.name||tool?.metadata?.id||tool?.metadata?.name||ctx.state.input?.name||tool?.fullName;if(!rawToolName){logger?.verbose("SkillToolGuard: skipping (no tool name in context)");return}const toolName=rawToolName.includes(":")?rawToolName.substring(rawToolName.lastIndexOf(":")+1):rawToolName;const sessionId=verifiedSessionId?.();if(sessionId&&sessionManager.getActiveSession()?.sessionId!==sessionId){await sessionManager.runWithSession(sessionId,()=>authorizeInActiveSession(toolName));return}await authorizeInActiveSession(toolName)}}__decorateClass([Will("checkToolAuthorization",{priority:-1e3})],SkillToolGuardHookImpl.prototype,"checkSkillToolAuthorization",1);async function authorizeInActiveSession(toolName){const session=sessionManager.getActiveSession();if(!session?.activeSkillId){const authResult2=sessionManager.checkToolAuthorization(toolName);if(!authResult2.allowed)throw new ToolNotAllowedError(authResult2);logger?.verbose("SkillToolGuard: skipping (no active skill)");return}logger?.verbose(`SkillToolGuard: checking authorization for tool "${toolName}"`,{skillId:session.activeSkillId,policyMode:session.policyMode});const authResult=sessionManager.checkToolAuthorization(toolName);if(trackToolCalls&&authResult.allowed){sessionManager.recordToolCall(toolName)}await handleAuthorizationResult(authResult,sessionManager,session.strictAllowlist?"strict":session.policyMode,session.activeSkillId,onApprovalRequired,logger)}return SkillToolGuardHookImpl}var Will;var init_skill_tool_hook=__esm({"libs/sdk/src/skill/hooks/skill-tool.hook.ts"(){"use strict";init_common();init_tool_not_allowed_error();({Will}=FlowHooksOf("tools:call-tool"))}});var hooks_exports={};__export(hooks_exports,{createSkillToolGuardHook:()=>createSkillToolGuardHook});var init_hooks=__esm({"libs/sdk/src/skill/hooks/index.ts"(){"use strict";init_skill_tool_hook()}});var authorities_engine_exports={};__export(authorities_engine_exports,{authoritiesFromConfig:()=>authoritiesFromConfig,createAuthoritiesEngine:()=>createAuthoritiesEngine});import{AuthoritiesContextBuilder,AuthoritiesEngine,AuthoritiesEvaluatorRegistry,AuthoritiesProfileRegistry}from"@frontmcp/auth";function createAuthoritiesEngine(config){const profileRegistry=new AuthoritiesProfileRegistry;if(config["profiles"]){profileRegistry.registerAll(config["profiles"])}const evaluatorRegistry=new AuthoritiesEvaluatorRegistry;if(config["evaluators"]){evaluatorRegistry.registerAll(config["evaluators"])}return new AuthoritiesEngine(profileRegistry,evaluatorRegistry)}function authoritiesFromConfig(config){return{engine:createAuthoritiesEngine(config),contextBuilder:new AuthoritiesContextBuilder({claimsMapping:config["claimsMapping"],claimsResolver:config["claimsResolver"],relationshipResolver:config["relationshipResolver"]}),scopeMapping:config["scopeMapping"]}}var init_authorities_engine=__esm({"libs/sdk/src/front-mcp/authorities-engine.ts"(){"use strict"}});var send_elicitation_result_tool_exports={};__export(send_elicitation_result_tool_exports,{SendElicitationResultTool:()=>SendElicitationResultTool});import{internalZ as z148}from"@frontmcp/lazy-zod";var inputSchema50,SendElicitationResultTool;var init_send_elicitation_result_tool=__esm({"libs/sdk/src/elicitation/send-elicitation-result.tool.ts"(){"use strict";init_common();init_call_surface();init_errors();init_fallback_helper();inputSchema50={elicitId:z148.string().describe("The elicitation ID from the pending request"),action:z148.enum(["accept","cancel","decline"]).describe("User action: accept (submit), cancel, or decline"),content:z148.unknown().optional().describe("User response content (required for accept action)")};SendElicitationResultTool=class extends ToolContext{async execute(input){const{elicitId,action,content}=input;this.logger.info("sendElicitationResult: processing",{elicitId,action});const store=this.scope.elicitationStore;if(!store){this.logger.error("sendElicitationResult: scope or elicitationStore not available");return{content:[{type:"text",text:"Error: Elicitation store not available. Server may not be properly configured."}],isError:true}}const pending=await store.getPendingFallback(elicitId);if(!pending){this.logger.warn("sendElicitationResult: no pending elicitation found",{elicitId});return{content:[{type:"text",text:`Error: No pending elicitation found for ID: ${elicitId}. The request may have expired or already been processed.`}],isError:true}}const caller=resolveElicitationOwner(this.tryGetContext());if(!pending.owner||pending.owner!==caller){this.logger.warn("sendElicitationResult: refused a result from a caller the elicitation was not asked of",{elicitId});throw new ElicitationNotOwnedError(elicitId)}if(Date.now()>pending.expiresAt){await store.deletePendingFallback(elicitId);this.logger.warn("sendElicitationResult: elicitation expired",{elicitId});return{content:[{type:"text",text:`Error: Elicitation request has expired. Please try the original operation again.`}],isError:true}}const elicitResult={status:action,...action==="accept"&&content!==void 0&&{content}};await store.setResolvedResult(elicitId,elicitResult,pending.sessionId);await store.deletePendingFallback(elicitId);this.logger.info("sendElicitationResult: re-invoking original tool",{elicitId,toolName:pending.toolName});const ctx=this.tryGetContext();if(ctx){ctx.setPreResolvedElicitResult(elicitResult)}try{const toolResult=await this.scope.runFlowForOutput("tools:call-tool",{request:{method:"tools/call",params:{name:pending.toolName,arguments:pending.toolInput}},ctx:Object.defineProperty({authInfo:this.authInfo,requestId:this.tryGetContext()?.requestId??this.runId,surface:getCallSurface(),...this.signal?{signal:this.signal}:{}},"idempotencyKey",{value:pending.idempotencyKey})});this.logger.info("sendElicitationResult: original tool completed",{elicitId,toolName:pending.toolName});await store.publishFallbackResult(elicitId,pending.sessionId,{success:true,result:toolResult});await store.deleteResolvedResult(elicitId);return toolResult}catch(error){const errorMessage2=error instanceof Error?error.message:String(error);await store.publishFallbackResult(elicitId,pending.sessionId,{success:false,error:errorMessage2});await store.deleteResolvedResult(elicitId);this.logger.error("sendElicitationResult: original tool failed",{elicitId,toolName:pending.toolName,error:errorMessage2});return{content:[{type:"text",text:`Error re-invoking ${pending.toolName}: ${errorMessage2}`}],isError:true}}}};SendElicitationResultTool=__decorateClass([Tool({name:"sendElicitationResult",description:'Submit user response for a pending elicitation request. Use this after collecting user input for a tool that requested elicitation. Actions: "accept" (user submitted response), "cancel" (user cancelled), "decline" (user declined to answer).',inputSchema:inputSchema50,hideFromDiscovery:true})],SendElicitationResultTool)}});import"reflect-metadata";import{createGuardManager}from"@frontmcp/guard";import{createRedisClient as createRedisClient3,getEnvFlag,getMachineId as getMachineId6,getRuntimeContext as getRuntimeContext29,isEdgeRuntime as isEdgeRuntime2,mkdir as mkdir3}from"@frontmcp/utils";function keptUntilFailure(start,forget){return start.catch(error=>{forget();throw error})}function entriesWithAuthorities(registries,agentPath=""){const entries=[];const add=(kind,name59,metadata)=>{const authorities=metadata?.["authorities"];if(authorities!==void 0&&authorities!==null&&authorities!==false){entries.push({label:`${kind} "${agentPath}${name59}"`,authorities})}};for(const tool of registries.tools.getTools(true))add("Tool",tool.name,tool.metadata);for(const resource of registries.resources.getResources(true))add("Resource",resource.name,resource.metadata);for(const template of registries.resources.getResourceTemplates()){add("Resource template",template.name,template.metadata)}for(const prompt of registries.prompts.getPrompts(true))add("Prompt",prompt.name,prompt.metadata);for(const agent of registries.agents.getAgents(true)){add("Agent",agent.name,agent.metadata);const agentScope=agent.getAgentScope?.();if(!agentScope){for(const metadata of agentToolMetadata(agent))add("Tool",`${agent.name}:${metadata.name}`,metadata);continue}const{tools,resources,prompts,agents}=agentScope;entries.push(...entriesWithAuthorities({tools,resources,prompts,agents},`${agentPath}${agent.name}:`))}for(const skill of registries.skills?.getSkills(true)??[])add("Skill",skill.name,skill.metadata);return entries}var SCOPE_NON_DISPATCHABLE_FLOWS,Scope;var init_scope_instance=__esm({"libs/sdk/src/scope/scope.instance.ts"(){"use strict";init_adapter_registry();init_agent_registry();init_app_registry();init_auth_registry();init_direct_public_auth();init_channel_utils();init_common();init_sqlite();init_forward_headers_utils();init_path_utils();init_complete_flow();init_context();init_metadata_utils();init_errors();init_plugin_errors();init_event_utils();init_flow_registry();init_authorities_rules_check();init_detached_job_flag();init_direct_only_flag();init_hook_order();init_hook_registry();init_hooks_utils();init_job_utils();init_set_level_flow();init_instructions_budget_check();init_notification();init_offload_service();init_enforced_metadata_check();init_plugin_registry();init_prompt_registry();init_provider_registry();init_materialized_resources();init_resource_registry();init_skill_validation_error();init_skill_scope_helper();init_skill_registry();init_live_surface();init_task_backend_utils();init_tool_output_policy();init_tool_instance();init_tool_registry();init_tool_utils();init_serving_mode_default();init_ui_shared();init_request_state();init_session_mode_check();init_browser_stores();init_dev_events_observability();init_event_publisher_providers();init_server_entries_helper();init_startup_report_helper();SCOPE_NON_DISPATCHABLE_FLOWS=new Set(["http:request"]);Scope=class _Scope extends ScopeEntry{id;globalProviders;logger;scopeProviders;scopeAuth;scopeFlows;scopeApps;scopeHooks;scopeTools;scopeResources;scopePrompts;scopeAgents;scopeSkills;scopePlugins;transportService;notificationService;liveSurface;haRedisClient;haSubscriberClient;transportBus;sessionRelayHandle;toolUIRegistry;authUiRegistry;entryPath;routeBase;orchestrated=false;server;registeredHttpRoutes=[];httpRouteRegistrar={registerRoute:(method,path4,handler)=>{this.registeredHttpRoutes.push({method,path:path4,handler});return this.server.registerRoute(method,path4,handler)}};_elicitationStore;elicitationBackendType;_persistentQuestions;_taskStore;taskBackendType;_taskRegistry;_skillSession;agentCallsServed;skillsServed;pendingAppJobs=[];jobsDecided=false;topLevelSqlite;lateJobsStart;_eventStore;_scopeJobs;_scopeWorkflows;_jobExecutionManager;_jobStateStore;_jobDefinitionStore;_rateLimitManager;_publicAccessGuard;lateGuardSetup=Promise.resolve();_authoritiesEngine;_authoritiesContextBuilder;_authoritiesScopeMapping;scopeAdapters;_scopeChannels;_channelNotificationService;_channelEventBus;_workflowEvents;_channelTeardown;_scopeEvents;_healthService;cliMode;directOnly;constructor(rec,globalProviders){super(rec,rec.provide);this.id=rec.metadata.id;this.logger=globalProviders.get(FrontMcpLogger).child("FrontMcp.MultiAppScope");this.globalProviders=globalProviders;this.server=this.globalProviders.get(FrontMcpServer);this.entryPath=resolveEntryPath(rec.metadata.http?.entryPath);if(rec.kind==="SPLIT_BY_APP"){this.routeBase=`/${rec.metadata.id}`}else{this.routeBase=""}this.cliMode=!!rec.metadata["__cliMode"];this.directOnly=isDirectOnly(rec.metadata);const distributedMode=rec.metadata.transport?.distributedMode;const providerCaching=rec.metadata.transport?.providerCaching;const userProviders=rec.metadata.providers??[];this.scopeProviders=new ProviderRegistry([...userProviders,...this.defaultScopeProviders],globalProviders,{distributedMode,providerCaching});this.ready=this.initialize()}async initialize(){const startedAt=Date.now();await this.scopeProviders.ready;const scopeRef={kind:"scope",id:this.id,ref:_Scope};const scopeProviders=this.scopeProviders;const perf=getEnvFlag("FRONTMCP_PERF");const t0=perf?performance.now():0;const mark=perf?label=>this.logger.info(`[PERF] ${label}: ${(performance.now()-t0).toFixed(1)}ms`):()=>{};await refuseStoresInBrowser(this.metadata);const httpServing=this.directOnly?void 0:await Promise.resolve().then(()=>(init_http_scope_helper(),http_scope_helper_exports));const createPrimaryAuth2=await this.primaryAuthFactory();this.scopeHooks=new HookRegistry(scopeProviders,[]);this.scopeFlows=new FlowRegistry(scopeProviders,httpServing?[httpServing.HttpRouteFlow,httpServing.HttpRequestFlow,httpServing.HttpIpFilterFlow]:[]);this.scopeAuth=new AuthRegistry(this,scopeProviders,[],scopeRef,this.metadata.auth,createPrimaryAuth2);this.scopeApps=new AppRegistry(this.scopeProviders,this.metadata.apps,scopeRef);this.logger.info(`Initializing ${this.metadata.apps.length} app(s)...`);const transportConfig=this.metadata.transport;const isDistributed=getRuntimeContext29().deployment==="distributed";if(isDistributed&&this.metadata.redis&&!this.cliMode&&!this.directOnly){const ha=await Promise.resolve().then(()=>(init_ha(),ha_exports));try{const haRedis=this.createHaRedisClient();const haSubscriber=this.createHaRedisClient("ha-subscriber");this.haManager=ha.HaManager.create({redis:haRedis,pubsubPublisher:haRedis,pubsubSubscriber:haSubscriber,nodeId:getMachineId6(),config:ha.resolveHaConfigFromEnv(),logger:this.logger});await this.haManager.start();this.logger.info("[HA] Manager started for distributed deployment")}catch(err){this.logger.warn("[HA] Failed to start HA manager \u2014 running without HA",{error:err});this.haManager=void 0;await this.closeHaRedisClient()}}let transportBus;if(this.haManager&&this.haRedisClient&&isDistributed){const bus=await Promise.resolve().then(()=>(init_bus(),bus_exports));const haConfig=this.haManager.getConfig();transportBus=new bus.RedisTransportBus(this.haRedisClient,getMachineId6(),{haKeyPrefix:haConfig.redisKeyPrefix,retryAfterSeconds:Math.ceil(haConfig.heartbeatTtlMs/1e3),logger:this.logger});this.transportBus=transportBus;this.logger.info("[HA] Transport bus created for distributed session routing")}const resolvedTopLevelSqlite=await this.resolveTopLevelSqlite();let effectivePersistence=transportConfig?.persistence;if(effectivePersistence===void 0&&resolvedTopLevelSqlite){effectivePersistence={sqlite:resolvedTopLevelSqlite}}if(httpServing){const service=new httpServing.TransportService(this,effectivePersistence,transportBus);this.transportService=service;this.onDispose(()=>service.destroy());httpServing.loadStreamableHttpTransportOnStart(this)}warnIfRequestStateKeyNotShared({logger:this.logger,metadata:this.metadata});warnIfSessionModeIgnored({logger:this.logger,transport:transportConfig,session:this.metadata.session});const transportService=this.transportService;if(this.haManager&&isDistributed&&transportService?.getBackendKind()==="redis"){this.haManager.startOrphanScanner({sessionKeyPrefix:transportService.getSessionKeyPrefix(),onOrphan:(sessionId,previousNodeId,session)=>transportService.adoptClaimedSession(sessionId,previousNodeId,session)})}if(getRuntimeContext29().deployment==="serverless"){const protocolCfg=transportConfig?.protocol;const hasSSE=typeof protocolCfg==="string"?protocolCfg!=="stateless-api":protocolCfg?.sse===true;if(hasSSE){this.logger.warn('[Deployment] SSE transport is not supported in serverless deployments. Consider using protocol: "stateless-api" for serverless targets.')}}const effectiveEventStoreConfig=transportConfig?.eventStore??(isDistributed&&this.metadata.redis&&!this.cliMode&&!this.directOnly?{enabled:true,provider:"redis",redis:this.metadata.redis}:void 0);if(effectiveEventStoreConfig?.enabled&&!this.cliMode&&!this.directOnly){const{createEventStore:createEventStore2}=await Promise.resolve().then(()=>(init_event_stores(),event_stores_exports));const{eventStore}=createEventStore2(effectiveEventStoreConfig,this.logger);this._eventStore=eventStore;this.logger.info("EventStore initialized for SSE resumability",{provider:effectiveEventStoreConfig.provider??"memory",autoEnabled:!transportConfig?.eventStore&&isDistributed})}const elicitationConfigured=this.metadata.elicitation?.enabled===true;const elicitationEnabled=elicitationConfigured&&!this.cliMode;const elicitationPromise=elicitationConfigured?(async()=>{const inheritedRedis=this.metadata.elicitation?.redis??this.metadata.redis;const elicitationInMemory=this.cliMode||this.metadata.elicitation?.store===false;const elicitationRedis=elicitationInMemory?void 0:inheritedRedis;const elicitationSqlite=elicitationInMemory||elicitationRedis?void 0:resolvedTopLevelSqlite;const persistent=this.cliMode?void 0:this.metadata.elicitation?.persistent;const questionsHelper=persistent?await Promise.resolve().then(()=>(init_question_scope_helper(),question_scope_helper_exports)):void 0;const onEdgeRuntime2=isEdgeRuntime2();const questionsStorage=questionsHelper?.persistentQuestionsSettings(persistent,onEdgeRuntime2).storage;const questionsRedis=!elicitationInMemory&&!elicitationRedis&&questionsStorage?.type==="redis"?questionsStorage:void 0;const{createElicitationStore:createElicitationStore2}=await Promise.resolve().then(()=>(init_elicitation_store_factory(),elicitation_store_factory_exports));const{store:elicitStore,type:elicitType,storage:elicitStorage}=await createElicitationStore2({redis:elicitationRedis,storage:elicitationInMemory?{type:"memory"}:questionsRedis,sqlite:elicitationSqlite,keyPrefix:elicitationRedis?.keyPrefix??"mcp:elicit:",logger:this.logger,isEdgeRuntime:onEdgeRuntime2});this._elicitationStore=elicitStore;this.elicitationBackendType=elicitType;if(elicitStorage){this.onDispose(async()=>{await elicitStore.destroy?.();await elicitStorage.disconnect()})}if(questionsHelper){const questions=await questionsHelper.openPersistentQuestions({persistent,serverName:this.metadata.info.name,redis:inheritedRedis,sqlite:resolvedTopLevelSqlite,onEdgeRuntime:onEdgeRuntime2,logger:this.logger});this._persistentQuestions=questions;if(questions)this.onDispose(()=>questions.store.close())}})():void 0;const tasksConfig=this.metadata.tasks;const tasksInMemory=tasksConfig?.store===false;const tasksMemoryStorage=tasksInMemory?{type:"memory"}:void 0;const serverRedisForTasks=tasksInMemory?void 0:this.metadata.redis;const serverSqliteForTasks=tasksInMemory?void 0:resolvedTopLevelSqlite;const tasksExplicitlyDisabled=tasksConfig?.enabled===false;const tasksExplicitlyEnabled=tasksConfig?.enabled===true;const isTaskWorker=!!this.metadata["__taskWorkerMode"];const hasPersistentBackend=Boolean(tasksConfig?.sqlite||tasksConfig?.redis||serverRedisForTasks||serverSqliteForTasks);const tasksEnabledForCli=this.cliMode&&hasPersistentBackend;const hasDistributedTaskBackend=Boolean(tasksConfig?.redis??serverRedisForTasks);const onEdgeRuntime=isEdgeRuntime2();const tasksUnavailableOnEdge=onEdgeRuntime&&!hasDistributedTaskBackend&&!tasksExplicitlyEnabled;if(tasksUnavailableOnEdge){this.logger.info("[tasks] Background tasks are unavailable on this edge/serverless runtime: the in-process runner cannot continue past the HTTP response, and an in-memory store is not shared between isolates. Serving without tasks. Configure `tasks.redis` (Upstash Redis over HTTP works on Workers) to enable them.")}const gateTasksRedis=tasksConfig?.redis??serverRedisForTasks;const tasksUseSqlite=Boolean(tasksConfig?.sqlite??(gateTasksRedis?void 0:serverSqliteForTasks));const tasksUnavailableOnVercelKv=!tasksExplicitlyEnabled&&!tasksUseSqlite&&resolvesToVercelKvTaskBackend(gateTasksRedis,tasksMemoryStorage);if(tasksUnavailableOnVercelKv&&!tasksExplicitlyDisabled){this.logger.warn("[tasks] Background tasks are disabled: Vercel KV has no pub/sub, which task results and cancellation require. Serving without tasks. Configure `tasks.redis` with Redis or Upstash to enable them.")}const shouldInitTasks=!tasksExplicitlyDisabled&&!tasksUnavailableOnEdge&&!tasksUnavailableOnVercelKv&&(!this.cliMode||tasksEnabledForCli||isTaskWorker);const useCliRunner=!isTaskWorker&&tasksConfig?.runner==="cli";let taskModule;let cliTaskRunner;const tasksPromise=shouldInitTasks?(async()=>{taskModule=await Promise.resolve().then(()=>(init_task_scope_runtime(),task_scope_runtime_exports));if(useCliRunner)cliTaskRunner=(await Promise.resolve().then(()=>(init_cli_task_runner(),cli_task_runner_exports))).CliTaskRunner;const tasksRedis=tasksConfig?.redis??serverRedisForTasks;const tasksSqlite=tasksConfig?.sqlite??(tasksRedis?void 0:serverSqliteForTasks);const onEdge=onEdgeRuntime;if(onEdge){const msg="[tasks] Background tasks are enabled on an edge/serverless runtime. The in-process runner cannot continue past the HTTP response on this platform \u2014 task bodies will not execute. Run on a long-lived Node process, or set `tasks.enabled: false`.";if(tasksConfig?.strict){throw new Error(msg+" (tasks.strict: true refuses startup)")}this.logger.warn(msg)}const{store:taskStore,type:taskType,storage:taskStorage}=await taskModule.createTaskStore({storage:tasksMemoryStorage,redis:tasksRedis,sqlite:tasksSqlite,keyPrefix:tasksConfig?.keyPrefix??"mcp:task:",logger:this.logger,isEdgeRuntime:onEdge,listFrom:tasksConfig?.listFrom,maxTtlMs:tasksConfig?.maxTtlMs});this._taskStore=taskStore;this.onDispose(async()=>{await taskStore.destroy?.();await taskStorage?.disconnect()});this.taskBackendType=taskType;this._taskRegistry=new taskModule.TaskRegistry({enabled:tasksConfig?.enabled,defaultTtlMs:tasksConfig?.defaultTtlMs,maxTtlMs:tasksConfig?.maxTtlMs,defaultPollIntervalMs:tasksConfig?.defaultPollIntervalMs,maxConcurrentPerSession:tasksConfig?.maxConcurrentPerSession,keyPrefix:tasksConfig?.keyPrefix,strict:tasksConfig?.strict,sqlite:tasksConfig?.sqlite,cliRunnerCommand:tasksConfig?.cliRunnerCommand},this.logger)})():void 0;const installTaskRunner=shouldInitTasks?()=>{const tasks=taskModule;if(!this._taskStore||!this._taskRegistry||!tasks)return;if(useCliRunner&&!tasksConfig?.sqlite&&!tasksConfig?.redis&&!serverRedisForTasks&&!serverSqliteForTasks){throw new Error('[tasks] runner: "cli" requires a persistent backend (`tasks.sqlite`, `tasks.redis`, or a top-level `sqlite` without `tasks.store: false`) \u2014 the detached worker cannot share an in-memory store with this host.')}const runner=cliTaskRunner?new cliTaskRunner({store:this._taskStore,command:tasksConfig?.cliRunnerCommand,logger:this.logger}):new tasks.InProcessTaskRunner({scope:this,store:this._taskStore,registry:this._taskRegistry,notifier:new tasks.TaskNotifier(this.notificationService,this.logger),logger:this.logger});this._taskRegistry.setRunner(runner);this.logger.info(`[tasks] runner installed: ${runner.kind}`)}:void 0;const throttleConfig=this.metadata.throttle;const rateLimitPromise=throttleConfig?.enabled&&!this.cliMode?createGuardManager({config:{...throttleConfig,storage:guardStorageInBrowser(throttleConfig.storage,this.logger)},logger:this.logger}).then(mgr=>{this._rateLimitManager=mgr}):void 0;const batch1=[this.scopeHooks.ready,this.scopeFlows.ready,this.scopeAuth.ready,this.scopeApps.ready];if(elicitationPromise)batch1.push(elicitationPromise);if(tasksPromise)batch1.push(tasksPromise);if(rateLimitPromise)batch1.push(rateLimitPromise);await Promise.all(batch1);if(this.metadata.authProvidersVault){const{registerAuthProvidersVault:registerAuthProvidersVault2}=await Promise.resolve().then(()=>(init_auth_providers_providers(),auth_providers_providers_exports));const closeVaultStorage=await registerAuthProvidersVault2(scopeProviders,this.metadata.authProvidersVault,this.auth.tokenStorageAdapter,this.logger);if(closeVaultStorage)this.onDispose(closeVaultStorage)}const serverHooks=serverProviderHooks(this.scopeProviders,this.metadata.providers,scopeRef);if(serverHooks.length>0)await this.scopeHooks.registerHooks(false,...serverHooks);this.logger.verbose("HookRegistry initialized");this.logger.verbose("FlowRegistry initialized");if(this.transportService)this.logger.verbose("TransportService initialized");this.logger.verbose("AuthRegistry initialized");mark("batch1:parallel (hooks+flows+auth+apps)");let topLevelSqliteUsed=this.transportService?.isSessionStoreConfigured()===true&&this.transportService.getBackendKind()==="sqlite"||this.taskBackendType==="sqlite"||this.elicitationBackendType==="sqlite"||this._persistentQuestions?.type==="sqlite";const serverPlugins=[...this.metadata.plugins??[]];const appPlugins=this.scopeApps.getApps().flatMap(app=>"plugins"in app.metadata?app.metadata.plugins??[]:[]);const impliedObservability=this.metadata.observability===void 0?devEventsObservabilityConfig([...serverPlugins,...appPlugins]):void 0;const observabilityConfig=this.metadata.observability??impliedObservability;if(observabilityConfig){if(listsObservabilityPlugin(serverPlugins)){throw new PluginConfiguredTwiceError("ObservabilityPlugin","observability")}const{observabilityPlugins:observabilityPlugins2}=await Promise.resolve().then(()=>(init_observability_scope_helper(),observability_scope_helper_exports));serverPlugins.push(...observabilityPlugins2({config:observabilityConfig,logger:this.logger,globalProviders:this.globalProviders,implied:impliedObservability!==void 0}))}if(serverPlugins.length>0){const serverPluginScopeInfo={ownScope:this,parentScope:void 0,isStandaloneApp:false};this.scopePlugins=new PluginRegistry(this.scopeProviders,serverPlugins,scopeRef,serverPluginScopeInfo)}if(this.scopePlugins){await this.scopePlugins.ready}if(this.metadata.adapters?.length){const scopeAdapters=new AdapterRegistry(this.scopeProviders,this.metadata.adapters);this.scopeAdapters=scopeAdapters;await scopeAdapters.ready;this.onDispose(()=>scopeAdapters.dispose())}await registerServerEntries(this.scopeProviders,this.metadata,this.scopeApps.getApps().map(app=>app.id));await this.initAuthoritiesFromConfig();this.scopeTools=new ToolRegistry(this.scopeProviders,[],scopeRef);this.scopeResources=new ResourceRegistry(this.scopeProviders,[],scopeRef);this.scopePrompts=new PromptRegistry(this.scopeProviders,[],scopeRef);this.scopeAgents=new AgentRegistry(this.scopeProviders,[],scopeRef);const skillsConfig=this.metadata.skillsConfig;this.scopeSkills=new SkillRegistry(this.scopeProviders,this.metadata.skills??[],scopeRef,{...skillsConfig?.scoring?{scoring:skillsConfig.scoring}:{},...skillsConfig?.decision?{decision:skillsConfig.decision}:{},...skillsConfig?.failOnInvalidSkills!==void 0&&{failOnInvalidSkills:skillsConfig.failOnInvalidSkills}});await Promise.all([this.scopeTools.ready,this.scopeResources.ready,this.scopePrompts.ready,this.scopeAgents.ready,this.scopeSkills.ready]);if(this.scopePlugins){const pluginNames=this.scopePlugins.getPluginNames();this.logger.verbose(`PluginRegistry initialized (${pluginNames.length} plugin(s): [${pluginNames.join(", ")}])`)}const toolNames=this.scopeTools.getTools(true).map(t=>t.metadata.name);this.logger.verbose(`ToolRegistry initialized with initial ${toolNames.length} tool(s): [${toolNames.join(", ")}]`);this.logger.verbose(`ResourceRegistry initialized (${this.scopeResources.getResources().length} resource(s))`);this.logger.verbose(`PromptRegistry initialized (${this.scopePrompts.getPrompts().length} prompt(s))`);this.logger.verbose(`AgentRegistry initialized (${this.scopeAgents.getAgents().length} agent(s))`);this.logger.verbose(`SkillRegistry initialized (${this.scopeSkills.getSkills().length} skill(s))`);mark("batch2:parallel (tools+resources+prompts+agents+skills+plugins)");this.validateAuthoritiesConfig();this.validateEnforcedMetadata();checkHookOrder(hookRunsOf(this.scopeHooks),message=>this.logger.warn(message));for(const message of describeUnlistedOutputSchemas(this))this.logger.warn(message);await this.initGuardForDeclaredLimits();if(elicitationEnabled){await this.registerSendElicitationResultTool(scopeRef)}let uiResolver;if(!this.cliMode){const cdnOverrides=this.metadata.ui?.cdnOverrides;if(cdnOverrides&&Object.keys(cdnOverrides).length>0){const{createResolverWithOverrides:createResolverWithOverrides2}=__require("@frontmcp/uipack/resolver");uiResolver=createResolverWithOverrides2(cdnOverrides);this.logger.verbose("Created UI resolver with CDN overrides",{overrides:Object.keys(cdnOverrides)})}}this.toolUIRegistry=new ToolUIRegistry(uiResolver,{escapeStringResults:this.metadata.ui?.escapeStringResults,logger:this.logger});if(!this.cliMode){await this.compileUIWidgets()}if(!this.cliMode){await this.buildAuthUiRegistry()}const dynamicSkills=pluginsRegisterDynamicSkills([...serverPlugins,...appPlugins]);if(this.scopeSkills.hasAny()||dynamicSkills){await this.startSkillSession()}if(this.scopeSkills.hasAny()){try{const report=await this.scopeSkills.validateAllTools();if(report.warningCount>0){this.logger.verbose("Skill validation completed with warnings",{totalSkills:report.totalSkills,warningCount:report.warningCount})}}catch(error){if(error instanceof SkillValidationError){this.logger.error("Skill validation failed",{failedSkills:error.failedSkills.map(s=>({name:s.skillName,missingTools:s.missingTools}))});throw error}throw error}}await registerSkillCapabilities({skillRegistry:this.scopeSkills,flowRegistry:this.scopeFlows,resourceRegistry:this.scopeResources,providers:this.scopeProviders,skillsConfig:this.metadata.skillsConfig,logger:this.logger,dynamicSkills});if(this.scopeSkills.servesSkills())this.skillsServed=Promise.resolve();const jobsConfig=this.metadata.jobs;const metaRecord=this.metadata;const jobsList=metaRecord["jobTypes"]??[];const workflowsList=metaRecord["workflowTypes"]??[];const{items:appJobs,providers:jobProviders}=this.appEntryProviders("jobs",normalizeJob);const appWorkflows=[];for(const app of this.scopeApps.getApps()){const appMeta=app.metadata;if(Array.isArray(appMeta["workflows"]))appWorkflows.push(...appMeta["workflows"])}for(const served of this.pendingAppJobs){appJobs.push(...served.entries.jobs);for(const job of served.entries.jobs){jobProviders.set(normalizeJob(job).provide,served.entries.providers)}appWorkflows.push(...served.entries.workflows)}const allJobs=[...jobsList,...appJobs];const allWorkflows=[...workflowsList,...appWorkflows];const hasJobDeclarations=allJobs.length>0||allWorkflows.length>0;const explicitlyDisabled=jobsConfig?.enabled===false;const explicitlyEnabled=jobsConfig?.enabled===true;const autoEnabled=!explicitlyEnabled&&!explicitlyDisabled&&hasJobDeclarations;const effectivelyEnabled=explicitlyEnabled||autoEnabled;if(explicitlyDisabled&&hasJobDeclarations){this.logger.warn(`Jobs are explicitly disabled but ${allJobs.length} job(s) and ${allWorkflows.length} workflow(s) were declared on @App. Agents will NOT be able to invoke them \u2014 remove jobs.enabled: false or drop the @App({ jobs }) declarations.`)}if(effectivelyEnabled){if(autoEnabled){this.logger.info(`Jobs auto-enabled: detected ${allJobs.length} job(s) and ${allWorkflows.length} workflow(s) in @App declarations. Their runs are kept in jobs.store, else the top-level redis or sqlite, else in memory.`)}const jobsUseTopLevelSqlite=await this.startJobs(allJobs,jobProviders,allWorkflows,resolvedTopLevelSqlite);topLevelSqliteUsed||=jobsUseTopLevelSqlite;const jobRegistry=this._scopeJobs;const workflowRegistry=this._scopeWorkflows;if(jobRegistry&&workflowRegistry&&this.pendingAppJobs.length>0){const{unregistersAppJobEntries:unregistersAppJobEntries2}=await Promise.resolve().then(()=>(init_job_scope_helper(),job_scope_helper_exports));for(const served of this.pendingAppJobs){served.unregister=unregistersAppJobEntries2(jobRegistry,workflowRegistry,served.entries)}}}this.pendingAppJobs.length=0;this.jobsDecided=true;this.topLevelSqlite=resolvedTopLevelSqlite;if(this.metadata.sqlite&&!topLevelSqliteUsed&&getRuntimeContext29().runtime!=="browser"){this.logger.warn("[FrontMcp] Top-level `sqlite` config was provided but no subsystem consumes it (transport persistence, tasks, elicitation and jobs were all disabled or pre-configured with a different backend). Sessions will use in-memory storage. Remove the `sqlite` block or enable one of the subsystems.")}this.notificationService=new NotificationService(this);await this.notificationService.initialize();this.logger.verbose("NotificationService initialized");const liveSurface=new LiveSurface(this);liveSurface.start();this.liveSurface=liveSurface;this.onDispose(()=>liveSurface.stop());const materializedResources=new MaterializedResources(this);await materializedResources.start();this.onDispose(()=>materializedResources.stop());installTaskRunner?.();await this.scopeFlows.registryFlows([SetLevelFlow,CompleteFlow]);if(this.scopeAgents.listAllInstances().length>0){await this.serveAgentCalls()}if(this.metadata.elicitation?.enabled===true){const{ElicitationRequestFlow:ElicitationRequestFlow2,ElicitationResultFlow:ElicitationResultFlow2}=await Promise.resolve().then(()=>(init_flows2(),flows_exports2));await this.scopeFlows.registryFlows([ElicitationRequestFlow2,ElicitationResultFlow2])}if(taskModule){const{TasksGetFlow:TasksGetFlow2,TasksResultFlow:TasksResultFlow2,TasksCancelFlow:TasksCancelFlow2,TasksListFlow:TasksListFlow2}=taskModule;await this.scopeFlows.registryFlows([TasksGetFlow2,TasksResultFlow2,TasksCancelFlow2,TasksListFlow2])}if(this.metadata.registry){const{registerMcpRegistryFlows:registerMcpRegistryFlows2}=await Promise.resolve().then(()=>(init_mcp_registry_scope_helper(),mcp_registry_scope_helper_exports));await registerMcpRegistryFlows2({flowRegistry:this.scopeFlows,registryOptions:this.metadata.registry,servesServerEndpoint:this.routeBase===""&&this.metadata.apps.length>0})}await this.auth.ready;await transportService?.ready;if(this.haManager&&this.transportBus&&transportService){const{wireSessionRelay:wireSessionRelay2}=await Promise.resolve().then(()=>(init_relay_scope_helper(),relay_scope_helper_exports));this.sessionRelayHandle=wireSessionRelay2({nodeId:getMachineId6(),haManager:this.haManager,bus:this.transportBus,transportService,notifications:this.notificationService,flows:{runFlow:(name59,input)=>this.runFlow(name59,input)},logger:this.logger})}if(httpServing){httpServing.attachHttpRoutes(this,this.globalProviders);httpServing.registerCustomHttpRoutes({routes:this.metadata.http?.routes,server:this.httpRouteRegistrar,verifySession:request2=>this.runFlow("session:verify",{request:request2}),checkClientIp:(request2,response)=>this.runFlow("http:ip-filter",{request:request2,response}),entryPath:this.entryPath,routeBase:this.routeBase,healthPaths:httpServing.servedHealthPaths(this.metadata.health),logger:this.logger})}const channelsConfig=this.metadata.channels;if(channelsConfig?.enabled){const{items:appChannels,providers:channelProviders}=this.appEntryProviders("channels",normalizeChannel);const{registerChannelCapabilities:registerChannelCapabilities2}=await Promise.resolve().then(()=>(init_channel_scope_helper(),channel_scope_helper_exports));const channelResult=await registerChannelCapabilities2({providers:this.scopeProviders,owner:scopeRef,channelsList:appChannels,channelProviders,channelsConfig,eventBus:this._channelEventBus,notificationService:this.notificationService,flowRegistry:this.scopeFlows,toolRegistry:this.scopeTools,http:httpServing&&{server:this.httpRouteRegistrar,checkClientIp:(request2,response)=>this.runFlow("http:ip-filter",{request:request2,response}),entryPath:this.entryPath,routeBase:this.routeBase,healthPaths:httpServing.servedHealthPaths(this.metadata.health)},logger:this.logger});this._scopeChannels=channelResult.channelRegistry;this._channelNotificationService=channelResult.channelNotificationService;this._channelEventBus=channelResult.channelEventBus;this._channelTeardown=channelResult.teardown;this.onDispose(()=>this.teardownChannels());this.validateAuthoritiesConfig();this.validateEnforcedMetadata();if(!isJobWorker(this.metadata))await channelResult.connectServices()}const{items:appEvents,providers:eventProviders}=this.appEntryProviders("events",normalizeEvent);if(appEvents.length>0||this.metadata.events?.enabled===true){const{registerEventCapabilities:registerEventCapabilities2}=await Promise.resolve().then(()=>(init_event_scope_helper(),event_scope_helper_exports));const eventsResult=await registerEventCapabilities2({providers:this.scopeProviders,owner:scopeRef,eventsList:appEvents,eventProviders,eventsConfig:this.metadata.events,channelsEnabled:channelsConfig?.enabled,logger:this.logger});this._scopeEvents=eventsResult?.eventRegistry}await this.registerWidgetRoutes(httpServing);if(httpServing&&this.metadata.health?.enabled!==false){this._healthService=new httpServing.HealthService(this.metadata.health??{},this.metadata.info);this._healthService.autoDiscoverProbes(this);this.logger.verbose(`HealthService initialized (${this._healthService.getProbeCount()} probe(s))`)}for(const message of await describeBudgetOverruns(this))this.logger.warn(message);mark("batch3:finalization");this.logger.info(`Scope ready \u2014 ${this.formatScopeSummary()}`);reportStartup(this.scopePlugins,{toolsCount:this.scopeTools.getTools(true).length,resourcesCount:this.scopeResources.getResources().length,promptsCount:this.scopePrompts.getPrompts().length,durationMs:Date.now()-startedAt,scopeId:this.id},this.logger)}async primaryAuthFactory(){if(this.directOnly&&this.metadata.auth===void 0){return(scope,_providers,options)=>new DirectPublicAuth(scope,options)}const{createPrimaryAuth:createPrimaryAuth2}=await Promise.resolve().then(()=>(init_primary_auth_factory(),primary_auth_factory_exports));return createPrimaryAuth2}async resolveTopLevelSqlite(){const raw=this.metadata.sqlite;if(!raw||getRuntimeContext29().runtime==="browser")return void 0;let finalPath=raw.path;if(!finalPath||finalPath.length===0){finalPath=resolveDefaultSqlitePath({appName:this.metadata.info?.name,cliMode:this.cliMode});this.logger.info("[FrontMcp] No `sqlite.path` set \u2014 using default",{path:finalPath})}try{const{dirname:dirname10}=__require("path");await mkdir3(dirname10(finalPath),{recursive:true})}catch(err){this.logger.warn("[FrontMcp] Could not ensure sqlite parent directory exists",{path:finalPath,error:err.message})}return{...raw,path:finalPath}}async compileUIWidgets(){const toolsWithUI=this.scopeTools.getTools(true).filter(t=>hasUIConfig(t.metadata));if(toolsWithUI.length===0)return;const[{describeIgnoredUiOptions:describeIgnoredUiOptions2,describeServingModeDefault:describeServingModeDefault2},{StaticWidgetResourceTemplate:StaticWidgetResourceTemplate2},{describeWidgetServingProblems:describeWidgetServingProblems2,widgetUrlSourceOf:widgetUrlSourceOf2}]=await Promise.all([Promise.resolve().then(()=>(init_ui_option_warnings(),ui_option_warnings_exports)),Promise.resolve().then(()=>(init_ui_resource_template(),ui_resource_template_exports)),Promise.resolve().then(()=>(init_widget_serving(),widget_serving_exports)),this.toolUIRegistry.load()]);for(const tool of toolsWithUI){const resourceUri=tool.metadata.ui?.resourceUri;this.toolUIRegistry.registerTool(tool.metadata.name,typeof resourceUri==="string"?resourceUri:void 0);this.toolUIRegistry.checkTemplate(tool.metadata.name,tool.metadata.ui?.template,tool.metadata.ui?.uiType);await this.toolUIRegistry.checkRenderOptions(tool.metadata.name,tool.metadata.ui);for(const message of describeIgnoredUiOptions2(tool.metadata.name,tool.metadata.ui)){this.logger.warn(message)}}for(const message of describeServingModeDefault2("`@FrontMcp({ ui })`",this.metadata.ui?.servingMode)){this.logger.warn(message)}for(const app of this.apps.getApps()){const appMode=app.metadata.ui?.servingMode;for(const message of describeServingModeDefault2(`App "${app.id}" \`@App({ ui })\``,appMode)){this.logger.warn(message)}}this.scopeResources.registerDynamicResource(StaticWidgetResourceTemplate2);this.logger.verbose(`Registered UI resource template for ${toolsWithUI.length} tool(s) with UI configs`);const servingModes=new Map(toolsWithUI.map(t=>[t,toolServingMode(t,this)]));const servingProblems=toolsWithUI.flatMap(t=>describeWidgetServingProblems2(t.metadata.name,t.metadata.ui??{},servingModes.get(t)??"auto"));if(servingProblems.length>0)throw new InvalidToolUiConfigError(servingProblems);for(const tool of toolsWithUI){const uiConfig=tool.metadata.ui??{};const source=widgetUrlSourceOf2(tool.metadata.name,uiConfig,servingModes.get(tool)??"auto");if(!source)continue;this.toolUIRegistry.registerWidgetUrl(tool.metadata.name,source);if(source.servingMode==="custom-url")this.toolUIRegistry.updateResourceMetaFromConfig(tool.metadata.name,uiConfig)}const staticModeTools=toolsWithUI.filter(t=>{const mode=servingModes.get(t);return t.metadata.ui&&(mode==="static"||mode==="direct-url")&&t.metadata.ui.template});if(staticModeTools.length>0){let staticCompiledCount=0;await Promise.all(staticModeTools.map(async tool=>{const uiConfig=tool.metadata.ui;if(!uiConfig?.template){this.logger.warn(`Skipping static widget pre-compile for tool "${tool.metadata.name}" due to missing ui.template`);return}try{await this.toolUIRegistry.compileStaticWidgetAsync({toolName:tool.metadata.name,template:uiConfig.template,uiConfig});staticCompiledCount++;this.logger.verbose(`Compiled static widget for tool: ${tool.metadata.name}`)}catch(error){const errorMessage2=error instanceof Error?error.message:String(error);this.logger.error(`Failed to compile static widget for tool "${tool.metadata.name}": ${errorMessage2}`)}}));this.logger.info(`Pre-compiled ${staticCompiledCount}/${staticModeTools.length} static widget(s) for static mode tools`)}const inlineTools=toolsWithUI.filter(t=>{const mode=servingModes.get(t);return t.metadata.ui&&(mode==="inline"||mode==="auto")&&t.metadata.ui.template});if(inlineTools.length>0){let inlineCompiledCount=0;await Promise.all(inlineTools.map(async tool=>{const uiConfig=tool.metadata.ui;if(!uiConfig){this.logger.warn(`Skipping lean widget pre-compile for tool "${tool.metadata.name}" due to missing ui config`);return}try{await this.toolUIRegistry.compileLeanWidgetAsync({toolName:tool.metadata.name,uiConfig});inlineCompiledCount++;this.logger.verbose(`Compiled lean widget shell for tool: ${tool.metadata.name}`)}catch(error){const errorMessage2=error instanceof Error?error.message:String(error);this.logger.error(`Failed to compile lean widget shell for tool "${tool.metadata.name}": ${errorMessage2}`)}}));this.logger.info(`Pre-compiled ${inlineCompiledCount}/${inlineTools.length} lean widget shell(s) for inline mode tools`)}const hybridTools=toolsWithUI.filter(t=>t.metadata.ui&&servingModes.get(t)==="hybrid"&&t.metadata.ui.template);if(hybridTools.length>0){let hybridCompiledCount=0;await Promise.all(hybridTools.map(async tool=>{const uiConfig=tool.metadata.ui;if(!uiConfig){this.logger.warn(`Skipping hybrid widget pre-compile for tool "${tool.metadata.name}" due to missing ui config`);return}try{await this.toolUIRegistry.compileHybridWidgetAsync({toolName:tool.metadata.name,template:uiConfig.template,uiConfig});hybridCompiledCount++;this.logger.verbose(`Compiled hybrid widget shell for tool: ${tool.metadata.name}`)}catch(error){const errorMessage2=error instanceof Error?error.message:String(error);this.logger.error(`Failed to compile hybrid widget shell for tool "${tool.metadata.name}": ${errorMessage2}`)}}));this.logger.info(`Pre-compiled ${hybridCompiledCount}/${hybridTools.length} hybrid widget shell(s) for hybrid mode tools`)}}async registerWidgetRoutes(httpServing){const widgets=this.toolUIRegistry?.widgetRoutes()??[];if(widgets.length===0)return;if(!httpServing){for(const{toolName,path:path4}of widgets){this.logger.warn(`Tool "${toolName}": \`ui.servingMode: 'direct-url'\` serves the widget on GET ${path4}, and this in-process server serves no HTTP, so hosts cannot load it.`)}return}const{registerWidgetRoutes:registerWidgetRoutes2}=await Promise.resolve().then(()=>(init_widget_routes(),widget_routes_exports));await registerWidgetRoutes2({widgets,registry:this.toolUIRegistry,server:this.httpRouteRegistrar,checkClientIp:(request2,response)=>this.runFlow("http:ip-filter",{request:request2,response}),entryPath:this.entryPath,routeBase:this.routeBase,healthPaths:httpServing.servedHealthPaths(this.metadata.health),takenRoutes:[...this.registeredHttpRoutes.map(route=>({...route,owner:"a route of the server"})),...(this.httpRouteTable?.routes??[]).map(route=>({...route,owner:"an @HttpRoute"}))],flowFor:request2=>this.findHttpFlowName(request2),logger:this.logger})}async buildAuthUiRegistry(){const auth=this.metadata.auth;const authUi=auth?.ui;const authExtras=auth?.extras;const uiSlotCount=authUi?Object.keys(authUi).length:0;const extraCount=authExtras?Object.keys(authExtras).length:0;if(uiSlotCount===0&&extraCount===0)return;let sourceDir=this.metadata.__sourceDir;if(!sourceDir){sourceDir=process.cwd();if(uiSlotCount>0){this.logger.warn(`auth.ui paths will resolve against process.cwd() ("${sourceDir}") \u2014 the declaring @FrontMcp/@App source directory could not be captured. Use absolute paths if this is wrong.`)}}const{AuthUiRegistry:AuthUiRegistry2}=await Promise.resolve().then(()=>(init_auth_ui(),auth_ui_exports));const registry=new AuthUiRegistry2(this.logger);registry.registerAuthUiMap(authUi,sourceDir);registry.registerAuthExtrasMap(authExtras);const cdnOverrides=this.metadata.ui?.cdnOverrides;if(cdnOverrides&&Object.keys(cdnOverrides).length>0){registry.setResolverOverrides(cdnOverrides)}try{await registry.warmup()}catch(error){this.logger.warn("Auth-UI registry warmup encountered errors \u2014 affected custom pages will fall back to built-in",{error:error instanceof Error?error.message:String(error)})}this.authUiRegistry=registry;this.logger.verbose(`Auth-UI registry initialized (${uiSlotCount} slot file(s), ${extraCount} extra(s))`)}formatScopeSummary(){const entries=[];const add=(count,label)=>{if(count>0)entries.push(`${count} ${label}${count!==1?"s":""}`)};add(this.scopeApps.getApps().length,"app");add(this.scopeTools.getTools(true).length,"tool");add(this.scopeResources.getResources().length,"resource");add(this.scopePrompts.getPrompts().length,"prompt");add(this.scopeAgents.getAgents().length,"agent");add(this.scopeSkills.getSkills().length,"skill");if(this._scopeJobs)add(this._scopeJobs.getJobs().length,"job");if(this._scopeWorkflows)add(this._scopeWorkflows.getWorkflows().length,"workflow");if(this._scopeChannels)add(this._scopeChannels.size,"channel");if(this._scopeEvents)add(this._scopeEvents.getEvents().length,"event");return entries.length>0?entries.join(", "):"empty"}get defaultScopeProviders(){return[{scope:ProviderScope2.GLOBAL,name:"ScopeEntry",provide:ScopeEntry,useValue:this},{scope:ProviderScope2.GLOBAL,name:"Scope",provide:_Scope,useValue:this},{scope:ProviderScope2.GLOBAL,name:"FrontMcpLogger",provide:FrontMcpLogger,useValue:this.logger},{scope:ProviderScope2.GLOBAL,name:"FrontMcpContextStorage",provide:FrontMcpContextStorage,useValue:new FrontMcpContextStorage().configure(this.metadata.fetch,{...proxyTrustOf(this.metadata.throttle),forwardsHeader:createHeaderForwarder(this.metadata.http?.forwardHeaders)})},FrontMcpContextProvider,{scope:ProviderScope2.GLOBAL,name:"OffloadService",provide:OffloadService,useValue:new OffloadService(this.metadata.offload,this.logger)},...eventPublisherProviders(this)]}get auth(){return this.scopeAuth.getPrimary()}get hooks(){return this.scopeHooks}get authProviders(){return this.scopeAuth}get providers(){return this.scopeProviders}get apps(){return this.scopeApps}get tools(){return this.scopeTools}get toolUI(){return this.toolUIRegistry}get authUi(){return this.authUiRegistry}get resources(){return this.scopeResources}get prompts(){return this.scopePrompts}get agents(){return this.scopeAgents}get skills(){return this.scopeSkills}get jobs(){return this._scopeJobs}get workflows(){return this._scopeWorkflows}get channels(){return this._scopeChannels}get channelNotifications(){return this._channelNotificationService}get events(){return this._scopeEvents}get channelEventBus(){return this._channelEventBus??this._workflowEvents?.bus}async startJobs(jobs,jobProviders,workflows,topLevelSqlite){const jobsConfig=this.metadata.jobs;const scopeRef={kind:"scope",id:this.id,ref:_Scope};const notifyFn=async data=>{if(this.notificationService){this.logger.debug("Job notification",data)}};const{registerJobCapabilities:registerJobCapabilities2,resolveJobsStore:resolveJobsStore2,jobsServerStore:jobsServerStore2}=await Promise.resolve().then(()=>(init_job_scope_helper(),job_scope_helper_exports));refuseServerStoresInBrowser({jobs:jobsServerStore2(jobsConfig?.store,this.metadata)});const jobsStore2=resolveJobsStore2(jobsConfig?.store,{redis:this.metadata.redis,sqlite:topLevelSqlite});const effectiveConfig={...jobsConfig??{},enabled:true,store:jobsStore2};const result=await registerJobCapabilities2({providers:this.scopeProviders,flowRegistry:this.scopeFlows,owner:scopeRef,jobsList:jobs,jobProviders,workflowsList:workflows,jobsConfig:effectiveConfig,logger:this.logger,notifyFn,entryServer:isEntryServer(this.metadata),jobWorker:isJobWorker(this.metadata)});this._scopeJobs=result.jobRegistry;this._scopeWorkflows=result.workflowRegistry;this._jobExecutionManager=result.executionManager;this._jobStateStore=result.stateStore;this._jobDefinitionStore=result.definitionStore;this._workflowEvents=result.workflowEvents;this._channelEventBus??=result.workflowEvents?.bus;for(const toolCls of result.managementTools){try{const toolRecord=normalizeTool(toolCls);const toolInstance=new ToolInstance(toolRecord,this.scopeProviders,{kind:"scope",id:"_jobs",ref:toolCls});this.scopeTools.registerToolInstance(toolInstance)}catch(error){this.logger.warn(`Failed to register job management tool: ${error instanceof Error?error.message:String(error)}`)}}this.logger.info(`Jobs system initialized: ${this._scopeJobs.getJobs().length} jobs, ${this._scopeWorkflows.getWorkflows().length} workflows`);return Boolean(topLevelSqlite)&&jobsStore2?.sqlite===topLevelSqlite}async serveAppJobs(entries){const served={entries};const withdraw=()=>{const pending=this.pendingAppJobs.indexOf(served);if(pending!==-1)this.pendingAppJobs.splice(pending,1);served.unregister?.();served.unregister=void 0};if(!this.jobsDecided){this.pendingAppJobs.push(served);return withdraw}if(this.metadata.jobs?.enabled===false){this.logger.warn(`Jobs are explicitly disabled, so the ${entries.jobs.length} job(s) and ${entries.workflows.length} workflow(s) an app loaded are not served. Remove jobs.enabled: false to serve them.`);return withdraw}this.lateJobsStart??=this._scopeJobs?Promise.resolve():keptUntilFailure(this.startJobs([],new Map,[],this.topLevelSqlite).then(()=>void 0),()=>this.lateJobsStart=void 0);await this.lateJobsStart;const jobRegistry=this._scopeJobs;const workflowRegistry=this._scopeWorkflows;if(!jobRegistry||!workflowRegistry)throw new InternalMcpError("The job system did not start");const{registerAppJobEntries:registerAppJobEntries2}=await Promise.resolve().then(()=>(init_job_scope_helper(),job_scope_helper_exports));served.unregister=await registerAppJobEntries2({jobRegistry,workflowRegistry,jobs:entries.jobs,workflows:entries.workflows,providers:entries.providers,runner:this.metadata.jobs?.runner});return withdraw}serveLateEntries(kinds){return Promise.all(kinds.map(kind=>kind==="agents"?this.serveAgentCalls():this.serveSkillsAddedLater())).then(()=>void 0)}serveAgentCalls(){this.agentCallsServed??=keptUntilFailure(Promise.resolve().then(()=>(init_flows4(),flows_exports3)).then(({CallAgentFlow:CallAgentFlow2})=>this.scopeFlows.registryFlows([CallAgentFlow2])),()=>this.agentCallsServed=void 0);return this.agentCallsServed}serveSkillsAddedLater(){this.skillsServed??=keptUntilFailure((async()=>{if(!this._skillSession)await this.startSkillSession();await serveSkillMethods({skillRegistry:this.scopeSkills,flowRegistry:this.scopeFlows,resourceRegistry:this.scopeResources,providers:this.scopeProviders,skillsConfig:this.metadata.skillsConfig,logger:this.logger})})(),()=>this.skillsServed=void 0);return this.skillsServed}async startSkillSession(){const[skillSession,{createSkillToolGuardHook:createSkillToolGuardHook2}]=await Promise.all([Promise.resolve().then(()=>(init_session2(),session_exports)),Promise.resolve().then(()=>(init_hooks(),hooks_exports))]);const store=skillSession.createSkillSessionStore({type:"memory"});this._skillSession=new skillSession.SkillSessionManager({defaultPolicyMode:"permissive"},this.logger,store);const GuardHookClass=createSkillToolGuardHook2(this._skillSession,{logger:this.logger,trackToolCalls:true,verifiedSessionId:()=>this.verifiedRequestSessionId()});const guardHookInstance=new GuardHookClass;const hookRecords=normalizeHooksFromCls(guardHookInstance);if(hookRecords.length>0){await this.scopeHooks.registerHooks(false,...hookRecords);this.logger.verbose("Skill tool authorization guard hook registered")}this.logger.verbose("Skill session manager initialized",{storeType:store.type})}verifiedRequestSessionId(){try{return this.scopeProviders.get(FrontMcpContextStorage).getStore()?.verifiedSessionId}catch{return void 0}}get skillSession(){return this._skillSession}get plugins(){return this.scopePlugins}get notifications(){return this.notificationService}get surface(){return this.liveSurface}get elicitationStore(){return this._elicitationStore}get persistentQuestions(){return this._persistentQuestions}get taskStore(){return this._taskStore}get tasks(){return this._taskRegistry}get eventStore(){return this._eventStore}get rateLimitManager(){return this._rateLimitManager}get publicAccessGuard(){return this._rateLimitManager??this._publicAccessGuard}get httpRoutes(){return this.registeredHttpRoutes}get healthService(){return this._healthService}get authoritiesEngine(){return this._authoritiesEngine}get authoritiesContextBuilder(){return this._authoritiesContextBuilder}get authoritiesScopeMapping(){return this._authoritiesScopeMapping}getAllSupportedScopes(){const scopes=new Set;const collectScopes=metadata=>{const authProviders=metadata?.["authProviders"];if(!Array.isArray(authProviders))return;for(const ap of authProviders){if(typeof ap==="object"&&ap!==null&&"scopes"in ap){const apScopes=ap["scopes"];if(Array.isArray(apScopes)){apScopes.forEach(s=>{if(typeof s==="string")scopes.add(s)})}}}};for(const tool of this.scopeTools.getTools(true)){collectScopes(tool.metadata)}for(const resource of this.scopeResources.getResources()){collectScopes(resource.metadata)}for(const prompt of this.scopePrompts.getPrompts()){collectScopes(prompt.metadata)}for(const agent of this.scopeAgents.getAgents()){collectScopes(agent["metadata"])}return[...scopes].sort()}registerAuthoritiesEngine(engine,contextBuilder){this._authoritiesEngine=engine;this._authoritiesContextBuilder=contextBuilder}async initAuthoritiesFromConfig(){const config=this.metadata["authorities"];if(!config)return;try{const{authoritiesFromConfig:authoritiesFromConfig2}=await Promise.resolve().then(()=>(init_authorities_engine(),authorities_engine_exports));const authorities=authoritiesFromConfig2(config);this._authoritiesEngine=authorities.engine;this._authoritiesContextBuilder=authorities.contextBuilder;this._authoritiesScopeMapping=authorities.scopeMapping;this.logger.verbose("Scope: authorities engine initialized from config")}catch(error){const msg=error instanceof Error?error.message:String(error);this.logger.warn(`Scope: authorities init failed \u2014 ${msg}`)}}appEntryProviders(key,normalize){const items=[];const providers=new Map;for(const app of this.scopeApps.getApps()){const declared=app.metadata[key];if(!Array.isArray(declared))continue;for(const item of declared){items.push(item);providers.set(normalize(item).provide,app.providers)}}return{items,providers}}async initGuardForDeclaredLimits(lateTools=[]){const throttleConfig=this.metadata.throttle;if(this._rateLimitManager||this.cliMode)return;if(throttleConfig?.enabled===false){await this.initPublicAccessGuard(throttleConfig.storage);return}const guardedEntries=[...this.scopeTools.getTools(true),...lateTools,...this.scopeAgents.getAgents(true)];const declaresLimits=guardedEntries.some(entry=>entry.metadata.rateLimit||entry.metadata.concurrency)||!!this.auth.options?.publicAccess||this.scopeAgents.listAllInstances().some(agent=>agent.declaresScopedLimits());if(!declaresLimits)return;this._rateLimitManager=await createGuardManager({config:{...throttleConfig,enabled:true,storage:guardStorageInBrowser(throttleConfig?.storage,this.logger)},logger:this.logger})}async initPublicAccessGuard(storage){const publicAccess=this.auth.options?.publicAccess;if(!publicAccess?.rateLimit||this._publicAccessGuard)return;this._publicAccessGuard=await createGuardManager({config:{enabled:true,storage:guardStorageInBrowser(storage,this.logger)},logger:this.logger})}collectEntriesWithAuthorities(){return entriesWithAuthorities({tools:this.scopeTools,resources:this.scopeResources,prompts:this.scopePrompts,agents:this.scopeAgents,skills:this.scopeSkills})}validateAuthoritiesConfig(){assertEntryAuthorities(this._authoritiesEngine,this._authoritiesContextBuilder,this.collectEntriesWithAuthorities())}async checkLateApp(app){const{tools,resources,prompts,agents,skills}=app;assertEntryAuthorities(this._authoritiesEngine,this._authoritiesContextBuilder,entriesWithAuthorities(app));const problems=findUnenforcedMetadata({hooks:this.scopeHooks,tools,resources,prompts,agents,skills});if(problems.length>0)throw new UnenforcedMetadataError(problems);checkHookOrder(hookRunsOf(this.scopeHooks),message=>this.logger.warn(message));const setup=this.lateGuardSetup.then(()=>this.initGuardForDeclaredLimits(tools.getTools(true)));this.lateGuardSetup=setup.catch(()=>void 0);await setup}validateEnforcedMetadata(){const problems=findUnenforcedMetadata({hooks:this.scopeHooks,tools:this.scopeTools,resources:this.scopeResources,prompts:this.scopePrompts,agents:this.scopeAgents,skills:this.scopeSkills});if(problems.length>0)throw new UnenforcedMetadataError(problems)}async registerSendElicitationResultTool(_scopeRef){try{const{SendElicitationResultTool:SendElicitationResultTool2}=await Promise.resolve().then(()=>(init_send_elicitation_result_tool(),send_elicitation_result_tool_exports));const toolRecord=normalizeTool(SendElicitationResultTool2);const systemToolEntry=new ToolInstance(toolRecord,this.scopeProviders,{kind:"scope",id:"_system",ref:SendElicitationResultTool2});this.scopeTools.registerToolInstance(systemToolEntry);this.logger.verbose("Registered sendElicitationResult system tool")}catch(error){this.logger.warn(`Failed to register sendElicitationResult tool: ${error instanceof Error?error.message:String(error)}`)}}get pagination(){return this.metadata.pagination}registryFlows(...flows){return this.scopeFlows.registryFlows(flows)}runFlow(name59,input,deps){return this.scopeFlows.runFlow(name59,input,deps)}async findHttpFlowName(request2){return this.scopeFlows.findHttpFlowName(request2,SCOPE_NON_DISPATCHABLE_FLOWS)}async runFlowForOutput(name59,input,deps){const result=await this.scopeFlows.runFlow(name59,input,deps);if(result){return result}throw new FlowExitedWithoutOutputError}createHaRedisClient(label="ha"){const redis=this.metadata.redis;if(!redis||redis.provider==="vercel-kv"){throw new Error("Distributed HA requires a TCP Redis (ioredis); Vercel KV over REST has no Lua/pub-sub support")}const client=createRedisClient3({...redis,label,logger:this.logger});if(label==="ha-subscriber")this.haSubscriberClient=client;else this.haRedisClient=client;return client}async closeHaRedisClient(){const clients=[this.haRedisClient,this.haSubscriberClient];this.haRedisClient=void 0;this.haSubscriberClient=void 0;for(const client of clients){if(!client)continue;try{await client.quit()}catch{client.disconnect()}}}async shutdown(){if(this.sessionRelayHandle){try{await this.sessionRelayHandle.close()}catch(err){this.logger.error("[HA] Session relay shutdown failed",{error:err})}this.sessionRelayHandle=void 0}if(this.haManager){try{await this.haManager.stop()}catch(err){this.logger.error("[HA] Manager shutdown failed",{error:err})}}await this.closeHaRedisClient();await this.teardownChannels();this.httpRouteTable?.closeStreams()}async teardownChannels(){const teardown=this._channelTeardown;if(!teardown)return;this._channelTeardown=void 0;try{await teardown()}catch(err){this.logger.error("Channel teardown failed",{error:err})}}async dispose(){await this.emitDispose();await this.scopeProviders.runShutdownHooks(this.logger);this.scopeProviders.dispose();if(this.notificationService){await this.notificationService.destroy()}}}}});var init_scope=__esm({"libs/sdk/src/scope/index.ts"(){"use strict";init_scope_instance()}});function isProbe(property){return property==="then"||property==="toJSON"||property.startsWith("on")}function storeProvider(provider){storeFactories.add(provider.useFactory);return provider}function opensStore(factory){return typeof factory==="function"&&storeFactories.has(factory)}function storeNotOpened(name59){return new Proxy({},{get:(target,property,receiver)=>typeof property==="symbol"||isProbe(property)||property in target?Reflect.get(target,property,receiver):()=>{throw new StoreNotOpenedInBuildError(name59)}})}var storeFactories;var init_store_provider=__esm({"libs/sdk/src/provider/store.provider.ts"(){"use strict";init_build_store_errors();storeFactories=new WeakSet}});var LazyLeaseStore;var init_lazy_lease_store=__esm({"libs/sdk/src/duty/lazy-lease-store.ts"(){"use strict";init_describe_thrown();init_lease_store();LazyLeaseStore=class{constructor(config){this.config=config}config;openFailure;opened;async get(key){return(await this.open()).get(key)}async set(key,value,options){await(await this.open()).set(key,value,options)}async setIfEquals(key,expectedValue,value){return(await this.open()).setIfEquals(key,expectedValue,value)}async ttl(key){return(await this.open()).ttl(key)}async expireIfEquals(key,expectedValue,ttlSeconds){return(await this.open()).expireIfEquals(key,expectedValue,ttlSeconds)}async deleteIfEquals(key,expectedValue){return(await this.open()).deleteIfEquals(key,expectedValue)}async disconnect(){const storage=await this.opened?.catch(()=>void 0);await storage?.disconnect()}open(){this.opened??=openLeaseStore(this.config).then(storage=>{this.openFailure=void 0;return storage},error=>{this.opened=void 0;this.openFailure=describeThrown(error);throw error});return this.opened}}}});var duty_lifecycle_exports={};__export(duty_lifecycle_exports,{DutyLifecycle:()=>DutyLifecycle,dutyHealth:()=>dutyHealth,dutyLifecycleOf:()=>dutyLifecycleOf,dutyStorageConfig:()=>dutyStorageConfig,startDuties:()=>startDuties});function dutyLifecycleOf(duty,metadata,providers){let lifecycle=lifecycles.get(duty);if(!lifecycle){lifecycle=new DutyLifecycle(duty,metadata,providers);lifecycles.set(duty,lifecycle)}return lifecycle}async function startDuties(providers){for(const instance of providers.getAllSingletons().values()){if(typeof instance==="object"&&instance!==null)await lifecycles.get(instance)?.onReady()}}function dutyStorageConfig(redis,scope="machine"){return leaseStorageConfig(redis,"duty",scope)}function dutyHealth(holdsLease,leaseStoreFailure){const details={holdsLease};if(leaseStoreFailure===void 0)return{status:"healthy",details};return{status:"unhealthy",details,error:`the lease store cannot be opened: ${leaseStoreFailure}`}}var lifecycles,claims,DutyLifecycle;var init_duty_lifecycle=__esm({"libs/sdk/src/duty/duty.lifecycle.ts"(){"use strict";init_common();init_duty_errors();init_front_mcp_tokens2();init_cron_schedule();init_duty_runner();init_lazy_lease_store();init_lease_store();lifecycles=new WeakMap;claims=new LeaseClaims;DutyLifecycle=class{constructor(duty,metadata,providers){this.duty=duty;this.metadata=metadata;this.providers=providers}duty;metadata;providers;started;resumable=false;shutDown=false;lastTurn=Promise.resolve();claimedKey;cron;async onBootstrap(){await this.refuseWhatCannotRun();await this.duty.onBootstrap?.()}async onReady(){await this.duty.onReady?.();this.started??=this.startRunner();await this.started}async stopBackground(){await this.inTurn(async()=>{if(this.started)this.resumable=true;await this.stopRunner()})}async resumeBackground(){await this.inTurn(async()=>{if(!this.resumable||this.shutDown)return;this.resumable=false;this.started=this.startRunner();await this.started})}async onShutdown(){this.shutDown=true;await this.inTurn(()=>this.stopRunner());await this.duty.onShutdown?.()}inTurn(step){const turn=this.lastTurn.then(step);this.lastTurn=turn.catch(()=>void 0);return turn}async stopRunner(){const starting=this.started;this.started=void 0;const started=await starting?.catch(()=>void 0);if(started){await started.runner.stop();await started.storage.disconnect();started.removeHealthProbe()}this.releaseClaim()}async refuseWhatCannotRun(){const{name:name59,cron,scope}=this.metadata;if(cron)await this.cronSchedule(cron);if(scope!=="cluster"||!isLongLivedProcess())return;const config=this.providers.get(FrontMcpConfig);if(startsBackgroundWork(config)&&dutyStorageConfig(config.redis,scope).type!=="redis"){throw new ClusterScopeNeedsRedisError(`Duty "${name59}"`)}}cronSchedule(cron){this.cron??=loadCronSchedule(cron).catch(error=>{throw new InvalidDutyCronError(this.metadata.name,cron.expression,error.message)});return this.cron}async startRunner(){const{metadata}=this;const{name:name59,leaseMs,scope}=metadata;const logger=this.providers.get(FrontMcpLogger);if(!isLongLivedProcess()){logger.warn(`Duty "${name59}" does not run in a serverless or edge deployment: it needs a long-lived process`);return void 0}const config=this.providers.get(FrontMcpConfig);const serverName=config.info?.name??"frontmcp";const key=leaseKey(name59,scope,serverName);this.claim(serverName);const storage=new LazyLeaseStore(dutyStorageConfig(config.redis,scope));const run=context=>this.duty.run(context);const common={name:name59,key,leaseMs,storage,logger,run};const runner=new DutyRunner(metadata.cron?{...common,cron:await this.cronSchedule(metadata.cron)}:{...common,everyMs:metadata.everyMs});const removeHealthProbe=registerReadinessProbe(this.providers,{name:`duty:${name59}`,check:async()=>dutyHealth(runner.holdsLease,storage.openFailure)});await runner.start();return{runner,storage,removeHealthProbe}}claim(serverName){const key=nameKey(this.metadata.name,serverName);const type=this.duty.constructor;const otherClass=claims.claim(key,type);if(otherClass!==void 0){throw new DutyNameConflictError(this.metadata.name,serverName,otherClass,type.name)}this.claimedKey=key}releaseClaim(){const key=this.claimedKey;this.claimedKey=void 0;if(key!==void 0)claims.release(key)}}}});function aborted(signal,timeoutMs){return new Promise(resolve4=>{const settle=()=>{clearTimeout(timer);signal.removeEventListener("abort",settle);resolve4()};const timer=setTimeout(settle,timeoutMs);timer.unref?.();signal.addEventListener("abort",settle)})}var WorkerSupervisor;var init_worker_supervisor=__esm({"libs/sdk/src/worker/worker.supervisor.ts"(){"use strict";init_describe_thrown();WorkerSupervisor=class{constructor(options){this.options=options}options;controller;ended=Promise.resolve();state="standby";restarts=0;lastError;stopped=false;finished=false;start(){if(this.stopped)return;const controller=new AbortController;this.controller=controller;this.ended=this.ended.then(()=>this.supervise(controller.signal)).catch(error=>this.options.logger.error(`Worker "${this.options.name}" is no longer supervised: ${describeThrown(error)}`))}abort(){this.controller?.abort();if(this.state==="stopped")this.state="standby"}async stop(){this.stopped=true;this.abort();await this.ended}status(){const{state,restarts,lastError}=this;return lastError===void 0?{state,restarts}:{state,restarts,lastError}}async supervise(signal){if(this.finished){if(!signal.aborted)this.state="stopped";return}const{restart}=this.options;let delayMs=restart?restart.minDelayMs:0;while(!signal.aborted){this.state="running";const startedAt=performance.now();const failure=await this.runOnce(signal);if(signal.aborted)break;if(!restart){this.finished=true;this.state="stopped";this.report(failure,"it does not run again (restart: false)");return}if(performance.now()-startedAt>restart.maxDelayMs)delayMs=restart.minDelayMs;this.state="restarting";this.restarts++;this.report(failure,`it runs again in ${delayMs} ms`);await aborted(signal,delayMs);delayMs=Math.min(delayMs*restart.factor,restart.maxDelayMs)}this.state="standby"}async runOnce(signal){try{await this.options.run({signal});this.lastError=void 0;return void 0}catch(error){if(signal.aborted)return void 0;this.lastError=describeThrown(error);return this.lastError}}report(failure,next){const{name:name59,logger}=this.options;if(failure===void 0)logger.warn(`Worker "${name59}" returned before its signal was aborted; ${next}`);else logger.error(`Worker "${name59}" failed: ${failure}; ${next}`)}}}});var worker_lifecycle_exports={};__export(worker_lifecycle_exports,{WorkerLifecycle:()=>WorkerLifecycle,startWorkers:()=>startWorkers,workerHealth:()=>workerHealth,workerLifecycleOf:()=>workerLifecycleOf});function workerLifecycleOf(worker,metadata,providers){let lifecycle=lifecycles2.get(worker);if(!lifecycle){lifecycle=new WorkerLifecycle(worker,metadata,providers);lifecycles2.set(worker,lifecycle)}return lifecycle}async function startWorkers(providers){for(const instance of providers.getAllSingletons().values()){if(typeof instance==="object"&&instance!==null)await lifecycles2.get(instance)?.onReady()}}function workerHealth(status,leaseStoreFailure){const{state,lastError}=status;if(leaseStoreFailure!==void 0){const error=`the lease store cannot be opened: ${leaseStoreFailure}`;return{status:"unhealthy",details:{...status},error}}if(state==="restarting")return{status:"degraded",details:{...status},error:lastError};if(state==="stopped"&&lastError!==void 0){return{status:"unhealthy",details:{...status},error:lastError}}return{status:"healthy",details:{...status}}}var lifecycles2,claims2,WorkerLifecycle;var init_worker_lifecycle=__esm({"libs/sdk/src/worker/worker.lifecycle.ts"(){"use strict";init_common();init_lazy_lease_store();init_lease_holder();init_lease_store();init_duty_errors();init_worker_errors();init_front_mcp_tokens2();init_worker_supervisor();lifecycles2=new WeakMap;claims2=new LeaseClaims;WorkerLifecycle=class{constructor(worker,metadata,providers){this.worker=worker;this.metadata=metadata;this.providers=providers}worker;metadata;providers;started;resumable=false;shutDown=false;lastTurn=Promise.resolve();claimedKey;async onBootstrap(){this.refuseClusterWithoutRedis();await this.worker.onBootstrap?.()}async onReady(){await this.worker.onReady?.();this.started??=this.start();await this.started}async stopBackground(){await this.inTurn(async()=>{if(this.started)this.resumable=true;await this.stopStarted()})}async resumeBackground(){await this.inTurn(async()=>{if(!this.resumable||this.shutDown)return;this.resumable=false;this.started=this.start();await this.started})}async onShutdown(){this.shutDown=true;await this.inTurn(()=>this.stopStarted());await this.worker.onShutdown?.()}inTurn(step){const turn=this.lastTurn.then(step);this.lastTurn=turn.catch(()=>void 0);return turn}async stopStarted(){const starting=this.started;this.started=void 0;const started=await starting?.catch(()=>void 0);if(started)await this.stop(started);this.releaseClaim()}refuseClusterWithoutRedis(){const{name:name59,scope}=this.metadata;if(scope!=="cluster"||!isLongLivedProcess())return;const config=this.providers.get(FrontMcpConfig);if(startsBackgroundWork(config)&&leaseStorageConfig(config.redis,"worker",scope).type!=="redis"){throw new ClusterScopeNeedsRedisError(`Worker "${name59}"`)}}async start(){const{name:name59,restart,scope}=this.metadata;const logger=this.providers.get(FrontMcpLogger);if(!isLongLivedProcess()){logger.warn(`Worker "${name59}" does not run in a serverless or edge deployment: it needs a long-lived process`);return void 0}const serverName=this.providers.get(FrontMcpConfig).info?.name??"frontmcp";this.claim(serverName);const supervisor=new WorkerSupervisor({name:name59,restart,logger,run:context=>this.worker.run(context)});if(scope!=="process")return this.contend(supervisor,scope,logger);logger.info(`Worker "${name59}" runs in this process`);supervisor.start();return{supervisor,removeHealthProbe:this.registerHealthProbe(supervisor)}}async contend(supervisor,scope,logger){const{name:name59,leaseMs}=this.metadata;const config=this.providers.get(FrontMcpConfig);const serverName=config.info?.name??"frontmcp";const key=leaseKey(name59,scope,serverName);const storage=new LazyLeaseStore(leaseStorageConfig(config.redis,"worker",scope));const removeHealthProbe=this.registerHealthProbe(supervisor,storage);const holder=new LeaseHolder({label:`Worker "${name59}"`,key,leaseMs,storage,logger,onAcquired:()=>{logger.info(`Worker "${name59}" runs in this process`);supervisor.start()},onLost:()=>supervisor.abort()});await holder.start();return{supervisor,lease:{holder,storage},removeHealthProbe}}async stop({supervisor,lease,removeHealthProbe}){if(lease){await lease.holder.stop(()=>supervisor.stop());await lease.storage.disconnect()}else{await supervisor.stop()}removeHealthProbe()}claim(serverName){const key=nameKey(this.metadata.name,serverName);const type=this.worker.constructor;const otherClass=claims2.claim(key,type);if(otherClass!==void 0){throw new WorkerNameConflictError(this.metadata.name,serverName,otherClass,type.name)}this.claimedKey=key}releaseClaim(){const key=this.claimedKey;this.claimedKey=void 0;if(key!==void 0)claims2.release(key)}registerHealthProbe(supervisor,storage){return registerReadinessProbe(this.providers,{name:`worker:${this.metadata.name}`,check:async()=>workerHealth(supervisor.status(),storage?.openFailure)})}}}});import"reflect-metadata";import{depsOfClass as depsOfClass12,hasAsyncWith,isClass as isClass20,isPromise,ProviderKind as ProviderKind4,ProviderScope as ProviderScope11,tokenName as tokenName22}from"@frontmcp/di";function verifiedSessionOf2(requestContext){const{authInfo}=requestContext;const verified=authInfo.sessionId??authInfo.extra?.["sessionId"];return typeof verified==="string"&&verified.length>0&&verified!==STATELESS_SESSION_ID?verified:void 0}function requestScopedTokens(contextProviders){const requestContext=contextProviders?.get(FRONTMCP_CONTEXT);const carriedTokens=requestContext instanceof FrontMcpContext?requestContext.getContextTokens().keys():[];return new Set([FRONTMCP_CONTEXT,...carriedTokens])}function newProviderStore(){return{providers:new Map,bySource:new Map,lastAccess:Date.now()}}var ProviderRegistry,REQUEST_PROVIDER_STORES;var init_provider_registry=__esm({"libs/sdk/src/provider/provider.registry.ts"(){"use strict";init_common();init_transport();init_frontmcp_context();init_frontmcp_context_provider();init_errors();init_front_mcp_tokens2();init_manifest_mode_flag();init_regsitry();init_scope();init_transport_types();init_provider_lifecycle();init_provider_utils();init_store_provider();ProviderRegistry=class _ProviderRegistry extends RegistryAbstract{constructor(list,parentProviders,options){super("ProviderRegistry",parentProviders,list,false);this.parentProviders=parentProviders;this.providedBy=new Map;const configured=options?.distributedMode!==void 0||options?.providerCaching!==void 0;this.sessionCacheEnabled=!configured&&parentProviders?parentProviders.sessionCacheEnabled:shouldCacheProviders(options?.distributedMode,options?.providerCaching);this.sharedLifecycles=parentProviders?.sharedLifecycles??new WeakMap;this.shutdownHookTimeoutMs=options?.shutdownHookTimeoutMs??parentProviders?.shutdownHookTimeoutMs??DEFAULT_SHUTDOWN_HOOK_TIMEOUT_MS;this.buildGraph();this.topoSort();parentProviders?.childRegistries.add(this);this.ready=this.initialize()}parentProviders;providedBy;visibleOnlyBelow=new Map;order=new Set;registries=new Map;sessionStores=new Map;sessionBuildLocks=new Map;static MAX_SESSION_CACHE_SIZE=1e4;static SESSION_CACHE_TTL_MS=36e5;static SESSION_CLEANUP_INTERVAL_MS=6e4;sessionCleanupInterval=null;sessionCacheEnabled;childRegistries=new Set;lifecycleEntries=[];heldEntries=[];backgroundEntries=[];sharedLifecycles;shutdownHookTimeoutMs;readyHooksRun;shutdownHooksRun;getProviders(){return[...this.instances.values()]}lookupDefInHierarchy(token,requester=this){const rec=this.defs.get(token);if(rec&&!this.hidesFrom(token,requester))return{registry:this,rec};return this.providers?.lookupDefInHierarchy(token,requester)}hidesFrom(token,requester){const roots=this.visibleOnlyBelow.get(token);if(!roots||requester===this)return false;for(const root of roots){if(requester.isWithin(root))return false}return true}isWithin(root){return this===root||(this.parentProviders?.isWithin(root)??false)}subtreeBelow(ancestor){if(this.parentProviders===ancestor)return this;return this.parentProviders?.subtreeBelow(ancestor)}resolveDefaultFromHierarchy(token){const found=this.lookupDefInHierarchy(token);if(!found)throw new ProviderNotRegisteredError(tokenName22(token),"not registered in hierarchy");const{registry,rec}=found;const sc=registry.getProviderScope(rec);if(sc!==ProviderScope11.GLOBAL){const scName=ProviderScope11[sc];throw new ProviderScopeMismatchError(tokenName22(token),scName,registry.constructor.name)}const inst=registry.instances.get(token);if(inst===void 0){throw new ProviderNotInstantiatedError(tokenName22(token),"DEFAULT",registry.constructor.name)}return inst}buildMap(list){const tokens=new Set;const defs=new Map;const graph=new Map;for(const raw of list){const rec=normalizeProvider(raw);const provide=rec.provide;tokens.add(provide);defs.set(provide,rec);graph.set(provide,new Set)}return{tokens,defs,graph}}buildGraph(){for(const token of this.tokens){const rec=this.defs.get(token);const deps=this.discoveryDeps(rec);for(const d of deps){const isLocal=this.tokens.has(d);const up=isLocal?void 0:this.lookupDefInHierarchy(d);if(!isLocal&&!up){throw new ProviderDependencyError(`Provider ${tokenName22(token)} depends on ${tokenName22(d)}, which is not registered (local or parent).`)}this.assertDependencyScope(token,rec,d);if(isLocal)this.graph.get(token).add(d)}}}assertDependencyScope(token,rec,dependency){if(this.getProviderScope(rec)!==ProviderScope11.GLOBAL)return;const local=this.defs.get(dependency);const up=local?void 0:this.lookupDefInHierarchy(dependency);const depScope=local?this.getProviderScope(local):up&&up.registry.getProviderScope(up.rec);if(depScope===void 0||depScope===ProviderScope11.GLOBAL)return;throw new InvalidDependencyScopeError(`Invalid dependency: DEFAULT-scoped provider ${tokenName22(token)} cannot depend on scoped provider ${tokenName22(dependency)}.`)}topoSort(){const WHITE=0,GRAY=1,BLACK=2;const color=new Map;const order=new Set;const path4=[];const dfs=n=>{color.set(n,GRAY);path4.push(n);for(const dep of this.graph.get(n)??[]){const c=color.get(dep)??WHITE;if(c===GRAY){const idx=path4.findIndex(p=>p===dep);const cycle=[...path4.slice(idx),dep].map(t=>tokenName22(t)).join(" -> ");throw new DependencyCycleError(cycle)}if(c===WHITE)dfs(dep)}color.set(n,BLACK);order.add(n);path4.pop()};for(const n of this.graph.keys())if((color.get(n)??WHITE)===WHITE)dfs(n);this.order=order}async initialize(opts){const force=!!opts?.force;const only=opts?.onlyTokens?new Set(opts.onlyTokens):null;for(const token of this.order){const rec=this.defs.get(token);if(this.getProviderScope(rec)!==ProviderScope11.GLOBAL)continue;if(only&&!only.has(token))continue;if(!force&&this.instances.has(token))continue;if(force&&this.instances.has(token)){this.instances.delete(token)}try{await this.initiateOne(token,rec)}catch(e){const msg=e?.message??e;console.error(`Failed instantiating:`,msg);throw new ProviderConstructionError(tokenName22(token),e instanceof Error?e:msg)}await this.bootstrapBuilt(token)}if(this.parentProviders){this.startSessionCleanup()}}async bootstrapBuilt(token){const built=this.instances.get(token);const background=await this.backgroundLifecycleOf(built);const instance=lifecycleHooksOf(background??built);if(!instance||this.heldEntries.some(held=>held.instance===instance))return;const entry={token,instance};const shared=this.sharedLifecycles.get(instance);const lifecycle=shared??{holders:0,bootstrapped:bootstrapProvider(entry)};if(!shared)this.sharedLifecycles.set(instance,lifecycle);lifecycle.holders++;await lifecycle.bootstrapped;if(!shared)this.lifecycleEntries.push(entry);if(!shared&&background)this.backgroundEntries.push({token,lifecycle:background});this.heldEntries.push(entry)}async backgroundLifecycleOf(built){if(typeof built!=="object"||built===null)return void 0;const duty=dutyMetadataOf(built);if(duty){const{dutyLifecycleOf:dutyLifecycleOf2}=await Promise.resolve().then(()=>(init_duty_lifecycle(),duty_lifecycle_exports));return dutyLifecycleOf2(built,duty,this)}const worker=workerMetadataOf(built);if(!worker)return void 0;const{workerLifecycleOf:workerLifecycleOf2}=await Promise.resolve().then(()=>(init_worker_lifecycle(),worker_lifecycle_exports));return workerLifecycleOf2(built,worker,this)}get readyHooksStarted(){return this.readyHooksRun!==void 0}runReadyHooks(logger){this.readyHooksRun??=this.readyHereAndBelow(logger);return this.readyHooksRun}runShutdownHooks(logger){this.shutdownHooksRun??=this.shutdownBelowAndHere(logger);return this.shutdownHooksRun}async readyHereAndBelow(logger){const failures=await readyProviders(this.lifecycleEntries,logger);for(const child of[...this.childRegistries])failures.push(...await child.runReadyHooks(logger));return failures}async stopBackgroundWork(logger){const timeoutMs=this.shutdownHookTimeoutMs;for(const{token,lifecycle}of this.backgroundEntries){const stillStopping=await outlasts(()=>lifecycle.stopBackground(),timeoutMs);if(!stillStopping)continue;const message=`Provider "${tokenName22(token)}" did not stop its background work within ${timeoutMs} ms`;logger.warn(message);throw new InternalMcpError(message,"BACKGROUND_STOP_TIMEOUT")}}resumeBackgroundWork(logger){for(const{token,lifecycle}of this.backgroundEntries){void lifecycle.resumeBackground().catch(error=>{logger.error(`Provider "${tokenName22(token)}" failed to start again: ${messageOf3(error)}`)})}}async shutdownBelowAndHere(logger){for(const child of[...this.childRegistries].reverse())await child.runShutdownHooks(logger);const lastHeld=this.heldEntries.filter(entry=>this.releaseLifecycleHold(entry.instance));await shutdownProviders(lastHeld,this.shutdownHookTimeoutMs,logger)}releaseLifecycleHold(instance){const lifecycle=this.sharedLifecycles.get(instance);if(!lifecycle)return true;lifecycle.holders--;return lifecycle.holders===0}getAllSingletons(){return this.instances}getContextScopedClasses(){const out=[];for(const[token,rec]of this.defs){if(this.getProviderScope(rec)!==ProviderScope11.CONTEXT)continue;if(rec.kind===ProviderKind4.CLASS)out.push({token,cls:rec.useClass});else if(rec.kind===ProviderKind4.CLASS_TOKEN)out.push({token,cls:rec.provide})}return out}discoveryDeps(rec){const registered={has:token=>this.tokens.has(token)||this.lookupDefInHierarchy(token)!==void 0};return providerDiscoveryDeps(rec,registered,(k,phase)=>depsOfClass12(k,phase))}invocationTokens(_token,rec){return providerInvocationTokens(rec,(k,phase)=>depsOfClass12(k,phase))}normalizeScope(scope){switch(scope){case ProviderScope11.SESSION:case ProviderScope11.REQUEST:return ProviderScope11.CONTEXT;default:return scope}}getProviderScope(rec){const rawScope=rec.metadata?.scope??ProviderScope11.GLOBAL;return this.normalizeScope(rawScope)}getScope(){return this.getActiveScope()}async withTimeout(p,ms,label){if(ms<=0||!Number.isFinite(ms))return p;let timer;try{const tm=new Promise((_,rej)=>timer=setTimeout(()=>rej(new Error(`Timeout after ${ms}ms: ${label}`)),ms));return await Promise.race([p,tm])}finally{clearTimeout(timer)}}async resolveFactoryArg(t,store,scopeKey){if(t===_ProviderRegistry)return this;if(store.has(t))return store.get(t);if(this.instances.has(t))return this.instances.get(t);const rec=this.defs.get(t);if(rec){const sc=this.getProviderScope(rec);if(sc===ProviderScope11.GLOBAL){if(!this.instances.has(t)){throw new ProviderNotInstantiatedError(tokenName22(t),"DEFAULT")}return this.instances.get(t)}else{await this.buildIntoStore(t,rec,store,scopeKey);return store.get(t)}}const up=this.lookupDefInHierarchy(t);if(up){const sc=up.registry.getProviderScope(up.rec);if(sc===ProviderScope11.GLOBAL){const inst=up.registry.instances.get(t);if(inst===void 0){throw new ProviderNotInstantiatedError(tokenName22(t),"DEFAULT","parent")}return inst}else{await up.registry.buildIntoStore(t,up.rec,store,scopeKey);return store.get(t)}}if(isClass20(t)){if(hasAsyncWith(t)){const out=t.with();return isPromise(out)?await this.withTimeout(out,this.asyncTimeoutMs,`${t.name}.with(...)`):out}const instance=new t;const init=instance?.init;if(typeof init==="function"){const ret=init.call(instance);if(isPromise(ret))await this.withTimeout(ret,this.asyncTimeoutMs,`${t.name}.init()`)}return instance}throw new ProviderNotRegisteredError(tokenName22(t),"not registered in hierarchy and not constructable")}bootsForBuild(){const config=this.lookupDefInHierarchy(FrontMcpConfig)?.rec;return config?.kind===ProviderKind4.VALUE&&typeof config.useValue==="object"&&config.useValue!==null&&isManifestMode(config.useValue)}async initiateOne(token,rec){switch(rec.kind){case ProviderKind4.VALUE:{this.instances.set(token,rec.useValue);return}case ProviderKind4.FACTORY:{if(opensStore(rec.useFactory)&&this.bootsForBuild()){this.instances.set(token,storeNotOpened(rec.metadata?.name??tokenName22(token)));return}const deps=this.invocationTokens(token,rec);const args=[];for(const d of deps)args.push(await this.resolveFactoryArg(d,this.instances));const out=rec.useFactory(...args);const val=isPromise(out)?await this.withTimeout(out,this.asyncTimeoutMs,`${tokenName22(token)}.useFactory(...)`):out;this.instances.set(token,val);return}case ProviderKind4.CLASS:{const depTokens=this.invocationTokens(token,rec);const deps=depTokens.map(t=>this.resolveDefaultFromHierarchy(t));const klass=rec.useClass;if(hasAsyncWith(klass)){const out=klass.with(...deps);const val=isPromise(out)?await this.withTimeout(out,this.asyncTimeoutMs,`${klass.name}.with(...)`):out;this.instances.set(token,val)}else{const instance=new klass(...deps);const init=instance?.init;if(typeof init==="function"){const ret=init.call(instance);if(isPromise(ret))await this.withTimeout(ret,this.asyncTimeoutMs,`${klass.name}.init()`)}this.instances.set(token,instance)}return}case ProviderKind4.CLASS_TOKEN:{const depTokens=this.invocationTokens(token,rec);const deps=depTokens.map(t=>this.resolveDefaultFromHierarchy(t));const klass=rec.provide;if(hasAsyncWith(klass)){const out=klass.with(...deps);const val=isPromise(out)?await this.withTimeout(out,this.asyncTimeoutMs,`${klass.name}.with(...)`):out;this.instances.set(token,val)}else{const instance=new klass(...deps);const init=instance?.init;if(typeof init==="function"){const ret=init.call(instance);if(isPromise(ret))await this.withTimeout(ret,this.asyncTimeoutMs,`${klass.name}.init()`)}this.instances.set(token,instance)}return}}}async buildIntoStore(token,rec,store,scopeKey,injectedDeps){if(store.has(token))return;try{switch(rec.kind){case ProviderKind4.VALUE:{store.set(token,rec.useValue);return}case ProviderKind4.FACTORY:{const deps=this.invocationTokens(token,rec);const args=[];for(const d of deps)args.push(await this.resolveFactoryArg(d,store,scopeKey));const out=rec.useFactory(...args);const val=isPromise(out)?await this.withTimeout(out,this.asyncTimeoutMs,`${tokenName22(token)}.useFactory(...)`):out;store.set(token,val);return}case ProviderKind4.CLASS:{const depsTokens=this.invocationTokens(token,rec);const deps=[];for(const d of depsTokens)deps.push(await this.resolveManagedForClass(d,store,scopeKey));const klass=rec.useClass;if(hasAsyncWith(klass)){const out=klass.with(...deps);const val=isPromise(out)?await this.withTimeout(out,this.asyncTimeoutMs,`${klass.name}.with(...)`):out;store.set(token,val)}else{const instance=new klass(...deps);const init=instance?.init;if(typeof init==="function"){const ret=init.call(instance);if(isPromise(ret))await this.withTimeout(ret,this.asyncTimeoutMs,`${klass.name}.init()`)}store.set(token,instance)}return}case ProviderKind4.CLASS_TOKEN:{const depsTokens=this.invocationTokens(token,rec);const deps=injectedDeps??[];for(const d of depsTokens)deps.push(await this.resolveManagedForClass(d,store,scopeKey));const klass=rec.provide;if(hasAsyncWith(klass)){const out=klass.with(...deps);const val=isPromise(out)?await this.withTimeout(out,this.asyncTimeoutMs,`${klass.name}.with(...)`):out;store.set(token,val)}else{const instance=new klass(...deps);const init=instance?.init;if(typeof init==="function"){const ret=init.call(instance);if(isPromise(ret))await this.withTimeout(ret,this.asyncTimeoutMs,`${klass.name}.init()`)}store.set(token,instance)}return}}}catch(e){const msg=e?.message??e;console.error(`Failed constructing:`,msg);throw new ProviderConstructionError(tokenName22(token),e instanceof Error?e:msg,"scoped")}}async resolveManagedForClass(d,store,scopeKey){if(store.has(d))return store.get(d);if(this.instances.has(d))return this.instances.get(d);const depRec=this.defs.get(d);if(depRec){const sc=this.getProviderScope(depRec);if(sc===ProviderScope11.GLOBAL){const v=this.instances.get(d);if(v===void 0)throw new ProviderNotInstantiatedError(tokenName22(d),"DEFAULT");return v}else{await this.buildIntoStore(d,depRec,store,scopeKey);return store.get(d)}}const up=this.lookupDefInHierarchy(d);if(up){const sc=up.registry.getProviderScope(up.rec);if(sc===ProviderScope11.GLOBAL){const v=up.registry.instances.get(d);if(v===void 0)throw new ProviderNotInstantiatedError(tokenName22(d),"DEFAULT","parent");return v}else{await up.registry.buildIntoStore(d,up.rec,store,scopeKey);return store.get(d)}}throw new ProviderNotInstantiatedError(tokenName22(d))}get(token){return this.getFor(token,this)}getFor(token,requester){const visible=!this.hidesFrom(token,requester);if(visible&&this.instances.has(token))return this.instances.get(token);const rec=visible?this.defs.get(token):void 0;if(rec&&this.getProviderScope(rec)!==ProviderScope11.GLOBAL){const scName=ProviderScope11[this.getProviderScope(rec)];throw new ProviderScopedAccessError(tokenName22(token),scName)}if(this.providers)return this.providers.getFor(token,requester);throw new ProviderNotAvailableError(tokenName22(token),"not found in local or parent registries")}addRegistry(type,value){let registry=this.registries.get(type);if(!registry){this.registries.set(type,new Set);registry=this.registries.get(type)}registry.add(value)}getRegistries(type){return[...this.registries.get(type)??[]]}getHooksRegistry(){return this.getRegistries("HookRegistry")[0]}getScopeRegistry(){return this.getRegistries("ScopeRegistry")[0]}async resolveBootstrapDep(t){if(this.instances.has(t))return this.instances.get(t);if(this.registries.has(t))return this.registries.get(t);const found=this.lookupDefInHierarchy(t);if(found){const{registry,rec}=found;const sc=registry.getProviderScope(rec);if(sc!==ProviderScope11.GLOBAL)throw new PluginDependencyError(`Plugin dependency ${tokenName22(t)} must be DEFAULT-scoped at bootstrap`);const v=registry.instances.get(t);if(v===void 0)throw new PluginDependencyError(`Plugin dependency ${tokenName22(t)} (DEFAULT scope) is not instantiated`);return v}throw new PluginDependencyError(`Cannot resolve plugin dependency ${tokenName22(t)} (local or parent)`)}resolve(cls){const found=this.lookupDefInHierarchy(cls);if(found){const{registry,rec}=found;const sc=registry.getProviderScope(rec);if(sc!==ProviderScope11.GLOBAL){const scName=ProviderScope11[sc];throw new ProviderScopedAccessError(tokenName22(cls),scName)}if(!registry.instances.has(cls)){throw new ProviderNotInstantiatedError(tokenName22(cls),"DEFAULT","Call providers.instantiate() first")}return registry.instances.get(cls)}if(isClass20(cls)){const instance=new cls;const init=instance?.init;if(typeof init==="function"){init.call(instance)}return instance}throw new ProviderNotRegisteredError(tokenName22(cls),"not a registered DEFAULT provider and not a constructable class")}mergeFromRegistry(providedBy,exported,visibleBelow){for(const{token,def,instance}of exported){if(visibleBelow){if(this.defs.has(token)&&!this.visibleOnlyBelow.has(token))continue;const roots=this.visibleOnlyBelow.get(token)??new Set;roots.add(visibleBelow);this.visibleOnlyBelow.set(token,roots)}else{this.visibleOnlyBelow.delete(token)}const scope=def.metadata.scope??ProviderScope11.GLOBAL;if(scope===ProviderScope11.GLOBAL&&instance!==void 0){this.instances.set(token,instance)}this.defs.set(token,def);this.providedBy.set(token,providedBy)}}getProviderInfo(token){const def=this.defs.get(token);if(!def)throw new ProviderNotRegisteredError(tokenName22(token),"not a registered DEFAULT provider and not a constructable class");const instance=this.instances.get(token);return{token,def,instance}}injectProvider(injected){const rec={...injected,kind:ProviderKind4.INJECTED};this.tokens.add(rec.provide);this.defs.set(rec.provide,rec);this.graph.set(rec.provide,new Set);this.instances.set(rec.provide,rec.value)}async addDynamicProviders(dynamicProviders){const normalized2=dynamicProviders.map(p=>normalizeProvider(p));for(const rec of normalized2){const provide=rec.provide;this.tokens.add(provide);this.defs.set(provide,rec);if(!this.graph.has(provide)){this.graph.set(provide,new Set)}const deps=this.discoveryDeps(rec);for(const d of deps){if(this.tokens.has(d)){this.graph.get(provide).add(d)}}}for(const rec of normalized2){for(const d of this.discoveryDeps(rec))this.assertDependencyScope(rec.provide,rec,d)}const globalProviders=normalized2.filter(rec=>this.getProviderScope(rec)===ProviderScope11.GLOBAL);return Promise.all(globalProviders.map(async rec=>{await this.initiateOne(rec.provide,rec);await this.bootstrapBuilt(rec.provide)}))}getWithParents(token){if(this.instances.has(token)){return this.get(token)}const parent=this.parentProviders;if(!parent){return this.get(token)}return parent.getWithParents(token)}getActiveScope(){return this.getWithParents(Scope)}getActiveServer(){return this.getWithParents(FrontMcpServer)}cleanupSession(sessionKey){this.sessionStores.delete(sessionKey);const lock=this.sessionBuildLocks.get(sessionKey);if(lock){lock.resolve();this.sessionBuildLocks.delete(sessionKey)}}cleanupExpiredSessions(){const now=Date.now();const cutoff=now-_ProviderRegistry.SESSION_CACHE_TTL_MS;let cleaned=0;for(const[key,entry]of this.sessionStores){if(entry.lastAccess<cutoff){this.sessionStores.delete(key);const lock=this.sessionBuildLocks.get(key);if(lock){lock.resolve();this.sessionBuildLocks.delete(key)}cleaned++}}return cleaned}startSessionCleanup(){if(this.sessionCleanupInterval){return}this.sessionCleanupInterval=setInterval(()=>{const cleaned=this.cleanupExpiredSessions();if(cleaned>0){console.debug(`[ProviderRegistry] Cleaned up ${cleaned} expired sessions`)}},_ProviderRegistry.SESSION_CLEANUP_INTERVAL_MS);if(this.sessionCleanupInterval.unref){this.sessionCleanupInterval.unref()}}stopSessionCleanup(){if(this.sessionCleanupInterval){clearInterval(this.sessionCleanupInterval);this.sessionCleanupInterval=null}}dispose(){for(const child of[...this.childRegistries])child.dispose();this.parentProviders?.childRegistries.delete(this);this.stopSessionCleanup();this.sessionStores.clear();for(const lock of this.sessionBuildLocks.values()){lock.resolve()}this.sessionBuildLocks.clear()}getSessionCacheStats(){return{enabled:this.sessionCacheEnabled,size:this.sessionStores.size,maxSize:_ProviderRegistry.MAX_SESSION_CACHE_SIZE,ttlMs:_ProviderRegistry.SESSION_CACHE_TTL_MS}}isSessionCacheEnabled(){return this.sessionCacheEnabled}async buildViews(sessionKey,contextProviders,contextSource){validateSessionId(sessionKey);const global=this.getAllSingletons();const ownDefs=(contextSource&&this.defsBelow(contextSource))??new Map;const cached=this.providerStoreFor(sessionKey,contextProviders?.get(FRONTMCP_CONTEXT));let sessionProviders=cached.providers;if(contextSource&&ownDefs.size>0){let bySource=cached.bySource.get(contextSource);if(!bySource){bySource=new Map;cached.bySource.set(contextSource,bySource)}sessionProviders=bySource}const requestTokens=requestScopedTokens(contextProviders);const contextStore=new Map(sessionProviders);const sourceRegistry=contextSource instanceof _ProviderRegistry&&contextSource!==this?contextSource:void 0;for(const[token,instance]of contextProviders??[]){if(ownDefs.has(token)||sourceRegistry?.hidesFrom(token,this))continue;contextStore.set(token,instance)}for(const token of this.order){const rec=this.defs.get(token);if(!rec)continue;if(this.getProviderScope(rec)!==ProviderScope11.CONTEXT)continue;if(contextStore.has(token))continue;await this.buildIntoStoreWithViews(token,rec,contextStore,sessionKey,contextStore,global)}for(const[token,rec]of this.defs){if(this.order.has(token))continue;if(this.getProviderScope(rec)!==ProviderScope11.CONTEXT)continue;if(contextStore.has(token))continue;await this.buildIntoStoreWithViews(token,rec,contextStore,sessionKey,contextStore,global)}for(const[token,{registry,rec}]of ownDefs){if(registry===this||contextStore.has(token))continue;if(registry.getProviderScope(rec)!==ProviderScope11.CONTEXT)continue;await registry.buildIntoStoreWithViews(token,rec,contextStore,sessionKey,contextStore,registry.getAllSingletons())}for(const[token,instance]of contextStore){if(!sessionProviders.has(token)&&!this.dependsOnAny(token,requestTokens)){sessionProviders.set(token,instance)}}return{global,context:contextStore}}providerStoreFor(sessionKey,requestContext){if(!(requestContext instanceof FrontMcpContext)){return newProviderStore()}if(!this.sessionCacheEnabled||verifiedSessionOf2(requestContext)!==sessionKey){let stores=requestContext.get(REQUEST_PROVIDER_STORES);if(!stores){stores=new WeakMap;requestContext.set(REQUEST_PROVIDER_STORES,stores)}let store=stores.get(this);if(!store){store=newProviderStore();stores.set(this,store)}return store}let cached=this.sessionStores.get(sessionKey);if(!cached){cached=newProviderStore();this.sessionStores.set(sessionKey,cached)}else{cached.lastAccess=Date.now()}return cached}defsBelow(ancestor){if(this===ancestor)return new Map;const owned=this.parentProviders?.defsBelow(ancestor);if(!owned)return void 0;for(const[token,rec]of this.defs)owned.set(token,{registry:this,rec});return owned}dependsOnAny(token,targets,visited=new Set){if(targets.has(token))return true;if(visited.has(token))return false;visited.add(token);const found=this.lookupDefInHierarchy(token);if(!found)return false;return found.registry.discoveryDeps(found.rec).some(dep=>this.dependsOnAny(dep,targets,visited))}async buildIntoStoreWithViews(token,rec,store,scopeKey,contextStore,globalStore){if(store.has(token))return;try{switch(rec.kind){case ProviderKind4.VALUE:{store.set(token,rec.useValue);return}case ProviderKind4.FACTORY:{const deps=this.invocationTokens(token,rec);const args=[];for(const d of deps){args.push(await this.resolveFromViews(d,contextStore,globalStore,scopeKey))}const out=rec.useFactory(...args);const val=isPromise(out)?await this.withTimeout(out,this.asyncTimeoutMs,`${tokenName22(token)}.useFactory(...)`):out;store.set(token,val);return}case ProviderKind4.CLASS:case ProviderKind4.CLASS_TOKEN:{const depsTokens=this.invocationTokens(token,rec);const deps=[];for(const d of depsTokens){deps.push(await this.resolveFromViews(d,contextStore,globalStore,scopeKey))}const klass=rec.kind===ProviderKind4.CLASS?rec.useClass:rec.provide;if(hasAsyncWith(klass)){const out=klass.with(...deps);const val=isPromise(out)?await this.withTimeout(out,this.asyncTimeoutMs,`${klass.name}.with(...)`):out;store.set(token,val)}else{const instance=new klass(...deps);const init=instance?.init;if(typeof init==="function"){const ret=init.call(instance);if(isPromise(ret))await this.withTimeout(ret,this.asyncTimeoutMs,`${klass.name}.init()`)}store.set(token,instance)}return}}}catch(e){const msg=e?.message??e;console.error(`Failed constructing (context-scoped):`,msg);throw new ProviderConstructionError(tokenName22(token),e instanceof Error?e:msg,"context-scoped")}}async resolveFromViews(token,contextStore,globalStore,scopeKey){if(token===_ProviderRegistry)return this;if(contextStore.has(token))return contextStore.get(token);if(globalStore.has(token))return globalStore.get(token);if(this.instances.has(token))return this.instances.get(token);const rec=this.defs.get(token);if(rec){const scope=this.getProviderScope(rec);if(scope===ProviderScope11.GLOBAL){throw new ProviderNotInstantiatedError(tokenName22(token),"GLOBAL")}else{await this.buildIntoStoreWithViews(token,rec,contextStore,scopeKey,contextStore,globalStore);return contextStore.get(token)}}const up=this.lookupDefInHierarchy(token);if(up){const sc=up.registry.getProviderScope(up.rec);if(sc===ProviderScope11.GLOBAL){const v=up.registry.instances.get(token);if(v!==void 0)return v;throw new ProviderNotInstantiatedError(tokenName22(token),"GLOBAL","parent")}await up.registry.buildIntoStoreWithViews(token,up.rec,contextStore,scopeKey,contextStore,up.registry.getAllSingletons());return contextStore.get(token)}throw new ProviderDependencyError(`Cannot resolve dependency ${tokenName22(token)} from views`)}getScoped(token,views){if(views.context.has(token))return views.context.get(token);if(views.global.has(token))return views.global.get(token);if(this.instances.has(token))return this.instances.get(token);throw new ProviderNotAvailableError(tokenName22(token),"not found in views. Ensure it was built via buildViews()")}};REQUEST_PROVIDER_STORES=Symbol("frontmcp:request-provider-stores")}});import{depsOfClass as depsOfClass13}from"@frontmcp/di";function normalizeAppScope(appItem,metadata){const app=normalizeApp(appItem);const appMetadata=app.metadata;if(metadata.splitByApp===true&&appMetadata.standalone==="includeInParent"){throw new ScopeConfigurationError("standalone: includeInParent is not supported for splitByApp scope")}const scopeId=appMetadata.id??appMetadata.name;const token=Symbol(scopeId);return{kind:"SPLIT_BY_APP",provide:token,metadata:{...metadata,id:scopeId,apps:[appItem],auth:appMetadata.auth??metadata.auth,__sourceDir:appMetadata.__sourceDir??metadata.__sourceDir}}}function normalizeMultiAppScope(includedApps,metadata){return{kind:"MULTI_APP",provide:Scope,metadata:{...metadata,id:"root",apps:includedApps}}}function scopeDiscoveryDeps(rec){switch(rec.kind){case"MULTI_APP":return depsOfClass13(rec.provide,"discovery").slice(1);case"SPLIT_BY_APP":return[]}}var init_scope_utils=__esm({"libs/sdk/src/scope/scope.utils.ts"(){"use strict";init_app_utils();init_errors();init_scope_instance()}});import"reflect-metadata";import{tokenName as tokenName23}from"@frontmcp/di";var ScopeRegistry;var init_scope_registry=__esm({"libs/sdk/src/scope/scope.registry.ts"(){"use strict";init_app_utils();init_common();init_errors();init_front_mcp_tokens2();init_regsitry();init_scope_instance();init_scope_utils();ScopeRegistry=class extends RegistryAbstract{logger;constructor(globalProviders){const metadata=globalProviders.get(FrontMcpConfig);super("ScopeRegistry",globalProviders,metadata);this.logger=globalProviders.get(FrontMcpLogger)?.child("ScopeRegistry")}buildMap(metadata){const tokens=new Set;const defs=new Map;const graph=new Map;if(metadata.splitByApp){for(const raw of metadata.apps){const rec=normalizeAppScope(raw,metadata);const provide=rec.provide;tokens.add(provide);defs.set(provide,rec);graph.set(provide,new Set)}}else{const includeInParent=[];for(const raw of metadata.apps){const app=normalizeApp(raw);const appMetadata=app.metadata;if(appMetadata.standalone===false){includeInParent.push(raw);continue}if(appMetadata.standalone==="includeInParent"){includeInParent.push(raw)}const appScopeRec=normalizeAppScope(raw,metadata);const provide2=appScopeRec.provide;tokens.add(provide2);defs.set(provide2,appScopeRec);graph.set(provide2,new Set)}const rec=normalizeMultiAppScope(includeInParent,metadata);const provide=rec.provide;tokens.add(provide);defs.set(provide,rec);graph.set(provide,new Set)}return{tokens,defs,graph}}buildGraph(){for(const token of this.tokens){const rec=this.defs.get(token);const deps=scopeDiscoveryDeps(rec).slice(1);for(const d of deps){if(!this.providers.get(d)){throw new RegistryDependencyNotRegisteredError("Scope",tokenName23(token),tokenName23(d))}this.graph.get(token).add(d)}}}async initialize(){this.logger?.verbose(`ScopeRegistry: initializing ${this.tokens.size} scope(s)`);for(const token of this.tokens){const rec=this.defs.get(token);let scope;switch(rec.kind){case"SPLIT_BY_APP":scope=new Scope(rec,this.providers);break;case"MULTI_APP":scope=new rec.provide(rec,this.providers);break;default:throw new InvalidRegistryKindError("scope",String(rec.kind))}try{await scope.ready}finally{this.instances.set(token,scope)}this.logger?.verbose(`ScopeRegistry: initialized scope '${tokenName23(token)}'`)}this.logger?.verbose(`ScopeRegistry: initialization complete (${this.instances.size} scope(s))`)}getScopes(){return[...this.instances.values()]}getPrimaryScope(){const scopes=this.getScopes();const multiApp=scopes.find(scope=>scope.record.kind==="MULTI_APP");if(multiApp&&multiApp.apps.getApps().length>0)return multiApp;return scopes[0]}}}});var NoopFrontMcpServer;var init_noop_server=__esm({"libs/sdk/src/server/noop-server.ts"(){"use strict";init_common();NoopFrontMcpServer=class extends FrontMcpServer{registerMiddleware(_entryPath,_handler){}registerRoute(_method,_path2,_handler){}prepare(){}getHandler(){return void 0}async start(){}}}});var MetricsPathConflictError,MetricsTokenNotConfiguredError;var init_metrics_errors=__esm({"libs/sdk/src/metrics/metrics.errors.ts"(){"use strict";init_mcp_error();MetricsPathConflictError=class extends InternalMcpError{conflictingPath;constructor(conflictingPath){super(`metrics.path "${conflictingPath}" conflicts with an MCP transport route. Pick a non-MCP path (e.g. "/metrics", "/internal/metrics").`,"METRICS_PATH_CONFLICT");this.conflictingPath=conflictingPath}};MetricsTokenNotConfiguredError=class extends InternalMcpError{tokenEnv;constructor(tokenEnv){super(`metrics.auth is "token" but env var "${tokenEnv}" is not set. Set the env var or switch metrics.auth to "public" / { token: "..." }.`,"METRICS_TOKEN_NOT_CONFIGURED");this.tokenEnv=tokenEnv}}}});function loadObservability(){if(!observabilityRuntime){observabilityRuntime=requireOptionalModule("@frontmcp/observability",()=>__require("@frontmcp/observability"))}return observabilityRuntime}function createProcessStatsCollectorIfEnabled(config){const include=config.include;const processEnabled=!include||include.length===0||include.includes("process");if(!processEnabled)return void 0;const obs=loadObservability();return new obs.ProcessStatsCollector({options:config.process})}var PROMETHEUS_CONTENT_TYPE,observabilityRuntime,MCP_RESERVED_PATH_PREFIXES,COUNTER_CATEGORY_PREFIX,MetricsService;var init_metrics_service=__esm({"libs/sdk/src/metrics/metrics.service.ts"(){"use strict";init_optional_dependency_util();init_metrics_errors();PROMETHEUS_CONTENT_TYPE="text/plain; version=0.0.4; charset=utf-8";MCP_RESERVED_PATH_PREFIXES=["/mcp","/sse","/messages"];COUNTER_CATEGORY_PREFIX={process:["frontmcp_process_","frontmcp_nodejs_","frontmcp_event_loop_"],skills:["frontmcp_skills_"],tools:["frontmcp_tool_"],resources:["frontmcp_resource_"],http:["frontmcp_http_"],storage:["frontmcp_storage_"],auth:["frontmcp_auth_"],sessions:["frontmcp_session_"],events:["frontmcp_events_"]};MetricsService=class{config;processCollector;snapshotSource;resolvedToken;constructor(config,processCollector,options={}){this.config=config;this.processCollector=processCollector;this.snapshotSource=options.snapshotSource??(()=>loadObservability().getMetricSnapshot());const path4=config.path??"/metrics";for(const prefix of MCP_RESERVED_PATH_PREFIXES){if(path4===prefix||path4.startsWith(`${prefix}/`)){throw new MetricsPathConflictError(path4)}}if(config.auth==="token"){const envName=config.tokenEnv??"FRONTMCP_METRICS_TOKEN";const value=process.env[envName];if(!value){throw new MetricsTokenNotConfiguredError(envName)}this.resolvedToken=value}else if(typeof config.auth==="object"&&config.auth!==null&&"token"in config.auth){this.resolvedToken=config.auth.token}}getMetrics(){const format=this.config.format??"prometheus";const include=this.config.include;let counters=this.snapshotSource();let gauges=this.processCollector?.collect()??[];if(include&&include.length>0){const includeSet=new Set(include);const allowedPrefixes=include.flatMap(category=>COUNTER_CATEGORY_PREFIX[category]??[]);const matchesAllowed=name59=>allowedPrefixes.some(prefix=>name59.startsWith(prefix));counters=counters.filter(c=>matchesAllowed(c.name));if(!includeSet.has("process")){gauges=[]}else{gauges=gauges.filter(g=>matchesAllowed(g.name))}}const obs=loadObservability();if(format==="json"){return{contentType:"application/json",body:JSON.stringify(obs.renderJsonExposition(counters,gauges))}}return{contentType:PROMETHEUS_CONTENT_TYPE,body:obs.renderPrometheusExposition(counters,gauges)}}authorize(authorizationHeader){const auth=this.config.auth??"public";if(auth==="public")return 200;if(!authorizationHeader)return 401;const expected=this.resolvedToken;if(!expected)return 401;const match=/^Bearer\s+(.+)$/i.exec(authorizationHeader);if(!match)return 401;return match[1]===expected?200:403}}}});function readAuthorizationHeader(headers){if(!headers)return void 0;const raw=headers["authorization"]??headers["Authorization"];if(Array.isArray(raw))return raw[0];return typeof raw==="string"?raw:void 0}function metricsPath(config){return config.path??"/metrics"}function renderMetricsScrape(service,config,authorizationHeader){const status=service.authorize(authorizationHeader);if(status!==200){return{status,headers:{"Cache-Control":"no-store"},kind:"json",body:{error:status===401?"unauthorized":"forbidden",message:status===401?"Missing or malformed Authorization header":"Bearer token did not match the configured metrics token"}}}const result=service.getMetrics();const headers={"Cache-Control":"no-store","Content-Type":result.contentType};if((config.format??"prometheus")!=="json"){return{status:200,headers,kind:"text",body:result.body}}try{return{status:200,headers,kind:"json",body:JSON.parse(result.body)}}catch{return{status:500,headers,kind:"json",body:{error:"internal_error",message:"Failed to serialise metrics JSON"}}}}function registerMetricsRoutes(server,service,config){if(config.enabled!==true)return;server.registerRoute("GET",metricsPath(config),async(req,res)=>{const result=renderMetricsScrape(service,config,readAuthorizationHeader(req.headers));for(const[name59,value]of Object.entries(result.headers))res.setHeader?.(name59,value);if(result.kind==="json"){res.status(result.status).json(result.body);return}if(typeof res.send==="function"){res.status(result.status);res.send(result.body);return}res.status(500).json({error:"internal_error",message:'Server adapter does not support Prometheus text format. Use `format: "json"` or upgrade the adapter.'})})}var init_metrics_routes=__esm({"libs/sdk/src/metrics/metrics.routes.ts"(){"use strict"}});var metrics_exports={};__export(metrics_exports,{MetricsPathConflictError:()=>MetricsPathConflictError,MetricsService:()=>MetricsService,MetricsTokenNotConfiguredError:()=>MetricsTokenNotConfiguredError,createProcessStatsCollectorIfEnabled:()=>createProcessStatsCollectorIfEnabled,metricsPath:()=>metricsPath,registerMetricsRoutes:()=>registerMetricsRoutes,renderMetricsScrape:()=>renderMetricsScrape});var init_metrics2=__esm({"libs/sdk/src/metrics/index.ts"(){"use strict";init_metrics_service();init_metrics_routes();init_metrics_errors()}});import{getEnv as getEnv21}from"@frontmcp/utils";function readCorsFromEnv(){const rawOrigins=getEnv21("FRONTMCP_CORS_ORIGINS");if(!rawOrigins)return void 0;let origins;try{origins=JSON.parse(rawOrigins)}catch{origins=rawOrigins.split(",")}const list=(Array.isArray(origins)?origins:[origins]).filter(origin=>typeof origin==="string").map(origin=>origin.trim()).filter(origin=>origin.length>0);if(list.length===0)return void 0;const cors2={origin:list.includes("*")?true:list};const credentials=getEnv21("FRONTMCP_CORS_CREDENTIALS");if(credentials!==void 0)cors2.credentials=credentials==="true"||credentials==="1";const maxAge=Number(getEnv21("FRONTMCP_CORS_MAX_AGE"));if(Number.isFinite(maxAge)&&maxAge>0)cors2.maxAge=maxAge;return cors2}function resolveHttpCors(cors2){return cors2!==void 0?cors2:readCorsFromEnv()}var init_cors_env=__esm({"libs/sdk/src/server/middleware/cors-env.ts"(){"use strict"}});function auditSecurityDefaults(config,isProduction11){const findings=[];if(!isProduction11&&config.deploymentMode!=="distributed"){return findings}const strict=config.security?.strict===true;const cors2=resolveHttpCors(config.cors);const corsOrigin=cors2===false?void 0:cors2?.origin;if(corsOrigin===void 0||corsOrigin===false){findings.push({level:"info",code:"CORS_DISABLED",message:"No CORS headers are sent, so a browser will not let a page on another origin read the response. CORS is not server-side access control: on a routable bind, cross-origin requests still reach the server."})}else if(corsOrigin===true){findings.push({level:"warn",code:"CORS_ORIGIN_TRUE",message:"CORS origin=true allows all origins to make cross-origin requests.",recommendation:"Set cors.origin to specific allowed origins."})}else{findings.push({level:"info",code:"CORS_CONFIGURED",message:"CORS is explicitly configured."})}const bindAddress=config.resolvedBindAddress??"127.0.0.1";if(bindAddress==="0.0.0.0"||bindAddress==="::"){if(config.deploymentMode!=="distributed"){findings.push({level:"warn",code:"BIND_ALL_INTERFACES",message:`Server bound to ${bindAddress} \u2014 accessible from all network interfaces.`,recommendation:"Set security.bindAddress to 'loopback' or '127.0.0.1' for local-only access, or configure a reverse proxy. Distributed deployments require 'all' (0.0.0.0)."})}else{findings.push({level:"info",code:"BIND_ALL_INTERFACES_DISTRIBUTED",message:`Server bound to ${bindAddress} (expected for distributed deployment).`})}}else{findings.push({level:"info",code:"BIND_RESTRICTED",message:`Server bound to ${bindAddress}.`})}findings.push(auditDnsRebinding(config,bindAddress));if(config.security?.strict){findings.push({level:"info",code:"STRICT_MODE_ENABLED",message:config.deploymentMode==="distributed"?"Strict security mode is enabled: DNS rebinding protection. Binding is unchanged for a distributed deployment \u2014 it still listens on all interfaces so peers can reach it.":"Strict security mode is enabled: loopback binding and DNS rebinding protection."})}else{findings.push({level:"info",code:"STRICT_MODE_HINT",message:"To enable strict security defaults, set security.strict = true in HttpOptions."})}return findings}function auditDnsRebinding(config,bindAddress){const protection=config.security?.dnsRebindingProtection;if(protection?.enabled===false){return{level:"warn",code:"DNS_REBINDING_UNPROTECTED",message:"DNS rebinding protection is disabled (security.dnsRebindingProtection.enabled is false).",recommendation:"Remove `enabled: false` to turn DNS rebinding protection back on (an allowedHosts list is ignored while it is set). On a routable bind, also set security.dnsRebindingProtection.allowedHosts (or FRONTMCP_ALLOWED_HOSTS) to your public hostname(s)."}}const explicitHosts=protection?.allowedHosts??allowedHostsFromEnv();if(explicitHosts?.length||protection?.allowedOrigins?.length){return{level:"info",code:"DNS_REBINDING_PROTECTED",message:"DNS rebinding protection is enabled: Host/Origin headers are checked against the configured allow-list."}}if(config.socketPath){return{level:"info",code:"DNS_REBINDING_NOT_APPLICABLE",message:"Server listens on a Unix socket: there is no TCP Host to check; the socket permissions are the boundary."}}if(!isRoutableBind(bindAddress)){return{level:"info",code:"DNS_REBINDING_PROTECTED",message:corsAllowedOrigins(resolveHttpCors(config.cors))?`DNS rebinding protection is enabled: Host and Origin headers are checked against the loopback names for ${bindAddress}. A request with no Origin header is allowed.`:`DNS rebinding protection is enabled: Host headers are checked against the loopback names for ${bindAddress}. Origin is not checked: CORS admits every origin.`}}return{level:"info",code:"DNS_REBINDING_NOT_ENFORCED",message:`DNS rebinding protection is on, but no Host allow-list is enforced: the server binds ${bindAddress} and no allowed hosts are configured.`,recommendation:"Set security.dnsRebindingProtection.allowedHosts (or FRONTMCP_ALLOWED_HOSTS) to your public hostname(s)."}}function logSecurityFindings(findings,logger){if(findings.length===0)return;for(const finding of findings){const prefix=`[Security] ${finding.code}:`;const message=finding.recommendation?`${prefix} ${finding.message} ${finding.recommendation}`:`${prefix} ${finding.message}`;if(finding.level==="warn"){logger.warn(message)}else{logger.info(message)}}}function toBindAddress(value){if(value==="loopback")return"127.0.0.1";if(value==="all")return"0.0.0.0";return value}function resolveBindAddress(security,deploymentMode){if(security?.bindAddress){return toBindAddress(security.bindAddress)}const envBindAddress=process.env["FRONTMCP_BIND_ADDRESS"]?.trim();if(envBindAddress){return toBindAddress(envBindAddress)}if(security?.strict){return deploymentMode==="distributed"?"0.0.0.0":"127.0.0.1"}if(deploymentMode==="distributed")return"0.0.0.0";return"127.0.0.1"}var init_security_audit=__esm({"libs/sdk/src/server/security/security-audit.ts"(){"use strict";init_cors_env();init_resolve_allowed_hosts()}});import{getEnv as getEnv22,getEnvFlag as getEnvFlag2}from"@frontmcp/utils";function readCspFromEnv(){if(!getEnvFlag2("FRONTMCP_CSP_ENABLED"))return void 0;const rawDirectives=getEnv22("FRONTMCP_CSP_DIRECTIVES")??"";const directives={};for(const part of rawDirectives.split(";")){const trimmed=part.trim();if(!trimmed)continue;const spaceIdx=trimmed.indexOf(" ");if(spaceIdx>0){directives[trimmed.slice(0,spaceIdx)]=trimmed.slice(spaceIdx+1)}else{directives[trimmed]=""}}return{enabled:true,directives,reportUri:getEnv22("FRONTMCP_CSP_REPORT_URI"),reportOnly:getEnvFlag2("FRONTMCP_CSP_REPORT_ONLY")}}function buildCspHeaderValue(options){const parts=[];for(const[directive,value]of Object.entries(options.directives)){parts.push(value?`${directive} ${value}`:directive)}if(options.reportUri){parts.push(`report-uri ${options.reportUri}`)}return parts.join("; ")}function getCspHeaderName(reportOnly){return reportOnly?"Content-Security-Policy-Report-Only":"Content-Security-Policy"}function readSecurityHeadersFromEnv(){return{hsts:readHeaderEnv("FRONTMCP_HSTS"),contentTypeOptions:readHeaderEnv("FRONTMCP_CONTENT_TYPE_OPTIONS","nosniff"),frameOptions:readHeaderEnv("FRONTMCP_FRAME_OPTIONS","DENY"),custom:readCustomHeadersFromEnv()}}function readHeaderEnv(name59,fallback){const value=getEnv22(name59);if(value===void 0||value==="")return fallback;return["off","false","none"].includes(value.trim().toLowerCase())?void 0:value}function readCustomHeadersFromEnv(){const raw=getEnv22("FRONTMCP_HEADERS_CUSTOM");if(!raw)return void 0;try{const parsed=JSON.parse(raw);if(typeof parsed!=="object"||parsed===null||Array.isArray(parsed))return void 0;return Object.fromEntries(Object.entries(parsed).filter(entry=>typeof entry[1]==="string"))}catch{return void 0}}function applySecurityHeaders(res,headers,csp){if(headers.hsts){res.setHeader("Strict-Transport-Security",headers.hsts)}if(headers.contentTypeOptions){res.setHeader("X-Content-Type-Options",headers.contentTypeOptions)}if(headers.frameOptions){res.setHeader("X-Frame-Options",headers.frameOptions)}if(headers.custom){for(const[name59,value]of Object.entries(headers.custom)){res.setHeader(name59,value)}}if(csp?.enabled){const headerName=getCspHeaderName(csp.reportOnly);const headerValue=buildCspHeaderValue(csp);if(headerValue){res.setHeader(headerName,headerValue)}}}function resolveSecurityHeaders(options={}){const env=readSecurityHeadersFromEnv();const pick=(explicit,fromEnv)=>explicit===false?void 0:explicit??fromEnv;const resolved={hsts:pick(options.hsts,env.hsts),contentTypeOptions:pick(options.contentTypeOptions,env.contentTypeOptions),frameOptions:pick(options.frameOptions,env.frameOptions),custom:{...env.custom,...options.custom}};let csp;if(options.csp?.enabled===false){csp=void 0}else if(options.csp?.enabled===true){const directives={};for(const[name59,value]of Object.entries(options.csp.directives??{})){directives[name59]=Array.isArray(value)?value.join(" "):value}csp={enabled:true,directives,reportUri:options.csp.reportUri,reportOnly:options.csp.reportOnly??false}}else{csp=readCspFromEnv()}const headers={};applySecurityHeaders({setHeader:(name59,value)=>void(headers[name59]=value)},resolved,csp);return headers}var init_csp_middleware=__esm({"libs/sdk/src/server/middleware/csp.middleware.ts"(){"use strict"}});function createHostValidationMiddleware(options){if(!options.enabled){return(_req,_res,next)=>next()}const compiled=compileHostValidation({allowedHosts:options.allowedHosts,allowedOrigins:options.allowedOrigins});return(req,res,next)=>{const rejection=validateHostHeaders({host:req.headers?.["host"],forwardedHost:req.headers?.["x-forwarded-host"],origin:req.headers?.["origin"]},compiled);if(rejection){res.status(rejection.status).json({error:rejection.error,message:rejection.message});return}next()}}var init_host_validation_middleware=__esm({"libs/sdk/src/server/middleware/host-validation.middleware.ts"(){"use strict";init_host_validation()}});import cluster from"node:cluster";import*as net from"node:net";import*as path from"node:path";import{chmod,lstat as lstat3,realpath as realpath4,stat as stat5,unlink}from"@frontmcp/utils";function hasSocketFileMode(){return process.platform!=="win32"}function errorCode(error){return error?.code}async function assertSafeSocketDirectory(socketPath){const socketDirectory=path.dirname(path.resolve(socketPath));const realSocketDirectory=await realpath4(socketDirectory);await assertNoOtherUserCanReplace2(socketDirectory);if(realSocketDirectory!==socketDirectory)await assertNoOtherUserCanReplace2(realSocketDirectory);if(canBindOwnerOnly())return;const{mode}=await stat5(socketDirectory);if(mode&GROUP_OR_OTHER_ACCESS2){throw new SocketPermissionError(socketPath,`the umask cannot be set here (a worker thread, or a cluster worker whose primary binds the socket), so its directory ${socketDirectory} must be owner-only (0700), not 0${(mode&511).toString(8)}`)}}async function assertNoOtherUserCanReplace2(start){const replaceable=await findReplaceableDirectory(start);if(replaceable)throw new UnsafeSocketDirectoryError(replaceable.directory,replaceable.mode,replaceable.ownerUid)}function canBindOwnerOnly(){if(cluster.isWorker)return false;const previousUmask=setUmask(OWNER_ONLY_UMASK);if(previousUmask===void 0)return false;setUmask(previousUmask);return true}function probe(socketPath){return new Promise((resolve4,reject)=>{const socket=net.connect(socketPath);socket.once("connect",()=>{socket.destroy();resolve4("live")});socket.once("error",error=>{const code=errorCode(error);if(code==="ECONNREFUSED")resolve4("stale");else if(code==="ENOENT")resolve4("gone");else reject(new SocketPathConflictError(socketPath,`connecting to it failed (${code??error.message})`))})})}async function clearStaleSocket(socketPath){let stats;try{stats=await lstat3(socketPath)}catch(error){if(errorCode(error)==="ENOENT")return;throw error}if(!stats.isSocket())throw new SocketPathConflictError(socketPath,"it is not a socket");if(stats.uid!==process.getuid?.()){throw new SocketPathConflictError(socketPath,`it belongs to another user (uid ${stats.uid})`)}const state=await probe(socketPath);if(state==="live")throw new SocketInUseError(socketPath);if(state==="stale")await unlink(socketPath)}function listenOwnerOnly(server,socketPath,onListening){const previousUmask=setUmask(OWNER_ONLY_UMASK);try{server.listen(socketPath,onListening)}finally{if(previousUmask!==void 0)setUmask(previousUmask)}}function setUmask(mask){try{return process.umask(mask)}catch{return void 0}}async function enforceOwnerOnly(socketPath){try{await chmod(socketPath,OWNER_ONLY_MODE)}catch(error){throw new SocketPermissionError(socketPath,`chmod failed (${errorCode(error)??String(error)})`)}const mode=(await lstat3(socketPath)).mode&511;if(mode!==OWNER_ONLY_MODE)throw new SocketPermissionError(socketPath,`its mode is 0${mode.toString(8)}`)}var OWNER_ONLY_MODE,OWNER_ONLY_UMASK,GROUP_OR_OTHER_ACCESS2;var init_unix_socket_guard=__esm({"libs/sdk/src/server/security/unix-socket-guard.ts"(){"use strict";init_transport_errors();init_replaceable_directory();OWNER_ONLY_MODE=384;OWNER_ONLY_UMASK=63;GROUP_OR_OTHER_ACCESS2=63}});var HostServerAdapter;var init_base_host_adapter=__esm({"libs/sdk/src/server/adapters/base.host.adapter.ts"(){"use strict";init_common();HostServerAdapter=class extends FrontMcpServer{}}});import express from"express";function utf8JsonParser(limit){const readBody=express.raw({limit,type:isUtf8Json});return(req,res,next)=>{const unparsedBody=req.body;readBody(req,res,readError=>{if(readError||req.body===unparsedBody||!Buffer.isBuffer(req.body)){next(readError);return}const text=decodeUtf8(req.body);keepBodyBytes(req,res,req.body);try{req.body=parseStrictJson(text)}catch(error){req.body=unparsedBody;next(Object.assign(error,parseFailure(text)));return}next()})}}function keepBodyBytes(req,_res,bytes){req.bodyBytes=bytes}function decodeUtf8(body){const text=body.toString("utf8");return text.charCodeAt(0)===65279?text.slice(1):text}function parseStrictJson(text){if(text.length===0)return{};const first3=FIRST_NON_WHITESPACE.exec(text)?.[1];if(first3!=="{"&&first3!=="[")throw strictSyntaxError(text,first3);return JSON.parse(text)}function strictSyntaxError(text,first3){const index=first3===void 0?-1:text.indexOf(first3);const error=jsonParseError(index===-1?"":text.slice(0,index).padEnd(text.length,"#"));const message=error.message.replace(/#+/g,mask=>text.substring(index,index+mask.length));error.stack=error.stack?.replace(error.message,message);error.message=message;return error}function jsonParseError(invalidJson){try{JSON.parse(invalidJson)}catch(error){return error}return new SyntaxError(`Expected invalid JSON: ${invalidJson}`)}var UTF8_JSON_TYPE,FIRST_NON_WHITESPACE,isUtf8Json,parseFailure;var init_utf8_json_parser=__esm({"libs/sdk/src/server/adapters/utf8-json.parser.ts"(){"use strict";UTF8_JSON_TYPE=/^application\/json(?:; ?charset=utf-8)?$/i;FIRST_NON_WHITESPACE=/^[ \t\n\r]*([^ \t\n\r])/;isUtf8Json=req=>UTF8_JSON_TYPE.test(req.headers["content-type"]??"");parseFailure=body=>({expose:true,statusCode:400,status:400,body,type:"entity.parse.failed"})}});import*as http from"node:http";import cors from"cors";import express2 from"express";var SERVER_DRAIN_MS,DEFAULT_EXPRESS_BODY_LIMIT,ExpressHostAdapter;var init_express_host_adapter=__esm({"libs/sdk/src/server/adapters/express.host.adapter.ts"(){"use strict";init_mcp_error();init_ha_headers();init_csp_middleware();init_host_validation_middleware();init_resolve_allowed_hosts();init_unix_socket_guard();init_base_host_adapter();init_utf8_json_parser();SERVER_DRAIN_MS=5e3;DEFAULT_EXPRESS_BODY_LIMIT="4mb";ExpressHostAdapter=class extends HostServerAdapter{app=express2();router=express2.Router();prepared=false;httpServer;hostValidation;deriveHostValidation;constructor(options){super();this.app.disable("x-powered-by");const securityHeaders=resolveSecurityHeaders(options?.securityHeaders);this.app.use((_req,res,next)=>{for(const[name59,value]of Object.entries(securityHeaders))res.setHeader(name59,value);applyMachineIdHeader(res);next()});const corsOptions=options?.cors;const corsEnabled=corsOptions?.origin!==void 0&&corsOptions.origin!==false;if(corsEnabled){const configuredCors=cors({origin:corsOptions.origin,credentials:corsOptions.credentials??false,maxAge:corsOptions.maxAge??300});const publicCorsPaths=new Set(options?.publicCorsPaths);this.app.use((req,res,next)=>publicCorsPaths.has(req.path)?next():configuredCors(req,res,next))}this.installHostValidation(options);const jsonLimit=options?.bodyLimit??DEFAULT_EXPRESS_BODY_LIMIT;const formLimit=options?.urlencodedLimit??jsonLimit;const headerContains=(req,needle)=>(req.headers["content-type"]??"").toLowerCase().includes(needle);const isUrlencoded=req=>headerContains(req,"application/x-www-form-urlencoded");const isJson=req=>headerContains(req,"application/json")&&!isUrlencoded(req);this.app.use(express2.urlencoded({extended:true,limit:formLimit,type:isUrlencoded,verify:keepBodyBytes}));this.app.use(utf8JsonParser(jsonLimit));this.app.use(express2.json({limit:jsonLimit,type:isJson,verify:keepBodyBytes}));this.app.use((err,_req,res,next)=>{const e=err;if(e?.type==="entity.too.large"){const payloadError=new PayloadTooLargeError(e.limit,e.length);res.status(payloadError.statusCode).json({jsonrpc:"2.0",id:null,error:payloadError.toJsonRpcError()});return}next(err)});this.app.use((req,res,next)=>{if(corsEnabled){res.setHeader("Access-Control-Expose-Headers","WWW-Authenticate, Mcp-Session-Id")}res.setHeader("Cache-Control","no-cache, no-transform");res.setHeader("Content-Type","application/json; charset=utf-8");next()})}installHostValidation(options){const protection=options?.security?.dnsRebindingProtection;if(protection?.enabled===false)return;const allowedOrigins=protection?.allowedOrigins;const explicitHosts=protection?.allowedHosts??allowedHostsFromEnv();if(explicitHosts?.length){this.hostValidation=createHostValidationMiddleware({enabled:true,allowedHosts:explicitHosts,allowedOrigins})}else{if(allowedOrigins!==void 0){this.hostValidation=createHostValidationMiddleware({enabled:true,allowedOrigins})}this.deriveHostValidation=(portOrSocketPath,bindAddress)=>{if(typeof portOrSocketPath==="string")return void 0;const derivation={bindAddress:bindAddress??"127.0.0.1",port:portOrSocketPath,issuer:options?.listen?.issuer};if(!shouldEnforceDerivedHosts(derivation)){console.warn(`[frontmcp] DNS-rebinding protection is not enforcing a Host allow-list: the server binds a routable address (${derivation.bindAddress}) and no allowed hosts are configured. Set security.dnsRebindingProtection.allowedHosts (or FRONTMCP_ALLOWED_HOSTS) to your public hostname(s).`);return void 0}const allowedHosts=deriveAllowedHosts(derivation);if(!allowedHosts.length)return void 0;const corsOrigins=corsAllowedOrigins(options?.cors);const derivedOrigins=isLoopbackAddress(derivation.bindAddress)&&corsOrigins?deriveAllowedOrigins({port:derivation.port,issuer:derivation.issuer,extraOrigins:corsOrigins}):void 0;return createHostValidationMiddleware({enabled:true,allowedHosts,allowedOrigins:allowedOrigins??derivedOrigins})}}this.app.use(((req,res,next)=>{const validate=this.hostValidation;if(!validate)return next();return validate(req,res,next)}))}enableDerivedHostValidation(portOrSocketPath,bindAddress){if(!this.deriveHostValidation)return;this.hostValidation=this.deriveHostValidation(portOrSocketPath,bindAddress)??this.hostValidation;this.deriveHostValidation=void 0}registerRoute(method,path4,handler){this.router[method.toLowerCase()](path4,this.enhancedHandler(handler))}registerMiddleware(entryPath,handler){this.router.use(entryPath,handler)}enhancedHandler(handler){return(req,res,next)=>{const request2=req;const response=res;return handler(request2,response,next)}}prepare(){if(this.prepared)return;this.prepared=true;this.app.use("/",this.router)}getHandler(){this.prepare();return this.app}async start(portOrSocketPath,bindAddress){this.prepare();const server=http.createServer(this.app);this.httpServer=server;server.requestTimeout=0;server.headersTimeout=0;server.keepAliveTimeout=75e3;if(typeof portOrSocketPath==="string"){const ownerOnly=hasSocketFileMode();if(ownerOnly){await assertSafeSocketDirectory(portOrSocketPath);await clearStaleSocket(portOrSocketPath)}this.enableDerivedHostValidation(portOrSocketPath);await new Promise((resolve4,reject)=>{server.on("error",reject);if(ownerOnly)listenOwnerOnly(server,portOrSocketPath,resolve4);else server.listen(portOrSocketPath,resolve4)});if(ownerOnly){try{await enforceOwnerOnly(portOrSocketPath)}catch(error){await this.stop(0);throw error}}console.log(`MCP HTTP (Express) on unix://${portOrSocketPath}`)}else{const host=bindAddress??"127.0.0.1";await new Promise((resolve4,reject)=>{server.on("error",reject);server.listen(portOrSocketPath,host,()=>{const bound=server.address();const boundPort=typeof bound==="object"&&bound?bound.port:portOrSocketPath;const boundAddress=typeof bound==="object"&&bound?bound.address:host;this.enableDerivedHostValidation(boundPort,boundAddress);console.log(`MCP HTTP (Express) on ${host}:${boundPort}`);resolve4()})})}}async stop(drainMs=SERVER_DRAIN_MS){const server=this.httpServer;if(!server)return;this.httpServer=void 0;const closed=new Promise(resolve4=>server.close(()=>resolve4()));server.closeIdleConnections();const forceClose=setTimeout(()=>server.closeAllConnections(),drainMs);try{await closed}finally{clearTimeout(forceClose)}}}}});var node_express_host_exports={};__export(node_express_host_exports,{DEFAULT_EXPRESS_BODY_LIMIT:()=>DEFAULT_EXPRESS_BODY_LIMIT,ExpressHostAdapter:()=>ExpressHostAdapter});var init_node_express_host=__esm({"libs/sdk/src/server/adapters/polyfills/node-express-host.ts"(){"use strict";init_express_host_adapter()}});var server_instance_exports={};__export(server_instance_exports,{FrontMcpServerInstance:()=>FrontMcpServerInstance});import{getRuntimeContext as getRuntimeContext30,isProduction as isProduction9}from"@frontmcp/utils";var DEFAULT_CORS,FrontMcpServerInstance;var init_server_instance=__esm({"libs/sdk/src/server/server.instance.ts"(){"use strict";init_common();init_path_utils();init_health2();init_mcp_registry_utils();init_metrics2();init_cors_env();init_security_audit();DEFAULT_CORS=void 0;FrontMcpServerInstance=class extends FrontMcpServer{config;host;healthRouteRegistered=false;_healthService;_healthConfig;metricsRouteRegistered=false;_metricsService;_metricsConfig;constructor(httpConfig){super();this.config=httpConfig;this.setupDefaults()}setupDefaults(){if(typeof this.config.hostFactory==="function"){const{hostFactory,...config}=this.config;this.host=this.config.hostFactory(config)}else if(this.config.hostFactory!==void 0){this.host=this.config.hostFactory}else{const cors2=resolveHttpCors(this.config.cors);const corsConfig=cors2===false?void 0:cors2??DEFAULT_CORS;const{ExpressHostAdapter:ExpressHostAdapter2}=(init_node_express_host(),__toCommonJS(node_express_host_exports));this.host=new ExpressHostAdapter2({...corsConfig?{cors:corsConfig}:{},publicCorsPaths:[serverCardPath({entryPath:resolveEntryPath(this.config.entryPath),routeBase:""})],...this.config.security?{security:this.config.security}:{},...this.config.securityHeaders?{securityHeaders:this.config.securityHeaders}:{},...this.config.bodyLimit!==void 0?{bodyLimit:this.config.bodyLimit}:{},...this.config.urlencodedLimit!==void 0?{urlencodedLimit:this.config.urlencodedLimit}:{}})}}registerMiddleware(entryPath,handler){return this.host.registerMiddleware(entryPath,handler)}registerRoute(method,path4,handler){return this.host.registerRoute(method,path4,handler)}setHealthService(healthService,healthConfig){this._healthService=healthService;this._healthConfig=healthConfig}setHealthConfig(healthConfig){this._healthConfig=healthConfig}setMetricsService(metricsService,metricsConfig){this._metricsService=metricsService;this._metricsConfig=metricsConfig}setMetricsConfig(metricsConfig){this._metricsConfig=metricsConfig}prepare(){if(!this.healthRouteRegistered){this.healthRouteRegistered=true;if(this._healthService&&this._healthConfig){registerHealthRoutes(this,this._healthService,this._healthConfig)}else if(this._healthConfig?.enabled===false){}else{this.registerRoute("GET","/health",async(req,res)=>{res.status(200).json({status:"ok"})})}}if(!this.metricsRouteRegistered){this.metricsRouteRegistered=true;if(this._metricsService&&this._metricsConfig?.enabled===true){registerMetricsRoutes(this,this._metricsService,this._metricsConfig)}}this.host.prepare()}getHandler(){return this.host.getHandler()}async start(){this.prepare();const deploymentMode=getRuntimeContext30().deployment;const bindAddress=resolveBindAddress(this.config.security,deploymentMode);const findings=auditSecurityDefaults({cors:this.config.cors,security:this.config.security,resolvedBindAddress:bindAddress,socketPath:this.config.socketPath,deploymentMode},isProduction9());logSecurityFindings(findings,console);await this.host.start(this.config.socketPath??this.config.port,bindAddress)}async stop(){await this.host.stop()}}}});import{ProviderScope as ProviderScope12}from"@frontmcp/di";function createMcpGlobalProviders(metadata){const isCli=!!metadata["__cliMode"];const isNoServe=metadata.serve===false;const serverProvider=isCli||isNoServe?noopServer:frontMcpServer;return[frontMcpConfig.with(metadata),serverProvider,FrontMcpContextStorage]}var frontMcpConfig,defaultHttpOptions,frontMcpServer,noopServer;var init_front_mcp_providers=__esm({"libs/sdk/src/front-mcp/front-mcp.providers.ts"(){"use strict";init_common();init_context();init_noop_server();init_front_mcp_tokens2();frontMcpConfig={with:metadata=>({name:"frontmcp:config",provide:FrontMcpConfig,scope:ProviderScope12.GLOBAL,useValue:metadata})};defaultHttpOptions=()=>({port:defaultHttpPort(),entryPath:"/mcp"});frontMcpServer=AsyncProvider({name:"frontmcp:server",scope:ProviderScope12.GLOBAL,provide:FrontMcpServer,inject:()=>[FrontMcpConfig],useFactory:async config=>{const{FrontMcpServerInstance:FrontMcpServerInstance2}=await Promise.resolve().then(()=>(init_server_instance(),server_instance_exports));return new FrontMcpServerInstance2(config.http??defaultHttpOptions())}});noopServer={name:"frontmcp:server:noop",provide:FrontMcpServer,scope:ProviderScope12.GLOBAL,useValue:new NoopFrontMcpServer}}});import{isSessionSecretConfigured,SessionSecretRequiredError as SessionSecretRequiredError2}from"@frontmcp/auth";import{isProduction as isProduction10}from"@frontmcp/utils";function checkSessionSecret(config,entryFallback){if(!isProduction10()||isSessionSecretConfigured())return false;if((config.transport?.defaultProtocolVersion??entryFallback)==="legacy"){throw new SessionSecretRequiredError2("the session ids of MCP clients before 2026-07-28: set MCP_SESSION_SECRET (openssl rand -hex 32), or, if every client uses MCP 2026-07-28, set transport.defaultProtocolVersion to '2026-07-28'")}return true}var MISSING_SESSION_SECRET_WARNING,missingSessionSecretProbe;var init_session_secret_check=__esm({"libs/sdk/src/front-mcp/session-secret.check.ts"(){"use strict";MISSING_SESSION_SECRET_WARNING="MCP_SESSION_SECRET is not set: clients before MCP 2026-07-28 get 500 SESSION_SECRET_REQUIRED on initialize, while clients on MCP 2026-07-28 are served. Set MCP_SESSION_SECRET (openssl rand -hex 32).";missingSessionSecretProbe={name:"session-secret",check:async()=>({status:"degraded",error:MISSING_SESSION_SECRET_WARNING})}}});import{watchParent}from"@frontmcp/utils";function exitOnShutdownSignals(shutdown,options={}){const target=options.target??process;const deadlineMs=options.deadlineMs??DEFAULT_SHUTDOWN_DEADLINE_MS;let shuttingDown=false;let watcher;const begin=trigger=>{if(shuttingDown)return;shuttingDown=true;watcher?.close();const deadline=setTimeout(()=>target.exit(1),deadlineMs);shutdown(trigger).then(()=>{clearTimeout(deadline);target.exit(0)},error=>{clearTimeout(deadline);options.logger?.error("Graceful shutdown failed",error);target.exit(1)})};const onSignal=()=>begin("signal");for(const signal of SHUTDOWN_SIGNALS)target.on(signal,onSignal);if(options.whenOrphaned){watcher=watchParent({stdin:options.whenOrphaned.stdin,onGone:reason=>{options.logger?.info?.(ORPHANED_MESSAGES[reason]);begin(reason)}})}return()=>{watcher?.close();for(const signal of SHUTDOWN_SIGNALS)target.removeListener(signal,onSignal)}}var SHUTDOWN_SIGNALS,ORPHANED_MESSAGES,DEFAULT_SHUTDOWN_DEADLINE_MS,STDIO_SHUTDOWN_DEADLINE_MS,STDIO_DRAIN_MS;var init_shutdown_signals=__esm({"libs/sdk/src/front-mcp/shutdown-signals.ts"(){"use strict";SHUTDOWN_SIGNALS=["SIGTERM","SIGINT"];ORPHANED_MESSAGES={"parent-exited":"The parent process exited; shutting down","stdin-ended":"stdin ended; shutting down"};DEFAULT_SHUTDOWN_DEADLINE_MS=1e4;STDIO_SHUTDOWN_DEADLINE_MS=5e3;STDIO_DRAIN_MS=2e3}});function redirectConsoleToStderr(){const{Console}=__require("node:console");const stderrConsole=new Console({stdout:process.stderr,stderr:process.stderr});console.log=stderrConsole.log.bind(stderrConsole);console.info=stderrConsole.info.bind(stderrConsole);console.debug=stderrConsole.debug.bind(stderrConsole);console.dir=stderrConsole.dir.bind(stderrConsole);console.table=stderrConsole.table.bind(stderrConsole);console.time=stderrConsole.time.bind(stderrConsole);console.timeLog=stderrConsole.timeLog.bind(stderrConsole);console.group=stderrConsole.group.bind(stderrConsole);console.groupEnd=stderrConsole.groupEnd.bind(stderrConsole);console.count=stderrConsole.count.bind(stderrConsole)}var init_stdio_console=__esm({"libs/sdk/src/front-mcp/stdio-console.ts"(){"use strict"}});var instance_file_logger_exports={};__export(instance_file_logger_exports,{FileLogTransportInstance:()=>FileLogTransportInstance});import{escapeControlCharacters as escapeControlCharacters6}from"@frontmcp/utils";function getFs(){return _fs??=__require("fs")}function getOs(){return _os??=__require("os")}function getPath(){return _path??=__require("path")}function stripAnsi(str){return str.split(ESC).map(s=>s.replace(/\[[0-9;]*m/,"")).join("")}var _fs,_os,_path,LOG_LEVEL_LABELS,ESC,DEFAULT_LOGS_MAX,FileLogTransportInstance;var init_instance_file_logger=__esm({"libs/sdk/src/logger/instances/instance.file-logger.ts"(){"use strict";init_common();LOG_LEVEL_LABELS={[100]:"OFF",[0]:"DEBUG",[1]:"VERBOSE",[2]:"INFO",[3]:"WARN",[4]:"ERROR"};ESC=String.fromCharCode(27);DEFAULT_LOGS_MAX=25;FileLogTransportInstance=class extends LogTransportInterface{fd;logDir;appName;constructor(){super();const rawAppName=process.env["FRONTMCP_APP_NAME"]||"frontmcp";const sanitized=rawAppName.replace(/[^a-zA-Z0-9._-]/g,"_");this.appName=sanitized.length>0?sanitized:"frontmcp";this.logDir=process.env["FRONTMCP_LOG_DIR"]||getPath().join(process.env["FRONTMCP_HOME"]||getPath().join(getOs().homedir(),".frontmcp"),"logs");const logsMax=parseInt(process.env["FRONTMCP_LOGS_MAX"]||"",10);if(logsMax===0){this.fd=void 0;return}try{getFs().mkdirSync(this.logDir,{recursive:true});const ts=new Date().toISOString().replace(/:/g,"_");const filePath=getPath().join(this.logDir,`${this.appName}-${ts}.log`);this.fd=getFs().openSync(filePath,"a");this.rotate(isNaN(logsMax)?DEFAULT_LOGS_MAX:logsMax)}catch{this.fd=void 0}}close(){if(this.fd!==void 0){try{getFs().closeSync(this.fd)}catch{}this.fd=void 0}}log(rec){if(this.fd===void 0)return;const ts=rec.timestamp.toISOString();const level=LOG_LEVEL_LABELS[rec.level]??"INFO";const prefix=rec.prefix?` [${escapeControlCharacters6(rec.prefix)}]`:"";const message=escapeControlCharacters6(stripAnsi(String(rec.message)));const line=`[${ts}] ${level}${prefix} ${message}
489
+ Activate a skill first: send a skills/load request with activateSession: true.`;default:return`Tool '${toolName}' is not authorized for use in this skill session.`}}static formatSkillDisplay(skillName,skillId,activeSkillNames){if(activeSkillNames&&activeSkillNames.length>1){return activeSkillNames.join(" + ")}return skillName||skillId||"the active skill"}getPublicMessage(){return this.message}toJsonRpcError(){return{code:this.mcpErrorCode,message:this.getPublicMessage(),data:{toolName:this.toolName,skillId:this.skillId,skillName:this.skillName,activeSkillIds:this.activeSkillIds,activeSkillNames:this.activeSkillNames,reason:this.reason,allowedTools:this.allowedTools}}}};ToolApprovalRequiredError=class extends PublicMcpError{mcpErrorCode=MCP_ERROR_CODES.INVALID_REQUEST;toolName;skillId;constructor(toolName,skillId){const message=skillId?`Tool '${toolName}' requires approval to be used with skill '${skillId}'.`:`Tool '${toolName}' requires approval.`;super(message);this.name="ToolApprovalRequiredError";this.toolName=toolName;this.skillId=skillId}getPublicMessage(){return this.message}toJsonRpcError(){return{code:this.mcpErrorCode,message:this.getPublicMessage(),data:{toolName:this.toolName,skillId:this.skillId,requiresApproval:true}}}}}});async function handleAuthorizationResult(authResult,sessionManager,policyMode,skillId,onApprovalRequired,logger){if(authResult.allowed){logger?.verbose(`SkillToolGuard: tool "${authResult.toolName}" allowed`,{reason:authResult.reason});return}const allowlist=sessionManager.getToolAllowlist();if(authResult.reason==="no_active_skill")throw new ToolNotAllowedError(authResult,allowlist);switch(policyMode){case"strict":logger?.warn(`SkillToolGuard: blocking tool "${authResult.toolName}" (strict mode)`,{skillId,reason:authResult.reason,allowedTools:allowlist});throw new ToolNotAllowedError(authResult,allowlist);case"approval":logger?.info(`SkillToolGuard: tool "${authResult.toolName}" requires approval`,{skillId});if(authResult.requiresApproval&&onApprovalRequired){const approved=await onApprovalRequired(authResult.toolName,skillId);if(approved){sessionManager.approveToolForSession(authResult.toolName);logger?.info(`SkillToolGuard: tool "${authResult.toolName}" approved dynamically`);return}}throw new ToolApprovalRequiredError(authResult.toolName,skillId);case"permissive":default:logger?.warn(`SkillToolGuard: tool "${authResult.toolName}" not in allowlist (permissive mode)`,{skillId,reason:authResult.reason,allowedTools:allowlist});sessionManager.recordToolCall(authResult.toolName);return}}function createSkillToolGuardHook(sessionManager,options={}){const{logger,onApprovalRequired,trackToolCalls=true,verifiedSessionId}=options;class SkillToolGuardHookImpl{async checkSkillToolAuthorization(ctx){const{tool}=ctx.state;const rawToolName=tool?.name||tool?.metadata?.id||tool?.metadata?.name||ctx.state.input?.name||tool?.fullName;if(!rawToolName){logger?.verbose("SkillToolGuard: skipping (no tool name in context)");return}const toolName=rawToolName.includes(":")?rawToolName.substring(rawToolName.lastIndexOf(":")+1):rawToolName;const sessionId=verifiedSessionId?.();if(sessionId&&sessionManager.getActiveSession()?.sessionId!==sessionId){await sessionManager.runWithSession(sessionId,()=>authorizeInActiveSession(toolName));return}await authorizeInActiveSession(toolName)}}__decorateClass([Will("checkToolAuthorization",{priority:-1e3})],SkillToolGuardHookImpl.prototype,"checkSkillToolAuthorization",1);async function authorizeInActiveSession(toolName){const session=sessionManager.getActiveSession();if(!session?.activeSkillId){const authResult2=sessionManager.checkToolAuthorization(toolName);if(!authResult2.allowed)throw new ToolNotAllowedError(authResult2);logger?.verbose("SkillToolGuard: skipping (no active skill)");return}logger?.verbose(`SkillToolGuard: checking authorization for tool "${toolName}"`,{skillId:session.activeSkillId,policyMode:session.policyMode});const authResult=sessionManager.checkToolAuthorization(toolName);if(trackToolCalls&&authResult.allowed){sessionManager.recordToolCall(toolName)}await handleAuthorizationResult(authResult,sessionManager,session.strictAllowlist?"strict":session.policyMode,session.activeSkillId,onApprovalRequired,logger)}return SkillToolGuardHookImpl}var Will;var init_skill_tool_hook=__esm({"libs/sdk/src/skill/hooks/skill-tool.hook.ts"(){"use strict";init_common();init_tool_not_allowed_error();({Will}=FlowHooksOf("tools:call-tool"))}});var hooks_exports={};__export(hooks_exports,{createSkillToolGuardHook:()=>createSkillToolGuardHook});var init_hooks=__esm({"libs/sdk/src/skill/hooks/index.ts"(){"use strict";init_skill_tool_hook()}});var authorities_engine_exports={};__export(authorities_engine_exports,{authoritiesFromConfig:()=>authoritiesFromConfig,createAuthoritiesEngine:()=>createAuthoritiesEngine});import{AuthoritiesContextBuilder,AuthoritiesEngine,AuthoritiesEvaluatorRegistry,AuthoritiesProfileRegistry}from"@frontmcp/auth";function createAuthoritiesEngine(config){const profileRegistry=new AuthoritiesProfileRegistry;if(config["profiles"]){profileRegistry.registerAll(config["profiles"])}const evaluatorRegistry=new AuthoritiesEvaluatorRegistry;if(config["evaluators"]){evaluatorRegistry.registerAll(config["evaluators"])}return new AuthoritiesEngine(profileRegistry,evaluatorRegistry)}function authoritiesFromConfig(config){return{engine:createAuthoritiesEngine(config),contextBuilder:new AuthoritiesContextBuilder({claimsMapping:config["claimsMapping"],claimsResolver:config["claimsResolver"],relationshipResolver:config["relationshipResolver"]}),scopeMapping:config["scopeMapping"]}}var init_authorities_engine=__esm({"libs/sdk/src/front-mcp/authorities-engine.ts"(){"use strict"}});var send_elicitation_result_tool_exports={};__export(send_elicitation_result_tool_exports,{SendElicitationResultTool:()=>SendElicitationResultTool});import{internalZ as z148}from"@frontmcp/lazy-zod";var inputSchema50,SendElicitationResultTool;var init_send_elicitation_result_tool=__esm({"libs/sdk/src/elicitation/send-elicitation-result.tool.ts"(){"use strict";init_common();init_call_surface();init_errors();init_fallback_helper();inputSchema50={elicitId:z148.string().describe("The elicitation ID from the pending request"),action:z148.enum(["accept","cancel","decline"]).describe("User action: accept (submit), cancel, or decline"),content:z148.unknown().optional().describe("User response content (required for accept action)")};SendElicitationResultTool=class extends ToolContext{async execute(input){const{elicitId,action,content}=input;this.logger.info("sendElicitationResult: processing",{elicitId,action});const store=this.scope.elicitationStore;if(!store){this.logger.error("sendElicitationResult: scope or elicitationStore not available");return{content:[{type:"text",text:"Error: Elicitation store not available. Server may not be properly configured."}],isError:true}}const pending=await store.getPendingFallback(elicitId);if(!pending){this.logger.warn("sendElicitationResult: no pending elicitation found",{elicitId});return{content:[{type:"text",text:`Error: No pending elicitation found for ID: ${elicitId}. The request may have expired or already been processed.`}],isError:true}}const caller=resolveElicitationOwner(this.tryGetContext());if(!pending.owner||pending.owner!==caller){this.logger.warn("sendElicitationResult: refused a result from a caller the elicitation was not asked of",{elicitId});throw new ElicitationNotOwnedError(elicitId)}if(Date.now()>pending.expiresAt){await store.deletePendingFallback(elicitId);this.logger.warn("sendElicitationResult: elicitation expired",{elicitId});return{content:[{type:"text",text:`Error: Elicitation request has expired. Please try the original operation again.`}],isError:true}}const elicitResult={status:action,...action==="accept"&&content!==void 0&&{content}};await store.setResolvedResult(elicitId,elicitResult,pending.sessionId);await store.deletePendingFallback(elicitId);this.logger.info("sendElicitationResult: re-invoking original tool",{elicitId,toolName:pending.toolName});const ctx=this.tryGetContext();if(ctx){ctx.setPreResolvedElicitResult(elicitResult)}try{const toolResult=await this.scope.runFlowForOutput("tools:call-tool",{request:{method:"tools/call",params:{name:pending.toolName,arguments:pending.toolInput}},ctx:Object.defineProperty({authInfo:this.authInfo,requestId:this.tryGetContext()?.requestId??this.runId,surface:getCallSurface(),...this.signal?{signal:this.signal}:{}},"idempotencyKey",{value:pending.idempotencyKey})});this.logger.info("sendElicitationResult: original tool completed",{elicitId,toolName:pending.toolName});await store.publishFallbackResult(elicitId,pending.sessionId,{success:true,result:toolResult});await store.deleteResolvedResult(elicitId);return toolResult}catch(error){const errorMessage2=error instanceof Error?error.message:String(error);await store.publishFallbackResult(elicitId,pending.sessionId,{success:false,error:errorMessage2});await store.deleteResolvedResult(elicitId);this.logger.error("sendElicitationResult: original tool failed",{elicitId,toolName:pending.toolName,error:errorMessage2});return{content:[{type:"text",text:`Error re-invoking ${pending.toolName}: ${errorMessage2}`}],isError:true}}}};SendElicitationResultTool=__decorateClass([Tool({name:"sendElicitationResult",description:'Submit user response for a pending elicitation request. Use this after collecting user input for a tool that requested elicitation. Actions: "accept" (user submitted response), "cancel" (user cancelled), "decline" (user declined to answer).',inputSchema:inputSchema50,hideFromDiscovery:true})],SendElicitationResultTool)}});import"reflect-metadata";import{createGuardManager}from"@frontmcp/guard";import{createRedisClient as createRedisClient3,getEnvFlag,getMachineId as getMachineId6,getRuntimeContext as getRuntimeContext29,isEdgeRuntime as isEdgeRuntime2,mkdir as mkdir3}from"@frontmcp/utils";function keptUntilFailure(start,forget){return start.catch(error=>{forget();throw error})}function entriesWithAuthorities(registries,agentPath=""){const entries=[];const add=(kind,name59,metadata)=>{const authorities=metadata?.["authorities"];if(authorities!==void 0&&authorities!==null&&authorities!==false){entries.push({label:`${kind} "${agentPath}${name59}"`,authorities})}};for(const tool of registries.tools.getTools(true))add("Tool",tool.name,tool.metadata);for(const resource of registries.resources.getResources(true))add("Resource",resource.name,resource.metadata);for(const template of registries.resources.getResourceTemplates()){add("Resource template",template.name,template.metadata)}for(const prompt of registries.prompts.getPrompts(true))add("Prompt",prompt.name,prompt.metadata);for(const agent of registries.agents.getAgents(true)){add("Agent",agent.name,agent.metadata);const agentScope=agent.getAgentScope?.();if(!agentScope){for(const metadata of agentToolMetadata(agent))add("Tool",`${agent.name}:${metadata.name}`,metadata);continue}const{tools,resources,prompts,agents}=agentScope;entries.push(...entriesWithAuthorities({tools,resources,prompts,agents},`${agentPath}${agent.name}:`))}for(const skill of registries.skills?.getSkills(true)??[])add("Skill",skill.name,skill.metadata);return entries}var SCOPE_NON_DISPATCHABLE_FLOWS,Scope;var init_scope_instance=__esm({"libs/sdk/src/scope/scope.instance.ts"(){"use strict";init_adapter_registry();init_agent_registry();init_app_registry();init_auth_registry();init_direct_public_auth();init_channel_utils();init_common();init_sqlite();init_forward_headers_utils();init_path_utils();init_complete_flow();init_context();init_metadata_utils();init_errors();init_plugin_errors();init_event_utils();init_flow_registry();init_authorities_rules_check();init_detached_job_flag();init_direct_only_flag();init_hook_order();init_hook_registry();init_hooks_utils();init_job_utils();init_set_level_flow();init_instructions_budget_check();init_notification();init_offload_service();init_enforced_metadata_check();init_plugin_registry();init_prompt_registry();init_provider_registry();init_materialized_resources();init_resource_registry();init_skill_validation_error();init_skill_scope_helper();init_skill_registry();init_live_surface();init_task_backend_utils();init_tool_output_policy();init_tool_instance();init_tool_registry();init_tool_utils();init_serving_mode_default();init_ui_shared();init_request_state();init_session_mode_check();init_browser_stores();init_dev_events_observability();init_event_publisher_providers();init_server_entries_helper();init_startup_report_helper();SCOPE_NON_DISPATCHABLE_FLOWS=new Set(["http:request"]);Scope=class _Scope extends ScopeEntry{id;globalProviders;logger;scopeProviders;scopeAuth;scopeFlows;scopeApps;scopeHooks;scopeTools;scopeResources;scopePrompts;scopeAgents;scopeSkills;scopePlugins;transportService;notificationService;liveSurface;haRedisClient;haSubscriberClient;transportBus;sessionRelayHandle;toolUIRegistry;authUiRegistry;entryPath;routeBase;orchestrated=false;server;registeredHttpRoutes=[];httpRouteRegistrar={registerRoute:(method,path4,handler)=>{this.registeredHttpRoutes.push({method,path:path4,handler});return this.server.registerRoute(method,path4,handler)}};_elicitationStore;elicitationBackendType;_persistentQuestions;_taskStore;taskBackendType;_taskRegistry;_skillSession;agentCallsServed;skillsServed;pendingAppJobs=[];jobsDecided=false;topLevelSqlite;lateJobsStart;_eventStore;_scopeJobs;_scopeWorkflows;_jobExecutionManager;_jobStateStore;_jobDefinitionStore;_rateLimitManager;_publicAccessGuard;lateGuardSetup=Promise.resolve();_authoritiesEngine;_authoritiesContextBuilder;_authoritiesScopeMapping;scopeAdapters;_scopeChannels;_channelNotificationService;_channelEventBus;_workflowEvents;_channelTeardown;_scopeEvents;_healthService;cliMode;directOnly;constructor(rec,globalProviders){super(rec,rec.provide);this.id=rec.metadata.id;this.logger=globalProviders.get(FrontMcpLogger).child("FrontMcp.MultiAppScope");this.globalProviders=globalProviders;this.server=this.globalProviders.get(FrontMcpServer);this.entryPath=resolveEntryPath(rec.metadata.http?.entryPath);if(rec.kind==="SPLIT_BY_APP"){this.routeBase=`/${rec.metadata.id}`}else{this.routeBase=""}this.cliMode=!!rec.metadata["__cliMode"];this.directOnly=isDirectOnly(rec.metadata);const distributedMode=rec.metadata.transport?.distributedMode;const providerCaching=rec.metadata.transport?.providerCaching;const userProviders=rec.metadata.providers??[];this.scopeProviders=new ProviderRegistry([...userProviders,...this.defaultScopeProviders],globalProviders,{distributedMode,providerCaching});this.ready=this.initialize()}async initialize(){const startedAt=Date.now();await this.scopeProviders.ready;const scopeRef={kind:"scope",id:this.id,ref:_Scope};const scopeProviders=this.scopeProviders;const perf=getEnvFlag("FRONTMCP_PERF");const t0=perf?performance.now():0;const mark=perf?label=>this.logger.info(`[PERF] ${label}: ${(performance.now()-t0).toFixed(1)}ms`):()=>{};await refuseStoresInBrowser(this.metadata);const httpServing=this.directOnly?void 0:await Promise.resolve().then(()=>(init_http_scope_helper(),http_scope_helper_exports));const createPrimaryAuth2=await this.primaryAuthFactory();this.scopeHooks=new HookRegistry(scopeProviders,[]);this.scopeFlows=new FlowRegistry(scopeProviders,httpServing?[httpServing.HttpRouteFlow,httpServing.HttpRequestFlow,httpServing.HttpIpFilterFlow]:[]);this.scopeAuth=new AuthRegistry(this,scopeProviders,[],scopeRef,this.metadata.auth,createPrimaryAuth2);this.scopeApps=new AppRegistry(this.scopeProviders,this.metadata.apps,scopeRef);this.logger.info(`Initializing ${this.metadata.apps.length} app(s)...`);const transportConfig=this.metadata.transport;const isDistributed=getRuntimeContext29().deployment==="distributed";if(isDistributed&&this.metadata.redis&&!this.cliMode&&!this.directOnly){const ha=await Promise.resolve().then(()=>(init_ha(),ha_exports));try{const haRedis=this.createHaRedisClient();const haSubscriber=this.createHaRedisClient("ha-subscriber");this.haManager=ha.HaManager.create({redis:haRedis,pubsubPublisher:haRedis,pubsubSubscriber:haSubscriber,nodeId:getMachineId6(),config:ha.resolveHaConfigFromEnv(),logger:this.logger});await this.haManager.start();this.logger.info("[HA] Manager started for distributed deployment")}catch(err){this.logger.warn("[HA] Failed to start HA manager \u2014 running without HA",{error:err});this.haManager=void 0;await this.closeHaRedisClient()}}let transportBus;if(this.haManager&&this.haRedisClient&&isDistributed){const bus=await Promise.resolve().then(()=>(init_bus(),bus_exports));const haConfig=this.haManager.getConfig();transportBus=new bus.RedisTransportBus(this.haRedisClient,getMachineId6(),{haKeyPrefix:haConfig.redisKeyPrefix,retryAfterSeconds:Math.ceil(haConfig.heartbeatTtlMs/1e3),logger:this.logger});this.transportBus=transportBus;this.logger.info("[HA] Transport bus created for distributed session routing")}const resolvedTopLevelSqlite=await this.resolveTopLevelSqlite();let effectivePersistence=transportConfig?.persistence;if(effectivePersistence===void 0&&resolvedTopLevelSqlite){effectivePersistence={sqlite:resolvedTopLevelSqlite}}if(httpServing){const service=new httpServing.TransportService(this,effectivePersistence,transportBus);this.transportService=service;this.onDispose(()=>service.destroy());httpServing.loadStreamableHttpTransportOnStart(this)}warnIfRequestStateKeyNotShared({logger:this.logger,metadata:this.metadata});warnIfSessionModeIgnored({logger:this.logger,transport:transportConfig,session:this.metadata.session});const transportService=this.transportService;if(this.haManager&&isDistributed&&transportService?.getBackendKind()==="redis"){this.haManager.startOrphanScanner({sessionKeyPrefix:transportService.getSessionKeyPrefix(),onOrphan:(sessionId,previousNodeId,session)=>transportService.adoptClaimedSession(sessionId,previousNodeId,session)})}if(getRuntimeContext29().deployment==="serverless"){const protocolCfg=transportConfig?.protocol;const hasSSE=typeof protocolCfg==="string"?protocolCfg!=="stateless-api":protocolCfg?.sse===true;if(hasSSE){this.logger.warn('[Deployment] SSE transport is not supported in serverless deployments. Consider using protocol: "stateless-api" for serverless targets.')}}const effectiveEventStoreConfig=transportConfig?.eventStore??(isDistributed&&this.metadata.redis&&!this.cliMode&&!this.directOnly?{enabled:true,provider:"redis",redis:this.metadata.redis}:void 0);if(effectiveEventStoreConfig?.enabled&&!this.cliMode&&!this.directOnly){const{createEventStore:createEventStore2}=await Promise.resolve().then(()=>(init_event_stores(),event_stores_exports));const{eventStore}=createEventStore2(effectiveEventStoreConfig,this.logger);this._eventStore=eventStore;this.logger.info("EventStore initialized for SSE resumability",{provider:effectiveEventStoreConfig.provider??"memory",autoEnabled:!transportConfig?.eventStore&&isDistributed})}const elicitationConfigured=this.metadata.elicitation?.enabled===true;const elicitationEnabled=elicitationConfigured&&!this.cliMode;const elicitationPromise=elicitationConfigured?(async()=>{const inheritedRedis=this.metadata.elicitation?.redis??this.metadata.redis;const elicitationInMemory=this.cliMode||this.metadata.elicitation?.store===false;const elicitationRedis=elicitationInMemory?void 0:inheritedRedis;const elicitationSqlite=elicitationInMemory||elicitationRedis?void 0:resolvedTopLevelSqlite;const persistent=this.cliMode?void 0:this.metadata.elicitation?.persistent;const questionsHelper=persistent?await Promise.resolve().then(()=>(init_question_scope_helper(),question_scope_helper_exports)):void 0;const onEdgeRuntime2=isEdgeRuntime2();const questionsStorage=questionsHelper?.persistentQuestionsSettings(persistent,onEdgeRuntime2).storage;const questionsRedis=!elicitationInMemory&&!elicitationRedis&&questionsStorage?.type==="redis"?questionsStorage:void 0;const{createElicitationStore:createElicitationStore2}=await Promise.resolve().then(()=>(init_elicitation_store_factory(),elicitation_store_factory_exports));const{store:elicitStore,type:elicitType,storage:elicitStorage}=await createElicitationStore2({redis:elicitationRedis,storage:elicitationInMemory?{type:"memory"}:questionsRedis,sqlite:elicitationSqlite,keyPrefix:elicitationRedis?.keyPrefix??"mcp:elicit:",logger:this.logger,isEdgeRuntime:onEdgeRuntime2});this._elicitationStore=elicitStore;this.elicitationBackendType=elicitType;if(elicitStorage){this.onDispose(async()=>{await elicitStore.destroy?.();await elicitStorage.disconnect()})}if(questionsHelper){const questions=await questionsHelper.openPersistentQuestions({persistent,serverName:this.metadata.info.name,redis:inheritedRedis,sqlite:resolvedTopLevelSqlite,onEdgeRuntime:onEdgeRuntime2,logger:this.logger});if(questions){this._persistentQuestions={...questions,sessionEndCheck:sessionId=>this.transportService?.sessionEndCheck(sessionId)};this.onDispose(()=>questions.store.close())}}})():void 0;const tasksConfig=this.metadata.tasks;const tasksInMemory=tasksConfig?.store===false;const tasksMemoryStorage=tasksInMemory?{type:"memory"}:void 0;const serverRedisForTasks=tasksInMemory?void 0:this.metadata.redis;const serverSqliteForTasks=tasksInMemory?void 0:resolvedTopLevelSqlite;const tasksExplicitlyDisabled=tasksConfig?.enabled===false;const tasksExplicitlyEnabled=tasksConfig?.enabled===true;const isTaskWorker=!!this.metadata["__taskWorkerMode"];const hasPersistentBackend=Boolean(tasksConfig?.sqlite||tasksConfig?.redis||serverRedisForTasks||serverSqliteForTasks);const tasksEnabledForCli=this.cliMode&&hasPersistentBackend;const hasDistributedTaskBackend=Boolean(tasksConfig?.redis??serverRedisForTasks);const onEdgeRuntime=isEdgeRuntime2();const tasksUnavailableOnEdge=onEdgeRuntime&&!hasDistributedTaskBackend&&!tasksExplicitlyEnabled;if(tasksUnavailableOnEdge){this.logger.info("[tasks] Background tasks are unavailable on this edge/serverless runtime: the in-process runner cannot continue past the HTTP response, and an in-memory store is not shared between isolates. Serving without tasks. Configure `tasks.redis` (Upstash Redis over HTTP works on Workers) to enable them.")}const gateTasksRedis=tasksConfig?.redis??serverRedisForTasks;const tasksUseSqlite=Boolean(tasksConfig?.sqlite??(gateTasksRedis?void 0:serverSqliteForTasks));const tasksUnavailableOnVercelKv=!tasksExplicitlyEnabled&&!tasksUseSqlite&&resolvesToVercelKvTaskBackend(gateTasksRedis,tasksMemoryStorage);if(tasksUnavailableOnVercelKv&&!tasksExplicitlyDisabled){this.logger.warn("[tasks] Background tasks are disabled: Vercel KV has no pub/sub, which task results and cancellation require. Serving without tasks. Configure `tasks.redis` with Redis or Upstash to enable them.")}const shouldInitTasks=!tasksExplicitlyDisabled&&!tasksUnavailableOnEdge&&!tasksUnavailableOnVercelKv&&(!this.cliMode||tasksEnabledForCli||isTaskWorker);const useCliRunner=!isTaskWorker&&tasksConfig?.runner==="cli";let taskModule;let cliTaskRunner;const tasksPromise=shouldInitTasks?(async()=>{taskModule=await Promise.resolve().then(()=>(init_task_scope_runtime(),task_scope_runtime_exports));if(useCliRunner)cliTaskRunner=(await Promise.resolve().then(()=>(init_cli_task_runner(),cli_task_runner_exports))).CliTaskRunner;const tasksRedis=tasksConfig?.redis??serverRedisForTasks;const tasksSqlite=tasksConfig?.sqlite??(tasksRedis?void 0:serverSqliteForTasks);const onEdge=onEdgeRuntime;if(onEdge){const msg="[tasks] Background tasks are enabled on an edge/serverless runtime. The in-process runner cannot continue past the HTTP response on this platform \u2014 task bodies will not execute. Run on a long-lived Node process, or set `tasks.enabled: false`.";if(tasksConfig?.strict){throw new Error(msg+" (tasks.strict: true refuses startup)")}this.logger.warn(msg)}const{store:taskStore,type:taskType,storage:taskStorage}=await taskModule.createTaskStore({storage:tasksMemoryStorage,redis:tasksRedis,sqlite:tasksSqlite,keyPrefix:tasksConfig?.keyPrefix??"mcp:task:",logger:this.logger,isEdgeRuntime:onEdge,listFrom:tasksConfig?.listFrom,maxTtlMs:tasksConfig?.maxTtlMs});this._taskStore=taskStore;this.onDispose(async()=>{await taskStore.destroy?.();await taskStorage?.disconnect()});this.taskBackendType=taskType;this._taskRegistry=new taskModule.TaskRegistry({enabled:tasksConfig?.enabled,defaultTtlMs:tasksConfig?.defaultTtlMs,maxTtlMs:tasksConfig?.maxTtlMs,defaultPollIntervalMs:tasksConfig?.defaultPollIntervalMs,maxConcurrentPerSession:tasksConfig?.maxConcurrentPerSession,keyPrefix:tasksConfig?.keyPrefix,strict:tasksConfig?.strict,sqlite:tasksConfig?.sqlite,cliRunnerCommand:tasksConfig?.cliRunnerCommand},this.logger)})():void 0;const installTaskRunner=shouldInitTasks?()=>{const tasks=taskModule;if(!this._taskStore||!this._taskRegistry||!tasks)return;if(useCliRunner&&!tasksConfig?.sqlite&&!tasksConfig?.redis&&!serverRedisForTasks&&!serverSqliteForTasks){throw new Error('[tasks] runner: "cli" requires a persistent backend (`tasks.sqlite`, `tasks.redis`, or a top-level `sqlite` without `tasks.store: false`) \u2014 the detached worker cannot share an in-memory store with this host.')}const runner=cliTaskRunner?new cliTaskRunner({store:this._taskStore,command:tasksConfig?.cliRunnerCommand,logger:this.logger}):new tasks.InProcessTaskRunner({scope:this,store:this._taskStore,registry:this._taskRegistry,notifier:new tasks.TaskNotifier(this.notificationService,this.logger),logger:this.logger});this._taskRegistry.setRunner(runner);this.logger.info(`[tasks] runner installed: ${runner.kind}`)}:void 0;const throttleConfig=this.metadata.throttle;const rateLimitPromise=throttleConfig?.enabled&&!this.cliMode?createGuardManager({config:{...throttleConfig,storage:guardStorageInBrowser(throttleConfig.storage,this.logger)},logger:this.logger}).then(mgr=>{this._rateLimitManager=mgr}):void 0;const batch1=[this.scopeHooks.ready,this.scopeFlows.ready,this.scopeAuth.ready,this.scopeApps.ready];if(elicitationPromise)batch1.push(elicitationPromise);if(tasksPromise)batch1.push(tasksPromise);if(rateLimitPromise)batch1.push(rateLimitPromise);await Promise.all(batch1);if(this.metadata.authProvidersVault){const{registerAuthProvidersVault:registerAuthProvidersVault2}=await Promise.resolve().then(()=>(init_auth_providers_providers(),auth_providers_providers_exports));const closeVaultStorage=await registerAuthProvidersVault2(scopeProviders,this.metadata.authProvidersVault,this.auth.tokenStorageAdapter,this.logger);if(closeVaultStorage)this.onDispose(closeVaultStorage)}const serverHooks=serverProviderHooks(this.scopeProviders,this.metadata.providers,scopeRef);if(serverHooks.length>0)await this.scopeHooks.registerHooks(false,...serverHooks);this.logger.verbose("HookRegistry initialized");this.logger.verbose("FlowRegistry initialized");if(this.transportService)this.logger.verbose("TransportService initialized");this.logger.verbose("AuthRegistry initialized");mark("batch1:parallel (hooks+flows+auth+apps)");let topLevelSqliteUsed=this.transportService?.isSessionStoreConfigured()===true&&this.transportService.getBackendKind()==="sqlite"||this.taskBackendType==="sqlite"||this.elicitationBackendType==="sqlite"||this._persistentQuestions?.type==="sqlite";const serverPlugins=[...this.metadata.plugins??[]];const appPlugins=this.scopeApps.getApps().flatMap(app=>"plugins"in app.metadata?app.metadata.plugins??[]:[]);const impliedObservability=this.metadata.observability===void 0?devEventsObservabilityConfig([...serverPlugins,...appPlugins]):void 0;const observabilityConfig=this.metadata.observability??impliedObservability;if(observabilityConfig){if(listsObservabilityPlugin(serverPlugins)){throw new PluginConfiguredTwiceError("ObservabilityPlugin","observability")}const{observabilityPlugins:observabilityPlugins2}=await Promise.resolve().then(()=>(init_observability_scope_helper(),observability_scope_helper_exports));serverPlugins.push(...observabilityPlugins2({config:observabilityConfig,logger:this.logger,globalProviders:this.globalProviders,implied:impliedObservability!==void 0}))}if(serverPlugins.length>0){const serverPluginScopeInfo={ownScope:this,parentScope:void 0,isStandaloneApp:false};this.scopePlugins=new PluginRegistry(this.scopeProviders,serverPlugins,scopeRef,serverPluginScopeInfo)}if(this.scopePlugins){await this.scopePlugins.ready}if(this.metadata.adapters?.length){const scopeAdapters=new AdapterRegistry(this.scopeProviders,this.metadata.adapters);this.scopeAdapters=scopeAdapters;await scopeAdapters.ready;this.onDispose(()=>scopeAdapters.dispose())}await registerServerEntries(this.scopeProviders,this.metadata,this.scopeApps.getApps().map(app=>app.id));await this.initAuthoritiesFromConfig();this.scopeTools=new ToolRegistry(this.scopeProviders,[],scopeRef);this.scopeResources=new ResourceRegistry(this.scopeProviders,[],scopeRef);this.scopePrompts=new PromptRegistry(this.scopeProviders,[],scopeRef);this.scopeAgents=new AgentRegistry(this.scopeProviders,[],scopeRef);const skillsConfig=this.metadata.skillsConfig;this.scopeSkills=new SkillRegistry(this.scopeProviders,this.metadata.skills??[],scopeRef,{...skillsConfig?.scoring?{scoring:skillsConfig.scoring}:{},...skillsConfig?.decision?{decision:skillsConfig.decision}:{},...skillsConfig?.failOnInvalidSkills!==void 0&&{failOnInvalidSkills:skillsConfig.failOnInvalidSkills}});await Promise.all([this.scopeTools.ready,this.scopeResources.ready,this.scopePrompts.ready,this.scopeAgents.ready,this.scopeSkills.ready]);if(this.scopePlugins){const pluginNames=this.scopePlugins.getPluginNames();this.logger.verbose(`PluginRegistry initialized (${pluginNames.length} plugin(s): [${pluginNames.join(", ")}])`)}const toolNames=this.scopeTools.getTools(true).map(t=>t.metadata.name);this.logger.verbose(`ToolRegistry initialized with initial ${toolNames.length} tool(s): [${toolNames.join(", ")}]`);this.logger.verbose(`ResourceRegistry initialized (${this.scopeResources.getResources().length} resource(s))`);this.logger.verbose(`PromptRegistry initialized (${this.scopePrompts.getPrompts().length} prompt(s))`);this.logger.verbose(`AgentRegistry initialized (${this.scopeAgents.getAgents().length} agent(s))`);this.logger.verbose(`SkillRegistry initialized (${this.scopeSkills.getSkills().length} skill(s))`);mark("batch2:parallel (tools+resources+prompts+agents+skills+plugins)");this.validateAuthoritiesConfig();this.validateEnforcedMetadata();checkHookOrder(hookRunsOf(this.scopeHooks),message=>this.logger.warn(message));for(const message of describeUnlistedOutputSchemas(this))this.logger.warn(message);await this.initGuardForDeclaredLimits();if(elicitationEnabled){await this.registerSendElicitationResultTool(scopeRef)}let uiResolver;if(!this.cliMode){const cdnOverrides=this.metadata.ui?.cdnOverrides;if(cdnOverrides&&Object.keys(cdnOverrides).length>0){const{createResolverWithOverrides:createResolverWithOverrides2}=__require("@frontmcp/uipack/resolver");uiResolver=createResolverWithOverrides2(cdnOverrides);this.logger.verbose("Created UI resolver with CDN overrides",{overrides:Object.keys(cdnOverrides)})}}this.toolUIRegistry=new ToolUIRegistry(uiResolver,{escapeStringResults:this.metadata.ui?.escapeStringResults,logger:this.logger});if(!this.cliMode){await this.compileUIWidgets()}if(!this.cliMode){await this.buildAuthUiRegistry()}const dynamicSkills=pluginsRegisterDynamicSkills([...serverPlugins,...appPlugins]);if(this.scopeSkills.hasAny()||dynamicSkills){await this.startSkillSession()}if(this.scopeSkills.hasAny()){try{const report=await this.scopeSkills.validateAllTools();if(report.warningCount>0){this.logger.verbose("Skill validation completed with warnings",{totalSkills:report.totalSkills,warningCount:report.warningCount})}}catch(error){if(error instanceof SkillValidationError){this.logger.error("Skill validation failed",{failedSkills:error.failedSkills.map(s=>({name:s.skillName,missingTools:s.missingTools}))});throw error}throw error}}await registerSkillCapabilities({skillRegistry:this.scopeSkills,flowRegistry:this.scopeFlows,resourceRegistry:this.scopeResources,providers:this.scopeProviders,skillsConfig:this.metadata.skillsConfig,logger:this.logger,dynamicSkills});if(this.scopeSkills.servesSkills())this.skillsServed=Promise.resolve();const jobsConfig=this.metadata.jobs;const metaRecord=this.metadata;const jobsList=metaRecord["jobTypes"]??[];const workflowsList=metaRecord["workflowTypes"]??[];const{items:appJobs,providers:jobProviders}=this.appEntryProviders("jobs",normalizeJob);const appWorkflows=[];for(const app of this.scopeApps.getApps()){const appMeta=app.metadata;if(Array.isArray(appMeta["workflows"]))appWorkflows.push(...appMeta["workflows"])}for(const served of this.pendingAppJobs){appJobs.push(...served.entries.jobs);for(const job of served.entries.jobs){jobProviders.set(normalizeJob(job).provide,served.entries.providers)}appWorkflows.push(...served.entries.workflows)}const allJobs=[...jobsList,...appJobs];const allWorkflows=[...workflowsList,...appWorkflows];const hasJobDeclarations=allJobs.length>0||allWorkflows.length>0;const explicitlyDisabled=jobsConfig?.enabled===false;const explicitlyEnabled=jobsConfig?.enabled===true;const autoEnabled=!explicitlyEnabled&&!explicitlyDisabled&&hasJobDeclarations;const effectivelyEnabled=explicitlyEnabled||autoEnabled;if(explicitlyDisabled&&hasJobDeclarations){this.logger.warn(`Jobs are explicitly disabled but ${allJobs.length} job(s) and ${allWorkflows.length} workflow(s) were declared on @App. Agents will NOT be able to invoke them \u2014 remove jobs.enabled: false or drop the @App({ jobs }) declarations.`)}if(effectivelyEnabled){if(autoEnabled){this.logger.info(`Jobs auto-enabled: detected ${allJobs.length} job(s) and ${allWorkflows.length} workflow(s) in @App declarations. Their runs are kept in jobs.store, else the top-level redis or sqlite, else in memory.`)}const jobsUseTopLevelSqlite=await this.startJobs(allJobs,jobProviders,allWorkflows,resolvedTopLevelSqlite);topLevelSqliteUsed||=jobsUseTopLevelSqlite;const jobRegistry=this._scopeJobs;const workflowRegistry=this._scopeWorkflows;if(jobRegistry&&workflowRegistry&&this.pendingAppJobs.length>0){const{unregistersAppJobEntries:unregistersAppJobEntries2}=await Promise.resolve().then(()=>(init_job_scope_helper(),job_scope_helper_exports));for(const served of this.pendingAppJobs){served.unregister=unregistersAppJobEntries2(jobRegistry,workflowRegistry,served.entries)}}}this.pendingAppJobs.length=0;this.jobsDecided=true;this.topLevelSqlite=resolvedTopLevelSqlite;if(this.metadata.sqlite&&!topLevelSqliteUsed&&getRuntimeContext29().runtime!=="browser"){this.logger.warn("[FrontMcp] Top-level `sqlite` config was provided but no subsystem consumes it (transport persistence, tasks, elicitation and jobs were all disabled or pre-configured with a different backend). Sessions will use in-memory storage. Remove the `sqlite` block or enable one of the subsystems.")}this.notificationService=new NotificationService(this);await this.notificationService.initialize();this.logger.verbose("NotificationService initialized");const liveSurface=new LiveSurface(this);liveSurface.start();this.liveSurface=liveSurface;this.onDispose(()=>liveSurface.stop());const materializedResources=new MaterializedResources(this);await materializedResources.start();this.onDispose(()=>materializedResources.stop());installTaskRunner?.();await this.scopeFlows.registryFlows([SetLevelFlow,CompleteFlow]);if(this.scopeAgents.listAllInstances().length>0){await this.serveAgentCalls()}if(this.metadata.elicitation?.enabled===true){const{ElicitationRequestFlow:ElicitationRequestFlow2,ElicitationResultFlow:ElicitationResultFlow2}=await Promise.resolve().then(()=>(init_flows2(),flows_exports2));await this.scopeFlows.registryFlows([ElicitationRequestFlow2,ElicitationResultFlow2])}if(taskModule){const{TasksGetFlow:TasksGetFlow2,TasksResultFlow:TasksResultFlow2,TasksCancelFlow:TasksCancelFlow2,TasksListFlow:TasksListFlow2}=taskModule;await this.scopeFlows.registryFlows([TasksGetFlow2,TasksResultFlow2,TasksCancelFlow2,TasksListFlow2])}if(this.metadata.registry){const{registerMcpRegistryFlows:registerMcpRegistryFlows2}=await Promise.resolve().then(()=>(init_mcp_registry_scope_helper(),mcp_registry_scope_helper_exports));await registerMcpRegistryFlows2({flowRegistry:this.scopeFlows,registryOptions:this.metadata.registry,servesServerEndpoint:this.routeBase===""&&this.metadata.apps.length>0})}await this.auth.ready;await transportService?.ready;if(this.haManager&&this.transportBus&&transportService){const{wireSessionRelay:wireSessionRelay2}=await Promise.resolve().then(()=>(init_relay_scope_helper(),relay_scope_helper_exports));this.sessionRelayHandle=wireSessionRelay2({nodeId:getMachineId6(),haManager:this.haManager,bus:this.transportBus,transportService,notifications:this.notificationService,flows:{runFlow:(name59,input)=>this.runFlow(name59,input)},logger:this.logger})}if(httpServing){httpServing.attachHttpRoutes(this,this.globalProviders);httpServing.registerCustomHttpRoutes({routes:this.metadata.http?.routes,server:this.httpRouteRegistrar,verifySession:request2=>this.runFlow("session:verify",{request:request2}),checkClientIp:(request2,response)=>this.runFlow("http:ip-filter",{request:request2,response}),entryPath:this.entryPath,routeBase:this.routeBase,healthPaths:httpServing.servedHealthPaths(this.metadata.health),logger:this.logger})}const channelsConfig=this.metadata.channels;if(channelsConfig?.enabled){const{items:appChannels,providers:channelProviders}=this.appEntryProviders("channels",normalizeChannel);const{registerChannelCapabilities:registerChannelCapabilities2}=await Promise.resolve().then(()=>(init_channel_scope_helper(),channel_scope_helper_exports));const channelResult=await registerChannelCapabilities2({providers:this.scopeProviders,owner:scopeRef,channelsList:appChannels,channelProviders,channelsConfig,eventBus:this._channelEventBus,notificationService:this.notificationService,flowRegistry:this.scopeFlows,toolRegistry:this.scopeTools,http:httpServing&&{server:this.httpRouteRegistrar,checkClientIp:(request2,response)=>this.runFlow("http:ip-filter",{request:request2,response}),entryPath:this.entryPath,routeBase:this.routeBase,healthPaths:httpServing.servedHealthPaths(this.metadata.health)},logger:this.logger});this._scopeChannels=channelResult.channelRegistry;this._channelNotificationService=channelResult.channelNotificationService;this._channelEventBus=channelResult.channelEventBus;this._channelTeardown=channelResult.teardown;this.onDispose(()=>this.teardownChannels());this.validateAuthoritiesConfig();this.validateEnforcedMetadata();if(!isJobWorker(this.metadata))await channelResult.connectServices()}const{items:appEvents,providers:eventProviders}=this.appEntryProviders("events",normalizeEvent);if(appEvents.length>0||this.metadata.events?.enabled===true){const{registerEventCapabilities:registerEventCapabilities2}=await Promise.resolve().then(()=>(init_event_scope_helper(),event_scope_helper_exports));const eventsResult=await registerEventCapabilities2({providers:this.scopeProviders,owner:scopeRef,eventsList:appEvents,eventProviders,eventsConfig:this.metadata.events,channelsEnabled:channelsConfig?.enabled,logger:this.logger});this._scopeEvents=eventsResult?.eventRegistry}await this.registerWidgetRoutes(httpServing);if(httpServing&&this.metadata.health?.enabled!==false){this._healthService=new httpServing.HealthService(this.metadata.health??{},this.metadata.info);this._healthService.autoDiscoverProbes(this);this.logger.verbose(`HealthService initialized (${this._healthService.getProbeCount()} probe(s))`)}for(const message of await describeBudgetOverruns(this))this.logger.warn(message);mark("batch3:finalization");this.logger.info(`Scope ready \u2014 ${this.formatScopeSummary()}`);reportStartup(this.scopePlugins,{toolsCount:this.scopeTools.getTools(true).length,resourcesCount:this.scopeResources.getResources().length,promptsCount:this.scopePrompts.getPrompts().length,durationMs:Date.now()-startedAt,scopeId:this.id},this.logger)}async primaryAuthFactory(){if(this.directOnly&&this.metadata.auth===void 0){return(scope,_providers,options)=>new DirectPublicAuth(scope,options)}const{createPrimaryAuth:createPrimaryAuth2}=await Promise.resolve().then(()=>(init_primary_auth_factory(),primary_auth_factory_exports));return createPrimaryAuth2}async resolveTopLevelSqlite(){const raw=this.metadata.sqlite;if(!raw||getRuntimeContext29().runtime==="browser")return void 0;let finalPath=raw.path;if(!finalPath||finalPath.length===0){finalPath=resolveDefaultSqlitePath({appName:this.metadata.info?.name,cliMode:this.cliMode});this.logger.info("[FrontMcp] No `sqlite.path` set \u2014 using default",{path:finalPath})}try{const{dirname:dirname10}=__require("path");await mkdir3(dirname10(finalPath),{recursive:true})}catch(err){this.logger.warn("[FrontMcp] Could not ensure sqlite parent directory exists",{path:finalPath,error:err.message})}return{...raw,path:finalPath}}async compileUIWidgets(){const toolsWithUI=this.scopeTools.getTools(true).filter(t=>hasUIConfig(t.metadata));if(toolsWithUI.length===0)return;const[{describeIgnoredUiOptions:describeIgnoredUiOptions2,describeServingModeDefault:describeServingModeDefault2},{StaticWidgetResourceTemplate:StaticWidgetResourceTemplate2},{describeWidgetServingProblems:describeWidgetServingProblems2,widgetUrlSourceOf:widgetUrlSourceOf2}]=await Promise.all([Promise.resolve().then(()=>(init_ui_option_warnings(),ui_option_warnings_exports)),Promise.resolve().then(()=>(init_ui_resource_template(),ui_resource_template_exports)),Promise.resolve().then(()=>(init_widget_serving(),widget_serving_exports)),this.toolUIRegistry.load()]);for(const tool of toolsWithUI){const resourceUri=tool.metadata.ui?.resourceUri;this.toolUIRegistry.registerTool(tool.metadata.name,typeof resourceUri==="string"?resourceUri:void 0);this.toolUIRegistry.checkTemplate(tool.metadata.name,tool.metadata.ui?.template,tool.metadata.ui?.uiType);await this.toolUIRegistry.checkRenderOptions(tool.metadata.name,tool.metadata.ui);for(const message of describeIgnoredUiOptions2(tool.metadata.name,tool.metadata.ui)){this.logger.warn(message)}}for(const message of describeServingModeDefault2("`@FrontMcp({ ui })`",this.metadata.ui?.servingMode)){this.logger.warn(message)}for(const app of this.apps.getApps()){const appMode=app.metadata.ui?.servingMode;for(const message of describeServingModeDefault2(`App "${app.id}" \`@App({ ui })\``,appMode)){this.logger.warn(message)}}this.scopeResources.registerDynamicResource(StaticWidgetResourceTemplate2);this.logger.verbose(`Registered UI resource template for ${toolsWithUI.length} tool(s) with UI configs`);const servingModes=new Map(toolsWithUI.map(t=>[t,toolServingMode(t,this)]));const servingProblems=toolsWithUI.flatMap(t=>describeWidgetServingProblems2(t.metadata.name,t.metadata.ui??{},servingModes.get(t)??"auto"));if(servingProblems.length>0)throw new InvalidToolUiConfigError(servingProblems);for(const tool of toolsWithUI){const uiConfig=tool.metadata.ui??{};const source=widgetUrlSourceOf2(tool.metadata.name,uiConfig,servingModes.get(tool)??"auto");if(!source)continue;this.toolUIRegistry.registerWidgetUrl(tool.metadata.name,source);if(source.servingMode==="custom-url")this.toolUIRegistry.updateResourceMetaFromConfig(tool.metadata.name,uiConfig)}const staticModeTools=toolsWithUI.filter(t=>{const mode=servingModes.get(t);return t.metadata.ui&&(mode==="static"||mode==="direct-url")&&t.metadata.ui.template});if(staticModeTools.length>0){let staticCompiledCount=0;await Promise.all(staticModeTools.map(async tool=>{const uiConfig=tool.metadata.ui;if(!uiConfig?.template){this.logger.warn(`Skipping static widget pre-compile for tool "${tool.metadata.name}" due to missing ui.template`);return}try{await this.toolUIRegistry.compileStaticWidgetAsync({toolName:tool.metadata.name,template:uiConfig.template,uiConfig});staticCompiledCount++;this.logger.verbose(`Compiled static widget for tool: ${tool.metadata.name}`)}catch(error){const errorMessage2=error instanceof Error?error.message:String(error);this.logger.error(`Failed to compile static widget for tool "${tool.metadata.name}": ${errorMessage2}`)}}));this.logger.info(`Pre-compiled ${staticCompiledCount}/${staticModeTools.length} static widget(s) for static mode tools`)}const inlineTools=toolsWithUI.filter(t=>{const mode=servingModes.get(t);return t.metadata.ui&&(mode==="inline"||mode==="auto")&&t.metadata.ui.template});if(inlineTools.length>0){let inlineCompiledCount=0;await Promise.all(inlineTools.map(async tool=>{const uiConfig=tool.metadata.ui;if(!uiConfig){this.logger.warn(`Skipping lean widget pre-compile for tool "${tool.metadata.name}" due to missing ui config`);return}try{await this.toolUIRegistry.compileLeanWidgetAsync({toolName:tool.metadata.name,uiConfig});inlineCompiledCount++;this.logger.verbose(`Compiled lean widget shell for tool: ${tool.metadata.name}`)}catch(error){const errorMessage2=error instanceof Error?error.message:String(error);this.logger.error(`Failed to compile lean widget shell for tool "${tool.metadata.name}": ${errorMessage2}`)}}));this.logger.info(`Pre-compiled ${inlineCompiledCount}/${inlineTools.length} lean widget shell(s) for inline mode tools`)}const hybridTools=toolsWithUI.filter(t=>t.metadata.ui&&servingModes.get(t)==="hybrid"&&t.metadata.ui.template);if(hybridTools.length>0){let hybridCompiledCount=0;await Promise.all(hybridTools.map(async tool=>{const uiConfig=tool.metadata.ui;if(!uiConfig){this.logger.warn(`Skipping hybrid widget pre-compile for tool "${tool.metadata.name}" due to missing ui config`);return}try{await this.toolUIRegistry.compileHybridWidgetAsync({toolName:tool.metadata.name,template:uiConfig.template,uiConfig});hybridCompiledCount++;this.logger.verbose(`Compiled hybrid widget shell for tool: ${tool.metadata.name}`)}catch(error){const errorMessage2=error instanceof Error?error.message:String(error);this.logger.error(`Failed to compile hybrid widget shell for tool "${tool.metadata.name}": ${errorMessage2}`)}}));this.logger.info(`Pre-compiled ${hybridCompiledCount}/${hybridTools.length} hybrid widget shell(s) for hybrid mode tools`)}}async registerWidgetRoutes(httpServing){const widgets=this.toolUIRegistry?.widgetRoutes()??[];if(widgets.length===0)return;if(!httpServing){for(const{toolName,path:path4}of widgets){this.logger.warn(`Tool "${toolName}": \`ui.servingMode: 'direct-url'\` serves the widget on GET ${path4}, and this in-process server serves no HTTP, so hosts cannot load it.`)}return}const{registerWidgetRoutes:registerWidgetRoutes2}=await Promise.resolve().then(()=>(init_widget_routes(),widget_routes_exports));await registerWidgetRoutes2({widgets,registry:this.toolUIRegistry,server:this.httpRouteRegistrar,checkClientIp:(request2,response)=>this.runFlow("http:ip-filter",{request:request2,response}),entryPath:this.entryPath,routeBase:this.routeBase,healthPaths:httpServing.servedHealthPaths(this.metadata.health),takenRoutes:[...this.registeredHttpRoutes.map(route=>({...route,owner:"a route of the server"})),...(this.httpRouteTable?.routes??[]).map(route=>({...route,owner:"an @HttpRoute"}))],flowFor:request2=>this.findHttpFlowName(request2),logger:this.logger})}async buildAuthUiRegistry(){const auth=this.metadata.auth;const authUi=auth?.ui;const authExtras=auth?.extras;const uiSlotCount=authUi?Object.keys(authUi).length:0;const extraCount=authExtras?Object.keys(authExtras).length:0;if(uiSlotCount===0&&extraCount===0)return;let sourceDir=this.metadata.__sourceDir;if(!sourceDir){sourceDir=process.cwd();if(uiSlotCount>0){this.logger.warn(`auth.ui paths will resolve against process.cwd() ("${sourceDir}") \u2014 the declaring @FrontMcp/@App source directory could not be captured. Use absolute paths if this is wrong.`)}}const{AuthUiRegistry:AuthUiRegistry2}=await Promise.resolve().then(()=>(init_auth_ui(),auth_ui_exports));const registry=new AuthUiRegistry2(this.logger);registry.registerAuthUiMap(authUi,sourceDir);registry.registerAuthExtrasMap(authExtras);const cdnOverrides=this.metadata.ui?.cdnOverrides;if(cdnOverrides&&Object.keys(cdnOverrides).length>0){registry.setResolverOverrides(cdnOverrides)}try{await registry.warmup()}catch(error){this.logger.warn("Auth-UI registry warmup encountered errors \u2014 affected custom pages will fall back to built-in",{error:error instanceof Error?error.message:String(error)})}this.authUiRegistry=registry;this.logger.verbose(`Auth-UI registry initialized (${uiSlotCount} slot file(s), ${extraCount} extra(s))`)}formatScopeSummary(){const entries=[];const add=(count,label)=>{if(count>0)entries.push(`${count} ${label}${count!==1?"s":""}`)};add(this.scopeApps.getApps().length,"app");add(this.scopeTools.getTools(true).length,"tool");add(this.scopeResources.getResources().length,"resource");add(this.scopePrompts.getPrompts().length,"prompt");add(this.scopeAgents.getAgents().length,"agent");add(this.scopeSkills.getSkills().length,"skill");if(this._scopeJobs)add(this._scopeJobs.getJobs().length,"job");if(this._scopeWorkflows)add(this._scopeWorkflows.getWorkflows().length,"workflow");if(this._scopeChannels)add(this._scopeChannels.size,"channel");if(this._scopeEvents)add(this._scopeEvents.getEvents().length,"event");return entries.length>0?entries.join(", "):"empty"}get defaultScopeProviders(){return[{scope:ProviderScope2.GLOBAL,name:"ScopeEntry",provide:ScopeEntry,useValue:this},{scope:ProviderScope2.GLOBAL,name:"Scope",provide:_Scope,useValue:this},{scope:ProviderScope2.GLOBAL,name:"FrontMcpLogger",provide:FrontMcpLogger,useValue:this.logger},{scope:ProviderScope2.GLOBAL,name:"FrontMcpContextStorage",provide:FrontMcpContextStorage,useValue:new FrontMcpContextStorage().configure(this.metadata.fetch,{...proxyTrustOf(this.metadata.throttle),forwardsHeader:createHeaderForwarder(this.metadata.http?.forwardHeaders)})},FrontMcpContextProvider,{scope:ProviderScope2.GLOBAL,name:"OffloadService",provide:OffloadService,useValue:new OffloadService(this.metadata.offload,this.logger)},...eventPublisherProviders(this)]}get auth(){return this.scopeAuth.getPrimary()}get hooks(){return this.scopeHooks}get authProviders(){return this.scopeAuth}get providers(){return this.scopeProviders}get apps(){return this.scopeApps}get tools(){return this.scopeTools}get toolUI(){return this.toolUIRegistry}get authUi(){return this.authUiRegistry}get resources(){return this.scopeResources}get prompts(){return this.scopePrompts}get agents(){return this.scopeAgents}get skills(){return this.scopeSkills}get jobs(){return this._scopeJobs}get workflows(){return this._scopeWorkflows}get channels(){return this._scopeChannels}get channelNotifications(){return this._channelNotificationService}get events(){return this._scopeEvents}get channelEventBus(){return this._channelEventBus??this._workflowEvents?.bus}async startJobs(jobs,jobProviders,workflows,topLevelSqlite){const jobsConfig=this.metadata.jobs;const scopeRef={kind:"scope",id:this.id,ref:_Scope};const notifyFn=async data=>{if(this.notificationService){this.logger.debug("Job notification",data)}};const{registerJobCapabilities:registerJobCapabilities2,resolveJobsStore:resolveJobsStore2,jobsServerStore:jobsServerStore2}=await Promise.resolve().then(()=>(init_job_scope_helper(),job_scope_helper_exports));refuseServerStoresInBrowser({jobs:jobsServerStore2(jobsConfig?.store,this.metadata)});const jobsStore2=resolveJobsStore2(jobsConfig?.store,{redis:this.metadata.redis,sqlite:topLevelSqlite});const effectiveConfig={...jobsConfig??{},enabled:true,store:jobsStore2};const result=await registerJobCapabilities2({providers:this.scopeProviders,flowRegistry:this.scopeFlows,owner:scopeRef,jobsList:jobs,jobProviders,workflowsList:workflows,jobsConfig:effectiveConfig,logger:this.logger,notifyFn,entryServer:isEntryServer(this.metadata),jobWorker:isJobWorker(this.metadata)});this._scopeJobs=result.jobRegistry;this._scopeWorkflows=result.workflowRegistry;this._jobExecutionManager=result.executionManager;this._jobStateStore=result.stateStore;this._jobDefinitionStore=result.definitionStore;this._workflowEvents=result.workflowEvents;this._channelEventBus??=result.workflowEvents?.bus;for(const toolCls of result.managementTools){try{const toolRecord=normalizeTool(toolCls);const toolInstance=new ToolInstance(toolRecord,this.scopeProviders,{kind:"scope",id:"_jobs",ref:toolCls});this.scopeTools.registerToolInstance(toolInstance)}catch(error){this.logger.warn(`Failed to register job management tool: ${error instanceof Error?error.message:String(error)}`)}}this.logger.info(`Jobs system initialized: ${this._scopeJobs.getJobs().length} jobs, ${this._scopeWorkflows.getWorkflows().length} workflows`);return Boolean(topLevelSqlite)&&jobsStore2?.sqlite===topLevelSqlite}async serveAppJobs(entries){const served={entries};const withdraw=()=>{const pending=this.pendingAppJobs.indexOf(served);if(pending!==-1)this.pendingAppJobs.splice(pending,1);served.unregister?.();served.unregister=void 0};if(!this.jobsDecided){this.pendingAppJobs.push(served);return withdraw}if(this.metadata.jobs?.enabled===false){this.logger.warn(`Jobs are explicitly disabled, so the ${entries.jobs.length} job(s) and ${entries.workflows.length} workflow(s) an app loaded are not served. Remove jobs.enabled: false to serve them.`);return withdraw}this.lateJobsStart??=this._scopeJobs?Promise.resolve():keptUntilFailure(this.startJobs([],new Map,[],this.topLevelSqlite).then(()=>void 0),()=>this.lateJobsStart=void 0);await this.lateJobsStart;const jobRegistry=this._scopeJobs;const workflowRegistry=this._scopeWorkflows;if(!jobRegistry||!workflowRegistry)throw new InternalMcpError("The job system did not start");const{registerAppJobEntries:registerAppJobEntries2}=await Promise.resolve().then(()=>(init_job_scope_helper(),job_scope_helper_exports));served.unregister=await registerAppJobEntries2({jobRegistry,workflowRegistry,jobs:entries.jobs,workflows:entries.workflows,providers:entries.providers,runner:this.metadata.jobs?.runner});return withdraw}serveLateEntries(kinds){return Promise.all(kinds.map(kind=>kind==="agents"?this.serveAgentCalls():this.serveSkillsAddedLater())).then(()=>void 0)}serveAgentCalls(){this.agentCallsServed??=keptUntilFailure(Promise.resolve().then(()=>(init_flows4(),flows_exports3)).then(({CallAgentFlow:CallAgentFlow2})=>this.scopeFlows.registryFlows([CallAgentFlow2])),()=>this.agentCallsServed=void 0);return this.agentCallsServed}serveSkillsAddedLater(){this.skillsServed??=keptUntilFailure((async()=>{if(!this._skillSession)await this.startSkillSession();await serveSkillMethods({skillRegistry:this.scopeSkills,flowRegistry:this.scopeFlows,resourceRegistry:this.scopeResources,providers:this.scopeProviders,skillsConfig:this.metadata.skillsConfig,logger:this.logger})})(),()=>this.skillsServed=void 0);return this.skillsServed}async startSkillSession(){const[skillSession,{createSkillToolGuardHook:createSkillToolGuardHook2}]=await Promise.all([Promise.resolve().then(()=>(init_session2(),session_exports)),Promise.resolve().then(()=>(init_hooks(),hooks_exports))]);const store=skillSession.createSkillSessionStore({type:"memory"});this._skillSession=new skillSession.SkillSessionManager({defaultPolicyMode:"permissive"},this.logger,store);const GuardHookClass=createSkillToolGuardHook2(this._skillSession,{logger:this.logger,trackToolCalls:true,verifiedSessionId:()=>this.verifiedRequestSessionId()});const guardHookInstance=new GuardHookClass;const hookRecords=normalizeHooksFromCls(guardHookInstance);if(hookRecords.length>0){await this.scopeHooks.registerHooks(false,...hookRecords);this.logger.verbose("Skill tool authorization guard hook registered")}this.logger.verbose("Skill session manager initialized",{storeType:store.type})}verifiedRequestSessionId(){try{return this.scopeProviders.get(FrontMcpContextStorage).getStore()?.verifiedSessionId}catch{return void 0}}get skillSession(){return this._skillSession}get plugins(){return this.scopePlugins}get notifications(){return this.notificationService}get surface(){return this.liveSurface}get elicitationStore(){return this._elicitationStore}get persistentQuestions(){return this._persistentQuestions}get taskStore(){return this._taskStore}get tasks(){return this._taskRegistry}get eventStore(){return this._eventStore}get rateLimitManager(){return this._rateLimitManager}get publicAccessGuard(){return this._rateLimitManager??this._publicAccessGuard}get httpRoutes(){return this.registeredHttpRoutes}get healthService(){return this._healthService}get authoritiesEngine(){return this._authoritiesEngine}get authoritiesContextBuilder(){return this._authoritiesContextBuilder}get authoritiesScopeMapping(){return this._authoritiesScopeMapping}getAllSupportedScopes(){const scopes=new Set;const collectScopes=metadata=>{const authProviders=metadata?.["authProviders"];if(!Array.isArray(authProviders))return;for(const ap of authProviders){if(typeof ap==="object"&&ap!==null&&"scopes"in ap){const apScopes=ap["scopes"];if(Array.isArray(apScopes)){apScopes.forEach(s=>{if(typeof s==="string")scopes.add(s)})}}}};for(const tool of this.scopeTools.getTools(true)){collectScopes(tool.metadata)}for(const resource of this.scopeResources.getResources()){collectScopes(resource.metadata)}for(const prompt of this.scopePrompts.getPrompts()){collectScopes(prompt.metadata)}for(const agent of this.scopeAgents.getAgents()){collectScopes(agent["metadata"])}return[...scopes].sort()}registerAuthoritiesEngine(engine,contextBuilder){this._authoritiesEngine=engine;this._authoritiesContextBuilder=contextBuilder}async initAuthoritiesFromConfig(){const config=this.metadata["authorities"];if(!config)return;try{const{authoritiesFromConfig:authoritiesFromConfig2}=await Promise.resolve().then(()=>(init_authorities_engine(),authorities_engine_exports));const authorities=authoritiesFromConfig2(config);this._authoritiesEngine=authorities.engine;this._authoritiesContextBuilder=authorities.contextBuilder;this._authoritiesScopeMapping=authorities.scopeMapping;this.logger.verbose("Scope: authorities engine initialized from config")}catch(error){const msg=error instanceof Error?error.message:String(error);this.logger.warn(`Scope: authorities init failed \u2014 ${msg}`)}}appEntryProviders(key,normalize){const items=[];const providers=new Map;for(const app of this.scopeApps.getApps()){const declared=app.metadata[key];if(!Array.isArray(declared))continue;for(const item of declared){items.push(item);providers.set(normalize(item).provide,app.providers)}}return{items,providers}}async initGuardForDeclaredLimits(lateTools=[]){const throttleConfig=this.metadata.throttle;if(this._rateLimitManager||this.cliMode)return;if(throttleConfig?.enabled===false){await this.initPublicAccessGuard(throttleConfig.storage);return}const guardedEntries=[...this.scopeTools.getTools(true),...lateTools,...this.scopeAgents.getAgents(true)];const declaresLimits=guardedEntries.some(entry=>entry.metadata.rateLimit||entry.metadata.concurrency)||!!this.auth.options?.publicAccess||this.scopeAgents.listAllInstances().some(agent=>agent.declaresScopedLimits());if(!declaresLimits)return;this._rateLimitManager=await createGuardManager({config:{...throttleConfig,enabled:true,storage:guardStorageInBrowser(throttleConfig?.storage,this.logger)},logger:this.logger})}async initPublicAccessGuard(storage){const publicAccess=this.auth.options?.publicAccess;if(!publicAccess?.rateLimit||this._publicAccessGuard)return;this._publicAccessGuard=await createGuardManager({config:{enabled:true,storage:guardStorageInBrowser(storage,this.logger)},logger:this.logger})}collectEntriesWithAuthorities(){return entriesWithAuthorities({tools:this.scopeTools,resources:this.scopeResources,prompts:this.scopePrompts,agents:this.scopeAgents,skills:this.scopeSkills})}validateAuthoritiesConfig(){assertEntryAuthorities(this._authoritiesEngine,this._authoritiesContextBuilder,this.collectEntriesWithAuthorities())}async checkLateApp(app){const{tools,resources,prompts,agents,skills}=app;assertEntryAuthorities(this._authoritiesEngine,this._authoritiesContextBuilder,entriesWithAuthorities(app));const problems=findUnenforcedMetadata({hooks:this.scopeHooks,tools,resources,prompts,agents,skills});if(problems.length>0)throw new UnenforcedMetadataError(problems);checkHookOrder(hookRunsOf(this.scopeHooks),message=>this.logger.warn(message));const setup=this.lateGuardSetup.then(()=>this.initGuardForDeclaredLimits(tools.getTools(true)));this.lateGuardSetup=setup.catch(()=>void 0);await setup}validateEnforcedMetadata(){const problems=findUnenforcedMetadata({hooks:this.scopeHooks,tools:this.scopeTools,resources:this.scopeResources,prompts:this.scopePrompts,agents:this.scopeAgents,skills:this.scopeSkills});if(problems.length>0)throw new UnenforcedMetadataError(problems)}async registerSendElicitationResultTool(_scopeRef){try{const{SendElicitationResultTool:SendElicitationResultTool2}=await Promise.resolve().then(()=>(init_send_elicitation_result_tool(),send_elicitation_result_tool_exports));const toolRecord=normalizeTool(SendElicitationResultTool2);const systemToolEntry=new ToolInstance(toolRecord,this.scopeProviders,{kind:"scope",id:"_system",ref:SendElicitationResultTool2});this.scopeTools.registerToolInstance(systemToolEntry);this.logger.verbose("Registered sendElicitationResult system tool")}catch(error){this.logger.warn(`Failed to register sendElicitationResult tool: ${error instanceof Error?error.message:String(error)}`)}}get pagination(){return this.metadata.pagination}registryFlows(...flows){return this.scopeFlows.registryFlows(flows)}runFlow(name59,input,deps){return this.scopeFlows.runFlow(name59,input,deps)}async findHttpFlowName(request2){return this.scopeFlows.findHttpFlowName(request2,SCOPE_NON_DISPATCHABLE_FLOWS)}async runFlowForOutput(name59,input,deps){const result=await this.scopeFlows.runFlow(name59,input,deps);if(result){return result}throw new FlowExitedWithoutOutputError}createHaRedisClient(label="ha"){const redis=this.metadata.redis;if(!redis||redis.provider==="vercel-kv"){throw new Error("Distributed HA requires a TCP Redis (ioredis); Vercel KV over REST has no Lua/pub-sub support")}const client=createRedisClient3({...redis,label,logger:this.logger});if(label==="ha-subscriber")this.haSubscriberClient=client;else this.haRedisClient=client;return client}async closeHaRedisClient(){const clients=[this.haRedisClient,this.haSubscriberClient];this.haRedisClient=void 0;this.haSubscriberClient=void 0;for(const client of clients){if(!client)continue;try{await client.quit()}catch{client.disconnect()}}}async shutdown(){if(this.sessionRelayHandle){try{await this.sessionRelayHandle.close()}catch(err){this.logger.error("[HA] Session relay shutdown failed",{error:err})}this.sessionRelayHandle=void 0}if(this.haManager){try{await this.haManager.stop()}catch(err){this.logger.error("[HA] Manager shutdown failed",{error:err})}}await this.closeHaRedisClient();await this.teardownChannels();this.httpRouteTable?.closeStreams()}async teardownChannels(){const teardown=this._channelTeardown;if(!teardown)return;this._channelTeardown=void 0;try{await teardown()}catch(err){this.logger.error("Channel teardown failed",{error:err})}}async dispose(){await this.emitDispose();await this.scopeProviders.runShutdownHooks(this.logger);this.scopeProviders.dispose();if(this.notificationService){await this.notificationService.destroy()}}}}});var init_scope=__esm({"libs/sdk/src/scope/index.ts"(){"use strict";init_scope_instance()}});function isProbe(property){return property==="then"||property==="toJSON"||property.startsWith("on")}function storeProvider(provider){storeFactories.add(provider.useFactory);return provider}function opensStore(factory){return typeof factory==="function"&&storeFactories.has(factory)}function storeNotOpened(name59){return new Proxy({},{get:(target,property,receiver)=>typeof property==="symbol"||isProbe(property)||property in target?Reflect.get(target,property,receiver):()=>{throw new StoreNotOpenedInBuildError(name59)}})}var storeFactories;var init_store_provider=__esm({"libs/sdk/src/provider/store.provider.ts"(){"use strict";init_build_store_errors();storeFactories=new WeakSet}});var LazyLeaseStore;var init_lazy_lease_store=__esm({"libs/sdk/src/duty/lazy-lease-store.ts"(){"use strict";init_describe_thrown();init_lease_store();LazyLeaseStore=class{constructor(config){this.config=config}config;openFailure;opened;async get(key){return(await this.open()).get(key)}async set(key,value,options){await(await this.open()).set(key,value,options)}async setIfEquals(key,expectedValue,value){return(await this.open()).setIfEquals(key,expectedValue,value)}async ttl(key){return(await this.open()).ttl(key)}async expireIfEquals(key,expectedValue,ttlSeconds){return(await this.open()).expireIfEquals(key,expectedValue,ttlSeconds)}async deleteIfEquals(key,expectedValue){return(await this.open()).deleteIfEquals(key,expectedValue)}async disconnect(){const storage=await this.opened?.catch(()=>void 0);await storage?.disconnect()}open(){this.opened??=openLeaseStore(this.config).then(storage=>{this.openFailure=void 0;return storage},error=>{this.opened=void 0;this.openFailure=describeThrown(error);throw error});return this.opened}}}});var duty_lifecycle_exports={};__export(duty_lifecycle_exports,{DutyLifecycle:()=>DutyLifecycle,dutyHealth:()=>dutyHealth,dutyLifecycleOf:()=>dutyLifecycleOf,dutyStorageConfig:()=>dutyStorageConfig,startDuties:()=>startDuties});function dutyLifecycleOf(duty,metadata,providers){let lifecycle=lifecycles.get(duty);if(!lifecycle){lifecycle=new DutyLifecycle(duty,metadata,providers);lifecycles.set(duty,lifecycle)}return lifecycle}async function startDuties(providers){for(const instance of providers.getAllSingletons().values()){if(typeof instance==="object"&&instance!==null)await lifecycles.get(instance)?.onReady()}}function dutyStorageConfig(redis,scope="machine"){return leaseStorageConfig(redis,"duty",scope)}function dutyHealth(holdsLease,leaseStoreFailure){const details={holdsLease};if(leaseStoreFailure===void 0)return{status:"healthy",details};return{status:"unhealthy",details,error:`the lease store cannot be opened: ${leaseStoreFailure}`}}var lifecycles,claims,DutyLifecycle;var init_duty_lifecycle=__esm({"libs/sdk/src/duty/duty.lifecycle.ts"(){"use strict";init_common();init_duty_errors();init_front_mcp_tokens2();init_cron_schedule();init_duty_runner();init_lazy_lease_store();init_lease_store();lifecycles=new WeakMap;claims=new LeaseClaims;DutyLifecycle=class{constructor(duty,metadata,providers){this.duty=duty;this.metadata=metadata;this.providers=providers}duty;metadata;providers;started;resumable=false;shutDown=false;lastTurn=Promise.resolve();claimedKey;cron;async onBootstrap(){await this.refuseWhatCannotRun();await this.duty.onBootstrap?.()}async onReady(){await this.duty.onReady?.();this.started??=this.startRunner();await this.started}async stopBackground(){await this.inTurn(async()=>{if(this.started)this.resumable=true;await this.stopRunner()})}async resumeBackground(){await this.inTurn(async()=>{if(!this.resumable||this.shutDown)return;this.resumable=false;this.started=this.startRunner();await this.started})}async onShutdown(){this.shutDown=true;await this.inTurn(()=>this.stopRunner());await this.duty.onShutdown?.()}inTurn(step){const turn=this.lastTurn.then(step);this.lastTurn=turn.catch(()=>void 0);return turn}async stopRunner(){const starting=this.started;this.started=void 0;const started=await starting?.catch(()=>void 0);if(started){await started.runner.stop();await started.storage.disconnect();started.removeHealthProbe()}this.releaseClaim()}async refuseWhatCannotRun(){const{name:name59,cron,scope}=this.metadata;if(cron)await this.cronSchedule(cron);if(scope!=="cluster"||!isLongLivedProcess())return;const config=this.providers.get(FrontMcpConfig);if(startsBackgroundWork(config)&&dutyStorageConfig(config.redis,scope).type!=="redis"){throw new ClusterScopeNeedsRedisError(`Duty "${name59}"`)}}cronSchedule(cron){this.cron??=loadCronSchedule(cron).catch(error=>{throw new InvalidDutyCronError(this.metadata.name,cron.expression,error.message)});return this.cron}async startRunner(){const{metadata}=this;const{name:name59,leaseMs,scope}=metadata;const logger=this.providers.get(FrontMcpLogger);if(!isLongLivedProcess()){logger.warn(`Duty "${name59}" does not run in a serverless or edge deployment: it needs a long-lived process`);return void 0}const config=this.providers.get(FrontMcpConfig);const serverName=config.info?.name??"frontmcp";const key=leaseKey(name59,scope,serverName);this.claim(serverName);const storage=new LazyLeaseStore(dutyStorageConfig(config.redis,scope));const run=context=>this.duty.run(context);const common={name:name59,key,leaseMs,storage,logger,run};const runner=new DutyRunner(metadata.cron?{...common,cron:await this.cronSchedule(metadata.cron)}:{...common,everyMs:metadata.everyMs});const removeHealthProbe=registerReadinessProbe(this.providers,{name:`duty:${name59}`,check:async()=>dutyHealth(runner.holdsLease,storage.openFailure)});await runner.start();return{runner,storage,removeHealthProbe}}claim(serverName){const key=nameKey(this.metadata.name,serverName);const type=this.duty.constructor;const otherClass=claims.claim(key,type);if(otherClass!==void 0){throw new DutyNameConflictError(this.metadata.name,serverName,otherClass,type.name)}this.claimedKey=key}releaseClaim(){const key=this.claimedKey;this.claimedKey=void 0;if(key!==void 0)claims.release(key)}}}});function aborted(signal,timeoutMs){return new Promise(resolve4=>{const settle=()=>{clearTimeout(timer);signal.removeEventListener("abort",settle);resolve4()};const timer=setTimeout(settle,timeoutMs);timer.unref?.();signal.addEventListener("abort",settle)})}var WorkerSupervisor;var init_worker_supervisor=__esm({"libs/sdk/src/worker/worker.supervisor.ts"(){"use strict";init_describe_thrown();WorkerSupervisor=class{constructor(options){this.options=options}options;controller;ended=Promise.resolve();state="standby";restarts=0;lastError;stopped=false;finished=false;start(){if(this.stopped)return;const controller=new AbortController;this.controller=controller;this.ended=this.ended.then(()=>this.supervise(controller.signal)).catch(error=>this.options.logger.error(`Worker "${this.options.name}" is no longer supervised: ${describeThrown(error)}`))}abort(){this.controller?.abort();if(this.state==="stopped")this.state="standby"}async stop(){this.stopped=true;this.abort();await this.ended}status(){const{state,restarts,lastError}=this;return lastError===void 0?{state,restarts}:{state,restarts,lastError}}async supervise(signal){if(this.finished){if(!signal.aborted)this.state="stopped";return}const{restart}=this.options;let delayMs=restart?restart.minDelayMs:0;while(!signal.aborted){this.state="running";const startedAt=performance.now();const failure=await this.runOnce(signal);if(signal.aborted)break;if(!restart){this.finished=true;this.state="stopped";this.report(failure,"it does not run again (restart: false)");return}if(performance.now()-startedAt>restart.maxDelayMs)delayMs=restart.minDelayMs;this.state="restarting";this.restarts++;this.report(failure,`it runs again in ${delayMs} ms`);await aborted(signal,delayMs);delayMs=Math.min(delayMs*restart.factor,restart.maxDelayMs)}this.state="standby"}async runOnce(signal){try{await this.options.run({signal});this.lastError=void 0;return void 0}catch(error){if(signal.aborted)return void 0;this.lastError=describeThrown(error);return this.lastError}}report(failure,next){const{name:name59,logger}=this.options;if(failure===void 0)logger.warn(`Worker "${name59}" returned before its signal was aborted; ${next}`);else logger.error(`Worker "${name59}" failed: ${failure}; ${next}`)}}}});var worker_lifecycle_exports={};__export(worker_lifecycle_exports,{WorkerLifecycle:()=>WorkerLifecycle,startWorkers:()=>startWorkers,workerHealth:()=>workerHealth,workerLifecycleOf:()=>workerLifecycleOf});function workerLifecycleOf(worker,metadata,providers){let lifecycle=lifecycles2.get(worker);if(!lifecycle){lifecycle=new WorkerLifecycle(worker,metadata,providers);lifecycles2.set(worker,lifecycle)}return lifecycle}async function startWorkers(providers){for(const instance of providers.getAllSingletons().values()){if(typeof instance==="object"&&instance!==null)await lifecycles2.get(instance)?.onReady()}}function workerHealth(status,leaseStoreFailure){const{state,lastError}=status;if(leaseStoreFailure!==void 0){const error=`the lease store cannot be opened: ${leaseStoreFailure}`;return{status:"unhealthy",details:{...status},error}}if(state==="restarting")return{status:"degraded",details:{...status},error:lastError};if(state==="stopped"&&lastError!==void 0){return{status:"unhealthy",details:{...status},error:lastError}}return{status:"healthy",details:{...status}}}var lifecycles2,claims2,WorkerLifecycle;var init_worker_lifecycle=__esm({"libs/sdk/src/worker/worker.lifecycle.ts"(){"use strict";init_common();init_lazy_lease_store();init_lease_holder();init_lease_store();init_duty_errors();init_worker_errors();init_front_mcp_tokens2();init_worker_supervisor();lifecycles2=new WeakMap;claims2=new LeaseClaims;WorkerLifecycle=class{constructor(worker,metadata,providers){this.worker=worker;this.metadata=metadata;this.providers=providers}worker;metadata;providers;started;resumable=false;shutDown=false;lastTurn=Promise.resolve();claimedKey;async onBootstrap(){this.refuseClusterWithoutRedis();await this.worker.onBootstrap?.()}async onReady(){await this.worker.onReady?.();this.started??=this.start();await this.started}async stopBackground(){await this.inTurn(async()=>{if(this.started)this.resumable=true;await this.stopStarted()})}async resumeBackground(){await this.inTurn(async()=>{if(!this.resumable||this.shutDown)return;this.resumable=false;this.started=this.start();await this.started})}async onShutdown(){this.shutDown=true;await this.inTurn(()=>this.stopStarted());await this.worker.onShutdown?.()}inTurn(step){const turn=this.lastTurn.then(step);this.lastTurn=turn.catch(()=>void 0);return turn}async stopStarted(){const starting=this.started;this.started=void 0;const started=await starting?.catch(()=>void 0);if(started)await this.stop(started);this.releaseClaim()}refuseClusterWithoutRedis(){const{name:name59,scope}=this.metadata;if(scope!=="cluster"||!isLongLivedProcess())return;const config=this.providers.get(FrontMcpConfig);if(startsBackgroundWork(config)&&leaseStorageConfig(config.redis,"worker",scope).type!=="redis"){throw new ClusterScopeNeedsRedisError(`Worker "${name59}"`)}}async start(){const{name:name59,restart,scope}=this.metadata;const logger=this.providers.get(FrontMcpLogger);if(!isLongLivedProcess()){logger.warn(`Worker "${name59}" does not run in a serverless or edge deployment: it needs a long-lived process`);return void 0}const serverName=this.providers.get(FrontMcpConfig).info?.name??"frontmcp";this.claim(serverName);const supervisor=new WorkerSupervisor({name:name59,restart,logger,run:context=>this.worker.run(context)});if(scope!=="process")return this.contend(supervisor,scope,logger);logger.info(`Worker "${name59}" runs in this process`);supervisor.start();return{supervisor,removeHealthProbe:this.registerHealthProbe(supervisor)}}async contend(supervisor,scope,logger){const{name:name59,leaseMs}=this.metadata;const config=this.providers.get(FrontMcpConfig);const serverName=config.info?.name??"frontmcp";const key=leaseKey(name59,scope,serverName);const storage=new LazyLeaseStore(leaseStorageConfig(config.redis,"worker",scope));const removeHealthProbe=this.registerHealthProbe(supervisor,storage);const holder=new LeaseHolder({label:`Worker "${name59}"`,key,leaseMs,storage,logger,onAcquired:()=>{logger.info(`Worker "${name59}" runs in this process`);supervisor.start()},onLost:()=>supervisor.abort()});await holder.start();return{supervisor,lease:{holder,storage},removeHealthProbe}}async stop({supervisor,lease,removeHealthProbe}){if(lease){await lease.holder.stop(()=>supervisor.stop());await lease.storage.disconnect()}else{await supervisor.stop()}removeHealthProbe()}claim(serverName){const key=nameKey(this.metadata.name,serverName);const type=this.worker.constructor;const otherClass=claims2.claim(key,type);if(otherClass!==void 0){throw new WorkerNameConflictError(this.metadata.name,serverName,otherClass,type.name)}this.claimedKey=key}releaseClaim(){const key=this.claimedKey;this.claimedKey=void 0;if(key!==void 0)claims2.release(key)}registerHealthProbe(supervisor,storage){return registerReadinessProbe(this.providers,{name:`worker:${this.metadata.name}`,check:async()=>workerHealth(supervisor.status(),storage?.openFailure)})}}}});import"reflect-metadata";import{depsOfClass as depsOfClass12,hasAsyncWith,isClass as isClass20,isPromise,ProviderKind as ProviderKind4,ProviderScope as ProviderScope11,tokenName as tokenName22}from"@frontmcp/di";function verifiedSessionOf2(requestContext){const{authInfo}=requestContext;const verified=authInfo.sessionId??authInfo.extra?.["sessionId"];return typeof verified==="string"&&verified.length>0&&verified!==STATELESS_SESSION_ID?verified:void 0}function requestScopedTokens(contextProviders){const requestContext=contextProviders?.get(FRONTMCP_CONTEXT);const carriedTokens=requestContext instanceof FrontMcpContext?requestContext.getContextTokens().keys():[];return new Set([FRONTMCP_CONTEXT,...carriedTokens])}function newProviderStore(){return{providers:new Map,bySource:new Map,lastAccess:Date.now()}}var ProviderRegistry,REQUEST_PROVIDER_STORES;var init_provider_registry=__esm({"libs/sdk/src/provider/provider.registry.ts"(){"use strict";init_common();init_transport();init_frontmcp_context();init_frontmcp_context_provider();init_errors();init_front_mcp_tokens2();init_manifest_mode_flag();init_regsitry();init_scope();init_transport_types();init_provider_lifecycle();init_provider_utils();init_store_provider();ProviderRegistry=class _ProviderRegistry extends RegistryAbstract{constructor(list,parentProviders,options){super("ProviderRegistry",parentProviders,list,false);this.parentProviders=parentProviders;this.providedBy=new Map;const configured=options?.distributedMode!==void 0||options?.providerCaching!==void 0;this.sessionCacheEnabled=!configured&&parentProviders?parentProviders.sessionCacheEnabled:shouldCacheProviders(options?.distributedMode,options?.providerCaching);this.sharedLifecycles=parentProviders?.sharedLifecycles??new WeakMap;this.shutdownHookTimeoutMs=options?.shutdownHookTimeoutMs??parentProviders?.shutdownHookTimeoutMs??DEFAULT_SHUTDOWN_HOOK_TIMEOUT_MS;this.buildGraph();this.topoSort();parentProviders?.childRegistries.add(this);this.ready=this.initialize()}parentProviders;providedBy;visibleOnlyBelow=new Map;order=new Set;registries=new Map;sessionStores=new Map;sessionBuildLocks=new Map;static MAX_SESSION_CACHE_SIZE=1e4;static SESSION_CACHE_TTL_MS=36e5;static SESSION_CLEANUP_INTERVAL_MS=6e4;sessionCleanupInterval=null;sessionCacheEnabled;childRegistries=new Set;lifecycleEntries=[];heldEntries=[];backgroundEntries=[];sharedLifecycles;shutdownHookTimeoutMs;readyHooksRun;shutdownHooksRun;getProviders(){return[...this.instances.values()]}lookupDefInHierarchy(token,requester=this){const rec=this.defs.get(token);if(rec&&!this.hidesFrom(token,requester))return{registry:this,rec};return this.providers?.lookupDefInHierarchy(token,requester)}hidesFrom(token,requester){const roots=this.visibleOnlyBelow.get(token);if(!roots||requester===this)return false;for(const root of roots){if(requester.isWithin(root))return false}return true}isWithin(root){return this===root||(this.parentProviders?.isWithin(root)??false)}subtreeBelow(ancestor){if(this.parentProviders===ancestor)return this;return this.parentProviders?.subtreeBelow(ancestor)}resolveDefaultFromHierarchy(token){const found=this.lookupDefInHierarchy(token);if(!found)throw new ProviderNotRegisteredError(tokenName22(token),"not registered in hierarchy");const{registry,rec}=found;const sc=registry.getProviderScope(rec);if(sc!==ProviderScope11.GLOBAL){const scName=ProviderScope11[sc];throw new ProviderScopeMismatchError(tokenName22(token),scName,registry.constructor.name)}const inst=registry.instances.get(token);if(inst===void 0){throw new ProviderNotInstantiatedError(tokenName22(token),"DEFAULT",registry.constructor.name)}return inst}buildMap(list){const tokens=new Set;const defs=new Map;const graph=new Map;for(const raw of list){const rec=normalizeProvider(raw);const provide=rec.provide;tokens.add(provide);defs.set(provide,rec);graph.set(provide,new Set)}return{tokens,defs,graph}}buildGraph(){for(const token of this.tokens){const rec=this.defs.get(token);const deps=this.discoveryDeps(rec);for(const d of deps){const isLocal=this.tokens.has(d);const up=isLocal?void 0:this.lookupDefInHierarchy(d);if(!isLocal&&!up){throw new ProviderDependencyError(`Provider ${tokenName22(token)} depends on ${tokenName22(d)}, which is not registered (local or parent).`)}this.assertDependencyScope(token,rec,d);if(isLocal)this.graph.get(token).add(d)}}}assertDependencyScope(token,rec,dependency){if(this.getProviderScope(rec)!==ProviderScope11.GLOBAL)return;const local=this.defs.get(dependency);const up=local?void 0:this.lookupDefInHierarchy(dependency);const depScope=local?this.getProviderScope(local):up&&up.registry.getProviderScope(up.rec);if(depScope===void 0||depScope===ProviderScope11.GLOBAL)return;throw new InvalidDependencyScopeError(`Invalid dependency: DEFAULT-scoped provider ${tokenName22(token)} cannot depend on scoped provider ${tokenName22(dependency)}.`)}topoSort(){const WHITE=0,GRAY=1,BLACK=2;const color=new Map;const order=new Set;const path4=[];const dfs=n=>{color.set(n,GRAY);path4.push(n);for(const dep of this.graph.get(n)??[]){const c=color.get(dep)??WHITE;if(c===GRAY){const idx=path4.findIndex(p=>p===dep);const cycle=[...path4.slice(idx),dep].map(t=>tokenName22(t)).join(" -> ");throw new DependencyCycleError(cycle)}if(c===WHITE)dfs(dep)}color.set(n,BLACK);order.add(n);path4.pop()};for(const n of this.graph.keys())if((color.get(n)??WHITE)===WHITE)dfs(n);this.order=order}async initialize(opts){const force=!!opts?.force;const only=opts?.onlyTokens?new Set(opts.onlyTokens):null;for(const token of this.order){const rec=this.defs.get(token);if(this.getProviderScope(rec)!==ProviderScope11.GLOBAL)continue;if(only&&!only.has(token))continue;if(!force&&this.instances.has(token))continue;if(force&&this.instances.has(token)){this.instances.delete(token)}try{await this.initiateOne(token,rec)}catch(e){const msg=e?.message??e;console.error(`Failed instantiating:`,msg);throw new ProviderConstructionError(tokenName22(token),e instanceof Error?e:msg)}await this.bootstrapBuilt(token)}if(this.parentProviders){this.startSessionCleanup()}}async bootstrapBuilt(token){const built=this.instances.get(token);const background=await this.backgroundLifecycleOf(built);const instance=lifecycleHooksOf(background??built);if(!instance||this.heldEntries.some(held=>held.instance===instance))return;const entry={token,instance};const shared=this.sharedLifecycles.get(instance);const lifecycle=shared??{holders:0,bootstrapped:bootstrapProvider(entry)};if(!shared)this.sharedLifecycles.set(instance,lifecycle);lifecycle.holders++;await lifecycle.bootstrapped;if(!shared)this.lifecycleEntries.push(entry);if(!shared&&background)this.backgroundEntries.push({token,lifecycle:background});this.heldEntries.push(entry)}async backgroundLifecycleOf(built){if(typeof built!=="object"||built===null)return void 0;const duty=dutyMetadataOf(built);if(duty){const{dutyLifecycleOf:dutyLifecycleOf2}=await Promise.resolve().then(()=>(init_duty_lifecycle(),duty_lifecycle_exports));return dutyLifecycleOf2(built,duty,this)}const worker=workerMetadataOf(built);if(!worker)return void 0;const{workerLifecycleOf:workerLifecycleOf2}=await Promise.resolve().then(()=>(init_worker_lifecycle(),worker_lifecycle_exports));return workerLifecycleOf2(built,worker,this)}get readyHooksStarted(){return this.readyHooksRun!==void 0}runReadyHooks(logger){this.readyHooksRun??=this.readyHereAndBelow(logger);return this.readyHooksRun}runShutdownHooks(logger){this.shutdownHooksRun??=this.shutdownBelowAndHere(logger);return this.shutdownHooksRun}async readyHereAndBelow(logger){const failures=await readyProviders(this.lifecycleEntries,logger);for(const child of[...this.childRegistries])failures.push(...await child.runReadyHooks(logger));return failures}async stopBackgroundWork(logger){const timeoutMs=this.shutdownHookTimeoutMs;for(const{token,lifecycle}of this.backgroundEntries){const stillStopping=await outlasts(()=>lifecycle.stopBackground(),timeoutMs);if(!stillStopping)continue;const message=`Provider "${tokenName22(token)}" did not stop its background work within ${timeoutMs} ms`;logger.warn(message);throw new InternalMcpError(message,"BACKGROUND_STOP_TIMEOUT")}}resumeBackgroundWork(logger){for(const{token,lifecycle}of this.backgroundEntries){void lifecycle.resumeBackground().catch(error=>{logger.error(`Provider "${tokenName22(token)}" failed to start again: ${messageOf3(error)}`)})}}async shutdownBelowAndHere(logger){for(const child of[...this.childRegistries].reverse())await child.runShutdownHooks(logger);const lastHeld=this.heldEntries.filter(entry=>this.releaseLifecycleHold(entry.instance));await shutdownProviders(lastHeld,this.shutdownHookTimeoutMs,logger)}releaseLifecycleHold(instance){const lifecycle=this.sharedLifecycles.get(instance);if(!lifecycle)return true;lifecycle.holders--;return lifecycle.holders===0}getAllSingletons(){return this.instances}getContextScopedClasses(){const out=[];for(const[token,rec]of this.defs){if(this.getProviderScope(rec)!==ProviderScope11.CONTEXT)continue;if(rec.kind===ProviderKind4.CLASS)out.push({token,cls:rec.useClass});else if(rec.kind===ProviderKind4.CLASS_TOKEN)out.push({token,cls:rec.provide})}return out}discoveryDeps(rec){const registered={has:token=>this.tokens.has(token)||this.lookupDefInHierarchy(token)!==void 0};return providerDiscoveryDeps(rec,registered,(k,phase)=>depsOfClass12(k,phase))}invocationTokens(_token,rec){return providerInvocationTokens(rec,(k,phase)=>depsOfClass12(k,phase))}normalizeScope(scope){switch(scope){case ProviderScope11.SESSION:case ProviderScope11.REQUEST:return ProviderScope11.CONTEXT;default:return scope}}getProviderScope(rec){const rawScope=rec.metadata?.scope??ProviderScope11.GLOBAL;return this.normalizeScope(rawScope)}getScope(){return this.getActiveScope()}async withTimeout(p,ms,label){if(ms<=0||!Number.isFinite(ms))return p;let timer;try{const tm=new Promise((_,rej)=>timer=setTimeout(()=>rej(new Error(`Timeout after ${ms}ms: ${label}`)),ms));return await Promise.race([p,tm])}finally{clearTimeout(timer)}}async resolveFactoryArg(t,store,scopeKey){if(t===_ProviderRegistry)return this;if(store.has(t))return store.get(t);if(this.instances.has(t))return this.instances.get(t);const rec=this.defs.get(t);if(rec){const sc=this.getProviderScope(rec);if(sc===ProviderScope11.GLOBAL){if(!this.instances.has(t)){throw new ProviderNotInstantiatedError(tokenName22(t),"DEFAULT")}return this.instances.get(t)}else{await this.buildIntoStore(t,rec,store,scopeKey);return store.get(t)}}const up=this.lookupDefInHierarchy(t);if(up){const sc=up.registry.getProviderScope(up.rec);if(sc===ProviderScope11.GLOBAL){const inst=up.registry.instances.get(t);if(inst===void 0){throw new ProviderNotInstantiatedError(tokenName22(t),"DEFAULT","parent")}return inst}else{await up.registry.buildIntoStore(t,up.rec,store,scopeKey);return store.get(t)}}if(isClass20(t)){if(hasAsyncWith(t)){const out=t.with();return isPromise(out)?await this.withTimeout(out,this.asyncTimeoutMs,`${t.name}.with(...)`):out}const instance=new t;const init=instance?.init;if(typeof init==="function"){const ret=init.call(instance);if(isPromise(ret))await this.withTimeout(ret,this.asyncTimeoutMs,`${t.name}.init()`)}return instance}throw new ProviderNotRegisteredError(tokenName22(t),"not registered in hierarchy and not constructable")}bootsForBuild(){const config=this.lookupDefInHierarchy(FrontMcpConfig)?.rec;return config?.kind===ProviderKind4.VALUE&&typeof config.useValue==="object"&&config.useValue!==null&&isManifestMode(config.useValue)}async initiateOne(token,rec){switch(rec.kind){case ProviderKind4.VALUE:{this.instances.set(token,rec.useValue);return}case ProviderKind4.FACTORY:{if(opensStore(rec.useFactory)&&this.bootsForBuild()){this.instances.set(token,storeNotOpened(rec.metadata?.name??tokenName22(token)));return}const deps=this.invocationTokens(token,rec);const args=[];for(const d of deps)args.push(await this.resolveFactoryArg(d,this.instances));const out=rec.useFactory(...args);const val=isPromise(out)?await this.withTimeout(out,this.asyncTimeoutMs,`${tokenName22(token)}.useFactory(...)`):out;this.instances.set(token,val);return}case ProviderKind4.CLASS:{const depTokens=this.invocationTokens(token,rec);const deps=depTokens.map(t=>this.resolveDefaultFromHierarchy(t));const klass=rec.useClass;if(hasAsyncWith(klass)){const out=klass.with(...deps);const val=isPromise(out)?await this.withTimeout(out,this.asyncTimeoutMs,`${klass.name}.with(...)`):out;this.instances.set(token,val)}else{const instance=new klass(...deps);const init=instance?.init;if(typeof init==="function"){const ret=init.call(instance);if(isPromise(ret))await this.withTimeout(ret,this.asyncTimeoutMs,`${klass.name}.init()`)}this.instances.set(token,instance)}return}case ProviderKind4.CLASS_TOKEN:{const depTokens=this.invocationTokens(token,rec);const deps=depTokens.map(t=>this.resolveDefaultFromHierarchy(t));const klass=rec.provide;if(hasAsyncWith(klass)){const out=klass.with(...deps);const val=isPromise(out)?await this.withTimeout(out,this.asyncTimeoutMs,`${klass.name}.with(...)`):out;this.instances.set(token,val)}else{const instance=new klass(...deps);const init=instance?.init;if(typeof init==="function"){const ret=init.call(instance);if(isPromise(ret))await this.withTimeout(ret,this.asyncTimeoutMs,`${klass.name}.init()`)}this.instances.set(token,instance)}return}}}async buildIntoStore(token,rec,store,scopeKey,injectedDeps){if(store.has(token))return;try{switch(rec.kind){case ProviderKind4.VALUE:{store.set(token,rec.useValue);return}case ProviderKind4.FACTORY:{const deps=this.invocationTokens(token,rec);const args=[];for(const d of deps)args.push(await this.resolveFactoryArg(d,store,scopeKey));const out=rec.useFactory(...args);const val=isPromise(out)?await this.withTimeout(out,this.asyncTimeoutMs,`${tokenName22(token)}.useFactory(...)`):out;store.set(token,val);return}case ProviderKind4.CLASS:{const depsTokens=this.invocationTokens(token,rec);const deps=[];for(const d of depsTokens)deps.push(await this.resolveManagedForClass(d,store,scopeKey));const klass=rec.useClass;if(hasAsyncWith(klass)){const out=klass.with(...deps);const val=isPromise(out)?await this.withTimeout(out,this.asyncTimeoutMs,`${klass.name}.with(...)`):out;store.set(token,val)}else{const instance=new klass(...deps);const init=instance?.init;if(typeof init==="function"){const ret=init.call(instance);if(isPromise(ret))await this.withTimeout(ret,this.asyncTimeoutMs,`${klass.name}.init()`)}store.set(token,instance)}return}case ProviderKind4.CLASS_TOKEN:{const depsTokens=this.invocationTokens(token,rec);const deps=injectedDeps??[];for(const d of depsTokens)deps.push(await this.resolveManagedForClass(d,store,scopeKey));const klass=rec.provide;if(hasAsyncWith(klass)){const out=klass.with(...deps);const val=isPromise(out)?await this.withTimeout(out,this.asyncTimeoutMs,`${klass.name}.with(...)`):out;store.set(token,val)}else{const instance=new klass(...deps);const init=instance?.init;if(typeof init==="function"){const ret=init.call(instance);if(isPromise(ret))await this.withTimeout(ret,this.asyncTimeoutMs,`${klass.name}.init()`)}store.set(token,instance)}return}}}catch(e){const msg=e?.message??e;console.error(`Failed constructing:`,msg);throw new ProviderConstructionError(tokenName22(token),e instanceof Error?e:msg,"scoped")}}async resolveManagedForClass(d,store,scopeKey){if(store.has(d))return store.get(d);if(this.instances.has(d))return this.instances.get(d);const depRec=this.defs.get(d);if(depRec){const sc=this.getProviderScope(depRec);if(sc===ProviderScope11.GLOBAL){const v=this.instances.get(d);if(v===void 0)throw new ProviderNotInstantiatedError(tokenName22(d),"DEFAULT");return v}else{await this.buildIntoStore(d,depRec,store,scopeKey);return store.get(d)}}const up=this.lookupDefInHierarchy(d);if(up){const sc=up.registry.getProviderScope(up.rec);if(sc===ProviderScope11.GLOBAL){const v=up.registry.instances.get(d);if(v===void 0)throw new ProviderNotInstantiatedError(tokenName22(d),"DEFAULT","parent");return v}else{await up.registry.buildIntoStore(d,up.rec,store,scopeKey);return store.get(d)}}throw new ProviderNotInstantiatedError(tokenName22(d))}get(token){return this.getFor(token,this)}getFor(token,requester){const visible=!this.hidesFrom(token,requester);if(visible&&this.instances.has(token))return this.instances.get(token);const rec=visible?this.defs.get(token):void 0;if(rec&&this.getProviderScope(rec)!==ProviderScope11.GLOBAL){const scName=ProviderScope11[this.getProviderScope(rec)];throw new ProviderScopedAccessError(tokenName22(token),scName)}if(this.providers)return this.providers.getFor(token,requester);throw new ProviderNotAvailableError(tokenName22(token),"not found in local or parent registries")}addRegistry(type,value){let registry=this.registries.get(type);if(!registry){this.registries.set(type,new Set);registry=this.registries.get(type)}registry.add(value)}getRegistries(type){return[...this.registries.get(type)??[]]}getHooksRegistry(){return this.getRegistries("HookRegistry")[0]}getScopeRegistry(){return this.getRegistries("ScopeRegistry")[0]}async resolveBootstrapDep(t){if(this.instances.has(t))return this.instances.get(t);if(this.registries.has(t))return this.registries.get(t);const found=this.lookupDefInHierarchy(t);if(found){const{registry,rec}=found;const sc=registry.getProviderScope(rec);if(sc!==ProviderScope11.GLOBAL)throw new PluginDependencyError(`Plugin dependency ${tokenName22(t)} must be DEFAULT-scoped at bootstrap`);const v=registry.instances.get(t);if(v===void 0)throw new PluginDependencyError(`Plugin dependency ${tokenName22(t)} (DEFAULT scope) is not instantiated`);return v}throw new PluginDependencyError(`Cannot resolve plugin dependency ${tokenName22(t)} (local or parent)`)}resolve(cls){const found=this.lookupDefInHierarchy(cls);if(found){const{registry,rec}=found;const sc=registry.getProviderScope(rec);if(sc!==ProviderScope11.GLOBAL){const scName=ProviderScope11[sc];throw new ProviderScopedAccessError(tokenName22(cls),scName)}if(!registry.instances.has(cls)){throw new ProviderNotInstantiatedError(tokenName22(cls),"DEFAULT","Call providers.instantiate() first")}return registry.instances.get(cls)}if(isClass20(cls)){const instance=new cls;const init=instance?.init;if(typeof init==="function"){init.call(instance)}return instance}throw new ProviderNotRegisteredError(tokenName22(cls),"not a registered DEFAULT provider and not a constructable class")}mergeFromRegistry(providedBy,exported,visibleBelow){for(const{token,def,instance}of exported){if(visibleBelow){if(this.defs.has(token)&&!this.visibleOnlyBelow.has(token))continue;const roots=this.visibleOnlyBelow.get(token)??new Set;roots.add(visibleBelow);this.visibleOnlyBelow.set(token,roots)}else{this.visibleOnlyBelow.delete(token)}const scope=def.metadata.scope??ProviderScope11.GLOBAL;if(scope===ProviderScope11.GLOBAL&&instance!==void 0){this.instances.set(token,instance)}this.defs.set(token,def);this.providedBy.set(token,providedBy)}}getProviderInfo(token){const def=this.defs.get(token);if(!def)throw new ProviderNotRegisteredError(tokenName22(token),"not a registered DEFAULT provider and not a constructable class");const instance=this.instances.get(token);return{token,def,instance}}injectProvider(injected){const rec={...injected,kind:ProviderKind4.INJECTED};this.tokens.add(rec.provide);this.defs.set(rec.provide,rec);this.graph.set(rec.provide,new Set);this.instances.set(rec.provide,rec.value)}async addDynamicProviders(dynamicProviders){const normalized2=dynamicProviders.map(p=>normalizeProvider(p));for(const rec of normalized2){const provide=rec.provide;this.tokens.add(provide);this.defs.set(provide,rec);if(!this.graph.has(provide)){this.graph.set(provide,new Set)}const deps=this.discoveryDeps(rec);for(const d of deps){if(this.tokens.has(d)){this.graph.get(provide).add(d)}}}for(const rec of normalized2){for(const d of this.discoveryDeps(rec))this.assertDependencyScope(rec.provide,rec,d)}const globalProviders=normalized2.filter(rec=>this.getProviderScope(rec)===ProviderScope11.GLOBAL);return Promise.all(globalProviders.map(async rec=>{await this.initiateOne(rec.provide,rec);await this.bootstrapBuilt(rec.provide)}))}getWithParents(token){if(this.instances.has(token)){return this.get(token)}const parent=this.parentProviders;if(!parent){return this.get(token)}return parent.getWithParents(token)}getActiveScope(){return this.getWithParents(Scope)}getActiveServer(){return this.getWithParents(FrontMcpServer)}cleanupSession(sessionKey){this.sessionStores.delete(sessionKey);const lock=this.sessionBuildLocks.get(sessionKey);if(lock){lock.resolve();this.sessionBuildLocks.delete(sessionKey)}}cleanupExpiredSessions(){const now=Date.now();const cutoff=now-_ProviderRegistry.SESSION_CACHE_TTL_MS;let cleaned=0;for(const[key,entry]of this.sessionStores){if(entry.lastAccess<cutoff){this.sessionStores.delete(key);const lock=this.sessionBuildLocks.get(key);if(lock){lock.resolve();this.sessionBuildLocks.delete(key)}cleaned++}}return cleaned}startSessionCleanup(){if(this.sessionCleanupInterval){return}this.sessionCleanupInterval=setInterval(()=>{const cleaned=this.cleanupExpiredSessions();if(cleaned>0){console.debug(`[ProviderRegistry] Cleaned up ${cleaned} expired sessions`)}},_ProviderRegistry.SESSION_CLEANUP_INTERVAL_MS);if(this.sessionCleanupInterval.unref){this.sessionCleanupInterval.unref()}}stopSessionCleanup(){if(this.sessionCleanupInterval){clearInterval(this.sessionCleanupInterval);this.sessionCleanupInterval=null}}dispose(){for(const child of[...this.childRegistries])child.dispose();this.parentProviders?.childRegistries.delete(this);this.stopSessionCleanup();this.sessionStores.clear();for(const lock of this.sessionBuildLocks.values()){lock.resolve()}this.sessionBuildLocks.clear()}getSessionCacheStats(){return{enabled:this.sessionCacheEnabled,size:this.sessionStores.size,maxSize:_ProviderRegistry.MAX_SESSION_CACHE_SIZE,ttlMs:_ProviderRegistry.SESSION_CACHE_TTL_MS}}isSessionCacheEnabled(){return this.sessionCacheEnabled}async buildViews(sessionKey,contextProviders,contextSource){validateSessionId(sessionKey);const global=this.getAllSingletons();const ownDefs=(contextSource&&this.defsBelow(contextSource))??new Map;const cached=this.providerStoreFor(sessionKey,contextProviders?.get(FRONTMCP_CONTEXT));let sessionProviders=cached.providers;if(contextSource&&ownDefs.size>0){let bySource=cached.bySource.get(contextSource);if(!bySource){bySource=new Map;cached.bySource.set(contextSource,bySource)}sessionProviders=bySource}const requestTokens=requestScopedTokens(contextProviders);const contextStore=new Map(sessionProviders);const sourceRegistry=contextSource instanceof _ProviderRegistry&&contextSource!==this?contextSource:void 0;for(const[token,instance]of contextProviders??[]){if(ownDefs.has(token)||sourceRegistry?.hidesFrom(token,this))continue;contextStore.set(token,instance)}for(const token of this.order){const rec=this.defs.get(token);if(!rec)continue;if(this.getProviderScope(rec)!==ProviderScope11.CONTEXT)continue;if(contextStore.has(token))continue;await this.buildIntoStoreWithViews(token,rec,contextStore,sessionKey,contextStore,global)}for(const[token,rec]of this.defs){if(this.order.has(token))continue;if(this.getProviderScope(rec)!==ProviderScope11.CONTEXT)continue;if(contextStore.has(token))continue;await this.buildIntoStoreWithViews(token,rec,contextStore,sessionKey,contextStore,global)}for(const[token,{registry,rec}]of ownDefs){if(registry===this||contextStore.has(token))continue;if(registry.getProviderScope(rec)!==ProviderScope11.CONTEXT)continue;await registry.buildIntoStoreWithViews(token,rec,contextStore,sessionKey,contextStore,registry.getAllSingletons())}for(const[token,instance]of contextStore){if(!sessionProviders.has(token)&&!this.dependsOnAny(token,requestTokens)){sessionProviders.set(token,instance)}}return{global,context:contextStore}}providerStoreFor(sessionKey,requestContext){if(!(requestContext instanceof FrontMcpContext)){return newProviderStore()}if(!this.sessionCacheEnabled||verifiedSessionOf2(requestContext)!==sessionKey){let stores=requestContext.get(REQUEST_PROVIDER_STORES);if(!stores){stores=new WeakMap;requestContext.set(REQUEST_PROVIDER_STORES,stores)}let store=stores.get(this);if(!store){store=newProviderStore();stores.set(this,store)}return store}let cached=this.sessionStores.get(sessionKey);if(!cached){cached=newProviderStore();this.sessionStores.set(sessionKey,cached)}else{cached.lastAccess=Date.now()}return cached}defsBelow(ancestor){if(this===ancestor)return new Map;const owned=this.parentProviders?.defsBelow(ancestor);if(!owned)return void 0;for(const[token,rec]of this.defs)owned.set(token,{registry:this,rec});return owned}dependsOnAny(token,targets,visited=new Set){if(targets.has(token))return true;if(visited.has(token))return false;visited.add(token);const found=this.lookupDefInHierarchy(token);if(!found)return false;return found.registry.discoveryDeps(found.rec).some(dep=>this.dependsOnAny(dep,targets,visited))}async buildIntoStoreWithViews(token,rec,store,scopeKey,contextStore,globalStore){if(store.has(token))return;try{switch(rec.kind){case ProviderKind4.VALUE:{store.set(token,rec.useValue);return}case ProviderKind4.FACTORY:{const deps=this.invocationTokens(token,rec);const args=[];for(const d of deps){args.push(await this.resolveFromViews(d,contextStore,globalStore,scopeKey))}const out=rec.useFactory(...args);const val=isPromise(out)?await this.withTimeout(out,this.asyncTimeoutMs,`${tokenName22(token)}.useFactory(...)`):out;store.set(token,val);return}case ProviderKind4.CLASS:case ProviderKind4.CLASS_TOKEN:{const depsTokens=this.invocationTokens(token,rec);const deps=[];for(const d of depsTokens){deps.push(await this.resolveFromViews(d,contextStore,globalStore,scopeKey))}const klass=rec.kind===ProviderKind4.CLASS?rec.useClass:rec.provide;if(hasAsyncWith(klass)){const out=klass.with(...deps);const val=isPromise(out)?await this.withTimeout(out,this.asyncTimeoutMs,`${klass.name}.with(...)`):out;store.set(token,val)}else{const instance=new klass(...deps);const init=instance?.init;if(typeof init==="function"){const ret=init.call(instance);if(isPromise(ret))await this.withTimeout(ret,this.asyncTimeoutMs,`${klass.name}.init()`)}store.set(token,instance)}return}}}catch(e){const msg=e?.message??e;console.error(`Failed constructing (context-scoped):`,msg);throw new ProviderConstructionError(tokenName22(token),e instanceof Error?e:msg,"context-scoped")}}async resolveFromViews(token,contextStore,globalStore,scopeKey){if(token===_ProviderRegistry)return this;if(contextStore.has(token))return contextStore.get(token);if(globalStore.has(token))return globalStore.get(token);if(this.instances.has(token))return this.instances.get(token);const rec=this.defs.get(token);if(rec){const scope=this.getProviderScope(rec);if(scope===ProviderScope11.GLOBAL){throw new ProviderNotInstantiatedError(tokenName22(token),"GLOBAL")}else{await this.buildIntoStoreWithViews(token,rec,contextStore,scopeKey,contextStore,globalStore);return contextStore.get(token)}}const up=this.lookupDefInHierarchy(token);if(up){const sc=up.registry.getProviderScope(up.rec);if(sc===ProviderScope11.GLOBAL){const v=up.registry.instances.get(token);if(v!==void 0)return v;throw new ProviderNotInstantiatedError(tokenName22(token),"GLOBAL","parent")}await up.registry.buildIntoStoreWithViews(token,up.rec,contextStore,scopeKey,contextStore,up.registry.getAllSingletons());return contextStore.get(token)}throw new ProviderDependencyError(`Cannot resolve dependency ${tokenName22(token)} from views`)}getScoped(token,views){if(views.context.has(token))return views.context.get(token);if(views.global.has(token))return views.global.get(token);if(this.instances.has(token))return this.instances.get(token);throw new ProviderNotAvailableError(tokenName22(token),"not found in views. Ensure it was built via buildViews()")}};REQUEST_PROVIDER_STORES=Symbol("frontmcp:request-provider-stores")}});import{depsOfClass as depsOfClass13}from"@frontmcp/di";function normalizeAppScope(appItem,metadata){const app=normalizeApp(appItem);const appMetadata=app.metadata;if(metadata.splitByApp===true&&appMetadata.standalone==="includeInParent"){throw new ScopeConfigurationError("standalone: includeInParent is not supported for splitByApp scope")}const scopeId=appMetadata.id??appMetadata.name;const token=Symbol(scopeId);return{kind:"SPLIT_BY_APP",provide:token,metadata:{...metadata,id:scopeId,apps:[appItem],auth:appMetadata.auth??metadata.auth,__sourceDir:appMetadata.__sourceDir??metadata.__sourceDir}}}function normalizeMultiAppScope(includedApps,metadata){return{kind:"MULTI_APP",provide:Scope,metadata:{...metadata,id:"root",apps:includedApps}}}function scopeDiscoveryDeps(rec){switch(rec.kind){case"MULTI_APP":return depsOfClass13(rec.provide,"discovery").slice(1);case"SPLIT_BY_APP":return[]}}var init_scope_utils=__esm({"libs/sdk/src/scope/scope.utils.ts"(){"use strict";init_app_utils();init_errors();init_scope_instance()}});import"reflect-metadata";import{tokenName as tokenName23}from"@frontmcp/di";var ScopeRegistry;var init_scope_registry=__esm({"libs/sdk/src/scope/scope.registry.ts"(){"use strict";init_app_utils();init_common();init_errors();init_front_mcp_tokens2();init_regsitry();init_scope_instance();init_scope_utils();ScopeRegistry=class extends RegistryAbstract{logger;constructor(globalProviders){const metadata=globalProviders.get(FrontMcpConfig);super("ScopeRegistry",globalProviders,metadata);this.logger=globalProviders.get(FrontMcpLogger)?.child("ScopeRegistry")}buildMap(metadata){const tokens=new Set;const defs=new Map;const graph=new Map;if(metadata.splitByApp){for(const raw of metadata.apps){const rec=normalizeAppScope(raw,metadata);const provide=rec.provide;tokens.add(provide);defs.set(provide,rec);graph.set(provide,new Set)}}else{const includeInParent=[];for(const raw of metadata.apps){const app=normalizeApp(raw);const appMetadata=app.metadata;if(appMetadata.standalone===false){includeInParent.push(raw);continue}if(appMetadata.standalone==="includeInParent"){includeInParent.push(raw)}const appScopeRec=normalizeAppScope(raw,metadata);const provide2=appScopeRec.provide;tokens.add(provide2);defs.set(provide2,appScopeRec);graph.set(provide2,new Set)}const rec=normalizeMultiAppScope(includeInParent,metadata);const provide=rec.provide;tokens.add(provide);defs.set(provide,rec);graph.set(provide,new Set)}return{tokens,defs,graph}}buildGraph(){for(const token of this.tokens){const rec=this.defs.get(token);const deps=scopeDiscoveryDeps(rec).slice(1);for(const d of deps){if(!this.providers.get(d)){throw new RegistryDependencyNotRegisteredError("Scope",tokenName23(token),tokenName23(d))}this.graph.get(token).add(d)}}}async initialize(){this.logger?.verbose(`ScopeRegistry: initializing ${this.tokens.size} scope(s)`);for(const token of this.tokens){const rec=this.defs.get(token);let scope;switch(rec.kind){case"SPLIT_BY_APP":scope=new Scope(rec,this.providers);break;case"MULTI_APP":scope=new rec.provide(rec,this.providers);break;default:throw new InvalidRegistryKindError("scope",String(rec.kind))}try{await scope.ready}finally{this.instances.set(token,scope)}this.logger?.verbose(`ScopeRegistry: initialized scope '${tokenName23(token)}'`)}this.logger?.verbose(`ScopeRegistry: initialization complete (${this.instances.size} scope(s))`)}getScopes(){return[...this.instances.values()]}getPrimaryScope(){const scopes=this.getScopes();const multiApp=scopes.find(scope=>scope.record.kind==="MULTI_APP");if(multiApp&&multiApp.apps.getApps().length>0)return multiApp;return scopes[0]}}}});var NoopFrontMcpServer;var init_noop_server=__esm({"libs/sdk/src/server/noop-server.ts"(){"use strict";init_common();NoopFrontMcpServer=class extends FrontMcpServer{registerMiddleware(_entryPath,_handler){}registerRoute(_method,_path2,_handler){}prepare(){}getHandler(){return void 0}async start(){}}}});var MetricsPathConflictError,MetricsTokenNotConfiguredError;var init_metrics_errors=__esm({"libs/sdk/src/metrics/metrics.errors.ts"(){"use strict";init_mcp_error();MetricsPathConflictError=class extends InternalMcpError{conflictingPath;constructor(conflictingPath){super(`metrics.path "${conflictingPath}" conflicts with an MCP transport route. Pick a non-MCP path (e.g. "/metrics", "/internal/metrics").`,"METRICS_PATH_CONFLICT");this.conflictingPath=conflictingPath}};MetricsTokenNotConfiguredError=class extends InternalMcpError{tokenEnv;constructor(tokenEnv){super(`metrics.auth is "token" but env var "${tokenEnv}" is not set. Set the env var or switch metrics.auth to "public" / { token: "..." }.`,"METRICS_TOKEN_NOT_CONFIGURED");this.tokenEnv=tokenEnv}}}});function loadObservability(){if(!observabilityRuntime){observabilityRuntime=requireOptionalModule("@frontmcp/observability",()=>__require("@frontmcp/observability"))}return observabilityRuntime}function createProcessStatsCollectorIfEnabled(config){const include=config.include;const processEnabled=!include||include.length===0||include.includes("process");if(!processEnabled)return void 0;const obs=loadObservability();return new obs.ProcessStatsCollector({options:config.process})}var PROMETHEUS_CONTENT_TYPE,observabilityRuntime,MCP_RESERVED_PATH_PREFIXES,COUNTER_CATEGORY_PREFIX,MetricsService;var init_metrics_service=__esm({"libs/sdk/src/metrics/metrics.service.ts"(){"use strict";init_optional_dependency_util();init_metrics_errors();PROMETHEUS_CONTENT_TYPE="text/plain; version=0.0.4; charset=utf-8";MCP_RESERVED_PATH_PREFIXES=["/mcp","/sse","/messages"];COUNTER_CATEGORY_PREFIX={process:["frontmcp_process_","frontmcp_nodejs_","frontmcp_event_loop_"],skills:["frontmcp_skills_"],tools:["frontmcp_tool_"],resources:["frontmcp_resource_"],http:["frontmcp_http_"],storage:["frontmcp_storage_"],auth:["frontmcp_auth_"],sessions:["frontmcp_session_"],events:["frontmcp_events_"]};MetricsService=class{config;processCollector;snapshotSource;resolvedToken;constructor(config,processCollector,options={}){this.config=config;this.processCollector=processCollector;this.snapshotSource=options.snapshotSource??(()=>loadObservability().getMetricSnapshot());const path4=config.path??"/metrics";for(const prefix of MCP_RESERVED_PATH_PREFIXES){if(path4===prefix||path4.startsWith(`${prefix}/`)){throw new MetricsPathConflictError(path4)}}if(config.auth==="token"){const envName=config.tokenEnv??"FRONTMCP_METRICS_TOKEN";const value=process.env[envName];if(!value){throw new MetricsTokenNotConfiguredError(envName)}this.resolvedToken=value}else if(typeof config.auth==="object"&&config.auth!==null&&"token"in config.auth){this.resolvedToken=config.auth.token}}getMetrics(){const format=this.config.format??"prometheus";const include=this.config.include;let counters=this.snapshotSource();let gauges=this.processCollector?.collect()??[];if(include&&include.length>0){const includeSet=new Set(include);const allowedPrefixes=include.flatMap(category=>COUNTER_CATEGORY_PREFIX[category]??[]);const matchesAllowed=name59=>allowedPrefixes.some(prefix=>name59.startsWith(prefix));counters=counters.filter(c=>matchesAllowed(c.name));if(!includeSet.has("process")){gauges=[]}else{gauges=gauges.filter(g=>matchesAllowed(g.name))}}const obs=loadObservability();if(format==="json"){return{contentType:"application/json",body:JSON.stringify(obs.renderJsonExposition(counters,gauges))}}return{contentType:PROMETHEUS_CONTENT_TYPE,body:obs.renderPrometheusExposition(counters,gauges)}}authorize(authorizationHeader){const auth=this.config.auth??"public";if(auth==="public")return 200;if(!authorizationHeader)return 401;const expected=this.resolvedToken;if(!expected)return 401;const match=/^Bearer\s+(.+)$/i.exec(authorizationHeader);if(!match)return 401;return match[1]===expected?200:403}}}});function readAuthorizationHeader(headers){if(!headers)return void 0;const raw=headers["authorization"]??headers["Authorization"];if(Array.isArray(raw))return raw[0];return typeof raw==="string"?raw:void 0}function metricsPath(config){return config.path??"/metrics"}function renderMetricsScrape(service,config,authorizationHeader){const status=service.authorize(authorizationHeader);if(status!==200){return{status,headers:{"Cache-Control":"no-store"},kind:"json",body:{error:status===401?"unauthorized":"forbidden",message:status===401?"Missing or malformed Authorization header":"Bearer token did not match the configured metrics token"}}}const result=service.getMetrics();const headers={"Cache-Control":"no-store","Content-Type":result.contentType};if((config.format??"prometheus")!=="json"){return{status:200,headers,kind:"text",body:result.body}}try{return{status:200,headers,kind:"json",body:JSON.parse(result.body)}}catch{return{status:500,headers,kind:"json",body:{error:"internal_error",message:"Failed to serialise metrics JSON"}}}}function registerMetricsRoutes(server,service,config){if(config.enabled!==true)return;server.registerRoute("GET",metricsPath(config),async(req,res)=>{const result=renderMetricsScrape(service,config,readAuthorizationHeader(req.headers));for(const[name59,value]of Object.entries(result.headers))res.setHeader?.(name59,value);if(result.kind==="json"){res.status(result.status).json(result.body);return}if(typeof res.send==="function"){res.status(result.status);res.send(result.body);return}res.status(500).json({error:"internal_error",message:'Server adapter does not support Prometheus text format. Use `format: "json"` or upgrade the adapter.'})})}var init_metrics_routes=__esm({"libs/sdk/src/metrics/metrics.routes.ts"(){"use strict"}});var metrics_exports={};__export(metrics_exports,{MetricsPathConflictError:()=>MetricsPathConflictError,MetricsService:()=>MetricsService,MetricsTokenNotConfiguredError:()=>MetricsTokenNotConfiguredError,createProcessStatsCollectorIfEnabled:()=>createProcessStatsCollectorIfEnabled,metricsPath:()=>metricsPath,registerMetricsRoutes:()=>registerMetricsRoutes,renderMetricsScrape:()=>renderMetricsScrape});var init_metrics2=__esm({"libs/sdk/src/metrics/index.ts"(){"use strict";init_metrics_service();init_metrics_routes();init_metrics_errors()}});import{getEnv as getEnv21}from"@frontmcp/utils";function readCorsFromEnv(){const rawOrigins=getEnv21("FRONTMCP_CORS_ORIGINS");if(!rawOrigins)return void 0;let origins;try{origins=JSON.parse(rawOrigins)}catch{origins=rawOrigins.split(",")}const list=(Array.isArray(origins)?origins:[origins]).filter(origin=>typeof origin==="string").map(origin=>origin.trim()).filter(origin=>origin.length>0);if(list.length===0)return void 0;const cors2={origin:list.includes("*")?true:list};const credentials=getEnv21("FRONTMCP_CORS_CREDENTIALS");if(credentials!==void 0)cors2.credentials=credentials==="true"||credentials==="1";const maxAge=Number(getEnv21("FRONTMCP_CORS_MAX_AGE"));if(Number.isFinite(maxAge)&&maxAge>0)cors2.maxAge=maxAge;return cors2}function resolveHttpCors(cors2){return cors2!==void 0?cors2:readCorsFromEnv()}var init_cors_env=__esm({"libs/sdk/src/server/middleware/cors-env.ts"(){"use strict"}});function auditSecurityDefaults(config,isProduction11){const findings=[];if(!isProduction11&&config.deploymentMode!=="distributed"){return findings}const strict=config.security?.strict===true;const cors2=resolveHttpCors(config.cors);const corsOrigin=cors2===false?void 0:cors2?.origin;if(corsOrigin===void 0||corsOrigin===false){findings.push({level:"info",code:"CORS_DISABLED",message:"No CORS headers are sent, so a browser will not let a page on another origin read the response. CORS is not server-side access control: on a routable bind, cross-origin requests still reach the server."})}else if(corsOrigin===true){findings.push({level:"warn",code:"CORS_ORIGIN_TRUE",message:"CORS origin=true allows all origins to make cross-origin requests.",recommendation:"Set cors.origin to specific allowed origins."})}else{findings.push({level:"info",code:"CORS_CONFIGURED",message:"CORS is explicitly configured."})}const bindAddress=config.resolvedBindAddress??"127.0.0.1";if(bindAddress==="0.0.0.0"||bindAddress==="::"){if(config.deploymentMode!=="distributed"){findings.push({level:"warn",code:"BIND_ALL_INTERFACES",message:`Server bound to ${bindAddress} \u2014 accessible from all network interfaces.`,recommendation:"Set security.bindAddress to 'loopback' or '127.0.0.1' for local-only access, or configure a reverse proxy. Distributed deployments require 'all' (0.0.0.0)."})}else{findings.push({level:"info",code:"BIND_ALL_INTERFACES_DISTRIBUTED",message:`Server bound to ${bindAddress} (expected for distributed deployment).`})}}else{findings.push({level:"info",code:"BIND_RESTRICTED",message:`Server bound to ${bindAddress}.`})}findings.push(auditDnsRebinding(config,bindAddress));if(config.security?.strict){findings.push({level:"info",code:"STRICT_MODE_ENABLED",message:config.deploymentMode==="distributed"?"Strict security mode is enabled: DNS rebinding protection. Binding is unchanged for a distributed deployment \u2014 it still listens on all interfaces so peers can reach it.":"Strict security mode is enabled: loopback binding and DNS rebinding protection."})}else{findings.push({level:"info",code:"STRICT_MODE_HINT",message:"To enable strict security defaults, set security.strict = true in HttpOptions."})}return findings}function auditDnsRebinding(config,bindAddress){const protection=config.security?.dnsRebindingProtection;if(protection?.enabled===false){return{level:"warn",code:"DNS_REBINDING_UNPROTECTED",message:"DNS rebinding protection is disabled (security.dnsRebindingProtection.enabled is false).",recommendation:"Remove `enabled: false` to turn DNS rebinding protection back on (an allowedHosts list is ignored while it is set). On a routable bind, also set security.dnsRebindingProtection.allowedHosts (or FRONTMCP_ALLOWED_HOSTS) to your public hostname(s)."}}const explicitHosts=protection?.allowedHosts??allowedHostsFromEnv();if(explicitHosts?.length||protection?.allowedOrigins?.length){return{level:"info",code:"DNS_REBINDING_PROTECTED",message:"DNS rebinding protection is enabled: Host/Origin headers are checked against the configured allow-list."}}if(config.socketPath){return{level:"info",code:"DNS_REBINDING_NOT_APPLICABLE",message:"Server listens on a Unix socket: there is no TCP Host to check; the socket permissions are the boundary."}}if(!isRoutableBind(bindAddress)){return{level:"info",code:"DNS_REBINDING_PROTECTED",message:corsAllowedOrigins(resolveHttpCors(config.cors))?`DNS rebinding protection is enabled: Host and Origin headers are checked against the loopback names for ${bindAddress}. A request with no Origin header is allowed.`:`DNS rebinding protection is enabled: Host headers are checked against the loopback names for ${bindAddress}. Origin is not checked: CORS admits every origin.`}}return{level:"info",code:"DNS_REBINDING_NOT_ENFORCED",message:`DNS rebinding protection is on, but no Host allow-list is enforced: the server binds ${bindAddress} and no allowed hosts are configured.`,recommendation:"Set security.dnsRebindingProtection.allowedHosts (or FRONTMCP_ALLOWED_HOSTS) to your public hostname(s)."}}function logSecurityFindings(findings,logger){if(findings.length===0)return;for(const finding of findings){const prefix=`[Security] ${finding.code}:`;const message=finding.recommendation?`${prefix} ${finding.message} ${finding.recommendation}`:`${prefix} ${finding.message}`;if(finding.level==="warn"){logger.warn(message)}else{logger.info(message)}}}function toBindAddress(value){if(value==="loopback")return"127.0.0.1";if(value==="all")return"0.0.0.0";return value}function resolveBindAddress(security,deploymentMode){if(security?.bindAddress){return toBindAddress(security.bindAddress)}const envBindAddress=process.env["FRONTMCP_BIND_ADDRESS"]?.trim();if(envBindAddress){return toBindAddress(envBindAddress)}if(security?.strict){return deploymentMode==="distributed"?"0.0.0.0":"127.0.0.1"}if(deploymentMode==="distributed")return"0.0.0.0";return"127.0.0.1"}var init_security_audit=__esm({"libs/sdk/src/server/security/security-audit.ts"(){"use strict";init_cors_env();init_resolve_allowed_hosts()}});import{getEnv as getEnv22,getEnvFlag as getEnvFlag2}from"@frontmcp/utils";function readCspFromEnv(){if(!getEnvFlag2("FRONTMCP_CSP_ENABLED"))return void 0;const rawDirectives=getEnv22("FRONTMCP_CSP_DIRECTIVES")??"";const directives={};for(const part of rawDirectives.split(";")){const trimmed=part.trim();if(!trimmed)continue;const spaceIdx=trimmed.indexOf(" ");if(spaceIdx>0){directives[trimmed.slice(0,spaceIdx)]=trimmed.slice(spaceIdx+1)}else{directives[trimmed]=""}}return{enabled:true,directives,reportUri:getEnv22("FRONTMCP_CSP_REPORT_URI"),reportOnly:getEnvFlag2("FRONTMCP_CSP_REPORT_ONLY")}}function buildCspHeaderValue(options){const parts=[];for(const[directive,value]of Object.entries(options.directives)){parts.push(value?`${directive} ${value}`:directive)}if(options.reportUri){parts.push(`report-uri ${options.reportUri}`)}return parts.join("; ")}function getCspHeaderName(reportOnly){return reportOnly?"Content-Security-Policy-Report-Only":"Content-Security-Policy"}function readSecurityHeadersFromEnv(){return{hsts:readHeaderEnv("FRONTMCP_HSTS"),contentTypeOptions:readHeaderEnv("FRONTMCP_CONTENT_TYPE_OPTIONS","nosniff"),frameOptions:readHeaderEnv("FRONTMCP_FRAME_OPTIONS","DENY"),custom:readCustomHeadersFromEnv()}}function readHeaderEnv(name59,fallback){const value=getEnv22(name59);if(value===void 0||value==="")return fallback;return["off","false","none"].includes(value.trim().toLowerCase())?void 0:value}function readCustomHeadersFromEnv(){const raw=getEnv22("FRONTMCP_HEADERS_CUSTOM");if(!raw)return void 0;try{const parsed=JSON.parse(raw);if(typeof parsed!=="object"||parsed===null||Array.isArray(parsed))return void 0;return Object.fromEntries(Object.entries(parsed).filter(entry=>typeof entry[1]==="string"))}catch{return void 0}}function applySecurityHeaders(res,headers,csp){if(headers.hsts){res.setHeader("Strict-Transport-Security",headers.hsts)}if(headers.contentTypeOptions){res.setHeader("X-Content-Type-Options",headers.contentTypeOptions)}if(headers.frameOptions){res.setHeader("X-Frame-Options",headers.frameOptions)}if(headers.custom){for(const[name59,value]of Object.entries(headers.custom)){res.setHeader(name59,value)}}if(csp?.enabled){const headerName=getCspHeaderName(csp.reportOnly);const headerValue=buildCspHeaderValue(csp);if(headerValue){res.setHeader(headerName,headerValue)}}}function resolveSecurityHeaders(options={}){const env=readSecurityHeadersFromEnv();const pick=(explicit,fromEnv)=>explicit===false?void 0:explicit??fromEnv;const resolved={hsts:pick(options.hsts,env.hsts),contentTypeOptions:pick(options.contentTypeOptions,env.contentTypeOptions),frameOptions:pick(options.frameOptions,env.frameOptions),custom:{...env.custom,...options.custom}};let csp;if(options.csp?.enabled===false){csp=void 0}else if(options.csp?.enabled===true){const directives={};for(const[name59,value]of Object.entries(options.csp.directives??{})){directives[name59]=Array.isArray(value)?value.join(" "):value}csp={enabled:true,directives,reportUri:options.csp.reportUri,reportOnly:options.csp.reportOnly??false}}else{csp=readCspFromEnv()}const headers={};applySecurityHeaders({setHeader:(name59,value)=>void(headers[name59]=value)},resolved,csp);return headers}var init_csp_middleware=__esm({"libs/sdk/src/server/middleware/csp.middleware.ts"(){"use strict"}});function createHostValidationMiddleware(options){if(!options.enabled){return(_req,_res,next)=>next()}const compiled=compileHostValidation({allowedHosts:options.allowedHosts,allowedOrigins:options.allowedOrigins});return(req,res,next)=>{const rejection=validateHostHeaders({host:req.headers?.["host"],forwardedHost:req.headers?.["x-forwarded-host"],origin:req.headers?.["origin"]},compiled);if(rejection){res.status(rejection.status).json({error:rejection.error,message:rejection.message});return}next()}}var init_host_validation_middleware=__esm({"libs/sdk/src/server/middleware/host-validation.middleware.ts"(){"use strict";init_host_validation()}});import cluster from"node:cluster";import*as net from"node:net";import*as path from"node:path";import{chmod,lstat as lstat3,realpath as realpath4,stat as stat5,unlink}from"@frontmcp/utils";function hasSocketFileMode(){return process.platform!=="win32"}function errorCode(error){return error?.code}async function assertSafeSocketDirectory(socketPath){const socketDirectory=path.dirname(path.resolve(socketPath));const realSocketDirectory=await realpath4(socketDirectory);await assertNoOtherUserCanReplace2(socketDirectory);if(realSocketDirectory!==socketDirectory)await assertNoOtherUserCanReplace2(realSocketDirectory);if(canBindOwnerOnly())return;const{mode}=await stat5(socketDirectory);if(mode&GROUP_OR_OTHER_ACCESS2){throw new SocketPermissionError(socketPath,`the umask cannot be set here (a worker thread, or a cluster worker whose primary binds the socket), so its directory ${socketDirectory} must be owner-only (0700), not 0${(mode&511).toString(8)}`)}}async function assertNoOtherUserCanReplace2(start){const replaceable=await findReplaceableDirectory(start);if(replaceable)throw new UnsafeSocketDirectoryError(replaceable.directory,replaceable.mode,replaceable.ownerUid)}function canBindOwnerOnly(){if(cluster.isWorker)return false;const previousUmask=setUmask(OWNER_ONLY_UMASK);if(previousUmask===void 0)return false;setUmask(previousUmask);return true}function probe(socketPath){return new Promise((resolve4,reject)=>{const socket=net.connect(socketPath);socket.once("connect",()=>{socket.destroy();resolve4("live")});socket.once("error",error=>{const code=errorCode(error);if(code==="ECONNREFUSED")resolve4("stale");else if(code==="ENOENT")resolve4("gone");else reject(new SocketPathConflictError(socketPath,`connecting to it failed (${code??error.message})`))})})}async function clearStaleSocket(socketPath){let stats;try{stats=await lstat3(socketPath)}catch(error){if(errorCode(error)==="ENOENT")return;throw error}if(!stats.isSocket())throw new SocketPathConflictError(socketPath,"it is not a socket");if(stats.uid!==process.getuid?.()){throw new SocketPathConflictError(socketPath,`it belongs to another user (uid ${stats.uid})`)}const state=await probe(socketPath);if(state==="live")throw new SocketInUseError(socketPath);if(state==="stale")await unlink(socketPath)}function listenOwnerOnly(server,socketPath,onListening){const previousUmask=setUmask(OWNER_ONLY_UMASK);try{server.listen(socketPath,onListening)}finally{if(previousUmask!==void 0)setUmask(previousUmask)}}function setUmask(mask){try{return process.umask(mask)}catch{return void 0}}async function enforceOwnerOnly(socketPath){try{await chmod(socketPath,OWNER_ONLY_MODE)}catch(error){throw new SocketPermissionError(socketPath,`chmod failed (${errorCode(error)??String(error)})`)}const mode=(await lstat3(socketPath)).mode&511;if(mode!==OWNER_ONLY_MODE)throw new SocketPermissionError(socketPath,`its mode is 0${mode.toString(8)}`)}var OWNER_ONLY_MODE,OWNER_ONLY_UMASK,GROUP_OR_OTHER_ACCESS2;var init_unix_socket_guard=__esm({"libs/sdk/src/server/security/unix-socket-guard.ts"(){"use strict";init_transport_errors();init_replaceable_directory();OWNER_ONLY_MODE=384;OWNER_ONLY_UMASK=63;GROUP_OR_OTHER_ACCESS2=63}});var HostServerAdapter;var init_base_host_adapter=__esm({"libs/sdk/src/server/adapters/base.host.adapter.ts"(){"use strict";init_common();HostServerAdapter=class extends FrontMcpServer{}}});import express from"express";function utf8JsonParser(limit){const readBody=express.raw({limit,type:isUtf8Json});return(req,res,next)=>{const unparsedBody=req.body;readBody(req,res,readError=>{if(readError||req.body===unparsedBody||!Buffer.isBuffer(req.body)){next(readError);return}const text=decodeUtf8(req.body);keepBodyBytes(req,res,req.body);try{req.body=parseStrictJson(text)}catch(error){req.body=unparsedBody;next(Object.assign(error,parseFailure(text)));return}next()})}}function keepBodyBytes(req,_res,bytes){req.bodyBytes=bytes}function decodeUtf8(body){const text=body.toString("utf8");return text.charCodeAt(0)===65279?text.slice(1):text}function parseStrictJson(text){if(text.length===0)return{};const first3=FIRST_NON_WHITESPACE.exec(text)?.[1];if(first3!=="{"&&first3!=="[")throw strictSyntaxError(text,first3);return JSON.parse(text)}function strictSyntaxError(text,first3){const index=first3===void 0?-1:text.indexOf(first3);const error=jsonParseError(index===-1?"":text.slice(0,index).padEnd(text.length,"#"));const message=error.message.replace(/#+/g,mask=>text.substring(index,index+mask.length));error.stack=error.stack?.replace(error.message,message);error.message=message;return error}function jsonParseError(invalidJson){try{JSON.parse(invalidJson)}catch(error){return error}return new SyntaxError(`Expected invalid JSON: ${invalidJson}`)}var UTF8_JSON_TYPE,FIRST_NON_WHITESPACE,isUtf8Json,parseFailure;var init_utf8_json_parser=__esm({"libs/sdk/src/server/adapters/utf8-json.parser.ts"(){"use strict";UTF8_JSON_TYPE=/^application\/json(?:; ?charset=utf-8)?$/i;FIRST_NON_WHITESPACE=/^[ \t\n\r]*([^ \t\n\r])/;isUtf8Json=req=>UTF8_JSON_TYPE.test(req.headers["content-type"]??"");parseFailure=body=>({expose:true,statusCode:400,status:400,body,type:"entity.parse.failed"})}});import*as http from"node:http";import cors from"cors";import express2 from"express";var SERVER_DRAIN_MS,DEFAULT_EXPRESS_BODY_LIMIT,ExpressHostAdapter;var init_express_host_adapter=__esm({"libs/sdk/src/server/adapters/express.host.adapter.ts"(){"use strict";init_mcp_error();init_ha_headers();init_csp_middleware();init_host_validation_middleware();init_resolve_allowed_hosts();init_unix_socket_guard();init_base_host_adapter();init_utf8_json_parser();SERVER_DRAIN_MS=5e3;DEFAULT_EXPRESS_BODY_LIMIT="4mb";ExpressHostAdapter=class extends HostServerAdapter{app=express2();router=express2.Router();prepared=false;httpServer;hostValidation;deriveHostValidation;constructor(options){super();this.app.disable("x-powered-by");const securityHeaders=resolveSecurityHeaders(options?.securityHeaders);this.app.use((_req,res,next)=>{for(const[name59,value]of Object.entries(securityHeaders))res.setHeader(name59,value);applyMachineIdHeader(res);next()});const corsOptions=options?.cors;const corsEnabled=corsOptions?.origin!==void 0&&corsOptions.origin!==false;if(corsEnabled){const configuredCors=cors({origin:corsOptions.origin,credentials:corsOptions.credentials??false,maxAge:corsOptions.maxAge??300});const publicCorsPaths=new Set(options?.publicCorsPaths);this.app.use((req,res,next)=>publicCorsPaths.has(req.path)?next():configuredCors(req,res,next))}this.installHostValidation(options);const jsonLimit=options?.bodyLimit??DEFAULT_EXPRESS_BODY_LIMIT;const formLimit=options?.urlencodedLimit??jsonLimit;const headerContains=(req,needle)=>(req.headers["content-type"]??"").toLowerCase().includes(needle);const isUrlencoded=req=>headerContains(req,"application/x-www-form-urlencoded");const isJson=req=>headerContains(req,"application/json")&&!isUrlencoded(req);this.app.use(express2.urlencoded({extended:true,limit:formLimit,type:isUrlencoded,verify:keepBodyBytes}));this.app.use(utf8JsonParser(jsonLimit));this.app.use(express2.json({limit:jsonLimit,type:isJson,verify:keepBodyBytes}));this.app.use((err,_req,res,next)=>{const e=err;if(e?.type==="entity.too.large"){const payloadError=new PayloadTooLargeError(e.limit,e.length);res.status(payloadError.statusCode).json({jsonrpc:"2.0",id:null,error:payloadError.toJsonRpcError()});return}next(err)});this.app.use((req,res,next)=>{if(corsEnabled){res.setHeader("Access-Control-Expose-Headers","WWW-Authenticate, Mcp-Session-Id")}res.setHeader("Cache-Control","no-cache, no-transform");res.setHeader("Content-Type","application/json; charset=utf-8");next()})}installHostValidation(options){const protection=options?.security?.dnsRebindingProtection;if(protection?.enabled===false)return;const allowedOrigins=protection?.allowedOrigins;const explicitHosts=protection?.allowedHosts??allowedHostsFromEnv();if(explicitHosts?.length){this.hostValidation=createHostValidationMiddleware({enabled:true,allowedHosts:explicitHosts,allowedOrigins})}else{if(allowedOrigins!==void 0){this.hostValidation=createHostValidationMiddleware({enabled:true,allowedOrigins})}this.deriveHostValidation=(portOrSocketPath,bindAddress)=>{if(typeof portOrSocketPath==="string")return void 0;const derivation={bindAddress:bindAddress??"127.0.0.1",port:portOrSocketPath,issuer:options?.listen?.issuer};if(!shouldEnforceDerivedHosts(derivation)){console.warn(`[frontmcp] DNS-rebinding protection is not enforcing a Host allow-list: the server binds a routable address (${derivation.bindAddress}) and no allowed hosts are configured. Set security.dnsRebindingProtection.allowedHosts (or FRONTMCP_ALLOWED_HOSTS) to your public hostname(s).`);return void 0}const allowedHosts=deriveAllowedHosts(derivation);if(!allowedHosts.length)return void 0;const corsOrigins=corsAllowedOrigins(options?.cors);const derivedOrigins=isLoopbackAddress(derivation.bindAddress)&&corsOrigins?deriveAllowedOrigins({port:derivation.port,issuer:derivation.issuer,extraOrigins:corsOrigins}):void 0;return createHostValidationMiddleware({enabled:true,allowedHosts,allowedOrigins:allowedOrigins??derivedOrigins})}}this.app.use(((req,res,next)=>{const validate=this.hostValidation;if(!validate)return next();return validate(req,res,next)}))}enableDerivedHostValidation(portOrSocketPath,bindAddress){if(!this.deriveHostValidation)return;this.hostValidation=this.deriveHostValidation(portOrSocketPath,bindAddress)??this.hostValidation;this.deriveHostValidation=void 0}registerRoute(method,path4,handler){this.router[method.toLowerCase()](path4,this.enhancedHandler(handler))}registerMiddleware(entryPath,handler){this.router.use(entryPath,handler)}enhancedHandler(handler){return(req,res,next)=>{const request2=req;const response=res;return handler(request2,response,next)}}prepare(){if(this.prepared)return;this.prepared=true;this.app.use("/",this.router)}getHandler(){this.prepare();return this.app}async start(portOrSocketPath,bindAddress){this.prepare();const server=http.createServer(this.app);this.httpServer=server;server.requestTimeout=0;server.headersTimeout=0;server.keepAliveTimeout=75e3;if(typeof portOrSocketPath==="string"){const ownerOnly=hasSocketFileMode();if(ownerOnly){await assertSafeSocketDirectory(portOrSocketPath);await clearStaleSocket(portOrSocketPath)}this.enableDerivedHostValidation(portOrSocketPath);await new Promise((resolve4,reject)=>{server.on("error",reject);if(ownerOnly)listenOwnerOnly(server,portOrSocketPath,resolve4);else server.listen(portOrSocketPath,resolve4)});if(ownerOnly){try{await enforceOwnerOnly(portOrSocketPath)}catch(error){await this.stop(0);throw error}}console.log(`MCP HTTP (Express) on unix://${portOrSocketPath}`)}else{const host=bindAddress??"127.0.0.1";await new Promise((resolve4,reject)=>{server.on("error",reject);server.listen(portOrSocketPath,host,()=>{const bound=server.address();const boundPort=typeof bound==="object"&&bound?bound.port:portOrSocketPath;const boundAddress=typeof bound==="object"&&bound?bound.address:host;this.enableDerivedHostValidation(boundPort,boundAddress);console.log(`MCP HTTP (Express) on ${host}:${boundPort}`);resolve4()})})}}async stop(drainMs=SERVER_DRAIN_MS){const server=this.httpServer;if(!server)return;this.httpServer=void 0;const closed=new Promise(resolve4=>server.close(()=>resolve4()));server.closeIdleConnections();const forceClose=setTimeout(()=>server.closeAllConnections(),drainMs);try{await closed}finally{clearTimeout(forceClose)}}}}});var node_express_host_exports={};__export(node_express_host_exports,{DEFAULT_EXPRESS_BODY_LIMIT:()=>DEFAULT_EXPRESS_BODY_LIMIT,ExpressHostAdapter:()=>ExpressHostAdapter});var init_node_express_host=__esm({"libs/sdk/src/server/adapters/polyfills/node-express-host.ts"(){"use strict";init_express_host_adapter()}});var server_instance_exports={};__export(server_instance_exports,{FrontMcpServerInstance:()=>FrontMcpServerInstance});import{getRuntimeContext as getRuntimeContext30,isProduction as isProduction9}from"@frontmcp/utils";var DEFAULT_CORS,FrontMcpServerInstance;var init_server_instance=__esm({"libs/sdk/src/server/server.instance.ts"(){"use strict";init_common();init_path_utils();init_health2();init_mcp_registry_utils();init_metrics2();init_cors_env();init_security_audit();DEFAULT_CORS=void 0;FrontMcpServerInstance=class extends FrontMcpServer{config;host;healthRouteRegistered=false;_healthService;_healthConfig;metricsRouteRegistered=false;_metricsService;_metricsConfig;constructor(httpConfig){super();this.config=httpConfig;this.setupDefaults()}setupDefaults(){if(typeof this.config.hostFactory==="function"){const{hostFactory,...config}=this.config;this.host=this.config.hostFactory(config)}else if(this.config.hostFactory!==void 0){this.host=this.config.hostFactory}else{const cors2=resolveHttpCors(this.config.cors);const corsConfig=cors2===false?void 0:cors2??DEFAULT_CORS;const{ExpressHostAdapter:ExpressHostAdapter2}=(init_node_express_host(),__toCommonJS(node_express_host_exports));this.host=new ExpressHostAdapter2({...corsConfig?{cors:corsConfig}:{},publicCorsPaths:[serverCardPath({entryPath:resolveEntryPath(this.config.entryPath),routeBase:""})],...this.config.security?{security:this.config.security}:{},...this.config.securityHeaders?{securityHeaders:this.config.securityHeaders}:{},...this.config.bodyLimit!==void 0?{bodyLimit:this.config.bodyLimit}:{},...this.config.urlencodedLimit!==void 0?{urlencodedLimit:this.config.urlencodedLimit}:{}})}}registerMiddleware(entryPath,handler){return this.host.registerMiddleware(entryPath,handler)}registerRoute(method,path4,handler){return this.host.registerRoute(method,path4,handler)}setHealthService(healthService,healthConfig){this._healthService=healthService;this._healthConfig=healthConfig}setHealthConfig(healthConfig){this._healthConfig=healthConfig}setMetricsService(metricsService,metricsConfig){this._metricsService=metricsService;this._metricsConfig=metricsConfig}setMetricsConfig(metricsConfig){this._metricsConfig=metricsConfig}prepare(){if(!this.healthRouteRegistered){this.healthRouteRegistered=true;if(this._healthService&&this._healthConfig){registerHealthRoutes(this,this._healthService,this._healthConfig)}else if(this._healthConfig?.enabled===false){}else{this.registerRoute("GET","/health",async(req,res)=>{res.status(200).json({status:"ok"})})}}if(!this.metricsRouteRegistered){this.metricsRouteRegistered=true;if(this._metricsService&&this._metricsConfig?.enabled===true){registerMetricsRoutes(this,this._metricsService,this._metricsConfig)}}this.host.prepare()}getHandler(){return this.host.getHandler()}async start(){this.prepare();const deploymentMode=getRuntimeContext30().deployment;const bindAddress=resolveBindAddress(this.config.security,deploymentMode);const findings=auditSecurityDefaults({cors:this.config.cors,security:this.config.security,resolvedBindAddress:bindAddress,socketPath:this.config.socketPath,deploymentMode},isProduction9());logSecurityFindings(findings,console);await this.host.start(this.config.socketPath??this.config.port,bindAddress)}async stop(){await this.host.stop()}}}});import{ProviderScope as ProviderScope12}from"@frontmcp/di";function createMcpGlobalProviders(metadata){const isCli=!!metadata["__cliMode"];const isNoServe=metadata.serve===false;const serverProvider=isCli||isNoServe?noopServer:frontMcpServer;return[frontMcpConfig.with(metadata),serverProvider,FrontMcpContextStorage]}var frontMcpConfig,defaultHttpOptions,frontMcpServer,noopServer;var init_front_mcp_providers=__esm({"libs/sdk/src/front-mcp/front-mcp.providers.ts"(){"use strict";init_common();init_context();init_noop_server();init_front_mcp_tokens2();frontMcpConfig={with:metadata=>({name:"frontmcp:config",provide:FrontMcpConfig,scope:ProviderScope12.GLOBAL,useValue:metadata})};defaultHttpOptions=()=>({port:defaultHttpPort(),entryPath:"/mcp"});frontMcpServer=AsyncProvider({name:"frontmcp:server",scope:ProviderScope12.GLOBAL,provide:FrontMcpServer,inject:()=>[FrontMcpConfig],useFactory:async config=>{const{FrontMcpServerInstance:FrontMcpServerInstance2}=await Promise.resolve().then(()=>(init_server_instance(),server_instance_exports));return new FrontMcpServerInstance2(config.http??defaultHttpOptions())}});noopServer={name:"frontmcp:server:noop",provide:FrontMcpServer,scope:ProviderScope12.GLOBAL,useValue:new NoopFrontMcpServer}}});import{isSessionSecretConfigured,SessionSecretRequiredError as SessionSecretRequiredError2}from"@frontmcp/auth";import{isProduction as isProduction10}from"@frontmcp/utils";function checkSessionSecret(config,entryFallback){if(!isProduction10()||isSessionSecretConfigured())return false;if((config.transport?.defaultProtocolVersion??entryFallback)==="legacy"){throw new SessionSecretRequiredError2("the session ids of MCP clients before 2026-07-28: set MCP_SESSION_SECRET (openssl rand -hex 32), or, if every client uses MCP 2026-07-28, set transport.defaultProtocolVersion to '2026-07-28'")}return true}var MISSING_SESSION_SECRET_WARNING,missingSessionSecretProbe;var init_session_secret_check=__esm({"libs/sdk/src/front-mcp/session-secret.check.ts"(){"use strict";MISSING_SESSION_SECRET_WARNING="MCP_SESSION_SECRET is not set: clients before MCP 2026-07-28 get 500 SESSION_SECRET_REQUIRED on initialize, while clients on MCP 2026-07-28 are served. Set MCP_SESSION_SECRET (openssl rand -hex 32).";missingSessionSecretProbe={name:"session-secret",check:async()=>({status:"degraded",error:MISSING_SESSION_SECRET_WARNING})}}});import{watchParent}from"@frontmcp/utils";function exitOnShutdownSignals(shutdown,options={}){const target=options.target??process;const deadlineMs=options.deadlineMs??DEFAULT_SHUTDOWN_DEADLINE_MS;let shuttingDown=false;let watcher;const begin=trigger=>{if(shuttingDown)return;shuttingDown=true;watcher?.close();const deadline=setTimeout(()=>target.exit(1),deadlineMs);shutdown(trigger).then(()=>{clearTimeout(deadline);target.exit(0)},error=>{clearTimeout(deadline);options.logger?.error("Graceful shutdown failed",error);target.exit(1)})};const onSignal=()=>begin("signal");for(const signal of SHUTDOWN_SIGNALS)target.on(signal,onSignal);if(options.whenOrphaned){watcher=watchParent({stdin:options.whenOrphaned.stdin,onGone:reason=>{options.logger?.info?.(ORPHANED_MESSAGES[reason]);begin(reason)}})}return()=>{watcher?.close();for(const signal of SHUTDOWN_SIGNALS)target.removeListener(signal,onSignal)}}var SHUTDOWN_SIGNALS,ORPHANED_MESSAGES,DEFAULT_SHUTDOWN_DEADLINE_MS,STDIO_SHUTDOWN_DEADLINE_MS,STDIO_DRAIN_MS;var init_shutdown_signals=__esm({"libs/sdk/src/front-mcp/shutdown-signals.ts"(){"use strict";SHUTDOWN_SIGNALS=["SIGTERM","SIGINT"];ORPHANED_MESSAGES={"parent-exited":"The parent process exited; shutting down","stdin-ended":"stdin ended; shutting down"};DEFAULT_SHUTDOWN_DEADLINE_MS=1e4;STDIO_SHUTDOWN_DEADLINE_MS=5e3;STDIO_DRAIN_MS=2e3}});function redirectConsoleToStderr(){const{Console}=__require("node:console");const stderrConsole=new Console({stdout:process.stderr,stderr:process.stderr});console.log=stderrConsole.log.bind(stderrConsole);console.info=stderrConsole.info.bind(stderrConsole);console.debug=stderrConsole.debug.bind(stderrConsole);console.dir=stderrConsole.dir.bind(stderrConsole);console.table=stderrConsole.table.bind(stderrConsole);console.time=stderrConsole.time.bind(stderrConsole);console.timeLog=stderrConsole.timeLog.bind(stderrConsole);console.group=stderrConsole.group.bind(stderrConsole);console.groupEnd=stderrConsole.groupEnd.bind(stderrConsole);console.count=stderrConsole.count.bind(stderrConsole)}var init_stdio_console=__esm({"libs/sdk/src/front-mcp/stdio-console.ts"(){"use strict"}});var instance_file_logger_exports={};__export(instance_file_logger_exports,{FileLogTransportInstance:()=>FileLogTransportInstance});import{escapeControlCharacters as escapeControlCharacters6}from"@frontmcp/utils";function getFs(){return _fs??=__require("fs")}function getOs(){return _os??=__require("os")}function getPath(){return _path??=__require("path")}function stripAnsi(str){return str.split(ESC).map(s=>s.replace(/\[[0-9;]*m/,"")).join("")}var _fs,_os,_path,LOG_LEVEL_LABELS,ESC,DEFAULT_LOGS_MAX,FileLogTransportInstance;var init_instance_file_logger=__esm({"libs/sdk/src/logger/instances/instance.file-logger.ts"(){"use strict";init_common();LOG_LEVEL_LABELS={[100]:"OFF",[0]:"DEBUG",[1]:"VERBOSE",[2]:"INFO",[3]:"WARN",[4]:"ERROR"};ESC=String.fromCharCode(27);DEFAULT_LOGS_MAX=25;FileLogTransportInstance=class extends LogTransportInterface{fd;logDir;appName;constructor(){super();const rawAppName=process.env["FRONTMCP_APP_NAME"]||"frontmcp";const sanitized=rawAppName.replace(/[^a-zA-Z0-9._-]/g,"_");this.appName=sanitized.length>0?sanitized:"frontmcp";this.logDir=process.env["FRONTMCP_LOG_DIR"]||getPath().join(process.env["FRONTMCP_HOME"]||getPath().join(getOs().homedir(),".frontmcp"),"logs");const logsMax=parseInt(process.env["FRONTMCP_LOGS_MAX"]||"",10);if(logsMax===0){this.fd=void 0;return}try{getFs().mkdirSync(this.logDir,{recursive:true});const ts=new Date().toISOString().replace(/:/g,"_");const filePath=getPath().join(this.logDir,`${this.appName}-${ts}.log`);this.fd=getFs().openSync(filePath,"a");this.rotate(isNaN(logsMax)?DEFAULT_LOGS_MAX:logsMax)}catch{this.fd=void 0}}close(){if(this.fd!==void 0){try{getFs().closeSync(this.fd)}catch{}this.fd=void 0}}log(rec){if(this.fd===void 0)return;const ts=rec.timestamp.toISOString();const level=LOG_LEVEL_LABELS[rec.level]??"INFO";const prefix=rec.prefix?` [${escapeControlCharacters6(rec.prefix)}]`:"";const message=escapeControlCharacters6(stripAnsi(String(rec.message)));const line=`[${ts}] ${level}${prefix} ${message}
490
490
  `;try{getFs().writeSync(this.fd,line)}catch{}}rotate(maxFiles){try{const prefix=`${this.appName}-`;const files=getFs().readdirSync(this.logDir).filter(f=>f.startsWith(prefix)&&f.endsWith(".log")).sort();const excess=files.length-maxFiles;if(excess<=0)return;for(let i=0;i<excess;i++){try{getFs().unlinkSync(getPath().join(this.logDir,files[i]))}catch{}}}catch{}}};FileLogTransportInstance=__decorateClass([FrontMcpLogTransport({name:"FileLogger",description:"Writes logs to a file for CLI mode diagnostics"})],FileLogTransportInstance)}});var detached_job_worker_exports={};__export(detached_job_worker_exports,{runDetachedJob:()=>runDetachedJob});async function runDetachedJob(config,runId,boot=bootRunner){delete process.env[RUN_JOB_ENV_VAR];let host;try{host=await boot(config)}catch(error){await reportBootFailure(config,runId,error);return 1}const stop=()=>void host.shutdown().catch(()=>void 0);process.once("SIGTERM",stop);process.once("SIGINT",stop);const keepAlive=setInterval(()=>void 0,6e4);try{await(await managerOf(host,runId))?.runDetached(runId);return 0}finally{clearInterval(keepAlive);process.off("SIGTERM",stop);process.off("SIGINT",stop);await host.shutdown().catch(()=>void 0)}}async function bootRunner(config){const{FrontMcpInstance:FrontMcpInstance2}=await Promise.resolve().then(()=>(init_front_mcp(),front_mcp_exports));const parsed=frontMcpMetadataSchema.parse({...config,http:void 0,serve:false});markDirectOnly(parsed);parsed[JOB_WORKER_FLAG]=true;const instance=new FrontMcpInstance2(parsed);await instance.ready;return instance}async function managerOf(host,runId){for(const scope of host.getScopes()){const manager=jobExecutionManagerOf(scope);const record=await manager?.getStatus(runId);if(record&&(record.scopeId===void 0||record.scopeId===scope.id))return manager}return void 0}async function reportBootFailure(config,runId,cause){const sqlite=config.sqlite&&{...config.sqlite,path:config.sqlite.path||resolveDefaultSqlitePath({appName:config.info?.name,cliMode:false})};const jobs=config.jobs;const store=resolveJobsStore(jobs?.store,{redis:config.redis,sqlite});try{const{store:stateStore}=await createJobStateStore({redis:store?.redis,sqlite:store?.sqlite,keyPrefix:store?.keyPrefix??"mcp:jobs:"});try{const record=await stateStore.getRun(runId);if(!record||FINISHED_JOB_STATES.has(record.state)||await stateStore.isCancelRequested?.(runId))return;const error=new JobRunnerBootError(runId,toJobError(cause).message);await stateStore.updateRun(runId,{state:"failed",error:{name:error.name,message:error.message},completedAt:Date.now()})}finally{await stateStore.dispose()}}catch{}}var init_detached_job_worker=__esm({"libs/sdk/src/job/runner/detached-job.worker.ts"(){"use strict";init_common();init_resolve();init_errors();init_detached_job_flag();init_direct_only_flag();init_job_attempt();init_job_run_access();init_job_scope_helper();init_job_state_store_factory();init_job_state_interface()}});function toByteStream(streamLike){const iter=streamLike[Symbol.asyncIterator];if(typeof iter!=="function"){return new ReadableStream({start:c=>c.close()})}const it=iter.call(streamLike);return new ReadableStream({async pull(controller){const{value,done}=await it.next();if(done){controller.close();return}controller.enqueue(typeof value==="string"?encoder12.encode(value):value)},async cancel(){await it.return?.(void 0)}})}function bytesFrom(body,encoding){if(typeof body!=="string")return body;if(encoding==="base64")return Uint8Array.from(atob(body),c=>c.charCodeAt(0));if(encoding==="hex"){if(body.length%2!==0||!/^[0-9a-fA-F]*$/.test(body)){throw new TypeError("Invalid hex-encoded body")}const out=new Uint8Array(body.length/2);for(let i=0;i<out.length;i++)out[i]=parseInt(body.slice(i*2,i*2+2),16);return out}return encoder12.encode(body)}function buildHeaders(out,contentType2){const headers=new Headers;if(contentType2)headers.set("Content-Type",contentType2);const extra=out["headers"];if(extra)for(const[k,v]of Object.entries(extra))headers.set(k,v);const cookies=out["cookies"];if(Array.isArray(cookies)){for(const c of cookies)headers.append("Set-Cookie",typeof c==="string"?c:serializeHttpCookie(c))}return headers}function renderHttpOutputToWebResponse(output){const out=output;switch(out.kind){case"web-response":return out.response;case"next":case"consumed":return void 0;case"redirect":{const headers=buildHeaders(out);headers.set("Location",toLocationHeader(out.location));return new Response(null,{status:out.status,headers})}case"json":case"jsonrpc":case"problem":return new Response(JSON.stringify(out.body),{status:out.status,headers:buildHeaders(out,out.contentType)});case"text":case"html":return new Response(out.body,{status:out.status,headers:buildHeaders(out,out.contentType)});case"binary":case"image":{const headers=buildHeaders(out,out.contentType);headers.set("Content-Disposition",serializeContentDisposition(out.disposition,out.filename));return new Response(bytesFrom(out.body,out.encoding),{status:out.status,headers})}case"stream":case"sse":{const headers=buildHeaders(out,out.contentType);if(out.kind==="stream"){headers.set("Content-Disposition",serializeContentDisposition(out.disposition,out.filename))}if(out.kind==="sse"&&!headers.has("Cache-Control"))headers.set("Cache-Control","no-cache");return new Response(toByteStream(out.stream),{status:out.status,headers})}case"empty":return new Response(null,{status:out.status,headers:buildHeaders(out)});default:return void 0}}var encoder12;var init_web_response_renderer=__esm({"libs/sdk/src/transport/web-response.renderer.ts"(){"use strict";init_http_output_schema();init_content_disposition_utils();init_http_location_utils();encoder12=new TextEncoder}});import{runRequestExclusive as runRequestExclusive7}from"@frontmcp/utils";function findRoute(routes,request2){for(const route of routes){if(route.method!==request2.method)continue;const params=matchRoutePath(route.path,request2.path);if(params)return{route,params}}return void 0}function createWebRouteResponse(){let controller;const body=new ReadableStream({start:streamController=>controller=streamController});let resolveRendered=()=>void 0;const rendered=new Promise(resolve4=>resolveRendered=resolve4);const response=new RelayServerResponse({head(status,headers){const webHeaders=new Headers;for(const[name59,value]of Object.entries(headers)){for(const item of Array.isArray(value)?value:[value])webHeaders.append(name59,item)}resolveRendered(new Response(BODYLESS_STATUSES.has(status)?null:body,{status,headers:webHeaders}))},data(chunk){const data=decodeRelayChunk(chunk);controller?.enqueue(typeof data==="string"?encoder13.encode(data):data)},end(){controller?.close()}});const failBody=error=>{response.destroy();controller?.error(error)};return{response,rendered,failBody}}function failureResponse(error){const output=flowErrorToHttpOutput(error);return output?renderHttpOutputToWebResponse(output):Response.json({error:"Internal Server Error"},{status:500})}function serveHttpRouteWeb(routes,request2,logger){const match=findRoute(routes,request2);if(!match)return Promise.resolve(void 0);request2.params={...match.params,...request2.params};const{response,rendered,failBody}=createWebRouteResponse();return new Promise(resolve4=>{void rendered.then(resolve4);const passOn=()=>resolve4(void 0);runRequestExclusive7(async()=>match.route.handler(request2,response.asServerResponse(),passOn)).catch(error=>{if(!response.headersSent){resolve4(failureResponse(error));return}logger.error(`HTTP route ${match.route.method} ${match.route.path} failed after its response started`,error);failBody(error)})})}var encoder13,BODYLESS_STATUSES;var init_web_http_route=__esm({"libs/sdk/src/transport/web-http-route.ts"(){"use strict";init_flow_http_path();init_flow_error_output();init_relay_http();init_web_response_renderer();encoder13=new TextEncoder;BODYLESS_STATUSES=new Set([101,204,205,304])}});var web_fetch_handler_exports={};__export(web_fetch_handler_exports,{createDeferredServerBuild:()=>createDeferredServerBuild,createServerFetchHandler:()=>createServerFetchHandler,createWebFetchHandler:()=>createWebFetchHandler,misconfigurationResponse:()=>misconfigurationResponse,runHttpRequestFlowWeb:()=>runHttpRequestFlowWeb,runMatchingHttpFlowWeb:()=>runMatchingHttpFlowWeb,startupFailureResponse:()=>startupFailureResponse});import{runRequestExclusive as runRequestExclusive8}from"@frontmcp/utils";function isCloudflareWorkersRuntime(request2){if(typeof navigator!=="undefined"&&navigator.userAgent===CLOUDFLARE_WORKERS_USER_AGENT)return true;const cloudflareProperties=request2.cf;return typeof cloudflareProperties==="object"&&cloudflareProperties!==null}function resolvePeerAddress(request2,ctx){if(carriedPeerAddresses.has(request2))return carriedPeerAddresses.get(request2);if(typeof ctx?.requestIP==="function")return ctx.requestIP(request2)?.address;if(typeof ctx?.remoteAddr?.hostname==="string")return ctx.remoteAddr.hostname;if(isCloudflareWorkersRuntime(request2))return request2.headers.get("cf-connecting-ip")??void 0;return void 0}function mapHttpCors(httpCors,scope){if(!httpCors)return void 0;const{origin,credentials,maxAge}=httpCors;if(typeof origin==="function"){scope.logger.warn("[web-fetch] http.cors.origin is a function, which the worker adapter cannot replay \u2014 CORS left disabled. Use a static origin (true / string / string[]).");return void 0}return{origin,credentials,maxAge}}function metricsResponse(result){if(result.kind==="json")return Response.json(result.body,{status:result.status,headers:result.headers});return new Response(result.body,{status:result.status,headers:result.headers})}function createWebFetchHandler(scope,options={}){return buildWebFetchHandler(scope,options)}function buildWebFetchHandler(scope,options,listedEntryPaths){const httpConfig=scope.metadata.http;const healthConfig=scope.metadata.health??{};const healthEnabled=healthConfig.enabled!==false;const healthzPath=healthConfig.healthzPath??"/healthz";const readyzPath=healthConfig.readyzPath??"/readyz";const readyzEnabled=isReadyzEnabled(healthConfig);const bodyLimit=parseByteLimit(httpConfig?.bodyLimit);const securityHeaders=resolveSecurityHeaders(httpConfig?.securityHeaders);const normalizePath=p=>{const withSlash=p.startsWith("/")?p:`/${p}`;let end=withSlash.length;while(end>1&&withSlash.charCodeAt(end-1)===47)end--;return withSlash.slice(0,end)};const rawEntry=options.entryPath??(normalizeEntryPrefix(resolveEntryPath(httpConfig?.entryPath))||"/");const entryPaths=new Set((Array.isArray(rawEntry)?rawEntry:[rawEntry]).map(normalizePath));const cors2=options.cors??mapHttpCors(resolveHttpCors(httpConfig?.cors),scope);const corsEnabled=cors2?.origin!==void 0&&cors2.origin!==false;const rebinding=httpConfig?.security?.dnsRebindingProtection;const hostValidation=rebinding?.enabled===false||!rebinding?.allowedHosts?.length&&rebinding?.allowedOrigins===void 0?void 0:compileHostValidation({allowedHosts:rebinding.allowedHosts,allowedOrigins:rebinding.allowedOrigins});const corsHeadersFor=request2=>{if(!corsEnabled)return{};const reqOrigin=request2.headers.get("origin")??"";let allowOrigin;if(cors2.origin===true)allowOrigin=reqOrigin||"*";else if(cors2.origin==="*"||cors2.origin===reqOrigin)allowOrigin=cors2.origin;else if(typeof cors2.origin==="string")allowOrigin=cors2.origin;else if(Array.isArray(cors2.origin))allowOrigin=cors2.origin.includes(reqOrigin)?reqOrigin:void 0;if(!allowOrigin)return{};const h2={"Access-Control-Allow-Origin":allowOrigin,"Access-Control-Allow-Methods":(cors2.methods??["GET","POST","OPTIONS","DELETE"]).join(", "),"Access-Control-Allow-Headers":(cors2.headers??[request2.headers.get("access-control-request-headers")||"content-type, authorization, mcp-session-id, mcp-protocol-version, last-event-id"]).join(", "),"Access-Control-Expose-Headers":(cors2.exposeHeaders??["Mcp-Session-Id","WWW-Authenticate"]).join(", ")};if(cors2.credentials)h2["Access-Control-Allow-Credentials"]="true";if(cors2.maxAge!==void 0)h2["Access-Control-Max-Age"]=String(cors2.maxAge);if(allowOrigin!=="*")h2["Vary"]="Origin";return h2};const withCors=(response,request2)=>{if(!corsEnabled||response.headers.has("access-control-allow-origin"))return response;const headers=new Headers(response.headers);for(const[k,v]of Object.entries(corsHeadersFor(request2)))headers.set(k,v);return new Response(response.body,{status:response.status,statusText:response.statusText,headers})};const metrics=options.metrics?.config.enabled===true?options.metrics:void 0;const metricsEndpoint=metrics?normalizePath(metricsPath(metrics.config)):void 0;if(metrics&&metricsEndpoint&&entryPaths.has(metricsEndpoint)){throw new MetricsPathConflictError(metricsPath(metrics.config))}const withSecurityHeaders=response=>{const headers=new Headers(response.headers);const namesFrameAncestors=/(^|;)\s*frame-ancestors\b/i.test(headers.get("content-security-policy")??"");for(const[k,v]of Object.entries(securityHeaders)){if(namesFrameAncestors&&k.toLowerCase()==="x-frame-options")continue;if(!headers.has(k))headers.set(k,v)}const machineId=machineIdHeader();if(machineId)headers.set(machineId[0],machineId[1]);headers.delete("x-powered-by");return new Response(response.body,{status:response.status,statusText:response.statusText,headers})};const handleRequest=async(request2,ctx,env)=>{const url=new URL(request2.url);if(hostValidation){const rejection=validateHostHeaders({host:request2.headers.get("host")??url.host,forwardedHost:request2.headers.get("x-forwarded-host")??void 0,origin:request2.headers.get("origin")??void 0},hostValidation);if(rejection){return Response.json({error:rejection.error,message:rejection.message},{status:rejection.status})}}const limited=await enforceBodyLimit(request2,bodyLimit,ctx);if(limited instanceof Response)return withCors(limited,request2);request2=limited;if(corsEnabled&&request2.method==="OPTIONS"&&url.pathname!==serverCardPath(scope)){return new Response(null,{status:204,headers:corsHeadersFor(request2)})}if(options.healthPaths?options.healthPaths.includes(url.pathname):healthEnabled){const isReadyz=!options.healthPaths&&url.pathname===readyzPath&&readyzEnabled;const isHealthz=options.healthPaths?url.pathname!=="/readyz":url.pathname===healthzPath||url.pathname==="/health";if(isReadyz&&scope.healthService){const readiness=await scope.healthService.getReadyz();return withCors(Response.json({...readiness,transport:"web-fetch"},{status:readiness.status==="ready"?200:503,headers:{"Cache-Control":"no-store"}}),request2)}if(isHealthz||isReadyz||options.healthPaths){return withCors(Response.json({status:"ok",server:scope.metadata.info,transport:"web-fetch"},{headers:{"Cache-Control":"no-store"}}),request2)}}if(metrics&&metricsEndpoint===normalizePath(url.pathname)&&request2.method==="GET"){const scrape=renderMetricsScrape(metrics.service,metrics.config,request2.headers.get("authorization")??void 0);return withCors(metricsResponse(scrape),request2)}const onEntryPath=entryPaths.has(normalizePath(url.pathname));if(!onEntryPath||claimedByHttpRoute(scope,request2,url)){const flowResponse=await runMatchingHttpFlowWeb(scope,request2,{ctx,env});if(flowResponse)return withCors(flowResponse,request2)}if(!onEntryPath){return withCors(Response.json({error:"Not Found",entryPaths:listedEntryPaths??[...entryPaths]},{status:404}),request2)}if(options.sessionRouter){const routed=await options.sessionRouter(request2,env,ctx);if(routed)return withCors(routed,request2)}const rendered=await runHttpRequestFlowWeb(scope,request2,{ctx,env});return withCors(rendered??Response.json({error:"Not Found"},{status:404}),request2)};return async function handle(request2,ctx,env){return withSecurityHeaders(await handleRequest(request2,ctx,env))}}function createServerFetchHandler(primary,scopes,options={}){const routes=scopes.map(scope=>({scope,basePath:`${normalizeEntryPrefix(scope.entryPath)}${normalizeScopeBase(scope.routeBase)}`})).sort((a,b)=>b.basePath.length-a.basePath.length);const endpointPaths=routes.map(({basePath})=>basePath||"/");const handlers=routes.map(({scope,basePath})=>{const scopeOptions={...options,entryPath:basePath||"/",...scope!==primary&&{metrics:void 0}};return{scope,basePath,handler:buildWebFetchHandler(scope,scopeOptions,endpointPaths)}});const primaryRoute=handlers.find(route=>route.scope===primary)??handlers[handlers.length-1];const inScopeOrder=scopes.flatMap(scope=>handlers.filter(route=>route.scope===scope));const isUnder=(path4,basePath)=>basePath!==""&&(path4===basePath||path4.startsWith(`${basePath}/`));const metricsConfig=options.metrics?.config;if(metricsConfig?.enabled===true){const metricsEndpoint=normalizeEntryPrefix(metricsPath(metricsConfig));if(handlers.some(({scope,basePath})=>scope!==primary&&isUnder(metricsEndpoint,basePath))){throw new MetricsPathConflictError(metricsPath(metricsConfig))}}return(request2,ctx,env)=>{const url=new URL(request2.url);const path4=scopePathOf(url.pathname);const route=inScopeOrder.find(({scope})=>claimedByHttpRoute(scope,request2,url))??handlers.find(({basePath})=>isUnder(path4,basePath))??handlers.find(({basePath})=>basePath==="")??primaryRoute;return route.handler(request2,ctx,env)}}function scopePathOf(pathname){return pathname.replace(WELL_KNOWN_SEGMENT,"")||"/"}function payloadTooLarge(limit,length){const error=new PayloadTooLargeError(limit,length);return Response.json({jsonrpc:"2.0",error:error.toJsonRpcError(),id:null},{status:413})}async function enforceBodyLimit(request2,limit,ctx){const method=request2.method.toUpperCase();if(method==="GET"||method==="HEAD"||method==="OPTIONS"||!request2.body)return request2;const declared=request2.headers.get("content-length");if(declared!==null){const length=Number(declared);if(Number.isFinite(length)&&length>limit)return payloadTooLarge(limit,length)}const peerAddress=resolvePeerAddress(request2,ctx);const reader=request2.body.getReader();const chunks=[];let total=0;for(;;){const{done,value}=await reader.read();if(done)break;total+=value.byteLength;if(total>limit){await reader.cancel().catch(()=>void 0);return payloadTooLarge(limit,total)}chunks.push(value)}const buffered=new Uint8Array(total);let offset=0;for(const chunk of chunks){buffered.set(chunk,offset);offset+=chunk.byteLength}const rebuilt=new Request(request2.url,{method:request2.method,headers:request2.headers,body:buffered});carriedPeerAddresses.set(rebuilt,peerAddress);return rebuilt}async function runHttpRequestFlowWeb(scope,request2,opts={}){const url=new URL(request2.url);const serverRequest=await toServerRequest(request2,url,opts.ctx,opts.persistent,opts.env);let output;try{output=await runRequestExclusive8(()=>scope.runFlow("http:request",{request:serverRequest,response:{}}))}catch(error){output=flowErrorToHttpOutput(error)}return output?renderHttpOutputToWebResponse(output):void 0}async function runMatchingHttpFlowWeb(scope,request2,opts={}){const url=new URL(request2.url);const serverRequest=await toServerRequest(request2,url,opts.ctx,void 0,opts.env);const flowName=await scope.findHttpFlowName(serverRequest);if(!flowName)return serveHttpRouteWeb(scope.httpRoutes,serverRequest,scope.logger);let output;try{output=await runRequestExclusive8(()=>scope.runFlow(flowName,{request:serverRequest,response:{}}))}catch(error){output=flowErrorToHttpOutput(error)}return output?renderHttpOutputToWebResponse(output):void 0}function claimedByHttpRoute(scope,request2,url){const table=scope.httpRouteTable;if(!table)return false;const headers={};request2.headers.forEach((value,name59)=>headers[name59]=value);return table.match({method:request2.method,path:url.pathname,headers})!==void 0}async function toServerRequest(request2,url,ctx,persistent,env){const headers={};request2.headers.forEach((v,k)=>{headers[k]=v});headers["host"]=url.host;const query={};url.searchParams.forEach((v,k)=>{const existing=query[k];if(existing===void 0)query[k]=v;else if(Array.isArray(existing))existing.push(v);else query[k]=[existing,v]});const method=request2.method.toUpperCase();const hasBody=method!=="GET"&&method!=="HEAD";const bodyBytes=hasBody?await request2.arrayBuffer().then(buffer=>new Uint8Array(buffer),()=>void 0):void 0;const rawBody=bodyBytes?new TextDecoder().decode(bodyBytes):"";let body;if(rawBody){try{body=JSON.parse(rawBody)}catch{body=rawBody}}const init={method:request2.method,headers:request2.headers};if(rawBody)init.body=rawBody;const webRequest=new Request(url.toString(),init);const serverRequest={method,protocol:url.protocol.slice(0,-1),path:url.pathname,url:url.pathname+url.search,headers,query,body,bodyBytes,socket:{remoteAddress:resolvePeerAddress(request2,ctx)}};const tokenized=serverRequest;tokenized[ServerRequestTokens.webRequest]=webRequest;tokenized[ServerRequestTokens.webCtx]=ctx;tokenized[ServerRequestTokens.webEnv]=env;if(persistent)tokenized[ServerRequestTokens.webTransport]=persistent;return serverRequest}function misconfigurationResponse(error){const misconfiguration=findStartupMisconfiguration(error);if(!misconfiguration)return void 0;return Response.json(misconfigurationBody(misconfiguration),{status:500})}function createDeferredServerBuild(build,options={}){const now=options.now??Date.now;let built;let inFlight;let failure;return{get(arg){if(built)return Promise.resolve(built.value);if(inFlight)return inFlight;if(failure&&now()<failure.retryAt)return Promise.reject(failure.error);const failures=failure?.count??0;inFlight=build(arg).then(value=>{built={value};failure=void 0;inFlight=void 0;return value},error=>{const delay=Math.min(STARTUP_RETRY_MAX_MS,STARTUP_RETRY_MIN_MS*2**failures);failure={error,retryAt:now()+delay,count:failures+1};inFlight=void 0;options.onFailure?.(error);throw error});return inFlight},retryAfterSeconds(){if(!failure)return 0;return Math.max(1,Math.ceil((failure.retryAt-now())/1e3))}}}function startupFailureResponse(error,retryAfterSeconds=1){const misconfigured=misconfigurationResponse(error);if(misconfigured)return misconfigured;return Response.json({error:"server_unavailable",code:"SERVER_START_FAILED",message:"The server failed to start, so it refuses requests. Its log has the cause; a request after the Retry-After delay tries to start it again."},{status:503,headers:{"Retry-After":String(Math.max(1,retryAfterSeconds))}})}var CLOUDFLARE_WORKERS_USER_AGENT,carriedPeerAddresses,WELL_KNOWN_SEGMENT,STARTUP_RETRY_MIN_MS,STARTUP_RETRY_MAX_MS;var init_web_fetch_handler=__esm({"libs/sdk/src/transport/web-fetch-handler.ts"(){"use strict";init_server_tokens();init_path_utils();init_errors();init_misconfiguration();init_ha_headers();init_health_routes();init_mcp_registry_utils();init_metrics_errors();init_metrics_routes();init_cors_env();init_csp_middleware();init_host_validation();init_body_limit();init_flow_error_output();init_web_http_route();init_web_response_renderer();CLOUDFLARE_WORKERS_USER_AGENT="Cloudflare-Workers";carriedPeerAddresses=new WeakMap;WELL_KNOWN_SEGMENT=/\/\.well-known\/[^/]+/;STARTUP_RETRY_MIN_MS=1e3;STARTUP_RETRY_MAX_MS=6e4}});var static_startup_check_exports={};__export(static_startup_check_exports,{assertStaticStartupConfig:()=>assertStaticStartupConfig});function tryNormalize(normalize){try{return normalize()}catch{return void 0}}function asMetadata(value){return value!==null&&typeof value==="object"?value:void 0}function isServedEverywhere(metadata){const availability=asMetadata(metadata["availableWhen"]);if(!availability)return true;return Object.entries(availability).every(([axis,value])=>value===void 0||axis==="surface"&&Array.isArray(value)&&value.length>0)}function pluginClassOf(record){switch(record.kind){case"CLASS_TOKEN":return record.provide;case"CLASS":return record.useClass;case"VALUE":return record.useValue?.constructor;default:return void 0}}function pluginHooksOf(record){const pluginClass=pluginClassOf(record);if(!pluginClass)return void 0;return[...collectHook(pluginClass),...peekPendingTC39HooksForClass(pluginClass)]}function keysEnforcedByPlugins2(plugins,into=new Set){for(const plugin of plugins??[]){const record=tryNormalize(()=>normalizePlugin(plugin));if(!record)continue;for(const key of record.metadata.enforcesMetadata??[])into.add(key);keysEnforcedByPlugins2(record.metadata.plugins,into)}return into}function collectStaticEntries(config){const found=[];const everyAppKeys=new Set;const ownAppKeys=new Map;const add=(label,metadata,reach)=>{const fields=asMetadata(metadata);if(!fields||!isServedEverywhere(fields))return false;found.push({label,metadata:fields,reach});return true};const keysOfApp=app=>{const keys=ownAppKeys.get(app)??new Set;ownAppKeys.set(app,keys);return keys};const visitPlugins=(plugins,app)=>{for(const plugin of plugins??[]){const record=tryNormalize(()=>normalizePlugin(plugin));if(!record)continue;const hooks=pluginHooksOf(record);if(hooks===void 0||hooks.length>0){const gatesOnlyItsApp=record.metadata.scope!=="server"&&hooks!==void 0&&!hooks.some(hook=>hook.appliesTo==="uncovered-apps"||hook.appliesTo==="all-apps");const keys=app&&gatesOnlyItsApp?keysOfApp(app):everyAppKeys;for(const key of record.metadata.enforcesMetadata??[])keys.add(key)}visitEntries(record.metadata,app)}};const visitEntries=(owner,app)=>{const reach=app?{app}:"every-plugin";const toolReach=app?{app}:"every-app";for(const item of owner.tools??[]){const record=tryNormalize(()=>normalizeTool(item));if(record)add(`Tool "${record.metadata.id||record.metadata.name}"`,record.metadata,toolReach)}for(const item of owner.resources??[]){if(tryNormalize(()=>isResourceTemplate(item))){const record=tryNormalize(()=>normalizeResourceTemplate(item));if(record)add(`Resource template "${record.metadata.name}"`,record.metadata,reach)}else{const record=tryNormalize(()=>normalizeResource(item));if(record)add(`Resource "${record.metadata.name}"`,record.metadata,reach)}}for(const item of owner.prompts??[]){const record=tryNormalize(()=>normalizePrompt(item));if(record)add(`Prompt "${record.metadata.name}"`,record.metadata,reach)}for(const item of owner.agents??[]){const record=tryNormalize(()=>normalizeAgent(item));if(!record)continue;const agentName=record.metadata.id??record.metadata.name;if(!add(`Agent "${agentName}"`,record.metadata,reach))continue;const usesToolFlow=record.metadata.execution?.useToolFlow!==false;const agentKeys=usesToolFlow?keysEnforcedByPlugins2(record.metadata.plugins):new Set;const toolReachInAgent=usesToolFlow&&record.metadata.execution?.inheritPlugins===true?{agentKeys,inherits:toolReach}:{agentKeys};for(const toolItem of record.metadata.tools??[]){const toolRecord=tryNormalize(()=>normalizeTool(toolItem));if(toolRecord)add(`Tool "${agentName}:${toolRecord.metadata.name}"`,toolRecord.metadata,toolReachInAgent)}}for(const item of owner.skills??[]){const record=tryNormalize(()=>normalizeSkill(item));if(record)add(`Skill "${record.metadata.id??record.metadata.name}"`,record.metadata,"every-plugin")}visitPlugins(owner.plugins,app)};const server=config;visitEntries({tools:server.tools,resources:server.resources,skills:server.skills,plugins:server.plugins},void 0);for(const app of server.apps??[]){const record=tryNormalize(()=>normalizeApp(app));if(record?.kind==="LOCAL_CLASS")visitEntries(record.metadata,record)}const everyPluginKeys=new Set([...everyAppKeys,...[...ownAppKeys.values()].flatMap(keys=>[...keys])]);const keysReaching=reach=>{if(reach==="every-plugin")return everyPluginKeys;if(reach==="every-app")return everyAppKeys;if("agentKeys"in reach){return reach.inherits?new Set([...reach.agentKeys,...keysReaching(reach.inherits)]):reach.agentKeys}return new Set([...everyAppKeys,...ownAppKeys.get(reach.app)??[]])};return found.map(({label,metadata,reach})=>({label,metadata,enforcedBy:keysReaching(reach)}))}function assertStaticStartupConfig(config){const entries=collectStaticEntries(config);if(!config.authorities){const labels=entries.filter(({metadata})=>isEnforcementRequested(metadata["authorities"])).map(({label})=>label);if(labels.length>0){const names=labels.slice(0,5).join(", ");const suffix=labels.length>5?` and ${labels.length-5} more`:"";throw new AuthConfigurationError(`Authorities configuration required: ${names}${suffix} declare 'authorities' metadata but authorities enforcement is not fully configured (engine/context builder missing). Add 'authorities: { claimsMapping: {...}, profiles: {...} }' to your @FrontMcp() decorator to enable enforcement, or remove 'authorities' from entry metadata.`,{suggestion:"Add authorities config to @FrontMcp() or remove authorities from entry metadata"})}}const authoritiesConfig=config.authorities;if(authoritiesConfig){const declared=entries.filter(({metadata})=>isEnforcementRequested(metadata["authorities"])).map(({label,metadata})=>({label,authorities:metadata["authorities"]}));assertAuthoritiesRules(createAuthoritiesEngine(authoritiesConfig),declared)}const problems=entries.flatMap(({label,metadata,enforcedBy})=>getEnforcedMetadataKeys().filter(key=>isEnforcementRequested(metadata[key])&&!enforcedBy.has(key)).map(key=>{const enforcer=describeMetadataEnforcer(key);return`${label} declares '${key}'${enforcer?` (enforced by ${enforcer})`:""}`}));if(problems.length>0)throw new UnenforcedMetadataError(problems)}var init_static_startup_check=__esm({"libs/sdk/src/front-mcp/static-startup.check.ts"(){"use strict";init_agent_utils();init_app_utils();init_hook_decorator();init_enforced_metadata_utils();init_errors();init_hooks_utils();init_plugin_utils();init_prompt_utils();init_resource_utils();init_skill_utils();init_tool_utils();init_authorities_engine();init_authorities_rules_check()}});var ipc_server_transport_exports={};__export(ipc_server_transport_exports,{IPC_READY_MESSAGE:()=>IPC_READY_MESSAGE,IpcServerTransport:()=>IpcServerTransport,isIpcStdioRequested:()=>isIpcStdioRequested});function isIpcStdioRequested(){return!!process.env["FRONTMCP_DEV_STDIO_FD"]&&typeof process.send==="function"}var IPC_READY_MESSAGE,IpcServerTransport;var init_ipc_server_transport=__esm({"libs/sdk/src/transport/ipc-server.transport.ts"(){"use strict";IPC_READY_MESSAGE={__frontmcp:"ready"};IpcServerTransport=class{onclose;onerror;onmessage;started=false;handleMessage=raw=>{if(!raw||typeof raw!=="object"||raw.__frontmcp!==void 0)return;this.onmessage?.(raw)};handleDisconnect=()=>{this.onclose?.()};async start(){if(this.started)throw new Error("IpcServerTransport already started");if(typeof process.send!=="function"){throw new Error("IpcServerTransport requires a process forked with an IPC channel")}this.started=true;process.on("message",this.handleMessage);process.once("disconnect",this.handleDisconnect);process.send(IPC_READY_MESSAGE)}async send(message){const send=process.send;if(!process.connected||typeof send!=="function"){throw new Error("IPC channel is closed")}await new Promise((resolve4,reject)=>{send.call(process,message,err=>err?reject(err):resolve4())})}async close(){process.off("message",this.handleMessage);process.off("disconnect",this.handleDisconnect);this.started=false;this.onclose?.()}}}});var stdio_revision_router_exports={};__export(stdio_revision_router_exports,{StdioRevisionRouter:()=>StdioRevisionRouter});import{isJSONRPCErrorResponse,isJSONRPCNotification,isJSONRPCRequest,isJSONRPCResultResponse,MCP_20260728_META as MCP_20260728_META10,PROTOCOL_2026_07_28 as PROTOCOL_2026_07_284}from"@frontmcp/protocol";function eventData(event){return event.split("\n").filter(line=>line.startsWith(EVENT_DATA_FIELD)).map(line=>line.slice(EVENT_DATA_FIELD.length).trimStart()).join("\n")}async function*eventStreamMessages(stream){const decoder4=new TextDecoder;let pending="";for await(const chunk of stream){pending+=decoder4.decode(chunk,{stream:true});let boundary=pending.indexOf(EVENT_SEPARATOR);while(boundary!==-1){const data=eventData(pending.slice(0,boundary));pending=pending.slice(boundary+EVENT_SEPARATOR.length);if(data)yield JSON.parse(data);boundary=pending.indexOf(EVENT_SEPARATOR)}}}function isAsyncIterable(stream){return Symbol.asyncIterator in stream}function cancelledRequestId(message){if(!isJSONRPCNotification(message)||message.method!=="notifications/cancelled")return void 0;const requestId=message.params?.["requestId"];return typeof requestId==="string"||typeof requestId==="number"?requestId:void 0}function internalError(id){return{jsonrpc:"2.0",id,error:{code:-32603,message:"Internal error"}}}function requestedRevision(request2){const declared=request2.params?._meta?.[MCP_20260728_META10.protocolVersion];return typeof declared==="string"?declared:PROTOCOL_2026_07_284}var LISTEN_METHOD,EVENT_SEPARATOR,EVENT_DATA_FIELD,StdioRevisionRouter;var init_stdio_revision_router=__esm({"libs/sdk/src/transport/stdio-revision-router.ts"(){"use strict";init_channel_utils();init_common();init_flow_error_output();init_mcp_20260728();LISTEN_METHOD="subscriptions/listen";EVENT_SEPARATOR="\n\n";EVENT_DATA_FIELD="data:";StdioRevisionRouter=class{constructor(inner,options){this.inner=inner;this.options=options}inner;options;onclose;onerror;onmessage;inFlight=new Map;awaitingReply=new Set;idleWaiters=new Set;era="unknown";async start(){this.inner.onmessage=(message,extra)=>this.route(message,extra);this.inner.onerror=error=>this.onerror?.(error);this.inner.onclose=()=>{this.cancelAll();this.onclose?.()};await this.inner.start()}async send(message,options){if(this.era==="modern"&&isJSONRPCNotification(message))return;try{await this.inner.send(message,options)}finally{const repliedTo=isJSONRPCResultResponse(message)||isJSONRPCErrorResponse(message)?message.id:void 0;if(repliedTo!==void 0)this.replied(repliedTo)}}async close(){this.cancelAll();await this.inner.close()}whenIdle(timeoutMs){if(this.awaitingReply.size===0)return Promise.resolve();return new Promise(resolve4=>{const done=()=>{clearTimeout(timer);this.idleWaiters.delete(done);resolve4()};const timer=setTimeout(done,timeoutMs);this.idleWaiters.add(done)})}replied(id){this.awaitingReply.delete(id);if(this.awaitingReply.size===0)for(const done of[...this.idleWaiters])done()}route(message,extra){if(isJSONRPCRequest(message)&&message.method!==LISTEN_METHOD)this.awaitingReply.add(message.id);const cancelled=cancelledRequestId(message);if(cancelled!==void 0){this.replied(cancelled);if(this.abortsModernRequest(cancelled))return}if((isJSONRPCRequest(message)||isJSONRPCNotification(message))&&this.servesModern(message)){if(servesClaudeCodeChannels(this.options.scope)){if(isJSONRPCRequest(message))void this.declineModern(message);return}if(this.era==="unknown")this.era="modern";void this.serveModern(message);return}if(isJSONRPCRequest(message)&&message.method==="initialize")this.era="legacy";this.onmessage?.(message,extra)}servesModern(message){const configured=this.options.scope.metadata.transport?.defaultProtocolVersion??"legacy";return isProtocol20260728Request({headers:void 0,body:message,defaultVersion:this.era==="legacy"?"legacy":configured})}async declineModern(request2){const error=unsupportedProtocolVersionError(requestedRevision(request2),INITIALIZE_PROTOCOL_VERSIONS);try{await this.send({jsonrpc:"2.0",id:request2.id,error})}catch(cause){this.options.scope.logger.child("StdioRevisionRouter").error("failed to decline a 2026-07-28 request",{method:request2.method,error:cause instanceof Error?cause.message:String(cause)})}}abortsModernRequest(requestId){const controller=this.inFlight.get(requestId);if(!controller)return false;this.inFlight.delete(requestId);controller.abort();return true}async serveModern(message){const id=isJSONRPCRequest(message)?message.id:void 0;const controller=new AbortController;if(id!==void 0)this.inFlight.set(id,controller);try{const output=await this.runFlow(message,controller.signal);if(id!==void 0)await this.reply(output,id,controller.signal)}catch(error){this.options.scope.logger.child("StdioRevisionRouter").error("failed to serve a 2026-07-28 message",{method:message.method,error:error instanceof Error?error.message:String(error)})}finally{if(id!==void 0){if(this.inFlight.get(id)===controller)this.inFlight.delete(id);this.replied(id)}}}async runFlow(message,signal){const origin={principal:this.options.principal,signal};const request2={method:"POST",path:"/",url:"/",headers:{},query:{},body:message,[ServerRequestTokens.stdio]:origin};try{return await this.options.scope.runFlow("handle:mcp-202607280728",{request:request2,response:{}})}catch(error){return flowErrorToHttpOutput(error)}}async reply(output,id,signal){if(output?.kind==="sse"&&isAsyncIterable(output.stream)){for await(const message of eventStreamMessages(output.stream)){if(signal.aborted)return;await this.inner.send(message)}return}if(signal.aborted)return;const body=output?.kind==="json"?output.body:void 0;const isReply=isJSONRPCResultResponse(body)||isJSONRPCErrorResponse(body);await this.inner.send(isReply?body:internalError(id))}cancelAll(){for(const controller of this.inFlight.values())controller.abort();this.inFlight.clear();for(const id of[...this.awaitingReply])this.replied(id)}}}});import*as http2 from"node:http";import{Readable}from"node:stream";function headersOf(init){const headers={};new Headers(init?.headers).forEach((value,name59)=>{headers[name59]=value});return headers}function nodeHttpFetch(target,refuseSocket){return(input,init)=>new Promise((resolve4,reject)=>{const url=new URL(input instanceof Request?input.url:String(input));const request2=http2.request({...target,path:`${url.pathname}${url.search}`,method:init?.method??"GET",headers:{...target.headers,...headersOf(init)},signal:init?.signal??void 0},response=>{const headers=new Headers;for(const[name59,value]of Object.entries(response.headers)){if(value!==void 0)headers.set(name59,Array.isArray(value)?value.join(", "):value)}const status=response.statusCode??502;if(status===204||status===304||response.headers["content-length"]==="0"){response.resume();resolve4(new Response(null,{status,headers}));return}resolve4(new Response(Readable.toWeb(response),{status,headers}))});request2.on("socket",socket=>{const refusal4=refuseSocket?.(socket);if(refusal4)request2.destroy(refusal4)});request2.on("error",reject);request2.end(typeof init?.body==="string"?init.body:void 0)})}function unixSocketFetch(socketPath){return nodeHttpFetch({socketPath,agent:false})}var init_unix_socket_fetch=__esm({"libs/sdk/src/shared/unix-socket-fetch.ts"(){"use strict"}});import*as http3 from"node:http";import{createSharedServerNonce,verifySharedServerIdentity}from"@frontmcp/auth";import{readTextWithLimit}from"@frontmcp/utils";function unixEndpoint(socketPath){return{id:`unix:${socketPath}`,baseUrl:"http://localhost",fetch:unixSocketFetch(socketPath)}}function httpEndpoint(port){const baseUrl=`http://127.0.0.1:${port}`;return{id:baseUrl,baseUrl,fetch:(input,init)=>fetch(input,init)}}async function readAnswer(response){const length=Number(response.headers.get("content-length")??Number.NaN);if(!(length<=MAX_ANSWER_BYTES)){await response.body?.cancel();return void 0}try{return JSON.parse(await readTextWithLimit(response,MAX_ANSWER_BYTES))}catch{return void 0}}function isSharedVersion(value){return typeof value==="string"&&/^[\x20-\x7e]+$/.test(value)&&value.length<=MAX_SHARED_VERSION_LENGTH}async function identifySharedServer(endpoint,proofKey,timeoutMs=IDENTIFY_TIMEOUT_MS){const nonce=createSharedServerNonce();let response;try{response=await endpoint.fetch(`${endpoint.baseUrl}${SHARED_IDENTIFY_PATH}`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({nonce}),signal:AbortSignal.timeout(Math.min(timeoutMs,IDENTIFY_TIMEOUT_MS))})}catch{return{outcome:"unreachable"}}if(!response.ok){await response.body?.cancel();const exiting=response.status===503&&response.headers.get(SHARED_STATE_HEADER)===SHARED_EXITING;return{outcome:exiting?"exiting":"refused"}}const answer=await readAnswer(response);const{proof,version}=typeof answer==="object"&&answer!==null?answer:{};if(isSharedVersion(version)&&verifySharedServerIdentity(proofKey,{endpoint:endpoint.id,nonce,version},proof)){return{outcome:"verified",version}}return{outcome:"refused"}}function fetchAfterIdentity(endpoint,proofKey){const{hostname,port}=new URL(endpoint.baseUrl);return async(input,init)=>{const agent=new http3.Agent({keepAlive:true,maxSockets:1});let answered;const challenge=nodeHttpFetch({host:hostname,port,agent},socket=>{answered=socket;return void 0});const{outcome}=await identifySharedServer({...endpoint,fetch:challenge},proofKey);if(outcome!=="verified"){agent.destroy();throw new SharedServerIdentityError(endpoint.id)}const onAnsweredConnection=nodeHttpFetch({host:hostname,port,agent,headers:{connection:"close"}},socket=>socket===answered?void 0:new SharedServerIdentityError(endpoint.id));return onAnsweredConnection(input,init)}}async function requestSharedServerDrain(server,version){try{const response=await server.fetch(`${server.endpoint.baseUrl}${SHARED_DRAIN_PATH}`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${server.token}`},body:JSON.stringify({version}),signal:AbortSignal.timeout(IDENTIFY_TIMEOUT_MS)});await response.body?.cancel();return response.status===202}catch{return false}}var SHARED_IDENTIFY_PATH,SHARED_DRAIN_PATH,SHARED_STATE_HEADER,SHARED_EXITING,MAX_SHARED_VERSION_LENGTH,IDENTIFY_TIMEOUT_MS,MAX_ANSWER_BYTES;var init_shared_endpoint=__esm({"libs/sdk/src/shared/shared-endpoint.ts"(){"use strict";init_shared_server_errors();init_unix_socket_fetch();SHARED_IDENTIFY_PATH="/.well-known/frontmcp-shared-server";SHARED_DRAIN_PATH=`${SHARED_IDENTIFY_PATH}/drain`;SHARED_STATE_HEADER="x-frontmcp-shared-server";SHARED_EXITING="exiting";MAX_SHARED_VERSION_LENGTH=256;IDENTIFY_TIMEOUT_MS=5e3;MAX_ANSWER_BYTES=1024}});import*as os from"node:os";import*as path2 from"node:path";import{z as z149}from"@frontmcp/lazy-zod";import{getEnv as getEnv23,lstat as lstat4,mkdir as mkdir4,readFile as readFile7,realpath as realpath5,rename,unlink as unlink2,writeFile as writeFile3}from"@frontmcp/utils";function checksFileModes(){return process.platform!=="win32"}function isMissing(error){return error?.code==="ENOENT"}function sharedServerFiles(key){const home=getEnv23("FRONTMCP_HOME")||path2.join(os.homedir(),".frontmcp");const directory=path2.join(path2.resolve(home),"shared",key);return{directory,recordFile:path2.join(directory,"server.json"),socketPath:path2.join(directory,"server.sock"),lockFile:path2.join(directory,"start-lock.sqlite")}}function assertSocketPathFits(files){if(new TextEncoder().encode(files.socketPath).length<=MAX_SOCKET_PATH_BYTES)return;throw new InvalidSharedServerOptionsError(`transport: the socket path ${files.socketPath} is longer than ${MAX_SOCKET_PATH_BYTES} bytes; use a shorter key or FRONTMCP_HOME, or transport 'http'`)}async function prepareSharedDirectory(files){await mkdir4(files.directory,{recursive:true,mode:OWNER_ONLY_DIRECTORY3});if(!checksFileModes())return;for(const directory of new Set([files.directory,await realpath5(files.directory)])){const replaceable=await findReplaceableDirectory(directory);if(!replaceable)continue;const{ownerUid}=replaceable;throw new UnsafeSharedServerDirectoryError(replaceable.directory,replaceable.mode,ownerUid===void 0?"the group or others can write to it":`it belongs to another user (uid ${ownerUid})`)}}async function writeServerRecord(files,record){const temporary=`${files.recordFile}.${process.pid}.tmp`;await unlink2(temporary).catch(error=>{if(!isMissing(error))throw error});await writeFile3(temporary,JSON.stringify(record),{mode:OWNER_ONLY_FILE3,flag:"wx"});await rename(temporary,files.recordFile)}function unsafeFileReason(stats){if(!stats.isFile())return"it is not a regular file";if(stats.uid!==process.getuid?.())return`it belongs to another user (uid ${stats.uid})`;if(stats.mode&GROUP_OR_OTHER_ACCESS3)return"the group or others can read it";return void 0}async function readServerRecord(files){let stats;try{stats=await lstat4(files.recordFile)}catch(error){if(isMissing(error))return void 0;throw error}const unsafe=checksFileModes()?unsafeFileReason(stats):void 0;if(unsafe)throw new UnsafeSharedServerDirectoryError(files.recordFile,stats.mode,unsafe);let content;try{content=JSON.parse(await readFile7(files.recordFile))}catch{return void 0}const parsed=serverRecordSchema.safeParse(content);return parsed.success?parsed.data:void 0}async function removeServerRecord(files,pid){const record=await readServerRecord(files).catch(()=>void 0);if(record?.pid!==pid)return;await unlink2(files.recordFile).catch(error=>{if(!isMissing(error))throw error})}var OWNER_ONLY_DIRECTORY3,OWNER_ONLY_FILE3,GROUP_OR_OTHER_ACCESS3,MAX_SOCKET_PATH_BYTES,serverRecordSchema;var init_shared_files=__esm({"libs/sdk/src/shared/shared-files.ts"(){"use strict";init_shared_server_errors();init_replaceable_directory();OWNER_ONLY_DIRECTORY3=448;OWNER_ONLY_FILE3=384;GROUP_OR_OTHER_ACCESS3=63;MAX_SOCKET_PATH_BYTES=103;serverRecordSchema=z149.object({name:z149.string(),transport:z149.enum(["unix","http"]),port:z149.number().int().min(1).max(65535).optional(),path:z149.string().startsWith("/"),pid:z149.number().int().positive(),secret:z149.string().regex(/^[A-Za-z0-9_-]{43}$/)}).strict().refine(({transport,port})=>transport==="http"===(port!==void 0))}});function compareSharedVersions(version,own){if(version===own)return 0;if(!isValidVersion(version)||!isValidVersion(own))return void 0;return compareVersions(version,own)}var init_shared_version=__esm({"libs/sdk/src/shared/shared-version.ts"(){"use strict";init_semver_utils()}});import{deriveSharedServerKeys}from"@frontmcp/auth";import{getSpawnFn,randomBytes as randomBytes15}from"@frontmcp/utils";function endpointOf(files,record){if(record.transport==="unix")return unixEndpoint(files.socketPath);return record.port===void 0?void 0:httpEndpoint(record.port)}async function findRunning(options,refused2,timeoutMs){const record=await readServerRecord(options.files);if(!record||record.transport!==options.transport)return void 0;const endpoint=endpointOf(options.files,record);if(!endpoint)return void 0;const{proofKey,token}=deriveSharedServerKeys(record.secret);const identified=await identifySharedServer(endpoint,proofKey,timeoutMs);if(identified.outcome==="verified"){const send=record.transport==="http"?fetchAfterIdentity(endpoint,proofKey):endpoint.fetch;const url=`${endpoint.baseUrl}${record.path}`;const server={url,token,pid:record.pid,version:identified.version,endpoint,fetch:send};return{server,name:record.name,proofKey}}if(identified.outcome==="refused"&&!refused2.has(endpoint.id)){refused2.add(endpoint.id);options.logger.warn(`the process at ${endpoint.id} did not prove it is the shared server "${options.key}"; it was not sent the token`)}return void 0}function skewOf(found,options){if(found.name!==options.name){return{embedded:"its key is taken by a server of another info.name; give each server a key of its own"}}const{version}=found.server;const order=compareSharedVersions(version,options.version);if(order===void 0){return{embedded:`the shared server runs version ${version}, which can't be ordered against this session's ${options.version}`}}if(order>=0)return"attach";if(options.replaceOlder)return"replace";return{embedded:`the shared server runs version ${version}, older than this session's ${options.version}, and replaceOlder is off`}}async function ensureSharedServer(options){const{key,budgetMs,pollMs=POLL_MS}=options;const deadline=Date.now()+budgetMs;const remaining=()=>Math.max(deadline-Date.now(),1);const refused2=new Set;let handle;let holding=false;let spawned;let draining;try{for(;;){const found=await findRunning(options,refused2,remaining());const skew=found&&skewOf(found,options);if(found&&skew==="attach")return{server:found.server};if(typeof skew==="object")return skew;handle??=await options.openLock();holding=holding?await handle.lock.renew():await handle.lock.acquire();if(holding&&found){if(draining?.server.endpoint.id!==found.server.endpoint.id){if(await requestSharedServerDrain(found.server,options.version))draining=found}}else if(holding&&!spawned&&!await endpointHeld(options,draining,remaining())){spawned=options.spawnServer(handle.lock.holder)}if(spawned?.exitReason){if(holding)throw new SharedServerStartError(key,spawned.exitReason);spawned=void 0}if(Date.now()>=deadline){throw new SharedServerStartError(key,`no server proved its identity within ${budgetMs} ms`)}await new Promise(resolve4=>setTimeout(resolve4,Math.min(pollMs,remaining())))}}finally{if(holding)await handle?.lock.release().catch(()=>void 0);await handle?.close()}}async function endpointHeld(options,drained,timeoutMs){if(drained){const{outcome:outcome2}=await identifySharedServer(drained.server.endpoint,drained.proofKey,timeoutMs);return outcome2==="verified"||outcome2==="exiting"}if(options.transport!=="unix")return false;const{outcome}=await identifySharedServer(unixEndpoint(options.files.socketPath),randomBytes15(32),timeoutMs);return outcome==="exiting"}function spawnSharedServer(key,startLockHolder){const spawned={exitReason:void 0};const child=getSpawnFn()(process.execPath,[...process.execArgv,...process.argv.slice(1)],{cwd:process.cwd(),detached:true,stdio:"ignore",windowsHide:true,env:{...process.env,[SHARED_SERVE_ENV]:key,[SHARED_START_LOCK_ENV]:startLockHolder}});child.once("error",error=>{spawned.exitReason=`it could not be started (${error.message})`});child.once("exit",(code,signal)=>{spawned.exitReason??=`it exited with ${signal??`code ${code}`}`});child.unref();return spawned}var SHARED_SERVE_ENV,SHARED_START_LOCK_ENV,POLL_MS;var init_ensure_shared_server=__esm({"libs/sdk/src/shared/ensure-shared-server.ts"(){"use strict";init_shared_server_errors();init_shared_endpoint();init_shared_files();init_shared_version();SHARED_SERVE_ENV="FRONTMCP_SHARED_SERVE";SHARED_START_LOCK_ENV="FRONTMCP_SHARED_START_LOCK";POLL_MS=100}});import{createStorage as createStorage9,randomUUID as randomUUID38,writeFile as writeFile4}from"@frontmcp/utils";async function holdStartLock(files,key,holder,ttlSeconds=DEFAULT_TTL_SECONDS){const storage=await openStartLockStorage(files);const lock=new SharedStartLock(storage,key,ttlSeconds,holder);let lost=false;const keep=async()=>{if(!lost&&!await lock.acquire())lost=true;return!lost};let renewing=Promise.resolve();const renewal=setInterval(()=>{renewing=keep().catch(()=>void 0)},ttlSeconds*1e3/5);renewal.unref();return{held:keep,release:async()=>{clearInterval(renewal);await renewing;await lock.release().catch(()=>void 0);await storage.disconnect()}}}async function openStartLockStorage(files){await writeFile4(files.lockFile,"",{mode:OWNER_ONLY_FILE4,flag:"a"});return createStorage9({type:"sqlite",sqlite:{path:files.lockFile},prefix:"frontmcp:shared:",fallback:"error"})}var DEFAULT_TTL_SECONDS,OWNER_ONLY_FILE4,SharedStartLock;var init_start_lock=__esm({"libs/sdk/src/shared/start-lock.ts"(){"use strict";DEFAULT_TTL_SECONDS=10;OWNER_ONLY_FILE4=384;SharedStartLock=class{constructor(storage,key,ttlSeconds=DEFAULT_TTL_SECONDS,holder=randomUUID38()){this.storage=storage;this.ttlSeconds=ttlSeconds;this.holder=holder;this.lockKey=`${key}:start`}storage;ttlSeconds;holder;lockKey;async acquire(){await this.storage.set(this.lockKey,this.holder,{ttlSeconds:this.ttlSeconds,ifNotExists:true});return this.renew()}renew(){return this.storage.expireIfEquals(this.lockKey,this.holder,this.ttlSeconds)}async release(){await this.storage.deleteIfEquals(this.lockKey,this.holder)}}}});import{createBridgeStateMachine,createHttpUpstream,createStdioFramer,listChangedNotifications}from"@frontmcp/utils";function stderrLogger(){const ignore=()=>void 0;const write=level=>(message,data)=>{process.stderr.write(`[frontmcp shared] ${level} ${message}${data?` ${JSON.stringify(data)}`:""}
491
491
  `)};return{path:void 0,debug:ignore,info:ignore,reloadEvent:ignore,warn:write("warn"),error:write("error"),close:async()=>void 0}}function messageOf6(error){return error instanceof Error?error.message:String(error)}function codeOf(error){const code=error?.code;return code??error?.cause?.code}function towardsServer(send){return async(input,init)=>{let response;try{response=await send(input,init)}catch(error){if(init?.signal?.aborted)throw error;const neverSent=error instanceof SharedServerIdentityError||NOT_SENT_CODES.has(String(codeOf(error)));throw new SharedServerLostError(!neverSent,messageOf6(error))}const exiting=response.status===503&&response.headers.get(SHARED_STATE_HEADER)===SHARED_EXITING;if(response.status!==401&&!exiting)return response;await response.body?.cancel();throw new SharedServerLostError(false,exiting?"it is exiting":"it no longer knows the token")}}async function connect3(options,logger){const files=sharedServerFiles(options.key);if(options.transport==="unix")assertSocketPathFits(files);await prepareSharedDirectory(files);try{return await ensureSharedServer({key:options.key,transport:options.transport,files,logger,name:options.name,version:options.version,replaceOlder:options.replaceOlder,budgetMs:options.attachBudgetMs,spawnServer:options.spawnServer??(startLockHolder=>spawnSharedServer(options.key,startLockHolder)),openLock:async()=>{const storage=await openStartLockStorage(files);return{lock:new SharedStartLock(storage,options.key),close:()=>storage.disconnect()}}})}catch(error){if(error instanceof SharedServerStartError)return{embedded:error.message};throw error}}function attachSharedSession(options){const log=stderrLogger();let upstream;let embedded;let stopping;let clientInitialize;let clientInitialized=false;let successorWatch;const resends=new WeakMap;const framer=createStdioFramer({input:options.input,output:options.output,log,onFrame:frame4=>fsm.enqueue(frame4)});const fsm=createBridgeStateMachine({log,bufferSize:BUFFER_SIZE,reloadDeadlineMs:options.attachBudgetMs+RELOAD_MARGIN_MS,respond:frame4=>framer.write(frame4),forward});async function forward(frame4){if(frame4.method==="initialize"&&frame4.id!==void 0&&frame4.id!==null){clientInitialize=frame4;clientInitialized=false}else if(frame4.method==="notifications/initialized"){clientInitialized=true}const current=upstream;if(!current)throw new Error("the session has not reached its shared server");try{await current.send(frame4)}catch(error){if(!(error instanceof SharedServerLostError))throw error;lose(current,error);if(frame4===clientInitialize)clientInitialize=void 0;const resent=resends.get(frame4)??0;if(error.reached||resent>=MAX_RESENDS)throw error;resends.set(frame4,resent+1);await fsm.requeue(frame4)}}function lose(lost,error){if(upstream!==lost||stopping)return;upstream=void 0;endSuccessorWatch();lost.leaveSession();log.warn("reaching the next shared server",{reason:error.message});fsm.onUpstreamLost(error.message);reach().catch(fail)}function endSuccessorWatch(){clearInterval(successorWatch);successorWatch=void 0}function watchForSuccessor(lost,lostPid){if(lostPid===void 0||upstream!==lost||successorWatch||stopping)return;successorWatch=setInterval(()=>void moveToSuccessor(lost,lostPid),SUCCESSOR_WATCH_MS);successorWatch.unref();void moveToSuccessor(lost,lostPid)}function isSuccessor(record,lostPid){if(!record||record.pid===lostPid)return false;return record.transport===options.transport&&record.name===options.name}async function moveToSuccessor(lost,lostPid){let record;try{record=await readServerRecord(sharedServerFiles(options.key))}catch(error){if(upstream!==lost||stopping)return;endSuccessorWatch();log.warn("no longer watching for the next shared server",{reason:messageOf6(error)});return}if(!isSuccessor(record,lostPid))return;lose(lost,new SharedServerLostError(false,"another server took its key over"))}function fail(error){const message=messageOf6(error);log.error("attach-failed",{error:message});fsm.onReloadDeadline({error:message})}async function serverToReach(){if(embedded)return embedded;const attachment=await connect3(options,log);if("server"in attachment){const{url,token,fetch:send,pid}=attachment.server;return{url,headers:{authorization:`Bearer ${token}`},fetch:send,pid}}log.warn(`running the shared server "${options.key}" in this process: ${attachment.embedded}`);embedded=await options.embed();return embedded}async function reach(){for(let replays=0;;replays++){const server=await serverToReach();if(stopping){await embedded?.close();return}const next=createHttpUpstream({url:server.url,headers:server.headers,fetch:towardsServer(server.fetch),log,onFrame:frame4=>fsm.relayUpstream(frame4),claudeCodeChannels:true,onNotificationStreamLost:()=>watchForSuccessor(next,server.pid)});try{if(clientInitialize){const result=await next.reinitialize(clientInitialize,clientInitialized);for(const notification of listChangedNotifications(result))await framer.write(notification)}}catch(error){await next.close();if(error instanceof SharedServerLostError&&replays<MAX_RESENDS)continue;throw error}upstream=next;fsm.onChildReady();return}}framer.start();fsm.onBootStart();const attached=reach().catch(error=>{fail(error);throw error});attached.catch(()=>void 0);async function shutdown(){endSuccessorWatch();await fsm.stop();await upstream?.endSession();await upstream?.close();await embedded?.close();framer.stop()}return{attached,stop:async()=>{stopping??=shutdown();await stopping}}}var BUFFER_SIZE,RELOAD_MARGIN_MS,MAX_RESENDS,NOT_SENT_CODES,SUCCESSOR_WATCH_MS,SharedServerLostError;var init_shared_attach=__esm({"libs/sdk/src/shared/shared-attach.ts"(){"use strict";init_mcp_error();init_shared_server_errors();init_ensure_shared_server();init_shared_endpoint();init_shared_files();init_start_lock();BUFFER_SIZE=16;RELOAD_MARGIN_MS=3e4;MAX_RESENDS=3;NOT_SENT_CODES=new Set(["ECONNREFUSED","ENOENT"]);SUCCESSOR_WATCH_MS=1e3;SharedServerLostError=class extends InternalMcpError{constructor(reached,reason){super(`the shared server went away: ${reason}`,"SHARED_SERVER_LOST");this.reached=reached}reached}}});import{proveSharedServerIdentity}from"@frontmcp/auth";import{sha256 as sha2563,timingSafeEqual as timingSafeEqual7}from"@frontmcp/utils";var BEARER,SharedServerIdentity;var init_shared_server_identity=__esm({"libs/sdk/src/shared/shared-server.identity.ts"(){"use strict";BEARER="Bearer ";SharedServerIdentity=class{constructor(keys,endpoint,version){this.endpoint=endpoint;this.version=version;this.#proofKey=keys.proofKey;this.#tokenDigest=sha2563(keys.token)}endpoint;version;#proofKey;#tokenDigest;prove(nonce){const proof=proveSharedServerIdentity(this.#proofKey,{endpoint:this.endpoint,nonce,version:this.version});return{proof,version:this.version}}acceptsToken(authorization){if(typeof authorization!=="string"||!authorization.startsWith(BEARER))return false;return timingSafeEqual7(sha2563(authorization.slice(BEARER.length)),this.#tokenDigest)}}}});function exitingResponse(){return httpRespond.json({error:"the shared server is exiting"},{status:503,headers:{"retry-after":"1",connection:"close",[SHARED_STATE_HEADER]:SHARED_EXITING}})}var Will2,SharedServerLifecycle;var init_shared_server_lifecycle=__esm({"libs/sdk/src/shared/shared-server.lifecycle.ts"(){"use strict";init_common();init_shared_endpoint();({Will:Will2}=FlowHooksOf("http:request"));SharedServerLifecycle=class{#inFlight=0;#streams=new Set;#lastActivity=Date.now();#exitReason;#settledWaiters=new Set;#resolveExit=()=>void 0;exiting=new Promise(resolve4=>{this.#resolveExit=resolve4});get isExiting(){return this.#exitReason!==void 0}exit(reason){if(this.#exitReason!==void 0)return;this.#exitReason=reason;this.#resolveExit(reason);for(const stream of this.#streams)stream.destroy?.()}touch(){this.#lastActivity=Date.now()}idleFor(now=Date.now()){return this.#inFlight>0||this.#streams.size>0?0:now-this.#lastActivity}settled(timeoutMs){if(this.#inFlight===0)return Promise.resolve();return new Promise(resolve4=>{const done=()=>{clearTimeout(timer);this.#settledWaiters.delete(done);resolve4()};const timer=setTimeout(done,timeoutMs);this.#settledWaiters.add(done)})}trackRequest(run){if(run.state.get("verifyResult")?.kind!=="authorized")return;if(this.isExiting)run.respond(exitingResponse());const{request:request2,response}=run.rawInput;if(request2?.method==="GET"&&typeof response?.once==="function"){this.holdStream(response);return}this.#inFlight++;this.#lastActivity=Date.now();if(typeof response?.once==="function")response.once("close",()=>this.finishRequest());else this.finishRequest()}holdStream(stream){this.#streams.add(stream);stream.once?.("close",()=>{this.#streams.delete(stream);this.#lastActivity=Date.now()})}finishRequest(){this.#inFlight--;this.#lastActivity=Date.now();if(this.#inFlight>0)return;for(const done of[...this.#settledWaiters])done()}};__decorateClass([Will2("router")],SharedServerLifecycle.prototype,"trackRequest",1)}});var inputSchema51,outputSchema49,plan56,name57,Stage57,SharedDrainFlow;var init_shared_drain_flow=__esm({"libs/sdk/src/shared/flows/shared.drain.flow.ts"(){"use strict";init_common();init_shared_endpoint();init_shared_server_identity();init_shared_server_lifecycle();init_shared_version();inputSchema51=httpInputSchema;outputSchema49=HttpJsonSchema;plan56={pre:["checkIpFilter","acquireQuota","authorize"],execute:["drain"]};name57="shared:drain";Stage57=StageHookOf(name57);SharedDrainFlow=class extends FlowBase{static canActivate(request2){return request2.path===SHARED_DRAIN_PATH}async checkIpFilter(){enforceIpFilter(this.scope,this.tryGetContext()?.metadata.clientIp)}async acquireQuota(){await enforceGlobalRateLimit(this.scope,this.tryGetContext())}async authorize(){if(!this.get(SharedServerIdentity).acceptsToken(this.rawInput.request?.headers?.["authorization"])){this.respond(httpRespond.unauthorized())}}async drain(){const version=this.rawInput.request?.body?.version;if(!isSharedVersion(version)){this.respond(httpRespond.json({error:"version must be the version of the session"},{status:400}));return}const own=this.get(SharedServerIdentity).version;if(!((compareSharedVersions(version,own)??0)>0)){this.respond(httpRespond.json({error:"only a session of a newer version replaces this server",version:own},{status:409}));return}this.get(SharedServerLifecycle).exit(`a session of version ${version} replaces it`);this.respond(httpRespond.json({draining:true},{status:202}))}};__decorateClass([Stage57("checkIpFilter")],SharedDrainFlow.prototype,"checkIpFilter",1);__decorateClass([Stage57("acquireQuota")],SharedDrainFlow.prototype,"acquireQuota",1);__decorateClass([Stage57("authorize")],SharedDrainFlow.prototype,"authorize",1);__decorateClass([Stage57("drain")],SharedDrainFlow.prototype,"drain",1);SharedDrainFlow=__decorateClass([FrontMcpFlow({name:name57,plan:plan56,inputSchema:inputSchema51,outputSchema:outputSchema49,access:"public",middleware:{method:"POST"}})],SharedDrainFlow)}});import{isSharedServerNonce}from"@frontmcp/auth";var inputSchema52,outputSchema50,plan57,name58,Stage58,SharedIdentifyFlow;var init_shared_identify_flow=__esm({"libs/sdk/src/shared/flows/shared.identify.flow.ts"(){"use strict";init_common();init_shared_endpoint();init_shared_server_identity();init_shared_server_lifecycle();inputSchema52=httpInputSchema;outputSchema50=HttpJsonSchema;plan57={pre:["checkIpFilter","acquireQuota"],execute:["prove"]};name58="shared:identify";Stage58=StageHookOf(name58);SharedIdentifyFlow=class extends FlowBase{static canActivate(request2){return request2.path===SHARED_IDENTIFY_PATH}async checkIpFilter(){enforceIpFilter(this.scope,this.tryGetContext()?.metadata.clientIp)}async acquireQuota(){await enforceGlobalRateLimit(this.scope,this.tryGetContext())}async prove(){const nonce=this.rawInput.request?.body?.nonce;if(!isSharedServerNonce(nonce)){this.respond(httpRespond.json({error:"nonce must be 32 random bytes in base64url"},{status:400}));return}const lifecycle=this.get(SharedServerLifecycle);if(lifecycle.isExiting)this.respond(exitingResponse());lifecycle.touch();this.respond(httpRespond.json(this.get(SharedServerIdentity).prove(nonce)))}};__decorateClass([Stage58("checkIpFilter")],SharedIdentifyFlow.prototype,"checkIpFilter",1);__decorateClass([Stage58("acquireQuota")],SharedIdentifyFlow.prototype,"acquireQuota",1);__decorateClass([Stage58("prove")],SharedIdentifyFlow.prototype,"prove",1);SharedIdentifyFlow=__decorateClass([FrontMcpFlow({name:name58,plan:plan57,inputSchema:inputSchema52,outputSchema:outputSchema50,access:"public",middleware:{method:"POST"}})],SharedIdentifyFlow)}});import*as net2 from"node:net";import{createSharedServerSecret,deriveSharedServerKeys as deriveSharedServerKeys2,isStaticMode as isStaticMode2}from"@frontmcp/auth";import{ProviderScope as ProviderScope13}from"@frontmcp/di";import{watchPath}from"@frontmcp/utils";function freeLoopbackPort(){return new Promise((resolve4,reject)=>{const probe2=net2.createServer();probe2.once("error",reject);probe2.listen(0,LOOPBACK,()=>{const{port}=probe2.address();probe2.close(()=>resolve4(port))})})}function sharedHttpOptions(files,port){if(port===void 0)return{socketPath:files.socketPath,cors:false};return{port,cors:false,security:{bindAddress:LOOPBACK,dnsRebindingProtection:{enabled:true,allowedHosts:deriveAllowedHosts({bindAddress:LOOPBACK,port}),allowedOrigins:[]}}}}function withFileLogging(logging){const transports=logging?.transports??[];return{...logging,transports:transports.includes(FileLogTransportInstance)?transports:[...transports,FileLogTransportInstance]}}function assertTokenGuardsEveryScope(instance,key,token){for(const scope of instance.getScopes()){const auth=scope.auth.options;if(isStaticMode2(auth)&&auth.tokens.length===1&&auth.tokens[0]===token)continue;throw new SharedServerStartError(key,`app "${scope.id}" has auth of its own (mode ${auth.mode}), which the shared server's token would not guard; remove auth from its @App, or serve it without runShared()`)}}async function serveShared(serve){const{options}=serve;const files=sharedServerFiles(options.key);if(options.transport==="unix")assertSocketPathFits(files);await prepareSharedDirectory(files);const startLock=await holdStartLock(files,options.key,serve.startLockHolder);try{if(!await startLock.held())throw new SharedServerStartError(options.key,ANOTHER_START);return await startSharedServer(serve,files,startLock)}finally{await startLock.release()}}async function startSharedServer(serve,files,startLock){const{config,options}=serve;const secret=createSharedServerSecret();const keys=deriveSharedServerKeys2(secret);const port=options.transport==="http"?await freeLoopbackPort():void 0;const endpoint=port===void 0?unixEndpoint(files.socketPath):httpEndpoint(port);const lifecycle=new SharedServerLifecycle;const instance=serve.create(frontMcpMetadataSchema.parse({...config,serve:true,http:sharedHttpOptions(files,port),auth:{mode:"static",tokens:[keys.token]},logging:withFileLogging(config.logging),providers:[...config.providers??[],{name:"frontmcp:shared-server-identity",provide:SharedServerIdentity,scope:ProviderScope13.GLOBAL,useValue:new SharedServerIdentity(keys,endpoint.id,config.info.version)},{name:"frontmcp:shared-server-lifecycle",provide:SharedServerLifecycle,scope:ProviderScope13.GLOBAL,useValue:lifecycle}]}));await instance.ready;let scope;try{const primary=instance.getPrimaryScope();if(!primary)throw new InternalMcpError("No scopes initialized. Ensure at least one app is configured.");scope=primary;await scope.registryFlows(SharedIdentifyFlow,SharedDrainFlow);assertTokenGuardsEveryScope(instance,options.key,keys.token);await instance.start();if(!await startLock.held())throw new SharedServerStartError(options.key,ANOTHER_START);await writeServerRecord(files,{name:config.info.name,transport:options.transport,...port===void 0?{}:{port},path:scope.fullPath||"/",pid:process.pid,secret})}catch(error){await instance.shutdown().catch(()=>void 0);throw error}return runUntilExit(serve,files,instance,scope,lifecycle)}function watchForExit(serve,lifecycle){const{idleTimeoutMs,checkout}=serve.options;const intervalMs=serve.watchIntervalMs??WATCH_INTERVAL_MS;const stops=[];if(idleTimeoutMs!==false){const startedAt=Date.now();const timer=setInterval(()=>{if(Math.min(lifecycle.idleFor(),Date.now()-startedAt)<idleTimeoutMs)return;lifecycle.exit(`it had no request for ${idleTimeoutMs} ms`)},Math.min(intervalMs,idleTimeoutMs));timer.unref();stops.push(()=>clearInterval(timer))}if(checkout!==false){const watcher=watchPath(checkout,{intervalMs,onGone:()=>lifecycle.exit(`its checkout ${checkout} was removed`)});stops.push(()=>watcher.close())}return()=>{for(const stop of stops)stop()}}function runUntilExit(serve,files,instance,scope,lifecycle){const stopWatching=watchForExit(serve,lifecycle);let closing;const close=()=>{closing??=(async()=>{lifecycle.exit("it was stopped");stopWatching();await removeServerRecord(files,process.pid).catch(()=>void 0);await Promise.all([lifecycle.settled(DRAIN_MS),new Promise(resolve4=>setTimeout(resolve4,EXIT_GRACE_MS))]);await instance.shutdown()})();return closing};void lifecycle.exiting.then(reason=>{if(closing)return;scope.logger.info(`The shared server "${serve.options.key}" exits: ${reason}`);const deadline=setTimeout(()=>serve.exit(1),EXIT_DEADLINE_MS);close().then(()=>{clearTimeout(deadline);serve.exit(0)},()=>{clearTimeout(deadline);serve.exit(1)})});return{close}}var LOOPBACK,ANOTHER_START,DRAIN_MS,EXIT_GRACE_MS,EXIT_DEADLINE_MS,WATCH_INTERVAL_MS;var init_shared_serve=__esm({"libs/sdk/src/shared/shared-serve.ts"(){"use strict";init_common();init_errors();init_shared_server_errors();init_instance_file_logger();init_resolve_allowed_hosts();init_shared_drain_flow();init_shared_identify_flow();init_shared_endpoint();init_shared_files();init_shared_server_identity();init_shared_server_lifecycle();init_start_lock();LOOPBACK="127.0.0.1";ANOTHER_START="another session is starting it";DRAIN_MS=5e3;EXIT_GRACE_MS=250;EXIT_DEADLINE_MS=15e3;WATCH_INTERVAL_MS=1e3}});import{createSharedServerSecret as createSharedServerSecret2,deriveSharedServerKeys as deriveSharedServerKeys3}from"@frontmcp/auth";async function runEmbeddedServer(config,key,create2){const{token}=deriveSharedServerKeys3(createSharedServerSecret2());const instance=create2(frontMcpMetadataSchema.parse({...config,serve:false,auth:{mode:"static",tokens:[token]}}));await instance.ready;try{const scope=instance.getPrimaryScope();if(!scope)throw new InternalMcpError("No scopes initialized. Ensure at least one app is configured.");assertTokenGuardsEveryScope(instance,key,token);await instance.emitProvidersReady();const handler=createServerFetchHandler(scope,instance.getScopes());return{url:`http://localhost${scope.fullPath||"/"}`,headers:{authorization:`Bearer ${token}`},fetch:(input,init)=>handler(new Request(input,init)),close:()=>instance.shutdown()}}catch(error){await instance.shutdown().catch(()=>void 0);throw error}}var init_shared_embedded=__esm({"libs/sdk/src/shared/shared-embedded.ts"(){"use strict";init_common();init_errors();init_web_fetch_handler();init_shared_serve()}});import*as path3 from"node:path";import{z as z150}from"@frontmcp/lazy-zod";function milliseconds(max,message){return z150.number({message}).int(message).min(1,message).max(max,message)}function parseSharedServerOptions(input,platform=process.platform,entry){const result=sharedServerOptionsSchema.safeParse(input);if(!result.success){const issues=result.error.issues.map(({path:at,message})=>at.length?`${at.join(".")}: ${message}`:message);throw new InvalidSharedServerOptionsError(issues.join("; "))}const{key,transport=platform==="win32"?"http":"unix",checkout}=result.data;if(transport==="unix"&&platform==="win32"){throw new InvalidSharedServerOptionsError("transport: a Unix socket can't be kept owner-only on Windows; use transport 'http'")}return{key,transport,attachBudgetMs:result.data.attachBudgetMs??DEFAULT_ATTACH_BUDGET_MS,replaceOlder:result.data.replaceOlder??true,idleTimeoutMs:result.data.idleTimeoutMs??DEFAULT_IDLE_TIMEOUT_MS2,checkout:checkout===false?false:path3.resolve(checkout??(entry?path3.dirname(entry):process.cwd()))}}var DEFAULT_ATTACH_BUDGET_MS,MAX_ATTACH_BUDGET_MS,DEFAULT_IDLE_TIMEOUT_MS2,MAX_IDLE_TIMEOUT_MS,KEY_FORMAT,WINDOWS_DEVICE,ATTACH_BUDGET,IDLE_TIMEOUT,CHECKOUT,sharedServerOptionsSchema;var init_shared_server_options=__esm({"libs/sdk/src/shared/shared-server.options.ts"(){"use strict";init_shared_server_errors();DEFAULT_ATTACH_BUDGET_MS=15e3;MAX_ATTACH_BUDGET_MS=6e5;DEFAULT_IDLE_TIMEOUT_MS2=6e5;MAX_IDLE_TIMEOUT_MS=6048e5;KEY_FORMAT='key must be 1 to 64 lowercase letters, digits, ".", "_" or "-", starting and ending with a letter or digit';WINDOWS_DEVICE="key can't be a device name Windows reserves (con, prn, aux, nul, com0-9 and lpt0-9)";ATTACH_BUDGET=`attachBudgetMs must be a whole number of milliseconds from 1 to ${MAX_ATTACH_BUDGET_MS}`;IDLE_TIMEOUT=`idleTimeoutMs must be a whole number of milliseconds from 1 to ${MAX_IDLE_TIMEOUT_MS}, or false`;CHECKOUT="checkout must be the path of a folder, or false";sharedServerOptionsSchema=z150.object({key:z150.string({message:"key is required"}).regex(/^[a-z0-9]([a-z0-9._-]{0,62}[a-z0-9])?$/,KEY_FORMAT).refine(key=>!/^(con|prn|aux|nul|com\d|lpt\d)(\.|$)/.test(key),WINDOWS_DEVICE),transport:z150.enum(["unix","http"],{message:"transport must be 'unix' or 'http'"}).optional(),attachBudgetMs:milliseconds(MAX_ATTACH_BUDGET_MS,ATTACH_BUDGET).optional(),replaceOlder:z150.boolean({message:"replaceOlder must be true or false"}).optional(),idleTimeoutMs:z150.union([milliseconds(MAX_IDLE_TIMEOUT_MS,IDLE_TIMEOUT),z150.literal(false)],{message:IDLE_TIMEOUT}).optional(),checkout:z150.union([z150.string().min(1,CHECKOUT).refine(folder=>!folder.includes("\0"),CHECKOUT),z150.literal(false)],{message:CHECKOUT}).optional()}).strict()}});var shared_exports={};__export(shared_exports,{runShared:()=>runShared});import{getEnv as getEnv24,stat as stat6}from"@frontmcp/utils";async function isFolder(folder){try{return(await stat6(folder)).isDirectory()}catch{return false}}async function runShared(config,sharedOptions,create2){const options=parseSharedServerOptions(sharedOptions,process.platform,process.argv[1]);const version=config.info?.version;if(!isSharedVersion(version)){throw new InvalidSharedServerOptionsError(`info.version: a shared server states its version, which must be 1 to ${MAX_SHARED_VERSION_LENGTH} printable ASCII characters`)}if(options.checkout!==false&&!await isFolder(options.checkout)){throw new InvalidSharedServerOptionsError(`checkout: ${options.checkout} is not a folder`)}if(getEnv24(SHARED_SERVE_ENV)===options.key){const startLockHolder=getEnv24(SHARED_START_LOCK_ENV);delete process.env[SHARED_SERVE_ENV];delete process.env[SHARED_START_LOCK_ENV];const server=await serveShared({config,options,create:create2,startLockHolder,exit:code=>process.exit(code)});exitOnShutdownSignals(()=>server.close());return}redirectConsoleToStderr();const session=attachSharedSession({...options,name:config.info.name,version,input:process.stdin,output:process.stdout,embed:()=>runEmbeddedServer(config,options.key,create2)});exitOnShutdownSignals(()=>session.stop(),{deadlineMs:STDIO_SHUTDOWN_DEADLINE_MS,whenOrphaned:{stdin:process.stdin}});await session.attached}var init_shared=__esm({"libs/sdk/src/shared/index.ts"(){"use strict";init_shared_server_errors();init_shutdown_signals();init_stdio_console();init_ensure_shared_server();init_shared_attach();init_shared_embedded();init_shared_endpoint();init_shared_serve();init_shared_server_options()}});var front_mcp_exports={};__export(front_mcp_exports,{FrontMcpInstance:()=>FrontMcpInstance});import{StdioServerTransport}from"@frontmcp/protocol";import{getEnv as getEnv25,getEnvFlag as getEnvFlag3,getRuntimeContext as getRuntimeContext31,isEdgeRuntime as isEdgeRuntime3,randomUUID as randomUUID39}from"@frontmcp/utils";function resolveConfigInput(optionsOrClass){if(typeof optionsOrClass==="function"){const stored=getDecoratorConfig(optionsOrClass);if(stored)return stored;throw new InternalMcpError("runStdio() received a class without @FrontMcp() metadata. Pass a @FrontMcp-decorated class, or the same config object you pass to @FrontMcp().")}return optionsOrClass}function isSchemaExtraction(){return getEnvFlag3("FRONTMCP_SCHEMA_EXTRACT")}async function loadFileLogTransport(){return(await Promise.resolve().then(()=>(init_instance_file_logger(),instance_file_logger_exports))).FileLogTransportInstance}async function parseCliConfig(options,{fileLog}){const parsedConfig=parseFrontMcpConfigLite(options);const fileLogTransport=fileLog?await loadFileLogTransport():void 0;parsedConfig["__cliMode"]=true;const verbose=process.env["FRONTMCP_CLI_VERBOSE"]==="1";if(parsedConfig.logging){parsedConfig.logging.enableConsole=verbose;const transports=parsedConfig.logging.transports??[];if(fileLogTransport&&!transports.includes(fileLogTransport)){transports.push(fileLogTransport)}parsedConfig.logging.transports=transports}else{parsedConfig["logging"]={...loggingOptionsSchema.parse({}),enableConsole:verbose,transports:fileLogTransport?[fileLogTransport]:[]}}return parsedConfig}async function exitAfterDetachedRun(config,runId){const{runDetachedJob:runDetachedJob2}=await Promise.resolve().then(()=>(init_detached_job_worker(),detached_job_worker_exports));process.exit(await runDetachedJob2(config,runId))}var stdioServing,FrontMcpInstance;var init_front_mcp=__esm({"libs/sdk/src/front-mcp/front-mcp.ts"(){"use strict";init_channel_utils();init_common();init_front_mcp_stores();init_direct();init_errors();init_logger_registry();init_provider_registry();init_scope_registry();init_skill_instructions_helper();init_task_scope_helper();init_mcp_server_factory();init_detached_job_flag();init_direct_only_flag();init_front_mcp_providers();init_manifest_mode_flag();init_session_secret_check();init_shutdown_signals();init_stdio_console();stdioServing=false;FrontMcpInstance=class _FrontMcpInstance{config;ready;logger;providers;scopes;log;shutdownPromise;initialization;constructor(config){this.config=config;this.initialization=this.initialize();this.ready=this.initialization.catch(error=>this.releaseFailedStart(error))}async releaseFailedStart(error){await this.releaseWithin(DEFAULT_SHUTDOWN_DEADLINE_MS);throw error}async releaseWithin(deadlineMs){let deadline;const outlasted=new Promise(resolve4=>{deadline=setTimeout(()=>resolve4(true),deadlineMs)});const released=this.shutdown().then(()=>false,()=>false);if(await Promise.race([released,outlasted])){this.log?.error(`Releasing a server that failed to start did not finish within ${deadlineMs} ms`)}clearTimeout(deadline)}async initialize(){this.providers=new ProviderRegistry([...createMcpGlobalProviders(this.config)],void 0,{shutdownHookTimeoutMs:this.config.lifecycle?.shutdownHookTimeoutMs});await this.providers.ready;this.logger=new LoggerRegistry(this.providers);await this.logger.ready;this.log=this.providers.get(FrontMcpLogger);const name59=this.config.info?.name;const version=this.config.info?.version;const tag=[name59,version].filter(Boolean).join(" v");this.log?.info(`Initializing FrontMCP${tag?` "${tag}"`:""}...`);this.scopes=new ScopeRegistry(this.providers);await this.scopes.ready}async start(){this.log?.info("Starting FrontMCP server...");const server=this.providers.get(FrontMcpServer);if(!server){throw new ServerNotFoundError}await this.wireHealthService(server);await this.wireMetricsService(server);await server.start();for(const scope of this.getScopes()){await scope.emitServerStarted()}await this.emitProvidersReady();if(getEnv25("FRONTMCP_DEV_BOOTSTRAP_SENTINEL")==="1"){process.stderr.write(`__FRONTMCP_BOOTSTRAP_COMPLETE__ ${JSON.stringify(this.devListenerInfo(server))}
492
492
  `)}}async startOrRelease(){try{await this.start()}catch(error){return this.releaseFailedStart(error)}}reportMissingSessionSecret(){this.log?.warn(MISSING_SESSION_SECRET_WARNING);for(const scope of this.getScopes())scope.registerHealthProbe(missingSessionSecretProbe)}devListenerInfo(server){const http4=server.config;const path4=this.getPrimaryScope()?.fullPath||"/";if(http4?.socketPath)return{socketPath:http4.socketPath,path:path4};return typeof http4?.port==="number"?{port:http4.port,path:path4}:{path:path4}}getConfig(){return this.config}getScopes(){return this.scopes.getScopes()}async emitProvidersReady(){for(const scope of this.getScopes()){await scope.providers.runReadyHooks(scope.logger)}}shutdown(){this.shutdownPromise??=this.runShutdown();return this.shutdownPromise}async runShutdown(){await this.initialization.catch(()=>void 0);const scopes=this.scopes?.getScopes()??[];const failures=[];const serverStopped=this.providers?.get(FrontMcpServer)?.stop();for(const scope of scopes){await this.bestEffort("scope shutdown",()=>scope.shutdown(),failures)}await this.bestEffort("server stop",()=>serverStopped,failures);for(const scope of scopes){await this.bestEffort("scope dispose",()=>scope.dispose(),failures)}if(failures.length===1)throw failures[0];if(failures.length>1)throw new AggregateError(failures,`Graceful shutdown: ${failures.length} steps failed`)}async bestEffort(step,run,failures){try{await run()}catch(error){failures.push(error);this.log?.error(`Graceful shutdown: ${step} failed`,error)}}getPrimaryScope(){return this.scopes.getPrimaryScope()}getAppScope(app){const appScopes=this.getScopes().filter(scope2=>scope2.routeBase!=="");const scope=appScopes.find(candidate=>candidate.id===app);if(scope)return scope;const known=appScopes.map(candidate=>`"${candidate.id}"`).join(", ")||"none";throw new ScopeConfigurationError(`No endpoint serves app "${app}" on its own. Apps with an endpoint of their own (splitByApp or standalone): ${known}`)}async wireHealthService(server){const serverInstance=server;if(typeof serverInstance.setHealthService!=="function")return;const healthConfig=this.config.health??{};const scopes=this.getScopes();const scopeServices=scopes.map(s=>s.healthService).filter(hs=>hs!==void 0);if(scopeServices.length===1){serverInstance.setHealthService(scopeServices[0],healthConfig)}else if(scopeServices.length>1){const{HealthService:HealthService2}=await Promise.resolve().then(()=>(init_health2(),health_exports));const composite=new HealthService2(healthConfig,this.config.info);for(const scopeService of scopeServices){composite.registerProbeSource(()=>scopeService.getProbes())}const primaryScope=this.getPrimaryScope();if(primaryScope){composite.setScopeView(primaryScope)}serverInstance.setHealthService(composite,healthConfig)}else{serverInstance.setHealthConfig(healthConfig)}}async wireMetricsService(server){const serverInstance=server;if(typeof serverInstance.setMetricsService!=="function")return;const metricsConfig=this.config.metrics;const service=await this.createMetricsService();if(!metricsConfig||!service){serverInstance.setMetricsConfig(metricsConfig??{});return}serverInstance.setMetricsService(service,metricsConfig)}async createMetricsService(){const metricsConfig=this.config.metrics;if(!metricsConfig||metricsConfig.enabled!==true)return void 0;const{createProcessStatsCollectorIfEnabled:createProcessStatsCollectorIfEnabled2,MetricsService:MetricsService2}=await Promise.resolve().then(()=>(init_metrics2(),metrics_exports));try{const processCollector=createProcessStatsCollectorIfEnabled2(metricsConfig);return new MetricsService2(metricsConfig,processCollector)}catch(err){this.log?.error?.("Failed to wire /metrics endpoint",err);throw err}}static async bootstrap(options){if(isSchemaExtraction())return void 0;const sqlitePath=process.env["FRONTMCP_SQLITE_PATH"];const parsedConfig=frontMcpMetadataSchema.parse(sqlitePath?{...options,sqlite:{...options.sqlite??{},path:sqlitePath}}:options);const detachedRunId=detachedJobRunId();if(detachedRunId){await exitAfterDetachedRun(parsedConfig,detachedRunId);return void 0}const daemonSocket=process.env["FRONTMCP_DAEMON_SOCKET"];if(daemonSocket){await _FrontMcpInstance.runUnixSocket({...parsedConfig,socketPath:daemonSocket});return void 0}markEntryServer(parsedConfig);const sessionSecretMissing=parsedConfig.serve!==false&&checkSessionSecret(parsedConfig,"legacy");const frontMcp=new _FrontMcpInstance(parsedConfig);await frontMcp.ready;if(sessionSecretMissing)frontMcp.reportMissingSessionSecret();await frontMcp.startOrRelease();exitOnShutdownSignals(()=>frontMcp.shutdown(),{logger:frontMcp.log,whenOrphaned:parsedConfig.lifecycle?.exitWhenOrphaned?{}:void 0});frontMcp.log?.info("FrontMCP bootstrap complete");return frontMcp}static async createHandler(options){const parsedConfig=frontMcpMetadataSchema.parse(options);const sessionSecretMissing=checkSessionSecret(parsedConfig,"legacy");const frontMcp=new _FrontMcpInstance(parsedConfig);await frontMcp.ready;if(sessionSecretMissing)frontMcp.reportMissingSessionSecret();const server=frontMcp.providers.get(FrontMcpServer);if(!server){throw new ServerNotFoundError}await frontMcp.wireHealthService(server);await frontMcp.wireMetricsService(server);server.prepare();await frontMcp.emitProvidersReady();frontMcp.log?.info("FrontMCP handler created (serverless mode)");return server.getHandler()}static async createFetchHandler(options){const{createDeferredServerBuild:createDeferredServerBuild2,createServerFetchHandler:createServerFetchHandler2,startupFailureResponse:startupFailureResponse2}=await Promise.resolve().then(()=>(init_web_fetch_handler(),web_fetch_handler_exports));const build=async deferred=>{let frontMcp;let sessionSecretMissing;try{const parsedConfig=frontMcpMetadataSchema.parse({...options,serve:false});sessionSecretMissing=checkSessionSecret(parsedConfig,"2026-07-28");frontMcp=new _FrontMcpInstance(parsedConfig);await frontMcp.ready}catch(err){if(deferred){const configIssues=describeConfigIssues(err);const message="FrontMCP failed to start; requests are refused until a retry succeeds"+(configIssues?`. Invalid configuration: ${configIssues}`:"");if(frontMcp?.log)frontMcp.log.error(message,err);else console.error(`[frontmcp] ${message}`,err)}throw err}if(sessionSecretMissing)frontMcp.reportMissingSessionSecret();const scope=frontMcp.getPrimaryScope();if(!scope){throw new ServerNotFoundError}const metricsService=await frontMcp.createMetricsService();const metricsConfig=frontMcp.config.metrics;await frontMcp.emitProvidersReady();frontMcp.log?.info("FrontMCP fetch handler created (web-standard transport)");return createServerFetchHandler2(scope,frontMcp.getScopes(),metricsService&&metricsConfig?{metrics:{service:metricsService,config:metricsConfig}}:{})};if(!isEdgeRuntime3())return build(false);const{assertStaticStartupConfig:assertStaticStartupConfig2}=await Promise.resolve().then(()=>(init_static_startup_check(),static_startup_check_exports));assertStaticStartupConfig2(options);const server=createDeferredServerBuild2(()=>build(true));return async(request2,ctx,env)=>{let inner;try{inner=await server.get()}catch(err){return startupFailureResponse2(err,server.retryAfterSeconds())}return inner(request2,ctx,env)}}static async createForGraph(options){const parsedConfig=frontMcpMetadataSchema.parse({...options,serve:false});const frontMcp=new _FrontMcpInstance(parsedConfig);await frontMcp.ready;return frontMcp}static async createForConnect(options){const parsedConfig=frontMcpMetadataSchema.parse({...options,serve:false});markDirectOnly(parsedConfig);const frontMcp=new _FrontMcpInstance(parsedConfig);await frontMcp.ready;return frontMcp}static async createForCli(options){const config=getEnvFlag3("FRONTMCP_BUILD_EXTRACT")?frontMcpMetadataSchema.parse(options):options;const frontMcp=new _FrontMcpInstance(await parseCliConfig(config,{fileLog:true}));await frontMcp.ready;return frontMcp}static async createForManifest(options){const parsedConfig=await parseCliConfig(withoutStores(options),{fileLog:false});markDirectOnly(parsedConfig);markManifestMode(parsedConfig);const frontMcp=new _FrontMcpInstance(parsedConfig);await frontMcp.ready;return frontMcp}static async createDirect(options,endpoint){const{workerEnv,...config}=options;const parsedConfig=frontMcpMetadataSchema.parse({...config,http:config.http?.forwardHeaders?{forwardHeaders:config.http.forwardHeaders}:void 0,serve:false});markDirectOnly(parsedConfig);const frontMcp=new _FrontMcpInstance(parsedConfig);await frontMcp.ready;try{const scope=endpoint?.app===void 0?frontMcp.getPrimaryScope():frontMcp.getAppScope(endpoint.app);if(!scope){throw new InternalMcpError("No scopes initialized. Ensure at least one app is configured.")}frontMcp.log?.info("FrontMCP direct server created");const server=new DirectMcpServerImpl(scope,()=>frontMcp.shutdown(),{workerEnv});await frontMcp.emitProvidersReady();return server}catch(error){await frontMcp.shutdown().catch(()=>void 0);throw error}}static async runUnixSocket(options){if(isSchemaExtraction())return{close:async()=>void 0};if(getRuntimeContext31().runtime==="browser"){const{BrowserEntryPointUnavailableError:BrowserEntryPointUnavailableError2}=await Promise.resolve().then(()=>(init_browser_entry_point_errors(),browser_entry_point_errors_exports));throw new BrowserEntryPointUnavailableError2("runUnixSocket")}const{socketPath,sqlite,...configInput}=options;const detachedRunId=detachedJobRunId();if(detachedRunId){await exitAfterDetachedRun({...configInput,...sqlite?{sqlite}:{}},detachedRunId);return{close:async()=>void 0}}const parsedConfig=frontMcpMetadataSchema.parse({...configInput,http:{...configInput.http??{},socketPath},...sqlite?{sqlite}:{}});markEntryServer(parsedConfig);const sessionSecretMissing=checkSessionSecret(parsedConfig,"legacy");const frontMcp=new _FrontMcpInstance(parsedConfig);await frontMcp.ready;if(sessionSecretMissing)frontMcp.reportMissingSessionSecret();await frontMcp.startOrRelease();frontMcp.log?.info(`MCP server listening on unix://${socketPath}`);const shutdown=()=>frontMcp.shutdown();const removeSignalHandlers=exitOnShutdownSignals(shutdown,{logger:frontMcp.log,whenOrphaned:parsedConfig.lifecycle?.exitWhenOrphaned?{}:void 0});const close=async()=>{removeSignalHandlers();await shutdown()};return{close}}static async runStdio(optionsOrClass){if(isSchemaExtraction())return;const options=resolveConfigInput(optionsOrClass);const detachedRunId=detachedJobRunId();if(detachedRunId)return exitAfterDetachedRun(options,detachedRunId);redirectConsoleToStderr();process.env["FRONTMCP_STDIO"]="1";if(stdioServing){console.error("[FrontMCP] runStdio() called more than once; ignoring the duplicate stdio connection.");return}stdioServing=true;let startupSucceeded=false;const startupCleanups=[];try{const parsedConfig=frontMcpMetadataSchema.parse({...options,http:void 0,serve:false});const fileLogTransport=await loadFileLogTransport();if(parsedConfig.logging){parsedConfig.logging.enableConsole=true;const transports=parsedConfig.logging.transports??[];if(!transports.includes(fileLogTransport)){transports.push(fileLogTransport)}parsedConfig.logging.transports=transports}else{parsedConfig["logging"]={...loggingOptionsSchema.parse({}),enableConsole:true,transports:[fileLogTransport]}}markEntryServer(parsedConfig);const frontMcp=new _FrontMcpInstance(parsedConfig);await frontMcp.ready;startupCleanups.push(()=>frontMcp.releaseWithin(STDIO_SHUTDOWN_DEADLINE_MS));const primaryScope=frontMcp.getPrimaryScope();if(!primaryScope){throw new InternalMcpError("No scopes initialized. Ensure at least one app is configured.")}const scope=primaryScope;const{createMcpHandlers:createMcpHandlers2,registerMcpHandler:registerMcpHandler2}=await Promise.resolve().then(()=>(init_mcp_handlers(),mcp_handlers_exports));const hasRemoteApps=scope.apps?.getApps().some(app=>app.isRemote)??false;const hasResources=scope.resources.hasAny()||hasRemoteApps;const hasPrompts=scope.prompts.hasAny()||hasRemoteApps;const completionsCapability=hasPrompts||hasResources?{completions:{}}:{};const remoteCapabilities=hasRemoteApps?{tools:{listChanged:true},resources:{subscribe:true,listChanged:true},prompts:{listChanged:true}}:{};const channelCapabilities=channelCapabilitiesOf(scope);const composeInstructions=(caller,clientName)=>composeCallerInstructions(scope,{ctx:caller,clientName});const instructions="";const serverOptions={instructions,capabilities:{...remoteCapabilities,...scope.tools.getCapabilities(),...scope.resources.getCapabilities(),...scope.prompts.getCapabilities(),...scope.agents.getCapabilities(),...channelCapabilities,...scope.events?.getCapabilities(),...completionsCapability,...computeTaskCapabilities(scope),logging:{}},serverInfo:scope.metadata.info};const mcpServer=createMcpServer(scope.metadata.info,serverOptions);startupCleanups.push(()=>mcpServer.close());const sessionId=`stdio:${randomUUID39()}`;const handlers=createMcpHandlers2({scope,serverOptions,composeInstructions});for(const handler of handlers){const originalHandler=handler.handler;const wrappedHandler=async(request2,ctx)=>{const existingAuthInfo=ctx?.["authInfo"];const enrichedCtx={...ctx,authInfo:{...existingAuthInfo,sessionId}};return originalHandler(request2,enrichedCtx)};registerMcpHandler2(mcpServer,handler.requestSchema,wrappedHandler)}const{IpcServerTransport:IpcServerTransport2,isIpcStdioRequested:isIpcStdioRequested2}=await Promise.resolve().then(()=>(init_ipc_server_transport(),ipc_server_transport_exports));const{StdioRevisionRouter:StdioRevisionRouter2}=await Promise.resolve().then(()=>(init_stdio_revision_router(),stdio_revision_router_exports));const overIpc=isIpcStdioRequested2();const stdioTransport=overIpc?new IpcServerTransport2:new StdioServerTransport;const transport=new StdioRevisionRouter2(stdioTransport,{scope,principal:sessionId});startupCleanups.push(()=>transport.close());await mcpServer.connect(transport);startupSucceeded=true;scope.notifications.registerServer(sessionId,mcpServer,{stdio:true});await frontMcp.emitProvidersReady();exitOnShutdownSignals(async trigger=>{if(trigger==="stdin-ended")await transport.whenIdle(STDIO_DRAIN_MS);scope.notifications.unregisterServer(sessionId);try{await frontMcp.shutdown()}finally{await mcpServer.close()}},{logger:frontMcp.log,deadlineMs:STDIO_SHUTDOWN_DEADLINE_MS,whenOrphaned:parsedConfig.lifecycle?.exitWhenOrphaned===false?void 0:{stdin:overIpc?void 0:process.stdin}})}finally{if(!startupSucceeded){for(const cleanup of startupCleanups.reverse()){try{await cleanup()}catch{}}stdioServing=false}}}static async runShared(optionsOrClass,shared){if(isSchemaExtraction())return;const options=resolveConfigInput(optionsOrClass);const{runShared:runShared2}=await Promise.resolve().then(()=>(init_shared(),shared_exports));await runShared2(options,shared,config=>new _FrontMcpInstance(config))}}}});function isTaskWorkerProcess(){return typeof process!=="undefined"&&process.env?.[RUN_TASK_ENV_VAR]!==void 0}var TASK_WORKER_MODE_FLAG;var init_execute_task_flag=__esm({"libs/sdk/src/task/runtime/execute-task-flag.ts"(){"use strict";init_cli_task_runner();TASK_WORKER_MODE_FLAG="__taskWorkerMode"}});var execute_task_exports={};__export(execute_task_exports,{executeTaskWorker:()=>executeTaskWorker});import{getHostname as getHostname4}from"@frontmcp/utils";async function executeTaskWorker(options,taskId){const parsedConfig=frontMcpMetadataSchema.parse({...options,http:void 0});parsedConfig[TASK_WORKER_MODE_FLAG]=true;parsedConfig["__cliMode"]=true;if(parsedConfig.logging){parsedConfig.logging.enableConsole=false;const transports=parsedConfig.logging.transports??[];if(!transports.includes(FileLogTransportInstance))transports.push(FileLogTransportInstance);parsedConfig.logging.transports=transports}else{parsedConfig["logging"]={enableConsole:false,transports:[FileLogTransportInstance]}}const instance=new FrontMcpInstance(parsedConfig);await instance.ready;const primary=instance.getPrimaryScope();if(!primary)return fatal("no scope initialized in task worker",instance);const logger=primary.logger.child("task-worker");const scopes=instance.getScopes();const store=primary.taskStore;if(!store||!primary.tasks){return fatal("task worker booted without a task store \u2014 did you forget `tasks.sqlite` in config?",instance,logger)}const anyStore=store;let sessionId;if(typeof anyStore.getDatabase==="function"){const db=anyStore.getDatabase();const row=db.prepare("SELECT session_id FROM mcp_tasks WHERE task_id = ?").get(taskId);sessionId=row?.session_id}if(!sessionId){logger.warn("task worker: task record not found",{taskId});await shutdownScopeResources(scopes);return 0}const record=await store.get(taskId,sessionId);if(!record){logger.warn("task worker: task record missing after session resolution",{taskId});await shutdownScopeResources(scopes);return 0}if(isTerminal(record.status)){logger.info("task worker: record already terminal, nothing to do",{taskId,status:record.status});await shutdownScopeResources(scopes);return 0}const scope=record.scopeId===void 0?primary:scopes.find(candidate=>candidate.id===record.scopeId);const registry=scope?.tasks;if(!scope||!scope.taskStore||!registry){logger.error("task worker: the scope that created the task is not on this server",{taskId,scopeId:record.scopeId});const message="The server no longer has the app that created this task.";const failed=await store.update(taskId,sessionId,{status:"failed",statusMessage:message,outcome:{kind:"error",error:{code:MCP_ERROR_CODES.INTERNAL_ERROR,message}}});if(failed)await store.publishTerminal(failed).catch(()=>void 0);await shutdownScopeResources(scopes);return 1}const taskStore=scope.taskStore;await taskStore.update(taskId,sessionId,{executor:{host:"cli",pid:process.pid,spawnedAt:new Date().toISOString(),hostname:getHostname4()}});const onSignal=()=>registry.abort(taskId,"SIGTERM");process.on("SIGTERM",onSignal);process.on("SIGINT",onSignal);const notifier=new TaskNotifier(scope.notifications,logger);try{await runTaskInBackground({record,cleanedRequestParams:record.request.params,ctx:{authInfo:{sessionId},...record.surface!==void 0&&{surface:record.surface}},scope,store:taskStore,registry,notifier,logger});return 0}catch(err){logger.error("task worker: runner threw",{taskId,error:err instanceof Error?err.message:String(err)});return 1}finally{process.off("SIGTERM",onSignal);process.off("SIGINT",onSignal);await shutdownScopeResources(scopes)}}function fatal(message,_instance,logger){if(logger)logger.error(message);else console.error(`[task-worker] ${message}`);return 2}async function shutdownScopeResources(scopes){for(const scope of scopes){const storeAny=scope.taskStore;if(storeAny?.destroy){try{await storeAny.destroy()}catch{}}}}var init_execute_task=__esm({"libs/sdk/src/task/runtime/execute-task.ts"(){"use strict";init_common();init_mcp_error();init_front_mcp();init_instance_file_logger();init_task_notifier();init_task_runner();init_task_types();init_execute_task_flag()}});import"reflect-metadata";import{getEnvFlag as getEnvFlag4}from"@frontmcp/utils";function getDecoratorConfig(target){if(typeof target!=="function")return void 0;if(typeof Reflect==="undefined")return void 0;const reflect=Reflect;if(typeof reflect.getMetadata!=="function")return void 0;const config=reflect.getMetadata(FRONTMCP_CONFIG_METADATA_KEY,target);return config??void 0}function loadFrontMcpInstance(){return Promise.resolve().then(()=>(init_front_mcp(),front_mcp_exports)).then(({FrontMcpInstance:FrontMcpInstance2})=>FrontMcpInstance2)}function FrontMcp(providedMetadata){const sourceDir=captureCallerDir(FRONT_MCP_DECORATOR_BASENAMES);return target=>{const withSourceDir=sourceDir&&!providedMetadata.__sourceDir?{...providedMetadata,__sourceDir:sourceDir}:providedMetadata;const isBuildExtract=getEnvFlag4("FRONTMCP_BUILD_EXTRACT");const{error,data:parsed}=frontMcpMetadataSchema.safeParse(isBuildExtract?withoutStores(withSourceDir):withSourceDir);if(error){const formatted=error.format();if(formatted.apps){throw new InvalidDecoratorMetadataError("FrontMcp","apps",JSON.stringify(formatted.apps,null,2))}if(formatted.providers){throw new InvalidDecoratorMetadataError("FrontMcp","providers",JSON.stringify(formatted.providers,null,2))}for(const field of["skillsConfig","http","output","clients","offload","instructionsBudget"]){if(formatted[field]){throw new InvalidDecoratorMetadataError("FrontMcp",field,JSON.stringify(formatted[field],null,2))}}const loggingFormat=formatted["logging"];if(loggingFormat?.["transports"]){throw new InvalidDecoratorMetadataError("FrontMcp","logging.transports",JSON.stringify(loggingFormat["transports"],null,2))}throw error}const metadata=isBuildExtract?withStoresOf(parsed,withSourceDir):parsed;Reflect.defineMetadata(FrontMcpTokens.type,true,target);for(const property in metadata){Reflect.defineMetadata(FrontMcpTokens[property]??property,metadata[property],target)}Reflect.defineMetadata(FRONTMCP_CONFIG_METADATA_KEY,metadata,target);const isServerless2=getEnvFlag4("FRONTMCP_SERVERLESS");const isSchemaExtract=getEnvFlag4("FRONTMCP_SCHEMA_EXTRACT");const isStdio=getEnvFlag4("FRONTMCP_STDIO");const taskWorkerId=typeof process!=="undefined"?process.env?.["FRONTMCP_RUN_TASK_ID"]:void 0;if(taskWorkerId&&metadata.serve!==false){void(async()=>{try{const{executeTaskWorker:executeTaskWorker2}=await Promise.resolve().then(()=>(init_execute_task(),execute_task_exports));const code=await executeTaskWorker2(metadata,taskWorkerId);process.exit(code)}catch(err){console.error("[FrontMCP] task worker failed:",err);process.exit(2)}})();return}if(isSchemaExtract||isOffloadWorker()){}else if(isStdio){if(metadata.serve){loadFrontMcpInstance().then(FrontMcpInstance2=>FrontMcpInstance2.runStdio(metadata)).catch(err=>{console.error("[FrontMCP] stdio server failed:",err);process.exit(1)})}}else if(isServerless2){const isWorker=getEnvFlag4("FRONTMCP_WORKER");const handlerPromise=loadFrontMcpInstance().then(FrontMcpInstance2=>isWorker?FrontMcpInstance2.createFetchHandler(metadata):FrontMcpInstance2.createHandler(metadata));setServerlessHandlerPromise(handlerPromise);handlerPromise.then(setServerlessHandler).catch(err=>{const e=err instanceof Error?err:new InternalMcpError(String(err),"SERVERLESS_INIT_FAILED");setServerlessHandlerError(e);console.error("[FrontMCP] Serverless initialization failed:",e)})}else if(metadata.serve){loadFrontMcpInstance().then(FrontMcpInstance2=>FrontMcpInstance2.bootstrap(metadata)).catch(err=>{console.error("[FrontMCP] server failed to start:",err);process.exit(1)})}}}var FRONT_MCP_DECORATOR_BASENAMES,FRONTMCP_CONFIG_METADATA_KEY;var init_front_mcp_decorator=__esm({"libs/sdk/src/common/decorators/front-mcp.decorator.ts"(){"use strict";init_decorator_errors();init_mcp_error();init_serverless_handler();init_offload_worker_globals();init_metadata();init_front_mcp_stores();init_tokens();init_caller_dir_utils();FRONT_MCP_DECORATOR_BASENAMES=["front-mcp.decorator.ts","front-mcp.decorator.js"];FRONTMCP_CONFIG_METADATA_KEY="__frontmcp:config"}});function FrontMcpFlow(providedMetadata){return target=>{const metadata=frontMcpFlowMetadataSchema.parse(providedMetadata);Reflect.defineMetadata(FrontMcpFlowTokens.type,true,target);for(const property in metadata){Reflect.defineMetadata(FrontMcpFlowTokens[property]??property,metadata[property],target)}}}var init_flow_decorator=__esm({"libs/sdk/src/common/decorators/flow.decorator.ts"(){"use strict";init_metadata();init_tokens()}});import"reflect-metadata";import{idFromString as idFromString3}from"@frontmcp/utils";function FrontMcpApp(providedMetadata){const sourceDir=captureCallerDir(APP_DECORATOR_BASENAMES);return target=>{const withSourceDir=sourceDir&&!providedMetadata.__sourceDir?{...providedMetadata,__sourceDir:sourceDir}:providedMetadata;const{error,data:metadata}=frontMcpLocalAppMetadataSchema.safeParse(withSourceDir);if(error){const formatted=error.format();if(formatted.plugins){throw new InvalidDecoratorMetadataError("App","plugins",JSON.stringify(formatted.plugins,null,2))}if(formatted.providers){throw new InvalidDecoratorMetadataError("App","providers",JSON.stringify(formatted.providers,null,2))}if(formatted.authProviders){throw new InvalidDecoratorMetadataError("App","authProviders",JSON.stringify(formatted.authProviders,null,2))}if(formatted.adapters){throw new InvalidDecoratorMetadataError("App","adapters",JSON.stringify(formatted.adapters,null,2))}if(formatted.tools){throw new InvalidDecoratorMetadataError("App","tools",JSON.stringify(formatted.tools,null,2))}if(formatted.resources){throw new InvalidDecoratorMetadataError("App","resources",JSON.stringify(formatted.resources,null,2))}if(formatted.prompts){throw new InvalidDecoratorMetadataError("App","prompts",JSON.stringify(formatted.prompts,null,2))}throw error}Reflect.defineMetadata(FrontMcpLocalAppTokens.type,true,target);for(const property in metadata){Reflect.defineMetadata(FrontMcpLocalAppTokens[property]??property,metadata[property],target)}}}function namespaceIdOf(options){return options?.name===void 0&&options?.namespace?{id:idFromString3(options.namespace)}:{}}function esmApp(specifier,options){const parsed=parsePackageSpecifier(specifier);const packageConfig={};let hasPackageConfig=false;if(options?.loader){packageConfig.loader=options.loader;hasPackageConfig=true}if(options?.autoUpdate){packageConfig.autoUpdate=options.autoUpdate;hasPackageConfig=true}if(options?.cacheTTL!==void 0){packageConfig.cacheTTL=options.cacheTTL;hasPackageConfig=true}if(options?.importMap){packageConfig.importMap=options.importMap;hasPackageConfig=true}return{name:options?.name??parsed.fullName,...namespaceIdOf(options),urlType:"esm",url:specifier,namespace:options?.namespace,description:options?.description,standalone:options?.standalone??false,filter:options?.filter,...hasPackageConfig?{packageConfig}:{}}}function remoteApp(url,options){validateRemoteUrl(url);let derivedName;try{const parsed=new URL(url);derivedName=parsed.hostname.split(".")[0]}catch{derivedName=url}return{name:options?.name??derivedName,...namespaceIdOf(options),urlType:"url",url,namespace:options?.namespace,description:options?.description,standalone:options?.standalone??false,transportOptions:options?.transportOptions,remoteAuth:options?.remoteAuth,refreshInterval:options?.refreshInterval,cacheTTL:options?.cacheTTL,filter:options?.filter}}function frontMcpApp(metadata){const FunctionalApp=class{};FrontMcpApp(metadata)(FunctionalApp);return FunctionalApp}var APP_DECORATOR_BASENAMES,App;var init_app_decorator=__esm({"libs/sdk/src/common/decorators/app.decorator.ts"(){"use strict";init_decorator_errors();init_package_specifier();init_metadata();init_tokens();init_caller_dir_utils();init_validate_remote_url();APP_DECORATOR_BASENAMES=["app.decorator.ts","app.decorator.js"];Object.assign(FrontMcpApp,{esm:esmApp,remote:remoteApp});App=FrontMcpApp}});import"reflect-metadata";function FrontMcpAuthProvider(providedMetadata){return target=>{const metadata=frontMcpAuthProviderMetadataSchema.parse(providedMetadata);Reflect.defineMetadata(FrontMcpAuthProviderTokens.type,true,target);for(const property in metadata){Reflect.defineMetadata(FrontMcpAuthProviderTokens[property]??property,metadata[property],target)}}}var init_auth_provider_decorator=__esm({"libs/sdk/src/common/decorators/auth-provider.decorator.ts"(){"use strict";init_metadata();init_tokens()}});import"reflect-metadata";function FrontMcpAdapter(providedMetadata){return target=>{const metadata=frontMcpAdapterMetadataSchema.parse(providedMetadata);Reflect.defineMetadata(FrontMcpAdapterTokens.type,true,target);for(const property in metadata){Reflect.defineMetadata(FrontMcpAdapterTokens[property]??property,metadata[property],target)}}}var init_adapter_decorator=__esm({"libs/sdk/src/common/decorators/adapter.decorator.ts"(){"use strict";init_metadata();init_tokens()}});import"reflect-metadata";function FrontMcpPlugin(providedMetadata){return target=>{const{error,data:metadata}=frontMcpPluginMetadataSchema.safeParse(providedMetadata);if(error){const formatted=error.format();if(formatted.providers){throw new InvalidDecoratorMetadataError("Plugin","providers",JSON.stringify(formatted.providers,null,2))}if(formatted.adapters){throw new InvalidDecoratorMetadataError("Plugin","adapters",JSON.stringify(formatted.adapters,null,2))}if(formatted.tools){throw new InvalidDecoratorMetadataError("Plugin","tools",JSON.stringify(formatted.tools,null,2))}if(formatted.resources){throw new InvalidDecoratorMetadataError("Plugin","resources",JSON.stringify(formatted.resources,null,2))}if(formatted.prompts){throw new InvalidDecoratorMetadataError("Plugin","prompts",JSON.stringify(formatted.prompts,null,2))}throw error}Reflect.defineMetadata(FrontMcpPluginTokens.type,true,target);for(const property in metadata){Reflect.defineMetadata(FrontMcpPluginTokens[property]??property,metadata[property],target)}if(metadata.enforcesMetadata?.length){registerEnforcedMetadataKeys(metadata.enforcesMetadata,`plugin "${metadata.name}"`)}}}var init_plugin_decorator=__esm({"libs/sdk/src/common/decorators/plugin.decorator.ts"(){"use strict";init_decorator_errors();init_metadata();init_tokens();init_enforced_metadata_utils()}});import"reflect-metadata";function FrontMcpPrompt(providedMetadata){return target=>{const metadata=frontMcpPromptMetadataSchema.parse(providedMetadata);Reflect.defineMetadata(FrontMcpPromptTokens.type,true,target);const extended={};for(const property in metadata){if(FrontMcpPromptTokens[property]){Reflect.defineMetadata(FrontMcpPromptTokens[property],metadata[property],target)}else{extended[property]=metadata[property]}}Reflect.defineMetadata(extendedPromptMetadata,extended,target)}}function frontMcpPrompt(providedMetadata){return execute=>{const metadata=frontMcpPromptMetadataSchema.parse(providedMetadata);const toolFunction=function(){return execute};Object.assign(toolFunction,{[FrontMcpPromptTokens.type]:"function-prompt",[FrontMcpPromptTokens.metadata]:metadata});return toolFunction}}function promptEsm(specifier,targetName,options){const parsed=parsePackageSpecifier(specifier);return{kind:"ESM",provide:Symbol(`esm-prompt:${parsed.fullName}:${targetName}`),specifier:parsed,targetName,options,metadata:{name:targetName,description:`Prompt "${targetName}" from ${parsed.fullName}`,arguments:[],...options?.metadata}}}function promptRemote(url,targetName,options){validateRemoteUrl(url);return{kind:"REMOTE",provide:Symbol(`remote-prompt:${url}:${targetName}`),url,targetName,transportOptions:options?.transportOptions,remoteAuth:options?.remoteAuth,options,metadata:{name:targetName,description:`Remote prompt "${targetName}" from ${url}`,arguments:[],...options?.metadata}}}var Prompt;var init_prompt_decorator=__esm({"libs/sdk/src/common/decorators/prompt.decorator.ts"(){"use strict";init_package_specifier();init_metadata();init_tokens();init_validate_remote_url();Object.assign(FrontMcpPrompt,{esm:promptEsm,remote:promptRemote});Prompt=FrontMcpPrompt}});import"reflect-metadata";function FrontMcpLogTransport(providedMetadata){return target=>{const{error,data:metadata}=frontMcpLogTransportMetadataSchema.safeParse(providedMetadata);Reflect.defineMetadata(FrontMcpLogTransportTokens.type,true,target);for(const property in metadata){Reflect.defineMetadata(FrontMcpLogTransportTokens[property]??property,metadata[property],target)}}}var init_logger_decorator=__esm({"libs/sdk/src/common/decorators/logger.decorator.ts"(){"use strict";init_metadata();init_tokens()}});import"reflect-metadata";function FrontMcpAgent(providedMetadata){return target=>{const metadata=frontMcpAgentMetadataSchema.parse(providedMetadata);Reflect.defineMetadata(FrontMcpAgentTokens.type,true,target);const extended={};for(const property in metadata){if(FrontMcpAgentTokens[property]){Reflect.defineMetadata(FrontMcpAgentTokens[property],metadata[property],target)}else{extended[property]=metadata[property]}}Reflect.defineMetadata(extendedAgentMetadata,extended,target)}}function frontMcpAgent(providedMetadata){return execute=>{const metadata=frontMcpAgentMetadataSchema.parse(providedMetadata);const agentFunction=function(){return execute};Object.assign(agentFunction,{[FrontMcpAgentTokens.type]:"function-agent",[FrontMcpAgentTokens.metadata]:metadata});return agentFunction}}function agentEsm(specifier,targetName,options){const parsed=parsePackageSpecifier(specifier);return{kind:"ESM",provide:Symbol(`esm-agent:${parsed.fullName}:${targetName}`),specifier:parsed,targetName,options,metadata:{name:targetName,description:`Agent "${targetName}" from ${parsed.fullName}`,llm:{adapter:"placeholder"},...options?.metadata}}}function agentRemote(url,targetName,options){validateRemoteUrl(url);return{kind:"REMOTE",provide:Symbol(`remote-agent:${url}:${targetName}`),url,targetName,transportOptions:options?.transportOptions,remoteAuth:options?.remoteAuth,metadata:{name:targetName,description:`Remote agent "${targetName}" from ${url}`,llm:{adapter:"placeholder"},...options?.metadata}}}var Agent2;var init_agent_decorator=__esm({"libs/sdk/src/common/decorators/agent.decorator.ts"(){"use strict";init_package_specifier();init_metadata();init_tokens();init_validate_remote_url();Object.assign(FrontMcpAgent,{esm:agentEsm,remote:agentRemote});Agent2=FrontMcpAgent}});import"reflect-metadata";function _FrontMcpJob(providedMetadata){const declaringModule=captureCallerFile(JOB_DECORATOR_BASENAMES);return target=>{const metadata=frontMcpJobMetadataSchema.parse(providedMetadata);registerWorkerJob(target,providedMetadata,declaringModule);Reflect.defineMetadata(FrontMcpJobTokens.type,true,target);const extended={};for(const property in metadata){if(FrontMcpJobTokens[property]){Reflect.defineMetadata(FrontMcpJobTokens[property],metadata[property],target)}else{extended[property]=metadata[property]}}Reflect.defineMetadata(extendedJobMetadata,extended,target)}}function frontMcpJob(providedMetadata){const declaringModule=captureCallerFile(JOB_DECORATOR_BASENAMES);return execute=>{const metadata=frontMcpJobMetadataSchema.parse(providedMetadata);registerWorkerJob(execute,providedMetadata,declaringModule);const jobFunction=function(){return execute};Object.assign(jobFunction,{[FrontMcpJobTokens.type]:"function-job",[FrontMcpJobTokens.metadata]:metadata});return jobFunction}}function jobEsm(specifier,targetName,options){const parsed=parsePackageSpecifier(specifier);return{kind:"ESM",provide:Symbol(`esm-job:${parsed.fullName}:${targetName}`),specifier:parsed,targetName,options,metadata:{name:targetName,description:`Job "${targetName}" from ${parsed.fullName}`,inputSchema:{},outputSchema:{},...options?.metadata}}}function jobRemote(url,targetName,options){validateRemoteUrl(url);return{kind:"REMOTE",provide:Symbol(`remote-job:${url}:${targetName}`),url,targetName,transportOptions:options?.transportOptions,remoteAuth:options?.remoteAuth,metadata:{name:targetName,description:`Remote job "${targetName}" from ${url}`,inputSchema:{},outputSchema:{},...options?.metadata}}}var JOB_DECORATOR_BASENAMES,FrontMcpJob,Job;var init_job_decorator=__esm({"libs/sdk/src/common/decorators/job.decorator.ts"(){"use strict";init_package_specifier();init_worker_jobs();init_job_metadata();init_tokens();init_caller_dir_utils();init_validate_remote_url();JOB_DECORATOR_BASENAMES=["job.decorator.ts","job.decorator.js","job.decorator.mjs","job.decorator.cjs"];Object.assign(_FrontMcpJob,{esm:jobEsm,remote:jobRemote});FrontMcpJob=_FrontMcpJob;Job=_FrontMcpJob}});import"reflect-metadata";function FrontMcpWorkflow(providedMetadata){return target=>{const metadata=frontMcpWorkflowMetadataSchema.parse(providedMetadata);Reflect.defineMetadata(FrontMcpWorkflowTokens.type,true,target);const extended={};for(const property in metadata){if(FrontMcpWorkflowTokens[property]){Reflect.defineMetadata(FrontMcpWorkflowTokens[property],metadata[property],target)}else{extended[property]=metadata[property]}}Reflect.defineMetadata(extendedWorkflowMetadata,extended,target)}}function frontMcpWorkflow(providedMetadata){const metadata=frontMcpWorkflowMetadataSchema.parse(providedMetadata);const workflowFunction=function(){return metadata};Object.assign(workflowFunction,{[FrontMcpWorkflowTokens.type]:"value-workflow",[FrontMcpWorkflowTokens.metadata]:metadata});return workflowFunction}var init_workflow_decorator=__esm({"libs/sdk/src/common/decorators/workflow.decorator.ts"(){"use strict";init_workflow_metadata();init_tokens()}});import"reflect-metadata";function Duty(metadata){return target=>{const result=dutyMetadataSchema.safeParse(metadata);if(!result.success){const[issue]=result.error.issues;throw new InvalidDecoratorMetadataError("Duty",issue.path.join("."),issue.message)}if(typeof target.prototype?.run!=="function"){throw new InvalidDecoratorMetadataError("Duty","run",`${target.name} has no run() method`)}Reflect.defineMetadata(FrontMcpProviderTokens.type,true,target);defineDutyMetadata(target,{...result.data,name:result.data.name??target.name})}}var init_duty_decorator=__esm({"libs/sdk/src/common/decorators/duty.decorator.ts"(){"use strict";init_decorator_errors();init_duty_metadata();init_duty_resolved();init_tokens()}});import"reflect-metadata";function Worker(metadata){return target=>{const result=workerMetadataSchema.safeParse(metadata);if(!result.success){const[issue]=result.error.issues;throw new InvalidDecoratorMetadataError("Worker",issue.path.join("."),issue.message)}if(typeof target.prototype?.run!=="function"){throw new InvalidDecoratorMetadataError("Worker","run",`${target.name} has no run() method`)}Reflect.defineMetadata(FrontMcpProviderTokens.type,true,target);defineWorkerMetadata(target,{...result.data,name:result.data.name??target.name})}}var init_worker_decorator=__esm({"libs/sdk/src/common/decorators/worker.decorator.ts"(){"use strict";init_decorator_errors();init_worker_metadata();init_worker_resolved();init_tokens()}});import"reflect-metadata";import{z as z151}from"@frontmcp/lazy-zod";function HttpRoute(metadata){return target=>{const result=httpRouteMetadataSchema.safeParse(metadata);if(!result.success){const[issue]=result.error.issues;throw new InvalidDecoratorMetadataError("HttpRoute",issue.path.join(".")||"metadata",issue.message)}if(typeof target.prototype?.handle!=="function"){throw new InvalidDecoratorMetadataError("HttpRoute","handle",`${target.name} has no handle() method`)}defineHttpRouteMetadata(target,result.data)}}var httpRouteMetadataSchema;var init_http_route_decorator=__esm({"libs/sdk/src/common/decorators/http-route.decorator.ts"(){"use strict";init_decorator_errors();init_http_route_metadata();httpRouteMetadataSchema=z151.object({method:z151.enum(["GET","POST","PUT","PATCH","DELETE"],{message:"method must be 'GET', 'POST', 'PUT', 'PATCH' or 'DELETE'"}),path:z151.custom(value=>typeof value==="function"||isHttpRoutePath(value),{message:HTTP_ROUTE_PATH_MESSAGE}),auth:z151.enum(["people","subject","public"],{message:"auth must be 'people', 'subject' or 'public'"}).optional(),sse:z151.object({store:z151.custom(value=>typeof value?.subscribe==="function",{message:"sse.store must have subscribe(topic, listener), such as a resourceStore()"}),topics:z151.array(z151.string().min(1,"a topic must not be empty")).min(1,"sse.topics must name at least one topic"),coalesceMs:z151.number().int().nonnegative("sse.coalesceMs must not be negative").default(50),heartbeatMs:z151.number().int().positive("sse.heartbeatMs must be greater than 0").default(15e3)}).strict().optional()}).strict().refine(metadata=>!metadata.sse||metadata.method==="GET",{message:"an sse route must use method GET",path:["sse"]})}});var init_decorators=__esm({"libs/sdk/src/common/decorators/index.ts"(){"use strict";init_front_mcp_decorator();init_flow_decorator();init_hook_decorator();init_app_decorator();init_provider_decorator();init_auth_provider_decorator();init_adapter_decorator();init_plugin_decorator();init_tool_decorator();init_resource_decorator();init_prompt_decorator();init_logger_decorator();init_agent_decorator();init_skill_decorator();init_job_decorator();init_workflow_decorator();init_channel_decorator();init_event_decorator();init_duty_decorator();init_worker_decorator();init_http_route_decorator()}});var init_dynamic=__esm({"libs/sdk/src/common/dynamic/index.ts"(){"use strict";init_dynamic_adapter();init_dynamic_plugin()}});var ScopeEntry;var init_scope_entry=__esm({"libs/sdk/src/common/entries/scope.entry.ts"(){"use strict";init_list_change_batch();init_utils3();init_base_entry();ScopeEntry=class extends BaseEntry{get fullPath(){const prefix=normalizeEntryPrefix(this.entryPath??"");const scope=normalizeScopeBase(this.routeBase??"");return`${prefix}${scope}`}haManager;lifecycleCallbacks=[];onServerStarted(callback){this.lifecycleCallbacks.push(callback)}async emitServerStarted(){for(const cb of this.lifecycleCallbacks){await cb()}}batchListChanges(change){return runListChangeBatch(this,change)}addedHealthProbes=[];registerHealthProbe(probe2){const registration={name:probe2.name,check:()=>probe2.check()};this.addedHealthProbes.push(registration);return()=>{const index=this.addedHealthProbes.indexOf(registration);if(index!==-1)this.addedHealthProbes.splice(index,1)}}get healthProbes(){return this.addedHealthProbes}disposeCallbacks=[];disposeEmitted=false;get isDisposed(){return this.disposeEmitted}onDispose(callback){if(this.disposeEmitted){void this.runDisposeCallback(callback);return()=>void 0}this.disposeCallbacks.push(callback);return()=>{const index=this.disposeCallbacks.indexOf(callback);if(index!==-1)this.disposeCallbacks.splice(index,1)}}async emitDispose(){if(this.disposeEmitted)return;this.disposeEmitted=true;const callbacks=this.disposeCallbacks.splice(0).reverse();for(const cb of callbacks){await this.runDisposeCallback(cb)}}async runDisposeCallback(callback){try{await callback()}catch(error){this.logger.warn(`Scope dispose callback failed: ${error instanceof Error?error.message:String(error)}`)}}}}});import"reflect-metadata";var FlowEntry;var init_flow_entry=__esm({"libs/sdk/src/common/entries/flow.entry.ts"(){"use strict";init_base_entry();FlowEntry=class extends BaseEntry{name;path;method;scope;constructor(scope,record,token,metadata){super(record,token,metadata);const{path:path4,method}=record.metadata.middleware??metadata?.middleware??{};this.name=metadata?.name??record.metadata?.name;this.path=path4;this.method=method;this.scope=scope}}}});var HookEntry;var init_hook_entry=__esm({"libs/sdk/src/common/entries/hook.entry.ts"(){"use strict";init_base_entry();HookEntry=class extends BaseEntry{scope;providers;options;constructor(scope,providers,record,token,metadata){super(record,token,metadata);this.scope=scope;this.providers=providers;this.options={filter:metadata.filter,priority:metadata.priority}}}}});var AppEntry;var init_app_entry=__esm({"libs/sdk/src/common/entries/app.entry.ts"(){"use strict";init_base_entry();AppEntry=class extends BaseEntry{id;get isRemote(){return false}}}});var ProviderEntry;var init_provider_entry=__esm({"libs/sdk/src/common/entries/provider.entry.ts"(){"use strict";init_base_entry();ProviderEntry=class extends BaseEntry{}}});var AuthProviderEntry;var init_auth_provider_entry=__esm({"libs/sdk/src/common/entries/auth-provider.entry.ts"(){"use strict";init_base_entry();AuthProviderEntry=class extends BaseEntry{}}});var PluginEntry;var init_plugin_entry=__esm({"libs/sdk/src/common/entries/plugin.entry.ts"(){"use strict";init_base_entry();PluginEntry=class extends BaseEntry{}}});var AdapterEntry;var init_adapter_entry=__esm({"libs/sdk/src/common/entries/adapter.entry.ts"(){"use strict";init_base_entry();AdapterEntry=class extends BaseEntry{}}});import{toJSONSchema as toJSONSchema8,internalZ as z152}from"@frontmcp/lazy-zod";import{isDebug as isDebug3,isDevelopment as isDevelopment6}from"@frontmcp/utils";function literalOutputJsonSchema(literal){if(literal==="string"||literal==="number"||literal==="boolean"){return objectJsonSchema({content:{type:literal}})}if(literal==="date"){return objectJsonSchema({iso:{type:"string",format:"date-time"},timeInMilli:{type:"integer"}})}return null}function objectJsonSchema(properties){return{type:"object",properties,required:Object.keys(properties),additionalProperties:false}}function asObjectOutputSchema(json){if(json["type"]==="object")return json;return isObjectSchema(json,json["$defs"],new Set)?{type:"object",...json}:null}function isObjectSchema(schema,definitions,followedRefs){if(typeof schema!=="object"||schema===null)return false;const node=schema;if(node["type"]==="object")return true;const ref=node["$ref"];if(typeof ref==="string"){if(!ref.startsWith(DEFINITION_REF_PREFIX)||followedRefs.has(ref))return false;const definition=definitions?.[ref.slice(DEFINITION_REF_PREFIX.length)];return isObjectSchema(definition,definitions,new Set([...followedRefs,ref]))}const members=node["anyOf"]??node["oneOf"];return Array.isArray(members)&&members.length>0&&members.every(member=>isObjectSchema(member,definitions,followedRefs))}var PRIMITIVE_ZOD_OUTPUT_TYPES,DEFINITION_REF_PREFIX,ToolEntry;var init_tool_entry=__esm({"libs/sdk/src/common/entries/tool.entry.ts"(){"use strict";init_base_entry();PRIMITIVE_ZOD_OUTPUT_TYPES=new Set(["string","number","boolean","bigint","date"]);DEFINITION_REF_PREFIX="#/$defs/";ToolEntry=class extends BaseEntry{owner;name;fullName;inputSchema;rawInputSchema;outputSchema;rawOutputSchema;getOutputSchema(){return this.outputSchema}getRawOutputSchema(){return this.rawOutputSchema}_cachedInputJsonSchema;getInputJsonSchema(){if(this._cachedInputJsonSchema!==void 0)return this._cachedInputJsonSchema;const result=this.computeInputJsonSchema();this._cachedInputJsonSchema=result;return result}computeInputJsonSchema(){if(this.rawInputSchema){if(typeof this.rawInputSchema==="object"&&this.rawInputSchema!==null&&!Array.isArray(this.rawInputSchema)){return this.rawInputSchema}}if(this.inputSchema&&Object.keys(this.inputSchema).length>0){try{return toJSONSchema8(z152.object(this.inputSchema),{io:"input",unrepresentable:"any"})}catch(error){if(isDebug3()||isDevelopment6()){console.warn("[ToolEntry] Failed to convert Zod schema to JSON Schema:",error)}return{type:"object",properties:{}}}}return null}outputJsonSchemaResolution;getOutputJsonSchema(){return this.resolveOutputJsonSchema().schema}getUnlistedOutputSchemaReason(){return this.resolveOutputJsonSchema().unlistedReason}resolveOutputJsonSchema(){this.outputJsonSchemaResolution??=this.computeOutputJsonSchema();return this.outputJsonSchemaResolution}computeOutputJsonSchema(){if(typeof this.rawOutputSchema==="object"&&this.rawOutputSchema!==null&&!Array.isArray(this.rawOutputSchema)){return{schema:this.rawOutputSchema}}const schema=this.outputSchema;if(typeof schema==="string"){return{schema:literalOutputJsonSchema(schema)}}if(!schema||Array.isArray(schema)){return{schema:null}}const isZodSchema=typeof schema.safeParse==="function"&&typeof schema.parse==="function";if(!isZodSchema&&Object.keys(schema).length===0){return{schema:null}}if(isZodSchema&&PRIMITIVE_ZOD_OUTPUT_TYPES.has(schema.type)){return{schema:null}}try{const zodSchema=isZodSchema?schema:z152.object(schema);const objectSchema=asObjectOutputSchema(toJSONSchema8(zodSchema));return objectSchema?{schema:objectSchema}:{schema:null,unlistedReason:"it is not an object schema or a union of object schemas"}}catch(error){const message=error instanceof Error?error.message:String(error);return{schema:null,unlistedReason:`it cannot be converted to JSON Schema (${message})`}}}}}});var ResourceEntry;var init_resource_entry=__esm({"libs/sdk/src/common/entries/resource.entry.ts"(){"use strict";init_base_entry();ResourceEntry=class extends BaseEntry{owner;name;fullName;uri;uriTemplate;isTemplate;getArgumentCompleter(_argName){return null}}}});var PromptEntry;var init_prompt_entry=__esm({"libs/sdk/src/common/entries/prompt.entry.ts"(){"use strict";init_base_entry();PromptEntry=class extends BaseEntry{owner;name;fullName}}});var LoggerEntry;var init_logger_entry=__esm({"libs/sdk/src/common/entries/logger.entry.ts"(){"use strict";init_base_entry();LoggerEntry=class extends BaseEntry{}}});var AgentEntry;var init_agent_entry=__esm({"libs/sdk/src/common/entries/agent.entry.ts"(){"use strict";init_base_entry();AgentEntry=class extends BaseEntry{owner;name;fullName;id;inputSchema;rawInputSchema;outputSchema;systemInstructions;getInputSchema(){return this.inputSchema}getOutputSchema(){return this.outputSchema}}}});var SkillEntry;var init_skill_entry=__esm({"libs/sdk/src/common/entries/skill.entry.ts"(){"use strict";init_metadata();init_base_entry();SkillEntry=class extends BaseEntry{owner;name;fullName;getToolRefs(){const tools=this.metadata.tools;if(!tools)return[];return tools.map(t=>normalizeToolRef(t))}getToolNames(){return this.getToolRefs().map(t=>t.name)}getTags(){return this.metadata.tags??[]}isHidden(){return this.metadata.hideFromDiscovery===true}isAlwaysLoaded(){return this.metadata.alwaysLoad===true}getReferencedOperations(){return this.metadata.referencedOperations??[]}isExecutable(){const hasTools=(this.metadata.tools?.length??0)>0;const hasOps=(this.metadata.referencedOperations?.length??0)>0;return hasTools||hasOps}isKnowledgeOnly(){return!this.isExecutable()}getPriority(){return this.metadata.priority??0}getLicense(){return this.metadata.license}getCompatibility(){return this.metadata.compatibility}getSpecMetadata(){return this.metadata.specMetadata}getAllowedTools(){return this.metadata.allowedTools}getResources(){return this.metadata.resources}getSkillPathSegments(){return this.metadata.skillPath&&this.metadata.skillPath.length>0?[...this.metadata.skillPath]:[this.metadata.name]}getSkillPath(){return this.getSkillPathSegments().join("/")}}}});var ChannelEntry;var init_channel_entry=__esm({"libs/sdk/src/common/entries/channel.entry.ts"(){"use strict";init_base_entry();ChannelEntry=class extends BaseEntry{owner;name;fullName;get source(){return this.metadata.source}get twoWay(){return this.metadata.twoWay===true}get staticMeta(){return this.metadata.meta}getTags(){return this.metadata.tags??[]}}}});import{toJSONSchema as toJSONSchema9,internalZ as z153}from"@frontmcp/lazy-zod";function toObjectSchema(schema){const isZodSchema=typeof schema.safeParse==="function";return isZodSchema?schema:z153.object(schema)}function toObjectJsonSchema(schema,io){return toJSONSchema9(toObjectSchema(schema),{io,unrepresentable:"any"})}var EventEntry;var init_event_entry=__esm({"libs/sdk/src/common/entries/event.entry.ts"(){"use strict";init_base_entry();EventEntry=class extends BaseEntry{owner;name;fullName;inputJsonSchema;payloadJsonSchema;getTags(){return this.metadata.tags??[]}getAuthorities(){const declared=this.metadata.authorities;const isUnguarded=declared===void 0||declared===null||declared===false;return isUnguarded?void 0:this.metadata.authorities}getInputJsonSchema(){this.inputJsonSchema??=this.buildInputJsonSchema();return this.inputJsonSchema}getPayloadJsonSchema(){this.payloadJsonSchema??=toObjectJsonSchema(this.metadata.payloadSchema,"output");return this.payloadJsonSchema}parseArguments(args){const{inputSchema:inputSchema53}=this.metadata;const schema=inputSchema53?toObjectSchema(inputSchema53):z153.object({}).strict();return schema.parse(args)}parsePayload(data){return toObjectSchema(this.metadata.payloadSchema).parse(data)}buildInputJsonSchema(){const{inputSchema:inputSchema53}=this.metadata;if(!inputSchema53){return{type:"object",properties:{},additionalProperties:false}}return toObjectJsonSchema(inputSchema53,"input")}}}});var init_entries=__esm({"libs/sdk/src/common/entries/index.ts"(){"use strict";init_base_entry();init_scope_entry();init_flow_entry();init_hook_entry();init_app_entry();init_provider_entry();init_auth_provider_entry();init_plugin_entry();init_adapter_entry();init_tool_entry();init_resource_entry();init_prompt_entry();init_logger_entry();init_agent_entry();init_skill_entry();init_job_entry();init_workflow_entry();init_channel_entry();init_event_entry()}});import{internalZ as z154}from"@frontmcp/lazy-zod";function parseListInput(rawInput,schema,expectedMethod){let method;let params;try{const inputData=schema.parse(rawInput);method=inputData.request.method;params=inputData.request.params??{}}catch(e){throw new InvalidInputError("Invalid request format",e instanceof z154.ZodError?e.issues:void 0)}if(method!==expectedMethod){throw new InvalidMethodError(method,expectedMethod)}return{cursor:params?.["cursor"],params}}function resolveNameConflicts(entries,getBaseName){const counts=new Map;for(const{entry}of entries){const baseName=getBaseName(entry);counts.set(baseName,(counts.get(baseName)??0)+1)}const conflicts=new Set([...counts.entries()].filter(([,n])=>n>1).map(([k])=>k));return entries.map(({ownerName,entry})=>{const baseName=getBaseName(entry);const finalName=conflicts.has(baseName)?`${ownerName}:${baseName}`:baseName;return{ownerName,entry,finalName}})}function previewItems(items,getName,n=5){const names=items.slice(0,n).map(getName);const preview=names.join(", ");const extra=items.length>n?`, +${items.length-n} more`:"";return`${preview}${extra}`}function detectConflicts(entries,getBaseName){const counts=new Map;for(const entry of entries){const baseName=getBaseName(entry);counts.set(baseName,(counts.get(baseName)??0)+1)}const conflictNames=[...counts.entries()].filter(([,n])=>n>1).map(([k])=>k);return{count:conflictNames.length,names:conflictNames}}var init_flow_utils3=__esm({"libs/sdk/src/common/flow/flow.utils.ts"(){"use strict";init_errors()}});var ToolHookStage;var init_tool_hook_interface=__esm({"libs/sdk/src/common/interfaces/tool-hook.interface.ts"(){"use strict";ToolHookStage=(ToolHookStage2=>{ToolHookStage2["willBindProviders"]="willBindProviders";ToolHookStage2["willCreateInvokeContext"]="willCreateInvokeContext";ToolHookStage2["didCreateInvokeContext"]="didCreateInvokeContext";ToolHookStage2["willAuthorize"]="willAuthorize";ToolHookStage2["willCheckConsent"]="willCheckConsent";ToolHookStage2["willCheckFeatureFlags"]="willCheckFeatureFlags";ToolHookStage2["willAcquireQuota"]="willAcquireQuota";ToolHookStage2["didReleaseQuota"]="didReleaseQuota";ToolHookStage2["willAcquireSemaphore"]="willAcquireSemaphore";ToolHookStage2["didReleaseSemaphore"]="didReleaseSemaphore";ToolHookStage2["willParseInput"]="willParseInput";ToolHookStage2["willValidateInput"]="willValidateInput";ToolHookStage2["willNormalizeInput"]="willNormalizeInput";ToolHookStage2["willRedactInput"]="willRedactInput";ToolHookStage2["willInjectSecrets"]="willInjectSecrets";ToolHookStage2["willReadCache"]="willReadCache";ToolHookStage2["didCacheHit"]="didCacheHit";ToolHookStage2["didCacheMiss"]="didCacheMiss";ToolHookStage2["willWriteCache"]="willWriteCache";ToolHookStage2["aroundExecute"]="aroundExecute";ToolHookStage2["willExecute"]="willExecute";ToolHookStage2["didExecute"]="didExecute";ToolHookStage2["willRedactOutput"]="willRedactOutput";ToolHookStage2["willValidateOutput"]="willValidateOutput";ToolHookStage2["willTransformOutput"]="willTransformOutput";ToolHookStage2["onRetry"]="onRetry";ToolHookStage2["onGiveUp"]="onGiveUp";ToolHookStage2["willAudit"]="willAudit";ToolHookStage2["didAudit"]="didAudit";ToolHookStage2["onMetrics"]="onMetrics";ToolHookStage2["onError"]="onError";ToolHookStage2["willFinalizeInvoke"]="willFinalizeInvoke";return ToolHookStage2})(ToolHookStage||{})}});var SessionHookStage;var init_session_hook_interface=__esm({"libs/sdk/src/common/interfaces/session-hook.interface.ts"(){"use strict";SessionHookStage=(SessionHookStage2=>{SessionHookStage2["willCreateSession"]="willCreateSession";SessionHookStage2["didCreateSession"]="didCreateSession";SessionHookStage2["willBindProviders"]="willBindProviders";SessionHookStage2["willBeginAuth"]="willBeginAuth";SessionHookStage2["willAuthorize"]="willAuthorize";SessionHookStage2["willExchangeToken"]="willExchangeToken";SessionHookStage2["didIssueSecureJwt"]="didIssueSecureJwt";SessionHookStage2["willStoreTokens"]="willStoreTokens";SessionHookStage2["willGetSession"]="willGetSession";SessionHookStage2["didGetSession"]="didGetSession";SessionHookStage2["willDisposeSession"]="willDisposeSession";SessionHookStage2["didDisposeSession"]="didDisposeSession";SessionHookStage2["willFinalize"]="willFinalize";SessionHookStage2["onError"]="onError";SessionHookStage2["willAudit"]="willAudit";SessionHookStage2["didAudit"]="didAudit";SessionHookStage2["onMetrics"]="onMetrics";return SessionHookStage2})(SessionHookStage||{})}});var AuthHookStage;var init_auth_hook_interface=__esm({"libs/sdk/src/common/interfaces/auth-hook.interface.ts"(){"use strict";AuthHookStage=(AuthHookStage2=>{AuthHookStage2["willCreateSession"]="willCreateSession";AuthHookStage2["didCreateSession"]="didCreateSession";AuthHookStage2["willBindProviders"]="willBindProviders";AuthHookStage2["willBeginAuth"]="willBeginAuth";AuthHookStage2["willAuthorize"]="willAuthorize";AuthHookStage2["willExchangeToken"]="willExchangeToken";AuthHookStage2["didIssueSecureJwt"]="didIssueSecureJwt";AuthHookStage2["willStoreTokens"]="willStoreTokens";AuthHookStage2["willGetSession"]="willGetSession";AuthHookStage2["didGetSession"]="didGetSession";AuthHookStage2["willDisposeSession"]="willDisposeSession";AuthHookStage2["didDisposeSession"]="didDisposeSession";AuthHookStage2["willFinalize"]="willFinalize";AuthHookStage2["onError"]="onError";AuthHookStage2["willAudit"]="willAudit";AuthHookStage2["didAudit"]="didAudit";AuthHookStage2["onMetrics"]="onMetrics";return AuthHookStage2})(AuthHookStage||{})}});var BaseConfig;var init_base_config_provider=__esm({"libs/sdk/src/common/providers/base-config.provider.ts"(){"use strict";init_errors();BaseConfig=class{config;constructor(config){this.config=config}getAll(){return this.config}get(path4,defaultValue){const keys=path4.split(".");let result=this.config;for(const key of keys){if(result&&typeof result==="object"&&key in result){result=result[key]}else{return defaultValue!==void 0?defaultValue:void 0}}const value=result;return value!==void 0?value:defaultValue!==void 0?defaultValue:void 0}has(path4){const keys=path4.split(".");let result=this.config;for(const key of keys){if(result&&typeof result==="object"&&key in result){result=result[key]}else{return false}}return result!==void 0}getOrDefault(path4,defaultValue){const value=this.get(path4);return value!==void 0?value:defaultValue}getRequired(path4){const value=this.get(path4);if(value===void 0){throw new RequiredConfigUndefinedError(path4)}return value}getOrThrow(path4){return this.getRequired(path4)}getSection(section){return this.config[section]}matches(path4,value){return this.get(path4)===value}getMany(paths){const result={};for(const path4 of paths){result[path4]=this.get(path4)}return result}toJSON(){return this.config}toString(){return JSON.stringify(this.config,null,2)}}}});var init_common=__esm({"libs/sdk/src/common/index.ts"(){"use strict";init_decorators();init_types();init_metadata();init_interfaces2();init_tokens();init_dynamic();init_records();init_entries();init_utils3();init_schemas();init_flow_utils3();init_tool_hook_interface();init_session_hook_interface();init_auth_hook_interface();init_base_config_provider()}});init_common();import"reflect-metadata";init_front_mcp();init_front_mcp_tokens2();init_static_startup_check();init_optional_dependency_util();init_browser_stores();init_serverless_handler();init_common();init_answer();init_surface();init_materialized_resource_context();init_mcp_error();init_browser_stores();import{z as z155}from"@frontmcp/lazy-zod";import{createChangeFeed as createChangeFeed2,createStorage as createStorage10}from"@frontmcp/utils";var STORAGE_TYPES=["memory","redis","sqlite"];var resourceStoreOptionsSchema=z155.object({storage:z155.object({type:z155.enum(STORAGE_TYPES)}).passthrough().optional(),pollIntervalMs:z155.number().int().positive().optional(),coalesceMs:z155.number().int().nonnegative().optional(),onError:z155.custom(value=>typeof value==="function").optional()}).strict();var NAMESPACE="frontmcp-resources";var ResourceStore=class{constructor(options={}){this.options=options}options;opened;connections=0;backend={storage:async()=>(await this.open()).storage,reportError:error=>this.options.onError?.(error)};key(name59,options={}){if(typeof name59!=="string"||name59.length===0){throw new InvalidResourceStoreError('a key needs a name, such as key("board")')}let initialRecord;try{initialRecord=JSON.stringify({value:options.initial,revision:0})}catch(error){const reason=error instanceof Error?error.message:String(error);throw new InvalidResourceStoreError(`the initial value of key "${name59}" cannot be stored as JSON: ${reason}`)}return new StoredResourceKey(this,this.backend,name59,initialRecord)}subscribe(topic,listener){let stopped=false;let unsubscribe;this.open().then(({feed})=>{if(!stopped)unsubscribe=feed.subscribe(topic,listener)},error=>this.backend.reportError(error));return()=>{stopped=true;unsubscribe?.()}}async publish(topic){const{feed}=await this.open();await feed.publish(topic)}async connect(){this.connections++;try{await this.open()}catch(error){this.connections--;throw error}}async close(){if(this.connections>1){this.connections--;return}this.connections=0;const opened=this.opened;this.opened=void 0;if(!opened)return;const{feed,root}=await opened.catch(()=>({feed:void 0,root:void 0}));await feed?.close();await root?.disconnect()}open(){if(!this.opened){const opening=this.openStorage();opening.catch(()=>{if(this.opened===opening)this.opened=void 0});this.opened=opening}return this.opened}async openStorage(){const{storage={type:"memory"},pollIntervalMs,coalesceMs}=this.options;refuseServerStoresInBrowser({resourceStore:storage.type==="memory"?void 0:`storage: { type: '${storage.type}' }`});const root=await createStorage10({fallback:"error",...storage});const namespaced=root.namespace(NAMESPACE);const feed=createChangeFeed2(namespaced,{pollIntervalMs,coalesceMs,onError:error=>this.backend.reportError(error)});return{root,storage:namespaced,feed}}};var StoredResourceKey=class{constructor(store,backend,name59,initialRecord){this.store=store;this.backend=backend;this.name=name59;this.initialRecord=initialRecord;this.recordKey=`value:${name59}`}store;backend;name;initialRecord;recordKey;async get(){const storage=await this.backend.storage();return this.parse(await storage.get(this.recordKey))}set(value){return this.update(()=>value)}async update(change){const storage=await this.backend.storage();for(;;){const raw=await storage.get(this.recordKey);if(raw===null){await storage.set(this.recordKey,this.initialRecord,{ifNotExists:true});continue}const current=this.parse(raw);const next=JSON.stringify({value:await change(current.value),revision:current.revision+1,updatedAt:new Date().toISOString()});if(await storage.setIfEquals(this.recordKey,raw,next)){await this.store.publish(this.name).catch(error=>this.backend.reportError(error));return this.parse(next)}}}subscribe(listener){let active=true;let seen=this.get().then(snapshot=>snapshot.revision,()=>-1);const check=async revision=>{if(!active)return revision;let snapshot;try{snapshot=await this.get()}catch(error){this.backend.reportError(error);return revision}if(!active||snapshot.revision===revision)return snapshot.revision;try{listener(snapshot)}catch(error){this.backend.reportError(error)}return snapshot.revision};const stop=this.store.subscribe(this.name,()=>{seen=seen.then(check)});return()=>{active=false;stop()}}parse(raw){const record=JSON.parse(raw??this.initialRecord);return record.updatedAt===void 0?{value:record.value,revision:record.revision}:{value:record.value,revision:record.revision,updatedAt:record.updatedAt}}};function resourceStore(options={}){const parsed=resourceStoreOptionsSchema.safeParse(options);if(!parsed.success){const problems=parsed.error.issues.map(issue=>`${issue.path.join(".")||"options"}: ${issue.message}`);throw new InvalidResourceStoreError(problems.join("; "))}return new ResourceStore(options)}init_errors();init_hook_observers();init_elicitation_types();init_elicitation_fallback_schema();init_storage_elicitation_store();init_encrypted_elicitation_store();init_elicitation_encryption();init_elicitation_store_factory();init_helpers();init_question_inbox_routes();init_question_subject();init_question_store_factory();init_question_store();init_question_scope_helper();init_question_errors();init_task_types();init_storage_task_store();init_task_store_factory();init_task_registry();init_task_scope_helper();init_task_notifier();init_task_id();init_task_runner();init_in_process_task_runner();init_cli_task_runner();init_process_liveness();init_execute_task_flag();init_tasks_get_flow();init_tasks_result_flow();init_tasks_cancel_flow();init_tasks_list_flow();init_logger_registry();export*from"@frontmcp/guard";init_mcp_client_service();init_cache();init_resilience();init_factories();init_package_specifier();init_esm_auth_types();init_semver_utils();init_esm_cache();init_esm_manifest();init_version_resolver();init_esm_module_loader();init_version_poller();init_esm_context_factories();init_esm_record_builders();init_prompt_instance();init_resource_instance();init_tool_instance();init_esm_record_builders();function createEsmToolInstance(tool,providers,owner,namespace){const record=buildEsmToolRecord(tool,namespace);return new ToolInstance(record,providers,owner)}function createEsmResourceInstance(resource,providers,owner,namespace){const record=buildEsmResourceRecord(resource,namespace);return new ResourceInstance(record,providers,owner)}function createEsmPromptInstance(prompt,providers,owner,namespace){const record=buildEsmPromptRecord(prompt,namespace);return new PromptInstance(record,providers,owner)}init_mcp_stateless_client_adapter();init_job_registry();init_job_instance();init_job_events();init_job_utils();init_job_permission_guard();init_job_admission();init_job_run_access();init_job_run_resource();init_job_scope_helper();init_job_execution_manager();init_list_jobs_tool();init_execute_job_tool();init_get_job_status_tool();init_cancel_job_tool();init_register_job_tool();init_remove_job_tool();init_update_job_tool();init_workflow_registry();init_workflow_instance();init_workflow_events2();init_workflow_utils();init_workflow_engine();init_workflow_step_executor();init_list_workflows_tool();init_execute_workflow_tool();init_get_workflow_status_tool();init_register_workflow_tool();init_remove_workflow_tool();init_update_workflow_tool();init_streamable_http_transport();init_sse_transport();init_node_sse_transport();init_event_stores();init_channel_instance();init_channel_registry();init_channel_events();init_channel_notification_service();init_app_event_source();init_channel_reply_tool();init_event_instance();init_event_registry();init_context();init_tool_registry();init_tool_instance();init_provider_registry();import{default as default9}from"@frontmcp/lazy-zod";import{z as z158,eagerZ,lazyZ,isLazy,forceMaterialize,LazyZodSchema,toJSONSchema as toJSONSchema10,NEVER as NEVER2,ZodAny,ZodArray,ZodBigInt as ZodBigInt2,ZodBoolean as ZodBoolean2,ZodDate as ZodDate2,ZodDefault,ZodDiscriminatedUnion,ZodEnum,ZodError,ZodIntersection,ZodLiteral,ZodNever,ZodNull,ZodNullable,ZodNumber as ZodNumber2,ZodObject,ZodOptional,ZodRecord,ZodString as ZodString2,ZodSymbol,ZodTuple,ZodType,ZodUndefined,ZodUnion,ZodUnknown,ZodVoid}from"@frontmcp/lazy-zod";init_app_utils();init_common();init_errors();init_front_mcp_tokens2();init_logger_registry();init_provider_registry();import{isClass as isClass21}from"@frontmcp/di";import{z as z156}from"@frontmcp/lazy-zod";var createContainerOptionsSchema=z156.object({providers:z156.array(annotatedFrontMcpProvidersSchema).optional().default([]),apps:z156.array(annotatedFrontMcpAppSchema).optional().default([]),logging:loggingOptionsSchema.optional(),lifecycle:lifecycleOptionsSchema.optional(),runBackground:z156.boolean({message:"runBackground must be true or false"}).optional(),runDuties:z156.boolean({message:"runDuties must be true or false"}).optional(),info:z156.object({name:z156.string().min(1,"info.name must not be empty")}).optional(),redis:redisOptionsSchema.optional()}).superRefine(({runBackground,runDuties,info},context)=>{const asked=runBackground?"runBackground":runDuties?"runDuties":void 0;if(asked===void 0||info!==void 0)return;const message=`${asked} needs info.name: duties and workers share their leases by server name`;context.addIssue({code:"custom",path:["info"],message})});async function createContainer(options){const{providers,apps,logging,lifecycle,...parsed}=createContainerOptionsSchema.parse(options);const runBackground=parsed.runBackground===true||parsed.runDuties===true;const config={...options,logging,lifecycle,runBackground};const root=new ProviderRegistry([{name:"frontmcp:config",provide:FrontMcpConfig,useValue:config}],void 0,{shutdownHookTimeoutMs:lifecycle?.shutdownHookTimeoutMs});await root.ready;const loggers=new LoggerRegistry(root);await loggers.ready;const logger=root.get(FrontMcpLogger);const dispose=async()=>{await root.runShutdownHooks(logger);root.dispose()};const registries=[];try{const serverProviders=new ProviderRegistry(providers,root);registries.push(serverProviders);await serverProviders.ready;for(const app of apps.filter(isClass21)){const appProviders=new ProviderRegistry(collectAppMetadata(app).providers??[],serverProviders);registries.push(appProviders);await appProviders.ready}if(runBackground){const{startDuties:startDuties2}=await Promise.resolve().then(()=>(init_duty_lifecycle(),duty_lifecycle_exports));const{startWorkers:startWorkers2}=await Promise.resolve().then(()=>(init_worker_lifecycle(),worker_lifecycle_exports));for(const registry of registries){await startDuties2(registry);await startWorkers2(registry)}}}catch(error){await dispose();throw error}const get=token=>{let missing;for(const registry of registries){try{return registry.get(token)}catch(error){if(!(error instanceof ProviderNotAvailableError))throw error;missing=error}}throw missing};const tryGet=token=>{try{return get(token)}catch(error){if(error instanceof ProviderNotAvailableError)return void 0;throw error}};return{get,tryGet,dispose}}init_store_provider();init_common();init_store_provider();init_browser_stores();import{createStorage as createStorage11}from"@frontmcp/utils";var SqliteStorageToken=Symbol.for("frontmcp:storage.sqlite");function sqliteStorageProvider(options){const{prefix,provide=SqliteStorageToken,...sqlite}=options;return storeProvider({name:"storage.sqlite",scope:ProviderScope2.GLOBAL,provide,inject:()=>[],useFactory:async()=>{refuseServerStoresInBrowser({sqliteStorage:"sqliteStorageProvider()"});const storage=await createStorage11({type:"sqlite",sqlite,prefix,fallback:"error"});return Object.assign(storage,{onShutdown:()=>storage.disconnect()})}})}init_detached_job_flag();init_event_client();import{EVENTS_EXTENSION_ID as EVENTS_EXTENSION_ID2}from"@frontmcp/protocol";init_skill_registry();init_skill_instance();init_skill_events();init_memory_skill_provider();init_errors();init_skill_hash();function createEmptySyncState(){return{version:1,lastFullSync:0,entries:new Map}}var ExternalSkillProviderBase=class{type="external";mode;syncState=null;syncStateStore;logger;defaultTopK;defaultMinScore;initialized=false;constructor(options){this.mode=options.mode;this.syncStateStore=options.syncStateStore;this.logger=options.logger;this.defaultTopK=options.defaultTopK??10;this.defaultMinScore=options.defaultMinScore??.1;if(this.mode==="persistent"&&!this.syncStateStore){this.logger?.warn("[ExternalSkillProvider] Persistent mode without syncStateStore - sync state will not persist across restarts")}}async initialize(){if(this.initialized){return}if(this.mode==="persistent"&&this.syncStateStore){this.syncState=await this.syncStateStore.load();this.logger?.debug("[ExternalSkillProvider] Loaded sync state",{entriesCount:this.syncState?.entries.size??0,lastFullSync:this.syncState?.lastFullSync??"never"})}this.initialized=true;this.logger?.info("[ExternalSkillProvider] Initialized",{mode:this.mode})}async search(query,options){return this.searchExternal(query,{...options,topK:options?.topK??this.defaultTopK,minScore:options?.minScore??this.defaultMinScore})}async load(skillId){const skill=await this.fetchSkill(skillId);if(!skill){return null}const toolNames=skill.tools.map(t=>t.name);return{skill,availableTools:toolNames,missingTools:[],isComplete:true}}async list(options){const skills=await this.fetchSkills(options);const total=await this.countExternal({tags:options?.tags,includeHidden:options?.includeHidden});const offset=options?.offset??0;const limit=options?.limit??50;return{skills:skills.map(s=>this.skillToMetadata(s)),total,hasMore:offset+skills.length<total}}async exists(skillId){return this.existsExternal(skillId)}async count(options){return this.countExternal(options)}async dispose(){this.initialized=false;this.syncState=null;this.logger?.debug("[ExternalSkillProvider] Disposed")}async syncSkills(localSkills){if(this.mode!=="persistent"){throw new PublicMcpError("[ExternalSkillProvider] syncSkills is only available in persistent mode",String(MCP_ERROR_CODES.INVALID_REQUEST),400)}if(!this.syncState){await this.initialize()}const startTime=Date.now();this.logger?.info("[ExternalSkillProvider] Starting skill sync",{skillCount:localSkills.length});const prevState=this.syncState??createEmptySyncState();const newState=createEmptySyncState();newState.version=prevState.version;const added=[];const updated=[];const unchanged=[];const removed=[];const failed=[];const currentIds=new Set(localSkills.map(s=>s.id));for(const skill of localSkills){const hash=computeSkillHash(skill);const prevEntry=prevState.entries.get(skill.id);try{if(!prevEntry){await this.upsertSkill(skill);added.push(skill.id);this.logger?.debug("[ExternalSkillProvider] Added skill",{skillId:skill.id})}else if(prevEntry.hash!==hash){await this.upsertSkill(skill);updated.push(skill.id);this.logger?.debug("[ExternalSkillProvider] Updated skill",{skillId:skill.id})}else{unchanged.push(skill.id)}const entry={skillId:skill.id,hash,lastSyncedAt:Date.now(),status:"synced",externalId:prevEntry?.externalId};newState.entries.set(skill.id,entry)}catch(error){const errorMsg=error instanceof Error?error.message:String(error);failed.push({skillId:skill.id,error:errorMsg});const entry={skillId:skill.id,hash,lastSyncedAt:prevEntry?.lastSyncedAt??0,status:"failed",error:errorMsg};newState.entries.set(skill.id,entry);this.logger?.error("[ExternalSkillProvider] Failed to sync skill",{skillId:skill.id,error:errorMsg})}}for(const[skillId,entry]of prevState.entries){if(!currentIds.has(skillId)){try{await this.deleteSkill(skillId);removed.push(skillId);this.logger?.debug("[ExternalSkillProvider] Removed skill",{skillId})}catch(error){const errorMsg=error instanceof Error?error.message:String(error);failed.push({skillId,error:errorMsg});newState.entries.set(skillId,{...entry,status:"failed",error:errorMsg});this.logger?.error("[ExternalSkillProvider] Failed to remove skill",{skillId,error:errorMsg})}}}newState.lastFullSync=Date.now();this.syncState=newState;if(this.syncStateStore){await this.syncStateStore.save(newState)}const durationMs=Date.now()-startTime;this.logger?.info("[ExternalSkillProvider] Skill sync complete",{added:added.length,updated:updated.length,unchanged:unchanged.length,removed:removed.length,failed:failed.length,durationMs});return{added,updated,unchanged,removed,failed,durationMs}}getSyncState(){if(!this.syncState){return null}const clonedEntries=new Map([...this.syncState.entries].map(([key,value])=>[key,{...value}]));return{...this.syncState,entries:clonedEntries}}async clearSyncState(){this.syncState=null;if(this.syncStateStore){await this.syncStateStore.clear()}this.logger?.info("[ExternalSkillProvider] Sync state cleared")}isReadOnly(){return this.mode==="read-only"}isPersistent(){return this.mode==="persistent"}skillToMetadata(skill){return{id:skill.id,name:skill.name,description:skill.description,instructions:skill.instructions,tools:skill.tools.map(t=>{if(t.purpose||t.required){return{name:t.name,...t.purpose&&{purpose:t.purpose},...t.required&&{required:t.required}}}return t.name}),parameters:skill.parameters,examples:skill.examples}}};init_skill_validator();init_errors();init_memory_skill_provider();init_skill_validator();function createSkillStorageProvider(options={}){const{provider:providerType="memory",memory,externalProvider,toolRegistry,logger}=options;let toolValidator;if(toolRegistry){toolValidator=new SkillToolValidator(toolRegistry)}let provider;let type;let extProvider;switch(providerType){case"external":{if(!externalProvider){logger?.error("[SkillStorageFactory] External provider type requires externalProvider instance to be passed");throw new PublicMcpError("External provider type requires externalProvider instance. Create a class extending ExternalSkillProviderBase and pass it via externalProvider option.",String(MCP_ERROR_CODES.INVALID_PARAMS),500)}provider=externalProvider;extProvider=externalProvider;type="external";logger?.debug("[SkillStorageFactory] Using external skill provider",{mode:externalProvider.isReadOnly()?"read-only":"persistent"});break}case"vectordb":{try{logger?.warn("[SkillStorageFactory] VectorDB provider not yet implemented, falling back to memory provider");provider=new MemorySkillProvider({...memory,toolValidator});type="memory"}catch(error){logger?.warn("[SkillStorageFactory] Failed to create VectorDB provider, falling back to memory",{error:error instanceof Error?error.message:String(error)});provider=new MemorySkillProvider({...memory,toolValidator});type="memory"}break}case"memory":default:{provider=new MemorySkillProvider({...memory,toolValidator});type="memory";break}}logger?.debug("[SkillStorageFactory] Created skill storage provider",{type,hasToolValidator:!!toolValidator,hasExternalProvider:!!extProvider});return{provider,type,toolValidator,externalProvider:extProvider}}function createMemorySkillProvider(options={}){const{toolRegistry,defaultTopK,defaultMinScore,logger}=options;let toolValidator;if(toolRegistry){toolValidator=new SkillToolValidator(toolRegistry)}const provider=new MemorySkillProvider({defaultTopK,defaultMinScore,toolValidator});logger?.debug("[SkillStorageFactory] Created explicit memory skill provider");return{provider,type:"memory",toolValidator}}init_skill_utils();init_skill_metadata();import{basename as basename3,fileExists as fileExists7,isAbsolute as isAbsolute5,pathJoin as pathJoin4,pathResolve as pathResolve8,readdir as readdir2,readFile as readFile8,realpath as realpath6,stat as stat7}from"@frontmcp/utils";init_caller_dir_utils();init_sdk_errors();init_skill_md_parser();async function scanSkillResources(dirPath){const resources={};const scriptsPath=pathJoin4(dirPath,"scripts");const referencesPath=pathJoin4(dirPath,"references");const assetsPath=pathJoin4(dirPath,"assets");const examplesPath=pathJoin4(dirPath,"examples");const checks=await Promise.all([checkDirectory(scriptsPath),checkDirectory(referencesPath),checkDirectory(assetsPath),checkDirectory(examplesPath),fileExists7(pathJoin4(dirPath,"SKILL.md"))]);if(checks[0])resources.scripts=scriptsPath;if(checks[1])resources.references=referencesPath;if(checks[2])resources.assets=assetsPath;if(checks[3])resources.examples=examplesPath;return{resources,hasSkillMd:checks[4]}}async function checkDirectory(path4){try{const s=await stat7(path4);return s.isDirectory()}catch(err){if(err.code==="ENOENT")return false;throw err}}async function findNestedSkillMd(dirPath,maxDepth=Number.POSITIVE_INFINITY){const found=[];const visited=new Set;async function walk(current,depth2,relPath){if(depth2>maxDepth)return;let entries;try{const realDir=await realpath6(current);if(visited.has(realDir))return;visited.add(realDir);entries=await readdir2(current)}catch(err){if(err.code==="ENOENT")return;throw err}for(const entry of entries){const full=pathJoin4(current,entry);let entryStat;try{entryStat=await stat7(full)}catch(err){if(err.code==="ENOENT")continue;throw err}if(entryStat.isDirectory()){await walk(full,depth2+1,relPath?`${relPath}/${entry}`:entry)}else if(entryStat.isFile()&&entry==="SKILL.md"&&depth2>0){found.push(relPath?`${relPath}/SKILL.md`:"SKILL.md")}}}await walk(dirPath,0,"");return found.sort()}var SKILL_DIRECTORY_LOADER_BASENAMES=["skill-directory-loader.ts","skill-directory-loader.js"];async function resolveSkillDirectory(dirPath,callerDir){if(isAbsolute5(dirPath))return dirPath;const fromCaller=callerDir?pathResolve8(callerDir,dirPath):void 0;if(fromCaller&&await fileExists7(pathJoin4(fromCaller,"SKILL.md")))return fromCaller;const fromCwd=pathResolve8(dirPath);if(await fileExists7(pathJoin4(fromCwd,"SKILL.md")))return fromCwd;return fromCaller??fromCwd}async function loadSkillDirectory(dirPath,logger){return loadResolvedSkillDirectory(await resolveSkillDirectory(dirPath,captureCallerDir(SKILL_DIRECTORY_LOADER_BASENAMES)),logger)}async function loadResolvedSkillDirectory(dirPath,logger){const skillMdPath=pathJoin4(dirPath,"SKILL.md");const exists=await fileExists7(skillMdPath);if(!exists){throw new InvalidSkillError(basename3(dirPath),"SKILL.md not found in directory")}let content;let partialMetadata;try{content=await readFile8(skillMdPath,"utf-8");const{frontmatter,body}=parseSkillMdFrontmatter(content);partialMetadata=skillMdFrontmatterToMetadata(frontmatter,body)}catch(err){const name59=basename3(dirPath);const message=err instanceof Error?err.message:String(err);throw new InvalidSkillError(name59,`Failed to read or parse SKILL.md: ${message}`)}const{resources}=await scanSkillResources(dirPath);const hasResources=resources.scripts||resources.references||resources.assets||resources.examples;if(hasResources){partialMetadata.resources=resources}const nested=await findNestedSkillMd(dirPath);if(nested.length>0){const skillName2=partialMetadata.name??basename3(dirPath);throw new InvalidSkillError(skillName2,`Skill directory contains nested SKILL.md files (forbidden by SEP-2640 \xA7Resource Mapping): ${nested.join(", ")}`)}const dirName=basename3(dirPath);if(partialMetadata.name&&dirName&&partialMetadata.name!==dirName){const msg=`Skill name "${partialMetadata.name}" does not match directory name "${dirName}"`;if(logger){logger.warn(msg,{skillName:partialMetadata.name,dirName})}else{console.warn(msg)}}if(!partialMetadata.name){throw new InvalidSkillError("unknown","SKILL.md is missing required 'name' field in frontmatter")}const skillName=partialMetadata.name;if(!partialMetadata.description){throw new InvalidSkillError(skillName,"SKILL.md is missing required 'description' field in frontmatter")}if(!partialMetadata.instructions){throw new InvalidSkillError(skillName,"SKILL.md has no body content for instructions")}const metadata=partialMetadata;const parsed=skillMetadataSchema.safeParse(metadata);if(!parsed.success){const issues=parsed.error.issues.map(i=>`${i.path.join(".")}: ${i.message}`).join("; ");throw new InvalidSkillError(partialMetadata.name??"unknown",issues)}return{kind:"FILE",provide:Symbol(`skill:${metadata.name}`),metadata:parsed.data,filePath:skillMdPath}}async function skillDir(dirPath,logger){return loadSkillDirectory(dirPath,logger)}init_skill_filter_helper();init_skill_validation_error();init_skill_bundle_not_loaded_error();init_skill_audit_helper();init_skill_instructions_helper();import{sha256Hex as sha256Hex33}from"@frontmcp/utils";var NO_SKILL_CHOICE="__none__";function withoutTrailingSlashes(url){let end=url.length;while(end>0&&url[end-1]==="/")end--;return url.slice(0,end)}function catalogText(candidates){const lines=candidates.map(c=>{const tags=c.tags?.length?` [${c.tags.join(", ")}]`:"";return`- ${c.id}: ${c.name}: ${c.description}${tags}`});return`These are the skills of a server. A skill is a playbook for a kind of task.