@frontmcp/sdk 1.12.1 → 1.12.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.js CHANGED
@@ -191,7 +191,7 @@ ${promptContentToText(message.content)}`);return[...result.description?[result.d
191
191
  expires_at INTEGER
192
192
  );
193
193
  CREATE INDEX IF NOT EXISTS idx_kv_expires ON kv(expires_at) WHERE expires_at IS NOT NULL;
194
- `)}prepareStatements(){this.stmts={get:this.db.prepare("SELECT value, expires_at FROM kv WHERE key = ?"),set:this.db.prepare("INSERT OR REPLACE INTO kv (key, value, expires_at) VALUES (?, ?, ?)"),del:this.db.prepare("DELETE FROM kv WHERE key = ?"),delExpired:this.db.prepare("DELETE FROM kv WHERE key = ? AND expires_at IS NOT NULL AND expires_at <= ?"),has:this.db.prepare("SELECT 1 FROM kv WHERE key = ? AND (expires_at IS NULL OR expires_at > ?)"),keys:this.db.prepare("SELECT key FROM kv WHERE (expires_at IS NULL OR expires_at > ?)"),keysInRange:this.db.prepare("SELECT key FROM kv WHERE key >= ? AND key < ? AND (expires_at IS NULL OR expires_at > ?)"),cleanup:this.db.prepare("DELETE FROM kv WHERE expires_at IS NOT NULL AND expires_at <= ?"),ttl:this.db.prepare("SELECT expires_at FROM kv WHERE key = ?"),expire:this.db.prepare("UPDATE kv SET expires_at = ? WHERE key = ? AND (expires_at IS NULL OR expires_at > ?)")}}prepared(){if(!this.stmts){throw new Error("SqliteKvStore: prepared statements not initialized. Was prepareStatements() called?")}return this.stmts}get(key){const stmts=this.prepared();const row=stmts.get.get(key);if(!row)return null;const now=Date.now();if(row.expires_at!==null&&row.expires_at<=now){stmts.delExpired.run(key,now);return null}if(this.encryptionKey){return decryptValue(this.encryptionKey,row.value)}return row.value}getJSON(key){const value=this.get(key);if(value===null)return null;try{return JSON.parse(value)}catch{return null}}set(key,value,ttlMs){const expiresAt=ttlMs!==void 0?Date.now()+ttlMs:null;const storedValue=this.encryptionKey?encryptValue(this.encryptionKey,value):value;this.prepared().set.run(key,storedValue,expiresAt)}setJSON(key,value,ttlMs){this.set(key,JSON.stringify(value),ttlMs)}del(key){this.prepared().del.run(key)}has(key){const row=this.prepared().has.get(key,Date.now());return row!==void 0}keys(pattern){const stmts=this.prepared();const now=Date.now();if(!pattern)return stmts.keys.all(now).map(r=>r.key);const{prefix,tokens}=parseLikePattern(pattern);const upperBound=upperBoundOf(prefix);const rows=upperBound===void 0?stmts.keys.all(now):stmts.keysInRange.all(prefix,upperBound,now);return rows.map(r=>r.key).filter(key=>matchesLikeTokens(tokens,key))}expire(key,ttlMs){const now=Date.now();const result=this.prepared().expire.run(now+ttlMs,key,now);return result.changes>0}ttl(key){const stmts=this.prepared();const row=stmts.ttl.get(key);if(!row)return-2;if(row.expires_at===null)return-1;const now=Date.now();const remaining=row.expires_at-now;if(remaining<=0){stmts.delExpired.run(key,now);return-2}return remaining}purgeExpired(){const result=this.prepared().cleanup.run(Date.now());return result.changes}close(){if(this.cleanupTimer){clearInterval(this.cleanupTimer);this.cleanupTimer=null}this.connection.release()}getDatabase(){return this.db}getConnection(){return this.connection}};var import_utils410=require("@frontmcp/utils");var SqliteStorageAdapter=class extends import_utils410.BaseStorageAdapter{backendName="sqlite";kv;connection;ownsKvStore;constructor(options){super();this.ownsKvStore=!(options instanceof SqliteKvStore);this.kv=options instanceof SqliteKvStore?options:new SqliteKvStore(options);this.connection=this.kv.getConnection()}async connect(){this.connected=true}async disconnect(){if(!this.connected)return;this.connected=false;if(this.ownsKvStore){await this.connection.idle();this.kv.close()}}async ping(){if(!this.connected)return false;try{await this.connection.read(()=>this.kv.has("__frontmcp_ping__"));return true}catch{return false}}async get(key){this.ensureConnected();return this.connection.read(()=>this.kv.get(key))}async doSet(key,value,options){const ttlMs=options?.ttlSeconds!==void 0?options.ttlSeconds*1e3:void 0;return this.connection.write(()=>{if(options?.ifNotExists&&this.kv.has(key))return;if(options?.ifExists&&!this.kv.has(key))return;this.kv.set(key,value,ttlMs)})}async delete(key){this.ensureConnected();return this.connection.write(()=>{const existed=this.kv.has(key);this.kv.del(key);return existed})}async deleteIfEquals(key,expectedValue){this.ensureConnected();return this.connection.write(()=>{if(this.kv.get(key)!==expectedValue)return false;this.kv.del(key);return true})}async expireIfEquals(key,expectedValue,ttlSeconds){this.ensureConnected();(0,import_utils410.validateTTL)(ttlSeconds);return this.connection.write(()=>this.kv.get(key)===expectedValue&&this.kv.expire(key,ttlSeconds*1e3))}async setIfEquals(key,expectedValue,value){this.ensureConnected();return this.connection.write(()=>{if(this.kv.get(key)!==expectedValue)return false;this.kv.set(key,value);return true})}async dataVersion(){this.ensureConnected();return this.connection.read(()=>Number(this.connection.db.pragma("data_version",{simple:true})))}async exists(key){this.ensureConnected();return this.connection.read(()=>this.kv.has(key))}async expire(key,ttlSeconds){this.ensureConnected();(0,import_utils410.validateTTL)(ttlSeconds);return this.connection.write(()=>this.kv.expire(key,ttlSeconds*1e3))}async ttl(key){this.ensureConnected();const ms=await this.connection.read(()=>this.kv.ttl(key));if(ms===-2)return null;if(ms===-1)return-1;return Math.max(0,Math.ceil(ms/1e3))}async keys(pattern="*"){this.ensureConnected();if(pattern==="*"||pattern===void 0){return this.connection.read(()=>this.kv.keys())}const like=pattern.replace(/[%_\\]/g,c=>`\\${c}`).replace(/\*/g,"%").replace(/\?/g,"_");return this.connection.read(()=>this.kv.keys(like))}async incr(key){return this.incrBy(key,1)}async decr(key){return this.incrBy(key,-1)}async incrBy(key,amount){this.ensureConnected();return this.connection.write(()=>{const current=this.kv.get(key);const base=current===null?0:Number.parseInt(current,10);if(Number.isNaN(base))throw new import_utils410.StorageOperationError("incrBy",key,"Value is not an integer");const next=base+amount;const remainingMs=this.kv.ttl(key);this.kv.set(key,String(next),remainingMs>0?remainingMs:void 0);return next})}getKvStore(){return this.kv}getPubSubSuggestion(){return"SQLite adapter does not support pub/sub. Use Redis or Upstash for pub/sub support."}};var REFUSED_PRAGMAS=new Map([["busy_timeout",0],["journal_mode","wal"]]);var DurableObjectDatabase=class{constructor(storage){this.storage=storage}storage;open=true;exec(source){this.storage.sql.exec(source).toArray()}prepare(source){const all=(...params)=>this.storage.sql.exec(source,...params).toArray();return{all,get:(...params)=>all(...params)[0],run:(...params)=>{all(...params);return{changes:Number(this.storage.sql.exec("SELECT changes() AS changes").one()["changes"])}}}}pragma(source,options){const name59=source.split("=")[0].trim().toLowerCase();const rows=REFUSED_PRAGMAS.has(name59)?[{[name59]:REFUSED_PRAGMAS.get(name59)}]:this.storage.sql.exec(`PRAGMA ${source}`).toArray();return options?.simple?Object.values(rows[0]??{})[0]:rows}transaction(operation){return{immediate:()=>this.storage.transactionSync(operation)}}close(){this.open=false}};function durableObjectSqlite(storage){return()=>new DurableObjectDatabase(storage)}var import_utils510=require("@frontmcp/utils");var SqliteSessionStore=class{kv;keyPrefix;defaultTtlMs;constructor(options){this.kv=new SqliteKvStore(options);this.keyPrefix=options.keyPrefix??"mcp:session:";this.defaultTtlMs=options.defaultTtlMs??36e5}sessionKey(sessionId){return`${this.keyPrefix}${sessionId}`}async get(sessionId){return this.kv.getJSON(this.sessionKey(sessionId))}async set(sessionId,session,ttlMs){this.kv.setJSON(this.sessionKey(sessionId),session,ttlMs??this.defaultTtlMs)}async delete(sessionId){this.kv.del(this.sessionKey(sessionId))}async exists(sessionId){return this.kv.has(this.sessionKey(sessionId))}allocId(){return(0,import_utils510.randomUUID)()}close(){this.kv.close()}getKvStore(){return this.kv}};var import_node_events=require("node:events");function resultRoute(sessionId,elicitId){return`${sessionId.replace(/%/g,"%25").replace(/:/g,"%3A")}:${elicitId}`}function requireSubscriberSession2(sessionId){if(!sessionId){throw new Error("A result subscription needs the session ID the elicitation belongs to; pass it as the third argument")}return sessionId}var SqliteElicitationStore=class{kv;emitter;keyPrefix;constructor(options){this.kv=new SqliteKvStore(options);this.emitter=new import_node_events.EventEmitter;this.emitter.setMaxListeners(100);this.keyPrefix=options.keyPrefix??"mcp:elicit:"}pendingKey(sessionId){return`${this.keyPrefix}pending:${sessionId}`}fallbackKey(elicitId){return`${this.keyPrefix}fallback:${elicitId}`}resolvedKey(elicitId){return`${this.keyPrefix}resolved:${elicitId}`}resultChannel(sessionId,elicitId){return`result:${resultRoute(sessionId,elicitId)}`}fallbackResultChannel(sessionId,elicitId){return`fallback-result:${resultRoute(sessionId,elicitId)}`}async setPending(record){const ttlMs=record.expiresAt-Date.now();if(ttlMs<=0)return;this.kv.setJSON(this.pendingKey(record.sessionId),record,ttlMs)}async getPending(sessionId){return this.kv.getJSON(this.pendingKey(sessionId))}async deletePending(sessionId){this.kv.del(this.pendingKey(sessionId))}async subscribeResult(elicitId,callback,sessionId){const channel2=this.resultChannel(requireSubscriberSession2(sessionId),elicitId);const handler=result=>callback(result);this.emitter.on(channel2,handler);return async()=>{this.emitter.removeListener(channel2,handler)}}async publishResult(elicitId,sessionId,result){this.kv.del(this.pendingKey(sessionId));this.emitter.emit(this.resultChannel(sessionId,elicitId),result)}async setPendingFallback(record){const elicitId=record["elicitId"];if(!elicitId)return;this.kv.setJSON(this.fallbackKey(elicitId),record,3e5)}async getPendingFallback(elicitId,_sessionId){return this.kv.getJSON(this.fallbackKey(elicitId))}async deletePendingFallback(elicitId){this.kv.del(this.fallbackKey(elicitId))}async setResolvedResult(elicitId,result,_sessionId){this.kv.setJSON(this.resolvedKey(elicitId),result,3e5)}async getResolvedResult(elicitId,_sessionId){return this.kv.getJSON(this.resolvedKey(elicitId))}async deleteResolvedResult(elicitId){this.kv.del(this.resolvedKey(elicitId))}async subscribeFallbackResult(elicitId,callback,sessionId){const channel2=this.fallbackResultChannel(requireSubscriberSession2(sessionId),elicitId);const handler=result=>callback(result);this.emitter.on(channel2,handler);return async()=>{this.emitter.removeListener(channel2,handler)}}async publishFallbackResult(elicitId,sessionId,result){this.emitter.emit(this.fallbackResultChannel(sessionId,elicitId),result)}async destroy(){this.emitter.removeAllListeners();this.kv.close()}getKvStore(){return this.kv}};var import_node_events2=require("node:events");var import_utils610=require("@frontmcp/utils");var defaultLivenessProbe=pid=>{try{process.kill(pid,0);return true}catch{return false}};var DEFAULT_PAGE_SIZE3=50;var SqliteTaskStore=class{connection;db;emitter=new import_node_events2.EventEmitter;logger;liveness;cleanupTimer;encryptionKey=null;stmts=null;constructor(options){this.connection=acquireConnection(options.path,"SqliteTaskStore",{busyTimeoutMs:options.busyTimeoutMs,walMode:options.walMode!==false});this.db=this.connection.db;this.logger=options.logger;this.liveness=options.livenessProbe??defaultLivenessProbe;if(options.encryption?.secret){this.encryptionKey=deriveEncryptionKey(options.encryption.secret)}this.emitter.setMaxListeners(200);try{withBusyRetry(()=>this.initSchema());this.prepareStatements()}catch(error){this.connection.release();throw error}const cleanupInterval=options.ttlCleanupIntervalMs??6e4;if(cleanupInterval>0){this.cleanupTimer=setInterval(()=>this.purgeExpired(),cleanupInterval);this.cleanupTimer.unref?.()}else{this.cleanupTimer=null}}initSchema(){this.db.exec(`
194
+ `)}prepareStatements(){this.stmts={get:this.db.prepare("SELECT value, expires_at FROM kv WHERE key = ?"),set:this.db.prepare("INSERT OR REPLACE INTO kv (key, value, expires_at) VALUES (?, ?, ?)"),del:this.db.prepare("DELETE FROM kv WHERE key = ?"),delExpired:this.db.prepare("DELETE FROM kv WHERE key = ? AND expires_at IS NOT NULL AND expires_at <= ?"),has:this.db.prepare("SELECT 1 FROM kv WHERE key = ? AND (expires_at IS NULL OR expires_at > ?)"),keys:this.db.prepare("SELECT key FROM kv WHERE (expires_at IS NULL OR expires_at > ?)"),keysInRange:this.db.prepare("SELECT key FROM kv WHERE key >= ? AND key < ? AND (expires_at IS NULL OR expires_at > ?)"),cleanup:this.db.prepare("DELETE FROM kv WHERE expires_at IS NOT NULL AND expires_at <= ?"),ttl:this.db.prepare("SELECT expires_at FROM kv WHERE key = ?"),expire:this.db.prepare("UPDATE kv SET expires_at = ? WHERE key = ? AND (expires_at IS NULL OR expires_at > ?)")}}prepared(){if(!this.stmts){throw new Error("SqliteKvStore: prepared statements not initialized. Was prepareStatements() called?")}return this.stmts}get(key){const stmts=this.prepared();const row=stmts.get.get(key);if(!row)return null;const now=Date.now();if(row.expires_at!==null&&row.expires_at<=now){stmts.delExpired.run(key,now);return null}if(this.encryptionKey){return decryptValue(this.encryptionKey,row.value)}return row.value}getJSON(key){const value=this.get(key);if(value===null)return null;try{return JSON.parse(value)}catch{return null}}set(key,value,ttlMs){const expiresAt=ttlMs!==void 0?Date.now()+ttlMs:null;const storedValue=this.encryptionKey?encryptValue(this.encryptionKey,value):value;this.prepared().set.run(key,storedValue,expiresAt)}setJSON(key,value,ttlMs){this.set(key,JSON.stringify(value),ttlMs)}del(key){this.prepared().del.run(key)}has(key){const row=this.prepared().has.get(key,Date.now());return row!==void 0}keys(pattern){const stmts=this.prepared();const now=Date.now();if(!pattern)return stmts.keys.all(now).map(r=>r.key);const{prefix,tokens}=parseLikePattern(pattern);const upperBound=upperBoundOf(prefix);const rows=upperBound===void 0?stmts.keys.all(now):stmts.keysInRange.all(prefix,upperBound,now);return rows.map(r=>r.key).filter(key=>matchesLikeTokens(tokens,key))}expire(key,ttlMs){const now=Date.now();const result=this.prepared().expire.run(now+ttlMs,key,now);return result.changes>0}ttl(key){const stmts=this.prepared();const row=stmts.ttl.get(key);if(!row)return-2;if(row.expires_at===null)return-1;const now=Date.now();const remaining=row.expires_at-now;if(remaining<=0){stmts.delExpired.run(key,now);return-2}return remaining}purgeExpired(){const result=this.prepared().cleanup.run(Date.now());return result.changes}close(){if(this.cleanupTimer){clearInterval(this.cleanupTimer);this.cleanupTimer=null}this.connection.release()}getDatabase(){return this.db}getConnection(){return this.connection}};var import_utils410=require("@frontmcp/utils");function likeLiteral(char){return char==="%"||char==="_"||char==="\\"?`\\${char}`:char}function globToLike(pattern){let like="";for(let index=0;index<pattern.length;index++){const char=pattern[index];if(char==="\\"&&index+1<pattern.length){index++;like+=likeLiteral(pattern[index])}else if(char==="*"){like+="%"}else if(char==="?"){like+="_"}else{like+=likeLiteral(char)}}return like}var SqliteStorageAdapter=class extends import_utils410.BaseStorageAdapter{backendName="sqlite";kv;connection;ownsKvStore;constructor(options){super();this.ownsKvStore=!(options instanceof SqliteKvStore);this.kv=options instanceof SqliteKvStore?options:new SqliteKvStore(options);this.connection=this.kv.getConnection()}async connect(){this.connected=true}async disconnect(){if(!this.connected)return;this.connected=false;if(this.ownsKvStore){await this.connection.idle();this.kv.close()}}async ping(){if(!this.connected)return false;try{await this.connection.read(()=>this.kv.has("__frontmcp_ping__"));return true}catch{return false}}async get(key){this.ensureConnected();return this.connection.read(()=>this.kv.get(key))}async doSet(key,value,options){const ttlMs=options?.ttlSeconds!==void 0?options.ttlSeconds*1e3:void 0;return this.connection.write(()=>{if(options?.ifNotExists&&this.kv.has(key))return;if(options?.ifExists&&!this.kv.has(key))return;this.kv.set(key,value,ttlMs)})}async delete(key){this.ensureConnected();return this.connection.write(()=>{const existed=this.kv.has(key);this.kv.del(key);return existed})}async deleteIfEquals(key,expectedValue){this.ensureConnected();return this.connection.write(()=>{if(this.kv.get(key)!==expectedValue)return false;this.kv.del(key);return true})}async expireIfEquals(key,expectedValue,ttlSeconds){this.ensureConnected();(0,import_utils410.validateTTL)(ttlSeconds);return this.connection.write(()=>this.kv.get(key)===expectedValue&&this.kv.expire(key,ttlSeconds*1e3))}async setIfEquals(key,expectedValue,value){this.ensureConnected();return this.connection.write(()=>{if(this.kv.get(key)!==expectedValue)return false;this.kv.set(key,value);return true})}async dataVersion(){this.ensureConnected();return this.connection.read(()=>Number(this.connection.db.pragma("data_version",{simple:true})))}async exists(key){this.ensureConnected();return this.connection.read(()=>this.kv.has(key))}async expire(key,ttlSeconds){this.ensureConnected();(0,import_utils410.validateTTL)(ttlSeconds);return this.connection.write(()=>this.kv.expire(key,ttlSeconds*1e3))}async ttl(key){this.ensureConnected();const ms=await this.connection.read(()=>this.kv.ttl(key));if(ms===-2)return null;if(ms===-1)return-1;return Math.max(0,Math.ceil(ms/1e3))}async keys(pattern="*"){this.ensureConnected();if(pattern==="*"||pattern===void 0){return this.connection.read(()=>this.kv.keys())}const like=globToLike(pattern);return this.connection.read(()=>this.kv.keys(like))}async incr(key){return this.incrBy(key,1)}async decr(key){return this.incrBy(key,-1)}async incrBy(key,amount){this.ensureConnected();return this.connection.write(()=>{const current=this.kv.get(key);const base=current===null?0:Number.parseInt(current,10);if(Number.isNaN(base))throw new import_utils410.StorageOperationError("incrBy",key,"Value is not an integer");const next=base+amount;const remainingMs=this.kv.ttl(key);this.kv.set(key,String(next),remainingMs>0?remainingMs:void 0);return next})}getKvStore(){return this.kv}getPubSubSuggestion(){return"SQLite adapter does not support pub/sub. Use Redis or Upstash for pub/sub support."}};var REFUSED_PRAGMAS=new Map([["busy_timeout",0],["journal_mode","wal"]]);var DurableObjectDatabase=class{constructor(storage){this.storage=storage}storage;open=true;exec(source){this.storage.sql.exec(source).toArray()}prepare(source){const all=(...params)=>this.storage.sql.exec(source,...params).toArray();return{all,get:(...params)=>all(...params)[0],run:(...params)=>{all(...params);return{changes:Number(this.storage.sql.exec("SELECT changes() AS changes").one()["changes"])}}}}pragma(source,options){const name59=source.split("=")[0].trim().toLowerCase();const rows=REFUSED_PRAGMAS.has(name59)?[{[name59]:REFUSED_PRAGMAS.get(name59)}]:this.storage.sql.exec(`PRAGMA ${source}`).toArray();return options?.simple?Object.values(rows[0]??{})[0]:rows}transaction(operation){return{immediate:()=>this.storage.transactionSync(operation)}}close(){this.open=false}};function durableObjectSqlite(storage){return()=>new DurableObjectDatabase(storage)}var import_utils510=require("@frontmcp/utils");var SqliteSessionStore=class{kv;keyPrefix;defaultTtlMs;constructor(options){this.kv=new SqliteKvStore(options);this.keyPrefix=options.keyPrefix??"mcp:session:";this.defaultTtlMs=options.defaultTtlMs??36e5}sessionKey(sessionId){return`${this.keyPrefix}${sessionId}`}async get(sessionId){return this.kv.getJSON(this.sessionKey(sessionId))}async set(sessionId,session,ttlMs){this.kv.setJSON(this.sessionKey(sessionId),session,ttlMs??this.defaultTtlMs)}async delete(sessionId){this.kv.del(this.sessionKey(sessionId))}async exists(sessionId){return this.kv.has(this.sessionKey(sessionId))}allocId(){return(0,import_utils510.randomUUID)()}close(){this.kv.close()}getKvStore(){return this.kv}};var import_node_events=require("node:events");function resultRoute(sessionId,elicitId){return`${sessionId.replace(/%/g,"%25").replace(/:/g,"%3A")}:${elicitId}`}function requireSubscriberSession2(sessionId){if(!sessionId){throw new Error("A result subscription needs the session ID the elicitation belongs to; pass it as the third argument")}return sessionId}var SqliteElicitationStore=class{kv;emitter;keyPrefix;constructor(options){this.kv=new SqliteKvStore(options);this.emitter=new import_node_events.EventEmitter;this.emitter.setMaxListeners(100);this.keyPrefix=options.keyPrefix??"mcp:elicit:"}pendingKey(sessionId){return`${this.keyPrefix}pending:${sessionId}`}fallbackKey(elicitId){return`${this.keyPrefix}fallback:${elicitId}`}resolvedKey(elicitId){return`${this.keyPrefix}resolved:${elicitId}`}resultChannel(sessionId,elicitId){return`result:${resultRoute(sessionId,elicitId)}`}fallbackResultChannel(sessionId,elicitId){return`fallback-result:${resultRoute(sessionId,elicitId)}`}async setPending(record){const ttlMs=record.expiresAt-Date.now();if(ttlMs<=0)return;this.kv.setJSON(this.pendingKey(record.sessionId),record,ttlMs)}async getPending(sessionId){return this.kv.getJSON(this.pendingKey(sessionId))}async deletePending(sessionId){this.kv.del(this.pendingKey(sessionId))}async subscribeResult(elicitId,callback,sessionId){const channel2=this.resultChannel(requireSubscriberSession2(sessionId),elicitId);const handler=result=>callback(result);this.emitter.on(channel2,handler);return async()=>{this.emitter.removeListener(channel2,handler)}}async publishResult(elicitId,sessionId,result){this.kv.del(this.pendingKey(sessionId));this.emitter.emit(this.resultChannel(sessionId,elicitId),result)}async setPendingFallback(record){const elicitId=record["elicitId"];if(!elicitId)return;this.kv.setJSON(this.fallbackKey(elicitId),record,3e5)}async getPendingFallback(elicitId,_sessionId){return this.kv.getJSON(this.fallbackKey(elicitId))}async deletePendingFallback(elicitId){this.kv.del(this.fallbackKey(elicitId))}async setResolvedResult(elicitId,result,_sessionId){this.kv.setJSON(this.resolvedKey(elicitId),result,3e5)}async getResolvedResult(elicitId,_sessionId){return this.kv.getJSON(this.resolvedKey(elicitId))}async deleteResolvedResult(elicitId){this.kv.del(this.resolvedKey(elicitId))}async subscribeFallbackResult(elicitId,callback,sessionId){const channel2=this.fallbackResultChannel(requireSubscriberSession2(sessionId),elicitId);const handler=result=>callback(result);this.emitter.on(channel2,handler);return async()=>{this.emitter.removeListener(channel2,handler)}}async publishFallbackResult(elicitId,sessionId,result){this.emitter.emit(this.fallbackResultChannel(sessionId,elicitId),result)}async destroy(){this.emitter.removeAllListeners();this.kv.close()}getKvStore(){return this.kv}};var import_node_events2=require("node:events");var import_utils610=require("@frontmcp/utils");var defaultLivenessProbe=pid=>{try{process.kill(pid,0);return true}catch{return false}};var DEFAULT_PAGE_SIZE3=50;var SqliteTaskStore=class{connection;db;emitter=new import_node_events2.EventEmitter;logger;liveness;cleanupTimer;encryptionKey=null;stmts=null;constructor(options){this.connection=acquireConnection(options.path,"SqliteTaskStore",{busyTimeoutMs:options.busyTimeoutMs,walMode:options.walMode!==false});this.db=this.connection.db;this.logger=options.logger;this.liveness=options.livenessProbe??defaultLivenessProbe;if(options.encryption?.secret){this.encryptionKey=deriveEncryptionKey(options.encryption.secret)}this.emitter.setMaxListeners(200);try{withBusyRetry(()=>this.initSchema());this.prepareStatements()}catch(error){this.connection.release();throw error}const cleanupInterval=options.ttlCleanupIntervalMs??6e4;if(cleanupInterval>0){this.cleanupTimer=setInterval(()=>this.purgeExpired(),cleanupInterval);this.cleanupTimer.unref?.()}else{this.cleanupTimer=null}}initSchema(){this.db.exec(`
195
195
  CREATE TABLE IF NOT EXISTS mcp_tasks (
196
196
  task_id TEXT PRIMARY KEY,
197
197
  session_id TEXT NOT NULL,
@@ -328,7 +328,7 @@ if nodeId == ARGV[1] then
328
328
  return 1
329
329
  end
330
330
  return 0
331
- `;RedisTransportBus=class{constructor(redis,machineId,options){this.redis=redis;this.machineId=machineId;this.keyPrefix=options?.keyPrefix??DEFAULT_BUS_PREFIX;this.ttlSeconds=options?.ttlSeconds??DEFAULT_BUS_TTL_SECONDS;this.haKeyPrefix=options?.haKeyPrefix??"mcp:ha:";this.retryAfterSeconds=options?.retryAfterSeconds??DEFAULT_RETRY_AFTER_SECONDS;this.logger=options?.logger}redis;machineId;keyPrefix;ttlSeconds;haKeyPrefix;retryAfterSeconds;logger;relay;nodeId(){return this.machineId}attachRelay(relay){this.relay=relay}canRelay(){return this.relay!==void 0}channelOf(nodeId){return`${this.haKeyPrefix}notify:${nodeId}`}async advertise(key){await this.redis.eval(ADVERTISE_LUA,1,this.busKey(key.sessionId),this.machineId,this.channelOf(this.machineId),key.type,key.tokenHash,this.ttlSeconds);this.logger?.debug("[TransportBus] Advertised session",{sessionId:key.sessionId.slice(0,20),nodeId:this.machineId})}async revoke(key){const redisKey=this.busKey(key.sessionId);const result=await this.redis.eval(REVOKE_LUA,1,redisKey,this.machineId);this.logger?.debug("[TransportBus] Revoked session",{sessionId:key.sessionId.slice(0,20),deleted:result===1})}async lookup(key){const entry=await this.readEntry(key.sessionId);if(!entry)return null;if(entry.nodeId===this.machineId)return null;if(entry.type&&entry.type!==key.type||entry.tokenHash&&entry.tokenHash!==key.tokenHash){return null}return{nodeId:entry.nodeId,channel:entry.channel}}async lookupOwner(sessionId){const entry=await this.readEntry(sessionId);return entry?{nodeId:entry.nodeId,channel:entry.channel}:null}async proxyRequest(location,sessionId,request2,response){if(isRelayedRequest(request2)){throw new SessionOwnerUnreachableError(location.nodeId,this.retryAfterSeconds,"the request was already relayed once and its session moved again")}if(!this.relay){throw new SessionOwnerUnreachableError(location.nodeId,this.retryAfterSeconds,"request relay is not available on this node (no Redis pub/sub)")}await this.relay.forward(location.nodeId,sessionId,serializeRelayRequest(request2),response)}async destroyRemote(key,reason){const entry=await this.readEntry(key.sessionId);if(!entry||entry.nodeId===this.machineId)return;const message=JSON.stringify({kind:"destroy-session",sessionId:key.sessionId,reason,sourceNodeId:this.machineId,timestamp:Date.now()});await this.redis.publish(entry.channel,message);this.logger?.info("[TransportBus] Sent destroy-remote",{sessionId:key.sessionId.slice(0,20),targetNodeId:entry.nodeId})}async readEntry(sessionId){const fields=await this.redis.hgetall(this.busKey(sessionId));const nodeId=fields?.["nodeId"];if(!nodeId)return null;return{nodeId,channel:fields["channel"]||this.channelOf(nodeId),type:fields["type"]||void 0,tokenHash:fields["tokenHash"]||void 0}}busKey(sessionId){return`${this.keyPrefix}session:${sessionId}`}}}});var bus_exports={};__export(bus_exports,{RedisTransportBus:()=>RedisTransportBus});var init_bus=__esm({"libs/sdk/src/transport/bus/index.ts"(){"use strict";init_redis_transport_bus()}});var MemoryEventStore;var init_memory_event_store=__esm({"libs/sdk/src/transport/event-stores/memory.event-store.ts"(){"use strict";MemoryEventStore=class{streams=new Map;index=new Map;maxEvents;ttlMs;constructor(options={}){this.maxEvents=options.maxEvents??1e4;this.ttlMs=options.ttlMs??3e5}async storeEvent(streamId,message){this.evictExpired();const list=this.streams.get(streamId)??[];const id=`${streamId}:${list.length+1}`;const rec={id,msg:message,timestamp:Date.now()};list.push(rec);this.streams.set(streamId,list);this.index.set(id,{streamId,idx:list.length-1});if(this.index.size>this.maxEvents){this.evictOldest()}return id}async getStreamIdForEventId(eventId){return this.index.get(eventId)?.streamId}async replayEventsAfter(lastEventId,{send}){const meta=this.index.get(lastEventId);if(!meta){const freshStream="default-stream";if(!this.streams.has(freshStream))this.streams.set(freshStream,[]);return freshStream}const{streamId,idx}=meta;const list=this.streams.get(streamId)??[];for(let k=idx+1;k<list.length;k++){const e=list[k];if(Date.now()-e.timestamp<this.ttlMs){await send(e.id,e.msg)}}return streamId}evictExpired(){const now=Date.now();for(const[streamId,list]of this.streams){const validEvents=list.filter(e=>now-e.timestamp<this.ttlMs);if(validEvents.length<list.length){this.streams.set(streamId,validEvents);this.rebuildIndex(streamId,validEvents)}}}evictOldest(){let oldest=null;for(const[streamId,list]of this.streams){if(list.length>0&&(!oldest||list[0].timestamp<oldest.timestamp)){oldest={streamId,idx:0,timestamp:list[0].timestamp}}}if(oldest){const list=this.streams.get(oldest.streamId);if(list&&list.length>0){const removed=list.shift();if(removed){this.index.delete(removed.id)}this.rebuildIndex(oldest.streamId,list)}}}rebuildIndex(streamId,list){for(const[id,meta]of this.index){if(meta.streamId===streamId){this.index.delete(id)}}list.forEach((e,idx)=>this.index.set(e.id,{streamId,idx}))}clear(){this.streams.clear();this.index.clear()}get size(){return this.index.size}}}});var import_utils147,RedisEventStore;var init_redis_event_store=__esm({"libs/sdk/src/transport/event-stores/redis.event-store.ts"(){"use strict";import_utils147=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 Redis=require("ioredis");const{host,port,password,db,tls}=redis;this.client=new Redis({host,port,password,db,tls:tls?{}:void 0,lazyConnect:true,enableReadyCheck:false,maxRetriesPerRequest:3});(0,import_utils147.attachRedisErrorListener)(this.client,{label:"RedisEventStore"});await this.client.connect()}return this.client}async storeEvent(streamId,message){const client=await this.getClient();const streamKey=`${this.keyPrefix}${streamId}`;const redisId=await client.xadd(streamKey,"MAXLEN","~",this.maxEvents.toString(),"*","msg",JSON.stringify(message));await client.expire(streamKey,this.ttlSeconds);return`${streamId}:${redisId}`}async getStreamIdForEventId(eventId){const parsed=this.parseEventId(eventId);return parsed?parsed[0]:void 0}async replayEventsAfter(lastEventId,{send}){const parsed=this.parseEventId(lastEventId);if(!parsed){return"default-stream"}const client=await this.getClient();const[streamId,redisId]=parsed;const streamKey=`${this.keyPrefix}${streamId}`;const entries=await client.xrange(streamKey,`(${redisId}`,"+");for(const[id,fields]of entries){const msgIndex=fields.indexOf("msg");if(msgIndex!==-1&&msgIndex+1<fields.length){const msgStr=fields[msgIndex+1];const msg=JSON.parse(msgStr);await send(`${streamId}:${id}`,msg)}}return streamId}parseEventId(eventId){const value=String(eventId);const lastDash=value.lastIndexOf("-");const separator=lastDash===-1?value.lastIndexOf(":"):value.lastIndexOf(":",lastDash);if(separator<=0||separator===value.length-1)return void 0;const streamId=value.slice(0,separator);const redisId=value.slice(separator+1);if(!/^\d+(-\d+)?$/.test(redisId))return void 0;return[streamId,redisId]}async close(){if(this.client){await this.client.quit();this.client=void 0}}}}});function createEventStore(config,logger){if(!config?.enabled){logger?.verbose("[EventStoreFactory] EventStore disabled (resumability not available)");return{eventStore:void 0,type:"disabled"}}const provider=config.provider??"memory";const maxEvents=config.maxEvents??1e4;const ttlMs=config.ttlMs??3e5;if(provider==="sqlite"){if(!config.sqlite||!config.sqlite.path){throw new PublicMcpError('EventStore SQLite configuration required when provider is "sqlite". Provide sqlite config: { provider: "sqlite", sqlite: { path: "..." } }',"INVALID_PARAMS")}const{SqliteEventStore}=(0,import_utils48.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_utils148.sha256Hex)(sessionId).slice(0,12)}var import_utils148;var init_session_id_hash=__esm({"libs/sdk/src/logger/session-id-hash.ts"(){"use strict";import_utils148=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_utils149,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_utils149=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_utils149.TypedStorage(storage.namespace("pending"));this.fallback=new import_utils149.TypedStorage(storage.namespace("fallback"));this.resolved=new import_utils149.TypedStorage(storage.namespace("resolved"))}async setPending(record){const{sessionId,expiresAt}=record;const ttlSeconds=(0,import_utils149.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_utils149.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_utils150.getEnv)("UPSTASH_REDIS_REST_URL")){return"upstash"}if((0,import_utils150.getEnv)("REDIS_URL")||(0,import_utils150.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: ... }')}const{host,port,password,db,tls}=redisOptions;finalStorageConfig={type:"redis",redis:{config:{host,port,password,db,tls}}};logger?.debug("[ElicitationStoreFactory] Converted redis option to storage config",{host,port})}const explicitBackend=Boolean(storageConfig||redis);if(finalStorageConfig?.type==="vercel-kv"||!explicitBackend&&(0,import_utils150.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_utils150.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_utils150.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_utils48.requireOptionalModule)("@frontmcp/storage-sqlite",()=>require_dist());logger?.info("[ElicitationStoreFactory] Creating SQLite elicitation store",{path:sqliteConfig.path,keyPrefix});return new SqliteElicitationStore({...sqliteConfig,keyPrefix})}var import_utils150;var init_elicitation_store_factory=__esm({"libs/sdk/src/elicitation/store/elicitation-store.factory.ts"(){"use strict";import_utils150=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()}});function recordKey(sessionId,taskId){return`${sessionId}:${taskId}`}function slotKey(sessionId,slot){return`${sessionId}:${slot}`}function encodeCursor(offset){return(0,import_utils151.base64urlEncode)(new TextEncoder().encode(JSON.stringify({offset})))}function decodeCursor(cursor){try{const bytes=(0,import_utils151.base64urlDecode)(cursor);const parsed=JSON.parse(new TextDecoder().decode(bytes));if(typeof parsed?.offset==="number"&&parsed.offset>=0&&Number.isInteger(parsed.offset)){return parsed.offset}}catch{}return 0}var import_utils151,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_utils151=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;logger;terminalCallbacks=new Map;terminalSubs=new Map;cancelCallbacks=new Map;cancelSubs=new Map;constructor(storage,logger){this.storage=storage;this.logger=logger;this.records=new import_utils151.TypedStorage(storage.namespace(RECORDS_NAMESPACE));this.slots=storage.namespace(SLOTS_NAMESPACE)}async create(record){const ttlSeconds=(0,import_utils151.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 this.records.set(key,record,{ttlSeconds});this.logger?.debug("[StorageTaskStore] created",{taskId:record.taskId,ttlSeconds})}async createWithinLimit(record,maxActive){const ttlSeconds=(0,import_utils151.expiresAtToTTL)(record.expiresAt);if(ttlSeconds<=0){await this.create(record);return true}const slot=await this.acquireSlot(record,maxActive,ttlSeconds);if(slot===void 0)return false;const slotted={...record,concurrencySlot:slot};try{await this.create(slotted)}catch(err){await this.releaseSlot(slotted);throw err}return true}async get(taskId,sessionId){const record=await this.records.get(recordKey(sessionId,taskId));if(!record)return null;if(record.sessionId!==sessionId)return null;if(record.expiresAt&&Date.now()>record.expiresAt){await this.delete(taskId,sessionId);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_utils151.expiresAtToTTL)(merged.expiresAt);if(ttlSeconds<=0){await this.delete(taskId,sessionId);return null}await this.records.set(recordKey(sessionId,taskId),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)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 namespaced=this.storage.namespace(RECORDS_NAMESPACE);const allKeys=await namespaced.keys();const sessionPrefix=`${sessionId}:`;const matching=allKeys.filter(k=>k.startsWith(sessionPrefix)).map(k=>k.slice(sessionPrefix.length)).sort();const offset=opts.cursor?decodeCursor(opts.cursor):0;const slice=matching.slice(offset,offset+pageSize);const records=[];for(const taskId of slice){const rec=await this.get(taskId,sessionId);if(rec)records.push(rec)}const nextOffset=offset+slice.length;const page2={tasks:records};if(nextOffset<matching.length){page2.nextCursor=encodeCursor(nextOffset)}return page2}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_utils152.getEnv)("UPSTASH_REDIS_REST_URL"))return"upstash";if((0,import_utils152.getEnv)("REDIS_URL")||(0,import_utils152.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_utils48.requireOptionalModule)("@frontmcp/storage-sqlite",()=>require_dist());const store2=new SqliteTaskStore({path:sqlite.path,encryption:sqlite.encryption,walMode:sqlite.walMode??true,ttlCleanupIntervalMs:sqlite.ttlCleanupIntervalMs??6e4,busyTimeoutMs:sqlite.busyTimeoutMs,logger:logger?{debug:(m,meta)=>logger.debug(m,meta),warn:(m,meta)=>logger.warn(m,meta),error:(m,meta)=>logger.error(m,meta)}:void 0});logger?.info("[TaskStoreFactory] Created SQLite task store",{path:sqlite.path,keyPrefix});return{store:store2,type:"sqlite"}}let finalStorageConfig=storageConfig;if(redis&&!isExplicitStorage(storageConfig)){const redisOptions=normalizeRedisOptions(redis);if(typeof redisOptions==="string"){throw new TaskStoreNotSupportedError(`Invalid Redis configuration: ${redisOptions}`)}if(isVercelKvProvider(redisOptions)){throw new TaskStoreNotSupportedError("Vercel KV is not supported for task stores. Task result blocking and cancel signalling require pub/sub. Use Redis or Upstash instead.")}const{host,port,password,db,tls}=redisOptions;finalStorageConfig={type:"redis",redis:{config:{host,port,password,db,tls}}}}const explicitBackend=isExplicitStorage(storageConfig)||Boolean(redis);if(finalStorageConfig?.type==="vercel-kv"||!explicitBackend&&(0,import_utils152.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_utils152.createStorage)({...finalStorageConfig,prefix:keyPrefix,fallback:isEdgeRuntime4?"error":"memory"});const store=new StorageTaskStore(storage,logger);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_utils152.createMemoryStorage)({prefix:keyPrefix});return{store:new StorageTaskStore(storage,logger),type:"memory",storage}}var import_utils152,TaskStoreNotSupportedError;var init_task_store_factory=__esm({"libs/sdk/src/task/store/task-store.factory.ts"(){"use strict";import_utils152=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_utils153.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;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_utils153;var init_task_runner=__esm({"libs/sdk/src/task/helpers/task-runner.ts"(){"use strict";import_utils153=require("@frontmcp/utils");init_errors();init_call_tool_error_utils();init_mcp_error_utils();init_task_types()}});var InProcessTaskRunner;var init_in_process_task_runner=__esm({"libs/sdk/src/task/helpers/in-process-task-runner.ts"(){"use strict";init_task_runner();InProcessTaskRunner=class{constructor(deps){this.deps=deps}deps;kind="in-process";async run(record,context){await this.deps.store.update(record.taskId,record.sessionId,{executor:{host:"in-process",spawnedAt:new Date().toISOString()}});void runTaskInBackground({record,cleanedRequestParams:context.cleanedRequestParams,ctx:context.ctx,scope:this.deps.scope,store:this.deps.store,registry:this.deps.registry,notifier:this.deps.notifier,logger:this.deps.logger})}async cancel(record){this.deps.registry.abort(record.taskId,"tasks/cancel")}}}});var import_lazy_zod119,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_zod119=require("@frontmcp/lazy-zod");import_protocol68=require("@frontmcp/protocol");init_common();init_errors();init_task_types();inputSchema21=import_lazy_zod119.internalZ.object({request:import_protocol68.GetTaskRequestSchema,ctx:import_lazy_zod119.internalZ.any()});outputSchema20=import_protocol68.GetTaskResultSchema;stateSchema25=import_lazy_zod119.internalZ.object({taskId:import_lazy_zod119.internalZ.string(),sessionId:import_lazy_zod119.internalZ.string(),authInfo:import_lazy_zod119.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_zod119.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_zod120,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_zod120=require("@frontmcp/lazy-zod");import_protocol69=require("@frontmcp/protocol");init_common();init_errors();init_task_types();inputSchema22=import_lazy_zod120.internalZ.object({request:import_protocol69.GetTaskPayloadRequestSchema,ctx:import_lazy_zod120.internalZ.any()});outputSchema21=import_protocol69.GetTaskPayloadResultSchema;stateSchema26=import_lazy_zod120.internalZ.object({taskId:import_lazy_zod120.internalZ.string(),sessionId:import_lazy_zod120.internalZ.string(),authInfo:import_lazy_zod120.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_zod120.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((resolve4,reject)=>{let settled=false;let unsubscribe;let pollTimer;const finalize=async(result,err)=>{if(settled)return;settled=true;if(pollTimer)clearTimeout(pollTimer);if(unsubscribe){try{await unsubscribe()}catch{}}if(err)reject(err);else resolve4(result)};const poll=async()=>{if(settled)return;try{const latest=await store.get(taskId,sessionId);if(!latest)return void finalize(null);if(isTerminal(latest.status))return void finalize(latest)}catch(err){return void finalize(null,err)}pollTimer=setTimeout(()=>void poll(),this.pollDelayMs())};store.subscribeTerminal(taskId,sessionId,record=>{if(isTerminal(record.status)){void finalize(record)}}).then(async unsub=>{unsubscribe=unsub;const latest=await store.get(taskId,sessionId);if(!latest){return void finalize(null)}if(isTerminal(latest.status)){return void finalize(latest)}pollTimer=setTimeout(()=>void poll(),this.pollDelayMs(latest.pollIntervalMs))}).catch(err=>void finalize(null,err))})}pollDelayMs(hint){const min=200;const max=5e3;if(typeof hint==="number"&&hint>0)return Math.max(min,Math.min(hint,max));return 500}respondWithOutcome(record){if(!record.outcome){throw new InternalMcpError("Terminal task has no outcome","TASK_MISSING_OUTCOME")}if(record.outcome.kind==="error"){const{code,message,data}=record.outcome.error;const err=new JsonRpcReplayError(code,message,data,record.taskId);throw err}const payload={...record.outcome.data};const existingMeta=payload["_meta"]??{};payload["_meta"]={...existingMeta,[RELATED_TASK_META_KEY]:{taskId:record.taskId}};this.respond(payload)}};__decorateClass([Stage29("parseInput")],TasksResultFlow.prototype,"parseInput",1);__decorateClass([Stage29("awaitTerminal")],TasksResultFlow.prototype,"awaitTerminal",1);TasksResultFlow=__decorateClass([FrontMcpFlow({name:name29,plan:plan29,inputSchema:inputSchema22,outputSchema:outputSchema21,access:"authorized"})],TasksResultFlow);JsonRpcReplayError=class extends Error{constructor(code,message,data,taskId){super(message);this.code=code;this.data=data;this.taskId=taskId;this.name="JsonRpcReplayError"}code;data;taskId;toJsonRpcError(){const out={code:this.code,message:this.message};if(this.data!==void 0)out.data=this.data;return out}}}});var import_lazy_zod121,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_zod121=require("@frontmcp/lazy-zod");import_protocol70=require("@frontmcp/protocol");init_common();init_errors();init_task_types();inputSchema23=import_lazy_zod121.internalZ.object({request:import_protocol70.CancelTaskRequestSchema,ctx:import_lazy_zod121.internalZ.any()});outputSchema22=import_protocol70.CancelTaskResultSchema;stateSchema27=import_lazy_zod121.internalZ.object({taskId:import_lazy_zod121.internalZ.string(),sessionId:import_lazy_zod121.internalZ.string(),authInfo:import_lazy_zod121.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_zod121.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_zod122,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_zod122=require("@frontmcp/lazy-zod");import_protocol71=require("@frontmcp/protocol");init_common();init_errors();init_task_types();inputSchema24=import_lazy_zod122.internalZ.object({request:import_protocol71.ListTasksRequestSchema,ctx:import_lazy_zod122.internalZ.any()});outputSchema23=import_protocol71.ListTasksResultSchema;stateSchema28=import_lazy_zod122.internalZ.object({sessionId:import_lazy_zod122.internalZ.string(),cursor:import_lazy_zod122.internalZ.string().optional(),authInfo:import_lazy_zod122.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_zod122.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_auth54.isAnonymousSubject)(candidate));return principal?`principal:${principal}`:void 0}var import_auth54;var init_session_scope_identity=__esm({"libs/sdk/src/auth/session-scope-identity.ts"(){"use strict";import_auth54=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_auth55.InMemoryAuthorizationVault){const providers=[];providers.push({provide:import_auth55.AUTH_PROVIDERS_REGISTRY,scope:import_di48.ProviderScope.GLOBAL,name:"AuthProvidersRegistry",useFactory:()=>new import_auth55.AuthProvidersRegistry(options)});providers.push({provide:import_auth55.AUTH_PROVIDERS_VAULT,scope:import_di48.ProviderScope.GLOBAL,name:"AuthProvidersVault",useFactory:logger=>new import_auth55.AuthProvidersVault(store.storage,{namespace:options.namespace,defaultCacheTtl:options.defaultCacheTtl,pepper:store.pepper,logger}),inject:()=>[FrontMcpLogger]});providers.push({provide:CREDENTIAL_CACHE,scope:import_di48.ProviderScope.CONTEXT,name:"CredentialCache",useFactory:()=>new import_auth55.CredentialCache(options.maxCredentialsPerSession??100)});providers.push({provide:LAZY_CREDENTIAL_LOADER,scope:import_di48.ProviderScope.CONTEXT,name:"LazyCredentialLoader",useFactory:logger=>new import_auth55.LazyCredentialLoader(logger),inject:()=>[FrontMcpLogger]});providers.push({provide:import_auth55.AUTH_PROVIDERS_ACCESSOR,scope:import_di48.ProviderScope.CONTEXT,name:"AuthProvidersAccessor",useFactory:(registry,vault,cache2,loader,ctx,logger)=>{const user=ctx.authInfo?.user;const signedIn=user&&!(0,import_auth55.isAnonymousSubject)(user.sub)?user:void 0;const factoryContext={sessionId:sessionScopeIdentity(ctx)??`${import_auth55.UNIDENTIFIED_SESSION_PREFIX}${(0,import_utils154.randomUUID)()}`,userSub:signedIn?.sub,userEmail:signedIn?.email,userName:signedIn?.name,vault:baseVault};return new import_auth55.AuthProvidersAccessorImpl(registry,vault,cache2,loader,factoryContext,logger)},inject:()=>[import_auth55.AUTH_PROVIDERS_REGISTRY,import_auth55.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_utils154.getEnv)("VAULT_SECRET")||(0,import_utils154.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_utils154.createStorage)({type:"memory"});await providers.addDynamicProviders(createAuthProvidersProviders(options,{storage}));return()=>storage.disconnect()}var import_auth55,import_di48,import_utils154,LAZY_CREDENTIAL_LOADER;var init_auth_providers_providers=__esm({"libs/sdk/src/auth/vault/auth-providers.providers.ts"(){"use strict";import_auth55=require("@frontmcp/auth");import_di48=require("@frontmcp/di");import_utils154=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_utils155.getRuntimeContext)().runtime==="browser"?"console":"stdout"}]}function observabilityPlugins({config:observabilityConfig,logger,globalProviders,implied=false}){const plugins=[];let ObservabilityPluginModule;try{ObservabilityPluginModule=(0,import_utils48.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_utils155;var init_observability_scope_helper=__esm({"libs/sdk/src/scope/observability-scope.helper.ts"(){"use strict";import_utils155=require("@frontmcp/utils");init_context();init_logger_registry();init_optional_dependency_util();init_tracer_provider_utils()}});var import_lazy_zod123,import_utils156,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_zod123=require("@frontmcp/lazy-zod");import_utils156=require("@frontmcp/utils");init_common();init_errors();init_session_id_hash();init_elicitation_types();inputSchema25=import_lazy_zod123.internalZ.object({relatedRequestId:import_lazy_zod123.internalZ.union([import_lazy_zod123.internalZ.string(),import_lazy_zod123.internalZ.number()]),sessionId:import_lazy_zod123.internalZ.string(),message:import_lazy_zod123.internalZ.string(),requestedSchema:import_lazy_zod123.internalZ.record(import_lazy_zod123.internalZ.string(),import_lazy_zod123.internalZ.unknown()),options:import_lazy_zod123.internalZ.object({mode:import_lazy_zod123.internalZ.enum(["form","url"]).optional(),ttl:import_lazy_zod123.internalZ.number().optional(),elicitationId:import_lazy_zod123.internalZ.string().optional(),url:import_lazy_zod123.internalZ.string().optional()}).optional()});outputSchema24=import_lazy_zod123.internalZ.object({elicitId:import_lazy_zod123.internalZ.string(),sessionId:import_lazy_zod123.internalZ.string(),expiresAt:import_lazy_zod123.internalZ.number(),mode:import_lazy_zod123.internalZ.enum(["form","url"]),requestParams:import_lazy_zod123.internalZ.record(import_lazy_zod123.internalZ.string(),import_lazy_zod123.internalZ.unknown()),pendingRecord:import_lazy_zod123.internalZ.any()});stateSchema29=import_lazy_zod123.internalZ.object({relatedRequestId:import_lazy_zod123.internalZ.union([import_lazy_zod123.internalZ.string(),import_lazy_zod123.internalZ.number()]),sessionId:import_lazy_zod123.internalZ.string(),message:import_lazy_zod123.internalZ.string(),requestedSchema:import_lazy_zod123.internalZ.record(import_lazy_zod123.internalZ.string(),import_lazy_zod123.internalZ.unknown()),mode:import_lazy_zod123.internalZ.enum(["form","url"]).default("form"),ttl:import_lazy_zod123.internalZ.number().default(DEFAULT_ELICIT_TTL),elicitationId:import_lazy_zod123.internalZ.string().optional(),url:import_lazy_zod123.internalZ.string().optional(),elicitId:import_lazy_zod123.internalZ.string(),expiresAt:import_lazy_zod123.internalZ.number(),pendingRecord:import_lazy_zod123.internalZ.any().optional(),requestParams:import_lazy_zod123.internalZ.record(import_lazy_zod123.internalZ.string(),import_lazy_zod123.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,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_utils156.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 store=this.scope.elicitationStore;if(!store){throw new ElicitationStoreNotInitializedError}const pendingRecord={elicitId,sessionId,createdAt:Date.now(),expiresAt,message,mode,requestedSchema};await store.setPending(pendingRecord);this.state.set("pendingRecord",pendingRecord);this.logger.verbose("storePendingRecord:done",{elicitId,sessionIdHash:sessionIdHash(sessionId)})}async buildRequestParams(){this.logger.verbose("buildRequestParams:start");const{mode,message,requestedSchema,elicitId}=this.state.required;const requestParams={mode,message,requestedSchema};if(mode==="url"){requestParams["elicitationId"]=elicitId;requestParams["url"]=this.state.url}this.state.set("requestParams",requestParams);this.logger.verbose("buildRequestParams:done")}async finalize(){this.logger.verbose("finalize:start");const{elicitId,sessionId,expiresAt,mode}=this.state.required;const{requestParams,pendingRecord}=this.state;if(!requestParams||!pendingRecord){throw new InvalidInputError("finalize: missing requestParams or pendingRecord from prior stages")}this.respond({elicitId,sessionId,expiresAt,mode,requestParams,pendingRecord});this.logger.verbose("finalize:done")}};__decorateClass([Stage32("parseInput")],ElicitationRequestFlow.prototype,"parseInput",1);__decorateClass([Stage32("validateRequest")],ElicitationRequestFlow.prototype,"validateRequest",1);__decorateClass([Stage32("generateElicitId")],ElicitationRequestFlow.prototype,"generateElicitId",1);__decorateClass([Stage32("storePendingRecord")],ElicitationRequestFlow.prototype,"storePendingRecord",1);__decorateClass([Stage32("buildRequestParams")],ElicitationRequestFlow.prototype,"buildRequestParams",1);__decorateClass([Stage32("finalize")],ElicitationRequestFlow.prototype,"finalize",1);ElicitationRequestFlow=__decorateClass([FrontMcpFlow({name:name32,plan:plan32,inputSchema:inputSchema25,outputSchema:outputSchema24,access:"authorized"})],ElicitationRequestFlow)}});var import_lazy_zod124,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_zod124=require("@frontmcp/lazy-zod");init_common();init_errors();init_session_id_hash();init_helpers();inputSchema26=import_lazy_zod124.internalZ.object({sessionId:import_lazy_zod124.internalZ.string(),result:import_lazy_zod124.internalZ.object({action:import_lazy_zod124.internalZ.enum(["accept","cancel","decline"]),content:import_lazy_zod124.internalZ.unknown().optional()})});outputSchema25=import_lazy_zod124.internalZ.object({handled:import_lazy_zod124.internalZ.boolean(),elicitId:import_lazy_zod124.internalZ.string().optional(),result:import_lazy_zod124.internalZ.any().optional()});stateSchema30=import_lazy_zod124.internalZ.object({sessionId:import_lazy_zod124.internalZ.string(),action:import_lazy_zod124.internalZ.enum(["accept","cancel","decline"]),content:import_lazy_zod124.internalZ.unknown().optional(),pendingRecord:import_lazy_zod124.internalZ.any().optional(),elicitResult:import_lazy_zod124.internalZ.any().optional(),handled:import_lazy_zod124.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,action:input.result.action,content:input.result.content});this.logger.verbose("parseInput:done",{sessionIdHash:sessionIdHash(input.sessionId),action:input.result.action})}async lookupPending(){this.logger.verbose("lookupPending:start");const{sessionId}=this.state.required;const store=this.scope.elicitationStore;if(!store){throw new ElicitationStoreNotInitializedError}const pendingRecord=await store.getPending(sessionId);this.state.set("pendingRecord",pendingRecord??void 0);if(!pendingRecord){this.logger.verbose("lookupPending:notFound",{sessionIdHash:sessionIdHash(sessionId)})}else{this.logger.verbose("lookupPending:found",{sessionIdHash:sessionIdHash(sessionId),elicitId:pendingRecord.elicitId})}}async validateContent(){this.logger.verbose("validateContent:start");const{action,content,pendingRecord}=this.state;if(action!=="accept"){this.logger.verbose("validateContent:skip (non-accept action)",{action});return}if(!pendingRecord){this.logger.verbose("validateContent:skip (no pending record)");return}if(pendingRecord.mode==="url"){this.logger.verbose("validateContent:skip (url mode)");return}if(!pendingRecord.requestedSchema){this.logger.verbose("validateContent:skip (no schema stored)");return}const validationResult=validateElicitationContent(content,pendingRecord.requestedSchema);if(!validationResult.success){this.logger.warn("validateContent:failed",{sessionIdHash:sessionIdHash(pendingRecord.sessionId),elicitId:pendingRecord.elicitId,errors:validationResult.errors});throw new InvalidInputError("Invalid elicitation result content",validationResult.errors)}this.logger.verbose("validateContent:done")}async buildResult(){this.logger.verbose("buildResult:start");const{action}=this.state.required;const{content,pendingRecord}=this.state;const keepsContent=action==="accept"&&content!==void 0&&pendingRecord?.mode!=="url";const elicitResult={status:action,...keepsContent&&{content}};this.state.set("elicitResult",elicitResult);this.logger.verbose("buildResult:done",{status:elicitResult.status})}async publishResult(){this.logger.verbose("publishResult:start");const{pendingRecord,elicitResult}=this.state;const{sessionId}=this.state.required;const store=this.scope.elicitationStore;if(!pendingRecord||!elicitResult||!store){this.state.set("handled",false);this.logger.verbose("publishResult:skip (no pending or no result)");return}try{await store.publishResult(pendingRecord.elicitId,sessionId,elicitResult);this.state.set("handled",true);this.logger.verbose("publishResult:done",{elicitId:pendingRecord.elicitId,sessionId:sessionId.slice(0,20)})}catch(error){this.logger.warn("publishResult:failed",{elicitId:pendingRecord.elicitId,error:error.message});this.state.set("handled",false)}}async finalize(){this.logger.verbose("finalize:start");const{handled,pendingRecord,elicitResult}=this.state;const output={handled:handled??false,elicitId:pendingRecord?.elicitId,result:elicitResult};this.state.set("output",output);this.respond(output);this.logger.verbose("finalize:done",{handled})}};__decorateClass([Stage33("parseInput")],ElicitationResultFlow.prototype,"parseInput",1);__decorateClass([Stage33("lookupPending")],ElicitationResultFlow.prototype,"lookupPending",1);__decorateClass([Stage33("validateContent")],ElicitationResultFlow.prototype,"validateContent",1);__decorateClass([Stage33("buildResult")],ElicitationResultFlow.prototype,"buildResult",1);__decorateClass([Stage33("publishResult")],ElicitationResultFlow.prototype,"publishResult",1);__decorateClass([Stage33("finalize")],ElicitationResultFlow.prototype,"finalize",1);ElicitationResultFlow=__decorateClass([FrontMcpFlow({name:name33,plan:plan33,inputSchema:inputSchema26,outputSchema:outputSchema25,access:"authorized"})],ElicitationResultFlow)}});var flows_exports2={};__export(flows_exports2,{ElicitRequestFlow:()=>ElicitationRequestFlow,ElicitResultFlow:()=>ElicitationResultFlow,ElicitationRequestFlow:()=>ElicitationRequestFlow,ElicitationResultFlow:()=>ElicitationResultFlow});var init_flows2=__esm({"libs/sdk/src/elicitation/flows/index.ts"(){"use strict";init_elicitation_request_flow();init_elicitation_result_flow()}});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_utils157.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_utils157,SERVER_CARD_MEDIA_TYPE,envVarsReportedInvalid;var init_mcp_registry_utils=__esm({"libs/sdk/src/mcp-registry/mcp-registry.utils.ts"(){"use strict";import_utils157=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_zod125,import_utils158,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_zod125=require("@frontmcp/lazy-zod");import_utils158=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_zod125.internalZ.object({card:import_lazy_zod125.internalZ.record(import_lazy_zod125.internalZ.string(),import_lazy_zod125.internalZ.unknown())});outputSchema27=import_lazy_zod125.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_utils158.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_zod126,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_zod126=require("@frontmcp/lazy-zod");init_common();init_mcp_registry_utils();AI_CATALOG_PATH="/.well-known/ai-catalog.json";inputSchema29=httpInputSchema;outputSchema28=import_lazy_zod126.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&&registryOptions.name&&registryOptions.serverCard!==false){flows.push(ServerCardFlow);if(registryOptions.aiCatalog!==false)flows.push(WellKnownAiCatalogFlow)}await flowRegistry.registryFlows(flows)}var init_mcp_registry_scope_helper=__esm({"libs/sdk/src/mcp-registry/mcp-registry-scope.helper.ts"(){"use strict";init_flows3()}});async function serveRelayedHttpRequest(scope,request2,response){let output;try{output=await scope.runFlow("http:request",{request:request2,response})}catch(error){output=flowErrorToHttpOutput(error)}if(output&&!response.writableEnded){await writeHttpResponse(response,output)}if(response.writableEnded)return;if(!response.headersSent){await writeHttpResponse(response,{kind:"json",status:404,contentType:"application/json; charset=utf-8",body:{error:"Not Found"}});return}response.end()}var init_relay_flow=__esm({"libs/sdk/src/transport/relay/relay-flow.ts"(){"use strict";init_server_validation();init_flow_error_output()}});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_utils159,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_utils159=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_utils159.randomUUID)();const sessionLabel=sessionId.slice(0,20);return new Promise((resolve4,reject)=>{let acked=false;let headWritten=false;let done=false;let lastFrameAt=Date.now();let ownerTimer;const cleanup=()=>{clearTimeout(ackTimer);if(ownerTimer)clearInterval(ownerTimer);response.removeListener("close",onClientClose);this.pending.delete(requestId)};const finish=()=>{if(done)return;done=true;cleanup();resolve4()};const fail=reason=>{if(done)return;done=true;cleanup();this.logger?.warn(`[HA] Relay to session owner failed: ${reason}`,{sessionId:sessionLabel,ownerNodeId});if(!headWritten&&!response.headersSent){reject(this.unreachable(ownerNodeId,reason));return}if(!response.writableEnded)response.end();resolve4()};const onClientClose=()=>{if(done||response.writableFinished)return;done=true;cleanup();this.options.publish(ownerNodeId,{kind:"relay-cancel",requestId,sourceNodeId:this.nodeId}).catch(()=>void 0);resolve4()};const checkOwner=async()=>{if(Date.now()-lastFrameAt>=this.ownerCheckIntervalMs*SILENT_CHECKS_BEFORE_FAILURE){fail("the owner stopped sending the response");return}try{if(!await this.options.isNodeAlive(ownerNodeId))fail("the owner stopped while serving the request")}catch{}};const markAcked=()=>{if(acked)return;acked=true;clearTimeout(ackTimer);ownerTimer=setInterval(()=>void checkOwner(),this.ownerCheckIntervalMs);ownerTimer.unref?.()};const onFrame=frame4=>{if(done)return;lastFrameAt=Date.now();switch(frame4.event){case"ack":markAcked();return;case"keepalive":return;case"head":markAcked();if(!response.headersSent){response.writeHead(frame4.status,frame4.headers);response.flushHeaders?.()}headWritten=true;return;case"data":response.write(decodeRelayChunk(frame4));return;case"end":if(!response.writableEnded)response.end();finish();return;case"error":fail(`the owner could not serve the request: ${frame4.message}`);return}};const ackTimer=setTimeout(()=>fail(`the owner did not acknowledge the request within ${this.ackTimeoutMs}ms`),this.ackTimeoutMs);ackTimer.unref?.();this.pending.set(requestId,{ownerNodeId,onFrame,fail});response.once("close",onClientClose);const message={kind:"relay-request",requestId,sourceNodeId:this.nodeId,sessionId,request:request2,timestamp:Date.now(),keepaliveMs:this.ownerCheckIntervalMs};this.logger?.verbose?.("[HA] Relaying request to session owner",{sessionId:sessionLabel,ownerNodeId});this.options.publish(ownerNodeId,message).then(receivers=>{if(receivers===0)fail("the owner does not listen on its relay channel")},error=>fail(`publishing the request failed: ${errorMessage(error)}`))})}handleMessage(message){switch(message.kind){case"relay-request":if(!isServableRequest(message)){this.logger?.warn("[HA] Dropped a malformed relayed request");return}this.serveRelayed(message).catch(error=>{this.logger?.warn("[HA] Serving a relayed request failed",{error:errorMessage(error)})});return;case"relay-response":{const pending=this.pending.get(message.requestId);if(pending&&pending.ownerNodeId===message.sourceNodeId)pending.onFrame(message);return}case"relay-cancel":{const serving=this.serving.get(message.requestId);if(serving&&serving.sourceNodeId===message.sourceNodeId)serving.response.destroy();return}default:return}}async close(){if(this.closed)return;this.closed=true;for(const pending of[...this.pending.values()])pending.fail("this node is shutting down");for(const serving of[...this.serving.values()]){if(!serving.response.writableEnded){serving.send({event:"error",message:"the owner is shutting down"});serving.response.destroy()}}this.serving.clear()}async serveRelayed(message){const{requestId,sourceNodeId}=message;let undeliverable=false;const publishFrame=event=>{const frame4={kind:"relay-response",requestId,sourceNodeId:this.nodeId,...event};return this.options.publish(sourceNodeId,frame4)};const abandon=reason=>{if(undeliverable)return;undeliverable=true;this.logger?.warn("[HA] Failed to publish a relayed response frame",{reason,targetNodeId:sourceNodeId});publishFrame({event:"error",message:reason}).catch(()=>void 0);response.destroy()};const send=event=>{if(undeliverable)return;publishFrame(event).then(receivers=>{if(receivers===0)abandon("the relaying node no longer listens")},error=>abandon(`publishing a response frame failed: ${errorMessage(error)}`))};const response=new RelayServerResponse({head:(status,headers)=>send({event:"head",status,headers}),data:chunk=>send({event:"data",...chunk}),end:()=>send({event:"end"})});if(this.closed){send({event:"error",message:"the owner is shutting down"});return}send({event:"ack"});const keepaliveTimer=setInterval(()=>send({event:"keepalive"}),keepaliveIntervalOf(message));keepaliveTimer.unref?.();this.serving.set(requestId,{sourceNodeId,response,send});try{const request2=createRelayedServerRequest(message.request,sourceNodeId);await this.options.serve(request2,response.asServerResponse())}catch(error){this.logger?.warn("[HA] Serving a relayed request failed",{sessionId:message.sessionId.slice(0,20),sourceNodeId,error:errorMessage(error)});if(!response.writableEnded&&!response.destroyed&&!response.headersSent){response.status(500).json(rpcError("Internal error"))}}finally{clearInterval(keepaliveTimer);if(!response.writableEnded&&!response.destroyed)response.end();this.serving.delete(requestId)}}}}});var relay_scope_helper_exports={};__export(relay_scope_helper_exports,{wireSessionRelay:()=>wireSessionRelay});function wireSessionRelay(options){const{haManager,bus,transportService,notifications,logger,nodeId}=options;if(!haManager.getRelay())return void 0;const config=haManager.getConfig();const relay=new SessionRelay({nodeId,publish:(target,message)=>haManager.publishToNode(target,message),isNodeAlive:target=>haManager.isNodeAlive(target),serve:(request2,response)=>serveRelayedHttpRequest(options.flows,request2,response),ackTimeoutMs:options.ackTimeoutMs,ownerCheckIntervalMs:config.heartbeatIntervalMs,retryAfterSeconds:Math.ceil(config.heartbeatTtlMs/1e3),logger});const handler=message=>{if(isRequestRelayMessage(message)){relay.handleMessage(message);return}if(message.kind==="destroy-session"){transportService.destroyLocalSession(message.sessionId,message.reason).catch(error=>{logger.warn("[HA] Failed to destroy a session on request of another node",{sessionId:message.sessionId.slice(0,20),error:error instanceof Error?error.message:String(error)})});return}if(message.kind===void 0||message.kind==="notification"){notifications.deliverRelayedNotification(message.sessionId,message.notification.method,message.notification.params)}};let closed=false;let retryTimer;let settleReady=()=>void 0;const ready=new Promise(resolve4=>{settleReady=resolve4;const attempt=failures=>{if(closed){resolve4();return}haManager.subscribeRelay(handler).then(()=>{if(closed){resolve4();return}bus.attachRelay(relay);logger.info("[HA] Request relay ready \u2014 sessions owned by other nodes are served through them");resolve4()},error=>{const delay=Math.min(SUBSCRIBE_RETRY_MAX_MS,SUBSCRIBE_RETRY_BASE_MS*2**failures);logger.warn(`[HA] Relay channel subscription failed \u2014 retrying in ${delay}ms`,{error:error instanceof Error?error.message:String(error)});retryTimer=setTimeout(()=>attempt(failures+1),delay);retryTimer.unref?.()})};attempt(0)});return{relay,ready,close:async()=>{closed=true;if(retryTimer)clearTimeout(retryTimer);settleReady();bus.attachRelay(void 0);await relay.close()}}}var SUBSCRIBE_RETRY_BASE_MS,SUBSCRIBE_RETRY_MAX_MS;var init_relay_scope_helper=__esm({"libs/sdk/src/transport/relay/relay-scope.helper.ts"(){"use strict";init_relay_messages();init_relay_flow();init_session_relay();SUBSCRIBE_RETRY_BASE_MS=1e3;SUBSCRIBE_RETRY_MAX_MS=3e4}});var ChannelNotificationService;var init_channel_notification_service=__esm({"libs/sdk/src/channel/channel-notification.service.ts"(){"use strict";init_notification_service();init_channel_utils();ChannelNotificationService=class{constructor(notificationService,logger,defaultMeta,sendThroughFlow){this.notificationService=notificationService;this.sendThroughFlow=sendThroughFlow;this.logger=logger.child("ChannelNotificationService");this.serverMeta={...defaultMeta??{}}}notificationService;sendThroughFlow;logger;serverMeta;streamListeners=new Set;get defaultMeta(){return this.serverMeta}sendToSubscribedSessions(content,meta){const channelName=meta.source;if(!channelName){this.logger.warn("Cannot send channel notification without source in meta");return}const safeMeta=this.safeMetaOf(meta);for(const listener of this.streamListeners){if(listener.channels.has(channelName))listener.deliver(content,safeMeta)}const subscribers=this.notificationService.getSubscribersForChannel(channelName);if(subscribers.length===0){this.logger.verbose(`No subscribers for channel "${channelName}", notification buffered only`);return}const recipients=new Set(subscribers.filter(sessionId=>{const registered=this.notificationService.getRegisteredServer(sessionId);return registered!==void 0&&isChannelCapableSession(registered)&&!hasExpiredCaller(registered)}));if(recipients.size>0){this.notificationService.sendCustomNotification(CHANNEL_NOTIFICATION_METHOD,{content,meta:safeMeta},session=>recipients.has(session.sessionId))}this.logger.verbose(`Sent channel "${channelName}" notification to ${subscribers.length} subscriber(s)`)}listen(channelNames,deliver){const listener={channels:new Set(channelNames),deliver};this.streamListeners.add(listener);return()=>{this.streamListeners.delete(listener)}}sendToAllCapableSessions(content,meta){this.sendToSubscribedSessions(content,meta)}sendToSession(sessionId,content,meta){const registered=this.notificationService.getRegisteredServer(sessionId);if(!registered){this.logger.warn(`Cannot send channel notification to unregistered session: ${sessionId.slice(0,20)}...`);return false}if(!isChannelCapableSession(registered)){this.logger.verbose(`Session ${sessionId.slice(0,20)}... does not support channels, skipping`);return false}if(hasExpiredCaller(registered)){this.logger.verbose(`Session ${sessionId.slice(0,20)}... was last seen with expired credentials, skipping`);return false}const channelName=meta.source;if(!channelName){this.logger.error(`Channel notification rejected for session ${sessionId.slice(0,20)}...: meta.source is required`);return false}if(!this.notificationService.isChannelSubscribed(sessionId,channelName)){this.logger.verbose(`Session ${sessionId.slice(0,20)}... not subscribed to channel "${channelName}", skipping`);return false}this.notificationService.sendCustomNotification(CHANNEL_NOTIFICATION_METHOD,{content,meta:this.safeMetaOf(meta)},session=>session.sessionId===sessionId);return true}safeMetaOf(meta){return{...channelMetaOf(meta),source:meta.source}}async send(channelName,content,additionalMeta){if(!this.sendThroughFlow){const ownMeta=channelMetaValuesOf(additionalMeta??{});this.sendToSubscribedSessions(content,{...this.serverMeta,...ownMeta,source:channelName});return}try{await this.sendThroughFlow({channelName,content,meta:additionalMeta})}catch(error){this.logger.error(`Channel "${channelName}" notification failed`,{error})}}}}});var ChannelEmitter;var init_channel_events=__esm({"libs/sdk/src/channel/channel.events.ts"(){"use strict";ChannelEmitter=class{listeners=new Set;on(l){this.listeners.add(l);return()=>this.listeners.delete(l)}emit(e){for(const l of[...this.listeners])l(e)}}}});function connectsItself(context){return context.onConnect!==ChannelContext.prototype.onConnect}function watchedTypesOf(sourceConfig){if(!sourceConfig.events)return void 0;const watchedTypes=sourceConfig.events.flatMap(declaredEvent=>WATCHED_TYPES[declaredEvent]);return[...new Set(watchedTypes)]}function warnAboutGlobs(channelName,paths,logger){const globs=paths.filter(path4=>path4.includes("*"));if(globs.length===0)return;logger.warn(`Channel "${channelName}" declares ${globs.map(glob=>`"${glob}"`).join(", ")}: a file-watcher path is not expanded as a glob. Declare the directory to watch its direct files.`)}async function forwardFileEvents(channel2,sourceConfig,signal,logger){const events=watchedTypesOf(sourceConfig);for await(const{type,path:path4}of(0,import_utils160.watchFiles)(sourceConfig.paths,{events,signal})){const fileEvent={event:REPORTED_EVENTS[type],path:path4};logger.verbose(`File ${fileEvent.event} for channel "${channel2.name}": ${path4}`);try{await channel2.handleEvent(fileEvent)}catch(error){logger.error(`Failed to handle a file event in channel "${channel2.name}"`,{error})}}}function wireFileWatcherSource(channel2,context,sourceConfig,logger){if(connectsItself(context)){logger.info(`Channel "${channel2.name}" defines onConnect(), so it watches by itself: the framework does not watch its declared paths. Remove onConnect() to have the framework watch them.`);return()=>void 0}if(!isLongLivedProcess()){logger.warn(`Channel "${channel2.name}" does not watch its paths in a serverless, edge or browser runtime: watching files needs a long-lived process`);return()=>void 0}warnAboutGlobs(channel2.name,sourceConfig.paths,logger);const watch=new AbortController;forwardFileEvents(channel2,sourceConfig,watch.signal,logger).catch(error=>{logger.error(`Channel "${channel2.name}" stopped watching its paths`,{error})});return()=>watch.abort()}var import_utils160,WATCHED_TYPES,REPORTED_EVENTS;var init_file_watcher_source=__esm({"libs/sdk/src/channel/sources/file-watcher.source.ts"(){"use strict";import_utils160=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_utils161,ChannelRegistry;var init_channel_registry=__esm({"libs/sdk/src/channel/channel.registry.ts"(){"use strict";import_utils161=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_utils161.getRuntimeContext)();for(const token of this.tokens){const rec=this.defs.get(token);if(!rec)continue;if(!(0,import_utils161.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(name59){return this.localRows.find(r=>r.instance.name===name59)?.instance}hasAny(){return this.localRows.length>0}get size(){return this.localRows.length}getCapabilities(){if(!this.hasAny())return{};return{experimental:{"claude/channel":{}}}}subscribe(opts,cb){const unsub=this.emitter.on(cb);if(opts.immediate&&this.localRows.length>0){cb({kind:"reset",changeScope:"global",version:this.version,snapshot:this.getChannels()})}return unsub}bump(kind){this.version++;this.emitter.emit({kind,changeScope:"global",version:this.version,snapshot:this.getChannels()})}}}});var import_lazy_zod127,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_zod127=require("@frontmcp/lazy-zod");init_common();inputSchema30=import_lazy_zod127.internalZ.object({}).optional();channelInfoSchema=import_lazy_zod127.internalZ.object({name:import_lazy_zod127.internalZ.string(),description:import_lazy_zod127.internalZ.string().optional(),sourceType:import_lazy_zod127.internalZ.string(),twoWay:import_lazy_zod127.internalZ.boolean(),tags:import_lazy_zod127.internalZ.array(import_lazy_zod127.internalZ.string())});outputSchema29=import_lazy_zod127.internalZ.object({channels:import_lazy_zod127.internalZ.array(channelInfoSchema),count:import_lazy_zod127.internalZ.number()});stateSchema32=import_lazy_zod127.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_zod128,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_zod128=require("@frontmcp/lazy-zod");init_common();init_errors();init_channel_utils();inputSchema31=import_lazy_zod128.internalZ.object({channelName:import_lazy_zod128.internalZ.string().min(1),content:import_lazy_zod128.internalZ.string().min(1),meta:import_lazy_zod128.internalZ.record(import_lazy_zod128.internalZ.string(),import_lazy_zod128.internalZ.unknown()).optional(),targetSessionId:import_lazy_zod128.internalZ.string().min(1).optional()});outputSchema30=import_lazy_zod128.internalZ.object({sent:import_lazy_zod128.internalZ.boolean(),channelName:import_lazy_zod128.internalZ.string()});stateSchema33=import_lazy_zod128.internalZ.object({channelName:import_lazy_zod128.internalZ.string(),content:import_lazy_zod128.internalZ.string(),meta:import_lazy_zod128.internalZ.record(import_lazy_zod128.internalZ.string(),import_lazy_zod128.internalZ.string()).optional(),targetSessionId:import_lazy_zod128.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_zod128.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_zod129,channelReplyInputSchema;var init_reply_types=__esm({"libs/sdk/src/channel/reply/reply.types.ts"(){"use strict";import_lazy_zod129=require("@frontmcp/lazy-zod");channelReplyInputSchema={channel_name:import_lazy_zod129.internalZ.string().describe("The name of the channel to reply to"),text:import_lazy_zod129.internalZ.string().describe("The reply text to send back through the channel"),meta:import_lazy_zod129.internalZ.record(import_lazy_zod129.internalZ.string(),import_lazy_zod129.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:http3,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=http3?computeReservedPaths(http3.entryPath,http3.routeBase,http3.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(!http3||!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 http3.server.registerRoute("POST",source.path,wrapWithIpFilter(handler,http3.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_utils162,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_utils162=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_utils162.getMachineId)()}:${(0,import_utils162.randomUUID)()}`;this.logger=options.logger.child("EventOutbox");this.random=options.random??Math.random;const{runtime,deployment}=(0,import_utils162.getRuntimeContext)();this.usesTimers=deployment!=="serverless"&&runtime!=="edge"&&runtime!=="browser"}options;ownerId;logger;random;usesTimers;timers=new Map;inFlight=new Map;waitingForSlot=[];activeAttempts=0;sweepTimer;lastSweepAt=0;stopped=false;async enqueue(delivery){const now=Date.now();const record={...delivery,id:`dlv_${(0,import_utils162.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){if(this.activeAttempts>=this.options.settings.concurrency){await new Promise(resolve4=>this.waitingForSlot.push(resolve4))}else{this.activeAttempts+=1}try{await this.attemptOnce(id)}finally{const nextWaiter=this.waitingForSlot.shift();if(nextWaiter)nextWaiter();else this.activeAttempts-=1}}async attemptOnce(id){const stored=await this.read(id);if(!stored||stored.record.leaseOwner!==this.ownerId)return;const startedAt=Date.now();const held=await this.replace(stored,{...stored.record,leaseUntil:this.leaseEnd(startedAt)});if(!held)return;const outcome=await this.outcomeOf(held.record);if(outcome.result==="delivered"||outcome.result==="dropped"){await this.options.storage.delete(RECORD_PREFIX2+id);this.options.metrics.count(outcome.result,held.record.eventName);return}await this.retryOrAbandon(held,outcome)}async outcomeOf(record){try{return await this.options.attempt(record)}catch(error){this.logger.warn(`The attempt of delivery ${record.id} threw`,error);return{result:"error"}}}async retryOrAbandon(held,outcome){const{settings,metrics,storage}=this.options;const{record}=held;const now=Date.now();const isWaiting=outcome.result==="waiting";const attemptsMade=isWaiting?record.attempt:record.attempt+1;const windowIsOver=now-record.firstAttemptAt>=settings.retryWindowMs;if(attemptsMade>=settings.maxAttempts||windowIsOver){await storage.delete(RECORD_PREFIX2+record.id);metrics.count("abandoned",record.eventName);this.logger.warn(`Delivery ${record.id} of event "${record.eventName}" to subscription ${record.subscriptionId} is abandoned after ${attemptsMade} attempt(s): ${reasonOf(outcome)}`);return}const waitMs=isWaiting?SUSPENDED_RECHECK_MS:this.backoffMs(attemptsMade);const nextAttemptAt=now+waitMs;const next={...record,attempt:attemptsMade,nextAttemptAt,leaseUntil:this.leaseEnd(nextAttemptAt)};if(!await this.replace(held,next))return;if(!isWaiting)metrics.count("retried",record.eventName);if(this.usesTimers)this.schedule(record.id,waitMs)}backoffMs(attemptsMade){const{backoffMs,maxBackoffMs}=this.options.settings;const exponential=Math.min(maxBackoffMs,backoffMs*2**(attemptsMade-1));return Math.round(exponential*(.5+this.random()*.5))}leaseEnd(attemptAt){return attemptAt+this.options.settings.timeoutMs+LEASE_MARGIN_MS}async claim(id,now){const stored=await this.read(id);if(!stored)return void 0;if(stored.record.leaseOwner===this.ownerId)return stored.record;if(stored.record.leaseUntil>now)return void 0;const claimed={...stored.record,leaseOwner:this.ownerId,leaseUntil:this.leaseEnd(now)};return(await this.replace(stored,claimed))?.record}async replace(stored,next){const raw=await this.encode(next);const replaced=await this.options.storage.setIfEquals(RECORD_PREFIX2+next.id,stored.raw,raw);return replaced?{raw,record:next}:void 0}async read(id){const raw=await this.options.storage.get(RECORD_PREFIX2+id);if(raw===null)return void 0;const record=await this.decode(raw,id);return record?{raw,record}:void 0}async encode(record){const{secret}=this.options;if(secret===void 0)return JSON.stringify(record);return encryptAndSerialize(record,`events-outbox:${record.id}`,secret)}async decode(raw,id){const{secret}=this.options;try{const record=secret===void 0?JSON.parse(raw):await deserializeAndDecrypt(raw,`events-outbox:${id}`,secret);return record?.id===id?record:void 0}catch{return void 0}}sweepInBackground(){this.sweep().catch(error=>this.logger.warn("The outbox sweep failed",error))}}}});function newEventId(){return`evt_${(0,import_utils163.base64urlEncode)((0,import_utils163.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_utils163,EVENT_ID_RANDOM_BYTES,ScopeEventPublisher;var init_event_publisher=__esm({"libs/sdk/src/event/event-publisher.ts"(){"use strict";import_utils163=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()}});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_utils164,EventRegistry;var init_event_registry=__esm({"libs/sdk/src/event/event.registry.ts"(){"use strict";import_protocol72=require("@frontmcp/protocol");import_utils164=require("@frontmcp/utils");init_common();init_errors();init_regsitry();init_event_instance();init_event_utils();EventRegistry=class extends RegistryAbstract{owner;config;subscriptions;publisher;outbox;metrics;storage;publishEndpoint;buffer;pollLeases;streams;replays;channelDelivery=true;withoutWebhook=new Set;eventsByName=new Map;enabledDeliveryModes=new Set;logger;entryProviders;constructor(providers,list,owner,config,entryProviders){super("EventRegistry",providers,list,false);this.owner=owner;this.config=config;this.entryProviders=entryProviders;this.logger=providers.get(FrontMcpLogger).child("EventRegistry");this.buildGraph();this.ready=this.initialize()}buildMap(list){const tokens=new Set;const defs=new Map;const graph=new Map;for(const item of list){const record=normalizeEvent(item);tokens.add(record.provide);defs.set(record.provide,record);graph.set(record.provide,new Set)}return{tokens,defs,graph}}buildGraph(){}async initialize(){const runtimeContext=(0,import_utils164.getRuntimeContext)();for(const[token,record]of this.defs){const eventName=record.metadata.name;if(!(0,import_utils164.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(name59){return this.eventsByName.get(name59)}hasAny(){return this.eventsByName.size>0}enableDeliveryMode(mode){this.enabledDeliveryModes.add(mode)}withholdWebhookFrom(eventName){this.withoutWebhook.add(eventName)}performs(mode){return this.enabledDeliveryModes.has(mode)}deliveryModesOf(event){const restriction=event.metadata.delivery;return 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))}getCapabilities(){if(!this.servesEvents())return{};return{events:{},extensions:{[import_protocol72.EVENTS_EXTENSION_ID]:{}}}}}}});function eventOutboundTargetOptions(allowLocal){return(0,import_utils165.isEdgeRuntime)()?{allowLocal,allowPlatformDns:true}:{allowLocal}}var import_utils165;var init_event_outbound=__esm({"libs/sdk/src/event/event-outbound.ts"(){"use strict";import_utils165=require("@frontmcp/utils")}});var import_lazy_zod130,import_protocol73,import_utils166,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_zod130=require("@frontmcp/lazy-zod");import_protocol73=require("@frontmcp/protocol");import_utils166=require("@frontmcp/utils");init_common();init_event_outbound();inputSchema32=import_lazy_zod130.internalZ.object({delivery:import_lazy_zod130.internalZ.any()});outputSchema31=import_lazy_zod130.internalZ.discriminatedUnion("result",[import_lazy_zod130.internalZ.object({result:import_lazy_zod130.internalZ.literal("delivered")}),import_lazy_zod130.internalZ.object({result:import_lazy_zod130.internalZ.literal("dropped"),reason:import_lazy_zod130.internalZ.enum(["gone","refused"])}),import_lazy_zod130.internalZ.object({result:import_lazy_zod130.internalZ.literal("failed"),category:import_protocol73.EventDeliveryErrorCategorySchema}),import_lazy_zod130.internalZ.object({result:import_lazy_zod130.internalZ.literal("waiting")})]);stateSchema34=import_lazy_zod130.internalZ.object({target:import_lazy_zod130.internalZ.any(),subscription:import_lazy_zod130.internalZ.any(),headers:import_lazy_zod130.internalZ.record(import_lazy_zod130.internalZ.string(),import_lazy_zod130.internalZ.string()),answer:import_lazy_zod130.internalZ.any(),outcome:import_lazy_zod130.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_utils166.signingKeyOf)(secret)];if(previousSecret!==void 0&&(previousSecretUntil??0)>now){signingKeys.push((0,import_utils166.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_utils166.webhookSignatureHeaders)(message,signingKeys)})}async send(){if(this.state.outcome)return;const{webhook}=this.events.config;const answer=await(0,import_utils166.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_utils166.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 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,name59){const value=claims3[name59];return typeof value==="string"&&value!==""?value:void 0}function eventSubscriberOf(authInfo,contextBuilder){const principalKey=principalKeyOf(authInfo);if(!principalKey)return void 0;const plainAuthInfo=authInfo;const tokenPrincipal=resolvePrincipal(plainAuthInfo);const principal=contextBuilder?resolvePrincipal(plainAuthInfo,contextBuilder):tokenPrincipal;const tenantId=contextBuilder?.build(plainAuthInfo).user.tenantId;const issuer=stringClaim(tokenPrincipal.claims,"iss");return{principalKey,subscriber:{sub:principal.sub||tokenPrincipal.sub,...issuer&&{iss:issuer},...tenantId&&{tenantId},roles:principal.roles,permissions:principal.permissions,scopes:principal.scopes,claims:principal.claims}}}var init_event_subscriber=__esm({"libs/sdk/src/event/event-subscriber.ts"(){"use strict";init_principal_utils();init_question_subject()}});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_auth56.isPublicMode)(authOptions)){throw new EventForbiddenError(codes,eventName,"this server needs a signed-in caller")}return{principalKey:void 0,subscriber:ANONYMOUS_SUBSCRIBER}}async function assertEventAuthorities(scope,event,authInfo,args,codes){const engine=scope.authoritiesEngine;const contextBuilder=scope.authoritiesContextBuilder;const authorities=event.getAuthorities();if(!engine||!contextBuilder||!authorities)return;const result=await engine.evaluate(authorities,contextBuilder.build(authInfo,args));if(!result.granted)throw new EventForbiddenError(codes,event.name,result.deniedBy??"policy denied")}function parsedEventArguments(event,args){try{return event.parseArguments(args??{})}catch(error){throw new InvalidInputError("Invalid subscription arguments",error instanceof import_lazy_zod131.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_utils167.canonicalJson)({principalKey:reader.principalKey??null,mode,name:eventName,arguments:args});return{id:`sub_${(0,import_utils167.sha256Hex)(key).slice(0,32)}`,name:eventName,mode,subscriber:reader.subscriber}}var import_auth56,import_lazy_zod131,import_utils167,ANONYMOUS_SUBSCRIBER;var init_event_gates=__esm({"libs/sdk/src/event/event-gates.ts"(){"use strict";import_auth56=require("@frontmcp/auth");import_lazy_zod131=require("@frontmcp/lazy-zod");import_utils167=require("@frontmcp/utils");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_utils168,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_utils168=require("@frontmcp/utils");POLL_LEASE_MIN_MS=3e5;POLL_LEASE_INTERVALS=5;POLL_LEASE_SWEEP_INTERVAL_MS=6e4;MAX_POLL_LEASES=1e4;EventPollLeases=class{constructor(options){this.options=options;this.logger=options.logger.child("EventPollLeases")}options;leases=new Map;starting=new Map;logger;sweepTimer;lastSweepAt=0;get size(){return this.leases.size}isFull(principalKey){if(this.leases.size>=MAX_POLL_LEASES)return true;let held=0;for(const lease of this.leases.values()){if(lease.principalKey===principalKey)held+=1}return held>=this.options.maxPerPrincipal}has(subscriptionId){return this.leases.has(subscriptionId)||this.starting.has(subscriptionId)}async renew(request2){const{subscription,leaseMs}=request2;const now=Date.now();this.sweepIfDue(now);const lease=this.leases.get(subscription.id);if(lease){lease.expiresAt=now+leaseMs;return}const pending=this.starting.get(subscription.id);if(pending)return pending;const start=this.subscribe(request2,now).finally(()=>this.starting.delete(subscription.id));this.starting.set(subscription.id,start);return start}async subscribe(request2,now){const{subscription,context,leaseMs}=request2;await context.onSubscribe?.(request2.arguments,subscription);this.leases.set(subscription.id,{subscription,arguments:request2.arguments,principalKey:request2.principalKey,expiresAt:now+leaseMs,end:async reason=>{await context.onUnsubscribe?.(request2.arguments,subscription,reason)}})}async sweep(now=Date.now()){this.lastSweepAt=now;for(const[subscriptionId,lease]of this.leases){if(lease.expiresAt>now)continue;this.leases.delete(subscriptionId);await this.end(lease,"expired")}}start(){const{runtime,deployment}=(0,import_utils168.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:name59}=lease.subscription;this.logger.warn(`onUnsubscribe of event "${name59}" failed for poll subscription ${id}`,error)}}}}});function eventChannelMessage(event,occurrence){const{channel:channel2}=event.metadata;const options=channel2===void 0||channel2===true?{}:channel2;const payload=occurrence.data;const content=options.content?options.content(payload):JSON.stringify(payload);const ownMeta=options.meta?options.meta(payload):{};return{content,meta:channelMetaOf({...ownMeta,event:occurrence.name,event_id:occurrence.eventId})}}function channelSessionReader(scope,event,session){if(hasExpiredCaller(session))return void 0;if(!isOfferedOnSurface(event.metadata.availableWhen,mcpRequestSurface(scope)))return void 0;try{return eventReaderOf(scope,session.caller??{},event.name,EVENT_DIALECTS["sep-3415"].errorCodes)}catch(error){if(error instanceof EventForbiddenError)return void 0;throw error}}var init_event_channel=__esm({"libs/sdk/src/event/event-channel.ts"(){"use strict";init_channel_utils();init_availability();init_errors();init_notification_service();init_mcp_surface();init_event_dialect();init_event_gates()}});function accessRevokedError(dialect){return{code:EVENT_DIALECTS[dialect].errorCodes.forbidden,message:"Forbidden",data:{reason:"Access revoked"}}}async function terminateEventSubscription(args){const{subscriptions,outbox,metrics,logger,subscription,error}=args;const removed=await subscriptions?.store.delete(subscription.id);if(!removed||!subscriptions||!outbox)return;await subscriptions.notifyUnsubscribed(removed,"terminated");metrics?.count("terminated",removed.eventName);logger.warn(`Subscription ${removed.id} to event "${removed.eventName}" is terminated: ${error.message} (${String(error.data["reason"])})`);if(!EVENT_DIALECTS[removed.dialect].sendsControlEnvelopes)return;const{url,secret,previousSecret,previousSecretUntil}=removed.delivery;await outbox.enqueue({kind:"terminated",subscriptionId:removed.id,eventName:removed.eventName,body:JSON.stringify({type:"terminated",error}),webhookId:(0,import_utils169.generateWebhookMessageId)("terminated"),target:{url,secret,previousSecret,previousSecretUntil}})}var import_utils169;var init_event_subscription_termination=__esm({"libs/sdk/src/event/subscription/event-subscription-termination.ts"(){"use strict";import_utils169=require("@frontmcp/utils");init_event_dialect()}});function eventWebhookIdOf(subscriptionId,eventId){return`msg_${(0,import_utils170.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_zod132,import_protocol75,import_utils170,EVENT_DELIVERY_MAX_BYTES,audienceValueSchema,inputSchema33,outputSchema32,stateSchema35,plan40,name40,Stage40,encoder9,EventPublishFlow;var init_event_publish_flow=__esm({"libs/sdk/src/event/flows/event-publish.flow.ts"(){"use strict";import_lazy_zod132=require("@frontmcp/lazy-zod");import_protocol75=require("@frontmcp/protocol");import_utils170=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_zod132.internalZ.union([import_lazy_zod132.internalZ.string(),import_lazy_zod132.internalZ.array(import_lazy_zod132.internalZ.string())]);inputSchema33=import_lazy_zod132.internalZ.object({occurrence:import_protocol75.EventOccurrenceSchema,subscriptionId:import_lazy_zod132.internalZ.string().optional(),audience:import_lazy_zod132.internalZ.object({sub:audienceValueSchema.optional(),tenantId:audienceValueSchema.optional(),roles:import_lazy_zod132.internalZ.object({any:import_lazy_zod132.internalZ.array(import_lazy_zod132.internalZ.string()).optional(),all:import_lazy_zod132.internalZ.array(import_lazy_zod132.internalZ.string()).optional()}).optional()}).optional()});outputSchema32=import_lazy_zod132.internalZ.object({eventId:import_lazy_zod132.internalZ.string(),matched:import_lazy_zod132.internalZ.number().int().nonnegative()});stateSchema35=import_lazy_zod132.internalZ.object({event:import_lazy_zod132.internalZ.instanceof(EventEntry),context:import_lazy_zod132.internalZ.any(),subscriptions:import_lazy_zod132.internalZ.array(import_lazy_zod132.internalZ.any()),deliveries:import_lazy_zod132.internalZ.array(import_lazy_zod132.internalZ.any()),buffered:import_lazy_zod132.internalZ.any()});plan40={pre:["validate","bufferOccurrence","pushToStreams"],execute:["loadSubscriptions","dropInactive","filterByAudience","reauthorize","match","transform","enforceBodyLimit","enqueue","bridgeToBus","notifyChannelSessions"],post:["buildResult"]};name40="events:publish";({Stage:Stage40}=FlowHooksOf(name40));encoder9=new TextEncoder;EventPublishFlow=class extends FlowBase{logger=this.scopeLogger.child("EventPublishFlow");get events(){return this.scope.events}async validate(){const eventName=this.input.occurrence.name;const event=this.events.findByName(eventName);if(!event)throw new EventNotRegisteredError(eventName);this.events.metrics?.count("published",eventName);this.state.set({event,context:event.create({}),deliveries:[]})}async bufferOccurrence(){const{occurrence,audience,subscriptionId}=this.input;const modes=this.events.deliveryModesOf(this.state.required.event);if(!modes.includes("poll")&&!modes.includes("push"))return;this.state.set("buffered",this.events.buffer?.append(occurrence,audience,subscriptionId))}async pushToStreams(){const{buffered}=this.state;if(buffered)await this.events.streams?.publish(buffered)}async loadSubscriptions(){const{subscriptions,outbox}=this.events;if(!subscriptions||!outbox){this.state.set("subscriptions",[]);return}subscriptions.sweepIfDue();await outbox.sweepIfDue();const{subscriptionId,occurrence}=this.input;if(subscriptionId===void 0){this.state.set("subscriptions",await subscriptions.store.listByEvent(occurrence.name));return}const targeted=await subscriptions.store.get(subscriptionId);this.state.set("subscriptions",targeted?.eventName===occurrence.name?[targeted]:[])}async dropInactive(){const{suspendedTtlMs}=this.events.config.subscriptions;const now=Date.now();const active=[];for(const subscription of this.state.required.subscriptions){if(subscription.active){active.push(subscription);continue}const suspendedFor=now-(subscription.status.suspendedSince??now);if(subscription.expiresAt===null&&suspendedFor>suspendedTtlMs){const codes=EVENT_DIALECTS[subscription.dialect].errorCodes;await this.terminate(subscription,{code:codes.callbackEndpointError,message:"CallbackEndpointError",data:{reason:subscription.status.lastError??"http_5xx"}})}}this.state.set("subscriptions",active)}async filterByAudience(){const{audience}=this.input;const inAudience=this.state.required.subscriptions.filter(subscription=>isInAudience(audience,subscription.subscriber));this.state.set("subscriptions",inAudience)}async reauthorize(){const{event,context}=this.state.required;if(!hasReauthorization(this.scope,event,context.authorize!==void 0))return;const{subscriptions}=this.events;const{reauthorizeEveryMs}=this.events.config.subscriptions;const now=Date.now();const allowed=[];for(const subscription of this.state.required.subscriptions){if(now-subscription.lastAuthorizedAt<=reauthorizeEveryMs){allowed.push(subscription);continue}const{subscriber,arguments:subscriptionArguments}=subscription;const check=await reauthorizeSubscriber({scope:this.scope,event,subscriber,arguments:subscriptionArguments});if(check.outcome==="granted"){await subscriptions?.store.update(subscription.id,{lastAuthorizedAt:now});allowed.push(subscription);continue}if(check.outcome==="failed"){this.logger.warn(`reauthorize: the access of subscription ${subscription.id} could not be checked`,check.error);continue}await this.terminate(subscription,accessRevokedError(subscription.dialect))}this.state.set("subscriptions",allowed)}async match(){const{context,subscriptions}=this.state.required;const{occurrence}=this.input;const deliveries=[];for(const subscription of subscriptions){try{const matches=await context.match?.(occurrence,subscription.arguments,subscription.subscriber)??true;if(matches)deliveries.push({subscription,occurrence})}catch(error){this.logger.warn(`match: event "${occurrence.name}" failed for subscription ${subscription.id}`,error)}}this.state.set("deliveries",deliveries)}async transform(){const{context,deliveries}=this.state.required;if(!context.transform)return;const shaped=[];for(const delivery of deliveries){const{subscription,occurrence}=delivery;try{const transformed=await context.transform(occurrence,subscription.arguments,subscription.subscriber);shaped.push({subscription,occurrence: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=encoder9.encode(body).byteLength;if(bytes<=EVENT_DELIVERY_MAX_BYTES){fitting.push({...delivery,body});continue}this.events.metrics?.count("dropped",delivery.occurrence.name);this.logger.warn(`enforceBodyLimit: event "${delivery.occurrence.name}" is ${bytes} bytes for subscription ${delivery.subscription.id}, over the ${EVENT_DELIVERY_MAX_BYTES} byte limit; it is not delivered`)}this.state.set("deliveries",fitting)}async enqueue(){const{outbox}=this.events;const{deliveries}=this.state.required;if(!outbox)return;const queued=deliveries.map(({subscription,occurrence,body})=>{const usesEventId=EVENT_DIALECTS[subscription.dialect].webhookId==="eventId";return outbox.enqueue({kind:"event",subscriptionId:subscription.id,eventName:occurrence.name,body,webhookId:usesEventId?occurrence.eventId:eventWebhookIdOf(subscription.id,occurrence.eventId)})});await Promise.all(queued);this.events.metrics?.count("matched",this.input.occurrence.name,deliveries.length)}async bridgeToBus(){if(!this.events.config.bridge)return;const{occurrence,audience,subscriptionId}=this.input;const forSomeOwners=audience!==void 0||subscriptionId!==void 0;this.scope.channelEventBus?.emit(occurrence.name,occurrence,{forSomeOwners})}async notifyChannelSessions(){const{event}=this.state.required;const{occurrence,subscriptionId}=this.input;if(subscriptionId!==void 0||!this.events.sendsToChannelSessions(event))return;let message;try{message=eventChannelMessage(event,occurrence)}catch(error){this.logger.warn(`notifyChannelSessions: the channel option of event "${occurrence.name}" failed`,error);return}let notified=0;for(const session of this.scope.notifications.getChannelCapableSessions()){const wasSent=await this.notifyChannelSession(session,message);if(wasSent)notified+=1}this.events.metrics?.count("notified",occurrence.name,notified);this.logger.verbose(`notifyChannelSessions: event "${occurrence.name}" was sent to ${notified} session(s)`)}async buildResult(){this.respond({eventId:this.input.occurrence.eventId,matched:this.state.required.deliveries.length})}async notifyChannelSession(session,message){const{event,context}=this.state.required;const{occurrence,audience}=this.input;try{const reader=channelSessionReader(this.scope,event,session);if(!reader||!isInAudience(audience,reader.subscriber))return false;if(hasReauthorization(this.scope,event,context.authorize!==void 0)){const{subscriber}=reader;const authInfo=session.caller;const access=await reauthorizeSubscriber({scope:this.scope,event,subscriber,arguments:{},authInfo});if(access.outcome==="failed")throw access.error;if(access.outcome==="refused")return false}const isThisSession=registered=>registered.sessionId===session.sessionId;this.scope.notifications.sendCustomNotification(CHANNEL_NOTIFICATION_METHOD,message,isThisSession);return true}catch(error){const sessionLabel=session.sessionId.slice(0,20);this.logger.warn(`notifyChannelSessions: event "${occurrence.name}" was not sent to session ${sessionLabel}...`,error);return false}}async terminate(subscription,error){const{subscriptions,outbox,metrics}=this.events;await terminateEventSubscription({subscriptions,outbox,metrics,logger:this.logger,subscription,error})}};__decorateClass([Stage40("validate")],EventPublishFlow.prototype,"validate",1);__decorateClass([Stage40("bufferOccurrence")],EventPublishFlow.prototype,"bufferOccurrence",1);__decorateClass([Stage40("pushToStreams")],EventPublishFlow.prototype,"pushToStreams",1);__decorateClass([Stage40("loadSubscriptions")],EventPublishFlow.prototype,"loadSubscriptions",1);__decorateClass([Stage40("dropInactive")],EventPublishFlow.prototype,"dropInactive",1);__decorateClass([Stage40("filterByAudience")],EventPublishFlow.prototype,"filterByAudience",1);__decorateClass([Stage40("reauthorize")],EventPublishFlow.prototype,"reauthorize",1);__decorateClass([Stage40("match")],EventPublishFlow.prototype,"match",1);__decorateClass([Stage40("transform")],EventPublishFlow.prototype,"transform",1);__decorateClass([Stage40("enforceBodyLimit")],EventPublishFlow.prototype,"enforceBodyLimit",1);__decorateClass([Stage40("enqueue")],EventPublishFlow.prototype,"enqueue",1);__decorateClass([Stage40("bridgeToBus")],EventPublishFlow.prototype,"bridgeToBus",1);__decorateClass([Stage40("notifyChannelSessions")],EventPublishFlow.prototype,"notifyChannelSessions",1);__decorateClass([Stage40("buildResult")],EventPublishFlow.prototype,"buildResult",1);EventPublishFlow=__decorateClass([FrontMcpFlow({name:name40,plan:plan40,inputSchema:inputSchema33,outputSchema:outputSchema32,access:"public"})],EventPublishFlow)}});var import_lazy_zod133,import_protocol76,inputSchema34,outputSchema33,stateSchema36,plan41,name41,Stage41,EventPollFlow;var init_event_poll_flow=__esm({"libs/sdk/src/event/flows/event-poll.flow.ts"(){"use strict";import_lazy_zod133=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();inputSchema34=import_lazy_zod133.internalZ.object({request:import_protocol76.PollEventsRequestSchema,ctx:import_lazy_zod133.internalZ.unknown()});outputSchema33=import_protocol76.PollEventsResultSchema;stateSchema36=import_lazy_zod133.internalZ.object({authInfo:import_lazy_zod133.internalZ.any(),dialect:import_lazy_zod133.internalZ.enum(["sep-3415","sketch"]),event:import_lazy_zod133.internalZ.instanceof(EventEntry),reader:import_lazy_zod133.internalZ.any(),arguments:import_lazy_zod133.internalZ.record(import_lazy_zod133.internalZ.string(),import_lazy_zod133.internalZ.unknown()),context:import_lazy_zod133.internalZ.any(),subscription:import_lazy_zod133.internalZ.any(),result:import_lazy_zod133.internalZ.any()});plan41={pre:["parseInput","resolveDialect","findEvent","resolveReader","checkEntryAuthorities","validateArguments","authorize"],execute:["renewLease","readEvents"],post:["buildResult"],finalize:["finalize"]};name41="events:poll";({Stage:Stage41}=FlowHooksOf(name41));EventPollFlow=class extends FlowBase{logger=this.scopeLogger.child("EventPollFlow");get events(){return this.scope.events}get codes(){return EVENT_DIALECTS[this.state.required.dialect].errorCodes}async parseInput(){const authInfo=this.input.ctx?.authInfo??{};this.state.set("authInfo",authInfo)}async resolveDialect(){const platform=callerPlatformOf(this.scope,this.state.required.authInfo,this.tryGetContext()?.platformType);this.state.set("dialect",resolveEventDialect(this.events.config.compat,platform))}async findEvent(){const eventName=this.input.request.params.name;this.state.set("event",offeredEventOf(this.events,eventName,"poll",this.input.ctx,this.codes))}async resolveReader(){const{authInfo,event}=this.state.required;this.state.set("reader",eventReaderOf(this.scope,authInfo,event.name,this.codes))}async checkEntryAuthorities(){const{event,authInfo}=this.state.required;const sentArguments=this.input.request.params.arguments??{};await assertEventAuthorities(this.scope,event,authInfo,sentArguments,this.codes)}async validateArguments(){const{event,reader}=this.state.required;const parsedArguments=parsedEventArguments(event,this.input.request.params.arguments);this.state.set({arguments:parsedArguments,subscription:readerSubscriptionOf(reader,"poll",event.name,parsedArguments)})}async authorize(){const{event,authInfo,reader}=this.state.required;const context=event.create(authInfo);await assertEventAuthorizes(context,event.name,this.state.required.arguments,reader.subscriber,this.codes);this.state.set("context",context)}async renewLease(){await this.renewLeaseFor(this.events.config.poll.nextPollMs)}async readEvents(){const{context}=this.state.required;const result=context.check?await this.readFromCheck():await this.readFromBuffer();this.state.set("result",result);if(result.nextPollMs!==void 0&&result.nextPollMs>this.events.config.poll.nextPollMs){await this.renewLeaseFor(result.nextPollMs)}}async buildResult(){this.respond(this.state.required.result)}async finalize(){this.logger.verbose("finalize")}get limit(){const serverLimit=this.events.config.poll.maxEvents;return Math.min(this.input.request.params.maxEvents??serverLimit,serverLimit)}replayFloor(now){const{cursor,maxAgeMs}=this.input.request.params;const hasCursor=cursor!==void 0&&cursor!==null;return hasCursor&&maxAgeMs!==void 0?now-maxAgeMs:void 0}async renewLeaseFor(nextPollMs){const leases=this.events.pollLeases;const{context,subscription,reader}=this.state.required;if(!context.onSubscribe&&!context.onUnsubscribe)return;if(!leases.has(subscription.id)&&leases.isFull(reader.principalKey)){const{maxPerPrincipal}=this.events.config.subscriptions;throw new EventResourceExhaustedError(this.codes,"pollLeases",maxPerPrincipal)}await leases.renew({subscription,arguments:this.state.required.arguments,principalKey:reader.principalKey,leaseMs:pollLeaseMs(nextPollMs),context})}async readFromCheck(){const{context,event}=this.state.required;const{cursor=null,maxAgeMs}=this.input.request.params;const now=Date.now();const floor=this.replayFloor(now);const limits={maxEvents:this.limit,...floor!==void 0&&{maxAgeMs}};const check=context.check;const checked=await check.call(context,this.state.required.arguments,cursor,limits);if(checked.events.length>this.limit){throw new InvalidEventPublishError(event.name,`check() returned ${checked.events.length} events, more than limits.maxEvents (${this.limit})`)}const events=[];let skippedOldEvents=false;for(const item of checked.events){const timestamp=item.timestamp??new Date(now).toISOString();if(floor!==void 0&&Date.parse(timestamp)<floor){skippedOldEvents=true;continue}events.push({eventId:item.eventId??newEventId(),name:event.name,timestamp,data:this.checkedPayload(item.data)})}return{events,cursor:checked.cursor,truncated:checked.truncated===true||skippedOldEvents,hasMore:checked.hasMore===true,nextPollMs:checked.nextPollMs??this.events.config.poll.nextPollMs}}checkedPayload(data){const{event}=this.state.required;try{return event.parsePayload(data)}catch(error){const problem2=error instanceof Error?error.message:String(error);throw new InvalidEventPublishError(event.name,`check() returned data that does not match payloadSchema: ${problem2}`)}}async readFromBuffer(){const buffer=this.events.buffer;const{cursor}=this.input.request.params;const nextPollMs=this.events.config.poll.nextPollMs;if(cursor===void 0||cursor===null){return{events:[],cursor:buffer.currentCursor(),truncated:false,hasMore:false,nextPollMs}}const read=buffer.read(this.state.required.event.name,cursor);const endCursor=buffer.currentCursor();const floor=this.replayFloor(Date.now());const events=[];let truncated=read.truncated;let lastExamined;for(const buffered of read.events){if(floor!==void 0&&buffered.publishedAt<floor){truncated=true;lastExamined=buffered;continue}const occurrence=await this.occurrenceFor(buffered);if(occurrence&&events.length===this.limit){const resumeCursor=lastExamined?buffer.cursorAt(lastExamined.sequence):cursor;return{events,cursor:resumeCursor,truncated,hasMore:true,nextPollMs}}if(occurrence)events.push(occurrence);lastExamined=buffered}return{events,cursor:endCursor,truncated,hasMore:false,nextPollMs}}async occurrenceFor(buffered){const{context,reader,subscription}=this.state.required;const{occurrence}=buffered;if(buffered.subscriptionId!==void 0&&buffered.subscriptionId!==subscription.id)return void 0;if(!isInAudience(buffered.audience,reader.subscriber))return void 0;const subscriptionArguments=this.state.required.arguments;try{const matches=await context.match?.(occurrence,subscriptionArguments,reader.subscriber)??true;if(!matches)return void 0;if(!context.transform)return occurrence;const transformed=await context.transform(occurrence,subscriptionArguments,reader.subscriber);return 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([Stage41("parseInput")],EventPollFlow.prototype,"parseInput",1);__decorateClass([Stage41("resolveDialect")],EventPollFlow.prototype,"resolveDialect",1);__decorateClass([Stage41("findEvent")],EventPollFlow.prototype,"findEvent",1);__decorateClass([Stage41("resolveReader")],EventPollFlow.prototype,"resolveReader",1);__decorateClass([Stage41("checkEntryAuthorities")],EventPollFlow.prototype,"checkEntryAuthorities",1);__decorateClass([Stage41("validateArguments")],EventPollFlow.prototype,"validateArguments",1);__decorateClass([Stage41("authorize")],EventPollFlow.prototype,"authorize",1);__decorateClass([Stage41("renewLease")],EventPollFlow.prototype,"renewLease",1);__decorateClass([Stage41("readEvents")],EventPollFlow.prototype,"readEvents",1);__decorateClass([Stage41("buildResult")],EventPollFlow.prototype,"buildResult",1);__decorateClass([Stage41("finalize")],EventPollFlow.prototype,"finalize",1);EventPollFlow=__decorateClass([FrontMcpFlow({name:name41,plan:plan41,inputSchema:inputSchema34,outputSchema:outputSchema33,access:"authorized"})],EventPollFlow)}});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(resolve4=>this.releaseDelivery=resolve4):Promise.resolve();if(options.signal?.aborted)this.close();else options.signal?.addEventListener("abort",()=>this.close(),{once:true})}options;queue=[];closeListeners=[];wake;closed=false;cursor;lastAuthorizedAt=Date.now();accessUnchecked=false;withheld=false;heartbeatTimer;checkTimer;delivering;releaseDelivery=()=>void 0;lastSequence=0;get subscription(){return this.options.subscription}get eventName(){return this.options.event.name}get principalKey(){return this.options.reader.principalKey}get isClosed(){return this.closed}async open(){const{context,heartbeatMs}=this.options;if(context.check){await this.openOnCheck()}else{await this.openOnBuffer()}this.releaseDelivery();if(this.closed)return;this.heartbeatTimer=setInterval(()=>void this.beat(),heartbeatMs);this.heartbeatTimer.unref?.()}offer(buffered){this.delivering=this.delivering.then(()=>this.deliver(buffered)).catch(error=>this.options.logger.warn(`An event was not delivered on stream ${this.subscription.id}`,error));return this.delivering}terminate(error){if(this.closed)return;this.push(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(resolve4=>this.wake=resolve4);this.wake=void 0}}async openOnBuffer(){const{buffer,cursor,maxAgeMs}=this.options;if(!buffer){this.pushActive(false);return}if(cursor===void 0||cursor===null){this.cursor=buffer.currentCursor();this.lastSequence=buffer.currentSequence();this.pushActive(false);return}const read=buffer.read(this.eventName,cursor);const endCursor=buffer.currentCursor();const endSequence=buffer.currentSequence();const floor=maxAgeMs===void 0?void 0:Date.now()-maxAgeMs;const replayed=read.events.filter(buffered=>floor===void 0||buffered.publishedAt>=floor);this.cursor=read.events.length===0?endCursor:cursor;this.pushActive(read.truncated||replayed.length<read.events.length);for(const buffered of replayed)await this.deliver(buffered);this.cursor=endCursor;this.lastSequence=endSequence}async deliver(buffered){if(this.closed||buffered.sequence<=this.lastSequence)return;if(this.accessUnchecked){this.withheld=true;return}this.lastSequence=buffered.sequence;const occurrence=await this.occurrenceFor(buffered);if(!occurrence)return;const{buffer}=this.options;if(buffer)this.cursor=buffer.cursorAt(buffered.sequence);this.pushEvent(occurrence)}async openOnCheck(){const checked=await this.check();this.pushActive(checked?.truncated===true);if(checked)this.pushChecked(checked);this.scheduleCheck(checked?.nextPollMs)}async check(){const{context,checkMaxEvents,maxAgeMs}=this.options;const check=context.check;const limits={maxEvents:checkMaxEvents,...this.cursor!==null&&maxAgeMs!==void 0&&{maxAgeMs}};try{const checked=await check.call(context,this.options.arguments,this.cursor,limits);this.cursor=checked.cursor;return checked}catch(error){this.options.logger.warn(`check() of event "${this.eventName}" failed for stream ${this.subscription.id}`,error);this.push(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_zod134,import_protocol78,inputSchema35,outputSchema34,stateSchema37,plan42,name42,Stage42,EventStreamFlow;var init_event_stream_flow=__esm({"libs/sdk/src/event/flows/event-stream.flow.ts"(){"use strict";import_lazy_zod134=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();inputSchema35=import_lazy_zod134.internalZ.object({request:import_protocol78.StreamEventsRequestSchema,ctx:import_lazy_zod134.internalZ.unknown(),requestId:import_lazy_zod134.internalZ.union([import_lazy_zod134.internalZ.string(),import_lazy_zod134.internalZ.number()]),signal:import_lazy_zod134.internalZ.any().optional()});outputSchema34=import_lazy_zod134.internalZ.object({stream:import_lazy_zod134.internalZ.instanceof(EventStream)});stateSchema37=import_lazy_zod134.internalZ.object({authInfo:import_lazy_zod134.internalZ.any(),dialect:import_lazy_zod134.internalZ.enum(["sep-3415","sketch"]),event:import_lazy_zod134.internalZ.instanceof(EventEntry),reader:import_lazy_zod134.internalZ.any(),arguments:import_lazy_zod134.internalZ.record(import_lazy_zod134.internalZ.string(),import_lazy_zod134.internalZ.unknown()),context:import_lazy_zod134.internalZ.any(),subscription:import_lazy_zod134.internalZ.any(),stream:import_lazy_zod134.internalZ.instanceof(EventStream)});plan42={pre:["parseInput","resolveDialect","findEvent","resolveReader","checkEntryAuthorities","validateArguments","authorize"],execute:["openStream"],post:["buildResult"],finalize:["finalize"]};name42="events:stream";({Stage:Stage42}=FlowHooksOf(name42));EventStreamFlow=class extends FlowBase{logger=this.scopeLogger.child("EventStreamFlow");get events(){return this.scope.events}get codes(){return EVENT_DIALECTS[this.state.required.dialect].errorCodes}async parseInput(){const authInfo=this.input.ctx?.authInfo??{};this.state.set("authInfo",authInfo)}async resolveDialect(){const platform=callerPlatformOf(this.scope,this.state.required.authInfo,this.tryGetContext()?.platformType);this.state.set("dialect",resolveEventDialect(this.events.config.compat,platform))}async findEvent(){const eventName=this.input.request.params.name;this.state.set("event",offeredEventOf(this.events,eventName,"push",this.input.ctx,this.codes))}async resolveReader(){const{authInfo,event}=this.state.required;this.state.set("reader",eventReaderOf(this.scope,authInfo,event.name,this.codes))}async checkEntryAuthorities(){const{event,authInfo}=this.state.required;const sentArguments=this.input.request.params.arguments??{};await assertEventAuthorities(this.scope,event,authInfo,sentArguments,this.codes)}async validateArguments(){const{event,reader}=this.state.required;const parsedArguments=parsedEventArguments(event,this.input.request.params.arguments);this.state.set({arguments:parsedArguments,subscription:readerSubscriptionOf(reader,"push",event.name,parsedArguments)})}async authorize(){const{event,authInfo,reader}=this.state.required;const context=event.create(authInfo);await assertEventAuthorizes(context,event.name,this.state.required.arguments,reader.subscriber,this.codes);this.state.set("context",context)}async openStream(){const streams=this.events.streams;const{event,context,reader,subscription,authInfo}=this.state.required;const{config}=this.events;const subscriptionArguments=this.state.required.arguments;const codes=this.codes;const stream=new EventStream({requestId:this.input.requestId,event,context,reader,subscription,arguments:subscriptionArguments,cursor:this.input.request.params.cursor,maxAgeMs:this.input.request.params.maxAgeMs,buffer:context.check?void 0:this.events.buffer,heartbeatMs:config.push.heartbeatMs,checkIntervalMs:config.poll.nextPollMs,checkMaxEvents:config.poll.maxEvents,reauthorizeEveryMs:config.subscriptions.reauthorizeEveryMs,reauthorize:()=>reauthorizeSubscriber({scope:this.scope,event,subscriber:reader.subscriber,arguments:subscriptionArguments,authInfo}),accessRevoked:{code:codes.forbidden,message:"Forbidden",data:{reason:"Access revoked"}},signal:this.input.signal,logger:this.logger});if(!streams.reserve(stream)){stream.close();throw new EventResourceExhaustedError(this.codes,"streams",config.subscriptions.maxPerPrincipal)}try{await context.onSubscribe?.(subscriptionArguments,subscription)}catch(error){stream.close();throw error}stream.onClose(()=>{const warn=error=>this.logger.warn(`onUnsubscribe of event "${event.name}" failed for stream ${subscription.id}`,error);try{Promise.resolve(context.onUnsubscribe?.(subscriptionArguments,subscription,"closed")).catch(warn)}catch(error){warn(error)}});streams.add(stream);try{await stream.open()}catch(error){stream.close();throw error}this.state.set("stream",stream);this.logger.verbose(`openStream: stream ${subscription.id} opened for event "${event.name}"`)}async buildResult(){this.respond({stream:this.state.required.stream})}async finalize(){this.logger.verbose("finalize")}};__decorateClass([Stage42("parseInput")],EventStreamFlow.prototype,"parseInput",1);__decorateClass([Stage42("resolveDialect")],EventStreamFlow.prototype,"resolveDialect",1);__decorateClass([Stage42("findEvent")],EventStreamFlow.prototype,"findEvent",1);__decorateClass([Stage42("resolveReader")],EventStreamFlow.prototype,"resolveReader",1);__decorateClass([Stage42("checkEntryAuthorities")],EventStreamFlow.prototype,"checkEntryAuthorities",1);__decorateClass([Stage42("validateArguments")],EventStreamFlow.prototype,"validateArguments",1);__decorateClass([Stage42("authorize")],EventStreamFlow.prototype,"authorize",1);__decorateClass([Stage42("openStream")],EventStreamFlow.prototype,"openStream",1);__decorateClass([Stage42("buildResult")],EventStreamFlow.prototype,"buildResult",1);__decorateClass([Stage42("finalize")],EventStreamFlow.prototype,"finalize",1);EventStreamFlow=__decorateClass([FrontMcpFlow({name:name42,plan:plan42,inputSchema:inputSchema35,outputSchema:outputSchema34,access:"authorized"})],EventStreamFlow)}});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_utils171,SUBSCRIPTION_SWEEP_INTERVAL_MS,EventSubscriptions;var init_event_subscriptions=__esm({"libs/sdk/src/event/subscription/event-subscriptions.ts"(){"use strict";import_utils171=require("@frontmcp/utils");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_utils171.canonicalJson)({principalKey,url,name:eventName,arguments:args});return{id:`sub_${(0,import_utils171.sha256Hex)(canonicalKey).slice(0,32)}`,argumentsKey:(0,import_utils171.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 expire(id,now=Date.now()){const removed=await this.store.deleteExpired(id,now);if(removed)await this.notifyUnsubscribed(removed,"expired")}async sweep(now=Date.now()){this.lastSweepAt=now;const expired=await this.store.listExpired(now);for(const record of expired){await this.expire(record.id,now)}}sweepIfDue(now=Date.now()){if(now-this.lastSweepAt<SUBSCRIPTION_SWEEP_INTERVAL_MS)return;this.sweepInBackground(now)}start(){const{runtime,deployment}=(0,import_utils171.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))}}}});function reactivatedStatus(status={}){const{failures:_failures,suspendedSince:_suspendedSince,...kept}=status;return kept}var import_lazy_zod135,import_protocol79,import_utils172,inputSchema36,outputSchema35,stateSchema38,plan43,name43,Stage43,URL_PROBLEMS,EventSubscribeFlow;var init_event_subscribe_flow=__esm({"libs/sdk/src/event/flows/event-subscribe.flow.ts"(){"use strict";import_lazy_zod135=require("@frontmcp/lazy-zod");import_protocol79=require("@frontmcp/protocol");import_utils172=require("@frontmcp/utils");init_common();init_availability();init_errors();init_event_dialect();init_event_subscriber();init_event_subscriptions();inputSchema36=import_lazy_zod135.internalZ.object({request:import_protocol79.SubscribeEventRequestSchema,ctx:import_lazy_zod135.internalZ.unknown()});outputSchema35=import_protocol79.SubscribeEventResultSchema;stateSchema38=import_lazy_zod135.internalZ.object({authInfo:import_lazy_zod135.internalZ.any(),dialect:import_lazy_zod135.internalZ.enum(["sep-3415","sketch"]),event:import_lazy_zod135.internalZ.instanceof(EventEntry),owner:import_lazy_zod135.internalZ.any(),arguments:import_lazy_zod135.internalZ.record(import_lazy_zod135.internalZ.string(),import_lazy_zod135.internalZ.unknown()),subscriptionId:import_lazy_zod135.internalZ.string(),argumentsKey:import_lazy_zod135.internalZ.string(),existing:import_lazy_zod135.internalZ.any(),verifiedAt:import_lazy_zod135.internalZ.number(),expiresAt:import_lazy_zod135.internalZ.number().nullable(),record:import_lazy_zod135.internalZ.any(),truncated:import_lazy_zod135.internalZ.boolean().optional()});plan43={pre:["parseInput","resolveDialect","findEvent","checkAvailability","requireWebhookMode","requireSubscriber","checkEntryAuthorities","validateArguments","authorize","validateDelivery"],execute:["findSubscription","enforceLimits","verifyCallback","grantTtl","upsertSubscription","notifySubscribed","startReplay"],post:["buildResult"],finalize:["finalize"]};name43="events:subscribe";({Stage:Stage43}=FlowHooksOf(name43));URL_PROBLEMS={malformed:"it is not a URL",scheme:"it must use https",credentials:"it must not carry a user name or a password",host:"its host is local, private or a metadata service"};EventSubscribeFlow=class extends FlowBase{logger=this.scopeLogger.child("EventSubscribeFlow");get events(){return this.scope.events}get subscriptions(){return this.events.subscriptions}get codes(){return EVENT_DIALECTS[this.state.required.dialect].errorCodes}async parseInput(){const authInfo=this.input.ctx?.authInfo??{};this.state.set("authInfo",authInfo)}async resolveDialect(){const platform=callerPlatformOf(this.scope,this.state.required.authInfo,this.tryGetContext()?.platformType);this.state.set("dialect",resolveEventDialect(this.events.config.compat,platform))}async findEvent(){const eventName=this.input.request.params.name;const event=this.events.findByName(eventName);if(!event)throw new EventNotFoundError(this.codes,"event",eventName);this.state.set("event",event)}async checkAvailability(){const{event}=this.state.required;if(!isOfferedOnSurface(event.metadata.availableWhen,callSurfaceOf(this.input.ctx))){throw new EventNotFoundError(this.codes,"event",event.name)}}async requireWebhookMode(){const requestedMode=this.input.request.params.delivery.mode??"webhook";const subscribableModes=this.events.deliveryModesOf(this.state.required.event).filter(mode=>mode==="webhook");if(requestedMode!=="webhook"||subscribableModes.length===0){throw new EventUnsupportedError(this.codes,"deliveryMode",requestedMode,subscribableModes)}}async requireSubscriber(){const{authInfo,event}=this.state.required;const owner=eventSubscriberOf(authInfo,this.scope.authoritiesContextBuilder);if(!owner)throw new EventForbiddenError(this.codes,event.name,"a webhook subscription needs a signed-in caller");this.state.set("owner",owner)}async checkEntryAuthorities(){const engine=this.scope.authoritiesEngine;const contextBuilder=this.scope.authoritiesContextBuilder;const{event,authInfo}=this.state.required;const authorities=event.getAuthorities();if(!engine||!contextBuilder||!authorities)return;const evaluationContext=contextBuilder.build(authInfo,this.input.request.params.arguments??{});const result=await engine.evaluate(authorities,evaluationContext);if(!result.granted){throw new EventForbiddenError(this.codes,event.name,result.deniedBy??"policy denied")}}async validateArguments(){try{this.state.set("arguments",this.state.required.event.parseArguments(this.input.request.params.arguments??{}))}catch(error){throw new InvalidInputError("Invalid subscription arguments",error instanceof import_lazy_zod135.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_utils172.validateOutboundUrl)(url,{allowLocal});if(!urlCheck.ok)throw new InvalidInputError(`Invalid delivery.url: ${URL_PROBLEMS[urlCheck.problem]}`);if(!(0,import_utils172.isStandardWebhookSecret)(secret)){throw new InvalidInputError('Invalid delivery.secret: expected "whsec_" followed by base64 that decodes to 24 to 64 bytes')}}async findSubscription(){const{owner,event}=this.state.required;const{url}=this.input.request.params.delivery;const identity=this.subscriptions.identityOf(owner.principalKey,url,event.name,this.state.required.arguments);this.subscriptions.sweepIfDue();const existing=await this.subscriptions.store.get(identity.id);if(!existing)await this.subscriptions.expire(identity.id);this.state.set({subscriptionId:identity.id,argumentsKey:identity.argumentsKey,existing})}async enforceLimits(){if(this.state.existing)return;const{maxPerPrincipal}=this.subscriptions.settings;const held=await this.subscriptions.store.countByPrincipal(this.state.required.owner.principalKey);if(held>=maxPerPrincipal)throw new EventResourceExhaustedError(this.codes,"subscriptions",maxPerPrincipal)}async verifyCallback(){const{url,secret}=this.input.request.params.delivery;const{owner,subscriptionId}=this.state.required;const verification=await this.subscriptions.verifier.verify({principalKey:owner.principalKey,url,secret,subscriptionId,verifiedAt:this.state.existing?.verifiedAt});if(verification.outcome==="limited"){throw new EventResourceExhaustedError(this.codes,"verifications",verification.max)}if(verification.outcome==="failed"){this.logger.verbose(`verifyCallback: subscription ${subscriptionId} refused (${verification.reason})`);throw new EventCallbackEndpointError(this.codes,verification.reason)}this.state.set("verifiedAt",verification.verifiedAt)}async grantTtl(){const requestedTtlMs=this.input.request.params.ttlMs;this.state.set("expiresAt",this.subscriptions.grantExpiry(this.state.required.event,requestedTtlMs,Date.now()))}async upsertSubscription(){const{url,secret}=this.input.request.params.delivery;const{owner,event,dialect,subscriptionId,argumentsKey,verifiedAt}=this.state.required;const expiresAt=this.state.get("expiresAt")??null;const existing=this.state.existing;const replay=existing?await this.currentReplayOf(subscriptionId):void 0;const now=Date.now();const record={id:subscriptionId,principalKey:owner.principalKey,subscriber:owner.subscriber,eventName:event.name,arguments:this.state.required.arguments,argumentsKey,delivery:this.subscriptions.rotatedDelivery(existing?.delivery,url,secret,now),dialect,createdAt:existing?.createdAt??now,updatedAt:now,expiresAt,verifiedAt,lastAuthorizedAt:now,active:true,status:reactivatedStatus(existing?.status),...replay&&{replay}};await this.subscriptions.store.upsert(record);this.state.set("record",record)}async notifySubscribed(){if(this.state.existing)return;const{event,record,authInfo}=this.state.required;try{await this.subscriptions.notifySubscribed(event,record,authInfo)}catch(error){await this.subscriptions.store.delete(record.id);throw error}this.logger.verbose(`notifySubscribed: subscription ${record.id} created for event "${event.name}"`)}async startReplay(){const{replays}=this.events;const{event,record}=this.state.required;if(!replays?.isReplayable(event))return;const{cursor=null,maxAgeMs}=this.input.request.params;const step=record.replay?await replays.refresh(record,record.replay):await replays.begin(event,record,cursor,maxAgeMs);this.state.set({record:{...record,replay:step.replay},truncated:step.truncated})}async currentReplayOf(subscriptionId){const stored=await this.subscriptions.store.get(subscriptionId);return stored?.replay}async buildResult(){const{record}=this.state.required;this.respond({id:record.id,refreshBefore:record.expiresAt===null?null:new Date(record.expiresAt).toISOString(),cursor:record.replay?.watermark??null,truncated:this.state.truncated??false,...this.state.existing&&{deliveryStatus:deliveryStatusOf(record)}})}async finalize(){this.logger.verbose("finalize")}};__decorateClass([Stage43("parseInput")],EventSubscribeFlow.prototype,"parseInput",1);__decorateClass([Stage43("resolveDialect")],EventSubscribeFlow.prototype,"resolveDialect",1);__decorateClass([Stage43("findEvent")],EventSubscribeFlow.prototype,"findEvent",1);__decorateClass([Stage43("checkAvailability")],EventSubscribeFlow.prototype,"checkAvailability",1);__decorateClass([Stage43("requireWebhookMode")],EventSubscribeFlow.prototype,"requireWebhookMode",1);__decorateClass([Stage43("requireSubscriber")],EventSubscribeFlow.prototype,"requireSubscriber",1);__decorateClass([Stage43("checkEntryAuthorities")],EventSubscribeFlow.prototype,"checkEntryAuthorities",1);__decorateClass([Stage43("validateArguments")],EventSubscribeFlow.prototype,"validateArguments",1);__decorateClass([Stage43("authorize")],EventSubscribeFlow.prototype,"authorize",1);__decorateClass([Stage43("validateDelivery")],EventSubscribeFlow.prototype,"validateDelivery",1);__decorateClass([Stage43("findSubscription")],EventSubscribeFlow.prototype,"findSubscription",1);__decorateClass([Stage43("enforceLimits")],EventSubscribeFlow.prototype,"enforceLimits",1);__decorateClass([Stage43("verifyCallback")],EventSubscribeFlow.prototype,"verifyCallback",1);__decorateClass([Stage43("grantTtl")],EventSubscribeFlow.prototype,"grantTtl",1);__decorateClass([Stage43("upsertSubscription")],EventSubscribeFlow.prototype,"upsertSubscription",1);__decorateClass([Stage43("notifySubscribed")],EventSubscribeFlow.prototype,"notifySubscribed",1);__decorateClass([Stage43("startReplay")],EventSubscribeFlow.prototype,"startReplay",1);__decorateClass([Stage43("buildResult")],EventSubscribeFlow.prototype,"buildResult",1);__decorateClass([Stage43("finalize")],EventSubscribeFlow.prototype,"finalize",1);EventSubscribeFlow=__decorateClass([FrontMcpFlow({name:name43,plan:plan43,inputSchema:inputSchema36,outputSchema:outputSchema35,access:"authorized"})],EventSubscribeFlow)}});var import_lazy_zod136,import_protocol80,inputSchema37,outputSchema36,stateSchema39,plan44,name44,Stage44,EventUnsubscribeFlow;var init_event_unsubscribe_flow=__esm({"libs/sdk/src/event/flows/event-unsubscribe.flow.ts"(){"use strict";import_lazy_zod136=require("@frontmcp/lazy-zod");import_protocol80=require("@frontmcp/protocol");init_common();init_errors();init_event_dialect();init_event_subscriber();inputSchema37=import_lazy_zod136.internalZ.object({request:import_protocol80.UnsubscribeEventRequestSchema,ctx:import_lazy_zod136.internalZ.unknown()});outputSchema36=import_protocol80.UnsubscribeEventResultSchema;stateSchema39=import_lazy_zod136.internalZ.object({authInfo:import_lazy_zod136.internalZ.any(),dialect:import_lazy_zod136.internalZ.enum(["sep-3415","sketch"]),owner:import_lazy_zod136.internalZ.any()});plan44={pre:["parseInput","resolveDialect","requireSubscriber"],execute:["removeSubscription"],post:["buildResult"],finalize:["finalize"]};name44="events:unsubscribe";({Stage:Stage44}=FlowHooksOf(name44));EventUnsubscribeFlow=class extends FlowBase{logger=this.scopeLogger.child("EventUnsubscribeFlow");get events(){return this.scope.events}get subscriptions(){return this.events.subscriptions}async parseInput(){const authInfo=this.input.ctx?.authInfo??{};this.state.set("authInfo",authInfo)}async resolveDialect(){const platform=callerPlatformOf(this.scope,this.state.required.authInfo,this.tryGetContext()?.platformType);this.state.set("dialect",resolveEventDialect(this.events.config.compat,platform))}async requireSubscriber(){const{authInfo,dialect}=this.state.required;const owner=eventSubscriberOf(authInfo,this.scope.authoritiesContextBuilder);if(!owner){const eventName=this.input.request.params.name;const codes=EVENT_DIALECTS[dialect].errorCodes;throw new EventForbiddenError(codes,eventName,"a webhook subscription needs a signed-in caller")}this.state.set("owner",owner)}async removeSubscription(){const{name:eventName,delivery}=this.input.request.params;const{owner,authInfo}=this.state.required;const identity=this.subscriptions.identityOf(owner.principalKey,delivery.url,eventName,this.storedArguments());this.subscriptions.sweepIfDue();const removed=await this.subscriptions.store.delete(identity.id);if(!removed)return;await this.subscriptions.notifyUnsubscribed(removed,"unsubscribed",authInfo);this.logger.verbose(`removeSubscription: subscription ${removed.id} removed from event "${eventName}"`)}async buildResult(){this.respond({})}async finalize(){this.logger.verbose("finalize")}storedArguments(){const{name:eventName,arguments:sentArguments={}}=this.input.request.params;try{return this.events.findByName(eventName)?.parseArguments(sentArguments)??sentArguments}catch{return sentArguments}}};__decorateClass([Stage44("parseInput")],EventUnsubscribeFlow.prototype,"parseInput",1);__decorateClass([Stage44("resolveDialect")],EventUnsubscribeFlow.prototype,"resolveDialect",1);__decorateClass([Stage44("requireSubscriber")],EventUnsubscribeFlow.prototype,"requireSubscriber",1);__decorateClass([Stage44("removeSubscription")],EventUnsubscribeFlow.prototype,"removeSubscription",1);__decorateClass([Stage44("buildResult")],EventUnsubscribeFlow.prototype,"buildResult",1);__decorateClass([Stage44("finalize")],EventUnsubscribeFlow.prototype,"finalize",1);EventUnsubscribeFlow=__decorateClass([FrontMcpFlow({name:name44,plan:plan44,inputSchema:inputSchema37,outputSchema:outputSchema36,access:"authorized"})],EventUnsubscribeFlow)}});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_zod137,import_protocol81,EVENTS_LIST_PAGE_SIZE,inputSchema38,outputSchema37,stateSchema40,plan45,name45,Stage45,ListEventsFlow;var init_list_events_flow=__esm({"libs/sdk/src/event/flows/list-events.flow.ts"(){"use strict";import_lazy_zod137=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;inputSchema38=import_lazy_zod137.internalZ.object({request:import_protocol81.ListEventsRequestSchema,ctx:import_lazy_zod137.internalZ.unknown()});outputSchema37=import_protocol81.ListEventsResultSchema;stateSchema40=import_lazy_zod137.internalZ.object({cursor:import_lazy_zod137.internalZ.string().optional(),authInfo:import_lazy_zod137.internalZ.any(),events:import_lazy_zod137.internalZ.array(import_lazy_zod137.internalZ.object({event:import_lazy_zod137.internalZ.instanceof(EventEntry),delivery:import_lazy_zod137.internalZ.array(import_protocol81.EventDeliveryModeSchema)}))});plan45={pre:["parseInput"],execute:["findEvents","filterByAvailability","filterByAuthorities","filterByDiscovery"],post:["parseEvents"],finalize:["finalize"]};name45="events:list";({Stage:Stage45}=FlowHooksOf(name45));ListEventsFlow=class extends FlowBase{logger=this.scopeLogger.child("ListEventsFlow");async parseInput(){const{request:request2,ctx}=this.input;const authInfo=ctx?.authInfo??{};this.state.set({cursor:request2.params?.cursor??void 0,authInfo})}async findEvents(){this.state.set("events",this.scope.events?.getServedEvents()??[])}async filterByAvailability(){const callSurface=callSurfaceOf(this.input.ctx);const offered=this.state.required.events.filter(({event})=>isOfferedOnSurface(event.metadata.availableWhen,callSurface));this.state.set("events",offered)}async filterByAuthorities(){const engine=this.scope.authoritiesEngine;const contextBuilder=this.scope.authoritiesContextBuilder;if(!engine||!contextBuilder)return;const{events,authInfo}=this.state.required;const answers=await Promise.all(events.map(({event})=>{const authorities=event.getAuthorities();if(authorities===void 0)return true;return isListedByAuthorities(engine,contextBuilder,authorities,authInfo,event.name,this.logger)}));this.state.set("events",events.filter((_item,index)=>answers[index]))}async filterByDiscovery(){const discoverable=this.state.required.events.filter(({event})=>!event.metadata.hideFromDiscovery);this.state.set("events",discoverable)}async parseEvents(){const sorted=[...this.state.required.events].sort(compareByName);const offset=this.state.cursor?parseOffsetCursor(this.state.cursor):0;if(offset>sorted.length){throw new InvalidInputError(`Invalid pagination cursor: offset ${offset} exceeds total event count ${sorted.length}`)}const events=sorted.slice(offset,offset+EVENTS_LIST_PAGE_SIZE).map(({event,delivery})=>({name:event.name,...event.metadata.description&&{description:event.metadata.description},delivery,inputSchema:event.getInputJsonSchema(),payloadSchema:event.getPayloadJsonSchema()}));const nextOffset=offset+EVENTS_LIST_PAGE_SIZE;this.respond({events,...nextOffset<sorted.length&&{nextCursor:encodeOffsetCursor(nextOffset)}})}async finalize(){this.logger.verbose("finalize")}};__decorateClass([Stage45("parseInput")],ListEventsFlow.prototype,"parseInput",1);__decorateClass([Stage45("findEvents")],ListEventsFlow.prototype,"findEvents",1);__decorateClass([Stage45("filterByAvailability")],ListEventsFlow.prototype,"filterByAvailability",1);__decorateClass([Stage45("filterByAuthorities")],ListEventsFlow.prototype,"filterByAuthorities",1);__decorateClass([Stage45("filterByDiscovery")],ListEventsFlow.prototype,"filterByDiscovery",1);__decorateClass([Stage45("parseEvents")],ListEventsFlow.prototype,"parseEvents",1);__decorateClass([Stage45("finalize")],ListEventsFlow.prototype,"finalize",1);ListEventsFlow=__decorateClass([FrontMcpFlow({name:name45,plan:plan45,inputSchema:inputSchema38,outputSchema:outputSchema37,access:"authorized"})],ListEventsFlow)}});var import_utils173,CURSOR_SEPARATOR,EventBuffer;var init_event_buffer=__esm({"libs/sdk/src/event/poll/event-buffer.ts"(){"use strict";import_utils173=require("@frontmcp/utils");CURSOR_SEPARATOR=".";EventBuffer=class{constructor(options){this.options=options;this.bootId=(0,import_utils173.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_zod138,EVENT_PUBLISH_MAX_BODY_BYTES,EVENT_ID_PATTERN,audienceValueSchema2,publishRequestSchema,inputSchema39,outputSchema38,stateSchema41,plan46,name46,Stage46,decoder3,EventPublishHttpFlow;var init_event_publish_http_flow=__esm({"libs/sdk/src/event/flows/event-publish-http.flow.ts"(){"use strict";import_lazy_zod138=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_zod138.internalZ.union([import_lazy_zod138.internalZ.string(),import_lazy_zod138.internalZ.array(import_lazy_zod138.internalZ.string())]);publishRequestSchema=import_lazy_zod138.internalZ.object({name:import_lazy_zod138.internalZ.string().min(1),data:import_lazy_zod138.internalZ.record(import_lazy_zod138.internalZ.string(),import_lazy_zod138.internalZ.unknown()),eventId:import_lazy_zod138.internalZ.string().regex(EVENT_ID_PATTERN,"eventId must be 1 to 255 visible ASCII characters").optional(),timestamp:import_lazy_zod138.internalZ.string().refine(isTimestamp,"timestamp must be a date such as 2026-10-02T12:00:00Z").optional(),subscriptionId:import_lazy_zod138.internalZ.string().min(1).optional(),audience:import_lazy_zod138.internalZ.object({sub:audienceValueSchema2.optional(),tenantId:audienceValueSchema2.optional(),roles:import_lazy_zod138.internalZ.object({any:import_lazy_zod138.internalZ.array(import_lazy_zod138.internalZ.string()).optional(),all:import_lazy_zod138.internalZ.array(import_lazy_zod138.internalZ.string()).optional()}).strict().optional()}).strict().optional()}).strict();inputSchema39=httpInputSchema;outputSchema38=HttpJsonSchema;stateSchema41=import_lazy_zod138.internalZ.object({body:import_lazy_zod138.internalZ.custom(),caller:import_lazy_zod138.internalZ.custom().optional(),publication:publishRequestSchema,event:import_lazy_zod138.internalZ.instanceof(EventEntry),claimedEventId:import_lazy_zod138.internalZ.string().optional(),claimToken:import_lazy_zod138.internalZ.string().optional(),result:import_lazy_zod138.internalZ.object({eventId:import_lazy_zod138.internalZ.string(),matched:import_lazy_zod138.internalZ.number()}),flowError:import_lazy_zod138.internalZ.instanceof(Error).optional()});plan46={pre:["checkIpFilter","acquireQuota","readBody","authenticate","parseBody","checkAuthorities","findEvent","validatePayload"],execute:["claimEventId","publish","rememberResult","buildResponse"],finalize:["finalize"]};name46="events:publish-http";({Stage:Stage46}=FlowHooksOf(name46));decoder3=new TextDecoder;EventPublishHttpFlow=class extends FlowBase{logger=this.scopeLogger.child("EventPublishHttpFlow");static canActivate(request2,scope){const endpoint=scope.events?.publishEndpoint;return endpoint!==void 0&&request2.method==="POST"&&matchRoutePath(endpoint.path,request2.path)!==void 0}get events(){return this.scope.events}get endpoint(){return this.events.publishEndpoint}get publisher(){return this.events.publisher}get httpRequest(){return this.rawInput.request}refuse(status,error,details={},headers){this.state.set("flowError",new PublicMcpError(`HTTP ${status}: ${error}`,"EVENT_PUBLISH_REFUSED",status));return FlowControl.respond(httpRespond.json({error,...details},{status,headers}))}async checkIpFilter(){enforceIpFilter(this.scope,this.tryGetContext()?.metadata.clientIp)}async acquireQuota(){await 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_zod138.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([Stage46("checkIpFilter")],EventPublishHttpFlow.prototype,"checkIpFilter",1);__decorateClass([Stage46("acquireQuota")],EventPublishHttpFlow.prototype,"acquireQuota",1);__decorateClass([Stage46("readBody")],EventPublishHttpFlow.prototype,"readBody",1);__decorateClass([Stage46("authenticate")],EventPublishHttpFlow.prototype,"authenticate",1);__decorateClass([Stage46("parseBody")],EventPublishHttpFlow.prototype,"parseBody",1);__decorateClass([Stage46("checkAuthorities")],EventPublishHttpFlow.prototype,"checkAuthorities",1);__decorateClass([Stage46("findEvent")],EventPublishHttpFlow.prototype,"findEvent",1);__decorateClass([Stage46("validatePayload")],EventPublishHttpFlow.prototype,"validatePayload",1);__decorateClass([Stage46("claimEventId")],EventPublishHttpFlow.prototype,"claimEventId",1);__decorateClass([Stage46("publish")],EventPublishHttpFlow.prototype,"publish",1);__decorateClass([Stage46("rememberResult")],EventPublishHttpFlow.prototype,"rememberResult",1);__decorateClass([Stage46("buildResponse")],EventPublishHttpFlow.prototype,"buildResponse",1);__decorateClass([Stage46("finalize")],EventPublishHttpFlow.prototype,"finalize",1);EventPublishHttpFlow=__decorateClass([FrontMcpFlow({name:name46,plan:plan46,inputSchema:inputSchema39,outputSchema:outputSchema38,access:"public",middleware:{method:"POST"}})],EventPublishHttpFlow)}});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_utils174,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_utils174=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_utils174.sha256Hex)(text);return(0,import_utils174.bytesToHex)((0,import_utils174.hmacSha256)(textEncoder3.encode(secret),textEncoder3.encode(text)))}}}});function eventsSecretFromEnv(){return(0,import_utils175.getEnv)("MCP_EVENTS_SECRET")||(0,import_utils175.getEnv)("MCP_SESSION_SECRET")||(0,import_utils175.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(!isRedisProvider(redis)){throw new EventSubscriptionStoreError("Vercel KV has no atomic compare-and-set, which subscription updates need. Use a Redis server in events.store.redis, or events.store.sqlite.")}const{host,port,password,db,tls}=redis;return{type:"redis",redis:{config:{host,port,password,db,tls}}}}async function openStorage(config,keyPrefix){try{return await(0,import_utils175.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_utils175;var init_event_subscription_store_factory=__esm({"libs/sdk/src/event/subscription/event-subscription-store.factory.ts"(){"use strict";import_utils175=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_utils176,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_utils176=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_utils176.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_utils176.sha256Hex)(JSON.stringify([this.scopeId,eventName,eventId])).slice(0,40)}}}});function assertPathFree(scope,path4){const reserved=computeReservedPaths(scope.entryPath,scope.routeBase,servedHealthPaths(scope.metadata.health));try{assertNotReserved("POST",path4,reserved)}catch(error){if(!(error instanceof ReservedRouteCollisionError))throw error;throw new EventPublishEndpointError(`events.publishEndpoint.path "${path4}" is on the reserved FrontMCP path "${error.reserved}": choose another path`)}const routes=[...scope.httpRouteTable?.routes??[],...scope.metadata.http?.routes??[]];const taken=routes.find(route=>route.method.toUpperCase()==="POST"&&matchRoutePath(route.path,path4)!==void 0);if(taken){throw new EventPublishEndpointError(`events.publishEndpoint.path "${path4}" is already served by the route POST ${taken.path}: choose another path`)}}async function enablePublishEndpoint(args){const{scope,eventRegistry,identifiesCallers,keyPrefix,logger}=args;const{secret,authorities,path:configuredPath}=eventRegistry.config.publishEndpoint;const{store:storeConfig}=eventRegistry.config;if(!secret&&!identifiesCallers){throw new EventPublishEndpointError("the server runs in public auth mode, so nothing tells who publishes. Set events.publishEndpoint.secret (at least 32 characters) for signed requests, or configure an auth mode that signs callers in.")}if(authorities!==void 0){assertEntryAuthorities(scope.authoritiesEngine,scope.authoritiesContextBuilder,[{label:"events.publishEndpoint",authorities}])}const path4=`${normalizeScopeBase(scope.routeBase)}${configuredPath}`;assertPathFree(scope,path4);let storage=eventRegistry.storage;if(!storage){const ownStorage=await openEventStorage({redis:storeConfig?.redis,sqlite:storeConfig?.sqlite,keyPrefix});scope.onDispose(()=>ownStorage.disconnect());storage=ownStorage}eventRegistry.publishEndpoint={path:path4,secret,authorities,replays:new WorkflowWebhookReplayGuard,idempotency:new EventPublishIdempotency(storage,scope.id)};await scope.registryFlows(EventPublishHttpFlow);logger.info(`Events can be published over HTTP: POST ${path4} (${secret?"signed requests":"bearer callers"})`);if(!secret&&authorities===void 0){logger.warn(`POST ${path4} lets every signed-in caller publish every event. Set events.publishEndpoint.authorities to name who may publish.`)}}var init_event_publish_endpoint=__esm({"libs/sdk/src/event/publish-endpoint/event-publish-endpoint.ts"(){"use strict";init_common();init_errors();init_flow_http_path();init_authorities_rules_check();init_health_routes();init_custom_routes_helper();init_workflow_webhook_signature();init_event_publish_http_flow();init_event_subscription_store_factory();init_event_publish_idempotency()}});function isSameReadPosition(current,expected){return current?.cursor===expected.cursor&&current.queuedAtCursor===expected.queuedAtCursor}function isSamePosition(current,expected){if(!current||current.cursor!==expected.cursor||current.pending.length!==expected.pending.length)return false;return current.pending.every((batch,index)=>batch.cursor===expected.pending[index].cursor)}var import_utils177,REPLAY_LEASE_MS,REPLAY_STOP_GRACE_MS,MAX_PENDING_BATCHES,MAX_ROUNDS_PER_TICK,encoder10,EventReplays;var init_event_replays=__esm({"libs/sdk/src/event/replay/event-replays.ts"(){"use strict";import_utils177=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;encoder10=new TextEncoder;EventReplays=class{constructor(options){this.options=options;this.logger=options.logger.child("EventReplays")}options;holders=new Map;timers=new Map;ticks=new Map;nextCheckAt=new Map;logger;isReplayable(event){return typeof event.create({}).check==="function"}async start(events){for(const event of events){const holder=new LeaseHolder({label:`Webhook delivery of event "${event.name}"`,key:`replay-lease:${(0,import_utils177.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,eventName:record.eventName,body:JSON.stringify({type:"gap",cursor:replay.watermark}),webhookId:(0,import_utils177.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=encoder10.encode(body).byteLength;if(bytes>this.options.maxBodyBytes){this.logger.warn(`Event "${event.name}" is ${bytes} bytes for subscription ${record.id}, over the ${this.options.maxBodyBytes} byte limit; it is not delivered`);return void 0}const usesEventId=EVENT_DIALECTS[record.dialect].webhookId==="eventId";return this.options.outbox.enqueue({kind:"event",subscriptionId:record.id,eventName:event.name,body,webhookId:usesEventId?eventId:(0,import_utils177.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_utils178,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_utils178=require("@frontmcp/utils");EVENT_RELAY_CHANNEL="occurrences";MAX_OPEN_STREAMS=1e4;EventStreams=class{constructor(options){this.options=options;this.nodeId=(0,import_utils178.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}async start(){const{storage}=this.options;if(!storage||!this.isRelayed)return;this.stopRelay=await storage.subscribe(EVENT_RELAY_CHANNEL,message=>this.receive(message))}async stop(){await this.stopRelay?.();this.stopRelay=void 0;for(const streams of[...this.streams.values()]){for(const stream of[...streams])stream.close()}}isFull(principalKey){if(this.held.size>=MAX_OPEN_STREAMS)return true;let heldByOwner=0;for(const stream of this.held){if(stream.principalKey===principalKey)heldByOwner+=1}return heldByOwner>=this.options.maxPerPrincipal}reserve(stream){if(this.held.has(stream))return true;if(this.isFull(stream.principalKey))return false;this.hold(stream);return true}add(stream){this.hold(stream);if(stream.isClosed)return;const streams=this.streams.get(stream.eventName)??new Set;this.streams.set(stream.eventName,streams);streams.add(stream)}hold(stream){if(this.held.has(stream)||stream.isClosed)return;this.held.add(stream);stream.onClose(()=>{this.held.delete(stream);this.streams.get(stream.eventName)?.delete(stream)})}async publish(buffered){await this.deliver(buffered);const{storage}=this.options;if(!storage||!this.isRelayed)return;const{occurrence,audience,subscriptionId}=buffered;const relayed={origin:this.nodeId,occurrence,audience,subscriptionId};try{await storage.publish(EVENT_RELAY_CHANNEL,JSON.stringify(relayed))}catch(error){this.logger.warn(`Event "${occurrence.name}" was not relayed to the other processes`,error)}}async deliver(buffered){const streams=this.streams.get(buffered.occurrence.name);if(!streams)return;await Promise.all([...streams].map(stream=>stream.offer(buffered)))}receive(message){const relayed=parseRelayed(message);if(!relayed||relayed.origin===this.nodeId)return;const buffered=this.options.buffer.append(relayed.occurrence,relayed.audience,relayed.subscriptionId);this.deliver(buffered).catch(error=>this.logger.warn("A relayed event was not delivered",error))}}}});function isSameText(left,right){const leftBytes=encoder11.encode(left);const rightBytes=encoder11.encode(right);return leftBytes.length===rightBytes.length&&(0,import_utils179.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_utils179,VERIFICATION_ATTEMPTS_PER_HOST,VERIFICATION_WINDOW_MS,WELL_KNOWN_CACHE_MS,WELL_KNOWN_MAX_BYTES,CHALLENGE_BYTES,CHALLENGE_ANSWER_MAX_BYTES,MAX_CACHED_ENTRIES,encoder11,ExpiringMap,EventCallbackVerifier;var init_event_callback_verifier=__esm({"libs/sdk/src/event/subscription/event-callback-verifier.ts"(){"use strict";import_protocol83=require("@frontmcp/protocol");import_utils179=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;encoder11=new TextEncoder;ExpiringMap=class{entries=new Map;get(key,now){const entry=this.entries.get(key);if(!entry)return void 0;if(entry.expiresAt>now)return entry.value;this.entries.delete(key);return void 0}set(key,value,expiresAt){this.entries.delete(key);if(this.entries.size>=MAX_CACHED_ENTRIES){const oldestKey=this.entries.keys().next().value;if(oldestKey!==void 0)this.entries.delete(oldestKey)}this.entries.set(key,{value,expiresAt})}};EventCallbackVerifier=class{constructor(options){this.options=options;this.send=options.send??import_utils179.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_utils179.sha256Hex)(`${request2.principalKey}
331
+ `;RedisTransportBus=class{constructor(redis,machineId,options){this.redis=redis;this.machineId=machineId;this.keyPrefix=options?.keyPrefix??DEFAULT_BUS_PREFIX;this.ttlSeconds=options?.ttlSeconds??DEFAULT_BUS_TTL_SECONDS;this.haKeyPrefix=options?.haKeyPrefix??"mcp:ha:";this.retryAfterSeconds=options?.retryAfterSeconds??DEFAULT_RETRY_AFTER_SECONDS;this.logger=options?.logger}redis;machineId;keyPrefix;ttlSeconds;haKeyPrefix;retryAfterSeconds;logger;relay;nodeId(){return this.machineId}attachRelay(relay){this.relay=relay}canRelay(){return this.relay!==void 0}channelOf(nodeId){return`${this.haKeyPrefix}notify:${nodeId}`}async advertise(key){await this.redis.eval(ADVERTISE_LUA,1,this.busKey(key.sessionId),this.machineId,this.channelOf(this.machineId),key.type,key.tokenHash,this.ttlSeconds);this.logger?.debug("[TransportBus] Advertised session",{sessionId:key.sessionId.slice(0,20),nodeId:this.machineId})}async revoke(key){const redisKey=this.busKey(key.sessionId);const result=await this.redis.eval(REVOKE_LUA,1,redisKey,this.machineId);this.logger?.debug("[TransportBus] Revoked session",{sessionId:key.sessionId.slice(0,20),deleted:result===1})}async lookup(key){const entry=await this.readEntry(key.sessionId);if(!entry)return null;if(entry.nodeId===this.machineId)return null;if(entry.type&&entry.type!==key.type||entry.tokenHash&&entry.tokenHash!==key.tokenHash){return null}return{nodeId:entry.nodeId,channel:entry.channel}}async lookupOwner(sessionId){const entry=await this.readEntry(sessionId);return entry?{nodeId:entry.nodeId,channel:entry.channel}:null}async proxyRequest(location,sessionId,request2,response){if(isRelayedRequest(request2)){throw new SessionOwnerUnreachableError(location.nodeId,this.retryAfterSeconds,"the request was already relayed once and its session moved again")}if(!this.relay){throw new SessionOwnerUnreachableError(location.nodeId,this.retryAfterSeconds,"request relay is not available on this node (no Redis pub/sub)")}await this.relay.forward(location.nodeId,sessionId,serializeRelayRequest(request2),response)}async destroyRemote(key,reason){const entry=await this.readEntry(key.sessionId);if(!entry||entry.nodeId===this.machineId)return;const message=JSON.stringify({kind:"destroy-session",sessionId:key.sessionId,reason,sourceNodeId:this.machineId,timestamp:Date.now()});await this.redis.publish(entry.channel,message);this.logger?.info("[TransportBus] Sent destroy-remote",{sessionId:key.sessionId.slice(0,20),targetNodeId:entry.nodeId})}async readEntry(sessionId){const fields=await this.redis.hgetall(this.busKey(sessionId));const nodeId=fields?.["nodeId"];if(!nodeId)return null;return{nodeId,channel:fields["channel"]||this.channelOf(nodeId),type:fields["type"]||void 0,tokenHash:fields["tokenHash"]||void 0}}busKey(sessionId){return`${this.keyPrefix}session:${sessionId}`}}}});var bus_exports={};__export(bus_exports,{RedisTransportBus:()=>RedisTransportBus});var init_bus=__esm({"libs/sdk/src/transport/bus/index.ts"(){"use strict";init_redis_transport_bus()}});var MemoryEventStore;var init_memory_event_store=__esm({"libs/sdk/src/transport/event-stores/memory.event-store.ts"(){"use strict";MemoryEventStore=class{streams=new Map;index=new Map;maxEvents;ttlMs;constructor(options={}){this.maxEvents=options.maxEvents??1e4;this.ttlMs=options.ttlMs??3e5}async storeEvent(streamId,message){this.evictExpired();const list=this.streams.get(streamId)??[];const id=`${streamId}:${list.length+1}`;const rec={id,msg:message,timestamp:Date.now()};list.push(rec);this.streams.set(streamId,list);this.index.set(id,{streamId,idx:list.length-1});if(this.index.size>this.maxEvents){this.evictOldest()}return id}async getStreamIdForEventId(eventId){return this.index.get(eventId)?.streamId}async replayEventsAfter(lastEventId,{send}){const meta=this.index.get(lastEventId);if(!meta){const freshStream="default-stream";if(!this.streams.has(freshStream))this.streams.set(freshStream,[]);return freshStream}const{streamId,idx}=meta;const list=this.streams.get(streamId)??[];for(let k=idx+1;k<list.length;k++){const e=list[k];if(Date.now()-e.timestamp<this.ttlMs){await send(e.id,e.msg)}}return streamId}evictExpired(){const now=Date.now();for(const[streamId,list]of this.streams){const validEvents=list.filter(e=>now-e.timestamp<this.ttlMs);if(validEvents.length<list.length){this.streams.set(streamId,validEvents);this.rebuildIndex(streamId,validEvents)}}}evictOldest(){let oldest=null;for(const[streamId,list]of this.streams){if(list.length>0&&(!oldest||list[0].timestamp<oldest.timestamp)){oldest={streamId,idx:0,timestamp:list[0].timestamp}}}if(oldest){const list=this.streams.get(oldest.streamId);if(list&&list.length>0){const removed=list.shift();if(removed){this.index.delete(removed.id)}this.rebuildIndex(oldest.streamId,list)}}}rebuildIndex(streamId,list){for(const[id,meta]of this.index){if(meta.streamId===streamId){this.index.delete(id)}}list.forEach((e,idx)=>this.index.set(e.id,{streamId,idx}))}clear(){this.streams.clear();this.index.clear()}get size(){return this.index.size}}}});var import_utils147,RedisEventStore;var init_redis_event_store=__esm({"libs/sdk/src/transport/event-stores/redis.event-store.ts"(){"use strict";import_utils147=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 Redis=require("ioredis");const{host,port,password,db,tls}=redis;this.client=new Redis({host,port,password,db,tls:tls?{}:void 0,lazyConnect:true,enableReadyCheck:false,maxRetriesPerRequest:3});(0,import_utils147.attachRedisErrorListener)(this.client,{label:"RedisEventStore"});await this.client.connect()}return this.client}async storeEvent(streamId,message){const client=await this.getClient();const streamKey=`${this.keyPrefix}${streamId}`;const redisId=await client.xadd(streamKey,"MAXLEN","~",this.maxEvents.toString(),"*","msg",JSON.stringify(message));await client.expire(streamKey,this.ttlSeconds);return`${streamId}:${redisId}`}async getStreamIdForEventId(eventId){const parsed=this.parseEventId(eventId);return parsed?parsed[0]:void 0}async replayEventsAfter(lastEventId,{send}){const parsed=this.parseEventId(lastEventId);if(!parsed){return"default-stream"}const client=await this.getClient();const[streamId,redisId]=parsed;const streamKey=`${this.keyPrefix}${streamId}`;const entries=await client.xrange(streamKey,`(${redisId}`,"+");for(const[id,fields]of entries){const msgIndex=fields.indexOf("msg");if(msgIndex!==-1&&msgIndex+1<fields.length){const msgStr=fields[msgIndex+1];const msg=JSON.parse(msgStr);await send(`${streamId}:${id}`,msg)}}return streamId}parseEventId(eventId){const value=String(eventId);const lastDash=value.lastIndexOf("-");const separator=lastDash===-1?value.lastIndexOf(":"):value.lastIndexOf(":",lastDash);if(separator<=0||separator===value.length-1)return void 0;const streamId=value.slice(0,separator);const redisId=value.slice(separator+1);if(!/^\d+(-\d+)?$/.test(redisId))return void 0;return[streamId,redisId]}async close(){if(this.client){await this.client.quit();this.client=void 0}}}}});function createEventStore(config,logger){if(!config?.enabled){logger?.verbose("[EventStoreFactory] EventStore disabled (resumability not available)");return{eventStore:void 0,type:"disabled"}}const provider=config.provider??"memory";const maxEvents=config.maxEvents??1e4;const ttlMs=config.ttlMs??3e5;if(provider==="sqlite"){if(!config.sqlite||!config.sqlite.path){throw new PublicMcpError('EventStore SQLite configuration required when provider is "sqlite". Provide sqlite config: { provider: "sqlite", sqlite: { path: "..." } }',"INVALID_PARAMS")}const{SqliteEventStore}=(0,import_utils48.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_utils148.sha256Hex)(sessionId).slice(0,12)}var import_utils148;var init_session_id_hash=__esm({"libs/sdk/src/logger/session-id-hash.ts"(){"use strict";import_utils148=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_utils149,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_utils149=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_utils149.TypedStorage(storage.namespace("pending"));this.fallback=new import_utils149.TypedStorage(storage.namespace("fallback"));this.resolved=new import_utils149.TypedStorage(storage.namespace("resolved"))}async setPending(record){const{sessionId,expiresAt}=record;const ttlSeconds=(0,import_utils149.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_utils149.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_utils150.getEnv)("UPSTASH_REDIS_REST_URL")){return"upstash"}if((0,import_utils150.getEnv)("REDIS_URL")||(0,import_utils150.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: ... }')}const{host,port,password,db,tls}=redisOptions;finalStorageConfig={type:"redis",redis:{config:{host,port,password,db,tls}}};logger?.debug("[ElicitationStoreFactory] Converted redis option to storage config",{host,port})}const explicitBackend=Boolean(storageConfig||redis);if(finalStorageConfig?.type==="vercel-kv"||!explicitBackend&&(0,import_utils150.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_utils150.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_utils150.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_utils48.requireOptionalModule)("@frontmcp/storage-sqlite",()=>require_dist());logger?.info("[ElicitationStoreFactory] Creating SQLite elicitation store",{path:sqliteConfig.path,keyPrefix});return new SqliteElicitationStore({...sqliteConfig,keyPrefix})}var import_utils150;var init_elicitation_store_factory=__esm({"libs/sdk/src/elicitation/store/elicitation-store.factory.ts"(){"use strict";import_utils150=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()}});function recordKey(sessionId,taskId){return`${sessionId}:${taskId}`}function slotKey(sessionId,slot){return`${sessionId}:${slot}`}function encodeCursor(offset){return(0,import_utils151.base64urlEncode)(new TextEncoder().encode(JSON.stringify({offset})))}function decodeCursor(cursor){try{const bytes=(0,import_utils151.base64urlDecode)(cursor);const parsed=JSON.parse(new TextDecoder().decode(bytes));if(typeof parsed?.offset==="number"&&parsed.offset>=0&&Number.isInteger(parsed.offset)){return parsed.offset}}catch{}return 0}var import_utils151,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_utils151=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;logger;terminalCallbacks=new Map;terminalSubs=new Map;cancelCallbacks=new Map;cancelSubs=new Map;constructor(storage,logger){this.storage=storage;this.logger=logger;this.records=new import_utils151.TypedStorage(storage.namespace(RECORDS_NAMESPACE));this.slots=storage.namespace(SLOTS_NAMESPACE)}async create(record){const ttlSeconds=(0,import_utils151.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 this.records.set(key,record,{ttlSeconds});this.logger?.debug("[StorageTaskStore] created",{taskId:record.taskId,ttlSeconds})}async createWithinLimit(record,maxActive){const ttlSeconds=(0,import_utils151.expiresAtToTTL)(record.expiresAt);if(ttlSeconds<=0){await this.create(record);return true}const slot=await this.acquireSlot(record,maxActive,ttlSeconds);if(slot===void 0)return false;const slotted={...record,concurrencySlot:slot};try{await this.create(slotted)}catch(err){await this.releaseSlot(slotted);throw err}return true}async get(taskId,sessionId){const record=await this.records.get(recordKey(sessionId,taskId));if(!record)return null;if(record.sessionId!==sessionId)return null;if(record.expiresAt&&Date.now()>record.expiresAt){await this.delete(taskId,sessionId);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_utils151.expiresAtToTTL)(merged.expiresAt);if(ttlSeconds<=0){await this.delete(taskId,sessionId);return null}await this.records.set(recordKey(sessionId,taskId),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)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 namespaced=this.storage.namespace(RECORDS_NAMESPACE);const allKeys=await namespaced.keys();const sessionPrefix=`${sessionId}:`;const matching=allKeys.filter(k=>k.startsWith(sessionPrefix)).map(k=>k.slice(sessionPrefix.length)).sort();const offset=opts.cursor?decodeCursor(opts.cursor):0;const slice=matching.slice(offset,offset+pageSize);const records=[];for(const taskId of slice){const rec=await this.get(taskId,sessionId);if(rec)records.push(rec)}const nextOffset=offset+slice.length;const page2={tasks:records};if(nextOffset<matching.length){page2.nextCursor=encodeCursor(nextOffset)}return page2}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_utils152.getEnv)("UPSTASH_REDIS_REST_URL"))return"upstash";if((0,import_utils152.getEnv)("REDIS_URL")||(0,import_utils152.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_utils48.requireOptionalModule)("@frontmcp/storage-sqlite",()=>require_dist());const store2=new SqliteTaskStore({path:sqlite.path,encryption:sqlite.encryption,walMode:sqlite.walMode??true,ttlCleanupIntervalMs:sqlite.ttlCleanupIntervalMs??6e4,busyTimeoutMs:sqlite.busyTimeoutMs,logger:logger?{debug:(m,meta)=>logger.debug(m,meta),warn:(m,meta)=>logger.warn(m,meta),error:(m,meta)=>logger.error(m,meta)}:void 0});logger?.info("[TaskStoreFactory] Created SQLite task store",{path:sqlite.path,keyPrefix});return{store:store2,type:"sqlite"}}let finalStorageConfig=storageConfig;if(redis&&!isExplicitStorage(storageConfig)){const redisOptions=normalizeRedisOptions(redis);if(typeof redisOptions==="string"){throw new TaskStoreNotSupportedError(`Invalid Redis configuration: ${redisOptions}`)}if(isVercelKvProvider(redisOptions)){throw new TaskStoreNotSupportedError("Vercel KV is not supported for task stores. Task result blocking and cancel signalling require pub/sub. Use Redis or Upstash instead.")}const{host,port,password,db,tls}=redisOptions;finalStorageConfig={type:"redis",redis:{config:{host,port,password,db,tls}}}}const explicitBackend=isExplicitStorage(storageConfig)||Boolean(redis);if(finalStorageConfig?.type==="vercel-kv"||!explicitBackend&&(0,import_utils152.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_utils152.createStorage)({...finalStorageConfig,prefix:keyPrefix,fallback:isEdgeRuntime4?"error":"memory"});const store=new StorageTaskStore(storage,logger);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_utils152.createMemoryStorage)({prefix:keyPrefix});return{store:new StorageTaskStore(storage,logger),type:"memory",storage}}var import_utils152,TaskStoreNotSupportedError;var init_task_store_factory=__esm({"libs/sdk/src/task/store/task-store.factory.ts"(){"use strict";import_utils152=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_utils153.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;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_utils153;var init_task_runner=__esm({"libs/sdk/src/task/helpers/task-runner.ts"(){"use strict";import_utils153=require("@frontmcp/utils");init_errors();init_call_tool_error_utils();init_mcp_error_utils();init_task_types()}});var InProcessTaskRunner;var init_in_process_task_runner=__esm({"libs/sdk/src/task/helpers/in-process-task-runner.ts"(){"use strict";init_task_runner();InProcessTaskRunner=class{constructor(deps){this.deps=deps}deps;kind="in-process";async run(record,context){await this.deps.store.update(record.taskId,record.sessionId,{executor:{host:"in-process",spawnedAt:new Date().toISOString()}});void runTaskInBackground({record,cleanedRequestParams:context.cleanedRequestParams,ctx:context.ctx,scope:this.deps.scope,store:this.deps.store,registry:this.deps.registry,notifier:this.deps.notifier,logger:this.deps.logger})}async cancel(record){this.deps.registry.abort(record.taskId,"tasks/cancel")}}}});var import_lazy_zod119,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_zod119=require("@frontmcp/lazy-zod");import_protocol68=require("@frontmcp/protocol");init_common();init_errors();init_task_types();inputSchema21=import_lazy_zod119.internalZ.object({request:import_protocol68.GetTaskRequestSchema,ctx:import_lazy_zod119.internalZ.any()});outputSchema20=import_protocol68.GetTaskResultSchema;stateSchema25=import_lazy_zod119.internalZ.object({taskId:import_lazy_zod119.internalZ.string(),sessionId:import_lazy_zod119.internalZ.string(),authInfo:import_lazy_zod119.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_zod119.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_zod120,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_zod120=require("@frontmcp/lazy-zod");import_protocol69=require("@frontmcp/protocol");init_common();init_errors();init_task_types();inputSchema22=import_lazy_zod120.internalZ.object({request:import_protocol69.GetTaskPayloadRequestSchema,ctx:import_lazy_zod120.internalZ.any()});outputSchema21=import_protocol69.GetTaskPayloadResultSchema;stateSchema26=import_lazy_zod120.internalZ.object({taskId:import_lazy_zod120.internalZ.string(),sessionId:import_lazy_zod120.internalZ.string(),authInfo:import_lazy_zod120.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_zod120.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((resolve4,reject)=>{let settled=false;let unsubscribe;let pollTimer;const finalize=async(result,err)=>{if(settled)return;settled=true;if(pollTimer)clearTimeout(pollTimer);if(unsubscribe){try{await unsubscribe()}catch{}}if(err)reject(err);else resolve4(result)};const poll=async()=>{if(settled)return;try{const latest=await store.get(taskId,sessionId);if(!latest)return void finalize(null);if(isTerminal(latest.status))return void finalize(latest)}catch(err){return void finalize(null,err)}pollTimer=setTimeout(()=>void poll(),this.pollDelayMs())};store.subscribeTerminal(taskId,sessionId,record=>{if(isTerminal(record.status)){void finalize(record)}}).then(async unsub=>{unsubscribe=unsub;const latest=await store.get(taskId,sessionId);if(!latest){return void finalize(null)}if(isTerminal(latest.status)){return void finalize(latest)}pollTimer=setTimeout(()=>void poll(),this.pollDelayMs(latest.pollIntervalMs))}).catch(err=>void finalize(null,err))})}pollDelayMs(hint){const min=200;const max=5e3;if(typeof hint==="number"&&hint>0)return Math.max(min,Math.min(hint,max));return 500}respondWithOutcome(record){if(!record.outcome){throw new InternalMcpError("Terminal task has no outcome","TASK_MISSING_OUTCOME")}if(record.outcome.kind==="error"){const{code,message,data}=record.outcome.error;const err=new JsonRpcReplayError(code,message,data,record.taskId);throw err}const payload={...record.outcome.data};const existingMeta=payload["_meta"]??{};payload["_meta"]={...existingMeta,[RELATED_TASK_META_KEY]:{taskId:record.taskId}};this.respond(payload)}};__decorateClass([Stage29("parseInput")],TasksResultFlow.prototype,"parseInput",1);__decorateClass([Stage29("awaitTerminal")],TasksResultFlow.prototype,"awaitTerminal",1);TasksResultFlow=__decorateClass([FrontMcpFlow({name:name29,plan:plan29,inputSchema:inputSchema22,outputSchema:outputSchema21,access:"authorized"})],TasksResultFlow);JsonRpcReplayError=class extends Error{constructor(code,message,data,taskId){super(message);this.code=code;this.data=data;this.taskId=taskId;this.name="JsonRpcReplayError"}code;data;taskId;toJsonRpcError(){const out={code:this.code,message:this.message};if(this.data!==void 0)out.data=this.data;return out}}}});var import_lazy_zod121,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_zod121=require("@frontmcp/lazy-zod");import_protocol70=require("@frontmcp/protocol");init_common();init_errors();init_task_types();inputSchema23=import_lazy_zod121.internalZ.object({request:import_protocol70.CancelTaskRequestSchema,ctx:import_lazy_zod121.internalZ.any()});outputSchema22=import_protocol70.CancelTaskResultSchema;stateSchema27=import_lazy_zod121.internalZ.object({taskId:import_lazy_zod121.internalZ.string(),sessionId:import_lazy_zod121.internalZ.string(),authInfo:import_lazy_zod121.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_zod121.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_zod122,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_zod122=require("@frontmcp/lazy-zod");import_protocol71=require("@frontmcp/protocol");init_common();init_errors();init_task_types();inputSchema24=import_lazy_zod122.internalZ.object({request:import_protocol71.ListTasksRequestSchema,ctx:import_lazy_zod122.internalZ.any()});outputSchema23=import_protocol71.ListTasksResultSchema;stateSchema28=import_lazy_zod122.internalZ.object({sessionId:import_lazy_zod122.internalZ.string(),cursor:import_lazy_zod122.internalZ.string().optional(),authInfo:import_lazy_zod122.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_zod122.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_auth54.isAnonymousSubject)(candidate));return principal?`principal:${principal}`:void 0}var import_auth54;var init_session_scope_identity=__esm({"libs/sdk/src/auth/session-scope-identity.ts"(){"use strict";import_auth54=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_auth55.InMemoryAuthorizationVault){const providers=[];providers.push({provide:import_auth55.AUTH_PROVIDERS_REGISTRY,scope:import_di48.ProviderScope.GLOBAL,name:"AuthProvidersRegistry",useFactory:()=>new import_auth55.AuthProvidersRegistry(options)});providers.push({provide:import_auth55.AUTH_PROVIDERS_VAULT,scope:import_di48.ProviderScope.GLOBAL,name:"AuthProvidersVault",useFactory:logger=>new import_auth55.AuthProvidersVault(store.storage,{namespace:options.namespace,defaultCacheTtl:options.defaultCacheTtl,pepper:store.pepper,logger}),inject:()=>[FrontMcpLogger]});providers.push({provide:CREDENTIAL_CACHE,scope:import_di48.ProviderScope.CONTEXT,name:"CredentialCache",useFactory:()=>new import_auth55.CredentialCache(options.maxCredentialsPerSession??100)});providers.push({provide:LAZY_CREDENTIAL_LOADER,scope:import_di48.ProviderScope.CONTEXT,name:"LazyCredentialLoader",useFactory:logger=>new import_auth55.LazyCredentialLoader(logger),inject:()=>[FrontMcpLogger]});providers.push({provide:import_auth55.AUTH_PROVIDERS_ACCESSOR,scope:import_di48.ProviderScope.CONTEXT,name:"AuthProvidersAccessor",useFactory:(registry,vault,cache2,loader,ctx,logger)=>{const user=ctx.authInfo?.user;const signedIn=user&&!(0,import_auth55.isAnonymousSubject)(user.sub)?user:void 0;const factoryContext={sessionId:sessionScopeIdentity(ctx)??`${import_auth55.UNIDENTIFIED_SESSION_PREFIX}${(0,import_utils154.randomUUID)()}`,userSub:signedIn?.sub,userEmail:signedIn?.email,userName:signedIn?.name,vault:baseVault};return new import_auth55.AuthProvidersAccessorImpl(registry,vault,cache2,loader,factoryContext,logger)},inject:()=>[import_auth55.AUTH_PROVIDERS_REGISTRY,import_auth55.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_utils154.getEnv)("VAULT_SECRET")||(0,import_utils154.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_utils154.createStorage)({type:"memory"});await providers.addDynamicProviders(createAuthProvidersProviders(options,{storage}));return()=>storage.disconnect()}var import_auth55,import_di48,import_utils154,LAZY_CREDENTIAL_LOADER;var init_auth_providers_providers=__esm({"libs/sdk/src/auth/vault/auth-providers.providers.ts"(){"use strict";import_auth55=require("@frontmcp/auth");import_di48=require("@frontmcp/di");import_utils154=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_utils155.getRuntimeContext)().runtime==="browser"?"console":"stdout"}]}function observabilityPlugins({config:observabilityConfig,logger,globalProviders,implied=false}){const plugins=[];let ObservabilityPluginModule;try{ObservabilityPluginModule=(0,import_utils48.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_utils155;var init_observability_scope_helper=__esm({"libs/sdk/src/scope/observability-scope.helper.ts"(){"use strict";import_utils155=require("@frontmcp/utils");init_context();init_logger_registry();init_optional_dependency_util();init_tracer_provider_utils()}});var import_lazy_zod123,import_utils156,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_zod123=require("@frontmcp/lazy-zod");import_utils156=require("@frontmcp/utils");init_common();init_errors();init_session_id_hash();init_elicitation_types();inputSchema25=import_lazy_zod123.internalZ.object({relatedRequestId:import_lazy_zod123.internalZ.union([import_lazy_zod123.internalZ.string(),import_lazy_zod123.internalZ.number()]),sessionId:import_lazy_zod123.internalZ.string(),message:import_lazy_zod123.internalZ.string(),requestedSchema:import_lazy_zod123.internalZ.record(import_lazy_zod123.internalZ.string(),import_lazy_zod123.internalZ.unknown()),options:import_lazy_zod123.internalZ.object({mode:import_lazy_zod123.internalZ.enum(["form","url"]).optional(),ttl:import_lazy_zod123.internalZ.number().optional(),elicitationId:import_lazy_zod123.internalZ.string().optional(),url:import_lazy_zod123.internalZ.string().optional()}).optional()});outputSchema24=import_lazy_zod123.internalZ.object({elicitId:import_lazy_zod123.internalZ.string(),sessionId:import_lazy_zod123.internalZ.string(),expiresAt:import_lazy_zod123.internalZ.number(),mode:import_lazy_zod123.internalZ.enum(["form","url"]),requestParams:import_lazy_zod123.internalZ.record(import_lazy_zod123.internalZ.string(),import_lazy_zod123.internalZ.unknown()),pendingRecord:import_lazy_zod123.internalZ.any()});stateSchema29=import_lazy_zod123.internalZ.object({relatedRequestId:import_lazy_zod123.internalZ.union([import_lazy_zod123.internalZ.string(),import_lazy_zod123.internalZ.number()]),sessionId:import_lazy_zod123.internalZ.string(),message:import_lazy_zod123.internalZ.string(),requestedSchema:import_lazy_zod123.internalZ.record(import_lazy_zod123.internalZ.string(),import_lazy_zod123.internalZ.unknown()),mode:import_lazy_zod123.internalZ.enum(["form","url"]).default("form"),ttl:import_lazy_zod123.internalZ.number().default(DEFAULT_ELICIT_TTL),elicitationId:import_lazy_zod123.internalZ.string().optional(),url:import_lazy_zod123.internalZ.string().optional(),elicitId:import_lazy_zod123.internalZ.string(),expiresAt:import_lazy_zod123.internalZ.number(),pendingRecord:import_lazy_zod123.internalZ.any().optional(),requestParams:import_lazy_zod123.internalZ.record(import_lazy_zod123.internalZ.string(),import_lazy_zod123.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,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_utils156.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 store=this.scope.elicitationStore;if(!store){throw new ElicitationStoreNotInitializedError}const pendingRecord={elicitId,sessionId,createdAt:Date.now(),expiresAt,message,mode,requestedSchema};await store.setPending(pendingRecord);this.state.set("pendingRecord",pendingRecord);this.logger.verbose("storePendingRecord:done",{elicitId,sessionIdHash:sessionIdHash(sessionId)})}async buildRequestParams(){this.logger.verbose("buildRequestParams:start");const{mode,message,requestedSchema,elicitId}=this.state.required;const requestParams={mode,message,requestedSchema};if(mode==="url"){requestParams["elicitationId"]=elicitId;requestParams["url"]=this.state.url}this.state.set("requestParams",requestParams);this.logger.verbose("buildRequestParams:done")}async finalize(){this.logger.verbose("finalize:start");const{elicitId,sessionId,expiresAt,mode}=this.state.required;const{requestParams,pendingRecord}=this.state;if(!requestParams||!pendingRecord){throw new InvalidInputError("finalize: missing requestParams or pendingRecord from prior stages")}this.respond({elicitId,sessionId,expiresAt,mode,requestParams,pendingRecord});this.logger.verbose("finalize:done")}};__decorateClass([Stage32("parseInput")],ElicitationRequestFlow.prototype,"parseInput",1);__decorateClass([Stage32("validateRequest")],ElicitationRequestFlow.prototype,"validateRequest",1);__decorateClass([Stage32("generateElicitId")],ElicitationRequestFlow.prototype,"generateElicitId",1);__decorateClass([Stage32("storePendingRecord")],ElicitationRequestFlow.prototype,"storePendingRecord",1);__decorateClass([Stage32("buildRequestParams")],ElicitationRequestFlow.prototype,"buildRequestParams",1);__decorateClass([Stage32("finalize")],ElicitationRequestFlow.prototype,"finalize",1);ElicitationRequestFlow=__decorateClass([FrontMcpFlow({name:name32,plan:plan32,inputSchema:inputSchema25,outputSchema:outputSchema24,access:"authorized"})],ElicitationRequestFlow)}});var import_lazy_zod124,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_zod124=require("@frontmcp/lazy-zod");init_common();init_errors();init_session_id_hash();init_helpers();inputSchema26=import_lazy_zod124.internalZ.object({sessionId:import_lazy_zod124.internalZ.string(),result:import_lazy_zod124.internalZ.object({action:import_lazy_zod124.internalZ.enum(["accept","cancel","decline"]),content:import_lazy_zod124.internalZ.unknown().optional()})});outputSchema25=import_lazy_zod124.internalZ.object({handled:import_lazy_zod124.internalZ.boolean(),elicitId:import_lazy_zod124.internalZ.string().optional(),result:import_lazy_zod124.internalZ.any().optional()});stateSchema30=import_lazy_zod124.internalZ.object({sessionId:import_lazy_zod124.internalZ.string(),action:import_lazy_zod124.internalZ.enum(["accept","cancel","decline"]),content:import_lazy_zod124.internalZ.unknown().optional(),pendingRecord:import_lazy_zod124.internalZ.any().optional(),elicitResult:import_lazy_zod124.internalZ.any().optional(),handled:import_lazy_zod124.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,action:input.result.action,content:input.result.content});this.logger.verbose("parseInput:done",{sessionIdHash:sessionIdHash(input.sessionId),action:input.result.action})}async lookupPending(){this.logger.verbose("lookupPending:start");const{sessionId}=this.state.required;const store=this.scope.elicitationStore;if(!store){throw new ElicitationStoreNotInitializedError}const pendingRecord=await store.getPending(sessionId);this.state.set("pendingRecord",pendingRecord??void 0);if(!pendingRecord){this.logger.verbose("lookupPending:notFound",{sessionIdHash:sessionIdHash(sessionId)})}else{this.logger.verbose("lookupPending:found",{sessionIdHash:sessionIdHash(sessionId),elicitId:pendingRecord.elicitId})}}async validateContent(){this.logger.verbose("validateContent:start");const{action,content,pendingRecord}=this.state;if(action!=="accept"){this.logger.verbose("validateContent:skip (non-accept action)",{action});return}if(!pendingRecord){this.logger.verbose("validateContent:skip (no pending record)");return}if(pendingRecord.mode==="url"){this.logger.verbose("validateContent:skip (url mode)");return}if(!pendingRecord.requestedSchema){this.logger.verbose("validateContent:skip (no schema stored)");return}const validationResult=validateElicitationContent(content,pendingRecord.requestedSchema);if(!validationResult.success){this.logger.warn("validateContent:failed",{sessionIdHash:sessionIdHash(pendingRecord.sessionId),elicitId:pendingRecord.elicitId,errors:validationResult.errors});throw new InvalidInputError("Invalid elicitation result content",validationResult.errors)}this.logger.verbose("validateContent:done")}async buildResult(){this.logger.verbose("buildResult:start");const{action}=this.state.required;const{content,pendingRecord}=this.state;const keepsContent=action==="accept"&&content!==void 0&&pendingRecord?.mode!=="url";const elicitResult={status:action,...keepsContent&&{content}};this.state.set("elicitResult",elicitResult);this.logger.verbose("buildResult:done",{status:elicitResult.status})}async publishResult(){this.logger.verbose("publishResult:start");const{pendingRecord,elicitResult}=this.state;const{sessionId}=this.state.required;const store=this.scope.elicitationStore;if(!pendingRecord||!elicitResult||!store){this.state.set("handled",false);this.logger.verbose("publishResult:skip (no pending or no result)");return}try{await store.publishResult(pendingRecord.elicitId,sessionId,elicitResult);this.state.set("handled",true);this.logger.verbose("publishResult:done",{elicitId:pendingRecord.elicitId,sessionId:sessionId.slice(0,20)})}catch(error){this.logger.warn("publishResult:failed",{elicitId:pendingRecord.elicitId,error:error.message});this.state.set("handled",false)}}async finalize(){this.logger.verbose("finalize:start");const{handled,pendingRecord,elicitResult}=this.state;const output={handled:handled??false,elicitId:pendingRecord?.elicitId,result:elicitResult};this.state.set("output",output);this.respond(output);this.logger.verbose("finalize:done",{handled})}};__decorateClass([Stage33("parseInput")],ElicitationResultFlow.prototype,"parseInput",1);__decorateClass([Stage33("lookupPending")],ElicitationResultFlow.prototype,"lookupPending",1);__decorateClass([Stage33("validateContent")],ElicitationResultFlow.prototype,"validateContent",1);__decorateClass([Stage33("buildResult")],ElicitationResultFlow.prototype,"buildResult",1);__decorateClass([Stage33("publishResult")],ElicitationResultFlow.prototype,"publishResult",1);__decorateClass([Stage33("finalize")],ElicitationResultFlow.prototype,"finalize",1);ElicitationResultFlow=__decorateClass([FrontMcpFlow({name:name33,plan:plan33,inputSchema:inputSchema26,outputSchema:outputSchema25,access:"authorized"})],ElicitationResultFlow)}});var flows_exports2={};__export(flows_exports2,{ElicitRequestFlow:()=>ElicitationRequestFlow,ElicitResultFlow:()=>ElicitationResultFlow,ElicitationRequestFlow:()=>ElicitationRequestFlow,ElicitationResultFlow:()=>ElicitationResultFlow});var init_flows2=__esm({"libs/sdk/src/elicitation/flows/index.ts"(){"use strict";init_elicitation_request_flow();init_elicitation_result_flow()}});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_utils157.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_utils157,SERVER_CARD_MEDIA_TYPE,envVarsReportedInvalid;var init_mcp_registry_utils=__esm({"libs/sdk/src/mcp-registry/mcp-registry.utils.ts"(){"use strict";import_utils157=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_zod125,import_utils158,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_zod125=require("@frontmcp/lazy-zod");import_utils158=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_zod125.internalZ.object({card:import_lazy_zod125.internalZ.record(import_lazy_zod125.internalZ.string(),import_lazy_zod125.internalZ.unknown())});outputSchema27=import_lazy_zod125.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_utils158.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_zod126,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_zod126=require("@frontmcp/lazy-zod");init_common();init_mcp_registry_utils();AI_CATALOG_PATH="/.well-known/ai-catalog.json";inputSchema29=httpInputSchema;outputSchema28=import_lazy_zod126.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&&registryOptions.name&&registryOptions.serverCard!==false){flows.push(ServerCardFlow);if(registryOptions.aiCatalog!==false)flows.push(WellKnownAiCatalogFlow)}await flowRegistry.registryFlows(flows)}var init_mcp_registry_scope_helper=__esm({"libs/sdk/src/mcp-registry/mcp-registry-scope.helper.ts"(){"use strict";init_flows3()}});async function serveRelayedHttpRequest(scope,request2,response){let output;try{output=await scope.runFlow("http:request",{request:request2,response})}catch(error){output=flowErrorToHttpOutput(error)}if(output&&!response.writableEnded){await writeHttpResponse(response,output)}if(response.writableEnded)return;if(!response.headersSent){await writeHttpResponse(response,{kind:"json",status:404,contentType:"application/json; charset=utf-8",body:{error:"Not Found"}});return}response.end()}var init_relay_flow=__esm({"libs/sdk/src/transport/relay/relay-flow.ts"(){"use strict";init_server_validation();init_flow_error_output()}});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_utils159,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_utils159=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_utils159.randomUUID)();const sessionLabel=sessionId.slice(0,20);return new Promise((resolve4,reject)=>{let acked=false;let headWritten=false;let done=false;let lastFrameAt=Date.now();let ownerTimer;const cleanup=()=>{clearTimeout(ackTimer);if(ownerTimer)clearInterval(ownerTimer);response.removeListener("close",onClientClose);this.pending.delete(requestId)};const finish=()=>{if(done)return;done=true;cleanup();resolve4()};const fail=reason=>{if(done)return;done=true;cleanup();this.logger?.warn(`[HA] Relay to session owner failed: ${reason}`,{sessionId:sessionLabel,ownerNodeId});if(!headWritten&&!response.headersSent){reject(this.unreachable(ownerNodeId,reason));return}if(!response.writableEnded)response.end();resolve4()};const onClientClose=()=>{if(done||response.writableFinished)return;done=true;cleanup();this.options.publish(ownerNodeId,{kind:"relay-cancel",requestId,sourceNodeId:this.nodeId}).catch(()=>void 0);resolve4()};const checkOwner=async()=>{if(Date.now()-lastFrameAt>=this.ownerCheckIntervalMs*SILENT_CHECKS_BEFORE_FAILURE){fail("the owner stopped sending the response");return}try{if(!await this.options.isNodeAlive(ownerNodeId))fail("the owner stopped while serving the request")}catch{}};const markAcked=()=>{if(acked)return;acked=true;clearTimeout(ackTimer);ownerTimer=setInterval(()=>void checkOwner(),this.ownerCheckIntervalMs);ownerTimer.unref?.()};const onFrame=frame4=>{if(done)return;lastFrameAt=Date.now();switch(frame4.event){case"ack":markAcked();return;case"keepalive":return;case"head":markAcked();if(!response.headersSent){response.writeHead(frame4.status,frame4.headers);response.flushHeaders?.()}headWritten=true;return;case"data":response.write(decodeRelayChunk(frame4));return;case"end":if(!response.writableEnded)response.end();finish();return;case"error":fail(`the owner could not serve the request: ${frame4.message}`);return}};const ackTimer=setTimeout(()=>fail(`the owner did not acknowledge the request within ${this.ackTimeoutMs}ms`),this.ackTimeoutMs);ackTimer.unref?.();this.pending.set(requestId,{ownerNodeId,onFrame,fail});response.once("close",onClientClose);const message={kind:"relay-request",requestId,sourceNodeId:this.nodeId,sessionId,request:request2,timestamp:Date.now(),keepaliveMs:this.ownerCheckIntervalMs};this.logger?.verbose?.("[HA] Relaying request to session owner",{sessionId:sessionLabel,ownerNodeId});this.options.publish(ownerNodeId,message).then(receivers=>{if(receivers===0)fail("the owner does not listen on its relay channel")},error=>fail(`publishing the request failed: ${errorMessage(error)}`))})}handleMessage(message){switch(message.kind){case"relay-request":if(!isServableRequest(message)){this.logger?.warn("[HA] Dropped a malformed relayed request");return}this.serveRelayed(message).catch(error=>{this.logger?.warn("[HA] Serving a relayed request failed",{error:errorMessage(error)})});return;case"relay-response":{const pending=this.pending.get(message.requestId);if(pending&&pending.ownerNodeId===message.sourceNodeId)pending.onFrame(message);return}case"relay-cancel":{const serving=this.serving.get(message.requestId);if(serving&&serving.sourceNodeId===message.sourceNodeId)serving.response.destroy();return}default:return}}async close(){if(this.closed)return;this.closed=true;for(const pending of[...this.pending.values()])pending.fail("this node is shutting down");for(const serving of[...this.serving.values()]){if(!serving.response.writableEnded){serving.send({event:"error",message:"the owner is shutting down"});serving.response.destroy()}}this.serving.clear()}async serveRelayed(message){const{requestId,sourceNodeId}=message;let undeliverable=false;const publishFrame=event=>{const frame4={kind:"relay-response",requestId,sourceNodeId:this.nodeId,...event};return this.options.publish(sourceNodeId,frame4)};const abandon=reason=>{if(undeliverable)return;undeliverable=true;this.logger?.warn("[HA] Failed to publish a relayed response frame",{reason,targetNodeId:sourceNodeId});publishFrame({event:"error",message:reason}).catch(()=>void 0);response.destroy()};const send=event=>{if(undeliverable)return;publishFrame(event).then(receivers=>{if(receivers===0)abandon("the relaying node no longer listens")},error=>abandon(`publishing a response frame failed: ${errorMessage(error)}`))};const response=new RelayServerResponse({head:(status,headers)=>send({event:"head",status,headers}),data:chunk=>send({event:"data",...chunk}),end:()=>send({event:"end"})});if(this.closed){send({event:"error",message:"the owner is shutting down"});return}send({event:"ack"});const keepaliveTimer=setInterval(()=>send({event:"keepalive"}),keepaliveIntervalOf(message));keepaliveTimer.unref?.();this.serving.set(requestId,{sourceNodeId,response,send});try{const request2=createRelayedServerRequest(message.request,sourceNodeId);await this.options.serve(request2,response.asServerResponse())}catch(error){this.logger?.warn("[HA] Serving a relayed request failed",{sessionId:message.sessionId.slice(0,20),sourceNodeId,error:errorMessage(error)});if(!response.writableEnded&&!response.destroyed&&!response.headersSent){response.status(500).json(rpcError("Internal error"))}}finally{clearInterval(keepaliveTimer);if(!response.writableEnded&&!response.destroyed)response.end();this.serving.delete(requestId)}}}}});var relay_scope_helper_exports={};__export(relay_scope_helper_exports,{wireSessionRelay:()=>wireSessionRelay});function wireSessionRelay(options){const{haManager,bus,transportService,notifications,logger,nodeId}=options;if(!haManager.getRelay())return void 0;const config=haManager.getConfig();const relay=new SessionRelay({nodeId,publish:(target,message)=>haManager.publishToNode(target,message),isNodeAlive:target=>haManager.isNodeAlive(target),serve:(request2,response)=>serveRelayedHttpRequest(options.flows,request2,response),ackTimeoutMs:options.ackTimeoutMs,ownerCheckIntervalMs:config.heartbeatIntervalMs,retryAfterSeconds:Math.ceil(config.heartbeatTtlMs/1e3),logger});const handler=message=>{if(isRequestRelayMessage(message)){relay.handleMessage(message);return}if(message.kind==="destroy-session"){transportService.destroyLocalSession(message.sessionId,message.reason).catch(error=>{logger.warn("[HA] Failed to destroy a session on request of another node",{sessionId:message.sessionId.slice(0,20),error:error instanceof Error?error.message:String(error)})});return}if(message.kind===void 0||message.kind==="notification"){notifications.deliverRelayedNotification(message.sessionId,message.notification.method,message.notification.params)}};let closed=false;let retryTimer;let settleReady=()=>void 0;const ready=new Promise(resolve4=>{settleReady=resolve4;const attempt=failures=>{if(closed){resolve4();return}haManager.subscribeRelay(handler).then(()=>{if(closed){resolve4();return}bus.attachRelay(relay);logger.info("[HA] Request relay ready \u2014 sessions owned by other nodes are served through them");resolve4()},error=>{const delay=Math.min(SUBSCRIBE_RETRY_MAX_MS,SUBSCRIBE_RETRY_BASE_MS*2**failures);logger.warn(`[HA] Relay channel subscription failed \u2014 retrying in ${delay}ms`,{error:error instanceof Error?error.message:String(error)});retryTimer=setTimeout(()=>attempt(failures+1),delay);retryTimer.unref?.()})};attempt(0)});return{relay,ready,close:async()=>{closed=true;if(retryTimer)clearTimeout(retryTimer);settleReady();bus.attachRelay(void 0);await relay.close()}}}var SUBSCRIBE_RETRY_BASE_MS,SUBSCRIBE_RETRY_MAX_MS;var init_relay_scope_helper=__esm({"libs/sdk/src/transport/relay/relay-scope.helper.ts"(){"use strict";init_relay_messages();init_relay_flow();init_session_relay();SUBSCRIBE_RETRY_BASE_MS=1e3;SUBSCRIBE_RETRY_MAX_MS=3e4}});var ChannelNotificationService;var init_channel_notification_service=__esm({"libs/sdk/src/channel/channel-notification.service.ts"(){"use strict";init_notification_service();init_channel_utils();ChannelNotificationService=class{constructor(notificationService,logger,defaultMeta,sendThroughFlow){this.notificationService=notificationService;this.sendThroughFlow=sendThroughFlow;this.logger=logger.child("ChannelNotificationService");this.serverMeta={...defaultMeta??{}}}notificationService;sendThroughFlow;logger;serverMeta;streamListeners=new Set;get defaultMeta(){return this.serverMeta}sendToSubscribedSessions(content,meta){const channelName=meta.source;if(!channelName){this.logger.warn("Cannot send channel notification without source in meta");return}const safeMeta=this.safeMetaOf(meta);for(const listener of this.streamListeners){if(listener.channels.has(channelName))listener.deliver(content,safeMeta)}const subscribers=this.notificationService.getSubscribersForChannel(channelName);if(subscribers.length===0){this.logger.verbose(`No subscribers for channel "${channelName}", notification buffered only`);return}const recipients=new Set(subscribers.filter(sessionId=>{const registered=this.notificationService.getRegisteredServer(sessionId);return registered!==void 0&&isChannelCapableSession(registered)&&!hasExpiredCaller(registered)}));if(recipients.size>0){this.notificationService.sendCustomNotification(CHANNEL_NOTIFICATION_METHOD,{content,meta:safeMeta},session=>recipients.has(session.sessionId))}this.logger.verbose(`Sent channel "${channelName}" notification to ${subscribers.length} subscriber(s)`)}listen(channelNames,deliver){const listener={channels:new Set(channelNames),deliver};this.streamListeners.add(listener);return()=>{this.streamListeners.delete(listener)}}sendToAllCapableSessions(content,meta){this.sendToSubscribedSessions(content,meta)}sendToSession(sessionId,content,meta){const registered=this.notificationService.getRegisteredServer(sessionId);if(!registered){this.logger.warn(`Cannot send channel notification to unregistered session: ${sessionId.slice(0,20)}...`);return false}if(!isChannelCapableSession(registered)){this.logger.verbose(`Session ${sessionId.slice(0,20)}... does not support channels, skipping`);return false}if(hasExpiredCaller(registered)){this.logger.verbose(`Session ${sessionId.slice(0,20)}... was last seen with expired credentials, skipping`);return false}const channelName=meta.source;if(!channelName){this.logger.error(`Channel notification rejected for session ${sessionId.slice(0,20)}...: meta.source is required`);return false}if(!this.notificationService.isChannelSubscribed(sessionId,channelName)){this.logger.verbose(`Session ${sessionId.slice(0,20)}... not subscribed to channel "${channelName}", skipping`);return false}this.notificationService.sendCustomNotification(CHANNEL_NOTIFICATION_METHOD,{content,meta:this.safeMetaOf(meta)},session=>session.sessionId===sessionId);return true}safeMetaOf(meta){return{...channelMetaOf(meta),source:meta.source}}async send(channelName,content,additionalMeta){if(!this.sendThroughFlow){const ownMeta=channelMetaValuesOf(additionalMeta??{});this.sendToSubscribedSessions(content,{...this.serverMeta,...ownMeta,source:channelName});return}try{await this.sendThroughFlow({channelName,content,meta:additionalMeta})}catch(error){this.logger.error(`Channel "${channelName}" notification failed`,{error})}}}}});var ChannelEmitter;var init_channel_events=__esm({"libs/sdk/src/channel/channel.events.ts"(){"use strict";ChannelEmitter=class{listeners=new Set;on(l){this.listeners.add(l);return()=>this.listeners.delete(l)}emit(e){for(const l of[...this.listeners])l(e)}}}});function connectsItself(context){return context.onConnect!==ChannelContext.prototype.onConnect}function watchedTypesOf(sourceConfig){if(!sourceConfig.events)return void 0;const watchedTypes=sourceConfig.events.flatMap(declaredEvent=>WATCHED_TYPES[declaredEvent]);return[...new Set(watchedTypes)]}function warnAboutGlobs(channelName,paths,logger){const globs=paths.filter(path4=>path4.includes("*"));if(globs.length===0)return;logger.warn(`Channel "${channelName}" declares ${globs.map(glob=>`"${glob}"`).join(", ")}: a file-watcher path is not expanded as a glob. Declare the directory to watch its direct files.`)}async function forwardFileEvents(channel2,sourceConfig,signal,logger){const events=watchedTypesOf(sourceConfig);for await(const{type,path:path4}of(0,import_utils160.watchFiles)(sourceConfig.paths,{events,signal})){const fileEvent={event:REPORTED_EVENTS[type],path:path4};logger.verbose(`File ${fileEvent.event} for channel "${channel2.name}": ${path4}`);try{await channel2.handleEvent(fileEvent)}catch(error){logger.error(`Failed to handle a file event in channel "${channel2.name}"`,{error})}}}function wireFileWatcherSource(channel2,context,sourceConfig,logger){if(connectsItself(context)){logger.info(`Channel "${channel2.name}" defines onConnect(), so it watches by itself: the framework does not watch its declared paths. Remove onConnect() to have the framework watch them.`);return()=>void 0}if(!isLongLivedProcess()){logger.warn(`Channel "${channel2.name}" does not watch its paths in a serverless, edge or browser runtime: watching files needs a long-lived process`);return()=>void 0}warnAboutGlobs(channel2.name,sourceConfig.paths,logger);const watch=new AbortController;forwardFileEvents(channel2,sourceConfig,watch.signal,logger).catch(error=>{logger.error(`Channel "${channel2.name}" stopped watching its paths`,{error})});return()=>watch.abort()}var import_utils160,WATCHED_TYPES,REPORTED_EVENTS;var init_file_watcher_source=__esm({"libs/sdk/src/channel/sources/file-watcher.source.ts"(){"use strict";import_utils160=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_utils161,ChannelRegistry;var init_channel_registry=__esm({"libs/sdk/src/channel/channel.registry.ts"(){"use strict";import_utils161=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_utils161.getRuntimeContext)();for(const token of this.tokens){const rec=this.defs.get(token);if(!rec)continue;if(!(0,import_utils161.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(name59){return this.localRows.find(r=>r.instance.name===name59)?.instance}hasAny(){return this.localRows.length>0}get size(){return this.localRows.length}getCapabilities(){if(!this.hasAny())return{};return{experimental:{"claude/channel":{}}}}subscribe(opts,cb){const unsub=this.emitter.on(cb);if(opts.immediate&&this.localRows.length>0){cb({kind:"reset",changeScope:"global",version:this.version,snapshot:this.getChannels()})}return unsub}bump(kind){this.version++;this.emitter.emit({kind,changeScope:"global",version:this.version,snapshot:this.getChannels()})}}}});var import_lazy_zod127,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_zod127=require("@frontmcp/lazy-zod");init_common();inputSchema30=import_lazy_zod127.internalZ.object({}).optional();channelInfoSchema=import_lazy_zod127.internalZ.object({name:import_lazy_zod127.internalZ.string(),description:import_lazy_zod127.internalZ.string().optional(),sourceType:import_lazy_zod127.internalZ.string(),twoWay:import_lazy_zod127.internalZ.boolean(),tags:import_lazy_zod127.internalZ.array(import_lazy_zod127.internalZ.string())});outputSchema29=import_lazy_zod127.internalZ.object({channels:import_lazy_zod127.internalZ.array(channelInfoSchema),count:import_lazy_zod127.internalZ.number()});stateSchema32=import_lazy_zod127.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_zod128,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_zod128=require("@frontmcp/lazy-zod");init_common();init_errors();init_channel_utils();inputSchema31=import_lazy_zod128.internalZ.object({channelName:import_lazy_zod128.internalZ.string().min(1),content:import_lazy_zod128.internalZ.string().min(1),meta:import_lazy_zod128.internalZ.record(import_lazy_zod128.internalZ.string(),import_lazy_zod128.internalZ.unknown()).optional(),targetSessionId:import_lazy_zod128.internalZ.string().min(1).optional()});outputSchema30=import_lazy_zod128.internalZ.object({sent:import_lazy_zod128.internalZ.boolean(),channelName:import_lazy_zod128.internalZ.string()});stateSchema33=import_lazy_zod128.internalZ.object({channelName:import_lazy_zod128.internalZ.string(),content:import_lazy_zod128.internalZ.string(),meta:import_lazy_zod128.internalZ.record(import_lazy_zod128.internalZ.string(),import_lazy_zod128.internalZ.string()).optional(),targetSessionId:import_lazy_zod128.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_zod128.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_zod129,channelReplyInputSchema;var init_reply_types=__esm({"libs/sdk/src/channel/reply/reply.types.ts"(){"use strict";import_lazy_zod129=require("@frontmcp/lazy-zod");channelReplyInputSchema={channel_name:import_lazy_zod129.internalZ.string().describe("The name of the channel to reply to"),text:import_lazy_zod129.internalZ.string().describe("The reply text to send back through the channel"),meta:import_lazy_zod129.internalZ.record(import_lazy_zod129.internalZ.string(),import_lazy_zod129.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:http3,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=http3?computeReservedPaths(http3.entryPath,http3.routeBase,http3.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(!http3||!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 http3.server.registerRoute("POST",source.path,wrapWithIpFilter(handler,http3.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_utils162,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_utils162=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_utils162.getMachineId)()}:${(0,import_utils162.randomUUID)()}`;this.logger=options.logger.child("EventOutbox");this.random=options.random??Math.random;const{runtime,deployment}=(0,import_utils162.getRuntimeContext)();this.usesTimers=deployment!=="serverless"&&runtime!=="edge"&&runtime!=="browser"}options;ownerId;logger;random;usesTimers;timers=new Map;inFlight=new Map;waitingForSlot=[];activeAttempts=0;sweepTimer;lastSweepAt=0;stopped=false;async enqueue(delivery){const now=Date.now();const record={...delivery,id:`dlv_${(0,import_utils162.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){if(this.activeAttempts>=this.options.settings.concurrency){await new Promise(resolve4=>this.waitingForSlot.push(resolve4))}else{this.activeAttempts+=1}try{await this.attemptOnce(id)}finally{const nextWaiter=this.waitingForSlot.shift();if(nextWaiter)nextWaiter();else this.activeAttempts-=1}}async attemptOnce(id){const stored=await this.read(id);if(!stored||stored.record.leaseOwner!==this.ownerId)return;const startedAt=Date.now();const held=await this.replace(stored,{...stored.record,leaseUntil:this.leaseEnd(startedAt)});if(!held)return;const outcome=await this.outcomeOf(held.record);if(outcome.result==="delivered"||outcome.result==="dropped"){await this.options.storage.delete(RECORD_PREFIX2+id);this.options.metrics.count(outcome.result,held.record.eventName);return}await this.retryOrAbandon(held,outcome)}async outcomeOf(record){try{return await this.options.attempt(record)}catch(error){this.logger.warn(`The attempt of delivery ${record.id} threw`,error);return{result:"error"}}}async retryOrAbandon(held,outcome){const{settings,metrics,storage}=this.options;const{record}=held;const now=Date.now();const isWaiting=outcome.result==="waiting";const attemptsMade=isWaiting?record.attempt:record.attempt+1;const windowIsOver=now-record.firstAttemptAt>=settings.retryWindowMs;if(attemptsMade>=settings.maxAttempts||windowIsOver){await storage.delete(RECORD_PREFIX2+record.id);metrics.count("abandoned",record.eventName);this.logger.warn(`Delivery ${record.id} of event "${record.eventName}" to subscription ${record.subscriptionId} is abandoned after ${attemptsMade} attempt(s): ${reasonOf(outcome)}`);return}const waitMs=isWaiting?SUSPENDED_RECHECK_MS:this.backoffMs(attemptsMade);const nextAttemptAt=now+waitMs;const next={...record,attempt:attemptsMade,nextAttemptAt,leaseUntil:this.leaseEnd(nextAttemptAt)};if(!await this.replace(held,next))return;if(!isWaiting)metrics.count("retried",record.eventName);if(this.usesTimers)this.schedule(record.id,waitMs)}backoffMs(attemptsMade){const{backoffMs,maxBackoffMs}=this.options.settings;const exponential=Math.min(maxBackoffMs,backoffMs*2**(attemptsMade-1));return Math.round(exponential*(.5+this.random()*.5))}leaseEnd(attemptAt){return attemptAt+this.options.settings.timeoutMs+LEASE_MARGIN_MS}async claim(id,now){const stored=await this.read(id);if(!stored)return void 0;if(stored.record.leaseOwner===this.ownerId)return stored.record;if(stored.record.leaseUntil>now)return void 0;const claimed={...stored.record,leaseOwner:this.ownerId,leaseUntil:this.leaseEnd(now)};return(await this.replace(stored,claimed))?.record}async replace(stored,next){const raw=await this.encode(next);const replaced=await this.options.storage.setIfEquals(RECORD_PREFIX2+next.id,stored.raw,raw);return replaced?{raw,record:next}:void 0}async read(id){const raw=await this.options.storage.get(RECORD_PREFIX2+id);if(raw===null)return void 0;const record=await this.decode(raw,id);return record?{raw,record}:void 0}async encode(record){const{secret}=this.options;if(secret===void 0)return JSON.stringify(record);return encryptAndSerialize(record,`events-outbox:${record.id}`,secret)}async decode(raw,id){const{secret}=this.options;try{const record=secret===void 0?JSON.parse(raw):await deserializeAndDecrypt(raw,`events-outbox:${id}`,secret);return record?.id===id?record:void 0}catch{return void 0}}sweepInBackground(){this.sweep().catch(error=>this.logger.warn("The outbox sweep failed",error))}}}});function newEventId(){return`evt_${(0,import_utils163.base64urlEncode)((0,import_utils163.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_utils163,EVENT_ID_RANDOM_BYTES,ScopeEventPublisher;var init_event_publisher=__esm({"libs/sdk/src/event/event-publisher.ts"(){"use strict";import_utils163=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()}});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_utils164,EventRegistry;var init_event_registry=__esm({"libs/sdk/src/event/event.registry.ts"(){"use strict";import_protocol72=require("@frontmcp/protocol");import_utils164=require("@frontmcp/utils");init_common();init_errors();init_regsitry();init_event_instance();init_event_utils();EventRegistry=class extends RegistryAbstract{owner;config;subscriptions;publisher;outbox;metrics;storage;publishEndpoint;buffer;pollLeases;streams;replays;channelDelivery=true;withoutWebhook=new Set;eventsByName=new Map;enabledDeliveryModes=new Set;logger;entryProviders;constructor(providers,list,owner,config,entryProviders){super("EventRegistry",providers,list,false);this.owner=owner;this.config=config;this.entryProviders=entryProviders;this.logger=providers.get(FrontMcpLogger).child("EventRegistry");this.buildGraph();this.ready=this.initialize()}buildMap(list){const tokens=new Set;const defs=new Map;const graph=new Map;for(const item of list){const record=normalizeEvent(item);tokens.add(record.provide);defs.set(record.provide,record);graph.set(record.provide,new Set)}return{tokens,defs,graph}}buildGraph(){}async initialize(){const runtimeContext=(0,import_utils164.getRuntimeContext)();for(const[token,record]of this.defs){const eventName=record.metadata.name;if(!(0,import_utils164.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(name59){return this.eventsByName.get(name59)}hasAny(){return this.eventsByName.size>0}enableDeliveryMode(mode){this.enabledDeliveryModes.add(mode)}withholdWebhookFrom(eventName){this.withoutWebhook.add(eventName)}performs(mode){return this.enabledDeliveryModes.has(mode)}deliveryModesOf(event){const restriction=event.metadata.delivery;return 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))}getCapabilities(){if(!this.servesEvents())return{};return{events:{},extensions:{[import_protocol72.EVENTS_EXTENSION_ID]:{}}}}}}});function eventOutboundTargetOptions(allowLocal){return(0,import_utils165.isEdgeRuntime)()?{allowLocal,allowPlatformDns:true}:{allowLocal}}var import_utils165;var init_event_outbound=__esm({"libs/sdk/src/event/event-outbound.ts"(){"use strict";import_utils165=require("@frontmcp/utils")}});var import_lazy_zod130,import_protocol73,import_utils166,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_zod130=require("@frontmcp/lazy-zod");import_protocol73=require("@frontmcp/protocol");import_utils166=require("@frontmcp/utils");init_common();init_event_outbound();inputSchema32=import_lazy_zod130.internalZ.object({delivery:import_lazy_zod130.internalZ.any()});outputSchema31=import_lazy_zod130.internalZ.discriminatedUnion("result",[import_lazy_zod130.internalZ.object({result:import_lazy_zod130.internalZ.literal("delivered")}),import_lazy_zod130.internalZ.object({result:import_lazy_zod130.internalZ.literal("dropped"),reason:import_lazy_zod130.internalZ.enum(["gone","refused"])}),import_lazy_zod130.internalZ.object({result:import_lazy_zod130.internalZ.literal("failed"),category:import_protocol73.EventDeliveryErrorCategorySchema}),import_lazy_zod130.internalZ.object({result:import_lazy_zod130.internalZ.literal("waiting")})]);stateSchema34=import_lazy_zod130.internalZ.object({target:import_lazy_zod130.internalZ.any(),subscription:import_lazy_zod130.internalZ.any(),headers:import_lazy_zod130.internalZ.record(import_lazy_zod130.internalZ.string(),import_lazy_zod130.internalZ.string()),answer:import_lazy_zod130.internalZ.any(),outcome:import_lazy_zod130.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_utils166.signingKeyOf)(secret)];if(previousSecret!==void 0&&(previousSecretUntil??0)>now){signingKeys.push((0,import_utils166.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_utils166.webhookSignatureHeaders)(message,signingKeys)})}async send(){if(this.state.outcome)return;const{webhook}=this.events.config;const answer=await(0,import_utils166.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_utils166.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 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,name59){const value=claims3[name59];return typeof value==="string"&&value!==""?value:void 0}function eventSubscriberOf(authInfo,contextBuilder){const principalKey=principalKeyOf(authInfo);if(!principalKey)return void 0;const plainAuthInfo=authInfo;const tokenPrincipal=resolvePrincipal(plainAuthInfo);const principal=contextBuilder?resolvePrincipal(plainAuthInfo,contextBuilder):tokenPrincipal;const tenantId=contextBuilder?.build(plainAuthInfo).user.tenantId;const issuer=stringClaim(tokenPrincipal.claims,"iss");return{principalKey,subscriber:{sub:principal.sub||tokenPrincipal.sub,...issuer&&{iss:issuer},...tenantId&&{tenantId},roles:principal.roles,permissions:principal.permissions,scopes:principal.scopes,claims:principal.claims}}}var init_event_subscriber=__esm({"libs/sdk/src/event/event-subscriber.ts"(){"use strict";init_principal_utils();init_question_subject()}});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_auth56.isPublicMode)(authOptions)){throw new EventForbiddenError(codes,eventName,"this server needs a signed-in caller")}return{principalKey:void 0,subscriber:ANONYMOUS_SUBSCRIBER}}async function assertEventAuthorities(scope,event,authInfo,args,codes){const engine=scope.authoritiesEngine;const contextBuilder=scope.authoritiesContextBuilder;const authorities=event.getAuthorities();if(!engine||!contextBuilder||!authorities)return;const result=await engine.evaluate(authorities,contextBuilder.build(authInfo,args));if(!result.granted)throw new EventForbiddenError(codes,event.name,result.deniedBy??"policy denied")}function parsedEventArguments(event,args){try{return event.parseArguments(args??{})}catch(error){throw new InvalidInputError("Invalid subscription arguments",error instanceof import_lazy_zod131.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_utils167.canonicalJson)({principalKey:reader.principalKey??null,mode,name:eventName,arguments:args});return{id:`sub_${(0,import_utils167.sha256Hex)(key).slice(0,32)}`,name:eventName,mode,subscriber:reader.subscriber}}var import_auth56,import_lazy_zod131,import_utils167,ANONYMOUS_SUBSCRIBER;var init_event_gates=__esm({"libs/sdk/src/event/event-gates.ts"(){"use strict";import_auth56=require("@frontmcp/auth");import_lazy_zod131=require("@frontmcp/lazy-zod");import_utils167=require("@frontmcp/utils");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_utils168,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_utils168=require("@frontmcp/utils");POLL_LEASE_MIN_MS=3e5;POLL_LEASE_INTERVALS=5;POLL_LEASE_SWEEP_INTERVAL_MS=6e4;MAX_POLL_LEASES=1e4;EventPollLeases=class{constructor(options){this.options=options;this.logger=options.logger.child("EventPollLeases")}options;leases=new Map;starting=new Map;logger;sweepTimer;lastSweepAt=0;get size(){return this.leases.size}isFull(principalKey){if(this.leases.size>=MAX_POLL_LEASES)return true;let held=0;for(const lease of this.leases.values()){if(lease.principalKey===principalKey)held+=1}return held>=this.options.maxPerPrincipal}has(subscriptionId){return this.leases.has(subscriptionId)||this.starting.has(subscriptionId)}async renew(request2){const{subscription,leaseMs}=request2;const now=Date.now();this.sweepIfDue(now);const lease=this.leases.get(subscription.id);if(lease){lease.expiresAt=now+leaseMs;return}const pending=this.starting.get(subscription.id);if(pending)return pending;const start=this.subscribe(request2,now).finally(()=>this.starting.delete(subscription.id));this.starting.set(subscription.id,start);return start}async subscribe(request2,now){const{subscription,context,leaseMs}=request2;await context.onSubscribe?.(request2.arguments,subscription);this.leases.set(subscription.id,{subscription,arguments:request2.arguments,principalKey:request2.principalKey,expiresAt:now+leaseMs,end:async reason=>{await context.onUnsubscribe?.(request2.arguments,subscription,reason)}})}async sweep(now=Date.now()){this.lastSweepAt=now;for(const[subscriptionId,lease]of this.leases){if(lease.expiresAt>now)continue;this.leases.delete(subscriptionId);await this.end(lease,"expired")}}start(){const{runtime,deployment}=(0,import_utils168.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:name59}=lease.subscription;this.logger.warn(`onUnsubscribe of event "${name59}" failed for poll subscription ${id}`,error)}}}}});function eventChannelMessage(event,occurrence){const{channel:channel2}=event.metadata;const options=channel2===void 0||channel2===true?{}:channel2;const payload=occurrence.data;const content=options.content?options.content(payload):JSON.stringify(payload);const ownMeta=options.meta?options.meta(payload):{};return{content,meta:channelMetaOf({...ownMeta,event:occurrence.name,event_id:occurrence.eventId})}}function channelSessionReader(scope,event,session){if(hasExpiredCaller(session))return void 0;if(!isOfferedOnSurface(event.metadata.availableWhen,mcpRequestSurface(scope)))return void 0;try{return eventReaderOf(scope,session.caller??{},event.name,EVENT_DIALECTS["sep-3415"].errorCodes)}catch(error){if(error instanceof EventForbiddenError)return void 0;throw error}}var init_event_channel=__esm({"libs/sdk/src/event/event-channel.ts"(){"use strict";init_channel_utils();init_availability();init_errors();init_notification_service();init_mcp_surface();init_event_dialect();init_event_gates()}});function accessRevokedError(dialect){return{code:EVENT_DIALECTS[dialect].errorCodes.forbidden,message:"Forbidden",data:{reason:"Access revoked"}}}async function terminateEventSubscription(args){const{subscriptions,outbox,metrics,logger,subscription,error}=args;const removed=await subscriptions?.store.delete(subscription.id);if(!removed||!subscriptions||!outbox)return;await subscriptions.notifyUnsubscribed(removed,"terminated");metrics?.count("terminated",removed.eventName);logger.warn(`Subscription ${removed.id} to event "${removed.eventName}" is terminated: ${error.message} (${String(error.data["reason"])})`);if(!EVENT_DIALECTS[removed.dialect].sendsControlEnvelopes)return;const{url,secret,previousSecret,previousSecretUntil}=removed.delivery;await outbox.enqueue({kind:"terminated",subscriptionId:removed.id,eventName:removed.eventName,body:JSON.stringify({type:"terminated",error}),webhookId:(0,import_utils169.generateWebhookMessageId)("terminated"),target:{url,secret,previousSecret,previousSecretUntil}})}var import_utils169;var init_event_subscription_termination=__esm({"libs/sdk/src/event/subscription/event-subscription-termination.ts"(){"use strict";import_utils169=require("@frontmcp/utils");init_event_dialect()}});function eventWebhookIdOf(subscriptionId,eventId){return`msg_${(0,import_utils170.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_zod132,import_protocol75,import_utils170,EVENT_DELIVERY_MAX_BYTES,audienceValueSchema,inputSchema33,outputSchema32,stateSchema35,plan40,name40,Stage40,encoder9,EventPublishFlow;var init_event_publish_flow=__esm({"libs/sdk/src/event/flows/event-publish.flow.ts"(){"use strict";import_lazy_zod132=require("@frontmcp/lazy-zod");import_protocol75=require("@frontmcp/protocol");import_utils170=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_zod132.internalZ.union([import_lazy_zod132.internalZ.string(),import_lazy_zod132.internalZ.array(import_lazy_zod132.internalZ.string())]);inputSchema33=import_lazy_zod132.internalZ.object({occurrence:import_protocol75.EventOccurrenceSchema,subscriptionId:import_lazy_zod132.internalZ.string().optional(),audience:import_lazy_zod132.internalZ.object({sub:audienceValueSchema.optional(),tenantId:audienceValueSchema.optional(),roles:import_lazy_zod132.internalZ.object({any:import_lazy_zod132.internalZ.array(import_lazy_zod132.internalZ.string()).optional(),all:import_lazy_zod132.internalZ.array(import_lazy_zod132.internalZ.string()).optional()}).optional()}).optional()});outputSchema32=import_lazy_zod132.internalZ.object({eventId:import_lazy_zod132.internalZ.string(),matched:import_lazy_zod132.internalZ.number().int().nonnegative()});stateSchema35=import_lazy_zod132.internalZ.object({event:import_lazy_zod132.internalZ.instanceof(EventEntry),context:import_lazy_zod132.internalZ.any(),subscriptions:import_lazy_zod132.internalZ.array(import_lazy_zod132.internalZ.any()),deliveries:import_lazy_zod132.internalZ.array(import_lazy_zod132.internalZ.any()),buffered:import_lazy_zod132.internalZ.any()});plan40={pre:["validate","bufferOccurrence","pushToStreams"],execute:["loadSubscriptions","dropInactive","filterByAudience","reauthorize","match","transform","enforceBodyLimit","enqueue","bridgeToBus","notifyChannelSessions"],post:["buildResult"]};name40="events:publish";({Stage:Stage40}=FlowHooksOf(name40));encoder9=new TextEncoder;EventPublishFlow=class extends FlowBase{logger=this.scopeLogger.child("EventPublishFlow");get events(){return this.scope.events}async validate(){const eventName=this.input.occurrence.name;const event=this.events.findByName(eventName);if(!event)throw new EventNotRegisteredError(eventName);this.events.metrics?.count("published",eventName);this.state.set({event,context:event.create({}),deliveries:[]})}async bufferOccurrence(){const{occurrence,audience,subscriptionId}=this.input;const modes=this.events.deliveryModesOf(this.state.required.event);if(!modes.includes("poll")&&!modes.includes("push"))return;this.state.set("buffered",this.events.buffer?.append(occurrence,audience,subscriptionId))}async pushToStreams(){const{buffered}=this.state;if(buffered)await this.events.streams?.publish(buffered)}async loadSubscriptions(){const{subscriptions,outbox}=this.events;if(!subscriptions||!outbox){this.state.set("subscriptions",[]);return}subscriptions.sweepIfDue();await outbox.sweepIfDue();const{subscriptionId,occurrence}=this.input;if(subscriptionId===void 0){this.state.set("subscriptions",await subscriptions.store.listByEvent(occurrence.name));return}const targeted=await subscriptions.store.get(subscriptionId);this.state.set("subscriptions",targeted?.eventName===occurrence.name?[targeted]:[])}async dropInactive(){const{suspendedTtlMs}=this.events.config.subscriptions;const now=Date.now();const active=[];for(const subscription of this.state.required.subscriptions){if(subscription.active){active.push(subscription);continue}const suspendedFor=now-(subscription.status.suspendedSince??now);if(subscription.expiresAt===null&&suspendedFor>suspendedTtlMs){const codes=EVENT_DIALECTS[subscription.dialect].errorCodes;await this.terminate(subscription,{code:codes.callbackEndpointError,message:"CallbackEndpointError",data:{reason:subscription.status.lastError??"http_5xx"}})}}this.state.set("subscriptions",active)}async filterByAudience(){const{audience}=this.input;const inAudience=this.state.required.subscriptions.filter(subscription=>isInAudience(audience,subscription.subscriber));this.state.set("subscriptions",inAudience)}async reauthorize(){const{event,context}=this.state.required;if(!hasReauthorization(this.scope,event,context.authorize!==void 0))return;const{subscriptions}=this.events;const{reauthorizeEveryMs}=this.events.config.subscriptions;const now=Date.now();const allowed=[];for(const subscription of this.state.required.subscriptions){if(now-subscription.lastAuthorizedAt<=reauthorizeEveryMs){allowed.push(subscription);continue}const{subscriber,arguments:subscriptionArguments}=subscription;const check=await reauthorizeSubscriber({scope:this.scope,event,subscriber,arguments:subscriptionArguments});if(check.outcome==="granted"){await subscriptions?.store.update(subscription.id,{lastAuthorizedAt:now});allowed.push(subscription);continue}if(check.outcome==="failed"){this.logger.warn(`reauthorize: the access of subscription ${subscription.id} could not be checked`,check.error);continue}await this.terminate(subscription,accessRevokedError(subscription.dialect))}this.state.set("subscriptions",allowed)}async match(){const{context,subscriptions}=this.state.required;const{occurrence}=this.input;const deliveries=[];for(const subscription of subscriptions){try{const matches=await context.match?.(occurrence,subscription.arguments,subscription.subscriber)??true;if(matches)deliveries.push({subscription,occurrence})}catch(error){this.logger.warn(`match: event "${occurrence.name}" failed for subscription ${subscription.id}`,error)}}this.state.set("deliveries",deliveries)}async transform(){const{context,deliveries}=this.state.required;if(!context.transform)return;const shaped=[];for(const delivery of deliveries){const{subscription,occurrence}=delivery;try{const transformed=await context.transform(occurrence,subscription.arguments,subscription.subscriber);shaped.push({subscription,occurrence: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=encoder9.encode(body).byteLength;if(bytes<=EVENT_DELIVERY_MAX_BYTES){fitting.push({...delivery,body});continue}this.events.metrics?.count("dropped",delivery.occurrence.name);this.logger.warn(`enforceBodyLimit: event "${delivery.occurrence.name}" is ${bytes} bytes for subscription ${delivery.subscription.id}, over the ${EVENT_DELIVERY_MAX_BYTES} byte limit; it is not delivered`)}this.state.set("deliveries",fitting)}async enqueue(){const{outbox}=this.events;const{deliveries}=this.state.required;if(!outbox)return;const queued=deliveries.map(({subscription,occurrence,body})=>{const usesEventId=EVENT_DIALECTS[subscription.dialect].webhookId==="eventId";return outbox.enqueue({kind:"event",subscriptionId:subscription.id,eventName:occurrence.name,body,webhookId:usesEventId?occurrence.eventId:eventWebhookIdOf(subscription.id,occurrence.eventId)})});await Promise.all(queued);this.events.metrics?.count("matched",this.input.occurrence.name,deliveries.length)}async bridgeToBus(){if(!this.events.config.bridge)return;const{occurrence,audience,subscriptionId}=this.input;const forSomeOwners=audience!==void 0||subscriptionId!==void 0;this.scope.channelEventBus?.emit(occurrence.name,occurrence,{forSomeOwners})}async notifyChannelSessions(){const{event}=this.state.required;const{occurrence,subscriptionId}=this.input;if(subscriptionId!==void 0||!this.events.sendsToChannelSessions(event))return;let message;try{message=eventChannelMessage(event,occurrence)}catch(error){this.logger.warn(`notifyChannelSessions: the channel option of event "${occurrence.name}" failed`,error);return}let notified=0;for(const session of this.scope.notifications.getChannelCapableSessions()){const wasSent=await this.notifyChannelSession(session,message);if(wasSent)notified+=1}this.events.metrics?.count("notified",occurrence.name,notified);this.logger.verbose(`notifyChannelSessions: event "${occurrence.name}" was sent to ${notified} session(s)`)}async buildResult(){this.respond({eventId:this.input.occurrence.eventId,matched:this.state.required.deliveries.length})}async notifyChannelSession(session,message){const{event,context}=this.state.required;const{occurrence,audience}=this.input;try{const reader=channelSessionReader(this.scope,event,session);if(!reader||!isInAudience(audience,reader.subscriber))return false;if(hasReauthorization(this.scope,event,context.authorize!==void 0)){const{subscriber}=reader;const authInfo=session.caller;const access=await reauthorizeSubscriber({scope:this.scope,event,subscriber,arguments:{},authInfo});if(access.outcome==="failed")throw access.error;if(access.outcome==="refused")return false}const isThisSession=registered=>registered.sessionId===session.sessionId;this.scope.notifications.sendCustomNotification(CHANNEL_NOTIFICATION_METHOD,message,isThisSession);return true}catch(error){const sessionLabel=session.sessionId.slice(0,20);this.logger.warn(`notifyChannelSessions: event "${occurrence.name}" was not sent to session ${sessionLabel}...`,error);return false}}async terminate(subscription,error){const{subscriptions,outbox,metrics}=this.events;await terminateEventSubscription({subscriptions,outbox,metrics,logger:this.logger,subscription,error})}};__decorateClass([Stage40("validate")],EventPublishFlow.prototype,"validate",1);__decorateClass([Stage40("bufferOccurrence")],EventPublishFlow.prototype,"bufferOccurrence",1);__decorateClass([Stage40("pushToStreams")],EventPublishFlow.prototype,"pushToStreams",1);__decorateClass([Stage40("loadSubscriptions")],EventPublishFlow.prototype,"loadSubscriptions",1);__decorateClass([Stage40("dropInactive")],EventPublishFlow.prototype,"dropInactive",1);__decorateClass([Stage40("filterByAudience")],EventPublishFlow.prototype,"filterByAudience",1);__decorateClass([Stage40("reauthorize")],EventPublishFlow.prototype,"reauthorize",1);__decorateClass([Stage40("match")],EventPublishFlow.prototype,"match",1);__decorateClass([Stage40("transform")],EventPublishFlow.prototype,"transform",1);__decorateClass([Stage40("enforceBodyLimit")],EventPublishFlow.prototype,"enforceBodyLimit",1);__decorateClass([Stage40("enqueue")],EventPublishFlow.prototype,"enqueue",1);__decorateClass([Stage40("bridgeToBus")],EventPublishFlow.prototype,"bridgeToBus",1);__decorateClass([Stage40("notifyChannelSessions")],EventPublishFlow.prototype,"notifyChannelSessions",1);__decorateClass([Stage40("buildResult")],EventPublishFlow.prototype,"buildResult",1);EventPublishFlow=__decorateClass([FrontMcpFlow({name:name40,plan:plan40,inputSchema:inputSchema33,outputSchema:outputSchema32,access:"public"})],EventPublishFlow)}});var import_lazy_zod133,import_protocol76,inputSchema34,outputSchema33,stateSchema36,plan41,name41,Stage41,EventPollFlow;var init_event_poll_flow=__esm({"libs/sdk/src/event/flows/event-poll.flow.ts"(){"use strict";import_lazy_zod133=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();inputSchema34=import_lazy_zod133.internalZ.object({request:import_protocol76.PollEventsRequestSchema,ctx:import_lazy_zod133.internalZ.unknown()});outputSchema33=import_protocol76.PollEventsResultSchema;stateSchema36=import_lazy_zod133.internalZ.object({authInfo:import_lazy_zod133.internalZ.any(),dialect:import_lazy_zod133.internalZ.enum(["sep-3415","sketch"]),event:import_lazy_zod133.internalZ.instanceof(EventEntry),reader:import_lazy_zod133.internalZ.any(),arguments:import_lazy_zod133.internalZ.record(import_lazy_zod133.internalZ.string(),import_lazy_zod133.internalZ.unknown()),context:import_lazy_zod133.internalZ.any(),subscription:import_lazy_zod133.internalZ.any(),result:import_lazy_zod133.internalZ.any()});plan41={pre:["parseInput","resolveDialect","findEvent","resolveReader","checkEntryAuthorities","validateArguments","authorize"],execute:["renewLease","readEvents"],post:["buildResult"],finalize:["finalize"]};name41="events:poll";({Stage:Stage41}=FlowHooksOf(name41));EventPollFlow=class extends FlowBase{logger=this.scopeLogger.child("EventPollFlow");get events(){return this.scope.events}get codes(){return EVENT_DIALECTS[this.state.required.dialect].errorCodes}async parseInput(){const authInfo=this.input.ctx?.authInfo??{};this.state.set("authInfo",authInfo)}async resolveDialect(){const platform=callerPlatformOf(this.scope,this.state.required.authInfo,this.tryGetContext()?.platformType);this.state.set("dialect",resolveEventDialect(this.events.config.compat,platform))}async findEvent(){const eventName=this.input.request.params.name;this.state.set("event",offeredEventOf(this.events,eventName,"poll",this.input.ctx,this.codes))}async resolveReader(){const{authInfo,event}=this.state.required;this.state.set("reader",eventReaderOf(this.scope,authInfo,event.name,this.codes))}async checkEntryAuthorities(){const{event,authInfo}=this.state.required;const sentArguments=this.input.request.params.arguments??{};await assertEventAuthorities(this.scope,event,authInfo,sentArguments,this.codes)}async validateArguments(){const{event,reader}=this.state.required;const parsedArguments=parsedEventArguments(event,this.input.request.params.arguments);this.state.set({arguments:parsedArguments,subscription:readerSubscriptionOf(reader,"poll",event.name,parsedArguments)})}async authorize(){const{event,authInfo,reader}=this.state.required;const context=event.create(authInfo);await assertEventAuthorizes(context,event.name,this.state.required.arguments,reader.subscriber,this.codes);this.state.set("context",context)}async renewLease(){await this.renewLeaseFor(this.events.config.poll.nextPollMs)}async readEvents(){const{context}=this.state.required;const result=context.check?await this.readFromCheck():await this.readFromBuffer();this.state.set("result",result);if(result.nextPollMs!==void 0&&result.nextPollMs>this.events.config.poll.nextPollMs){await this.renewLeaseFor(result.nextPollMs)}}async buildResult(){this.respond(this.state.required.result)}async finalize(){this.logger.verbose("finalize")}get limit(){const serverLimit=this.events.config.poll.maxEvents;return Math.min(this.input.request.params.maxEvents??serverLimit,serverLimit)}replayFloor(now){const{cursor,maxAgeMs}=this.input.request.params;const hasCursor=cursor!==void 0&&cursor!==null;return hasCursor&&maxAgeMs!==void 0?now-maxAgeMs:void 0}async renewLeaseFor(nextPollMs){const leases=this.events.pollLeases;const{context,subscription,reader}=this.state.required;if(!context.onSubscribe&&!context.onUnsubscribe)return;if(!leases.has(subscription.id)&&leases.isFull(reader.principalKey)){const{maxPerPrincipal}=this.events.config.subscriptions;throw new EventResourceExhaustedError(this.codes,"pollLeases",maxPerPrincipal)}await leases.renew({subscription,arguments:this.state.required.arguments,principalKey:reader.principalKey,leaseMs:pollLeaseMs(nextPollMs),context})}async readFromCheck(){const{context,event}=this.state.required;const{cursor=null,maxAgeMs}=this.input.request.params;const now=Date.now();const floor=this.replayFloor(now);const limits={maxEvents:this.limit,...floor!==void 0&&{maxAgeMs}};const check=context.check;const checked=await check.call(context,this.state.required.arguments,cursor,limits);if(checked.events.length>this.limit){throw new InvalidEventPublishError(event.name,`check() returned ${checked.events.length} events, more than limits.maxEvents (${this.limit})`)}const events=[];let skippedOldEvents=false;for(const item of checked.events){const timestamp=item.timestamp??new Date(now).toISOString();if(floor!==void 0&&Date.parse(timestamp)<floor){skippedOldEvents=true;continue}events.push({eventId:item.eventId??newEventId(),name:event.name,timestamp,data:this.checkedPayload(item.data)})}return{events,cursor:checked.cursor,truncated:checked.truncated===true||skippedOldEvents,hasMore:checked.hasMore===true,nextPollMs:checked.nextPollMs??this.events.config.poll.nextPollMs}}checkedPayload(data){const{event}=this.state.required;try{return event.parsePayload(data)}catch(error){const problem2=error instanceof Error?error.message:String(error);throw new InvalidEventPublishError(event.name,`check() returned data that does not match payloadSchema: ${problem2}`)}}async readFromBuffer(){const buffer=this.events.buffer;const{cursor}=this.input.request.params;const nextPollMs=this.events.config.poll.nextPollMs;if(cursor===void 0||cursor===null){return{events:[],cursor:buffer.currentCursor(),truncated:false,hasMore:false,nextPollMs}}const read=buffer.read(this.state.required.event.name,cursor);const endCursor=buffer.currentCursor();const floor=this.replayFloor(Date.now());const events=[];let truncated=read.truncated;let lastExamined;for(const buffered of read.events){if(floor!==void 0&&buffered.publishedAt<floor){truncated=true;lastExamined=buffered;continue}const occurrence=await this.occurrenceFor(buffered);if(occurrence&&events.length===this.limit){const resumeCursor=lastExamined?buffer.cursorAt(lastExamined.sequence):cursor;return{events,cursor:resumeCursor,truncated,hasMore:true,nextPollMs}}if(occurrence)events.push(occurrence);lastExamined=buffered}return{events,cursor:endCursor,truncated,hasMore:false,nextPollMs}}async occurrenceFor(buffered){const{context,reader,subscription}=this.state.required;const{occurrence}=buffered;if(buffered.subscriptionId!==void 0&&buffered.subscriptionId!==subscription.id)return void 0;if(!isInAudience(buffered.audience,reader.subscriber))return void 0;const subscriptionArguments=this.state.required.arguments;try{const matches=await context.match?.(occurrence,subscriptionArguments,reader.subscriber)??true;if(!matches)return void 0;if(!context.transform)return occurrence;const transformed=await context.transform(occurrence,subscriptionArguments,reader.subscriber);return 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([Stage41("parseInput")],EventPollFlow.prototype,"parseInput",1);__decorateClass([Stage41("resolveDialect")],EventPollFlow.prototype,"resolveDialect",1);__decorateClass([Stage41("findEvent")],EventPollFlow.prototype,"findEvent",1);__decorateClass([Stage41("resolveReader")],EventPollFlow.prototype,"resolveReader",1);__decorateClass([Stage41("checkEntryAuthorities")],EventPollFlow.prototype,"checkEntryAuthorities",1);__decorateClass([Stage41("validateArguments")],EventPollFlow.prototype,"validateArguments",1);__decorateClass([Stage41("authorize")],EventPollFlow.prototype,"authorize",1);__decorateClass([Stage41("renewLease")],EventPollFlow.prototype,"renewLease",1);__decorateClass([Stage41("readEvents")],EventPollFlow.prototype,"readEvents",1);__decorateClass([Stage41("buildResult")],EventPollFlow.prototype,"buildResult",1);__decorateClass([Stage41("finalize")],EventPollFlow.prototype,"finalize",1);EventPollFlow=__decorateClass([FrontMcpFlow({name:name41,plan:plan41,inputSchema:inputSchema34,outputSchema:outputSchema33,access:"authorized"})],EventPollFlow)}});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(resolve4=>this.releaseDelivery=resolve4):Promise.resolve();if(options.signal?.aborted)this.close();else options.signal?.addEventListener("abort",()=>this.close(),{once:true})}options;queue=[];closeListeners=[];wake;closed=false;cursor;lastAuthorizedAt=Date.now();accessUnchecked=false;withheld=false;heartbeatTimer;checkTimer;delivering;releaseDelivery=()=>void 0;lastSequence=0;get subscription(){return this.options.subscription}get eventName(){return this.options.event.name}get principalKey(){return this.options.reader.principalKey}get isClosed(){return this.closed}async open(){const{context,heartbeatMs}=this.options;if(context.check){await this.openOnCheck()}else{await this.openOnBuffer()}this.releaseDelivery();if(this.closed)return;this.heartbeatTimer=setInterval(()=>void this.beat(),heartbeatMs);this.heartbeatTimer.unref?.()}offer(buffered){this.delivering=this.delivering.then(()=>this.deliver(buffered)).catch(error=>this.options.logger.warn(`An event was not delivered on stream ${this.subscription.id}`,error));return this.delivering}terminate(error){if(this.closed)return;this.push(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(resolve4=>this.wake=resolve4);this.wake=void 0}}async openOnBuffer(){const{buffer,cursor,maxAgeMs}=this.options;if(!buffer){this.pushActive(false);return}if(cursor===void 0||cursor===null){this.cursor=buffer.currentCursor();this.lastSequence=buffer.currentSequence();this.pushActive(false);return}const read=buffer.read(this.eventName,cursor);const endCursor=buffer.currentCursor();const endSequence=buffer.currentSequence();const floor=maxAgeMs===void 0?void 0:Date.now()-maxAgeMs;const replayed=read.events.filter(buffered=>floor===void 0||buffered.publishedAt>=floor);this.cursor=read.events.length===0?endCursor:cursor;this.pushActive(read.truncated||replayed.length<read.events.length);for(const buffered of replayed)await this.deliver(buffered);this.cursor=endCursor;this.lastSequence=endSequence}async deliver(buffered){if(this.closed||buffered.sequence<=this.lastSequence)return;if(this.accessUnchecked){this.withheld=true;return}this.lastSequence=buffered.sequence;const occurrence=await this.occurrenceFor(buffered);if(!occurrence)return;const{buffer}=this.options;if(buffer)this.cursor=buffer.cursorAt(buffered.sequence);this.pushEvent(occurrence)}async openOnCheck(){const checked=await this.check();this.pushActive(checked?.truncated===true);if(checked)this.pushChecked(checked);this.scheduleCheck(checked?.nextPollMs)}async check(){const{context,checkMaxEvents,maxAgeMs}=this.options;const check=context.check;const limits={maxEvents:checkMaxEvents,...this.cursor!==null&&maxAgeMs!==void 0&&{maxAgeMs}};try{const checked=await check.call(context,this.options.arguments,this.cursor,limits);this.cursor=checked.cursor;return checked}catch(error){this.options.logger.warn(`check() of event "${this.eventName}" failed for stream ${this.subscription.id}`,error);this.push(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_zod134,import_protocol78,inputSchema35,outputSchema34,stateSchema37,plan42,name42,Stage42,EventStreamFlow;var init_event_stream_flow=__esm({"libs/sdk/src/event/flows/event-stream.flow.ts"(){"use strict";import_lazy_zod134=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();inputSchema35=import_lazy_zod134.internalZ.object({request:import_protocol78.StreamEventsRequestSchema,ctx:import_lazy_zod134.internalZ.unknown(),requestId:import_lazy_zod134.internalZ.union([import_lazy_zod134.internalZ.string(),import_lazy_zod134.internalZ.number()]),signal:import_lazy_zod134.internalZ.any().optional()});outputSchema34=import_lazy_zod134.internalZ.object({stream:import_lazy_zod134.internalZ.instanceof(EventStream)});stateSchema37=import_lazy_zod134.internalZ.object({authInfo:import_lazy_zod134.internalZ.any(),dialect:import_lazy_zod134.internalZ.enum(["sep-3415","sketch"]),event:import_lazy_zod134.internalZ.instanceof(EventEntry),reader:import_lazy_zod134.internalZ.any(),arguments:import_lazy_zod134.internalZ.record(import_lazy_zod134.internalZ.string(),import_lazy_zod134.internalZ.unknown()),context:import_lazy_zod134.internalZ.any(),subscription:import_lazy_zod134.internalZ.any(),stream:import_lazy_zod134.internalZ.instanceof(EventStream)});plan42={pre:["parseInput","resolveDialect","findEvent","resolveReader","checkEntryAuthorities","validateArguments","authorize"],execute:["openStream"],post:["buildResult"],finalize:["finalize"]};name42="events:stream";({Stage:Stage42}=FlowHooksOf(name42));EventStreamFlow=class extends FlowBase{logger=this.scopeLogger.child("EventStreamFlow");get events(){return this.scope.events}get codes(){return EVENT_DIALECTS[this.state.required.dialect].errorCodes}async parseInput(){const authInfo=this.input.ctx?.authInfo??{};this.state.set("authInfo",authInfo)}async resolveDialect(){const platform=callerPlatformOf(this.scope,this.state.required.authInfo,this.tryGetContext()?.platformType);this.state.set("dialect",resolveEventDialect(this.events.config.compat,platform))}async findEvent(){const eventName=this.input.request.params.name;this.state.set("event",offeredEventOf(this.events,eventName,"push",this.input.ctx,this.codes))}async resolveReader(){const{authInfo,event}=this.state.required;this.state.set("reader",eventReaderOf(this.scope,authInfo,event.name,this.codes))}async checkEntryAuthorities(){const{event,authInfo}=this.state.required;const sentArguments=this.input.request.params.arguments??{};await assertEventAuthorities(this.scope,event,authInfo,sentArguments,this.codes)}async validateArguments(){const{event,reader}=this.state.required;const parsedArguments=parsedEventArguments(event,this.input.request.params.arguments);this.state.set({arguments:parsedArguments,subscription:readerSubscriptionOf(reader,"push",event.name,parsedArguments)})}async authorize(){const{event,authInfo,reader}=this.state.required;const context=event.create(authInfo);await assertEventAuthorizes(context,event.name,this.state.required.arguments,reader.subscriber,this.codes);this.state.set("context",context)}async openStream(){const streams=this.events.streams;const{event,context,reader,subscription,authInfo}=this.state.required;const{config}=this.events;const subscriptionArguments=this.state.required.arguments;const codes=this.codes;const stream=new EventStream({requestId:this.input.requestId,event,context,reader,subscription,arguments:subscriptionArguments,cursor:this.input.request.params.cursor,maxAgeMs:this.input.request.params.maxAgeMs,buffer:context.check?void 0:this.events.buffer,heartbeatMs:config.push.heartbeatMs,checkIntervalMs:config.poll.nextPollMs,checkMaxEvents:config.poll.maxEvents,reauthorizeEveryMs:config.subscriptions.reauthorizeEveryMs,reauthorize:()=>reauthorizeSubscriber({scope:this.scope,event,subscriber:reader.subscriber,arguments:subscriptionArguments,authInfo}),accessRevoked:{code:codes.forbidden,message:"Forbidden",data:{reason:"Access revoked"}},signal:this.input.signal,logger:this.logger});if(!streams.reserve(stream)){stream.close();throw new EventResourceExhaustedError(this.codes,"streams",config.subscriptions.maxPerPrincipal)}try{await context.onSubscribe?.(subscriptionArguments,subscription)}catch(error){stream.close();throw error}stream.onClose(()=>{const warn=error=>this.logger.warn(`onUnsubscribe of event "${event.name}" failed for stream ${subscription.id}`,error);try{Promise.resolve(context.onUnsubscribe?.(subscriptionArguments,subscription,"closed")).catch(warn)}catch(error){warn(error)}});streams.add(stream);try{await stream.open()}catch(error){stream.close();throw error}this.state.set("stream",stream);this.logger.verbose(`openStream: stream ${subscription.id} opened for event "${event.name}"`)}async buildResult(){this.respond({stream:this.state.required.stream})}async finalize(){this.logger.verbose("finalize")}};__decorateClass([Stage42("parseInput")],EventStreamFlow.prototype,"parseInput",1);__decorateClass([Stage42("resolveDialect")],EventStreamFlow.prototype,"resolveDialect",1);__decorateClass([Stage42("findEvent")],EventStreamFlow.prototype,"findEvent",1);__decorateClass([Stage42("resolveReader")],EventStreamFlow.prototype,"resolveReader",1);__decorateClass([Stage42("checkEntryAuthorities")],EventStreamFlow.prototype,"checkEntryAuthorities",1);__decorateClass([Stage42("validateArguments")],EventStreamFlow.prototype,"validateArguments",1);__decorateClass([Stage42("authorize")],EventStreamFlow.prototype,"authorize",1);__decorateClass([Stage42("openStream")],EventStreamFlow.prototype,"openStream",1);__decorateClass([Stage42("buildResult")],EventStreamFlow.prototype,"buildResult",1);__decorateClass([Stage42("finalize")],EventStreamFlow.prototype,"finalize",1);EventStreamFlow=__decorateClass([FrontMcpFlow({name:name42,plan:plan42,inputSchema:inputSchema35,outputSchema:outputSchema34,access:"authorized"})],EventStreamFlow)}});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_utils171,SUBSCRIPTION_SWEEP_INTERVAL_MS,EventSubscriptions;var init_event_subscriptions=__esm({"libs/sdk/src/event/subscription/event-subscriptions.ts"(){"use strict";import_utils171=require("@frontmcp/utils");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_utils171.canonicalJson)({principalKey,url,name:eventName,arguments:args});return{id:`sub_${(0,import_utils171.sha256Hex)(canonicalKey).slice(0,32)}`,argumentsKey:(0,import_utils171.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 expire(id,now=Date.now()){const removed=await this.store.deleteExpired(id,now);if(removed)await this.notifyUnsubscribed(removed,"expired")}async sweep(now=Date.now()){this.lastSweepAt=now;const expired=await this.store.listExpired(now);for(const record of expired){await this.expire(record.id,now)}}sweepIfDue(now=Date.now()){if(now-this.lastSweepAt<SUBSCRIPTION_SWEEP_INTERVAL_MS)return;this.sweepInBackground(now)}start(){const{runtime,deployment}=(0,import_utils171.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))}}}});function reactivatedStatus(status={}){const{failures:_failures,suspendedSince:_suspendedSince,...kept}=status;return kept}var import_lazy_zod135,import_protocol79,import_utils172,inputSchema36,outputSchema35,stateSchema38,plan43,name43,Stage43,URL_PROBLEMS,EventSubscribeFlow;var init_event_subscribe_flow=__esm({"libs/sdk/src/event/flows/event-subscribe.flow.ts"(){"use strict";import_lazy_zod135=require("@frontmcp/lazy-zod");import_protocol79=require("@frontmcp/protocol");import_utils172=require("@frontmcp/utils");init_common();init_availability();init_errors();init_event_dialect();init_event_subscriber();init_event_subscriptions();inputSchema36=import_lazy_zod135.internalZ.object({request:import_protocol79.SubscribeEventRequestSchema,ctx:import_lazy_zod135.internalZ.unknown()});outputSchema35=import_protocol79.SubscribeEventResultSchema;stateSchema38=import_lazy_zod135.internalZ.object({authInfo:import_lazy_zod135.internalZ.any(),dialect:import_lazy_zod135.internalZ.enum(["sep-3415","sketch"]),event:import_lazy_zod135.internalZ.instanceof(EventEntry),owner:import_lazy_zod135.internalZ.any(),arguments:import_lazy_zod135.internalZ.record(import_lazy_zod135.internalZ.string(),import_lazy_zod135.internalZ.unknown()),subscriptionId:import_lazy_zod135.internalZ.string(),argumentsKey:import_lazy_zod135.internalZ.string(),existing:import_lazy_zod135.internalZ.any(),verifiedAt:import_lazy_zod135.internalZ.number(),expiresAt:import_lazy_zod135.internalZ.number().nullable(),record:import_lazy_zod135.internalZ.any(),truncated:import_lazy_zod135.internalZ.boolean().optional()});plan43={pre:["parseInput","resolveDialect","findEvent","checkAvailability","requireWebhookMode","requireSubscriber","checkEntryAuthorities","validateArguments","authorize","validateDelivery"],execute:["findSubscription","enforceLimits","verifyCallback","grantTtl","upsertSubscription","notifySubscribed","startReplay"],post:["buildResult"],finalize:["finalize"]};name43="events:subscribe";({Stage:Stage43}=FlowHooksOf(name43));URL_PROBLEMS={malformed:"it is not a URL",scheme:"it must use https",credentials:"it must not carry a user name or a password",host:"its host is local, private or a metadata service"};EventSubscribeFlow=class extends FlowBase{logger=this.scopeLogger.child("EventSubscribeFlow");get events(){return this.scope.events}get subscriptions(){return this.events.subscriptions}get codes(){return EVENT_DIALECTS[this.state.required.dialect].errorCodes}async parseInput(){const authInfo=this.input.ctx?.authInfo??{};this.state.set("authInfo",authInfo)}async resolveDialect(){const platform=callerPlatformOf(this.scope,this.state.required.authInfo,this.tryGetContext()?.platformType);this.state.set("dialect",resolveEventDialect(this.events.config.compat,platform))}async findEvent(){const eventName=this.input.request.params.name;const event=this.events.findByName(eventName);if(!event)throw new EventNotFoundError(this.codes,"event",eventName);this.state.set("event",event)}async checkAvailability(){const{event}=this.state.required;if(!isOfferedOnSurface(event.metadata.availableWhen,callSurfaceOf(this.input.ctx))){throw new EventNotFoundError(this.codes,"event",event.name)}}async requireWebhookMode(){const requestedMode=this.input.request.params.delivery.mode??"webhook";const subscribableModes=this.events.deliveryModesOf(this.state.required.event).filter(mode=>mode==="webhook");if(requestedMode!=="webhook"||subscribableModes.length===0){throw new EventUnsupportedError(this.codes,"deliveryMode",requestedMode,subscribableModes)}}async requireSubscriber(){const{authInfo,event}=this.state.required;const owner=eventSubscriberOf(authInfo,this.scope.authoritiesContextBuilder);if(!owner)throw new EventForbiddenError(this.codes,event.name,"a webhook subscription needs a signed-in caller");this.state.set("owner",owner)}async checkEntryAuthorities(){const engine=this.scope.authoritiesEngine;const contextBuilder=this.scope.authoritiesContextBuilder;const{event,authInfo}=this.state.required;const authorities=event.getAuthorities();if(!engine||!contextBuilder||!authorities)return;const evaluationContext=contextBuilder.build(authInfo,this.input.request.params.arguments??{});const result=await engine.evaluate(authorities,evaluationContext);if(!result.granted){throw new EventForbiddenError(this.codes,event.name,result.deniedBy??"policy denied")}}async validateArguments(){try{this.state.set("arguments",this.state.required.event.parseArguments(this.input.request.params.arguments??{}))}catch(error){throw new InvalidInputError("Invalid subscription arguments",error instanceof import_lazy_zod135.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_utils172.validateOutboundUrl)(url,{allowLocal});if(!urlCheck.ok)throw new InvalidInputError(`Invalid delivery.url: ${URL_PROBLEMS[urlCheck.problem]}`);if(!(0,import_utils172.isStandardWebhookSecret)(secret)){throw new InvalidInputError('Invalid delivery.secret: expected "whsec_" followed by base64 that decodes to 24 to 64 bytes')}}async findSubscription(){const{owner,event}=this.state.required;const{url}=this.input.request.params.delivery;const identity=this.subscriptions.identityOf(owner.principalKey,url,event.name,this.state.required.arguments);this.subscriptions.sweepIfDue();const existing=await this.subscriptions.store.get(identity.id);if(!existing)await this.subscriptions.expire(identity.id);this.state.set({subscriptionId:identity.id,argumentsKey:identity.argumentsKey,existing})}async enforceLimits(){if(this.state.existing)return;const{maxPerPrincipal}=this.subscriptions.settings;const held=await this.subscriptions.store.countByPrincipal(this.state.required.owner.principalKey);if(held>=maxPerPrincipal)throw new EventResourceExhaustedError(this.codes,"subscriptions",maxPerPrincipal)}async verifyCallback(){const{url,secret}=this.input.request.params.delivery;const{owner,subscriptionId}=this.state.required;const verification=await this.subscriptions.verifier.verify({principalKey:owner.principalKey,url,secret,subscriptionId,verifiedAt:this.state.existing?.verifiedAt});if(verification.outcome==="limited"){throw new EventResourceExhaustedError(this.codes,"verifications",verification.max)}if(verification.outcome==="failed"){this.logger.verbose(`verifyCallback: subscription ${subscriptionId} refused (${verification.reason})`);throw new EventCallbackEndpointError(this.codes,verification.reason)}this.state.set("verifiedAt",verification.verifiedAt)}async grantTtl(){const requestedTtlMs=this.input.request.params.ttlMs;this.state.set("expiresAt",this.subscriptions.grantExpiry(this.state.required.event,requestedTtlMs,Date.now()))}async upsertSubscription(){const{url,secret}=this.input.request.params.delivery;const{owner,event,dialect,subscriptionId,argumentsKey,verifiedAt}=this.state.required;const expiresAt=this.state.get("expiresAt")??null;const existing=this.state.existing;const replay=existing?await this.currentReplayOf(subscriptionId):void 0;const now=Date.now();const record={id:subscriptionId,principalKey:owner.principalKey,subscriber:owner.subscriber,eventName:event.name,arguments:this.state.required.arguments,argumentsKey,delivery:this.subscriptions.rotatedDelivery(existing?.delivery,url,secret,now),dialect,createdAt:existing?.createdAt??now,updatedAt:now,expiresAt,verifiedAt,lastAuthorizedAt:now,active:true,status:reactivatedStatus(existing?.status),...replay&&{replay}};await this.subscriptions.store.upsert(record);this.state.set("record",record)}async notifySubscribed(){if(this.state.existing)return;const{event,record,authInfo}=this.state.required;try{await this.subscriptions.notifySubscribed(event,record,authInfo)}catch(error){await this.subscriptions.store.delete(record.id);throw error}this.logger.verbose(`notifySubscribed: subscription ${record.id} created for event "${event.name}"`)}async startReplay(){const{replays}=this.events;const{event,record}=this.state.required;if(!replays?.isReplayable(event))return;const{cursor=null,maxAgeMs}=this.input.request.params;const step=record.replay?await replays.refresh(record,record.replay):await replays.begin(event,record,cursor,maxAgeMs);this.state.set({record:{...record,replay:step.replay},truncated:step.truncated})}async currentReplayOf(subscriptionId){const stored=await this.subscriptions.store.get(subscriptionId);return stored?.replay}async buildResult(){const{record}=this.state.required;this.respond({id:record.id,refreshBefore:record.expiresAt===null?null:new Date(record.expiresAt).toISOString(),cursor:record.replay?.watermark??null,truncated:this.state.truncated??false,...this.state.existing&&{deliveryStatus:deliveryStatusOf(record)}})}async finalize(){this.logger.verbose("finalize")}};__decorateClass([Stage43("parseInput")],EventSubscribeFlow.prototype,"parseInput",1);__decorateClass([Stage43("resolveDialect")],EventSubscribeFlow.prototype,"resolveDialect",1);__decorateClass([Stage43("findEvent")],EventSubscribeFlow.prototype,"findEvent",1);__decorateClass([Stage43("checkAvailability")],EventSubscribeFlow.prototype,"checkAvailability",1);__decorateClass([Stage43("requireWebhookMode")],EventSubscribeFlow.prototype,"requireWebhookMode",1);__decorateClass([Stage43("requireSubscriber")],EventSubscribeFlow.prototype,"requireSubscriber",1);__decorateClass([Stage43("checkEntryAuthorities")],EventSubscribeFlow.prototype,"checkEntryAuthorities",1);__decorateClass([Stage43("validateArguments")],EventSubscribeFlow.prototype,"validateArguments",1);__decorateClass([Stage43("authorize")],EventSubscribeFlow.prototype,"authorize",1);__decorateClass([Stage43("validateDelivery")],EventSubscribeFlow.prototype,"validateDelivery",1);__decorateClass([Stage43("findSubscription")],EventSubscribeFlow.prototype,"findSubscription",1);__decorateClass([Stage43("enforceLimits")],EventSubscribeFlow.prototype,"enforceLimits",1);__decorateClass([Stage43("verifyCallback")],EventSubscribeFlow.prototype,"verifyCallback",1);__decorateClass([Stage43("grantTtl")],EventSubscribeFlow.prototype,"grantTtl",1);__decorateClass([Stage43("upsertSubscription")],EventSubscribeFlow.prototype,"upsertSubscription",1);__decorateClass([Stage43("notifySubscribed")],EventSubscribeFlow.prototype,"notifySubscribed",1);__decorateClass([Stage43("startReplay")],EventSubscribeFlow.prototype,"startReplay",1);__decorateClass([Stage43("buildResult")],EventSubscribeFlow.prototype,"buildResult",1);__decorateClass([Stage43("finalize")],EventSubscribeFlow.prototype,"finalize",1);EventSubscribeFlow=__decorateClass([FrontMcpFlow({name:name43,plan:plan43,inputSchema:inputSchema36,outputSchema:outputSchema35,access:"authorized"})],EventSubscribeFlow)}});var import_lazy_zod136,import_protocol80,inputSchema37,outputSchema36,stateSchema39,plan44,name44,Stage44,EventUnsubscribeFlow;var init_event_unsubscribe_flow=__esm({"libs/sdk/src/event/flows/event-unsubscribe.flow.ts"(){"use strict";import_lazy_zod136=require("@frontmcp/lazy-zod");import_protocol80=require("@frontmcp/protocol");init_common();init_errors();init_event_dialect();init_event_subscriber();inputSchema37=import_lazy_zod136.internalZ.object({request:import_protocol80.UnsubscribeEventRequestSchema,ctx:import_lazy_zod136.internalZ.unknown()});outputSchema36=import_protocol80.UnsubscribeEventResultSchema;stateSchema39=import_lazy_zod136.internalZ.object({authInfo:import_lazy_zod136.internalZ.any(),dialect:import_lazy_zod136.internalZ.enum(["sep-3415","sketch"]),owner:import_lazy_zod136.internalZ.any()});plan44={pre:["parseInput","resolveDialect","requireSubscriber"],execute:["removeSubscription"],post:["buildResult"],finalize:["finalize"]};name44="events:unsubscribe";({Stage:Stage44}=FlowHooksOf(name44));EventUnsubscribeFlow=class extends FlowBase{logger=this.scopeLogger.child("EventUnsubscribeFlow");get events(){return this.scope.events}get subscriptions(){return this.events.subscriptions}async parseInput(){const authInfo=this.input.ctx?.authInfo??{};this.state.set("authInfo",authInfo)}async resolveDialect(){const platform=callerPlatformOf(this.scope,this.state.required.authInfo,this.tryGetContext()?.platformType);this.state.set("dialect",resolveEventDialect(this.events.config.compat,platform))}async requireSubscriber(){const{authInfo,dialect}=this.state.required;const owner=eventSubscriberOf(authInfo,this.scope.authoritiesContextBuilder);if(!owner){const eventName=this.input.request.params.name;const codes=EVENT_DIALECTS[dialect].errorCodes;throw new EventForbiddenError(codes,eventName,"a webhook subscription needs a signed-in caller")}this.state.set("owner",owner)}async removeSubscription(){const{name:eventName,delivery}=this.input.request.params;const{owner,authInfo}=this.state.required;const identity=this.subscriptions.identityOf(owner.principalKey,delivery.url,eventName,this.storedArguments());this.subscriptions.sweepIfDue();const removed=await this.subscriptions.store.delete(identity.id);if(!removed)return;await this.subscriptions.notifyUnsubscribed(removed,"unsubscribed",authInfo);this.logger.verbose(`removeSubscription: subscription ${removed.id} removed from event "${eventName}"`)}async buildResult(){this.respond({})}async finalize(){this.logger.verbose("finalize")}storedArguments(){const{name:eventName,arguments:sentArguments={}}=this.input.request.params;try{return this.events.findByName(eventName)?.parseArguments(sentArguments)??sentArguments}catch{return sentArguments}}};__decorateClass([Stage44("parseInput")],EventUnsubscribeFlow.prototype,"parseInput",1);__decorateClass([Stage44("resolveDialect")],EventUnsubscribeFlow.prototype,"resolveDialect",1);__decorateClass([Stage44("requireSubscriber")],EventUnsubscribeFlow.prototype,"requireSubscriber",1);__decorateClass([Stage44("removeSubscription")],EventUnsubscribeFlow.prototype,"removeSubscription",1);__decorateClass([Stage44("buildResult")],EventUnsubscribeFlow.prototype,"buildResult",1);__decorateClass([Stage44("finalize")],EventUnsubscribeFlow.prototype,"finalize",1);EventUnsubscribeFlow=__decorateClass([FrontMcpFlow({name:name44,plan:plan44,inputSchema:inputSchema37,outputSchema:outputSchema36,access:"authorized"})],EventUnsubscribeFlow)}});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_zod137,import_protocol81,EVENTS_LIST_PAGE_SIZE,inputSchema38,outputSchema37,stateSchema40,plan45,name45,Stage45,ListEventsFlow;var init_list_events_flow=__esm({"libs/sdk/src/event/flows/list-events.flow.ts"(){"use strict";import_lazy_zod137=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;inputSchema38=import_lazy_zod137.internalZ.object({request:import_protocol81.ListEventsRequestSchema,ctx:import_lazy_zod137.internalZ.unknown()});outputSchema37=import_protocol81.ListEventsResultSchema;stateSchema40=import_lazy_zod137.internalZ.object({cursor:import_lazy_zod137.internalZ.string().optional(),authInfo:import_lazy_zod137.internalZ.any(),events:import_lazy_zod137.internalZ.array(import_lazy_zod137.internalZ.object({event:import_lazy_zod137.internalZ.instanceof(EventEntry),delivery:import_lazy_zod137.internalZ.array(import_protocol81.EventDeliveryModeSchema)}))});plan45={pre:["parseInput"],execute:["findEvents","filterByAvailability","filterByAuthorities","filterByDiscovery"],post:["parseEvents"],finalize:["finalize"]};name45="events:list";({Stage:Stage45}=FlowHooksOf(name45));ListEventsFlow=class extends FlowBase{logger=this.scopeLogger.child("ListEventsFlow");async parseInput(){const{request:request2,ctx}=this.input;const authInfo=ctx?.authInfo??{};this.state.set({cursor:request2.params?.cursor??void 0,authInfo})}async findEvents(){this.state.set("events",this.scope.events?.getServedEvents()??[])}async filterByAvailability(){const callSurface=callSurfaceOf(this.input.ctx);const offered=this.state.required.events.filter(({event})=>isOfferedOnSurface(event.metadata.availableWhen,callSurface));this.state.set("events",offered)}async filterByAuthorities(){const engine=this.scope.authoritiesEngine;const contextBuilder=this.scope.authoritiesContextBuilder;if(!engine||!contextBuilder)return;const{events,authInfo}=this.state.required;const answers=await Promise.all(events.map(({event})=>{const authorities=event.getAuthorities();if(authorities===void 0)return true;return isListedByAuthorities(engine,contextBuilder,authorities,authInfo,event.name,this.logger)}));this.state.set("events",events.filter((_item,index)=>answers[index]))}async filterByDiscovery(){const discoverable=this.state.required.events.filter(({event})=>!event.metadata.hideFromDiscovery);this.state.set("events",discoverable)}async parseEvents(){const sorted=[...this.state.required.events].sort(compareByName);const offset=this.state.cursor?parseOffsetCursor(this.state.cursor):0;if(offset>sorted.length){throw new InvalidInputError(`Invalid pagination cursor: offset ${offset} exceeds total event count ${sorted.length}`)}const events=sorted.slice(offset,offset+EVENTS_LIST_PAGE_SIZE).map(({event,delivery})=>({name:event.name,...event.metadata.description&&{description:event.metadata.description},delivery,inputSchema:event.getInputJsonSchema(),payloadSchema:event.getPayloadJsonSchema()}));const nextOffset=offset+EVENTS_LIST_PAGE_SIZE;this.respond({events,...nextOffset<sorted.length&&{nextCursor:encodeOffsetCursor(nextOffset)}})}async finalize(){this.logger.verbose("finalize")}};__decorateClass([Stage45("parseInput")],ListEventsFlow.prototype,"parseInput",1);__decorateClass([Stage45("findEvents")],ListEventsFlow.prototype,"findEvents",1);__decorateClass([Stage45("filterByAvailability")],ListEventsFlow.prototype,"filterByAvailability",1);__decorateClass([Stage45("filterByAuthorities")],ListEventsFlow.prototype,"filterByAuthorities",1);__decorateClass([Stage45("filterByDiscovery")],ListEventsFlow.prototype,"filterByDiscovery",1);__decorateClass([Stage45("parseEvents")],ListEventsFlow.prototype,"parseEvents",1);__decorateClass([Stage45("finalize")],ListEventsFlow.prototype,"finalize",1);ListEventsFlow=__decorateClass([FrontMcpFlow({name:name45,plan:plan45,inputSchema:inputSchema38,outputSchema:outputSchema37,access:"authorized"})],ListEventsFlow)}});var import_utils173,CURSOR_SEPARATOR,EventBuffer;var init_event_buffer=__esm({"libs/sdk/src/event/poll/event-buffer.ts"(){"use strict";import_utils173=require("@frontmcp/utils");CURSOR_SEPARATOR=".";EventBuffer=class{constructor(options){this.options=options;this.bootId=(0,import_utils173.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_zod138,EVENT_PUBLISH_MAX_BODY_BYTES,EVENT_ID_PATTERN,audienceValueSchema2,publishRequestSchema,inputSchema39,outputSchema38,stateSchema41,plan46,name46,Stage46,decoder3,EventPublishHttpFlow;var init_event_publish_http_flow=__esm({"libs/sdk/src/event/flows/event-publish-http.flow.ts"(){"use strict";import_lazy_zod138=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_zod138.internalZ.union([import_lazy_zod138.internalZ.string(),import_lazy_zod138.internalZ.array(import_lazy_zod138.internalZ.string())]);publishRequestSchema=import_lazy_zod138.internalZ.object({name:import_lazy_zod138.internalZ.string().min(1),data:import_lazy_zod138.internalZ.record(import_lazy_zod138.internalZ.string(),import_lazy_zod138.internalZ.unknown()),eventId:import_lazy_zod138.internalZ.string().regex(EVENT_ID_PATTERN,"eventId must be 1 to 255 visible ASCII characters").optional(),timestamp:import_lazy_zod138.internalZ.string().refine(isTimestamp,"timestamp must be a date such as 2026-10-02T12:00:00Z").optional(),subscriptionId:import_lazy_zod138.internalZ.string().min(1).optional(),audience:import_lazy_zod138.internalZ.object({sub:audienceValueSchema2.optional(),tenantId:audienceValueSchema2.optional(),roles:import_lazy_zod138.internalZ.object({any:import_lazy_zod138.internalZ.array(import_lazy_zod138.internalZ.string()).optional(),all:import_lazy_zod138.internalZ.array(import_lazy_zod138.internalZ.string()).optional()}).strict().optional()}).strict().optional()}).strict();inputSchema39=httpInputSchema;outputSchema38=HttpJsonSchema;stateSchema41=import_lazy_zod138.internalZ.object({body:import_lazy_zod138.internalZ.custom(),caller:import_lazy_zod138.internalZ.custom().optional(),publication:publishRequestSchema,event:import_lazy_zod138.internalZ.instanceof(EventEntry),claimedEventId:import_lazy_zod138.internalZ.string().optional(),claimToken:import_lazy_zod138.internalZ.string().optional(),result:import_lazy_zod138.internalZ.object({eventId:import_lazy_zod138.internalZ.string(),matched:import_lazy_zod138.internalZ.number()}),flowError:import_lazy_zod138.internalZ.instanceof(Error).optional()});plan46={pre:["checkIpFilter","acquireQuota","readBody","authenticate","parseBody","checkAuthorities","findEvent","validatePayload"],execute:["claimEventId","publish","rememberResult","buildResponse"],finalize:["finalize"]};name46="events:publish-http";({Stage:Stage46}=FlowHooksOf(name46));decoder3=new TextDecoder;EventPublishHttpFlow=class extends FlowBase{logger=this.scopeLogger.child("EventPublishHttpFlow");static canActivate(request2,scope){const endpoint=scope.events?.publishEndpoint;return endpoint!==void 0&&request2.method==="POST"&&matchRoutePath(endpoint.path,request2.path)!==void 0}get events(){return this.scope.events}get endpoint(){return this.events.publishEndpoint}get publisher(){return this.events.publisher}get httpRequest(){return this.rawInput.request}refuse(status,error,details={},headers){this.state.set("flowError",new PublicMcpError(`HTTP ${status}: ${error}`,"EVENT_PUBLISH_REFUSED",status));return FlowControl.respond(httpRespond.json({error,...details},{status,headers}))}async recordingRefusal(guard){try{await guard()}catch(signal){const refusal4=signal instanceof FlowControl&&signal.type==="respond"?signal.output:void 0;if(refusal4?.kind==="json"){const reason=Array.isArray(refusal4.body)?void 0:refusal4.body["error"];const error=typeof reason==="string"?reason:"Refused";this.state.set("flowError",new PublicMcpError(`HTTP ${refusal4.status}: ${error}`,"EVENT_PUBLISH_REFUSED",refusal4.status))}throw signal}}async checkIpFilter(){await this.recordingRefusal(()=>enforceIpFilter(this.scope,this.tryGetContext()?.metadata.clientIp))}async acquireQuota(){await this.recordingRefusal(()=>enforceGlobalRateLimit(this.scope,this.tryGetContext()))}async readBody(){const request2=this.httpRequest;if(mediaTypeOf2(request2.headers["content-type"])!=="application/json"){this.refuse(415,"The body must be application/json")}const body=request2.bodyBytes??new Uint8Array;if(body.length>EVENT_PUBLISH_MAX_BODY_BYTES)this.refuse(413,"Payload too large");this.state.set("body",body)}async authenticate(){const{secret,replays}=this.endpoint;if(secret===void 0){this.state.set("caller",await this.verifyBearer());return}const signedRequest={headers:this.httpRequest.headers,body:this.state.required.body};const refusal4=verifyWorkflowWebhook(signedRequest,secret,replays);if(refusal4){this.logger.warn(`authenticate: a publish request was refused: ${refusal4}`);this.refuse(401,"Unauthorized")}}async parseBody(){const parsed=publishRequestSchema.safeParse(jsonOf(this.state.required.body));if(!parsed.success)this.refuse(400,"Invalid publish request",{issues:summarizeIssues(parsed.error)});this.state.set("publication",parsed.data)}async checkAuthorities(){const engine=this.scope.authoritiesEngine;const contextBuilder=this.scope.authoritiesContextBuilder;const{authorities}=this.endpoint;if(!engine||!contextBuilder||authorities===void 0)return;const caller=this.state.caller??{};const evaluationContext=contextBuilder.build(caller,this.state.required.publication);const result=await engine.evaluate(authorities,evaluationContext);if(result.granted)return;this.logger.verbose(`checkAuthorities: a publish request was refused: ${result.deniedBy??"policy denied"}`);this.refuse(403,"Forbidden")}async findEvent(){const eventName=this.state.required.publication.name;const event=this.events.findByName(eventName);if(!event)this.refuse(404,`Event "${eventName}" is not registered`);this.state.set("event",event)}async validatePayload(){const{event,publication}=this.state.required;try{event.parsePayload(publication.data)}catch(error){if(!(error instanceof import_lazy_zod138.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([Stage46("checkIpFilter")],EventPublishHttpFlow.prototype,"checkIpFilter",1);__decorateClass([Stage46("acquireQuota")],EventPublishHttpFlow.prototype,"acquireQuota",1);__decorateClass([Stage46("readBody")],EventPublishHttpFlow.prototype,"readBody",1);__decorateClass([Stage46("authenticate")],EventPublishHttpFlow.prototype,"authenticate",1);__decorateClass([Stage46("parseBody")],EventPublishHttpFlow.prototype,"parseBody",1);__decorateClass([Stage46("checkAuthorities")],EventPublishHttpFlow.prototype,"checkAuthorities",1);__decorateClass([Stage46("findEvent")],EventPublishHttpFlow.prototype,"findEvent",1);__decorateClass([Stage46("validatePayload")],EventPublishHttpFlow.prototype,"validatePayload",1);__decorateClass([Stage46("claimEventId")],EventPublishHttpFlow.prototype,"claimEventId",1);__decorateClass([Stage46("publish")],EventPublishHttpFlow.prototype,"publish",1);__decorateClass([Stage46("rememberResult")],EventPublishHttpFlow.prototype,"rememberResult",1);__decorateClass([Stage46("buildResponse")],EventPublishHttpFlow.prototype,"buildResponse",1);__decorateClass([Stage46("finalize")],EventPublishHttpFlow.prototype,"finalize",1);EventPublishHttpFlow=__decorateClass([FrontMcpFlow({name:name46,plan:plan46,inputSchema:inputSchema39,outputSchema:outputSchema38,access:"public",middleware:{method:"POST"}})],EventPublishHttpFlow)}});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_utils174,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_utils174=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_utils174.sha256Hex)(text);return(0,import_utils174.bytesToHex)((0,import_utils174.hmacSha256)(textEncoder3.encode(secret),textEncoder3.encode(text)))}}}});function eventsSecretFromEnv(){return(0,import_utils175.getEnv)("MCP_EVENTS_SECRET")||(0,import_utils175.getEnv)("MCP_SESSION_SECRET")||(0,import_utils175.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(!isRedisProvider(redis)){throw new EventSubscriptionStoreError("Vercel KV has no atomic compare-and-set, which subscription updates need. Use a Redis server in events.store.redis, or events.store.sqlite.")}const{host,port,password,db,tls}=redis;return{type:"redis",redis:{config:{host,port,password,db,tls}}}}async function openStorage(config,keyPrefix){try{return await(0,import_utils175.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_utils175;var init_event_subscription_store_factory=__esm({"libs/sdk/src/event/subscription/event-subscription-store.factory.ts"(){"use strict";import_utils175=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_utils176,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_utils176=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_utils176.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_utils176.sha256Hex)(JSON.stringify([this.scopeId,eventName,eventId])).slice(0,40)}}}});function assertPathFree(scope,path4){const reserved=computeReservedPaths(scope.entryPath,scope.routeBase,servedHealthPaths(scope.metadata.health));try{assertNotReserved("POST",path4,reserved)}catch(error){if(!(error instanceof ReservedRouteCollisionError))throw error;throw new EventPublishEndpointError(`events.publishEndpoint.path "${path4}" is on the reserved FrontMCP path "${error.reserved}": choose another path`)}const routes=[...scope.httpRouteTable?.routes??[],...scope.metadata.http?.routes??[]];const taken=routes.find(route=>route.method.toUpperCase()==="POST"&&matchRoutePath(route.path,path4)!==void 0);if(taken){throw new EventPublishEndpointError(`events.publishEndpoint.path "${path4}" is already served by the route POST ${taken.path}: choose another path`)}}async function enablePublishEndpoint(args){const{scope,eventRegistry,identifiesCallers,keyPrefix,logger}=args;const{secret,authorities,path:configuredPath}=eventRegistry.config.publishEndpoint;const{store:storeConfig}=eventRegistry.config;if(!secret&&!identifiesCallers){throw new EventPublishEndpointError("the server runs in public auth mode, so nothing tells who publishes. Set events.publishEndpoint.secret (at least 32 characters) for signed requests, or configure an auth mode that signs callers in.")}if(authorities!==void 0){assertEntryAuthorities(scope.authoritiesEngine,scope.authoritiesContextBuilder,[{label:"events.publishEndpoint",authorities}])}const path4=`${normalizeScopeBase(scope.routeBase)}${configuredPath}`;assertPathFree(scope,path4);let storage=eventRegistry.storage;if(!storage){const ownStorage=await openEventStorage({redis:storeConfig?.redis,sqlite:storeConfig?.sqlite,keyPrefix});scope.onDispose(()=>ownStorage.disconnect());storage=ownStorage}eventRegistry.publishEndpoint={path:path4,secret,authorities,replays:new WorkflowWebhookReplayGuard,idempotency:new EventPublishIdempotency(storage,scope.id)};await scope.registryFlows(EventPublishHttpFlow);logger.info(`Events can be published over HTTP: POST ${path4} (${secret?"signed requests":"bearer callers"})`);if(!secret&&authorities===void 0){logger.warn(`POST ${path4} lets every signed-in caller publish every event. Set events.publishEndpoint.authorities to name who may publish.`)}}var init_event_publish_endpoint=__esm({"libs/sdk/src/event/publish-endpoint/event-publish-endpoint.ts"(){"use strict";init_common();init_errors();init_flow_http_path();init_authorities_rules_check();init_health_routes();init_custom_routes_helper();init_workflow_webhook_signature();init_event_publish_http_flow();init_event_subscription_store_factory();init_event_publish_idempotency()}});function isSameReadPosition(current,expected){return current?.cursor===expected.cursor&&current.queuedAtCursor===expected.queuedAtCursor}function isSamePosition(current,expected){if(!current||current.cursor!==expected.cursor||current.pending.length!==expected.pending.length)return false;return current.pending.every((batch,index)=>batch.cursor===expected.pending[index].cursor)}var import_utils177,REPLAY_LEASE_MS,REPLAY_STOP_GRACE_MS,MAX_PENDING_BATCHES,MAX_ROUNDS_PER_TICK,encoder10,EventReplays;var init_event_replays=__esm({"libs/sdk/src/event/replay/event-replays.ts"(){"use strict";import_utils177=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;encoder10=new TextEncoder;EventReplays=class{constructor(options){this.options=options;this.logger=options.logger.child("EventReplays")}options;holders=new Map;timers=new Map;ticks=new Map;nextCheckAt=new Map;logger;isReplayable(event){return typeof event.create({}).check==="function"}async start(events){for(const event of events){const holder=new LeaseHolder({label:`Webhook delivery of event "${event.name}"`,key:`replay-lease:${(0,import_utils177.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,eventName:record.eventName,body:JSON.stringify({type:"gap",cursor:replay.watermark}),webhookId:(0,import_utils177.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=encoder10.encode(body).byteLength;if(bytes>this.options.maxBodyBytes){this.logger.warn(`Event "${event.name}" is ${bytes} bytes for subscription ${record.id}, over the ${this.options.maxBodyBytes} byte limit; it is not delivered`);return void 0}const usesEventId=EVENT_DIALECTS[record.dialect].webhookId==="eventId";return this.options.outbox.enqueue({kind:"event",subscriptionId:record.id,eventName:event.name,body,webhookId:usesEventId?eventId:(0,import_utils177.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_utils178,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_utils178=require("@frontmcp/utils");EVENT_RELAY_CHANNEL="occurrences";MAX_OPEN_STREAMS=1e4;EventStreams=class{constructor(options){this.options=options;this.nodeId=(0,import_utils178.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}async start(){const{storage}=this.options;if(!storage||!this.isRelayed)return;this.stopRelay=await storage.subscribe(EVENT_RELAY_CHANNEL,message=>this.receive(message))}async stop(){await this.stopRelay?.();this.stopRelay=void 0;for(const streams of[...this.streams.values()]){for(const stream of[...streams])stream.close()}}isFull(principalKey){if(this.held.size>=MAX_OPEN_STREAMS)return true;let heldByOwner=0;for(const stream of this.held){if(stream.principalKey===principalKey)heldByOwner+=1}return heldByOwner>=this.options.maxPerPrincipal}reserve(stream){if(this.held.has(stream))return true;if(this.isFull(stream.principalKey))return false;this.hold(stream);return true}add(stream){this.hold(stream);if(stream.isClosed)return;const streams=this.streams.get(stream.eventName)??new Set;this.streams.set(stream.eventName,streams);streams.add(stream)}hold(stream){if(this.held.has(stream)||stream.isClosed)return;this.held.add(stream);stream.onClose(()=>{this.held.delete(stream);this.streams.get(stream.eventName)?.delete(stream)})}async publish(buffered){await this.deliver(buffered);const{storage}=this.options;if(!storage||!this.isRelayed)return;const{occurrence,audience,subscriptionId}=buffered;const relayed={origin:this.nodeId,occurrence,audience,subscriptionId};try{await storage.publish(EVENT_RELAY_CHANNEL,JSON.stringify(relayed))}catch(error){this.logger.warn(`Event "${occurrence.name}" was not relayed to the other processes`,error)}}async deliver(buffered){const streams=this.streams.get(buffered.occurrence.name);if(!streams)return;await Promise.all([...streams].map(stream=>stream.offer(buffered)))}receive(message){const relayed=parseRelayed(message);if(!relayed||relayed.origin===this.nodeId)return;const buffered=this.options.buffer.append(relayed.occurrence,relayed.audience,relayed.subscriptionId);this.deliver(buffered).catch(error=>this.logger.warn("A relayed event was not delivered",error))}}}});function isSameText(left,right){const leftBytes=encoder11.encode(left);const rightBytes=encoder11.encode(right);return leftBytes.length===rightBytes.length&&(0,import_utils179.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_utils179,VERIFICATION_ATTEMPTS_PER_HOST,VERIFICATION_WINDOW_MS,WELL_KNOWN_CACHE_MS,WELL_KNOWN_MAX_BYTES,CHALLENGE_BYTES,CHALLENGE_ANSWER_MAX_BYTES,MAX_CACHED_ENTRIES,encoder11,ExpiringMap,EventCallbackVerifier;var init_event_callback_verifier=__esm({"libs/sdk/src/event/subscription/event-callback-verifier.ts"(){"use strict";import_protocol83=require("@frontmcp/protocol");import_utils179=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;encoder11=new TextEncoder;ExpiringMap=class{entries=new Map;get(key,now){const entry=this.entries.get(key);if(!entry)return void 0;if(entry.expiresAt>now)return entry.value;this.entries.delete(key);return void 0}set(key,value,expiresAt){this.entries.delete(key);if(this.entries.size>=MAX_CACHED_ENTRIES){const oldestKey=this.entries.keys().next().value;if(oldestKey!==void 0)this.entries.delete(oldestKey)}this.entries.set(key,{value,expiresAt})}};EventCallbackVerifier=class{constructor(options){this.options=options;this.send=options.send??import_utils179.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_utils179.sha256Hex)(`${request2.principalKey}
332
332
  ${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_utils179.base64urlEncode)((0,import_utils179.randomBytes)(CHALLENGE_BYTES));const body=JSON.stringify({type:"verification",challenge:nonce});const message={id:(0,import_utils179.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_utils179.webhookSignatureHeaders)(message,[(0,import_utils179.signingKeyOf)(request2.secret)])},body,timeoutMs:this.options.timeoutMs,maxResponseBytes:CHALLENGE_ANSWER_MAX_BYTES,...eventOutboundTargetOptions(this.options.allowLocal)});const category=(0,import_utils179.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_auth57.isPublicMode)(authOptions)}function storeKeyPrefixOf(scope,eventsConfig){const configuredPrefix=eventsConfig.store?.keyPrefix;if(configuredPrefix)return configuredPrefix;return`mcp:events:${(0,import_utils180.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});const outbox=new EventOutbox({storage,secret,durable,settings:webhook.delivery,attempt:delivery=>scope.runFlowForOutput("events:deliver",{delivery}),metrics:eventRegistry.metrics??createEventMetrics(void 0),logger});eventRegistry.subscriptions=subscriptions;eventRegistry.outbox=outbox;eventRegistry.storage=storage;await scope.registryFlows(EventDeliverFlow);subscriptions.start();outbox.start();const replays=new EventReplays({store,outbox,storage,intervalMs:eventsConfig.poll.nextPollMs,maxEvents:eventsConfig.poll.maxEvents,maxBodyBytes:EVENT_DELIVERY_MAX_BYTES,reauthorizeEveryMs:eventsConfig.subscriptions.reauthorizeEveryMs,reauthorize:(event,record)=>reauthorizeSubscriber({scope,event,subscriber:record.subscriber,arguments:record.arguments}),terminate:record=>terminateEventSubscription({subscriptions,outbox,metrics:eventRegistry.metrics,logger,subscription:record,error:accessRevokedError(record.dialect)}),logger});await startReplays(eventRegistry,replays,logger);scope.onDispose(async()=>{await replays.stop();await outbox.stop();await subscriptions.close()});scope.registerHealthProbe({name:"events-outbox",check:()=>outboxHealth(outbox)});if(webhook.unsafeAllowLocalCallbacks){logger.warn("events.webhook.unsafeAllowLocalCallbacks is on: callbacks may be http and local. Use it in tests only.")}eventRegistry.enableDeliveryMode("webhook");await scope.registryFlows(EventSubscribeFlow,EventUnsubscribeFlow);return storage}async function enablePollDelivery(scope,eventRegistry,eventsConfig,logger){const pollLeases=new EventPollLeases({maxPerPrincipal:eventsConfig.subscriptions.maxPerPrincipal,logger});eventRegistry.pollLeases=pollLeases;pollLeases.start();scope.onDispose(()=>pollLeases.stop());eventRegistry.enableDeliveryMode("poll");await scope.registryFlows(EventPollFlow);const readsBuffer=eventRegistry.getEvents().some(event=>typeof event.create({}).check!=="function");if(readsBuffer&&(0,import_utils180.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_utils180.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_auth57,import_utils180;var init_event_scope_helper=__esm({"libs/sdk/src/event/event-scope.helper.ts"(){"use strict";import_auth57=require("@frontmcp/auth");import_utils180=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_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_auth58;var init_cimd=__esm({"libs/sdk/src/auth/cimd/index.ts"(){"use strict";import_auth58=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_di49.ProviderScope.GLOBAL,name:"SessionCredentialVault"};const accessorProvider={provide:import_auth59.CREDENTIALS_ACCESSOR,inject:()=>[FRONTMCP_CONTEXT,FrontMcpLogger],useFactory:(ctx,logger)=>new import_auth59.CredentialsAccessorImpl({vault,resolveSub:()=>resolveRequestSub(ctx),signingSecret,basePath,resumeTtlMs,logger:logger.child("CredentialsAccessor")}),scope:import_di49.ProviderScope.CONTEXT,name:"CredentialsAccessor"};return[vaultProvider,accessorProvider]}var import_auth59,import_di49,SESSION_CREDENTIAL_VAULT;var init_credentials_providers=__esm({"libs/sdk/src/auth/credentials/credentials.providers.ts"(){"use strict";import_auth59=require("@frontmcp/auth");import_di49=require("@frontmcp/di");init_common();init_frontmcp_context_provider();SESSION_CREDENTIAL_VAULT=Symbol.for("frontmcp:SESSION_CREDENTIAL_VAULT")}});var import_auth60,credentialsContextExtension;var init_credentials_context_extension=__esm({"libs/sdk/src/auth/credentials/credentials.context-extension.ts"(){"use strict";import_auth60=require("@frontmcp/auth");credentialsContextExtension={property:"credentials",token:import_auth60.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_utils181,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_utils181=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_utils181.isAbsolute)(rawPath)?rawPath:(0,import_utils181.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[name59,handler]of Object.entries(map)){if(typeof handler!=="function"){throw new Error(`auth.extras["${name59}"] must be a handler function (input, ctx) => AuthExtraResult.`)}this.extras.set(name59,handler);this.logger?.verbose(`Registered auth.extras handler "${name59}"`)}}setResolverOverrides(overrides){this.resolverOverrides=overrides}getResolverOverrides(){return this.resolverOverrides}hasAny(){return this.slots.size>0}hasSlot(slot){return this.slots.has(slot)}hasExtras(){return this.extras.size>0}getSlotSource(slot){const entry=this.slots.get(slot);if(!entry||entry.error)return void 0;return{file:entry.file}}canRenderSlot(slot){return this.getSlotSource(slot)!==void 0}recordSlotError(slot,message){const entry=this.slots.get(slot);if(entry&&!entry.error){entry.error=message;this.logger?.error(`Failed to build auth.ui page for slot "${slot}": ${message}`)}}mintCsrf(pendingAuthId){const existing=this.pending.get(pendingAuthId);if(existing)return existing.csrf;const csrf=(0,import_utils181.sha256Hex)((0,import_utils181.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(([name59,items])=>[name59,[...items]]))}appendItems(pendingAuthId,extraName2,items){const state=this.ensurePending(pendingAuthId);const current=state.addedItems[extraName2]??[];state.addedItems[extraName2]=[...current,...items];return{...state.addedItems}}ensurePending(pendingAuthId){let state=this.pending.get(pendingAuthId);if(!state){state={csrf:(0,import_utils181.sha256Hex)((0,import_utils181.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(name59){return this.extras.has(name59)}async runExtra(name59,pendingAuthId,input){const handler=this.extras.get(name59);if(!handler){return{ok:false,error:`Unknown extra "${name59}".`}}const ctx={name:name59,pendingAuthId,current:pendingAuthId?this.getAddedItems(pendingAuthId)[name59]??[]:[]};let result;try{result=await handler(input,ctx)}catch(err){this.logger?.error(`auth.extras["${name59}"] handler threw: ${err instanceof Error?err.message:String(err)}`);return{ok:false,error:"Validation failed. Please try again."}}if(!result||typeof result.ok!=="boolean"){this.logger?.error(`auth.extras["${name59}"] returned a malformed result.`);return{ok:false,error:"Validation failed. Please try again."}}if(result.ok&&pendingAuthId&&Array.isArray(result.addedItems)&&result.addedItems.length>0){if(ctx.current.length+result.addedItems.length>MAX_ITEMS_PER_EXTRA){return{ok:false,error:`This list holds at most ${MAX_ITEMS_PER_EXTRA} items.`,addedItems:this.getAddedItems(pendingAuthId)}}const addedItems=this.appendItems(pendingAuthId,name59,result.addedItems);return{ok:true,sideEffects:result.sideEffects,addedItems}}return{ok:result.ok,error:result.error,sideEffects:result.sideEffects,...pendingAuthId?{addedItems:this.getAddedItems(pendingAuthId)}:{}}}async warmup(){if(!this.hasAny())return;for(const slot of this.slots.keys()){if(this.getSlotSource(slot)){this.logger?.verbose(`Validated auth.ui source for slot "${slot}"`)}}}}}});function authUiExtraPath(fullPath){return`${fullPath.replace(/\/+$/,"")}/oauth/ui/extra`}function formActionSource(target){let url;try{url=new URL(target)}catch{return void 0}if(url.protocol==="http:"||url.protocol==="https:"){return url.hostname.startsWith("[")?void 0:url.origin}if(!/^[a-z][a-z0-9+.-]*:$/.test(url.protocol)||UNSAFE_FORM_TARGET_SCHEMES.has(url.protocol))return void 0;return url.protocol}function authUiCsp(formTargets=[]){const formAction=new Set(["'self'"]);for(const target of formTargets){const source=formActionSource(target);if(source)formAction.add(source)}return["default-src 'self'","script-src 'self' 'unsafe-inline' https://esm.sh","connect-src 'self' https://esm.sh","style-src 'self' 'unsafe-inline' https://esm.sh","img-src 'self' data: https:","frame-ancestors 'none'","base-uri 'self'",`form-action ${[...formAction].join(" ")}`].join("; ")}function authUiPageHeaders(csp=AUTH_UI_CSP){return{"Content-Security-Policy":csp,"X-Frame-Options":"DENY","X-Content-Type-Options":"nosniff","Referrer-Policy":"same-origin","Cache-Control":"no-store"}}function authUiSecurityHeaders(){return authUiPageHeaders(AUTH_UI_CSP)}function authMountDescriptor(){return{moduleSpecifier:"@frontmcp/ui/auth",generate:exportName=>`
333
333
  import { mountAuthPage as __mountAuthPage } from '@frontmcp/ui/auth';
334
334
  __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,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:"]);AUTH_UI_CSP=authUiCsp()}});function buildLoginState(common,data){return{slot:"login",pendingAuthId:common.pendingAuthId,clientId:data.clientId,clientName:data.clientName??data.clientId,scopes:data.scopes,redirectUri:data.redirectUri,csrfToken:common.csrfToken,submitUrl:common.submitUrl,submitMethod:SUBMIT_METHOD,extraUrl:common.extraUrl,addedItems:common.addedItems,...data.logoUri?{extras:{logoUri:data.logoUri}}:{}}}function buildConsentState(common,data){return{slot:"consent",pendingAuthId:common.pendingAuthId,clientId:data.clientId,clientName:data.clientName??data.clientId,redirectUri:data.redirectUri,tools:data.tools,csrfToken:common.csrfToken,submitUrl:common.submitUrl,submitMethod:SUBMIT_METHOD,extraUrl:common.extraUrl,addedItems:common.addedItems}}function buildFederatedState(common,data){return{slot:"federated",pendingAuthId:common.pendingAuthId,clientId:data.clientId,clientName:data.clientName??data.clientId,redirectUri:data.redirectUri,providers:data.providers,csrfToken:common.csrfToken,submitUrl:common.submitUrl,submitMethod:SUBMIT_METHOD,extraUrl:common.extraUrl,addedItems:common.addedItems,extras:{[AUTH_WIRE_FIELDS.federated]:true,...data.step?{step:data.step}:{}}}}function buildIncrementalState(common,data){return{slot:"incremental",pendingAuthId:common.pendingAuthId,redirectUri:data.redirectUri,csrfToken:common.csrfToken,submitUrl:common.submitUrl,submitMethod:SUBMIT_METHOD,extraUrl:common.extraUrl,addedItems:common.addedItems,extras:{[AUTH_WIRE_FIELDS.incremental]:true,[AUTH_WIRE_FIELDS.appId]:data.appId,appName:data.appName,appDescription:data.appDescription,toolId:data.toolId}}}function buildErrorState(data){return{slot:"error",error:data.error,...data.pendingAuthId?{pendingAuthId:data.pendingAuthId}:{}}}var SUBMIT_METHOD;var init_auth_ui_state=__esm({"libs/sdk/src/auth/auth-ui/auth-ui.state.ts"(){"use strict";init_auth_ui_contract();SUBMIT_METHOD="POST"}});var auth_ui_exports={};__export(auth_ui_exports,{AUTH_FLOW_GLOBAL_KEY:()=>AUTH_FLOW_GLOBAL_KEY,AUTH_MOUNT_ID:()=>AUTH_MOUNT_ID,AUTH_UI_CSP:()=>AUTH_UI_CSP,AuthUiRegistry:()=>AuthUiRegistry,authUiExtraPath:()=>authUiExtraPath,authUiPageHeaders:()=>authUiPageHeaders,authUiSecurityHeaders:()=>authUiSecurityHeaders,buildAuthUiPage:()=>buildAuthUiPage,buildConsentState:()=>buildConsentState,buildErrorState:()=>buildErrorState,buildFederatedState:()=>buildFederatedState,buildIncrementalState:()=>buildIncrementalState,buildLoginState:()=>buildLoginState});var init_auth_ui=__esm({"libs/sdk/src/auth/auth-ui/index.ts"(){"use strict";init_auth_ui_contract();init_auth_ui_registry();init_auth_ui_render();init_auth_ui_state()}});function effectiveToolId(metadata){return metadata.id??metadata.name}function projectConsentTools(scope,excludedTools){const excluded=new Set(excludedTools??[]);const apps=scope.apps.getApps();const appNameById=new Map;for(const app of apps){const appId=app.id??app.metadata?.id;if(appId)appNameById.set(appId,app.metadata?.name??appId)}const toolCards=[];const availableToolIds=[];for(const tool of scope.tools.getTools()){const id=effectiveToolId(tool.metadata);if(excluded.has(id))continue;const appId=tool.owner?.id??"app";toolCards.push({toolId:id,toolName:tool.metadata.name,description:tool.metadata.description,appId,appName:appNameById.get(appId)??appId});availableToolIds.push(id)}return{toolCards,availableToolIds}}var init_consent_tools_helper=__esm({"libs/sdk/src/auth/consent-tools.helper.ts"(){"use strict"}});function allowsSkippingApps(authOptions){return!(authOptions&&(0,import_auth61.isOrchestratedMode)(authOptions)&&authOptions.incrementalAuth?.allowSkip===false)}function requiredProviderIds(authOptions,apps){if(!authOptions||!(0,import_auth61.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_auth61;var init_required_providers_utils=__esm({"libs/sdk/src/auth/required-providers.utils.ts"(){"use strict";import_auth61=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_utils182.base64urlEncode)((0,import_utils182.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_auth62.buildFederatedStepPage)({provider:{providerId,providerName:providerId,providerUrl:provider?.providerUrl,mode:provider?.mode??"unknown",appIds:(provider?.appIds??[]).filter(id=>id!=="__parent__"),isPrimary:provider?.isParentProvider,required:!step.canSkip},step,clientName:options.clientName,pendingAuthId:record.id,callbackPath:submitUrl,csrfToken,error:options.error});return httpRespond.html(markup,200,(0,import_auth62.builtInAuthPageHeaders)())}function providerAuthorizationEndpoints(scope,providerIds){const localAuth=scope.auth;if(typeof localAuth?.getProviderConfig!=="function")return[];const endpoints=[];for(const id of providerIds){const endpoint=localAuth.getProviderConfig(id)?.authorizationEndpoint;if(endpoint)endpoints.push(endpoint)}return endpoints}var import_auth62,import_utils182,FEDERATED_STEP_FIELD;var init_federated_steps=__esm({"libs/sdk/src/auth/federated-steps.ts"(){"use strict";import_auth62=require("@frontmcp/auth");import_utils182=require("@frontmcp/utils");init_common();init_flow_http_path();init_auth_ui();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_utils183.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_auth63.createSigninBinding)(pendingAuthId,{secure:signinOverHttps(request2)})}function signinBindingCookie(request2,binding,path4){const secure=signinOverHttps(request2);return{name:binding.cookieName,value:binding.value,path:secure?"/":path4,httpOnly:true,sameSite:"lax",secure,maxAge:import_auth63.SIGNIN_BINDING_MAX_AGE_SECONDS}}function clearedSigninBindingCookie(request2,pendingAuthId,path4){const secure=signinOverHttps(request2);return{name:(0,import_auth63.signinBindingCookieName)(pendingAuthId,{secure}),value:"",path:secure?"/":path4,httpOnly:true,sameSite:"lax",secure,maxAge:0}}function requestHoldsSigninBinding(request2,pendingAuthId,hash){const raw=request2.headers?.["cookie"];const header2=Array.isArray(raw)?raw.join("; "):raw;return(0,import_auth63.signinBindingMatches)(header2,pendingAuthId,hash,{secure:signinOverHttps(request2)})}function withCookie(output,cookie){return{...output,cookies:[...output.cookies??[],cookie]}}var import_auth63,import_utils183,SIGNIN_BINDING_REFUSED;var init_signin_binding_utils=__esm({"libs/sdk/src/auth/flows/signin-binding.utils.ts"(){"use strict";import_auth63=require("@frontmcp/auth");import_utils183=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_auth64,import_lazy_zod139,import_utils184,pkceChallengeSchema,codeChallengeMethodSchema,responseTypeSchema,safeRedirectUriSchema,oauthAuthorizeRequestSchema,anonymousAuthorizeRequestSchema,inputSchema40,stateSchema42,outputSchema39,plan47,name47,Stage47,OauthAuthorizeFlow;var init_oauth_authorize_flow=__esm({"libs/sdk/src/auth/flows/oauth.authorize.flow.ts"(){"use strict";import_auth64=require("@frontmcp/auth");import_lazy_zod139=require("@frontmcp/lazy-zod");import_utils184=require("@frontmcp/utils");init_common();init_flow_http_path();init_auth_ui();init_authorized_apps_utils();init_cimd();init_consent_tools_helper();init_federated_steps();init_required_providers_utils();init_signin_binding_utils();pkceChallengeSchema=import_lazy_zod139.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_zod139.internalZ.literal("S256",{message:'code_challenge_method must be "S256" (OAuth 2.1)'});responseTypeSchema=import_lazy_zod139.internalZ.literal("code",{message:'response_type must be "code" (OAuth 2.1)'});safeRedirectUriSchema=import_lazy_zod139.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_zod139.internalZ.object({response_type:responseTypeSchema,client_id:import_lazy_zod139.internalZ.string().min(1,"client_id is required"),redirect_uri:safeRedirectUriSchema,code_challenge:pkceChallengeSchema,code_challenge_method:codeChallengeMethodSchema.optional().default("S256"),scope:import_lazy_zod139.internalZ.string().optional(),state:import_lazy_zod139.internalZ.string().optional(),resource:import_lazy_zod139.internalZ.string().url().optional()});anonymousAuthorizeRequestSchema=import_lazy_zod139.internalZ.object({redirect_uri:safeRedirectUriSchema,state:import_lazy_zod139.internalZ.string().optional()});inputSchema40=httpInputSchema;stateSchema42=import_lazy_zod139.internalZ.object({isDefaultAuthProvider:import_lazy_zod139.internalZ.boolean().describe("No sign-in to run: no auth options, or public mode (the same configuration, written out)"),isOrchestrated:import_lazy_zod139.internalZ.boolean().describe("If FrontMcp is orchestrated (local oauth proxy, remote oauth proxy)"),allowAnonymous:import_lazy_zod139.internalZ.boolean().describe("Allow anonymous access, force orchestrated mode"),validatedRequest:oauthAuthorizeRequestSchema.optional(),rawRedirectUri:import_lazy_zod139.internalZ.string().optional(),rawState:import_lazy_zod139.internalZ.string().optional(),validationErrors:import_lazy_zod139.internalZ.array(import_lazy_zod139.internalZ.string()).optional(),pendingAuthId:import_lazy_zod139.internalZ.string().optional(),isIncrementalAuth:import_lazy_zod139.internalZ.boolean().default(false).describe("Whether this is an incremental auth request"),targetAppId:import_lazy_zod139.internalZ.string().optional().describe("Target app ID for incremental authorization"),targetToolId:import_lazy_zod139.internalZ.string().optional().describe("Target tool ID that triggered the incremental auth"),existingSessionId:import_lazy_zod139.internalZ.string().optional().describe("Existing session ID for incremental auth"),incrementalTicket:import_lazy_zod139.internalZ.custom().optional(),priorAuthorizedAppIds:import_lazy_zod139.internalZ.array(import_lazy_zod139.internalZ.string()).optional().describe("Prior authorized app IDs to carry forward"),requiresFederatedLogin:import_lazy_zod139.internalZ.boolean().default(false).describe("Whether this auth requires federated login UI"),requiresConsent:import_lazy_zod139.internalZ.boolean().default(false).describe("Whether consent flow is enabled"),isCimdClient:import_lazy_zod139.internalZ.boolean().default(false).describe("Whether client_id is a CIMD URL"),cimdMetadata:import_auth58.clientMetadataDocumentSchema.optional().describe("CIMD metadata document for the client")});outputSchema39=import_lazy_zod139.internalZ.union([HttpRedirectSchema,HttpTextSchema,HttpHtmlSchema]);plan47={pre:["checkIpFilter","acquireQuota","parseInput","validateInput","checkIfAuthorized"],execute:["prepareAuthorizationRequest","buildAuthorizeOutput"],post:["validateOutput"]};name47="oauth:authorize";Stage47=StageHookOf(name47);OauthAuthorizeFlow=class extends FlowBase{resolveIssuer(request2){const auth=this.scope.auth;const issuer=request2&&auth?.issuerFor?auth.issuerFor(request2):auth?.issuer;return typeof issuer==="string"&&issuer.length>0?issuer:void 0}logger=this.scope.logger.child("OauthAuthorizeFlow");signinCookie;signinBindingHash;federatedStepRecord;respond(output){super.respond(this.signinCookie?withCookie(output,this.signinCookie):output)}async checkIpFilter(){enforceIpFilter(this.scope,this.tryGetContext()?.metadata.clientIp)}async acquireQuota(){await enforceGlobalRateLimit(this.scope,this.tryGetContext())}async parseInput(){const{metadata}=this.scope;const{request:request2}=this.rawInput;const rawRedirectUri=request2.query["redirect_uri"];const rawState=request2.query["state"];const incrementalTicket=this.verifyIncrementalTicket(request2.query["ticket"]);const isIncrementalAuth=incrementalTicket!==void 0;const targetAppId=incrementalTicket?.appId;const targetToolId=incrementalTicket?.toolId;let priorAuthorizedAppIds;if(incrementalTicket){priorAuthorizedAppIds=incrementalTicket.priorAppIds&&incrementalTicket.priorAppIds.length>0?Array.from(new Set(incrementalTicket.priorAppIds)):void 0}else{const appsParam=request2.query["apps"];if(appsParam){const ids=(Array.isArray(appsParam)?appsParam:[appsParam]).flatMap(v=>String(v).split(",")).map(v=>v.trim()).filter(Boolean);priorAuthorizedAppIds=ids.length>0?Array.from(new Set(ids)):void 0}}const existingSessionId=request2.query["session_id"];const isDefaultAuthProvider=!metadata.auth||(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_auth64.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_auth64.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_auth58.CimdService);const registry=this.scope.auth?.dcrClientRegistry;const redirectAllowlisted=!!registry?.hasRedirectAllowlist()&&registry.isRedirectUriAllowed(redirect_uri);let redirectVerified=redirectAllowlisted;let declaredClientScope;const isCimdClientId2=!!cimdService?.enabled&&cimdService.isCimdClientId(client_id);const redirectError=this.checkDcrRedirectAllowlist(redirect_uri);if(redirectError){this.logger.warn(`OAuth authorize: DCR allowlist rejection \u2014 ${redirectError}`);this.respondWithError([redirectError],void 0,rawState);return}if(cimdService&&!cimdService.enabled&&cimdService.isCimdClientId(client_id)&&!registry?.get?.(client_id)){const disabled=new import_auth58.CimdDisabledError;this.logger.warn(`OAuth authorize: CIMD client_id refused, CIMD is disabled: ${client_id}`);this.respondWithError([disabled.message],void 0,rawState);return}if(isCimdClientId2){try{this.logger.debug(`Processing CIMD client_id: ${client_id}`);const resolution=await cimdService.resolveClientMetadata(client_id);if(resolution.isCimdClient&&resolution.metadata){cimdService.validateRedirectUri(redirect_uri,resolution.metadata);redirectVerified=true;cimdService.assertSupportedClient(resolution.metadata);declaredClientScope=resolution.metadata.scope;this.state.set("isCimdClient",true);this.state.set("cimdMetadata",resolution.metadata);this.logger.info(`CIMD client validated: ${resolution.metadata.client_name} (${client_id})`,resolution.fromCache?" [from cache]":"")}}catch(error){const detail=error instanceof Error?error.message:String(error);this.logger.warn(`CIMD validation failed for ${client_id}: ${detail}`);const publicMessage=error instanceof import_auth58.CimdError?error.getPublicMessage():"CIMD validation failed";this.respondWithError([publicMessage],void 0,rawState);return}}const registered=isCimdClientId2?void 0:registry?.get?.(client_id);if(registered){if(!registered.redirect_uris.includes(redirect_uri)){this.logger.warn(`OAuth authorize: redirect_uri "${redirect_uri}" not registered for client "${client_id}"`);this.respondWithError(["redirect_uri is not registered for this client"],void 0,rawState);return}redirectVerified=true;declaredClientScope=registered.scope}const clientIdError=isCimdClientId2?void 0:this.checkDcrClientIdAllowlist(client_id);if(clientIdError){this.logger.warn(`OAuth authorize: DCR allowlist rejection \u2014 ${clientIdError}`);this.respondWithError([clientIdError],redirectVerified?redirect_uri:void 0,rawState,"unauthorized_client");return}if(!isCimdClientId2&&!registered&&authOptions?.requireRegisteredClients!==false){this.logger.warn(`OAuth authorize: rejecting unregistered client_id "${client_id}" (requireRegisteredClients)`);this.respondWithError(["Unknown client_id: register the client (DCR / pre-registered) or use a CIMD client-id URL"],void 0,rawState);return}if(declaredClientScope!==void 0){const clientScopes=declaredClientScope.split(" ");const clientGrantedScopes=grantedScopes.filter(scope=>clientScopes.includes(scope));validatedRequest={...validatedRequest,scope:clientGrantedScopes.length>0?clientGrantedScopes.join(" "):void 0};this.state.set("validatedRequest",validatedRequest)}const canonicalResource=computeResource(request2,this.scope.entryPath,this.scope.routeBase);if(!validatedRequest.resource){this.state.set("validatedRequest",{...validatedRequest,resource:canonicalResource})}else if(!resourceUriMatches(validatedRequest.resource,canonicalResource)){this.logger.warn(`OAuth authorize: resource mismatch. Provided: ${validatedRequest.resource}, canonical: ${canonicalResource}`);this.respondWithError(["Invalid resource parameter: does not match server resource URI"],redirectVerified?redirect_uri:void 0,rawState);return}}verifyIncrementalTicket(raw){const token=typeof raw==="string"?raw:Array.isArray(raw)?raw[0]:void 0;if(typeof token!=="string"||token.length===0)return void 0;const localAuth=this.scope.auth;const secret=localAuth?.signingSecret;if(!secret)return void 0;const payload=(0,import_auth64.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});const ticketProfile=effectiveIncremental&&incrementalTicket&&localAuth.signingSecret?(0,import_auth64.openIncrementalAuthTicketProfile)(incrementalTicket,localAuth.signingSecret):void 0;if(ticketProfile){pendingRecord.verifiedLogin=(0,import_auth64.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 clientDisplayName=cimdMetadata?.client_name??validatedRequest.client_id;if(isIncrementalAuth&&targetAppId){const apps=this.scope.apps.getApps();const app=apps.find(a=>a.metadata.id===targetAppId);const appName=app?.metadata?.name||targetAppId;const appDescription=app?.metadata?.description;const customIncremental=await this.tryRenderCustomSlot("incremental",pendingAuthId,common=>buildIncrementalState(common,{appId:targetAppId,appName,appDescription,toolId:targetToolId,redirectUri:validatedRequest.redirect_uri}),[validatedRequest.redirect_uri]);if(customIncremental)return;const incrementalAuthHtml=this.renderIncrementalAuthPage({pendingAuthId,appId:targetAppId,appName,appDescription,toolId:targetToolId,redirectUri:validatedRequest.redirect_uri});this.respond(this.htmlPage(incrementalAuthHtml));return}if(requiresFederatedLogin){if(this.federatedStepRecord){this.respond(renderFederatedStep(this.scope,this.federatedStepRecord,{clientName:clientDisplayName}));return}const providers=pickerProviders(this.scope);const hasConfiguredProviders=getConfiguredProviders(metadata.auth).length>0;const detection={providers:new Map(providers.map(p=>[p.id,p])),requiresOrchestration:true,parentProviderId:hasConfiguredProviders?void 0:"__parent__",childProviderIds:providers.filter(p=>!p.isParentProvider).map(p=>p.id),uniqueProviderCount:providers.length,validationErrors:[],warnings:[]};const customFederated=await this.tryRenderCustomSlot("federated",pendingAuthId,common=>buildFederatedState(common,{clientId:validatedRequest.client_id,clientName:clientDisplayName,redirectUri:validatedRequest.redirect_uri,providers:[...detection.providers.values()].map(toAuthProvider)}),[validatedRequest.redirect_uri,...providerAuthorizationEndpoints(this.scope,detection.providers.keys())]);if(customFederated)return;const federatedLoginHtml=this.renderFederatedLoginPage({pendingAuthId,detection,clientId:validatedRequest.client_id,redirectUri:validatedRequest.redirect_uri});this.respond(this.htmlPage(federatedLoginHtml));return}const customLogin=await this.tryRenderCustomSlot("login",pendingAuthId,common=>buildLoginState(common,{clientId:validatedRequest.client_id,clientName:clientDisplayName,scopes:validatedRequest.scope?validatedRequest.scope.split(" ").filter(Boolean):[],redirectUri:validatedRequest.redirect_uri,logoUri:cimdMetadata?.logo_uri}),[validatedRequest.redirect_uri]);if(customLogin)return;const loginHtml=this.renderLoginPage({pendingAuthId,clientId:validatedRequest.client_id,clientName:clientDisplayName,scope:validatedRequest.scope??"",redirectUri:validatedRequest.redirect_uri,logoUri:cimdMetadata?.logo_uri});const auth=this.scope.metadata.auth;const customRender=!!(auth&&auth.mode==="local"&&auth.login?.render);this.respond(httpRespond.html(loginHtml,200,(0,import_auth64.builtInAuthPageHeaders)({csp:!customRender})))}async tryRenderCustomSlot(slot,pendingAuthId,buildState,formTargets){const authUi=this.scope.authUi;if(!authUi||!authUi.hasSlot(slot))return false;const csrfToken=authUi.mintCsrf(pendingAuthId);try{const localAuth=this.scope.auth;const record=await localAuth.authorizationStore.getPendingAuthorization(pendingAuthId);if(record){record.authUiCsrf=csrfToken;await localAuth.authorizationStore.storePendingAuthorization(record)}}catch(err){this.logger.warn(`Failed to persist auth-UI CSRF on pending record: ${err instanceof Error?err.message:err}`)}const state=buildState({pendingAuthId,submitUrl:`${oauthBasePath(this.scope)}/oauth/callback`,extraUrl:authUiExtraPath(this.scope.fullPath),csrfToken,addedItems:authUi.getAddedItems(pendingAuthId)});const page2=buildAuthUiPage({registry:authUi,slot,state,fullPath:this.scope.fullPath,formTargets});if(!page2)return false;this.respond(httpRespond.html(page2.html,200,page2.headers));return true}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_auth64.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,authorizedAppIds:initialAuthorizedApps(this.scope.auth?.options,this.scope.apps.getApps(),this.state.priorAuthorizedAppIds)});const verifier=(0,import_utils184.generateCodeVerifier)();const challenge=(0,import_utils184.sha256Base64url)(verifier);const pkce={verifier,challenge,method:"S256"};const providerState=`federated:${session.id}:${(0,import_utils184.randomUUID)()}`;(0,import_auth64.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_auth64.builtInAuthPageHeaders)())}checkDcrRedirectAllowlist(redirectUri){const registry=this.scope.auth?.dcrClientRegistry;if(registry?.hasRedirectAllowlist()&&!registry.isRedirectUriAllowed(redirectUri)){return`redirect_uri "${redirectUri}" is not in the configured allowlist`}return void 0}checkDcrClientIdAllowlist(clientId){const registry=this.scope.auth?.dcrClientRegistry;if(registry?.hasClientIdAllowlist()&&!registry.isClientIdAllowed(clientId)){return`client_id "${clientId}" is not in the configured allowlist`}return void 0}formatZodErrors(error){return error.issues.map(err=>{const path4=err.path.length>0?`${err.path.join(".")}: `:"";return`${path4}${err.message}`})}respondWithError(errors,redirectUri,state,error="invalid_request"){const errorDescription=errors.join("; ");if(redirectUri){const safe=safeRedirectUriSchema.safeParse(redirectUri);if(safe.success){const url=new URL(safe.data);url.searchParams.set("error",error);url.searchParams.set("error_description",errorDescription);if(state){url.searchParams.set("state",state)}const issuer=this.resolveIssuer(this.rawInput.request);if(issuer)url.searchParams.set("iss",issuer);this.respond(httpRespond.redirect(url.toString()));return}}this.respond(this.htmlPage(this.renderErrorPage(error,errorDescription),400))}renderLoginPage(params){const{pendingAuthId,clientId,clientName,scope,logoUri}=params;const callbackPath=`${oauthBasePath(this.scope)}/oauth/callback`;const auth=this.scope.metadata.auth;const login=auth&&auth.mode==="local"?auth.login:void 0;const ctx={clientId,clientName:clientName??clientId,logoUri,scopes:scope?scope.split(" ").filter(Boolean):[],pendingAuthId,callbackPath,fields:login?.fields??{}};return(0,import_auth64.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_auth64.buildIncrementalAuthPage)({app,toolId:toolId||"unknown tool",sessionHint:pendingAuthId,callbackPath})}renderFederatedLoginPage(params){const{pendingAuthId,detection,clientId}=params;const callbackPath=`${oauthBasePath(this.scope)}/oauth/callback`;const authOptions=this.scope.auth?.options;const required=requiredProviderIds(authOptions,this.scope.apps.getApps());const providers=[...detection.providers.values()].map(provider=>({providerId:provider.id,providerName:provider.id,providerUrl:provider.providerUrl,mode:provider.mode,appIds:provider.appIds.filter(id=>id!=="__parent__"),isPrimary:provider.isParentProvider,required:required.includes(provider.id)}));return(0,import_auth64.buildFederatedLoginPage)({providers,clientName:clientId,pendingAuthId,callbackPath,allowSkip:allowsSkippingApps(authOptions)})}renderErrorPage(error,description){return`<!DOCTYPE html>
@@ -466,7 +466,7 @@ __mountAuthPage(${exportName});`,mountNodeId:AUTH_MOUNT_ID,mountNodeInnerHtml:"<
466
466
  <a href="javascript:history.back()" class="retry-link">\u2190 Go Back</a>
467
467
  </div>
468
468
  </body>
469
- </html>`}htmlPage(markup,status=200){return httpRespond.html(markup,status,(0,import_auth70.builtInAuthPageHeaders)())}getStateValidation(){const authOptions=this.scope.auth?.options;if(authOptions&&(0,import_auth13.isOrchestratedMode)(authOptions)){return authOptions.federatedAuth?.stateValidation??"strict"}return"strict"}};__decorateClass([Stage53("checkIpFilter")],OauthProviderCallbackFlow.prototype,"checkIpFilter",1);__decorateClass([Stage53("acquireQuota")],OauthProviderCallbackFlow.prototype,"acquireQuota",1);__decorateClass([Stage53("parseInput")],OauthProviderCallbackFlow.prototype,"parseInput",1);__decorateClass([Stage53("handleConsentSubmission")],OauthProviderCallbackFlow.prototype,"handleConsentSubmission",1);__decorateClass([Stage53("loadFederatedSession")],OauthProviderCallbackFlow.prototype,"loadFederatedSession",1);__decorateClass([Stage53("validateProviderCallback")],OauthProviderCallbackFlow.prototype,"validateProviderCallback",1);__decorateClass([Stage53("exchangeProviderCode")],OauthProviderCallbackFlow.prototype,"exchangeProviderCode",1);__decorateClass([Stage53("storeProviderTokens")],OauthProviderCallbackFlow.prototype,"storeProviderTokens",1);__decorateClass([Stage53("handleNextProviderOrComplete")],OauthProviderCallbackFlow.prototype,"handleNextProviderOrComplete",1);OauthProviderCallbackFlow=__decorateClass([FrontMcpFlow({name:name53,plan:plan53,inputSchema:inputSchema46,outputSchema:outputSchema45,access:"public",middleware:{path:"/oauth/provider/:providerId/callback"}})],OauthProviderCallbackFlow)}});var oauth_auth_ui_flow_exports={};__export(oauth_auth_ui_flow_exports,{OauthAuthUiExtraFlow:()=>OauthAuthUiExtraFlow,default:()=>OauthAuthUiExtraFlow});function timingSafeEqualStr4(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_lazy_zod146,extraInputSchema,extraStateSchema,extraOutputSchema,extraPlan,extraName,ExtraStage,OauthAuthUiExtraFlow;var init_oauth_auth_ui_flow=__esm({"libs/sdk/src/auth/flows/oauth.auth-ui.flow.ts"(){"use strict";import_lazy_zod146=require("@frontmcp/lazy-zod");init_common();extraInputSchema=httpInputSchema;extraStateSchema=import_lazy_zod146.internalZ.object({action:import_lazy_zod146.internalZ.string().optional(),pendingAuthId:import_lazy_zod146.internalZ.string().optional(),csrf:import_lazy_zod146.internalZ.string().optional(),payload:import_lazy_zod146.internalZ.record(import_lazy_zod146.internalZ.string(),import_lazy_zod146.internalZ.unknown()).optional()});extraOutputSchema=HttpJsonSchema;extraPlan={pre:["checkIpFilter","acquireQuota","parseInput"],execute:["handleExtra"]};extraName="oauth:auth-ui-extra";ExtraStage=StageHookOf(extraName);OauthAuthUiExtraFlow=class extends FlowBase{logger=this.scope.logger.child("OauthAuthUiExtraFlow");async checkIpFilter(){enforceIpFilter(this.scope,this.tryGetContext()?.metadata.clientIp)}async acquireQuota(){await enforceGlobalRateLimit(this.scope,this.tryGetContext())}async parseInput(){const{request:request2}=this.rawInput;const body=request2.body&&typeof request2.body==="object"?request2.body:{};const query=request2.query??{};const readStr=key=>{const v=body[key]??query[key];return typeof v==="string"?v:Array.isArray(v)&&typeof v[0]==="string"?v[0]:void 0};const reserved=new Set(["action","pending_auth_id","csrf","__proto__","constructor","prototype"]);const payload=Object.create(null);for(const[k,v]of Object.entries(body)){if(!reserved.has(k))payload[k]=v}this.state.set({action:readStr("action"),pendingAuthId:readStr("pending_auth_id"),csrf:readStr("csrf"),payload})}async handleExtra(){const{action,pendingAuthId,csrf,payload}=this.state;const authUi=this.scope.authUi;if(!authUi||!authUi.hasExtras()){this.respond(httpRespond.json({ok:false,error:"No extras are configured."},{status:404}));return}if(!action||!authUi.hasExtra(action)){this.respond(httpRespond.json({ok:false,error:`Unknown extra "${action??""}".`},{status:400}));return}const ok=await this.verifyExtraCsrf(pendingAuthId,csrf,authUi);if(!ok){this.logger.warn("Auth-UI extra CSRF mismatch");this.respond(httpRespond.json({ok:false,error:"Invalid or missing CSRF token"},{status:400}));return}const result=await authUi.runExtra(action,pendingAuthId,payload??{});this.respond(httpRespond.json(result,{status:result.ok?200:400}))}async verifyExtraCsrf(pendingAuthId,submitted,authUi){if(!pendingAuthId||!submitted)return false;try{const localAuth=this.scope.auth;const record=await localAuth.authorizationStore.getPendingAuthorization(pendingAuthId);if(record?.authUiCsrf){return timingSafeEqualStr4(record.authUiCsrf,submitted)}}catch{}return authUi.verifyCsrf(pendingAuthId,submitted)}};__decorateClass([ExtraStage("checkIpFilter")],OauthAuthUiExtraFlow.prototype,"checkIpFilter",1);__decorateClass([ExtraStage("acquireQuota")],OauthAuthUiExtraFlow.prototype,"acquireQuota",1);__decorateClass([ExtraStage("parseInput")],OauthAuthUiExtraFlow.prototype,"parseInput",1);__decorateClass([ExtraStage("handleExtra")],OauthAuthUiExtraFlow.prototype,"handleExtra",1);OauthAuthUiExtraFlow=__decorateClass([FrontMcpFlow({name:extraName,plan:extraPlan,inputSchema:extraInputSchema,outputSchema:extraOutputSchema,access:"public",middleware:{method:"POST",path:"/oauth/ui/extra"}})],OauthAuthUiExtraFlow)}});var oauthFlows;var init_oauth_flows=__esm({"libs/sdk/src/auth/flows/oauth-flows.ts"(){"use strict";init_deferred_flow();oauthFlows=[deferredFlow({name:"oauth:authorize",middleware:{method:"GET",path:"/oauth/authorize"}},()=>Promise.resolve().then(()=>(init_oauth_authorize_flow(),oauth_authorize_flow_exports)).then(flow=>flow.OauthAuthorizeFlow)),deferredFlow({name:"oauth:token",middleware:{method:"POST",path:"/oauth/token"}},()=>Promise.resolve().then(()=>(init_oauth_token_flow(),oauth_token_flow_exports)).then(flow=>flow.OauthTokenFlow)),deferredFlow({name:"oauth:userinfo",middleware:{method:"GET",path:"/oauth/userinfo"}},()=>Promise.resolve().then(()=>(init_oauth_userinfo_flow(),oauth_userinfo_flow_exports)).then(flow=>flow.OauthUserInfoFlow)),deferredFlow({name:"oauth:callback",middleware:{path:"/oauth/callback"}},()=>Promise.resolve().then(()=>(init_oauth_callback_flow(),oauth_callback_flow_exports)).then(flow=>flow.OauthCallbackFlow)),deferredFlow({name:"oauth:connect",middleware:{path:"/oauth/connect"}},()=>Promise.resolve().then(()=>(init_oauth_connect_flow(),oauth_connect_flow_exports)).then(flow=>flow.OauthConnectFlow)),deferredFlow({name:"oauth:register",middleware:{method:"POST",path:"/oauth/register"}},()=>Promise.resolve().then(()=>(init_oauth_register_flow(),oauth_register_flow_exports)).then(flow=>flow.OauthRegisterFlow)),deferredFlow({name:"oauth:provider-callback",middleware:{path:"/oauth/provider/:providerId/callback"}},()=>Promise.resolve().then(()=>(init_oauth_provider_callback_flow(),oauth_provider_callback_flow_exports)).then(flow=>flow.OauthProviderCallbackFlow)),deferredFlow({name:"oauth:auth-ui-extra",middleware:{method:"POST",path:"/oauth/ui/extra"}},()=>Promise.resolve().then(()=>(init_oauth_auth_ui_flow(),oauth_auth_ui_flow_exports)).then(flow=>flow.OauthAuthUiExtraFlow))]}});var import_reflect_metadata26,import_auth71,import_lazy_zod147,inputSchema47,stateSchema49,outputSchema46,plan54,name54,Stage54,WellKnownJwksFlow;var init_well_known_jwks_flow=__esm({"libs/sdk/src/auth/flows/well-known.jwks.flow.ts"(){"use strict";init_common();import_reflect_metadata26=require("reflect-metadata");import_auth71=require("@frontmcp/auth");import_lazy_zod147=require("@frontmcp/lazy-zod");init_auth_internal_errors();inputSchema47=httpInputSchema;stateSchema49=import_lazy_zod147.internalZ.object({isOrchestrated:import_lazy_zod147.internalZ.boolean()});outputSchema46=import_lazy_zod147.internalZ.union([HttpJsonSchema,HttpTextSchema,HttpRedirectSchema]);plan54={pre:["checkIpFilter","acquireQuota","parseInput","validateInput"],execute:["collectData"]};name54="well-known.jwks";Stage54=StageHookOf(name54);WellKnownJwksFlow=class extends FlowBase{static canActivate(request2,scope){return makeWellKnownPaths("jwks.json",scope.entryPath,scope.routeBase).has(request2.path)}async checkIpFilter(){enforceIpFilter(this.scope,this.tryGetContext()?.metadata.clientIp)}async acquireQuota(){await enforceGlobalRateLimit(this.scope,this.tryGetContext())}async parseInput(){this.state.set({isOrchestrated:false})}async collectData(){const{isOrchestrated}=this.state.required;const jwksSvc=this.get(import_auth71.JwksService);if(isOrchestrated){const keysDoc=await jwksSvc.getPublicJwks();if(!keysDoc?.keys||!Array.isArray(keysDoc.keys)){throw new import_auth16.OrchestratorJwksNotAvailableError}this.respond(httpRespond.json(keysDoc));return}const options=this.scope.auth.options;if(options&&(0,import_auth13.isTransparentMode)(options)){if(options.providerConfig?.jwks&&options.providerConfig.jwks.keys.length){this.respond(httpRespond.json(options.providerConfig.jwks))}else{const location=options.providerConfig?.jwksUri??`${options.provider}/.well-known/jwks.json`;this.respond(httpRespond.redirect(location))}}else{const keysDoc=await jwksSvc.getPublicJwks();if(keysDoc?.keys&&Array.isArray(keysDoc.keys)){this.respond(httpRespond.json(keysDoc))}else{this.respond(httpRespond.notFound())}}}};__decorateClass([Stage54("checkIpFilter")],WellKnownJwksFlow.prototype,"checkIpFilter",1);__decorateClass([Stage54("acquireQuota")],WellKnownJwksFlow.prototype,"acquireQuota",1);__decorateClass([Stage54("parseInput")],WellKnownJwksFlow.prototype,"parseInput",1);__decorateClass([Stage54("collectData")],WellKnownJwksFlow.prototype,"collectData",1);WellKnownJwksFlow=__decorateClass([FrontMcpFlow({name:name54,plan:plan54,inputSchema:inputSchema47,outputSchema:outputSchema46,access:"public",middleware:{method:"GET"}})],WellKnownJwksFlow)}});function resolveDcrEnabled(auth){if(auth&&(0,import_auth13.isLocalMode)(auth)){const dcr=auth.dcr;if(dcr&&typeof dcr.enabled==="boolean"){return dcr.enabled}}return!(0,import_utils189.isProduction)()}var import_reflect_metadata27,import_auth72,import_lazy_zod148,import_utils189,inputSchema48,tokenEndpointAuthMethodSchema,AuthServerMetadataSchema,outputSchema47,wellKnownAsStateSchema,wellKnownAsPlan,name55,Stage55,WellKnownAsFlow;var init_well_known_oauth_authorization_server_flow=__esm({"libs/sdk/src/auth/flows/well-known.oauth-authorization-server.flow.ts"(){"use strict";import_reflect_metadata27=require("reflect-metadata");import_auth72=require("@frontmcp/auth");import_lazy_zod148=require("@frontmcp/lazy-zod");import_utils189=require("@frontmcp/utils");init_common();init_sdk_errors();init_flow_http_path();inputSchema48=httpInputSchema;tokenEndpointAuthMethodSchema=import_lazy_zod148.internalZ.enum(["none","client_secret_basic","client_secret_post","private_key_jwt"]);AuthServerMetadataSchema=import_lazy_zod148.internalZ.object({kind:import_lazy_zod148.internalZ.literal("json"),status:import_lazy_zod148.internalZ.literal(200),contentType:import_lazy_zod148.internalZ.literal("application/json; charset=utf-8"),headers:import_lazy_zod148.internalZ.record(import_lazy_zod148.internalZ.string(),import_lazy_zod148.internalZ.string()).optional(),body:import_lazy_zod148.internalZ.object({issuer:import_lazy_zod148.internalZ.string().min(1),authorization_endpoint:import_lazy_zod148.internalZ.string().min(1),token_endpoint:import_lazy_zod148.internalZ.string().min(1),userinfo_endpoint:import_lazy_zod148.internalZ.string().min(1).optional(),jwks_uri:import_lazy_zod148.internalZ.string().min(1),registration_endpoint:import_lazy_zod148.internalZ.string().min(1).optional(),token_endpoint_auth_methods_supported:import_lazy_zod148.internalZ.array(tokenEndpointAuthMethodSchema).optional(),token_endpoint_auth_signing_alg_values_supported:import_lazy_zod148.internalZ.array(import_lazy_zod148.internalZ.string()).optional(),response_types_supported:import_lazy_zod148.internalZ.array(import_lazy_zod148.internalZ.enum(["code"])).default(["code"]),grant_types_supported:import_lazy_zod148.internalZ.array(import_lazy_zod148.internalZ.enum(["authorization_code","refresh_token"])).default(["authorization_code","refresh_token"]),scopes_supported:import_lazy_zod148.internalZ.array(import_lazy_zod148.internalZ.string()).default(["openid","profile","email"]),code_challenge_methods_supported:import_lazy_zod148.internalZ.array(import_lazy_zod148.internalZ.enum(["S256"])).default(["S256"])}).passthrough()});outputSchema47=import_lazy_zod148.internalZ.union([AuthServerMetadataSchema,HttpRedirectSchema,HttpTextSchema]);wellKnownAsStateSchema=import_lazy_zod148.internalZ.object({baseUrl:import_lazy_zod148.internalZ.string().min(1),issuer:import_lazy_zod148.internalZ.string().min(1).optional(),oauthBaseUrl:import_lazy_zod148.internalZ.string().min(1),scopesSupported:import_lazy_zod148.internalZ.array(import_lazy_zod148.internalZ.string()).default(["openid","profile","email"]),tokenEndpointAuthMethods:import_lazy_zod148.internalZ.array(tokenEndpointAuthMethodSchema).default(["none","client_secret_basic","client_secret_post"]),dcrEnabled:import_lazy_zod148.internalZ.boolean().default(true),isOrchestrated:import_lazy_zod148.internalZ.boolean(),cimdEnabled:import_lazy_zod148.internalZ.boolean().default(true)});wellKnownAsPlan={pre:["checkIpFilter","acquireQuota","parseInput"],execute:["collectData"]};name55="well-known.oauth-authorization-server";Stage55=StageHookOf(name55);WellKnownAsFlow=class extends FlowBase{static canActivate(request2,scope){return makeWellKnownPaths("oauth-authorization-server",scope.entryPath,scope.routeBase).has(request2.path)}async checkIpFilter(){enforceIpFilter(this.scope,this.tryGetContext()?.metadata.clientIp)}async acquireQuota(){await enforceGlobalRateLimit(this.scope,this.tryGetContext())}async parseInput(){const{request:request2}=this.rawInput;if(!request2)throw new FlowInputMissingError("request","well-known:oauth-authorization-server");const{metadata}=this.scope;const baseUrl=getRequestBaseUrl(request2,this.scope.entryPath);const issuer=this.scope.auth?.issuerFor?.(request2);const oauthBaseUrl=getRequestBaseUrl(request2,oauthBasePath(this.scope));let cimdEnabled=true;if(metadata.auth&&(0,import_auth13.isOrchestratedMode)(metadata.auth)){cimdEnabled=metadata.auth.cimd?.enabled??true}this.state.set(wellKnownAsStateSchema.parse({baseUrl,issuer,oauthBaseUrl,scopesSupported:metadata.auth&&(0,import_auth13.isOrchestratedMode)(metadata.auth)?(0,import_auth72.advertisedScopes)(metadata.auth.allowedScopes):[],tokenEndpointAuthMethods:cimdEnabled?["none","client_secret_basic","client_secret_post","private_key_jwt"]:["none","client_secret_basic","client_secret_post"],dcrEnabled:resolveDcrEnabled(metadata.auth),isOrchestrated:metadata.auth?(0,import_auth13.isOrchestratedMode)(metadata.auth):false,cimdEnabled}))}async collectData(){const{issuer}=this.state;const{baseUrl,oauthBaseUrl,scopesSupported,tokenEndpointAuthMethods,dcrEnabled,isOrchestrated,cimdEnabled}=this.state.required;if(isOrchestrated){const baseIssuer=issuer??baseUrl;this.respond({kind:"json",contentType:"application/json; charset=utf-8",status:200,headers:{"cache-control":"no-store"},body:{issuer:baseIssuer,authorization_endpoint:`${oauthBaseUrl}/oauth/authorize`,token_endpoint:`${oauthBaseUrl}/oauth/token`,userinfo_endpoint:`${oauthBaseUrl}/oauth/userinfo`,jwks_uri:`${baseIssuer}/.well-known/jwks.json`,...dcrEnabled?{registration_endpoint:`${oauthBaseUrl}/oauth/register`}:{},token_endpoint_auth_methods_supported:tokenEndpointAuthMethods,...tokenEndpointAuthMethods.includes("private_key_jwt")?{token_endpoint_auth_signing_alg_values_supported:import_auth72.CLIENT_ASSERTION_SIGNING_ALGORITHMS}:{},response_types_supported:["code"],grant_types_supported:["authorization_code","refresh_token"],scopes_supported:scopesSupported,code_challenge_methods_supported:["S256"],authorization_response_iss_parameter_supported:true,client_id_metadata_document_supported:cimdEnabled}});return}const authOptions=this.scope.auth?.options;if(!authOptions||!(0,import_auth13.isTransparentMode)(authOptions)){this.respond(httpRespond.notFound());return}this.respond(httpRespond.redirect(`${(0,import_auth72.trimSlash)(this.scope.auth.issuer)}/.well-known/oauth-authorization-server`))}};__decorateClass([Stage55("checkIpFilter")],WellKnownAsFlow.prototype,"checkIpFilter",1);__decorateClass([Stage55("acquireQuota")],WellKnownAsFlow.prototype,"acquireQuota",1);__decorateClass([Stage55("parseInput")],WellKnownAsFlow.prototype,"parseInput",1);__decorateClass([Stage55("collectData")],WellKnownAsFlow.prototype,"collectData",1);WellKnownAsFlow=__decorateClass([FrontMcpFlow({name:name55,plan:wellKnownAsPlan,inputSchema:inputSchema48,outputSchema:outputSchema47,access:"public",middleware:{method:"GET"}})],WellKnownAsFlow)}});var import_reflect_metadata28,import_auth73,import_lazy_zod149,inputSchema49,stateSchema50,outputSchema48,plan55,name56,Stage56,WellKnownPrmFlow;var init_well_known_prm_flow=__esm({"libs/sdk/src/auth/flows/well-known.prm.flow.ts"(){"use strict";import_reflect_metadata28=require("reflect-metadata");import_auth73=require("@frontmcp/auth");import_lazy_zod149=require("@frontmcp/lazy-zod");init_common();init_sdk_errors();inputSchema49=httpInputSchema;stateSchema50=import_lazy_zod149.internalZ.object({resource:import_lazy_zod149.internalZ.string().min(1),baseUrl:import_lazy_zod149.internalZ.string().min(1),authorizationServer:import_lazy_zod149.internalZ.string().min(1).optional(),scopesSupported:import_lazy_zod149.internalZ.array(import_lazy_zod149.internalZ.string()),isOrchestrated:import_lazy_zod149.internalZ.boolean()});outputSchema48=HttpJsonSchema.extend({body:import_lazy_zod149.internalZ.object({resource:import_lazy_zod149.internalZ.string().min(1),authorization_servers:import_lazy_zod149.internalZ.array(import_lazy_zod149.internalZ.string().min(1)).min(1).optional(),scopes_supported:import_lazy_zod149.internalZ.array(import_lazy_zod149.internalZ.string()).optional(),bearer_methods_supported:import_lazy_zod149.internalZ.array(import_lazy_zod149.internalZ.string()).default(["header"])}).passthrough()});plan55={pre:["checkIpFilter","acquireQuota","parseInput"],execute:["collectData"],post:["validateOutput"]};name56="well-known.oauth-protected-resource";Stage56=StageHookOf(name56);WellKnownPrmFlow=class extends FlowBase{static canActivate(request2,scope){return makeWellKnownPaths("oauth-protected-resource",scope.entryPath,scope.routeBase).has(request2.path)}async checkIpFilter(){enforceIpFilter(this.scope,this.tryGetContext()?.metadata.clientIp)}async acquireQuota(){await enforceGlobalRateLimit(this.scope,this.tryGetContext())}async parseInput(){const{request:request2}=this.rawInput;const scope=this.scope;if(!request2)throw new FlowInputMissingError("request","well-known:prm");const resource=computeResource(request2,scope.entryPath,scope.routeBase);const baseUrl=getRequestBaseUrl(request2,scope.entryPath);const authOptions=scope.auth?.options??scope.metadata.auth;const transparentProvider=authOptions?.mode==="transparent"?authOptions.provider:void 0;const authorizationServer=transparentProvider??scope.auth?.issuerFor?.(request2)??baseUrl;const granted=(0,import_auth73.resourceScopesFor)(authOptions);const orchestrated=authOptions?.mode==="local"||authOptions?.mode==="remote";const hasAuthorizationServer=authOptions?.mode!=="public"&&authOptions?.mode!=="static";const scopesSupported=orchestrated?granted:[...new Set([...granted,...scope.getAllSupportedScopes()])];this.state.set(stateSchema50.parse({resource,baseUrl,authorizationServer:hasAuthorizationServer?authorizationServer:void 0,scopesSupported,isOrchestrated:false}))}async collectData(){const{resource,scopesSupported,isOrchestrated}=this.state.required;const{authorizationServer}=this.state;const scopes=scopesSupported.length>0?{scopes_supported:scopesSupported}:{};const authorizationServers=authorizationServer?{authorization_servers:[authorizationServer]}:{};if(isOrchestrated){this.respond({kind:"json",contentType:"application/json; charset=utf-8",status:200,headers:{"cache-control":"no-store"},body:{resource,...authorizationServers,...scopes,bearer_methods_supported:["header"]}});return}this.respond({kind:"json",status:200,contentType:"application/json; charset=utf-8",headers:{"cache-control":"no-store"},body:{resource,...authorizationServers,...scopes,bearer_methods_supported:["header"]}})}};__decorateClass([Stage56("checkIpFilter")],WellKnownPrmFlow.prototype,"checkIpFilter",1);__decorateClass([Stage56("acquireQuota")],WellKnownPrmFlow.prototype,"acquireQuota",1);__decorateClass([Stage56("parseInput")],WellKnownPrmFlow.prototype,"parseInput",1);__decorateClass([Stage56("collectData")],WellKnownPrmFlow.prototype,"collectData",1);WellKnownPrmFlow=__decorateClass([FrontMcpFlow({name:name56,plan:plan55,inputSchema:inputSchema49,outputSchema:outputSchema48,access:"public",middleware:{method:"GET"}})],WellKnownPrmFlow)}});function resolveRequestSessionId(ctx){const identity=sessionScopeIdentity(ctx);if(identity)return identity;throw new SessionIdentityRequiredError("The secure store's session scope")}function createSecureStoreProviders(opts){const{backend,scope,ttlMs}=opts;const backendProvider={provide:SECURE_STORE_BACKEND,useValue:backend,scope:import_di50.ProviderScope.GLOBAL,name:"SecureStoreBackend"};const accessorProvider={provide:import_auth74.SECURE_STORE_ACCESSOR,inject:()=>[FRONTMCP_CONTEXT,FrontMcpLogger],useFactory:(ctx,logger)=>new import_auth74.SecureStoreAccessorImpl({backend,scope,resolveSub:()=>resolveRequestSub(ctx),resolveSessionId:()=>resolveRequestSessionId(ctx),ttlMs,logger:logger.child("SecureStore")}),scope:import_di50.ProviderScope.CONTEXT,name:"SecureStoreAccessor"};return[backendProvider,accessorProvider]}var import_auth74,import_di50,SECURE_STORE_BACKEND;var init_secure_store_providers=__esm({"libs/sdk/src/auth/secure-store/secure-store.providers.ts"(){"use strict";import_auth74=require("@frontmcp/auth");import_di50=require("@frontmcp/di");init_common();init_frontmcp_context_provider();init_session_identity_required_error();init_credentials_providers();init_session_scope_identity();SECURE_STORE_BACKEND=Symbol.for("frontmcp:SECURE_STORE_BACKEND")}});var import_auth75,secureStoreContextExtension;var init_secure_store_context_extension=__esm({"libs/sdk/src/auth/secure-store/secure-store.context-extension.ts"(){"use strict";import_auth75=require("@frontmcp/auth");secureStoreContextExtension={property:"secureStore",token:import_auth75.SECURE_STORE_ACCESSOR,errorMessage:"The secure store is not available. Ensure the server uses auth mode 'local' (or 'remote'); the secure store is enabled automatically there."}}});var init_secure_store=__esm({"libs/sdk/src/auth/secure-store/index.ts"(){"use strict";init_secure_store_providers()}});function loadJose(){jose??=importWithRequireFallback(()=>import("jose"),()=>require("jose")).catch(error=>{jose=void 0;throw error});return jose}function getDefaultNoAuthSecret(){if(!defaultNoAuthSecret){defaultNoAuthSecret=(0,import_utils190.randomBytes)(32)}return defaultNoAuthSecret}function normalizeIssuer(value){return value.replace(/\/+$/,"")}function validateAuthorizationIssuer(received,expected,additional=[]){if(received===void 0)return{ok:true};if(!expected)return{ok:true};const accepted=[expected,...additional].map(normalizeIssuer);if(!accepted.includes(normalizeIssuer(received))){return{ok:false,reason:`Authorization response issuer "${received}" does not match the configured issuer "${expected}"`}}return{ok:true}}function audienceMatchesResource(aud,expected){const audiences=typeof aud==="string"?[aud]:Array.isArray(aud)?aud:[];const resources=typeof expected==="string"?[expected]:expected;return audiences.some(value=>typeof value==="string"&&resources.some(resource=>resourceUriMatches(value,resource)))}function isUnsupportedOperation(error){return error instanceof import_utils190.StorageNotSupportedError}function originOf2(value){try{const origin=new URL(value).origin;return origin==="null"?void 0:origin}catch{return void 0}}var import_auth76,import_utils190,jose,MIN_HS256_SECRET_BYTES,defaultNoAuthSecret,RESERVED_JWT_CLAIMS,LocalPrimaryAuth;var init_instance_local_primary_auth=__esm({"libs/sdk/src/auth/instances/instance.local-primary-auth.ts"(){"use strict";import_auth76=require("@frontmcp/auth");import_utils190=require("@frontmcp/utils");init_common();init_auth2();init_context_extension();init_errors();init_dynamic_import_utils();init_cimd();init_credentials();init_credentials_context_extension();init_oauth_flows();init_session_verify_flow();init_well_known_jwks_flow();init_well_known_oauth_authorization_server_flow();init_well_known_prm_flow();init_secure_store();init_secure_store_context_extension();MIN_HS256_SECRET_BYTES=32;RESERVED_JWT_CLAIMS=new Set(["sub","iss","aud","exp","iat","nbf","jti","scope","email","name","picture","roles","consent","federated","authorized_apps"]);LocalPrimaryAuth=class extends FrontMcpAuth{constructor(scope,providers,options){super(options);this.scope=scope;this.providers=providers;this.logger=this.providers.getActiveScope().logger.child("LocalPrimaryAuth");this.port=this.providers.getActiveScope().metadata.http?.port??defaultHttpPort();this.host=(0,import_utils190.getEnv)("FRONTMCP_PUBLIC_HOST")?.trim()||"localhost";this.issuer=this.deriveIssuer(options);this.publicHostPinned=!!(0,import_utils190.getEnv)("FRONTMCP_PUBLIC_HOST")?.trim();const jwtSecret=(0,import_utils190.getEnv)("JWT_SECRET");const hasJwtSecret=!!jwtSecret?.trim();if(hasJwtSecret&&jwtSecret){const encoded=new TextEncoder().encode(jwtSecret);if(encoded.length<MIN_HS256_SECRET_BYTES){if((0,import_utils190.isProduction)())throw new import_auth16.JwtSecretWeakError(encoded.length);this.logger.warn(`JWT_SECRET is ${encoded.length} bytes; HS256 wants at least ${MIN_HS256_SECRET_BYTES} (RFC 7518). This is refused in production \u2014 generate one with \`openssl rand -hex 32\`.`)}this.secret=encoded}else if((0,import_utils190.isProduction)()&&(0,import_auth13.isOrchestratedMode)(options)){throw new import_auth16.JwtSecretRequiredError(options.mode)}else{if(!(0,import_auth13.isPublicMode)(options)){this.logger.warn("JWT_SECRET is not set; signing with a random per-process secret. Tokens will not survive a restart and will not verify across instances. Set JWT_SECRET for any deployment that mints tokens.")}this.secret=getDefaultNoAuthSecret()}this.tokenKeys=import_auth76.LocalTokenKeys.fromConfig(this.signingConfig(options),this.secret,(0,import_auth13.isPublicMode)(options)?"auth":"auth.local");this.jwks.setPublicJwks(this.tokenKeys.publicJwks);this.tokenStorage=this.readTokenStorage(options);this.authorizationStoreImpl=new import_auth76.InMemoryAuthorizationStore;this.federatedSessionStoreImpl=new import_auth76.InMemoryFederatedAuthSessionStore;this.orchestratedTokenStoreImpl=new import_auth76.InMemoryOrchestratedTokenStore({encryptionKey:this.secret,refreshSkewMs:this.providerRefreshSkewMs()});this.consentStoreImpl=new import_auth76.InMemoryConsentStore;this.scope.onDispose(()=>this.releaseResources());this.dcrClientRegistryImpl=new import_auth76.DcrClientRegistry(this.getDcrConfig()??{});if((0,import_auth13.isOrchestratedMode)(options)){const cimdConfig=options.cimd;this.cimdService=new import_auth58.CimdService(this.logger,cimdConfig)}this.ready=this.initialize()}scope;providers;host;port;issuer;publicHostPinned;keys=[];secret;logger;jwks=new import_auth76.JwksService;tokenKeys;cimdService;tokenStorage;authorizationStoreImpl;federatedSessionStoreImpl;orchestratedTokenStoreImpl;consentStoreImpl;dcrClientRegistryImpl;storageAdapter;storageClosers=[];ticketReplayStorage;credentialVaultImpl;get credentialVault(){return this.credentialVaultImpl}secureStoreBackendImpl;get secureStoreBackend(){return this.secureStoreBackendImpl}get authorizationStore(){return this.authorizationStoreImpl}get federatedSessionStore(){return this.federatedSessionStoreImpl}get orchestratedTokenStore(){return this.orchestratedTokenStoreImpl}get consentStore(){return this.consentStoreImpl}get dcrClientRegistry(){return this.dcrClientRegistryImpl}getDcrConfig(){if((0,import_auth13.isLocalMode)(this.options)){return this.options.dcr}return void 0}isDcrEnabled(){const dcr=this.getDcrConfig();if(dcr&&typeof dcr.enabled==="boolean"){return dcr.enabled}return!(0,import_utils190.isProduction)()}providerConfigs=new Map;providerRenewals=new Map;remoteProviderIdImpl;get remoteProviderId(){return this.remoteProviderIdImpl}accessTokenTtlSeconds=3600;refreshTokenTtlSeconds=30*24*3600;deriveIssuer(options){return this.configuredIssuer(options)??`http://${this.host}:${this.port}${this.scope.fullPath}`}signingConfig(options){if((0,import_auth13.isPublicMode)(options))return{signKey:options.signKey,jwks:options.jwks};return(0,import_auth13.isOrchestratedMode)(options)?options.local??{}:{}}configuredIssuer(options){const configured=(0,import_auth13.isPublicMode)(options)?options.issuer:(0,import_auth13.isOrchestratedMode)(options)?options.local?.issuer:void 0;return configured===void 0?void 0:normalizeIssuer(configured)}issuerFor(request2){const configured=this.configuredIssuer(this.options);if(configured!==void 0)return configured;const pinned=getPinnedPublicUrl();if(pinned!==void 0){return request2?computeIssuer(request2,this.scope.entryPath,this.scope.routeBase):`${pinned}${this.scope.fullPath}`}if(this.publicHostPinned||!request2)return this.issuer;return computeIssuer(request2,this.scope.entryPath,this.scope.routeBase)}acceptedIssuersFor(request2){const issuer=this.issuerFor(request2);const options=this.options;const followsRequest=!!request2&&this.configuredIssuer(options)===void 0&&getPinnedPublicUrl()===void 0&&!this.publicHostPinned;if(!followsRequest||!(0,import_auth13.isOrchestratedMode)(options)||options.expectedAudience===void 0)return issuer;const listed=Array.isArray(options.expectedAudience)?options.expectedAudience:[options.expectedAudience];const accepted=new Set([issuer,this.issuer]);for(const audience of listed){const origin=originOf2(audience);if(origin)accepted.add(`${origin}${this.scope.fullPath}`)}return[...accepted]}readTokenStorage(options){if("tokenStorage"in options){return options.tokenStorage}return void 0}get tokenStorageAdapter(){return this.storageAdapter}async initializeStores(){if(!(0,import_auth76.isPersistentTokenStorage)(this.tokenStorage)){return}try{const adapter=await(0,import_auth76.createTokenStorageAdapter)(this.tokenStorage);this.storageAdapter=adapter;this.storageClosers.push(()=>adapter.disconnect());this.disposeInMemoryStores();this.authorizationStoreImpl=new import_auth76.StorageAuthorizationStore(adapter);this.federatedSessionStoreImpl=new import_auth76.StorageFederatedAuthSessionStore(adapter);this.orchestratedTokenStoreImpl=new import_auth76.StorageOrchestratedTokenStore(adapter,{encryptionKey:this.secret,refreshSkewMs:this.providerRefreshSkewMs()});this.consentStoreImpl=new import_auth76.StorageConsentStore(adapter);const backend=(0,import_auth76.isSqliteTokenStorage)(this.tokenStorage)?"sqlite":(0,import_auth76.isRedisTokenStorage)(this.tokenStorage)?"redis":"unknown";this.logger.info(`Token storage initialized with persistent backend: ${backend}`)}catch(err){this.logger.error("Failed to initialize persistent token storage",err);throw err}}get signingSecret(){return new TextDecoder().decode(this.secret)}async claimIncrementalTicket(jti,ttlMs){return this.claimOnce(`incremental-ticket:${jti}`,ttlMs)}async claimOnce(key,ttlMs){const nonce=(0,import_utils190.randomUUID)();const ttlSeconds=Math.max(1,Math.ceil(ttlMs/1e3));let storage=await this.getTicketReplayStorage();try{await storage.set(key,nonce,{ifNotExists:true,ttlSeconds})}catch(error){if(!isUnsupportedOperation(error)){this.logger.warn(`Replay guard unavailable: ${String(error)}`);return false}this.logger.warn("Replay guard: the configured storage has no conditional write; falling back to an in-memory guard (single use holds within this instance only).");storage=await this.useInMemoryTicketReplayStorage();try{await storage.set(key,nonce,{ifNotExists:true,ttlSeconds})}catch(fallbackError){this.logger.warn(`Replay guard unavailable: ${String(fallbackError)}`);return false}}try{return await storage.get(key)===nonce}catch(error){this.logger.warn(`Replay guard unavailable: ${String(error)}`);return false}}getTicketReplayStorage(){if(!this.ticketReplayStorage){if(this.storageAdapter){this.ticketReplayStorage=Promise.resolve(this.storageAdapter)}else{this.logger.debug("Replay guard is in-memory (no persistent tokenStorage configured); single use holds within this instance only.");this.ticketReplayStorage=this.useInMemoryTicketReplayStorage()}}return this.ticketReplayStorage}useInMemoryTicketReplayStorage(){const pending=(async()=>{const memory=new import_utils190.MemoryStorageAdapter;await memory.connect();this.storageClosers.push(()=>memory.disconnect());return memory})();this.ticketReplayStorage=pending;return pending}async initializeCredentialVault(){if((0,import_auth13.isPublicMode)(this.options)){return}let storage;if(this.storageAdapter){storage=this.storageAdapter}else{const memory=new import_utils190.MemoryStorageAdapter;await memory.connect();this.storageClosers.push(()=>memory.disconnect());storage=memory}const pepper=(0,import_utils190.getEnv)("VAULT_SECRET")??(0,import_utils190.getEnv)("JWT_SECRET")??void 0;this.credentialVaultImpl=new import_auth76.SessionCredentialVault({storage,pepper,logger:this.logger.child("SessionCredentialVault")});const signingSecret=this.signingSecret;const basePath=this.issuer;await this.providers.addDynamicProviders(createCredentialsProviders({vault:this.credentialVaultImpl,signingSecret,basePath}));installContextExtensions("credentials",[credentialsContextExtension]);this.logger.debug("SessionCredentialVault initialized; this.credentials enabled")}readSecureStoreConfig(){if("secureStore"in this.options){return this.options.secureStore}return void 0}async initializeSecureStore(){if((0,import_auth13.isPublicMode)(this.options)){return}const config=this.readSecureStoreConfig();const reuseAdapter=this.storageAdapter&&this.secureStoreSharesTokenStorage(config)?this.storageAdapter:void 0;const pepper=(0,import_utils190.getEnv)("VAULT_SECRET")??(0,import_utils190.getEnv)("JWT_SECRET")??new TextDecoder().decode(this.secret);const resolved=await(0,import_auth76.createSecureStore)({config,pepper,storage:reuseAdapter,logger:this.logger.child("SecureStore")});this.secureStoreBackendImpl=resolved.backend;if(resolved.close)this.storageClosers.push(resolved.close);await this.providers.addDynamicProviders(createSecureStoreProviders({backend:resolved.backend,scope:resolved.scope,ttlMs:resolved.ttlMs}));installContextExtensions("secureStore",[secureStoreContextExtension]);this.logger.debug(`SecureStore initialized (backing: ${resolved.kind}, scope: ${resolved.scope}); this.secureStore enabled`)}disposeInMemoryStores(){if(this.federatedSessionStoreImpl instanceof import_auth76.InMemoryFederatedAuthSessionStore){this.federatedSessionStoreImpl.dispose()}if(this.orchestratedTokenStoreImpl instanceof import_auth76.InMemoryOrchestratedTokenStore){this.orchestratedTokenStoreImpl.dispose()}}async releaseResources(){this.disposeInMemoryStores();await Promise.allSettled(this.storageClosers.splice(0).map(close=>close()))}secureStoreSharesTokenStorage(config){if(typeof config!=="object"||config===null)return false;if("sqlite"in config&&config.sqlite)return(0,import_auth76.isSqliteTokenStorage)(this.tokenStorage);if("redis"in config&&config.redis)return(0,import_auth76.isRedisTokenStorage)(this.tokenStorage);return false}async signAnonymousJwt(options={}){const{SignJWT}=await loadJose();const jwt=new SignJWT({sub:`anon:${(0,import_utils190.randomUUID)()}`,anonymous:true,scope:this.anonymousScopes().join(" ")}).setProtectedHeader(this.tokenKeys.protectedHeader()).setIssuedAt().setIssuer(options.issuer??this.issuer).setExpirationTime(`${this.anonymousTokenTtlSeconds()}s`).setJti((0,import_utils190.randomUUID)());if(options.audience)jwt.setAudience(options.audience);return jwt.sign(await this.tokenKeys.signingKey())}anonymousTokenTtlSeconds(){return(0,import_auth13.isPublicMode)(this.options)?this.options.sessionTtl??3600:86400}anonymousScopes(){const scopes=this.options.anonymousScopes;return Array.isArray(scopes)?scopes.filter(s=>typeof s==="string"):["anonymous"]}async verifyGatewayToken(token,requestBaseUrl,expectedAudience,expectedIssuer){try{const{payload,protectedHeader}=await this.tokenKeys.verify(token,{issuer:typeof expectedIssuer==="string"?expectedIssuer:expectedIssuer?[...expectedIssuer]:this.issuer,requiredClaims:["exp"]});if(expectedAudience!==void 0&&!audienceMatchesResource(payload.aud,expectedAudience)){return{ok:false,error:"Token audience does not match this resource"}}return{ok:true,issuer:payload.iss??requestBaseUrl,sub:payload.sub,header:protectedHeader,payload}}catch(err){const message=err instanceof Error?err.message:"verification_failed";return{ok:false,error:message}}}async signAccessToken(user,scopes,audience,consentMetadata,issuer){const claims3={sub:user.sub,scope:scopes.join(" ")};if(user.email)claims3["email"]=user.email;if(user.name)claims3["name"]=user.name;if(user.picture)claims3["picture"]=user.picture;if(user.roles)claims3["roles"]=user.roles;if(consentMetadata){if(consentMetadata.consentEnabled){claims3["consent"]={enabled:true,selectedTools:consentMetadata.selectedToolIds??[]}}if(consentMetadata.federatedLoginUsed){claims3["federated"]={enabled:true,selectedProviders:consentMetadata.selectedProviderIds??[],skippedProviders:consentMetadata.skippedProviderIds??[]}}if(consentMetadata.authorizedAppIds){claims3["authorized_apps"]=consentMetadata.authorizedAppIds}if(consentMetadata.customClaims){for(const[key,value]of Object.entries(consentMetadata.customClaims)){if(RESERVED_JWT_CLAIMS.has(key)){this.logger.warn(`Dropping reserved claim "${key}" from authenticate() custom claims`);continue}claims3[key]=value}}}const{SignJWT}=await loadJose();const jwt=new SignJWT(claims3).setProtectedHeader(this.tokenKeys.protectedHeader()).setIssuedAt().setIssuer(issuer??this.issuer).setExpirationTime(`${this.accessTokenTtlSeconds}s`).setJti((0,import_utils190.randomUUID)());if(audience){jwt.setAudience(audience)}return jwt.sign(await this.tokenKeys.signingKey())}async exchangeCode(code,clientId,redirectUri,codeVerifier,clientSecret,defaultAudience,issuer,clientAssertion){if(this.dcrClientRegistryImpl.verifyClientSecret(clientId,clientSecret)==="invalid"){this.logger.warn("Client authentication failed at token endpoint (authorization_code)");return{error:"invalid_client",error_description:"Client authentication failed"}}const declared=await this.checkDeclaredGrant(clientId,"authorization_code",clientAssertion);if("error"in declared)return declared;const codeRecord=await this.authorizationStore.getAuthorizationCode(code);if(!codeRecord){this.logger.warn(`Authorization code not found or expired: ${code.substring(0,8)}...`);return{error:"invalid_grant",error_description:"Authorization code is invalid or expired"}}if(codeRecord.used){this.logger.warn(`Authorization code already used: ${code.substring(0,8)}...`);if(codeRecord.issuedRefreshToken){try{await this.authorizationStore.revokeRefreshToken(codeRecord.issuedRefreshToken)}catch(err){this.logger.warn(`Failed to revoke refresh token on authorization-code replay: ${err}`)}}await this.authorizationStore.deleteAuthorizationCode(code);return{error:"invalid_grant",error_description:"Authorization code has already been used"}}if(codeRecord.clientId!==clientId){this.logger.warn(`Client ID mismatch: expected ${codeRecord.clientId}, got ${clientId}`);return{error:"invalid_grant",error_description:"Client ID does not match"}}if(codeRecord.redirectUri!==redirectUri){this.logger.warn(`Redirect URI mismatch`);return{error:"invalid_grant",error_description:"Redirect URI does not match"}}if(!(0,import_auth76.verifyPkce)(codeVerifier,codeRecord.pkce)){this.logger.warn(`PKCE verification failed`);return{error:"invalid_grant",error_description:"PKCE verification failed"}}await this.authorizationStore.markCodeUsed(code);const user={sub:codeRecord.userSub,email:codeRecord.userEmail,name:codeRecord.userName};const hasCustomClaims=!!codeRecord.customClaims&&Object.keys(codeRecord.customClaims).length>0;const hasAuthorizedApps=Array.isArray(codeRecord.authorizedAppIds);const consentMetadata=codeRecord.consentEnabled||codeRecord.federatedLoginUsed||hasCustomClaims||hasAuthorizedApps?{selectedToolIds:codeRecord.selectedToolIds,selectedProviderIds:codeRecord.selectedProviderIds,skippedProviderIds:codeRecord.skippedProviderIds,consentEnabled:codeRecord.consentEnabled,federatedLoginUsed:codeRecord.federatedLoginUsed,authorizedAppIds:codeRecord.authorizedAppIds,customClaims:codeRecord.customClaims}:void 0;const resource=codeRecord.resource??defaultAudience;const accessToken=await this.signAccessToken(user,codeRecord.scopes,resource,consentMetadata,issuer);let providerTokensId;if(codeRecord.pendingAuthId&&codeRecord.federatedLoginUsed){providerTokensId=await this.moveProviderTokens(`pending:${codeRecord.pendingAuthId}`,accessToken)}this.logger.info(`Tokens issued for user: ${user.sub}`);const tokens={access_token:accessToken,token_type:"Bearer",expires_in:this.accessTokenTtlSeconds,scope:codeRecord.scopes.join(" ")};if(declared.grantTypes&&!declared.grantTypes.includes("refresh_token"))return tokens;const refreshTokenRecord=this.authorizationStore.createRefreshTokenRecord({clientId,userSub:user.sub,scopes:codeRecord.scopes,resource,userEmail:user.email,userName:user.name,consentEnabled:codeRecord.consentEnabled,selectedToolIds:codeRecord.selectedToolIds,authorizedAppIds:codeRecord.authorizedAppIds,customClaims:codeRecord.customClaims,federatedLoginUsed:codeRecord.federatedLoginUsed,selectedProviderIds:codeRecord.selectedProviderIds,skippedProviderIds:codeRecord.skippedProviderIds,providerTokensId});await this.authorizationStore.storeRefreshToken(refreshTokenRecord);await this.authorizationStore.markCodeUsed(code,refreshTokenRecord.token);return{...tokens,refresh_token:refreshTokenRecord.token}}async checkDeclaredGrant(clientId,grantType,clientAssertion){let grantTypes;try{const cimd=this.cimdService;if(cimd?.enabled&&cimd.isCimdClientId(clientId)){const{metadata}=await cimd.resolveClientMetadata(clientId);if(metadata)cimd.assertSupportedClient(metadata);if(metadata?.token_endpoint_auth_method==="private_key_jwt"){await cimd.verifyClientAssertion(metadata,{audiences:[],...clientAssertion,claimOnce:(key,ttlMs)=>this.claimOnce(key,ttlMs)})}grantTypes=metadata?.grant_types}else{grantTypes=this.dcrClientRegistryImpl.get(clientId)?.grant_types}}catch(err){this.logger.warn(`Client metadata refused at token endpoint (${grantType}): ${err.message}`);return{error:"invalid_client",error_description:"Client authentication failed"}}if(grantTypes&&!grantTypes.includes(grantType)){this.logger.warn(`Client did not declare the ${grantType} grant`);return{error:"unauthorized_client",error_description:`This client may not use the ${grantType} grant`}}return{grantTypes}}async moveProviderTokens(fromAuthorizationId,accessToken){const toAuthorizationId=(0,import_auth76.deriveAuthorizationId)(accessToken);try{await this.orchestratedTokenStore.migrateTokens(fromAuthorizationId,toAuthorizationId);this.logger.info(`Migrated tokens from ${fromAuthorizationId} to ${toAuthorizationId}`);return toAuthorizationId}catch(err){this.logger.warn(`Failed to migrate tokens: ${err}`);return fromAuthorizationId}}async copyProviderTokens(fromAuthorizationId,accessToken){const store=this.orchestratedTokenStore;if(!store.copyTokens)return void 0;const toAuthorizationId=(0,import_auth76.deriveAuthorizationId)(accessToken);try{await store.copyTokens(fromAuthorizationId,toAuthorizationId);return toAuthorizationId}catch(err){this.logger.warn(`Failed to copy provider tokens: ${err}`);await this.discardProviderTokens(toAuthorizationId);return void 0}}async discardProviderTokens(authorizationId){const store=this.orchestratedTokenStore;try{const providerIds=await store.getProviderIds(authorizationId);await Promise.all(providerIds.map(providerId=>store.deleteTokens(authorizationId,providerId)))}catch(err){this.logger.warn(`Failed to discard provider tokens: ${err}`)}}async refreshAccessToken(refreshToken,clientId,clientSecret,defaultAudience,issuer,clientAssertion){if(this.dcrClientRegistryImpl.verifyClientSecret(clientId,clientSecret)==="invalid"){this.logger.warn("Client authentication failed at token endpoint (refresh_token)");return{error:"invalid_client",error_description:"Client authentication failed"}}const declared=await this.checkDeclaredGrant(clientId,"refresh_token",clientAssertion);if("error"in declared)return declared;const tokenRecord=await this.authorizationStore.getRefreshToken(refreshToken);if(!tokenRecord){this.logger.warn("Refresh token not found or expired");return{error:"invalid_grant",error_description:"Refresh token is invalid or expired"}}if(tokenRecord.clientId!==clientId){this.logger.warn("Client ID mismatch on refresh");return{error:"invalid_grant",error_description:"Client ID does not match"}}const user={sub:tokenRecord.userSub,email:tokenRecord.userEmail,name:tokenRecord.userName};const hasAuthorizedApps=Array.isArray(tokenRecord.authorizedAppIds);const hasCustomClaims=!!tokenRecord.customClaims&&Object.keys(tokenRecord.customClaims).length>0;const consentMetadata=tokenRecord.consentEnabled||tokenRecord.federatedLoginUsed||hasCustomClaims||hasAuthorizedApps?{selectedToolIds:tokenRecord.selectedToolIds,selectedProviderIds:tokenRecord.selectedProviderIds,skippedProviderIds:tokenRecord.skippedProviderIds,consentEnabled:tokenRecord.consentEnabled,federatedLoginUsed:tokenRecord.federatedLoginUsed,authorizedAppIds:tokenRecord.authorizedAppIds,customClaims:tokenRecord.customClaims}:void 0;const resource=tokenRecord.resource??defaultAudience;const accessToken=await this.signAccessToken(user,tokenRecord.scopes,resource,consentMetadata,issuer);const sourceId=tokenRecord.providerTokensId;const copiedTo=sourceId?await this.copyProviderTokens(sourceId,accessToken):void 0;if(sourceId&&!await this.authorizationStore.getRefreshToken(refreshToken)){if(copiedTo)await this.discardProviderTokens(copiedTo);this.logger.warn("Refresh token was redeemed by a concurrent request");return{error:"invalid_grant",error_description:"Refresh token is invalid or expired"}}const newRefreshRecord=this.authorizationStore.createRefreshTokenRecord({clientId,userSub:tokenRecord.userSub,scopes:tokenRecord.scopes,resource,userEmail:tokenRecord.userEmail,userName:tokenRecord.userName,consentEnabled:tokenRecord.consentEnabled,selectedToolIds:tokenRecord.selectedToolIds,authorizedAppIds:tokenRecord.authorizedAppIds,customClaims:tokenRecord.customClaims,federatedLoginUsed:tokenRecord.federatedLoginUsed,selectedProviderIds:tokenRecord.selectedProviderIds,skippedProviderIds:tokenRecord.skippedProviderIds,providerTokensId:copiedTo??sourceId});try{await this.authorizationStore.rotateRefreshToken(refreshToken,newRefreshRecord)}catch(err){if(copiedTo)await this.discardProviderTokens(copiedTo);throw err}if(sourceId&&copiedTo)await this.discardProviderTokens(sourceId);if(sourceId&&!this.orchestratedTokenStore.copyTokens){const movedTo=await this.moveProviderTokens(sourceId,accessToken);if(movedTo!==sourceId){await this.authorizationStore.storeRefreshToken({...newRefreshRecord,providerTokensId:movedTo})}}this.logger.info(`Tokens refreshed for user: ${user.sub}`);return{access_token:accessToken,token_type:"Bearer",expires_in:this.accessTokenTtlSeconds,refresh_token:newRefreshRecord.token,scope:tokenRecord.scopes.join(" ")}}async createAuthorizationCode(params){const codeRecord=this.authorizationStore.createCodeRecord({clientId:params.clientId,redirectUri:params.redirectUri,scopes:params.scopes,pkce:{challenge:params.codeChallenge,method:"S256"},userSub:params.userSub,userEmail:params.userEmail,userName:params.userName,state:params.state,resource:params.resource,selectedToolIds:params.selectedToolIds,selectedProviderIds:params.selectedProviderIds,skippedProviderIds:params.skippedProviderIds,consentEnabled:params.consentEnabled,federatedLoginUsed:params.federatedLoginUsed,pendingAuthId:params.pendingAuthId,authorizedAppIds:params.authorizedAppIds,customClaims:params.customClaims});await this.authorizationStore.storeAuthorizationCode(codeRecord);this.logger.info(`Authorization code created for user: ${params.userSub}`);return codeRecord.code}async initialize(){await this.tokenKeys.signingKey();await this.initializeStores();this.registerConfiguredProviders();await this.registerRemoteProvider();await this.initializeCredentialVault();await this.initializeSecureStore();this.providers.injectProvider({value:this.jwks,metadata:{scope:import_di4.ProviderScope.GLOBAL,name:"auth:jwk-service"},provide:import_auth76.JwksService});if(this.cimdService){const cimdService=this.cimdService;if(cimdService.enabled)await cimdService.initialize();this.scope.onDispose(()=>cimdService.dispose());this.providers.injectProvider({value:cimdService,metadata:{scope:import_di4.ProviderScope.GLOBAL,name:"auth:cimd-service"},provide:import_auth58.CimdService});this.logger.debug("CIMD service registered")}await this.registerAuthFlows();return Promise.resolve()}fetch(input,init){return fetch(input,init)}validate(request2){return Promise.resolve()}async registerAuthFlows(){const scope=this.providers.getActiveScope();await scope.registryFlows(WellKnownPrmFlow,WellKnownAsFlow,WellKnownJwksFlow,SessionVerifyFlow,...oauthFlows)}registerProvider(config){const previous=this.providerConfigs.get(config.id);const issuerChanged=previous?.issuer!==void 0&&config.issuer!==void 0&&normalizeIssuer(previous.issuer)!==normalizeIssuer(config.issuer);if(issuerChanged){this.logger.warn(`Upstream provider "${config.id}" changed issuer (${previous.issuer} \u2192 ${config.issuer}); discarding credentials bound to the previous authorization server`);void this.discardProviderCredentials(config.id)}this.providerConfigs.set(config.id,config);this.logger.info(`Registered upstream provider: ${config.id}`)}async discardProviderCredentials(providerId){try{const store=this.orchestratedTokenStoreImpl;if(typeof store.deleteTokensForProvider!=="function"){this.logger.warn(`Cannot auto-discard credentials for provider "${providerId}": the configured token store does not support provider-wide deletion. Rotate or clear the store manually so credentials issued by the previous authorization server are not reused.`);return}await store.deleteTokensForProvider(providerId)}catch(error){this.logger.error(`Failed to discard credentials for provider "${providerId}" after an issuer change`,error instanceof Error?{message:error.message}:{error})}}registerConfiguredProviders(){if(!(0,import_auth13.isLocalMode)(this.options)){return}const providers=this.options.providers;if(!providers||providers.length===0){return}for(const p of providers){const authorizationEndpoint=p.authorizationEndpoint??p.authorizeUrl;const tokenEndpoint=p.tokenEndpoint??p.tokenUrl;if(!authorizationEndpoint||!tokenEndpoint){const missing=!authorizationEndpoint?!tokenEndpoint?"authorization and token endpoints":"authorization endpoint (authorizationEndpoint/authorizeUrl)":"token endpoint (tokenEndpoint/tokenUrl)";throw new Error(`Provider "${p.id}" is missing its ${missing}.`)}this.registerProvider({id:p.id,name:p.name??p.id,authorizationEndpoint,tokenEndpoint,userInfoEndpoint:p.userInfoEndpoint,jwksUri:p.jwksUri,clientId:p.clientId,clientSecret:p.clientSecret,scopes:p.scopes??[],callbackUrl:`${this.issuer}/oauth/provider/${p.id}/callback`,issuer:p.issuer,additionalIssuers:p.additionalIssuers})}}async registerRemoteProvider(){if(!(0,import_auth13.isRemoteMode)(this.options)){return}const options=this.options;const base=options.provider.replace(/\/+$/,"");const cfg=options.providerConfig;const id=cfg?.id??this.deriveRemoteProviderId(options.provider);this.remoteProviderIdImpl=id;const callbackUrl=`${this.issuer}/oauth/provider/${id}/callback`;const scopes=options.scopes??["openid"];const client=await this.resolveRemoteClient(options,id,callbackUrl,scopes);if(!client){return}this.registerProvider({id,name:cfg?.name??id,authorizationEndpoint:cfg?.authEndpoint??`${base}/authorize`,tokenEndpoint:cfg?.tokenEndpoint??`${base}/token`,userInfoEndpoint:cfg?.userInfoEndpoint??`${base}/userinfo`,jwksUri:cfg?.jwksUri??`${base}/.well-known/jwks.json`,jwks:cfg?.jwks,clientId:client.clientId,clientSecret:client.clientSecret,scopes,callbackUrl,issuer:options.provider,additionalIssuers:cfg?.additionalIssuers,verifyIssuer:cfg?.verifyIssuer})}async resolveRemoteClient(options,providerId,callbackUrl,scopes){const cfg=options.providerConfig;if(options.clientId){if(cfg?.dcrEnabled){this.logger.info(`Remote mode: clientId is set, so provider "${providerId}" is not registered dynamically`)}return{clientId:options.clientId,clientSecret:options.clientSecret}}if(!cfg?.dcrEnabled){this.logger.warn(`Remote mode: no clientId configured for provider "${providerId}"; upstream OAuth is not available. Set clientId, or providerConfig.dcrEnabled to register with the provider.`);return void 0}return(0,import_auth76.resolveUpstreamClient)({provider:options.provider,registrationEndpoint:cfg.registrationEndpoint,redirectUri:callbackUrl,clientName:this.scope.metadata.info?.name??"FrontMCP",scopes,storage:this.storageAdapter,encryptionKey:this.secret,logger:this.logger})}deriveRemoteProviderId(provider){try{return new URL(provider).hostname.replace(/\./g,"_")}catch{return provider.replace(/[^a-zA-Z0-9]/g,"_")}}getProviderConfig(providerId){return this.providerConfigs.get(providerId)}async buildProviderAuthorizeUrl(providerId,params){const config=this.providerConfigs.get(providerId);if(!config){this.logger.error(`Provider not found: ${providerId}`);return null}const url=new URL(config.authorizationEndpoint);url.searchParams.set("response_type","code");url.searchParams.set("client_id",config.clientId);url.searchParams.set("redirect_uri",config.callbackUrl);url.searchParams.set("state",params.state);url.searchParams.set("code_challenge",params.codeChallenge);url.searchParams.set("code_challenge_method",params.codeChallengeMethod);const scopes=params.scopes??config.scopes;if(scopes.length>0){url.searchParams.set("scope",scopes.join(" "))}return url.toString()}async exchangeProviderCode(providerId,code,codeVerifier){const config=this.providerConfigs.get(providerId);if(!config){return{error:"invalid_provider",error_description:`Provider not configured: ${providerId}`}}try{const body=new URLSearchParams({grant_type:"authorization_code",code,redirect_uri:config.callbackUrl,client_id:config.clientId});if(config.clientSecret){body.set("client_secret",config.clientSecret)}if(codeVerifier){body.set("code_verifier",codeVerifier)}this.logger.debug(`Exchanging code with provider: ${providerId}`);const response=await fetch(config.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:body.toString()});if(!response.ok){const errorData=await response.json().catch(()=>({}));this.logger.error(`Provider token exchange failed: ${response.status}`,errorData);return{error:errorData.error||"provider_error",error_description:errorData.error_description||`Provider returned ${response.status}`}}const tokenData=await response.json();if(typeof tokenData?.access_token!=="string"||tokenData.access_token.length===0){this.logger.error(`Provider ${providerId} returned 200 without an access_token`);return{error:"provider_error",error_description:`Provider ${providerId} did not return an access_token`}}this.logger.info(`Successfully exchanged code with provider: ${providerId}`);return tokenData}catch(err){this.logger.error(`Provider token exchange error for ${providerId}:`,err);return{error:"provider_error",error_description:`Failed to exchange code with provider: ${err}`}}}async getProviderUserInfo(providerId,accessToken,idToken){const config=this.providerConfigs.get(providerId);if(idToken&&config){const claims3=await this.verifyProviderIdToken(config,idToken);const sub=typeof claims3?.["sub"]==="string"&&claims3["sub"].trim()?claims3["sub"]:void 0;if(claims3&&sub){return{sub,email:claims3["email"],name:claims3["name"],picture:claims3["picture"],claims:claims3}}this.logger.warn(`ID token for ${providerId} was not verified; using the userinfo endpoint for identity`)}if(config?.userInfoEndpoint){try{const response=await fetch(config.userInfoEndpoint,{headers:{Authorization:`Bearer ${accessToken}`,Accept:"application/json"}});if(response.ok){const userInfo=await response.json();const sub=typeof userInfo["sub"]==="string"&&userInfo["sub"].trim()?userInfo["sub"]:void 0;if(sub){return{sub,email:userInfo["email"],name:userInfo["name"],picture:userInfo["picture"],claims:userInfo}}this.logger.warn(`userinfo for ${providerId} returned no usable sub`)}}catch(err){this.logger.warn(`Failed to get userinfo from ${providerId}: ${err}`)}}throw new Error(`Unable to determine a stable user identity from provider "${providerId}" (no id_token sub and no usable userinfo endpoint)`)}async verifyProviderIdToken(config,idToken){if(!config.jwks?.keys?.length&&!config.jwksUri)return void 0;if(!config.issuer&&config.verifyIssuer!==false){this.logger.warn(`ID token for ${config.id} not used: the provider has no configured issuer to check it against`);return void 0}const result=await this.jwks.verifyTransparentToken(idToken,[{id:`upstream:${config.id}`,issuerUrl:config.issuer??"",additionalIssuers:config.additionalIssuers,verifyIssuer:config.verifyIssuer,jwks:config.jwks,jwksUri:config.jwksUri}]);if(!result.ok||!result.payload){this.logger.warn(`ID token for ${config.id} failed verification: ${result.error??"unknown"}`);return void 0}const aud=result.payload["aud"];const audiences=typeof aud==="string"?[aud]:Array.isArray(aud)?aud:[];if(!audiences.includes(config.clientId)){this.logger.warn(`ID token for ${config.id} was issued for another client`);return void 0}return result.payload}async refreshProviderToken(providerId,refreshToken){const config=this.providerConfigs.get(providerId);if(!config){return{error:"invalid_provider",error_description:`Provider not configured: ${providerId}`}}try{const body=new URLSearchParams({grant_type:"refresh_token",refresh_token:refreshToken,client_id:config.clientId});if(config.clientSecret){body.set("client_secret",config.clientSecret)}const response=await fetch(config.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:body.toString()});if(!response.ok){const errorData=await response.json().catch(()=>({}));return{error:errorData.error||"provider_error",error_description:errorData.error_description||`Provider returned ${response.status}`}}return await response.json()}catch(err){return{error:"provider_error",error_description:`Failed to refresh token with provider: ${err}`}}}providerTokenRefresher(){if(!(0,import_auth13.isOrchestratedMode)(this.options)||this.options.refresh?.enabled===false)return void 0;return(providerId,refreshToken)=>{const key=JSON.stringify([providerId,refreshToken]);const inFlight=this.providerRenewals.get(key);if(inFlight)return inFlight;const renewal=this.renewProviderToken(providerId,refreshToken).finally(()=>this.providerRenewals.delete(key));this.providerRenewals.set(key,renewal);return renewal}}async renewProviderToken(providerId,refreshToken){const result=await this.refreshProviderToken(providerId,refreshToken);if("error"in result||typeof result.access_token!=="string"||!result.access_token){this.logger.warn(`Provider ${providerId} did not refresh its token: ${"error"in result?result.error:"no access_token"}`);throw new import_auth76.TokenNotAvailableError(`Provider "${providerId}" did not refresh its token; the user has to sign in again`)}return{accessToken:result.access_token,refreshToken:result.refresh_token,expiresIn:result.expires_in}}providerRefreshSkewMs(){if(!(0,import_auth13.isOrchestratedMode)(this.options)||this.options.refresh?.enabled===false)return 0;return(this.options.refresh?.skewSeconds??60)*1e3}}}});var import_auth78,RemotePrimaryAuth;var init_instance_remote_primary_auth=__esm({"libs/sdk/src/auth/instances/instance.remote-primary-auth.ts"(){"use strict";import_auth78=require("@frontmcp/auth");init_common();init_session_verify_flow();init_well_known_jwks_flow();init_well_known_oauth_authorization_server_flow();init_well_known_prm_flow();RemotePrimaryAuth=class extends FrontMcpAuth{constructor(scope,providers,options){super(options);this.scope=scope;this.providers=providers;this.ready=this.initialize()}scope;providers;ready;jwks=new import_auth78.JwksService;fetch(input,init){return fetch(input,init)}validate(request2){return Promise.resolve()}get issuer(){return this.options.provider}async initialize(){const scope=this.providers.getActiveScope();this.providers.injectProvider({value:this.jwks,metadata:{scope:import_di4.ProviderScope.GLOBAL,name:"auth:jwk-service"},provide:import_auth78.JwksService});await this.registerAuthFlows(scope);return Promise.resolve()}async registerAuthFlows(scope){await scope.registryFlows(WellKnownPrmFlow,WellKnownAsFlow,WellKnownJwksFlow,SessionVerifyFlow)}}}});var primary_auth_factory_exports={};__export(primary_auth_factory_exports,{createPrimaryAuth:()=>createPrimaryAuth});var createPrimaryAuth;var init_primary_auth_factory=__esm({"libs/sdk/src/auth/primary-auth.factory.ts"(){"use strict";init_common();init_instance_local_primary_auth();init_instance_remote_primary_auth();createPrimaryAuth=(scope,providers,options)=>{if((0,import_auth13.isPublicMode)(options)){return new LocalPrimaryAuth(scope,providers,options)}if((0,import_auth13.isStaticMode)(options)){return new LocalPrimaryAuth(scope,providers,options)}if((0,import_auth13.isTransparentMode)(options)){return new RemotePrimaryAuth(scope,providers,options)}if((0,import_auth13.isOrchestratedMode)(options)){if((0,import_auth13.isOrchestratedLocal)(options)){return new LocalPrimaryAuth(scope,providers,options)}else{return new LocalPrimaryAuth(scope,providers,options)}}const defaultOptions=(0,import_auth13.parseAuthOptions)({mode:"public"});return new LocalPrimaryAuth(scope,providers,defaultOptions)}}});var ui_option_warnings_exports={};__export(ui_option_warnings_exports,{describeIgnoredUiOptions:()=>describeIgnoredUiOptions,describeServingModeDefault:()=>describeServingModeDefault});function describeIgnoredUiOptions(toolName,ui){if(!ui)return[];const messages=[];messages.push(...describeInvalidCspOrigins(toolName,ui["csp"]));if(ui["servingMode"]==="hybrid"){messages.push(`Tool "${toolName}": \`ui.servingMode: 'hybrid'\` sends only a reference in \`_meta['ui/component']\` ({ type, hash, toolName }), not the component code; the widget is rendered from its \`ui://\` resource.`)}return messages}function describeServingModeDefault(owner,mode){if(mode==="hybrid"){return[`${owner}: \`ui.servingMode: 'hybrid'\` sends only a reference in \`_meta['ui/component']\` ({ type, hash, toolName }), not the component code; the widgets of the tools that inherit it are rendered from their \`ui://\` resource.`]}return[]}function describeInvalidCspOrigins(toolName,csp){if(!csp||typeof csp!=="object")return[];const messages=[];for(const key of["connectDomains","resourceDomains"]){const domains=csp[key];if(!Array.isArray(domains))continue;for(const domain of domains){if(typeof domain==="string"&&(0,import_shell3.validateCSPDomain)(domain))continue;messages.push(`Tool "${toolName}": \`ui.csp.${key}\` origin ${JSON.stringify(domain)} is not an https:// or wss:// origin (or http:// / ws:// on localhost), so the widget page's Content-Security-Policy leaves it out.`)}}return messages}var import_shell3;var init_ui_option_warnings=__esm({"libs/sdk/src/tool/ui/ui-option-warnings.ts"(){"use strict";import_shell3=require("@frontmcp/uipack/shell")}});function workerModuleOf(metadata){return metadata.worker?captureCallerFile(RESOURCE_DECORATOR_BASENAMES):void 0}function FrontMcpResource(providedMetadata){const workerModule=workerModuleOf(providedMetadata);return target=>{const metadata=frontMcpResourceMetadataSchema.parse(providedMetadata);if(metadata.worker)registerWorkerResourceClass(target,metadata,workerModule);Reflect.defineMetadata(FrontMcpResourceTokens.type,true,target);const extended={};for(const property in metadata){if(FrontMcpResourceTokens[property]){Reflect.defineMetadata(FrontMcpResourceTokens[property],metadata[property],target)}else{extended[property]=metadata[property]}}Reflect.defineMetadata(extendedResourceMetadata,extended,target)}}function FrontMcpResourceTemplate(providedMetadata){const workerModule=workerModuleOf(providedMetadata);return target=>{const metadata=frontMcpResourceTemplateMetadataSchema.parse(providedMetadata);if(metadata.worker)registerWorkerResourceClass(target,metadata,workerModule);Reflect.defineMetadata(FrontMcpResourceTemplateTokens.type,true,target);const extended=Object.create(null);for(const property in metadata){if(Object.prototype.hasOwnProperty.call(FrontMcpResourceTemplateTokens,property)){Reflect.defineMetadata(FrontMcpResourceTemplateTokens[property],metadata[property],target)}else{extended[property]=metadata[property]}}Reflect.defineMetadata(extendedResourceTemplateMetadata,extended,target)}}function frontMcpResource(providedMetadata){const workerModule=workerModuleOf(providedMetadata);return execute=>{const metadata=frontMcpResourceMetadataSchema.parse(providedMetadata);if(metadata.worker)registerWorkerResourceHandler(execute,metadata,workerModule);const resourceFunction=function(){return execute};Object.assign(resourceFunction,{[FrontMcpResourceTokens.type]:"function-resource",[FrontMcpResourceTokens.metadata]:metadata});return resourceFunction}}function frontMcpResourceTemplate(providedMetadata){const workerModule=workerModuleOf(providedMetadata);return execute=>{const metadata=frontMcpResourceTemplateMetadataSchema.parse(providedMetadata);if(metadata.worker)registerWorkerResourceHandler(execute,metadata,workerModule);const resourceFunction=function(){return execute};Object.assign(resourceFunction,{[FrontMcpResourceTemplateTokens.type]:"function-resource-template",[FrontMcpResourceTemplateTokens.metadata]:metadata});return resourceFunction}}function resourceEsm(specifier,targetName,options){const parsed=parsePackageSpecifier(specifier);return{kind:"ESM",provide:Symbol(`esm-resource:${parsed.fullName}:${targetName}`),specifier:parsed,targetName,options,metadata:{name:targetName,description:`Resource "${targetName}" from ${parsed.fullName}`,uri:`esm://${targetName}`,...options?.metadata}}}function resourceRemote(url,targetName,options){validateRemoteUrl(url);return{kind:"REMOTE",provide:Symbol(`remote-resource:${url}:${targetName}`),url,targetName,transportOptions:options?.transportOptions,remoteAuth:options?.remoteAuth,options,metadata:{name:targetName,description:`Remote resource "${targetName}" from ${url}`,uri:`remote://${targetName}`,...options?.metadata}}}var import_reflect_metadata29,RESOURCE_DECORATOR_BASENAMES,Resource,_ResourceTemplate;var init_resource_decorator=__esm({"libs/sdk/src/common/decorators/resource.decorator.ts"(){"use strict";import_reflect_metadata29=require("reflect-metadata");init_package_specifier();init_worker_resources();init_metadata();init_tokens();init_caller_dir_utils();init_validate_remote_url();RESOURCE_DECORATOR_BASENAMES=["resource.decorator.ts","resource.decorator.js","resource.decorator.mjs","resource.decorator.cjs"];Object.assign(FrontMcpResource,{esm:resourceEsm,remote:resourceRemote});Resource=FrontMcpResource;_ResourceTemplate=FrontMcpResourceTemplate}});var import_utils191,import_shell4;var init_template_helpers=__esm({"libs/sdk/src/tool/ui/template-helpers.ts"(){"use strict";import_utils191=require("@frontmcp/uipack/utils");import_shell4=require("@frontmcp/uipack/shell")}});var ui_resource_template_exports={};__export(ui_resource_template_exports,{StaticWidgetResourceTemplate:()=>StaticWidgetResourceTemplate});var StaticWidgetResourceTemplate;var init_ui_resource_template=__esm({"libs/sdk/src/tool/ui/ui-resource-template.ts"(){"use strict";init_resource_decorator();init_template_helpers();StaticWidgetResourceTemplate=frontMcpResourceTemplate({name:"static-widget",description:"Static widget HTML for tool UI (OpenAI discovery)",uriTemplate:"ui://widget/{toolName}.html",mimeType:"text/html;profile=mcp-app"})((uri,params)=>{return{contents:[{uri,mimeType:"text/html;profile=mcp-app",text:`<!DOCTYPE html>
469
+ </html>`}htmlPage(markup,status=200){return httpRespond.html(markup,status,(0,import_auth70.builtInAuthPageHeaders)())}getStateValidation(){const authOptions=this.scope.auth?.options;if(authOptions&&(0,import_auth13.isOrchestratedMode)(authOptions)){return authOptions.federatedAuth?.stateValidation??"strict"}return"strict"}};__decorateClass([Stage53("checkIpFilter")],OauthProviderCallbackFlow.prototype,"checkIpFilter",1);__decorateClass([Stage53("acquireQuota")],OauthProviderCallbackFlow.prototype,"acquireQuota",1);__decorateClass([Stage53("parseInput")],OauthProviderCallbackFlow.prototype,"parseInput",1);__decorateClass([Stage53("handleConsentSubmission")],OauthProviderCallbackFlow.prototype,"handleConsentSubmission",1);__decorateClass([Stage53("loadFederatedSession")],OauthProviderCallbackFlow.prototype,"loadFederatedSession",1);__decorateClass([Stage53("validateProviderCallback")],OauthProviderCallbackFlow.prototype,"validateProviderCallback",1);__decorateClass([Stage53("exchangeProviderCode")],OauthProviderCallbackFlow.prototype,"exchangeProviderCode",1);__decorateClass([Stage53("storeProviderTokens")],OauthProviderCallbackFlow.prototype,"storeProviderTokens",1);__decorateClass([Stage53("handleNextProviderOrComplete")],OauthProviderCallbackFlow.prototype,"handleNextProviderOrComplete",1);OauthProviderCallbackFlow=__decorateClass([FrontMcpFlow({name:name53,plan:plan53,inputSchema:inputSchema46,outputSchema:outputSchema45,access:"public",middleware:{path:"/oauth/provider/:providerId/callback"}})],OauthProviderCallbackFlow)}});var oauth_auth_ui_flow_exports={};__export(oauth_auth_ui_flow_exports,{OauthAuthUiExtraFlow:()=>OauthAuthUiExtraFlow,default:()=>OauthAuthUiExtraFlow});function timingSafeEqualStr4(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_lazy_zod146,extraInputSchema,extraStateSchema,extraOutputSchema,extraPlan,extraName,ExtraStage,OauthAuthUiExtraFlow;var init_oauth_auth_ui_flow=__esm({"libs/sdk/src/auth/flows/oauth.auth-ui.flow.ts"(){"use strict";import_lazy_zod146=require("@frontmcp/lazy-zod");init_common();extraInputSchema=httpInputSchema;extraStateSchema=import_lazy_zod146.internalZ.object({action:import_lazy_zod146.internalZ.string().optional(),pendingAuthId:import_lazy_zod146.internalZ.string().optional(),csrf:import_lazy_zod146.internalZ.string().optional(),payload:import_lazy_zod146.internalZ.record(import_lazy_zod146.internalZ.string(),import_lazy_zod146.internalZ.unknown()).optional()});extraOutputSchema=HttpJsonSchema;extraPlan={pre:["checkIpFilter","acquireQuota","parseInput"],execute:["handleExtra"]};extraName="oauth:auth-ui-extra";ExtraStage=StageHookOf(extraName);OauthAuthUiExtraFlow=class extends FlowBase{logger=this.scope.logger.child("OauthAuthUiExtraFlow");async checkIpFilter(){enforceIpFilter(this.scope,this.tryGetContext()?.metadata.clientIp)}async acquireQuota(){await enforceGlobalRateLimit(this.scope,this.tryGetContext())}async parseInput(){const{request:request2}=this.rawInput;const body=request2.body&&typeof request2.body==="object"?request2.body:{};const query=request2.query??{};const readStr=key=>{const v=body[key]??query[key];return typeof v==="string"?v:Array.isArray(v)&&typeof v[0]==="string"?v[0]:void 0};const reserved=new Set(["action","pending_auth_id","csrf","__proto__","constructor","prototype"]);const payload=Object.create(null);for(const[k,v]of Object.entries(body)){if(!reserved.has(k))payload[k]=v}this.state.set({action:readStr("action"),pendingAuthId:readStr("pending_auth_id"),csrf:readStr("csrf"),payload})}async handleExtra(){const{action,pendingAuthId,csrf,payload}=this.state;const authUi=this.scope.authUi;if(!authUi||!authUi.hasExtras()){this.respond(httpRespond.json({ok:false,error:"No extras are configured."},{status:404}));return}if(!action||!authUi.hasExtra(action)){this.respond(httpRespond.json({ok:false,error:`Unknown extra "${action??""}".`},{status:400}));return}const ok=await this.verifyExtraCsrf(pendingAuthId,csrf,authUi);if(!ok){this.logger.warn("Auth-UI extra CSRF mismatch");this.respond(httpRespond.json({ok:false,error:"Invalid or missing CSRF token"},{status:400}));return}const result=await authUi.runExtra(action,pendingAuthId,payload??{});this.respond(httpRespond.json(result,{status:result.ok?200:400}))}async verifyExtraCsrf(pendingAuthId,submitted,authUi){if(!pendingAuthId||!submitted)return false;try{const localAuth=this.scope.auth;const record=await localAuth.authorizationStore.getPendingAuthorization(pendingAuthId);if(record?.authUiCsrf){return timingSafeEqualStr4(record.authUiCsrf,submitted)}}catch{}return authUi.verifyCsrf(pendingAuthId,submitted)}};__decorateClass([ExtraStage("checkIpFilter")],OauthAuthUiExtraFlow.prototype,"checkIpFilter",1);__decorateClass([ExtraStage("acquireQuota")],OauthAuthUiExtraFlow.prototype,"acquireQuota",1);__decorateClass([ExtraStage("parseInput")],OauthAuthUiExtraFlow.prototype,"parseInput",1);__decorateClass([ExtraStage("handleExtra")],OauthAuthUiExtraFlow.prototype,"handleExtra",1);OauthAuthUiExtraFlow=__decorateClass([FrontMcpFlow({name:extraName,plan:extraPlan,inputSchema:extraInputSchema,outputSchema:extraOutputSchema,access:"public",middleware:{method:"POST",path:"/oauth/ui/extra"}})],OauthAuthUiExtraFlow)}});var oauthFlows;var init_oauth_flows=__esm({"libs/sdk/src/auth/flows/oauth-flows.ts"(){"use strict";init_deferred_flow();oauthFlows=[deferredFlow({name:"oauth:authorize",middleware:{method:"GET",path:"/oauth/authorize"}},()=>Promise.resolve().then(()=>(init_oauth_authorize_flow(),oauth_authorize_flow_exports)).then(flow=>flow.OauthAuthorizeFlow)),deferredFlow({name:"oauth:token",middleware:{method:"POST",path:"/oauth/token"}},()=>Promise.resolve().then(()=>(init_oauth_token_flow(),oauth_token_flow_exports)).then(flow=>flow.OauthTokenFlow)),deferredFlow({name:"oauth:userinfo",middleware:{method:"GET",path:"/oauth/userinfo"}},()=>Promise.resolve().then(()=>(init_oauth_userinfo_flow(),oauth_userinfo_flow_exports)).then(flow=>flow.OauthUserInfoFlow)),deferredFlow({name:"oauth:callback",middleware:{path:"/oauth/callback"}},()=>Promise.resolve().then(()=>(init_oauth_callback_flow(),oauth_callback_flow_exports)).then(flow=>flow.OauthCallbackFlow)),deferredFlow({name:"oauth:connect",middleware:{path:"/oauth/connect"}},()=>Promise.resolve().then(()=>(init_oauth_connect_flow(),oauth_connect_flow_exports)).then(flow=>flow.OauthConnectFlow)),deferredFlow({name:"oauth:register",middleware:{method:"POST",path:"/oauth/register"}},()=>Promise.resolve().then(()=>(init_oauth_register_flow(),oauth_register_flow_exports)).then(flow=>flow.OauthRegisterFlow)),deferredFlow({name:"oauth:provider-callback",middleware:{path:"/oauth/provider/:providerId/callback"}},()=>Promise.resolve().then(()=>(init_oauth_provider_callback_flow(),oauth_provider_callback_flow_exports)).then(flow=>flow.OauthProviderCallbackFlow)),deferredFlow({name:"oauth:auth-ui-extra",middleware:{method:"POST",path:"/oauth/ui/extra"}},()=>Promise.resolve().then(()=>(init_oauth_auth_ui_flow(),oauth_auth_ui_flow_exports)).then(flow=>flow.OauthAuthUiExtraFlow))]}});var import_reflect_metadata26,import_auth71,import_lazy_zod147,inputSchema47,stateSchema49,outputSchema46,plan54,name54,Stage54,WellKnownJwksFlow;var init_well_known_jwks_flow=__esm({"libs/sdk/src/auth/flows/well-known.jwks.flow.ts"(){"use strict";init_common();import_reflect_metadata26=require("reflect-metadata");import_auth71=require("@frontmcp/auth");import_lazy_zod147=require("@frontmcp/lazy-zod");init_auth_internal_errors();inputSchema47=httpInputSchema;stateSchema49=import_lazy_zod147.internalZ.object({isOrchestrated:import_lazy_zod147.internalZ.boolean()});outputSchema46=import_lazy_zod147.internalZ.union([HttpJsonSchema,HttpTextSchema,HttpRedirectSchema]);plan54={pre:["checkIpFilter","acquireQuota","parseInput","validateInput"],execute:["collectData"]};name54="well-known.jwks";Stage54=StageHookOf(name54);WellKnownJwksFlow=class extends FlowBase{static canActivate(request2,scope){return makeWellKnownPaths("jwks.json",scope.entryPath,scope.routeBase).has(request2.path)}async checkIpFilter(){enforceIpFilter(this.scope,this.tryGetContext()?.metadata.clientIp)}async acquireQuota(){await enforceGlobalRateLimit(this.scope,this.tryGetContext())}async parseInput(){this.state.set({isOrchestrated:false})}async collectData(){const{isOrchestrated}=this.state.required;const jwksSvc=this.get(import_auth71.JwksService);if(isOrchestrated){const keysDoc=await jwksSvc.getPublicJwks();if(!keysDoc?.keys||!Array.isArray(keysDoc.keys)){throw new import_auth16.OrchestratorJwksNotAvailableError}this.respond(httpRespond.json(keysDoc));return}const options=this.scope.auth.options;if(options&&(0,import_auth13.isTransparentMode)(options)){if(options.providerConfig?.jwks&&options.providerConfig.jwks.keys.length){this.respond(httpRespond.json(options.providerConfig.jwks))}else{const location=options.providerConfig?.jwksUri??`${options.provider}/.well-known/jwks.json`;this.respond(httpRespond.redirect(location))}}else{const keysDoc=await jwksSvc.getPublicJwks();if(keysDoc?.keys&&Array.isArray(keysDoc.keys)){this.respond(httpRespond.json(keysDoc))}else{this.respond(httpRespond.notFound())}}}};__decorateClass([Stage54("checkIpFilter")],WellKnownJwksFlow.prototype,"checkIpFilter",1);__decorateClass([Stage54("acquireQuota")],WellKnownJwksFlow.prototype,"acquireQuota",1);__decorateClass([Stage54("parseInput")],WellKnownJwksFlow.prototype,"parseInput",1);__decorateClass([Stage54("collectData")],WellKnownJwksFlow.prototype,"collectData",1);WellKnownJwksFlow=__decorateClass([FrontMcpFlow({name:name54,plan:plan54,inputSchema:inputSchema47,outputSchema:outputSchema46,access:"public",middleware:{method:"GET"}})],WellKnownJwksFlow)}});function resolveDcrEnabled(auth){if(auth&&(0,import_auth13.isLocalMode)(auth)){const dcr=auth.dcr;if(dcr&&typeof dcr.enabled==="boolean"){return dcr.enabled}}return!(0,import_utils189.isProduction)()}var import_reflect_metadata27,import_auth72,import_lazy_zod148,import_utils189,inputSchema48,tokenEndpointAuthMethodSchema,AuthServerMetadataSchema,outputSchema47,wellKnownAsStateSchema,wellKnownAsPlan,name55,Stage55,WellKnownAsFlow;var init_well_known_oauth_authorization_server_flow=__esm({"libs/sdk/src/auth/flows/well-known.oauth-authorization-server.flow.ts"(){"use strict";import_reflect_metadata27=require("reflect-metadata");import_auth72=require("@frontmcp/auth");import_lazy_zod148=require("@frontmcp/lazy-zod");import_utils189=require("@frontmcp/utils");init_common();init_sdk_errors();init_flow_http_path();inputSchema48=httpInputSchema;tokenEndpointAuthMethodSchema=import_lazy_zod148.internalZ.enum(["none","client_secret_basic","client_secret_post","private_key_jwt"]);AuthServerMetadataSchema=import_lazy_zod148.internalZ.object({kind:import_lazy_zod148.internalZ.literal("json"),status:import_lazy_zod148.internalZ.literal(200),contentType:import_lazy_zod148.internalZ.literal("application/json; charset=utf-8"),headers:import_lazy_zod148.internalZ.record(import_lazy_zod148.internalZ.string(),import_lazy_zod148.internalZ.string()).optional(),body:import_lazy_zod148.internalZ.object({issuer:import_lazy_zod148.internalZ.string().min(1),authorization_endpoint:import_lazy_zod148.internalZ.string().min(1),token_endpoint:import_lazy_zod148.internalZ.string().min(1),userinfo_endpoint:import_lazy_zod148.internalZ.string().min(1).optional(),jwks_uri:import_lazy_zod148.internalZ.string().min(1),registration_endpoint:import_lazy_zod148.internalZ.string().min(1).optional(),token_endpoint_auth_methods_supported:import_lazy_zod148.internalZ.array(tokenEndpointAuthMethodSchema).optional(),token_endpoint_auth_signing_alg_values_supported:import_lazy_zod148.internalZ.array(import_lazy_zod148.internalZ.string()).optional(),response_types_supported:import_lazy_zod148.internalZ.array(import_lazy_zod148.internalZ.enum(["code"])).default(["code"]),grant_types_supported:import_lazy_zod148.internalZ.array(import_lazy_zod148.internalZ.enum(["authorization_code","refresh_token"])).default(["authorization_code","refresh_token"]),scopes_supported:import_lazy_zod148.internalZ.array(import_lazy_zod148.internalZ.string()).default(["openid","profile","email"]),code_challenge_methods_supported:import_lazy_zod148.internalZ.array(import_lazy_zod148.internalZ.enum(["S256"])).default(["S256"])}).passthrough()});outputSchema47=import_lazy_zod148.internalZ.union([AuthServerMetadataSchema,HttpRedirectSchema,HttpTextSchema]);wellKnownAsStateSchema=import_lazy_zod148.internalZ.object({baseUrl:import_lazy_zod148.internalZ.string().min(1),issuer:import_lazy_zod148.internalZ.string().min(1).optional(),oauthBaseUrl:import_lazy_zod148.internalZ.string().min(1),scopesSupported:import_lazy_zod148.internalZ.array(import_lazy_zod148.internalZ.string()).default(["openid","profile","email"]),tokenEndpointAuthMethods:import_lazy_zod148.internalZ.array(tokenEndpointAuthMethodSchema).default(["none","client_secret_basic","client_secret_post"]),dcrEnabled:import_lazy_zod148.internalZ.boolean().default(true),isOrchestrated:import_lazy_zod148.internalZ.boolean(),cimdEnabled:import_lazy_zod148.internalZ.boolean().default(true)});wellKnownAsPlan={pre:["checkIpFilter","acquireQuota","parseInput"],execute:["collectData"]};name55="well-known.oauth-authorization-server";Stage55=StageHookOf(name55);WellKnownAsFlow=class extends FlowBase{static canActivate(request2,scope){return makeWellKnownPaths("oauth-authorization-server",scope.entryPath,scope.routeBase).has(request2.path)}async checkIpFilter(){enforceIpFilter(this.scope,this.tryGetContext()?.metadata.clientIp)}async acquireQuota(){await enforceGlobalRateLimit(this.scope,this.tryGetContext())}async parseInput(){const{request:request2}=this.rawInput;if(!request2)throw new FlowInputMissingError("request","well-known:oauth-authorization-server");const{metadata}=this.scope;const baseUrl=getRequestBaseUrl(request2,this.scope.entryPath);const issuer=this.scope.auth?.issuerFor?.(request2);const oauthBaseUrl=getRequestBaseUrl(request2,oauthBasePath(this.scope));let cimdEnabled=true;if(metadata.auth&&(0,import_auth13.isOrchestratedMode)(metadata.auth)){cimdEnabled=metadata.auth.cimd?.enabled??true}this.state.set(wellKnownAsStateSchema.parse({baseUrl,issuer,oauthBaseUrl,scopesSupported:metadata.auth&&(0,import_auth13.isOrchestratedMode)(metadata.auth)?(0,import_auth72.advertisedScopes)(metadata.auth.allowedScopes):[],tokenEndpointAuthMethods:cimdEnabled?["none","client_secret_basic","client_secret_post","private_key_jwt"]:["none","client_secret_basic","client_secret_post"],dcrEnabled:resolveDcrEnabled(metadata.auth),isOrchestrated:metadata.auth?(0,import_auth13.isOrchestratedMode)(metadata.auth):false,cimdEnabled}))}async collectData(){const{issuer}=this.state;const{baseUrl,oauthBaseUrl,scopesSupported,tokenEndpointAuthMethods,dcrEnabled,isOrchestrated,cimdEnabled}=this.state.required;if(isOrchestrated){const baseIssuer=issuer??baseUrl;this.respond({kind:"json",contentType:"application/json; charset=utf-8",status:200,headers:{"cache-control":"no-store"},body:{issuer:baseIssuer,authorization_endpoint:`${oauthBaseUrl}/oauth/authorize`,token_endpoint:`${oauthBaseUrl}/oauth/token`,userinfo_endpoint:`${oauthBaseUrl}/oauth/userinfo`,jwks_uri:`${baseIssuer}/.well-known/jwks.json`,...dcrEnabled?{registration_endpoint:`${oauthBaseUrl}/oauth/register`}:{},token_endpoint_auth_methods_supported:tokenEndpointAuthMethods,...tokenEndpointAuthMethods.includes("private_key_jwt")?{token_endpoint_auth_signing_alg_values_supported:import_auth72.CLIENT_ASSERTION_SIGNING_ALGORITHMS}:{},response_types_supported:["code"],grant_types_supported:["authorization_code","refresh_token"],scopes_supported:scopesSupported,code_challenge_methods_supported:["S256"],authorization_response_iss_parameter_supported:true,client_id_metadata_document_supported:cimdEnabled}});return}const authOptions=this.scope.auth?.options;if(!authOptions||!(0,import_auth13.isTransparentMode)(authOptions)){this.respond(httpRespond.notFound());return}this.respond(httpRespond.redirect(`${(0,import_auth72.trimSlash)(this.scope.auth.issuer)}/.well-known/oauth-authorization-server`))}};__decorateClass([Stage55("checkIpFilter")],WellKnownAsFlow.prototype,"checkIpFilter",1);__decorateClass([Stage55("acquireQuota")],WellKnownAsFlow.prototype,"acquireQuota",1);__decorateClass([Stage55("parseInput")],WellKnownAsFlow.prototype,"parseInput",1);__decorateClass([Stage55("collectData")],WellKnownAsFlow.prototype,"collectData",1);WellKnownAsFlow=__decorateClass([FrontMcpFlow({name:name55,plan:wellKnownAsPlan,inputSchema:inputSchema48,outputSchema:outputSchema47,access:"public",middleware:{method:"GET"}})],WellKnownAsFlow)}});var import_reflect_metadata28,import_auth73,import_lazy_zod149,inputSchema49,stateSchema50,outputSchema48,plan55,name56,Stage56,WellKnownPrmFlow;var init_well_known_prm_flow=__esm({"libs/sdk/src/auth/flows/well-known.prm.flow.ts"(){"use strict";import_reflect_metadata28=require("reflect-metadata");import_auth73=require("@frontmcp/auth");import_lazy_zod149=require("@frontmcp/lazy-zod");init_common();init_sdk_errors();inputSchema49=httpInputSchema;stateSchema50=import_lazy_zod149.internalZ.object({resource:import_lazy_zod149.internalZ.string().min(1),baseUrl:import_lazy_zod149.internalZ.string().min(1),authorizationServer:import_lazy_zod149.internalZ.string().min(1).optional(),scopesSupported:import_lazy_zod149.internalZ.array(import_lazy_zod149.internalZ.string()),isOrchestrated:import_lazy_zod149.internalZ.boolean()});outputSchema48=HttpJsonSchema.extend({body:import_lazy_zod149.internalZ.object({resource:import_lazy_zod149.internalZ.string().min(1),authorization_servers:import_lazy_zod149.internalZ.array(import_lazy_zod149.internalZ.string().min(1)).min(1).optional(),scopes_supported:import_lazy_zod149.internalZ.array(import_lazy_zod149.internalZ.string()).optional(),bearer_methods_supported:import_lazy_zod149.internalZ.array(import_lazy_zod149.internalZ.string()).default(["header"])}).passthrough()});plan55={pre:["checkIpFilter","acquireQuota","parseInput"],execute:["collectData"],post:["validateOutput"]};name56="well-known.oauth-protected-resource";Stage56=StageHookOf(name56);WellKnownPrmFlow=class extends FlowBase{static canActivate(request2,scope){return makeWellKnownPaths("oauth-protected-resource",scope.entryPath,scope.routeBase).has(request2.path)}async checkIpFilter(){enforceIpFilter(this.scope,this.tryGetContext()?.metadata.clientIp)}async acquireQuota(){await enforceGlobalRateLimit(this.scope,this.tryGetContext())}async parseInput(){const{request:request2}=this.rawInput;const scope=this.scope;if(!request2)throw new FlowInputMissingError("request","well-known:prm");const resource=computeResource(request2,scope.entryPath,scope.routeBase);const baseUrl=getRequestBaseUrl(request2,scope.entryPath);const authOptions=scope.auth?.options??scope.metadata.auth;const transparentProvider=authOptions?.mode==="transparent"?authOptions.provider:void 0;const authorizationServer=transparentProvider??scope.auth?.issuerFor?.(request2)??baseUrl;const granted=(0,import_auth73.resourceScopesFor)(authOptions);const orchestrated=authOptions?.mode==="local"||authOptions?.mode==="remote";const hasAuthorizationServer=authOptions?.mode!=="public"&&authOptions?.mode!=="static";const scopesSupported=orchestrated?granted:[...new Set([...granted,...scope.getAllSupportedScopes()])];this.state.set(stateSchema50.parse({resource,baseUrl,authorizationServer:hasAuthorizationServer?authorizationServer:void 0,scopesSupported,isOrchestrated:false}))}async collectData(){const{resource,scopesSupported,isOrchestrated}=this.state.required;const{authorizationServer}=this.state;const scopes=scopesSupported.length>0?{scopes_supported:scopesSupported}:{};const authorizationServers=authorizationServer?{authorization_servers:[authorizationServer]}:{};if(isOrchestrated){this.respond({kind:"json",contentType:"application/json; charset=utf-8",status:200,headers:{"cache-control":"no-store"},body:{resource,...authorizationServers,...scopes,bearer_methods_supported:["header"]}});return}this.respond({kind:"json",status:200,contentType:"application/json; charset=utf-8",headers:{"cache-control":"no-store"},body:{resource,...authorizationServers,...scopes,bearer_methods_supported:["header"]}})}};__decorateClass([Stage56("checkIpFilter")],WellKnownPrmFlow.prototype,"checkIpFilter",1);__decorateClass([Stage56("acquireQuota")],WellKnownPrmFlow.prototype,"acquireQuota",1);__decorateClass([Stage56("parseInput")],WellKnownPrmFlow.prototype,"parseInput",1);__decorateClass([Stage56("collectData")],WellKnownPrmFlow.prototype,"collectData",1);WellKnownPrmFlow=__decorateClass([FrontMcpFlow({name:name56,plan:plan55,inputSchema:inputSchema49,outputSchema:outputSchema48,access:"public",middleware:{method:"GET"}})],WellKnownPrmFlow)}});function resolveRequestSessionId(ctx){const identity=sessionScopeIdentity(ctx);if(identity)return identity;throw new SessionIdentityRequiredError("The secure store's session scope")}function createSecureStoreProviders(opts){const{backend,scope,ttlMs}=opts;const backendProvider={provide:SECURE_STORE_BACKEND,useValue:backend,scope:import_di50.ProviderScope.GLOBAL,name:"SecureStoreBackend"};const accessorProvider={provide:import_auth74.SECURE_STORE_ACCESSOR,inject:()=>[FRONTMCP_CONTEXT,FrontMcpLogger],useFactory:(ctx,logger)=>new import_auth74.SecureStoreAccessorImpl({backend,scope,resolveSub:()=>resolveRequestSub(ctx),resolveSessionId:()=>resolveRequestSessionId(ctx),ttlMs,logger:logger.child("SecureStore")}),scope:import_di50.ProviderScope.CONTEXT,name:"SecureStoreAccessor"};return[backendProvider,accessorProvider]}var import_auth74,import_di50,SECURE_STORE_BACKEND;var init_secure_store_providers=__esm({"libs/sdk/src/auth/secure-store/secure-store.providers.ts"(){"use strict";import_auth74=require("@frontmcp/auth");import_di50=require("@frontmcp/di");init_common();init_frontmcp_context_provider();init_session_identity_required_error();init_credentials_providers();init_session_scope_identity();SECURE_STORE_BACKEND=Symbol.for("frontmcp:SECURE_STORE_BACKEND")}});var import_auth75,secureStoreContextExtension;var init_secure_store_context_extension=__esm({"libs/sdk/src/auth/secure-store/secure-store.context-extension.ts"(){"use strict";import_auth75=require("@frontmcp/auth");secureStoreContextExtension={property:"secureStore",token:import_auth75.SECURE_STORE_ACCESSOR,errorMessage:"The secure store is not available. Ensure the server uses auth mode 'local' (or 'remote'); the secure store is enabled automatically there."}}});var init_secure_store=__esm({"libs/sdk/src/auth/secure-store/index.ts"(){"use strict";init_secure_store_providers()}});function loadJose(){jose??=importWithRequireFallback(()=>import("jose"),()=>require("jose")).catch(error=>{jose=void 0;throw error});return jose}function getDefaultNoAuthSecret(){if(!defaultNoAuthSecret){defaultNoAuthSecret=(0,import_utils190.randomBytes)(32)}return defaultNoAuthSecret}function normalizeIssuer(value){return value.replace(/\/+$/,"")}function validateAuthorizationIssuer(received,expected,additional=[]){if(received===void 0)return{ok:true};if(!expected)return{ok:true};const accepted=[expected,...additional].map(normalizeIssuer);if(!accepted.includes(normalizeIssuer(received))){return{ok:false,reason:`Authorization response issuer "${received}" does not match the configured issuer "${expected}"`}}return{ok:true}}function audienceMatchesResource(aud,expected){const audiences=typeof aud==="string"?[aud]:Array.isArray(aud)?aud:[];const resources=typeof expected==="string"?[expected]:expected;return audiences.some(value=>typeof value==="string"&&resources.some(resource=>resourceUriMatches(value,resource)))}function isUnsupportedOperation(error){return error instanceof import_utils190.StorageNotSupportedError}function originOf2(value){try{const origin=new URL(value).origin;return origin==="null"?void 0:origin}catch{return void 0}}var import_auth76,import_utils190,jose,MIN_HS256_SECRET_BYTES,defaultNoAuthSecret,RESERVED_JWT_CLAIMS,LocalPrimaryAuth;var init_instance_local_primary_auth=__esm({"libs/sdk/src/auth/instances/instance.local-primary-auth.ts"(){"use strict";import_auth76=require("@frontmcp/auth");import_utils190=require("@frontmcp/utils");init_common();init_auth2();init_context_extension();init_errors();init_dynamic_import_utils();init_cimd();init_credentials();init_credentials_context_extension();init_oauth_flows();init_session_verify_flow();init_well_known_jwks_flow();init_well_known_oauth_authorization_server_flow();init_well_known_prm_flow();init_secure_store();init_secure_store_context_extension();MIN_HS256_SECRET_BYTES=32;RESERVED_JWT_CLAIMS=new Set(["sub","iss","aud","exp","iat","nbf","jti","scope","email","name","picture","roles","consent","federated","authorized_apps"]);LocalPrimaryAuth=class extends FrontMcpAuth{constructor(scope,providers,options){super(options);this.scope=scope;this.providers=providers;this.logger=this.providers.getActiveScope().logger.child("LocalPrimaryAuth");this.port=this.providers.getActiveScope().metadata.http?.port??defaultHttpPort();this.host=(0,import_utils190.getEnv)("FRONTMCP_PUBLIC_HOST")?.trim()||"localhost";this.issuer=this.deriveIssuer(options);this.publicHostPinned=!!(0,import_utils190.getEnv)("FRONTMCP_PUBLIC_HOST")?.trim();const jwtSecret=(0,import_utils190.getEnv)("JWT_SECRET");const hasJwtSecret=!!jwtSecret?.trim();if(hasJwtSecret&&jwtSecret){const encoded=new TextEncoder().encode(jwtSecret);if(encoded.length<MIN_HS256_SECRET_BYTES){if((0,import_utils190.isProduction)())throw new import_auth16.JwtSecretWeakError(encoded.length);this.logger.warn(`JWT_SECRET is ${encoded.length} bytes; HS256 wants at least ${MIN_HS256_SECRET_BYTES} (RFC 7518). This is refused in production \u2014 generate one with \`openssl rand -hex 32\`.`)}this.secret=encoded}else if((0,import_utils190.isProduction)()&&(0,import_auth13.isOrchestratedMode)(options)){throw new import_auth16.JwtSecretRequiredError(options.mode)}else{if(!(0,import_auth13.isPublicMode)(options)){this.logger.warn("JWT_SECRET is not set; signing with a random per-process secret. Tokens will not survive a restart and will not verify across instances. Set JWT_SECRET for any deployment that mints tokens.")}this.secret=getDefaultNoAuthSecret()}this.tokenKeys=import_auth76.LocalTokenKeys.fromConfig(this.signingConfig(options),this.secret,(0,import_auth13.isPublicMode)(options)?"auth":"auth.local");this.jwks.setPublicJwks(this.tokenKeys.publicJwks);this.tokenStorage=this.readTokenStorage(options);this.authorizationStoreImpl=new import_auth76.InMemoryAuthorizationStore;this.federatedSessionStoreImpl=new import_auth76.InMemoryFederatedAuthSessionStore;this.orchestratedTokenStoreImpl=new import_auth76.InMemoryOrchestratedTokenStore({encryptionKey:this.secret,refreshSkewMs:this.providerRefreshSkewMs()});this.consentStoreImpl=new import_auth76.InMemoryConsentStore;this.scope.onDispose(()=>this.releaseResources());this.dcrClientRegistryImpl=new import_auth76.DcrClientRegistry(this.getDcrConfig()??{});if((0,import_auth13.isOrchestratedMode)(options)){const cimdConfig=options.cimd;this.cimdService=new import_auth58.CimdService(this.logger,cimdConfig)}this.ready=this.initialize()}scope;providers;host;port;issuer;publicHostPinned;keys=[];secret;logger;jwks=new import_auth76.JwksService;tokenKeys;cimdService;tokenStorage;authorizationStoreImpl;federatedSessionStoreImpl;orchestratedTokenStoreImpl;consentStoreImpl;dcrClientRegistryImpl;storageAdapter;storageClosers=[];ticketReplayStorage;credentialVaultImpl;get credentialVault(){return this.credentialVaultImpl}secureStoreBackendImpl;get secureStoreBackend(){return this.secureStoreBackendImpl}get authorizationStore(){return this.authorizationStoreImpl}get federatedSessionStore(){return this.federatedSessionStoreImpl}get orchestratedTokenStore(){return this.orchestratedTokenStoreImpl}get consentStore(){return this.consentStoreImpl}get dcrClientRegistry(){return this.dcrClientRegistryImpl}getDcrConfig(){if((0,import_auth13.isLocalMode)(this.options)){return this.options.dcr}return void 0}isDcrEnabled(){const dcr=this.getDcrConfig();if(dcr&&typeof dcr.enabled==="boolean"){return dcr.enabled}return!(0,import_utils190.isProduction)()}providerConfigs=new Map;providerRenewals=new Map;remoteProviderIdImpl;get remoteProviderId(){return this.remoteProviderIdImpl}accessTokenTtlSeconds=3600;refreshTokenTtlSeconds=30*24*3600;deriveIssuer(options){return this.configuredIssuer(options)??`http://${this.host}:${this.port}${this.scope.fullPath}`}signingConfig(options){if((0,import_auth13.isPublicMode)(options))return{signKey:options.signKey,jwks:options.jwks};return(0,import_auth13.isOrchestratedMode)(options)?options.local??{}:{}}configuredIssuer(options){const configured=(0,import_auth13.isPublicMode)(options)?options.issuer:(0,import_auth13.isOrchestratedMode)(options)?options.local?.issuer:void 0;return configured===void 0?void 0:normalizeIssuer(configured)}issuerFor(request2){const configured=this.configuredIssuer(this.options);if(configured!==void 0)return configured;const pinned=getPinnedPublicUrl();if(pinned!==void 0){return request2?computeIssuer(request2,this.scope.entryPath,this.scope.routeBase):`${pinned}${this.scope.fullPath}`}if(this.publicHostPinned||!request2)return this.issuer;return computeIssuer(request2,this.scope.entryPath,this.scope.routeBase)}acceptedIssuersFor(request2){const issuer=this.issuerFor(request2);const options=this.options;const followsRequest=!!request2&&this.configuredIssuer(options)===void 0&&getPinnedPublicUrl()===void 0&&!this.publicHostPinned;if(!followsRequest||!(0,import_auth13.isOrchestratedMode)(options)||options.expectedAudience===void 0)return issuer;const listed=Array.isArray(options.expectedAudience)?options.expectedAudience:[options.expectedAudience];const accepted=new Set([issuer,this.issuer]);for(const audience of listed){const origin=originOf2(audience);if(origin)accepted.add(`${origin}${this.scope.fullPath}`)}return[...accepted]}readTokenStorage(options){if("tokenStorage"in options){return options.tokenStorage}return void 0}get tokenStorageAdapter(){return this.storageAdapter}async initializeStores(){if(!(0,import_auth76.isPersistentTokenStorage)(this.tokenStorage)){return}try{const adapter=await(0,import_auth76.createTokenStorageAdapter)(this.tokenStorage);this.storageAdapter=adapter;this.storageClosers.push(()=>adapter.disconnect());this.disposeInMemoryStores();this.authorizationStoreImpl=new import_auth76.StorageAuthorizationStore(adapter);this.federatedSessionStoreImpl=new import_auth76.StorageFederatedAuthSessionStore(adapter);this.orchestratedTokenStoreImpl=new import_auth76.StorageOrchestratedTokenStore(adapter,{encryptionKey:this.secret,refreshSkewMs:this.providerRefreshSkewMs()});this.consentStoreImpl=new import_auth76.StorageConsentStore(adapter);const backend=(0,import_auth76.isSqliteTokenStorage)(this.tokenStorage)?"sqlite":(0,import_auth76.isRedisTokenStorage)(this.tokenStorage)?"redis":"unknown";this.logger.info(`Token storage initialized with persistent backend: ${backend}`)}catch(err){this.logger.error("Failed to initialize persistent token storage",err);throw err}}get signingSecret(){return new TextDecoder().decode(this.secret)}async claimIncrementalTicket(jti,ttlMs){return this.claimOnce(`incremental-ticket:${jti}`,ttlMs)}async claimOnce(key,ttlMs){const nonce=(0,import_utils190.randomUUID)();const ttlSeconds=Math.max(1,Math.ceil(ttlMs/1e3));let storage=await this.getTicketReplayStorage();try{await storage.set(key,nonce,{ifNotExists:true,ttlSeconds})}catch(error){if(!isUnsupportedOperation(error)){this.logger.warn(`Replay guard unavailable: ${String(error)}`);return false}this.logger.warn("Replay guard: the configured storage has no conditional write; falling back to an in-memory guard (single use holds within this instance only).");storage=await this.useInMemoryTicketReplayStorage();try{await storage.set(key,nonce,{ifNotExists:true,ttlSeconds})}catch(fallbackError){this.logger.warn(`Replay guard unavailable: ${String(fallbackError)}`);return false}}try{return await storage.get(key)===nonce}catch(error){this.logger.warn(`Replay guard unavailable: ${String(error)}`);return false}}getTicketReplayStorage(){if(!this.ticketReplayStorage){if(this.storageAdapter){this.ticketReplayStorage=Promise.resolve(this.storageAdapter)}else{this.logger.debug("Replay guard is in-memory (no persistent tokenStorage configured); single use holds within this instance only.");this.ticketReplayStorage=this.useInMemoryTicketReplayStorage()}}return this.ticketReplayStorage}useInMemoryTicketReplayStorage(){const pending=(async()=>{const memory=new import_utils190.MemoryStorageAdapter;await memory.connect();this.storageClosers.push(()=>memory.disconnect());return memory})();this.ticketReplayStorage=pending;return pending}async initializeCredentialVault(){if((0,import_auth13.isPublicMode)(this.options)){return}let storage;if(this.storageAdapter){storage=this.storageAdapter}else{const memory=new import_utils190.MemoryStorageAdapter;await memory.connect();this.storageClosers.push(()=>memory.disconnect());storage=memory}const pepper=(0,import_utils190.getEnv)("VAULT_SECRET")??(0,import_utils190.getEnv)("JWT_SECRET")??void 0;this.credentialVaultImpl=new import_auth76.SessionCredentialVault({storage,pepper,logger:this.logger.child("SessionCredentialVault")});const signingSecret=this.signingSecret;const basePath=this.issuer;await this.providers.addDynamicProviders(createCredentialsProviders({vault:this.credentialVaultImpl,signingSecret,basePath}));installContextExtensions("credentials",[credentialsContextExtension]);this.logger.debug("SessionCredentialVault initialized; this.credentials enabled")}readSecureStoreConfig(){if("secureStore"in this.options){return this.options.secureStore}return void 0}async initializeSecureStore(){if((0,import_auth13.isPublicMode)(this.options)){return}const config=this.readSecureStoreConfig();const reuseAdapter=this.storageAdapter&&this.secureStoreSharesTokenStorage(config)?this.storageAdapter:void 0;const pepper=(0,import_utils190.getEnv)("VAULT_SECRET")??(0,import_utils190.getEnv)("JWT_SECRET")??new TextDecoder().decode(this.secret);const resolved=await(0,import_auth76.createSecureStore)({config,pepper,storage:reuseAdapter,logger:this.logger.child("SecureStore")});this.secureStoreBackendImpl=resolved.backend;if(resolved.close)this.storageClosers.push(resolved.close);await this.providers.addDynamicProviders(createSecureStoreProviders({backend:resolved.backend,scope:resolved.scope,ttlMs:resolved.ttlMs}));installContextExtensions("secureStore",[secureStoreContextExtension]);this.logger.debug(`SecureStore initialized (backing: ${resolved.kind}, scope: ${resolved.scope}); this.secureStore enabled`)}disposeInMemoryStores(){if(this.federatedSessionStoreImpl instanceof import_auth76.InMemoryFederatedAuthSessionStore){this.federatedSessionStoreImpl.dispose()}if(this.orchestratedTokenStoreImpl instanceof import_auth76.InMemoryOrchestratedTokenStore){this.orchestratedTokenStoreImpl.dispose()}}async releaseResources(){this.disposeInMemoryStores();await Promise.allSettled(this.storageClosers.splice(0).map(close=>close()))}secureStoreSharesTokenStorage(config){if(typeof config!=="object"||config===null)return false;if("sqlite"in config&&config.sqlite)return(0,import_auth76.isSqliteTokenStorage)(this.tokenStorage);if("redis"in config&&config.redis)return(0,import_auth76.isRedisTokenStorage)(this.tokenStorage);return false}async signAnonymousJwt(options={}){const{SignJWT}=await loadJose();const jwt=new SignJWT({sub:`anon:${(0,import_utils190.randomUUID)()}`,anonymous:true,scope:this.anonymousScopes().join(" ")}).setProtectedHeader(this.tokenKeys.protectedHeader()).setIssuedAt().setIssuer(options.issuer??this.issuer).setExpirationTime(`${this.anonymousTokenTtlSeconds()}s`).setJti((0,import_utils190.randomUUID)());if(options.audience)jwt.setAudience(options.audience);return jwt.sign(await this.tokenKeys.signingKey())}anonymousTokenTtlSeconds(){return(0,import_auth13.isPublicMode)(this.options)?this.options.sessionTtl??3600:86400}anonymousScopes(){const scopes=this.options.anonymousScopes;return Array.isArray(scopes)?scopes.filter(s=>typeof s==="string"):["anonymous"]}async verifyGatewayToken(token,requestBaseUrl,expectedAudience,expectedIssuer){try{const{payload,protectedHeader}=await this.tokenKeys.verify(token,{issuer:typeof expectedIssuer==="string"?expectedIssuer:expectedIssuer?[...expectedIssuer]:this.issuer,requiredClaims:["exp"]});if(expectedAudience!==void 0&&!audienceMatchesResource(payload.aud,expectedAudience)){return{ok:false,error:"Token audience does not match this resource"}}return{ok:true,issuer:payload.iss??requestBaseUrl,sub:payload.sub,header:protectedHeader,payload}}catch(err){const message=err instanceof Error?err.message:"verification_failed";return{ok:false,error:message}}}async signAccessToken(user,scopes,audience,consentMetadata,issuer){const claims3={sub:user.sub,scope:scopes.join(" ")};if(user.email)claims3["email"]=user.email;if(user.name)claims3["name"]=user.name;if(user.picture)claims3["picture"]=user.picture;if(user.roles)claims3["roles"]=user.roles;if(consentMetadata){if(consentMetadata.consentEnabled){claims3["consent"]={enabled:true,selectedTools:consentMetadata.selectedToolIds??[]}}if(consentMetadata.federatedLoginUsed){claims3["federated"]={enabled:true,selectedProviders:consentMetadata.selectedProviderIds??[],skippedProviders:consentMetadata.skippedProviderIds??[]}}if(consentMetadata.authorizedAppIds){claims3["authorized_apps"]=consentMetadata.authorizedAppIds}if(consentMetadata.customClaims){for(const[key,value]of Object.entries(consentMetadata.customClaims)){if(RESERVED_JWT_CLAIMS.has(key)){this.logger.warn(`Dropping reserved claim "${key}" from authenticate() custom claims`);continue}claims3[key]=value}}}const{SignJWT}=await loadJose();const jwt=new SignJWT(claims3).setProtectedHeader(this.tokenKeys.protectedHeader()).setIssuedAt().setIssuer(issuer??this.issuer).setExpirationTime(`${this.accessTokenTtlSeconds}s`).setJti((0,import_utils190.randomUUID)());if(audience){jwt.setAudience(audience)}return jwt.sign(await this.tokenKeys.signingKey())}async exchangeCode(code,clientId,redirectUri,codeVerifier,clientSecret,defaultAudience,issuer,clientAssertion){if(this.dcrClientRegistryImpl.verifyClientSecret(clientId,clientSecret)==="invalid"){this.logger.warn("Client authentication failed at token endpoint (authorization_code)");return{error:"invalid_client",error_description:"Client authentication failed"}}const declared=await this.checkDeclaredGrant(clientId,"authorization_code",clientAssertion);if("error"in declared)return declared;const codeRecord=await this.authorizationStore.getAuthorizationCode(code);if(!codeRecord){this.logger.warn(`Authorization code not found or expired: ${code.substring(0,8)}...`);return{error:"invalid_grant",error_description:"Authorization code is invalid or expired"}}if(codeRecord.used){this.logger.warn(`Authorization code already used: ${code.substring(0,8)}...`);if(codeRecord.issuedRefreshToken){try{await this.authorizationStore.revokeRefreshToken(codeRecord.issuedRefreshToken)}catch(err){this.logger.warn(`Failed to revoke refresh token on authorization-code replay: ${err}`)}}await this.authorizationStore.deleteAuthorizationCode(code);return{error:"invalid_grant",error_description:"Authorization code has already been used"}}if(codeRecord.clientId!==clientId){this.logger.warn(`Client ID mismatch: expected ${codeRecord.clientId}, got ${clientId}`);return{error:"invalid_grant",error_description:"Client ID does not match"}}if(codeRecord.redirectUri!==redirectUri){this.logger.warn(`Redirect URI mismatch`);return{error:"invalid_grant",error_description:"Redirect URI does not match"}}if(!(0,import_auth76.verifyPkce)(codeVerifier,codeRecord.pkce)){this.logger.warn(`PKCE verification failed`);return{error:"invalid_grant",error_description:"PKCE verification failed"}}try{await this.authorizationStore.markCodeUsed(code)}catch(err){if(!(0,import_auth76.isGrantRedeemedError)(err))throw err;this.logger.warn("Authorization code was redeemed by a concurrent request");return{error:"invalid_grant",error_description:"Authorization code has already been used"}}const user={sub:codeRecord.userSub,email:codeRecord.userEmail,name:codeRecord.userName};const hasCustomClaims=!!codeRecord.customClaims&&Object.keys(codeRecord.customClaims).length>0;const hasAuthorizedApps=Array.isArray(codeRecord.authorizedAppIds);const consentMetadata=codeRecord.consentEnabled||codeRecord.federatedLoginUsed||hasCustomClaims||hasAuthorizedApps?{selectedToolIds:codeRecord.selectedToolIds,selectedProviderIds:codeRecord.selectedProviderIds,skippedProviderIds:codeRecord.skippedProviderIds,consentEnabled:codeRecord.consentEnabled,federatedLoginUsed:codeRecord.federatedLoginUsed,authorizedAppIds:codeRecord.authorizedAppIds,customClaims:codeRecord.customClaims}:void 0;const resource=codeRecord.resource??defaultAudience;const accessToken=await this.signAccessToken(user,codeRecord.scopes,resource,consentMetadata,issuer);let providerTokensId;if(codeRecord.pendingAuthId&&codeRecord.federatedLoginUsed){providerTokensId=await this.moveProviderTokens(`pending:${codeRecord.pendingAuthId}`,accessToken)}this.logger.info(`Tokens issued for user: ${user.sub}`);const tokens={access_token:accessToken,token_type:"Bearer",expires_in:this.accessTokenTtlSeconds,scope:codeRecord.scopes.join(" ")};if(declared.grantTypes&&!declared.grantTypes.includes("refresh_token"))return tokens;const refreshTokenRecord=this.authorizationStore.createRefreshTokenRecord({clientId,userSub:user.sub,scopes:codeRecord.scopes,resource,userEmail:user.email,userName:user.name,consentEnabled:codeRecord.consentEnabled,selectedToolIds:codeRecord.selectedToolIds,authorizedAppIds:codeRecord.authorizedAppIds,customClaims:codeRecord.customClaims,federatedLoginUsed:codeRecord.federatedLoginUsed,selectedProviderIds:codeRecord.selectedProviderIds,skippedProviderIds:codeRecord.skippedProviderIds,providerTokensId});await this.authorizationStore.storeRefreshToken(refreshTokenRecord);await this.authorizationStore.markCodeUsed(code,refreshTokenRecord.token);return{...tokens,refresh_token:refreshTokenRecord.token}}async checkDeclaredGrant(clientId,grantType,clientAssertion){let grantTypes;try{const cimd=this.cimdService;if(cimd?.enabled&&cimd.isCimdClientId(clientId)){const{metadata}=await cimd.resolveClientMetadata(clientId);if(metadata)cimd.assertSupportedClient(metadata);if(metadata?.token_endpoint_auth_method==="private_key_jwt"){await cimd.verifyClientAssertion(metadata,{audiences:[],...clientAssertion,claimOnce:(key,ttlMs)=>this.claimOnce(key,ttlMs)})}grantTypes=metadata?.grant_types}else{grantTypes=this.dcrClientRegistryImpl.get(clientId)?.grant_types}}catch(err){this.logger.warn(`Client metadata refused at token endpoint (${grantType}): ${err.message}`);return{error:"invalid_client",error_description:"Client authentication failed"}}if(grantTypes&&!grantTypes.includes(grantType)){this.logger.warn(`Client did not declare the ${grantType} grant`);return{error:"unauthorized_client",error_description:`This client may not use the ${grantType} grant`}}return{grantTypes}}async moveProviderTokens(fromAuthorizationId,accessToken){const toAuthorizationId=(0,import_auth76.deriveAuthorizationId)(accessToken);try{await this.orchestratedTokenStore.migrateTokens(fromAuthorizationId,toAuthorizationId);this.logger.info(`Migrated tokens from ${fromAuthorizationId} to ${toAuthorizationId}`);return toAuthorizationId}catch(err){this.logger.warn(`Failed to migrate tokens: ${err}`);return fromAuthorizationId}}async copyProviderTokens(fromAuthorizationId,accessToken){const store=this.orchestratedTokenStore;if(!store.copyTokens)return void 0;const toAuthorizationId=(0,import_auth76.deriveAuthorizationId)(accessToken);try{await store.copyTokens(fromAuthorizationId,toAuthorizationId);return toAuthorizationId}catch(err){this.logger.warn(`Failed to copy provider tokens: ${err}`);await this.discardProviderTokens(toAuthorizationId);return void 0}}async discardProviderTokens(authorizationId){const store=this.orchestratedTokenStore;try{const providerIds=await store.getProviderIds(authorizationId);await Promise.all(providerIds.map(providerId=>store.deleteTokens(authorizationId,providerId)))}catch(err){this.logger.warn(`Failed to discard provider tokens: ${err}`)}}async refreshAccessToken(refreshToken,clientId,clientSecret,defaultAudience,issuer,clientAssertion){if(this.dcrClientRegistryImpl.verifyClientSecret(clientId,clientSecret)==="invalid"){this.logger.warn("Client authentication failed at token endpoint (refresh_token)");return{error:"invalid_client",error_description:"Client authentication failed"}}const declared=await this.checkDeclaredGrant(clientId,"refresh_token",clientAssertion);if("error"in declared)return declared;const tokenRecord=await this.authorizationStore.getRefreshToken(refreshToken);if(!tokenRecord){this.logger.warn("Refresh token not found or expired");return{error:"invalid_grant",error_description:"Refresh token is invalid or expired"}}if(tokenRecord.clientId!==clientId){this.logger.warn("Client ID mismatch on refresh");return{error:"invalid_grant",error_description:"Client ID does not match"}}const user={sub:tokenRecord.userSub,email:tokenRecord.userEmail,name:tokenRecord.userName};const hasAuthorizedApps=Array.isArray(tokenRecord.authorizedAppIds);const hasCustomClaims=!!tokenRecord.customClaims&&Object.keys(tokenRecord.customClaims).length>0;const consentMetadata=tokenRecord.consentEnabled||tokenRecord.federatedLoginUsed||hasCustomClaims||hasAuthorizedApps?{selectedToolIds:tokenRecord.selectedToolIds,selectedProviderIds:tokenRecord.selectedProviderIds,skippedProviderIds:tokenRecord.skippedProviderIds,consentEnabled:tokenRecord.consentEnabled,federatedLoginUsed:tokenRecord.federatedLoginUsed,authorizedAppIds:tokenRecord.authorizedAppIds,customClaims:tokenRecord.customClaims}:void 0;const resource=tokenRecord.resource??defaultAudience;const accessToken=await this.signAccessToken(user,tokenRecord.scopes,resource,consentMetadata,issuer);const sourceId=tokenRecord.providerTokensId;const copiedTo=sourceId?await this.copyProviderTokens(sourceId,accessToken):void 0;if(sourceId&&!await this.authorizationStore.getRefreshToken(refreshToken)){if(copiedTo)await this.discardProviderTokens(copiedTo);this.logger.warn("Refresh token was redeemed by a concurrent request");return{error:"invalid_grant",error_description:"Refresh token is invalid or expired"}}const newRefreshRecord=this.authorizationStore.createRefreshTokenRecord({clientId,userSub:tokenRecord.userSub,scopes:tokenRecord.scopes,resource,userEmail:tokenRecord.userEmail,userName:tokenRecord.userName,consentEnabled:tokenRecord.consentEnabled,selectedToolIds:tokenRecord.selectedToolIds,authorizedAppIds:tokenRecord.authorizedAppIds,customClaims:tokenRecord.customClaims,federatedLoginUsed:tokenRecord.federatedLoginUsed,selectedProviderIds:tokenRecord.selectedProviderIds,skippedProviderIds:tokenRecord.skippedProviderIds,providerTokensId:copiedTo??sourceId});try{await this.authorizationStore.rotateRefreshToken(refreshToken,newRefreshRecord)}catch(err){if(copiedTo)await this.discardProviderTokens(copiedTo);if(!(0,import_auth76.isGrantRedeemedError)(err))throw err;this.logger.warn("Refresh token was redeemed by a concurrent request");return{error:"invalid_grant",error_description:"Refresh token is invalid or expired"}}if(sourceId&&copiedTo)await this.discardProviderTokens(sourceId);if(sourceId&&!this.orchestratedTokenStore.copyTokens){const movedTo=await this.moveProviderTokens(sourceId,accessToken);if(movedTo!==sourceId){await this.authorizationStore.storeRefreshToken({...newRefreshRecord,providerTokensId:movedTo})}}this.logger.info(`Tokens refreshed for user: ${user.sub}`);return{access_token:accessToken,token_type:"Bearer",expires_in:this.accessTokenTtlSeconds,refresh_token:newRefreshRecord.token,scope:tokenRecord.scopes.join(" ")}}async createAuthorizationCode(params){const codeRecord=this.authorizationStore.createCodeRecord({clientId:params.clientId,redirectUri:params.redirectUri,scopes:params.scopes,pkce:{challenge:params.codeChallenge,method:"S256"},userSub:params.userSub,userEmail:params.userEmail,userName:params.userName,state:params.state,resource:params.resource,selectedToolIds:params.selectedToolIds,selectedProviderIds:params.selectedProviderIds,skippedProviderIds:params.skippedProviderIds,consentEnabled:params.consentEnabled,federatedLoginUsed:params.federatedLoginUsed,pendingAuthId:params.pendingAuthId,authorizedAppIds:params.authorizedAppIds,customClaims:params.customClaims});await this.authorizationStore.storeAuthorizationCode(codeRecord);this.logger.info(`Authorization code created for user: ${params.userSub}`);return codeRecord.code}async initialize(){await this.tokenKeys.signingKey();await this.initializeStores();this.registerConfiguredProviders();await this.registerRemoteProvider();await this.initializeCredentialVault();await this.initializeSecureStore();this.providers.injectProvider({value:this.jwks,metadata:{scope:import_di4.ProviderScope.GLOBAL,name:"auth:jwk-service"},provide:import_auth76.JwksService});if(this.cimdService){const cimdService=this.cimdService;if(cimdService.enabled)await cimdService.initialize();this.scope.onDispose(()=>cimdService.dispose());this.providers.injectProvider({value:cimdService,metadata:{scope:import_di4.ProviderScope.GLOBAL,name:"auth:cimd-service"},provide:import_auth58.CimdService});this.logger.debug("CIMD service registered")}await this.registerAuthFlows();return Promise.resolve()}fetch(input,init){return fetch(input,init)}validate(request2){return Promise.resolve()}async registerAuthFlows(){const scope=this.providers.getActiveScope();await scope.registryFlows(WellKnownPrmFlow,WellKnownAsFlow,WellKnownJwksFlow,SessionVerifyFlow,...oauthFlows)}registerProvider(config){const previous=this.providerConfigs.get(config.id);const issuerChanged=previous?.issuer!==void 0&&config.issuer!==void 0&&normalizeIssuer(previous.issuer)!==normalizeIssuer(config.issuer);if(issuerChanged){this.logger.warn(`Upstream provider "${config.id}" changed issuer (${previous.issuer} \u2192 ${config.issuer}); discarding credentials bound to the previous authorization server`);void this.discardProviderCredentials(config.id)}this.providerConfigs.set(config.id,config);this.logger.info(`Registered upstream provider: ${config.id}`)}async discardProviderCredentials(providerId){try{const store=this.orchestratedTokenStoreImpl;if(typeof store.deleteTokensForProvider!=="function"){this.logger.warn(`Cannot auto-discard credentials for provider "${providerId}": the configured token store does not support provider-wide deletion. Rotate or clear the store manually so credentials issued by the previous authorization server are not reused.`);return}await store.deleteTokensForProvider(providerId)}catch(error){this.logger.error(`Failed to discard credentials for provider "${providerId}" after an issuer change`,error instanceof Error?{message:error.message}:{error})}}registerConfiguredProviders(){if(!(0,import_auth13.isLocalMode)(this.options)){return}const providers=this.options.providers;if(!providers||providers.length===0){return}for(const p of providers){const authorizationEndpoint=p.authorizationEndpoint??p.authorizeUrl;const tokenEndpoint=p.tokenEndpoint??p.tokenUrl;if(!authorizationEndpoint||!tokenEndpoint){const missing=!authorizationEndpoint?!tokenEndpoint?"authorization and token endpoints":"authorization endpoint (authorizationEndpoint/authorizeUrl)":"token endpoint (tokenEndpoint/tokenUrl)";throw new Error(`Provider "${p.id}" is missing its ${missing}.`)}this.registerProvider({id:p.id,name:p.name??p.id,authorizationEndpoint,tokenEndpoint,userInfoEndpoint:p.userInfoEndpoint,jwksUri:p.jwksUri,clientId:p.clientId,clientSecret:p.clientSecret,scopes:p.scopes??[],callbackUrl:`${this.issuer}/oauth/provider/${p.id}/callback`,issuer:p.issuer,additionalIssuers:p.additionalIssuers})}}async registerRemoteProvider(){if(!(0,import_auth13.isRemoteMode)(this.options)){return}const options=this.options;const base=options.provider.replace(/\/+$/,"");const cfg=options.providerConfig;const id=cfg?.id??this.deriveRemoteProviderId(options.provider);this.remoteProviderIdImpl=id;const callbackUrl=`${this.issuer}/oauth/provider/${id}/callback`;const scopes=options.scopes??["openid"];const client=await this.resolveRemoteClient(options,id,callbackUrl,scopes);if(!client){return}this.registerProvider({id,name:cfg?.name??id,authorizationEndpoint:cfg?.authEndpoint??`${base}/authorize`,tokenEndpoint:cfg?.tokenEndpoint??`${base}/token`,userInfoEndpoint:cfg?.userInfoEndpoint??`${base}/userinfo`,jwksUri:cfg?.jwksUri??`${base}/.well-known/jwks.json`,jwks:cfg?.jwks,clientId:client.clientId,clientSecret:client.clientSecret,scopes,callbackUrl,issuer:options.provider,additionalIssuers:cfg?.additionalIssuers,verifyIssuer:cfg?.verifyIssuer})}async resolveRemoteClient(options,providerId,callbackUrl,scopes){const cfg=options.providerConfig;if(options.clientId){if(cfg?.dcrEnabled){this.logger.info(`Remote mode: clientId is set, so provider "${providerId}" is not registered dynamically`)}return{clientId:options.clientId,clientSecret:options.clientSecret}}if(!cfg?.dcrEnabled){this.logger.warn(`Remote mode: no clientId configured for provider "${providerId}"; upstream OAuth is not available. Set clientId, or providerConfig.dcrEnabled to register with the provider.`);return void 0}return(0,import_auth76.resolveUpstreamClient)({provider:options.provider,registrationEndpoint:cfg.registrationEndpoint,redirectUri:callbackUrl,clientName:this.scope.metadata.info?.name??"FrontMCP",scopes,storage:this.storageAdapter,encryptionKey:this.secret,logger:this.logger})}deriveRemoteProviderId(provider){try{return new URL(provider).hostname.replace(/\./g,"_")}catch{return provider.replace(/[^a-zA-Z0-9]/g,"_")}}getProviderConfig(providerId){return this.providerConfigs.get(providerId)}async buildProviderAuthorizeUrl(providerId,params){const config=this.providerConfigs.get(providerId);if(!config){this.logger.error(`Provider not found: ${providerId}`);return null}const url=new URL(config.authorizationEndpoint);url.searchParams.set("response_type","code");url.searchParams.set("client_id",config.clientId);url.searchParams.set("redirect_uri",config.callbackUrl);url.searchParams.set("state",params.state);url.searchParams.set("code_challenge",params.codeChallenge);url.searchParams.set("code_challenge_method",params.codeChallengeMethod);const scopes=params.scopes??config.scopes;if(scopes.length>0){url.searchParams.set("scope",scopes.join(" "))}return url.toString()}async exchangeProviderCode(providerId,code,codeVerifier){const config=this.providerConfigs.get(providerId);if(!config){return{error:"invalid_provider",error_description:`Provider not configured: ${providerId}`}}try{const body=new URLSearchParams({grant_type:"authorization_code",code,redirect_uri:config.callbackUrl,client_id:config.clientId});if(config.clientSecret){body.set("client_secret",config.clientSecret)}if(codeVerifier){body.set("code_verifier",codeVerifier)}this.logger.debug(`Exchanging code with provider: ${providerId}`);const response=await fetch(config.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:body.toString()});if(!response.ok){const errorData=await response.json().catch(()=>({}));this.logger.error(`Provider token exchange failed: ${response.status}`,errorData);return{error:errorData.error||"provider_error",error_description:errorData.error_description||`Provider returned ${response.status}`}}const tokenData=await response.json();if(typeof tokenData?.access_token!=="string"||tokenData.access_token.length===0){this.logger.error(`Provider ${providerId} returned 200 without an access_token`);return{error:"provider_error",error_description:`Provider ${providerId} did not return an access_token`}}this.logger.info(`Successfully exchanged code with provider: ${providerId}`);return tokenData}catch(err){this.logger.error(`Provider token exchange error for ${providerId}:`,err);return{error:"provider_error",error_description:`Failed to exchange code with provider: ${err}`}}}async getProviderUserInfo(providerId,accessToken,idToken){const config=this.providerConfigs.get(providerId);if(idToken&&config){const claims3=await this.verifyProviderIdToken(config,idToken);const sub=typeof claims3?.["sub"]==="string"&&claims3["sub"].trim()?claims3["sub"]:void 0;if(claims3&&sub){return{sub,email:claims3["email"],name:claims3["name"],picture:claims3["picture"],claims:claims3}}this.logger.warn(`ID token for ${providerId} was not verified; using the userinfo endpoint for identity`)}if(config?.userInfoEndpoint){try{const response=await fetch(config.userInfoEndpoint,{headers:{Authorization:`Bearer ${accessToken}`,Accept:"application/json"}});if(response.ok){const userInfo=await response.json();const sub=typeof userInfo["sub"]==="string"&&userInfo["sub"].trim()?userInfo["sub"]:void 0;if(sub){return{sub,email:userInfo["email"],name:userInfo["name"],picture:userInfo["picture"],claims:userInfo}}this.logger.warn(`userinfo for ${providerId} returned no usable sub`)}}catch(err){this.logger.warn(`Failed to get userinfo from ${providerId}: ${err}`)}}throw new Error(`Unable to determine a stable user identity from provider "${providerId}" (no id_token sub and no usable userinfo endpoint)`)}async verifyProviderIdToken(config,idToken){if(!config.jwks?.keys?.length&&!config.jwksUri)return void 0;if(!config.issuer&&config.verifyIssuer!==false){this.logger.warn(`ID token for ${config.id} not used: the provider has no configured issuer to check it against`);return void 0}const result=await this.jwks.verifyTransparentToken(idToken,[{id:`upstream:${config.id}`,issuerUrl:config.issuer??"",additionalIssuers:config.additionalIssuers,verifyIssuer:config.verifyIssuer,jwks:config.jwks,jwksUri:config.jwksUri}]);if(!result.ok||!result.payload){this.logger.warn(`ID token for ${config.id} failed verification: ${result.error??"unknown"}`);return void 0}const aud=result.payload["aud"];const audiences=typeof aud==="string"?[aud]:Array.isArray(aud)?aud:[];if(!audiences.includes(config.clientId)){this.logger.warn(`ID token for ${config.id} was issued for another client`);return void 0}return result.payload}async refreshProviderToken(providerId,refreshToken){const config=this.providerConfigs.get(providerId);if(!config){return{error:"invalid_provider",error_description:`Provider not configured: ${providerId}`}}try{const body=new URLSearchParams({grant_type:"refresh_token",refresh_token:refreshToken,client_id:config.clientId});if(config.clientSecret){body.set("client_secret",config.clientSecret)}const response=await fetch(config.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:body.toString()});if(!response.ok){const errorData=await response.json().catch(()=>({}));return{error:errorData.error||"provider_error",error_description:errorData.error_description||`Provider returned ${response.status}`}}return await response.json()}catch(err){return{error:"provider_error",error_description:`Failed to refresh token with provider: ${err}`}}}providerTokenRefresher(){if(!(0,import_auth13.isOrchestratedMode)(this.options)||this.options.refresh?.enabled===false)return void 0;return(providerId,refreshToken)=>{const key=JSON.stringify([providerId,refreshToken]);const inFlight=this.providerRenewals.get(key);if(inFlight)return inFlight;const renewal=this.renewProviderToken(providerId,refreshToken).finally(()=>this.providerRenewals.delete(key));this.providerRenewals.set(key,renewal);return renewal}}async renewProviderToken(providerId,refreshToken){const result=await this.refreshProviderToken(providerId,refreshToken);if("error"in result||typeof result.access_token!=="string"||!result.access_token){this.logger.warn(`Provider ${providerId} did not refresh its token: ${"error"in result?result.error:"no access_token"}`);throw new import_auth76.TokenNotAvailableError(`Provider "${providerId}" did not refresh its token; the user has to sign in again`)}return{accessToken:result.access_token,refreshToken:result.refresh_token,expiresIn:result.expires_in}}providerRefreshSkewMs(){if(!(0,import_auth13.isOrchestratedMode)(this.options)||this.options.refresh?.enabled===false)return 0;return(this.options.refresh?.skewSeconds??60)*1e3}}}});var import_auth78,RemotePrimaryAuth;var init_instance_remote_primary_auth=__esm({"libs/sdk/src/auth/instances/instance.remote-primary-auth.ts"(){"use strict";import_auth78=require("@frontmcp/auth");init_common();init_session_verify_flow();init_well_known_jwks_flow();init_well_known_oauth_authorization_server_flow();init_well_known_prm_flow();RemotePrimaryAuth=class extends FrontMcpAuth{constructor(scope,providers,options){super(options);this.scope=scope;this.providers=providers;this.ready=this.initialize()}scope;providers;ready;jwks=new import_auth78.JwksService;fetch(input,init){return fetch(input,init)}validate(request2){return Promise.resolve()}get issuer(){return this.options.provider}async initialize(){const scope=this.providers.getActiveScope();this.providers.injectProvider({value:this.jwks,metadata:{scope:import_di4.ProviderScope.GLOBAL,name:"auth:jwk-service"},provide:import_auth78.JwksService});await this.registerAuthFlows(scope);return Promise.resolve()}async registerAuthFlows(scope){await scope.registryFlows(WellKnownPrmFlow,WellKnownAsFlow,WellKnownJwksFlow,SessionVerifyFlow)}}}});var primary_auth_factory_exports={};__export(primary_auth_factory_exports,{createPrimaryAuth:()=>createPrimaryAuth});var createPrimaryAuth;var init_primary_auth_factory=__esm({"libs/sdk/src/auth/primary-auth.factory.ts"(){"use strict";init_common();init_instance_local_primary_auth();init_instance_remote_primary_auth();createPrimaryAuth=(scope,providers,options)=>{if((0,import_auth13.isPublicMode)(options)){return new LocalPrimaryAuth(scope,providers,options)}if((0,import_auth13.isStaticMode)(options)){return new LocalPrimaryAuth(scope,providers,options)}if((0,import_auth13.isTransparentMode)(options)){return new RemotePrimaryAuth(scope,providers,options)}if((0,import_auth13.isOrchestratedMode)(options)){if((0,import_auth13.isOrchestratedLocal)(options)){return new LocalPrimaryAuth(scope,providers,options)}else{return new LocalPrimaryAuth(scope,providers,options)}}const defaultOptions=(0,import_auth13.parseAuthOptions)({mode:"public"});return new LocalPrimaryAuth(scope,providers,defaultOptions)}}});var ui_option_warnings_exports={};__export(ui_option_warnings_exports,{describeIgnoredUiOptions:()=>describeIgnoredUiOptions,describeServingModeDefault:()=>describeServingModeDefault});function describeIgnoredUiOptions(toolName,ui){if(!ui)return[];const messages=[];messages.push(...describeInvalidCspOrigins(toolName,ui["csp"]));if(ui["servingMode"]==="hybrid"){messages.push(`Tool "${toolName}": \`ui.servingMode: 'hybrid'\` sends only a reference in \`_meta['ui/component']\` ({ type, hash, toolName }), not the component code; the widget is rendered from its \`ui://\` resource.`)}return messages}function describeServingModeDefault(owner,mode){if(mode==="hybrid"){return[`${owner}: \`ui.servingMode: 'hybrid'\` sends only a reference in \`_meta['ui/component']\` ({ type, hash, toolName }), not the component code; the widgets of the tools that inherit it are rendered from their \`ui://\` resource.`]}return[]}function describeInvalidCspOrigins(toolName,csp){if(!csp||typeof csp!=="object")return[];const messages=[];for(const key of["connectDomains","resourceDomains"]){const domains=csp[key];if(!Array.isArray(domains))continue;for(const domain of domains){if(typeof domain==="string"&&(0,import_shell3.validateCSPDomain)(domain))continue;messages.push(`Tool "${toolName}": \`ui.csp.${key}\` origin ${JSON.stringify(domain)} is not an https:// or wss:// origin (or http:// / ws:// on localhost), so the widget page's Content-Security-Policy leaves it out.`)}}return messages}var import_shell3;var init_ui_option_warnings=__esm({"libs/sdk/src/tool/ui/ui-option-warnings.ts"(){"use strict";import_shell3=require("@frontmcp/uipack/shell")}});function workerModuleOf(metadata){return metadata.worker?captureCallerFile(RESOURCE_DECORATOR_BASENAMES):void 0}function FrontMcpResource(providedMetadata){const workerModule=workerModuleOf(providedMetadata);return target=>{const metadata=frontMcpResourceMetadataSchema.parse(providedMetadata);if(metadata.worker)registerWorkerResourceClass(target,metadata,workerModule);Reflect.defineMetadata(FrontMcpResourceTokens.type,true,target);const extended={};for(const property in metadata){if(FrontMcpResourceTokens[property]){Reflect.defineMetadata(FrontMcpResourceTokens[property],metadata[property],target)}else{extended[property]=metadata[property]}}Reflect.defineMetadata(extendedResourceMetadata,extended,target)}}function FrontMcpResourceTemplate(providedMetadata){const workerModule=workerModuleOf(providedMetadata);return target=>{const metadata=frontMcpResourceTemplateMetadataSchema.parse(providedMetadata);if(metadata.worker)registerWorkerResourceClass(target,metadata,workerModule);Reflect.defineMetadata(FrontMcpResourceTemplateTokens.type,true,target);const extended=Object.create(null);for(const property in metadata){if(Object.prototype.hasOwnProperty.call(FrontMcpResourceTemplateTokens,property)){Reflect.defineMetadata(FrontMcpResourceTemplateTokens[property],metadata[property],target)}else{extended[property]=metadata[property]}}Reflect.defineMetadata(extendedResourceTemplateMetadata,extended,target)}}function frontMcpResource(providedMetadata){const workerModule=workerModuleOf(providedMetadata);return execute=>{const metadata=frontMcpResourceMetadataSchema.parse(providedMetadata);if(metadata.worker)registerWorkerResourceHandler(execute,metadata,workerModule);const resourceFunction=function(){return execute};Object.assign(resourceFunction,{[FrontMcpResourceTokens.type]:"function-resource",[FrontMcpResourceTokens.metadata]:metadata});return resourceFunction}}function frontMcpResourceTemplate(providedMetadata){const workerModule=workerModuleOf(providedMetadata);return execute=>{const metadata=frontMcpResourceTemplateMetadataSchema.parse(providedMetadata);if(metadata.worker)registerWorkerResourceHandler(execute,metadata,workerModule);const resourceFunction=function(){return execute};Object.assign(resourceFunction,{[FrontMcpResourceTemplateTokens.type]:"function-resource-template",[FrontMcpResourceTemplateTokens.metadata]:metadata});return resourceFunction}}function resourceEsm(specifier,targetName,options){const parsed=parsePackageSpecifier(specifier);return{kind:"ESM",provide:Symbol(`esm-resource:${parsed.fullName}:${targetName}`),specifier:parsed,targetName,options,metadata:{name:targetName,description:`Resource "${targetName}" from ${parsed.fullName}`,uri:`esm://${targetName}`,...options?.metadata}}}function resourceRemote(url,targetName,options){validateRemoteUrl(url);return{kind:"REMOTE",provide:Symbol(`remote-resource:${url}:${targetName}`),url,targetName,transportOptions:options?.transportOptions,remoteAuth:options?.remoteAuth,options,metadata:{name:targetName,description:`Remote resource "${targetName}" from ${url}`,uri:`remote://${targetName}`,...options?.metadata}}}var import_reflect_metadata29,RESOURCE_DECORATOR_BASENAMES,Resource,_ResourceTemplate;var init_resource_decorator=__esm({"libs/sdk/src/common/decorators/resource.decorator.ts"(){"use strict";import_reflect_metadata29=require("reflect-metadata");init_package_specifier();init_worker_resources();init_metadata();init_tokens();init_caller_dir_utils();init_validate_remote_url();RESOURCE_DECORATOR_BASENAMES=["resource.decorator.ts","resource.decorator.js","resource.decorator.mjs","resource.decorator.cjs"];Object.assign(FrontMcpResource,{esm:resourceEsm,remote:resourceRemote});Resource=FrontMcpResource;_ResourceTemplate=FrontMcpResourceTemplate}});var import_utils191,import_shell4;var init_template_helpers=__esm({"libs/sdk/src/tool/ui/template-helpers.ts"(){"use strict";import_utils191=require("@frontmcp/uipack/utils");import_shell4=require("@frontmcp/uipack/shell")}});var ui_resource_template_exports={};__export(ui_resource_template_exports,{StaticWidgetResourceTemplate:()=>StaticWidgetResourceTemplate});var StaticWidgetResourceTemplate;var init_ui_resource_template=__esm({"libs/sdk/src/tool/ui/ui-resource-template.ts"(){"use strict";init_resource_decorator();init_template_helpers();StaticWidgetResourceTemplate=frontMcpResourceTemplate({name:"static-widget",description:"Static widget HTML for tool UI (OpenAI discovery)",uriTemplate:"ui://widget/{toolName}.html",mimeType:"text/html;profile=mcp-app"})((uri,params)=>{return{contents:[{uri,mimeType:"text/html;profile=mcp-app",text:`<!DOCTYPE html>
470
470
  <html>
471
471
  <head><title>Widget Placeholder</title></head>
472
472
  <body>