@frontmcp/sdk 1.14.0-rc.1 → 1.14.0
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/browser/event/event-gates.mjs +7 -2
- package/browser/index.cjs +9 -4
- package/esm/index.mjs +2 -2
- package/event/event-gates.d.ts +3 -2
- package/event/event-gates.d.ts.map +1 -1
- package/index.js +2 -2
- package/package.json +10 -10
package/index.js
CHANGED
|
@@ -333,7 +333,7 @@ if nodeId == ARGV[1] then
|
|
|
333
333
|
return 1
|
|
334
334
|
end
|
|
335
335
|
return 0
|
|
336
|
-
`;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;this.signingKey=options?.signingKey}redis;machineId;keyPrefix;ttlSeconds;haKeyPrefix;retryAfterSeconds;logger;relay;signingKey;pendingDestroys=new Map;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 requestId=(0,import_utils163.randomUUID)();const confirmed=new Promise(confirm=>this.pendingDestroys.set(requestId,{ownerNodeId:entry.nodeId,confirm}));try{const message={kind:"destroy-session",sessionId:key.sessionId,reason,sourceNodeId:this.machineId,timestamp:Date.now(),requestId};this.signingKey??=deriveChannelKey("relay");const receivers=await(0,import_utils163.publishRedisMessage)(this.redis,entry.channel,signChannelMessage(this.signingKey,message));this.logger?.info("[TransportBus] Sent destroy-remote",{sessionId:key.sessionId.slice(0,20),targetNodeId:entry.nodeId});if(receivers===0){throw new SessionEndUnconfirmedError(entry.nodeId,this.retryAfterSeconds,"no node listens on the session owner's relay channel","not-listening")}if(await this.untilClosed(key.sessionId,confirmed))return;this.logger?.warn("[TransportBus] The session owner did not confirm in time that it closed the session",{sessionId:key.sessionId.slice(0,20),ownerNodeId:entry.nodeId});throw new SessionEndUnconfirmedError(entry.nodeId,this.retryAfterSeconds,`the session owner did not confirm within ${RELEASE_TIMEOUT_MS}ms that it closed the session`,"timed-out")}finally{this.pendingDestroys.delete(requestId)}}handleSessionDestroyed(message){const pending=this.pendingDestroys.get(message.requestId);if(pending&&pending.ownerNodeId===message.sourceNodeId)pending.confirm()}async revokeSession(sessionId){await this.redis.eval(REVOKE_LUA,1,this.busKey(sessionId),this.machineId)}async untilClosed(sessionId,confirmed){let waiting=true;let timer;const revoked=(async()=>{while(waiting){await new Promise(resolve5=>setTimeout(resolve5,RELEASE_POLL_MS));try{if(waiting&&!await this.readEntry(sessionId))return true}catch{}}return false})();const timedOut=new Promise(resolve5=>timer=setTimeout(()=>resolve5(false),RELEASE_TIMEOUT_MS));return Promise.race([confirmed.then(()=>true),revoked,timedOut]).finally(()=>{waiting=false;clearTimeout(timer)})}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}}}});var import_utils164,RedisEventStore;var init_redis_event_store=__esm({"libs/sdk/src/transport/event-stores/redis.event-store.ts"(){"use strict";import_utils164=require("@frontmcp/utils");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{client,owned,kind}=(0,import_utils164.createRedisConnection)({...redisConnectionOfOptions(redis),label:"RedisEventStore",ioredisOptions:{lazyConnect:true,enableReadyCheck:false}});if(kind==="custom"&&(typeof client.xadd!=="function"||typeof client.xrange!=="function")){throw new InternalMcpError("The event store's redis client has no xadd/xrange: give it a client that runs Redis Streams commands.","INVALID_REDIS_CONFIG")}this.client=client;if(owned)await 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}=(0,import_utils50.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}}}}});function sessionIdHash(sessionId){return(0,import_utils165.sha256Hex)(sessionId).slice(0,12)}var import_utils165;var init_session_id_hash=__esm({"libs/sdk/src/logger/session-id-hash.ts"(){"use strict";import_utils165=require("@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 import_utils166,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";import_utils166=require("@frontmcp/utils");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 import_utils166.TypedStorage(storage.namespace("pending"));this.fallback=new import_utils166.TypedStorage(storage.namespace("fallback"));this.resolved=new import_utils166.TypedStorage(storage.namespace("resolved"))}async setPending(record){const{sessionId,expiresAt}=record;const ttlSeconds=(0,import_utils166.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=(0,import_utils166.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});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((0,import_utils167.getEnv)("UPSTASH_REDIS_REST_URL")){return"upstash"}if((0,import_utils167.getEnv)("REDIS_URL")||(0,import_utils167.getEnv)("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: ... }')}finalStorageConfig=redisStorageConfigOf(redisOptions);const{host,port,client}=redisOptions;logger?.debug("[ElicitationStoreFactory] Converted redis option to storage config",{host,port,client:client!==void 0})}const explicitBackend=Boolean(storageConfig||redis);if(finalStorageConfig?.type==="vercel-kv"||!explicitBackend&&(0,import_utils167.getEnv)("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(0,import_utils167.createStorage)({...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=(0,import_utils167.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}=(0,import_utils50.requireOptionalModule)("@frontmcp/storage-sqlite",()=>require_dist());logger?.info("[ElicitationStoreFactory] Creating SQLite elicitation store",{path:sqliteConfig.path,keyPrefix});return new SqliteElicitationStore({...sqliteConfig,keyPrefix})}var import_utils167;var init_elicitation_store_factory=__esm({"libs/sdk/src/elicitation/store/elicitation-store.factory.ts"(){"use strict";import_utils167=require("@frontmcp/utils");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});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 import_utils168,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";import_utils168=require("@frontmcp/utils");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=(0,import_utils168.randomUUID)();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&&(0,import_utils168.expiresAtToTTL)(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,(0,import_utils168.expiresAtToTTL)(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=(0,import_utils168.expiresAtToTTL)(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?(0,import_utils168.expiresAtToTTL)(current.expiresAt):0;if(current&¤tTtl>ttlSeconds)await this.extend(current,currentTtl)}}}});function recordKey(sessionId,taskId){return`${sessionId}:${taskId}`}function slotKey(sessionId,slot){return`${sessionId}:${slot}`}function encodeCursor(offset,source){return(0,import_utils169.base64urlEncode)(new TextEncoder().encode(JSON.stringify({offset,source})))}function decodeCursor(cursor){try{const bytes=(0,import_utils169.base64urlDecode)(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 import_utils169,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";import_utils169=require("@frontmcp/utils");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 import_utils169.TypedStorage(storage.namespace(RECORDS_NAMESPACE));this.slots=storage.namespace(SLOTS_NAMESPACE)}async create(record){const ttlSeconds=(0,import_utils169.expiresAtToTTL)(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=(0,import_utils169.expiresAtToTTL)(record.expiresAt);if(ttlSeconds<=0)return false;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=(0,import_utils169.expiresAtToTTL)(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()}}}});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((0,import_utils170.getEnv)("UPSTASH_REDIS_REST_URL"))return"upstash";if((0,import_utils170.getEnv)("REDIS_URL")||(0,import_utils170.getEnv)("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}=(0,import_utils50.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.")}finalStorageConfig=redisStorageConfigOf(redisOptions)}const explicitBackend=isExplicitStorage(storageConfig)||Boolean(redis);if(finalStorageConfig?.type==="vercel-kv"||!explicitBackend&&(0,import_utils170.getEnv)("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(0,import_utils170.createStorage)({...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=(0,import_utils170.createMemoryStorage)({prefix:keyPrefix});return{store:new StorageTaskStore(storage,logger),type:"memory",storage}}var import_utils170,TaskStoreNotSupportedError;var init_task_store_factory=__esm({"libs/sdk/src/task/store/task-store.factory.ts"(){"use strict";import_utils170=require("@frontmcp/utils");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}}}}});function runTaskInBackground(params){return Promise.resolve().then(()=>(0,import_utils171.runRequestExclusive)(()=>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;markTaskRunContext(taskCtx);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 import_utils171;var init_task_runner=__esm({"libs/sdk/src/task/helpers/task-runner.ts"(){"use strict";import_utils171=require("@frontmcp/utils");init_errors();init_call_tool_error_utils();init_mcp_error_utils();init_task_types();init_task_run_context()}});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")}}}});var import_lazy_zod122,import_protocol68,inputSchema21,outputSchema20,stateSchema25,plan28,name28,Stage28,TasksGetFlow;var init_tasks_get_flow=__esm({"libs/sdk/src/task/flows/tasks-get.flow.ts"(){"use strict";import_lazy_zod122=require("@frontmcp/lazy-zod");import_protocol68=require("@frontmcp/protocol");init_common();init_errors();init_task_types();inputSchema21=import_lazy_zod122.internalZ.object({request:import_protocol68.GetTaskRequestSchema,ctx:import_lazy_zod122.internalZ.any()});outputSchema20=import_protocol68.GetTaskResultSchema;stateSchema25=import_lazy_zod122.internalZ.object({taskId:import_lazy_zod122.internalZ.string(),sessionId:import_lazy_zod122.internalZ.string(),authInfo:import_lazy_zod122.internalZ.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 import_lazy_zod122.internalZ.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)}});var import_lazy_zod123,import_protocol69,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";import_lazy_zod123=require("@frontmcp/lazy-zod");import_protocol69=require("@frontmcp/protocol");init_common();init_errors();init_task_types();inputSchema22=import_lazy_zod123.internalZ.object({request:import_protocol69.GetTaskPayloadRequestSchema,ctx:import_lazy_zod123.internalZ.any()});outputSchema21=import_protocol69.GetTaskPayloadResultSchema;stateSchema26=import_lazy_zod123.internalZ.object({taskId:import_lazy_zod123.internalZ.string(),sessionId:import_lazy_zod123.internalZ.string(),authInfo:import_lazy_zod123.internalZ.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 import_lazy_zod123.internalZ.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((resolve5,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 resolve5(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}}}});var import_lazy_zod124,import_protocol70,inputSchema23,outputSchema22,stateSchema27,plan30,name30,Stage30,TasksCancelFlow;var init_tasks_cancel_flow=__esm({"libs/sdk/src/task/flows/tasks-cancel.flow.ts"(){"use strict";import_lazy_zod124=require("@frontmcp/lazy-zod");import_protocol70=require("@frontmcp/protocol");init_common();init_errors();init_task_types();inputSchema23=import_lazy_zod124.internalZ.object({request:import_protocol70.CancelTaskRequestSchema,ctx:import_lazy_zod124.internalZ.any()});outputSchema22=import_protocol70.CancelTaskResultSchema;stateSchema27=import_lazy_zod124.internalZ.object({taskId:import_lazy_zod124.internalZ.string(),sessionId:import_lazy_zod124.internalZ.string(),authInfo:import_lazy_zod124.internalZ.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 import_lazy_zod124.internalZ.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)}});var import_lazy_zod125,import_protocol71,inputSchema24,outputSchema23,stateSchema28,plan31,name31,Stage31,TasksListFlow;var init_tasks_list_flow=__esm({"libs/sdk/src/task/flows/tasks-list.flow.ts"(){"use strict";import_lazy_zod125=require("@frontmcp/lazy-zod");import_protocol71=require("@frontmcp/protocol");init_common();init_errors();init_task_types();inputSchema24=import_lazy_zod125.internalZ.object({request:import_protocol71.ListTasksRequestSchema,ctx:import_lazy_zod125.internalZ.any()});outputSchema23=import_protocol71.ListTasksResultSchema;stateSchema28=import_lazy_zod125.internalZ.object({sessionId:import_lazy_zod125.internalZ.string(),cursor:import_lazy_zod125.internalZ.string().optional(),authInfo:import_lazy_zod125.internalZ.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 import_lazy_zod125.internalZ.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()}});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=>!(0,import_auth57.isAnonymousSubject)(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 import_auth57;var init_session_scope_identity=__esm({"libs/sdk/src/auth/session-scope-identity.ts"(){"use strict";import_auth57=require("@frontmcp/auth")}});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});function createAuthProvidersProviders(options,store,baseVault=new import_auth58.InMemoryAuthorizationVault){const providers=[];providers.push({provide:import_auth58.AUTH_PROVIDERS_REGISTRY,scope:import_di49.ProviderScope.GLOBAL,name:"AuthProvidersRegistry",useFactory:()=>new import_auth58.AuthProvidersRegistry(options)});providers.push({provide:import_auth58.AUTH_PROVIDERS_VAULT,scope:import_di49.ProviderScope.GLOBAL,name:"AuthProvidersVault",useFactory:logger=>new import_auth58.AuthProvidersVault(store.storage,{namespace:options.namespace,defaultCacheTtl:options.defaultCacheTtl,pepper:store.pepper,logger}),inject:()=>[FrontMcpLogger]});providers.push({provide:CREDENTIAL_CACHE,scope:import_di49.ProviderScope.CONTEXT,name:"CredentialCache",useFactory:()=>new import_auth58.CredentialCache(options.maxCredentialsPerSession??100)});providers.push({provide:LAZY_CREDENTIAL_LOADER,scope:import_di49.ProviderScope.CONTEXT,name:"LazyCredentialLoader",useFactory:logger=>new import_auth58.LazyCredentialLoader(logger),inject:()=>[FrontMcpLogger]});providers.push({provide:import_auth58.AUTH_PROVIDERS_ACCESSOR,scope:import_di49.ProviderScope.CONTEXT,name:"AuthProvidersAccessor",useFactory:(registry,vault,cache2,loader,ctx,logger)=>{const user=ctx.authInfo?.user;const signedIn=user&&!(0,import_auth58.isAnonymousSubject)(user.sub)?user:void 0;const factoryContext={sessionId:sessionScopeIdentity(ctx)??`${import_auth58.UNIDENTIFIED_SESSION_PREFIX}${(0,import_utils172.randomUUID)()}`,userSub:signedIn?.sub,userEmail:signedIn?.email,userName:signedIn?.name,vault:baseVault};return new import_auth58.AuthProvidersAccessorImpl(registry,vault,cache2,loader,factoryContext,logger)},inject:()=>[import_auth58.AUTH_PROVIDERS_REGISTRY,import_auth58.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=(0,import_utils172.getEnv)("VAULT_SECRET")||(0,import_utils172.getEnv)("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(0,import_utils172.createStorage)({type:"memory"});await providers.addDynamicProviders(createAuthProvidersProviders(options,{storage}));return()=>storage.disconnect()}var import_auth58,import_di49,import_utils172,LAZY_CREDENTIAL_LOADER;var init_auth_providers_providers=__esm({"libs/sdk/src/auth/vault/auth-providers.providers.ts"(){"use strict";import_auth58=require("@frontmcp/auth");import_di49=require("@frontmcp/di");import_utils172=require("@frontmcp/utils");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});function defaultLogSinks(){return[{type:(0,import_utils173.getRuntimeContext)().runtime==="browser"?"console":"stdout"}]}function observabilityPlugins({config:observabilityConfig,logger,globalProviders,implied=false}){const plugins=[];let ObservabilityPluginModule;try{ObservabilityPluginModule=(0,import_utils50.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 import_utils173;var init_observability_scope_helper=__esm({"libs/sdk/src/scope/observability-scope.helper.ts"(){"use strict";import_utils173=require("@frontmcp/utils");init_context();init_logger_registry();init_optional_dependency_util();init_tracer_provider_utils()}});var import_lazy_zod126,import_utils174,inputSchema25,outputSchema24,stateSchema29,plan32,name32,Stage32,ElicitationRequestFlow;var init_elicitation_request_flow=__esm({"libs/sdk/src/elicitation/flows/elicitation-request.flow.ts"(){"use strict";import_lazy_zod126=require("@frontmcp/lazy-zod");import_utils174=require("@frontmcp/utils");init_common();init_errors();init_session_id_hash();init_elicitation_types();inputSchema25=import_lazy_zod126.internalZ.object({relatedRequestId:import_lazy_zod126.internalZ.union([import_lazy_zod126.internalZ.string(),import_lazy_zod126.internalZ.number()]),requestId:import_lazy_zod126.internalZ.union([import_lazy_zod126.internalZ.string(),import_lazy_zod126.internalZ.number()]).optional(),sessionId:import_lazy_zod126.internalZ.string(),message:import_lazy_zod126.internalZ.string(),requestedSchema:import_lazy_zod126.internalZ.record(import_lazy_zod126.internalZ.string(),import_lazy_zod126.internalZ.unknown()),options:import_lazy_zod126.internalZ.object({mode:import_lazy_zod126.internalZ.enum(["form","url"]).optional(),ttl:import_lazy_zod126.internalZ.number().optional(),elicitationId:import_lazy_zod126.internalZ.string().optional(),url:import_lazy_zod126.internalZ.string().optional()}).optional()});outputSchema24=import_lazy_zod126.internalZ.object({elicitId:import_lazy_zod126.internalZ.string(),sessionId:import_lazy_zod126.internalZ.string(),expiresAt:import_lazy_zod126.internalZ.number(),mode:import_lazy_zod126.internalZ.enum(["form","url"]),requestParams:import_lazy_zod126.internalZ.record(import_lazy_zod126.internalZ.string(),import_lazy_zod126.internalZ.unknown()),pendingRecord:import_lazy_zod126.internalZ.any()});stateSchema29=import_lazy_zod126.internalZ.object({relatedRequestId:import_lazy_zod126.internalZ.union([import_lazy_zod126.internalZ.string(),import_lazy_zod126.internalZ.number()]),requestId:import_lazy_zod126.internalZ.union([import_lazy_zod126.internalZ.string(),import_lazy_zod126.internalZ.number()]).optional(),sessionId:import_lazy_zod126.internalZ.string(),message:import_lazy_zod126.internalZ.string(),requestedSchema:import_lazy_zod126.internalZ.record(import_lazy_zod126.internalZ.string(),import_lazy_zod126.internalZ.unknown()),mode:import_lazy_zod126.internalZ.enum(["form","url"]).default("form"),ttl:import_lazy_zod126.internalZ.number().default(DEFAULT_ELICIT_TTL),elicitationId:import_lazy_zod126.internalZ.string().optional(),url:import_lazy_zod126.internalZ.string().optional(),elicitId:import_lazy_zod126.internalZ.string(),expiresAt:import_lazy_zod126.internalZ.number(),pendingRecord:import_lazy_zod126.internalZ.any().optional(),requestParams:import_lazy_zod126.internalZ.record(import_lazy_zod126.internalZ.string(),import_lazy_zod126.internalZ.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,...input.requestId===void 0?{}:{requestId:input.requestId},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-${(0,import_utils174.randomUUID)()}`;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{requestId}=this.state;const store=this.scope.elicitationStore;if(!store){throw new ElicitationStoreNotInitializedError}const pendingRecord={elicitId,sessionId,createdAt:Date.now(),expiresAt,message,mode,requestedSchema,...requestId===void 0?{}:{requestId}};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)}});var import_lazy_zod127,inputSchema26,outputSchema25,stateSchema30,plan33,name33,Stage33,ElicitationResultFlow;var init_elicitation_result_flow=__esm({"libs/sdk/src/elicitation/flows/elicitation-result.flow.ts"(){"use strict";import_lazy_zod127=require("@frontmcp/lazy-zod");init_common();init_errors();init_session_id_hash();init_helpers();inputSchema26=import_lazy_zod127.internalZ.object({sessionId:import_lazy_zod127.internalZ.string(),requestId:import_lazy_zod127.internalZ.union([import_lazy_zod127.internalZ.string(),import_lazy_zod127.internalZ.number()]).optional(),result:import_lazy_zod127.internalZ.object({action:import_lazy_zod127.internalZ.enum(["accept","cancel","decline"]),content:import_lazy_zod127.internalZ.unknown().optional()})});outputSchema25=import_lazy_zod127.internalZ.object({handled:import_lazy_zod127.internalZ.boolean(),elicitId:import_lazy_zod127.internalZ.string().optional(),result:import_lazy_zod127.internalZ.any().optional()});stateSchema30=import_lazy_zod127.internalZ.object({sessionId:import_lazy_zod127.internalZ.string(),requestId:import_lazy_zod127.internalZ.union([import_lazy_zod127.internalZ.string(),import_lazy_zod127.internalZ.number()]).optional(),action:import_lazy_zod127.internalZ.enum(["accept","cancel","decline"]),content:import_lazy_zod127.internalZ.unknown().optional(),pendingRecord:import_lazy_zod127.internalZ.any().optional(),elicitResult:import_lazy_zod127.internalZ.any().optional(),handled:import_lazy_zod127.internalZ.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,...input.requestId===void 0?{}:{requestId:input.requestId},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{requestId}=this.state;const found=await store.getPending(sessionId);const pendingRecord=found&&(requestId===void 0||found.requestId===requestId)?found:void 0;this.state.set("pendingRecord",pendingRecord);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()}});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=(0,import_utils175.getEnv)(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 import_utils175,SERVER_CARD_MEDIA_TYPE,envVarsReportedInvalid;var init_mcp_registry_utils=__esm({"libs/sdk/src/mcp-registry/mcp-registry.utils.ts"(){"use strict";import_utils175=require("@frontmcp/utils");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)}});function ifNoneMatchIncludes(ifNoneMatch,etag){const candidates=(ifNoneMatch??"").split(",").map(candidate=>candidate.trim().replace(/^W\//,""));return candidates.includes("*")||candidates.includes(etag)}var import_lazy_zod128,import_utils176,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";import_lazy_zod128=require("@frontmcp/lazy-zod");import_utils176=require("@frontmcp/utils");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=import_lazy_zod128.internalZ.object({card:import_lazy_zod128.internalZ.record(import_lazy_zod128.internalZ.string(),import_lazy_zod128.internalZ.unknown())});outputSchema27=import_lazy_zod128.internalZ.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=`"${(0,import_utils176.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)}});function aiCatalogIdentifier(registryName){const[namespace,serverName]=registryName.split("/");return`urn:air:${namespace.split(".").reverse().join(".")}:mcp:${serverName}`}var import_lazy_zod129,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";import_lazy_zod129=require("@frontmcp/lazy-zod");init_common();init_mcp_registry_utils();AI_CATALOG_PATH="/.well-known/ai-catalog.json";inputSchema29=httpInputSchema;outputSchema28=import_lazy_zod129.internalZ.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&®istryOptions.name&®istryOptions.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()}});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 import_utils177,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";import_utils177=require("@frontmcp/utils");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=(0,import_utils177.randomUUID)();const sessionLabel=sessionId.slice(0,20);return new Promise((resolve5,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();resolve5()};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();resolve5()};const onClientClose=()=>{if(done||response.writableFinished)return;done=true;cleanup();this.options.publish(ownerNodeId,{kind:"relay-cancel",requestId,sourceNodeId:this.nodeId}).catch(()=>void 0);resolve5()};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 destroyOnRequest=async message=>{const sessionLabel=message.sessionId.slice(0,20);let held;try{held=await transportService.destroyLocalSession(message.sessionId,message.reason);if(!held)await bus.revokeSession(message.sessionId)}catch(error){logger.warn("[HA] Failed to destroy a session on request of another node",{sessionId:sessionLabel,error:error instanceof Error?error.message:String(error)});return}if(!message.requestId||typeof message.sourceNodeId!=="string")return;try{await haManager.publishToNode(message.sourceNodeId,{kind:"session-destroyed",requestId:message.requestId,sessionId:message.sessionId,held,sourceNodeId:nodeId})}catch(error){logger.warn("[HA] Failed to tell another node a session it asked to close is closed",{sessionId:sessionLabel,error:error instanceof Error?error.message:String(error)})}};const handler=message=>{if(isRequestRelayMessage(message)){relay.handleMessage(message);return}if(message.kind==="destroy-session"){void destroyOnRequest(message);return}if(message.kind==="session-destroyed"){bus.handleSessionDestroyed(message);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(resolve5=>{settleReady=resolve5;const attempt=failures=>{if(closed){resolve5();return}haManager.subscribeRelay(handler).then(()=>{if(closed){resolve5();return}bus.attachRelay(relay);logger.info("[HA] Request relay ready \u2014 sessions owned by other nodes are served through them");resolve5()},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)}}}});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(path7=>path7.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:path7}of(0,import_utils178.watchFiles)(sourceConfig.paths,{events,signal})){const fileEvent={event:REPORTED_EVENTS[type],path:path7};logger.verbose(`File ${fileEvent.event} for channel "${channel2.name}": ${path7}`);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 import_utils178,WATCHED_TYPES,REPORTED_EVENTS;var init_file_watcher_source=__esm({"libs/sdk/src/channel/sources/file-watcher.source.ts"(){"use strict";import_utils178=require("@frontmcp/utils");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)}}}});var import_utils179,ChannelRegistry;var init_channel_registry=__esm({"libs/sdk/src/channel/channel.registry.ts"(){"use strict";import_utils179=require("@frontmcp/utils");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=(0,import_utils179.getRuntimeContext)();for(const token of this.tokens){const rec=this.defs.get(token);if(!rec)continue;if(!(0,import_utils179.isEntryAvailable)(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(name60){return this.localRows.find(r=>r.instance.name===name60)?.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()})}}}});var import_lazy_zod130,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";import_lazy_zod130=require("@frontmcp/lazy-zod");init_common();inputSchema30=import_lazy_zod130.internalZ.object({}).optional();channelInfoSchema=import_lazy_zod130.internalZ.object({name:import_lazy_zod130.internalZ.string(),description:import_lazy_zod130.internalZ.string().optional(),sourceType:import_lazy_zod130.internalZ.string(),twoWay:import_lazy_zod130.internalZ.boolean(),tags:import_lazy_zod130.internalZ.array(import_lazy_zod130.internalZ.string())});outputSchema29=import_lazy_zod130.internalZ.object({channels:import_lazy_zod130.internalZ.array(channelInfoSchema),count:import_lazy_zod130.internalZ.number()});stateSchema32=import_lazy_zod130.internalZ.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)}});var import_lazy_zod131,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";import_lazy_zod131=require("@frontmcp/lazy-zod");init_common();init_errors();init_channel_utils();inputSchema31=import_lazy_zod131.internalZ.object({channelName:import_lazy_zod131.internalZ.string().min(1),content:import_lazy_zod131.internalZ.string().min(1),meta:import_lazy_zod131.internalZ.record(import_lazy_zod131.internalZ.string(),import_lazy_zod131.internalZ.unknown()).optional(),targetSessionId:import_lazy_zod131.internalZ.string().min(1).optional()});outputSchema30=import_lazy_zod131.internalZ.object({sent:import_lazy_zod131.internalZ.boolean(),channelName:import_lazy_zod131.internalZ.string()});stateSchema33=import_lazy_zod131.internalZ.object({channelName:import_lazy_zod131.internalZ.string(),content:import_lazy_zod131.internalZ.string(),meta:import_lazy_zod131.internalZ.record(import_lazy_zod131.internalZ.string(),import_lazy_zod131.internalZ.string()).optional(),targetSessionId:import_lazy_zod131.internalZ.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 import_lazy_zod131.internalZ.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)}});var import_lazy_zod132,channelReplyInputSchema;var init_reply_types=__esm({"libs/sdk/src/channel/reply/reply.types.ts"(){"use strict";import_lazy_zod132=require("@frontmcp/lazy-zod");channelReplyInputSchema={channel_name:import_lazy_zod132.internalZ.string().describe("The name of the channel to reply to"),text:import_lazy_zod132.internalZ.string().describe("The reply text to send back through the channel"),meta:import_lazy_zod132.internalZ.record(import_lazy_zod132.internalZ.string(),import_lazy_zod132.internalZ.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:http5,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=http5?computeReservedPaths(http5.entryPath,http5.routeBase,http5.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(!http5||!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 http5.server.registerRoute("POST",source.path,wrapWithIpFilter(handler,http5.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"}}});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 import_utils180,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";import_utils180=require("@frontmcp/utils");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=`${(0,import_utils180.getMachineId)()}:${(0,import_utils180.randomUUID)()}`;this.logger=options.logger.child("EventOutbox");this.random=options.random??Math.random;const{runtime,deployment}=(0,import_utils180.getRuntimeContext)();this.usesTimers=deployment!=="serverless"&&runtime!=="edge"&&runtime!=="browser"}options;ownerId;logger;random;usesTimers;timers=new Map;inFlight=new Map;waitingForSlot=[];activeAttempts=0;activeByOwner=new Map;sweepTimer;lastSweepAt=0;stopped=false;async enqueue(delivery){const now=Date.now();const record={...delivery,id:`dlv_${(0,import_utils180.randomUUID)()}`,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){const stored=await this.read(id);if(!stored)return;const owner=stored.record.principalKey??`subscription:${stored.record.subscriptionId}`;if(this.hasSlotFor(owner))this.takeSlot(owner);else await new Promise(start=>this.waitingForSlot.push({owner,start}));try{await this.attemptOnce(id)}finally{this.freeSlot(owner)}}hasSlotFor(owner){const{concurrency}=this.options.settings;return this.activeAttempts<concurrency&&(this.activeByOwner.get(owner)??0)<this.slotsPerOwner()}slotsPerOwner(){const{concurrency,concurrencyPerSubscriber}=this.options.settings;return Math.min(concurrency,concurrencyPerSubscriber??Math.max(1,Math.ceil(concurrency/4)))}takeSlot(owner){this.activeAttempts+=1;this.activeByOwner.set(owner,(this.activeByOwner.get(owner)??0)+1)}freeSlot(owner){this.activeAttempts-=1;const held=(this.activeByOwner.get(owner)??1)-1;if(held>0)this.activeByOwner.set(owner,held);else this.activeByOwner.delete(owner);for(let index=0;index<this.waitingForSlot.length;){if(this.activeAttempts>=this.options.settings.concurrency)return;const waiter=this.waitingForSlot[index];if(!this.hasSlotFor(waiter.owner)){index+=1;continue}this.waitingForSlot.splice(index,1);this.takeSlot(waiter.owner);waiter.start()}}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))}}}});function newEventId(){return`evt_${(0,import_utils181.base64urlEncode)((0,import_utils181.randomBytes)(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 import_utils181,EVENT_ID_RANDOM_BYTES,ScopeEventPublisher;var init_event_publisher=__esm({"libs/sdk/src/event/event-publisher.ts"(){"use strict";import_utils181=require("@frontmcp/utils");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()}});function subscriberSummaryOf(subscriber){return{sub:subscriber.sub,...subscriber.iss!==void 0&&{iss:subscriber.iss},...subscriber.tenantId!==void 0&&{tenantId:subscriber.tenantId}}}function callbackHostOf(url){try{return new URL(url).host}catch{return""}}function webhookSubscriptionInfoOf(record){const{lastDeliveryAt,lastError,failedSince,failures,suspendedSince}=record.status;return{id:record.id,eventName:record.eventName,mode:"webhook",principalKey:record.principalKey,subscriber:subscriberSummaryOf(record.subscriber),arguments:record.arguments,dialect:record.dialect,createdAt:record.createdAt,updatedAt:record.updatedAt,expiresAt:record.expiresAt,verifiedAt:record.verifiedAt,lastAuthorizedAt:record.lastAuthorizedAt,active:record.active,delivery:{host:callbackHostOf(record.delivery.url),failures:failures??0,...suspendedSince!==void 0&&{suspendedSince},...lastDeliveryAt!==void 0&&{lastDeliveryAt},...lastError!==void 0&&{lastError},...failedSince!==void 0&&{failedSince}}}}function heldSubscriptionInfoOf(subscription,principalKey,args){return{id:subscription.id,eventName:subscription.name,principalKey,subscriber:subscriberSummaryOf(subscription.subscriber),arguments:args}}var init_event_subscription_info=__esm({"libs/sdk/src/event/event-subscription-info.ts"(){"use strict"}});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())}}}});var import_protocol72,import_utils182,EventRegistry;var init_event_registry=__esm({"libs/sdk/src/event/event.registry.ts"(){"use strict";import_protocol72=require("@frontmcp/protocol");import_utils182=require("@frontmcp/utils");init_common();init_errors();init_regsitry();init_event_subscription_info();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=(0,import_utils182.getRuntimeContext)();for(const[token,record]of this.defs){const eventName=record.metadata.name;if(!(0,import_utils182.isEntryAvailable)(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(name60){return this.eventsByName.get(name60)}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 import_protocol72.EVENT_DELIVERY_MODES.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))}async listSubscriptions(eventName){const listed=[];const store=this.subscriptions?.store;if(store){const eventNames=eventName===void 0?this.getEvents().map(event=>event.name):[eventName];for(const name60 of eventNames){for(const record of await store.listByEvent(name60))listed.push(webhookSubscriptionInfoOf(record))}}listed.push(...this.pollLeases?.list(eventName)??[],...this.streams?.list(eventName)??[]);return listed}getCapabilities(){if(!this.servesEvents())return{};return{events:{},extensions:{[import_protocol72.EVENTS_EXTENSION_ID]:{}}}}}}});function eventOutboundTargetOptions(allowLocal){return(0,import_utils183.isEdgeRuntime)()?{allowLocal,allowPlatformDns:true}:{allowLocal}}var import_utils183;var init_event_outbound=__esm({"libs/sdk/src/event/event-outbound.ts"(){"use strict";import_utils183=require("@frontmcp/utils")}});var import_lazy_zod133,import_protocol73,import_utils184,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";import_lazy_zod133=require("@frontmcp/lazy-zod");import_protocol73=require("@frontmcp/protocol");import_utils184=require("@frontmcp/utils");init_common();init_event_outbound();inputSchema32=import_lazy_zod133.internalZ.object({delivery:import_lazy_zod133.internalZ.any()});outputSchema31=import_lazy_zod133.internalZ.discriminatedUnion("result",[import_lazy_zod133.internalZ.object({result:import_lazy_zod133.internalZ.literal("delivered")}),import_lazy_zod133.internalZ.object({result:import_lazy_zod133.internalZ.literal("dropped"),reason:import_lazy_zod133.internalZ.enum(["gone","refused"])}),import_lazy_zod133.internalZ.object({result:import_lazy_zod133.internalZ.literal("failed"),category:import_protocol73.EventDeliveryErrorCategorySchema}),import_lazy_zod133.internalZ.object({result:import_lazy_zod133.internalZ.literal("waiting")})]);stateSchema34=import_lazy_zod133.internalZ.object({target:import_lazy_zod133.internalZ.any(),subscription:import_lazy_zod133.internalZ.any(),headers:import_lazy_zod133.internalZ.record(import_lazy_zod133.internalZ.string(),import_lazy_zod133.internalZ.string()),answer:import_lazy_zod133.internalZ.any(),outcome:import_lazy_zod133.internalZ.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=[(0,import_utils184.signingKeyOf)(secret)];if(previousSecret!==void 0&&(previousSecretUntil??0)>now){signingKeys.push((0,import_utils184.signingKeyOf)(previousSecret))}const message={id:delivery.webhookId,timestamp:Math.floor(now/1e3),body:delivery.body};this.state.set("headers",{"content-type":"application/json",[import_protocol73.MCP_SUBSCRIPTION_ID_HEADER]:delivery.subscriptionId,...(0,import_utils184.webhookSignatureHeaders)(message,signingKeys)})}async send(){if(this.state.outcome)return;const{webhook}=this.events.config;const answer=await(0,import_utils184.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=(0,import_utils184.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)}});function subscriptionWithoutSecrets(record){const{secret:_secret,previousSecret:_previous,previousSecretUntil:_until,...delivery}=record.delivery;return{...record,delivery}}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 import_utils185,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";import_utils185=require("@frontmcp/utils");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(0,import_utils185.sha256Hex)(text);return(0,import_utils185.bytesToHex)((0,import_utils185.hmacSha256)(textEncoder3.encode(secret),textEncoder3.encode(text)))}}}});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 import_utils186,SUBSCRIPTION_SWEEP_INTERVAL_MS,EventSubscriptions;var init_event_subscriptions=__esm({"libs/sdk/src/event/subscription/event-subscriptions.ts"(){"use strict";import_utils186=require("@frontmcp/utils");init_event_subscription_store();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=(0,import_utils186.canonicalJson)({principalKey,url,name:eventName,arguments:args});return{id:`sub_${(0,import_utils186.sha256Hex)(canonicalKey).slice(0,32)}`,argumentsKey:(0,import_utils186.canonicalJson)(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 notifyEnded(ending){const{ended}=this.options;if(!ended)return;try{await ended({...ending,record:subscriptionWithoutSecrets(ending.record)})}catch(error){this.logger.warn(`events:ended failed for subscription ${ending.record.id} (${ending.reason})`,error)}}async expire(id,now=Date.now()){const removed=await this.store.deleteExpired(id,now);if(!removed)return;await this.notifyUnsubscribed(removed,"expired");await this.notifyEnded({record:removed,reason:"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}=(0,import_utils186.getRuntimeContext)();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))}}}});var import_lazy_zod134,reasonSchema,inputSchema33,outputSchema32,stateSchema35,plan40,name40,Stage40,EventEndedFlow;var init_event_ended_flow=__esm({"libs/sdk/src/event/flows/event-ended.flow.ts"(){"use strict";import_lazy_zod134=require("@frontmcp/lazy-zod");init_common();init_event_subscription_store();init_event_subscriptions();reasonSchema=import_lazy_zod134.internalZ.enum(["unsubscribed","expired","closed","terminated"]);inputSchema33=import_lazy_zod134.internalZ.object({record:import_lazy_zod134.internalZ.any(),reason:reasonSchema,termination:import_lazy_zod134.internalZ.any().optional(),ctx:import_lazy_zod134.internalZ.unknown().optional()});outputSchema32=import_lazy_zod134.internalZ.object({});stateSchema35=import_lazy_zod134.internalZ.object({record:import_lazy_zod134.internalZ.any(),subscription:import_lazy_zod134.internalZ.any(),reason:reasonSchema,termination:import_lazy_zod134.internalZ.any()});plan40={pre:["parseInput"],execute:["notifyEnded"],post:["buildResult"],finalize:["finalize"]};name40="events:ended";({Stage:Stage40}=FlowHooksOf(name40));EventEndedFlow=class extends FlowBase{logger=this.scopeLogger.child("EventEndedFlow");async parseInput(){const{reason,termination}=this.input;const record=subscriptionWithoutSecrets(this.input.record);this.state.set({record,subscription:subscriptionRefOf(record),reason,...termination&&{termination}})}async notifyEnded(){const{record,reason}=this.state.required;this.logger.verbose(`notifyEnded: subscription ${record.id} to event "${record.eventName}" ended (${reason})`)}async buildResult(){this.respond({})}async finalize(){this.logger.verbose("finalize")}};__decorateClass([Stage40("parseInput")],EventEndedFlow.prototype,"parseInput",1);__decorateClass([Stage40("notifyEnded")],EventEndedFlow.prototype,"notifyEnded",1);__decorateClass([Stage40("buildResult")],EventEndedFlow.prototype,"buildResult",1);__decorateClass([Stage40("finalize")],EventEndedFlow.prototype,"finalize",1);EventEndedFlow=__decorateClass([FrontMcpFlow({name:name40,plan:plan40,inputSchema:inputSchema33,outputSchema:outputSchema32,access:"public"})],EventEndedFlow)}});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 import_protocol74,EVENT_DIALECTS;var init_event_dialect=__esm({"libs/sdk/src/event/event-dialect.ts"(){"use strict";import_protocol74=require("@frontmcp/protocol");EVENT_DIALECTS={"sep-3415":{errorCodes:import_protocol74.EVENTS_ERROR_CODES,webhookId:"message",sendsControlEnvelopes:true},sketch:{errorCodes:import_protocol74.EVENTS_SKETCH_ERROR_CODES,webhookId:"eventId",sendsControlEnvelopes:false}}}});function stringClaim(claims3,name60){const value=claims3[name60];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()}});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&&!(0,import_auth59.isPublicMode)(authOptions)){throw new EventForbiddenError(codes,eventName,"this server needs a signed-in caller")}const{sessionId}=authInfo;const quotaKey=typeof sessionId==="string"&&sessionId!==""?`session:${sessionId}`:void 0;return{principalKey:void 0,...quotaKey&&{quotaKey},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 input=argumentsAsParsed(()=>event.parseArguments(args),args);const result=await engine.evaluate(authorities,contextBuilder.build(authInfo,input));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 import_lazy_zod135.internalZ.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=(0,import_utils187.canonicalJson)({principalKey:reader.principalKey??null,mode,name:eventName,arguments:args});return{id:`sub_${(0,import_utils187.sha256Hex)(key).slice(0,32)}`,name:eventName,mode,subscriber:reader.subscriber}}var import_auth59,import_lazy_zod135,import_utils187,ANONYMOUS_SUBSCRIBER;var init_event_gates=__esm({"libs/sdk/src/event/event-gates.ts"(){"use strict";import_auth59=require("@frontmcp/auth");import_lazy_zod135=require("@frontmcp/lazy-zod");import_utils187=require("@frontmcp/utils");init_authorities_input();init_availability();init_errors();init_event_subscriber();ANONYMOUS_SUBSCRIBER={sub:"",roles:[],permissions:[],scopes:[],claims:{}}}});function pollLeaseMs(nextPollMs){return Math.max(POLL_LEASE_MIN_MS,POLL_LEASE_INTERVALS*nextPollMs)}var import_utils188,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";import_utils188=require("@frontmcp/utils");init_event_subscription_info();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(quotaKey){if(this.leases.size>=MAX_POLL_LEASES)return true;let held=0;for(const lease of this.leases.values()){if(lease.quotaKey===quotaKey)held+=1}return held>=this.options.maxPerPrincipal}has(subscriptionId){return this.leases.has(subscriptionId)||this.starting.has(subscriptionId)}list(eventName){const listed=[];for(const lease of this.leases.values()){if(eventName!==void 0&&lease.subscription.name!==eventName)continue;const held=heldSubscriptionInfoOf(lease.subscription,lease.principalKey,lease.arguments);listed.push({...held,mode:"poll",expiresAt:lease.expiresAt})}return listed}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,quotaKey:request2.quotaKey??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}=(0,import_utils188.getRuntimeContext)();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:name60}=lease.subscription;this.logger.warn(`onUnsubscribe of event "${name60}" 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()}});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");await subscriptions.notifyEnded({record:removed,reason:"terminated",termination:error});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,principalKey:removed.principalKey,eventName:removed.eventName,body:JSON.stringify({type:"terminated",error}),webhookId:(0,import_utils189.generateWebhookMessageId)("terminated"),target:{url,secret,previousSecret,previousSecretUntil}})}var import_utils189;var init_event_subscription_termination=__esm({"libs/sdk/src/event/subscription/event-subscription-termination.ts"(){"use strict";import_utils189=require("@frontmcp/utils");init_event_dialect()}});function eventWebhookIdOf(subscriptionId,eventId){return`msg_${(0,import_utils190.sha256Hex)(`${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 import_lazy_zod136,import_protocol75,import_utils190,EVENT_DELIVERY_MAX_BYTES,audienceValueSchema,inputSchema34,outputSchema33,stateSchema36,plan41,name41,Stage41,encoder10,EventPublishFlow;var init_event_publish_flow=__esm({"libs/sdk/src/event/flows/event-publish.flow.ts"(){"use strict";import_lazy_zod136=require("@frontmcp/lazy-zod");import_protocol75=require("@frontmcp/protocol");import_utils190=require("@frontmcp/utils");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=import_lazy_zod136.internalZ.union([import_lazy_zod136.internalZ.string(),import_lazy_zod136.internalZ.array(import_lazy_zod136.internalZ.string())]);inputSchema34=import_lazy_zod136.internalZ.object({occurrence:import_protocol75.EventOccurrenceSchema,subscriptionId:import_lazy_zod136.internalZ.string().optional(),audience:import_lazy_zod136.internalZ.object({sub:audienceValueSchema.optional(),tenantId:audienceValueSchema.optional(),roles:import_lazy_zod136.internalZ.object({any:import_lazy_zod136.internalZ.array(import_lazy_zod136.internalZ.string()).optional(),all:import_lazy_zod136.internalZ.array(import_lazy_zod136.internalZ.string()).optional()}).optional()}).optional()});outputSchema33=import_lazy_zod136.internalZ.object({eventId:import_lazy_zod136.internalZ.string(),matched:import_lazy_zod136.internalZ.number().int().nonnegative()});stateSchema36=import_lazy_zod136.internalZ.object({event:import_lazy_zod136.internalZ.instanceof(EventEntry),context:import_lazy_zod136.internalZ.any(),subscriptions:import_lazy_zod136.internalZ.array(import_lazy_zod136.internalZ.any()),deliveries:import_lazy_zod136.internalZ.array(import_lazy_zod136.internalZ.any()),buffered:import_lazy_zod136.internalZ.any()});plan41={pre:["validate","bufferOccurrence","pushToStreams"],execute:["loadSubscriptions","dropInactive","filterByAudience","reauthorize","match","transform","enforceBodyLimit","enqueue","bridgeToBus","notifyChannelSessions"],post:["buildResult"]};name41="events:publish";({Stage:Stage41}=FlowHooksOf(name41));encoder10=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:import_protocol75.EventOccurrenceSchema.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=encoder10.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,principalKey:subscription.principalKey,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([Stage41("validate")],EventPublishFlow.prototype,"validate",1);__decorateClass([Stage41("bufferOccurrence")],EventPublishFlow.prototype,"bufferOccurrence",1);__decorateClass([Stage41("pushToStreams")],EventPublishFlow.prototype,"pushToStreams",1);__decorateClass([Stage41("loadSubscriptions")],EventPublishFlow.prototype,"loadSubscriptions",1);__decorateClass([Stage41("dropInactive")],EventPublishFlow.prototype,"dropInactive",1);__decorateClass([Stage41("filterByAudience")],EventPublishFlow.prototype,"filterByAudience",1);__decorateClass([Stage41("reauthorize")],EventPublishFlow.prototype,"reauthorize",1);__decorateClass([Stage41("match")],EventPublishFlow.prototype,"match",1);__decorateClass([Stage41("transform")],EventPublishFlow.prototype,"transform",1);__decorateClass([Stage41("enforceBodyLimit")],EventPublishFlow.prototype,"enforceBodyLimit",1);__decorateClass([Stage41("enqueue")],EventPublishFlow.prototype,"enqueue",1);__decorateClass([Stage41("bridgeToBus")],EventPublishFlow.prototype,"bridgeToBus",1);__decorateClass([Stage41("notifyChannelSessions")],EventPublishFlow.prototype,"notifyChannelSessions",1);__decorateClass([Stage41("buildResult")],EventPublishFlow.prototype,"buildResult",1);EventPublishFlow=__decorateClass([FrontMcpFlow({name:name41,plan:plan41,inputSchema:inputSchema34,outputSchema:outputSchema33,access:"public"})],EventPublishFlow)}});var import_lazy_zod137,import_protocol76,inputSchema35,outputSchema34,stateSchema37,plan42,name42,Stage42,EventPollFlow;var init_event_poll_flow=__esm({"libs/sdk/src/event/flows/event-poll.flow.ts"(){"use strict";import_lazy_zod137=require("@frontmcp/lazy-zod");import_protocol76=require("@frontmcp/protocol");init_common();init_errors();init_event_dialect();init_event_gates();init_event_publisher();init_event_poll_leases();init_event_publish_flow();inputSchema35=import_lazy_zod137.internalZ.object({request:import_protocol76.PollEventsRequestSchema,ctx:import_lazy_zod137.internalZ.unknown()});outputSchema34=import_protocol76.PollEventsResultSchema;stateSchema37=import_lazy_zod137.internalZ.object({authInfo:import_lazy_zod137.internalZ.any(),dialect:import_lazy_zod137.internalZ.enum(["sep-3415","sketch"]),event:import_lazy_zod137.internalZ.instanceof(EventEntry),reader:import_lazy_zod137.internalZ.any(),arguments:import_lazy_zod137.internalZ.record(import_lazy_zod137.internalZ.string(),import_lazy_zod137.internalZ.unknown()),context:import_lazy_zod137.internalZ.any(),subscription:import_lazy_zod137.internalZ.any(),result:import_lazy_zod137.internalZ.any()});plan42={pre:["parseInput","resolveDialect","findEvent","resolveReader","checkEntryAuthorities","validateArguments","authorize"],execute:["renewLease","readEvents"],post:["buildResult"],finalize:["finalize"]};name42="events:poll";({Stage:Stage42}=FlowHooksOf(name42));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;const quotaKey=reader.quotaKey??reader.principalKey;if(!leases.has(subscription.id)&&leases.isFull(quotaKey)){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,quotaKey,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 import_protocol76.EventOccurrenceSchema.parse(transformed)}catch(error){this.logger.warn(`readEvents: event "${occurrence.name}" failed for poll subscription ${subscription.id}`,error);return void 0}}};__decorateClass([Stage42("parseInput")],EventPollFlow.prototype,"parseInput",1);__decorateClass([Stage42("resolveDialect")],EventPollFlow.prototype,"resolveDialect",1);__decorateClass([Stage42("findEvent")],EventPollFlow.prototype,"findEvent",1);__decorateClass([Stage42("resolveReader")],EventPollFlow.prototype,"resolveReader",1);__decorateClass([Stage42("checkEntryAuthorities")],EventPollFlow.prototype,"checkEntryAuthorities",1);__decorateClass([Stage42("validateArguments")],EventPollFlow.prototype,"validateArguments",1);__decorateClass([Stage42("authorize")],EventPollFlow.prototype,"authorize",1);__decorateClass([Stage42("renewLease")],EventPollFlow.prototype,"renewLease",1);__decorateClass([Stage42("readEvents")],EventPollFlow.prototype,"readEvents",1);__decorateClass([Stage42("buildResult")],EventPollFlow.prototype,"buildResult",1);__decorateClass([Stage42("finalize")],EventPollFlow.prototype,"finalize",1);EventPollFlow=__decorateClass([FrontMcpFlow({name:name42,plan:plan42,inputSchema:inputSchema35,outputSchema:outputSchema34,access:"authorized"})],EventPollFlow)}});var import_protocol77,MAX_QUEUED_NOTIFICATIONS,EventStream;var init_event_stream=__esm({"libs/sdk/src/event/stream/event-stream.ts"(){"use strict";import_protocol77=require("@frontmcp/protocol");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(resolve5=>this.releaseDelivery=resolve5):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 arguments(){return this.options.arguments}get principalKey(){return this.options.reader.principalKey}get quotaKey(){return this.options.reader.quotaKey??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(import_protocol77.EVENTS_NOTIFICATIONS.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(resolve5=>this.wake=resolve5);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(import_protocol77.EVENTS_NOTIFICATIONS.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 import_protocol77.EventOccurrenceSchema.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(import_protocol77.EVENTS_NOTIFICATIONS.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(import_protocol77.EVENTS_NOTIFICATIONS.active,{cursor:this.cursor,truncated})}pushEvent(occurrence){this.push(import_protocol77.EVENTS_NOTIFICATIONS.event,{...occurrence,cursor:this.cursor})}push(method,params){if(this.closed)return;const meta={[import_protocol77.MCP_20260728_META.subscriptionId]:this.options.requestId};if(this.queue.length>=MAX_QUEUED_NOTIFICATIONS){this.queue.length=0;this.queue.push({method:import_protocol77.EVENTS_NOTIFICATIONS.active,params:{cursor:this.cursor,truncated:true,_meta:meta}})}this.queue.push({method,params:{...params,_meta:meta}});this.wake?.()}}}});var import_lazy_zod138,import_protocol78,inputSchema36,outputSchema35,stateSchema38,plan43,name43,Stage43,EventStreamFlow;var init_event_stream_flow=__esm({"libs/sdk/src/event/flows/event-stream.flow.ts"(){"use strict";import_lazy_zod138=require("@frontmcp/lazy-zod");import_protocol78=require("@frontmcp/protocol");init_common();init_errors();init_event_dialect();init_event_gates();init_event_reauthorization();init_event_stream();inputSchema36=import_lazy_zod138.internalZ.object({request:import_protocol78.StreamEventsRequestSchema,ctx:import_lazy_zod138.internalZ.unknown(),requestId:import_lazy_zod138.internalZ.union([import_lazy_zod138.internalZ.string(),import_lazy_zod138.internalZ.number()]),signal:import_lazy_zod138.internalZ.any().optional()});outputSchema35=import_lazy_zod138.internalZ.object({stream:import_lazy_zod138.internalZ.instanceof(EventStream)});stateSchema38=import_lazy_zod138.internalZ.object({authInfo:import_lazy_zod138.internalZ.any(),dialect:import_lazy_zod138.internalZ.enum(["sep-3415","sketch"]),event:import_lazy_zod138.internalZ.instanceof(EventEntry),reader:import_lazy_zod138.internalZ.any(),arguments:import_lazy_zod138.internalZ.record(import_lazy_zod138.internalZ.string(),import_lazy_zod138.internalZ.unknown()),context:import_lazy_zod138.internalZ.any(),subscription:import_lazy_zod138.internalZ.any(),stream:import_lazy_zod138.internalZ.instanceof(EventStream)});plan43={pre:["parseInput","resolveDialect","findEvent","resolveReader","checkEntryAuthorities","validateArguments","authorize"],execute:["openStream"],post:["buildResult"],finalize:["finalize"]};name43="events:stream";({Stage:Stage43}=FlowHooksOf(name43));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([Stage43("parseInput")],EventStreamFlow.prototype,"parseInput",1);__decorateClass([Stage43("resolveDialect")],EventStreamFlow.prototype,"resolveDialect",1);__decorateClass([Stage43("findEvent")],EventStreamFlow.prototype,"findEvent",1);__decorateClass([Stage43("resolveReader")],EventStreamFlow.prototype,"resolveReader",1);__decorateClass([Stage43("checkEntryAuthorities")],EventStreamFlow.prototype,"checkEntryAuthorities",1);__decorateClass([Stage43("validateArguments")],EventStreamFlow.prototype,"validateArguments",1);__decorateClass([Stage43("authorize")],EventStreamFlow.prototype,"authorize",1);__decorateClass([Stage43("openStream")],EventStreamFlow.prototype,"openStream",1);__decorateClass([Stage43("buildResult")],EventStreamFlow.prototype,"buildResult",1);__decorateClass([Stage43("finalize")],EventStreamFlow.prototype,"finalize",1);EventStreamFlow=__decorateClass([FrontMcpFlow({name:name43,plan:plan43,inputSchema:inputSchema36,outputSchema:outputSchema35,access:"authorized"})],EventStreamFlow)}});function reactivatedStatus(status={}){const{failures:_failures,suspendedSince:_suspendedSince,...kept}=status;return kept}var import_lazy_zod139,import_protocol79,import_utils191,inputSchema37,outputSchema36,stateSchema39,plan44,name44,Stage44,URL_PROBLEMS,EventSubscribeFlow;var init_event_subscribe_flow=__esm({"libs/sdk/src/event/flows/event-subscribe.flow.ts"(){"use strict";import_lazy_zod139=require("@frontmcp/lazy-zod");import_protocol79=require("@frontmcp/protocol");import_utils191=require("@frontmcp/utils");init_common();init_availability();init_errors();init_event_dialect();init_event_gates();init_event_subscriber();init_event_subscriptions();inputSchema37=import_lazy_zod139.internalZ.object({request:import_protocol79.SubscribeEventRequestSchema,ctx:import_lazy_zod139.internalZ.unknown()});outputSchema36=import_protocol79.SubscribeEventResultSchema;stateSchema39=import_lazy_zod139.internalZ.object({authInfo:import_lazy_zod139.internalZ.any(),dialect:import_lazy_zod139.internalZ.enum(["sep-3415","sketch"]),event:import_lazy_zod139.internalZ.instanceof(EventEntry),owner:import_lazy_zod139.internalZ.any(),arguments:import_lazy_zod139.internalZ.record(import_lazy_zod139.internalZ.string(),import_lazy_zod139.internalZ.unknown()),subscriptionId:import_lazy_zod139.internalZ.string(),argumentsKey:import_lazy_zod139.internalZ.string(),existing:import_lazy_zod139.internalZ.any(),verifiedAt:import_lazy_zod139.internalZ.number(),expiresAt:import_lazy_zod139.internalZ.number().nullable(),record:import_lazy_zod139.internalZ.any(),truncated:import_lazy_zod139.internalZ.boolean().optional()});plan44={pre:["parseInput","resolveDialect","findEvent","checkAvailability","requireWebhookMode","requireSubscriber","checkEntryAuthorities","validateArguments","authorize","validateDelivery"],execute:["findSubscription","enforceLimits","verifyCallback","grantTtl","upsertSubscription","notifySubscribed","startReplay"],post:["buildResult"],finalize:["finalize"]};name44="events:subscribe";({Stage:Stage44}=FlowHooksOf(name44));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{event,authInfo}=this.state.required;await assertEventAuthorities(this.scope,event,authInfo,this.input.request.params.arguments??{},this.codes)}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 import_lazy_zod139.internalZ.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=(0,import_utils191.validateOutboundUrl)(url,{allowLocal});if(!urlCheck.ok)throw new InvalidInputError(`Invalid delivery.url: ${URL_PROBLEMS[urlCheck.problem]}`);if(!(0,import_utils191.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([Stage44("parseInput")],EventSubscribeFlow.prototype,"parseInput",1);__decorateClass([Stage44("resolveDialect")],EventSubscribeFlow.prototype,"resolveDialect",1);__decorateClass([Stage44("findEvent")],EventSubscribeFlow.prototype,"findEvent",1);__decorateClass([Stage44("checkAvailability")],EventSubscribeFlow.prototype,"checkAvailability",1);__decorateClass([Stage44("requireWebhookMode")],EventSubscribeFlow.prototype,"requireWebhookMode",1);__decorateClass([Stage44("requireSubscriber")],EventSubscribeFlow.prototype,"requireSubscriber",1);__decorateClass([Stage44("checkEntryAuthorities")],EventSubscribeFlow.prototype,"checkEntryAuthorities",1);__decorateClass([Stage44("validateArguments")],EventSubscribeFlow.prototype,"validateArguments",1);__decorateClass([Stage44("authorize")],EventSubscribeFlow.prototype,"authorize",1);__decorateClass([Stage44("validateDelivery")],EventSubscribeFlow.prototype,"validateDelivery",1);__decorateClass([Stage44("findSubscription")],EventSubscribeFlow.prototype,"findSubscription",1);__decorateClass([Stage44("enforceLimits")],EventSubscribeFlow.prototype,"enforceLimits",1);__decorateClass([Stage44("verifyCallback")],EventSubscribeFlow.prototype,"verifyCallback",1);__decorateClass([Stage44("grantTtl")],EventSubscribeFlow.prototype,"grantTtl",1);__decorateClass([Stage44("upsertSubscription")],EventSubscribeFlow.prototype,"upsertSubscription",1);__decorateClass([Stage44("notifySubscribed")],EventSubscribeFlow.prototype,"notifySubscribed",1);__decorateClass([Stage44("startReplay")],EventSubscribeFlow.prototype,"startReplay",1);__decorateClass([Stage44("buildResult")],EventSubscribeFlow.prototype,"buildResult",1);__decorateClass([Stage44("finalize")],EventSubscribeFlow.prototype,"finalize",1);EventSubscribeFlow=__decorateClass([FrontMcpFlow({name:name44,plan:plan44,inputSchema:inputSchema37,outputSchema:outputSchema36,access:"authorized"})],EventSubscribeFlow)}});var import_lazy_zod140,import_protocol80,inputSchema38,outputSchema37,stateSchema40,plan45,name45,Stage45,EventUnsubscribeFlow;var init_event_unsubscribe_flow=__esm({"libs/sdk/src/event/flows/event-unsubscribe.flow.ts"(){"use strict";import_lazy_zod140=require("@frontmcp/lazy-zod");import_protocol80=require("@frontmcp/protocol");init_common();init_errors();init_event_dialect();init_event_subscriber();init_event_subscription_store();inputSchema38=import_lazy_zod140.internalZ.object({request:import_protocol80.UnsubscribeEventRequestSchema,ctx:import_lazy_zod140.internalZ.unknown()});outputSchema37=import_protocol80.UnsubscribeEventResultSchema;stateSchema40=import_lazy_zod140.internalZ.object({authInfo:import_lazy_zod140.internalZ.any(),dialect:import_lazy_zod140.internalZ.enum(["sep-3415","sketch"]),owner:import_lazy_zod140.internalZ.any(),subscriptionId:import_lazy_zod140.internalZ.string(),removed:import_lazy_zod140.internalZ.any()});plan45={pre:["parseInput","resolveDialect","requireSubscriber"],execute:["removeSubscription"],post:["buildResult"],finalize:["finalize"]};name45="events:unsubscribe";({Stage:Stage45}=FlowHooksOf(name45));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);this.state.set({subscriptionId:identity.id,removed:removed&&subscriptionWithoutSecrets(removed)});if(!removed)return;await this.subscriptions.notifyUnsubscribed(removed,"unsubscribed",authInfo);await this.subscriptions.notifyEnded({record:removed,reason:"unsubscribed"});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([Stage45("parseInput")],EventUnsubscribeFlow.prototype,"parseInput",1);__decorateClass([Stage45("resolveDialect")],EventUnsubscribeFlow.prototype,"resolveDialect",1);__decorateClass([Stage45("requireSubscriber")],EventUnsubscribeFlow.prototype,"requireSubscriber",1);__decorateClass([Stage45("removeSubscription")],EventUnsubscribeFlow.prototype,"removeSubscription",1);__decorateClass([Stage45("buildResult")],EventUnsubscribeFlow.prototype,"buildResult",1);__decorateClass([Stage45("finalize")],EventUnsubscribeFlow.prototype,"finalize",1);EventUnsubscribeFlow=__decorateClass([FrontMcpFlow({name:name45,plan:plan45,inputSchema:inputSchema38,outputSchema:outputSchema37,access:"authorized"})],EventUnsubscribeFlow)}});function compareByName(left,right){if(left.event.name<right.event.name)return-1;return left.event.name>right.event.name?1:0}var import_lazy_zod141,import_protocol81,EVENTS_LIST_PAGE_SIZE,inputSchema39,outputSchema38,stateSchema41,plan46,name46,Stage46,ListEventsFlow;var init_list_events_flow=__esm({"libs/sdk/src/event/flows/list-events.flow.ts"(){"use strict";import_lazy_zod141=require("@frontmcp/lazy-zod");import_protocol81=require("@frontmcp/protocol");init_common();init_availability();init_offset_cursor_utils();init_errors();init_entry_authorized();EVENTS_LIST_PAGE_SIZE=40;inputSchema39=import_lazy_zod141.internalZ.object({request:import_protocol81.ListEventsRequestSchema,ctx:import_lazy_zod141.internalZ.unknown()});outputSchema38=import_protocol81.ListEventsResultSchema;stateSchema41=import_lazy_zod141.internalZ.object({cursor:import_lazy_zod141.internalZ.string().optional(),authInfo:import_lazy_zod141.internalZ.any(),events:import_lazy_zod141.internalZ.array(import_lazy_zod141.internalZ.object({event:import_lazy_zod141.internalZ.instanceof(EventEntry),delivery:import_lazy_zod141.internalZ.array(import_protocol81.EventDeliveryModeSchema)}))});plan46={pre:["parseInput"],execute:["findEvents","filterByAvailability","filterByAuthorities","filterByDiscovery"],post:["parseEvents"],finalize:["finalize"]};name46="events:list";({Stage:Stage46}=FlowHooksOf(name46));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([Stage46("parseInput")],ListEventsFlow.prototype,"parseInput",1);__decorateClass([Stage46("findEvents")],ListEventsFlow.prototype,"findEvents",1);__decorateClass([Stage46("filterByAvailability")],ListEventsFlow.prototype,"filterByAvailability",1);__decorateClass([Stage46("filterByAuthorities")],ListEventsFlow.prototype,"filterByAuthorities",1);__decorateClass([Stage46("filterByDiscovery")],ListEventsFlow.prototype,"filterByDiscovery",1);__decorateClass([Stage46("parseEvents")],ListEventsFlow.prototype,"parseEvents",1);__decorateClass([Stage46("finalize")],ListEventsFlow.prototype,"finalize",1);ListEventsFlow=__decorateClass([FrontMcpFlow({name:name46,plan:plan46,inputSchema:inputSchema39,outputSchema:outputSchema38,access:"authorized"})],ListEventsFlow)}});var import_utils192,CURSOR_SEPARATOR,EventBuffer;var init_event_buffer=__esm({"libs/sdk/src/event/poll/event-buffer.ts"(){"use strict";import_utils192=require("@frontmcp/utils");CURSOR_SEPARATOR=".";EventBuffer=class{constructor(options){this.options=options;this.bootId=(0,import_utils192.randomUUID)().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)}}}});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 import_lazy_zod142,EVENT_PUBLISH_MAX_BODY_BYTES,EVENT_ID_PATTERN,audienceValueSchema2,publishRequestSchema,inputSchema40,outputSchema39,stateSchema42,plan47,name47,Stage47,decoder3,EventPublishHttpFlow;var init_event_publish_http_flow=__esm({"libs/sdk/src/event/flows/event-publish-http.flow.ts"(){"use strict";import_lazy_zod142=require("@frontmcp/lazy-zod");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=import_lazy_zod142.internalZ.union([import_lazy_zod142.internalZ.string(),import_lazy_zod142.internalZ.array(import_lazy_zod142.internalZ.string())]);publishRequestSchema=import_lazy_zod142.internalZ.object({name:import_lazy_zod142.internalZ.string().min(1),data:import_lazy_zod142.internalZ.record(import_lazy_zod142.internalZ.string(),import_lazy_zod142.internalZ.unknown()),eventId:import_lazy_zod142.internalZ.string().regex(EVENT_ID_PATTERN,"eventId must be 1 to 255 visible ASCII characters").optional(),timestamp:import_lazy_zod142.internalZ.string().refine(isTimestamp,"timestamp must be a date such as 2026-10-02T12:00:00Z").optional(),subscriptionId:import_lazy_zod142.internalZ.string().min(1).optional(),audience:import_lazy_zod142.internalZ.object({sub:audienceValueSchema2.optional(),tenantId:audienceValueSchema2.optional(),roles:import_lazy_zod142.internalZ.object({any:import_lazy_zod142.internalZ.array(import_lazy_zod142.internalZ.string()).optional(),all:import_lazy_zod142.internalZ.array(import_lazy_zod142.internalZ.string()).optional()}).strict().optional()}).strict().optional()}).strict();inputSchema40=httpInputSchema;outputSchema39=HttpJsonSchema;stateSchema42=import_lazy_zod142.internalZ.object({body:import_lazy_zod142.internalZ.custom(),caller:import_lazy_zod142.internalZ.custom().optional(),publication:publishRequestSchema,event:import_lazy_zod142.internalZ.instanceof(EventEntry),claimedEventId:import_lazy_zod142.internalZ.string().optional(),claimToken:import_lazy_zod142.internalZ.string().optional(),result:import_lazy_zod142.internalZ.object({eventId:import_lazy_zod142.internalZ.string(),matched:import_lazy_zod142.internalZ.number()}),flowError:import_lazy_zod142.internalZ.instanceof(Error).optional()});plan47={pre:["checkIpFilter","acquireQuota","readBody","authenticate","parseBody","checkAuthorities","findEvent","validatePayload"],execute:["claimEventId","publish","rememberResult","buildResponse"],finalize:["finalize"]};name47="events:publish-http";({Stage:Stage47}=FlowHooksOf(name47));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 import_lazy_zod142.internalZ.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([Stage47("checkIpFilter")],EventPublishHttpFlow.prototype,"checkIpFilter",1);__decorateClass([Stage47("acquireQuota")],EventPublishHttpFlow.prototype,"acquireQuota",1);__decorateClass([Stage47("readBody")],EventPublishHttpFlow.prototype,"readBody",1);__decorateClass([Stage47("authenticate")],EventPublishHttpFlow.prototype,"authenticate",1);__decorateClass([Stage47("parseBody")],EventPublishHttpFlow.prototype,"parseBody",1);__decorateClass([Stage47("checkAuthorities")],EventPublishHttpFlow.prototype,"checkAuthorities",1);__decorateClass([Stage47("findEvent")],EventPublishHttpFlow.prototype,"findEvent",1);__decorateClass([Stage47("validatePayload")],EventPublishHttpFlow.prototype,"validatePayload",1);__decorateClass([Stage47("claimEventId")],EventPublishHttpFlow.prototype,"claimEventId",1);__decorateClass([Stage47("publish")],EventPublishHttpFlow.prototype,"publish",1);__decorateClass([Stage47("rememberResult")],EventPublishHttpFlow.prototype,"rememberResult",1);__decorateClass([Stage47("buildResponse")],EventPublishHttpFlow.prototype,"buildResponse",1);__decorateClass([Stage47("finalize")],EventPublishHttpFlow.prototype,"finalize",1);EventPublishHttpFlow=__decorateClass([FrontMcpFlow({name:name47,plan:plan47,inputSchema:inputSchema40,outputSchema:outputSchema39,access:"public",middleware:{method:"POST"}})],EventPublishHttpFlow)}});function eventsSecretFromEnv(){return(0,import_utils193.getEnv)("MCP_EVENTS_SECRET")||(0,import_utils193.getEnv)("MCP_SESSION_SECRET")||(0,import_utils193.getEnv)("MCP_SERVER_SECRET")||void 0}function storageConfigOf(options){const{redis,sqlite}=options;if(sqlite)return{type:"sqlite",sqlite};if(!redis)return{type:"memory"};if(!isRedisConnectionOptions(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.")}return redisStorageConfigOf(redis)}async function openStorage(config,keyPrefix){try{return await(0,import_utils193.createStorage)({...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 import_utils193;var init_event_subscription_store_factory=__esm({"libs/sdk/src/event/subscription/event-subscription-store.factory.ts"(){"use strict";import_utils193=require("@frontmcp/utils");init_common();init_errors();init_event_subscription_store()}});function pendingRecordOf(token){return JSON.stringify({pending:token})}function isPending(record){return"pending"in record}var import_utils194,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";import_utils194=require("@frontmcp/utils");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=(0,import_utils194.randomUUID)();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+(0,import_utils194.sha256Hex)(JSON.stringify([this.scopeId,eventName,eventId])).slice(0,40)}}}});function assertPathFree(scope,path7){const reserved=computeReservedPaths(scope.entryPath,scope.routeBase,servedHealthPaths(scope.metadata.health));try{assertNotReserved("POST",path7,reserved)}catch(error){if(!(error instanceof ReservedRouteCollisionError))throw error;throw new EventPublishEndpointError(`events.publishEndpoint.path "${path7}" 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,path7)!==void 0);if(taken){throw new EventPublishEndpointError(`events.publishEndpoint.path "${path7}" 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 path7=`${normalizeScopeBase(scope.routeBase)}${configuredPath}`;assertPathFree(scope,path7);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:path7,secret,authorities,replays:new WorkflowWebhookReplayGuard,idempotency:new EventPublishIdempotency(storage,scope.id)};await scope.registryFlows(EventPublishHttpFlow);logger.info(`Events can be published over HTTP: POST ${path7} (${secret?"signed requests":"bearer callers"})`);if(!secret&&authorities===void 0){logger.warn(`POST ${path7} 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()}});function isSameReadPosition(current,expected){return current?.cursor===expected.cursor&¤t.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 import_utils195,REPLAY_LEASE_MS,REPLAY_STOP_GRACE_MS,MAX_PENDING_BATCHES,MAX_ROUNDS_PER_TICK,encoder11,EventReplays;var init_event_replays=__esm({"libs/sdk/src/event/replay/event-replays.ts"(){"use strict";import_utils195=require("@frontmcp/utils");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;encoder11=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:${(0,import_utils195.sha256Hex)(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,principalKey:record.principalKey,eventName:record.eventName,body:JSON.stringify({type:"gap",cursor:replay.watermark}),webhookId:(0,import_utils195.generateWebhookMessageId)("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=encoder11.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,principalKey:record.principalKey,eventName:event.name,body,webhookId:usesEventId?eventId:(0,import_utils195.generateWebhookMessageId)()})}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}}}}});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=import_protocol82.EventOccurrenceSchema.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 import_protocol82,import_utils196,EVENT_RELAY_CHANNEL,MAX_OPEN_STREAMS,EventStreams;var init_event_streams=__esm({"libs/sdk/src/event/stream/event-streams.ts"(){"use strict";import_protocol82=require("@frontmcp/protocol");import_utils196=require("@frontmcp/utils");init_event_subscription_info();EVENT_RELAY_CHANNEL="occurrences";MAX_OPEN_STREAMS=1e4;EventStreams=class{constructor(options){this.options=options;this.nodeId=(0,import_utils196.randomUUID)();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}list(eventName){const listed=[];for(const stream of this.held){if(stream.isClosed||eventName!==void 0&&stream.eventName!==eventName)continue;listed.push({...heldSubscriptionInfoOf(stream.subscription,stream.principalKey,stream.arguments),mode:"push"})}return listed}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(quotaKey){if(this.held.size>=MAX_OPEN_STREAMS)return true;let heldByReader=0;for(const stream of this.held){if(stream.quotaKey===quotaKey)heldByReader+=1}return heldByReader>=this.options.maxPerPrincipal}reserve(stream){if(this.held.has(stream))return true;if(this.isFull(stream.quotaKey))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))}}}});function isSameText(left,right){const leftBytes=encoder12.encode(left);const rightBytes=encoder12.encode(right);return leftBytes.length===rightBytes.length&&(0,import_utils197.timingSafeEqual)(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 import_protocol83,import_utils197,VERIFICATION_ATTEMPTS_PER_HOST,VERIFICATION_WINDOW_MS,WELL_KNOWN_CACHE_MS,WELL_KNOWN_MAX_BYTES,CHALLENGE_BYTES,CHALLENGE_ANSWER_MAX_BYTES,MAX_CACHED_ENTRIES,encoder12,ExpiringMap,EventCallbackVerifier;var init_event_callback_verifier=__esm({"libs/sdk/src/event/subscription/event-callback-verifier.ts"(){"use strict";import_protocol83=require("@frontmcp/protocol");import_utils197=require("@frontmcp/utils");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;encoder12=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??import_utils197.sendOutboundRequest;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=(0,import_utils197.sha256Hex)(`${request2.principalKey}
|
|
336
|
+
`;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;this.signingKey=options?.signingKey}redis;machineId;keyPrefix;ttlSeconds;haKeyPrefix;retryAfterSeconds;logger;relay;signingKey;pendingDestroys=new Map;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 requestId=(0,import_utils163.randomUUID)();const confirmed=new Promise(confirm=>this.pendingDestroys.set(requestId,{ownerNodeId:entry.nodeId,confirm}));try{const message={kind:"destroy-session",sessionId:key.sessionId,reason,sourceNodeId:this.machineId,timestamp:Date.now(),requestId};this.signingKey??=deriveChannelKey("relay");const receivers=await(0,import_utils163.publishRedisMessage)(this.redis,entry.channel,signChannelMessage(this.signingKey,message));this.logger?.info("[TransportBus] Sent destroy-remote",{sessionId:key.sessionId.slice(0,20),targetNodeId:entry.nodeId});if(receivers===0){throw new SessionEndUnconfirmedError(entry.nodeId,this.retryAfterSeconds,"no node listens on the session owner's relay channel","not-listening")}if(await this.untilClosed(key.sessionId,confirmed))return;this.logger?.warn("[TransportBus] The session owner did not confirm in time that it closed the session",{sessionId:key.sessionId.slice(0,20),ownerNodeId:entry.nodeId});throw new SessionEndUnconfirmedError(entry.nodeId,this.retryAfterSeconds,`the session owner did not confirm within ${RELEASE_TIMEOUT_MS}ms that it closed the session`,"timed-out")}finally{this.pendingDestroys.delete(requestId)}}handleSessionDestroyed(message){const pending=this.pendingDestroys.get(message.requestId);if(pending&&pending.ownerNodeId===message.sourceNodeId)pending.confirm()}async revokeSession(sessionId){await this.redis.eval(REVOKE_LUA,1,this.busKey(sessionId),this.machineId)}async untilClosed(sessionId,confirmed){let waiting=true;let timer;const revoked=(async()=>{while(waiting){await new Promise(resolve5=>setTimeout(resolve5,RELEASE_POLL_MS));try{if(waiting&&!await this.readEntry(sessionId))return true}catch{}}return false})();const timedOut=new Promise(resolve5=>timer=setTimeout(()=>resolve5(false),RELEASE_TIMEOUT_MS));return Promise.race([confirmed.then(()=>true),revoked,timedOut]).finally(()=>{waiting=false;clearTimeout(timer)})}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}}}});var import_utils164,RedisEventStore;var init_redis_event_store=__esm({"libs/sdk/src/transport/event-stores/redis.event-store.ts"(){"use strict";import_utils164=require("@frontmcp/utils");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{client,owned,kind}=(0,import_utils164.createRedisConnection)({...redisConnectionOfOptions(redis),label:"RedisEventStore",ioredisOptions:{lazyConnect:true,enableReadyCheck:false}});if(kind==="custom"&&(typeof client.xadd!=="function"||typeof client.xrange!=="function")){throw new InternalMcpError("The event store's redis client has no xadd/xrange: give it a client that runs Redis Streams commands.","INVALID_REDIS_CONFIG")}this.client=client;if(owned)await 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}=(0,import_utils50.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}}}}});function sessionIdHash(sessionId){return(0,import_utils165.sha256Hex)(sessionId).slice(0,12)}var import_utils165;var init_session_id_hash=__esm({"libs/sdk/src/logger/session-id-hash.ts"(){"use strict";import_utils165=require("@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 import_utils166,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";import_utils166=require("@frontmcp/utils");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 import_utils166.TypedStorage(storage.namespace("pending"));this.fallback=new import_utils166.TypedStorage(storage.namespace("fallback"));this.resolved=new import_utils166.TypedStorage(storage.namespace("resolved"))}async setPending(record){const{sessionId,expiresAt}=record;const ttlSeconds=(0,import_utils166.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=(0,import_utils166.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});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((0,import_utils167.getEnv)("UPSTASH_REDIS_REST_URL")){return"upstash"}if((0,import_utils167.getEnv)("REDIS_URL")||(0,import_utils167.getEnv)("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: ... }')}finalStorageConfig=redisStorageConfigOf(redisOptions);const{host,port,client}=redisOptions;logger?.debug("[ElicitationStoreFactory] Converted redis option to storage config",{host,port,client:client!==void 0})}const explicitBackend=Boolean(storageConfig||redis);if(finalStorageConfig?.type==="vercel-kv"||!explicitBackend&&(0,import_utils167.getEnv)("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(0,import_utils167.createStorage)({...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=(0,import_utils167.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}=(0,import_utils50.requireOptionalModule)("@frontmcp/storage-sqlite",()=>require_dist());logger?.info("[ElicitationStoreFactory] Creating SQLite elicitation store",{path:sqliteConfig.path,keyPrefix});return new SqliteElicitationStore({...sqliteConfig,keyPrefix})}var import_utils167;var init_elicitation_store_factory=__esm({"libs/sdk/src/elicitation/store/elicitation-store.factory.ts"(){"use strict";import_utils167=require("@frontmcp/utils");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});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 import_utils168,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";import_utils168=require("@frontmcp/utils");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=(0,import_utils168.randomUUID)();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&&(0,import_utils168.expiresAtToTTL)(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,(0,import_utils168.expiresAtToTTL)(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=(0,import_utils168.expiresAtToTTL)(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?(0,import_utils168.expiresAtToTTL)(current.expiresAt):0;if(current&¤tTtl>ttlSeconds)await this.extend(current,currentTtl)}}}});function recordKey(sessionId,taskId){return`${sessionId}:${taskId}`}function slotKey(sessionId,slot){return`${sessionId}:${slot}`}function encodeCursor(offset,source){return(0,import_utils169.base64urlEncode)(new TextEncoder().encode(JSON.stringify({offset,source})))}function decodeCursor(cursor){try{const bytes=(0,import_utils169.base64urlDecode)(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 import_utils169,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";import_utils169=require("@frontmcp/utils");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 import_utils169.TypedStorage(storage.namespace(RECORDS_NAMESPACE));this.slots=storage.namespace(SLOTS_NAMESPACE)}async create(record){const ttlSeconds=(0,import_utils169.expiresAtToTTL)(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=(0,import_utils169.expiresAtToTTL)(record.expiresAt);if(ttlSeconds<=0)return false;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=(0,import_utils169.expiresAtToTTL)(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()}}}});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((0,import_utils170.getEnv)("UPSTASH_REDIS_REST_URL"))return"upstash";if((0,import_utils170.getEnv)("REDIS_URL")||(0,import_utils170.getEnv)("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}=(0,import_utils50.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.")}finalStorageConfig=redisStorageConfigOf(redisOptions)}const explicitBackend=isExplicitStorage(storageConfig)||Boolean(redis);if(finalStorageConfig?.type==="vercel-kv"||!explicitBackend&&(0,import_utils170.getEnv)("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(0,import_utils170.createStorage)({...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=(0,import_utils170.createMemoryStorage)({prefix:keyPrefix});return{store:new StorageTaskStore(storage,logger),type:"memory",storage}}var import_utils170,TaskStoreNotSupportedError;var init_task_store_factory=__esm({"libs/sdk/src/task/store/task-store.factory.ts"(){"use strict";import_utils170=require("@frontmcp/utils");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}}}}});function runTaskInBackground(params){return Promise.resolve().then(()=>(0,import_utils171.runRequestExclusive)(()=>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;markTaskRunContext(taskCtx);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 import_utils171;var init_task_runner=__esm({"libs/sdk/src/task/helpers/task-runner.ts"(){"use strict";import_utils171=require("@frontmcp/utils");init_errors();init_call_tool_error_utils();init_mcp_error_utils();init_task_types();init_task_run_context()}});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")}}}});var import_lazy_zod122,import_protocol68,inputSchema21,outputSchema20,stateSchema25,plan28,name28,Stage28,TasksGetFlow;var init_tasks_get_flow=__esm({"libs/sdk/src/task/flows/tasks-get.flow.ts"(){"use strict";import_lazy_zod122=require("@frontmcp/lazy-zod");import_protocol68=require("@frontmcp/protocol");init_common();init_errors();init_task_types();inputSchema21=import_lazy_zod122.internalZ.object({request:import_protocol68.GetTaskRequestSchema,ctx:import_lazy_zod122.internalZ.any()});outputSchema20=import_protocol68.GetTaskResultSchema;stateSchema25=import_lazy_zod122.internalZ.object({taskId:import_lazy_zod122.internalZ.string(),sessionId:import_lazy_zod122.internalZ.string(),authInfo:import_lazy_zod122.internalZ.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 import_lazy_zod122.internalZ.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)}});var import_lazy_zod123,import_protocol69,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";import_lazy_zod123=require("@frontmcp/lazy-zod");import_protocol69=require("@frontmcp/protocol");init_common();init_errors();init_task_types();inputSchema22=import_lazy_zod123.internalZ.object({request:import_protocol69.GetTaskPayloadRequestSchema,ctx:import_lazy_zod123.internalZ.any()});outputSchema21=import_protocol69.GetTaskPayloadResultSchema;stateSchema26=import_lazy_zod123.internalZ.object({taskId:import_lazy_zod123.internalZ.string(),sessionId:import_lazy_zod123.internalZ.string(),authInfo:import_lazy_zod123.internalZ.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 import_lazy_zod123.internalZ.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((resolve5,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 resolve5(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}}}});var import_lazy_zod124,import_protocol70,inputSchema23,outputSchema22,stateSchema27,plan30,name30,Stage30,TasksCancelFlow;var init_tasks_cancel_flow=__esm({"libs/sdk/src/task/flows/tasks-cancel.flow.ts"(){"use strict";import_lazy_zod124=require("@frontmcp/lazy-zod");import_protocol70=require("@frontmcp/protocol");init_common();init_errors();init_task_types();inputSchema23=import_lazy_zod124.internalZ.object({request:import_protocol70.CancelTaskRequestSchema,ctx:import_lazy_zod124.internalZ.any()});outputSchema22=import_protocol70.CancelTaskResultSchema;stateSchema27=import_lazy_zod124.internalZ.object({taskId:import_lazy_zod124.internalZ.string(),sessionId:import_lazy_zod124.internalZ.string(),authInfo:import_lazy_zod124.internalZ.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 import_lazy_zod124.internalZ.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)}});var import_lazy_zod125,import_protocol71,inputSchema24,outputSchema23,stateSchema28,plan31,name31,Stage31,TasksListFlow;var init_tasks_list_flow=__esm({"libs/sdk/src/task/flows/tasks-list.flow.ts"(){"use strict";import_lazy_zod125=require("@frontmcp/lazy-zod");import_protocol71=require("@frontmcp/protocol");init_common();init_errors();init_task_types();inputSchema24=import_lazy_zod125.internalZ.object({request:import_protocol71.ListTasksRequestSchema,ctx:import_lazy_zod125.internalZ.any()});outputSchema23=import_protocol71.ListTasksResultSchema;stateSchema28=import_lazy_zod125.internalZ.object({sessionId:import_lazy_zod125.internalZ.string(),cursor:import_lazy_zod125.internalZ.string().optional(),authInfo:import_lazy_zod125.internalZ.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 import_lazy_zod125.internalZ.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()}});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=>!(0,import_auth57.isAnonymousSubject)(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 import_auth57;var init_session_scope_identity=__esm({"libs/sdk/src/auth/session-scope-identity.ts"(){"use strict";import_auth57=require("@frontmcp/auth")}});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});function createAuthProvidersProviders(options,store,baseVault=new import_auth58.InMemoryAuthorizationVault){const providers=[];providers.push({provide:import_auth58.AUTH_PROVIDERS_REGISTRY,scope:import_di49.ProviderScope.GLOBAL,name:"AuthProvidersRegistry",useFactory:()=>new import_auth58.AuthProvidersRegistry(options)});providers.push({provide:import_auth58.AUTH_PROVIDERS_VAULT,scope:import_di49.ProviderScope.GLOBAL,name:"AuthProvidersVault",useFactory:logger=>new import_auth58.AuthProvidersVault(store.storage,{namespace:options.namespace,defaultCacheTtl:options.defaultCacheTtl,pepper:store.pepper,logger}),inject:()=>[FrontMcpLogger]});providers.push({provide:CREDENTIAL_CACHE,scope:import_di49.ProviderScope.CONTEXT,name:"CredentialCache",useFactory:()=>new import_auth58.CredentialCache(options.maxCredentialsPerSession??100)});providers.push({provide:LAZY_CREDENTIAL_LOADER,scope:import_di49.ProviderScope.CONTEXT,name:"LazyCredentialLoader",useFactory:logger=>new import_auth58.LazyCredentialLoader(logger),inject:()=>[FrontMcpLogger]});providers.push({provide:import_auth58.AUTH_PROVIDERS_ACCESSOR,scope:import_di49.ProviderScope.CONTEXT,name:"AuthProvidersAccessor",useFactory:(registry,vault,cache2,loader,ctx,logger)=>{const user=ctx.authInfo?.user;const signedIn=user&&!(0,import_auth58.isAnonymousSubject)(user.sub)?user:void 0;const factoryContext={sessionId:sessionScopeIdentity(ctx)??`${import_auth58.UNIDENTIFIED_SESSION_PREFIX}${(0,import_utils172.randomUUID)()}`,userSub:signedIn?.sub,userEmail:signedIn?.email,userName:signedIn?.name,vault:baseVault};return new import_auth58.AuthProvidersAccessorImpl(registry,vault,cache2,loader,factoryContext,logger)},inject:()=>[import_auth58.AUTH_PROVIDERS_REGISTRY,import_auth58.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=(0,import_utils172.getEnv)("VAULT_SECRET")||(0,import_utils172.getEnv)("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(0,import_utils172.createStorage)({type:"memory"});await providers.addDynamicProviders(createAuthProvidersProviders(options,{storage}));return()=>storage.disconnect()}var import_auth58,import_di49,import_utils172,LAZY_CREDENTIAL_LOADER;var init_auth_providers_providers=__esm({"libs/sdk/src/auth/vault/auth-providers.providers.ts"(){"use strict";import_auth58=require("@frontmcp/auth");import_di49=require("@frontmcp/di");import_utils172=require("@frontmcp/utils");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});function defaultLogSinks(){return[{type:(0,import_utils173.getRuntimeContext)().runtime==="browser"?"console":"stdout"}]}function observabilityPlugins({config:observabilityConfig,logger,globalProviders,implied=false}){const plugins=[];let ObservabilityPluginModule;try{ObservabilityPluginModule=(0,import_utils50.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 import_utils173;var init_observability_scope_helper=__esm({"libs/sdk/src/scope/observability-scope.helper.ts"(){"use strict";import_utils173=require("@frontmcp/utils");init_context();init_logger_registry();init_optional_dependency_util();init_tracer_provider_utils()}});var import_lazy_zod126,import_utils174,inputSchema25,outputSchema24,stateSchema29,plan32,name32,Stage32,ElicitationRequestFlow;var init_elicitation_request_flow=__esm({"libs/sdk/src/elicitation/flows/elicitation-request.flow.ts"(){"use strict";import_lazy_zod126=require("@frontmcp/lazy-zod");import_utils174=require("@frontmcp/utils");init_common();init_errors();init_session_id_hash();init_elicitation_types();inputSchema25=import_lazy_zod126.internalZ.object({relatedRequestId:import_lazy_zod126.internalZ.union([import_lazy_zod126.internalZ.string(),import_lazy_zod126.internalZ.number()]),requestId:import_lazy_zod126.internalZ.union([import_lazy_zod126.internalZ.string(),import_lazy_zod126.internalZ.number()]).optional(),sessionId:import_lazy_zod126.internalZ.string(),message:import_lazy_zod126.internalZ.string(),requestedSchema:import_lazy_zod126.internalZ.record(import_lazy_zod126.internalZ.string(),import_lazy_zod126.internalZ.unknown()),options:import_lazy_zod126.internalZ.object({mode:import_lazy_zod126.internalZ.enum(["form","url"]).optional(),ttl:import_lazy_zod126.internalZ.number().optional(),elicitationId:import_lazy_zod126.internalZ.string().optional(),url:import_lazy_zod126.internalZ.string().optional()}).optional()});outputSchema24=import_lazy_zod126.internalZ.object({elicitId:import_lazy_zod126.internalZ.string(),sessionId:import_lazy_zod126.internalZ.string(),expiresAt:import_lazy_zod126.internalZ.number(),mode:import_lazy_zod126.internalZ.enum(["form","url"]),requestParams:import_lazy_zod126.internalZ.record(import_lazy_zod126.internalZ.string(),import_lazy_zod126.internalZ.unknown()),pendingRecord:import_lazy_zod126.internalZ.any()});stateSchema29=import_lazy_zod126.internalZ.object({relatedRequestId:import_lazy_zod126.internalZ.union([import_lazy_zod126.internalZ.string(),import_lazy_zod126.internalZ.number()]),requestId:import_lazy_zod126.internalZ.union([import_lazy_zod126.internalZ.string(),import_lazy_zod126.internalZ.number()]).optional(),sessionId:import_lazy_zod126.internalZ.string(),message:import_lazy_zod126.internalZ.string(),requestedSchema:import_lazy_zod126.internalZ.record(import_lazy_zod126.internalZ.string(),import_lazy_zod126.internalZ.unknown()),mode:import_lazy_zod126.internalZ.enum(["form","url"]).default("form"),ttl:import_lazy_zod126.internalZ.number().default(DEFAULT_ELICIT_TTL),elicitationId:import_lazy_zod126.internalZ.string().optional(),url:import_lazy_zod126.internalZ.string().optional(),elicitId:import_lazy_zod126.internalZ.string(),expiresAt:import_lazy_zod126.internalZ.number(),pendingRecord:import_lazy_zod126.internalZ.any().optional(),requestParams:import_lazy_zod126.internalZ.record(import_lazy_zod126.internalZ.string(),import_lazy_zod126.internalZ.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,...input.requestId===void 0?{}:{requestId:input.requestId},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-${(0,import_utils174.randomUUID)()}`;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{requestId}=this.state;const store=this.scope.elicitationStore;if(!store){throw new ElicitationStoreNotInitializedError}const pendingRecord={elicitId,sessionId,createdAt:Date.now(),expiresAt,message,mode,requestedSchema,...requestId===void 0?{}:{requestId}};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)}});var import_lazy_zod127,inputSchema26,outputSchema25,stateSchema30,plan33,name33,Stage33,ElicitationResultFlow;var init_elicitation_result_flow=__esm({"libs/sdk/src/elicitation/flows/elicitation-result.flow.ts"(){"use strict";import_lazy_zod127=require("@frontmcp/lazy-zod");init_common();init_errors();init_session_id_hash();init_helpers();inputSchema26=import_lazy_zod127.internalZ.object({sessionId:import_lazy_zod127.internalZ.string(),requestId:import_lazy_zod127.internalZ.union([import_lazy_zod127.internalZ.string(),import_lazy_zod127.internalZ.number()]).optional(),result:import_lazy_zod127.internalZ.object({action:import_lazy_zod127.internalZ.enum(["accept","cancel","decline"]),content:import_lazy_zod127.internalZ.unknown().optional()})});outputSchema25=import_lazy_zod127.internalZ.object({handled:import_lazy_zod127.internalZ.boolean(),elicitId:import_lazy_zod127.internalZ.string().optional(),result:import_lazy_zod127.internalZ.any().optional()});stateSchema30=import_lazy_zod127.internalZ.object({sessionId:import_lazy_zod127.internalZ.string(),requestId:import_lazy_zod127.internalZ.union([import_lazy_zod127.internalZ.string(),import_lazy_zod127.internalZ.number()]).optional(),action:import_lazy_zod127.internalZ.enum(["accept","cancel","decline"]),content:import_lazy_zod127.internalZ.unknown().optional(),pendingRecord:import_lazy_zod127.internalZ.any().optional(),elicitResult:import_lazy_zod127.internalZ.any().optional(),handled:import_lazy_zod127.internalZ.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,...input.requestId===void 0?{}:{requestId:input.requestId},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{requestId}=this.state;const found=await store.getPending(sessionId);const pendingRecord=found&&(requestId===void 0||found.requestId===requestId)?found:void 0;this.state.set("pendingRecord",pendingRecord);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()}});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=(0,import_utils175.getEnv)(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 import_utils175,SERVER_CARD_MEDIA_TYPE,envVarsReportedInvalid;var init_mcp_registry_utils=__esm({"libs/sdk/src/mcp-registry/mcp-registry.utils.ts"(){"use strict";import_utils175=require("@frontmcp/utils");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)}});function ifNoneMatchIncludes(ifNoneMatch,etag){const candidates=(ifNoneMatch??"").split(",").map(candidate=>candidate.trim().replace(/^W\//,""));return candidates.includes("*")||candidates.includes(etag)}var import_lazy_zod128,import_utils176,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";import_lazy_zod128=require("@frontmcp/lazy-zod");import_utils176=require("@frontmcp/utils");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=import_lazy_zod128.internalZ.object({card:import_lazy_zod128.internalZ.record(import_lazy_zod128.internalZ.string(),import_lazy_zod128.internalZ.unknown())});outputSchema27=import_lazy_zod128.internalZ.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=`"${(0,import_utils176.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)}});function aiCatalogIdentifier(registryName){const[namespace,serverName]=registryName.split("/");return`urn:air:${namespace.split(".").reverse().join(".")}:mcp:${serverName}`}var import_lazy_zod129,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";import_lazy_zod129=require("@frontmcp/lazy-zod");init_common();init_mcp_registry_utils();AI_CATALOG_PATH="/.well-known/ai-catalog.json";inputSchema29=httpInputSchema;outputSchema28=import_lazy_zod129.internalZ.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&®istryOptions.name&®istryOptions.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()}});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 import_utils177,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";import_utils177=require("@frontmcp/utils");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=(0,import_utils177.randomUUID)();const sessionLabel=sessionId.slice(0,20);return new Promise((resolve5,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();resolve5()};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();resolve5()};const onClientClose=()=>{if(done||response.writableFinished)return;done=true;cleanup();this.options.publish(ownerNodeId,{kind:"relay-cancel",requestId,sourceNodeId:this.nodeId}).catch(()=>void 0);resolve5()};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 destroyOnRequest=async message=>{const sessionLabel=message.sessionId.slice(0,20);let held;try{held=await transportService.destroyLocalSession(message.sessionId,message.reason);if(!held)await bus.revokeSession(message.sessionId)}catch(error){logger.warn("[HA] Failed to destroy a session on request of another node",{sessionId:sessionLabel,error:error instanceof Error?error.message:String(error)});return}if(!message.requestId||typeof message.sourceNodeId!=="string")return;try{await haManager.publishToNode(message.sourceNodeId,{kind:"session-destroyed",requestId:message.requestId,sessionId:message.sessionId,held,sourceNodeId:nodeId})}catch(error){logger.warn("[HA] Failed to tell another node a session it asked to close is closed",{sessionId:sessionLabel,error:error instanceof Error?error.message:String(error)})}};const handler=message=>{if(isRequestRelayMessage(message)){relay.handleMessage(message);return}if(message.kind==="destroy-session"){void destroyOnRequest(message);return}if(message.kind==="session-destroyed"){bus.handleSessionDestroyed(message);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(resolve5=>{settleReady=resolve5;const attempt=failures=>{if(closed){resolve5();return}haManager.subscribeRelay(handler).then(()=>{if(closed){resolve5();return}bus.attachRelay(relay);logger.info("[HA] Request relay ready \u2014 sessions owned by other nodes are served through them");resolve5()},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)}}}});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(path7=>path7.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:path7}of(0,import_utils178.watchFiles)(sourceConfig.paths,{events,signal})){const fileEvent={event:REPORTED_EVENTS[type],path:path7};logger.verbose(`File ${fileEvent.event} for channel "${channel2.name}": ${path7}`);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 import_utils178,WATCHED_TYPES,REPORTED_EVENTS;var init_file_watcher_source=__esm({"libs/sdk/src/channel/sources/file-watcher.source.ts"(){"use strict";import_utils178=require("@frontmcp/utils");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)}}}});var import_utils179,ChannelRegistry;var init_channel_registry=__esm({"libs/sdk/src/channel/channel.registry.ts"(){"use strict";import_utils179=require("@frontmcp/utils");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=(0,import_utils179.getRuntimeContext)();for(const token of this.tokens){const rec=this.defs.get(token);if(!rec)continue;if(!(0,import_utils179.isEntryAvailable)(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(name60){return this.localRows.find(r=>r.instance.name===name60)?.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()})}}}});var import_lazy_zod130,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";import_lazy_zod130=require("@frontmcp/lazy-zod");init_common();inputSchema30=import_lazy_zod130.internalZ.object({}).optional();channelInfoSchema=import_lazy_zod130.internalZ.object({name:import_lazy_zod130.internalZ.string(),description:import_lazy_zod130.internalZ.string().optional(),sourceType:import_lazy_zod130.internalZ.string(),twoWay:import_lazy_zod130.internalZ.boolean(),tags:import_lazy_zod130.internalZ.array(import_lazy_zod130.internalZ.string())});outputSchema29=import_lazy_zod130.internalZ.object({channels:import_lazy_zod130.internalZ.array(channelInfoSchema),count:import_lazy_zod130.internalZ.number()});stateSchema32=import_lazy_zod130.internalZ.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)}});var import_lazy_zod131,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";import_lazy_zod131=require("@frontmcp/lazy-zod");init_common();init_errors();init_channel_utils();inputSchema31=import_lazy_zod131.internalZ.object({channelName:import_lazy_zod131.internalZ.string().min(1),content:import_lazy_zod131.internalZ.string().min(1),meta:import_lazy_zod131.internalZ.record(import_lazy_zod131.internalZ.string(),import_lazy_zod131.internalZ.unknown()).optional(),targetSessionId:import_lazy_zod131.internalZ.string().min(1).optional()});outputSchema30=import_lazy_zod131.internalZ.object({sent:import_lazy_zod131.internalZ.boolean(),channelName:import_lazy_zod131.internalZ.string()});stateSchema33=import_lazy_zod131.internalZ.object({channelName:import_lazy_zod131.internalZ.string(),content:import_lazy_zod131.internalZ.string(),meta:import_lazy_zod131.internalZ.record(import_lazy_zod131.internalZ.string(),import_lazy_zod131.internalZ.string()).optional(),targetSessionId:import_lazy_zod131.internalZ.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 import_lazy_zod131.internalZ.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)}});var import_lazy_zod132,channelReplyInputSchema;var init_reply_types=__esm({"libs/sdk/src/channel/reply/reply.types.ts"(){"use strict";import_lazy_zod132=require("@frontmcp/lazy-zod");channelReplyInputSchema={channel_name:import_lazy_zod132.internalZ.string().describe("The name of the channel to reply to"),text:import_lazy_zod132.internalZ.string().describe("The reply text to send back through the channel"),meta:import_lazy_zod132.internalZ.record(import_lazy_zod132.internalZ.string(),import_lazy_zod132.internalZ.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:http5,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=http5?computeReservedPaths(http5.entryPath,http5.routeBase,http5.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(!http5||!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 http5.server.registerRoute("POST",source.path,wrapWithIpFilter(handler,http5.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"}}});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 import_utils180,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";import_utils180=require("@frontmcp/utils");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=`${(0,import_utils180.getMachineId)()}:${(0,import_utils180.randomUUID)()}`;this.logger=options.logger.child("EventOutbox");this.random=options.random??Math.random;const{runtime,deployment}=(0,import_utils180.getRuntimeContext)();this.usesTimers=deployment!=="serverless"&&runtime!=="edge"&&runtime!=="browser"}options;ownerId;logger;random;usesTimers;timers=new Map;inFlight=new Map;waitingForSlot=[];activeAttempts=0;activeByOwner=new Map;sweepTimer;lastSweepAt=0;stopped=false;async enqueue(delivery){const now=Date.now();const record={...delivery,id:`dlv_${(0,import_utils180.randomUUID)()}`,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){const stored=await this.read(id);if(!stored)return;const owner=stored.record.principalKey??`subscription:${stored.record.subscriptionId}`;if(this.hasSlotFor(owner))this.takeSlot(owner);else await new Promise(start=>this.waitingForSlot.push({owner,start}));try{await this.attemptOnce(id)}finally{this.freeSlot(owner)}}hasSlotFor(owner){const{concurrency}=this.options.settings;return this.activeAttempts<concurrency&&(this.activeByOwner.get(owner)??0)<this.slotsPerOwner()}slotsPerOwner(){const{concurrency,concurrencyPerSubscriber}=this.options.settings;return Math.min(concurrency,concurrencyPerSubscriber??Math.max(1,Math.ceil(concurrency/4)))}takeSlot(owner){this.activeAttempts+=1;this.activeByOwner.set(owner,(this.activeByOwner.get(owner)??0)+1)}freeSlot(owner){this.activeAttempts-=1;const held=(this.activeByOwner.get(owner)??1)-1;if(held>0)this.activeByOwner.set(owner,held);else this.activeByOwner.delete(owner);for(let index=0;index<this.waitingForSlot.length;){if(this.activeAttempts>=this.options.settings.concurrency)return;const waiter=this.waitingForSlot[index];if(!this.hasSlotFor(waiter.owner)){index+=1;continue}this.waitingForSlot.splice(index,1);this.takeSlot(waiter.owner);waiter.start()}}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))}}}});function newEventId(){return`evt_${(0,import_utils181.base64urlEncode)((0,import_utils181.randomBytes)(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 import_utils181,EVENT_ID_RANDOM_BYTES,ScopeEventPublisher;var init_event_publisher=__esm({"libs/sdk/src/event/event-publisher.ts"(){"use strict";import_utils181=require("@frontmcp/utils");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()}});function subscriberSummaryOf(subscriber){return{sub:subscriber.sub,...subscriber.iss!==void 0&&{iss:subscriber.iss},...subscriber.tenantId!==void 0&&{tenantId:subscriber.tenantId}}}function callbackHostOf(url){try{return new URL(url).host}catch{return""}}function webhookSubscriptionInfoOf(record){const{lastDeliveryAt,lastError,failedSince,failures,suspendedSince}=record.status;return{id:record.id,eventName:record.eventName,mode:"webhook",principalKey:record.principalKey,subscriber:subscriberSummaryOf(record.subscriber),arguments:record.arguments,dialect:record.dialect,createdAt:record.createdAt,updatedAt:record.updatedAt,expiresAt:record.expiresAt,verifiedAt:record.verifiedAt,lastAuthorizedAt:record.lastAuthorizedAt,active:record.active,delivery:{host:callbackHostOf(record.delivery.url),failures:failures??0,...suspendedSince!==void 0&&{suspendedSince},...lastDeliveryAt!==void 0&&{lastDeliveryAt},...lastError!==void 0&&{lastError},...failedSince!==void 0&&{failedSince}}}}function heldSubscriptionInfoOf(subscription,principalKey,args){return{id:subscription.id,eventName:subscription.name,principalKey,subscriber:subscriberSummaryOf(subscription.subscriber),arguments:args}}var init_event_subscription_info=__esm({"libs/sdk/src/event/event-subscription-info.ts"(){"use strict"}});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())}}}});var import_protocol72,import_utils182,EventRegistry;var init_event_registry=__esm({"libs/sdk/src/event/event.registry.ts"(){"use strict";import_protocol72=require("@frontmcp/protocol");import_utils182=require("@frontmcp/utils");init_common();init_errors();init_regsitry();init_event_subscription_info();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=(0,import_utils182.getRuntimeContext)();for(const[token,record]of this.defs){const eventName=record.metadata.name;if(!(0,import_utils182.isEntryAvailable)(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(name60){return this.eventsByName.get(name60)}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 import_protocol72.EVENT_DELIVERY_MODES.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))}async listSubscriptions(eventName){const listed=[];const store=this.subscriptions?.store;if(store){const eventNames=eventName===void 0?this.getEvents().map(event=>event.name):[eventName];for(const name60 of eventNames){for(const record of await store.listByEvent(name60))listed.push(webhookSubscriptionInfoOf(record))}}listed.push(...this.pollLeases?.list(eventName)??[],...this.streams?.list(eventName)??[]);return listed}getCapabilities(){if(!this.servesEvents())return{};return{events:{},extensions:{[import_protocol72.EVENTS_EXTENSION_ID]:{}}}}}}});function eventOutboundTargetOptions(allowLocal){return(0,import_utils183.isEdgeRuntime)()?{allowLocal,allowPlatformDns:true}:{allowLocal}}var import_utils183;var init_event_outbound=__esm({"libs/sdk/src/event/event-outbound.ts"(){"use strict";import_utils183=require("@frontmcp/utils")}});var import_lazy_zod133,import_protocol73,import_utils184,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";import_lazy_zod133=require("@frontmcp/lazy-zod");import_protocol73=require("@frontmcp/protocol");import_utils184=require("@frontmcp/utils");init_common();init_event_outbound();inputSchema32=import_lazy_zod133.internalZ.object({delivery:import_lazy_zod133.internalZ.any()});outputSchema31=import_lazy_zod133.internalZ.discriminatedUnion("result",[import_lazy_zod133.internalZ.object({result:import_lazy_zod133.internalZ.literal("delivered")}),import_lazy_zod133.internalZ.object({result:import_lazy_zod133.internalZ.literal("dropped"),reason:import_lazy_zod133.internalZ.enum(["gone","refused"])}),import_lazy_zod133.internalZ.object({result:import_lazy_zod133.internalZ.literal("failed"),category:import_protocol73.EventDeliveryErrorCategorySchema}),import_lazy_zod133.internalZ.object({result:import_lazy_zod133.internalZ.literal("waiting")})]);stateSchema34=import_lazy_zod133.internalZ.object({target:import_lazy_zod133.internalZ.any(),subscription:import_lazy_zod133.internalZ.any(),headers:import_lazy_zod133.internalZ.record(import_lazy_zod133.internalZ.string(),import_lazy_zod133.internalZ.string()),answer:import_lazy_zod133.internalZ.any(),outcome:import_lazy_zod133.internalZ.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=[(0,import_utils184.signingKeyOf)(secret)];if(previousSecret!==void 0&&(previousSecretUntil??0)>now){signingKeys.push((0,import_utils184.signingKeyOf)(previousSecret))}const message={id:delivery.webhookId,timestamp:Math.floor(now/1e3),body:delivery.body};this.state.set("headers",{"content-type":"application/json",[import_protocol73.MCP_SUBSCRIPTION_ID_HEADER]:delivery.subscriptionId,...(0,import_utils184.webhookSignatureHeaders)(message,signingKeys)})}async send(){if(this.state.outcome)return;const{webhook}=this.events.config;const answer=await(0,import_utils184.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=(0,import_utils184.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)}});function subscriptionWithoutSecrets(record){const{secret:_secret,previousSecret:_previous,previousSecretUntil:_until,...delivery}=record.delivery;return{...record,delivery}}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 import_utils185,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";import_utils185=require("@frontmcp/utils");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(0,import_utils185.sha256Hex)(text);return(0,import_utils185.bytesToHex)((0,import_utils185.hmacSha256)(textEncoder3.encode(secret),textEncoder3.encode(text)))}}}});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 import_utils186,SUBSCRIPTION_SWEEP_INTERVAL_MS,EventSubscriptions;var init_event_subscriptions=__esm({"libs/sdk/src/event/subscription/event-subscriptions.ts"(){"use strict";import_utils186=require("@frontmcp/utils");init_event_subscription_store();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=(0,import_utils186.canonicalJson)({principalKey,url,name:eventName,arguments:args});return{id:`sub_${(0,import_utils186.sha256Hex)(canonicalKey).slice(0,32)}`,argumentsKey:(0,import_utils186.canonicalJson)(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 notifyEnded(ending){const{ended}=this.options;if(!ended)return;try{await ended({...ending,record:subscriptionWithoutSecrets(ending.record)})}catch(error){this.logger.warn(`events:ended failed for subscription ${ending.record.id} (${ending.reason})`,error)}}async expire(id,now=Date.now()){const removed=await this.store.deleteExpired(id,now);if(!removed)return;await this.notifyUnsubscribed(removed,"expired");await this.notifyEnded({record:removed,reason:"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}=(0,import_utils186.getRuntimeContext)();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))}}}});var import_lazy_zod134,reasonSchema,inputSchema33,outputSchema32,stateSchema35,plan40,name40,Stage40,EventEndedFlow;var init_event_ended_flow=__esm({"libs/sdk/src/event/flows/event-ended.flow.ts"(){"use strict";import_lazy_zod134=require("@frontmcp/lazy-zod");init_common();init_event_subscription_store();init_event_subscriptions();reasonSchema=import_lazy_zod134.internalZ.enum(["unsubscribed","expired","closed","terminated"]);inputSchema33=import_lazy_zod134.internalZ.object({record:import_lazy_zod134.internalZ.any(),reason:reasonSchema,termination:import_lazy_zod134.internalZ.any().optional(),ctx:import_lazy_zod134.internalZ.unknown().optional()});outputSchema32=import_lazy_zod134.internalZ.object({});stateSchema35=import_lazy_zod134.internalZ.object({record:import_lazy_zod134.internalZ.any(),subscription:import_lazy_zod134.internalZ.any(),reason:reasonSchema,termination:import_lazy_zod134.internalZ.any()});plan40={pre:["parseInput"],execute:["notifyEnded"],post:["buildResult"],finalize:["finalize"]};name40="events:ended";({Stage:Stage40}=FlowHooksOf(name40));EventEndedFlow=class extends FlowBase{logger=this.scopeLogger.child("EventEndedFlow");async parseInput(){const{reason,termination}=this.input;const record=subscriptionWithoutSecrets(this.input.record);this.state.set({record,subscription:subscriptionRefOf(record),reason,...termination&&{termination}})}async notifyEnded(){const{record,reason}=this.state.required;this.logger.verbose(`notifyEnded: subscription ${record.id} to event "${record.eventName}" ended (${reason})`)}async buildResult(){this.respond({})}async finalize(){this.logger.verbose("finalize")}};__decorateClass([Stage40("parseInput")],EventEndedFlow.prototype,"parseInput",1);__decorateClass([Stage40("notifyEnded")],EventEndedFlow.prototype,"notifyEnded",1);__decorateClass([Stage40("buildResult")],EventEndedFlow.prototype,"buildResult",1);__decorateClass([Stage40("finalize")],EventEndedFlow.prototype,"finalize",1);EventEndedFlow=__decorateClass([FrontMcpFlow({name:name40,plan:plan40,inputSchema:inputSchema33,outputSchema:outputSchema32,access:"public"})],EventEndedFlow)}});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 import_protocol74,EVENT_DIALECTS;var init_event_dialect=__esm({"libs/sdk/src/event/event-dialect.ts"(){"use strict";import_protocol74=require("@frontmcp/protocol");EVENT_DIALECTS={"sep-3415":{errorCodes:import_protocol74.EVENTS_ERROR_CODES,webhookId:"message",sendsControlEnvelopes:true},sketch:{errorCodes:import_protocol74.EVENTS_SKETCH_ERROR_CODES,webhookId:"eventId",sendsControlEnvelopes:false}}}});function stringClaim(claims3,name60){const value=claims3[name60];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()}});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&&!(0,import_auth59.isPublicMode)(authOptions)){throw new EventForbiddenError(codes,eventName,"this server needs a signed-in caller")}const sessionId=verifiedSessionOf2(authInfo);const quotaKey=sessionId?`session:${sessionId}`:void 0;return{principalKey:void 0,...quotaKey&&{quotaKey},subscriber:ANONYMOUS_SUBSCRIBER}}function verifiedSessionOf2(authInfo){const recorded=authInfo.extra?.["sessionId"];return typeof recorded==="string"&&recorded!==""&&recorded!==STATELESS_SESSION_ID?recorded:void 0}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 input=argumentsAsParsed(()=>event.parseArguments(args),args);const result=await engine.evaluate(authorities,contextBuilder.build(authInfo,input));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 import_lazy_zod135.internalZ.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=(0,import_utils187.canonicalJson)({principalKey:reader.principalKey??null,mode,name:eventName,arguments:args});return{id:`sub_${(0,import_utils187.sha256Hex)(key).slice(0,32)}`,name:eventName,mode,subscriber:reader.subscriber}}var import_auth59,import_lazy_zod135,import_utils187,ANONYMOUS_SUBSCRIBER;var init_event_gates=__esm({"libs/sdk/src/event/event-gates.ts"(){"use strict";import_auth59=require("@frontmcp/auth");import_lazy_zod135=require("@frontmcp/lazy-zod");import_utils187=require("@frontmcp/utils");init_authorities_input();init_availability();init_errors();init_transport_types();init_event_subscriber();ANONYMOUS_SUBSCRIBER={sub:"",roles:[],permissions:[],scopes:[],claims:{}}}});function pollLeaseMs(nextPollMs){return Math.max(POLL_LEASE_MIN_MS,POLL_LEASE_INTERVALS*nextPollMs)}var import_utils188,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";import_utils188=require("@frontmcp/utils");init_event_subscription_info();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(quotaKey){if(this.leases.size>=MAX_POLL_LEASES)return true;let held=0;for(const lease of this.leases.values()){if(lease.quotaKey===quotaKey)held+=1}return held>=this.options.maxPerPrincipal}has(subscriptionId){return this.leases.has(subscriptionId)||this.starting.has(subscriptionId)}list(eventName){const listed=[];for(const lease of this.leases.values()){if(eventName!==void 0&&lease.subscription.name!==eventName)continue;const held=heldSubscriptionInfoOf(lease.subscription,lease.principalKey,lease.arguments);listed.push({...held,mode:"poll",expiresAt:lease.expiresAt})}return listed}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,quotaKey:request2.quotaKey??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}=(0,import_utils188.getRuntimeContext)();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:name60}=lease.subscription;this.logger.warn(`onUnsubscribe of event "${name60}" 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()}});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");await subscriptions.notifyEnded({record:removed,reason:"terminated",termination:error});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,principalKey:removed.principalKey,eventName:removed.eventName,body:JSON.stringify({type:"terminated",error}),webhookId:(0,import_utils189.generateWebhookMessageId)("terminated"),target:{url,secret,previousSecret,previousSecretUntil}})}var import_utils189;var init_event_subscription_termination=__esm({"libs/sdk/src/event/subscription/event-subscription-termination.ts"(){"use strict";import_utils189=require("@frontmcp/utils");init_event_dialect()}});function eventWebhookIdOf(subscriptionId,eventId){return`msg_${(0,import_utils190.sha256Hex)(`${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 import_lazy_zod136,import_protocol75,import_utils190,EVENT_DELIVERY_MAX_BYTES,audienceValueSchema,inputSchema34,outputSchema33,stateSchema36,plan41,name41,Stage41,encoder10,EventPublishFlow;var init_event_publish_flow=__esm({"libs/sdk/src/event/flows/event-publish.flow.ts"(){"use strict";import_lazy_zod136=require("@frontmcp/lazy-zod");import_protocol75=require("@frontmcp/protocol");import_utils190=require("@frontmcp/utils");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=import_lazy_zod136.internalZ.union([import_lazy_zod136.internalZ.string(),import_lazy_zod136.internalZ.array(import_lazy_zod136.internalZ.string())]);inputSchema34=import_lazy_zod136.internalZ.object({occurrence:import_protocol75.EventOccurrenceSchema,subscriptionId:import_lazy_zod136.internalZ.string().optional(),audience:import_lazy_zod136.internalZ.object({sub:audienceValueSchema.optional(),tenantId:audienceValueSchema.optional(),roles:import_lazy_zod136.internalZ.object({any:import_lazy_zod136.internalZ.array(import_lazy_zod136.internalZ.string()).optional(),all:import_lazy_zod136.internalZ.array(import_lazy_zod136.internalZ.string()).optional()}).optional()}).optional()});outputSchema33=import_lazy_zod136.internalZ.object({eventId:import_lazy_zod136.internalZ.string(),matched:import_lazy_zod136.internalZ.number().int().nonnegative()});stateSchema36=import_lazy_zod136.internalZ.object({event:import_lazy_zod136.internalZ.instanceof(EventEntry),context:import_lazy_zod136.internalZ.any(),subscriptions:import_lazy_zod136.internalZ.array(import_lazy_zod136.internalZ.any()),deliveries:import_lazy_zod136.internalZ.array(import_lazy_zod136.internalZ.any()),buffered:import_lazy_zod136.internalZ.any()});plan41={pre:["validate","bufferOccurrence","pushToStreams"],execute:["loadSubscriptions","dropInactive","filterByAudience","reauthorize","match","transform","enforceBodyLimit","enqueue","bridgeToBus","notifyChannelSessions"],post:["buildResult"]};name41="events:publish";({Stage:Stage41}=FlowHooksOf(name41));encoder10=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:import_protocol75.EventOccurrenceSchema.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=encoder10.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,principalKey:subscription.principalKey,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([Stage41("validate")],EventPublishFlow.prototype,"validate",1);__decorateClass([Stage41("bufferOccurrence")],EventPublishFlow.prototype,"bufferOccurrence",1);__decorateClass([Stage41("pushToStreams")],EventPublishFlow.prototype,"pushToStreams",1);__decorateClass([Stage41("loadSubscriptions")],EventPublishFlow.prototype,"loadSubscriptions",1);__decorateClass([Stage41("dropInactive")],EventPublishFlow.prototype,"dropInactive",1);__decorateClass([Stage41("filterByAudience")],EventPublishFlow.prototype,"filterByAudience",1);__decorateClass([Stage41("reauthorize")],EventPublishFlow.prototype,"reauthorize",1);__decorateClass([Stage41("match")],EventPublishFlow.prototype,"match",1);__decorateClass([Stage41("transform")],EventPublishFlow.prototype,"transform",1);__decorateClass([Stage41("enforceBodyLimit")],EventPublishFlow.prototype,"enforceBodyLimit",1);__decorateClass([Stage41("enqueue")],EventPublishFlow.prototype,"enqueue",1);__decorateClass([Stage41("bridgeToBus")],EventPublishFlow.prototype,"bridgeToBus",1);__decorateClass([Stage41("notifyChannelSessions")],EventPublishFlow.prototype,"notifyChannelSessions",1);__decorateClass([Stage41("buildResult")],EventPublishFlow.prototype,"buildResult",1);EventPublishFlow=__decorateClass([FrontMcpFlow({name:name41,plan:plan41,inputSchema:inputSchema34,outputSchema:outputSchema33,access:"public"})],EventPublishFlow)}});var import_lazy_zod137,import_protocol76,inputSchema35,outputSchema34,stateSchema37,plan42,name42,Stage42,EventPollFlow;var init_event_poll_flow=__esm({"libs/sdk/src/event/flows/event-poll.flow.ts"(){"use strict";import_lazy_zod137=require("@frontmcp/lazy-zod");import_protocol76=require("@frontmcp/protocol");init_common();init_errors();init_event_dialect();init_event_gates();init_event_publisher();init_event_poll_leases();init_event_publish_flow();inputSchema35=import_lazy_zod137.internalZ.object({request:import_protocol76.PollEventsRequestSchema,ctx:import_lazy_zod137.internalZ.unknown()});outputSchema34=import_protocol76.PollEventsResultSchema;stateSchema37=import_lazy_zod137.internalZ.object({authInfo:import_lazy_zod137.internalZ.any(),dialect:import_lazy_zod137.internalZ.enum(["sep-3415","sketch"]),event:import_lazy_zod137.internalZ.instanceof(EventEntry),reader:import_lazy_zod137.internalZ.any(),arguments:import_lazy_zod137.internalZ.record(import_lazy_zod137.internalZ.string(),import_lazy_zod137.internalZ.unknown()),context:import_lazy_zod137.internalZ.any(),subscription:import_lazy_zod137.internalZ.any(),result:import_lazy_zod137.internalZ.any()});plan42={pre:["parseInput","resolveDialect","findEvent","resolveReader","checkEntryAuthorities","validateArguments","authorize"],execute:["renewLease","readEvents"],post:["buildResult"],finalize:["finalize"]};name42="events:poll";({Stage:Stage42}=FlowHooksOf(name42));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;const quotaKey=reader.quotaKey??reader.principalKey;if(!leases.has(subscription.id)&&leases.isFull(quotaKey)){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,quotaKey,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 import_protocol76.EventOccurrenceSchema.parse(transformed)}catch(error){this.logger.warn(`readEvents: event "${occurrence.name}" failed for poll subscription ${subscription.id}`,error);return void 0}}};__decorateClass([Stage42("parseInput")],EventPollFlow.prototype,"parseInput",1);__decorateClass([Stage42("resolveDialect")],EventPollFlow.prototype,"resolveDialect",1);__decorateClass([Stage42("findEvent")],EventPollFlow.prototype,"findEvent",1);__decorateClass([Stage42("resolveReader")],EventPollFlow.prototype,"resolveReader",1);__decorateClass([Stage42("checkEntryAuthorities")],EventPollFlow.prototype,"checkEntryAuthorities",1);__decorateClass([Stage42("validateArguments")],EventPollFlow.prototype,"validateArguments",1);__decorateClass([Stage42("authorize")],EventPollFlow.prototype,"authorize",1);__decorateClass([Stage42("renewLease")],EventPollFlow.prototype,"renewLease",1);__decorateClass([Stage42("readEvents")],EventPollFlow.prototype,"readEvents",1);__decorateClass([Stage42("buildResult")],EventPollFlow.prototype,"buildResult",1);__decorateClass([Stage42("finalize")],EventPollFlow.prototype,"finalize",1);EventPollFlow=__decorateClass([FrontMcpFlow({name:name42,plan:plan42,inputSchema:inputSchema35,outputSchema:outputSchema34,access:"authorized"})],EventPollFlow)}});var import_protocol77,MAX_QUEUED_NOTIFICATIONS,EventStream;var init_event_stream=__esm({"libs/sdk/src/event/stream/event-stream.ts"(){"use strict";import_protocol77=require("@frontmcp/protocol");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(resolve5=>this.releaseDelivery=resolve5):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 arguments(){return this.options.arguments}get principalKey(){return this.options.reader.principalKey}get quotaKey(){return this.options.reader.quotaKey??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(import_protocol77.EVENTS_NOTIFICATIONS.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(resolve5=>this.wake=resolve5);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(import_protocol77.EVENTS_NOTIFICATIONS.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 import_protocol77.EventOccurrenceSchema.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(import_protocol77.EVENTS_NOTIFICATIONS.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(import_protocol77.EVENTS_NOTIFICATIONS.active,{cursor:this.cursor,truncated})}pushEvent(occurrence){this.push(import_protocol77.EVENTS_NOTIFICATIONS.event,{...occurrence,cursor:this.cursor})}push(method,params){if(this.closed)return;const meta={[import_protocol77.MCP_20260728_META.subscriptionId]:this.options.requestId};if(this.queue.length>=MAX_QUEUED_NOTIFICATIONS){this.queue.length=0;this.queue.push({method:import_protocol77.EVENTS_NOTIFICATIONS.active,params:{cursor:this.cursor,truncated:true,_meta:meta}})}this.queue.push({method,params:{...params,_meta:meta}});this.wake?.()}}}});var import_lazy_zod138,import_protocol78,inputSchema36,outputSchema35,stateSchema38,plan43,name43,Stage43,EventStreamFlow;var init_event_stream_flow=__esm({"libs/sdk/src/event/flows/event-stream.flow.ts"(){"use strict";import_lazy_zod138=require("@frontmcp/lazy-zod");import_protocol78=require("@frontmcp/protocol");init_common();init_errors();init_event_dialect();init_event_gates();init_event_reauthorization();init_event_stream();inputSchema36=import_lazy_zod138.internalZ.object({request:import_protocol78.StreamEventsRequestSchema,ctx:import_lazy_zod138.internalZ.unknown(),requestId:import_lazy_zod138.internalZ.union([import_lazy_zod138.internalZ.string(),import_lazy_zod138.internalZ.number()]),signal:import_lazy_zod138.internalZ.any().optional()});outputSchema35=import_lazy_zod138.internalZ.object({stream:import_lazy_zod138.internalZ.instanceof(EventStream)});stateSchema38=import_lazy_zod138.internalZ.object({authInfo:import_lazy_zod138.internalZ.any(),dialect:import_lazy_zod138.internalZ.enum(["sep-3415","sketch"]),event:import_lazy_zod138.internalZ.instanceof(EventEntry),reader:import_lazy_zod138.internalZ.any(),arguments:import_lazy_zod138.internalZ.record(import_lazy_zod138.internalZ.string(),import_lazy_zod138.internalZ.unknown()),context:import_lazy_zod138.internalZ.any(),subscription:import_lazy_zod138.internalZ.any(),stream:import_lazy_zod138.internalZ.instanceof(EventStream)});plan43={pre:["parseInput","resolveDialect","findEvent","resolveReader","checkEntryAuthorities","validateArguments","authorize"],execute:["openStream"],post:["buildResult"],finalize:["finalize"]};name43="events:stream";({Stage:Stage43}=FlowHooksOf(name43));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([Stage43("parseInput")],EventStreamFlow.prototype,"parseInput",1);__decorateClass([Stage43("resolveDialect")],EventStreamFlow.prototype,"resolveDialect",1);__decorateClass([Stage43("findEvent")],EventStreamFlow.prototype,"findEvent",1);__decorateClass([Stage43("resolveReader")],EventStreamFlow.prototype,"resolveReader",1);__decorateClass([Stage43("checkEntryAuthorities")],EventStreamFlow.prototype,"checkEntryAuthorities",1);__decorateClass([Stage43("validateArguments")],EventStreamFlow.prototype,"validateArguments",1);__decorateClass([Stage43("authorize")],EventStreamFlow.prototype,"authorize",1);__decorateClass([Stage43("openStream")],EventStreamFlow.prototype,"openStream",1);__decorateClass([Stage43("buildResult")],EventStreamFlow.prototype,"buildResult",1);__decorateClass([Stage43("finalize")],EventStreamFlow.prototype,"finalize",1);EventStreamFlow=__decorateClass([FrontMcpFlow({name:name43,plan:plan43,inputSchema:inputSchema36,outputSchema:outputSchema35,access:"authorized"})],EventStreamFlow)}});function reactivatedStatus(status={}){const{failures:_failures,suspendedSince:_suspendedSince,...kept}=status;return kept}var import_lazy_zod139,import_protocol79,import_utils191,inputSchema37,outputSchema36,stateSchema39,plan44,name44,Stage44,URL_PROBLEMS,EventSubscribeFlow;var init_event_subscribe_flow=__esm({"libs/sdk/src/event/flows/event-subscribe.flow.ts"(){"use strict";import_lazy_zod139=require("@frontmcp/lazy-zod");import_protocol79=require("@frontmcp/protocol");import_utils191=require("@frontmcp/utils");init_common();init_availability();init_errors();init_event_dialect();init_event_gates();init_event_subscriber();init_event_subscriptions();inputSchema37=import_lazy_zod139.internalZ.object({request:import_protocol79.SubscribeEventRequestSchema,ctx:import_lazy_zod139.internalZ.unknown()});outputSchema36=import_protocol79.SubscribeEventResultSchema;stateSchema39=import_lazy_zod139.internalZ.object({authInfo:import_lazy_zod139.internalZ.any(),dialect:import_lazy_zod139.internalZ.enum(["sep-3415","sketch"]),event:import_lazy_zod139.internalZ.instanceof(EventEntry),owner:import_lazy_zod139.internalZ.any(),arguments:import_lazy_zod139.internalZ.record(import_lazy_zod139.internalZ.string(),import_lazy_zod139.internalZ.unknown()),subscriptionId:import_lazy_zod139.internalZ.string(),argumentsKey:import_lazy_zod139.internalZ.string(),existing:import_lazy_zod139.internalZ.any(),verifiedAt:import_lazy_zod139.internalZ.number(),expiresAt:import_lazy_zod139.internalZ.number().nullable(),record:import_lazy_zod139.internalZ.any(),truncated:import_lazy_zod139.internalZ.boolean().optional()});plan44={pre:["parseInput","resolveDialect","findEvent","checkAvailability","requireWebhookMode","requireSubscriber","checkEntryAuthorities","validateArguments","authorize","validateDelivery"],execute:["findSubscription","enforceLimits","verifyCallback","grantTtl","upsertSubscription","notifySubscribed","startReplay"],post:["buildResult"],finalize:["finalize"]};name44="events:subscribe";({Stage:Stage44}=FlowHooksOf(name44));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{event,authInfo}=this.state.required;await assertEventAuthorities(this.scope,event,authInfo,this.input.request.params.arguments??{},this.codes)}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 import_lazy_zod139.internalZ.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=(0,import_utils191.validateOutboundUrl)(url,{allowLocal});if(!urlCheck.ok)throw new InvalidInputError(`Invalid delivery.url: ${URL_PROBLEMS[urlCheck.problem]}`);if(!(0,import_utils191.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([Stage44("parseInput")],EventSubscribeFlow.prototype,"parseInput",1);__decorateClass([Stage44("resolveDialect")],EventSubscribeFlow.prototype,"resolveDialect",1);__decorateClass([Stage44("findEvent")],EventSubscribeFlow.prototype,"findEvent",1);__decorateClass([Stage44("checkAvailability")],EventSubscribeFlow.prototype,"checkAvailability",1);__decorateClass([Stage44("requireWebhookMode")],EventSubscribeFlow.prototype,"requireWebhookMode",1);__decorateClass([Stage44("requireSubscriber")],EventSubscribeFlow.prototype,"requireSubscriber",1);__decorateClass([Stage44("checkEntryAuthorities")],EventSubscribeFlow.prototype,"checkEntryAuthorities",1);__decorateClass([Stage44("validateArguments")],EventSubscribeFlow.prototype,"validateArguments",1);__decorateClass([Stage44("authorize")],EventSubscribeFlow.prototype,"authorize",1);__decorateClass([Stage44("validateDelivery")],EventSubscribeFlow.prototype,"validateDelivery",1);__decorateClass([Stage44("findSubscription")],EventSubscribeFlow.prototype,"findSubscription",1);__decorateClass([Stage44("enforceLimits")],EventSubscribeFlow.prototype,"enforceLimits",1);__decorateClass([Stage44("verifyCallback")],EventSubscribeFlow.prototype,"verifyCallback",1);__decorateClass([Stage44("grantTtl")],EventSubscribeFlow.prototype,"grantTtl",1);__decorateClass([Stage44("upsertSubscription")],EventSubscribeFlow.prototype,"upsertSubscription",1);__decorateClass([Stage44("notifySubscribed")],EventSubscribeFlow.prototype,"notifySubscribed",1);__decorateClass([Stage44("startReplay")],EventSubscribeFlow.prototype,"startReplay",1);__decorateClass([Stage44("buildResult")],EventSubscribeFlow.prototype,"buildResult",1);__decorateClass([Stage44("finalize")],EventSubscribeFlow.prototype,"finalize",1);EventSubscribeFlow=__decorateClass([FrontMcpFlow({name:name44,plan:plan44,inputSchema:inputSchema37,outputSchema:outputSchema36,access:"authorized"})],EventSubscribeFlow)}});var import_lazy_zod140,import_protocol80,inputSchema38,outputSchema37,stateSchema40,plan45,name45,Stage45,EventUnsubscribeFlow;var init_event_unsubscribe_flow=__esm({"libs/sdk/src/event/flows/event-unsubscribe.flow.ts"(){"use strict";import_lazy_zod140=require("@frontmcp/lazy-zod");import_protocol80=require("@frontmcp/protocol");init_common();init_errors();init_event_dialect();init_event_subscriber();init_event_subscription_store();inputSchema38=import_lazy_zod140.internalZ.object({request:import_protocol80.UnsubscribeEventRequestSchema,ctx:import_lazy_zod140.internalZ.unknown()});outputSchema37=import_protocol80.UnsubscribeEventResultSchema;stateSchema40=import_lazy_zod140.internalZ.object({authInfo:import_lazy_zod140.internalZ.any(),dialect:import_lazy_zod140.internalZ.enum(["sep-3415","sketch"]),owner:import_lazy_zod140.internalZ.any(),subscriptionId:import_lazy_zod140.internalZ.string(),removed:import_lazy_zod140.internalZ.any()});plan45={pre:["parseInput","resolveDialect","requireSubscriber"],execute:["removeSubscription"],post:["buildResult"],finalize:["finalize"]};name45="events:unsubscribe";({Stage:Stage45}=FlowHooksOf(name45));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);this.state.set({subscriptionId:identity.id,removed:removed&&subscriptionWithoutSecrets(removed)});if(!removed)return;await this.subscriptions.notifyUnsubscribed(removed,"unsubscribed",authInfo);await this.subscriptions.notifyEnded({record:removed,reason:"unsubscribed"});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([Stage45("parseInput")],EventUnsubscribeFlow.prototype,"parseInput",1);__decorateClass([Stage45("resolveDialect")],EventUnsubscribeFlow.prototype,"resolveDialect",1);__decorateClass([Stage45("requireSubscriber")],EventUnsubscribeFlow.prototype,"requireSubscriber",1);__decorateClass([Stage45("removeSubscription")],EventUnsubscribeFlow.prototype,"removeSubscription",1);__decorateClass([Stage45("buildResult")],EventUnsubscribeFlow.prototype,"buildResult",1);__decorateClass([Stage45("finalize")],EventUnsubscribeFlow.prototype,"finalize",1);EventUnsubscribeFlow=__decorateClass([FrontMcpFlow({name:name45,plan:plan45,inputSchema:inputSchema38,outputSchema:outputSchema37,access:"authorized"})],EventUnsubscribeFlow)}});function compareByName(left,right){if(left.event.name<right.event.name)return-1;return left.event.name>right.event.name?1:0}var import_lazy_zod141,import_protocol81,EVENTS_LIST_PAGE_SIZE,inputSchema39,outputSchema38,stateSchema41,plan46,name46,Stage46,ListEventsFlow;var init_list_events_flow=__esm({"libs/sdk/src/event/flows/list-events.flow.ts"(){"use strict";import_lazy_zod141=require("@frontmcp/lazy-zod");import_protocol81=require("@frontmcp/protocol");init_common();init_availability();init_offset_cursor_utils();init_errors();init_entry_authorized();EVENTS_LIST_PAGE_SIZE=40;inputSchema39=import_lazy_zod141.internalZ.object({request:import_protocol81.ListEventsRequestSchema,ctx:import_lazy_zod141.internalZ.unknown()});outputSchema38=import_protocol81.ListEventsResultSchema;stateSchema41=import_lazy_zod141.internalZ.object({cursor:import_lazy_zod141.internalZ.string().optional(),authInfo:import_lazy_zod141.internalZ.any(),events:import_lazy_zod141.internalZ.array(import_lazy_zod141.internalZ.object({event:import_lazy_zod141.internalZ.instanceof(EventEntry),delivery:import_lazy_zod141.internalZ.array(import_protocol81.EventDeliveryModeSchema)}))});plan46={pre:["parseInput"],execute:["findEvents","filterByAvailability","filterByAuthorities","filterByDiscovery"],post:["parseEvents"],finalize:["finalize"]};name46="events:list";({Stage:Stage46}=FlowHooksOf(name46));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([Stage46("parseInput")],ListEventsFlow.prototype,"parseInput",1);__decorateClass([Stage46("findEvents")],ListEventsFlow.prototype,"findEvents",1);__decorateClass([Stage46("filterByAvailability")],ListEventsFlow.prototype,"filterByAvailability",1);__decorateClass([Stage46("filterByAuthorities")],ListEventsFlow.prototype,"filterByAuthorities",1);__decorateClass([Stage46("filterByDiscovery")],ListEventsFlow.prototype,"filterByDiscovery",1);__decorateClass([Stage46("parseEvents")],ListEventsFlow.prototype,"parseEvents",1);__decorateClass([Stage46("finalize")],ListEventsFlow.prototype,"finalize",1);ListEventsFlow=__decorateClass([FrontMcpFlow({name:name46,plan:plan46,inputSchema:inputSchema39,outputSchema:outputSchema38,access:"authorized"})],ListEventsFlow)}});var import_utils192,CURSOR_SEPARATOR,EventBuffer;var init_event_buffer=__esm({"libs/sdk/src/event/poll/event-buffer.ts"(){"use strict";import_utils192=require("@frontmcp/utils");CURSOR_SEPARATOR=".";EventBuffer=class{constructor(options){this.options=options;this.bootId=(0,import_utils192.randomUUID)().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)}}}});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 import_lazy_zod142,EVENT_PUBLISH_MAX_BODY_BYTES,EVENT_ID_PATTERN,audienceValueSchema2,publishRequestSchema,inputSchema40,outputSchema39,stateSchema42,plan47,name47,Stage47,decoder3,EventPublishHttpFlow;var init_event_publish_http_flow=__esm({"libs/sdk/src/event/flows/event-publish-http.flow.ts"(){"use strict";import_lazy_zod142=require("@frontmcp/lazy-zod");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=import_lazy_zod142.internalZ.union([import_lazy_zod142.internalZ.string(),import_lazy_zod142.internalZ.array(import_lazy_zod142.internalZ.string())]);publishRequestSchema=import_lazy_zod142.internalZ.object({name:import_lazy_zod142.internalZ.string().min(1),data:import_lazy_zod142.internalZ.record(import_lazy_zod142.internalZ.string(),import_lazy_zod142.internalZ.unknown()),eventId:import_lazy_zod142.internalZ.string().regex(EVENT_ID_PATTERN,"eventId must be 1 to 255 visible ASCII characters").optional(),timestamp:import_lazy_zod142.internalZ.string().refine(isTimestamp,"timestamp must be a date such as 2026-10-02T12:00:00Z").optional(),subscriptionId:import_lazy_zod142.internalZ.string().min(1).optional(),audience:import_lazy_zod142.internalZ.object({sub:audienceValueSchema2.optional(),tenantId:audienceValueSchema2.optional(),roles:import_lazy_zod142.internalZ.object({any:import_lazy_zod142.internalZ.array(import_lazy_zod142.internalZ.string()).optional(),all:import_lazy_zod142.internalZ.array(import_lazy_zod142.internalZ.string()).optional()}).strict().optional()}).strict().optional()}).strict();inputSchema40=httpInputSchema;outputSchema39=HttpJsonSchema;stateSchema42=import_lazy_zod142.internalZ.object({body:import_lazy_zod142.internalZ.custom(),caller:import_lazy_zod142.internalZ.custom().optional(),publication:publishRequestSchema,event:import_lazy_zod142.internalZ.instanceof(EventEntry),claimedEventId:import_lazy_zod142.internalZ.string().optional(),claimToken:import_lazy_zod142.internalZ.string().optional(),result:import_lazy_zod142.internalZ.object({eventId:import_lazy_zod142.internalZ.string(),matched:import_lazy_zod142.internalZ.number()}),flowError:import_lazy_zod142.internalZ.instanceof(Error).optional()});plan47={pre:["checkIpFilter","acquireQuota","readBody","authenticate","parseBody","checkAuthorities","findEvent","validatePayload"],execute:["claimEventId","publish","rememberResult","buildResponse"],finalize:["finalize"]};name47="events:publish-http";({Stage:Stage47}=FlowHooksOf(name47));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 import_lazy_zod142.internalZ.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([Stage47("checkIpFilter")],EventPublishHttpFlow.prototype,"checkIpFilter",1);__decorateClass([Stage47("acquireQuota")],EventPublishHttpFlow.prototype,"acquireQuota",1);__decorateClass([Stage47("readBody")],EventPublishHttpFlow.prototype,"readBody",1);__decorateClass([Stage47("authenticate")],EventPublishHttpFlow.prototype,"authenticate",1);__decorateClass([Stage47("parseBody")],EventPublishHttpFlow.prototype,"parseBody",1);__decorateClass([Stage47("checkAuthorities")],EventPublishHttpFlow.prototype,"checkAuthorities",1);__decorateClass([Stage47("findEvent")],EventPublishHttpFlow.prototype,"findEvent",1);__decorateClass([Stage47("validatePayload")],EventPublishHttpFlow.prototype,"validatePayload",1);__decorateClass([Stage47("claimEventId")],EventPublishHttpFlow.prototype,"claimEventId",1);__decorateClass([Stage47("publish")],EventPublishHttpFlow.prototype,"publish",1);__decorateClass([Stage47("rememberResult")],EventPublishHttpFlow.prototype,"rememberResult",1);__decorateClass([Stage47("buildResponse")],EventPublishHttpFlow.prototype,"buildResponse",1);__decorateClass([Stage47("finalize")],EventPublishHttpFlow.prototype,"finalize",1);EventPublishHttpFlow=__decorateClass([FrontMcpFlow({name:name47,plan:plan47,inputSchema:inputSchema40,outputSchema:outputSchema39,access:"public",middleware:{method:"POST"}})],EventPublishHttpFlow)}});function eventsSecretFromEnv(){return(0,import_utils193.getEnv)("MCP_EVENTS_SECRET")||(0,import_utils193.getEnv)("MCP_SESSION_SECRET")||(0,import_utils193.getEnv)("MCP_SERVER_SECRET")||void 0}function storageConfigOf(options){const{redis,sqlite}=options;if(sqlite)return{type:"sqlite",sqlite};if(!redis)return{type:"memory"};if(!isRedisConnectionOptions(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.")}return redisStorageConfigOf(redis)}async function openStorage(config,keyPrefix){try{return await(0,import_utils193.createStorage)({...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 import_utils193;var init_event_subscription_store_factory=__esm({"libs/sdk/src/event/subscription/event-subscription-store.factory.ts"(){"use strict";import_utils193=require("@frontmcp/utils");init_common();init_errors();init_event_subscription_store()}});function pendingRecordOf(token){return JSON.stringify({pending:token})}function isPending(record){return"pending"in record}var import_utils194,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";import_utils194=require("@frontmcp/utils");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=(0,import_utils194.randomUUID)();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+(0,import_utils194.sha256Hex)(JSON.stringify([this.scopeId,eventName,eventId])).slice(0,40)}}}});function assertPathFree(scope,path7){const reserved=computeReservedPaths(scope.entryPath,scope.routeBase,servedHealthPaths(scope.metadata.health));try{assertNotReserved("POST",path7,reserved)}catch(error){if(!(error instanceof ReservedRouteCollisionError))throw error;throw new EventPublishEndpointError(`events.publishEndpoint.path "${path7}" 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,path7)!==void 0);if(taken){throw new EventPublishEndpointError(`events.publishEndpoint.path "${path7}" 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 path7=`${normalizeScopeBase(scope.routeBase)}${configuredPath}`;assertPathFree(scope,path7);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:path7,secret,authorities,replays:new WorkflowWebhookReplayGuard,idempotency:new EventPublishIdempotency(storage,scope.id)};await scope.registryFlows(EventPublishHttpFlow);logger.info(`Events can be published over HTTP: POST ${path7} (${secret?"signed requests":"bearer callers"})`);if(!secret&&authorities===void 0){logger.warn(`POST ${path7} 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()}});function isSameReadPosition(current,expected){return current?.cursor===expected.cursor&¤t.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 import_utils195,REPLAY_LEASE_MS,REPLAY_STOP_GRACE_MS,MAX_PENDING_BATCHES,MAX_ROUNDS_PER_TICK,encoder11,EventReplays;var init_event_replays=__esm({"libs/sdk/src/event/replay/event-replays.ts"(){"use strict";import_utils195=require("@frontmcp/utils");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;encoder11=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:${(0,import_utils195.sha256Hex)(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,principalKey:record.principalKey,eventName:record.eventName,body:JSON.stringify({type:"gap",cursor:replay.watermark}),webhookId:(0,import_utils195.generateWebhookMessageId)("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=encoder11.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,principalKey:record.principalKey,eventName:event.name,body,webhookId:usesEventId?eventId:(0,import_utils195.generateWebhookMessageId)()})}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}}}}});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=import_protocol82.EventOccurrenceSchema.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 import_protocol82,import_utils196,EVENT_RELAY_CHANNEL,MAX_OPEN_STREAMS,EventStreams;var init_event_streams=__esm({"libs/sdk/src/event/stream/event-streams.ts"(){"use strict";import_protocol82=require("@frontmcp/protocol");import_utils196=require("@frontmcp/utils");init_event_subscription_info();EVENT_RELAY_CHANNEL="occurrences";MAX_OPEN_STREAMS=1e4;EventStreams=class{constructor(options){this.options=options;this.nodeId=(0,import_utils196.randomUUID)();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}list(eventName){const listed=[];for(const stream of this.held){if(stream.isClosed||eventName!==void 0&&stream.eventName!==eventName)continue;listed.push({...heldSubscriptionInfoOf(stream.subscription,stream.principalKey,stream.arguments),mode:"push"})}return listed}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(quotaKey){if(this.held.size>=MAX_OPEN_STREAMS)return true;let heldByReader=0;for(const stream of this.held){if(stream.quotaKey===quotaKey)heldByReader+=1}return heldByReader>=this.options.maxPerPrincipal}reserve(stream){if(this.held.has(stream))return true;if(this.isFull(stream.quotaKey))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))}}}});function isSameText(left,right){const leftBytes=encoder12.encode(left);const rightBytes=encoder12.encode(right);return leftBytes.length===rightBytes.length&&(0,import_utils197.timingSafeEqual)(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 import_protocol83,import_utils197,VERIFICATION_ATTEMPTS_PER_HOST,VERIFICATION_WINDOW_MS,WELL_KNOWN_CACHE_MS,WELL_KNOWN_MAX_BYTES,CHALLENGE_BYTES,CHALLENGE_ANSWER_MAX_BYTES,MAX_CACHED_ENTRIES,encoder12,ExpiringMap,EventCallbackVerifier;var init_event_callback_verifier=__esm({"libs/sdk/src/event/subscription/event-callback-verifier.ts"(){"use strict";import_protocol83=require("@frontmcp/protocol");import_utils197=require("@frontmcp/utils");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;encoder12=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??import_utils197.sendOutboundRequest;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=(0,import_utils197.sha256Hex)(`${request2.principalKey}
|
|
337
337
|
${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(import_protocol83.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=(0,import_utils197.base64urlEncode)((0,import_utils197.randomBytes)(CHALLENGE_BYTES));const body=JSON.stringify({type:"verification",challenge:nonce});const message={id:(0,import_utils197.generateWebhookMessageId)("verification"),timestamp:Math.floor(now/1e3),body};const result=await this.send({url:request2.url,method:"POST",headers:{"content-type":"application/json",[import_protocol83.MCP_SUBSCRIPTION_ID_HEADER]:request2.subscriptionId,...(0,import_utils197.webhookSignatureHeaders)(message,[(0,import_utils197.signingKeyOf)(request2.secret)])},body,timeoutMs:this.options.timeoutMs,maxResponseBytes:CHALLENGE_ANSWER_MAX_BYTES,...eventOutboundTargetOptions(this.options.allowLocal)});const category=(0,import_utils197.outboundFailureCategory)(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});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&&!(0,import_auth60.isPublicMode)(authOptions)}function storeKeyPrefixOf(scope,eventsConfig){const configuredPrefix=eventsConfig.store?.keyPrefix;if(configuredPrefix)return configuredPrefix;return`mcp:events:${(0,import_utils198.sha256Hex)(`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,ended:ending=>scope.runFlow("events:ended",ending.reason==="unsubscribed"?ending:{...ending,ctx:{ownRequest:true}})});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,EventEndedFlow);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&&(0,import_utils198.getRuntimeContext)().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(0,import_utils198.getRuntimeContext)().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:import_di4.ProviderScope.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 import_auth60,import_utils198;var init_event_scope_helper=__esm({"libs/sdk/src/event/event-scope.helper.ts"(){"use strict";import_auth60=require("@frontmcp/auth");import_utils198=require("@frontmcp/utils");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_ended_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()}});var import_auth61;var init_cimd=__esm({"libs/sdk/src/auth/cimd/index.ts"(){"use strict";import_auth61=require("@frontmcp/auth")}});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:import_di50.ProviderScope.GLOBAL,name:"SessionCredentialVault"};const accessorProvider={provide:import_auth62.CREDENTIALS_ACCESSOR,inject:()=>[FRONTMCP_CONTEXT,FrontMcpLogger],useFactory:(ctx,logger)=>new import_auth62.CredentialsAccessorImpl({vault,resolveSub:()=>resolveRequestSub(ctx),signingSecret,basePath,resumeTtlMs,logger:logger.child("CredentialsAccessor")}),scope:import_di50.ProviderScope.CONTEXT,name:"CredentialsAccessor"};return[vaultProvider,accessorProvider]}var import_auth62,import_di50,SESSION_CREDENTIAL_VAULT;var init_credentials_providers=__esm({"libs/sdk/src/auth/credentials/credentials.providers.ts"(){"use strict";import_auth62=require("@frontmcp/auth");import_di50=require("@frontmcp/di");init_common();init_frontmcp_context_provider();SESSION_CREDENTIAL_VAULT=Symbol.for("frontmcp:SESSION_CREDENTIAL_VAULT")}});var import_auth63,credentialsContextExtension;var init_credentials_context_extension=__esm({"libs/sdk/src/auth/credentials/credentials.context-extension.ts"(){"use strict";import_auth63=require("@frontmcp/auth");credentialsContextExtension={property:"credentials",token:import_auth63.CREDENTIALS_ACCESSOR,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"}}});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 import_utils199,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";import_utils199=require("@frontmcp/utils");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=(0,import_utils199.isAbsolute)(rawPath)?rawPath:(0,import_utils199.pathResolve)(sourceDir,rawPath);this.slots.set(slot,{file});this.logger?.verbose(`Registered auth.ui slot "${slot}" \u2192 ${file}`)}}registerAuthExtrasMap(map){if(!map)return;for(const[name60,handler]of Object.entries(map)){if(typeof handler!=="function"){throw new Error(`auth.extras["${name60}"] must be a handler function (input, ctx) => AuthExtraResult.`)}this.extras.set(name60,handler);this.logger?.verbose(`Registered auth.extras handler "${name60}"`)}}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=(0,import_utils199.sha256Hex)((0,import_utils199.randomBytes)(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(([name60,items])=>[name60,[...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:(0,import_utils199.sha256Hex)((0,import_utils199.randomBytes)(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(name60){return this.extras.has(name60)}async runExtra(name60,pendingAuthId,input){const handler=this.extras.get(name60);if(!handler){return{ok:false,error:`Unknown extra "${name60}".`}}const ctx={name:name60,pendingAuthId,current:pendingAuthId?this.getAddedItems(pendingAuthId)[name60]??[]:[]};let result;try{result=await handler(input,ctx)}catch(err){this.logger?.error(`auth.extras["${name60}"] 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["${name60}"] 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,name60,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}"`)}}}}}});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 CSP_SOURCE_HOST.test(url.hostname)?url.origin:void 0}if(!/^[a-z][a-z0-9+.-]*:$/.test(url.protocol)||UNSAFE_FORM_TARGET_SCHEMES.has(url.protocol))return void 0;return url.protocol}function formActionSources(targets){const sources3=targets.map(formActionSource).filter(source=>source!==void 0);return[...new Set(sources3)]}function authUiCsp(formTargets=[]){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 ${["'self'",...formActionSources(formTargets)].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=>`
|
|
338
338
|
import { mountAuthPage as __mountAuthPage } from '@frontmcp/ui/auth';
|
|
339
339
|
__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:(0,import_uipack_render.createResolverWithOverrides)(overrides)}:{}};const result=(0,import_uipack_render.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 import_uipack_render,UNSAFE_FORM_TARGET_SCHEMES,CSP_SOURCE_HOST,AUTH_UI_CSP;var init_auth_ui_render=__esm({"libs/sdk/src/auth/auth-ui/auth-ui.render.ts"(){"use strict";import_uipack_render=require("#uipack-render");init_auth_ui_contract();UNSAFE_FORM_TARGET_SCHEMES=new Set(["javascript:","data:","blob:","filesystem:","about:","file:"]);CSP_SOURCE_HOST=/^[a-z0-9.-]+$/;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,formActionSources:()=>formActionSources});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 forDisplay(name60){const visible=name60.replace(BREAKING_CHARACTERS," ").replace(BLANK_CHARACTERS," ").replace(INVISIBLE_CHARACTERS,"").replace(/\s+/g," ").trim();if(!READABLE_CHARACTER.test(visible))return"";const characters=Array.from(visible);if(characters.length<=CLIENT_NAME_DISPLAY_MAX)return visible;return`${characters.slice(0,CLIENT_NAME_DISPLAY_MAX-1).join("").trimEnd()}\u2026`}function clientDisplayName(clientId,...names){for(const name60 of names){const shown=typeof name60==="string"?forDisplay(name60):"";if(shown)return shown}return forDisplay(clientId)||UNNAMED_CLIENT}async function resolveClientDisplayName(scope,client){const{clientId}=client;if(client.clientName)return clientDisplayName(clientId,client.clientName);const auth=scope.auth;const cimd=auth?.cimdService;if(cimd?.enabled&&cimd.isCimdClientId?.(clientId)){try{const resolution=await cimd.resolveClientMetadata?.(clientId);return clientDisplayName(clientId,resolution?.metadata?.client_name)}catch{return clientDisplayName(clientId)}}const registry=auth?.dcrClientRegistry;try{const registered=registry?.load?await registry.load(clientId):registry?.get?.(clientId);return clientDisplayName(clientId,registered?.client_name)}catch{return clientDisplayName(clientId)}}function isListedClient(scope,clientId){const auth=scope.auth;if(auth?.dcrClientRegistry?.get(clientId)?.preRegistered)return true;const options=scope.auth?.options;const cimd=options&&(0,import_auth64.isOrchestratedMode)(options)?options.cimd:void 0;if(cimd?.enabled===false||!cimd?.trustedClientIds?.includes(clientId))return false;return(0,import_auth64.isCimdClientId)(clientId,cimd.security?.allowInsecureForTesting)}function clientDetailsOf(scope,client){return{clientId:client.clientId,redirectUri:client.redirectUri,listed:isListedClient(scope,client.clientId)}}var import_auth64,CLIENT_NAME_DISPLAY_MAX,UNNAMED_CLIENT,BREAKING_CHARACTERS,INVISIBLE_CHARACTERS,BLANK_CHARACTERS,READABLE_CHARACTER;var init_client_display_name=__esm({"libs/sdk/src/auth/client-display-name.ts"(){"use strict";import_auth64=require("@frontmcp/auth");CLIENT_NAME_DISPLAY_MAX=64;UNNAMED_CLIENT="Unnamed client";BREAKING_CHARACTERS=/[\p{Cc}\p{Zl}\p{Zp}]/gu;INVISIBLE_CHARACTERS=/(?![\u200C\u200D])\p{Cf}/gu;BLANK_CHARACTERS=/[\u115F\u1160\u3164\uFFA0\u2800]/gu;READABLE_CHARACTER=/[\p{L}\p{N}\p{P}\p{S}]/u}});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"}});function allowsSkippingApps(authOptions){return!(authOptions&&(0,import_auth65.isOrchestratedMode)(authOptions)&&authOptions.incrementalAuth?.allowSkip===false)}function requiredProviderIds(authOptions,apps){if(!authOptions||!(0,import_auth65.isOrchestratedMode)(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 import_auth65;var init_required_providers_utils=__esm({"libs/sdk/src/auth/required-providers.utils.ts"(){"use strict";import_auth65=require("@frontmcp/auth")}});function showsProvidersStepByStep(authOptions){return!!authOptions&&(0,import_auth13.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&&(0,import_auth13.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)??(0,import_utils200.base64urlEncode)((0,import_utils200.randomBytes)(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=(0,import_auth66.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,client:clientDetailsOf(scope,record),pendingAuthId:record.id,callbackPath:submitUrl,csrfToken,error:options.error});return httpRespond.html(markup,200,(0,import_auth66.builtInAuthPageHeaders)({csp:"inline"}))}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 import_auth66,import_utils200,FEDERATED_STEP_FIELD;var init_federated_steps=__esm({"libs/sdk/src/auth/federated-steps.ts"(){"use strict";import_auth66=require("@frontmcp/auth");import_utils200=require("@frontmcp/utils");init_common();init_flow_http_path();init_auth_ui();init_client_display_name();init_required_providers_utils();FEDERATED_STEP_FIELD="federated_step"}});function signinCookiePath(issuer,scopePath){let issuerPath;try{issuerPath=new URL(issuer).pathname.replace(/\/+$/,"")}catch{return"/"}return issuerPath===""&&scopePath.replace(/\/+$/,"")===""?"/oauth":"/"}function signinOverHttps(request2){if((0,import_utils201.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(0,import_auth67.createSigninBinding)(pendingAuthId,{secure:signinOverHttps(request2)})}function signinBindingCookie(request2,binding,path7){const secure=signinOverHttps(request2);return{name:binding.cookieName,value:binding.value,path:secure?"/":path7,httpOnly:true,sameSite:"lax",secure,maxAge:import_auth67.SIGNIN_BINDING_MAX_AGE_SECONDS}}function clearedSigninBindingCookie(request2,pendingAuthId,path7){const secure=signinOverHttps(request2);return{name:(0,import_auth67.signinBindingCookieName)(pendingAuthId,{secure}),value:"",path:secure?"/":path7,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(0,import_auth67.signinBindingMatches)(header2,pendingAuthId,hash,{secure:signinOverHttps(request2)})}function withCookie(output,cookie){return{...output,cookies:[...output.cookies??[],cookie]}}var import_auth67,import_utils201,SIGNIN_BINDING_REFUSED;var init_signin_binding_utils=__esm({"libs/sdk/src/auth/flows/signin-binding.utils.ts"(){"use strict";import_auth67=require("@frontmcp/auth");import_utils201=require("@frontmcp/utils");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});function getConfiguredProviderIds(auth){return getConfiguredProviders(auth).map(p=>p.id)}var import_auth68,import_lazy_zod143,import_utils202,pkceChallengeSchema,codeChallengeMethodSchema,responseTypeSchema,safeRedirectUriSchema,oauthAuthorizeRequestSchema,anonymousAuthorizeRequestSchema,inputSchema41,stateSchema43,outputSchema40,plan48,name48,Stage48,OauthAuthorizeFlow;var init_oauth_authorize_flow=__esm({"libs/sdk/src/auth/flows/oauth.authorize.flow.ts"(){"use strict";import_auth68=require("@frontmcp/auth");import_lazy_zod143=require("@frontmcp/lazy-zod");import_utils202=require("@frontmcp/utils");init_common();init_flow_http_path();init_auth_ui();init_authorized_apps_utils();init_cimd();init_client_display_name();init_consent_tools_helper();init_federated_steps();init_required_providers_utils();init_signin_binding_utils();pkceChallengeSchema=import_lazy_zod143.internalZ.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=import_lazy_zod143.internalZ.literal("S256",{message:'code_challenge_method must be "S256" (OAuth 2.1)'});responseTypeSchema=import_lazy_zod143.internalZ.literal("code",{message:'response_type must be "code" (OAuth 2.1)'});safeRedirectUriSchema=import_lazy_zod143.internalZ.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=import_lazy_zod143.internalZ.object({response_type:responseTypeSchema,client_id:import_lazy_zod143.internalZ.string().min(1,"client_id is required"),redirect_uri:safeRedirectUriSchema,code_challenge:pkceChallengeSchema,code_challenge_method:codeChallengeMethodSchema.optional().default("S256"),scope:import_lazy_zod143.internalZ.string().optional(),state:import_lazy_zod143.internalZ.string().optional(),resource:import_lazy_zod143.internalZ.string().url().optional()});anonymousAuthorizeRequestSchema=import_lazy_zod143.internalZ.object({redirect_uri:safeRedirectUriSchema,state:import_lazy_zod143.internalZ.string().optional()});inputSchema41=httpInputSchema;stateSchema43=import_lazy_zod143.internalZ.object({isDefaultAuthProvider:import_lazy_zod143.internalZ.boolean().describe("No sign-in to run: no auth options, or public mode (the same configuration, written out)"),isOrchestrated:import_lazy_zod143.internalZ.boolean().describe("If FrontMcp is orchestrated (local oauth proxy, remote oauth proxy)"),allowAnonymous:import_lazy_zod143.internalZ.boolean().describe("Allow anonymous access, force orchestrated mode"),validatedRequest:oauthAuthorizeRequestSchema.optional(),rawRedirectUri:import_lazy_zod143.internalZ.string().optional(),rawState:import_lazy_zod143.internalZ.string().optional(),validationErrors:import_lazy_zod143.internalZ.array(import_lazy_zod143.internalZ.string()).optional(),pendingAuthId:import_lazy_zod143.internalZ.string().optional(),isIncrementalAuth:import_lazy_zod143.internalZ.boolean().default(false).describe("Whether this is an incremental auth request"),targetAppId:import_lazy_zod143.internalZ.string().optional().describe("Target app ID for incremental authorization"),targetToolId:import_lazy_zod143.internalZ.string().optional().describe("Target tool ID that triggered the incremental auth"),existingSessionId:import_lazy_zod143.internalZ.string().optional().describe("Existing session ID for incremental auth"),incrementalTicket:import_lazy_zod143.internalZ.custom().optional(),priorAuthorizedAppIds:import_lazy_zod143.internalZ.array(import_lazy_zod143.internalZ.string()).optional().describe("Prior authorized app IDs to carry forward"),requiresFederatedLogin:import_lazy_zod143.internalZ.boolean().default(false).describe("Whether this auth requires federated login UI"),requiresConsent:import_lazy_zod143.internalZ.boolean().default(false).describe("Whether consent flow is enabled"),isCimdClient:import_lazy_zod143.internalZ.boolean().default(false).describe("Whether client_id is a CIMD URL"),cimdMetadata:import_auth61.clientMetadataDocumentSchema.optional().describe("CIMD metadata document for the client"),registeredClientAuthMethod:import_lazy_zod143.internalZ.string().optional().describe("How the registered client validated here authenticates at the token endpoint"),clientName:import_lazy_zod143.internalZ.string().optional().describe("The name the auth pages show for the client: its CIMD or registered client_name, else its client_id")});outputSchema40=import_lazy_zod143.internalZ.union([HttpRedirectSchema,HttpTextSchema,HttpHtmlSchema]);plan48={pre:["checkIpFilter","acquireQuota","parseInput","validateInput","checkIfAuthorized"],execute:["prepareAuthorizationRequest","buildAuthorizeOutput"],post:["validateOutput"]};name48="oauth:authorize";Stage48=StageHookOf(name48);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||(0,import_auth13.isPublicMode)(metadata.auth);let requiresFederatedLogin=false;if(metadata.auth&&(0,import_auth13.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&&(0,import_auth13.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&&(0,import_auth13.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(!(0,import_auth68.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||!(0,import_auth13.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=(0,import_auth68.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(import_auth61.CimdService);const registry=this.scope.auth?.dcrClientRegistry;const redirectAllowlisted=!!registry?.hasRedirectAllowlist()&®istry.isRedirectUriAllowed(redirect_uri);let redirectVerified=redirectAllowlisted;let declaredClientScope;const isCimdClientId3=!!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}let loaded;if(!isCimdClientId3)loaded=registry?.load?await registry.load(client_id):registry?.get?.(client_id);if(cimdService&&!cimdService.enabled&&cimdService.isCimdClientId(client_id)&&!loaded){const disabled=new import_auth61.CimdDisabledError;this.logger.warn(`OAuth authorize: CIMD client_id refused, CIMD is disabled: ${client_id}`);this.respondWithError([disabled.message],void 0,rawState);return}if(isCimdClientId3){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 import_auth61.CimdError?error.getPublicMessage():"CIMD validation failed";this.respondWithError([publicMessage],void 0,rawState);return}}const registered=loaded;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;this.state.set("registeredClientAuthMethod",registered.token_endpoint_auth_method)}this.state.set("clientName",clientDisplayName(client_id,this.state.cimdMetadata?.client_name,registered?.client_name));const clientIdError=isCimdClientId3?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(!isCimdClientId3&&!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=(0,import_auth68.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&&(0,import_auth13.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&&(0,import_auth13.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),clientName:this.clientNameOf(validatedRequest.client_id)});const ticketProfile=effectiveIncremental&&incrementalTicket&&localAuth.signingSecret?(0,import_auth68.openIncrementalAuthTicketProfile)(incrementalTicket,localAuth.signingSecret):void 0;if(ticketProfile){pendingRecord.verifiedLogin=(0,import_auth68.sealPendingLogin)(localAuth.secret,pendingRecord.id,ticketProfile)}if(federatedLogin&&!effectiveIncremental&&metadata.auth&&!(0,import_auth13.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&&(0,import_auth13.isRemoteMode)(metadata.auth)&&!isIncrementalAuth){await this.startRemoteFederation(pendingAuthId,validatedRequest);return}const clientName=this.clientNameOf(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}));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,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,clientName,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,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,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,(0,import_auth68.builtInAuthPageHeaders)({csp:customRender?false:"inline"})))}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??this.state.registeredClientAuthMethod??localAuth.dcrClientRegistry.get(clientId)?.token_endpoint_auth_method??"none"}clientNameOf(clientId){return this.state.clientName??clientDisplayName(clientId,this.state.cimdMetadata?.client_name)}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=(0,import_auth68.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),clientName:this.clientNameOf(validatedRequest.client_id),authorizedAppIds:initialAuthorizedApps(this.scope.auth?.options,this.scope.apps.getApps(),this.state.priorAuthorizedAppIds)});const verifier=(0,import_utils202.generateCodeVerifier)();const challenge=(0,import_utils202.sha256Base64url)(verifier);const pkce={verifier,challenge,method:"S256"};const providerState=`federated:${session.id}:${(0,import_utils202.randomUUID)()}`;(0,import_auth68.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,(0,import_auth68.builtInAuthPageHeaders)({csp:"inline"}))}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 path7=err.path.length>0?`${err.path.join(".")}: `:"";return`${path7}${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,redirectUri,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,redirectUri,clientListed:isListedClient(this.scope,clientId),formTargets:formActionSources([redirectUri]),fields:login?.fields??{}};return(0,import_auth68.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(0,import_auth68.buildIncrementalAuthPage)({app,toolId:toolId||"unknown tool",sessionHint:pendingAuthId,callbackPath})}renderFederatedLoginPage(params){const{pendingAuthId,detection,clientId,clientName,redirectUri}=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(0,import_auth68.buildFederatedLoginPage)({providers,clientName,client:clientDetailsOf(this.scope,{clientId,redirectUri}),pendingAuthId,callbackPath,allowSkip:allowsSkippingApps(authOptions)})}renderErrorPage(error,description){return`<!DOCTYPE html>
|
|
@@ -488,7 +488,7 @@ This tool was blocked during the '${skillDisplay}' skill session. Please use the
|
|
|
488
488
|
|
|
489
489
|
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.
|
|
490
490
|
|
|
491
|
-
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});function createAuthoritiesEngine(config){const profileRegistry=new import_auth83.AuthoritiesProfileRegistry;if(config["profiles"]){profileRegistry.registerAll(config["profiles"])}const evaluatorRegistry=new import_auth83.AuthoritiesEvaluatorRegistry;if(config["evaluators"]){evaluatorRegistry.registerAll(config["evaluators"])}return new import_auth83.AuthoritiesEngine(profileRegistry,evaluatorRegistry)}function authoritiesFromConfig(config){return{engine:createAuthoritiesEngine(config),contextBuilder:new import_auth83.AuthoritiesContextBuilder({claimsMapping:config["claimsMapping"],claimsResolver:config["claimsResolver"],relationshipResolver:config["relationshipResolver"]}),scopeMapping:config["scopeMapping"]}}var import_auth83;var init_authorities_engine=__esm({"libs/sdk/src/front-mcp/authorities-engine.ts"(){"use strict";import_auth83=require("@frontmcp/auth")}});var send_elicitation_result_tool_exports={};__export(send_elicitation_result_tool_exports,{SendElicitationResultTool:()=>SendElicitationResultTool});var import_lazy_zod154,inputSchema51,SendElicitationResultTool;var init_send_elicitation_result_tool=__esm({"libs/sdk/src/elicitation/send-elicitation-result.tool.ts"(){"use strict";import_lazy_zod154=require("@frontmcp/lazy-zod");init_common();init_call_surface();init_errors();init_fallback_helper();inputSchema51={elicitId:import_lazy_zod154.internalZ.string().describe("The elicitation ID from the pending request"),action:import_lazy_zod154.internalZ.enum(["accept","cancel","decline"]).describe("User action: accept (submit), cancel, or decline"),content:import_lazy_zod154.internalZ.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:inputSchema51,hideFromDiscovery:true})],SendElicitationResultTool)}});function keptUntilFailure(start,forget){return start.catch(error=>{forget();throw error})}function entriesWithAuthorities(registries,agentPath=""){const entries=[];const add=(kind,name60,metadata)=>{const authorities=metadata?.["authorities"];if(authorities!==void 0&&authorities!==null&&authorities!==false){entries.push({label:`${kind} "${agentPath}${name60}"`,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 import_reflect_metadata30,import_guard9,import_utils211,SCOPE_NON_DISPATCHABLE_FLOWS,Scope;var init_scope_instance=__esm({"libs/sdk/src/scope/scope.instance.ts"(){"use strict";import_reflect_metadata30=require("reflect-metadata");import_guard9=require("@frontmcp/guard");import_utils211=require("@frontmcp/utils");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_borrow_providers();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,path7,handler)=>{this.registeredHttpRoutes.push({method,path:path7,handler});return this.server.registerRoute(method,path7,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=serverProvidersOn(rec.metadata.providers??[],globalProviders.container);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=(0,import_utils211.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=(0,import_utils211.getRuntimeContext)().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(ha);const haSubscriber=this.createHaRedisClient(ha,"ha-subscriber");this.haManager=ha.HaManager.create({redis:haRedis,pubsubPublisher:haRedis,pubsubSubscriber:haSubscriber,nodeId:(0,import_utils211.getMachineId)(),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,(0,import_utils211.getMachineId)(),{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((0,import_utils211.getRuntimeContext)().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:createEventStore3}=await Promise.resolve().then(()=>(init_event_stores(),event_stores_exports));const{eventStore}=createEventStore3(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=(0,import_utils211.isEdgeRuntime)();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=(0,import_utils211.isEdgeRuntime)();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?(0,import_guard9.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 serverProviders=serverProvidersOn(this.metadata.providers??[],this.globalProviders.container);const serverHooks=serverProviderHooks(this.scopeProviders,serverProviders,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"||httpServing?.peopleKeepSessionsInSqlite(this,resolvedTopLevelSqlite)===true;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&&(0,import_utils211.getRuntimeContext)().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:(0,import_utils211.getMachineId)(),haManager:this.haManager,bus:this.transportBus,transportService,notifications:this.notificationService,flows:{runFlow:(name60,input)=>this.runFlow(name60,input)},logger:this.logger})}if(httpServing){await httpServing.attachHttpRoutes(this,this.globalProviders,{sqlite:this.topLevelSqlite});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||(0,import_utils211.getRuntimeContext)().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:dirname11}=require("path");await(0,import_utils211.mkdir)(dirname11(finalPath),{recursive:true,mode:448})}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:path7}of widgets){this.logger.warn(`Tool "${toolName}": \`ui.servingMode: 'direct-url'\` serves the widget on GET ${path7}, 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:import_di4.ProviderScope.GLOBAL,name:"ScopeEntry",provide:ScopeEntry,useValue:this},{scope:import_di4.ProviderScope.GLOBAL,name:"Scope",provide:_Scope,useValue:this},{scope:import_di4.ProviderScope.GLOBAL,name:"FrontMcpLogger",provide:FrontMcpLogger,useValue:this.logger},{scope:import_di4.ProviderScope.GLOBAL,name:"FrontMcpContextStorage",provide:FrontMcpContextStorage,useValue:new FrontMcpContextStorage().configure(this.metadata.fetch,{...proxyTrustOf(this.metadata.throttle),forwardsHeader:createHeaderForwarder(this.metadata.http?.forwardHeaders)})},FrontMcpContextProvider,{scope:import_di4.ProviderScope.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(0,import_guard9.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(0,import_guard9.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(name60,input,deps){return this.scopeFlows.runFlow(name60,input,deps)}async findHttpFlowName(request2){return this.scopeFlows.findHttpFlowName(request2,SCOPE_NON_DISPATCHABLE_FLOWS)}async runFlowForOutput(name60,input,deps){const result=await this.scopeFlows.runFlow(name60,input,deps);if(result){return result}throw new FlowExitedWithoutOutputError}createHaRedisClient(ha,label="ha"){const client=ha.createHaRedisClient(this.metadata.redis,label,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(name60){return new Proxy({},{get:(target,property,receiver)=>typeof property==="symbol"||isProbe(property)||property in target?Reflect.get(target,property,receiver):()=>{throw new StoreNotOpenedInBuildError(name60)}})}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",typeof scope==="string"?scope:"machine")}async function appLeaseKey(name60,scope){let key;try{key=typeof scope.key==="function"?await scope.key():scope.key}catch(error){throw new DutyLeaseKeyError(name60,`failed (${error instanceof Error?error.message:String(error)})`)}const trimmed=typeof key==="string"?key.trim():"";if(trimmed==="")throw new DutyLeaseKeyError(name60,"answered no string");if(trimmed.length>MAX_DUTY_LEASE_KEY_LENGTH){throw new DutyLeaseKeyError(name60,`answered a key longer than ${MAX_DUTY_LEASE_KEY_LENGTH} characters`)}return trimmed}async function preferenceOf(prefer){if(prefer===void 0)return void 0;return(typeof prefer==="function"?await prefer():prefer)===true}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,MAX_DUTY_LEASE_KEY_LENGTH,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_work_spans();init_cron_schedule();init_duty_runner();init_lazy_lease_store();init_lease_store();lifecycles=new WeakMap;claims=new LeaseClaims;MAX_DUTY_LEASE_KEY_LENGTH=1024;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:name60,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 "${name60}"`)}}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:name60,leaseMs,scope}=metadata;const logger=this.providers.get(FrontMcpLogger);if(!isLongLivedProcess()){logger.warn(`Duty "${name60}" 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=typeof scope==="string"?leaseKey(name60,scope,serverName):keyedLeaseKey(name60,await appLeaseKey(name60,scope),serverName);const prefer=await preferenceOf(metadata.prefer);this.claim(serverName);const storage=new LazyLeaseStore(dutyStorageConfig(config.redis,scope));const run=context=>withWorkSpan("duty",name60,()=>this.duty.run(context));const common={name:name60,key,leaseMs,storage,logger,run,...prefer===void 0?{}:{prefer}};const runner=new DutyRunner(metadata.cron?{...common,cron:await this.cronSchedule(metadata.cron)}:{...common,everyMs:metadata.everyMs});const removeHealthProbe=registerReadinessProbe(this.providers,{name:`duty:${name60}`,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(resolve5=>{const settle=()=>{clearTimeout(timer);signal.removeEventListener("abort",settle);resolve5()};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:name60,logger}=this.options;if(failure===void 0)logger.warn(`Worker "${name60}" returned before its signal was aborted; ${next}`);else logger.error(`Worker "${name60}" 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_work_spans();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:name60,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 "${name60}"`)}}async start(){const{name:name60,restart,scope}=this.metadata;const logger=this.providers.get(FrontMcpLogger);if(!isLongLivedProcess()){logger.warn(`Worker "${name60}" 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 run=context=>withWorkSpan("worker",name60,()=>this.worker.run(context));const supervisor=new WorkerSupervisor({name:name60,restart,logger,run});if(scope!=="process")return this.contend(supervisor,scope,logger);logger.info(`Worker "${name60}" runs in this process`);supervisor.start();return{supervisor,removeHealthProbe:this.registerHealthProbe(supervisor)}}async contend(supervisor,scope,logger){const{name:name60,leaseMs}=this.metadata;const config=this.providers.get(FrontMcpConfig);const serverName=config.info?.name??"frontmcp";const key=leaseKey(name60,scope,serverName);const storage=new LazyLeaseStore(leaseStorageConfig(config.redis,"worker",scope));const removeHealthProbe=this.registerHealthProbe(supervisor,storage);const holder=new LeaseHolder({label:`Worker "${name60}"`,key,leaseMs,storage,logger,onAcquired:()=>{logger.info(`Worker "${name60}" 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)})}}}});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 import_reflect_metadata31,import_di52,ProviderRegistry,REQUEST_PROVIDER_STORES;var init_provider_registry=__esm({"libs/sdk/src/provider/provider.registry.ts"(){"use strict";import_reflect_metadata31=require("reflect-metadata");import_di52=require("@frontmcp/di");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??options?.sharedLifecycles??new WeakMap;this.container=parentProviders?.container??options?.container;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;heldEntries=[];backgroundEntries=[];readyEntries=[];container;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((0,import_di52.tokenName)(token),"not registered in hierarchy");const{registry,rec}=found;const sc=registry.getProviderScope(rec);if(sc!==import_di52.ProviderScope.GLOBAL){const scName=import_di52.ProviderScope[sc];throw new ProviderScopeMismatchError((0,import_di52.tokenName)(token),scName,registry.constructor.name)}const inst=registry.instances.get(token);if(inst===void 0){throw new ProviderNotInstantiatedError((0,import_di52.tokenName)(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 ${(0,import_di52.tokenName)(token)} depends on ${(0,import_di52.tokenName)(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)!==import_di52.ProviderScope.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===import_di52.ProviderScope.GLOBAL)return;throw new InvalidDependencyScopeError(`Invalid dependency: DEFAULT-scoped provider ${(0,import_di52.tokenName)(token)} cannot depend on scoped provider ${(0,import_di52.tokenName)(dependency)}.`)}topoSort(){const WHITE=0,GRAY=1,BLACK=2;const color=new Map;const order=new Set;const path7=[];const dfs=n=>{color.set(n,GRAY);path7.push(n);for(const dep of this.graph.get(n)??[]){const c=color.get(dep)??WHITE;if(c===GRAY){const idx=path7.findIndex(p=>p===dep);const cycle=[...path7.slice(idx),dep].map(t=>(0,import_di52.tokenName)(t)).join(" -> ");throw new DependencyCycleError(cycle)}if(c===WHITE)dfs(dep)}color.set(n,BLACK);order.add(n);path7.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)!==import_di52.ProviderScope.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((0,import_di52.tokenName)(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 borrowed=!!shared&&!!this.container?.owned.has(instance);if(borrowed&&this.container?.disposed)throw new ContainerDisposedError;const lifecycle=shared??{holders:0,bootstrapped:bootstrapProvider(entry)};if(!shared)this.sharedLifecycles.set(instance,lifecycle);lifecycle.holders++;await lifecycle.bootstrapped;if(!shared&&background)this.backgroundEntries.push({token,lifecycle:background});if(!shared||this.container)this.readyEntries.push({entry,borrowed,background:!!background});this.heldEntries.push(entry)}heldLifecycles(){return this.heldEntries.map(({instance})=>instance)}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 this.readyInBuildOrder(logger);for(const child of[...this.childRegistries])failures.push(...await child.runReadyHooks(logger));return failures}async readyInBuildOrder(logger){const container=this.container;const failures=[];for(const{entry,borrowed,background}of this.readyEntries){if(!container){failures.push(...await readyProviders([entry],logger));continue}if(borrowed&&background&&container.backgroundStarted)continue;const running=container.readied.get(entry.instance);if(running){await running;continue}const readying=readyProviders([entry],logger);container.readied.set(entry.instance,readying);failures.push(...await readying)}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 "${(0,import_di52.tokenName)(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 "${(0,import_di52.tokenName)(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)!==import_di52.ProviderScope.CONTEXT)continue;if(rec.kind===import_di52.ProviderKind.CLASS)out.push({token,cls:rec.useClass});else if(rec.kind===import_di52.ProviderKind.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)=>(0,import_di52.depsOfClass)(k,phase))}invocationTokens(_token,rec){return providerInvocationTokens(rec,(k,phase)=>(0,import_di52.depsOfClass)(k,phase))}normalizeScope(scope){switch(scope){case import_di52.ProviderScope.SESSION:case import_di52.ProviderScope.REQUEST:return import_di52.ProviderScope.CONTEXT;default:return scope}}getProviderScope(rec){const rawScope=rec.metadata?.scope??import_di52.ProviderScope.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===import_di52.ProviderScope.GLOBAL){if(!this.instances.has(t)){throw new ProviderNotInstantiatedError((0,import_di52.tokenName)(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===import_di52.ProviderScope.GLOBAL){const inst=up.registry.instances.get(t);if(inst===void 0){throw new ProviderNotInstantiatedError((0,import_di52.tokenName)(t),"DEFAULT","parent")}return inst}else{await up.registry.buildIntoStore(t,up.rec,store,scopeKey);return store.get(t)}}if((0,import_di52.isClass)(t)){if((0,import_di52.hasAsyncWith)(t)){const out=t.with();return(0,import_di52.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((0,import_di52.isPromise)(ret))await this.withTimeout(ret,this.asyncTimeoutMs,`${t.name}.init()`)}return instance}throw new ProviderNotRegisteredError((0,import_di52.tokenName)(t),"not registered in hierarchy and not constructable")}bootsForBuild(){const config=this.lookupDefInHierarchy(FrontMcpConfig)?.rec;return config?.kind===import_di52.ProviderKind.VALUE&&typeof config.useValue==="object"&&config.useValue!==null&&isManifestMode(config.useValue)}async initiateOne(token,rec){switch(rec.kind){case import_di52.ProviderKind.VALUE:{this.instances.set(token,rec.useValue);return}case import_di52.ProviderKind.FACTORY:{if(opensStore(rec.useFactory)&&this.bootsForBuild()){this.instances.set(token,storeNotOpened(rec.metadata?.name??(0,import_di52.tokenName)(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=(0,import_di52.isPromise)(out)?await this.withTimeout(out,this.asyncTimeoutMs,`${(0,import_di52.tokenName)(token)}.useFactory(...)`):out;this.instances.set(token,val);return}case import_di52.ProviderKind.CLASS:{const depTokens=this.invocationTokens(token,rec);const deps=depTokens.map(t=>this.resolveDefaultFromHierarchy(t));const klass=rec.useClass;if((0,import_di52.hasAsyncWith)(klass)){const out=klass.with(...deps);const val=(0,import_di52.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((0,import_di52.isPromise)(ret))await this.withTimeout(ret,this.asyncTimeoutMs,`${klass.name}.init()`)}this.instances.set(token,instance)}return}case import_di52.ProviderKind.CLASS_TOKEN:{const depTokens=this.invocationTokens(token,rec);const deps=depTokens.map(t=>this.resolveDefaultFromHierarchy(t));const klass=rec.provide;if((0,import_di52.hasAsyncWith)(klass)){const out=klass.with(...deps);const val=(0,import_di52.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((0,import_di52.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 import_di52.ProviderKind.VALUE:{store.set(token,rec.useValue);return}case import_di52.ProviderKind.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=(0,import_di52.isPromise)(out)?await this.withTimeout(out,this.asyncTimeoutMs,`${(0,import_di52.tokenName)(token)}.useFactory(...)`):out;store.set(token,val);return}case import_di52.ProviderKind.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((0,import_di52.hasAsyncWith)(klass)){const out=klass.with(...deps);const val=(0,import_di52.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((0,import_di52.isPromise)(ret))await this.withTimeout(ret,this.asyncTimeoutMs,`${klass.name}.init()`)}store.set(token,instance)}return}case import_di52.ProviderKind.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((0,import_di52.hasAsyncWith)(klass)){const out=klass.with(...deps);const val=(0,import_di52.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((0,import_di52.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((0,import_di52.tokenName)(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===import_di52.ProviderScope.GLOBAL){const v=this.instances.get(d);if(v===void 0)throw new ProviderNotInstantiatedError((0,import_di52.tokenName)(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===import_di52.ProviderScope.GLOBAL){const v=up.registry.instances.get(d);if(v===void 0)throw new ProviderNotInstantiatedError((0,import_di52.tokenName)(d),"DEFAULT","parent");return v}else{await up.registry.buildIntoStore(d,up.rec,store,scopeKey);return store.get(d)}}throw new ProviderNotInstantiatedError((0,import_di52.tokenName)(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)!==import_di52.ProviderScope.GLOBAL){const scName=import_di52.ProviderScope[this.getProviderScope(rec)];throw new ProviderScopedAccessError((0,import_di52.tokenName)(token),scName)}if(this.providers)return this.providers.getFor(token,requester);throw new ProviderNotAvailableError((0,import_di52.tokenName)(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!==import_di52.ProviderScope.GLOBAL)throw new PluginDependencyError(`Plugin dependency ${(0,import_di52.tokenName)(t)} must be DEFAULT-scoped at bootstrap`);const v=registry.instances.get(t);if(v===void 0)throw new PluginDependencyError(`Plugin dependency ${(0,import_di52.tokenName)(t)} (DEFAULT scope) is not instantiated`);return v}throw new PluginDependencyError(`Cannot resolve plugin dependency ${(0,import_di52.tokenName)(t)} (local or parent)`)}resolve(cls){const found=this.lookupDefInHierarchy(cls);if(found){const{registry,rec}=found;const sc=registry.getProviderScope(rec);if(sc!==import_di52.ProviderScope.GLOBAL){const scName=import_di52.ProviderScope[sc];throw new ProviderScopedAccessError((0,import_di52.tokenName)(cls),scName)}if(!registry.instances.has(cls)){throw new ProviderNotInstantiatedError((0,import_di52.tokenName)(cls),"DEFAULT","Call providers.instantiate() first")}return registry.instances.get(cls)}if((0,import_di52.isClass)(cls)){const instance=new cls;const init=instance?.init;if(typeof init==="function"){init.call(instance)}return instance}throw new ProviderNotRegisteredError((0,import_di52.tokenName)(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??import_di52.ProviderScope.GLOBAL;if(scope===import_di52.ProviderScope.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((0,import_di52.tokenName)(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:import_di52.ProviderKind.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)===import_di52.ProviderScope.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){for(const child of this.childRegistries)child.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)!==import_di52.ProviderScope.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)!==import_di52.ProviderScope.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)!==import_di52.ProviderScope.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 import_di52.ProviderKind.VALUE:{store.set(token,rec.useValue);return}case import_di52.ProviderKind.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=(0,import_di52.isPromise)(out)?await this.withTimeout(out,this.asyncTimeoutMs,`${(0,import_di52.tokenName)(token)}.useFactory(...)`):out;store.set(token,val);return}case import_di52.ProviderKind.CLASS:case import_di52.ProviderKind.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===import_di52.ProviderKind.CLASS?rec.useClass:rec.provide;if((0,import_di52.hasAsyncWith)(klass)){const out=klass.with(...deps);const val=(0,import_di52.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((0,import_di52.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((0,import_di52.tokenName)(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===import_di52.ProviderScope.GLOBAL){throw new ProviderNotInstantiatedError((0,import_di52.tokenName)(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===import_di52.ProviderScope.GLOBAL){const v=up.registry.instances.get(token);if(v!==void 0)return v;throw new ProviderNotInstantiatedError((0,import_di52.tokenName)(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 ${(0,import_di52.tokenName)(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((0,import_di52.tokenName)(token),"not found in views. Ensure it was built via buildViews()")}};REQUEST_PROVIDER_STORES=Symbol("frontmcp:request-provider-stores")}});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(0,import_di53.depsOfClass)(rec.provide,"discovery").slice(1);case"SPLIT_BY_APP":return[]}}var import_di53;var init_scope_utils=__esm({"libs/sdk/src/scope/scope.utils.ts"(){"use strict";import_di53=require("@frontmcp/di");init_app_utils();init_errors();init_scope_instance()}});var import_reflect_metadata32,import_di54,ScopeRegistry;var init_scope_registry=__esm({"libs/sdk/src/scope/scope.registry.ts"(){"use strict";import_reflect_metadata32=require("reflect-metadata");import_di54=require("@frontmcp/di");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",(0,import_di54.tokenName)(token),(0,import_di54.tokenName)(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 '${(0,import_di54.tokenName)(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=(0,import_utils50.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 path7=config.path??"/metrics";for(const prefix of MCP_RESERVED_PATH_PREFIXES){if(path7===prefix||path7.startsWith(`${prefix}/`)){throw new MetricsPathConflictError(path7)}}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=name60=>allowedPrefixes.some(prefix=>name60.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[name60,value]of Object.entries(result.headers))res.setHeader?.(name60,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()}});function readCorsFromEnv(){const rawOrigins=(0,import_utils212.getEnv)("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=(0,import_utils212.getEnv)("FRONTMCP_CORS_CREDENTIALS");if(credentials!==void 0)cors2.credentials=credentials==="true"||credentials==="1";const maxAge=Number((0,import_utils212.getEnv)("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 import_utils212;var init_cors_env=__esm({"libs/sdk/src/server/middleware/cors-env.ts"(){"use strict";import_utils212=require("@frontmcp/utils")}});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()}});function readCspFromEnv(){if(!(0,import_utils213.getEnvFlag)("FRONTMCP_CSP_ENABLED"))return void 0;const rawDirectives=(0,import_utils213.getEnv)("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:(0,import_utils213.getEnv)("FRONTMCP_CSP_REPORT_URI"),reportOnly:(0,import_utils213.getEnvFlag)("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(name60,fallback){const value=(0,import_utils213.getEnv)(name60);if(value===void 0||value==="")return fallback;return["off","false","none"].includes(value.trim().toLowerCase())?void 0:value}function readCustomHeadersFromEnv(){const raw=(0,import_utils213.getEnv)("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[name60,value]of Object.entries(headers.custom)){res.setHeader(name60,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[name60,value]of Object.entries(options.csp.directives??{})){directives[name60]=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:(name60,value)=>void(headers[name60]=value)},resolved,csp);return headers}var import_utils213;var init_csp_middleware=__esm({"libs/sdk/src/server/middleware/csp.middleware.ts"(){"use strict";import_utils213=require("@frontmcp/utils")}});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()}});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(0,import_utils214.realpath)(socketDirectory);await assertNoOtherUserCanReplace2(socketDirectory);if(realSocketDirectory!==socketDirectory)await assertNoOtherUserCanReplace2(realSocketDirectory);if(canBindOwnerOnly())return;const{mode}=await(0,import_utils214.stat)(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(import_node_cluster.default.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((resolve5,reject)=>{const socket=net.connect(socketPath);socket.once("connect",()=>{socket.destroy();resolve5("live")});socket.once("error",error=>{const code=errorCode(error);if(code==="ECONNREFUSED")resolve5("stale");else if(code==="ENOENT")resolve5("gone");else reject(new SocketPathConflictError(socketPath,`connecting to it failed (${code??error.message})`))})})}async function clearStaleSocket(socketPath){let stats;try{stats=await(0,import_utils214.lstat)(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(0,import_utils214.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(0,import_utils214.chmod)(socketPath,OWNER_ONLY_MODE)}catch(error){throw new SocketPermissionError(socketPath,`chmod failed (${errorCode(error)??String(error)})`)}const mode=(await(0,import_utils214.lstat)(socketPath)).mode&511;if(mode!==OWNER_ONLY_MODE)throw new SocketPermissionError(socketPath,`its mode is 0${mode.toString(8)}`)}var import_node_cluster,net,path,import_utils214,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";import_node_cluster=__toESM(require("node:cluster"));net=__toESM(require("node:net"));path=__toESM(require("node:path"));import_utils214=require("@frontmcp/utils");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{}}});function utf8JsonParser(limit){const readBody=import_express.default.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 import_express,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";import_express=__toESM(require("express"));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"})}});function isClientRequestError(error){const{expose,status}=error??{};return expose===true&&typeof status==="number"&&status>=400&&status<500}function clientRequestJsonRpcError(error){if(error.type==="entity.too.large")return new PayloadTooLargeError(error.limit,error.length).toJsonRpcError();if(error.type==="entity.parse.failed")return{code:MCP_ERROR_CODES.PARSE_ERROR,message:"Parse error"};return{code:MCP_ERROR_CODES.INVALID_REQUEST,message:String(error.message)}}function answerRequestError(error,_req,res,next){if(res.headersSent)return next(error);if(isClientRequestError(error)){res.status(error.status).json({jsonrpc:"2.0",id:null,error:clientRequestJsonRpcError(error)});return}const output=flowErrorToHttpOutput(error)??INTERNAL_SERVER_ERROR;if(output.status>=500)console.error("[frontmcp] HTTP request failed:",error);writeHttpResponse(res,output).catch(()=>res.destroy())}async function drainAndClose(server,drainMs){const closed=new Promise(resolve5=>server.close(()=>resolve5()));server.closeIdleConnections();const forceClose=setTimeout(()=>server.closeAllConnections(),drainMs);try{await closed}finally{clearTimeout(forceClose)}}var http,import_cors,import_express2,SERVER_DRAIN_MS,DEFAULT_EXPRESS_BODY_LIMIT,DEFAULT_HEADERS_TIMEOUT_MS,DEFAULT_REQUEST_TIMEOUT_MS,INTERNAL_SERVER_ERROR,ExpressHostAdapter,NO_SUCH_ADDRESS;var init_express_host_adapter=__esm({"libs/sdk/src/server/adapters/express.host.adapter.ts"(){"use strict";http=__toESM(require("node:http"));import_cors=__toESM(require("cors"));import_express2=__toESM(require("express"));init_mcp_error();init_ha_headers();init_flow_error_output();init_csp_middleware();init_host_validation_middleware();init_resolve_allowed_hosts();init_unix_socket_guard();init_server_validation();init_base_host_adapter();init_utf8_json_parser();SERVER_DRAIN_MS=5e3;DEFAULT_EXPRESS_BODY_LIMIT="4mb";DEFAULT_HEADERS_TIMEOUT_MS=6e4;DEFAULT_REQUEST_TIMEOUT_MS=3e5;INTERNAL_SERVER_ERROR={kind:"text",status:500,body:"Internal Server Error"};ExpressHostAdapter=class extends HostServerAdapter{app=(0,import_express2.default)();router=import_express2.default.Router();prepared=false;httpServer;headersTimeout;requestTimeout;partnerServer;listeningLoopbackNames;hostValidation;deriveHostValidation;constructor(options){super();this.requestTimeout=options?.requestTimeout??DEFAULT_REQUEST_TIMEOUT_MS;const headersTimeout=options?.headersTimeout??DEFAULT_HEADERS_TIMEOUT_MS;this.headersTimeout=this.requestTimeout>0?Math.min(headersTimeout,this.requestTimeout):headersTimeout;this.app.disable("x-powered-by");const securityHeaders=resolveSecurityHeaders(options?.securityHeaders);this.app.use((_req,res,next)=>{for(const[name60,value]of Object.entries(securityHeaders))res.setHeader(name60,value);applyMachineIdHeader(res);next()});const corsOptions=options?.cors;const corsEnabled=corsOptions?.origin!==void 0&&corsOptions.origin!==false;if(corsEnabled){const configuredCors=(0,import_cors.default)({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(import_express2.default.urlencoded({extended:true,limit:formLimit,type:isUrlencoded,verify:keepBodyBytes}));this.app.use(utf8JsonParser(jsonLimit));this.app.use(import_express2.default.json({limit:jsonLimit,type:isJson,verify:keepBodyBytes}));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,loopbackNames)=>{if(typeof portOrSocketPath==="string")return void 0;const derivation={bindAddress:bindAddress??"127.0.0.1",port:portOrSocketPath,issuer:options?.listen?.issuer,loopbackNames};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,loopbackNames}):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,loopbackNames){if(!this.deriveHostValidation)return;this.hostValidation=this.deriveHostValidation(portOrSocketPath,bindAddress,loopbackNames)??this.hostValidation}loopbackNames(){return this.listeningLoopbackNames}registerRoute(method,path7,handler){this.router[method.toLowerCase()](path7,this.enhancedHandler(handler))}registerMiddleware(entryPath,handler){this.router.use(entryPath,this.enhancedHandler(handler))}enhancedHandler(handler){return(req,res,next)=>{Promise.resolve(handler(req,res,next)).catch(error=>next(error||new Error("Rejected promise")))}}prepare(){if(this.prepared)return;this.prepared=true;this.app.use("/",this.router);this.app.use(answerRequestError)}getHandler(){this.prepare();return this.app}createHttpServer(){const server=http.createServer(this.app);server.requestTimeout=this.requestTimeout;server.headersTimeout=this.headersTimeout;server.keepAliveTimeout=75e3;return server}async start(portOrSocketPath,bindAddress){this.prepare();const server=this.createHttpServer();this.httpServer=server;if(typeof portOrSocketPath==="string"){const ownerOnly=hasSocketFileMode();if(ownerOnly){await assertSafeSocketDirectory(portOrSocketPath);await clearStaleSocket(portOrSocketPath)}this.enableDerivedHostValidation(portOrSocketPath);this.deriveHostValidation=void 0;await new Promise((resolve5,reject)=>{server.on("error",reject);if(ownerOnly)listenOwnerOnly(server,portOrSocketPath,resolve5);else server.listen(portOrSocketPath,resolve5)});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";const{boundPort,boundAddress}=await new Promise((resolve5,reject)=>{server.on("error",reject);server.listen(portOrSocketPath,host,()=>{const bound=server.address();const port=typeof bound==="object"&&bound?bound.port:portOrSocketPath;const address=typeof bound==="object"&&bound?bound.address:host;this.listeningLoopbackNames=loopbackNamesOf(address,"pending");this.enableDerivedHostValidation(port,address,this.listeningLoopbackNames);resolve5({boundPort:port,boundAddress:address})})});const partner=await this.holdLoopbackPartner(server,boundAddress,boundPort);if(this.httpServer!==server)return;this.listeningLoopbackNames=loopbackNamesOf(boundAddress,partner);this.enableDerivedHostValidation(boundPort,boundAddress,this.listeningLoopbackNames);this.deriveHostValidation=void 0;console.log(`MCP HTTP (Express) on ${host}:${boundPort}`)}}async holdLoopbackPartner(owner,boundAddress,port){const partnerAddress=loopbackPartnerOf(boundAddress);if(!partnerAddress)return"absent";const partner=this.createHttpServer();const failure=await new Promise(resolve5=>{partner.on("error",error=>resolve5(error.code??"an error"));partner.listen(port,partnerAddress,()=>resolve5(void 0))});if(failure===void 0){if(this.httpServer===owner)this.partnerServer=partner;else await drainAndClose(partner,0);return"held"}if(NO_SUCH_ADDRESS.has(failure))return"absent";const[own]=loopbackNamesOf(boundAddress,"taken");const partnerUrl=`${partnerAddress}:${port}`;const elsewhere=failure==="EADDRINUSE"?`another process listens on ${partnerUrl}, so a browser that opens http://localhost:${port} may reach it instead`:`${partnerUrl} could not be held (${failure}), so a browser that opens http://localhost:${port} may reach another process there`;console.warn(`[frontmcp] ${elsewhere}: this server answers http://${own}:${port} only.`);return"taken"}async stop(drainMs=SERVER_DRAIN_MS){const servers=[this.httpServer,this.partnerServer].filter(server=>!!server);this.httpServer=void 0;this.partnerServer=void 0;this.listeningLoopbackNames=void 0;await Promise.all(servers.map(server=>drainAndClose(server,drainMs)))}};NO_SUCH_ADDRESS=new Set(["EADDRNOTAVAIL","EAFNOSUPPORT"])}});function isUnder(candidate,root){const relative2=path2.relative(root,candidate);return relative2===""||relative2!==".."&&!relative2.startsWith(`..${path2.sep}`)&&!path2.isAbsolute(relative2)}async function resolvesOutside(target,realRoot){const real=await(0,import_utils215.realpath)(target).catch(()=>void 0);if(real===void 0)return false;if(!isUnder(real,realRoot))return true;const isDirectory=await(0,import_utils215.stat)(real).then(stats=>stats.isDirectory(),()=>false);if(!isDirectory)return false;const index=await(0,import_utils215.realpath)(path2.join(real,"index.html")).catch(()=>void 0);return index!==void 0&&!isUnder(index,realRoot)}var http2,path2,import_express3,import_utils215,SERVER_DRAIN_MS2,DEFAULT_USER_CONTENT_CSP,UserContentListener;var init_user_content_listener=__esm({"libs/sdk/src/server/adapters/user-content.listener.ts"(){"use strict";http2=__toESM(require("node:http"));path2=__toESM(require("node:path"));import_express3=__toESM(require("express"));import_utils215=require("@frontmcp/utils");init_transport_errors();init_csp_middleware();init_host_validation_middleware();init_resolve_allowed_hosts();init_unix_socket_guard();SERVER_DRAIN_MS2=5e3;DEFAULT_USER_CONTENT_CSP="sandbox allow-scripts";UserContentListener=class{constructor(options,refuseClient){this.options=options;this.refuseClient=refuseClient;if(options.allowedHosts?.length&&!options.socketPath){this.hostValidation=createHostValidationMiddleware({enabled:true,allowedHosts:options.allowedHosts})}}options;refuseClient;httpServer;hostValidation;async start(mainListener,bindAddress="127.0.0.1"){const{socketPath}=this.options;const port=this.options.port??0;if(socketPath?socketPath===mainListener:port!==0&&port===mainListener){throw new UserContentConfigurationError(`it needs a port or socketPath of its own, not the MCP listener's (${mainListener})`)}const root=path2.resolve(this.options.root);const isDirectory=await(0,import_utils215.stat)(root).then(stats=>stats.isDirectory(),()=>false);if(!isDirectory)throw new UserContentConfigurationError(`root ${root} is not a directory`);const realRoot=await(0,import_utils215.realpath)(root);const server=http2.createServer(this.createApp(root,realRoot,this.responseHeaders()));this.httpServer=server;server.keepAliveTimeout=75e3;if(socketPath){const ownerOnly=hasSocketFileMode();if(ownerOnly){await assertSafeSocketDirectory(socketPath);await clearStaleSocket(socketPath)}await new Promise((resolve5,reject)=>{server.on("error",reject);if(ownerOnly)listenOwnerOnly(server,socketPath,resolve5);else server.listen(socketPath,resolve5)});if(ownerOnly){try{await enforceOwnerOnly(socketPath)}catch(error){await this.stop(0);throw error}}console.log(`User content on unix://${socketPath} (files from ${root})`);return}await new Promise((resolve5,reject)=>{server.on("error",reject);server.listen(port,bindAddress,()=>{const bound=server.address();const boundPort=typeof bound==="object"&&bound?bound.port:port;const boundAddress=typeof bound==="object"&&bound?bound.address:bindAddress;this.hostValidation??=this.derivedHostValidation(boundAddress,boundPort);console.log(`User content on ${bindAddress}:${boundPort} (files from ${root})`);resolve5()})})}address(){return this.httpServer?.address()}async stop(drainMs=SERVER_DRAIN_MS2){const server=this.httpServer;if(!server)return;this.httpServer=void 0;const closed=new Promise(resolve5=>server.close(()=>resolve5()));server.closeIdleConnections();const forceClose=setTimeout(()=>server.closeAllConnections(),drainMs);try{await closed}finally{clearTimeout(forceClose)}}createApp(root,realRoot,headers){const app=(0,import_express3.default)();app.disable("x-powered-by");app.use((_req,res,next)=>{for(const[name60,value]of Object.entries(headers))res.setHeader(name60,value);next()});app.use(((req,res,next)=>{const validate=this.hostValidation;if(!validate)return next();return validate(req,res,next)}));app.use(((req,res,next)=>{const refuse=this.refuseClient;if(!refuse)return next();refuse(req,res).then(refused2=>refused2?void 0:next(),next)}));app.use(this.confinedToRoot(root,realRoot));app.use(import_express3.default.static(root,{dotfiles:"ignore",fallthrough:true}));app.use((_req,res)=>{res.status(404).type("text/plain").send("Not Found")});app.use((_error,_req,res,_next)=>{res.status(500).type("text/plain").send("Internal Server Error")});return app}confinedToRoot(root,realRoot){const rootPrefix=root.endsWith(path2.sep)?root:`${root}${path2.sep}`;return(req,res,next)=>{if(req.method!=="GET"&&req.method!=="HEAD")return next();let pathname;try{pathname=decodeURIComponent(req.path)}catch{return next()}const target=path2.resolve(root,`.${pathname}`);if(pathname.includes("\0")||target!==root&&!target.startsWith(rootPrefix))return next();resolvesOutside(target,realRoot).then(outside=>outside?res.status(404).type("text/plain").send("Not Found"):next(),next)}}derivedHostValidation(bindAddress,port){const derivation={bindAddress,port};if(!shouldEnforceDerivedHosts(derivation)){console.warn(`[frontmcp] http.userContent is not checking the Host header: it binds a routable address (${bindAddress}) and no allowed hosts are configured. Set http.userContent.allowedHosts to the content origin hostname(s).`);return void 0}return createHostValidationMiddleware({enabled:true,allowedHosts:deriveAllowedHosts(derivation)})}responseHeaders(){const headers={"X-Content-Type-Options":"nosniff",...this.options.headers};const csp=this.options.csp;if(csp){const directives=Object.fromEntries(Object.entries(csp.directives).map(([name60,value2])=>[name60,Array.isArray(value2)?value2.join(" "):value2]));const reportOnly=csp.reportOnly??false;const value=buildCspHeaderValue({enabled:true,directives,reportUri:csp.reportUri,reportOnly});if(value)headers[getCspHeaderName(reportOnly)]=value}const enforcesOwnPolicy=Object.keys(headers).some(name60=>name60.toLowerCase()==="content-security-policy");if(csp!==false&&!enforcesOwnPolicy)headers["Content-Security-Policy"]=DEFAULT_USER_CONTENT_CSP;for(const[name60,value]of Object.entries(headers)){try{http2.validateHeaderName(name60);http2.validateHeaderValue(name60,value)}catch(error){throw new UserContentConfigurationError(`header "${name60}" cannot be sent: ${error.message}`)}}return headers}}}});var node_express_host_exports={};__export(node_express_host_exports,{DEFAULT_EXPRESS_BODY_LIMIT:()=>DEFAULT_EXPRESS_BODY_LIMIT,ExpressHostAdapter:()=>ExpressHostAdapter,UserContentListener:()=>UserContentListener});var init_node_express_host=__esm({"libs/sdk/src/server/adapters/polyfills/node-express-host.ts"(){"use strict";init_express_host_adapter();init_user_content_listener()}});var server_instance_exports={};__export(server_instance_exports,{FrontMcpServerInstance:()=>FrontMcpServerInstance});var import_utils216,DEFAULT_CORS,FrontMcpServerInstance;var init_server_instance=__esm({"libs/sdk/src/server/server.instance.ts"(){"use strict";import_utils216=require("@frontmcp/utils");init_common();init_path_utils();init_health2();init_mcp_registry_utils();init_metrics2();init_custom_routes_helper();init_cors_env();init_resolve_allowed_hosts();init_security_audit();init_server_validation();DEFAULT_CORS=void 0;FrontMcpServerInstance=class extends FrontMcpServer{config;host;healthRouteRegistered=false;_healthService;_healthConfig;metricsRouteRegistered=false;_metricsService;_metricsConfig;userContent;checkClientIp;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}:{},...this.config.headersTimeout!==void 0?{headersTimeout:this.config.headersTimeout}:{},...this.config.requestTimeout!==void 0?{requestTimeout:this.config.requestTimeout}:{}})}}registerMiddleware(entryPath,handler){return this.host.registerMiddleware(entryPath,handler)}registerRoute(method,path7,handler){return this.host.registerRoute(method,path7,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}setClientIpCheck(checkClientIp){this.checkClientIp=checkClientIp}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){const check=this.checkClientIp;const routes=check?{registerRoute:(method,path7,handler)=>this.registerRoute(method,path7,wrapWithIpFilter(handler,check))}:this;registerMetricsRoutes(routes,this._metricsService,this._metricsConfig)}}this.host.prepare()}getHandler(){return this.host.getHandler()}async start(){this.prepare();const deploymentMode=(0,import_utils216.getRuntimeContext)().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},(0,import_utils216.isProduction)());logSecurityFindings(findings,console);const mainListener=this.config.socketPath??this.config.port;await this.host.start(mainListener,bindAddress);if(this.config.userContent){const{UserContentListener:UserContentListener2}=(init_node_express_host(),__toCommonJS(node_express_host_exports));this.userContent=new UserContentListener2(this.config.userContent,this.refuseClient());await this.userContent.start(mainListener,bindAddress);this.warnOfSharedContentHosts(bindAddress)}}loopbackNames(){return this.host.loopbackNames?.()}warnOfSharedContentHosts(bindAddress){const contentHosts=this.config.userContent?.allowedHosts;if(!contentHosts?.length||this.config.userContent?.socketPath)return;const mcpHosts=this.mcpListenerHosts(bindAddress);const shared=mcpHosts==="any"?sharedHostnames(contentHosts,contentHosts):sharedHostnames(contentHosts,mcpHosts);if(shared.length===0)return;const answers=mcpHosts==="any"?"which the MCP listener answers to as well, since it checks no Host (set http.security.dnsRebindingProtection.allowedHosts)":"which the MCP listener answers to as well";console.warn(`[frontmcp] http.userContent.allowedHosts names ${shared.join(", ")}, ${answers}. Browsers share cookies between the ports of a host: serve user content from a registrable domain of its own in production, and keep a sandbox directive in http.userContent.csp.`)}mcpListenerHosts(bindAddress){if(this.config.socketPath)return[];const protection=this.config.security?.dnsRebindingProtection;if(protection?.enabled===false)return"any";const explicit=protection?.allowedHosts??allowedHostsFromEnv();if(explicit?.length)return explicit;return isLoopbackAddress(bindAddress)?deriveAllowedHosts({bindAddress,port:this.config.port}):"any"}refuseClient(){const check=this.checkClientIp;if(!check)return void 0;return async(req,res)=>{const rejection=await check(req,res);if(rejection)await writeHttpResponse(res,rejection);return rejection!==void 0}}async stop(){const results=await Promise.allSettled([(async()=>this.host.stop())(),(async()=>this.userContent?.stop())()]);const failure=results.find(result=>result.status==="rejected");if(failure)throw failure.reason}}}});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 import_di55,frontMcpConfig,defaultHttpOptions,frontMcpServer,noopServer;var init_front_mcp_providers=__esm({"libs/sdk/src/front-mcp/front-mcp.providers.ts"(){"use strict";import_di55=require("@frontmcp/di");init_common();init_context();init_noop_server();init_front_mcp_tokens2();frontMcpConfig={with:metadata=>({name:"frontmcp:config",provide:FrontMcpConfig,scope:import_di55.ProviderScope.GLOBAL,useValue:metadata})};defaultHttpOptions=()=>({port:defaultHttpPort(),entryPath:"/mcp"});frontMcpServer=AsyncProvider({name:"frontmcp:server",scope:import_di55.ProviderScope.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:import_di55.ProviderScope.GLOBAL,useValue:new NoopFrontMcpServer}}});function checkSessionSecret(config,entryFallback){if(!(0,import_utils217.isProduction)()||(0,import_auth85.isSessionSecretConfigured)())return false;if((config.transport?.defaultProtocolVersion??entryFallback)==="legacy"){throw new import_auth85.SessionSecretRequiredError("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 import_auth85,import_utils217,MISSING_SESSION_SECRET_WARNING,missingSessionSecretProbe;var init_session_secret_check=__esm({"libs/sdk/src/front-mcp/session-secret.check.ts"(){"use strict";import_auth85=require("@frontmcp/auth");import_utils217=require("@frontmcp/utils");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})}}});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=(0,import_utils218.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 import_utils218,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";import_utils218=require("@frontmcp/utils");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});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 import_utils219,_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";import_utils219=require("@frontmcp/utils");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 filePath2=getPath().join(this.logDir,`${this.appName}-${ts}.log`);this.fd=getFs().openSync(filePath2,"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?` [${(0,import_utils219.escapeControlCharacters)(rec.prefix)}]`:"";const message=(0,import_utils219.escapeControlCharacters)(stripAnsi(String(rec.message)));const line=`[${ts}] ${level}${prefix} ${message}
|
|
491
|
+
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});function createAuthoritiesEngine(config){const profileRegistry=new import_auth83.AuthoritiesProfileRegistry;if(config["profiles"]){profileRegistry.registerAll(config["profiles"])}const evaluatorRegistry=new import_auth83.AuthoritiesEvaluatorRegistry;if(config["evaluators"]){evaluatorRegistry.registerAll(config["evaluators"])}return new import_auth83.AuthoritiesEngine(profileRegistry,evaluatorRegistry)}function authoritiesFromConfig(config){return{engine:createAuthoritiesEngine(config),contextBuilder:new import_auth83.AuthoritiesContextBuilder({claimsMapping:config["claimsMapping"],claimsResolver:config["claimsResolver"],relationshipResolver:config["relationshipResolver"]}),scopeMapping:config["scopeMapping"]}}var import_auth83;var init_authorities_engine=__esm({"libs/sdk/src/front-mcp/authorities-engine.ts"(){"use strict";import_auth83=require("@frontmcp/auth")}});var send_elicitation_result_tool_exports={};__export(send_elicitation_result_tool_exports,{SendElicitationResultTool:()=>SendElicitationResultTool});var import_lazy_zod154,inputSchema51,SendElicitationResultTool;var init_send_elicitation_result_tool=__esm({"libs/sdk/src/elicitation/send-elicitation-result.tool.ts"(){"use strict";import_lazy_zod154=require("@frontmcp/lazy-zod");init_common();init_call_surface();init_errors();init_fallback_helper();inputSchema51={elicitId:import_lazy_zod154.internalZ.string().describe("The elicitation ID from the pending request"),action:import_lazy_zod154.internalZ.enum(["accept","cancel","decline"]).describe("User action: accept (submit), cancel, or decline"),content:import_lazy_zod154.internalZ.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:inputSchema51,hideFromDiscovery:true})],SendElicitationResultTool)}});function keptUntilFailure(start,forget){return start.catch(error=>{forget();throw error})}function entriesWithAuthorities(registries,agentPath=""){const entries=[];const add=(kind,name60,metadata)=>{const authorities=metadata?.["authorities"];if(authorities!==void 0&&authorities!==null&&authorities!==false){entries.push({label:`${kind} "${agentPath}${name60}"`,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 import_reflect_metadata30,import_guard9,import_utils211,SCOPE_NON_DISPATCHABLE_FLOWS,Scope;var init_scope_instance=__esm({"libs/sdk/src/scope/scope.instance.ts"(){"use strict";import_reflect_metadata30=require("reflect-metadata");import_guard9=require("@frontmcp/guard");import_utils211=require("@frontmcp/utils");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_borrow_providers();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,path7,handler)=>{this.registeredHttpRoutes.push({method,path:path7,handler});return this.server.registerRoute(method,path7,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=serverProvidersOn(rec.metadata.providers??[],globalProviders.container);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=(0,import_utils211.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=(0,import_utils211.getRuntimeContext)().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(ha);const haSubscriber=this.createHaRedisClient(ha,"ha-subscriber");this.haManager=ha.HaManager.create({redis:haRedis,pubsubPublisher:haRedis,pubsubSubscriber:haSubscriber,nodeId:(0,import_utils211.getMachineId)(),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,(0,import_utils211.getMachineId)(),{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((0,import_utils211.getRuntimeContext)().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:createEventStore3}=await Promise.resolve().then(()=>(init_event_stores(),event_stores_exports));const{eventStore}=createEventStore3(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=(0,import_utils211.isEdgeRuntime)();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=(0,import_utils211.isEdgeRuntime)();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?(0,import_guard9.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 serverProviders=serverProvidersOn(this.metadata.providers??[],this.globalProviders.container);const serverHooks=serverProviderHooks(this.scopeProviders,serverProviders,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"||httpServing?.peopleKeepSessionsInSqlite(this,resolvedTopLevelSqlite)===true;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&&(0,import_utils211.getRuntimeContext)().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:(0,import_utils211.getMachineId)(),haManager:this.haManager,bus:this.transportBus,transportService,notifications:this.notificationService,flows:{runFlow:(name60,input)=>this.runFlow(name60,input)},logger:this.logger})}if(httpServing){await httpServing.attachHttpRoutes(this,this.globalProviders,{sqlite:this.topLevelSqlite});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||(0,import_utils211.getRuntimeContext)().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:dirname11}=require("path");await(0,import_utils211.mkdir)(dirname11(finalPath),{recursive:true,mode:448})}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:path7}of widgets){this.logger.warn(`Tool "${toolName}": \`ui.servingMode: 'direct-url'\` serves the widget on GET ${path7}, 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:import_di4.ProviderScope.GLOBAL,name:"ScopeEntry",provide:ScopeEntry,useValue:this},{scope:import_di4.ProviderScope.GLOBAL,name:"Scope",provide:_Scope,useValue:this},{scope:import_di4.ProviderScope.GLOBAL,name:"FrontMcpLogger",provide:FrontMcpLogger,useValue:this.logger},{scope:import_di4.ProviderScope.GLOBAL,name:"FrontMcpContextStorage",provide:FrontMcpContextStorage,useValue:new FrontMcpContextStorage().configure(this.metadata.fetch,{...proxyTrustOf(this.metadata.throttle),forwardsHeader:createHeaderForwarder(this.metadata.http?.forwardHeaders)})},FrontMcpContextProvider,{scope:import_di4.ProviderScope.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(0,import_guard9.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(0,import_guard9.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(name60,input,deps){return this.scopeFlows.runFlow(name60,input,deps)}async findHttpFlowName(request2){return this.scopeFlows.findHttpFlowName(request2,SCOPE_NON_DISPATCHABLE_FLOWS)}async runFlowForOutput(name60,input,deps){const result=await this.scopeFlows.runFlow(name60,input,deps);if(result){return result}throw new FlowExitedWithoutOutputError}createHaRedisClient(ha,label="ha"){const client=ha.createHaRedisClient(this.metadata.redis,label,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(name60){return new Proxy({},{get:(target,property,receiver)=>typeof property==="symbol"||isProbe(property)||property in target?Reflect.get(target,property,receiver):()=>{throw new StoreNotOpenedInBuildError(name60)}})}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",typeof scope==="string"?scope:"machine")}async function appLeaseKey(name60,scope){let key;try{key=typeof scope.key==="function"?await scope.key():scope.key}catch(error){throw new DutyLeaseKeyError(name60,`failed (${error instanceof Error?error.message:String(error)})`)}const trimmed=typeof key==="string"?key.trim():"";if(trimmed==="")throw new DutyLeaseKeyError(name60,"answered no string");if(trimmed.length>MAX_DUTY_LEASE_KEY_LENGTH){throw new DutyLeaseKeyError(name60,`answered a key longer than ${MAX_DUTY_LEASE_KEY_LENGTH} characters`)}return trimmed}async function preferenceOf(prefer){if(prefer===void 0)return void 0;return(typeof prefer==="function"?await prefer():prefer)===true}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,MAX_DUTY_LEASE_KEY_LENGTH,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_work_spans();init_cron_schedule();init_duty_runner();init_lazy_lease_store();init_lease_store();lifecycles=new WeakMap;claims=new LeaseClaims;MAX_DUTY_LEASE_KEY_LENGTH=1024;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:name60,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 "${name60}"`)}}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:name60,leaseMs,scope}=metadata;const logger=this.providers.get(FrontMcpLogger);if(!isLongLivedProcess()){logger.warn(`Duty "${name60}" 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=typeof scope==="string"?leaseKey(name60,scope,serverName):keyedLeaseKey(name60,await appLeaseKey(name60,scope),serverName);const prefer=await preferenceOf(metadata.prefer);this.claim(serverName);const storage=new LazyLeaseStore(dutyStorageConfig(config.redis,scope));const run=context=>withWorkSpan("duty",name60,()=>this.duty.run(context));const common={name:name60,key,leaseMs,storage,logger,run,...prefer===void 0?{}:{prefer}};const runner=new DutyRunner(metadata.cron?{...common,cron:await this.cronSchedule(metadata.cron)}:{...common,everyMs:metadata.everyMs});const removeHealthProbe=registerReadinessProbe(this.providers,{name:`duty:${name60}`,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(resolve5=>{const settle=()=>{clearTimeout(timer);signal.removeEventListener("abort",settle);resolve5()};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:name60,logger}=this.options;if(failure===void 0)logger.warn(`Worker "${name60}" returned before its signal was aborted; ${next}`);else logger.error(`Worker "${name60}" 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_work_spans();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:name60,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 "${name60}"`)}}async start(){const{name:name60,restart,scope}=this.metadata;const logger=this.providers.get(FrontMcpLogger);if(!isLongLivedProcess()){logger.warn(`Worker "${name60}" 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 run=context=>withWorkSpan("worker",name60,()=>this.worker.run(context));const supervisor=new WorkerSupervisor({name:name60,restart,logger,run});if(scope!=="process")return this.contend(supervisor,scope,logger);logger.info(`Worker "${name60}" runs in this process`);supervisor.start();return{supervisor,removeHealthProbe:this.registerHealthProbe(supervisor)}}async contend(supervisor,scope,logger){const{name:name60,leaseMs}=this.metadata;const config=this.providers.get(FrontMcpConfig);const serverName=config.info?.name??"frontmcp";const key=leaseKey(name60,scope,serverName);const storage=new LazyLeaseStore(leaseStorageConfig(config.redis,"worker",scope));const removeHealthProbe=this.registerHealthProbe(supervisor,storage);const holder=new LeaseHolder({label:`Worker "${name60}"`,key,leaseMs,storage,logger,onAcquired:()=>{logger.info(`Worker "${name60}" 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)})}}}});function verifiedSessionOf3(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 import_reflect_metadata31,import_di52,ProviderRegistry,REQUEST_PROVIDER_STORES;var init_provider_registry=__esm({"libs/sdk/src/provider/provider.registry.ts"(){"use strict";import_reflect_metadata31=require("reflect-metadata");import_di52=require("@frontmcp/di");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??options?.sharedLifecycles??new WeakMap;this.container=parentProviders?.container??options?.container;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;heldEntries=[];backgroundEntries=[];readyEntries=[];container;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((0,import_di52.tokenName)(token),"not registered in hierarchy");const{registry,rec}=found;const sc=registry.getProviderScope(rec);if(sc!==import_di52.ProviderScope.GLOBAL){const scName=import_di52.ProviderScope[sc];throw new ProviderScopeMismatchError((0,import_di52.tokenName)(token),scName,registry.constructor.name)}const inst=registry.instances.get(token);if(inst===void 0){throw new ProviderNotInstantiatedError((0,import_di52.tokenName)(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 ${(0,import_di52.tokenName)(token)} depends on ${(0,import_di52.tokenName)(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)!==import_di52.ProviderScope.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===import_di52.ProviderScope.GLOBAL)return;throw new InvalidDependencyScopeError(`Invalid dependency: DEFAULT-scoped provider ${(0,import_di52.tokenName)(token)} cannot depend on scoped provider ${(0,import_di52.tokenName)(dependency)}.`)}topoSort(){const WHITE=0,GRAY=1,BLACK=2;const color=new Map;const order=new Set;const path7=[];const dfs=n=>{color.set(n,GRAY);path7.push(n);for(const dep of this.graph.get(n)??[]){const c=color.get(dep)??WHITE;if(c===GRAY){const idx=path7.findIndex(p=>p===dep);const cycle=[...path7.slice(idx),dep].map(t=>(0,import_di52.tokenName)(t)).join(" -> ");throw new DependencyCycleError(cycle)}if(c===WHITE)dfs(dep)}color.set(n,BLACK);order.add(n);path7.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)!==import_di52.ProviderScope.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((0,import_di52.tokenName)(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 borrowed=!!shared&&!!this.container?.owned.has(instance);if(borrowed&&this.container?.disposed)throw new ContainerDisposedError;const lifecycle=shared??{holders:0,bootstrapped:bootstrapProvider(entry)};if(!shared)this.sharedLifecycles.set(instance,lifecycle);lifecycle.holders++;await lifecycle.bootstrapped;if(!shared&&background)this.backgroundEntries.push({token,lifecycle:background});if(!shared||this.container)this.readyEntries.push({entry,borrowed,background:!!background});this.heldEntries.push(entry)}heldLifecycles(){return this.heldEntries.map(({instance})=>instance)}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 this.readyInBuildOrder(logger);for(const child of[...this.childRegistries])failures.push(...await child.runReadyHooks(logger));return failures}async readyInBuildOrder(logger){const container=this.container;const failures=[];for(const{entry,borrowed,background}of this.readyEntries){if(!container){failures.push(...await readyProviders([entry],logger));continue}if(borrowed&&background&&container.backgroundStarted)continue;const running=container.readied.get(entry.instance);if(running){await running;continue}const readying=readyProviders([entry],logger);container.readied.set(entry.instance,readying);failures.push(...await readying)}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 "${(0,import_di52.tokenName)(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 "${(0,import_di52.tokenName)(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)!==import_di52.ProviderScope.CONTEXT)continue;if(rec.kind===import_di52.ProviderKind.CLASS)out.push({token,cls:rec.useClass});else if(rec.kind===import_di52.ProviderKind.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)=>(0,import_di52.depsOfClass)(k,phase))}invocationTokens(_token,rec){return providerInvocationTokens(rec,(k,phase)=>(0,import_di52.depsOfClass)(k,phase))}normalizeScope(scope){switch(scope){case import_di52.ProviderScope.SESSION:case import_di52.ProviderScope.REQUEST:return import_di52.ProviderScope.CONTEXT;default:return scope}}getProviderScope(rec){const rawScope=rec.metadata?.scope??import_di52.ProviderScope.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===import_di52.ProviderScope.GLOBAL){if(!this.instances.has(t)){throw new ProviderNotInstantiatedError((0,import_di52.tokenName)(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===import_di52.ProviderScope.GLOBAL){const inst=up.registry.instances.get(t);if(inst===void 0){throw new ProviderNotInstantiatedError((0,import_di52.tokenName)(t),"DEFAULT","parent")}return inst}else{await up.registry.buildIntoStore(t,up.rec,store,scopeKey);return store.get(t)}}if((0,import_di52.isClass)(t)){if((0,import_di52.hasAsyncWith)(t)){const out=t.with();return(0,import_di52.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((0,import_di52.isPromise)(ret))await this.withTimeout(ret,this.asyncTimeoutMs,`${t.name}.init()`)}return instance}throw new ProviderNotRegisteredError((0,import_di52.tokenName)(t),"not registered in hierarchy and not constructable")}bootsForBuild(){const config=this.lookupDefInHierarchy(FrontMcpConfig)?.rec;return config?.kind===import_di52.ProviderKind.VALUE&&typeof config.useValue==="object"&&config.useValue!==null&&isManifestMode(config.useValue)}async initiateOne(token,rec){switch(rec.kind){case import_di52.ProviderKind.VALUE:{this.instances.set(token,rec.useValue);return}case import_di52.ProviderKind.FACTORY:{if(opensStore(rec.useFactory)&&this.bootsForBuild()){this.instances.set(token,storeNotOpened(rec.metadata?.name??(0,import_di52.tokenName)(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=(0,import_di52.isPromise)(out)?await this.withTimeout(out,this.asyncTimeoutMs,`${(0,import_di52.tokenName)(token)}.useFactory(...)`):out;this.instances.set(token,val);return}case import_di52.ProviderKind.CLASS:{const depTokens=this.invocationTokens(token,rec);const deps=depTokens.map(t=>this.resolveDefaultFromHierarchy(t));const klass=rec.useClass;if((0,import_di52.hasAsyncWith)(klass)){const out=klass.with(...deps);const val=(0,import_di52.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((0,import_di52.isPromise)(ret))await this.withTimeout(ret,this.asyncTimeoutMs,`${klass.name}.init()`)}this.instances.set(token,instance)}return}case import_di52.ProviderKind.CLASS_TOKEN:{const depTokens=this.invocationTokens(token,rec);const deps=depTokens.map(t=>this.resolveDefaultFromHierarchy(t));const klass=rec.provide;if((0,import_di52.hasAsyncWith)(klass)){const out=klass.with(...deps);const val=(0,import_di52.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((0,import_di52.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 import_di52.ProviderKind.VALUE:{store.set(token,rec.useValue);return}case import_di52.ProviderKind.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=(0,import_di52.isPromise)(out)?await this.withTimeout(out,this.asyncTimeoutMs,`${(0,import_di52.tokenName)(token)}.useFactory(...)`):out;store.set(token,val);return}case import_di52.ProviderKind.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((0,import_di52.hasAsyncWith)(klass)){const out=klass.with(...deps);const val=(0,import_di52.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((0,import_di52.isPromise)(ret))await this.withTimeout(ret,this.asyncTimeoutMs,`${klass.name}.init()`)}store.set(token,instance)}return}case import_di52.ProviderKind.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((0,import_di52.hasAsyncWith)(klass)){const out=klass.with(...deps);const val=(0,import_di52.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((0,import_di52.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((0,import_di52.tokenName)(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===import_di52.ProviderScope.GLOBAL){const v=this.instances.get(d);if(v===void 0)throw new ProviderNotInstantiatedError((0,import_di52.tokenName)(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===import_di52.ProviderScope.GLOBAL){const v=up.registry.instances.get(d);if(v===void 0)throw new ProviderNotInstantiatedError((0,import_di52.tokenName)(d),"DEFAULT","parent");return v}else{await up.registry.buildIntoStore(d,up.rec,store,scopeKey);return store.get(d)}}throw new ProviderNotInstantiatedError((0,import_di52.tokenName)(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)!==import_di52.ProviderScope.GLOBAL){const scName=import_di52.ProviderScope[this.getProviderScope(rec)];throw new ProviderScopedAccessError((0,import_di52.tokenName)(token),scName)}if(this.providers)return this.providers.getFor(token,requester);throw new ProviderNotAvailableError((0,import_di52.tokenName)(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!==import_di52.ProviderScope.GLOBAL)throw new PluginDependencyError(`Plugin dependency ${(0,import_di52.tokenName)(t)} must be DEFAULT-scoped at bootstrap`);const v=registry.instances.get(t);if(v===void 0)throw new PluginDependencyError(`Plugin dependency ${(0,import_di52.tokenName)(t)} (DEFAULT scope) is not instantiated`);return v}throw new PluginDependencyError(`Cannot resolve plugin dependency ${(0,import_di52.tokenName)(t)} (local or parent)`)}resolve(cls){const found=this.lookupDefInHierarchy(cls);if(found){const{registry,rec}=found;const sc=registry.getProviderScope(rec);if(sc!==import_di52.ProviderScope.GLOBAL){const scName=import_di52.ProviderScope[sc];throw new ProviderScopedAccessError((0,import_di52.tokenName)(cls),scName)}if(!registry.instances.has(cls)){throw new ProviderNotInstantiatedError((0,import_di52.tokenName)(cls),"DEFAULT","Call providers.instantiate() first")}return registry.instances.get(cls)}if((0,import_di52.isClass)(cls)){const instance=new cls;const init=instance?.init;if(typeof init==="function"){init.call(instance)}return instance}throw new ProviderNotRegisteredError((0,import_di52.tokenName)(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??import_di52.ProviderScope.GLOBAL;if(scope===import_di52.ProviderScope.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((0,import_di52.tokenName)(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:import_di52.ProviderKind.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)===import_di52.ProviderScope.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){for(const child of this.childRegistries)child.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)!==import_di52.ProviderScope.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)!==import_di52.ProviderScope.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)!==import_di52.ProviderScope.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||verifiedSessionOf3(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 import_di52.ProviderKind.VALUE:{store.set(token,rec.useValue);return}case import_di52.ProviderKind.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=(0,import_di52.isPromise)(out)?await this.withTimeout(out,this.asyncTimeoutMs,`${(0,import_di52.tokenName)(token)}.useFactory(...)`):out;store.set(token,val);return}case import_di52.ProviderKind.CLASS:case import_di52.ProviderKind.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===import_di52.ProviderKind.CLASS?rec.useClass:rec.provide;if((0,import_di52.hasAsyncWith)(klass)){const out=klass.with(...deps);const val=(0,import_di52.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((0,import_di52.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((0,import_di52.tokenName)(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===import_di52.ProviderScope.GLOBAL){throw new ProviderNotInstantiatedError((0,import_di52.tokenName)(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===import_di52.ProviderScope.GLOBAL){const v=up.registry.instances.get(token);if(v!==void 0)return v;throw new ProviderNotInstantiatedError((0,import_di52.tokenName)(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 ${(0,import_di52.tokenName)(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((0,import_di52.tokenName)(token),"not found in views. Ensure it was built via buildViews()")}};REQUEST_PROVIDER_STORES=Symbol("frontmcp:request-provider-stores")}});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(0,import_di53.depsOfClass)(rec.provide,"discovery").slice(1);case"SPLIT_BY_APP":return[]}}var import_di53;var init_scope_utils=__esm({"libs/sdk/src/scope/scope.utils.ts"(){"use strict";import_di53=require("@frontmcp/di");init_app_utils();init_errors();init_scope_instance()}});var import_reflect_metadata32,import_di54,ScopeRegistry;var init_scope_registry=__esm({"libs/sdk/src/scope/scope.registry.ts"(){"use strict";import_reflect_metadata32=require("reflect-metadata");import_di54=require("@frontmcp/di");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",(0,import_di54.tokenName)(token),(0,import_di54.tokenName)(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 '${(0,import_di54.tokenName)(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=(0,import_utils50.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 path7=config.path??"/metrics";for(const prefix of MCP_RESERVED_PATH_PREFIXES){if(path7===prefix||path7.startsWith(`${prefix}/`)){throw new MetricsPathConflictError(path7)}}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=name60=>allowedPrefixes.some(prefix=>name60.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[name60,value]of Object.entries(result.headers))res.setHeader?.(name60,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()}});function readCorsFromEnv(){const rawOrigins=(0,import_utils212.getEnv)("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=(0,import_utils212.getEnv)("FRONTMCP_CORS_CREDENTIALS");if(credentials!==void 0)cors2.credentials=credentials==="true"||credentials==="1";const maxAge=Number((0,import_utils212.getEnv)("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 import_utils212;var init_cors_env=__esm({"libs/sdk/src/server/middleware/cors-env.ts"(){"use strict";import_utils212=require("@frontmcp/utils")}});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()}});function readCspFromEnv(){if(!(0,import_utils213.getEnvFlag)("FRONTMCP_CSP_ENABLED"))return void 0;const rawDirectives=(0,import_utils213.getEnv)("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:(0,import_utils213.getEnv)("FRONTMCP_CSP_REPORT_URI"),reportOnly:(0,import_utils213.getEnvFlag)("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(name60,fallback){const value=(0,import_utils213.getEnv)(name60);if(value===void 0||value==="")return fallback;return["off","false","none"].includes(value.trim().toLowerCase())?void 0:value}function readCustomHeadersFromEnv(){const raw=(0,import_utils213.getEnv)("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[name60,value]of Object.entries(headers.custom)){res.setHeader(name60,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[name60,value]of Object.entries(options.csp.directives??{})){directives[name60]=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:(name60,value)=>void(headers[name60]=value)},resolved,csp);return headers}var import_utils213;var init_csp_middleware=__esm({"libs/sdk/src/server/middleware/csp.middleware.ts"(){"use strict";import_utils213=require("@frontmcp/utils")}});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()}});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(0,import_utils214.realpath)(socketDirectory);await assertNoOtherUserCanReplace2(socketDirectory);if(realSocketDirectory!==socketDirectory)await assertNoOtherUserCanReplace2(realSocketDirectory);if(canBindOwnerOnly())return;const{mode}=await(0,import_utils214.stat)(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(import_node_cluster.default.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((resolve5,reject)=>{const socket=net.connect(socketPath);socket.once("connect",()=>{socket.destroy();resolve5("live")});socket.once("error",error=>{const code=errorCode(error);if(code==="ECONNREFUSED")resolve5("stale");else if(code==="ENOENT")resolve5("gone");else reject(new SocketPathConflictError(socketPath,`connecting to it failed (${code??error.message})`))})})}async function clearStaleSocket(socketPath){let stats;try{stats=await(0,import_utils214.lstat)(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(0,import_utils214.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(0,import_utils214.chmod)(socketPath,OWNER_ONLY_MODE)}catch(error){throw new SocketPermissionError(socketPath,`chmod failed (${errorCode(error)??String(error)})`)}const mode=(await(0,import_utils214.lstat)(socketPath)).mode&511;if(mode!==OWNER_ONLY_MODE)throw new SocketPermissionError(socketPath,`its mode is 0${mode.toString(8)}`)}var import_node_cluster,net,path,import_utils214,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";import_node_cluster=__toESM(require("node:cluster"));net=__toESM(require("node:net"));path=__toESM(require("node:path"));import_utils214=require("@frontmcp/utils");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{}}});function utf8JsonParser(limit){const readBody=import_express.default.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 import_express,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";import_express=__toESM(require("express"));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"})}});function isClientRequestError(error){const{expose,status}=error??{};return expose===true&&typeof status==="number"&&status>=400&&status<500}function clientRequestJsonRpcError(error){if(error.type==="entity.too.large")return new PayloadTooLargeError(error.limit,error.length).toJsonRpcError();if(error.type==="entity.parse.failed")return{code:MCP_ERROR_CODES.PARSE_ERROR,message:"Parse error"};return{code:MCP_ERROR_CODES.INVALID_REQUEST,message:String(error.message)}}function answerRequestError(error,_req,res,next){if(res.headersSent)return next(error);if(isClientRequestError(error)){res.status(error.status).json({jsonrpc:"2.0",id:null,error:clientRequestJsonRpcError(error)});return}const output=flowErrorToHttpOutput(error)??INTERNAL_SERVER_ERROR;if(output.status>=500)console.error("[frontmcp] HTTP request failed:",error);writeHttpResponse(res,output).catch(()=>res.destroy())}async function drainAndClose(server,drainMs){const closed=new Promise(resolve5=>server.close(()=>resolve5()));server.closeIdleConnections();const forceClose=setTimeout(()=>server.closeAllConnections(),drainMs);try{await closed}finally{clearTimeout(forceClose)}}var http,import_cors,import_express2,SERVER_DRAIN_MS,DEFAULT_EXPRESS_BODY_LIMIT,DEFAULT_HEADERS_TIMEOUT_MS,DEFAULT_REQUEST_TIMEOUT_MS,INTERNAL_SERVER_ERROR,ExpressHostAdapter,NO_SUCH_ADDRESS;var init_express_host_adapter=__esm({"libs/sdk/src/server/adapters/express.host.adapter.ts"(){"use strict";http=__toESM(require("node:http"));import_cors=__toESM(require("cors"));import_express2=__toESM(require("express"));init_mcp_error();init_ha_headers();init_flow_error_output();init_csp_middleware();init_host_validation_middleware();init_resolve_allowed_hosts();init_unix_socket_guard();init_server_validation();init_base_host_adapter();init_utf8_json_parser();SERVER_DRAIN_MS=5e3;DEFAULT_EXPRESS_BODY_LIMIT="4mb";DEFAULT_HEADERS_TIMEOUT_MS=6e4;DEFAULT_REQUEST_TIMEOUT_MS=3e5;INTERNAL_SERVER_ERROR={kind:"text",status:500,body:"Internal Server Error"};ExpressHostAdapter=class extends HostServerAdapter{app=(0,import_express2.default)();router=import_express2.default.Router();prepared=false;httpServer;headersTimeout;requestTimeout;partnerServer;listeningLoopbackNames;hostValidation;deriveHostValidation;constructor(options){super();this.requestTimeout=options?.requestTimeout??DEFAULT_REQUEST_TIMEOUT_MS;const headersTimeout=options?.headersTimeout??DEFAULT_HEADERS_TIMEOUT_MS;this.headersTimeout=this.requestTimeout>0?Math.min(headersTimeout,this.requestTimeout):headersTimeout;this.app.disable("x-powered-by");const securityHeaders=resolveSecurityHeaders(options?.securityHeaders);this.app.use((_req,res,next)=>{for(const[name60,value]of Object.entries(securityHeaders))res.setHeader(name60,value);applyMachineIdHeader(res);next()});const corsOptions=options?.cors;const corsEnabled=corsOptions?.origin!==void 0&&corsOptions.origin!==false;if(corsEnabled){const configuredCors=(0,import_cors.default)({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(import_express2.default.urlencoded({extended:true,limit:formLimit,type:isUrlencoded,verify:keepBodyBytes}));this.app.use(utf8JsonParser(jsonLimit));this.app.use(import_express2.default.json({limit:jsonLimit,type:isJson,verify:keepBodyBytes}));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,loopbackNames)=>{if(typeof portOrSocketPath==="string")return void 0;const derivation={bindAddress:bindAddress??"127.0.0.1",port:portOrSocketPath,issuer:options?.listen?.issuer,loopbackNames};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,loopbackNames}):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,loopbackNames){if(!this.deriveHostValidation)return;this.hostValidation=this.deriveHostValidation(portOrSocketPath,bindAddress,loopbackNames)??this.hostValidation}loopbackNames(){return this.listeningLoopbackNames}registerRoute(method,path7,handler){this.router[method.toLowerCase()](path7,this.enhancedHandler(handler))}registerMiddleware(entryPath,handler){this.router.use(entryPath,this.enhancedHandler(handler))}enhancedHandler(handler){return(req,res,next)=>{Promise.resolve(handler(req,res,next)).catch(error=>next(error||new Error("Rejected promise")))}}prepare(){if(this.prepared)return;this.prepared=true;this.app.use("/",this.router);this.app.use(answerRequestError)}getHandler(){this.prepare();return this.app}createHttpServer(){const server=http.createServer(this.app);server.requestTimeout=this.requestTimeout;server.headersTimeout=this.headersTimeout;server.keepAliveTimeout=75e3;return server}async start(portOrSocketPath,bindAddress){this.prepare();const server=this.createHttpServer();this.httpServer=server;if(typeof portOrSocketPath==="string"){const ownerOnly=hasSocketFileMode();if(ownerOnly){await assertSafeSocketDirectory(portOrSocketPath);await clearStaleSocket(portOrSocketPath)}this.enableDerivedHostValidation(portOrSocketPath);this.deriveHostValidation=void 0;await new Promise((resolve5,reject)=>{server.on("error",reject);if(ownerOnly)listenOwnerOnly(server,portOrSocketPath,resolve5);else server.listen(portOrSocketPath,resolve5)});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";const{boundPort,boundAddress}=await new Promise((resolve5,reject)=>{server.on("error",reject);server.listen(portOrSocketPath,host,()=>{const bound=server.address();const port=typeof bound==="object"&&bound?bound.port:portOrSocketPath;const address=typeof bound==="object"&&bound?bound.address:host;this.listeningLoopbackNames=loopbackNamesOf(address,"pending");this.enableDerivedHostValidation(port,address,this.listeningLoopbackNames);resolve5({boundPort:port,boundAddress:address})})});const partner=await this.holdLoopbackPartner(server,boundAddress,boundPort);if(this.httpServer!==server)return;this.listeningLoopbackNames=loopbackNamesOf(boundAddress,partner);this.enableDerivedHostValidation(boundPort,boundAddress,this.listeningLoopbackNames);this.deriveHostValidation=void 0;console.log(`MCP HTTP (Express) on ${host}:${boundPort}`)}}async holdLoopbackPartner(owner,boundAddress,port){const partnerAddress=loopbackPartnerOf(boundAddress);if(!partnerAddress)return"absent";const partner=this.createHttpServer();const failure=await new Promise(resolve5=>{partner.on("error",error=>resolve5(error.code??"an error"));partner.listen(port,partnerAddress,()=>resolve5(void 0))});if(failure===void 0){if(this.httpServer===owner)this.partnerServer=partner;else await drainAndClose(partner,0);return"held"}if(NO_SUCH_ADDRESS.has(failure))return"absent";const[own]=loopbackNamesOf(boundAddress,"taken");const partnerUrl=`${partnerAddress}:${port}`;const elsewhere=failure==="EADDRINUSE"?`another process listens on ${partnerUrl}, so a browser that opens http://localhost:${port} may reach it instead`:`${partnerUrl} could not be held (${failure}), so a browser that opens http://localhost:${port} may reach another process there`;console.warn(`[frontmcp] ${elsewhere}: this server answers http://${own}:${port} only.`);return"taken"}async stop(drainMs=SERVER_DRAIN_MS){const servers=[this.httpServer,this.partnerServer].filter(server=>!!server);this.httpServer=void 0;this.partnerServer=void 0;this.listeningLoopbackNames=void 0;await Promise.all(servers.map(server=>drainAndClose(server,drainMs)))}};NO_SUCH_ADDRESS=new Set(["EADDRNOTAVAIL","EAFNOSUPPORT"])}});function isUnder(candidate,root){const relative2=path2.relative(root,candidate);return relative2===""||relative2!==".."&&!relative2.startsWith(`..${path2.sep}`)&&!path2.isAbsolute(relative2)}async function resolvesOutside(target,realRoot){const real=await(0,import_utils215.realpath)(target).catch(()=>void 0);if(real===void 0)return false;if(!isUnder(real,realRoot))return true;const isDirectory=await(0,import_utils215.stat)(real).then(stats=>stats.isDirectory(),()=>false);if(!isDirectory)return false;const index=await(0,import_utils215.realpath)(path2.join(real,"index.html")).catch(()=>void 0);return index!==void 0&&!isUnder(index,realRoot)}var http2,path2,import_express3,import_utils215,SERVER_DRAIN_MS2,DEFAULT_USER_CONTENT_CSP,UserContentListener;var init_user_content_listener=__esm({"libs/sdk/src/server/adapters/user-content.listener.ts"(){"use strict";http2=__toESM(require("node:http"));path2=__toESM(require("node:path"));import_express3=__toESM(require("express"));import_utils215=require("@frontmcp/utils");init_transport_errors();init_csp_middleware();init_host_validation_middleware();init_resolve_allowed_hosts();init_unix_socket_guard();SERVER_DRAIN_MS2=5e3;DEFAULT_USER_CONTENT_CSP="sandbox allow-scripts";UserContentListener=class{constructor(options,refuseClient){this.options=options;this.refuseClient=refuseClient;if(options.allowedHosts?.length&&!options.socketPath){this.hostValidation=createHostValidationMiddleware({enabled:true,allowedHosts:options.allowedHosts})}}options;refuseClient;httpServer;hostValidation;async start(mainListener,bindAddress="127.0.0.1"){const{socketPath}=this.options;const port=this.options.port??0;if(socketPath?socketPath===mainListener:port!==0&&port===mainListener){throw new UserContentConfigurationError(`it needs a port or socketPath of its own, not the MCP listener's (${mainListener})`)}const root=path2.resolve(this.options.root);const isDirectory=await(0,import_utils215.stat)(root).then(stats=>stats.isDirectory(),()=>false);if(!isDirectory)throw new UserContentConfigurationError(`root ${root} is not a directory`);const realRoot=await(0,import_utils215.realpath)(root);const server=http2.createServer(this.createApp(root,realRoot,this.responseHeaders()));this.httpServer=server;server.keepAliveTimeout=75e3;if(socketPath){const ownerOnly=hasSocketFileMode();if(ownerOnly){await assertSafeSocketDirectory(socketPath);await clearStaleSocket(socketPath)}await new Promise((resolve5,reject)=>{server.on("error",reject);if(ownerOnly)listenOwnerOnly(server,socketPath,resolve5);else server.listen(socketPath,resolve5)});if(ownerOnly){try{await enforceOwnerOnly(socketPath)}catch(error){await this.stop(0);throw error}}console.log(`User content on unix://${socketPath} (files from ${root})`);return}await new Promise((resolve5,reject)=>{server.on("error",reject);server.listen(port,bindAddress,()=>{const bound=server.address();const boundPort=typeof bound==="object"&&bound?bound.port:port;const boundAddress=typeof bound==="object"&&bound?bound.address:bindAddress;this.hostValidation??=this.derivedHostValidation(boundAddress,boundPort);console.log(`User content on ${bindAddress}:${boundPort} (files from ${root})`);resolve5()})})}address(){return this.httpServer?.address()}async stop(drainMs=SERVER_DRAIN_MS2){const server=this.httpServer;if(!server)return;this.httpServer=void 0;const closed=new Promise(resolve5=>server.close(()=>resolve5()));server.closeIdleConnections();const forceClose=setTimeout(()=>server.closeAllConnections(),drainMs);try{await closed}finally{clearTimeout(forceClose)}}createApp(root,realRoot,headers){const app=(0,import_express3.default)();app.disable("x-powered-by");app.use((_req,res,next)=>{for(const[name60,value]of Object.entries(headers))res.setHeader(name60,value);next()});app.use(((req,res,next)=>{const validate=this.hostValidation;if(!validate)return next();return validate(req,res,next)}));app.use(((req,res,next)=>{const refuse=this.refuseClient;if(!refuse)return next();refuse(req,res).then(refused2=>refused2?void 0:next(),next)}));app.use(this.confinedToRoot(root,realRoot));app.use(import_express3.default.static(root,{dotfiles:"ignore",fallthrough:true}));app.use((_req,res)=>{res.status(404).type("text/plain").send("Not Found")});app.use((_error,_req,res,_next)=>{res.status(500).type("text/plain").send("Internal Server Error")});return app}confinedToRoot(root,realRoot){const rootPrefix=root.endsWith(path2.sep)?root:`${root}${path2.sep}`;return(req,res,next)=>{if(req.method!=="GET"&&req.method!=="HEAD")return next();let pathname;try{pathname=decodeURIComponent(req.path)}catch{return next()}const target=path2.resolve(root,`.${pathname}`);if(pathname.includes("\0")||target!==root&&!target.startsWith(rootPrefix))return next();resolvesOutside(target,realRoot).then(outside=>outside?res.status(404).type("text/plain").send("Not Found"):next(),next)}}derivedHostValidation(bindAddress,port){const derivation={bindAddress,port};if(!shouldEnforceDerivedHosts(derivation)){console.warn(`[frontmcp] http.userContent is not checking the Host header: it binds a routable address (${bindAddress}) and no allowed hosts are configured. Set http.userContent.allowedHosts to the content origin hostname(s).`);return void 0}return createHostValidationMiddleware({enabled:true,allowedHosts:deriveAllowedHosts(derivation)})}responseHeaders(){const headers={"X-Content-Type-Options":"nosniff",...this.options.headers};const csp=this.options.csp;if(csp){const directives=Object.fromEntries(Object.entries(csp.directives).map(([name60,value2])=>[name60,Array.isArray(value2)?value2.join(" "):value2]));const reportOnly=csp.reportOnly??false;const value=buildCspHeaderValue({enabled:true,directives,reportUri:csp.reportUri,reportOnly});if(value)headers[getCspHeaderName(reportOnly)]=value}const enforcesOwnPolicy=Object.keys(headers).some(name60=>name60.toLowerCase()==="content-security-policy");if(csp!==false&&!enforcesOwnPolicy)headers["Content-Security-Policy"]=DEFAULT_USER_CONTENT_CSP;for(const[name60,value]of Object.entries(headers)){try{http2.validateHeaderName(name60);http2.validateHeaderValue(name60,value)}catch(error){throw new UserContentConfigurationError(`header "${name60}" cannot be sent: ${error.message}`)}}return headers}}}});var node_express_host_exports={};__export(node_express_host_exports,{DEFAULT_EXPRESS_BODY_LIMIT:()=>DEFAULT_EXPRESS_BODY_LIMIT,ExpressHostAdapter:()=>ExpressHostAdapter,UserContentListener:()=>UserContentListener});var init_node_express_host=__esm({"libs/sdk/src/server/adapters/polyfills/node-express-host.ts"(){"use strict";init_express_host_adapter();init_user_content_listener()}});var server_instance_exports={};__export(server_instance_exports,{FrontMcpServerInstance:()=>FrontMcpServerInstance});var import_utils216,DEFAULT_CORS,FrontMcpServerInstance;var init_server_instance=__esm({"libs/sdk/src/server/server.instance.ts"(){"use strict";import_utils216=require("@frontmcp/utils");init_common();init_path_utils();init_health2();init_mcp_registry_utils();init_metrics2();init_custom_routes_helper();init_cors_env();init_resolve_allowed_hosts();init_security_audit();init_server_validation();DEFAULT_CORS=void 0;FrontMcpServerInstance=class extends FrontMcpServer{config;host;healthRouteRegistered=false;_healthService;_healthConfig;metricsRouteRegistered=false;_metricsService;_metricsConfig;userContent;checkClientIp;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}:{},...this.config.headersTimeout!==void 0?{headersTimeout:this.config.headersTimeout}:{},...this.config.requestTimeout!==void 0?{requestTimeout:this.config.requestTimeout}:{}})}}registerMiddleware(entryPath,handler){return this.host.registerMiddleware(entryPath,handler)}registerRoute(method,path7,handler){return this.host.registerRoute(method,path7,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}setClientIpCheck(checkClientIp){this.checkClientIp=checkClientIp}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){const check=this.checkClientIp;const routes=check?{registerRoute:(method,path7,handler)=>this.registerRoute(method,path7,wrapWithIpFilter(handler,check))}:this;registerMetricsRoutes(routes,this._metricsService,this._metricsConfig)}}this.host.prepare()}getHandler(){return this.host.getHandler()}async start(){this.prepare();const deploymentMode=(0,import_utils216.getRuntimeContext)().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},(0,import_utils216.isProduction)());logSecurityFindings(findings,console);const mainListener=this.config.socketPath??this.config.port;await this.host.start(mainListener,bindAddress);if(this.config.userContent){const{UserContentListener:UserContentListener2}=(init_node_express_host(),__toCommonJS(node_express_host_exports));this.userContent=new UserContentListener2(this.config.userContent,this.refuseClient());await this.userContent.start(mainListener,bindAddress);this.warnOfSharedContentHosts(bindAddress)}}loopbackNames(){return this.host.loopbackNames?.()}warnOfSharedContentHosts(bindAddress){const contentHosts=this.config.userContent?.allowedHosts;if(!contentHosts?.length||this.config.userContent?.socketPath)return;const mcpHosts=this.mcpListenerHosts(bindAddress);const shared=mcpHosts==="any"?sharedHostnames(contentHosts,contentHosts):sharedHostnames(contentHosts,mcpHosts);if(shared.length===0)return;const answers=mcpHosts==="any"?"which the MCP listener answers to as well, since it checks no Host (set http.security.dnsRebindingProtection.allowedHosts)":"which the MCP listener answers to as well";console.warn(`[frontmcp] http.userContent.allowedHosts names ${shared.join(", ")}, ${answers}. Browsers share cookies between the ports of a host: serve user content from a registrable domain of its own in production, and keep a sandbox directive in http.userContent.csp.`)}mcpListenerHosts(bindAddress){if(this.config.socketPath)return[];const protection=this.config.security?.dnsRebindingProtection;if(protection?.enabled===false)return"any";const explicit=protection?.allowedHosts??allowedHostsFromEnv();if(explicit?.length)return explicit;return isLoopbackAddress(bindAddress)?deriveAllowedHosts({bindAddress,port:this.config.port}):"any"}refuseClient(){const check=this.checkClientIp;if(!check)return void 0;return async(req,res)=>{const rejection=await check(req,res);if(rejection)await writeHttpResponse(res,rejection);return rejection!==void 0}}async stop(){const results=await Promise.allSettled([(async()=>this.host.stop())(),(async()=>this.userContent?.stop())()]);const failure=results.find(result=>result.status==="rejected");if(failure)throw failure.reason}}}});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 import_di55,frontMcpConfig,defaultHttpOptions,frontMcpServer,noopServer;var init_front_mcp_providers=__esm({"libs/sdk/src/front-mcp/front-mcp.providers.ts"(){"use strict";import_di55=require("@frontmcp/di");init_common();init_context();init_noop_server();init_front_mcp_tokens2();frontMcpConfig={with:metadata=>({name:"frontmcp:config",provide:FrontMcpConfig,scope:import_di55.ProviderScope.GLOBAL,useValue:metadata})};defaultHttpOptions=()=>({port:defaultHttpPort(),entryPath:"/mcp"});frontMcpServer=AsyncProvider({name:"frontmcp:server",scope:import_di55.ProviderScope.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:import_di55.ProviderScope.GLOBAL,useValue:new NoopFrontMcpServer}}});function checkSessionSecret(config,entryFallback){if(!(0,import_utils217.isProduction)()||(0,import_auth85.isSessionSecretConfigured)())return false;if((config.transport?.defaultProtocolVersion??entryFallback)==="legacy"){throw new import_auth85.SessionSecretRequiredError("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 import_auth85,import_utils217,MISSING_SESSION_SECRET_WARNING,missingSessionSecretProbe;var init_session_secret_check=__esm({"libs/sdk/src/front-mcp/session-secret.check.ts"(){"use strict";import_auth85=require("@frontmcp/auth");import_utils217=require("@frontmcp/utils");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})}}});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=(0,import_utils218.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 import_utils218,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";import_utils218=require("@frontmcp/utils");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});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 import_utils219,_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";import_utils219=require("@frontmcp/utils");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 filePath2=getPath().join(this.logDir,`${this.appName}-${ts}.log`);this.fd=getFs().openSync(filePath2,"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?` [${(0,import_utils219.escapeControlCharacters)(rec.prefix)}]`:"";const message=(0,import_utils219.escapeControlCharacters)(stripAnsi(String(rec.message)));const line=`[${ts}] ${level}${prefix} ${message}
|
|
492
492
|
`;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,{appsForRun:()=>appsForRun,runDetachedJob:()=>runDetachedJob});async function runDetachedJob(config,runId,boot=bootRunner){delete process.env[RUN_JOB_ENV_VAR];let host;try{host=await boot(await configForRun(config,runId))}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 openRunStore(config){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});const{store:stateStore}=await createJobStateStore({redis:store?.redis,sqlite:store?.sqlite,keyPrefix:store?.keyPrefix??"mcp:jobs:"});return stateStore}async function configForRun(config,runId){const jobs=config.jobs;if(jobs?.detached?.boot!=="app"||!Array.isArray(config.apps))return config;let record;try{const store=await openRunStore(config);try{record=await store.getRun(runId)}finally{await store.dispose()}}catch{return config}const apps=record?appsForRun(config.apps,record):void 0;return apps?{...config,apps}:config}function appsForRun(apps,run){const declared=apps.map(app=>{if(!(0,import_di56.isClass)(app))return{app,jobs:new Set,workflows:new Map};const metadata=collectAppMetadata(app);const jobs=new Set((metadata.jobs??[]).map(job=>normalizeJob(job).metadata.name));const workflows=new Map((metadata.workflows??[]).map(workflow=>{const{metadata:flow}=normalizeWorkflow(workflow);return[flow.name,flow.steps.map(step=>step.jobName)]}));return{app,jobs,workflows}});const needed=new Set;const take=found=>{if(found)needed.add(found.app);return found!==void 0};const{workflowName}=run;if(workflowName!==void 0){const owner=declared.find(({workflows})=>workflows.has(workflowName));if(!take(owner))return void 0;for(const jobName of owner?.workflows.get(workflowName)??[]){if(!take(declared.find(({jobs})=>jobs.has(jobName))))return void 0}}else if(!take(declared.find(({jobs})=>jobs.has(run.jobName)))){return void 0}return apps.filter(app=>needed.has(app))}async function reportBootFailure(config,runId,cause){try{const stateStore=await openRunStore(config);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);console.error(`[frontmcp] ${error.getInternalMessage()}`);const failed={state:"failed",error:{name:error.name,message:error.message},completedAt:Date.now()};if(stateStore.updateUnfinishedRun)await stateStore.updateUnfinishedRun(runId,failed);else await stateStore.updateRun(runId,failed)}finally{await stateStore.dispose()}}catch{}}var import_di56;var init_detached_job_worker=__esm({"libs/sdk/src/job/runner/detached-job.worker.ts"(){"use strict";import_di56=require("@frontmcp/di");init_app_utils();init_common();init_resolve();init_errors();init_detached_job_flag();init_direct_only_flag();init_workflow_utils();init_job_attempt();init_job_run_access();init_job_scope_helper();init_job_utils();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"?encoder13.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 encoder13.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 encoder13;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();encoder13=new TextEncoder}});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(resolve5=>resolveRendered=resolve5);const response=new RelayServerResponse({head(status,headers){const webHeaders=new Headers;for(const[name60,value]of Object.entries(headers)){for(const item of Array.isArray(value)?value:[value])webHeaders.append(name60,item)}resolveRendered(new Response(BODYLESS_STATUSES.has(status)?null:body,{status,headers:webHeaders}))},data(chunk){const data=decodeRelayChunk(chunk);controller?.enqueue(typeof data==="string"?encoder14.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(resolve5=>{void rendered.then(resolve5);const passOn=()=>resolve5(void 0);(0,import_utils220.runRequestExclusive)(async()=>match.route.handler(request2,response.asServerResponse(),passOn)).catch(error=>{if(!response.headersSent){resolve5(failureResponse(error));return}logger.error(`HTTP route ${match.route.method} ${match.route.path} failed after its response started`,error);failBody(error)})})}var import_utils220,encoder14,BODYLESS_STATUSES;var init_web_http_route=__esm({"libs/sdk/src/transport/web-http-route.ts"(){"use strict";import_utils220=require("@frontmcp/utils");init_flow_http_path();init_flow_error_output();init_relay_http();init_web_response_renderer();encoder14=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});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 urlOfHost(host){try{return new URL(`http://${host}`)}catch{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 rebindingOff=rebinding?.enabled===false;const configuredHostValidation=rebindingOff||!rebinding?.allowedHosts?.length&&rebinding?.allowedOrigins===void 0?void 0:compileHostValidation({allowedHosts:rebinding.allowedHosts,allowedOrigins:rebinding.allowedOrigins});const loopbackDefaultApplies=!rebindingOff&&!rebinding?.allowedHosts?.length;const corsOriginsForLoopback=corsAllowedOrigins(cors2&&{origin:cors2.origin});const loopbackValidationByPort=new Map;const loopbackHostValidation=url=>{let compiled=loopbackValidationByPort.get(url.port);if(!compiled){const port=url.port?Number(url.port):void 0;compiled=compileHostValidation({allowedHosts:deriveAllowedHosts({bindAddress:"127.0.0.1",port}),allowedOrigins:rebinding?.allowedOrigins??(corsOriginsForLoopback?deriveAllowedOrigins({port,extraOrigins:corsOriginsForLoopback}):void 0)});loopbackValidationByPort.set(url.port,compiled)}return compiled};const hostValidationFor=(request2,url,ctx)=>{if(loopbackDefaultApplies&&isLoopbackAddress(resolvePeerAddress(request2,ctx))){return loopbackHostValidation(url)}return configuredHostValidation};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);const hostValidation=hostValidationFor(request2,url,ctx);if(hostValidation){const hostHeader=request2.headers.get("host");const rejection=validateHostHeaders({host:url.host,forwardedHost:request2.headers.get("x-forwarded-host")??void 0,origin:request2.headers.get("origin")??void 0},hostValidation)??(hostHeader&&hostHeader!==url.host?validateHostHeaders({host:hostHeader},hostValidationFor(request2,urlOfHost(hostHeader)??url,ctx)??hostValidation):void 0);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 refused2=await ipFilterRejectionWeb(scope,request2,ctx,env);if(refused2)return withCors(refused2,request2);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 isUnder2=(path7,basePath)=>basePath!==""&&(path7===basePath||path7.startsWith(`${basePath}/`));const metricsConfig=options.metrics?.config;if(metricsConfig?.enabled===true){const metricsEndpoint=normalizeEntryPrefix(metricsPath(metricsConfig));if(handlers.some(({scope,basePath})=>scope!==primary&&isUnder2(metricsEndpoint,basePath))){throw new MetricsPathConflictError(metricsPath(metricsConfig))}}return(request2,ctx,env)=>{const url=new URL(request2.url);const path7=scopePathOf(url.pathname);const route=inScopeOrder.find(({scope})=>claimedByHttpRoute(scope,request2,url))??handlers.find(({basePath})=>isUnder2(path7,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(0,import_utils221.runRequestExclusive)(()=>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(0,import_utils221.runRequestExclusive)(()=>scope.runFlow(flowName,{request:serverRequest,response:{}}))}catch(error){output=flowErrorToHttpOutput(error)}return output?renderHttpOutputToWebResponse(output):void 0}async function ipFilterRejectionWeb(scope,request2,ctx,env){const serverRequest=await toServerRequest(request2,new URL(request2.url),ctx,void 0,env);let output;try{output=await(0,import_utils221.runRequestExclusive)(()=>scope.runFlow("http:ip-filter",{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,name60)=>headers[name60]=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 import_utils221,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";import_utils221=require("@frontmcp/utils");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_resolve_allowed_hosts();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((resolve5,reject)=>{send.call(process,message,err=>err?reject(err):resolve5())})}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});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(!(0,import_protocol84.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?.[import_protocol84.MCP_20260728_META.protocolVersion];return typeof declared==="string"?declared:import_protocol84.PROTOCOL_2026_07_28}var import_protocol84,LISTEN_METHOD,EVENT_SEPARATOR,EVENT_DATA_FIELD,StdioRevisionRouter;var init_stdio_revision_router=__esm({"libs/sdk/src/transport/stdio-revision-router.ts"(){"use strict";import_protocol84=require("@frontmcp/protocol");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"&&(0,import_protocol84.isJSONRPCNotification)(message))return;try{await this.inner.send(message,options)}finally{const repliedTo=(0,import_protocol84.isJSONRPCResultResponse)(message)||(0,import_protocol84.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(resolve5=>{const done=()=>{clearTimeout(timer);this.idleWaiters.delete(done);resolve5()};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((0,import_protocol84.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(((0,import_protocol84.isJSONRPCRequest)(message)||(0,import_protocol84.isJSONRPCNotification)(message))&&this.servesModern(message)){if(servesClaudeCodeChannels(this.options.scope)){if((0,import_protocol84.isJSONRPCRequest)(message))void this.declineModern(message);return}if(this.era==="unknown")this.era="modern";void this.serveModern(message);return}if((0,import_protocol84.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=(0,import_protocol84.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=(0,import_protocol84.isJSONRPCResultResponse)(body)||(0,import_protocol84.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)}}}});function headersOf(init){const headers={};new Headers(init?.headers).forEach((value,name60)=>{headers[name60]=value});return headers}function nodeHttpFetch(target,refuseSocket){return(input,init)=>new Promise((resolve5,reject)=>{const url=new URL(input instanceof Request?input.url:String(input));const request2=http3.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[name60,value]of Object.entries(response.headers)){if(value!==void 0)headers.set(name60,Array.isArray(value)?value.join(", "):value)}const status=response.statusCode??502;if(status===204||status===304||response.headers["content-length"]==="0"){response.resume();resolve5(new Response(null,{status,headers}));return}resolve5(new Response(import_node_stream.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 http3,import_node_stream;var init_unix_socket_fetch=__esm({"libs/sdk/src/shared/unix-socket-fetch.ts"(){"use strict";http3=__toESM(require("node:http"));import_node_stream=require("node:stream")}});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(0,import_utils222.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=(0,import_auth86.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"}}const exiting=response.status===503&&response.headers.get(SHARED_STATE_HEADER)===SHARED_EXITING;if(!response.ok&&!exiting){await response.body?.cancel();return{outcome:"refused"}}const answer=await readAnswer(response);const{proof,version}=typeof answer==="object"&&answer!==null?answer:{};const proven=isSharedVersion(version)&&(0,import_auth86.verifySharedServerIdentity)(proofKey,{endpoint:endpoint.id,nonce,version},proof);if(exiting)return{outcome:"exiting",proven};return proven?{outcome:"verified",version}:{outcome:"refused"}}function fetchAfterIdentity(endpoint,proofKey){const{hostname,port}=new URL(endpoint.baseUrl);return async(input,init)=>{const agent=new http4.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 http4,import_auth86,import_utils222,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";http4=__toESM(require("node:http"));import_auth86=require("@frontmcp/auth");import_utils222=require("@frontmcp/utils");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}});function checksFileModes(){return process.platform!=="win32"}function isMissing(error){return error?.code==="ENOENT"}function sharedServerFiles(key){const home=(0,import_utils223.getEnv)("FRONTMCP_HOME")||path3.join(os.homedir(),".frontmcp");const directory=path3.join(path3.resolve(home),"shared",key);return{directory,recordFile:path3.join(directory,"server.json"),socketPath:path3.join(directory,"server.sock"),lockFile:path3.join(directory,"start-lock.sqlite")}}function socketPathFits(socketPath){return new TextEncoder().encode(socketPath).length<=MAX_SOCKET_PATH_BYTES}function assertSocketPathFits(files){if(socketPathFits(files.socketPath))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(0,import_utils223.mkdir)(files.directory,{recursive:true,mode:OWNER_ONLY_DIRECTORY3});if(!checksFileModes())return;for(const directory of new Set([files.directory,await(0,import_utils223.realpath)(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(0,import_utils223.unlink)(temporary).catch(error=>{if(!isMissing(error))throw error});await(0,import_utils223.writeFile)(temporary,JSON.stringify(record),{mode:OWNER_ONLY_FILE3,flag:"wx"});await(0,import_utils223.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(0,import_utils223.lstat)(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(0,import_utils223.readFile)(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(0,import_utils223.unlink)(files.recordFile).catch(error=>{if(!isMissing(error))throw error})}var os,path3,import_lazy_zod155,import_utils223,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";os=__toESM(require("node:os"));path3=__toESM(require("node:path"));import_lazy_zod155=require("@frontmcp/lazy-zod");import_utils223=require("@frontmcp/utils");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=import_lazy_zod155.z.object({name:import_lazy_zod155.z.string(),transport:import_lazy_zod155.z.enum(["unix","http"]),port:import_lazy_zod155.z.number().int().min(1).max(65535).optional(),path:import_lazy_zod155.z.string().startsWith("/"),pid:import_lazy_zod155.z.number().int().positive(),secret:import_lazy_zod155.z.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()}});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}=(0,import_auth87.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";const older=`the shared server runs version ${version}, older than this session's ${options.version}`;if(!options.replaceOlder)return{embedded:`${older}, and replaceOlder is off`};if(options.startsOwnVersion===false){return{embedded:`${older}, and the entry that would replace it may run an older one, so it is left running`}}return"replace"}async function ensureSharedServer(options){const{key,budgetMs,pollMs=POLL_MS,mayStart=true}=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,replaceOlder:options.replaceOlder&&mayStart});if(found&&skew==="attach")return{server:found.server};if(typeof skew==="object")return skew;if(!mayStart){if(Date.now()>=deadline){return{embedded:`no server proved its identity within ${budgetMs} ms, and the session may not start one`}}await new Promise(resolve5=>setTimeout(resolve5,Math.min(pollMs,remaining())));continue}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(resolve5=>setTimeout(resolve5,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 identified=await identifySharedServer(drained.server.endpoint,drained.proofKey,timeoutMs);if(identified.outcome==="verified")return true;return identified.outcome==="exiting"&&(identified.proven||options.transport==="unix")}if(options.transport!=="unix")return false;const{outcome}=await identifySharedServer(unixEndpoint(options.files.socketPath),(0,import_utils224.randomBytes)(32),timeoutMs);return outcome==="exiting"}function withoutInspector(){const flags=process.execArgv.filter(flag=>!INSPECTOR_FLAG2.test(flag));const nodeOptions=process.env["NODE_OPTIONS"];if(!nodeOptions?.includes("--inspect"))return{flags,env:{...process.env}};const kept=nodeOptionsArguments(nodeOptions).filter(option=>!INSPECTOR_FLAG2.test(option));return{flags,env:{...process.env,NODE_OPTIONS:kept.map(nodeOptionsArgument).join(" ")}}}function nodeOptionsArguments(nodeOptions){const options=[];let current;let quoted=false;for(let index=0;index<nodeOptions.length;index++){let character=nodeOptions[index];if(character==="\\"&"ed&&index+1<nodeOptions.length)character=nodeOptions[++index];else if(character===" "&&!quoted){if(current!==void 0)options.push(current);current=void 0;continue}else if(character==='"'){quoted=!quoted;current??="";continue}current=(current??"")+character}if(current!==void 0)options.push(current);return options}function nodeOptionsArgument(option){return/[ "]/.test(option)||option===""?`"${option.replace(/[\\"]/g,"\\$&")}"`:option}function spawnSharedServer(key,startLockHolder,entry){const spawned={exitReason:void 0};const{flags,env}=withoutInspector();const args=entry?[...flags,entry]:[...flags,...process.argv.slice(1)];const child=(0,import_utils224.getSpawnFn)()(process.execPath,args,{cwd:entry?path4.dirname(entry):process.cwd(),detached:true,stdio:"ignore",windowsHide:true,env:{...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 path4,import_auth87,import_utils224,SHARED_SERVE_ENV,SHARED_START_LOCK_ENV,POLL_MS,INSPECTOR_FLAG2;var init_ensure_shared_server=__esm({"libs/sdk/src/shared/ensure-shared-server.ts"(){"use strict";path4=__toESM(require("node:path"));import_auth87=require("@frontmcp/auth");import_utils224=require("@frontmcp/utils");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;INSPECTOR_FLAG2=/^--inspect(-brk|-wait)?(=|$)/}});function milliseconds(max,message){return import_lazy_zod156.z.number({message}).int(message).min(1,message).max(max,message)}function isDriveRelative(file){return/^[\\/]$/.test(path5.win32.parse(file).root)}function validateSharedServerOptions(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{transport=platform==="win32"?"http":"unix",checkout,rereadKey,entries}=result.data;const key=result.data.key;if(transport==="unix"&&platform==="win32"){throw new InvalidSharedServerOptionsError("transport: a Unix socket can't be kept owner-only on Windows; use transport 'http'")}if(platform==="win32"){const driveRelative=[...rereadKey&&isDriveRelative(rereadKey.file)?[`rereadKey.file: ${REREAD_ABSOLUTE}, nor to its drive`]:[],...Object.entries(entries??{}).filter(([,file])=>isDriveRelative(file)).map(([name60])=>`entries.${name60}: ${ENTRY_ABSOLUTE}, nor to its drive`)];if(driveRelative.length>0)throw new InvalidSharedServerOptionsError(driveRelative.join("; "))}if(typeof key==="string"&&rereadKey){throw new InvalidSharedServerOptionsError(`rereadKey: rereadKey ${NEEDS_KEY_FUNCTION}`)}if(typeof key==="string"&&entries){throw new InvalidSharedServerOptionsError(`entries: entries ${NEEDS_KEY_FUNCTION}`)}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:path5.resolve(checkout??(entry?path5.dirname(entry):process.cwd())),spare:result.data.spare??false,...rereadKey?{rereadKey:{file:path5.resolve(rereadKey.file),intervalMs:rereadKey.intervalMs??DEFAULT_REREAD_INTERVAL_MS}}:{},entries:Object.freeze(Object.fromEntries(Object.entries(entries??{}).map(([name60,file])=>[name60,path5.resolve(file)])))}}function isSharedServerKey(value){return typeof value==="string"&&KEY_PATTERN.test(value)&&!WINDOWS_DEVICE_PATTERN.test(value)}async function readSharedServerKey(source){let answer;try{answer=await source()}catch(error){return{error:`the key function failed (${error instanceof Error?error.message:describeValue3(error)})`}}if(isSharedServerKey(answer))return{key:answer};return{error:`the key function answered ${describeValue3(answer)}, and ${KEY_FORMAT2}`}}function describeValue3(value){if(typeof value==="string")return`"${value.slice(0,80)}"`;if(value===null||["undefined","number","boolean","bigint","symbol"].includes(typeof value))return String(value);if(Array.isArray(value))return`an array of ${value.length} item(s)`;if(typeof value==="object")return`an object with keys ${Object.keys(value).slice(0,5).join(", ")||"(none)"}`;return`a value of type ${typeof value}`}var path5,import_lazy_zod156,DEFAULT_ATTACH_BUDGET_MS,MAX_ATTACH_BUDGET_MS,DEFAULT_IDLE_TIMEOUT_MS2,MAX_IDLE_TIMEOUT_MS,DEFAULT_REREAD_INTERVAL_MS,MAX_REREAD_INTERVAL_MS,KEY_PATTERN,WINDOWS_DEVICE_PATTERN,KEY_FORMAT2,WINDOWS_DEVICE,KEY_TYPE,ATTACH_BUDGET,IDLE_TIMEOUT,CHECKOUT,SPARE,REREAD,ENTRY,NEEDS_KEY_FUNCTION,NOT_RELATIVE,REREAD_ABSOLUTE,ENTRY_ABSOLUTE,filePath,absoluteFilePath,keySchema,sharedServerOptionsSchema;var init_shared_server_options=__esm({"libs/sdk/src/shared/shared-server.options.ts"(){"use strict";path5=__toESM(require("node:path"));import_lazy_zod156=require("@frontmcp/lazy-zod");init_shared_server_errors();DEFAULT_ATTACH_BUDGET_MS=15e3;MAX_ATTACH_BUDGET_MS=6e5;DEFAULT_IDLE_TIMEOUT_MS2=6e5;MAX_IDLE_TIMEOUT_MS=6048e5;DEFAULT_REREAD_INTERVAL_MS=1e3;MAX_REREAD_INTERVAL_MS=6e5;KEY_PATTERN=/^[a-z0-9]([a-z0-9._-]{0,62}[a-z0-9])?$/;WINDOWS_DEVICE_PATTERN=/^(con|prn|aux|nul|com\d|lpt\d)(\.|$)/;KEY_FORMAT2='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)";KEY_TYPE="key is required: a string, or a function that answers one";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";SPARE="spare must be true or false";REREAD=`rereadKey must be { file, intervalMs? }: the path of a file, and 1 to ${MAX_REREAD_INTERVAL_MS} ms`;ENTRY="entries must map keys to the paths of entry files";NEEDS_KEY_FUNCTION="needs a function key, which the session reads again";NOT_RELATIVE="not one relative to the folder the MCP client starts the session in";REREAD_ABSOLUTE=`rereadKey.file must be an absolute path, ${NOT_RELATIVE}`;ENTRY_ABSOLUTE=`entries must map keys to absolute paths, ${NOT_RELATIVE}`;filePath=message=>import_lazy_zod156.z.string({message}).min(1,message).refine(value=>!value.includes("\0"),message);absoluteFilePath=(message,relative2)=>filePath(message).refine(value=>path5.isAbsolute(value),relative2);keySchema=import_lazy_zod156.z.string({message:KEY_TYPE}).regex(KEY_PATTERN,KEY_FORMAT2).refine(key=>!WINDOWS_DEVICE_PATTERN.test(key),WINDOWS_DEVICE);sharedServerOptionsSchema=import_lazy_zod156.z.object({key:import_lazy_zod156.z.unknown().optional(),transport:import_lazy_zod156.z.enum(["unix","http"],{message:"transport must be 'unix' or 'http'"}).optional(),attachBudgetMs:milliseconds(MAX_ATTACH_BUDGET_MS,ATTACH_BUDGET).optional(),replaceOlder:import_lazy_zod156.z.boolean({message:"replaceOlder must be true or false"}).optional(),idleTimeoutMs:import_lazy_zod156.z.union([milliseconds(MAX_IDLE_TIMEOUT_MS,IDLE_TIMEOUT),import_lazy_zod156.z.literal(false)],{message:IDLE_TIMEOUT}).optional(),checkout:import_lazy_zod156.z.union([filePath(CHECKOUT),import_lazy_zod156.z.literal(false)],{message:CHECKOUT}).optional(),spare:import_lazy_zod156.z.boolean({message:SPARE}).optional(),rereadKey:import_lazy_zod156.z.object({file:absoluteFilePath(REREAD,REREAD_ABSOLUTE),intervalMs:milliseconds(MAX_REREAD_INTERVAL_MS,REREAD).optional()},{message:REREAD}).strict().optional(),entries:import_lazy_zod156.z.record(keySchema,absoluteFilePath(ENTRY,ENTRY_ABSOLUTE),{message:ENTRY}).optional()}).strict().superRefine(({key},context)=>{if(typeof key==="function")return;if(typeof key!=="string"){context.addIssue({code:"custom",path:["key"],message:KEY_TYPE});return}for(const issue of keySchema.safeParse(key).error?.issues??[]){context.addIssue({code:"custom",path:["key"],message:issue.message})}})}});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(0,import_utils225.writeFile)(files.lockFile,"",{mode:OWNER_ONLY_FILE4,flag:"a"});return(0,import_utils225.createStorage)({type:"sqlite",sqlite:{path:files.lockFile},prefix:"frontmcp:shared:",fallback:"error"})}var import_utils225,DEFAULT_TTL_SECONDS,OWNER_ONLY_FILE4,SharedStartLock;var init_start_lock=__esm({"libs/sdk/src/shared/start-lock.ts"(){"use strict";import_utils225=require("@frontmcp/utils");DEFAULT_TTL_SECONDS=10;OWNER_ONLY_FILE4=384;SharedStartLock=class{constructor(storage,key,ttlSeconds=DEFAULT_TTL_SECONDS,holder=(0,import_utils225.randomUUID)()){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)}}}});async function keyFileSignature(file){try{const{size,mtimeMs}=await(0,import_utils226.stat)(file);return`${size}:${mtimeMs}`}catch{return"missing"}}function mayStartServerOf(options,key){return key===options.key||Object.hasOwn(options.entries,key)}function isResponse(frame4){return frame4.method===void 0&&frame4.id!==void 0}function stderrLogger(){const ignore=()=>void 0;const write=level=>(message,data)=>{process.stderr.write(`[frontmcp shared] ${level} ${message}${data?` ${JSON.stringify(data)}`:""}
|
|
493
493
|
`)};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")}}function spawnerOf(options,key){if(options.spawnServer)return startLockHolder=>options.spawnServer?.(startLockHolder,key);const entry=key===options.key?void 0:options.entries[key];return startLockHolder=>spawnSharedServer(key,startLockHolder,entry)}async function connect3(options,key,logger){const files=sharedServerFiles(key);if(options.transport==="unix")assertSocketPathFits(files);await prepareSharedDirectory(files);try{return await ensureSharedServer({key,transport:options.transport,files,logger,name:options.name,version:options.version,replaceOlder:options.replaceOlder,budgetMs:options.attachBudgetMs,mayStart:mayStartServerOf(options,key),startsOwnVersion:key===options.key,spawnServer:spawnerOf(options,key),openLock:async()=>{const storage=await openStartLockStorage(files);return{lock:new SharedStartLock(storage,key),close:()=>storage.disconnect()}}})}catch(error){if(error instanceof SharedServerStartError)return{embedded:error.message};throw error}}function attachSharedSession(options){const log=stderrLogger();let currentKey=options.key;const sending=new Map;let reaching;let keyWatch;let upstream;let embedded;let spare;let spareClosed;let stopping;let clientInitialize;let clientInitialized=false;let successorWatch;const resends=new WeakMap;const relayed=new Map;const leftServers=new WeakSet;let relayedCount=0;const framer=(0,import_utils226.createStdioFramer)({input:options.input,output:options.output,log,onFrame:frame4=>isResponse(frame4)?answerServer(frame4):fsm.enqueue(frame4)});const fsm=(0,import_utils226.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 sendTracked(current,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)}}async function relayFrom(server,frame4){if(frame4.method!==void 0&&frame4.id!==void 0&&frame4.id!==null){if(leftServers.has(server)){log.warn("dropped a request of a shared server the session left",{method:frame4.method});return}const id=`${RELAYED_ID_PREFIX}${++relayedCount}`;relayed.set(id,{server,id:frame4.id});return fsm.relayUpstream({...frame4,id})}if(frame4.method==="notifications/cancelled")return fsm.relayUpstream(cancelledAsRelayed(server,frame4));return fsm.relayUpstream(frame4)}function cancelledAsRelayed(server,frame4){const params=frame4.params;for(const[id,request2]of relayed){if(request2.server!==server||request2.id!==params?.requestId)continue;relayed.delete(id);return{...frame4,params:{...params,requestId:id}}}return frame4}async function answerServer(frame4){const id=typeof frame4.id==="string"?frame4.id:void 0;const asked=id===void 0?void 0:relayed.get(id);if(id===void 0||!asked){log.warn("dropped an answer to no request a shared server sent",{id:frame4.id});return}relayed.delete(id);try{await sendTracked(asked.server,{...frame4,id:asked.id})}catch(error){log.warn("an answer did not reach the shared server that asked",{error:messageOf6(error)})}}function forgetRequestsOf(server){for(const[id,request2]of relayed)if(request2.server===server)relayed.delete(id)}async function sendTracked(server,frame4){const sent=server.send(frame4);let inFlight=sending.get(server);if(!inFlight)sending.set(server,inFlight=new Set);inFlight.add(sent);try{await sent}finally{inFlight.delete(sent);if(inFlight.size===0&&sending.get(server)===inFlight)sending.delete(server)}}function lose(lost,error){if(upstream!==lost||stopping)return;upstream=void 0;endSuccessorWatch();lost.leaveSession();leftServers.add(lost);forgetRequestsOf(lost);log.warn("reaching the next shared server",{reason:error.message});fsm.onUpstreamLost(error.message);reaching=reach().catch(fail)}async function watchKey(){const{rereadKey,keySource}=options;if(!rereadKey||!keySource)return;let last=options.keySignature??await keyFileSignature(rereadKey.file);let checking=false;let again=false;const check=async()=>{if(checking){again=true;return}checking=true;try{do{again=false;await checkKey().catch(error=>log.warn("the key was not read again",{error:messageOf6(error)}))}while(again&&!stopping)}finally{checking=false}};keyWatch=setInterval(async()=>{if(stopping)return;const now=await keyFileSignature(rereadKey.file);if(now===last)return;last=now;await check()},rereadKey.intervalMs);keyWatch.unref();if(options.keySignature===void 0)await check()}async function checkKey(){if(!options.keySource)return;const read=await readSharedServerKey(options.keySource);if("error"in read){log.warn(`keeping the shared server key "${currentKey}": ${read.error}`);return}if(read.key!==currentKey)await moveTo(read.key)}async function moveTo(key){await attached.catch(()=>void 0);await reaching;const from=upstream;if(stopping||!from)return;const stay=reason=>log.warn(`staying on the shared server "${currentKey}": ${reason}`);let attachment;try{attachment=await connect3(options,key,log)}catch(error){stay(`the server of key "${key}" can't be reached (${messageOf6(error)})`);return}if("embedded"in attachment){stay(`the server of key "${key}" can't be reached (${attachment.embedded})`);return}const{url,token,fetch:send,pid}=attachment.server;const server={url,headers:{authorization:`Bearer ${token}`},fetch:send,pid};const left=embedded;let moved=false;const adopt=next=>{if(upstream!==from||stopping)return false;moved=true;upstream=next;embedded=void 0;currentKey=key;endSuccessorWatch();log.warn(`moved to the shared server "${key}"`);return true};try{await reach(async()=>server,adopt)}catch(error){stay(`the server of key "${key}" did not take the session (${messageOf6(error)})`);return}if(moved){void leave(from,left).catch(error=>log.warn("the server the session moved from did not let it go",{error:messageOf6(error)}))}}async function leave(server,ownServer){await Promise.allSettled([...sending.get(server)??[]]);sending.delete(server);forgetRequestsOf(server);await server.endSession();await server.close();await ownServer?.close()}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(currentKey))}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;let attachment;try{attachment=await connect3(options,currentKey,log)}catch(error){dropSpare();throw error}if(stopping){dropSpare();return void 0}if(!("server"in attachment)&¤tKey!==options.key){log.warn(`moving back to the shared server "${options.key}": the server of key "${currentKey}" can't be reached (${attachment.embedded})`);currentKey=options.key;attachment=await connect3(options,currentKey,log);if(stopping){dropSpare();return void 0}}if("server"in attachment){dropSpare();const{url,token,fetch:send,pid}=attachment.server;return{url,headers:{authorization:`Bearer ${token}`},fetch:send,pid}}log.warn(`running the shared server "${currentKey}" in this process: ${attachment.embedded}`);spare??=options.bootEmbedded(currentKey);const booted=await spare;if(stopping)return void 0;spare=void 0;embedded=await booted.start();return embedded}function dropSpare(){const booting=spare;if(!booting)return;spare=void 0;spareClosed=booting.then(booted=>booted.close().catch(error=>log.warn("the spare server did not shut down",{error:messageOf6(error)})),()=>void 0)}function caughtUp(replayed){return clientInitialize===replayed.frame&&(!replayed.frame||!clientInitialized||replayed.initialized)}async function replayHandshake(next,replayed){if(clientInitialize!==replayed.frame){replayed.frame=clientInitialize;replayed.initialized=clientInitialized;return replayed.frame?next.reinitialize(replayed.frame,replayed.initialized):void 0}replayed.initialized=true;await next.send({jsonrpc:"2.0",method:"notifications/initialized"});return void 0}function useUpstream(next){upstream=next;return true}async function reach(serverOf=serverToReach,adopt=useUpstream){for(let replays=0;;replays++){const server=await serverOf();if(!server||stopping){await embedded?.close();return}const next=(0,import_utils226.createHttpUpstream)({url:server.url,headers:server.headers,fetch:towardsServer(server.fetch),log,onFrame:frame4=>relayFrom(next,frame4),claudeCodeChannels:true,onNotificationStreamLost:()=>watchForSuccessor(next,server.pid)});let result;const replayed={initialized:false};try{while(!caughtUp(replayed))result=await replayHandshake(next,replayed)??result}catch(error){forgetRequestsOf(next);await next.close();if(error instanceof SharedServerLostError&&replays<MAX_RESENDS)continue;throw error}if(!adopt(next)){forgetRequestsOf(next);await next.close();return}if(clientInitialize){for(const notification of(0,import_utils226.listChangedNotifications)(result))await framer.write(notification)}fsm.onChildReady();return}}framer.start();fsm.onBootStart();if(options.spare){spare=options.bootEmbedded(currentKey);spare.catch(()=>void 0)}const attached=reach().catch(error=>{fail(error);throw error});attached.catch(()=>void 0);void watchKey();async function shutdown(){clearInterval(keyWatch);endSuccessorWatch();dropSpare();await fsm.stop();await upstream?.endSession();await upstream?.close();await embedded?.close();await spareClosed;framer.stop()}return{attached,stop:async()=>{stopping??=shutdown();await stopping}}}var import_utils226,BUFFER_SIZE,RELOAD_MARGIN_MS,MAX_RESENDS,NOT_SENT_CODES,SUCCESSOR_WATCH_MS,RELAYED_ID_PREFIX,SharedServerLostError;var init_shared_attach=__esm({"libs/sdk/src/shared/shared-attach.ts"(){"use strict";import_utils226=require("@frontmcp/utils");init_mcp_error();init_shared_server_errors();init_ensure_shared_server();init_shared_endpoint();init_shared_files();init_shared_server_options();init_start_lock();BUFFER_SIZE=16;RELOAD_MARGIN_MS=3e4;MAX_RESENDS=3;NOT_SENT_CODES=new Set(["ECONNREFUSED","ENOENT"]);SUCCESSOR_WATCH_MS=1e3;RELAYED_ID_PREFIX="frontmcp-shared:";SharedServerLostError=class extends InternalMcpError{constructor(reached,reason){super(`the shared server went away: ${reason}`,"SHARED_SERVER_LOST");this.reached=reached}reached}}});var import_auth88,import_utils227,BEARER,SharedServerIdentity;var init_shared_server_identity=__esm({"libs/sdk/src/shared/shared-server.identity.ts"(){"use strict";import_auth88=require("@frontmcp/auth");import_utils227=require("@frontmcp/utils");BEARER="Bearer ";SharedServerIdentity=class{constructor(keys,endpoint,version){this.endpoint=endpoint;this.version=version;this.#proofKey=keys.proofKey;this.#tokenDigest=(0,import_utils227.sha256)(keys.token)}endpoint;version;#proofKey;#tokenDigest;prove(nonce){const proof=(0,import_auth88.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(0,import_utils227.timingSafeEqual)((0,import_utils227.sha256)(authorization.slice(BEARER.length)),this.#tokenDigest)}}}});function exitingResponse(proof){return httpRespond.json({error:"the shared server is exiting",...proof},{status:503,headers:{"retry-after":"1",connection:"close",[SHARED_STATE_HEADER]:SHARED_EXITING}})}var Will2,RouteHook,HostRouteHook,SharedServerLifecycle;var init_shared_server_lifecycle=__esm({"libs/sdk/src/shared/shared-server.lifecycle.ts"(){"use strict";init_common();init_custom_routes_helper();init_shared_endpoint();({Will:Will2}=FlowHooksOf("http:request"));RouteHook=FlowHooksOf("http:route");HostRouteHook=FlowHooksOf("http:ip-filter");SharedServerLifecycle=class{#inFlight=0;#active=0;#streams=new Set;#routeHandlers=new WeakMap;#lastActivity=Date.now();#exitReason;#settledWaiters=new Set;#resolveExit=()=>void 0;exiting=new Promise(resolve5=>{this.#resolveExit=resolve5});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?.()}idleFor(now=Date.now()){return this.#active>0||this.#streams.size>0?0:now-this.#lastActivity}settled(timeoutMs){if(this.#inFlight===0)return Promise.resolve();return new Promise(resolve5=>{const done=()=>{clearTimeout(timer);this.#settledWaiters.delete(done);resolve5()};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.startRequest(response,true)}trackRouteRequest(run){this.refuseWhenExiting(run);const active=run.state.get("route")?.auth!=="public";this.startRequest(run.rawInput.response,active);this.#inFlight++;this.#routeHandlers.set(run,active?this.holdActivity():()=>void 0)}finishRouteHandler(run){const endActivity=this.#routeHandlers.get(run);if(!endActivity)return;this.#routeHandlers.delete(run);endActivity();this.finishRequest()}trackHostRouteRequest(run){this.refuseWhenExiting(run);const{request:request2,response}=run.rawInput;this.startRequest(response,false);const handled=request2&&routeHandlerSettled(request2);if(!request2||!handled)return;onRouteRequestAdmitted(request2,()=>{this.startRequest(response,true,false);void handled.then(this.holdActivity())});this.#inFlight++;void handled.then(()=>this.finishRequest())}refuseWhenExiting(run){if(this.isExiting)run.respond(exitingResponse())}startRequest(response,active,waited=true){if(waited)this.#inFlight++;const endActivity=active?this.holdActivity():()=>void 0;const finish=()=>{endActivity();if(waited)this.finishRequest()};if(typeof response?.once==="function"&&response.closed!==true)response.once("close",finish);else finish()}holdActivity(){this.#active++;this.#lastActivity=Date.now();let held=true;return()=>{if(!held)return;held=false;this.#active--;this.#lastActivity=Date.now()}}holdStream(stream){this.#streams.add(stream);stream.once?.("close",()=>{this.#streams.delete(stream);this.#lastActivity=Date.now()})}finishRequest(){this.#inFlight--;if(this.#inFlight>0)return;for(const done of[...this.#settledWaiters])done()}};__decorateClass([Will2("router")],SharedServerLifecycle.prototype,"trackRequest",1);__decorateClass([RouteHook.Will("handle")],SharedServerLifecycle.prototype,"trackRouteRequest",1);__decorateClass([RouteHook.Finally("handle")],SharedServerLifecycle.prototype,"finishRouteHandler",1);__decorateClass([HostRouteHook.Will("checkIpFilter")],SharedServerLifecycle.prototype,"trackHostRouteRequest",1)}});var inputSchema52,outputSchema50,plan57,name58,Stage58,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();inputSchema52=httpInputSchema;outputSchema50=HttpJsonSchema;plan57={pre:["checkIpFilter","acquireQuota","authorize"],execute:["drain"]};name58="shared:drain";Stage58=StageHookOf(name58);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([Stage58("checkIpFilter")],SharedDrainFlow.prototype,"checkIpFilter",1);__decorateClass([Stage58("acquireQuota")],SharedDrainFlow.prototype,"acquireQuota",1);__decorateClass([Stage58("authorize")],SharedDrainFlow.prototype,"authorize",1);__decorateClass([Stage58("drain")],SharedDrainFlow.prototype,"drain",1);SharedDrainFlow=__decorateClass([FrontMcpFlow({name:name58,plan:plan57,inputSchema:inputSchema52,outputSchema:outputSchema50,access:"public",middleware:{method:"POST"}})],SharedDrainFlow)}});var import_auth89,inputSchema53,outputSchema51,plan58,name59,Stage59,SharedIdentifyFlow;var init_shared_identify_flow=__esm({"libs/sdk/src/shared/flows/shared.identify.flow.ts"(){"use strict";import_auth89=require("@frontmcp/auth");init_common();init_shared_endpoint();init_shared_server_identity();init_shared_server_lifecycle();inputSchema53=httpInputSchema;outputSchema51=HttpJsonSchema;plan58={pre:["checkIpFilter","acquireQuota"],execute:["prove"]};name59="shared:identify";Stage59=StageHookOf(name59);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(!(0,import_auth89.isSharedServerNonce)(nonce)){this.respond(httpRespond.json({error:"nonce must be 32 random bytes in base64url"},{status:400}));return}const proof=this.get(SharedServerIdentity).prove(nonce);if(this.get(SharedServerLifecycle).isExiting)this.respond(exitingResponse(proof));this.respond(httpRespond.json(proof))}};__decorateClass([Stage59("checkIpFilter")],SharedIdentifyFlow.prototype,"checkIpFilter",1);__decorateClass([Stage59("acquireQuota")],SharedIdentifyFlow.prototype,"acquireQuota",1);__decorateClass([Stage59("prove")],SharedIdentifyFlow.prototype,"prove",1);SharedIdentifyFlow=__decorateClass([FrontMcpFlow({name:name59,plan:plan58,inputSchema:inputSchema53,outputSchema:outputSchema51,access:"public",middleware:{method:"POST"}})],SharedIdentifyFlow)}});function freeLoopbackPort(){return new Promise((resolve5,reject)=>{const probe2=net2.createServer();probe2.once("error",reject);probe2.listen(0,LOOPBACK,()=>{const{port}=probe2.address();probe2.close(()=>resolve5(port))})})}function sharedPeopleAuth(auth){const people=auth?.people;if(people==="loopback-token")return{...auth,people:{mode:people,store:false,startupToken:"off"}};if(typeof people!=="object"||people===null)return auth;return{...auth,people:{...people,store:false,startupToken:"off"}}}function keptHttpOptions(http5){if(!http5)return{};const{entryPath,routes,auth,bodyLimit,urlencodedLimit,securityHeaders,forwardHeaders}=http5;const kept={entryPath,routes,auth:sharedPeopleAuth(auth),bodyLimit,urlencodedLimit,securityHeaders,forwardHeaders};for(const name60 of Object.keys(kept)){if(kept[name60]===void 0)delete kept[name60]}return kept}function sharedHttpOptions(endpoint,http5){const kept=keptHttpOptions(http5);const{port}=endpoint;if(port===void 0)return{...kept,socketPath:endpoint.socketPath,cors:false};return{...kept,port,cors:false,security:{bindAddress:LOOPBACK,dnsRebindingProtection:{enabled:true,allowedHosts:deriveAllowedHosts({bindAddress:LOOPBACK,port}),allowedOrigins:deriveAllowedOrigins({port}).filter(origin=>origin.startsWith("http:"))}}}}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((0,import_auth90.isStaticMode)(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=(0,import_auth90.createSharedServerSecret)();const keys=(0,import_auth90.deriveSharedServerKeys)(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 parsed=frontMcpMetadataSchema.parse({...config,serve:true,http:sharedHttpOptions(port===void 0?{socketPath:files.socketPath}:{port},config.http),auth:{mode:"static",tokens:[keys.token]},logging:withFileLogging(config.logging),providers:[...config.providers??[],{name:"frontmcp:shared-server-identity",provide:SharedServerIdentity,scope:import_di57.ProviderScope.GLOBAL,useValue:new SharedServerIdentity(keys,endpoint.id,config.info.version)},{name:"frontmcp:shared-server-lifecycle",provide:SharedServerLifecycle,scope:import_di57.ProviderScope.GLOBAL,useValue:lifecycle}]});markEntryServer(parsed);const instance=serve.create(parsed);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=(0,import_utils228.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(resolve5=>setTimeout(resolve5,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 net2,import_auth90,import_di57,import_utils228,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";net2=__toESM(require("node:net"));import_auth90=require("@frontmcp/auth");import_di57=require("@frontmcp/di");import_utils228=require("@frontmcp/utils");init_common();init_errors();init_shared_server_errors();init_detached_job_flag();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}});async function embeddedListener(options){if(options.transport==="http")return{port:await freeLoopbackPort()};const files=sharedServerFiles(options.key);const id=Buffer.from((0,import_utils229.randomBytes)(4)).toString("hex");const socketPath=path6.join(files.directory,`s-${id}.sock`);if(!socketPathFits(socketPath))return void 0;await prepareSharedDirectory(files);return{socketPath}}function endpointOf2(listener){return listener.port===void 0?unixEndpoint(listener.socketPath):httpEndpoint(listener.port)}async function bootEmbeddedServer(config,options,create2){const{token}=(0,import_auth91.deriveSharedServerKeys)((0,import_auth91.createSharedServerSecret)());const listener=await embeddedListener(options);const parsed=frontMcpMetadataSchema.parse({...config,serve:listener!==void 0,...listener?{http:sharedHttpOptions(listener,config.http)}:{},auth:{mode:"static",tokens:[token]}});markEntryServer(parsed);const instance=create2(parsed);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;assertTokenGuardsEveryScope(instance,options.key,token)}catch(error){await instance.shutdown().catch(()=>void 0);throw error}const headers={authorization:`Bearer ${token}`};const close=()=>instance.shutdown();let started;const serve=async()=>{try{if(!listener){await instance.emitProvidersReady();const handler=createServerFetchHandler(scope,instance.getScopes());const fetchHandled=(input,init)=>handler(new Request(input,init));return{url:`http://localhost${scope.fullPath||"/"}`,headers,fetch:fetchHandled,close}}await instance.start();const endpoint=endpointOf2(listener);return{url:`${endpoint.baseUrl}${scope.fullPath||"/"}`,headers,fetch:endpoint.fetch,close}}catch(error){await close().catch(()=>void 0);throw error}};return{start:()=>started??=serve(),close}}var path6,import_auth91,import_utils229;var init_shared_embedded=__esm({"libs/sdk/src/shared/shared-embedded.ts"(){"use strict";path6=__toESM(require("node:path"));import_auth91=require("@frontmcp/auth");import_utils229=require("@frontmcp/utils");init_common();init_errors();init_detached_job_flag();init_web_fetch_handler();init_shared_endpoint();init_shared_files();init_shared_serve()}});var shared_exports={};__export(shared_exports,{runShared:()=>runShared});async function isFolder(folder){try{return(await(0,import_utils230.stat)(folder)).isDirectory()}catch{return false}}async function runShared(config,sharedOptions,create2){const{key,...validated}=validateSharedServerOptions(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(validated.checkout!==false&&!await isFolder(validated.checkout)){throw new InvalidSharedServerOptionsError(`checkout: ${validated.checkout} is not a folder`)}const serveKey=(0,import_utils230.getEnv)(SHARED_SERVE_ENV);if(serveKey!==void 0&&(typeof key==="string"?serveKey===key:isSharedServerKey(serveKey))){const options2={...validated,key:serveKey};const startLockHolder=(0,import_utils230.getEnv)(SHARED_START_LOCK_ENV);delete process.env[SHARED_SERVE_ENV];delete process.env[SHARED_START_LOCK_ENV];const server=await serveShared({config,options:options2,create:create2,startLockHolder,exit:code=>process.exit(code)});exitOnShutdownSignals(()=>server.close());return}redirectConsoleToStderr();let options;let keySignature;if(typeof key==="string"){options={...validated,key}}else{if(validated.rereadKey)keySignature=await keyFileSignature(validated.rereadKey.file);const read=await readSharedServerKey(key);if("error"in read)throw new InvalidSharedServerOptionsError(`key: ${read.error}`);options={...validated,key:read.key,keySource:key}}const session=attachSharedSession({...options,...keySignature===void 0?{}:{keySignature},name:config.info.name,version,input:process.stdin,output:process.stdout,bootEmbedded:sessionKey=>bootEmbeddedServer(config,{...options,key:sessionKey},create2)});exitOnShutdownSignals(()=>session.stop(),{deadlineMs:STDIO_SHUTDOWN_DEADLINE_MS,whenOrphaned:{stdin:process.stdin}});await session.attached}var import_utils230;var init_shared=__esm({"libs/sdk/src/shared/index.ts"(){"use strict";import_utils230=require("@frontmcp/utils");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});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(0,import_utils231.getEnvFlag)("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}function warnUserContentIgnored(log,http5,entry){if(!http5?.userContent)return;log?.warn(`http.userContent is ignored: ${entry} opens no listener of its own. Only a Node HTTP server (bootstrap, runUnixSocket) serves it.`)}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 import_protocol85,import_utils231,stdioServing,FrontMcpInstance;var init_front_mcp=__esm({"libs/sdk/src/front-mcp/front-mcp.ts"(){"use strict";import_protocol85=require("@frontmcp/protocol");import_utils231=require("@frontmcp/utils");init_channel_utils();init_common();init_front_mcp_stores();init_direct();init_errors();init_logger_registry();init_container_handle();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(resolve5=>{deadline=setTimeout(()=>resolve5(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(){const container=containerHandleOf(this.config.container);if(container?.disposed)throw new ContainerDisposedError;this.providers=new ProviderRegistry([...createMcpGlobalProviders(this.config)],void 0,{shutdownHookTimeoutMs:this.config.lifecycle?.shutdownHookTimeoutMs,...container?{sharedLifecycles:container.lifecycles,container}:{}});await this.providers.ready;this.logger=new LoggerRegistry(this.providers);await this.logger.ready;this.log=this.providers.get(FrontMcpLogger);const name60=this.config.info?.name;const version=this.config.info?.version;const tag=[name60,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);this.wireClientIpCheck(server);await this.wireMetricsService(server);await server.start();for(const scope of this.getScopes()){await scope.emitServerStarted()}await this.emitProvidersReady();if((0,import_utils231.getEnv)("FRONTMCP_DEV_BOOTSTRAP_SENTINEL")==="1"){process.stderr.write(`__FRONTMCP_BOOTSTRAP_COMPLETE__ ${JSON.stringify(this.devListenerInfo(server))}
|
|
494
494
|
`)}}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 http5=server.config;const path7=this.getPrimaryScope()?.fullPath||"/";if(http5?.socketPath)return{socketPath:http5.socketPath,path:path7};return typeof http5?.port==="number"?{port:http5.port,path:path7}:{path:path7}}getConfig(){return this.config}getScopes(){return this.scopes.getScopes()}async emitProvidersReady(){for(const scope of this.getScopes()){await scope.providers.runReadyHooks(scope.logger)}if(containerHandleOf(this.config.container)?.disposed)throw new ContainerDisposedError}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)}}wireClientIpCheck(server){const serverInstance=server;const scope=this.getPrimaryScope();if(typeof serverInstance.setClientIpCheck!=="function"||!scope)return;serverInstance.setClientIpCheck((request2,response)=>scope.runFlow("http:ip-filter",{request:request2,response}))}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;if((0,import_utils231.getRuntimeContext)().runtime==="browser"){const{BrowserEntryPointUnavailableError:BrowserEntryPointUnavailableError2}=await Promise.resolve().then(()=>(init_browser_entry_point_errors(),browser_entry_point_errors_exports));throw new BrowserEntryPointUnavailableError2("bootstrap")}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);frontMcp.wireClientIpCheck(server);await frontMcp.wireMetricsService(server);server.prepare();await frontMcp.emitProvidersReady();warnUserContentIgnored(frontMcp.log,frontMcp.config.http,"a serverless handler (createHandler)");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();warnUserContentIgnored(frontMcp.log,frontMcp.config.http,"a fetch handler for Workers and edge runtimes (createFetchHandler)");frontMcp.log?.info("FrontMCP fetch handler created (web-standard transport)");return createServerFetchHandler2(scope,frontMcp.getScopes(),metricsService&&metricsConfig?{metrics:{service:metricsService,config:metricsConfig}}:{})};if(!(0,import_utils231.isEdgeRuntime)())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=(0,import_utils231.getEnvFlag)("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((0,import_utils231.getRuntimeContext)().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));warnUserContentIgnored(frontMcp.log,options.http,"a stdio server (runStdio)");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:${(0,import_utils231.randomUUID)()}`;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 import_protocol85.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 detachedRunId=detachedJobRunId();if(detachedRunId)return exitAfterDetachedRun(options,detachedRunId);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});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:(0,import_utils232.getHostname)()}});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 import_utils232;var init_execute_task=__esm({"libs/sdk/src/task/runtime/execute-task.ts"(){"use strict";import_utils232=require("@frontmcp/utils");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()}});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=(0,import_utils233.getEnvFlag)("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=(0,import_utils233.getEnvFlag)("FRONTMCP_SERVERLESS");const isSchemaExtract=(0,import_utils233.getEnvFlag)("FRONTMCP_SCHEMA_EXTRACT");const isStdio=(0,import_utils233.getEnvFlag)("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=(0,import_utils233.getEnvFlag)("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&&(0,import_utils233.getRuntimeContext)().runtime==="browser"){}else if(metadata.serve){loadFrontMcpInstance().then(FrontMcpInstance2=>FrontMcpInstance2.bootstrap(metadata)).catch(err=>{console.error("[FrontMCP] server failed to start:",err);process.exit(1)})}}}var import_reflect_metadata33,import_utils233,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";import_reflect_metadata33=require("reflect-metadata");import_utils233=require("@frontmcp/utils");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()}});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:(0,import_utils234.idFromString)(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 import_reflect_metadata34,import_utils234,APP_DECORATOR_BASENAMES,App;var init_app_decorator=__esm({"libs/sdk/src/common/decorators/app.decorator.ts"(){"use strict";import_reflect_metadata34=require("reflect-metadata");import_utils234=require("@frontmcp/utils");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}});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 import_reflect_metadata35;var init_auth_provider_decorator=__esm({"libs/sdk/src/common/decorators/auth-provider.decorator.ts"(){"use strict";import_reflect_metadata35=require("reflect-metadata");init_metadata();init_tokens()}});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 import_reflect_metadata36;var init_adapter_decorator=__esm({"libs/sdk/src/common/decorators/adapter.decorator.ts"(){"use strict";import_reflect_metadata36=require("reflect-metadata");init_metadata();init_tokens()}});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 import_reflect_metadata37;var init_plugin_decorator=__esm({"libs/sdk/src/common/decorators/plugin.decorator.ts"(){"use strict";import_reflect_metadata37=require("reflect-metadata");init_decorator_errors();init_metadata();init_tokens();init_enforced_metadata_utils()}});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 import_reflect_metadata38,Prompt;var init_prompt_decorator=__esm({"libs/sdk/src/common/decorators/prompt.decorator.ts"(){"use strict";import_reflect_metadata38=require("reflect-metadata");init_package_specifier();init_metadata();init_tokens();init_validate_remote_url();Object.assign(FrontMcpPrompt,{esm:promptEsm,remote:promptRemote});Prompt=FrontMcpPrompt}});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 import_reflect_metadata39;var init_logger_decorator=__esm({"libs/sdk/src/common/decorators/logger.decorator.ts"(){"use strict";import_reflect_metadata39=require("reflect-metadata");init_metadata();init_tokens()}});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 import_reflect_metadata40,Agent2;var init_agent_decorator=__esm({"libs/sdk/src/common/decorators/agent.decorator.ts"(){"use strict";import_reflect_metadata40=require("reflect-metadata");init_package_specifier();init_metadata();init_tokens();init_validate_remote_url();Object.assign(FrontMcpAgent,{esm:agentEsm,remote:agentRemote});Agent2=FrontMcpAgent}});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 import_reflect_metadata41,JOB_DECORATOR_BASENAMES,FrontMcpJob,Job;var init_job_decorator=__esm({"libs/sdk/src/common/decorators/job.decorator.ts"(){"use strict";import_reflect_metadata41=require("reflect-metadata");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}});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 import_reflect_metadata42;var init_workflow_decorator=__esm({"libs/sdk/src/common/decorators/workflow.decorator.ts"(){"use strict";import_reflect_metadata42=require("reflect-metadata");init_workflow_metadata();init_tokens()}});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 import_reflect_metadata43;var init_duty_decorator=__esm({"libs/sdk/src/common/decorators/duty.decorator.ts"(){"use strict";import_reflect_metadata43=require("reflect-metadata");init_decorator_errors();init_duty_metadata();init_duty_resolved();init_tokens()}});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 import_reflect_metadata44;var init_worker_decorator=__esm({"libs/sdk/src/common/decorators/worker.decorator.ts"(){"use strict";import_reflect_metadata44=require("reflect-metadata");init_decorator_errors();init_worker_metadata();init_worker_resolved();init_tokens()}});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 import_reflect_metadata45,import_lazy_zod157,httpRouteMetadataSchema;var init_http_route_decorator=__esm({"libs/sdk/src/common/decorators/http-route.decorator.ts"(){"use strict";import_reflect_metadata45=require("reflect-metadata");import_lazy_zod157=require("@frontmcp/lazy-zod");init_decorator_errors();init_http_route_metadata();httpRouteMetadataSchema=import_lazy_zod157.z.object({method:import_lazy_zod157.z.enum(["GET","POST","PUT","PATCH","DELETE"],{message:"method must be 'GET', 'POST', 'PUT', 'PATCH' or 'DELETE'"}),path:import_lazy_zod157.z.custom(value=>typeof value==="function"||isHttpRoutePath(value),{message:HTTP_ROUTE_PATH_MESSAGE}),auth:import_lazy_zod157.z.enum(["people","subject","bearer","public"],{message:"auth must be 'people', 'subject', 'bearer' or 'public'"}).optional(),authorities:import_lazy_zod157.z.custom(rule=>typeof rule==="string"||typeof rule==="object"&&rule!==null,{message:"authorities must be a profile name, a list of names or a policy"}).optional(),allowAnonymous:import_lazy_zod157.z.boolean({message:"allowAnonymous must be true or false"}).optional(),sse:import_lazy_zod157.z.object({store:import_lazy_zod157.z.custom(value=>typeof value?.subscribe==="function",{message:"sse.store must have subscribe(topic, listener), such as a resourceStore()"}),topics:import_lazy_zod157.z.array(import_lazy_zod157.z.string().min(1,"a topic must not be empty")).min(1,"sse.topics must name at least one topic"),coalesceMs:import_lazy_zod157.z.number().int().nonnegative("sse.coalesceMs must not be negative").default(50),heartbeatMs:import_lazy_zod157.z.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"]}).refine(metadata=>metadata.authorities===void 0||metadata.auth==="bearer",{message:"authorities need auth: 'bearer', whose token names the caller they check",path:["authorities"]}).refine(metadata=>metadata.allowAnonymous===void 0||metadata.auth==="bearer",{message:"allowAnonymous needs auth: 'bearer', whose caller it lets be anonymous",path:["allowAnonymous"]})}});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)}`)}}}}});var import_reflect_metadata46,FlowEntry;var init_flow_entry=__esm({"libs/sdk/src/common/entries/flow.entry.ts"(){"use strict";import_reflect_metadata46=require("reflect-metadata");init_base_entry();FlowEntry=class extends BaseEntry{name;path;method;scope;constructor(scope,record,token,metadata){super(record,token,metadata);const{path:path7,method}=record.metadata.middleware??metadata?.middleware??{};this.name=metadata?.name??record.metadata?.name;this.path=path7;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{}}});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 import_lazy_zod158,import_utils236,PRIMITIVE_ZOD_OUTPUT_TYPES,DEFINITION_REF_PREFIX,ToolEntry;var init_tool_entry=__esm({"libs/sdk/src/common/entries/tool.entry.ts"(){"use strict";import_lazy_zod158=require("@frontmcp/lazy-zod");import_utils236=require("@frontmcp/utils");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(0,import_lazy_zod158.toJSONSchema)(import_lazy_zod158.internalZ.object(this.inputSchema),{io:"input",unrepresentable:"any"})}catch(error){if((0,import_utils236.isDebug)()||(0,import_utils236.isDevelopment)()){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:import_lazy_zod158.internalZ.object(schema);const objectSchema=asObjectOutputSchema((0,import_lazy_zod158.toJSONSchema)(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??[]}}}});function toObjectSchema(schema){const isZodSchema=typeof schema.safeParse==="function";return isZodSchema?schema:import_lazy_zod159.internalZ.object(schema)}function toObjectJsonSchema(schema,io){return(0,import_lazy_zod159.toJSONSchema)(toObjectSchema(schema),{io,unrepresentable:"any"})}var import_lazy_zod159,EventEntry;var init_event_entry=__esm({"libs/sdk/src/common/entries/event.entry.ts"(){"use strict";import_lazy_zod159=require("@frontmcp/lazy-zod");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:inputSchema54}=this.metadata;const schema=inputSchema54?toObjectSchema(inputSchema54):import_lazy_zod159.internalZ.object({}).strict();return schema.parse(args)}parsePayload(data){return toObjectSchema(this.metadata.payloadSchema).parse(data)}buildInputJsonSchema(){const{inputSchema:inputSchema54}=this.metadata;if(!inputSchema54){return{type:"object",properties:{},additionalProperties:false}}return toObjectJsonSchema(inputSchema54,"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()}});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 import_lazy_zod160.internalZ.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 import_lazy_zod160;var init_flow_utils3=__esm({"libs/sdk/src/common/flow/flow.utils.ts"(){"use strict";import_lazy_zod160=require("@frontmcp/lazy-zod");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(path7,defaultValue){const keys=path7.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(path7){const keys=path7.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(path7,defaultValue){const value=this.get(path7);return value!==void 0?value:defaultValue}getRequired(path7){const value=this.get(path7);if(value===void 0){throw new RequiredConfigUndefinedError(path7)}return value}getOrThrow(path7){return this.getRequired(path7)}getSection(section){return this.config[section]}matches(path7,value){return this.get(path7)===value}getMany(paths){const result={};for(const path7 of paths){result[path7]=this.get(path7)}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()}});var remote_mcp_exports={};__export(remote_mcp_exports,{CapabilityCache:()=>CapabilityCache,CircuitBreaker:()=>CircuitBreaker,CircuitBreakerManager:()=>CircuitBreakerManager,CircuitOpenError:()=>CircuitOpenError,HealthCheckManager:()=>HealthCheckManager,HealthChecker:()=>HealthChecker,McpClientService:()=>McpClientService,buildRemotePromptRecord:()=>buildRemotePromptRecord,buildRemoteResourceRecord:()=>buildRemoteResourceRecord,buildRemoteResourceTemplateRecord:()=>buildRemoteResourceTemplateRecord,buildRemoteToolRecord:()=>buildRemoteToolRecord,createRemotePromptContextClass:()=>createRemotePromptContextClass,createRemotePromptInstance:()=>createRemotePromptInstance,createRemoteResourceContextClass:()=>createRemoteResourceContextClass,createRemoteResourceInstance:()=>createRemoteResourceInstance,createRemoteResourceTemplateInstance:()=>createRemoteResourceTemplateInstance,createRemoteToolContextClass:()=>createRemoteToolContextClass,createRemoteToolInstance:()=>createRemoteToolInstance,isAuthError:()=>isAuthError,isConnectionError:()=>isConnectionError,isTransientError:()=>isTransientError,withRetry:()=>withRetry});var init_remote_mcp=__esm({"libs/sdk/src/remote-mcp/index.ts"(){"use strict";init_mcp_client_service();init_cache();init_resilience();init_factories()}});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)}var init_esm_instance_factories=__esm({"libs/sdk/src/esm-loader/factories/esm-instance-factories.ts"(){"use strict";init_prompt_instance();init_resource_instance();init_tool_instance();init_esm_record_builders()}});var init_factories2=__esm({"libs/sdk/src/esm-loader/factories/index.ts"(){"use strict";init_esm_context_factories();init_esm_record_builders();init_esm_instance_factories()}});var esm_loader_exports={};__export(esm_loader_exports,{DEFAULT_NPM_REGISTRY:()=>DEFAULT_NPM_REGISTRY,ESM_SH_BASE_URL:()=>ESM_SH_BASE_URL,EsmCacheManager:()=>EsmCacheManager,EsmModuleLoader:()=>EsmModuleLoader,MANIFEST_PRIMITIVE_KEYS:()=>MANIFEST_PRIMITIVE_KEYS,VersionPoller:()=>VersionPoller,VersionResolver:()=>VersionResolver,buildEsmPromptRecord:()=>buildEsmPromptRecord,buildEsmResourceRecord:()=>buildEsmResourceRecord,buildEsmShUrl:()=>buildEsmShUrl,buildEsmToolRecord:()=>buildEsmToolRecord,compareVersions:()=>compareVersions,createEsmPromptContextClass:()=>createEsmPromptContextClass,createEsmPromptInstance:()=>createEsmPromptInstance,createEsmResourceContextClass:()=>createEsmResourceContextClass,createEsmResourceInstance:()=>createEsmResourceInstance,createEsmToolContextClass:()=>createEsmToolContextClass,createEsmToolInstance:()=>createEsmToolInstance,esmRegistryAuthSchema:()=>esmRegistryAuthSchema,frontMcpPackageManifestSchema:()=>frontMcpPackageManifestSchema,getRegistryUrl:()=>getRegistryUrl,isNewerVersion:()=>isNewerVersion,isPackageSpecifier:()=>isPackageSpecifier,isValidRange:()=>isValidRange,isValidVersion:()=>isValidVersion,maxSatisfying:()=>maxSatisfying,normalizeEsmExport:()=>normalizeEsmExport,parsePackageSpecifier:()=>parsePackageSpecifier,resolveRegistryToken:()=>resolveRegistryToken,satisfiesRange:()=>satisfiesRange});var init_esm_loader=__esm({"libs/sdk/src/esm-loader/index.ts"(){"use strict";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_factories2()}});var init_job_definition_interface=__esm({"libs/sdk/src/job/store/job-definition.interface.ts"(){"use strict"}});var init_store=__esm({"libs/sdk/src/job/store/index.ts"(){"use strict";init_job_state_interface();init_memory_job_state_store();init_redis_job_state_store();init_storage_job_state_store();init_job_state_store_factory();init_job_definition_interface();init_memory_job_definition_store();init_redis_job_definition_store();init_storage_job_definition_store();init_job_definition_store_factory()}});var init_execution=__esm({"libs/sdk/src/job/execution/index.ts"(){"use strict";init_job_execution_manager()}});async function importEnclaveCore(){try{return await import("@enclave-vm/core")}catch{throw new Error("Missing optional dependency: dynamic jobs require @enclave-vm/core. Install it with: npm install @enclave-vm/core")}}var init_enclave_core=__esm({"libs/sdk/src/job/enclave/enclave-core.ts"(){"use strict"}});function toSandboxValue(value){try{return structuredClone(value)}catch{throw new Error("Value crossing the sandbox boundary is not structured-cloneable")}}var JobEnclaveBridge;var init_job_enclave_bridge=__esm({"libs/sdk/src/job/enclave/job-enclave.bridge.ts"(){"use strict";init_enclave_core();init_errors();JobEnclaveBridge=class{logger;options;enclaveCore;constructor(logger,options={}){this.logger=logger;this.options={timeout:options.timeout??3e4,maxIterations:options.maxIterations??1e3}}async getEnclaveCore(){if(!this.enclaveCore){const mod=await importEnclaveCore();const core=typeof mod?.Sandbox==="function"?mod:mod?.default;if(!core||typeof core.Sandbox!=="function"){throw new Error("The installed @enclave-vm/core did not export a usable `Sandbox` constructor. Ensure a compatible @enclave-vm/core version is installed.")}this.enclaveCore=core}return this.enclaveCore}async execute(script,input,context){const enclave=await this.getEnclaveCore();const{Sandbox}=enclave;const clonedInput=toSandboxValue(input??null);const sandbox=new Sandbox({timeout:this.options.timeout,maxIterations:this.options.maxIterations});const globals={input:clonedInput,console:{log:(...args)=>context.mcpLog?.("info",args.map(String).join(" ")),warn:(...args)=>context.mcpLog?.("warning",args.map(String).join(" ")),error:(...args)=>context.mcpLog?.("error",args.map(String).join(" "))}};const{callTool,getTool}=context;if(callTool){globals["callTool"]=async(name60,args)=>{try{return toSandboxValue(await callTool(name60,args))}catch(err){throw{message:err instanceof Error?err.message:String(err),type:"ToolError"}}}}if(getTool){globals["getTool"]=name60=>{try{return toSandboxValue(getTool(name60))}catch(err){throw{message:err instanceof Error?err.message:String(err),type:"ToolError"}}}}try{const result=await sandbox.run(script,globals);return result}catch(err){const error=err instanceof Error?err:new Error(String(err));this.logger.error(`Enclave execution failed: ${error.message}`);throw new EnclaveExecutionError(error.message,error)}finally{sandbox.dispose?.()}}}}});var JobDynamicExecutor;var init_job_dynamic_executor=__esm({"libs/sdk/src/job/enclave/job-dynamic.executor.ts"(){"use strict";init_job_enclave_bridge();JobDynamicExecutor=class{bridge;logger;constructor(logger){this.logger=logger;this.bridge=new JobEnclaveBridge(logger)}async execute(record,input,context){this.logger.info(`Executing dynamic job "${record.metadata.name}" via enclave`);const result=await this.bridge.execute(record.script,input,context??{});return result}}}});var init_enclave=__esm({"libs/sdk/src/job/enclave/index.ts"(){"use strict";init_job_enclave_bridge();init_job_dynamic_executor()}});var tools_exports={};__export(tools_exports,{CancelJobTool:()=>CancelJobTool,ExecuteJobTool:()=>ExecuteJobTool,GetJobStatusTool:()=>GetJobStatusTool,ListJobsTool:()=>ListJobsTool,RegisterJobTool:()=>RegisterJobTool,RemoveJobTool:()=>RemoveJobTool,UpdateJobTool:()=>UpdateJobTool});var init_tools=__esm({"libs/sdk/src/job/tools/index.ts"(){"use strict";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()}});var job_exports={};__export(job_exports,{CancelJobTool:()=>CancelJobTool,DEFAULT_JOB_TIMEOUT_MS:()=>DEFAULT_JOB_TIMEOUT_MS,EXECUTE_JOB_FLOW:()=>EXECUTE_JOB_FLOW,ExecuteJobFlow:()=>ExecuteJobFlow,ExecuteJobTool:()=>ExecuteJobTool,FINISHED_JOB_STATES:()=>FINISHED_JOB_STATES,GetJobStatusTool:()=>GetJobStatusTool,JobAdmission:()=>JobAdmission,JobDynamicExecutor:()=>JobDynamicExecutor,JobEmitter:()=>JobEmitter,JobEnclaveBridge:()=>JobEnclaveBridge,JobExecutionManager:()=>JobExecutionManager,JobInstance:()=>JobInstance,JobPermissionGuard:()=>JobPermissionGuard,JobRegistry:()=>JobRegistry,JobRunResource:()=>JobRunResource,ListJobsTool:()=>ListJobsTool,MachineJobAdmission:()=>MachineJobAdmission,MemoryJobDefinitionStore:()=>MemoryJobDefinitionStore,MemoryJobStateStore:()=>MemoryJobStateStore,RedisJobDefinitionStore:()=>RedisJobDefinitionStore,RedisJobStateStore:()=>RedisJobStateStore,RegisterJobTool:()=>RegisterJobTool,RemoveJobTool:()=>RemoveJobTool,StorageJobDefinitionStore:()=>StorageJobDefinitionStore,StorageJobStateStore:()=>StorageJobStateStore,UpdateJobTool:()=>UpdateJobTool,collectJobMetadata:()=>collectJobMetadata,createJobAdmission:()=>createJobAdmission,createJobDefinitionStore:()=>createJobDefinitionStore,createJobStateStore:()=>createJobStateStore,jobDiscoveryDeps:()=>jobDiscoveryDeps,jobRunUri:()=>jobRunUri,jobsServerStore:()=>jobsServerStore,mayAccessRun:()=>mayAccessRun,normalizeJob:()=>normalizeJob,registerAppJobEntries:()=>registerAppJobEntries,registerJobCapabilities:()=>registerJobCapabilities,resolveJobsStore:()=>resolveJobsStore,unregistersAppJobEntries:()=>unregistersAppJobEntries});var init_job=__esm({"libs/sdk/src/job/index.ts"(){"use strict";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_execute_job_flow();init_job_attempt();init_job_scope_helper();init_store();init_execution();init_enclave();init_tools()}});var init_engine=__esm({"libs/sdk/src/workflow/engine/index.ts"(){"use strict";init_workflow_engine();init_workflow_step_executor()}});var tools_exports2={};__export(tools_exports2,{ExecuteWorkflowTool:()=>ExecuteWorkflowTool,GetWorkflowStatusTool:()=>GetWorkflowStatusTool,ListWorkflowsTool:()=>ListWorkflowsTool,RegisterWorkflowTool:()=>RegisterWorkflowTool,RemoveWorkflowTool:()=>RemoveWorkflowTool,UpdateWorkflowTool:()=>UpdateWorkflowTool});var init_tools2=__esm({"libs/sdk/src/workflow/tools/index.ts"(){"use strict";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()}});var workflow_exports={};__export(workflow_exports,{ExecuteWorkflowTool:()=>ExecuteWorkflowTool,GetWorkflowStatusTool:()=>GetWorkflowStatusTool,ListWorkflowsTool:()=>ListWorkflowsTool,RegisterWorkflowTool:()=>RegisterWorkflowTool,RemoveWorkflowTool:()=>RemoveWorkflowTool,UpdateWorkflowTool:()=>UpdateWorkflowTool,WorkflowEmitter:()=>WorkflowEmitter,WorkflowEngine:()=>WorkflowEngine,WorkflowInstance:()=>WorkflowInstance,WorkflowRegistry:()=>WorkflowRegistry,WorkflowStepExecutor:()=>WorkflowStepExecutor,collectWorkflowMetadata:()=>collectWorkflowMetadata,normalizeWorkflow:()=>normalizeWorkflow,parseWorkflowInput:()=>parseWorkflowInput});var init_workflow=__esm({"libs/sdk/src/workflow/index.ts"(){"use strict";init_workflow_registry();init_workflow_instance();init_workflow_events2();init_workflow_utils();init_engine();init_tools2()}});var channel_exports={};__export(channel_exports,{ChannelEmitter:()=>ChannelEmitter,ChannelEventBus:()=>ChannelEventBus,ChannelInstance:()=>ChannelInstance,ChannelNotificationService:()=>ChannelNotificationService,ChannelRegistry:()=>ChannelRegistry,ChannelReplyTool:()=>ChannelReplyTool,normalizeChannel:()=>normalizeChannel,normalizeChannels:()=>normalizeChannels,registerChannelCapabilities:()=>registerChannelCapabilities});var init_channel=__esm({"libs/sdk/src/channel/index.ts"(){"use strict";init_channel_instance();init_channel_registry();init_channel_events();init_channel_utils();init_channel_notification_service();init_app_event_source();init_channel_scope_helper();init_channel_reply_tool()}});var event_exports={};__export(event_exports,{EVENT_COUNTERS:()=>EVENT_COUNTERS,EVENT_DELIVERY_MAX_BYTES:()=>EVENT_DELIVERY_MAX_BYTES,EVENT_DIALECTS:()=>EVENT_DIALECTS,EVENT_PUBLISH_MAX_BODY_BYTES:()=>EVENT_PUBLISH_MAX_BODY_BYTES,EVENT_RELAY_CHANNEL:()=>EVENT_RELAY_CHANNEL,EventBuffer:()=>EventBuffer,EventCallbackVerifier:()=>EventCallbackVerifier,EventInstance:()=>EventInstance,EventOutbox:()=>EventOutbox,EventPollLeases:()=>EventPollLeases,EventPublishIdempotency:()=>EventPublishIdempotency,EventRegistry:()=>EventRegistry,EventReplays:()=>EventReplays,EventStream:()=>EventStream,EventStreams:()=>EventStreams,EventSubscriptions:()=>EventSubscriptions,MAX_OPEN_STREAMS:()=>MAX_OPEN_STREAMS,MAX_PENDING_BATCHES:()=>MAX_PENDING_BATCHES,MAX_POLL_LEASES:()=>MAX_POLL_LEASES,MAX_QUEUED_NOTIFICATIONS:()=>MAX_QUEUED_NOTIFICATIONS,OUTBOX_SWEEP_INTERVAL_MS:()=>OUTBOX_SWEEP_INTERVAL_MS,POLL_LEASE_INTERVALS:()=>POLL_LEASE_INTERVALS,POLL_LEASE_MIN_MS:()=>POLL_LEASE_MIN_MS,POLL_LEASE_SWEEP_INTERVAL_MS:()=>POLL_LEASE_SWEEP_INTERVAL_MS,PUBLISH_CLAIM_SECONDS:()=>PUBLISH_CLAIM_SECONDS,PUBLISH_IDEMPOTENCY_WINDOW_SECONDS:()=>PUBLISH_IDEMPOTENCY_WINDOW_SECONDS,REPLAY_LEASE_MS:()=>REPLAY_LEASE_MS,SUBSCRIPTION_SWEEP_INTERVAL_MS:()=>SUBSCRIPTION_SWEEP_INTERVAL_MS,SUSPEND_AFTER_FAILURES:()=>SUSPEND_AFTER_FAILURES,ScopeEventPublisher:()=>ScopeEventPublisher,StorageEventSubscriptionStore:()=>StorageEventSubscriptionStore,VERIFICATION_ATTEMPTS_PER_HOST:()=>VERIFICATION_ATTEMPTS_PER_HOST,assertEventAuthorities:()=>assertEventAuthorities,assertEventAuthorizes:()=>assertEventAuthorizes,callerPlatformOf:()=>callerPlatformOf,createEventMetrics:()=>createEventMetrics,createEventSubscriptionStore:()=>createEventSubscriptionStore,deliveryStatusOf:()=>deliveryStatusOf,enablePublishEndpoint:()=>enablePublishEndpoint,eventOutboundTargetOptions:()=>eventOutboundTargetOptions,eventReaderOf:()=>eventReaderOf,eventSubscriberOf:()=>eventSubscriberOf,isInAudience:()=>isInAudience,newEventId:()=>newEventId,normalizeEvent:()=>normalizeEvent,offeredEventOf:()=>offeredEventOf,openEventStorage:()=>openEventStorage,parsedEventArguments:()=>parsedEventArguments,pollLeaseMs:()=>pollLeaseMs,readerSubscriptionOf:()=>readerSubscriptionOf,registerEventCapabilities:()=>registerEventCapabilities,resolveEventDialect:()=>resolveEventDialect,subscriptionRefOf:()=>subscriptionRefOf});var init_event=__esm({"libs/sdk/src/event/index.ts"(){"use strict";init_event_instance();init_event_registry();init_event_utils();init_event_scope_helper();init_event_dialect();init_event_outbound();init_event_subscriber();init_event_callback_verifier();init_event_subscription_store_factory();init_event_subscription_store();init_event_subscriptions();init_event_metrics();init_event_outbox();init_event_publisher();init_event_gates();init_event_buffer();init_event_poll_leases();init_event_replays();init_event_stream();init_event_streams();init_event_deliver_flow();init_event_publish_flow();init_event_publish_http_flow();init_event_publish_endpoint();init_event_publish_idempotency()}});var require_lazy_subsystems=__commonJS({"libs/sdk/src/lazy-subsystems.ts"(exports2){"use strict";{const defineLazyExports=(load3,names)=>{let loaded;for(const name60 of names){Object.defineProperty(exports2,name60,{enumerable:true,get:()=>(loaded??=load3())[name60]})}};defineLazyExports(()=>(init_remote_mcp(),__toCommonJS(remote_mcp_exports)),["CapabilityCache","CircuitBreaker","CircuitBreakerManager","CircuitOpenError","HealthCheckManager","HealthChecker","McpClientService","buildRemotePromptRecord","buildRemoteResourceRecord","buildRemoteResourceTemplateRecord","buildRemoteToolRecord","createRemotePromptContextClass","createRemotePromptInstance","createRemoteResourceContextClass","createRemoteResourceInstance","createRemoteResourceTemplateInstance","createRemoteToolContextClass","createRemoteToolInstance","isAuthError","isConnectionError","isTransientError","withRetry"]);defineLazyExports(()=>(init_mcp_stateless_client_adapter(),__toCommonJS(mcp_stateless_client_adapter_exports)),["McpStatelessClientAdapter","negotiateRemoteProtocol"]);defineLazyExports(()=>(init_esm_loader(),__toCommonJS(esm_loader_exports)),["DEFAULT_NPM_REGISTRY","ESM_SH_BASE_URL","EsmCacheManager","EsmModuleLoader","MANIFEST_PRIMITIVE_KEYS","VersionPoller","VersionResolver","buildEsmPromptRecord","buildEsmResourceRecord","buildEsmShUrl","buildEsmToolRecord","compareVersions","createEsmPromptContextClass","createEsmPromptInstance","createEsmResourceContextClass","createEsmResourceInstance","createEsmToolContextClass","createEsmToolInstance","esmRegistryAuthSchema","frontMcpPackageManifestSchema","getRegistryUrl","isNewerVersion","isPackageSpecifier","isValidRange","isValidVersion","maxSatisfying","normalizeEsmExport","parsePackageSpecifier","resolveRegistryToken","satisfiesRange"]);defineLazyExports(()=>(init_job(),__toCommonJS(job_exports)),["JobRegistry","JobInstance","JobPermissionGuard","JobExecutionManager","JobAdmission","JobEmitter","JobRunResource","jobRunUri","mayAccessRun"]);defineLazyExports(()=>(init_tools(),__toCommonJS(tools_exports)),["ExecuteJobTool","GetJobStatusTool","CancelJobTool","ListJobsTool","RegisterJobTool","RemoveJobTool","UpdateJobTool"]);defineLazyExports(()=>(init_workflow(),__toCommonJS(workflow_exports)),["WorkflowRegistry","WorkflowInstance","WorkflowEngine","WorkflowStepExecutor","WorkflowEmitter"]);defineLazyExports(()=>(init_tools2(),__toCommonJS(tools_exports2)),["ExecuteWorkflowTool","GetWorkflowStatusTool","ListWorkflowsTool","RegisterWorkflowTool","RemoveWorkflowTool","UpdateWorkflowTool"]);defineLazyExports(()=>(init_streamable_http_transport(),__toCommonJS(streamable_http_transport_exports)),["RecreateableStreamableHTTPServerTransport"]);defineLazyExports(()=>(init_sse_transport(),__toCommonJS(sse_transport_exports)),["RecreateableSSEServerTransport"]);defineLazyExports(()=>(init_node_sse_transport(),__toCommonJS(node_sse_transport_exports)),["SSEServerTransport"]);defineLazyExports(()=>(init_event_stores(),__toCommonJS(event_stores_exports)),["createEventStore","MemoryEventStore","RedisEventStore"]);defineLazyExports(()=>(init_channel(),__toCommonJS(channel_exports)),["ChannelInstance","ChannelRegistry","ChannelEmitter","ChannelNotificationService","ChannelEventBus","ChannelReplyTool"]);defineLazyExports(()=>(init_event(),__toCommonJS(event_exports)),["EventInstance","EventRegistry","MAX_OPEN_STREAMS","MAX_POLL_LEASES","POLL_LEASE_INTERVALS","POLL_LEASE_MIN_MS","POLL_LEASE_SWEEP_INTERVAL_MS","SUBSCRIPTION_SWEEP_INTERVAL_MS","SUSPEND_AFTER_FAILURES","pollLeaseMs"])}}});var index_exports={};__export(index_exports,{ANSWER_COUNTERS:()=>ANSWER_COUNTERS,Adapter:()=>FrontMcpAdapter,AdapterEntry:()=>AdapterEntry,AdapterKind:()=>AdapterKind,Agent:()=>Agent2,AgentCallDepthExceededError:()=>AgentCallDepthExceededError,AgentCallHook:()=>AgentCallHook,AgentConfigKeyNotFoundError:()=>AgentConfigKeyNotFoundError,AgentConfigurationError:()=>AgentConfigurationError,AgentContext:()=>AgentContext,AgentEntry:()=>AgentEntry,AgentExecutionError:()=>AgentExecutionError,AgentKind:()=>AgentKind,AgentLlmError:()=>AgentLlmError,AgentLoopExceededError:()=>AgentLoopExceededError,AgentMethodNotAvailableError:()=>AgentMethodNotAvailableError,AgentNotConfiguredError:()=>AgentNotConfiguredError,AgentNotFoundError:()=>AgentNotFoundError,AgentTimeoutError:()=>AgentTimeoutError,AgentToolExecutionError:()=>AgentToolExecutionError,AgentToolNotFoundError:()=>AgentToolNotFoundError,AgentVisibilityError:()=>AgentVisibilityError,AnthropicAdapter:()=>AnthropicAdapter,App:()=>App,AppEntry:()=>AppEntry,AppKind:()=>AppKind,AroundHookOf:()=>AroundHookOf,AsyncAuthProvider:()=>AsyncAuthProvider,AsyncProvider:()=>AsyncProvider,AudioOutputSchema:()=>AudioOutputSchema,Auth:()=>FrontMcpAuth,AuthConfigurationError:()=>AuthConfigurationError,AuthHookStage:()=>AuthHookStage,AuthProvider:()=>FrontMcpAuthProvider,AuthProviderEntry:()=>AuthProviderEntry,AuthProviderKind:()=>AuthProviderKind,AuthProviderScope:()=>AuthProviderScope,AuthProvidersNotConfiguredError:()=>import_auth16.AuthProvidersNotConfiguredError,AuthorizationRequiredError:()=>AuthorizationRequiredError,BUDGET_LIST_POLICIES:()=>BUDGET_LIST_POLICIES,BUDGET_META_KEY:()=>BUDGET_META_KEY,BaseConfig:()=>BaseConfig,BaseEntry:()=>BaseEntry,BrowserEntryPointUnavailableError:()=>BrowserEntryPointUnavailableError,BrowserStoreUnavailableError:()=>BrowserStoreUnavailableError,CallRecorderConfigurationError:()=>CallRecorderConfigurationError,CallRecorderPlugin:()=>CallRecorderPlugin,CancelJobTool:()=>import_subsystems4.CancelJobTool,CapabilityCache:()=>import_subsystems.CapabilityCache,Channel:()=>Channel,ChannelContext:()=>ChannelContext,ChannelEmitter:()=>import_subsystems7.ChannelEmitter,ChannelEntry:()=>ChannelEntry,ChannelEventBus:()=>import_subsystems7.ChannelEventBus,ChannelInstance:()=>import_subsystems7.ChannelInstance,ChannelKind:()=>ChannelKind,ChannelListHook:()=>ChannelListHook,ChannelNotificationService:()=>import_subsystems7.ChannelNotificationService,ChannelRegistry:()=>import_subsystems7.ChannelRegistry,ChannelReplyTool:()=>import_subsystems7.ChannelReplyTool,ChannelSendHook:()=>ChannelSendHook,CircuitBreaker:()=>import_subsystems.CircuitBreaker,CircuitBreakerManager:()=>import_subsystems.CircuitBreakerManager,CircuitOpenError:()=>import_subsystems.CircuitOpenError,CliTaskRunner:()=>CliTaskRunner,ClusterScopeNeedsRedisError:()=>ClusterScopeNeedsRedisError,CompletionHook:()=>CompletionHook,ConfigMissingError:()=>ConfigMissingError,ConfigNotFoundError:()=>ConfigNotFoundError,ConfigPlugin:()=>ConfigPlugin,ConfigPluginConfigToken:()=>ConfigPluginConfigToken,ConfigService:()=>ConfigService,ConfigValidationError:()=>ConfigValidationError,ContainerDisposedError:()=>ContainerDisposedError,ContainerProviderScopeError:()=>ContainerProviderScopeError,Context:()=>FrontMcpContext,ContextExtensionNotAvailableError:()=>ContextExtensionNotAvailableError,CredentialProviderAlreadyRegisteredError:()=>import_auth16.CredentialProviderAlreadyRegisteredError,CrossOriginRequestError:()=>CrossOriginRequestError,DEFAULT_ELICITATION_OPTIONS:()=>DEFAULT_ELICITATION_OPTIONS,DEFAULT_ELICIT_TTL:()=>DEFAULT_ELICIT_TTL,DEFAULT_FALLBACK_WAIT_TTL:()=>DEFAULT_FALLBACK_WAIT_TTL,DEFAULT_HEALTH_OPTIONS:()=>DEFAULT_HEALTH_OPTIONS,DEFAULT_INSTRUCTIONS_BUDGET:()=>DEFAULT_INSTRUCTIONS_BUDGET,DEFAULT_METRICS_OPTIONS:()=>DEFAULT_METRICS_OPTIONS,DEFAULT_NPM_REGISTRY:()=>import_subsystems2.DEFAULT_NPM_REGISTRY,DEFAULT_OUTPUT_SCHEMA_MODE:()=>DEFAULT_OUTPUT_SCHEMA_MODE,DEFAULT_QUESTION_TTL_MS:()=>DEFAULT_QUESTION_TTL_MS,DEFAULT_REGISTRY_PUBLIC_KEY_ENV:()=>DEFAULT_REGISTRY_PUBLIC_KEY_ENV,DEFAULT_SCHEMA_DESCRIPTION_FORMAT:()=>DEFAULT_SCHEMA_DESCRIPTION_FORMAT,DEFAULT_TOOL_PAGINATION:()=>DEFAULT_TOOL_PAGINATION,DependencyCycleError:()=>DependencyCycleError,DependencyNotFoundError:()=>DependencyNotFoundError,DidHookOf:()=>DidHookOf,DuplicateAppIdError:()=>DuplicateAppIdError,DuplicateEventSubscriptionError:()=>DuplicateEventSubscriptionError,DuplicatePluginEntryError:()=>DuplicatePluginEntryError,DuplicatePluginError:()=>DuplicatePluginError,Duty:()=>Duty,DutyLeaseKeyError:()=>DutyLeaseKeyError,DutyNameConflictError:()=>DutyNameConflictError,DynamicAdapter:()=>DynamicAdapter,DynamicAdapterNameError:()=>DynamicAdapterNameError,DynamicJobDirectExecutionError:()=>DynamicJobDirectExecutionError,DynamicJobRegistrationDisabledError:()=>DynamicJobRegistrationDisabledError,DynamicPlugin:()=>DynamicPlugin,ELICITATION_FALLBACK_JSON_SCHEMA:()=>ELICITATION_FALLBACK_JSON_SCHEMA,ESM_SH_BASE_URL:()=>import_subsystems2.ESM_SH_BASE_URL,EVENTS_EXTENSION_ID:()=>import_protocol87.EVENTS_EXTENSION_ID,EVENT_NAME_MAX_LENGTH:()=>EVENT_NAME_MAX_LENGTH,EVENT_PUBLISHER:()=>EVENT_PUBLISHER,EXT_APPS_ERROR_CODES:()=>EXT_APPS_ERROR_CODES,ElicitationDisabledError:()=>ElicitationDisabledError,ElicitationEncryptionError:()=>ElicitationEncryptionError,ElicitationFallbackRequired:()=>ElicitationFallbackRequired,ElicitationNotOwnedError:()=>ElicitationNotOwnedError,ElicitationNotSupportedError:()=>ElicitationNotSupportedError,ElicitationSecretRequiredError:()=>import_auth16.ElicitationSecretRequiredError,ElicitationStoreNotInitializedError:()=>ElicitationStoreNotInitializedError,ElicitationSubscriptionError:()=>ElicitationSubscriptionError,ElicitationTimeoutError:()=>ElicitationTimeoutError,EnclaveExecutionError:()=>EnclaveExecutionError,EncryptedElicitationStore:()=>EncryptedElicitationStore,EncryptionContextNotSetError:()=>import_auth16.EncryptionContextNotSetError,EncryptionKeyNotConfiguredError:()=>import_auth16.EncryptionKeyNotConfiguredError,EntryUnavailableError:()=>EntryUnavailableError,EntryValidationError:()=>EntryValidationError,ErrorHandler:()=>ErrorHandler,EsmCacheError:()=>EsmCacheError,EsmCacheManager:()=>import_subsystems2.EsmCacheManager,EsmInvalidSpecifierError:()=>EsmInvalidSpecifierError,EsmManifestInvalidError:()=>EsmManifestInvalidError,EsmModuleLoader:()=>import_subsystems2.EsmModuleLoader,EsmPackageLoadError:()=>EsmPackageLoadError,EsmRegistryAuthError:()=>EsmRegistryAuthError,EsmVersionResolutionError:()=>EsmVersionResolutionError,Event:()=>Event,EventCallbackEndpointError:()=>EventCallbackEndpointError,EventContext:()=>EventContext,EventDeliverHook:()=>EventDeliverHook,EventEndedHook:()=>EventEndedHook,EventEntry:()=>EventEntry,EventForbiddenError:()=>EventForbiddenError,EventInstance:()=>import_subsystems8.EventInstance,EventKind:()=>EventKind,EventNameConflictError:()=>EventNameConflictError,EventNotFoundError:()=>EventNotFoundError,EventNotRegisteredError:()=>EventNotRegisteredError,EventPollHook:()=>EventPollHook,EventProtocolError:()=>EventProtocolError,EventPublishEndpointError:()=>EventPublishEndpointError,EventPublishHook:()=>EventPublishHook,EventPublishHttpHook:()=>EventPublishHttpHook,EventPublisher:()=>EventPublisher,EventRegistry:()=>import_subsystems8.EventRegistry,EventRequestError:()=>EventRequestError,EventResourceExhaustedError:()=>EventResourceExhaustedError,EventStreamHook:()=>EventStreamHook,EventSubscribeHook:()=>EventSubscribeHook,EventSubscriptionStoreError:()=>EventSubscriptionStoreError,EventSubscriptionTerminatedError:()=>EventSubscriptionTerminatedError,EventUnsubscribeHook:()=>EventUnsubscribeHook,EventUnsupportedError:()=>EventUnsupportedError,EventsClient:()=>EventsClient,EventsNotEnabledError:()=>EventsNotEnabledError,ExecuteJobTool:()=>import_subsystems4.ExecuteJobTool,ExecuteWorkflowTool:()=>import_subsystems6.ExecuteWorkflowTool,ExecutionContextBase:()=>ExecutionContextBase,ExtAppsError:()=>ExtAppsError,ExtAppsInvalidParamsError:()=>ExtAppsInvalidParamsError,ExtAppsMessageHandler:()=>ExtAppsMessageHandler,ExtAppsMethodNotFoundError:()=>ExtAppsMethodNotFoundError,ExtAppsNotSupportedError:()=>ExtAppsNotSupportedError,ExtAppsToolNotFoundError:()=>ExtAppsToolNotFoundError,ExternalEntryError:()=>ExternalEntryError,ExternalEntryLoadError:()=>ExternalEntryLoadError,ExternalEntryNotFoundError:()=>ExternalEntryNotFoundError,ExternalEntryNotSupportedError:()=>ExternalEntryNotSupportedError,ExternalSkillProviderBase:()=>ExternalSkillProviderBase,FRONTMCP_CONFIG_METADATA_KEY:()=>FRONTMCP_CONFIG_METADATA_KEY,FRONTMCP_CONTEXT:()=>FRONTMCP_CONTEXT,FRONTMCP_LOGGER:()=>FRONTMCP_LOGGER,FRONTMCP_SUPPORTED_PROTOCOL_VERSIONS:()=>FRONTMCP_SUPPORTED_PROTOCOL_VERSIONS,FeatureOffError:()=>FeatureOffError,FinallyHookOf:()=>FinallyHookOf,Flow:()=>FrontMcpFlow,FlowBase:()=>FlowBase,FlowControl:()=>FlowControl,FlowEntry:()=>FlowEntry,FlowExitedWithoutOutputError:()=>FlowExitedWithoutOutputError,FlowHooksOf:()=>FlowHooksOf,FlowInputMissingError:()=>FlowInputMissingError,FlowKind:()=>FlowKind,FlowNotRegisteredError:()=>FlowNotRegisteredError,FrontMcp:()=>FrontMcp,FrontMcpAdapter:()=>FrontMcpAdapter,FrontMcpAdapterTokens:()=>FrontMcpAdapterTokens,FrontMcpAgent:()=>FrontMcpAgent,FrontMcpAgentTokens:()=>FrontMcpAgentTokens,FrontMcpApp:()=>FrontMcpApp,FrontMcpAuth:()=>FrontMcpAuth,FrontMcpAuthProvider:()=>FrontMcpAuthProvider,FrontMcpAuthProviderTokens:()=>FrontMcpAuthProviderTokens,FrontMcpChannelTokens:()=>FrontMcpChannelTokens,FrontMcpConfig:()=>FrontMcpConfig,FrontMcpContext:()=>FrontMcpContext,FrontMcpContextProvider:()=>FrontMcpContextProvider,FrontMcpContextStorage:()=>FrontMcpContextStorage,FrontMcpEvent:()=>FrontMcpEvent,FrontMcpEventTokens:()=>FrontMcpEventTokens,FrontMcpFlow:()=>FrontMcpFlow,FrontMcpFlowHookTokens:()=>FrontMcpFlowHookTokens,FrontMcpFlowTokens:()=>FrontMcpFlowTokens,FrontMcpInstance:()=>FrontMcpInstance,FrontMcpJob:()=>FrontMcpJob,FrontMcpJobTokens:()=>FrontMcpJobTokens,FrontMcpLocalAppTokens:()=>FrontMcpLocalAppTokens,FrontMcpLogTransport:()=>FrontMcpLogTransport,FrontMcpLogTransportTokens:()=>FrontMcpLogTransportTokens,FrontMcpLogger:()=>FrontMcpLogger,FrontMcpPlugin:()=>FrontMcpPlugin,FrontMcpPluginTokens:()=>FrontMcpPluginTokens,FrontMcpPrompt:()=>FrontMcpPrompt,FrontMcpPromptTokens:()=>FrontMcpPromptTokens,FrontMcpProvider:()=>FrontMcpProvider,FrontMcpProviderTokens:()=>FrontMcpProviderTokens,FrontMcpRemoteAppTokens:()=>FrontMcpRemoteAppTokens,FrontMcpResource:()=>FrontMcpResource,FrontMcpResourceTemplate:()=>FrontMcpResourceTemplate,FrontMcpResourceTemplateTokens:()=>FrontMcpResourceTemplateTokens,FrontMcpResourceTokens:()=>FrontMcpResourceTokens,FrontMcpServer:()=>FrontMcpServer,FrontMcpSkill:()=>FrontMcpSkill,FrontMcpSkillTokens:()=>FrontMcpSkillTokens,FrontMcpTokens:()=>FrontMcpTokens,FrontMcpTool:()=>FrontMcpTool,FrontMcpToolTokens:()=>FrontMcpToolTokens,FrontMcpWorkflow:()=>FrontMcpWorkflow,FrontMcpWorkflowTokens:()=>FrontMcpWorkflowTokens,GLOBAL_RATE_LIMIT_CHECKED:()=>GLOBAL_RATE_LIMIT_CHECKED,GenericServerError:()=>GenericServerError,GetJobStatusTool:()=>import_subsystems4.GetJobStatusTool,GetWorkflowStatusTool:()=>import_subsystems6.GetWorkflowStatusTool,GlobalConfigNotFoundError:()=>GlobalConfigNotFoundError,GuardLimitMcpError:()=>GuardLimitMcpError,HOOK_OBSERVER_KEY:()=>HOOK_OBSERVER_KEY,HOOK_TRACE_META_KEY:()=>HOOK_TRACE_META_KEY,HTTP_ROUTE_PATH_MESSAGE:()=>HTTP_ROUTE_PATH_MESSAGE,HaConfigurationError:()=>HaConfigurationError,HealthCheckManager:()=>import_subsystems.HealthCheckManager,HealthChecker:()=>import_subsystems.HealthChecker,HookEntry:()=>HookEntry,HookKind:()=>HookKind,HookOrderCycleError:()=>HookOrderCycleError,HookPhase:()=>HookPhase,HookTargetNotDefinedError:()=>HookTargetNotDefinedError,HostServerAdapter:()=>HostServerAdapter,HttpBinarySchema:()=>HttpBinarySchema,HttpConsumedSchema:()=>HttpConsumedSchema,HttpCookieSchema:()=>HttpCookieSchema,HttpCookies:()=>HttpCookies,HttpEmptySchema:()=>HttpEmptySchema,HttpEmptyStatus:()=>HttpEmptyStatus,HttpHeaders:()=>HttpHeaders,HttpHook:()=>HttpHook,HttpHtmlSchema:()=>HttpHtmlSchema,HttpImageSchema:()=>HttpImageSchema,HttpJsonRpcSchema:()=>HttpJsonRpcSchema,HttpJsonSchema:()=>HttpJsonSchema,HttpNextSchema:()=>HttpNextSchema,HttpProblemSchema:()=>HttpProblemSchema,HttpRedirectSchema:()=>HttpRedirectSchema,HttpRedirectStatus:()=>HttpRedirectStatus,HttpRoute:()=>HttpRoute,HttpRouteContext:()=>HttpRouteContext,HttpRouteHook:()=>HttpRouteHook,HttpSseSchema:()=>HttpSseSchema,HttpStatus:()=>HttpStatus,HttpStreamSchema:()=>HttpStreamSchema,HttpTextSchema:()=>HttpTextSchema,HttpWebResponseSchema:()=>HttpWebResponseSchema,IP_FILTER_REJECTION_BODY:()=>IP_FILTER_REJECTION_BODY,ImageOutputSchema:()=>ImageOutputSchema,InMemoryOrchestratedTokenStore:()=>import_auth94.InMemoryOrchestratedTokenStore,InMemoryStoreRequiredError:()=>import_auth16.InMemoryStoreRequiredError,InProcessTaskRunner:()=>InProcessTaskRunner,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,InvalidQuestionStoreError:()=>InvalidQuestionStoreError,InvalidRegistryKindError:()=>InvalidRegistryKindError,InvalidResourceStoreError:()=>InvalidResourceStoreError,InvalidResourceUriError:()=>InvalidResourceUriError,InvalidRetryOptionsError:()=>InvalidRetryOptionsError,InvalidSharedServerOptionsError:()=>InvalidSharedServerOptionsError,InvalidSkillError:()=>InvalidSkillError,InvalidToolUiConfigError:()=>InvalidToolUiConfigError,InvalidTransportSessionError:()=>InvalidTransportSessionError,InvalidUseClassError:()=>InvalidUseClassError,InvalidUseFactoryError:()=>InvalidUseFactoryError,InvalidUseValueError:()=>InvalidUseValueError,InvokeStateMissingKeyError:()=>InvokeStateMissingKeyError,JOB_WORKER_MARKER:()=>JOB_WORKER_MARKER,JSON_RPC:()=>JSON_RPC,Job:()=>Job,JobAdmission:()=>import_subsystems3.JobAdmission,JobAdmissionLostError:()=>JobAdmissionLostError,JobAdmissionTimeoutError:()=>JobAdmissionTimeoutError,JobCancelledError:()=>JobCancelledError,JobContext:()=>JobContext,JobEmitter:()=>import_subsystems3.JobEmitter,JobEntry:()=>JobEntry,JobExecutionManager:()=>import_subsystems3.JobExecutionManager,JobHook:()=>JobHook,JobInstance:()=>import_subsystems3.JobInstance,JobInterruptedError:()=>JobInterruptedError,JobKind:()=>JobKind,JobNotAuthorizedError:()=>JobNotAuthorizedError,JobPermissionGuard:()=>import_subsystems3.JobPermissionGuard,JobRegistry:()=>import_subsystems3.JobRegistry,JobRunFinishedError:()=>JobRunFinishedError,JobRunNotCancellableError:()=>JobRunNotCancellableError,JobRunNotFoundError:()=>JobRunNotFoundError,JobRunResource:()=>import_subsystems3.JobRunResource,JobRunnerBootError:()=>JobRunnerBootError,JobRunnerBusyError:()=>JobRunnerBusyError,JobRunnerUnavailableError:()=>JobRunnerUnavailableError,JobStoreNotSupportedError:()=>JobStoreNotSupportedError,JobTimeoutError:()=>JobTimeoutError,JwtSecretRequiredError:()=>import_auth16.JwtSecretRequiredError,JwtSecretWeakError:()=>import_auth16.JwtSecretWeakError,LLM_ADAPTER:()=>LLM_ADAPTER,LazyAppConfigurationError:()=>LazyAppConfigurationError,LazyAppLoadError:()=>LazyAppLoadError,LazyZodSchema:()=>import_lazy_zod164.LazyZodSchema,ListEventsHook:()=>ListEventsHook,ListJobsTool:()=>import_subsystems4.ListJobsTool,ListPromptsHook:()=>ListPromptsHook,ListResourceTemplatesHook:()=>ListResourceTemplatesHook,ListResourcesHook:()=>ListResourcesHook,ListToolsHook:()=>ListToolsHook,ListWorkflowsTool:()=>import_subsystems6.ListWorkflowsTool,LogLevel:()=>LogLevel,LogLevelName:()=>LogLevelName,LogTransport:()=>FrontMcpLogTransport,LogTransportInterface:()=>LogTransportInterface,LoggerEntry:()=>LoggerEntry,LoggerKind:()=>LoggerKind,LoggerRegistry:()=>LoggerRegistry,LoopbackTokenAuth:()=>import_auth93.LoopbackTokenAuth,MANIFEST_PRIMITIVE_KEYS:()=>import_subsystems2.MANIFEST_PRIMITIVE_KEYS,MATERIALIZED_META_KEY:()=>MATERIALIZED_META_KEY,MAX_CONCURRENT_TASKS_PER_SESSION:()=>MAX_CONCURRENT_TASKS_PER_SESSION,MAX_JOB_TIMER_MS:()=>MAX_JOB_TIMER_MS,MAX_OPEN_STREAMS:()=>import_subsystems8.MAX_OPEN_STREAMS,MAX_POLL_LEASES:()=>import_subsystems8.MAX_POLL_LEASES,MCP_ERROR_CODES:()=>MCP_ERROR_CODES,MIN_OUTPUT_BUDGET_BYTES:()=>MIN_OUTPUT_BUDGET_BYTES,MaterializedResourceContext:()=>MaterializedResourceContext,McpClientService:()=>import_subsystems.McpClientService,McpError:()=>McpError,McpStatelessClient:()=>McpStatelessClient,McpStatelessClientAdapter:()=>import_subsystems9.McpStatelessClientAdapter,McpStatelessError:()=>McpStatelessError,MemoryEventStore:()=>import_subsystems10.MemoryEventStore,MemorySkillProvider:()=>MemorySkillProvider,MethodNotImplementedError:()=>MethodNotImplementedError,MissingClientCapabilityError:()=>MissingClientCapabilityError,MissingPromptArgumentError:()=>MissingPromptArgumentError,MissingProvideError:()=>MissingProvideError,NEVER:()=>import_lazy_zod164.NEVER,NO_BODY_STATUSES:()=>NO_BODY_STATUSES,NO_STORE_HEADERS:()=>NO_STORE_HEADERS,NameDisambiguationError:()=>NameDisambiguationError,NoCompatibleDeliveryModeError:()=>NoCompatibleDeliveryModeError,NoProviderIdError:()=>import_auth16.NoProviderIdError,OAuthAuthorizeHook:()=>OAuthAuthorizeHook,OAuthCallbackHook:()=>OAuthCallbackHook,OAuthRegisterHook:()=>OAuthRegisterHook,OAuthTokenHook:()=>OAuthTokenHook,OUTPUT_SCHEMA_MODES:()=>OUTPUT_SCHEMA_MODES,OffloadAbortedError:()=>OffloadAbortedError,OffloadBudgetExceededError:()=>OffloadBudgetExceededError,OffloadNotCloneableError:()=>OffloadNotCloneableError,OffloadUnsupportedRuntimeError:()=>OffloadUnsupportedRuntimeError,OffloadWorkerError:()=>OffloadWorkerError,OpenAIAdapter:()=>OpenAIAdapter,OrchestratedAuthNotAvailableError:()=>import_auth16.OrchestratedAuthNotAvailableError,OrchestratorJwksNotAvailableError:()=>import_auth16.OrchestratorJwksNotAvailableError,PEOPLE_SESSION_COOKIE:()=>import_auth93.PEOPLE_SESSION_COOKIE,PLATFORM_CLIENT_INFO:()=>PLATFORM_CLIENT_INFO,POLL_LEASE_INTERVALS:()=>import_subsystems8.POLL_LEASE_INTERVALS,POLL_LEASE_MIN_MS:()=>import_subsystems8.POLL_LEASE_MIN_MS,POLL_LEASE_SWEEP_INTERVAL_MS:()=>import_subsystems8.POLL_LEASE_SWEEP_INTERVAL_MS,PRIMITIVE_FILTER_KEYS:()=>PRIMITIVE_FILTER_KEYS,PROTOCOL_2026_07_28:()=>import_protocol88.PROTOCOL_2026_07_28,PROTOCOL_PRESETS:()=>PROTOCOL_PRESETS,PayloadTooLargeError:()=>PayloadTooLargeError,PersonNotSignedInError:()=>PersonNotSignedInError,Plugin:()=>FrontMcpPlugin,PluginConfiguredTwiceError:()=>PluginConfiguredTwiceError,PluginDependencyError:()=>PluginDependencyError,PluginEntry:()=>PluginEntry,PluginKind:()=>PluginKind,Prompt:()=>Prompt,PromptContext:()=>PromptContext,PromptEntry:()=>PromptEntry,PromptExecutionError:()=>PromptExecutionError,PromptHook:()=>PromptHook2,PromptKind:()=>PromptKind,PromptNotFoundError:()=>PromptNotFoundError,Provider:()=>FrontMcpProvider,ProviderBootstrapError:()=>ProviderBootstrapError,ProviderConstructionError:()=>ProviderConstructionError,ProviderDependencyError:()=>ProviderDependencyError,ProviderEntry:()=>ProviderEntry,ProviderKind:()=>import_di13.ProviderKind,ProviderNotAvailableError:()=>ProviderNotAvailableError,ProviderNotInstantiatedError:()=>ProviderNotInstantiatedError,ProviderNotRegisteredError:()=>ProviderNotRegisteredError,ProviderRegistry:()=>ProviderRegistry,ProviderScope:()=>import_di4.ProviderScope,ProviderScopeMismatchError:()=>ProviderScopeMismatchError,ProviderScopedAccessError:()=>ProviderScopedAccessError,PublicAccessDeniedError:()=>PublicAccessDeniedError,PublicMcpError:()=>PublicMcpError,QUESTIONS_PATH:()=>QUESTIONS_PATH,QUESTIONS_TOPIC:()=>QUESTIONS_TOPIC,QUESTION_INBOX_PATH:()=>QUESTION_INBOX_PATH,QuestionAlreadyAnsweredError:()=>QuestionAlreadyAnsweredError,QuestionNotFoundError:()=>QuestionNotFoundError,QuestionPendingError:()=>QuestionPendingError,QuestionStore:()=>QuestionStore,QuestionStoreBusyError:()=>QuestionStoreBusyError,QuestionSupersededError:()=>QuestionSupersededError,QuotaExceededError:()=>QuotaExceededError,REDIRECTS:()=>REDIRECTS,REGISTRY_SERVER_NAME_PATTERN:()=>REGISTRY_SERVER_NAME_PATTERN,RELATED_TASK_META_KEY:()=>RELATED_TASK_META_KEY,RUN_TASK_ENV_VAR:()=>RUN_TASK_ENV_VAR,RUN_TASK_SUBCOMMAND:()=>RUN_TASK_SUBCOMMAND,RateLimitError:()=>RateLimitError,RecreateableSSEServerTransport:()=>import_subsystems10.RecreateableSSEServerTransport,RecreateableStreamableHTTPServerTransport:()=>import_subsystems10.RecreateableStreamableHTTPServerTransport,RedisEventStore:()=>import_subsystems10.RedisEventStore,RegisterJobTool:()=>import_subsystems4.RegisterJobTool,RegisterWorkflowTool:()=>import_subsystems6.RegisterWorkflowTool,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,RemoveJobTool:()=>import_subsystems4.RemoveJobTool,RemoveWorkflowTool:()=>import_subsystems6.RemoveWorkflowTool,RequestContextNotAvailableError:()=>RequestContextNotAvailableError,RequiredConfigUndefinedError:()=>RequiredConfigUndefinedError,ReservedAppIdError:()=>ReservedAppIdError,Resource:()=>Resource,ResourceContext:()=>ResourceContext,ResourceEntry:()=>ResourceEntry,ResourceHook:()=>ResourceHook2,ResourceKind:()=>ResourceKind,ResourceLinkOutputSchema:()=>ResourceLinkOutputSchema,ResourceNotFoundError:()=>ResourceNotFoundError,ResourceOutputSchema:()=>ResourceOutputSchema,ResourceReadError:()=>ResourceReadError,ResourceStore:()=>ResourceStore,ResourceTemplate:()=>_ResourceTemplate,ResourceTemplateKind:()=>ResourceTemplateKind,SCHEMA_DESCRIPTION_FORMATS:()=>SCHEMA_DESCRIPTION_FORMATS,SERVER_MANIFEST_FILE:()=>SERVER_MANIFEST_FILE,SERVER_MANIFEST_VERSION:()=>SERVER_MANIFEST_VERSION,SSEServerTransport:()=>import_subsystems10.SSEServerTransport,STATELESS_SESSION_ID:()=>STATELESS_SESSION_ID,SUBSCRIPTION_SWEEP_INTERVAL_MS:()=>import_subsystems8.SUBSCRIPTION_SWEEP_INTERVAL_MS,SURFACE_META_KEY:()=>SURFACE_META_KEY,SUSPEND_AFTER_FAILURES:()=>import_subsystems8.SUSPEND_AFTER_FAILURES,SamplingNotAvailableError:()=>SamplingNotAvailableError,ScopeConfigurationError:()=>ScopeConfigurationError,ScopeDeniedError:()=>import_auth16.ScopeDeniedError,ScopeEntry:()=>ScopeEntry,ScopeKind:()=>ScopeKind,ServerNotFoundError:()=>ServerNotFoundError,ServerRequest:()=>ServerRequest,ServerRequestTokens:()=>ServerRequestTokens,ServerResponse:()=>ServerResponse,ServerlessHandlerNotInitializedError:()=>ServerlessHandlerNotInitializedError,SessionClaimConflictError:()=>SessionClaimConflictError,SessionEndUnconfirmedError:()=>SessionEndUnconfirmedError,SessionHookStage:()=>SessionHookStage,SessionIdEmptyError:()=>import_auth16.SessionIdEmptyError,SessionIdentityRequiredError:()=>SessionIdentityRequiredError,SessionLimitReachedError:()=>SessionLimitReachedError,SessionMissingError:()=>SessionMissingError,SessionOwnerUnreachableError:()=>SessionOwnerUnreachableError,SessionSecretRequiredError:()=>import_auth16.SessionSecretRequiredError,SessionVerificationFailedError:()=>SessionVerificationFailedError,SharedServerIdentityError:()=>SharedServerIdentityError,SharedServerStartError:()=>SharedServerStartError,SignInLockedError:()=>SignInLockedError,SignInRefusedError:()=>SignInRefusedError,SigningKeyInvalidError:()=>import_auth16.SigningKeyInvalidError,Skill:()=>Skill,SkillBundleNotLoadedError:()=>SkillBundleNotLoadedError,SkillCatalogSourceToken:()=>SkillCatalogSourceToken,SkillContext:()=>SkillContext,SkillContextNotImplementedError:()=>SkillContextNotImplementedError,SkillEmitter:()=>SkillEmitter,SkillEntry:()=>SkillEntry,SkillHttpAuthValidator:()=>SkillHttpAuthValidator,SkillInstance:()=>SkillInstance,SkillInstructionFetchError:()=>SkillInstructionFetchError,SkillKind:()=>SkillKind,SkillRegistry:()=>SkillRegistry,SkillSessionError:()=>SkillSessionError,SkillToolValidator:()=>SkillToolValidator,SkillValidationError:()=>SkillValidationError,SocketInUseError:()=>SocketInUseError,SocketPathConflictError:()=>SocketPathConflictError,SocketPermissionError:()=>SocketPermissionError,SqliteStorageToken:()=>SqliteStorageToken,StageHookOf:()=>StageHookOf,StaleToolListError:()=>StaleToolListError,StorageElicitationStore:()=>StorageElicitationStore,StorageTaskStore:()=>StorageTaskStore,StoreNotOpenedInBuildError:()=>StoreNotOpenedInBuildError,TASKS_CLIENT_CAPABILITY:()=>TASKS_CLIENT_CAPABILITY,TASKS_EXTENSION_ID:()=>TASKS_EXTENSION_ID,TASK_DEFAULTS:()=>TASK_DEFAULTS,TASK_WORKER_MARKER:()=>TASK_WORKER_MARKER,TASK_WORKER_MODE_FLAG:()=>TASK_WORKER_MODE_FLAG,TaskAlreadyTerminalError:()=>TaskAlreadyTerminalError,TaskAugmentationNotSupportedError:()=>TaskAugmentationNotSupportedError,TaskAugmentationRequiredError:()=>TaskAugmentationRequiredError,TaskConcurrencyLimitError:()=>TaskConcurrencyLimitError,TaskNotFoundError:()=>TaskNotFoundError,TaskNotifier:()=>TaskNotifier,TaskRegistry:()=>TaskRegistry,TaskStoreNotInitializedError:()=>TaskStoreNotInitializedError,TaskStoreNotSupportedError:()=>TaskStoreNotSupportedError,TasksCancelFlow:()=>TasksCancelFlow,TasksGetFlow:()=>TasksGetFlow,TasksListFlow:()=>TasksListFlow,TasksResultFlow:()=>TasksResultFlow,TokenLeakDetectedError:()=>import_auth16.TokenLeakDetectedError,TokenNotAvailableError:()=>import_auth16.TokenNotAvailableError,TokenStoreRequiredError:()=>import_auth16.TokenStoreRequiredError,Tool:()=>Tool,ToolAliasConflictError:()=>ToolAliasConflictError,ToolCallError:()=>ToolCallError,ToolContext:()=>ToolContext,ToolCredentialsRequiredError:()=>ToolCredentialsRequiredError,ToolEntry:()=>ToolEntry,ToolExecutionError:()=>ToolExecutionError,ToolHook:()=>ToolHook2,ToolHookStage:()=>ToolHookStage,ToolInstance:()=>ToolInstance,ToolKind:()=>ToolKind,ToolNameConflictError:()=>ToolNameConflictError,ToolNotConsentedError:()=>ToolNotConsentedError,ToolNotFoundError:()=>ToolNotFoundError,ToolRegistry:()=>ToolRegistry,ToolUiConfigurationError:()=>ToolUiConfigurationError,TransportAlreadyStartedError:()=>TransportAlreadyStartedError,TransportBusRequiredError:()=>TransportBusRequiredError,TransportNotConnectedError:()=>TransportNotConnectedError,TransportServiceNotAvailableError:()=>TransportServiceNotAvailableError,UNDECLARED_KEYS_POLICIES:()=>UNDECLARED_KEYS_POLICIES,UnauthorizedError:()=>UnauthorizedError,UnenforcedMetadataError:()=>UnenforcedMetadataError,UnsafeDutyStoreError:()=>UnsafeDutyStoreError,UnsafeSharedServerDirectoryError:()=>UnsafeSharedServerDirectoryError,UnsafeSocketDirectoryError:()=>UnsafeSocketDirectoryError,UnsupportedClientVersionError:()=>UnsupportedClientVersionError,UnsupportedContentTypeError:()=>UnsupportedContentTypeError,UnsupportedHookOwnerKindError:()=>UnsupportedHookOwnerKindError,UnsupportedTransportTypeError:()=>UnsupportedTransportTypeError,UpdateJobTool:()=>import_subsystems4.UpdateJobTool,UpdateWorkflowTool:()=>import_subsystems6.UpdateWorkflowTool,UserContentConfigurationError:()=>UserContentConfigurationError,VaultLoadError:()=>import_auth16.VaultLoadError,VaultNotFoundError:()=>import_auth16.VaultNotFoundError,VercelKvAsyncInitRequiredError:()=>VercelKvAsyncInitRequiredError,VercelKvNotSupportedError:()=>VercelKvNotSupportedError,VersionPoller:()=>import_subsystems2.VersionPoller,VersionResolver:()=>import_subsystems2.VersionResolver,WillHookOf:()=>WillHookOf,Worker:()=>Worker,WorkerNameConflictError:()=>WorkerNameConflictError,Workflow:()=>FrontMcpWorkflow,WorkflowContext:()=>WorkflowContext,WorkflowDagValidationError:()=>WorkflowDagValidationError,WorkflowEmitter:()=>import_subsystems5.WorkflowEmitter,WorkflowEngine:()=>import_subsystems5.WorkflowEngine,WorkflowEntry:()=>WorkflowEntry,WorkflowInstance:()=>import_subsystems5.WorkflowInstance,WorkflowJobTimeoutError:()=>WorkflowJobTimeoutError,WorkflowKind:()=>WorkflowKind,WorkflowRegistry:()=>import_subsystems5.WorkflowRegistry,WorkflowStepExecutor:()=>import_subsystems5.WorkflowStepExecutor,WorkflowStepNotFoundError:()=>WorkflowStepNotFoundError,WorkflowTimeoutError:()=>WorkflowTimeoutError,WorkflowTriggerConfigError:()=>WorkflowTriggerConfigError,WorkflowTriggerPrincipal:()=>WorkflowTriggerPrincipal,ZodAny:()=>import_lazy_zod164.ZodAny,ZodArray:()=>import_lazy_zod164.ZodArray,ZodBigInt:()=>import_lazy_zod164.ZodBigInt,ZodBoolean:()=>import_lazy_zod164.ZodBoolean,ZodDate:()=>import_lazy_zod164.ZodDate,ZodDefault:()=>import_lazy_zod164.ZodDefault,ZodDiscriminatedUnion:()=>import_lazy_zod164.ZodDiscriminatedUnion,ZodEnum:()=>import_lazy_zod164.ZodEnum,ZodError:()=>import_lazy_zod164.ZodError,ZodIntersection:()=>import_lazy_zod164.ZodIntersection,ZodLiteral:()=>import_lazy_zod164.ZodLiteral,ZodNever:()=>import_lazy_zod164.ZodNever,ZodNull:()=>import_lazy_zod164.ZodNull,ZodNullable:()=>import_lazy_zod164.ZodNullable,ZodNumber:()=>import_lazy_zod164.ZodNumber,ZodObject:()=>import_lazy_zod164.ZodObject,ZodOptional:()=>import_lazy_zod164.ZodOptional,ZodRecord:()=>import_lazy_zod164.ZodRecord,ZodString:()=>import_lazy_zod164.ZodString,ZodSymbol:()=>import_lazy_zod164.ZodSymbol,ZodTuple:()=>import_lazy_zod164.ZodTuple,ZodType:()=>import_lazy_zod164.ZodType,ZodUndefined:()=>import_lazy_zod164.ZodUndefined,ZodUnion:()=>import_lazy_zod164.ZodUnion,ZodUnknown:()=>import_lazy_zod164.ZodUnknown,ZodVoid:()=>import_lazy_zod164.ZodVoid,acquireConcurrencySlots:()=>acquireConcurrencySlots,adapterInitOptionsOf:()=>adapterInitOptionsOf,addHookObserver:()=>addHookObserver,agent:()=>frontMcpAgent,aiPlatformTypeSchema:()=>import_auth5.aiPlatformTypeSchema,allowsPublicAccess:()=>import_auth13.allowsPublicAccess,annotatedFrontMcpAdaptersSchema:()=>annotatedFrontMcpAdaptersSchema,annotatedFrontMcpAgentsSchema:()=>annotatedFrontMcpAgentsSchema,annotatedFrontMcpAppSchema:()=>annotatedFrontMcpAppSchema,annotatedFrontMcpAuthProvidersSchema:()=>annotatedFrontMcpAuthProvidersSchema,annotatedFrontMcpChannelsSchema:()=>annotatedFrontMcpChannelsSchema,annotatedFrontMcpEventsSchema:()=>annotatedFrontMcpEventsSchema,annotatedFrontMcpJobsSchema:()=>annotatedFrontMcpJobsSchema,annotatedFrontMcpLoggerSchema:()=>annotatedFrontMcpLoggerSchema,annotatedFrontMcpPluginsSchema:()=>annotatedFrontMcpPluginsSchema,annotatedFrontMcpPromptsSchema:()=>annotatedFrontMcpPromptsSchema,annotatedFrontMcpProvidersSchema:()=>annotatedFrontMcpProvidersSchema,annotatedFrontMcpResourcesSchema:()=>annotatedFrontMcpResourcesSchema,annotatedFrontMcpSkillsSchema:()=>annotatedFrontMcpSkillsSchema,annotatedFrontMcpToolsSchema:()=>annotatedFrontMcpToolsSchema,annotatedFrontMcpWorkflowsSchema:()=>annotatedFrontMcpWorkflowsSchema,app:()=>frontMcpApp,appAuthOptionsSchema:()=>import_auth12.appAuthOptionsSchema,appFilterConfigSchema:()=>appFilterConfigSchema,applyPrimitiveFilter:()=>applyPrimitiveFilter,assertStaticStartupConfig:()=>assertStaticStartupConfig,authInfoFromAuthorization:()=>authInfoFromAuthorization,authOptionsSchema:()=>import_auth11.authOptionsSchema,authenticateFnSchema:()=>import_auth10.authenticateFnSchema,authorizationRequiredDataSchema:()=>authorizationRequiredDataSchema,authorizationRequiredMetaSchema:()=>authorizationRequiredMetaSchema,authorizationRequiredParamsSchema:()=>authorizationRequiredParamsSchema,authorizationSchema:()=>authorizationSchema,authorizeSessionTermination:()=>authorizeSessionTermination,authorizeSkillHttpRequest:()=>authorizeSkillHttpRequest,buildChannelInstructions:()=>buildChannelInstructions,buildEsmPromptRecord:()=>import_subsystems2.buildEsmPromptRecord,buildEsmResourceRecord:()=>import_subsystems2.buildEsmResourceRecord,buildEsmShUrl:()=>import_subsystems2.buildEsmShUrl,buildEsmToolRecord:()=>import_subsystems2.buildEsmToolRecord,buildManifest:()=>buildManifest,buildParamHeaders:()=>buildParamHeaders,buildPartitionContext:()=>buildPartitionContext,buildPersistentWebStandardMcp:()=>buildPersistentWebStandardMcp,buildRemotePromptRecord:()=>import_subsystems.buildRemotePromptRecord,buildRemoteResourceRecord:()=>import_subsystems.buildRemoteResourceRecord,buildRemoteResourceTemplateRecord:()=>import_subsystems.buildRemoteResourceTemplateRecord,buildRemoteToolRecord:()=>import_subsystems.buildRemoteToolRecord,buildScopedServerOptions:()=>buildScopedServerOptions,buildSkillsCatalogSummary:()=>buildSkillsCatalogSummary,canDeliverNotifications:()=>canDeliverNotifications,captureCallerDir:()=>captureCallerDir,captureCallerFile:()=>captureCallerFile,challengeHeaders:()=>challengeHeaders,channel:()=>channel,channelNotificationSchema:()=>channelNotificationSchema,channelSourceConfigSchema:()=>channelSourceConfigSchema,channelsConfigSchema:()=>channelsConfigSchema,clearCreateCache:()=>clearCreateCache,clientProfilesOptionsSchema:()=>clientProfilesOptionsSchema,compareVersions:()=>import_subsystems2.compareVersions,composeCallerInstructions:()=>composeCallerInstructions,composeInitializeInstructions:()=>composeInitializeInstructions,computeIssuer:()=>computeIssuer,computeResource:()=>computeResource,computeTaskCapabilities:()=>computeTaskCapabilities,connect:()=>connect,connectClaude:()=>connectClaude,connectLangChain:()=>connectLangChain,connectOpenAI:()=>connectOpenAI,connectVercelAI:()=>connectVercelAI,consentConfigSchema:()=>import_auth6.consentConfigSchema,consumePendingTC39Hooks:()=>consumePendingTC39Hooks,create:()=>create,createChildSpanContext:()=>createChildSpanContext,createContainer:()=>createContainer,createContextResolver:()=>createContextResolver,createDeferredServerBuild:()=>createDeferredServerBuild,createDirectResolver:()=>createDirectResolver,createElicitationStore:()=>createElicitationStore,createElicitationStoreFromStorage:()=>createElicitationStoreFromStorage,createErrorHandler:()=>createErrorHandler,createEsmPromptContextClass:()=>import_subsystems2.createEsmPromptContextClass,createEsmPromptInstance:()=>import_subsystems2.createEsmPromptInstance,createEsmResourceContextClass:()=>import_subsystems2.createEsmResourceContextClass,createEsmResourceInstance:()=>import_subsystems2.createEsmResourceInstance,createEsmToolContextClass:()=>import_subsystems2.createEsmToolContextClass,createEsmToolInstance:()=>import_subsystems2.createEsmToolInstance,createEventStore:()=>import_subsystems10.createEventStore,createEventWebhookReceiver:()=>createEventWebhookReceiver,createExtAppsMessageHandler:()=>createExtAppsMessageHandler,createInMemoryServer:()=>createInMemoryServer,createMemoryElicitationStore:()=>createMemoryElicitationStore,createMemorySkillProvider:()=>createMemorySkillProvider,createMemoryTaskStore:()=>createMemoryTaskStore,createQuestionStore:()=>createQuestionStore,createRemotePromptContextClass:()=>import_subsystems.createRemotePromptContextClass,createRemotePromptInstance:()=>import_subsystems.createRemotePromptInstance,createRemoteResourceContextClass:()=>import_subsystems.createRemoteResourceContextClass,createRemoteResourceInstance:()=>import_subsystems.createRemoteResourceInstance,createRemoteResourceTemplateInstance:()=>import_subsystems.createRemoteResourceTemplateInstance,createRemoteToolContextClass:()=>import_subsystems.createRemoteToolContextClass,createRemoteToolInstance:()=>import_subsystems.createRemoteToolInstance,createSkillHttpAuthValidator:()=>createSkillHttpAuthValidator,createSkillInstance:()=>createSkillInstance,createSkillStorageProvider:()=>createSkillStorageProvider,createTaskStore:()=>createTaskStore,createWebFetchHandler:()=>createWebFetchHandler,decideIntent:()=>decideIntent,decisionSchema:()=>decisionSchema,decisionsApiDecider:()=>decisionsApiDecider,decryptElicitationData:()=>decryptElicitationData,deepMerge:()=>deepMerge,default:()=>import_lazy_zod163.default,defaultHttpPort:()=>defaultHttpPort,defineDutyMetadata:()=>defineDutyMetadata,defineHttpRouteMetadata:()=>defineHttpRouteMetadata,defineWorkerMetadata:()=>defineWorkerMetadata,deriveElicitationKey:()=>deriveElicitationKey,describeConfigIssues:()=>describeConfigIssues,deserializeAndDecrypt:()=>deserializeAndDecrypt,deserializeElicitationBlob:()=>deserializeElicitationBlob,detectConflicts:()=>detectConflicts,detectPlatform:()=>detectPlatform,devtoolsOptionsSchema:()=>devtoolsOptionsSchema,dutyMetadataOf:()=>dutyMetadataOf,dutyMetadataSchema:()=>dutyMetadataSchema,eagerZ:()=>import_lazy_zod164.eagerZ,elicitationOptionsSchema:()=>elicitationOptionsSchema,enabledOptionSchema:()=>enabledOptionSchema,encryptAndSerialize:()=>encryptAndSerialize,encryptElicitationData:()=>encryptElicitationData,enforceGlobalRateLimit:()=>enforceGlobalRateLimit,enforceIpFilter:()=>enforceIpFilter,esmRegistryAuthSchema:()=>import_subsystems2.esmRegistryAuthSchema,event:()=>frontMcpEvent,eventStoreConfigSchema:()=>eventStoreConfigSchema,eventsConfigSchema:()=>eventsConfigSchema,expandProtocolConfig:()=>expandProtocolConfig,extAppsHostCapabilitiesSchema:()=>extAppsHostCapabilitiesSchema,extAppsOptionsSchema:()=>extAppsOptionsSchema,extendOutputSchemaForElicitation:()=>extendOutputSchemaForElicitation,extendedAgentMetadata:()=>extendedAgentMetadata,extendedJobMetadata:()=>extendedJobMetadata,extendedPromptMetadata:()=>extendedPromptMetadata,extendedResourceMetadata:()=>extendedResourceMetadata,extendedResourceTemplateMetadata:()=>extendedResourceTemplateMetadata,extendedSkillMetadata:()=>extendedSkillMetadata,extendedToolMetadata:()=>extendedToolMetadata,extendedWorkflowMetadata:()=>extendedWorkflowMetadata,extractPublicMessage:()=>extractPublicMessage,extractSchemaPaths:()=>extractSchemaPaths,extractToolNames:()=>extractToolNames,federatedAuthConfigSchema:()=>import_auth6.federatedAuthConfigSchema,fileSignal:()=>fileSignal,filterServableSkills:()=>filterServableSkills,findBudgetOverruns:()=>findBudgetOverruns,firstCallerFile:()=>firstCallerFile,fitResourceAnswer:()=>fitResourceAnswer,fitToolAnswer:()=>fitToolAnswer,flatRemoteProviderFields:()=>import_auth6.flatRemoteProviderFields,forceMaterialize:()=>import_lazy_zod164.forceMaterialize,formatMcpErrorResponse:()=>formatMcpErrorResponse,formatOutputSchemaForDescription:()=>formatOutputSchemaForDescription,formatResultForPlatform:()=>formatResultForPlatform,formatSkillForLLM:()=>formatSkillForLLM,formatToolsForPlatform:()=>formatToolsForPlatform,frontMcpAdapterMetadataSchema:()=>frontMcpAdapterMetadataSchema,frontMcpAgent:()=>frontMcpAgent,frontMcpAgentMetadataSchema:()=>frontMcpAgentMetadataSchema,frontMcpApp:()=>frontMcpApp,frontMcpAuthProviderMetadataSchema:()=>frontMcpAuthProviderMetadataSchema,frontMcpBaseSchema:()=>frontMcpBaseSchema,frontMcpChannelMetadataSchema:()=>frontMcpChannelMetadataSchema,frontMcpEvent:()=>frontMcpEvent,frontMcpEventMetadataSchema:()=>frontMcpEventMetadataSchema,frontMcpFlowMetadataSchema:()=>frontMcpFlowMetadataSchema,frontMcpJob:()=>frontMcpJob,frontMcpJobMetadataSchema:()=>frontMcpJobMetadataSchema,frontMcpLocalAppMetadataSchema:()=>frontMcpLocalAppMetadataSchema,frontMcpLogTransportMetadataSchema:()=>frontMcpLogTransportMetadataSchema,frontMcpMetadataSchema:()=>frontMcpMetadataSchema,frontMcpPackageManifestSchema:()=>import_subsystems2.frontMcpPackageManifestSchema,frontMcpPluginMetadataSchema:()=>frontMcpPluginMetadataSchema,frontMcpPrompt:()=>frontMcpPrompt,frontMcpPromptMetadataSchema:()=>frontMcpPromptMetadataSchema,frontMcpProviderMetadataSchema:()=>frontMcpProviderMetadataSchema,frontMcpRemoteAppMetadataSchema:()=>frontMcpRemoteAppMetadataSchema,frontMcpResource:()=>frontMcpResource,frontMcpResourceMetadataSchema:()=>frontMcpResourceMetadataSchema,frontMcpResourceTemplate:()=>frontMcpResourceTemplate,frontMcpResourceTemplateMetadataSchema:()=>frontMcpResourceTemplateMetadataSchema,frontMcpSkill:()=>frontMcpSkill,frontMcpTool:()=>frontMcpTool,frontMcpToolMetadataSchema:()=>frontMcpToolMetadataSchema,frontMcpWorkflow:()=>frontMcpWorkflow,frontMcpWorkflowMetadataSchema:()=>frontMcpWorkflowMetadataSchema,generateElicitationId:()=>generateElicitationId,generateEnvFallbacks:()=>generateEnvFallbacks,generateFallbacks:()=>generateFallbacks,generateTaskId:()=>generateTaskId,generateTraceContext:()=>generateTraceContext,getCallSurface:()=>getCallSurface,getConfig:()=>getConfig,getDecoratorConfig:()=>getDecoratorConfig,getElicitationSecret:()=>getElicitationSecret,getGlobalStoreConfig:()=>getGlobalStoreConfig,getNestedValue:()=>getNestedValue,getPinnedPublicUrl:()=>getPinnedPublicUrl,getRegistryUrl:()=>import_subsystems2.getRegistryUrl,getRequestBaseUrl:()=>getRequestBaseUrl,getRunningTool:()=>getRunningTool,getServerlessHandler:()=>getServerlessHandler,getServerlessHandlerAsync:()=>getServerlessHandlerAsync,getSkillMetadata:()=>getSkillMetadata,getToolNameFromClass:()=>getToolNameFromClass,handleWaitingFallback:()=>handleWaitingFallback,hasSkillAuditFactory:()=>hasSkillAuditFactory,healthOptionsSchema:()=>healthOptionsSchema,healthReadyzOptionsSchema:()=>healthReadyzOptionsSchema,hookOptionsSchema:()=>hookOptionsSchema,httpInputSchema:()=>httpInputSchema,httpOptionsSchema:()=>httpOptionsSchema,httpOutputSchema:()=>httpOutputSchema,httpRequestInputSchema:()=>httpRequestInputSchema,httpRespond:()=>httpRespond,httpRouteMetadataOf:()=>httpRouteMetadataOf,incrementalAuthConfigSchema:()=>import_auth6.incrementalAuthConfigSchema,initOptionsOf:()=>initOptionsOf,instructionsBudgetOptionsSchema:()=>instructionsBudgetOptionsSchema,intentSchema:()=>intentSchema,isAlive:()=>isAlive,isAnonymousSubject:()=>import_auth95.isAnonymousSubject,isAuthError:()=>import_subsystems.isAuthError,isChannelClass:()=>isChannelClass,isChannelFunction:()=>isChannelFunction,isClientFacingError:()=>isClientFacingError,isConnectionError:()=>import_subsystems.isConnectionError,isDistributedMode:()=>isDistributedMode,isDynamicPluginClass:()=>isDynamicPluginClass,isElicitationEncryptionAvailable:()=>isElicitationEncryptionAvailable,isEnabledSource:()=>isEnabledSource,isEncryptedBlob:()=>isEncryptedBlob,isEntryEnabled:()=>isEntryEnabled,isEntryGatedBy:()=>isEntryGatedBy,isEventClass:()=>isEventClass,isEventFunction:()=>isEventFunction,isFileInstructions:()=>isFileInstructions,isHttpRoutePath:()=>isHttpRoutePath,isInlineInstructions:()=>isInlineInstructions,isLazy:()=>import_lazy_zod164.isLazy,isLocalMode:()=>import_auth13.isLocalMode,isMrtrSignal:()=>isMrtrSignal,isNewerVersion:()=>import_subsystems2.isNewerVersion,isOrchestratedLocal:()=>import_auth13.isOrchestratedLocal,isOrchestratedMode:()=>import_auth13.isOrchestratedMode,isOrchestratedRemote:()=>import_auth13.isOrchestratedRemote,isPackageSpecifier:()=>import_subsystems2.isPackageSpecifier,isPrimitiveIncluded:()=>isPrimitiveIncluded,isProducedResourceKey:()=>isProducedResourceKey,isProxyTrusted:()=>isProxyTrusted,isPublicError:()=>isPublicError,isPublicMode:()=>import_auth13.isPublicMode,isPublicUrlPinned:()=>isPublicUrlPinned,isPubsubConfigured:()=>isPubsubConfigured,isRedisConnection:()=>import_utils10.isRedisConnection,isRedisConnectionOptions:()=>isRedisConnectionOptions,isRedisProvider:()=>isRedisProvider,isRemoteMode:()=>import_auth13.isRemoteMode,isResourceKey:()=>isResourceKey,isResourceKeyFamily:()=>isResourceKeyFamily,isSkillDecorated:()=>isSkillDecorated,isSkillRecord:()=>isSkillRecord,isStaticMode:()=>import_auth13.isStaticMode,isTaskWorkerProcess:()=>isTaskWorkerProcess,isTerminal:()=>isTerminal,isToolRefWithClass:()=>isToolRefWithClass,isToolRefWithName:()=>isToolRefWithName,isTransientError:()=>import_subsystems.isTransientError,isTransparentMode:()=>import_auth13.isTransparentMode,isUrlInstructions:()=>isUrlInstructions,isValidRange:()=>import_subsystems2.isValidRange,isValidVersion:()=>import_subsystems2.isValidVersion,isVercelKvProvider:()=>isVercelKvProvider,issuerSubjectKey:()=>issuerSubjectKey,job:()=>frontMcpJob,jobRunUri:()=>import_subsystems3.jobRunUri,jobRunnerSchema:()=>jobRunnerSchema,joinPath:()=>import_utils27.joinPath,jsonWebKeySetSchema:()=>import_auth3.jsonWebKeySetSchema,jwkParametersSchema:()=>import_auth3.jwkParametersSchema,jwkSchema:()=>import_auth3.jwkSchema,lazyAppMetadataSchema:()=>lazyAppMetadataSchema,lazyZ:()=>import_lazy_zod164.lazyZ,lifecycleOptionsSchema:()=>lifecycleOptionsSchema,lintServerManifest:()=>lintServerManifest,loadConfig:()=>loadConfig,loadEnvFiles:()=>loadEnvFiles,loadSkillDirectory:()=>loadSkillDirectory,localAuthSchema:()=>import_auth10.localAuthSchema,localDcrClientSchema:()=>import_auth6.localDcrClientSchema,localDcrConfigSchema:()=>import_auth6.localDcrConfigSchema,localSigningConfigSchema:()=>import_auth6.localSigningConfigSchema,loggingOptionsSchema:()=>loggingOptionsSchema,loginConfigSchema:()=>import_auth10.loginConfigSchema,makeWellKnownPaths:()=>makeWellKnownPaths,mapEnvToNestedConfig:()=>mapEnvToNestedConfig,maxSatisfying:()=>import_subsystems2.maxSatisfying,mayAccessRun:()=>import_subsystems3.mayAccessRun,mcpRegistryOptionsSchema:()=>mcpRegistryOptionsSchema,mcpRegistryRepositorySchema:()=>mcpRegistryRepositorySchema,mcpSessionHeaderSchema:()=>mcpSessionHeaderSchema,metricsOptionsSchema:()=>metricsOptionsSchema,metricsProcessOptionsSchema:()=>metricsProcessOptionsSchema,negotiateRemoteProtocol:()=>import_subsystems9.negotiateRemoteProtocol,normalizeEndpointConfig:()=>normalizeEndpointConfig,normalizeEntryPrefix:()=>normalizeEntryPrefix,normalizeEsmExport:()=>import_subsystems2.normalizeEsmExport,normalizeNameForEnv:()=>normalizeNameForEnv,normalizePathSegment:()=>normalizePathSegment,normalizeResourceUri:()=>normalizeResourceUri,normalizeScopeBase:()=>normalizeScopeBase,normalizeSkill:()=>normalizeSkill,normalizeSkillsConfigOptions:()=>normalizeSkillsConfigOptions,normalizeToolAuthProviders:()=>normalizeToolAuthProviders,normalizeToolRef:()=>normalizeToolRef,observabilityOptionsSchema:()=>observabilityOptionsSchema,offloadOptionsSchema:()=>offloadOptionsSchema,orchestratedLocalSchema:()=>import_auth10.orchestratedLocalSchema,orchestratedRemoteSchema:()=>import_auth10.orchestratedRemoteSchema,outboundFetchOptionsSchema:()=>outboundFetchOptionsSchema,outputPolicySchema:()=>outputPolicySchema,packageLoaderSchema:()=>packageLoaderSchema,paginationOptionsSchema:()=>paginationOptionsSchema,parseAuthOptions:()=>import_auth13.parseAuthOptions,parseCallerDir:()=>parseCallerDir,parseEnvContent:()=>parseEnvContent,parseEnvContentSync:()=>parseEnvContentSync,parseFrontMcpConfigLite:()=>parseFrontMcpConfigLite,parseListInput:()=>parseListInput,parsePackageSpecifier:()=>import_subsystems2.parsePackageSpecifier,parseRedisUrl:()=>parseRedisUrl,parseTraceContext:()=>parseTraceContext,partitionsByIdentity:()=>partitionsByIdentity,pathToEnvKey:()=>pathToEnvKey,peekPendingTC39HooksForClass:()=>peekPendingTC39HooksForClass,performElicit:()=>performElicit,performListRoots:()=>performListRoots,performSample:()=>performSample,persistenceConfigSchema:()=>persistenceConfigSchema,platformDetectionConfigSchema:()=>platformDetectionConfigSchema,platformMappingEntrySchema:()=>platformMappingEntrySchema,pollLeaseMs:()=>import_subsystems8.pollLeaseMs,populateProcessEnv:()=>populateProcessEnv,previewItems:()=>previewItems,printQuestionInboxLink:()=>printQuestionInboxLink,prompt:()=>frontMcpPrompt,providerConfigSchema:()=>import_auth6.providerConfigSchema,publicAccessConfigSchema:()=>import_auth6.publicAccessConfigSchema,publicAuthOptionsSchema:()=>import_auth7.publicAuthOptionsSchema,pubsubOptionsSchema:()=>pubsubOptionsSchema,questionInboxRoutes:()=>questionInboxRoutes,questionSubjectOf:()=>questionSubjectOf,redisClientSchema:()=>redisClientSchema,redisClusterNodesSchema:()=>redisClusterNodesSchema,redisClusterSchema:()=>redisClusterSchema,redisConnectionOfOptions:()=>redisConnectionOfOptions,redisOptionsSchema:()=>redisOptionsSchema,redisProviderSchema:()=>redisProviderSchema,redisStorageConfigOf:()=>redisStorageConfigOf,redisUrlSchema:()=>redisUrlSchema,refusePluginStoreInBrowser:()=>refusePluginStoreInBrowser,refused:()=>refused,registerOptionalModule:()=>import_utils50.registerOptionalModule,registerPendingTC39Hook:()=>registerPendingTC39Hook,registerWorkTracker:()=>registerWorkTracker,remoteAuthSchema:()=>import_auth10.remoteAuthSchema,remoteProviderConfigSchema:()=>import_auth6.remoteProviderConfigSchema,resolveAllowNonFinite:()=>resolveAllowNonFinite,resolveDefaultSqlitePath:()=>resolveDefaultSqlitePath,resolveEntryPath:()=>resolveEntryPath,resolveInstructionsBudget:()=>resolveInstructionsBudget,resolveIssuer:()=>resolveIssuer,resolveNameConflicts:()=>resolveNameConflicts,resolveOutputBudget:()=>resolveOutputBudget,resolveOutputSchemaMode:()=>resolveOutputSchemaMode,resolvePendingTC39HooksForClass:()=>resolvePendingTC39HooksForClass,resolvePrincipal:()=>resolvePrincipal,resolveQuestionStorage:()=>resolveQuestionStorage,resolveRegistryToken:()=>import_subsystems2.resolveRegistryToken,resolveSchemaDescriptionFormat:()=>resolveSchemaDescriptionFormat,resolveToolVisibility:()=>resolveToolVisibility,resolveUndeclaredKeysPolicy:()=>resolveUndeclaredKeysPolicy,resolveWithFallbacks:()=>resolveWithFallbacks,resolvesToVercelKvTaskBackend:()=>resolvesToVercelKvTaskBackend,resource:()=>frontMcpResource,resourceKeyFamilySchema:()=>resourceKeyFamilySchema,resourceKeySchema:()=>resourceKeySchema,resourceStore:()=>resourceStore,resourceTemplate:()=>frontMcpResourceTemplate,resourceUriMatches:()=>resourceUriMatches,runHttpRequestFlowWeb:()=>runHttpRequestFlowWeb,runTaskInBackground:()=>runTaskInBackground,runWebStandardMcp:()=>runWebStandardMcp,satisfiesRange:()=>import_subsystems2.satisfiesRange,scanSkillResources:()=>scanSkillResources,secureStoreConfigSchema:()=>import_auth6.secureStoreConfigSchema,secureStoreCustomBackendSchema:()=>import_auth6.secureStoreCustomBackendSchema,secureStoreEncryptionSchema:()=>import_auth6.secureStoreEncryptionSchema,secureStoreScopeSchema:()=>import_auth6.secureStoreScopeSchema,sendFallbackNotification:()=>sendFallbackNotification,serializeElicitationBlob:()=>serializeElicitationBlob,serializeHttpCookie:()=>serializeHttpCookie,serverInfoOptionsSchema:()=>serverInfoOptionsSchema,serverManifestSchema:()=>serverManifestSchema,sessionAuthInfoFromAuthorization:()=>sessionAuthInfoFromAuthorization,sessionIdPayloadSchema:()=>import_auth5.sessionIdPayloadSchema,sessionIdPresentedBy:()=>sessionIdPresentedBy,sessionIdSchema:()=>sessionIdSchema,sessionOptionsSchema:()=>sessionOptionsSchema,setNestedValue:()=>setNestedValue,setServerlessHandler:()=>setServerlessHandler,setServerlessHandlerError:()=>setServerlessHandlerError,setServerlessHandlerPromise:()=>setServerlessHandlerPromise,setSkillAuditFactory:()=>setSkillAuditFactory,shouldCacheProviders:()=>shouldCacheProviders,shouldStopExecution:()=>shouldStopExecution,skill:()=>frontMcpSkill,skillCallerDir:()=>skillCallerDir,skillDir:()=>skillDir,skillMetadataSchema:()=>skillMetadataSchema,skillsConfigAuthModeSchema:()=>skillsConfigAuthModeSchema,skillsConfigEndpointConfigSchema:()=>skillsConfigEndpointConfigSchema,skillsConfigOptionsSchema:()=>skillsConfigOptionsSchema,skippedAppBehaviorSchema:()=>import_auth6.skippedAppBehaviorSchema,sqliteOptionsSchema:()=>sqliteOptionsSchema,sqliteStorageProvider:()=>sqliteStorageProvider,startupFailureResponse:()=>startupFailureResponse,staticAuthOptionsSchema:()=>import_auth8.staticAuthOptionsSchema,storageProviderSchema:()=>storageProviderSchema,storeProvider:()=>storeProvider,supportsStreaming:()=>supportsStreaming,surfaceHash:()=>surfaceHash,switchesOf:()=>switchesOf,timerLimitMessage:()=>timerLimitMessage,toJSONSchema:()=>import_lazy_zod164.toJSONSchema,toMcpError:()=>toMcpError,toRegistryAuthRecord:()=>toRegistryAuthRecord,toWireShape:()=>toWireShape,tokenRefreshConfigSchema:()=>import_auth6.tokenRefreshConfigSchema,tokenStorageConfigSchema:()=>import_auth6.tokenStorageConfigSchema,tokenStorageSqliteSchema:()=>import_auth6.tokenStorageSqliteSchema,tool:()=>frontMcpTool,toolPaginationOptionsSchema:()=>toolPaginationOptionsSchema,trackWork:()=>trackWork,transparentAuthOptionsSchema:()=>import_auth9.transparentAuthOptionsSchema,transportOptionsSchema:()=>transportOptionsSchema,trimSlashes:()=>import_utils27.trimSlashes,tryDecryptStoredValue:()=>tryDecryptStoredValue,tryGetConfig:()=>tryGetConfig,upstreamProviderSchema:()=>import_auth6.upstreamProviderSchema,urlToSafeId:()=>urlToSafeId,userClaimSchema:()=>import_auth5.userClaimSchema,validateElicitationContent:()=>validateElicitationContent,validateHeaderParams:()=>validateHeaderParams,validateMcpSessionHeader:()=>validateMcpSessionHeader,validateRemoteUrl:()=>validateRemoteUrl,vercelKvProviderSchema:()=>vercelKvProviderSchema,withConfig:()=>withConfig,withHttpHeaders:()=>withHttpHeaders,withRetry:()=>import_subsystems.withRetry,withUndeclaredKeysAllowed:()=>withUndeclaredKeysAllowed,workerMetadataOf:()=>workerMetadataOf,workerMetadataSchema:()=>workerMetadataSchema,workflow:()=>frontMcpWorkflow,workflowTriggerOf:()=>workflowTriggerOf,z:()=>import_lazy_zod164.z});module.exports=__toCommonJS(index_exports);var import_reflect_metadata47=require("reflect-metadata");init_common();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_work_spans();init_materialized_resource_context();init_resource_store();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();__reExport(index_exports,require("@frontmcp/guard"),module.exports);var import_subsystems=__toESM(require_lazy_subsystems());var import_subsystems2=__toESM(require_lazy_subsystems());var import_lazy_zod163=__toESM(require("@frontmcp/lazy-zod"));var import_lazy_zod164=require("@frontmcp/lazy-zod");init_context();init_tool_registry();init_tool_instance();init_provider_registry();var import_di58=require("@frontmcp/di");var import_lazy_zod161=require("@frontmcp/lazy-zod");init_app_utils();init_common();init_errors();init_front_mcp_tokens2();init_logger_registry();init_container_handle();init_provider_registry();var createContainerOptionsSchema=import_lazy_zod161.z.object({providers:import_lazy_zod161.z.array(annotatedFrontMcpProvidersSchema).optional().default([]),apps:import_lazy_zod161.z.array(annotatedFrontMcpAppSchema).optional().default([]),logging:loggingOptionsSchema.optional(),lifecycle:lifecycleOptionsSchema.optional(),runBackground:import_lazy_zod161.z.boolean({message:"runBackground must be true or false"}).optional(),runDuties:import_lazy_zod161.z.boolean({message:"runDuties must be true or false"}).optional(),info:import_lazy_zod161.z.object({name:import_lazy_zod161.z.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 lifecycles3=new WeakMap;const root=new ProviderRegistry([{name:"frontmcp:config",provide:FrontMcpConfig,useValue:config}],void 0,{shutdownHookTimeoutMs:lifecycle?.shutdownHookTimeoutMs,sharedLifecycles:lifecycles3});await root.ready;const loggers=new LoggerRegistry(root);await loggers.ready;const logger=root.get(FrontMcpLogger);let disposed=false;const dispose=async()=>{disposed=true;await root.runShutdownHooks(logger);root.dispose()};const registries=[];let serverProviders;const appRegistries=new Map;try{serverProviders=new ProviderRegistry(providers,root);registries.push(serverProviders);await serverProviders.ready;for(const app of apps.filter(import_di58.isClass)){const appProviders=new ProviderRegistry(collectAppMetadata(app).providers??[],serverProviders);registries.push(appProviders);appRegistries.set(app,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}};const owned=new WeakSet(registries.flatMap(registry=>registry.heldLifecycles()));const handle={server:serverProviders.getAllSingletons(),serverDeclared:providers,apps:new Map([...appRegistries].map(([app,registry])=>[app,registry.getAllSingletons()])),lifecycles:lifecycles3,owned,readied:new WeakMap,backgroundStarted:runBackground,get disposed(){return disposed}};const container={get,tryGet,dispose};Object.defineProperty(container,CONTAINER_HANDLE,{value:handle,enumerable:false});return container}init_store_provider();var import_utils237=require("@frontmcp/utils");init_common();init_store_provider();init_browser_stores();var SqliteStorageToken=Symbol.for("frontmcp:storage.sqlite");function sqliteStorageProvider(options){const{prefix,provide=SqliteStorageToken,...sqlite}=options;return storeProvider({name:"storage.sqlite",scope:import_di4.ProviderScope.GLOBAL,provide,inject:()=>[],useFactory:async()=>{refuseServerStoresInBrowser({sqliteStorage:"sqliteStorageProvider()"});const storage=await(0,import_utils237.createStorage)({type:"sqlite",sqlite,prefix,fallback:"error"});return Object.assign(storage,{onShutdown:()=>storage.disconnect()})}})}var import_subsystems3=__toESM(require_lazy_subsystems());init_detached_job_flag();var import_subsystems4=__toESM(require_lazy_subsystems());var import_subsystems5=__toESM(require_lazy_subsystems());var import_subsystems6=__toESM(require_lazy_subsystems());var import_subsystems7=__toESM(require_lazy_subsystems());var import_subsystems8=__toESM(require_lazy_subsystems());var import_protocol87=require("@frontmcp/protocol");init_event_client();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();var import_utils238=require("@frontmcp/utils");init_skill_metadata();init_caller_dir_utils();init_sdk_errors();init_skill_md_parser();async function scanSkillResources(dirPath){const resources={};const scriptsPath=(0,import_utils238.pathJoin)(dirPath,"scripts");const referencesPath=(0,import_utils238.pathJoin)(dirPath,"references");const assetsPath=(0,import_utils238.pathJoin)(dirPath,"assets");const examplesPath=(0,import_utils238.pathJoin)(dirPath,"examples");const checks=await Promise.all([checkDirectory(scriptsPath),checkDirectory(referencesPath),checkDirectory(assetsPath),checkDirectory(examplesPath),(0,import_utils238.fileExists)((0,import_utils238.pathJoin)(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(path7){try{const s=await(0,import_utils238.stat)(path7);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(0,import_utils238.realpath)(current);if(visited.has(realDir))return;visited.add(realDir);entries=await(0,import_utils238.readdir)(current)}catch(err){if(err.code==="ENOENT")return;throw err}for(const entry of entries){const full=(0,import_utils238.pathJoin)(current,entry);let entryStat;try{entryStat=await(0,import_utils238.stat)(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((0,import_utils238.isAbsolute)(dirPath))return dirPath;const fromCaller=callerDir?(0,import_utils238.pathResolve)(callerDir,dirPath):void 0;if(fromCaller&&await(0,import_utils238.fileExists)((0,import_utils238.pathJoin)(fromCaller,"SKILL.md")))return fromCaller;const fromCwd=(0,import_utils238.pathResolve)(dirPath);if(await(0,import_utils238.fileExists)((0,import_utils238.pathJoin)(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=(0,import_utils238.pathJoin)(dirPath,"SKILL.md");const exists=await(0,import_utils238.fileExists)(skillMdPath);if(!exists){throw new InvalidSkillError((0,import_utils238.basename)(dirPath),"SKILL.md not found in directory")}let content;let partialMetadata;try{content=await(0,import_utils238.readFile)(skillMdPath,"utf-8");const{frontmatter,body}=parseSkillMdFrontmatter(content);partialMetadata=skillMdFrontmatterToMetadata(frontmatter,body)}catch(err){const name60=(0,import_utils238.basename)(dirPath);const message=err instanceof Error?err.message:String(err);throw new InvalidSkillError(name60,`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??(0,import_utils238.basename)(dirPath);throw new InvalidSkillError(skillName2,`Skill directory contains nested SKILL.md files (forbidden by SEP-2640 \xA7Resource Mapping): ${nested.join(", ")}`)}const dirName=(0,import_utils238.basename)(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();var import_utils239=require("@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.
|